Files
order-notification-automation/web/modules/assistant/conversation.js
T

305 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
window.AssistantConversation = (() => {
const labels = {
queued: '请求已接受',
snapshot: '已读取诊断快照',
runtime: 'DSH 运行包就绪',
model: 'DSH 正在分析',
validation: '校验回复',
proposal: '已生成操作建议',
awaiting_confirmation: '等待确认',
completed: '回答完成',
error: '诊断失败',
cancel_requested: '正在停止',
cancelled: '已停止',
interrupted: '已中断',
needs_review: '结果待核验',
action_running: '操作进行中',
action_progress: '操作进展',
action_result: '操作结果',
};
const states = {
running: '正在分析',
success: '已完成',
error: '失败',
cancelled: '已停止',
interrupted: '已中断',
needs_review: '待核验',
};
function actionSummary(a) {
const r = a.result;
if (a.kind === 'manage_schedule' && r)
return (
{
scheduled: '任务已创建,下一次触发:' + r.scheduledAt,
schedule_updated: '任务已修改,下一次触发:' + r.scheduledAt,
schedule_deleted: '未来触发已停止;已投递消息保留。',
}[r.status] || '任务结果需要核实。'
);
if (
['collect_field_samples', 'collect_history_samples'].includes(a.kind) &&
r &&
Number.isInteger(r.captured)
) {
if (r.total === 0)
return r.missing?.length
? '本次没有找到可补采的待办样本;仍缺少:' + r.missing.join('、')
: '当前没有需要补采的流程,未新增样本。';
return (
'已采集 ' +
r.captured +
' 个样本,失败 ' +
(r.failed || 0) +
' 个' +
(r.missing?.length ? ';仍缺少:' + r.missing.join('、') : '。')
);
}
if (a.kind === 'scan_bpm' && r && Number.isInteger(r.seen))
return '扫描读取 ' + r.seen + ' 条,新增 ' + (r.added || 0) + ' 条。';
if (a.kind === 'update_configuration' && r?.status === 'saved')
return '本次配置已保存,版本 ' + r.version + '。';
if (!r || (typeof r === 'object' && !Object.keys(r).length))
return '此历史操作没有保存结果明细,请到原功能页面核验。';
return '已返回操作结果,可展开查看明细。';
}
function actionState(a) {
if (a.status === 'success' && a.kind === 'manage_schedule')
return (
{
scheduled: '定时任务已创建',
schedule_updated: '定时任务已修改',
schedule_deleted: '定时任务已删除',
}[a.result?.status] || '任务结果待核实'
);
if (
a.status === 'success' &&
['collect_field_samples', 'collect_history_samples'].includes(a.kind) &&
a.result
) {
if (a.result.captured === 0 && a.result.missing?.length) return '未采集到样本';
if (a.result.total === 0 && Array.isArray(a.result.missing)) return '无需补采';
if (a.result.failed > 0) return '部分完成';
}
if (a.status === 'rejected') return '已拒绝,未修改';
if (a.status === 'success' && a.result?.status === 'saved') return '配置已保存';
if (a.status === 'proposed') return '等待确认';
if (a.status === 'running') return '操作进行中';
if (['interrupted', 'needs_review', 'unknown'].includes(a.status)) return '结果待核验';
if (a.status === 'error') return '操作未完成';
return (
{
ready_for_review: '测试通过,待审查',
rolled_back: '测试未通过,已回退',
needs_review: '结果待核验',
blocked: '操作受阻',
'needs-selection': '需人工选择',
failed: '操作失败',
error: '操作失败',
interrupted: '结果待核验',
unknown: '结果待核验',
checked: '草稿已检查',
}[a.result?.status] || '操作已完成'
);
}
function markdown(text, esc) {
if (!window.marked) return esc(text).replace(/\n/g, '<br>');
const renderer = {
html: (token) => esc(token.text),
image: (token) => esc(token.text || '图片'),
link(token) {
const label = this.parser.parseInline(token.tokens);
let url;
try {
url = new URL(token.href, location.href);
} catch {
return label;
}
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
return label;
const internal = url.origin === location.origin;
if (
internal &&
!/^#(?:bpm|storage|records(?:-pdf)?|rule-fields|order-rules|health|exceptions|notification-(?:orders|batches|execution|settings)|assistant-settings)(?:\?|$)/.test(
url.hash,
)
)
return label;
return `<a href="${esc(url.href)}"${internal ? '' : ' target="_blank" rel="noopener noreferrer"'}>${label}</a>`;
},
};
return new window.marked.Marked({ renderer, gfm: true, breaks: true }).parse(String(text));
}
function mount(messages, { esc, formatDate, user, onActions, onEvidence, onRetry }) {
const nodes = new Map();
let following = true;
const jump = messages.parentElement.querySelector('#assistant-new-progress');
const composer = messages.parentElement.querySelector('.aw-composer'),
positionJump = () => {
jump.style.bottom = composer.offsetHeight + 12 + 'px';
},
resize = new ResizeObserver(positionJump);
resize.observe(composer);
positionJump();
messages.onscroll = () => {
following = messages.scrollHeight - messages.scrollTop - messages.clientHeight < 70;
jump.hidden = following;
};
jump.onclick = () => {
messages.scrollTop = messages.scrollHeight;
following = true;
jump.hidden = true;
};
function update(c, events) {
const turns = c?.turns || [];
if (!turns.length) {
if (!messages.querySelector('.aw-welcome'))
messages.innerHTML =
'<div class="aw-welcome"><span class="aw-welcome-mark">DSH</span><h3>从运行情况开始</h3><p>查看连接健康、扫描异常与归档失败。<br>诊断依据和待确认操作会出现在右侧。</p></div>';
nodes.clear();
return;
}
messages.querySelector('.aw-welcome')?.remove();
let changed = false;
for (const t of turns) {
let row = nodes.get(t.id);
if (!row) {
const element = document.createElement('article');
element.className = 'assistant-turn';
element.dataset.turnId = t.id;
element.innerHTML =
'<div class="assistant-user"></div><div class="assistant-reply"><div class="aw-reply-header"><strong>DSH</strong><span class="aw-turn-model small text-secondary"></span><span class="aw-state"></span></div><details class="aw-process"><summary>本轮过程</summary><ol></ol></details><div class="assistant-answer"></div><div class="aw-turn-actions"></div></div>';
messages.append(element);
row = { element, answer: '', signature: '' };
nodes.set(t.id, row);
element.querySelector('.assistant-user').textContent = t.text;
if (t.attachments?.length) {
const files = document.createElement('div');
files.className = 'aw-sent-attachments';
for (const file of t.attachments) {
const span = document.createElement('span');
span.textContent =
'附件:' +
file.name +
(file.kind === 'image'
? ' · 图片 ' + file.width + '×' + file.height
: ' · ' + file.characters + ' 字');
files.append(span);
if (file.kind === 'image') {
const image = document.createElement('img');
image.className = 'aw-sent-image';
image.alt = file.name;
image.src =
'/api/assistant/conversations/' + c.id + '/attachments/' + file.id + '/preview';
files.append(image);
}
}
element.querySelector('.assistant-user').append(files);
}
if (t.modelSelection)
element.querySelector('.aw-turn-model').textContent =
t.modelSelection.providerName +
' / ' +
(t.modelSelection.modelName || t.modelSelection.modelId);
changed = true;
}
const relevant = events.filter((e) => e.turnId === t.id),
signature = JSON.stringify([
t.status,
t.error,
t.reply,
t.cancelRequested,
t.actions,
relevant.at(-1)?.seq,
]);
if (signature === row.signature) continue;
row.signature = signature;
changed = true;
const badge = row.element.querySelector('.aw-state');
badge.textContent =
t.cancelRequested && t.status === 'running' ? '正在停止' : states[t.status] || t.status;
badge.classList.toggle(
'error',
['error', 'needs_review', 'interrupted'].includes(t.status),
);
const process = row.element.querySelector('.aw-process'),
ol = process.querySelector('ol');
ol.replaceChildren();
if (relevant.length) {
for (const e of relevant) {
const li = document.createElement('li');
li.textContent = (labels[e.kind] || '阶段更新') + ' · ' + formatDate(e.at);
ol.append(li);
}
} else {
const li = document.createElement('li');
li.textContent = '历史阶段未记录';
ol.append(li);
}
process.open = t.status === 'running' || process.open;
const answer =
t.reply ||
t.error ||
(t.status === 'running' ? '正在分析授权范围内的运行状态…' : '暂无回复');
if (answer !== row.answer) {
row.element.querySelector('.assistant-answer').innerHTML = markdown(answer, esc);
row.answer = answer;
}
const actions = row.element.querySelector('.aw-turn-actions');
actions.replaceChildren();
function button(text, callback) {
const b = document.createElement('button');
b.type = 'button';
b.className = 'btn btn-sm';
b.textContent = text;
b.onclick = callback;
actions.append(b);
}
if (t.reply)
button('复制回答', async () => {
try {
await navigator.clipboard.writeText(t.reply);
} catch {
const selection = getSelection(),
range = document.createRange();
range.selectNodeContents(row.element.querySelector('.assistant-answer'));
selection.removeAllRanges();
selection.addRange(range);
}
});
button('诊断依据', () => onEvidence(t));
if (t.actions?.length) button('查看操作(' + t.actions.length + ')', () => onActions(t));
if (
!c?.archived &&
!c?.deletedAt &&
['error', 'cancelled', 'interrupted', 'needs_review'].includes(t.status)
)
button('重新诊断', () => onRetry(t));
}
for (const [id, row] of nodes)
if (!turns.some((t) => t.id === id)) {
row.element.remove();
nodes.delete(id);
}
if (changed) {
if (following) messages.scrollTop = messages.scrollHeight;
else jump.hidden = false;
}
}
return {
update,
dispose() {
resize.disconnect();
messages.onscroll = null;
jump.onclick = null;
},
reset() {
nodes.clear();
messages.replaceChildren();
following = true;
jump.hidden = true;
},
};
}
return { mount, labels, actionState, actionSummary, markdown };
})();