846 lines
31 KiB
JavaScript
846 lines
31 KiB
JavaScript
(() => {
|
||
'use strict';
|
||
let api, esc, formatDate, notify, user;
|
||
const states = {
|
||
running: '正在分析',
|
||
success: '已完成',
|
||
error: '失败',
|
||
cancelled: '已停止',
|
||
interrupted: '已中断',
|
||
};
|
||
async function render(container, isActive = () => true) {
|
||
const data = await api('/assistant');
|
||
if (!isActive()) return;
|
||
const key = 'order-assistant:' + user.username,
|
||
drafts = new Map(),
|
||
pendingActions = new Map();
|
||
let submitting = false,
|
||
disposed = false,
|
||
currentId = sessionStorage.getItem(key) || '',
|
||
conversation = null,
|
||
events = [],
|
||
revision = 0,
|
||
listRevision = 0,
|
||
loadChain = Promise.resolve(),
|
||
listPage = 1,
|
||
listTotal = 0,
|
||
scope = 'active',
|
||
listError = false,
|
||
managing = false,
|
||
creating = false,
|
||
watchTimer = null,
|
||
eventClient = null,
|
||
searchTimer = null,
|
||
pendingRequest = null,
|
||
usageSignature = '';
|
||
const live = () => !disposed && isActive() && container.isConnected;
|
||
const layout = window.AssistantLayout.mount(container, {
|
||
settings: data.settings,
|
||
usage: data.usage,
|
||
esc,
|
||
}),
|
||
root = layout.root;
|
||
let picker, attachmentManager;
|
||
const input = root.querySelector('#assistant-input'),
|
||
send = root.querySelector('#assistant-send'),
|
||
stop = root.querySelector('#assistant-stop'),
|
||
error = root.querySelector('#assistant-error'),
|
||
messages = root.querySelector('#assistant-messages');
|
||
send.disabled = true;
|
||
function showError(e) {
|
||
if (live()) error.textContent = e.message;
|
||
}
|
||
const panel = window.AssistantContextPanel.mount(root, {
|
||
api,
|
||
esc,
|
||
formatDate,
|
||
user,
|
||
settings: data.settings,
|
||
isActive: live,
|
||
showRight: () => layout.showRight(),
|
||
onExecute: execute,
|
||
onRepair: repair,
|
||
ensureConversation,
|
||
onScheduleChanged: async (id) => {
|
||
if (!live() || id !== currentId) return;
|
||
if (!eventClient) await select(id);
|
||
else await loadCurrent();
|
||
},
|
||
});
|
||
const taskManager = window.AssistantScheduleManager.mount(root, {
|
||
api,
|
||
esc,
|
||
formatDate,
|
||
user,
|
||
getConversation: () => conversation,
|
||
ensureConversation,
|
||
isActive: live,
|
||
onChanged: async (id) => {
|
||
if (!live() || id !== currentId) return;
|
||
if (!eventClient) await select(id);
|
||
else await loadCurrent();
|
||
},
|
||
});
|
||
root.querySelector('#assistant-schedules').onclick = () => taskManager.open();
|
||
root
|
||
.querySelector('#aw-panel-schedules')
|
||
.insertAdjacentHTML(
|
||
'afterbegin',
|
||
'<button type="button" class="btn btn-sm mb-3" data-open-task-manager>管理全部任务</button>',
|
||
);
|
||
root.querySelector('[data-open-task-manager]').onclick = () => taskManager.open();
|
||
const transcript = window.AssistantConversation.mount(messages, {
|
||
esc,
|
||
formatDate,
|
||
user,
|
||
onActions: () => panel.showActions(),
|
||
onEvidence: (turn) => panel.evidence(turn),
|
||
onRetry: (turn) => {
|
||
input.value = turn.text;
|
||
input.dataset.diagnostic = turn.diagnosticSnapshot?.diagnostic
|
||
? JSON.stringify(turn.diagnosticSnapshot.diagnostic)
|
||
: '';
|
||
pendingRequest = null;
|
||
input.dispatchEvent(new Event('input'));
|
||
input.focus();
|
||
error.textContent = '重新诊断将创建新一轮并使用新快照;不会重新执行旧操作。';
|
||
},
|
||
});
|
||
const commands = window.AssistantCommands.mount(root, {
|
||
getContext: () => panel.getContext(),
|
||
onStatus: async (kind, catalog) => {
|
||
error.textContent = '';
|
||
if (kind === 'help') panel.help(catalog);
|
||
else {
|
||
await panel.refresh();
|
||
panel.select('overview');
|
||
}
|
||
},
|
||
onSelect: (command, row) => {
|
||
input.value =
|
||
{
|
||
bpm: '分析此 BPM 连接及最近扫描异常',
|
||
storage: '分析此存储连接的最近状态',
|
||
archive: '分析这次归档的失败原因',
|
||
}[command] +
|
||
':' +
|
||
(row.name || row.orderNumber || row.id);
|
||
input.dataset.diagnostic = JSON.stringify({ command, targetId: row.id });
|
||
pendingRequest = null;
|
||
input.dispatchEvent(new Event('input'));
|
||
input.focus();
|
||
},
|
||
onError: showError,
|
||
onModel: () => picker.open(),
|
||
});
|
||
picker = window.AssistantModelPicker.mount(root, {
|
||
api,
|
||
isActive: live,
|
||
getConversation: () => conversation,
|
||
onError: showError,
|
||
onChange: updateComposer,
|
||
onSelect: async (choice) => {
|
||
const owner = await ensureConversation();
|
||
if (!owner) return;
|
||
const selected = await api('/assistant/conversations/' + owner.id + '/model', {
|
||
version: conversation.version,
|
||
...choice,
|
||
});
|
||
if (!live() || owner.id !== currentId || owner.at !== revision) return;
|
||
conversation = selected;
|
||
pendingRequest = null;
|
||
if (!eventClient) await select(owner.id);
|
||
else draw();
|
||
},
|
||
});
|
||
attachmentManager = window.AssistantAttachments?.mount(root, {
|
||
api,
|
||
isActive: live,
|
||
onChange: updateComposer,
|
||
onError: showError,
|
||
});
|
||
function updateComposer() {
|
||
attachmentManager?.setVisionSupport(picker?.supportsVision === true);
|
||
const running = conversation?.turns.some((t) => t.status === 'running'),
|
||
configured =
|
||
(data.settings.runtimeConfigured ?? !!data.settings.runtimePath) && picker.usable;
|
||
send.disabled =
|
||
creating ||
|
||
submitting ||
|
||
(!input.value.trim() && !attachmentManager?.ready.length) ||
|
||
!!attachmentManager?.pending ||
|
||
!!attachmentManager?.incompatible ||
|
||
!!running ||
|
||
!configured ||
|
||
!!conversation?.archived ||
|
||
!!conversation?.deletedAt ||
|
||
(conversation?.turns.length || 0) >= 100;
|
||
input.disabled = creating || !!conversation?.archived || !!conversation?.deletedAt;
|
||
const hint = root.querySelector('#assistant-send-hint');
|
||
if (hint) {
|
||
hint.replaceChildren();
|
||
if (!(data.settings.runtimeConfigured ?? !!data.settings.runtimePath)) {
|
||
hint.append('请先在助手设置配置 DSH 运行包:');
|
||
const link = document.createElement('a');
|
||
link.href = '#assistant-settings';
|
||
link.className = 'btn btn-sm btn-outline-warning ms-2';
|
||
link.textContent = '打开助手设置';
|
||
link.setAttribute('aria-label', '打开助手设置');
|
||
hint.append(link);
|
||
} else if (!picker.usable) {
|
||
hint.append('还没有可用模型。请在助手设置添加供应商或模型:');
|
||
const link = document.createElement('a');
|
||
link.href = '#assistant-settings';
|
||
link.className = 'btn btn-sm btn-outline-warning ms-2';
|
||
link.textContent = '打开助手设置';
|
||
link.setAttribute('aria-label', '打开助手设置');
|
||
hint.append(link);
|
||
} else if (attachmentManager?.incompatible)
|
||
hint.textContent = '当前模型不支持图片,请选择视觉模型或移除图片。';
|
||
else if (conversation?.archived || conversation?.deletedAt)
|
||
hint.textContent = '当前会话只读,请恢复或新建对话。';
|
||
else if (conversation?.turns.length >= 100)
|
||
hint.textContent = '当前会话已达 100 轮,请继续新对话。';
|
||
}
|
||
send.hidden = !!running;
|
||
stop.hidden = !running;
|
||
stop.disabled = !!conversation?.turns.some(
|
||
(t) => t.status === 'running' && t.cancelRequested,
|
||
);
|
||
stop.setAttribute('aria-label', stop.disabled ? '正在停止…' : '停止回复');
|
||
stop.title = stop.disabled ? '正在停止…' : '停止回复';
|
||
attachmentManager?.setDisabled(
|
||
creating || submitting || !!conversation?.archived || !!conversation?.deletedAt,
|
||
);
|
||
}
|
||
async function confirmPurge(target) {
|
||
const dialog = document.createElement('dialog');
|
||
dialog.className = 'page-leave-dialog';
|
||
dialog.setAttribute('aria-label', '永久删除会话');
|
||
dialog.innerHTML =
|
||
'<h2 class="h3">永久删除会话</h2><p>' +
|
||
esc(target.title) +
|
||
' 的消息和诊断快照将删除,无法从回收站恢复。操作审计、调用额度和已延续到其他会话的上下文保留。</p><div class="btn-list"><button class="btn" type="button">取消</button><button class="btn btn-danger" type="button">确认永久删除</button></div>';
|
||
root.append(dialog);
|
||
dialog.showModal();
|
||
const answer = await new Promise((resolve) => {
|
||
dialog.oncancel = (e) => {
|
||
e.preventDefault();
|
||
resolve(false);
|
||
};
|
||
dialog.onclose = () => resolve(false);
|
||
const buttons = dialog.querySelectorAll('button');
|
||
buttons[0].onclick = () => resolve(false);
|
||
buttons[1].onclick = () => resolve(true);
|
||
});
|
||
dialog.close();
|
||
dialog.remove();
|
||
return answer;
|
||
}
|
||
async function manage(action, id, target) {
|
||
if (managing) return;
|
||
const ownedTarget = id === currentId && conversation ? conversation : target,
|
||
at = revision;
|
||
managing = true;
|
||
drawLifecycle();
|
||
drawList();
|
||
try {
|
||
if (action === 'purge' && !(await confirmPurge(ownedTarget))) return;
|
||
if (!live() || at !== revision) return;
|
||
const path = action === 'delete' ? 'delete' : action;
|
||
const result = await api(
|
||
'/assistant/conversations/' + id + '/' + path,
|
||
{ version: ownedTarget.version, ...(action === 'purge' ? { confirm: 'delete' } : {}) },
|
||
{ managedOutcome: true },
|
||
);
|
||
if (!live()) return;
|
||
if (at !== revision) {
|
||
if (['delete', 'purge'].includes(action)) drafts.delete(id);
|
||
await refreshList();
|
||
return;
|
||
}
|
||
if (['delete', 'purge'].includes(action)) {
|
||
drafts.delete(id);
|
||
if (id === currentId) {
|
||
input.value = '';
|
||
pendingRequest = null;
|
||
currentId = '';
|
||
}
|
||
}
|
||
if (action === 'continue' || action === 'restore-deleted' || action === 'restore') {
|
||
scope = result.archived ? 'archived' : 'active';
|
||
root.querySelector('#assistant-scope').value = scope;
|
||
}
|
||
await refreshList(1);
|
||
if (!live() || at !== revision) return;
|
||
const next = ['continue', 'restore-deleted', 'restore'].includes(action)
|
||
? result.id
|
||
: data.conversations.some((c) => c.id === currentId)
|
||
? currentId
|
||
: data.conversations[0]?.id || '';
|
||
await select(next);
|
||
} catch (e) {
|
||
if (live() && at === revision) {
|
||
showError(e);
|
||
await refreshList();
|
||
}
|
||
} finally {
|
||
managing = false;
|
||
if (live()) {
|
||
drawLifecycle();
|
||
drawList();
|
||
}
|
||
}
|
||
}
|
||
function drawLifecycle() {
|
||
const box = root.querySelector('#assistant-lifecycle');
|
||
box.replaceChildren();
|
||
if (!conversation) return;
|
||
const actions = conversation.deletedAt
|
||
? [
|
||
['restore-deleted', '从回收站恢复'],
|
||
['purge', '永久删除'],
|
||
]
|
||
: [
|
||
[
|
||
conversation.archived ? 'restore' : 'archive',
|
||
conversation.archived ? '恢复会话' : '归档会话',
|
||
],
|
||
['continue', '继续新对话'],
|
||
['delete', '删除会话'],
|
||
];
|
||
for (const [action, label] of actions) {
|
||
const b = document.createElement('button');
|
||
b.type = 'button';
|
||
b.className = 'btn btn-sm' + (action === 'purge' ? ' btn-outline-danger' : '');
|
||
b.textContent = label;
|
||
b.disabled =
|
||
managing ||
|
||
conversation.turns.some(
|
||
(t) => t.status === 'running' || t.actions?.some((a) => a.status === 'running'),
|
||
);
|
||
b.onclick = () => manage(action, currentId, conversation);
|
||
box.append(b);
|
||
}
|
||
root.querySelector('#assistant-history-note').textContent = conversation.deletedAt
|
||
? '回收站 · 历史只读,可恢复或永久删除。'
|
||
: conversation.archived
|
||
? '已归档;恢复后可继续。'
|
||
: conversation.turns.length >= 100
|
||
? '已达100轮,继续新对话带入最近3轮。'
|
||
: '';
|
||
}
|
||
|
||
function draw() {
|
||
picker.update(conversation);
|
||
root.querySelector('#assistant-title').textContent = conversation?.title || '新对话';
|
||
updateComposer();
|
||
drawLifecycle();
|
||
transcript.update(conversation, events);
|
||
panel.update(conversation, events);
|
||
if (
|
||
conversation?.turns.some(
|
||
(t) => t.status === 'running' || t.actions?.some((a) => a.status === 'running'),
|
||
) ||
|
||
[...pendingActions.values()].includes(currentId)
|
||
)
|
||
watch();
|
||
}
|
||
function watch() {
|
||
if (watchTimer || !live()) return;
|
||
watchTimer = setTimeout(async () => {
|
||
watchTimer = null;
|
||
if (!live()) return;
|
||
try {
|
||
await loadCurrent();
|
||
} catch (e) {
|
||
showError(e);
|
||
}
|
||
}, 1200);
|
||
}
|
||
async function refreshUsage(id, at) {
|
||
const turn = conversation?.turns.at(-1),
|
||
signature = id + ':' + (turn?.id || '') + ':' + (turn?.status || '');
|
||
if (signature === usageSignature) return;
|
||
usageSignature = signature;
|
||
try {
|
||
const usage = await api('/assistant/usage');
|
||
if (live() && currentId === id && revision === at) {
|
||
data.usage = usage;
|
||
root.querySelector('.aw-usage').textContent = '今日 ' + usage.calls + ' / ' + usage.limit;
|
||
}
|
||
} catch {
|
||
if (live() && currentId === id && revision === at)
|
||
root.querySelector('.aw-usage').textContent = '调用额度暂不可用';
|
||
}
|
||
}
|
||
function loadCurrent(signal) {
|
||
if (!currentId || !live()) return Promise.resolve();
|
||
const id = currentId,
|
||
at = revision,
|
||
deletedScope = scope === 'deleted';
|
||
const work = loadChain
|
||
.catch(() => {})
|
||
.then(async () => {
|
||
if (!live() || currentId !== id || revision !== at) return;
|
||
const next = await api(
|
||
'/assistant/conversations/' + id + (deletedScope ? '?scope=deleted' : ''),
|
||
undefined,
|
||
{ signal, ownerCheck: () => live() && currentId === id && revision === at },
|
||
);
|
||
if (!live() || currentId !== id || revision !== at) return;
|
||
conversation = next;
|
||
draw();
|
||
void refreshUsage(id, at);
|
||
return next;
|
||
});
|
||
loadChain = work;
|
||
return work;
|
||
}
|
||
function drawList() {
|
||
if (listError) return;
|
||
const box = root.querySelector('#assistant-conversations');
|
||
box.innerHTML =
|
||
data.conversations
|
||
.map(
|
||
(c) =>
|
||
`<div class="aw-conversation-row" data-conversation-row="${esc(c.id)}"><button type="button" data-assistant-conversation="${esc(c.id)}" class="${c.id === currentId ? 'active' : ''}"><div>${esc(c.title)}</div><div class="small">${esc(formatDate(c.updatedAt))}</div></button><details class="aw-conversation-menu"><summary role="button" aria-label="会话操作" title="会话操作">⋯</summary><div>${(c.deletedAt
|
||
? [
|
||
['restore-deleted', '从回收站恢复'],
|
||
['purge', '永久删除'],
|
||
]
|
||
: [
|
||
[c.archived ? 'restore' : 'archive', c.archived ? '恢复会话' : '归档'],
|
||
['delete', '移至回收站'],
|
||
]
|
||
)
|
||
.map(
|
||
([action, label]) =>
|
||
`<button type="button" ${managing ? 'disabled' : ''} data-row-action="${action}" data-row-id="${esc(c.id)}">${label}</button>`,
|
||
)
|
||
.join('')}</div></details></div>`,
|
||
)
|
||
.join('') || '<p class="small text-secondary p-2">没有匹配会话。</p>';
|
||
box.querySelectorAll('[data-assistant-conversation]').forEach(
|
||
(b) =>
|
||
(b.onclick = () => {
|
||
layout.closeLeft();
|
||
void select(b.dataset.assistantConversation).catch(showError);
|
||
}),
|
||
);
|
||
box.querySelectorAll('[data-row-action]').forEach(
|
||
(b) =>
|
||
(b.onclick = () => {
|
||
const c = data.conversations.find((item) => item.id === b.dataset.rowId);
|
||
b.closest('details').open = false;
|
||
void manage(b.dataset.rowAction, c.id, c);
|
||
}),
|
||
);
|
||
}
|
||
|
||
function drawPager() {
|
||
root.querySelector('#assistant-page').textContent =
|
||
listPage + ' / ' + Math.max(1, Math.ceil(listTotal / 25));
|
||
root.querySelector('#assistant-prev').disabled = listPage <= 1;
|
||
root.querySelector('#assistant-next').disabled = listPage * 25 >= listTotal;
|
||
}
|
||
async function refreshList(page = listPage, requestedScope = scope) {
|
||
const at = ++listRevision,
|
||
owned = () => live() && at === listRevision;
|
||
root.querySelector('#assistant-prev').disabled = root.querySelector(
|
||
'#assistant-next',
|
||
).disabled = true;
|
||
try {
|
||
const query = root.querySelector('#assistant-search').value.trim();
|
||
const next = await api(
|
||
'/assistant/conversations?scope=' +
|
||
requestedScope +
|
||
'&page=' +
|
||
page +
|
||
'&pageSize=25' +
|
||
(query ? '&query=' + encodeURIComponent(query) : ''),
|
||
);
|
||
if (!owned()) return false;
|
||
data.conversations = next.items;
|
||
listPage = next.page;
|
||
listTotal = next.total;
|
||
scope = requestedScope;
|
||
listError = false;
|
||
error.textContent = '';
|
||
root.querySelector('#assistant-search-note').textContent = next.search?.truncated
|
||
? '仅搜索最近 ' + next.search.maximum + ' 个归档会话。'
|
||
: '';
|
||
drawList();
|
||
return true;
|
||
} catch (e) {
|
||
if (owned()) {
|
||
listError = true;
|
||
root.querySelector('#assistant-scope').value = scope;
|
||
const box = root.querySelector('#assistant-conversations');
|
||
box.innerHTML =
|
||
'<div class="alert alert-warning m-2" role="alert"><div>会话列表暂时无法加载。</div><button type="button" class="btn btn-sm btn-outline-primary mt-2" data-conversation-retry>重试加载会话</button></div>';
|
||
box.querySelector('[data-conversation-retry]').onclick = () =>
|
||
void refreshList(1, requestedScope);
|
||
showError(e);
|
||
}
|
||
return false;
|
||
} finally {
|
||
if (owned()) drawPager();
|
||
}
|
||
}
|
||
async function select(id) {
|
||
drafts.set(currentId, {
|
||
attachments: attachmentManager?.snapshot(),
|
||
text: input.value,
|
||
diagnostic: input.dataset.diagnostic || '',
|
||
scroll: messages.scrollTop,
|
||
request: pendingRequest,
|
||
});
|
||
eventClient?.dispose();
|
||
eventClient = null;
|
||
clearTimeout(watchTimer);
|
||
watchTimer = null;
|
||
currentId = id;
|
||
conversation = null;
|
||
events = [];
|
||
loadChain = Promise.resolve();
|
||
const at = ++revision;
|
||
sessionStorage.setItem(key, id);
|
||
const saved = drafts.get(id);
|
||
input.value = saved?.text || '';
|
||
input.dataset.diagnostic = saved?.diagnostic || '';
|
||
pendingRequest = saved?.request || null;
|
||
attachmentManager?.restore(saved?.attachments || []);
|
||
transcript.reset();
|
||
commands.close();
|
||
drawList();
|
||
draw();
|
||
if (!id) return;
|
||
await loadCurrent();
|
||
if (!live() || revision !== at) return;
|
||
if (conversation?.deletedAt) return;
|
||
try {
|
||
let cursor = 0,
|
||
more = true;
|
||
while (more) {
|
||
const batch = await api('/assistant/conversations/' + id + '/events?after=' + cursor);
|
||
if (!live() || revision !== at) return;
|
||
events.push(...batch.events);
|
||
cursor = batch.nextCursor;
|
||
more = batch.hasMore;
|
||
}
|
||
draw();
|
||
if (saved) messages.scrollTop = saved.scroll;
|
||
eventClient = window.AssistantEvents.connect({
|
||
id,
|
||
cursor,
|
||
api,
|
||
isActive: () => live() && revision === at,
|
||
onEvents: (rows) => {
|
||
const known = new Set(events.map((e) => e.seq));
|
||
events.push(...rows.filter((e) => !known.has(e.seq)));
|
||
draw();
|
||
},
|
||
onChange: loadCurrent,
|
||
onRemoved: async () => {
|
||
if (!live() || revision !== at || managing) return;
|
||
drafts.delete(id);
|
||
input.value = '';
|
||
pendingRequest = null;
|
||
currentId = '';
|
||
await refreshList(1);
|
||
if (live() && revision === at) await select(data.conversations[0]?.id || '');
|
||
},
|
||
onAuth: () => {
|
||
if (live() && revision === at) {
|
||
dispose();
|
||
container.innerHTML =
|
||
'<div class="alert alert-warning" role="alert">登录或权限已变化,已清除旧会话数据。<button class="btn btn-sm ms-2" type="button">重新加载</button></div>';
|
||
container.querySelector('button').onclick = () => location.reload();
|
||
void api('/me').catch(() => {});
|
||
}
|
||
},
|
||
});
|
||
} catch (e) {
|
||
if (live() && revision === at) {
|
||
if (e.status === 401 || e.status === 403) showError(e);
|
||
else if (e.status !== 404) showError(e);
|
||
}
|
||
}
|
||
}
|
||
async function ensureConversation() {
|
||
if (currentId) return { id: currentId, at: revision };
|
||
const before = revision,
|
||
c = await api('/assistant/conversations', {});
|
||
if (!live() || revision !== before) return null;
|
||
currentId = c.id;
|
||
conversation = c;
|
||
sessionStorage.setItem(key, c.id);
|
||
revision++;
|
||
const at = revision;
|
||
await refreshList(1);
|
||
return live() && revision === at ? { id: c.id, at } : null;
|
||
}
|
||
async function repair(text, paths) {
|
||
if (conversation?.archived || conversation?.deletedAt)
|
||
throw Error('请先恢复会话或新建对话。');
|
||
const owner = await ensureConversation();
|
||
if (!owner) return;
|
||
await api('/assistant/conversations/' + owner.id + '/repair-messages', { text, paths });
|
||
if (!live() || revision !== owner.at || currentId !== owner.id) return;
|
||
await refreshList();
|
||
if (revision !== owner.at) return;
|
||
await select(owner.id);
|
||
panel.showActions();
|
||
}
|
||
async function execute(actionId, button) {
|
||
if (pendingActions.has(actionId)) return;
|
||
const id = currentId,
|
||
at = revision;
|
||
pendingActions.set(actionId, id);
|
||
button.disabled = true;
|
||
error.textContent = '';
|
||
try {
|
||
const action = conversation?.turns
|
||
.flatMap((t) => t.actions || [])
|
||
.find((a) => a.id === actionId);
|
||
let body = {};
|
||
if (['update_configuration', 'manage_schedule'].includes(action?.kind)) {
|
||
body = await window.AssistantSettingsReview.open(root, {
|
||
api,
|
||
id,
|
||
actionId,
|
||
isActive: () => live() && id === currentId && revision === at,
|
||
});
|
||
if (!body) return;
|
||
}
|
||
if (!live() || id !== currentId || revision !== at) return;
|
||
watch();
|
||
await api('/assistant/conversations/' + id + '/actions/' + actionId + '/execute', body, {
|
||
managedOutcome: true,
|
||
});
|
||
} catch (e) {
|
||
if (live() && id === currentId && revision === at) showError(e);
|
||
} finally {
|
||
pendingActions.delete(actionId);
|
||
if (live() && id === currentId && revision === at) {
|
||
await loadCurrent();
|
||
if (button.isConnected) button.disabled = false;
|
||
}
|
||
}
|
||
}
|
||
async function sendMessage(event) {
|
||
event.preventDefault();
|
||
if (await commands.consume()) return;
|
||
if (send.disabled || (!input.value.trim() && !attachmentManager?.ready.length)) return;
|
||
submitting = true;
|
||
updateComposer();
|
||
error.textContent = '';
|
||
const text = input.value,
|
||
attachments = attachmentManager?.ready.map((f) => f.id) || [],
|
||
diagnostic = input.dataset.diagnostic ? JSON.parse(input.dataset.diagnostic) : undefined;
|
||
let owner = { id: currentId, at: revision };
|
||
const owns = () => live() && currentId === owner.id && revision === owner.at;
|
||
try {
|
||
const ensured = await ensureConversation();
|
||
if (!ensured) return;
|
||
owner = ensured;
|
||
if (!owns()) return;
|
||
const { id } = owner,
|
||
stamp = JSON.stringify([text, diagnostic, conversation?.modelSelection, attachments]);
|
||
if (!pendingRequest || pendingRequest.stamp !== stamp)
|
||
pendingRequest = {
|
||
stamp,
|
||
id: window.PageLifecycle?.requestKey?.() || crypto.randomUUID(),
|
||
};
|
||
const requestId = pendingRequest.id;
|
||
await api(
|
||
'/assistant/conversations/' + id + '/messages',
|
||
{ text, diagnostic, requestId, ...(attachments.length ? { attachments } : {}) },
|
||
{ managedOutcome: true },
|
||
);
|
||
if (!owns()) return;
|
||
if (input.value === text) {
|
||
input.value = '';
|
||
input.dataset.diagnostic = '';
|
||
}
|
||
attachmentManager?.clear();
|
||
pendingRequest = null;
|
||
drafts.delete(id);
|
||
await refreshList();
|
||
if (owns()) await select(id);
|
||
} catch (e) {
|
||
if (owns()) {
|
||
showError(e);
|
||
await loadCurrent().catch(() => {});
|
||
if (!owns()) return;
|
||
if (e.status === 409) await picker.refresh({ force: true }).catch(() => {});
|
||
if (e.outcome === 'uncertain')
|
||
error.textContent =
|
||
'提交结果待核实,已查询当前会话;再次发送同一草稿将使用原请求编号。';
|
||
updateComposer();
|
||
}
|
||
} finally {
|
||
submitting = false;
|
||
if (live()) updateComposer();
|
||
}
|
||
}
|
||
root.querySelector('#assistant-compose').onsubmit = sendMessage;
|
||
input.onkeydown = (event) => {
|
||
if (event.defaultPrevented || event.isComposing) return;
|
||
if (event.key === 'Enter' && !event.shiftKey) {
|
||
event.preventDefault();
|
||
root.querySelector('#assistant-compose').requestSubmit();
|
||
}
|
||
};
|
||
input.addEventListener('input', () => {
|
||
input.style.height = 'auto';
|
||
input.style.height = Math.min(input.scrollHeight, 180) + 'px';
|
||
updateComposer();
|
||
});
|
||
stop.onclick = async () => {
|
||
const id = currentId,
|
||
at = revision;
|
||
stop.disabled = true;
|
||
try {
|
||
await api('/assistant/conversations/' + id + '/cancel', {});
|
||
if (live() && id === currentId && revision === at) {
|
||
await loadCurrent();
|
||
watch();
|
||
}
|
||
} catch (e) {
|
||
showError(e);
|
||
} finally {
|
||
if (live()) updateComposer();
|
||
}
|
||
};
|
||
root.querySelector('#assistant-new').onclick = async () => {
|
||
if (creating) return;
|
||
creating = true;
|
||
const at = revision,
|
||
button = root.querySelector('#assistant-new');
|
||
button.disabled = true;
|
||
input.disabled = true;
|
||
try {
|
||
const c = await api('/assistant/conversations', {});
|
||
if (!live() || revision !== at) return;
|
||
scope = 'active';
|
||
root.querySelector('#assistant-scope').value = scope;
|
||
root.querySelector('#assistant-search').value = '';
|
||
await refreshList(1);
|
||
if (!live() || revision !== at) return;
|
||
await select(c.id);
|
||
layout.closeLeft();
|
||
} catch (e) {
|
||
if (live() && revision === at) showError(e);
|
||
} finally {
|
||
creating = false;
|
||
if (live()) {
|
||
button.disabled = false;
|
||
updateComposer();
|
||
input.focus();
|
||
}
|
||
}
|
||
};
|
||
root.querySelector('#assistant-scope').onchange = async (event) => {
|
||
if (await refreshList(1, event.target.value)) await select(data.conversations[0]?.id || '');
|
||
};
|
||
root.querySelector('#assistant-search').oninput = () => {
|
||
clearTimeout(searchTimer);
|
||
searchTimer = setTimeout(() => void refreshList(1), 250);
|
||
};
|
||
for (const [id, delta] of [
|
||
['assistant-prev', -1],
|
||
['assistant-next', 1],
|
||
])
|
||
root.querySelector('#' + id).onclick = () => refreshList(listPage + delta);
|
||
root.querySelectorAll('[data-diagnostic-start]').forEach(
|
||
(b) =>
|
||
(b.onclick = () => {
|
||
if (b.dataset.diagnosticStart === 'blockers') {
|
||
input.value = '根据当前授权快照,分析通知受阻原因;不要发送邮件。';
|
||
input.dataset.diagnostic = '';
|
||
input.dispatchEvent(new Event('input'));
|
||
input.focus();
|
||
} else commands.open(b.dataset.diagnosticStart);
|
||
}),
|
||
);
|
||
function dispose() {
|
||
if (disposed) return;
|
||
disposed = true;
|
||
revision++;
|
||
eventClient?.dispose();
|
||
clearTimeout(watchTimer);
|
||
clearTimeout(searchTimer);
|
||
commands.dispose();
|
||
picker.dispose();
|
||
attachmentManager?.dispose();
|
||
root.querySelectorAll('dialog').forEach((d) => {
|
||
d.close();
|
||
d.remove();
|
||
});
|
||
transcript.dispose();
|
||
regionWatcher?.dispose();
|
||
taskManager.dispose();
|
||
panel.dispose();
|
||
layout.dispose();
|
||
drafts.clear();
|
||
pendingActions.clear();
|
||
input.value = '';
|
||
}
|
||
const regionWatcher = window.PageLifecycle?.regionPoll?.(
|
||
'assistant',
|
||
{ refresh: async () => false, onError: showError },
|
||
1200,
|
||
{ isActive: live, enabled: () => false },
|
||
);
|
||
if (regionWatcher)
|
||
regionWatcher.refreshRegion = async () => {
|
||
const next = await api('/assistant');
|
||
if (!live()) return;
|
||
panel.updateSettings(next.settings);
|
||
data.usage = next.usage;
|
||
root.querySelector('.aw-usage').textContent =
|
||
'今日 ' + next.usage.calls + ' / ' + next.usage.limit;
|
||
root.querySelector('.aw-connection').textContent =
|
||
(next.settings.runtimeConfigured ?? !!next.settings.runtimePath)
|
||
? '诊断已配置'
|
||
: '待配置';
|
||
await picker.refresh({ force: true });
|
||
if (!live()) return;
|
||
await window.PageLifecycle.validateRegion('assistant').catch(showError);
|
||
await refreshList();
|
||
await loadCurrent();
|
||
await panel.refresh().catch(showError);
|
||
if (live()) draw();
|
||
};
|
||
window.PageLifecycle?.onDispose(dispose);
|
||
await Promise.all([
|
||
refreshList(1),
|
||
picker.refresh().catch((error) => {
|
||
picker.failure(error);
|
||
}),
|
||
]);
|
||
if (!data.conversations.some((c) => c.id === currentId))
|
||
currentId = data.conversations[0]?.id || '';
|
||
await select(currentId);
|
||
void panel.refresh().catch(showError);
|
||
}
|
||
|
||
async function settings(container, isActive = () => true) {
|
||
return window.AssistantProviderSettings.render(container, {
|
||
api,
|
||
esc,
|
||
formatDate,
|
||
notify,
|
||
user,
|
||
isActive,
|
||
});
|
||
}
|
||
window.AssistantViews = {
|
||
configure: (options) => ({ api, esc, formatDate, notify, user } = options),
|
||
render,
|
||
settings,
|
||
};
|
||
})();
|