@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-alpha.2
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 +24 -0
- package/README.md +54 -4
- package/README.zh.md +54 -4
- package/SECURITY.md +14 -0
- package/assets/workspace-sessions.js +648 -0
- package/assets/workspace.css +160 -0
- package/assets/workspace.js +1795 -0
- package/config.example.yaml +3 -2
- package/dist/codex/CodexEventMapper.js +35 -0
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +50 -4
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/codex/TraeTaskNotification.js +44 -0
- package/dist/codex/TraeTaskNotification.js.map +1 -0
- package/dist/config/SettingsStore.js +1 -1
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +3 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/paths.js +3 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/feishu/CardRenderer.js +54 -10
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +2 -2
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +103 -16
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +61 -17
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +1 -1
- package/dist/local-files/GitDiffPreview.js +11 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +273 -25
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownFileLinks.js +5 -4
- package/dist/local-files/MarkdownFileLinks.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +32 -10
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WebPageTitle.js +85 -0
- package/dist/local-files/WebPageTitle.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +553 -0
- package/dist/local-files/WorkspaceFiles.js.map +1 -0
- package/dist/local-files/WorkspaceOrigin.js +38 -0
- package/dist/local-files/WorkspaceOrigin.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +19 -0
- package/dist/local-files/WorkspacePage.js.map +1 -0
- package/dist/local-files/WorkspaceSessions.js +689 -0
- package/dist/local-files/WorkspaceSessions.js.map +1 -0
- package/dist/presentation/TurnStateReducer.js +74 -13
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnActivity.js +41 -0
- package/dist/presentation/turnActivity.js.map +1 -0
- package/dist/presentation/turnStatus.js +11 -0
- package/dist/presentation/turnStatus.js.map +1 -1
- package/dist/presentation/visibleTurnActivities.js +4 -2
- package/dist/presentation/visibleTurnActivities.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +150 -14
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/types.js +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/state/InboundMessageStore.js +54 -0
- package/dist/state/InboundMessageStore.js.map +1 -0
- package/dist/state/StateStore.js +71 -1
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +4 -2
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/migrations.js +20 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -0
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/supervision/SafeRestartScheduler.js +33 -16
- package/dist/supervision/SafeRestartScheduler.js.map +1 -1
- package/dist/terminal/TerminalLinks.js +32 -0
- package/dist/terminal/TerminalLinks.js.map +1 -1
- package/dist/terminal/TerminalPage.js +44 -24
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +103 -39
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +1 -1
- package/docs/technical-reference.zh.md +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +3 -1
- package/src/codex/CodexEventMapper.ts +39 -1
- package/src/codex/CodexRuntime.ts +54 -4
- package/src/codex/TraeTaskNotification.ts +49 -0
- package/src/config/SettingsStore.ts +1 -1
- package/src/config/loadConfig.ts +3 -2
- package/src/config/paths.ts +4 -0
- package/src/feishu/CardRenderer.ts +45 -11
- package/src/feishu/FeishuMessageClient.ts +2 -2
- package/src/feishu/FeishuTurnPresenter.ts +110 -20
- package/src/index.ts +62 -17
- package/src/local-files/DiagramPreview.ts +1 -1
- package/src/local-files/GitDiffPreview.ts +10 -7
- package/src/local-files/LocalFileViewerServer.ts +243 -25
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +35 -9
- package/src/local-files/WebPageTitle.ts +59 -0
- package/src/local-files/WorkspaceFiles.ts +468 -0
- package/src/local-files/WorkspaceOrigin.ts +31 -0
- package/src/local-files/WorkspacePage.ts +21 -0
- package/src/local-files/WorkspaceSessions.ts +587 -0
- package/src/presentation/TurnStateReducer.ts +76 -14
- package/src/presentation/turnActivity.ts +43 -0
- package/src/presentation/turnStatus.ts +14 -0
- package/src/presentation/turnViewTypes.ts +10 -1
- package/src/presentation/visibleTurnActivities.ts +4 -2
- package/src/proxy/ProxySessionController.ts +149 -13
- package/src/runtime/types.ts +17 -0
- package/src/state/InboundMessageStore.ts +72 -0
- package/src/state/StateStore.ts +80 -1
- package/src/state/TurnPreviewJournal.ts +4 -2
- package/src/state/migrations.ts +20 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -0
- package/src/supervision/SafeRestartScheduler.ts +42 -18
- package/src/terminal/TerminalLinks.ts +26 -0
- package/src/terminal/TerminalPage.ts +44 -24
- package/src/terminal/TerminalServer.ts +98 -36
|
@@ -0,0 +1,648 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const make = (tag, className, text) => {
|
|
3
|
+
const node = document.createElement(tag);
|
|
4
|
+
if (className) node.className = className;
|
|
5
|
+
if (text !== undefined) node.textContent = text;
|
|
6
|
+
return node;
|
|
7
|
+
};
|
|
8
|
+
const button = (text, handler, className) => {
|
|
9
|
+
const node = make('button',className,text); node.type = 'button'; node.onclick = handler; return node;
|
|
10
|
+
};
|
|
11
|
+
const labels = {ready:'空闲',starting:'启动中',running:'执行中',tool_running:'执行中',waiting_for_approval:'等待确认',completed:'已完成',failed:'失败',cancelled:'已停止',unknown:'待核实',closed:'已归档'};
|
|
12
|
+
const status = value => labels[value] || '空闲';
|
|
13
|
+
const activeTurn = value => ['running','tool_running','waiting_for_approval'].includes(value);
|
|
14
|
+
const read = (key,fallback,storage = 'localStorage') => { try { return JSON.parse(window[storage]?.getItem(key)) ?? fallback; } catch { return fallback; } };
|
|
15
|
+
const save = (key,value,storage = 'localStorage') => { try { window[storage]?.setItem(key,JSON.stringify(value)); } catch {} };
|
|
16
|
+
const uuid = () => {
|
|
17
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16)); bytes[6] = bytes[6]&15|64; bytes[8] = bytes[8]&63|128;
|
|
18
|
+
return Array.from(bytes,(byte,index) => ([4,6,8,10].includes(index)?'-':'')+byte.toString(16).padStart(2,'0')).join('');
|
|
19
|
+
};
|
|
20
|
+
class SessionWorkspace {
|
|
21
|
+
constructor(app, base) {
|
|
22
|
+
this.app = app; this.base = base;
|
|
23
|
+
this.left = app.querySelector('workspace-task-list'); this.chat = app.querySelector('workspace-chat');
|
|
24
|
+
this.page = uuid(); this.generation = this.connectionEpoch = 0;
|
|
25
|
+
const groups = read('agentbot-workspace-groups',[]);
|
|
26
|
+
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','任务');
|
|
28
|
+
this.left.classList.add('session-task-pane'); this.chat.classList.add('session-chat-pane');
|
|
29
|
+
this.locked('正在检查工作台会话…'); void this.session();
|
|
30
|
+
this.offline = () => { if (this.csrf) { this.connected = false; this.app.updateSessionStatus(false,'网络已断开'); } };
|
|
31
|
+
this.online = () => { if (this.csrf) this.connect(); };
|
|
32
|
+
window.addEventListener('offline',this.offline); window.addEventListener('online',this.online);
|
|
33
|
+
}
|
|
34
|
+
async fetch(route, options = {}) {
|
|
35
|
+
const {params,body,signal} = options, url = new URL(this.base+route,window.location.href);
|
|
36
|
+
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);
|
|
38
|
+
const abort = () => controller.abort(); if (signal?.aborted) abort(); else signal?.addEventListener('abort',abort,{once:true});
|
|
39
|
+
try {
|
|
40
|
+
const response = await fetch(url,{cache:'no-store',credentials:'same-origin',signal:controller.signal,
|
|
41
|
+
...(body === undefined ? {} : {method:'POST',headers:{'content-type':'application/json','x-workspace-csrf':this.csrf || ''},body:JSON.stringify(body)})});
|
|
42
|
+
const data = await response.json();
|
|
43
|
+
if (!response.ok) {
|
|
44
|
+
if (response.status === 401 && route !== '/login' && this.csrf) this.expire();
|
|
45
|
+
throw Object.assign(new Error(data.error || `请求失败(HTTP ${response.status})`),{status:response.status});
|
|
46
|
+
}
|
|
47
|
+
return data;
|
|
48
|
+
} finally { clearTimeout(timeout); signal?.removeEventListener('abort',abort); }
|
|
49
|
+
}
|
|
50
|
+
session(autoLogin = true, note) {
|
|
51
|
+
return this.sessionCheck ??= this.checkSession(autoLogin,note).finally(() => { this.sessionCheck = undefined; });
|
|
52
|
+
}
|
|
53
|
+
async checkSession(autoLogin, note) {
|
|
54
|
+
try {
|
|
55
|
+
const data = await this.fetch('/session'); if (this.disposed) return;
|
|
56
|
+
if (data.csrf) this.unlock(data.csrf);
|
|
57
|
+
else if (data.auth === 'automatic' && autoLogin) {
|
|
58
|
+
const login = await this.fetch('/login',{body:{}});
|
|
59
|
+
if (!this.disposed) this.unlock(login.csrf);
|
|
60
|
+
} else if (data.auth === 'automatic') this.locked(note || '点击继续使用工作台。','automatic');
|
|
61
|
+
else if (data.available) this.locked(note || '登录后可使用任务、聊天和终端。','password');
|
|
62
|
+
else this.locked('任务和聊天暂不可用。',undefined,data.hint);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (!this.disposed) this.locked('无法登录工作台。','retry',error.status ? error.message : '连接失败,请重试。文件浏览不受影响。');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
showLogin(afterLogin) {
|
|
68
|
+
this.afterLogin = afterLogin;
|
|
69
|
+
this.app.navigate(() => {
|
|
70
|
+
if (this.app.layout.sidebarCollapsed) { this.app.layout.sidebarCollapsed = false; this.app.applyLayout(); }
|
|
71
|
+
this.app.selectPane('tasks');
|
|
72
|
+
});
|
|
73
|
+
this.left.querySelector('.session-login input,.session-primary')?.focus({preventScroll:true});
|
|
74
|
+
}
|
|
75
|
+
locked(message, mode, hint) {
|
|
76
|
+
this.timelineObserver?.disconnect();
|
|
77
|
+
const box = make('div','session-empty'); box.append(make('strong',null,message));
|
|
78
|
+
if (hint) box.append(make('p',null,hint));
|
|
79
|
+
this.left.replaceChildren(this.heading,box);
|
|
80
|
+
this.chat.replaceChildren(make('h2','pane-heading','聊天'));
|
|
81
|
+
const view = make('div','chat-body session-chat-body session-empty'); view.append(make('strong',null,'在工作台继续任务'),make('p',null,'登录后查看 App Server 任务、执行过程与对话。文件链接保留原有只读权限。'));
|
|
82
|
+
this.chat.append(view);
|
|
83
|
+
if (mode === 'automatic' || mode === 'retry') {
|
|
84
|
+
const action = button(mode === 'automatic' ? '继续使用' : '重试',() => this.session(),'session-primary');
|
|
85
|
+
box.append(action);
|
|
86
|
+
view.append(button('前往任务栏',() => this.app.navigate(() => { this.app.selectPane('tasks'); action.focus({preventScroll:true}); }),'session-mobile-login'));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (mode !== 'password') return;
|
|
90
|
+
const form = make('form','session-login'), label = make('label',null,'工作台 / 终端密码'), input = make('input');
|
|
91
|
+
input.type = 'password'; input.required = true; input.maxLength = 256; input.autocomplete = 'current-password'; label.append(input);
|
|
92
|
+
const submit = make('button','session-primary','登录'); submit.type = 'submit';
|
|
93
|
+
const error = make('p','session-error'); error.setAttribute('role','alert');
|
|
94
|
+
form.append(label,submit,error); box.append(form);
|
|
95
|
+
form.onsubmit = async event => {
|
|
96
|
+
event.preventDefault(); if (submit.disabled || !input.value) return;
|
|
97
|
+
submit.disabled = true; error.textContent = '';
|
|
98
|
+
try { const data = await this.fetch('/login',{body:{password:input.value}}); input.value = ''; this.unlock(data.csrf); }
|
|
99
|
+
catch (failure) { error.textContent = failure.status ? failure.message : '连接失败,请重试。'; input.focus(); }
|
|
100
|
+
finally { submit.disabled = false; }
|
|
101
|
+
};
|
|
102
|
+
view.append(button('前往任务栏登录',() => this.app.navigate(() => { this.app.selectPane('tasks'); input.focus({preventScroll:true}); }), 'session-mobile-login'));
|
|
103
|
+
}
|
|
104
|
+
unlock(csrf) {
|
|
105
|
+
this.csrf = csrf; this.renderSidebar(); this.renderChat(); this.connect();
|
|
106
|
+
const afterLogin = this.afterLogin; this.afterLogin = undefined; afterLogin?.();
|
|
107
|
+
void this.loadGroups();
|
|
108
|
+
const href = window.location.href, task = this.app.taskFromUrl(href);
|
|
109
|
+
if (task) void this.choose(task,{initial:true,href});
|
|
110
|
+
}
|
|
111
|
+
expire() {
|
|
112
|
+
if (!this.csrf) return;
|
|
113
|
+
this.csrf = undefined; this.stream?.close(); clearTimeout(this.watchdog); this.connected = false;
|
|
114
|
+
this.selection?.abort(); this.groupRequest?.abort(); this.generation++;
|
|
115
|
+
this.app.releaseSessionPanels(); this.task = undefined; this.projects.clear();
|
|
116
|
+
this.selecting = false; this.refreshing = undefined; this.app.dataset.taskPending = 'false';
|
|
117
|
+
this.locked('正在检查工作台会话…');
|
|
118
|
+
this.app.updateSessionStatus(false,'未登录');
|
|
119
|
+
void this.session(!this.loggingOut,this.loggingOut ? '已退出工作台。' : '登录已过期,请重新进入。');
|
|
120
|
+
}
|
|
121
|
+
cancelSelection() {
|
|
122
|
+
this.selection?.abort(); this.generation++; this.selecting = false; this.target = this.task?.id;
|
|
123
|
+
this.app.dataset.taskPending = 'false'; this.setChatError(''); this.updateComposer();
|
|
124
|
+
if (this.connected && this.task) void this.refreshConversation(true);
|
|
125
|
+
}
|
|
126
|
+
clearTask() {
|
|
127
|
+
this.selection?.abort(); this.generation++; this.target = undefined; this.selecting = false; this.refreshing = undefined;
|
|
128
|
+
this.app.dataset.taskPending = 'false'; this.task = this.head = undefined; this.turns = [];
|
|
129
|
+
this.lastPosition = this.pendingPosition = undefined;
|
|
130
|
+
this.renderChat(); this.updateSelected();
|
|
131
|
+
if (this.connected) void this.fetch('/focus',{body:{page:this.page,generation:this.generation}}).catch(() => {});
|
|
132
|
+
}
|
|
133
|
+
dispose() {
|
|
134
|
+
this.timelineObserver?.disconnect();
|
|
135
|
+
this.disposed = true; this.stream?.close(); this.selection?.abort(); this.groupRequest?.abort(); clearTimeout(this.searchTimer); clearTimeout(this.watchdog);
|
|
136
|
+
window.removeEventListener('offline',this.offline); window.removeEventListener('online',this.online);
|
|
137
|
+
}
|
|
138
|
+
connect() {
|
|
139
|
+
this.stream?.close(); clearTimeout(this.watchdog); this.connected = false;
|
|
140
|
+
const url = new URL(this.base+'/events',window.location.href); url.searchParams.set('page',this.page);
|
|
141
|
+
const stream = this.stream = new EventSource(url);
|
|
142
|
+
const watch = () => {
|
|
143
|
+
if (this.stream !== stream || !this.csrf) return;
|
|
144
|
+
clearTimeout(this.watchdog);
|
|
145
|
+
this.watchdog = setTimeout(() => { this.app.updateSessionStatus(false,'正在重连'); this.connect(); },36_000);
|
|
146
|
+
};
|
|
147
|
+
watch(); stream.addEventListener('heartbeat',watch);
|
|
148
|
+
stream.addEventListener('sync',() => {
|
|
149
|
+
watch();
|
|
150
|
+
if (this.stream !== stream) return;
|
|
151
|
+
const wasConnected = this.everConnected; this.connected = this.everConnected = true; this.connectionEpoch++;
|
|
152
|
+
this.app.updateSessionStatus(true,'实时连接');
|
|
153
|
+
if (!this.selecting && this.task) void this.refreshConversation(true);
|
|
154
|
+
if (wasConnected) void this.loadGroups(true);
|
|
155
|
+
});
|
|
156
|
+
stream.addEventListener('tasks',() => { if (this.stream === stream) void this.loadGroups(true); });
|
|
157
|
+
stream.addEventListener('expired',() => this.expire());
|
|
158
|
+
stream.addEventListener('tail',event => {
|
|
159
|
+
if (this.stream !== stream) return;
|
|
160
|
+
try {
|
|
161
|
+
const data = {...JSON.parse(event.data), version:Number(event.lastEventId), epoch:this.connectionEpoch};
|
|
162
|
+
if (data.taskId !== this.target || data.generation !== this.generation) return;
|
|
163
|
+
if (this.selecting || this.refreshing) this.bufferedTail = data;
|
|
164
|
+
else if (data.taskId === this.task?.id) this.applyTail(data.value);
|
|
165
|
+
} catch { this.setChatError('实时更新无法读取,请刷新对话。',true); }
|
|
166
|
+
});
|
|
167
|
+
stream.onerror = () => {
|
|
168
|
+
if (this.stream !== stream || !this.csrf) return;
|
|
169
|
+
this.connected = false; this.app.updateSessionStatus(false,'正在重连');
|
|
170
|
+
if (!this.probing) {
|
|
171
|
+
this.probing = true;
|
|
172
|
+
void this.fetch('/session').then(data => { if (!data.csrf) this.expire(); }).catch(() => {}).finally(() => { this.probing = false; });
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
renderSidebar() {
|
|
177
|
+
const bar = make('div','session-task-header'), heading = make('h2',null,'任务');
|
|
178
|
+
const logout = button('退出',async () => {
|
|
179
|
+
logout.disabled = true; this.loggingOut = true;
|
|
180
|
+
try { await this.fetch('/logout',{body:{}}); this.expire(); }
|
|
181
|
+
catch (error) { if (this.csrf) this.listNote.textContent = error.message; }
|
|
182
|
+
finally { logout.disabled = false; this.loggingOut = false; }
|
|
183
|
+
},'session-quiet'); logout.setAttribute('aria-label','退出工作台');
|
|
184
|
+
bar.append(heading,logout);
|
|
185
|
+
const controls = make('div','session-task-controls'), field = this.search = make('input');
|
|
186
|
+
field.type = 'search'; field.placeholder = '搜索任务或项目'; field.setAttribute('aria-label','搜索任务或项目'); field.maxLength = 160;
|
|
187
|
+
const filter = this.filter = make('select'); filter.setAttribute('aria-label','任务筛选');
|
|
188
|
+
for (const [value,title] of [['open','未归档'],['archived','已归档']]) { const o = make('option',null,title); o.value = value; filter.append(o); }
|
|
189
|
+
this.listNote = make('div','session-list-note'); this.listNote.setAttribute('role','status');
|
|
190
|
+
this.groupList = make('div','session-groups');
|
|
191
|
+
field.oninput = event => { if (event.isComposing) return; clearTimeout(this.searchTimer); this.searchTimer = setTimeout(() => this.loadGroups(),220); };
|
|
192
|
+
field.oncompositionend = () => { clearTimeout(this.searchTimer); void this.loadGroups(); };
|
|
193
|
+
filter.onchange = () => { clearTimeout(this.searchTimer); void this.loadGroups(); };
|
|
194
|
+
controls.append(field,filter); this.left.replaceChildren(bar,controls,this.listNote,this.groupList);
|
|
195
|
+
}
|
|
196
|
+
listParams() { return {q:this.search.value.trim(),archived:this.filter.value === 'archived'?'1':undefined}; }
|
|
197
|
+
async loadGroups(refresh = false, more = false) {
|
|
198
|
+
if (!this.csrf || refresh && (this.groupPending || this.projects.size > 30)) return;
|
|
199
|
+
this.groupRequest?.abort(); const controller = this.groupRequest = new AbortController();
|
|
200
|
+
this.groupPending = true;
|
|
201
|
+
const params = this.listParams(), last = more ? [...this.projects.keys()].at(-1) : undefined;
|
|
202
|
+
if (!refresh) this.listNote.replaceChildren(make('span',null,'正在加载项目…'));
|
|
203
|
+
try {
|
|
204
|
+
const data = await this.fetch('/tasks',{params:{...params,after:last},signal:controller.signal});
|
|
205
|
+
if (controller.signal.aborted || !this.csrf) return;
|
|
206
|
+
this.listNote.replaceChildren();
|
|
207
|
+
if (!refresh && !more) { this.groupList.replaceChildren(); this.projects.clear(); }
|
|
208
|
+
const ids = new Set(data.groups.map(group => group.id));
|
|
209
|
+
if (refresh) for (const [id,view] of this.projects) if (!ids.has(id)) { view.node.remove(); this.projects.delete(id); }
|
|
210
|
+
for (const group of data.groups) {
|
|
211
|
+
let view = this.projects.get(group.id);
|
|
212
|
+
if (!view) { view = this.createGroup(group); this.projects.set(group.id,view); }
|
|
213
|
+
view.title.textContent = group.name; view.count.textContent = String(group.count);
|
|
214
|
+
view.title.title = group.root || group.name;
|
|
215
|
+
if (view.node.open) void this.loadGroup(view,false,refresh);
|
|
216
|
+
}
|
|
217
|
+
this.groupMore?.remove();
|
|
218
|
+
if (data.more) { this.groupMore = button('更多项目',() => this.loadGroups(false,true),'session-more'); this.groupList.append(this.groupMore); }
|
|
219
|
+
if (!this.projects.size) this.listNote.textContent = params.q ? '没有匹配的任务。' : '暂无'+(params.archived?'已归档':'未归档')+'任务。';
|
|
220
|
+
} catch (error) {
|
|
221
|
+
if (!controller.signal.aborted && this.csrf) this.listNote.replaceChildren(make('span','session-error',refresh?'任务列表暂未更新。':error.message),button('重试',() => this.loadGroups(),'session-quiet'));
|
|
222
|
+
} finally { if (this.groupRequest === controller) this.groupPending = false; }
|
|
223
|
+
}
|
|
224
|
+
createGroup(group) {
|
|
225
|
+
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};
|
|
227
|
+
summary.append(title,count); node.append(summary,rows); this.groupList.append(node);
|
|
228
|
+
node.open = Boolean(this.search.value || this.openGroups.has(group.id) || this.task?.project.id === group.id || this.projects.size === 0);
|
|
229
|
+
node.ontoggle = () => {
|
|
230
|
+
if (node.open) { this.openGroups.add(group.id); if (!view.items.length) void this.loadGroup(view); }
|
|
231
|
+
else this.openGroups.delete(group.id);
|
|
232
|
+
if (!this.search.value) save('agentbot-workspace-groups',[...this.openGroups].slice(-100));
|
|
233
|
+
};
|
|
234
|
+
return view;
|
|
235
|
+
}
|
|
236
|
+
async loadGroup(view, more = false, refresh = false) {
|
|
237
|
+
if (!this.csrf || view.loading || refresh && view.items.length > 20) return;
|
|
238
|
+
view.loading = true; const sequence = ++view.sequence, params = this.listParams();
|
|
239
|
+
if (!refresh && !more) view.rows.replaceChildren(make('div','session-list-note','加载任务…'));
|
|
240
|
+
try {
|
|
241
|
+
const data = await this.fetch('/tasks',{params:{...params,project:view.group.id,after:more?view.items.at(-1)?.id:undefined}});
|
|
242
|
+
if (!view.node.isConnected || sequence !== view.sequence || !this.csrf) return;
|
|
243
|
+
const items = more ? [...new Map([...view.items,...data.items].map(item => [item.id,item])).values()] : data.items;
|
|
244
|
+
const signature = JSON.stringify([items,data.more]);
|
|
245
|
+
if (signature !== view.signature) {
|
|
246
|
+
const focused = document.activeElement?.dataset?.sessionTask;
|
|
247
|
+
view.items = items; view.signature = signature;
|
|
248
|
+
view.rows.replaceChildren(...items.map(item => this.taskButton(item)));
|
|
249
|
+
if (data.more) view.rows.append(button('更多任务',() => this.loadGroup(view,true),'session-more'));
|
|
250
|
+
if (focused) [...view.rows.querySelectorAll('[data-session-task]')].find(node => node.dataset.sessionTask === focused)?.focus({preventScroll:true});
|
|
251
|
+
}
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (view.node.isConnected && !refresh) { view.signature = undefined; view.rows.replaceChildren(make('span','session-list-note session-error',error.message),button('重试',() => this.loadGroup(view),'session-quiet')); }
|
|
254
|
+
} finally { view.loading = false; }
|
|
255
|
+
}
|
|
256
|
+
taskButton(item) {
|
|
257
|
+
const node = button('',() => this.choose(item.id),'session-task'), title = make('span','session-task-title',item.title);
|
|
258
|
+
const dot = make('span','session-dot'); dot.dataset.status = item.status; dot.setAttribute('aria-hidden','true');
|
|
259
|
+
node.append(dot,title); node.dataset.sessionTask = item.id; node.title = `${item.title} · ${status(item.status)} · ${item.agent}`;
|
|
260
|
+
node.setAttribute('aria-label',node.title);
|
|
261
|
+
if (item.id === this.task?.id) node.setAttribute('aria-current','true'); return node;
|
|
262
|
+
}
|
|
263
|
+
updateSelected() {
|
|
264
|
+
for (const node of this.groupList?.querySelectorAll('[data-session-task]') || []) {
|
|
265
|
+
if (node.dataset.sessionTask === this.task?.id) node.setAttribute('aria-current','true'); else node.removeAttribute('aria-current');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
async choose(taskId, nav = {}) {
|
|
269
|
+
if (!this.csrf || !taskId || this.task?.id === taskId && !nav.history && !this.selecting) {
|
|
270
|
+
if (this.task?.id === taskId) this.app.navigate(() => this.app.selectPane('chat'),true);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
this.selection?.abort(); const controller = this.selection = new AbortController();
|
|
274
|
+
const generation = ++this.generation; this.target = taskId; this.selecting = true; this.bufferedTail = undefined; this.refreshing = undefined;
|
|
275
|
+
this.app.dataset.taskPending = 'true';
|
|
276
|
+
const position = nav.position?.chat || (nav.href ? this.app.chatPositionFromUrl(nav.href) : this.app.savedSessionChat(taskId));
|
|
277
|
+
const anchor = position?.turn;
|
|
278
|
+
let snapshot;
|
|
279
|
+
this.setChatError('正在打开任务…'); this.updateComposer();
|
|
280
|
+
try {
|
|
281
|
+
const data = snapshot = await this.loadTask(taskId,generation,anchor,controller.signal);
|
|
282
|
+
if (controller.signal.aborted || !this.csrf || generation !== this.generation) return;
|
|
283
|
+
this.app.activateTaskPanel(data.task,nav,() => {
|
|
284
|
+
this.task = data.task; this.head = data.head; this.headStatus = data.headStatus; this.anchored = data.anchored;
|
|
285
|
+
this.turns = data.turns; this.more = data.more; this.turnNodes.clear(); this.timeline.replaceChildren();
|
|
286
|
+
this.pendingPosition = position || {bottom:true}; this.input.value = this.draft(taskId); this.checkOperation(taskId,false);
|
|
287
|
+
this.renderConversation(); this.updateSelected();
|
|
288
|
+
});
|
|
289
|
+
this.setChatError('');
|
|
290
|
+
if (!nav.history && !nav.initial && !this.left.clientHeight) this.chatTitle.focus({preventScroll:true});
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (!controller.signal.aborted && this.csrf) {
|
|
293
|
+
const message = `无法打开任务:${error.status ? error.message : '连接失败,请重试。'}`;
|
|
294
|
+
const retry = () => this.choose(taskId,nav);
|
|
295
|
+
this.setChatError(message,false,retry);
|
|
296
|
+
if (this.app.dataset.pane === 'tasks') this.listNote.replaceChildren(make('span','session-error',message),button('重试',retry,'session-quiet'));
|
|
297
|
+
if (nav.history) this.app.finishHistoryTraversal();
|
|
298
|
+
}
|
|
299
|
+
} finally {
|
|
300
|
+
if (generation === this.generation) {
|
|
301
|
+
this.selecting = false; this.app.dataset.taskPending = 'false'; this.updateComposer(); this.restorePosition();
|
|
302
|
+
if (!snapshot) this.target = this.task?.id;
|
|
303
|
+
this.drainTail(snapshot);
|
|
304
|
+
if (this.connected && this.task && (!snapshot || snapshot.epoch !== this.connectionEpoch)) void this.refreshConversation(true);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async loadTask(task,generation,anchor,signal) {
|
|
309
|
+
if (this.connected) {
|
|
310
|
+
const epoch = this.connectionEpoch;
|
|
311
|
+
try { return {...await this.fetch('/focus',{body:{page:this.page,task,generation,anchor},signal}),epoch}; }
|
|
312
|
+
catch (error) { if (error.status !== 409) throw error; }
|
|
313
|
+
}
|
|
314
|
+
return this.fetch('/task',{params:{task,anchor},signal});
|
|
315
|
+
}
|
|
316
|
+
drainTail(snapshot) {
|
|
317
|
+
const tail = this.bufferedTail; this.bufferedTail = undefined;
|
|
318
|
+
if (tail && tail.taskId === this.task?.id && tail.generation === this.generation && tail.epoch === this.connectionEpoch
|
|
319
|
+
&& (snapshot?.epoch !== tail.epoch || tail.version > snapshot.version)) this.applyTail(tail.value);
|
|
320
|
+
}
|
|
321
|
+
applyTail(data) {
|
|
322
|
+
if (!this.task) return;
|
|
323
|
+
if (!data) { this.setChatError('此任务已不可用。'); this.task.status = 'closed'; this.updateComposer(); return; }
|
|
324
|
+
const previous = this.head;
|
|
325
|
+
Object.assign(this.task,data.task,{queued:data.queued});
|
|
326
|
+
this.headStatus = data.turn?.status;
|
|
327
|
+
if ((data.turn?.id || undefined) !== previous) {
|
|
328
|
+
if (!this.anchored) void this.refreshConversation(false);
|
|
329
|
+
else { this.head = data.turn?.id; this.jump.hidden = false; }
|
|
330
|
+
} else if (data.turn) {
|
|
331
|
+
const i = this.turns.findIndex(turn => turn.id === data.turn.id);
|
|
332
|
+
if (i >= 0) { this.turns[i] = data.turn; this.redraw(); }
|
|
333
|
+
}
|
|
334
|
+
this.updateComposer(); this.renderChatHeader();
|
|
335
|
+
}
|
|
336
|
+
async refreshConversation(refocus, latest = false) {
|
|
337
|
+
const task = this.task?.id;
|
|
338
|
+
if (!task || this.selecting || this.refreshing && !refocus && !latest) return;
|
|
339
|
+
const generation = this.generation, refresh = this.refreshing = {};
|
|
340
|
+
let snapshot;
|
|
341
|
+
const position = latest ? {bottom:true} : this.position();
|
|
342
|
+
try {
|
|
343
|
+
const anchor = this.anchored && !latest ? position?.turn : undefined;
|
|
344
|
+
const data = snapshot = await this.loadTask(task,generation,anchor);
|
|
345
|
+
if (generation !== this.generation || refresh !== this.refreshing || this.selecting) return;
|
|
346
|
+
const first = data.turns[0]?.id, overlap = this.turns.findIndex(turn => turn.id === first);
|
|
347
|
+
this.turns = !latest && overlap >= 0 ? [...this.turns.slice(0,overlap),...data.turns] : data.turns;
|
|
348
|
+
this.more = !latest && overlap > 0 ? this.more : data.more;
|
|
349
|
+
this.head = data.head; this.headStatus = data.headStatus; this.anchored = data.anchored; this.task = data.task;
|
|
350
|
+
this.pendingPosition = position; this.renderConversation(); this.setChatError('');
|
|
351
|
+
} catch (error) { if (generation === this.generation && this.csrf) this.setChatError('对话更新失败:'+error.message,true); }
|
|
352
|
+
finally {
|
|
353
|
+
if (this.refreshing === refresh) {
|
|
354
|
+
this.refreshing = undefined;
|
|
355
|
+
this.drainTail(snapshot);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
renderChat() {
|
|
360
|
+
this.chatHeader = make('header','session-chat-header');
|
|
361
|
+
this.chatTitle = make('h2',null,'聊天'); this.chatTitle.tabIndex = -1; this.chatMeta = make('div','session-chat-meta'); this.chatHeader.append(this.chatTitle,this.chatMeta);
|
|
362
|
+
this.chatError = make('div','session-chat-error'); this.chatError.setAttribute('role','status'); this.chatError.hidden = true;
|
|
363
|
+
this.body = make('div','chat-body session-chat-body'); this.body.tabIndex = 0; this.body.setAttribute('role','region'); this.body.setAttribute('aria-label','对话记录');
|
|
364
|
+
this.older = button('加载更早的对话',() => this.loadOlder(),'session-more session-older'); this.older.hidden = true;
|
|
365
|
+
this.timeline = make('div','session-timeline'); this.turnNodes = new Map();
|
|
366
|
+
this.timelineObserver?.disconnect();
|
|
367
|
+
this.timelineObserver = new ResizeObserver(() => {
|
|
368
|
+
if (!this.task || !this.body.clientHeight) return;
|
|
369
|
+
this.pendingPosition ||= this.lastPosition;
|
|
370
|
+
this.restorePosition();
|
|
371
|
+
});
|
|
372
|
+
this.timelineObserver.observe(this.timeline);
|
|
373
|
+
this.timeline.addEventListener('error', event => {
|
|
374
|
+
const image = event.target;
|
|
375
|
+
if (image instanceof HTMLImageElement) image.replaceWith(make('span','session-image-unavailable',image.alt ? `图片不可用:${image.alt}` : '图片不可用'));
|
|
376
|
+
}, true);
|
|
377
|
+
this.timeline.append(make('div','session-empty','从左侧选择一个任务,查看对话并继续工作。'));
|
|
378
|
+
this.body.append(this.older,this.timeline);
|
|
379
|
+
this.jump = button('回到最新',() => this.refreshConversation(false,true),'session-jump'); this.jump.hidden = true;
|
|
380
|
+
this.body.onscroll = () => {
|
|
381
|
+
if (!this.task || !this.body.clientHeight) return;
|
|
382
|
+
if (!this.pendingPosition) this.lastPosition = this.position(true);
|
|
383
|
+
if (!this.anchored) this.jump.hidden = this.atBottom();
|
|
384
|
+
};
|
|
385
|
+
const form = this.composer = make('form','chat-composer session-composer');
|
|
386
|
+
this.input = make('textarea'); this.input.rows = 2; this.input.maxLength = 24_000; this.input.setAttribute('aria-label','发送给 Agent 的消息');
|
|
387
|
+
this.input.oninput = () => { if (this.task) this.setDraft(this.task.id,this.input.value); this.updateComposer(); };
|
|
388
|
+
this.input.onkeydown = event => { if (event.key === 'Enter' && !event.isComposing && !this.composing && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void this.submit('send'); } };
|
|
389
|
+
this.input.oncompositionstart = () => { this.composing = true; }; this.input.oncompositionend = () => { this.composing = false; };
|
|
390
|
+
this.opNote = make('div','session-operation'); this.opNote.setAttribute('role','status'); this.opNote.hidden = true;
|
|
391
|
+
const actions = make('div','session-composer-actions'); this.queue = button('排队',() => this.submit('queue'),'session-quiet');
|
|
392
|
+
this.stop = button('停止',() => this.submit('stop'),'session-stop'); this.stop.hidden = true;
|
|
393
|
+
this.send = make('button','session-primary','发送'); this.send.type = 'submit'; this.send.title = 'Ctrl / ⌘ + Enter';
|
|
394
|
+
this.queueCount = make('small','session-queued'); actions.append(this.queueCount,this.stop,this.queue,this.send); form.append(this.input,actions);
|
|
395
|
+
form.onsubmit = event => { event.preventDefault(); void this.submit('send'); };
|
|
396
|
+
this.chat.replaceChildren(this.chatHeader,this.chatError,this.body,this.jump,this.opNote,form);
|
|
397
|
+
this.updateComposer();
|
|
398
|
+
}
|
|
399
|
+
setChatError(message, retry = false, action) {
|
|
400
|
+
if (!this.chatError?.isConnected) return;
|
|
401
|
+
this.chatError.replaceChildren(make('span',null,message)); this.chatError.hidden = !message;
|
|
402
|
+
if (retry || action) this.chatError.append(button('重试',action || (() => this.refreshConversation(true)),'session-quiet'));
|
|
403
|
+
}
|
|
404
|
+
renderChatHeader() {
|
|
405
|
+
const task = this.task;
|
|
406
|
+
this.chatTitle.textContent = task?.title || '聊天'; this.chatTitle.title = this.chatTitle.textContent;
|
|
407
|
+
this.chatMeta.replaceChildren();
|
|
408
|
+
if (!task) return;
|
|
409
|
+
const badge = make('span','session-state',status(task.status)); badge.dataset.status = task.status;
|
|
410
|
+
const info = make('span','session-model',[task.agent,task.provider,task.model].filter(Boolean).join(' · ')); info.title = info.textContent;
|
|
411
|
+
this.chatMeta.append(badge,info);
|
|
412
|
+
}
|
|
413
|
+
renderConversation() {
|
|
414
|
+
this.renderChatHeader(); this.redraw(); this.updateComposer();
|
|
415
|
+
this.older.hidden = !this.more;
|
|
416
|
+
if (this.anchored) this.jump.hidden = false;
|
|
417
|
+
}
|
|
418
|
+
redraw() {
|
|
419
|
+
const position = this.pendingPosition || this.position();
|
|
420
|
+
if (!this.turns.length) this.timeline.replaceChildren(make('div','session-empty','还没有对话。发送一条消息,开始新的轮次。'));
|
|
421
|
+
else {
|
|
422
|
+
this.timeline.querySelector('.session-empty')?.remove();
|
|
423
|
+
const keep = new Set(this.turns.map(turn => turn.id));
|
|
424
|
+
for (const [id,state] of this.turnNodes) if (!keep.has(id)) { state.node.remove(); this.turnNodes.delete(id); }
|
|
425
|
+
let previous = null;
|
|
426
|
+
for (const turn of this.turns) {
|
|
427
|
+
const node = this.renderTurn(turn), next = previous ? previous.nextSibling : this.timeline.firstChild;
|
|
428
|
+
if (node !== next) this.timeline.insertBefore(node,next);
|
|
429
|
+
previous = node;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
this.pendingPosition = position; this.restorePosition();
|
|
433
|
+
}
|
|
434
|
+
renderTurn(turn) {
|
|
435
|
+
let entry = this.turnNodes.get(turn.id);
|
|
436
|
+
if (!entry) {
|
|
437
|
+
const node = make('article','session-turn'); node.dataset.turn = turn.id;
|
|
438
|
+
const header = make('div','session-turn-meta'), content = make('div','session-turn-content'), details = make('details','session-turn-details');
|
|
439
|
+
const summary = make('summary',null,'执行过程'), body = make('div','session-detail-body');
|
|
440
|
+
details.append(summary,body); node.append(header,content,details);
|
|
441
|
+
entry = {node,header,content,details,body,rows:new Map()}; this.turnNodes.set(turn.id,entry);
|
|
442
|
+
details.ontoggle = () => { if (details.open && !entry.loaded) void this.loadDetail(turn.id,entry); };
|
|
443
|
+
}
|
|
444
|
+
const signature = JSON.stringify(turn);
|
|
445
|
+
if (entry.signature === signature) return entry.node;
|
|
446
|
+
entry.signature = signature;
|
|
447
|
+
const time = Number.isFinite(turn.startedAt) && turn.startedAt > 0 ? new Date(turn.startedAt).toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}) : '';
|
|
448
|
+
entry.header.textContent = [time,status(turn.status),turn.summary?'仅有摘要':null,turn.delivered === false?'飞书待投递':null].filter(Boolean).join(' · ');
|
|
449
|
+
const rows = new Map();
|
|
450
|
+
const place = (key, value, build) => {
|
|
451
|
+
const old = entry.rows.get(key), signature = JSON.stringify(value);
|
|
452
|
+
rows.set(key,old?.signature === signature ? old : {signature,node:build()});
|
|
453
|
+
};
|
|
454
|
+
const message = (key, name, role, text, images, answer) => place(key,[role,text,images,answer],() => {
|
|
455
|
+
const node = make('section','session-message '+role); node.append(make('div','session-message-label',name));
|
|
456
|
+
if (text) node.append(make('div','session-message-text',text));
|
|
457
|
+
if (images?.length) {
|
|
458
|
+
const attachments = make('div','session-message-images');
|
|
459
|
+
for (const [index,src] of images.entries()) {
|
|
460
|
+
if (!src) { attachments.append(make('span','session-image-unavailable','图片不可用')); continue; }
|
|
461
|
+
const image = make('img'); image.alt = `附件 ${index+1}`; image.loading = 'lazy'; image.decoding = 'async'; image.src = src;
|
|
462
|
+
attachments.append(image);
|
|
463
|
+
}
|
|
464
|
+
node.append(attachments);
|
|
465
|
+
}
|
|
466
|
+
if (answer) {
|
|
467
|
+
const rich = make('div','markdown-body'); rich.innerHTML = answer.html;
|
|
468
|
+
rich.onclick = event => {
|
|
469
|
+
const a = event.target.closest('[data-chat-file]'); if (!a || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
|
470
|
+
event.preventDefault(); this.app.openChatFile(a.dataset.chatFile,'file',a.getAttribute('href')?.slice(1)?a.getAttribute('href'):undefined);
|
|
471
|
+
};
|
|
472
|
+
node.append(rich); if (answer.truncated) node.append(make('small','session-muted','回答较长,此处只显示前一部分。'));
|
|
473
|
+
}
|
|
474
|
+
return node;
|
|
475
|
+
});
|
|
476
|
+
if (turn.prompt || turn.promptImages?.length) message('prompt','你','user',turn.prompt,turn.promptImages);
|
|
477
|
+
for (const item of turn.messages) message('message:'+item.id,item.role === 'user'?'你 · 追加':'Agent',item.role,item.text,item.images,item.rich);
|
|
478
|
+
if (turn.answer) message('answer','Agent','assistant',undefined,undefined,turn.answer);
|
|
479
|
+
if (turn.error) place('error',turn.error,() => make('p','session-error session-turn-error',turn.error));
|
|
480
|
+
if (turn.status === 'waiting_for_approval') place('approval',true,() => make('p','session-waiting','请到任务原来的飞书会话确认。'));
|
|
481
|
+
if (!rows.size) place('waiting',true,() => make('div','session-muted','正在等待 Agent 的输出…'));
|
|
482
|
+
for (const [key,old] of entry.rows) if (rows.get(key) !== old) old.node.remove();
|
|
483
|
+
let next = entry.content.firstChild;
|
|
484
|
+
for (const {node} of rows.values()) {
|
|
485
|
+
if (node !== next) entry.content.insertBefore(node,next);
|
|
486
|
+
next = node.nextSibling;
|
|
487
|
+
}
|
|
488
|
+
entry.rows = rows;
|
|
489
|
+
if (entry.details.open && entry.loaded && entry.loadedStatus !== turn.status) { entry.loaded = false; void this.loadDetail(turn.id,entry); }
|
|
490
|
+
entry.status = turn.status; return entry.node;
|
|
491
|
+
}
|
|
492
|
+
async loadDetail(id, entry) {
|
|
493
|
+
if (entry.loading || !this.task) return;
|
|
494
|
+
const task = this.task.id, generation = this.generation; entry.loading = true;
|
|
495
|
+
entry.body.replaceChildren(make('span','session-muted','正在读取执行过程…'));
|
|
496
|
+
try {
|
|
497
|
+
const data = await this.fetch('/detail',{params:{task,turn:id}});
|
|
498
|
+
if (generation !== this.generation || this.turnNodes.get(id) !== entry) return;
|
|
499
|
+
entry.body.replaceChildren();
|
|
500
|
+
if (data.plan.length) {
|
|
501
|
+
const list = make('ol','session-plan'); for (const item of data.plan) list.append(make('li',null,`${item.status === 'completed'?'✓ ':''}${item.text}`)); entry.body.append(list);
|
|
502
|
+
}
|
|
503
|
+
for (const tool of data.tools) {
|
|
504
|
+
const details = make('details','session-tool'), summary = make('summary',null,`${tool.title || '工具'} · ${status(tool.status)}`), output = make('div','session-tool-output');
|
|
505
|
+
details.append(summary); if (tool.command) details.append(make('pre',null,tool.command)); details.append(output); entry.body.append(details);
|
|
506
|
+
if (!tool.hasOutput) continue;
|
|
507
|
+
let loading = false, loaded = false;
|
|
508
|
+
const fetchOutput = async () => {
|
|
509
|
+
if (loading || loaded || generation !== this.generation) return;
|
|
510
|
+
loading = true; output.replaceChildren(make('span','session-muted','正在读取工具输出…'));
|
|
511
|
+
try {
|
|
512
|
+
const result = await this.fetch('/tool',{params:{task,turn:id,tool:tool.id}});
|
|
513
|
+
if (!output.isConnected || generation !== this.generation) return;
|
|
514
|
+
loaded = tool.status !== 'running'; output.replaceChildren();
|
|
515
|
+
const text = [result.output,result.error].filter(Boolean).join('\n\n');
|
|
516
|
+
if (text) output.append(make('pre',null,text)); else output.append(make('span','session-muted','该工具暂无输出。'));
|
|
517
|
+
if (result.truncated) output.append(make('p','session-muted','仅显示部分输出。完整记录请在原飞书会话打开 Turn Preview。'));
|
|
518
|
+
} catch (error) {
|
|
519
|
+
if (output.isConnected && generation === this.generation) output.replaceChildren(make('span','session-error',error.message),button('重试',fetchOutput,'session-quiet'));
|
|
520
|
+
} finally { loading = false; }
|
|
521
|
+
};
|
|
522
|
+
details.ontoggle = () => { if (details.open) void fetchOutput(); };
|
|
523
|
+
}
|
|
524
|
+
for (const change of data.changes) {
|
|
525
|
+
entry.body.append(change.entry ? button(change.name,() => this.app.openChatFile(change.entry,'diff'), 'session-quiet') : make('div','session-muted',change.name));
|
|
526
|
+
}
|
|
527
|
+
if (data.changes.length) entry.body.append(make('div','session-muted','文件名来自本轮记录,打开的是当前 Git 工作区的变更。'));
|
|
528
|
+
if (!entry.body.firstChild || data.compact) entry.body.append(make('div','session-muted',entry.body.firstChild?'此处显示已保存的执行摘要。':'暂无可显示的执行过程。'));
|
|
529
|
+
entry.loaded = true; entry.loadedStatus = entry.status;
|
|
530
|
+
} catch (error) {
|
|
531
|
+
if (generation === this.generation) entry.body.replaceChildren(make('span','session-error',error.message),button('重试',() => this.loadDetail(id,entry),'session-quiet'));
|
|
532
|
+
} finally { entry.loading = false; }
|
|
533
|
+
}
|
|
534
|
+
async loadOlder() {
|
|
535
|
+
if (!this.task || !this.more || !this.turns.length || this.older.disabled) return;
|
|
536
|
+
const generation = this.generation, task = this.task.id, before = this.turns[0].id;
|
|
537
|
+
this.older.disabled = true; this.older.textContent = '正在加载…';
|
|
538
|
+
try {
|
|
539
|
+
const data = await this.fetch('/task',{params:{task,before}});
|
|
540
|
+
if (generation !== this.generation) return;
|
|
541
|
+
this.pendingPosition = this.position(); this.turns = [...new Map([...data.turns,...this.turns].map(turn => [turn.id,turn])).values()]; this.more = data.more;
|
|
542
|
+
this.renderConversation();
|
|
543
|
+
} catch (error) { if (generation === this.generation) this.setChatError('历史读取失败:'+error.message,false,() => error.status === 409 ? this.refreshConversation(false,true) : this.loadOlder()); }
|
|
544
|
+
finally { this.older.disabled = false; this.older.textContent = '加载更早的对话'; }
|
|
545
|
+
}
|
|
546
|
+
restoreHistoryPosition(position) {
|
|
547
|
+
this.pendingPosition = position;
|
|
548
|
+
if (position.bottom && this.anchored) void this.refreshConversation(false,true);
|
|
549
|
+
else if (position.turn && !this.turnNodes.has(position.turn)) {
|
|
550
|
+
this.anchored = true;
|
|
551
|
+
void this.refreshConversation(true);
|
|
552
|
+
} else this.restorePosition();
|
|
553
|
+
}
|
|
554
|
+
atBottom() { return this.body.scrollHeight-this.body.scrollTop-this.body.clientHeight < 36; }
|
|
555
|
+
position(measure = false) {
|
|
556
|
+
if (this.pendingPosition && !measure) return this.pendingPosition;
|
|
557
|
+
if (!this.task || !this.body?.clientHeight) return this.lastPosition;
|
|
558
|
+
if (!this.anchored && this.atBottom()) return {bottom:true};
|
|
559
|
+
const top = this.body.getBoundingClientRect().top;
|
|
560
|
+
for (const node of this.timeline.children) {
|
|
561
|
+
const rect = node.getBoundingClientRect();
|
|
562
|
+
if (node.dataset.turn && rect.bottom > top + 1) return {turn:node.dataset.turn,offset:Math.round(top-rect.top)};
|
|
563
|
+
}
|
|
564
|
+
return {bottom:true};
|
|
565
|
+
}
|
|
566
|
+
restorePosition() {
|
|
567
|
+
if (!this.pendingPosition || !this.body?.clientHeight) return;
|
|
568
|
+
const position = this.pendingPosition; this.pendingPosition = undefined;
|
|
569
|
+
if (position.bottom) this.body.scrollTop = this.body.scrollHeight;
|
|
570
|
+
else {
|
|
571
|
+
const node = this.turnNodes.get(position.turn)?.node;
|
|
572
|
+
if (node) this.body.scrollTop += node.getBoundingClientRect().top - this.body.getBoundingClientRect().top + position.offset;
|
|
573
|
+
else this.body.scrollTop = this.body.scrollHeight;
|
|
574
|
+
}
|
|
575
|
+
this.lastPosition = this.position(true); this.jump.hidden = !this.anchored && this.atBottom();
|
|
576
|
+
}
|
|
577
|
+
draft(id) { return this.drafts.get(id) ?? read('agentbot-workspace-draft:'+id,'','sessionStorage'); }
|
|
578
|
+
setDraft(id,text) { this.drafts.set(id,text); save('agentbot-workspace-draft:'+id,text,'sessionStorage'); }
|
|
579
|
+
operation(id) { return this.operations.get(id) ?? read('agentbot-workspace-operation:'+id,null,'sessionStorage'); }
|
|
580
|
+
setOperation(id,op) {
|
|
581
|
+
this.operations.set(id,op); save('agentbot-workspace-operation:'+id,op,'sessionStorage');
|
|
582
|
+
if (this.task?.id === id) this.updateComposer();
|
|
583
|
+
}
|
|
584
|
+
updateComposer() {
|
|
585
|
+
const task = this.task, running = activeTurn(this.headStatus), archived = task?.status === 'closed';
|
|
586
|
+
const op = task && this.operation(task.id), blocked = !task || archived || this.selecting || Boolean(op?.status === 'pending' || op?.status === 'unknown');
|
|
587
|
+
this.input.disabled = !task || archived || Boolean(this.selecting);
|
|
588
|
+
this.input.placeholder = archived ? '任务已归档' : !task ? '选择任务后继续' : '输入消息…';
|
|
589
|
+
this.send.disabled = this.queue.disabled = blocked || !this.input.value.trim();
|
|
590
|
+
this.send.textContent = running ? '追加' : '发送';
|
|
591
|
+
this.stop.hidden = !running || archived;
|
|
592
|
+
this.stop.disabled = blocked;
|
|
593
|
+
this.queueCount.textContent = task?.queued ? `${task.queued} 条排队` : '';
|
|
594
|
+
this.opNote.replaceChildren(); this.opNote.hidden = !op?.message;
|
|
595
|
+
if (op?.message) {
|
|
596
|
+
this.opNote.append(make('span',op.status === 'unknown' || op.status === 'failed'?'session-error':null,op.message));
|
|
597
|
+
if (op.status === 'unknown' || op.status === 'pending') this.opNote.append(button('核实状态',() => this.checkOperation(task.id,true),'session-quiet'));
|
|
598
|
+
if (op.status === 'unknown') this.opNote.append(button('我已核实',() => this.setOperation(task.id,null),'session-quiet'));
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
async submit(action) {
|
|
602
|
+
const task = this.task?.id;
|
|
603
|
+
if (!task || this.selecting || (action === 'stop' ? this.stop.disabled || this.stop.hidden : this.send.disabled)) return;
|
|
604
|
+
const text = this.input.value.trim(), request = uuid(), turn = this.head;
|
|
605
|
+
const payload = {task,request,action,...(action === 'stop'?{turn}:{text})};
|
|
606
|
+
const pending = {request,action,submittedText:action === 'stop'?undefined:text};
|
|
607
|
+
this.setOperation(task,{...pending,status:'pending',message:action === 'stop'?'正在请求停止…':'正在提交…'});
|
|
608
|
+
try { this.handleOperation(task,request,action,await this.fetch('/operation',{body:payload}),text); }
|
|
609
|
+
catch (error) {
|
|
610
|
+
if ((error.status >= 400 && error.status < 500 && error.status !== 408) || (error.status === 503 && error.message.includes('未提交'))) {
|
|
611
|
+
this.setOperation(task,{request,action,status:'failed',message:error.message});
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
this.setOperation(task,{...pending,status:'unknown',message:'连接中断,结果待核实。没有自动重发。'});
|
|
615
|
+
void this.checkOperation(task,false);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
handleOperation(task,request,action,result,text) {
|
|
620
|
+
const op = this.operation(task); if (op?.request !== request) return;
|
|
621
|
+
text ??= op.submittedText;
|
|
622
|
+
if (result.status === 'accepted' && action !== 'stop' && text !== undefined && this.draft(task).trim() === text) {
|
|
623
|
+
this.setDraft(task,''); if (this.task?.id === task) this.input.value = '';
|
|
624
|
+
}
|
|
625
|
+
const message = result.status === 'accepted' ? ({send:'消息已受理,正在等待 Agent。',queue:'已加入队列。',stop:'已请求停止此轮。'})[action]
|
|
626
|
+
: result.status === 'pending' ? '服务端正在处理,可以稍后核实。'
|
|
627
|
+
: result.status === 'stale' ? '这一轮已结束,没有停止后续轮次。'
|
|
628
|
+
: result.status === 'unknown' ? `${result.posted?'消息已发到飞书,Agent 提交结果待核实。':'操作结果待核实。'}没有自动重发。`
|
|
629
|
+
: 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};
|
|
633
|
+
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
|
+
}
|
|
638
|
+
}
|
|
639
|
+
async checkOperation(task, explicit) {
|
|
640
|
+
const op = this.operation(task); if (!op || !['pending','unknown'].includes(op.status)) return;
|
|
641
|
+
try { this.handleOperation(task,op.request,op.action,await this.fetch('/operation',{params:{request:op.request}})); }
|
|
642
|
+
catch (error) {
|
|
643
|
+
if (explicit && this.operation(task)?.request === op.request) this.setOperation(task,{...op,status:'unknown',message:'仍未能确认操作结果:'+error.message+' 请检查对话后再发送。'});
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
window.AgentBotSessionWorkspace = SessionWorkspace;
|
|
648
|
+
})();
|