feat(assistant): complete controlled management attachments and native schedules
This commit is contained in:
1 parent
d0bc4b0da2
commit
8341986067
119 files changed
+20519
-1618
No files matched your search
@@ -0,0 +1,240 @@
|
||||
'use strict';
|
||||
window.AssistantAttachments = {
|
||||
mount(root, { api, isActive, onChange, onError }) {
|
||||
const button = root.querySelector('#assistant-attach'),
|
||||
input = root.querySelector('#assistant-files'),
|
||||
list = root.querySelector('#assistant-attachment-list'),
|
||||
note = root.querySelector('#assistant-attachment-note'),
|
||||
textTypes =
|
||||
'.txt,.log,.csv,.md,.json,.yaml,.yml,.xml,.ini,.conf,.js,.ts,.cjs,.mjs,.py,.css,.html,.pdf';
|
||||
let items = [],
|
||||
generation = 0,
|
||||
disabled = false,
|
||||
disposed = false,
|
||||
supportsVision = false;
|
||||
const requests = new Set();
|
||||
const alive = () => !disposed && isActive();
|
||||
function icon(image) {
|
||||
return (
|
||||
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
|
||||
(image
|
||||
? '<rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8" cy="8" r="1.5"/><path d="m4 17 5-5 4 4 3-3 5 5"/>'
|
||||
: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h6"/>') +
|
||||
'</svg>'
|
||||
);
|
||||
}
|
||||
function preview(file) {
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.className = 'aw-settings-review aw-attachment-preview';
|
||||
dialog.setAttribute('aria-label', '预览附件 ' + file.name);
|
||||
dialog.innerHTML =
|
||||
'<header><h2></h2></header><div class="aw-review-body"><p></p></div><footer><button type="button" class="btn">关闭</button></footer>';
|
||||
dialog.querySelector('h2').textContent = file.name;
|
||||
const body = dialog.querySelector('.aw-review-body');
|
||||
if (file.kind === 'image') {
|
||||
dialog.querySelector('p').textContent =
|
||||
'图片 ' + file.width + '×' + file.height + ',点击发送才以图像内容交给当前视觉模型。';
|
||||
const image = document.createElement('img');
|
||||
image.src = file.previewImage;
|
||||
image.alt = file.name;
|
||||
image.className = 'aw-image-preview';
|
||||
body.append(image);
|
||||
} else {
|
||||
dialog.querySelector('p').textContent =
|
||||
'本机解析预览(最多前 2000 字),正文共 ' +
|
||||
file.characters +
|
||||
' 字。发送时才交给当前模型。';
|
||||
const pre = document.createElement('pre');
|
||||
pre.textContent = file.preview;
|
||||
body.append(pre);
|
||||
}
|
||||
dialog.querySelector('button').onclick = () => dialog.close();
|
||||
dialog.onclose = () => dialog.remove();
|
||||
root.append(dialog);
|
||||
dialog.showModal();
|
||||
}
|
||||
function draw() {
|
||||
list.replaceChildren();
|
||||
for (const item of items) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'aw-attachment';
|
||||
const symbol = document.createElement('span');
|
||||
symbol.className = 'aw-attachment-icon';
|
||||
symbol.innerHTML = icon(item.kind === 'image');
|
||||
row.append(symbol);
|
||||
const info = document.createElement('div'),
|
||||
name = document.createElement('strong'),
|
||||
status = document.createElement('span');
|
||||
name.textContent = item.name;
|
||||
status.textContent = item.loading
|
||||
? '正在本机处理…'
|
||||
: item.kind === 'image'
|
||||
? '图片 · ' +
|
||||
item.width +
|
||||
'×' +
|
||||
item.height +
|
||||
' · ' +
|
||||
(item.size / 1024).toFixed(1) +
|
||||
' KB'
|
||||
: '已解析 · ' +
|
||||
(item.size / 1024).toFixed(1) +
|
||||
' KB · ' +
|
||||
item.characters +
|
||||
' 字' +
|
||||
(item.kind === 'pdf' ? ' · PDF 文字' : '');
|
||||
info.append(name, status);
|
||||
row.append(info);
|
||||
if (!item.loading) {
|
||||
const view = document.createElement('button');
|
||||
view.type = 'button';
|
||||
view.className = 'btn btn-sm';
|
||||
view.textContent = '预览';
|
||||
view.setAttribute('aria-label', '预览附件 ' + item.name);
|
||||
view.onclick = () => preview(item);
|
||||
row.append(view);
|
||||
}
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'btn btn-sm aw-remove-attachment';
|
||||
remove.innerHTML =
|
||||
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 6 12 12M6 18 18 6"/></svg>';
|
||||
remove.disabled = disabled;
|
||||
remove.setAttribute('aria-label', '移除附件 ' + item.name);
|
||||
remove.onclick = async () => {
|
||||
remove.disabled = true;
|
||||
try {
|
||||
if (item.id) await api('/assistant/attachments/' + item.id + '/remove', {});
|
||||
if (!alive()) return;
|
||||
items = items.filter((f) => f !== item);
|
||||
draw();
|
||||
} catch (error) {
|
||||
if (alive()) {
|
||||
if (error.status === 404) {
|
||||
items = items.filter((f) => f !== item);
|
||||
draw();
|
||||
} else {
|
||||
remove.disabled = false;
|
||||
onError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
row.append(remove);
|
||||
list.append(row);
|
||||
}
|
||||
note.hidden = !items.length;
|
||||
note.textContent = items.some((f) => f.kind === 'image')
|
||||
? '图片将以图像内容发送给所选视觉模型,不会当作文本;文件内容不授予操作权限。'
|
||||
: '文件在本机解析,点击发送才交给模型。最多 3 个、每个 2 MB、文字合计 40000 字;PDF 提取文字,扫描图片需先 OCR。';
|
||||
button.disabled = disabled || items.length >= 3;
|
||||
input.disabled = button.disabled;
|
||||
input.accept = textTypes + (supportsVision ? ',.png,.jpg,.jpeg' : '');
|
||||
button.title = supportsVision
|
||||
? '添加文件或图片(PNG、JPEG)'
|
||||
: '添加文本或 PDF;图片请选择视觉模型';
|
||||
onChange();
|
||||
}
|
||||
const encode = (file) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result).split(',')[1]);
|
||||
reader.onerror = () => reject(Error('读取附件失败。'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
input.onchange = async () => {
|
||||
const selected = [...input.files],
|
||||
at = generation;
|
||||
input.value = '';
|
||||
for (const file of selected) {
|
||||
if (!alive() || at !== generation) return;
|
||||
if (items.length >= 3) {
|
||||
onError(Error('每条消息最多添加 3 个附件。'));
|
||||
break;
|
||||
}
|
||||
if (/\.(?:png|jpe?g)$/i.test(file.name) && !supportsVision) {
|
||||
onError(Error('当前模型不支持图片,请先选择视觉模型。'));
|
||||
continue;
|
||||
}
|
||||
if (!file.size || file.size > 2 * 1024 * 1024) {
|
||||
onError(Error('附件为空或超过 2 MB。'));
|
||||
continue;
|
||||
}
|
||||
const item = { name: file.name, loading: true },
|
||||
controller = new AbortController();
|
||||
requests.add(controller);
|
||||
items.push(item);
|
||||
draw();
|
||||
try {
|
||||
const data = await encode(file);
|
||||
if (!alive() || at !== generation) return;
|
||||
const result = await api(
|
||||
'/assistant/attachments',
|
||||
{ name: file.name, data },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (!alive() || at !== generation || !items.includes(item)) {
|
||||
void api('/assistant/attachments/' + result.id + '/remove', {}).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
Object.assign(item, result, { loading: false });
|
||||
draw();
|
||||
} catch (error) {
|
||||
if (alive() && at === generation) {
|
||||
items = items.filter((f) => f !== item);
|
||||
draw();
|
||||
if (error.name !== 'AbortError') onError(error);
|
||||
}
|
||||
} finally {
|
||||
requests.delete(controller);
|
||||
}
|
||||
}
|
||||
};
|
||||
button.onclick = () => input.click();
|
||||
return {
|
||||
get pending() {
|
||||
return items.some((f) => f.loading);
|
||||
},
|
||||
get ready() {
|
||||
return items.filter((f) => !f.loading);
|
||||
},
|
||||
get incompatible() {
|
||||
return !supportsVision && items.some((f) => f.kind === 'image');
|
||||
},
|
||||
setVisionSupport(value) {
|
||||
if (supportsVision === value) return;
|
||||
supportsVision = value;
|
||||
draw();
|
||||
},
|
||||
snapshot() {
|
||||
return items.filter((f) => !f.loading).map((f) => ({ ...f }));
|
||||
},
|
||||
restore(saved = []) {
|
||||
generation++;
|
||||
for (const r of requests) r.abort();
|
||||
requests.clear();
|
||||
items = saved.map((f) => ({ ...f, loading: false }));
|
||||
draw();
|
||||
},
|
||||
clear() {
|
||||
generation++;
|
||||
items = [];
|
||||
draw();
|
||||
},
|
||||
setDisabled(value) {
|
||||
if (disabled === value) return;
|
||||
disabled = value;
|
||||
draw();
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
generation++;
|
||||
for (const r of requests) r.abort();
|
||||
requests.clear();
|
||||
items = [];
|
||||
input.onchange = null;
|
||||
button.onclick = null;
|
||||
list.replaceChildren();
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,21 +1,181 @@
|
||||
'use strict';
|
||||
window.AssistantCommands={mount(root,{getContext,onStatus,onSelect,onError,onModel}){
|
||||
const input=root.querySelector('#assistant-input'),menu=root.querySelector('#assistant-command-menu');let rows=[],index=0,mode='command',generation=0;
|
||||
const catalog=[{name:'help',label:'帮助',detail:'/help · 固定诊断命令'},{name:'status',label:'运行概况',detail:'/status · 只读刷新'},{name:'model',label:'选择模型',detail:'/model · 按供应商选择模型'},{name:'bpm',label:'BPM 连接',detail:'/bpm · 选择连接并诊断'},{name:'storage',label:'存储连接',detail:'/storage · 选择存储并诊断'},{name:'archive',label:'归档失败',detail:'/archive · 选择归档记录'}];
|
||||
function close(){generation++;menu.hidden=true;menu.replaceChildren();input.removeAttribute('aria-activedescendant');input.setAttribute('aria-expanded','false');}
|
||||
function draw(){menu.replaceChildren();menu.hidden=false;input.setAttribute('aria-expanded','true');for(const [i,row]of rows.entries()){const b=document.createElement('button');b.type='button';b.role='option';b.id='aw-command-'+i;b.setAttribute('aria-selected',String(i===index));const label=document.createElement('span');label.textContent=row.label;const detail=document.createElement('small');detail.textContent=row.detail||'';b.append(label,detail);b.onclick=()=>choose(row);menu.append(b);}if(!rows.length){const note=document.createElement('div');note.className='p-3 text-secondary small';note.textContent='没有可见的匹配目标';menu.append(note);}input.setAttribute('aria-activedescendant','aw-command-'+index);}
|
||||
function commands(query=''){mode='command';rows=window.AssistantNative.filterOptions(catalog.map(c=>({...c,detail:c.detail+' '+c.name})),query);index=0;draw();}
|
||||
async function choose(row){
|
||||
if(mode!=='command'){const command=mode;close();onSelect(command,row);input.focus();return;}
|
||||
const command=row.name;
|
||||
if(command==='model'){close();input.dataset.diagnostic='';input.value='';await onModel?.();return;}
|
||||
if(command==='help'){close();input.dataset.diagnostic='';onStatus('help',catalog);input.value='';return;}
|
||||
if(command==='status'){close();input.dataset.diagnostic='';input.value='';await onStatus('status');return;}
|
||||
const at=++generation;try{const context=await getContext();if(at!==generation)return;mode=command;rows=({bpm:context.connections,storage:context.servers,archive:context.archives}[command]||[]).map(item=>({id:item.id,label:item.name||item.orderNumber||item.id,detail:item.status||'',...item}));index=0;draw();input.focus();}catch(error){if(at===generation)onError(error);}
|
||||
}
|
||||
input.setAttribute('aria-controls','assistant-command-menu');input.setAttribute('aria-expanded','false');menu.role='listbox';
|
||||
const onInput=()=>{if(/^\/[^\s]*$/.test(input.value))commands(input.value.slice(1));else if(mode==='command')close();};input.addEventListener('input',onInput);
|
||||
const button=root.querySelector('#assistant-commands');button.onclick=()=>{if(menu.hidden){commands();input.focus();}else close();};
|
||||
const onKey=event=>{if(event.isComposing)return;if(event.key==='Escape'&&!menu.hidden){event.preventDefault();event.stopPropagation();close();input.focus();return;}if(!menu.hidden&&['ArrowDown','ArrowUp'].includes(event.key)){event.preventDefault();index=(index+(event.key==='ArrowDown'?1:-1)+Math.max(rows.length,1))%Math.max(rows.length,1);draw();return;}if(!menu.hidden&&['Tab','Enter'].includes(event.key)&&!event.shiftKey&&rows[index]){event.preventDefault();event.stopImmediatePropagation();void choose(rows[index]);}};input.addEventListener('keydown',onKey);
|
||||
return {close,async consume(){const value=input.value.trim();if(!value.startsWith('/'))return false;const found=window.AssistantNative.resolveCommand(value.slice(1),catalog);if(!found){close();onError(new Error('此命令未开放,请使用固定诊断命令。'));return true;}mode='command';await choose(found);return true;},open(name){const found=window.AssistantNative.resolveCommand(name,catalog);if(found){mode='command';void choose(found);}},dispose(){close();input.removeEventListener('input',onInput);input.removeEventListener('keydown',onKey);button.onclick=null;}};
|
||||
}};
|
||||
window.AssistantCommands = {
|
||||
mount(root, { getContext, onStatus, onSelect, onError, onModel }) {
|
||||
const input = root.querySelector('#assistant-input'),
|
||||
menu = root.querySelector('#assistant-command-menu');
|
||||
let rows = [],
|
||||
index = 0,
|
||||
mode = 'command',
|
||||
generation = 0;
|
||||
const catalog = [
|
||||
{ name: 'help', label: '帮助', detail: '/help · 固定诊断命令' },
|
||||
{ name: 'status', label: '运行概况', detail: '/status · 只读刷新' },
|
||||
{ name: 'model', label: '选择模型', detail: '/model · 按供应商选择模型' },
|
||||
{ name: 'bpm', label: 'BPM 连接', detail: '/bpm · 选择连接并诊断' },
|
||||
{ name: 'storage', label: '存储连接', detail: '/storage · 选择存储并诊断' },
|
||||
{ name: 'archive', label: '归档失败', detail: '/archive · 选择归档记录' },
|
||||
];
|
||||
function close() {
|
||||
generation++;
|
||||
menu.hidden = true;
|
||||
menu.replaceChildren();
|
||||
input.removeAttribute('aria-activedescendant');
|
||||
input.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
function draw() {
|
||||
menu.replaceChildren();
|
||||
menu.hidden = false;
|
||||
input.setAttribute('aria-expanded', 'true');
|
||||
for (const [i, row] of rows.entries()) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.role = 'option';
|
||||
b.id = 'aw-command-' + i;
|
||||
b.setAttribute('aria-selected', String(i === index));
|
||||
const label = document.createElement('span');
|
||||
label.textContent = row.label;
|
||||
const detail = document.createElement('small');
|
||||
detail.textContent = row.detail || '';
|
||||
b.append(label, detail);
|
||||
b.onclick = () => choose(row);
|
||||
menu.append(b);
|
||||
}
|
||||
if (!rows.length) {
|
||||
const note = document.createElement('div');
|
||||
note.className = 'p-3 text-secondary small';
|
||||
note.textContent = '没有可见的匹配目标';
|
||||
menu.append(note);
|
||||
}
|
||||
input.setAttribute('aria-activedescendant', 'aw-command-' + index);
|
||||
}
|
||||
function commands(query = '') {
|
||||
mode = 'command';
|
||||
rows = window.AssistantNative.filterOptions(
|
||||
catalog.map((c) => ({ ...c, detail: c.detail + ' ' + c.name })),
|
||||
query,
|
||||
);
|
||||
index = 0;
|
||||
draw();
|
||||
}
|
||||
async function choose(row) {
|
||||
if (mode !== 'command') {
|
||||
const command = mode;
|
||||
close();
|
||||
onSelect(command, row);
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
const command = row.name;
|
||||
if (command === 'model') {
|
||||
close();
|
||||
input.dataset.diagnostic = '';
|
||||
input.value = '';
|
||||
await onModel?.();
|
||||
return;
|
||||
}
|
||||
if (command === 'help') {
|
||||
close();
|
||||
input.dataset.diagnostic = '';
|
||||
onStatus('help', catalog);
|
||||
input.value = '';
|
||||
return;
|
||||
}
|
||||
if (command === 'status') {
|
||||
close();
|
||||
input.dataset.diagnostic = '';
|
||||
input.value = '';
|
||||
await onStatus('status');
|
||||
return;
|
||||
}
|
||||
const at = ++generation;
|
||||
try {
|
||||
const context = await getContext();
|
||||
if (at !== generation) return;
|
||||
mode = command;
|
||||
rows = (
|
||||
{ bpm: context.connections, storage: context.servers, archive: context.archives }[
|
||||
command
|
||||
] || []
|
||||
).map((item) => ({
|
||||
id: item.id,
|
||||
label: item.name || item.orderNumber || item.id,
|
||||
detail: item.status || '',
|
||||
...item,
|
||||
}));
|
||||
index = 0;
|
||||
draw();
|
||||
input.focus();
|
||||
} catch (error) {
|
||||
if (at === generation) onError(error);
|
||||
}
|
||||
}
|
||||
input.setAttribute('aria-controls', 'assistant-command-menu');
|
||||
input.setAttribute('aria-expanded', 'false');
|
||||
menu.role = 'listbox';
|
||||
const onInput = () => {
|
||||
if (/^\/[^\s]*$/.test(input.value)) commands(input.value.slice(1));
|
||||
else if (mode === 'command') close();
|
||||
};
|
||||
input.addEventListener('input', onInput);
|
||||
const button = root.querySelector('#assistant-commands');
|
||||
button.onclick = () => {
|
||||
if (menu.hidden) {
|
||||
commands();
|
||||
input.focus();
|
||||
} else close();
|
||||
};
|
||||
const onKey = (event) => {
|
||||
if (event.isComposing) return;
|
||||
if (event.key === 'Escape' && !menu.hidden) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close();
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
if (!menu.hidden && ['ArrowDown', 'ArrowUp'].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
index =
|
||||
(index + (event.key === 'ArrowDown' ? 1 : -1) + Math.max(rows.length, 1)) %
|
||||
Math.max(rows.length, 1);
|
||||
draw();
|
||||
return;
|
||||
}
|
||||
if (!menu.hidden && ['Tab', 'Enter'].includes(event.key) && !event.shiftKey && rows[index]) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
void choose(rows[index]);
|
||||
}
|
||||
};
|
||||
input.addEventListener('keydown', onKey);
|
||||
return {
|
||||
close,
|
||||
async consume() {
|
||||
const value = input.value.trim();
|
||||
if (!value.startsWith('/')) return false;
|
||||
const found = window.AssistantNative.resolveCommand(value.slice(1), catalog);
|
||||
if (!found) {
|
||||
close();
|
||||
onError(new Error('此命令未开放,请使用固定诊断命令。'));
|
||||
return true;
|
||||
}
|
||||
mode = 'command';
|
||||
await choose(found);
|
||||
return true;
|
||||
},
|
||||
open(name) {
|
||||
const found = window.AssistantNative.resolveCommand(name, catalog);
|
||||
if (found) {
|
||||
mode = 'command';
|
||||
void choose(found);
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
close();
|
||||
input.removeEventListener('input', onInput);
|
||||
input.removeEventListener('keydown', onKey);
|
||||
button.onclick = null;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,18 +1,247 @@
|
||||
'use strict';
|
||||
window.AssistantContextPanel={mount(root,{api,esc,formatDate,user,settings,isActive,onExecute,onRepair,showRight}){
|
||||
let active='overview',context=null,conversation=null,events=[],selected=null,auditMounted=false,actionSignature='';
|
||||
const panels=Object.fromEntries(['overview','evidence','actions','events'].map(id=>[id,root.querySelector('#aw-panel-'+id)]));
|
||||
function select(id){active=id;for(const [key,panel]of Object.entries(panels)){panel.hidden=key!==id;root.querySelector('[data-context-tab='+key+']').setAttribute('aria-selected',String(key===id));}showRight();if(id==='events')mountAudit();}
|
||||
root.querySelectorAll('[data-context-tab]').forEach(b=>b.onclick=()=>select(b.dataset.contextTab));
|
||||
const row=(title,detail)=>`<div class="aw-stat"><strong>${esc(title)}</strong><span>${esc(detail)}</span></div>`;
|
||||
function drawOverview(){const c=context;if(!c){panels.overview.innerHTML='<p class="text-secondary">正在读取授权状态…</p>';return;}panels.overview.innerHTML=`<div class="d-flex justify-content-between align-items-center"><h3>诊断概况</h3><button class="btn btn-sm" type="button" data-context-refresh>刷新概况</button></div><p class="text-secondary small">本机状态快照 · ${esc(formatDate(c.observedAt||c.at))}</p><h4>BPM 连接</h4>${c.connections?.map(item=>row(item.name,item.status||'未观测')).join('')||'<p class="text-secondary">没有可见连接</p>'}<h4>最近扫描</h4>${c.runs?.map(item=>row(item.status||'未知',formatDate(item.finishedAt||item.startedAt)+' · 新增 '+(item.added??'未知'))).join('')||'<p class="text-secondary">暂无可见扫描记录</p>'}<h4>存储与归档</h4>${c.servers?.map(item=>row(item.name,item.state?.message||'最近观测:'+(item.state?.readable?'可读':'未确认'))).join('')||'<p class="text-secondary">暂无配置</p>'}${row('归档记录',`${c.archives?.length||0} 条,最多展示 15 条`)}<h4>通知阻断</h4>${c.business?.blockers?.map(item=>row(item.status,item.error||item.step||'请到原页面核验')).join('')||'<p class="text-secondary">授权快照内没有阻断记录</p>'}<p class="text-secondary small mt-3">最近观测不等于实时健康;刷新不会连接外部系统。</p>`;panels.overview.querySelector('[data-context-refresh]').onclick=()=>refresh().catch(showError);}
|
||||
function showError(e){if(isActive()){let error=panels.overview.querySelector('[role=alert]');if(!error){error=document.createElement('p');error.role='alert';error.className='text-danger';panels.overview.append(error);}error.textContent=e.message;}}
|
||||
async function refresh(){const next=await api('/assistant/context');if(!isActive())return next;context=next;drawOverview();return next;}
|
||||
function evidence(turn){selected=turn;const c=turn?.diagnosticSnapshot;panels.evidence.innerHTML='<h3>本轮诊断依据</h3>'+(c?`<p class="text-secondary">实际用于该轮分析的授权快照,时间 ${esc(formatDate(c.at||c.observedAt))}</p>${row('BPM 连接',c.connections?.map(x=>x.name||x.id).join('、')||'无')}${row('最近记录',`${c.runs?.length||0} 条扫描 / ${c.archives?.length||0} 条归档 / ${c.jobs?.length||0} 条导出`)}${row('诊断范围',c.diagnostic?c.diagnostic.command+' · '+(c.diagnostic.targetId||'全部授权目标'):'全部授权目标')}<p class="small text-secondary mt-2">扫描最多10条,归档/导出最多15条;不代表全部历史。</p>`:turn?.evidence?.map(e=>row(e.label,e.value)).join('')||'<p class="text-secondary">此历史轮次没有保留完整快照。</p>');select('evidence');}
|
||||
function drawActions(){const turns=conversation?.turns||[],sig=JSON.stringify([conversation?.archived,turns.map(t=>t.actions)]);if(sig===actionSignature)return;actionSignature=sig;const list=turns.flatMap(t=>(t.actions||[]).map(a=>({a,t})));panels.actions.innerHTML='<h3>待确认与操作结果</h3>'+list.map(({a,t})=>`<article class="assistant-action" data-action-card="${esc(a.id)}"><strong>${esc(a.label)}</strong><div class="small text-secondary mt-2">目标:${esc(a.targetId)}</div><div class="small text-secondary mt-1">影响:${esc({check_storage:'发起一次存储连接检查',scan_bpm:'只读重新扫描,更新到达记录',retry_archive:'向原目标重试明确失败的归档',collect_field_samples:'读取待办样本并保存字段证据',collect_history_samples:'只读采集历史字段样本',prepare_field_mapping:'生成并检查草稿,不自动生效',repair_code:'在隔离 Git 工作区执行固定测试,不自动合并部署'}[a.kind]||'仅执行已列出的受控操作')}</div><div class="small text-secondary mt-1">操作编号:${esc(a.id)}</div>${a.kind==='repair_code'?`<p class="aw-verify-warning">以本机服务身份运行固定测试;工作区不是操作系统沙箱,通过后仍待人工审查。</p>${a.files.map(f=>`<details><summary>${esc(f.path)} · 查看修改前后</summary><div>修改前</div><pre>${esc(a.beforeFiles?.find(b=>b.path===f.path)?.content||'')}</pre><div>建议内容</div><pre>${esc(f.content)}</pre></details>`).join('')}`:''}${a.progress?`<p class="small mt-2">采样进度 ${esc(a.progress.completed)} / ${esc(a.progress.total)},成功 ${esc(a.progress.captured)},受阻 ${esc(a.progress.failed)}</p>`:''}<div class="mt-3">${a.status==='proposed'?`<button class="btn btn-sm btn-outline-primary" type="button" data-assistant-action="${esc(a.id)}" ${!settings.enabled||!settings.allowActions||conversation.archived||conversation.deletedAt||user.role==='viewer'?'disabled':''}>执行:${esc(a.label)}</button>`:`<strong>${esc(window.AssistantConversation.actionState(a))}</strong>`}</div>${a.error?`<p class="small text-danger mt-2">${esc(a.error)}</p>`:''}${a.result?`<details class="mt-2"><summary>结果详情</summary><pre>${esc(JSON.stringify(a.result,null,2))}</pre></details>`:''}${a.result?.link?'<a class="btn btn-sm mt-2" href="#rule-fields">查看字段映射</a>':''}</article>`).join('')+(list.length?'':'<p class="text-secondary">建议将在这里展示,确认前不会执行。</p>');panels.actions.querySelectorAll('[data-assistant-action]').forEach(button=>button.onclick=()=>onExecute(button.dataset.assistantAction,button));}
|
||||
const timeline=document.createElement('div');panels.events.append(timeline);const audit=document.createElement('div');panels.events.append(audit);
|
||||
function mountAudit(){if(auditMounted)return;auditMounted=true;window.AssistantOperations?.mount(audit,{api,esc,formatDate,user,settings,isActive,onRepair});}
|
||||
function drawEvents(){timeline.innerHTML='<h3>当前会话阶段</h3>'+(events.length?events.map(e=>`<div class="aw-event">${esc(window.AssistantConversation.labels[e.kind]||'阶段更新')}<br><time>${esc(formatDate(e.at))}</time></div>`).join(''):'<p class="text-secondary">历史阶段未记录</p>');}
|
||||
drawOverview();panels.evidence.innerHTML='<p class="text-secondary">点击回答下方“诊断依据”查看该轮快照。</p>';drawActions();drawEvents();
|
||||
return {refresh,getContext:async()=>context||refresh(),select,evidence,help(catalog){panels.overview.innerHTML='<h3>固定诊断命令</h3>'+catalog.map(c=>row('/'+c.name,c.label+' · '+c.detail)).join('');select('overview');},update(c,rows){if(conversation?.id!==c?.id){selected=null;panels.evidence.innerHTML='<p class="text-secondary">点击回答下方“诊断依据”查看该轮快照。</p>';}conversation=c;events=rows;drawActions();drawEvents();},showActions(){select('actions');},dispose(){context=null;conversation=null;events=[];selected=null;}};
|
||||
}};
|
||||
window.AssistantContextPanel = {
|
||||
mount(
|
||||
root,
|
||||
{
|
||||
api,
|
||||
esc,
|
||||
formatDate,
|
||||
user,
|
||||
settings,
|
||||
isActive,
|
||||
onExecute,
|
||||
onRepair,
|
||||
showRight,
|
||||
ensureConversation,
|
||||
onScheduleChanged,
|
||||
},
|
||||
) {
|
||||
let active = 'overview',
|
||||
context = null,
|
||||
conversation = null,
|
||||
events = [],
|
||||
selected = null,
|
||||
auditMounted = false,
|
||||
actionSignature = '';
|
||||
const panels = Object.fromEntries(
|
||||
['overview', 'evidence', 'actions', 'events', 'schedules'].map((id) => [
|
||||
id,
|
||||
root.querySelector('#aw-panel-' + id),
|
||||
]),
|
||||
);
|
||||
const schedules = window.AssistantSchedules.mount(panels.schedules, {
|
||||
api,
|
||||
esc,
|
||||
formatDate,
|
||||
user,
|
||||
getConversation: () => conversation,
|
||||
ensureConversation,
|
||||
onChanged: onScheduleChanged,
|
||||
isActive,
|
||||
});
|
||||
function select(id) {
|
||||
active = id;
|
||||
for (const [key, panel] of Object.entries(panels)) {
|
||||
panel.hidden = key !== id;
|
||||
root
|
||||
.querySelector('[data-context-tab=' + key + ']')
|
||||
.setAttribute('aria-selected', String(key === id));
|
||||
}
|
||||
showRight();
|
||||
schedules.show(id === 'schedules');
|
||||
if (id === 'events') mountAudit();
|
||||
}
|
||||
root
|
||||
.querySelectorAll('[data-context-tab]')
|
||||
.forEach((b) => (b.onclick = () => select(b.dataset.contextTab)));
|
||||
const row = (title, detail) =>
|
||||
`<div class="aw-stat"><strong>${esc(title)}</strong><span>${esc(detail)}</span></div>`;
|
||||
function drawOverview() {
|
||||
const c = context;
|
||||
if (!c) {
|
||||
panels.overview.innerHTML = '<p class="text-secondary">正在读取授权状态…</p>';
|
||||
return;
|
||||
}
|
||||
panels.overview.innerHTML = `<div class="d-flex justify-content-between align-items-center"><h3>诊断概况</h3><div class="btn-list"><button class="btn btn-sm" type="button" data-management-permissions>AI 管理权限</button><button class="btn btn-sm" type="button" data-context-refresh>刷新概况</button></div></div><p class="text-secondary small">本机状态快照 · ${esc(formatDate(c.observedAt || c.at))}</p><h4>BPM 连接</h4>${c.connections?.map((item) => row(item.name, item.status || '未观测')).join('') || '<p class="text-secondary">没有可见连接</p>'}<h4>最近扫描</h4>${c.runs?.map((item) => row(item.status || '未知', formatDate(item.finishedAt || item.startedAt) + ' · 新增 ' + (item.added ?? '未知'))).join('') || '<p class="text-secondary">暂无可见扫描记录</p>'}<h4>存储与归档</h4>${c.servers?.map((item) => row(item.name, item.state?.message || '最近观测:' + (item.state?.readable ? '可读' : '未确认'))).join('') || '<p class="text-secondary">暂无配置</p>'}${row('归档记录', `${c.archives?.length || 0} 条,最多展示 15 条`)}${c.configuration?.length ? '<h4>提供给 AI 的系统配置</h4>' + c.configuration.map((t) => '<details class="mb-2"><summary>' + esc(t.label) + ' · 版本 ' + esc(t.version) + '</summary><pre>' + esc(JSON.stringify(t.values, null, 2)) + '</pre><small>可建议修改:' + esc(t.editable.join('、')) + '</small></details>').join('') + '<p class="small text-secondary">凭据不提供给 AI。修改须逐次审查差异、风险并授权。</p>' : ''}<h4>通知阻断</h4>${c.business?.blockers?.map((item) => row(item.status, item.error || item.step || '请到原页面核验')).join('') || '<p class="text-secondary">授权快照内没有阻断记录</p>'}<p class="text-secondary small mt-3">最近观测不等于实时健康;刷新不会连接外部系统。</p>`;
|
||||
panels.overview.querySelector('[data-management-permissions]').onclick = () =>
|
||||
showPermissions().catch(showError);
|
||||
panels.overview.querySelector('[data-context-refresh]').onclick = () =>
|
||||
refresh().catch(showError);
|
||||
}
|
||||
async function showPermissions() {
|
||||
const data = await api('/assistant/management');
|
||||
if (!isActive()) return;
|
||||
const d = document.createElement('dialog');
|
||||
d.className = 'page-leave-dialog aw-permissions-dialog';
|
||||
d.setAttribute('aria-label', 'AI 管理权限');
|
||||
const mode = { approval: '逐次授权', confirmation: '逐次确认', manual: '仅人工' };
|
||||
d.innerHTML =
|
||||
'<h2 class="h3">AI 管理权限</h2><p>当前角色:' +
|
||||
esc(data.role) +
|
||||
'。只读查询按当前账号权限和资源归属过滤;配置修改须审查差异、风险并逐项授权。</p><h3 class="h4">只读管理查询</h3><div class="table-responsive"><table class="table table-sm"><thead><tr><th>资源</th><th>当前权限</th><th>范围</th></tr></thead><tbody>' +
|
||||
data.resources
|
||||
.map(
|
||||
(r) =>
|
||||
'<tr><td>' +
|
||||
esc(r.label) +
|
||||
'</td><td>' +
|
||||
(!r.allowed ? '无权限' : !r.available ? '服务未就绪' : '可查询') +
|
||||
'</td><td>' +
|
||||
esc(r.scope) +
|
||||
'</td></tr>',
|
||||
)
|
||||
.join('') +
|
||||
'</tbody></table></div><h3 class="h4">允许建议修改的配置</h3>' +
|
||||
data.writeTargets
|
||||
.map(
|
||||
(t) =>
|
||||
'<p><strong>' +
|
||||
esc(t.label) +
|
||||
'</strong> · ' +
|
||||
(t.allowed ? '需逐次授权' : '当前不可修改') +
|
||||
'<br><small>' +
|
||||
esc(t.fields.join('、')) +
|
||||
'</small></p>',
|
||||
)
|
||||
.join('') +
|
||||
'<h3 class="h4">执行边界</h3>' +
|
||||
data.boundaries
|
||||
.map(
|
||||
(b) =>
|
||||
'<p><strong>' +
|
||||
esc(b.label) +
|
||||
' · ' +
|
||||
esc(mode[b.mode]) +
|
||||
(!b.allowed && b.mode !== 'manual' ? '(当前账号不可执行)' : '') +
|
||||
'</strong><br><small>' +
|
||||
esc(b.description) +
|
||||
'</small></p>',
|
||||
)
|
||||
.join('') +
|
||||
'<button type="button" class="btn" data-permissions-close>关闭</button>';
|
||||
root.append(d);
|
||||
d.querySelector('[data-permissions-close]').onclick = () => d.close();
|
||||
d.onclose = () => d.remove();
|
||||
d.showModal();
|
||||
}
|
||||
function showError(e) {
|
||||
if (isActive()) {
|
||||
let error = panels.overview.querySelector('[role=alert]');
|
||||
if (!error) {
|
||||
error = document.createElement('p');
|
||||
error.role = 'alert';
|
||||
error.className = 'text-danger';
|
||||
panels.overview.append(error);
|
||||
}
|
||||
error.textContent = e.message;
|
||||
}
|
||||
}
|
||||
async function refresh() {
|
||||
const next = await api('/assistant/context');
|
||||
if (!isActive()) return next;
|
||||
context = next;
|
||||
drawOverview();
|
||||
return next;
|
||||
}
|
||||
function evidence(turn) {
|
||||
selected = turn;
|
||||
const c = turn?.diagnosticSnapshot;
|
||||
panels.evidence.innerHTML =
|
||||
'<h3>本轮诊断依据</h3>' +
|
||||
(c
|
||||
? `<p class="text-secondary">实际用于该轮分析的授权快照,时间 ${esc(formatDate(c.at || c.observedAt))}</p>${row('BPM 连接', c.connections?.map((x) => x.name || x.id).join('、') || '无')}${row('最近记录', `${c.runs?.length || 0} 条扫描 / ${c.archives?.length || 0} 条归档 / ${c.jobs?.length || 0} 条导出`)}${c.managementResults?.length ? row('本轮管理查询', c.managementResults.map((r) => r.resource + ':' + (r.error ? '查询受阻' : String(r.items?.length || 0) + ' / ' + r.total + ' 项')).join(';')) : ''}${row('诊断范围', c.diagnostic ? c.diagnostic.command + ' · ' + (c.diagnostic.targetId || '全部授权目标') : '全部授权目标')}<p class="small text-secondary mt-2">扫描最多10条,归档/导出最多15条;不代表全部历史。</p>`
|
||||
: turn?.evidence?.map((e) => row(e.label, e.value)).join('') ||
|
||||
'<p class="text-secondary">此历史轮次没有保留完整快照。</p>');
|
||||
select('evidence');
|
||||
}
|
||||
function drawActions() {
|
||||
const turns = conversation?.turns || [],
|
||||
sig = JSON.stringify([conversation?.archived, turns.map((t) => t.actions)]);
|
||||
if (sig === actionSignature) return;
|
||||
actionSignature = sig;
|
||||
const list = turns.flatMap((t) => (t.actions || []).map((a) => ({ a, t })));
|
||||
panels.actions.innerHTML =
|
||||
'<h3>待确认与操作结果</h3>' +
|
||||
list
|
||||
.map(
|
||||
({ a, t }) =>
|
||||
`<article class="assistant-action" data-action-card="${esc(a.id)}"><strong>${esc(a.label)}</strong><div class="small text-secondary mt-2">目标:${esc(a.targetId)}</div><div class="small text-secondary mt-1">影响:${esc({ check_storage: '发起一次存储连接检查', scan_bpm: '只读重新扫描,更新到达记录', retry_archive: '向原目标重试明确失败的归档', collect_field_samples: '读取待办样本并保存字段证据', collect_history_samples: '只读采集历史字段样本', prepare_field_mapping: '生成并检查草稿,不自动生效', repair_code: '在隔离 Git 工作区执行固定测试,不自动合并部署' }[a.kind] || '仅执行已列出的受控操作')}</div><div class="small text-secondary mt-1">操作编号:${esc(a.id)}</div>${['update_configuration', 'manage_schedule'].includes(a.kind) ? `<div class="aw-config-summary">${a.diff.map((d) => `<p>${esc(d.label)}:${esc(JSON.stringify(d.before))} → ${esc(JSON.stringify(d.after))}</p>`).join('')}<strong>风险与影响</strong><ul>${a.risks.map((r) => `<li>${esc(r)}</li>`).join('')}</ul><small>审查并授权后才会保存;建议过期或配置变化须重新生成。</small></div>` : ''}${a.kind === 'repair_code' ? `<p class="aw-verify-warning">以本机服务身份运行固定测试;工作区不是操作系统沙箱,通过后仍待人工审查。</p>${a.files.map((f) => `<details><summary>${esc(f.path)} · 查看修改前后</summary><div>修改前</div><pre>${esc(a.beforeFiles?.find((b) => b.path === f.path)?.content || '')}</pre><div>建议内容</div><pre>${esc(f.content)}</pre></details>`).join('')}` : ''}${a.progress ? `<p class="small mt-2">采样进度 ${esc(a.progress.completed)} / ${esc(a.progress.total)},成功 ${esc(a.progress.captured)},受阻 ${esc(a.progress.failed)}</p>` : ''}<div class="mt-3">${a.status === 'proposed' ? `<button class="btn btn-sm btn-outline-primary" type="button" data-assistant-action="${esc(a.id)}" ${(!settings.allowActions && a.kind !== 'manage_schedule') || conversation.archived || conversation.deletedAt || user.role === 'viewer' ? 'disabled' : ''}>${['update_configuration', 'manage_schedule'].includes(a.kind) ? '审查修改' : '执行:' + esc(a.label)}</button>` : `<strong>${esc(window.AssistantConversation.actionState(a))}</strong>`}</div>${a.error ? `<p class="small text-danger mt-2">${esc(a.error)}</p>` : ''}${a.result || ['success', 'error', 'needs_review', 'interrupted'].includes(a.status) ? `<details class="mt-2 aw-action-result"><summary>结果详情</summary><p class="mt-2">${esc(window.AssistantConversation.actionSummary(a))}</p>${a.result && (typeof a.result !== 'object' || Object.keys(a.result).length) ? `<pre>${esc(JSON.stringify(a.result, null, 2))}</pre>` : ''}</details>` : ''}${a.result?.link ? '<a class="btn btn-sm mt-2" href="' + esc(a.kind === 'update_configuration' ? a.result.link : '#rule-fields') + '">' + (a.kind === 'update_configuration' ? '查看设置' : '查看字段映射') + '</a>' : ''}</article>`,
|
||||
)
|
||||
.join('') +
|
||||
(list.length ? '' : '<p class="text-secondary">建议将在这里展示,确认前不会执行。</p>');
|
||||
panels.actions
|
||||
.querySelectorAll('[data-assistant-action]')
|
||||
.forEach(
|
||||
(button) => (button.onclick = () => onExecute(button.dataset.assistantAction, button)),
|
||||
);
|
||||
}
|
||||
const timeline = document.createElement('div');
|
||||
panels.events.append(timeline);
|
||||
const audit = document.createElement('div');
|
||||
panels.events.append(audit);
|
||||
function mountAudit() {
|
||||
if (auditMounted) return;
|
||||
auditMounted = true;
|
||||
window.AssistantOperations?.mount(audit, {
|
||||
api,
|
||||
esc,
|
||||
formatDate,
|
||||
user,
|
||||
settings,
|
||||
isActive,
|
||||
onRepair,
|
||||
});
|
||||
}
|
||||
function drawEvents() {
|
||||
timeline.innerHTML =
|
||||
'<h3>当前会话阶段</h3>' +
|
||||
(events.length
|
||||
? events
|
||||
.map(
|
||||
(e) =>
|
||||
`<div class="aw-event">${esc(window.AssistantConversation.labels[e.kind] || '阶段更新')}<br><time>${esc(formatDate(e.at))}</time></div>`,
|
||||
)
|
||||
.join('')
|
||||
: '<p class="text-secondary">历史阶段未记录</p>');
|
||||
}
|
||||
drawOverview();
|
||||
panels.evidence.innerHTML =
|
||||
'<p class="text-secondary">点击回答下方“诊断依据”查看该轮快照。</p>';
|
||||
drawActions();
|
||||
drawEvents();
|
||||
return {
|
||||
refresh,
|
||||
getContext: async () => context || refresh(),
|
||||
select,
|
||||
evidence,
|
||||
help(catalog) {
|
||||
panels.overview.innerHTML =
|
||||
'<h3>固定诊断命令</h3>' +
|
||||
catalog.map((c) => row('/' + c.name, c.label + ' · ' + c.detail)).join('');
|
||||
select('overview');
|
||||
},
|
||||
update(c, rows) {
|
||||
if (conversation?.id !== c?.id) {
|
||||
selected = null;
|
||||
panels.evidence.innerHTML =
|
||||
'<p class="text-secondary">点击回答下方“诊断依据”查看该轮快照。</p>';
|
||||
}
|
||||
conversation = c;
|
||||
schedules.update(c);
|
||||
events = rows;
|
||||
drawActions();
|
||||
drawEvents();
|
||||
},
|
||||
showActions() {
|
||||
select('actions');
|
||||
},
|
||||
dispose() {
|
||||
schedules.dispose();
|
||||
context = null;
|
||||
conversation = null;
|
||||
events = [];
|
||||
selected = null;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,37 +1,304 @@
|
||||
'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 actionState(a){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');
|
||||
messages.onscroll=()=>{following=messages.scrollHeight-messages.scrollTop-messages.clientHeight<70;if(following)jump.hidden=true;};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.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;}
|
||||
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 '已返回操作结果,可展开查看明细。';
|
||||
}
|
||||
return {update,dispose(){messages.onscroll=null;jump.onclick=null;},reset(){nodes.clear();messages.replaceChildren();following=true;}};
|
||||
}
|
||||
return {mount,labels,actionState,markdown};
|
||||
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 };
|
||||
})();
|
||||
@@ -2,64 +2,80 @@
|
||||
* MIT; see licenses/DeepSeek-Harness-MIT.txt and DSH-native-NOTICES.md.
|
||||
* Geometry/grouping bodies are upstream; wrapper and fixed-catalog resolution
|
||||
* remove React/Cordis and native host command aliases. */
|
||||
(function(root){
|
||||
'use strict';
|
||||
const SIDEBAR_AUTO_COLLAPSE = 1024;
|
||||
/** Maximum normal right panel width as a fraction of the frame. */
|
||||
const RIGHTBAR_MAX_RATIO = .7;
|
||||
/** First-open right panel preference as a fraction of the frame. */
|
||||
const RIGHTBAR_DEFAULT_RATIO = .45;
|
||||
/**
|
||||
* Clamp a panel width into its contract range.
|
||||
* @param px - requested width.
|
||||
* @param min - range lower bound.
|
||||
* @param max - range upper bound.
|
||||
* @returns the clamped width.
|
||||
*/
|
||||
function clampWidth(px, min, max) {
|
||||
return Math.min(max, Math.max(min, Math.round(px)));
|
||||
}
|
||||
/**
|
||||
* Solve the three column widths for one viewport frame.
|
||||
* @param viewport - available frame width in px.
|
||||
* @param sidebar - sidebar width preference in px (0 = closed).
|
||||
* @param rightbar - requested right panel width in px (0 = no track).
|
||||
* @param collapsedWidth - track width of the closed sidebar; the default keeps
|
||||
* the icon rail, 0 hides the column entirely (macOS desktop).
|
||||
* @returns actual widths after shrinking or removing the right track; only
|
||||
* without that track may the center fall below its minimum, down to zero.
|
||||
*/
|
||||
function computeColumns(viewport, sidebar, rightbar, collapsedWidth = 56) {
|
||||
const s = sidebar === 0 ? collapsedWidth : clampWidth(sidebar, 264, 420);
|
||||
const available = viewport - s - 400;
|
||||
const r = rightbar === 0 || available < 300 ? 0 : Math.min(available, clampWidth(rightbar, 300, viewport * RIGHTBAR_MAX_RATIO));
|
||||
return {
|
||||
sidebar: s,
|
||||
center: Math.max(0, viewport - s - r),
|
||||
rightbar: r
|
||||
};
|
||||
}
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const SIDEBAR_AUTO_COLLAPSE = 1024;
|
||||
/** Maximum normal right panel width as a fraction of the frame. */
|
||||
const RIGHTBAR_MAX_RATIO = 0.7;
|
||||
/** First-open right panel preference as a fraction of the frame. */
|
||||
const RIGHTBAR_DEFAULT_RATIO = 0.45;
|
||||
/**
|
||||
* Clamp a panel width into its contract range.
|
||||
* @param px - requested width.
|
||||
* @param min - range lower bound.
|
||||
* @param max - range upper bound.
|
||||
* @returns the clamped width.
|
||||
*/
|
||||
function clampWidth(px, min, max) {
|
||||
return Math.min(max, Math.max(min, Math.round(px)));
|
||||
}
|
||||
/**
|
||||
* Solve the three column widths for one viewport frame.
|
||||
* @param viewport - available frame width in px.
|
||||
* @param sidebar - sidebar width preference in px (0 = closed).
|
||||
* @param rightbar - requested right panel width in px (0 = no track).
|
||||
* @param collapsedWidth - track width of the closed sidebar; the default keeps
|
||||
* the icon rail, 0 hides the column entirely (macOS desktop).
|
||||
* @returns actual widths after shrinking or removing the right track; only
|
||||
* without that track may the center fall below its minimum, down to zero.
|
||||
*/
|
||||
function computeColumns(viewport, sidebar, rightbar, collapsedWidth = 56) {
|
||||
const s = sidebar === 0 ? collapsedWidth : clampWidth(sidebar, 264, 420);
|
||||
const available = viewport - s - 400;
|
||||
const r =
|
||||
rightbar === 0 || available < 300
|
||||
? 0
|
||||
: Math.min(available, clampWidth(rightbar, 300, viewport * RIGHTBAR_MAX_RATIO));
|
||||
return {
|
||||
sidebar: s,
|
||||
center: Math.max(0, viewport - s - r),
|
||||
rightbar: r,
|
||||
};
|
||||
}
|
||||
|
||||
function groupOptions(options) {
|
||||
const groups = /* @__PURE__ */ new Map();
|
||||
for (const option of options) {
|
||||
const name = option.group?.name;
|
||||
const existing = groups.get(name);
|
||||
if (existing !== void 0) existing.rows.push(option);
|
||||
else groups.set(name, {
|
||||
group: option.group,
|
||||
rows: [option]
|
||||
});
|
||||
}
|
||||
return [...groups.values()];
|
||||
}
|
||||
function resolveCommand(token,descriptors){return descriptors.find(descriptor=>descriptor.name===token);}
|
||||
// Native popup substring policy; fuzzy mode and its React primitives omitted.
|
||||
function filterOptions(options,search){
|
||||
const query=search.trim().toLowerCase(),groups=groupOptions(options);
|
||||
const ordered=groups.some(group=>group.group!==undefined)?groups.flatMap(group=>group.rows):options;
|
||||
return query===''?ordered:ordered.filter(o=>o.label.toLowerCase().includes(query)||(o.detail?.toLowerCase().includes(query)??false));
|
||||
}
|
||||
const api={clampWidth,computeColumns,resolveCommand,filterOptions,groupOptions};
|
||||
if(typeof module==='object'&&module.exports)module.exports=api;else root.AssistantNative=api;
|
||||
})(typeof window==='object'?window:globalThis);
|
||||
function groupOptions(options) {
|
||||
const groups = /* @__PURE__ */ new Map();
|
||||
for (const option of options) {
|
||||
const name = option.group?.name;
|
||||
const existing = groups.get(name);
|
||||
if (existing !== void 0) existing.rows.push(option);
|
||||
else
|
||||
groups.set(name, {
|
||||
group: option.group,
|
||||
rows: [option],
|
||||
});
|
||||
}
|
||||
return [...groups.values()];
|
||||
}
|
||||
function resolveCommand(token, descriptors) {
|
||||
return descriptors.find((descriptor) => descriptor.name === token);
|
||||
}
|
||||
// Native popup substring policy; fuzzy mode and its React primitives omitted.
|
||||
function filterOptions(options, search) {
|
||||
const query = search.trim().toLowerCase(),
|
||||
groups = groupOptions(options);
|
||||
const ordered = groups.some((group) => group.group !== undefined)
|
||||
? groups.flatMap((group) => group.rows)
|
||||
: options;
|
||||
return query === ''
|
||||
? ordered
|
||||
: ordered.filter(
|
||||
(o) =>
|
||||
o.label.toLowerCase().includes(query) ||
|
||||
(o.detail?.toLowerCase().includes(query) ?? false),
|
||||
);
|
||||
}
|
||||
const api = { clampWidth, computeColumns, resolveCommand, filterOptions, groupOptions };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.AssistantNative = api;
|
||||
})(typeof window === 'object' ? window : globalThis);
|
||||
@@ -1,32 +1,191 @@
|
||||
'use strict';
|
||||
window.AssistantEvents={connect({id,cursor=0,api,onEvents,onChange,onAuth,onRemoved,isActive=()=>true}){
|
||||
let disposed=false,controller=null,retryTimer=null,pollTimer=null,probeTimer=null,failures=0,backoff=0,polling=false,pollInFlight=false,delivery=Promise.resolve();const lifetime=new AbortController();
|
||||
const alive=()=>!disposed&&isActive();
|
||||
function auth(error){if(error.status===404){dispose();onRemoved?.();return true;}if(error.status===401||error.status===403){dispose();onAuth?.(error);return true;}return false;}
|
||||
function consume(events){const work=delivery.catch(()=>{}).then(async()=>{if(!alive())return;const fresh=[];let next=cursor;for(const e of events){if(e.conversationId!==id||!Number.isSafeInteger(e.seq)||e.seq<=next)continue;if(e.seq!==next+1)throw new Error('事件序列不连续');next=e.seq;fresh.push(e);}if(fresh.length){await onChange();if(!alive())return;onEvents(fresh);cursor=next;}});delivery=work;return work;}
|
||||
async function catchUp(){let more=true;while(alive()&&more){const batch=await api('/assistant/conversations/'+id+'/events?after='+cursor,undefined,{signal:lifetime.signal});if(!alive())return;await consume(batch.events);more=batch.hasMore;}}
|
||||
function beginPolling(){if(!alive())return;clearTimeout(probeTimer);probeTimer=setTimeout(()=>{if(alive())void stream();},60000);if(polling)return;polling=true;const poll=async()=>{if(pollInFlight)return;pollInFlight=true;try{await catchUp();}catch(e){if(auth(e))return;if(e.status===400){cursor=0;await onChange();}}finally{pollInFlight=false;if(alive()&&polling)pollTimer=setTimeout(poll,3000);}};void poll();}
|
||||
async function stream(){
|
||||
if(!alive())return;controller?.abort();const mine=new AbortController();controller=mine;let buffer='',idleTimer;const resetIdle=()=>{clearTimeout(idleTimer);idleTimer=setTimeout(()=>mine.abort(),45000);};
|
||||
resetIdle();try{
|
||||
const response=await fetch('/api/assistant/conversations/'+id+'/stream?after='+cursor,{credentials:'same-origin',signal:mine.signal,headers:cursor?{'Last-Event-ID':String(cursor)}:{}});
|
||||
if(!response.ok)throw Object.assign(new Error('事件连接失败'),{status:response.status});
|
||||
if(!/^text\/event-stream/.test(response.headers.get('content-type')||''))throw new Error('事件协议无效');
|
||||
polling=false;clearTimeout(pollTimer);clearTimeout(probeTimer);const reader=response.body.getReader(),decoder=new TextDecoder();resetIdle();
|
||||
while(alive()){
|
||||
const {done,value}=await reader.read();if(done)break;resetIdle();buffer+=decoder.decode(value,{stream:true}).replace(/\r\n/g,'\n');if(buffer.length>256*1024)throw new Error('事件数据超过限制');
|
||||
let end;while((end=buffer.indexOf('\n\n'))>=0){const frame=buffer.slice(0,end);buffer=buffer.slice(end+2);const type=frame.split('\n').find(l=>l.startsWith('event:'))?.slice(6).trim();const data=frame.split('\n').filter(l=>l.startsWith('data:')).map(l=>l.slice(5).trimStart()).join('\n');
|
||||
if(type==='auth_required')throw Object.assign(new Error('登录或权限已变化'),{status:401});
|
||||
if(type==='conversation_removed')throw Object.assign(new Error('会话已移入回收站或删除'),{status:404});
|
||||
if(type==='conversation_updated'){await onChange();continue;}
|
||||
if(type==='stream_error')throw new Error('事件服务暂不可用');
|
||||
if(type==='assistant_event'&&data){await consume([JSON.parse(data)]);failures=0;backoff=0;}
|
||||
window.AssistantEvents = {
|
||||
connect({ id, cursor = 0, api, onEvents, onChange, onAuth, onRemoved, isActive = () => true }) {
|
||||
let disposed = false,
|
||||
controller = null,
|
||||
retryTimer = null,
|
||||
pollTimer = null,
|
||||
probeTimer = null,
|
||||
failures = 0,
|
||||
backoff = 0,
|
||||
polling = false,
|
||||
pollInFlight = false,
|
||||
delivery = Promise.resolve();
|
||||
const lifetime = new AbortController();
|
||||
const alive = () => !disposed && isActive();
|
||||
function auth(error) {
|
||||
if (error.status === 404) {
|
||||
dispose();
|
||||
onRemoved?.();
|
||||
return true;
|
||||
}
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
dispose();
|
||||
onAuth?.(error);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if(alive())throw new Error('事件连接中断');
|
||||
}catch(error){if(!alive()||controller!==mine||auth(error))return;mine.abort();failures++;const delays=[1000,2000,4000,8000,15000];if(failures>=3){beginPolling();}else retryTimer=setTimeout(()=>void stream(),delays[Math.min(backoff++,delays.length-1)]);
|
||||
}finally{clearTimeout(idleTimer);}
|
||||
}
|
||||
function dispose(){disposed=true;controller?.abort();lifetime.abort();clearTimeout(retryTimer);clearTimeout(pollTimer);clearTimeout(probeTimer);}
|
||||
void stream();return {dispose,get cursor(){return cursor;}};
|
||||
}};
|
||||
function consume(events) {
|
||||
const work = delivery
|
||||
.catch(() => {})
|
||||
.then(async () => {
|
||||
if (!alive()) return;
|
||||
const fresh = [];
|
||||
let next = cursor;
|
||||
for (const e of events) {
|
||||
if (e.conversationId !== id || !Number.isSafeInteger(e.seq) || e.seq <= next) continue;
|
||||
if (e.seq !== next + 1) throw new Error('事件序列不连续');
|
||||
next = e.seq;
|
||||
fresh.push(e);
|
||||
}
|
||||
if (fresh.length) {
|
||||
await onChange();
|
||||
if (!alive()) return;
|
||||
onEvents(fresh);
|
||||
cursor = next;
|
||||
}
|
||||
});
|
||||
delivery = work;
|
||||
return work;
|
||||
}
|
||||
async function catchUp() {
|
||||
let more = true;
|
||||
while (alive() && more) {
|
||||
const batch = await api(
|
||||
'/assistant/conversations/' + id + '/events?after=' + cursor,
|
||||
undefined,
|
||||
{ signal: lifetime.signal },
|
||||
);
|
||||
if (!alive()) return;
|
||||
await consume(batch.events);
|
||||
more = batch.hasMore;
|
||||
}
|
||||
}
|
||||
function beginPolling() {
|
||||
if (!alive()) return;
|
||||
clearTimeout(probeTimer);
|
||||
probeTimer = setTimeout(() => {
|
||||
if (alive()) void stream();
|
||||
}, 60000);
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
const poll = async () => {
|
||||
if (pollInFlight) return;
|
||||
pollInFlight = true;
|
||||
try {
|
||||
await catchUp();
|
||||
} catch (e) {
|
||||
if (auth(e)) return;
|
||||
if (e.status === 400) {
|
||||
cursor = 0;
|
||||
await onChange();
|
||||
}
|
||||
} finally {
|
||||
pollInFlight = false;
|
||||
if (alive() && polling) pollTimer = setTimeout(poll, 3000);
|
||||
}
|
||||
};
|
||||
void poll();
|
||||
}
|
||||
async function stream() {
|
||||
if (!alive()) return;
|
||||
controller?.abort();
|
||||
const mine = new AbortController();
|
||||
controller = mine;
|
||||
let buffer = '',
|
||||
idleTimer;
|
||||
const resetIdle = () => {
|
||||
clearTimeout(idleTimer);
|
||||
idleTimer = setTimeout(() => mine.abort(), 45000);
|
||||
};
|
||||
resetIdle();
|
||||
try {
|
||||
const response = await fetch(
|
||||
'/api/assistant/conversations/' + id + '/stream?after=' + cursor,
|
||||
{
|
||||
credentials: 'same-origin',
|
||||
signal: mine.signal,
|
||||
headers: cursor ? { 'Last-Event-ID': String(cursor) } : {},
|
||||
},
|
||||
);
|
||||
if (!response.ok)
|
||||
throw Object.assign(new Error('事件连接失败'), { status: response.status });
|
||||
if (!/^text\/event-stream/.test(response.headers.get('content-type') || ''))
|
||||
throw new Error('事件协议无效');
|
||||
polling = false;
|
||||
clearTimeout(pollTimer);
|
||||
clearTimeout(probeTimer);
|
||||
const reader = response.body.getReader(),
|
||||
decoder = new TextDecoder();
|
||||
resetIdle();
|
||||
while (alive()) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
resetIdle();
|
||||
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
|
||||
if (buffer.length > 256 * 1024) throw new Error('事件数据超过限制');
|
||||
let end;
|
||||
while ((end = buffer.indexOf('\n\n')) >= 0) {
|
||||
const frame = buffer.slice(0, end);
|
||||
buffer = buffer.slice(end + 2);
|
||||
const type = frame
|
||||
.split('\n')
|
||||
.find((l) => l.startsWith('event:'))
|
||||
?.slice(6)
|
||||
.trim();
|
||||
const data = frame
|
||||
.split('\n')
|
||||
.filter((l) => l.startsWith('data:'))
|
||||
.map((l) => l.slice(5).trimStart())
|
||||
.join('\n');
|
||||
if (type === 'auth_required')
|
||||
throw Object.assign(new Error('登录或权限已变化'), { status: 401 });
|
||||
if (type === 'conversation_removed')
|
||||
throw Object.assign(new Error('会话已移入回收站或删除'), { status: 404 });
|
||||
if (type === 'conversation_updated') {
|
||||
await onChange();
|
||||
continue;
|
||||
}
|
||||
if (type === 'stream_error') throw new Error('事件服务暂不可用');
|
||||
if (type === 'assistant_event' && data) {
|
||||
await consume([JSON.parse(data)]);
|
||||
failures = 0;
|
||||
backoff = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (alive()) throw new Error('事件连接中断');
|
||||
} catch (error) {
|
||||
if (!alive() || controller !== mine || auth(error)) return;
|
||||
mine.abort();
|
||||
failures++;
|
||||
const delays = [1000, 2000, 4000, 8000, 15000];
|
||||
if (failures >= 3) {
|
||||
beginPolling();
|
||||
} else
|
||||
retryTimer = setTimeout(
|
||||
() => void stream(),
|
||||
delays[Math.min(backoff++, delays.length - 1)],
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(idleTimer);
|
||||
}
|
||||
}
|
||||
function dispose() {
|
||||
disposed = true;
|
||||
controller?.abort();
|
||||
lifetime.abort();
|
||||
clearTimeout(retryTimer);
|
||||
clearTimeout(pollTimer);
|
||||
clearTimeout(probeTimer);
|
||||
}
|
||||
void stream();
|
||||
return {
|
||||
dispose,
|
||||
get cursor() {
|
||||
return cursor;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
+199
-20
@@ -1,21 +1,200 @@
|
||||
'use strict';
|
||||
window.AssistantLayout={mount(host,{settings,usage,esc}){
|
||||
host.innerHTML=`<section class="assistant-workspace" aria-label="DSH 诊断工作区"><header class="aw-header"><button class="btn btn-sm" type="button" data-aw-left aria-label="会话列表" aria-expanded="true">☰</button><a href="#tools" class="btn btn-outline-primary aw-back" aria-label="返回工具">← 返回工具</a><strong>DSH 助手</strong><span class="aw-model">${esc(settings.model||'模型未配置')}</span><span class="aw-connection" role="status">${settings.enabled?'诊断已启用':'待配置 / 已暂停'}</span><span class="aw-usage">今日 ${usage.calls} / ${usage.limit}</span><button class="btn btn-sm" type="button" data-aw-right aria-label="诊断上下文" aria-expanded="true">上下文</button></header><div class="aw-body"><aside class="aw-sidebar" aria-label="个人会话"><div class="aw-sidebar-top"><button class="btn btn-primary w-100" id="assistant-new">新建对话</button><label class="visually-hidden" for="assistant-search">搜索会话</label><input class="form-control" id="assistant-search" maxlength="100" placeholder="搜索会话标题"><label class="visually-hidden" for="assistant-scope">会话范围</label><select class="form-select" id="assistant-scope"><option value="active">活跃会话</option><option value="archived">已归档</option><option value="deleted">回收站</option></select></div><div id="assistant-conversations" class="aw-conversations"></div><div class="aw-pager"><button class="btn btn-sm" id="assistant-prev" type="button">上一页</button><span id="assistant-page" class="small"></span><button class="btn btn-sm" id="assistant-next" type="button">下一页</button></div><div id="assistant-search-note" class="small text-secondary px-3 pb-2"></div></aside><div class="aw-drag aw-drag-left" role="separator" tabindex="0" aria-label="调整会话栏宽度" aria-orientation="vertical"></div><main class="assistant-chat aw-chat"><div class="aw-chat-header"><h2 id="assistant-title">新对话</h2><div id="assistant-lifecycle" class="btn-list"></div></div><div class="small text-secondary px-3" id="assistant-history-note"></div><div id="assistant-messages" class="assistant-messages" role="log" aria-live="polite"></div><button id="assistant-new-progress" class="btn btn-sm" hidden>有新进展 ↓</button><footer class="aw-composer"><div id="assistant-suggestions" class="aw-suggestions">${[['连接健康','status'],['扫描异常','bpm'],['归档失败','archive'],['通知阻断','blockers']].map(([label,command])=>`<button class="btn btn-sm" type="button" data-diagnostic-start="${command}">${label}</button>`).join('')}</div><form id="assistant-compose"><label class="visually-hidden" for="assistant-input">发送给 DSH</label><div class="aw-input-wrap"><textarea id="assistant-input" class="form-control" rows="2" maxlength="4000" placeholder="描述运行异常,或输入 / 选择诊断命令"></textarea><div id="assistant-command-menu" class="aw-command-menu" hidden></div></div><div class="aw-compose-tools"><button class="btn btn-sm" type="button" id="assistant-commands" aria-label="诊断命令">/</button><span class="small text-secondary flex-fill">Enter 发送 · Shift + Enter 换行</span><button class="btn btn-sm" type="button" id="assistant-stop" hidden>停止回复</button><button class="btn btn-primary btn-sm" type="submit" id="assistant-send">发送</button></div><div id="assistant-send-hint" class="small text-warning mt-2" role="status"></div><div id="assistant-error" class="small text-danger" role="alert"></div></form></footer></main><div class="aw-drag aw-drag-right" role="separator" tabindex="0" aria-label="调整上下文栏宽度" aria-orientation="vertical"></div><aside class="aw-context" aria-label="诊断详情"><div class="aw-context-tabs" role="tablist">${[['overview','概况'],['evidence','证据'],['actions','操作'],['events','记录']].map(([id,label])=>`<button type="button" role="tab" id="aw-tab-${id}" aria-controls="aw-panel-${id}" aria-selected="${id==='overview'}" data-context-tab="${id}">${label}</button>`).join('')}</div>${['overview','evidence','actions','events'].map(id=>`<section id="aw-panel-${id}" role="tabpanel" aria-labelledby="aw-tab-${id}" ${id==='overview'?'':'hidden'}></section>`).join('')}</aside></div></section>`;
|
||||
const root=host.querySelector('.assistant-workspace'),body=root.querySelector('.aw-body'),leftButton=root.querySelector('[data-aw-left]'),rightButton=root.querySelector('[data-aw-right]');let width=0,leftOpen=true,rightOpen=true,leftWidth=264,rightWidth=320,lastWidth=0;
|
||||
const shell=document.querySelector('#app>.page');shell?.classList.add('dsh-focused');
|
||||
function measure(){root.style.height=Math.max(240,(window.visualViewport?.height||innerHeight)-root.getBoundingClientRect().top)+'px';width=root.clientWidth;if(width!==lastWidth){if(width<880){leftOpen=false;rightOpen=false;}else if(width<1180){leftOpen=false;rightOpen=false;}else if(!lastWidth){leftOpen=true;rightOpen=true;}lastWidth=width;}apply();}
|
||||
function apply(){const narrow=width<880;const columns=window.AssistantNative.computeColumns(width,leftOpen?leftWidth:0,rightOpen?rightWidth:0,narrow?0:56);
|
||||
if(!narrow&&rightOpen&&columns.rightbar===0)rightOpen=false;
|
||||
root.classList.toggle('aw-narrow',narrow);root.classList.toggle('aw-left-open',leftOpen);root.classList.toggle('aw-right-open',rightOpen);root.classList.toggle('aw-left-collapsed',!leftOpen);leftButton.setAttribute('aria-expanded',String(leftOpen));rightButton.setAttribute('aria-expanded',String(rightOpen));
|
||||
body.style.gridTemplateColumns=narrow?'minmax(0,1fr)':`${columns.sidebar}px ${leftOpen?'5px':'0px'} minmax(0,1fr) ${rightOpen?'5px '+columns.rightbar+'px':'0px 0px'}`;
|
||||
root.querySelector('.aw-sidebar').inert=!leftOpen;root.querySelector('.aw-context').inert=!rightOpen;
|
||||
}
|
||||
leftButton.onclick=()=>{leftOpen=!leftOpen;if(width<880&&leftOpen)rightOpen=false;apply();if(leftOpen)root.querySelector('#assistant-search').focus();};
|
||||
rightButton.onclick=()=>{rightOpen=!rightOpen;if(width<1180&&rightOpen)leftOpen=false;apply();if(rightOpen)root.querySelector('[data-context-tab][aria-selected=true]').focus();};
|
||||
const onKey=event=>{if(event.key==='Escape'&&!root.querySelector('dialog[open]')&&root.querySelector('#assistant-command-menu').hidden){if(width<880&&leftOpen){leftOpen=false;apply();leftButton.focus();}else if(rightOpen){rightOpen=false;apply();rightButton.focus();}}};root.addEventListener('keydown',onKey);
|
||||
const disposers=[];for(const [side,selector] of [['left','.aw-drag-left'],['right','.aw-drag-right']]){const bar=root.querySelector(selector);let drag=null;
|
||||
const move=event=>{if(!drag)return;if(side==='left')leftWidth=window.AssistantNative.clampWidth(drag.value+event.clientX-drag.x,264,420);else rightWidth=window.AssistantNative.clampWidth(drag.value-event.clientX+drag.x,300,width*.7);apply();};
|
||||
bar.onpointerdown=event=>{drag={x:event.clientX,value:side==='left'?leftWidth:rightWidth};bar.setPointerCapture(event.pointerId);};bar.onpointermove=move;bar.onpointerup=bar.onpointercancel=()=>{drag=null;};bar.onkeydown=event=>{if(!['ArrowLeft','ArrowRight'].includes(event.key))return;event.preventDefault();const delta=event.key==='ArrowRight'?16:-16;if(side==='left')leftWidth=window.AssistantNative.clampWidth(leftWidth+delta,264,420);else rightWidth=window.AssistantNative.clampWidth(rightWidth-delta,300,width*.7);apply();};disposers.push(()=>{bar.onpointerdown=bar.onpointermove=bar.onpointerup=bar.onpointercancel=bar.onkeydown=null;});}
|
||||
const observer=new ResizeObserver(measure);observer.observe(root);window.visualViewport?.addEventListener('resize',measure);measure();
|
||||
return {root,showRight(){rightOpen=true;if(width<1180)leftOpen=false;apply();},closeLeft(){if(width<880){leftOpen=false;apply();}},dispose(){observer.disconnect();window.visualViewport?.removeEventListener('resize',measure);for(const dispose of disposers)dispose();root.removeEventListener('keydown',onKey);shell?.classList.remove('dsh-focused');}};
|
||||
}};
|
||||
window.AssistantLayout = {
|
||||
mount(host, { settings, usage, esc }) {
|
||||
host.innerHTML = `<section class="assistant-workspace" aria-label="DSH 诊断工作区"><header class="aw-header"><button class="btn btn-sm" type="button" data-aw-left aria-label="会话列表" aria-expanded="true"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h16"/></svg></button><a href="#tools" class="btn btn-outline-primary aw-back" aria-label="返回工具"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5m6-6-6 6 6 6"/></svg><span>返回工具</span></a><strong>DSH 助手</strong><span class="aw-model">${esc(settings.model || '模型未配置')}</span><span class="aw-connection" role="status">${settings.runtimePath ? '诊断已配置' : '待配置'}</span><span class="aw-usage">今日 ${usage.calls} / ${usage.limit}</span><button class="btn btn-sm" type="button" data-aw-right aria-label="右侧栏" aria-controls="assistant-context" aria-expanded="true" title="收起右侧栏"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="3"/><path d="M15 3v18"/></svg></button></header><div class="aw-body"><aside class="aw-sidebar" aria-label="个人会话"><div class="aw-sidebar-top"><button class="btn btn-primary w-100" id="assistant-new">新建对话</button><button class="btn w-100" type="button" id="assistant-schedules"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg> 定时任务</button><label class="visually-hidden" for="assistant-search">搜索会话</label><input class="form-control" id="assistant-search" maxlength="100" placeholder="搜索会话标题"><label class="visually-hidden" for="assistant-scope">会话范围</label><select class="form-select" id="assistant-scope"><option value="active">活跃会话</option><option value="archived">已归档</option><option value="deleted">回收站</option></select></div><div id="assistant-conversations" class="aw-conversations"></div><div class="aw-pager"><button class="btn btn-sm" id="assistant-prev" type="button">上一页</button><span id="assistant-page" class="small"></span><button class="btn btn-sm" id="assistant-next" type="button">下一页</button></div><div id="assistant-search-note" class="small text-secondary px-3 pb-2"></div></aside><div class="aw-drag aw-drag-left" role="separator" tabindex="0" aria-label="调整会话栏宽度" aria-orientation="vertical"></div><main class="assistant-chat aw-chat"><div class="aw-chat-header"><h2 id="assistant-title">新对话</h2><div id="assistant-lifecycle" class="btn-list"></div></div><div class="small text-secondary px-3" id="assistant-history-note"></div><div id="assistant-messages" class="assistant-messages" role="log" aria-live="polite"></div><button id="assistant-new-progress" class="aw-scroll-latest" type="button" aria-label="滚动到底部" title="滚动到底部" hidden><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14m-6-6 6 6 6-6"/></svg></button><footer class="aw-composer"><div id="assistant-suggestions" class="aw-suggestions">${[
|
||||
['连接健康', 'status'],
|
||||
['扫描异常', 'bpm'],
|
||||
['归档失败', 'archive'],
|
||||
['通知阻断', 'blockers'],
|
||||
]
|
||||
.map(
|
||||
([label, command]) =>
|
||||
`<button class="btn btn-sm" type="button" data-diagnostic-start="${command}">${label}</button>`,
|
||||
)
|
||||
.join(
|
||||
'',
|
||||
)}</div><form id="assistant-compose"><label class="visually-hidden" for="assistant-input">发送给 DSH</label><div class="aw-input-wrap"><textarea id="assistant-input" class="form-control" rows="2" maxlength="4000" placeholder="描述运行异常,或输入 / 选择诊断命令"></textarea><div id="assistant-command-menu" class="aw-command-menu" hidden></div></div><div id="assistant-attachment-list" class="aw-attachments" aria-live="polite"></div><p id="assistant-attachment-note" class="small text-secondary" hidden>附件在本机解析并暂存,点击发送才交给当前模型。最多 3 个、每个 2 MB、合计 40000 字;敏感凭据会脱敏。PDF 仅提取文字,扫描图片需先 OCR。</p><input id="assistant-files" type="file" accept=".txt,.log,.csv,.md,.json,.yaml,.yml,.xml,.ini,.conf,.js,.ts,.cjs,.mjs,.py,.css,.html,.pdf" multiple hidden><div class="aw-compose-tools"><button class="btn btn-sm aw-attach-button" type="button" id="assistant-attach" aria-label="添加附件" title="添加文件或图片"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg></button><button class="btn btn-sm" type="button" id="assistant-commands" aria-label="诊断命令">/</button><button class="aw-submit-icon aw-stop-icon" type="button" id="assistant-stop" aria-label="停止回复" title="停止回复" hidden><svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2" fill="currentColor"/></svg></button><button class="aw-submit-icon" type="submit" id="assistant-send" aria-label="发送" title="发送" disabled><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5m-6 6 6-6 6 6"/></svg></button></div><div class="aw-shortcut-note" aria-hidden="true">Enter 发送 · Shift + Enter 换行</div><div id="assistant-send-hint" class="small text-warning mt-2" role="status"></div><div id="assistant-error" class="small text-danger" role="alert"></div></form></footer></main><div class="aw-drag aw-drag-right" role="separator" tabindex="0" aria-label="调整上下文栏宽度" aria-orientation="vertical"></div><aside class="aw-context" id="assistant-context" aria-label="诊断详情"><div class="aw-context-header"><div class="aw-context-tabs" role="tablist">${[
|
||||
['overview', '概况'],
|
||||
['evidence', '证据'],
|
||||
['actions', '操作'],
|
||||
['events', '记录'],
|
||||
['schedules', '任务'],
|
||||
]
|
||||
.map(
|
||||
([id, label]) =>
|
||||
`<button type="button" role="tab" id="aw-tab-${id}" aria-controls="aw-panel-${id}" aria-selected="${id === 'overview'}" data-context-tab="${id}">${label}</button>`,
|
||||
)
|
||||
.join(
|
||||
'',
|
||||
)}</div><button type="button" class="aw-context-close" data-aw-close-right aria-label="收起右侧栏" title="收起右侧栏"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6M20 4v16"/></svg></button></div>${['overview', 'evidence', 'actions', 'events', 'schedules'].map((id) => `<section id="aw-panel-${id}" role="tabpanel" aria-labelledby="aw-tab-${id}" ${id === 'overview' ? '' : 'hidden'}></section>`).join('')}</aside></div></section>`;
|
||||
const root = host.querySelector('.assistant-workspace'),
|
||||
body = root.querySelector('.aw-body'),
|
||||
leftButton = root.querySelector('[data-aw-left]'),
|
||||
rightButton = root.querySelector('[data-aw-right]'),
|
||||
closeButton = root.querySelector('[data-aw-close-right]');
|
||||
let width = 0,
|
||||
leftOpen = true,
|
||||
rightOpen = true,
|
||||
leftWidth = 264,
|
||||
rightWidth = 320,
|
||||
lastWidth = 0;
|
||||
const shell = document.querySelector('#app>.page');
|
||||
shell?.classList.add('dsh-focused');
|
||||
function measure() {
|
||||
root.style.height =
|
||||
Math.max(
|
||||
240,
|
||||
(window.visualViewport?.height || innerHeight) - root.getBoundingClientRect().top,
|
||||
) + 'px';
|
||||
width = root.clientWidth;
|
||||
if (width !== lastWidth) {
|
||||
if (width < 880) {
|
||||
leftOpen = false;
|
||||
rightOpen = false;
|
||||
} else if (width < 1180) {
|
||||
leftOpen = false;
|
||||
rightOpen = false;
|
||||
} else if (!lastWidth) {
|
||||
leftOpen = true;
|
||||
rightOpen = true;
|
||||
}
|
||||
lastWidth = width;
|
||||
}
|
||||
apply();
|
||||
}
|
||||
function apply() {
|
||||
const narrow = width < 880;
|
||||
const columns = window.AssistantNative.computeColumns(
|
||||
width,
|
||||
leftOpen ? leftWidth : 0,
|
||||
rightOpen ? rightWidth : 0,
|
||||
narrow ? 0 : 56,
|
||||
);
|
||||
if (!narrow && rightOpen && columns.rightbar === 0) rightOpen = false;
|
||||
root.classList.toggle('aw-narrow', narrow);
|
||||
root.classList.toggle('aw-left-open', leftOpen);
|
||||
root.classList.toggle('aw-right-open', rightOpen);
|
||||
root.classList.toggle('aw-left-collapsed', !leftOpen);
|
||||
leftButton.setAttribute('aria-expanded', String(leftOpen));
|
||||
rightButton.setAttribute('aria-expanded', String(rightOpen));
|
||||
rightButton.title = rightOpen ? '收起右侧栏' : '展开右侧栏';
|
||||
body.style.gridTemplateColumns = narrow
|
||||
? 'minmax(0,1fr)'
|
||||
: `${columns.sidebar}px ${leftOpen ? '5px' : '0px'} minmax(0,1fr) ${rightOpen ? '5px ' + columns.rightbar + 'px' : '0px 0px'}`;
|
||||
root.querySelector('.aw-sidebar').inert = !leftOpen;
|
||||
root.querySelector('.aw-context').inert = !rightOpen;
|
||||
}
|
||||
function closeRight() {
|
||||
rightOpen = false;
|
||||
apply();
|
||||
rightButton.focus();
|
||||
}
|
||||
closeButton.onclick = closeRight;
|
||||
leftButton.onclick = () => {
|
||||
leftOpen = !leftOpen;
|
||||
if (width < 880 && leftOpen) rightOpen = false;
|
||||
apply();
|
||||
if (leftOpen) root.querySelector('#assistant-search').focus();
|
||||
};
|
||||
rightButton.onclick = () => {
|
||||
rightOpen = !rightOpen;
|
||||
if (width < 1180 && rightOpen) leftOpen = false;
|
||||
apply();
|
||||
if (rightOpen) root.querySelector('[data-context-tab][aria-selected=true]').focus();
|
||||
};
|
||||
const onKey = (event) => {
|
||||
if (
|
||||
event.key === 'Escape' &&
|
||||
!root.querySelector('dialog[open]') &&
|
||||
root.querySelector('#assistant-command-menu').hidden
|
||||
) {
|
||||
if (width < 880 && leftOpen) {
|
||||
leftOpen = false;
|
||||
apply();
|
||||
leftButton.focus();
|
||||
} else if (rightOpen) {
|
||||
rightOpen = false;
|
||||
apply();
|
||||
rightButton.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
root.addEventListener('keydown', onKey);
|
||||
const disposers = [];
|
||||
for (const [side, selector] of [
|
||||
['left', '.aw-drag-left'],
|
||||
['right', '.aw-drag-right'],
|
||||
]) {
|
||||
const bar = root.querySelector(selector);
|
||||
let drag = null;
|
||||
const move = (event) => {
|
||||
if (!drag) return;
|
||||
if (side === 'left')
|
||||
leftWidth = window.AssistantNative.clampWidth(
|
||||
drag.value + event.clientX - drag.x,
|
||||
264,
|
||||
420,
|
||||
);
|
||||
else
|
||||
rightWidth = window.AssistantNative.clampWidth(
|
||||
drag.value - event.clientX + drag.x,
|
||||
300,
|
||||
width * 0.7,
|
||||
);
|
||||
apply();
|
||||
};
|
||||
bar.onpointerdown = (event) => {
|
||||
drag = { x: event.clientX, value: side === 'left' ? leftWidth : rightWidth };
|
||||
bar.setPointerCapture(event.pointerId);
|
||||
};
|
||||
bar.onpointermove = move;
|
||||
bar.onpointerup = bar.onpointercancel = () => {
|
||||
drag = null;
|
||||
};
|
||||
bar.onkeydown = (event) => {
|
||||
if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const delta = event.key === 'ArrowRight' ? 16 : -16;
|
||||
if (side === 'left')
|
||||
leftWidth = window.AssistantNative.clampWidth(leftWidth + delta, 264, 420);
|
||||
else rightWidth = window.AssistantNative.clampWidth(rightWidth - delta, 300, width * 0.7);
|
||||
apply();
|
||||
};
|
||||
disposers.push(() => {
|
||||
bar.onpointerdown =
|
||||
bar.onpointermove =
|
||||
bar.onpointerup =
|
||||
bar.onpointercancel =
|
||||
bar.onkeydown =
|
||||
null;
|
||||
});
|
||||
}
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(root);
|
||||
window.visualViewport?.addEventListener('resize', measure);
|
||||
measure();
|
||||
return {
|
||||
root,
|
||||
showRight() {
|
||||
rightOpen = true;
|
||||
if (width < 1180) leftOpen = false;
|
||||
apply();
|
||||
},
|
||||
closeLeft() {
|
||||
if (width < 880) {
|
||||
leftOpen = false;
|
||||
apply();
|
||||
}
|
||||
},
|
||||
closeRight,
|
||||
dispose() {
|
||||
closeButton.onclick = null;
|
||||
observer.disconnect();
|
||||
window.visualViewport?.removeEventListener('resize', measure);
|
||||
for (const dispose of disposers) dispose();
|
||||
root.removeEventListener('keydown', onKey);
|
||||
shell?.classList.remove('dsh-focused');
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,18 +1,219 @@
|
||||
'use strict';
|
||||
window.AssistantModelPicker={mount(root,{api,isActive,getConversation,onSelect,onError}){
|
||||
const host=root.querySelector('.aw-compose-tools'),button=document.createElement('button');button.type='button';button.id='assistant-model-picker';button.className='btn btn-sm aw-model-picker';button.setAttribute('aria-haspopup','listbox');button.textContent='请选择模型';host.querySelector('#assistant-commands').after(button);const popup=document.createElement('div');popup.className='aw-model-popup';popup.hidden=true;host.append(popup);let data={providers:[],defaultSelection:null},conversation=null,disposed=false,generation=0,loaded=false,lastRefreshAt=0,refreshPromise=null;
|
||||
const alive=()=>!disposed&&isActive();
|
||||
function available(){return data.providers.filter(p=>p.enabled!==false&&p.hasApiKey!==false).flatMap(p=>p.models.map(m=>({provider:p,model:m})));}
|
||||
function selected(){return conversation?.modelSelection||data.defaultSelection;}
|
||||
function current(){const choice=selected();return available().find(row=>row.provider.id===choice?.providerId&&row.model.id===choice?.modelId);}
|
||||
function label(){const row=current();const text=row?row.provider.name+' / '+(row.model.name||row.model.id):'请选择模型';button.textContent=text;button.setAttribute('aria-label','选择模型:'+text);button.disabled=!!conversation?.archived||!!conversation?.deletedAt;const header=root.querySelector('.aw-model');if(header)header.textContent=row?(row.model.name||row.model.id):'模型未选择';}
|
||||
function close(){generation++;popup.hidden=true;popup.replaceChildren();button.setAttribute('aria-expanded','false');}
|
||||
async function refresh({force=false}={}){const now=Date.now();if(!force&&loaded&&now-lastRefreshAt<30000)return data;if(refreshPromise&&!force)return refreshPromise;const work=(async()=>{const next=await api('/assistant/providers');if(!alive())return;data=next;loaded=true;lastRefreshAt=Date.now();label();return next;})();refreshPromise=work;try{return await work;}finally{if(refreshPromise===work)refreshPromise=null;}}
|
||||
async function open(){const at=++generation;try{await refresh();if(!alive()||generation!==at)return;popup.hidden=false;button.setAttribute('aria-expanded','true');popup.innerHTML='<label class="visually-hidden" for="assistant-model-search">搜索模型</label><input id="assistant-model-search" class="form-control" placeholder="搜索供应商或模型"><div class="aw-model-options" role="listbox" aria-label="可用模型"></div>';const search=popup.querySelector('input'),options=popup.querySelector('[role=listbox]');let index=0,rows=[];
|
||||
function draw(){const query=search.value.trim().toLowerCase();rows=available().filter(row=>(row.provider.name+' '+row.model.name+' '+row.model.id).toLowerCase().includes(query));options.replaceChildren();let previous=null;for(const [i,row]of rows.entries()){if(previous!==row.provider.id){const heading=document.createElement('div');heading.className='small text-secondary px-2 py-1';heading.textContent=row.provider.name;options.append(heading);previous=row.provider.id;}const item=document.createElement('button');item.type='button';item.className='aw-model-option';item.role='option';item.setAttribute('aria-label',row.model.name||row.model.id);item.setAttribute('aria-selected',String(i===index));item.textContent=(row.model.name||row.model.id)+(selected()?.providerId===row.provider.id&&selected()?.modelId===row.model.id?' ✓':'');item.title=row.model.id;item.onclick=()=>choose(row);options.append(item);}if(!rows.length){options.innerHTML='<p class="small text-secondary p-2">暂无匹配的可用模型。</p><a class="btn btn-sm" href="#assistant-settings">前往助手设置</a>';}}
|
||||
async function choose(row){if(!alive()||generation!==at)return;const buttons=[...options.querySelectorAll('button')];buttons.forEach(b=>b.disabled=true);try{await onSelect({providerId:row.provider.id,modelId:row.model.id});if(alive()&&generation===at){conversation=getConversation();label();close();button.focus();}}catch(error){if(alive()&&generation===at){onError(error);buttons.forEach(b=>b.disabled=false);}}}
|
||||
search.oninput=()=>{index=0;draw();};search.onkeydown=event=>{if(event.isComposing)return;if(event.key==='Escape'){event.preventDefault();event.stopPropagation();close();button.focus();}else if(['ArrowDown','ArrowUp'].includes(event.key)){event.preventDefault();index=(index+(event.key==='ArrowDown'?1:-1)+Math.max(1,rows.length))%Math.max(1,rows.length);draw();}else if(['Enter','Tab'].includes(event.key)&&!event.shiftKey&&rows[index]){event.preventDefault();void choose(rows[index]);}};draw();search.focus();
|
||||
}catch(error){if(alive()&&generation===at)onError(error);}}
|
||||
button.onclick=()=>{if(popup.hidden)void open();else close();};
|
||||
return {refresh,open,close,get usable(){return !!current();},update(c){if(conversation?.id!==c?.id)close();conversation=c;label();},dispose(){disposed=true;close();button.remove();popup.remove();}};
|
||||
}};
|
||||
window.AssistantModelPicker = {
|
||||
mount(root, { api, isActive, getConversation, onSelect, onError, onChange }) {
|
||||
const host = root.querySelector('.aw-compose-tools'),
|
||||
button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.id = 'assistant-model-picker';
|
||||
button.className = 'btn btn-sm aw-model-picker';
|
||||
button.setAttribute('aria-haspopup', 'listbox');
|
||||
button.textContent = '请选择模型';
|
||||
host.querySelector('#assistant-commands').after(button);
|
||||
const popup = document.createElement('div');
|
||||
popup.className = 'aw-model-popup';
|
||||
popup.hidden = true;
|
||||
host.append(popup);
|
||||
let data = { providers: [], defaultSelection: null },
|
||||
conversation = null,
|
||||
disposed = false,
|
||||
generation = 0,
|
||||
loaded = false,
|
||||
lastRefreshAt = 0,
|
||||
refreshPromise = null;
|
||||
const alive = () => !disposed && isActive();
|
||||
function available() {
|
||||
return data.providers
|
||||
.filter((p) => p.enabled !== false && p.hasApiKey !== false)
|
||||
.flatMap((p) => p.models.map((m) => ({ provider: p, model: m })));
|
||||
}
|
||||
function selected() {
|
||||
return conversation?.modelSelection || data.defaultSelection;
|
||||
}
|
||||
function current() {
|
||||
const choice = selected();
|
||||
return available().find(
|
||||
(row) => row.provider.id === choice?.providerId && row.model.id === choice?.modelId,
|
||||
);
|
||||
}
|
||||
function capability(m) {
|
||||
return m?.inputModalities?.includes('image') ? '视觉' : '';
|
||||
}
|
||||
function label() {
|
||||
const row = current();
|
||||
const text = row
|
||||
? row.provider.name + ' / ' + (row.model.name || row.model.id)
|
||||
: '请选择模型';
|
||||
button.textContent = text + (row && capability(row.model) ? ' · 视觉' : '');
|
||||
button.title = row
|
||||
? capability(row.model)
|
||||
? '支持图像输入;PNG、JPEG 按视觉内容发送,PDF 提取文字。'
|
||||
: '文本附件和 PDF 文字可用;图片请选择视觉模型。'
|
||||
: '';
|
||||
button.setAttribute('aria-label', '选择模型:' + button.textContent);
|
||||
button.disabled = !!conversation?.archived || !!conversation?.deletedAt;
|
||||
const header = root.querySelector('.aw-model');
|
||||
if (header) header.textContent = row ? row.model.name || row.model.id : '模型未选择';
|
||||
}
|
||||
function close() {
|
||||
generation++;
|
||||
popup.hidden = true;
|
||||
popup.replaceChildren();
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
function showFailure(error, at) {
|
||||
if (!alive() || generation !== at) return;
|
||||
popup.hidden = false;
|
||||
button.setAttribute('aria-expanded', 'true');
|
||||
popup.innerHTML =
|
||||
'<div class="alert alert-warning mb-2" role="alert"><div>模型目录暂时无法加载。</div><button type="button" class="btn btn-sm btn-outline-primary mt-2" data-model-retry>重试加载模型</button></div>';
|
||||
popup.querySelector('[data-model-retry]').onclick = () => void open();
|
||||
onError(error);
|
||||
}
|
||||
async function refresh({ force = false } = {}) {
|
||||
const now = Date.now();
|
||||
if (!force && loaded && now - lastRefreshAt < 30000) return data;
|
||||
if (refreshPromise && !force) return refreshPromise;
|
||||
const work = (async () => {
|
||||
const next = await api('/assistant/providers');
|
||||
if (!alive()) return;
|
||||
data = next;
|
||||
loaded = true;
|
||||
lastRefreshAt = Date.now();
|
||||
label();
|
||||
onChange?.();
|
||||
return next;
|
||||
})();
|
||||
refreshPromise = work;
|
||||
try {
|
||||
return await work;
|
||||
} finally {
|
||||
if (refreshPromise === work) refreshPromise = null;
|
||||
}
|
||||
}
|
||||
async function open() {
|
||||
const at = ++generation;
|
||||
try {
|
||||
await refresh();
|
||||
if (!alive() || generation !== at) return;
|
||||
popup.hidden = false;
|
||||
button.setAttribute('aria-expanded', 'true');
|
||||
popup.innerHTML =
|
||||
'<label class="visually-hidden" for="assistant-model-search">搜索模型</label><input id="assistant-model-search" class="form-control" placeholder="搜索供应商或模型"><div class="aw-model-options" role="listbox" aria-label="可用模型"></div>';
|
||||
const search = popup.querySelector('input'),
|
||||
options = popup.querySelector('[role=listbox]');
|
||||
let index = 0,
|
||||
rows = [];
|
||||
function draw() {
|
||||
const query = search.value.trim().toLowerCase();
|
||||
rows = available().filter((row) =>
|
||||
(row.provider.name + ' ' + row.model.name + ' ' + row.model.id)
|
||||
.toLowerCase()
|
||||
.includes(query),
|
||||
);
|
||||
options.replaceChildren();
|
||||
let previous = null;
|
||||
for (const [i, row] of rows.entries()) {
|
||||
if (previous !== row.provider.id) {
|
||||
const heading = document.createElement('div');
|
||||
heading.className = 'small text-secondary px-2 py-1';
|
||||
heading.textContent = row.provider.name;
|
||||
options.append(heading);
|
||||
previous = row.provider.id;
|
||||
}
|
||||
const item = document.createElement('button');
|
||||
item.type = 'button';
|
||||
item.className = 'aw-model-option';
|
||||
item.role = 'option';
|
||||
item.setAttribute('aria-label', row.model.name || row.model.id);
|
||||
item.setAttribute('aria-selected', String(i === index));
|
||||
item.textContent =
|
||||
(row.model.name || row.model.id) +
|
||||
(capability(row.model) ? ' · 视觉' : '') +
|
||||
(selected()?.providerId === row.provider.id && selected()?.modelId === row.model.id
|
||||
? ' ✓'
|
||||
: '');
|
||||
item.title = row.model.id;
|
||||
item.onclick = () => choose(row);
|
||||
options.append(item);
|
||||
}
|
||||
if (!rows.length) {
|
||||
options.innerHTML =
|
||||
'<p class="small text-secondary p-2">暂无匹配的可用模型。</p><a class="btn btn-sm" href="#assistant-settings">前往助手设置</a>';
|
||||
}
|
||||
}
|
||||
async function choose(row) {
|
||||
if (!alive() || generation !== at) return;
|
||||
const buttons = [...options.querySelectorAll('button')];
|
||||
buttons.forEach((b) => (b.disabled = true));
|
||||
try {
|
||||
await onSelect({ providerId: row.provider.id, modelId: row.model.id });
|
||||
if (alive() && generation === at) {
|
||||
conversation = getConversation();
|
||||
label();
|
||||
close();
|
||||
button.focus();
|
||||
}
|
||||
} catch (error) {
|
||||
if (alive() && generation === at) {
|
||||
onError(error);
|
||||
buttons.forEach((b) => (b.disabled = false));
|
||||
}
|
||||
}
|
||||
}
|
||||
search.oninput = () => {
|
||||
index = 0;
|
||||
draw();
|
||||
};
|
||||
search.onkeydown = (event) => {
|
||||
if (event.isComposing) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close();
|
||||
button.focus();
|
||||
} else if (['ArrowDown', 'ArrowUp'].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
index =
|
||||
(index + (event.key === 'ArrowDown' ? 1 : -1) + Math.max(1, rows.length)) %
|
||||
Math.max(1, rows.length);
|
||||
draw();
|
||||
} else if (['Enter', 'Tab'].includes(event.key) && !event.shiftKey && rows[index]) {
|
||||
event.preventDefault();
|
||||
void choose(rows[index]);
|
||||
}
|
||||
};
|
||||
draw();
|
||||
search.focus();
|
||||
} catch (error) {
|
||||
showFailure(error, at);
|
||||
}
|
||||
}
|
||||
button.onclick = () => {
|
||||
if (popup.hidden) void open();
|
||||
else close();
|
||||
};
|
||||
return {
|
||||
refresh,
|
||||
open,
|
||||
close,
|
||||
failure: (error) => showFailure(error, generation),
|
||||
get usable() {
|
||||
return !!current();
|
||||
},
|
||||
get supportsVision() {
|
||||
return current()?.model.inputModalities?.includes('image') === true;
|
||||
},
|
||||
update(c) {
|
||||
if (conversation?.id !== c?.id) close();
|
||||
conversation = c;
|
||||
label();
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
close();
|
||||
button.remove();
|
||||
popup.remove();
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,8 +1,136 @@
|
||||
'use strict';
|
||||
window.AssistantOperations={mount(container,{api,esc,formatDate,user,settings,isActive,onRepair}){
|
||||
const stepNames={sample_progress:'逐项采样',context:'读取上下文',model:'模型分析',prepare:'准备工作区',files_written:'写入建议文件',commit:'Git提交',validate:'运行测试',rollback:'恢复基线',review:'提交审查',restart_recovery:'重启核验',execute:'执行受控操作',reject:'请求被拒绝',error:'异常'},statusNames={running:'执行中',success:'已完成',ready_for_review:'测试通过,待审查',rolled_back:'已回退',needs_review:'待人工核验',cancelled:'已取消',error:'失败',rejected:'已拒绝'};
|
||||
const host=document.createElement('section');host.className='card mb-3';const layout=container.querySelector('.assistant-layout');if(layout)layout.before(host);else container.append(host);
|
||||
host.innerHTML='<div class="card-header"><h3 class="card-title">AI 操作记录</h3><button type="button" class="btn btn-sm ms-auto" data-operation-refresh>刷新操作记录</button></div><div class="card-body"><div data-operation-list class="small text-secondary">正在读取操作记录…</div>'+(user.role==='admin'?'<details class="mt-3"><summary>提出代码修复</summary><form data-repair-form class="mt-3"><label class="form-label" for="repair-paths">已跟踪源码文件(相对路径,每行一个)</label><textarea id="repair-paths" class="form-control font-monospace" rows="2" required placeholder="src/modules/example.cjs"></textarea><label class="form-label mt-3" for="repair-goal">修复目标</label><textarea id="repair-goal" class="form-control" rows="2" maxlength="4000" required></textarea><p class="small text-secondary mt-2">仅将选定源码发送给已配置的模型。先生成可审查建议,不直接修改代码;执行时在独立 Git 工作区运行本机测试。工作区不是操作系统沙箱,通过后仍需人工审查合并,不自动部署。</p><button class="btn btn-primary" type="submit" '+(!settings.enabled||!settings.allowActions||!settings.allowCodeRepair?'disabled':'')+'>生成修复建议</button>'+(!settings.allowCodeRepair?'<span class="small text-secondary ms-2">请先在助手设置开启代码修复并指定源码仓库。</span>':'')+'</form></details>':'')+'<div class="text-danger mt-2" data-operation-error role="alert"></div></div>';
|
||||
const error=host.querySelector('[data-operation-error]');let rows=[],busy=false;const more=document.createElement('button');more.type='button';more.className='btn btn-sm mt-2';more.textContent='加载更早记录';more.hidden=true;host.querySelector('[data-operation-list]').after(more);async function refresh(append=false){if(busy)return;busy=true;more.disabled=true;try{const {events}=await api('/assistant/operations'+(append&&rows.length?'?beforeId='+rows.at(-1).id:''));if(!isActive()||!host.isConnected)return;rows=append?[...rows,...events]:events;more.hidden=events.length<100;host.querySelector('[data-operation-list]').innerHTML=rows.length?'<div class="table-responsive"><table class="table table-sm"><thead><tr><th>时间 / 操作编号</th><th>步骤 / 状态</th><th>结果与依据</th></tr></thead><tbody>'+rows.map(e=>'<tr><td>'+esc(formatDate(e.createdAt))+' · '+esc(e.actorLabel||e.actor)+'<div class="font-monospace small">'+esc(e.operationId)+'</div></td><td>'+esc(stepNames[e.step]||e.step)+' / '+esc(statusNames[e.status]||e.status)+'</td><td>'+esc(e.detail||'')+(e.resultCommit?'<div>提交:<code>'+esc(e.resultCommit)+'</code></div>':'')+(e.recovery?'<div>恢复:'+esc(e.recovery)+'</div>':'')+'</td></tr>').join('')+'</tbody></table></div>':'暂无操作记录。诊断和恢复操作均会记录,代码修改另有 Git 提交。';}catch(e){if(isActive())error.textContent=e.message;}finally{busy=false;more.disabled=false;}}
|
||||
host.querySelector('[data-operation-refresh]').onclick=()=>refresh();more.onclick=()=>refresh(true);void refresh();const form=host.querySelector('[data-repair-form]');if(form)form.onsubmit=async e=>{e.preventDefault();const button=e.submitter;button.disabled=true;error.textContent='';try{await onRepair(form.querySelector('#repair-goal').value,form.querySelector('#repair-paths').value.split(/\r?\n/).map(s=>s.trim()).filter(Boolean));if(isActive())await refresh();}catch(cause){if(isActive())error.textContent=cause.message;}finally{if(button.isConnected)button.disabled=false;}};
|
||||
}};
|
||||
window.AssistantOperations = {
|
||||
mount(container, { api, esc, formatDate, user, settings, isActive, onRepair }) {
|
||||
const stepNames = {
|
||||
management_query: '查询受控管理资源',
|
||||
schedule_create: '创建原生定时任务',
|
||||
schedule_update: '修改原生定时任务',
|
||||
schedule_delete: '删除原生定时任务',
|
||||
configuration_review: '审查设置差异与风险',
|
||||
configuration_authorized: '用户授权设置修改',
|
||||
configuration_rejected: '用户拒绝修改',
|
||||
configuration_saved: '保存设置',
|
||||
configuration_result: '核实设置结果',
|
||||
sample_progress: '逐项采样',
|
||||
context: '读取上下文',
|
||||
model: '模型分析',
|
||||
prepare: '准备工作区',
|
||||
files_written: '写入建议文件',
|
||||
commit: 'Git提交',
|
||||
validate: '运行测试',
|
||||
rollback: '恢复基线',
|
||||
review: '提交审查',
|
||||
restart_recovery: '重启核验',
|
||||
execute: '执行受控操作',
|
||||
reject: '请求被拒绝',
|
||||
error: '异常',
|
||||
},
|
||||
statusNames = {
|
||||
reviewed: '已审查,待授权',
|
||||
running: '执行中',
|
||||
success: '已完成',
|
||||
ready_for_review: '测试通过,待审查',
|
||||
rolled_back: '已回退',
|
||||
needs_review: '待人工核验',
|
||||
cancelled: '已取消',
|
||||
error: '失败',
|
||||
rejected: '已拒绝',
|
||||
};
|
||||
const host = document.createElement('section');
|
||||
host.className = 'card mb-3';
|
||||
const layout = container.querySelector('.assistant-layout');
|
||||
if (layout) layout.before(host);
|
||||
else container.append(host);
|
||||
host.innerHTML =
|
||||
'<div class="card-header"><h3 class="card-title">AI 操作记录</h3><button type="button" class="btn btn-sm ms-auto" data-operation-refresh>刷新操作记录</button></div><div class="card-body"><div data-operation-list class="small text-secondary">正在读取操作记录…</div>' +
|
||||
(user.role === 'admin'
|
||||
? '<details class="mt-3"><summary>提出代码修复</summary><form data-repair-form class="mt-3"><label class="form-label" for="repair-paths">已跟踪源码文件(相对路径,每行一个)</label><textarea id="repair-paths" class="form-control font-monospace" rows="2" required placeholder="src/modules/example.cjs"></textarea><label class="form-label mt-3" for="repair-goal">修复目标</label><textarea id="repair-goal" class="form-control" rows="2" maxlength="4000" required></textarea><p class="small text-secondary mt-2">仅将选定源码发送给已配置的模型。先生成可审查建议,不直接修改代码;执行时在独立 Git 工作区运行本机测试。工作区不是操作系统沙箱,通过后仍需人工审查合并,不自动部署。</p><button class="btn btn-primary" type="submit" ' +
|
||||
(!settings.allowActions || !settings.allowCodeRepair ? 'disabled' : '') +
|
||||
'>生成修复建议</button>' +
|
||||
(!settings.allowCodeRepair
|
||||
? '<span class="small text-secondary ms-2">请先在助手设置开启代码修复并指定源码仓库。</span>'
|
||||
: '') +
|
||||
'</form></details>'
|
||||
: '') +
|
||||
'<div class="text-danger mt-2" data-operation-error role="alert"></div></div>';
|
||||
const error = host.querySelector('[data-operation-error]');
|
||||
let rows = [],
|
||||
busy = false;
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
more.className = 'btn btn-sm mt-2';
|
||||
more.textContent = '加载更早记录';
|
||||
more.hidden = true;
|
||||
host.querySelector('[data-operation-list]').after(more);
|
||||
async function refresh(append = false) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
more.disabled = true;
|
||||
try {
|
||||
const { events } = await api(
|
||||
'/assistant/operations' + (append && rows.length ? '?beforeId=' + rows.at(-1).id : ''),
|
||||
);
|
||||
if (!isActive() || !host.isConnected) return;
|
||||
rows = append ? [...rows, ...events] : events;
|
||||
more.hidden = events.length < 100;
|
||||
host.querySelector('[data-operation-list]').innerHTML = rows.length
|
||||
? '<div class="table-responsive"><table class="table table-sm"><thead><tr><th>时间 / 操作编号</th><th>步骤 / 状态</th><th>结果与依据</th></tr></thead><tbody>' +
|
||||
rows
|
||||
.map(
|
||||
(e) =>
|
||||
'<tr><td>' +
|
||||
esc(formatDate(e.createdAt)) +
|
||||
' · ' +
|
||||
esc(e.actorLabel || e.actor) +
|
||||
'<div class="font-monospace small">' +
|
||||
esc(e.operationId) +
|
||||
'</div></td><td>' +
|
||||
esc(stepNames[e.step] || e.step) +
|
||||
' / ' +
|
||||
esc(statusNames[e.status] || e.status) +
|
||||
'</td><td>' +
|
||||
esc(e.detail || '') +
|
||||
(e.resultCommit
|
||||
? '<div>提交:<code>' + esc(e.resultCommit) + '</code></div>'
|
||||
: '') +
|
||||
(e.recovery ? '<div>恢复:' + esc(e.recovery) + '</div>' : '') +
|
||||
'</td></tr>',
|
||||
)
|
||||
.join('') +
|
||||
'</tbody></table></div>'
|
||||
: '暂无操作记录。诊断和恢复操作均会记录,代码修改另有 Git 提交。';
|
||||
} catch (e) {
|
||||
if (isActive()) error.textContent = e.message;
|
||||
} finally {
|
||||
busy = false;
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
host.querySelector('[data-operation-refresh]').onclick = () => refresh();
|
||||
more.onclick = () => refresh(true);
|
||||
void refresh();
|
||||
const form = host.querySelector('[data-repair-form]');
|
||||
if (form)
|
||||
form.onsubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
const button = e.submitter;
|
||||
button.disabled = true;
|
||||
error.textContent = '';
|
||||
try {
|
||||
await onRepair(
|
||||
form.querySelector('#repair-goal').value,
|
||||
form
|
||||
.querySelector('#repair-paths')
|
||||
.value.split(/\r?\n/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
if (isActive()) await refresh();
|
||||
} catch (cause) {
|
||||
if (isActive()) error.textContent = cause.message;
|
||||
} finally {
|
||||
if (button.isConnected) button.disabled = false;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,25 +1,401 @@
|
||||
'use strict';
|
||||
window.AssistantProviderSettings={async render(container,{api,esc,notify,user,formatDate,isActive=()=>true}){
|
||||
const [data,initial]=await Promise.all([api('/assistant'),api('/assistant/providers')]);if(!isActive())return;let directory=initial,editing=null,busy=false,disposed=false,unregisterEditor=null;const live=()=>!disposed&&isActive()&&container.isConnected;
|
||||
container.innerHTML='<div class="settings-width assistant-provider-settings"><section class="card mb-3"><div class="card-header"><h2 class="card-title">模型供应商</h2><a class="btn btn-sm ms-auto" href="#assistant">返回 DSH 助手</a></div><div class="card-body"><div id="provider-list"></div><div id="provider-editor"></div><div id="provider-feedback" class="small mt-3" role="status"></div></div></section><section class="card mb-3"><div class="card-header"><h2 class="card-title">默认模型</h2></div><div class="card-body" id="provider-default-host"></div></section><div id="assistant-runtime-host"></div><div id="assistant-settings-error" class="small text-danger" role="alert"></div></div>';
|
||||
const feedback=(text,error=false)=>{if(live()){const host=container.querySelector('#provider-feedback');host.className='small mt-3 '+(error?'text-danger':'text-success');host.textContent=text;}},failure=e=>feedback(e.message,true);
|
||||
const modelText=models=>(models||[]).map(m=>[m.id,m.name===m.id?'':m.name||'',m.contextWindow||'',m.maxTokens||''].join('|').replace(/\|+$/,'')).join('\n');
|
||||
const parseModels=text=>text.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(line=>{const [id,name,context,max,...extra]=line.split('|').map(s=>s.trim());if(extra.length)throw Error('模型每行最多四项:ID、显示名、上下文、输出上限。');return {id,...(name?{name}:{}),...(context?{contextWindow:Number(context)}:{}),...(max?{maxTokens:Number(max)}:{})};});
|
||||
function defaultForm(reset=false){const host=container.querySelector('#provider-default-host'),prior=reset?null:host.querySelector('select')?.value,available=directory.providers.filter(p=>p.enabled!==false&&p.hasApiKey!==false),current=directory.defaultSelection?JSON.stringify(directory.defaultSelection):'';host.innerHTML='<form id="assistant-default-form"><label class="form-label" for="provider-default">默认模型</label><div class="d-flex flex-wrap gap-2"><select id="provider-default" class="form-select flex-fill"><option value="">请选择可用模型</option>'+available.map(p=>'<optgroup label="'+esc(p.name)+'">'+p.models.map(m=>'<option value="'+esc(JSON.stringify({providerId:p.id,modelId:m.id}))+'">'+esc(p.name+' / '+(m.name||m.id))+'</option>').join('')+'</optgroup>').join('')+'</select>'+(user.role==='admin'?'<button class="btn btn-primary" type="submit">保存默认模型</button>':'')+'</div><p class="form-hint mt-2">新会话默认使用此模型,个人会话可独立选择。供应商或模型移除后需要重新选择。</p></form>';const select=host.querySelector('select');select.value=[...select.options].some(o=>o.value===prior)?prior:current;if(!select.value)select.value='';if(user.role!=='admin')select.disabled=true;host.querySelector('form').onsubmit=async e=>{e.preventDefault();if(!select.value||user.role!=='admin'||busy)return;const button=e.submitter;button.disabled=true;try{directory=await api('/assistant/providers/default',{version:directory.version,...JSON.parse(select.value)});if(live()){defaultForm(true);feedback('默认模型已保存。');}}catch(error){failure(error);}finally{if(button.isConnected)button.disabled=false;}};}
|
||||
async function requestEdit(p){if(busy)return;const action=()=>edit(p);if(window.PageLifecycle?.guard)await window.PageLifecycle.guard(action,{scope:'assistant-provider'});else action();}
|
||||
function draw(){const list=container.querySelector('#provider-list');list.innerHTML=directory.providers.map(p=>`<div class="provider-row" data-provider-row="${esc(p.id)}"><div class="flex-fill"><strong>${esc(p.name)}</strong><div class="small text-secondary">${esc(p.protocol||'已配置模型')} · ${p.models.length} 个模型${user.role==='admin'?' · '+(p.enabled?(p.hasApiKey?'密钥已保存':'待配置密钥'):'已停用'):''}</div></div>${user.role==='admin'?'<button type="button" class="btn btn-sm" data-provider-edit="'+esc(p.id)+'">编辑</button><button type="button" class="btn btn-sm" data-provider-remove="'+esc(p.id)+'">删除</button>':''}</div>`).join('')||'<p class="text-secondary">暂无可用供应商,请管理员添加。</p>';if(user.role==='admin')list.insertAdjacentHTML('beforeend','<button class="btn btn-outline-primary mt-3" type="button" id="provider-add" aria-label="添加供应商">+ 添加供应商</button>');list.querySelectorAll('[data-provider-edit]').forEach(button=>button.onclick=()=>requestEdit(directory.providers.find(p=>p.id===button.dataset.providerEdit)));list.querySelectorAll('[data-provider-remove]').forEach(button=>button.onclick=()=>remove(directory.providers.find(p=>p.id===button.dataset.providerRemove)));list.querySelector('#provider-add')?.addEventListener('click',()=>requestEdit(null));defaultForm();}
|
||||
async function remove(p){if(busy)return;if(window.PageLifecycle?.guard&&!await window.PageLifecycle.guard(()=>{unregisterEditor?.();editing=null;container.querySelector('#provider-editor').replaceChildren();},{scope:'assistant-provider'}))return;const dialog=document.createElement('dialog');dialog.className='page-leave-dialog';dialog.setAttribute('aria-label','删除供应商');dialog.innerHTML='<h3>删除供应商</h3><p>'+esc(p.name)+' 将从可选模型中移除。已有对话和审计保留,关联模型需要重新选择。</p><div class="btn-list"><button class="btn" type="button">取消</button><button class="btn btn-danger" type="button">确认删除供应商</button></div>';container.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();if(!answer||!live())return;busy=true;try{directory=await api('/assistant/providers/'+p.id+'/delete',{version:p.version});if(live()){editing=null;container.querySelector('#provider-editor').replaceChildren();draw();feedback('供应商已删除。');}}catch(error){failure(error);}finally{busy=false;}}
|
||||
function edit(p){if(busy)return;unregisterEditor?.();editing=p?.id||'new';const presets=directory.catalog?.presets||[],preset=p||presets.find(p=>p.id==='deepseek')||{preset:'custom',protocol:'openai-completions',apiBase:'',models:[]},host=container.querySelector('#provider-editor');host.innerHTML=`<form id="provider-edit-form" class="provider-editor mt-3"><h3>${p?'编辑供应商':'添加供应商'}</h3><div class="row g-3"><div class="col-md-6"><label class="form-label" for="provider-preset">供应商类型</label><select id="provider-preset" class="form-select">${presets.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.name)+'</option>').join('')}</select></div><div class="col-md-6"><label class="form-label" for="provider-name">供应商名称</label><input id="provider-name" class="form-control" maxlength="200" required value="${esc(p?.name||preset.name||'')}"></div><div class="col-md-6"><label class="form-label" for="provider-protocol">API 协议</label><select id="provider-protocol" class="form-select"><option value="openai-completions">OpenAI Chat Completions</option><option value="openai-responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></div><div class="col-md-6"><label class="form-label" for="provider-base">API 根地址</label><input id="provider-base" class="form-control" maxlength="1000" required value="${esc(p?.apiBase||preset.apiBase||'')}"></div><div class="col-12"><label class="form-label" for="provider-key">API 密钥</label><input id="provider-key" class="form-control" type="password" autocomplete="new-password" maxlength="4096" placeholder="${p?.hasApiKey?'已保存;留空保留,更换协议或地址需重填':'输入此供应商的 API Key'}"><div class="form-hint">仅保存到加密存储,页面不会读回已保存的密钥。</div></div><div class="col-12"><label class="form-label" for="provider-models">模型列表</label><textarea id="provider-models" class="form-control font-monospace" rows="5">${esc(modelText(p?.models||preset.models))}</textarea><div class="form-hint">每行:模型 ID | 显示名 | 上下文窗口 | 最大输出;后 3 项可省略。获取模型后先检查草稿,再保存。</div></div><div class="col-12"><label class="form-check"><input id="provider-enabled" class="form-check-input" type="checkbox" ${p?.enabled===false?'':'checked'}><span class="form-check-label">启用此供应商</span></label></div></div><div class="btn-list mt-3"><button class="btn" type="button" id="provider-cancel" data-lifecycle-approved="1">取消</button><button class="btn" type="button" id="provider-discover" ${p?'':'disabled'}>获取模型</button><button class="btn btn-primary ms-auto" type="submit">保存供应商</button></div><div id="provider-editor-feedback" class="small mt-2" role="alert"></div></form>`;
|
||||
const form=host.querySelector('form'),get=id=>form.querySelector('#provider-'+id),message=(text,error=false)=>{if(live()&&form.isConnected){get('editor-feedback').className='small mt-2 '+(error?'text-danger':'text-success');get('editor-feedback').textContent=text;}};get('preset').value=p?.preset||preset.id||'custom';get('protocol').value=p?.protocol||preset.protocol;form.dataset.lifecycle='custom';const snapshot=()=>JSON.stringify([...form.querySelectorAll('input,select,textarea')].map(e=>e.type==='checkbox'?e.checked:e.value)),baseline=snapshot();unregisterEditor=window.PageLifecycle?.register({scope:'assistant-provider',sensitive:true,dirty:()=>form.isConnected&&snapshot()!==baseline});
|
||||
function lockFields(){const fields=[...form.querySelectorAll('input,select,textarea,button')].map(field=>({field,disabled:field.disabled}));for(const {field}of fields)field.disabled=true;return()=>{if(form.isConnected)for(const {field,disabled}of fields)field.disabled=disabled;};}
|
||||
get('preset').onchange=()=>{const selected=presets.find(x=>x.id===get('preset').value);if(!selected)return;get('name').value=selected.name;get('protocol').value=selected.protocol;get('base').value=selected.apiBase||'';get('models').value=modelText(selected.models);};
|
||||
get('cancel').onclick=()=>{const cancel=()=>{unregisterEditor?.();editing=null;host.replaceChildren();};if(window.PageLifecycle?.guard)void window.PageLifecycle.guard(cancel,{scope:'assistant-provider'});else cancel();};
|
||||
get('discover').onclick=async()=>{if(!p||busy)return;if(get('base').value.replace(/\/+$/,'')!==p.apiBase.replace(/\/+$/,'')||get('protocol').value!==p.protocol||get('key').value){message('请先保存新的协议、地址或密钥,再获取模型。',true);return;}busy=true;const unlock=lockFields();try{const result=await api('/assistant/providers/'+p.id+'/models',{version:p.version}, {managedOutcome:true});if(live()&&editing===p.id&&form.isConnected){get('models').value=modelText(result.models);message('模型目录已填入草稿,请检查后保存。');}}catch(error){message(error.message,true);}finally{busy=false;unlock();}};
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy)return;busy=true;const button=event.submitter;let unlock=()=>{};try{const body={...(p?{id:p.id}:{}),version:p?.version||0,name:get('name').value,preset:get('preset').value,protocol:get('protocol').value,apiBase:get('base').value,apiKey:get('key').value,enabled:get('enabled').checked,models:parseModels(get('models').value)};unlock=lockFields();const result=await api('/assistant/providers',body);if(!live())return;directory=result;editing=null;unregisterEditor?.();get('key').value='';host.replaceChildren();draw();feedback('供应商已保存。');}catch(error){message(error.message,true);}finally{busy=false;unlock();}};
|
||||
}
|
||||
function runtimeForm(){const host=container.querySelector('#assistant-runtime-host');if(user.role!=='admin'){host.innerHTML='<p class="text-secondary">供应商与运行权限由管理员维护。</p>';return;}const s=data.settings;host.innerHTML=`<section class="card mb-3"><div class="card-header"><h2 class="card-title">运行与权限</h2></div><form id="assistant-settings-form"><div class="card-body"><label class="form-label" for="assistant-runtime">官方 CLI 运行包路径</label><input id="assistant-runtime" class="form-control" value="${esc(s.runtimePath)}" maxlength="1000"><div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label" for="assistant-timeout">回复超时(秒)</label><input id="assistant-timeout" class="form-control" type="number" min="15" max="180" value="${s.timeoutSeconds}"></div><div class="col-md-6"><label class="form-label" for="assistant-limit">每日对话轮次上限</label><input id="assistant-limit" class="form-control" type="number" min="1" max="1000" value="${s.dailyLimit}"></div></div><label class="form-check mt-3"><input id="assistant-enabled" class="form-check-input" type="checkbox" ${s.enabled?'checked':''}><span class="form-check-label">启用 DSH 对话诊断</span></label><label class="form-check mt-2"><input id="assistant-allow-actions" class="form-check-input" type="checkbox" ${s.allowActions?'checked':''}><span class="form-check-label">开放固定操作卡片(仍按工作台权限执行)</span></label><details class="mt-3"><summary>管理员隔离代码修复</summary><label class="form-check mt-2"><input id="assistant-code-repair" class="form-check-input" type="checkbox" ${s.allowCodeRepair?'checked':''}><span class="form-check-label">允许管理员提出并审查隔离代码修复</span></label><label class="form-label mt-2" for="assistant-repository">源码 Git 仓库路径</label><input id="assistant-repository" class="form-control" maxlength="1000" value="${esc(s.repairRepository||'')}"><div class="form-hint">固定测试通过后仍待人工审查,不自动合并部署。</div></details><div id="assistant-runtime-status" class="small mt-3" role="status"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="assistant-check">检查运行包</button><button class="btn btn-primary ms-auto" type="submit">保存助手设置</button></div></form></section>`;
|
||||
const get=id=>host.querySelector('#assistant-'+id);get('check').onclick=async()=>{get('check').disabled=true;try{const checked=await api('/assistant/check',{});if(live())get('runtime-status').textContent=checked.message+(checked.modelConfigured?' 默认模型配置完整,实际调用时验证。':' 请先添加供应商并选择可用默认模型。');}catch(error){if(live())get('runtime-status').textContent=error.message;}finally{if(live())get('check').disabled=false;}};
|
||||
host.querySelector('form').onsubmit=async event=>{event.preventDefault();const button=event.submitter;button.disabled=true;try{const saved=await api('/assistant/settings',{version:data.settings.version,runtimePath:get('runtime').value,timeoutSeconds:Number(get('timeout').value),dailyLimit:Number(get('limit').value),enabled:get('enabled').checked,allowActions:get('allow-actions').checked,allowCodeRepair:get('code-repair').checked,repairRepository:get('repository').value});if(!live())return;data.settings=saved;await window.PageLifecycle.afterSave(async()=>{const fresh=await api('/assistant');if(live())data.settings=fresh.settings;},'助手设置已保存。',feedback,live);}catch(error){if(live())container.querySelector('#assistant-settings-error').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}};
|
||||
}
|
||||
draw();runtimeForm();window.PageLifecycle?.onDispose(()=>{disposed=true;unregisterEditor?.();container.querySelectorAll('dialog').forEach(d=>{d.close();d.remove();});});
|
||||
}};
|
||||
window.AssistantProviderSettings = {
|
||||
async render(container, { api, esc, notify, user, formatDate, isActive = () => true }) {
|
||||
const [data, initial] = await Promise.all([api('/assistant'), api('/assistant/providers')]);
|
||||
if (!isActive()) return;
|
||||
let directory = initial,
|
||||
editing = null,
|
||||
busy = false,
|
||||
disposed = false,
|
||||
unregisterEditor = null;
|
||||
const live = () => !disposed && isActive() && container.isConnected;
|
||||
container.innerHTML =
|
||||
'<div class="settings-width assistant-provider-settings"><section class="card mb-3"><div class="card-header"><h2 class="card-title">模型供应商</h2><a class="btn btn-sm ms-auto" href="#assistant">返回 DSH 助手</a></div><div class="card-body"><div id="provider-list"></div><div id="provider-editor"></div><div id="provider-feedback" class="small mt-3" role="status"></div></div></section><section class="card mb-3"><div class="card-header"><h2 class="card-title">默认模型</h2></div><div class="card-body" id="provider-default-host"></div></section><div id="assistant-runtime-host"></div><div id="assistant-settings-error" class="small text-danger" role="alert"></div></div>';
|
||||
const feedback = (text, error = false) => {
|
||||
if (live()) {
|
||||
const host = container.querySelector('#provider-feedback');
|
||||
host.className = 'small mt-3 ' + (error ? 'text-danger' : 'text-success');
|
||||
host.textContent = text;
|
||||
}
|
||||
},
|
||||
failure = (e) => feedback(e.message, true);
|
||||
const modelText = (models) =>
|
||||
(models || [])
|
||||
.map((m) =>
|
||||
[
|
||||
m.id,
|
||||
m.name === m.id ? '' : m.name || '',
|
||||
m.contextWindow || '',
|
||||
m.maxTokens || '',
|
||||
m.inputModalities?.join(',') || '',
|
||||
]
|
||||
.join('|')
|
||||
.replace(/\|+$/, ''),
|
||||
)
|
||||
.join('\n');
|
||||
const parseModels = (text) =>
|
||||
text
|
||||
.split(/\r?\n/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const [id, name, context, max, modalities, ...extra] = line
|
||||
.split('|')
|
||||
.map((s) => s.trim());
|
||||
if (extra.length)
|
||||
throw Error('模型每行最多五项:ID、显示名、上下文、输出上限、输入能力。');
|
||||
return {
|
||||
id,
|
||||
...(name ? { name } : {}),
|
||||
...(context ? { contextWindow: Number(context) } : {}),
|
||||
...(max ? { maxTokens: Number(max) } : {}),
|
||||
...(modalities ? { inputModalities: modalities.split(',').map((x) => x.trim()) } : {}),
|
||||
};
|
||||
});
|
||||
function defaultForm(reset = false) {
|
||||
const host = container.querySelector('#provider-default-host'),
|
||||
prior = reset ? null : host.querySelector('select')?.value,
|
||||
available = directory.providers.filter((p) => p.enabled !== false && p.hasApiKey !== false),
|
||||
current = directory.defaultSelection ? JSON.stringify(directory.defaultSelection) : '';
|
||||
host.innerHTML =
|
||||
'<form id="assistant-default-form"><label class="form-label" for="provider-default">默认模型</label><div class="d-flex flex-wrap gap-2"><select id="provider-default" class="form-select flex-fill"><option value="">请选择可用模型</option>' +
|
||||
available
|
||||
.map(
|
||||
(p) =>
|
||||
'<optgroup label="' +
|
||||
esc(p.name) +
|
||||
'">' +
|
||||
p.models
|
||||
.map(
|
||||
(m) =>
|
||||
'<option value="' +
|
||||
esc(JSON.stringify({ providerId: p.id, modelId: m.id })) +
|
||||
'">' +
|
||||
esc(p.name + ' / ' + (m.name || m.id)) +
|
||||
'</option>',
|
||||
)
|
||||
.join('') +
|
||||
'</optgroup>',
|
||||
)
|
||||
.join('') +
|
||||
'</select>' +
|
||||
(user.role === 'admin'
|
||||
? '<button class="btn btn-primary" type="submit">保存默认模型</button>'
|
||||
: '') +
|
||||
'</div><p class="form-hint mt-2">新会话默认使用此模型,个人会话可独立选择。供应商或模型移除后需要重新选择。</p></form>';
|
||||
const select = host.querySelector('select');
|
||||
select.value = [...select.options].some((o) => o.value === prior) ? prior : current;
|
||||
if (!select.value) select.value = '';
|
||||
if (user.role !== 'admin') select.disabled = true;
|
||||
host.querySelector('form').onsubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!select.value || user.role !== 'admin' || busy) return;
|
||||
const button = e.submitter;
|
||||
button.disabled = true;
|
||||
try {
|
||||
directory = await api('/assistant/providers/default', {
|
||||
version: directory.version,
|
||||
...JSON.parse(select.value),
|
||||
});
|
||||
if (live()) {
|
||||
defaultForm(true);
|
||||
feedback('默认模型已保存。');
|
||||
}
|
||||
} catch (error) {
|
||||
failure(error);
|
||||
} finally {
|
||||
if (button.isConnected) button.disabled = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
async function requestEdit(p) {
|
||||
if (busy) return;
|
||||
const action = () => edit(p);
|
||||
if (window.PageLifecycle?.guard)
|
||||
await window.PageLifecycle.guard(action, { scope: 'assistant-provider' });
|
||||
else action();
|
||||
}
|
||||
function draw() {
|
||||
const list = container.querySelector('#provider-list');
|
||||
list.innerHTML =
|
||||
directory.providers
|
||||
.map(
|
||||
(p) =>
|
||||
`<div class="provider-row" data-provider-row="${esc(p.id)}"><div class="flex-fill"><strong>${esc(p.name)}</strong><div class="small text-secondary">${esc(p.protocol || '已配置模型')} · ${p.models.length} 个模型${user.role === 'admin' ? ' · ' + (p.enabled ? (p.hasApiKey ? '密钥已保存' : '待配置密钥') : '已停用') : ''}</div></div>${user.role === 'admin' ? '<button type="button" class="btn btn-sm" data-provider-edit="' + esc(p.id) + '">编辑</button><button type="button" class="btn btn-sm" data-provider-remove="' + esc(p.id) + '">删除</button>' : ''}</div>`,
|
||||
)
|
||||
.join('') || '<p class="text-secondary">暂无可用供应商,请管理员添加。</p>';
|
||||
if (user.role === 'admin')
|
||||
list.insertAdjacentHTML(
|
||||
'beforeend',
|
||||
'<button class="btn btn-outline-primary mt-3" type="button" id="provider-add" aria-label="添加供应商">+ 添加供应商</button>',
|
||||
);
|
||||
list
|
||||
.querySelectorAll('[data-provider-edit]')
|
||||
.forEach(
|
||||
(button) =>
|
||||
(button.onclick = () =>
|
||||
requestEdit(directory.providers.find((p) => p.id === button.dataset.providerEdit))),
|
||||
);
|
||||
list
|
||||
.querySelectorAll('[data-provider-remove]')
|
||||
.forEach(
|
||||
(button) =>
|
||||
(button.onclick = () =>
|
||||
remove(directory.providers.find((p) => p.id === button.dataset.providerRemove))),
|
||||
);
|
||||
list.querySelector('#provider-add')?.addEventListener('click', () => requestEdit(null));
|
||||
defaultForm();
|
||||
}
|
||||
async function remove(p) {
|
||||
if (busy) return;
|
||||
if (
|
||||
window.PageLifecycle?.guard &&
|
||||
!(await window.PageLifecycle.guard(
|
||||
() => {
|
||||
unregisterEditor?.();
|
||||
editing = null;
|
||||
container.querySelector('#provider-editor').replaceChildren();
|
||||
},
|
||||
{ scope: 'assistant-provider' },
|
||||
))
|
||||
)
|
||||
return;
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.className = 'page-leave-dialog';
|
||||
dialog.setAttribute('aria-label', '删除供应商');
|
||||
dialog.innerHTML =
|
||||
'<h3>删除供应商</h3><p>' +
|
||||
esc(p.name) +
|
||||
' 将从可选模型中移除。已有对话和审计保留,关联模型需要重新选择。</p><div class="btn-list"><button class="btn" type="button">取消</button><button class="btn btn-danger" type="button">确认删除供应商</button></div>';
|
||||
container.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();
|
||||
if (!answer || !live()) return;
|
||||
busy = true;
|
||||
try {
|
||||
directory = await api('/assistant/providers/' + p.id + '/delete', { version: p.version });
|
||||
if (live()) {
|
||||
editing = null;
|
||||
container.querySelector('#provider-editor').replaceChildren();
|
||||
draw();
|
||||
feedback('供应商已删除。');
|
||||
}
|
||||
} catch (error) {
|
||||
failure(error);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
function edit(p) {
|
||||
if (busy) return;
|
||||
unregisterEditor?.();
|
||||
editing = p?.id || 'new';
|
||||
const presets = directory.catalog?.presets || [],
|
||||
preset = p ||
|
||||
presets.find((p) => p.id === 'deepseek') || {
|
||||
preset: 'custom',
|
||||
protocol: 'openai-completions',
|
||||
apiBase: '',
|
||||
models: [],
|
||||
},
|
||||
host = container.querySelector('#provider-editor');
|
||||
host.innerHTML = `<form id="provider-edit-form" class="provider-editor mt-3"><h3>${p ? '编辑供应商' : '添加供应商'}</h3><div class="row g-3"><div class="col-md-6"><label class="form-label" for="provider-preset">供应商类型</label><select id="provider-preset" class="form-select">${presets.map((x) => '<option value="' + esc(x.id) + '">' + esc(x.name) + '</option>').join('')}</select></div><div class="col-md-6"><label class="form-label" for="provider-name">供应商名称</label><input id="provider-name" class="form-control" maxlength="200" required value="${esc(p?.name || preset.name || '')}"></div><div class="col-md-6"><label class="form-label" for="provider-protocol">API 协议</label><select id="provider-protocol" class="form-select"><option value="openai-completions">OpenAI Chat Completions</option><option value="openai-responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></div><div class="col-md-6"><label class="form-label" for="provider-base">API 根地址</label><input id="provider-base" class="form-control" maxlength="1000" required value="${esc(p?.apiBase || preset.apiBase || '')}"></div><div class="col-12"><label class="form-label" for="provider-key">API 密钥</label><input id="provider-key" class="form-control" type="password" autocomplete="new-password" maxlength="4096" placeholder="${p?.hasApiKey ? '已保存;留空保留,更换协议或地址需重填' : '输入此供应商的 API Key'}"><div class="form-hint">仅保存到加密存储,页面不会读回已保存的密钥。</div></div><div class="col-12"><label class="form-label" for="provider-models">模型列表</label><textarea id="provider-models" class="form-control font-monospace" rows="5">${esc(modelText(p?.models || preset.models))}</textarea><div class="form-hint">每行:模型 ID | 显示名 | 上下文窗口 | 最大输出 | 输入能力;后 4 项可省略。输入能力可填 text 或 text,image,须由供应商文档或目录确认。获取模型后先检查草稿,再保存。</div></div><div class="col-12"><label class="form-check"><input id="provider-enabled" class="form-check-input" type="checkbox" ${p?.enabled === false ? '' : 'checked'}><span class="form-check-label">启用此供应商</span></label></div></div><div class="btn-list mt-3"><button class="btn" type="button" id="provider-cancel" data-lifecycle-approved="1">取消</button><button class="btn" type="button" id="provider-discover" ${p ? '' : 'disabled'}>获取模型</button><button class="btn btn-primary ms-auto" type="submit">保存供应商</button></div><div id="provider-editor-feedback" class="small mt-2" role="alert"></div></form>`;
|
||||
const form = host.querySelector('form'),
|
||||
get = (id) => form.querySelector('#provider-' + id),
|
||||
message = (text, error = false) => {
|
||||
if (live() && form.isConnected) {
|
||||
get('editor-feedback').className =
|
||||
'small mt-2 ' + (error ? 'text-danger' : 'text-success');
|
||||
get('editor-feedback').textContent = text;
|
||||
}
|
||||
};
|
||||
get('preset').value = p?.preset || preset.id || 'custom';
|
||||
get('protocol').value = p?.protocol || preset.protocol;
|
||||
form.dataset.lifecycle = 'custom';
|
||||
const snapshot = () =>
|
||||
JSON.stringify(
|
||||
[...form.querySelectorAll('input,select,textarea')].map((e) =>
|
||||
e.type === 'checkbox' ? e.checked : e.value,
|
||||
),
|
||||
),
|
||||
baseline = snapshot();
|
||||
unregisterEditor = window.PageLifecycle?.register({
|
||||
scope: 'assistant-provider',
|
||||
sensitive: true,
|
||||
dirty: () => form.isConnected && snapshot() !== baseline,
|
||||
});
|
||||
function lockFields() {
|
||||
const fields = [...form.querySelectorAll('input,select,textarea,button')].map((field) => ({
|
||||
field,
|
||||
disabled: field.disabled,
|
||||
}));
|
||||
for (const { field } of fields) field.disabled = true;
|
||||
return () => {
|
||||
if (form.isConnected) for (const { field, disabled } of fields) field.disabled = disabled;
|
||||
};
|
||||
}
|
||||
get('preset').onchange = () => {
|
||||
const selected = presets.find((x) => x.id === get('preset').value);
|
||||
if (!selected) return;
|
||||
get('name').value = selected.name;
|
||||
get('protocol').value = selected.protocol;
|
||||
get('base').value = selected.apiBase || '';
|
||||
get('models').value = modelText(selected.models);
|
||||
};
|
||||
get('cancel').onclick = () => {
|
||||
const cancel = () => {
|
||||
unregisterEditor?.();
|
||||
editing = null;
|
||||
host.replaceChildren();
|
||||
};
|
||||
if (window.PageLifecycle?.guard)
|
||||
void window.PageLifecycle.guard(cancel, { scope: 'assistant-provider' });
|
||||
else cancel();
|
||||
};
|
||||
get('discover').onclick = async () => {
|
||||
if (!p || busy) return;
|
||||
if (
|
||||
get('base').value.replace(/\/+$/, '') !== p.apiBase.replace(/\/+$/, '') ||
|
||||
get('protocol').value !== p.protocol ||
|
||||
get('key').value
|
||||
) {
|
||||
message('请先保存新的协议、地址或密钥,再获取模型。', true);
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
const unlock = lockFields();
|
||||
try {
|
||||
const result = await api(
|
||||
'/assistant/providers/' + p.id + '/models',
|
||||
{ version: p.version },
|
||||
{ managedOutcome: true },
|
||||
);
|
||||
if (live() && editing === p.id && form.isConnected) {
|
||||
get('models').value = modelText(result.models);
|
||||
message('模型目录已填入草稿,请检查后保存。');
|
||||
}
|
||||
} catch (error) {
|
||||
message(error.message, true);
|
||||
} finally {
|
||||
busy = false;
|
||||
unlock();
|
||||
}
|
||||
};
|
||||
form.onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
const button = event.submitter;
|
||||
let unlock = () => {};
|
||||
try {
|
||||
const body = {
|
||||
...(p ? { id: p.id } : {}),
|
||||
version: p?.version || 0,
|
||||
name: get('name').value,
|
||||
preset: get('preset').value,
|
||||
protocol: get('protocol').value,
|
||||
apiBase: get('base').value,
|
||||
apiKey: get('key').value,
|
||||
enabled: get('enabled').checked,
|
||||
models: parseModels(get('models').value),
|
||||
};
|
||||
unlock = lockFields();
|
||||
const result = await api('/assistant/providers', body);
|
||||
if (!live()) return;
|
||||
directory = result;
|
||||
editing = null;
|
||||
unregisterEditor?.();
|
||||
get('key').value = '';
|
||||
host.replaceChildren();
|
||||
draw();
|
||||
feedback('供应商已保存。');
|
||||
} catch (error) {
|
||||
message(error.message, true);
|
||||
} finally {
|
||||
busy = false;
|
||||
unlock();
|
||||
}
|
||||
};
|
||||
}
|
||||
function runtimeForm() {
|
||||
const host = container.querySelector('#assistant-runtime-host');
|
||||
if (user.role !== 'admin') {
|
||||
host.innerHTML = '<p class="text-secondary">供应商与运行权限由管理员维护。</p>';
|
||||
return;
|
||||
}
|
||||
const s = data.settings;
|
||||
host.innerHTML = `<section class="card mb-3"><div class="card-header"><h2 class="card-title">运行与权限</h2></div><form id="assistant-settings-form"><div class="card-body"><label class="form-label" for="assistant-runtime">官方 CLI 运行包路径</label><input id="assistant-runtime" class="form-control" value="${esc(s.runtimePath)}" maxlength="1000"><div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label" for="assistant-timeout">回复超时(秒)</label><input id="assistant-timeout" class="form-control" type="number" min="15" max="180" value="${s.timeoutSeconds}"></div><div class="col-md-6"><label class="form-label" for="assistant-limit">每日对话轮次上限</label><input id="assistant-limit" class="form-control" type="number" min="1" max="1000" value="${s.dailyLimit}"></div></div><label class="form-check mt-2"><input id="assistant-allow-actions" class="form-check-input" type="checkbox" ${s.allowActions ? 'checked' : ''}><span class="form-check-label">开放固定操作卡片(仍按工作台权限执行)</span></label><details class="mt-3"><summary>管理员隔离代码修复</summary><label class="form-check mt-2"><input id="assistant-code-repair" class="form-check-input" type="checkbox" ${s.allowCodeRepair ? 'checked' : ''}><span class="form-check-label">允许管理员提出并审查隔离代码修复</span></label><label class="form-label mt-2" for="assistant-repository">源码 Git 仓库路径</label><input id="assistant-repository" class="form-control" maxlength="1000" value="${esc(s.repairRepository || '')}"><div class="form-hint">固定测试通过后仍待人工审查,不自动合并部署。</div></details><div id="assistant-runtime-status" class="small mt-3" role="status"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="assistant-check">检查运行包</button><button class="btn btn-primary ms-auto" type="submit">保存助手设置</button></div></form></section>`;
|
||||
const get = (id) => host.querySelector('#assistant-' + id);
|
||||
get('check').onclick = async () => {
|
||||
get('check').disabled = true;
|
||||
try {
|
||||
const checked = await api('/assistant/check', {});
|
||||
if (live())
|
||||
get('runtime-status').textContent =
|
||||
checked.message +
|
||||
(checked.modelConfigured
|
||||
? ' 默认模型配置完整,实际调用时验证。'
|
||||
: ' 请先添加供应商并选择可用默认模型。');
|
||||
} catch (error) {
|
||||
if (live()) get('runtime-status').textContent = error.message;
|
||||
} finally {
|
||||
if (live()) get('check').disabled = false;
|
||||
}
|
||||
};
|
||||
host.querySelector('form').onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
const button = event.submitter;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const saved = await api('/assistant/settings', {
|
||||
version: data.settings.version,
|
||||
runtimePath: get('runtime').value,
|
||||
timeoutSeconds: Number(get('timeout').value),
|
||||
dailyLimit: Number(get('limit').value),
|
||||
enabled: data.settings.enabled,
|
||||
allowActions: get('allow-actions').checked,
|
||||
allowCodeRepair: get('code-repair').checked,
|
||||
repairRepository: get('repository').value,
|
||||
});
|
||||
if (!live()) return;
|
||||
data.settings = saved;
|
||||
await window.PageLifecycle.afterSave(
|
||||
async () => {
|
||||
const fresh = await api('/assistant');
|
||||
if (live()) data.settings = fresh.settings;
|
||||
},
|
||||
'助手设置已保存。',
|
||||
feedback,
|
||||
live,
|
||||
);
|
||||
} catch (error) {
|
||||
if (live())
|
||||
container.querySelector('#assistant-settings-error').textContent = error.message;
|
||||
} finally {
|
||||
if (button.isConnected) button.disabled = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
draw();
|
||||
runtimeForm();
|
||||
window.PageLifecycle?.onDispose(() => {
|
||||
disposed = true;
|
||||
unregisterEditor?.();
|
||||
container.querySelectorAll('dialog').forEach((d) => {
|
||||
d.close();
|
||||
d.remove();
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,363 @@
|
||||
'use strict';
|
||||
window.AssistantScheduleManager = {
|
||||
mount(
|
||||
root,
|
||||
{ api, esc, formatDate, user, getConversation, ensureConversation, onChanged, isActive },
|
||||
) {
|
||||
const body = root.querySelector('.aw-body'),
|
||||
page = document.createElement('section');
|
||||
page.className = 'aw-task-page';
|
||||
page.setAttribute('aria-label', '定时任务管理');
|
||||
page.hidden = true;
|
||||
const backIcon =
|
||||
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5m6-6-6 6 6 6"/></svg>';
|
||||
page.innerHTML =
|
||||
'<header class="aw-task-heading"><div><button type="button" class="btn btn-sm" data-task-back>' +
|
||||
backIcon +
|
||||
' 返回对话</button><h2>定时任务管理</h2><p class="text-secondary small">管理你的全部会话任务,查看规则、下次触发时间和调用记录。</p></div><div class="btn-list"><button type="button" class="btn btn-primary" data-task-create>新建定时任务</button><button type="button" class="btn" data-task-refresh>刷新任务</button></div></header><div class="aw-task-filters"><div role="group" aria-label="任务状态">' +
|
||||
[
|
||||
['all', '全部'],
|
||||
['active', '进行中'],
|
||||
['inactive', '已结束'],
|
||||
]
|
||||
.map(
|
||||
([id, label]) =>
|
||||
'<button type="button" class="btn btn-sm" data-task-status="' +
|
||||
id +
|
||||
'" aria-pressed="' +
|
||||
(id === 'all') +
|
||||
'">' +
|
||||
label +
|
||||
'</button>',
|
||||
)
|
||||
.join('') +
|
||||
'</div><label class="visually-hidden" for="aw-task-search">搜索定时任务</label><input id="aw-task-search" class="form-control" type="search" maxlength="300" placeholder="搜索任务名称、内容或所属会话"><label class="visually-hidden" for="aw-task-session">筛选所属会话</label><select id="aw-task-session" class="form-select"><option value="">全部会话</option></select></div><p data-task-message class="small text-secondary" role="status">正在读取任务…</p><div data-task-list class="aw-task-list"></div><div data-task-editor hidden></div>';
|
||||
root.append(page);
|
||||
let visible = false,
|
||||
disposed = false,
|
||||
loading = false,
|
||||
generation = 0,
|
||||
timer = null,
|
||||
status = 'all',
|
||||
query = '',
|
||||
conversationFilter = '',
|
||||
tasks = [],
|
||||
conversations = [],
|
||||
history = [],
|
||||
settled = false,
|
||||
failed = false,
|
||||
selectedConversation = null,
|
||||
signature = '';
|
||||
const list = page.querySelector('[data-task-list]'),
|
||||
message = page.querySelector('[data-task-message]'),
|
||||
newButton = page.querySelector('[data-task-create]');
|
||||
const alive = () => !disposed && visible && isActive();
|
||||
const editor = window.AssistantSchedules.mount(page.querySelector('[data-task-editor]'), {
|
||||
api,
|
||||
esc,
|
||||
formatDate,
|
||||
user,
|
||||
getConversation: () => selectedConversation,
|
||||
ensureConversation,
|
||||
onChanged: async (id) => {
|
||||
await onChanged(id);
|
||||
await refresh();
|
||||
},
|
||||
isActive: alive,
|
||||
getConversations: () => conversations,
|
||||
});
|
||||
function frequency(t) {
|
||||
return (
|
||||
{
|
||||
after: '延时 ' + t.afterSeconds + ' 秒(一次)',
|
||||
at: '指定时间(一次)',
|
||||
every: '每隔 ' + t.everySeconds + ' 秒',
|
||||
daily: '每天 ' + t.time,
|
||||
weekly:
|
||||
'每周 ' +
|
||||
t.weekdays?.map((n) => ['', '一', '二', '三', '四', '五', '六', '日'][n]).join('、') +
|
||||
' · ' +
|
||||
t.time,
|
||||
cron: 'Cron ' + t.expression,
|
||||
}[t.kind] + (t.timeZone ? ' · ' + t.timeZone : '')
|
||||
);
|
||||
}
|
||||
function canWrite(t) {
|
||||
return user.role !== 'viewer' && settled && !failed && !t?.conversationArchived;
|
||||
}
|
||||
function nativeTask(t) {
|
||||
const { conversationTitle, conversationArchived, ...value } = t;
|
||||
return value;
|
||||
}
|
||||
function target(t) {
|
||||
selectedConversation = { id: t.sessionId, archived: !!t.conversationArchived };
|
||||
editor.update(selectedConversation);
|
||||
}
|
||||
function draw() {
|
||||
newButton.disabled = !canWrite();
|
||||
const rows = tasks
|
||||
.filter(
|
||||
(t) =>
|
||||
(status === 'all' || t.status === status) &&
|
||||
(!conversationFilter || t.sessionId === conversationFilter) &&
|
||||
(!query ||
|
||||
[t.title, t.prompt, t.conversationTitle, t.id, t.sessionId].some((v) =>
|
||||
String(v || '')
|
||||
.toLowerCase()
|
||||
.includes(query),
|
||||
)),
|
||||
)
|
||||
.sort((a, b) => Date.parse(a.scheduledAt) - Date.parse(b.scheduledAt));
|
||||
page
|
||||
.querySelectorAll('[data-task-status]')
|
||||
.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.taskStatus === status)));
|
||||
if (!failed)
|
||||
message.textContent = settled
|
||||
? '显示 ' +
|
||||
rows.length +
|
||||
' / ' +
|
||||
tasks.length +
|
||||
' 个任务;新建、详情、编辑和删除均可在此操作。'
|
||||
: '正在读取任务…';
|
||||
const next = JSON.stringify([rows, settled, failed, user.role]);
|
||||
if (next === signature) return;
|
||||
signature = next;
|
||||
list.innerHTML = rows.length
|
||||
? rows
|
||||
.map(
|
||||
(t) =>
|
||||
'<article class="aw-task-row"><div class="aw-task-row-heading"><strong>' +
|
||||
esc(t.title) +
|
||||
'</strong><span class="aw-state">' +
|
||||
(t.status === 'active' ? '进行中' : '已结束') +
|
||||
'</span></div><p class="small text-secondary">' +
|
||||
esc(frequency(t)) +
|
||||
'<br>' +
|
||||
esc(
|
||||
t.status === 'active'
|
||||
? '下次触发:' + formatDate(t.scheduledAt)
|
||||
: '最后触发时间:' + formatDate(t.scheduledAt),
|
||||
) +
|
||||
'<br>所属会话:' +
|
||||
esc(t.conversationTitle || '未命名会话') +
|
||||
'</p><p class="aw-task-excerpt">' +
|
||||
esc(t.prompt) +
|
||||
'</p>' +
|
||||
(t.lastError ? '<p class="text-danger small">' + esc(t.lastError) + '</p>' : '') +
|
||||
'<div class="btn-list"><button type="button" class="btn btn-sm" data-task-detail="' +
|
||||
esc(t.id) +
|
||||
'" aria-label="查看任务 ' +
|
||||
esc(t.title) +
|
||||
'">查看详情</button><button type="button" class="btn btn-sm" data-task-edit="' +
|
||||
esc(t.id) +
|
||||
'" aria-label="编辑任务 ' +
|
||||
esc(t.title) +
|
||||
'" ' +
|
||||
(!canWrite(t) || t.status !== 'active' ? 'disabled' : '') +
|
||||
'>编辑</button><button type="button" class="btn btn-sm btn-outline-danger" data-task-delete="' +
|
||||
esc(t.id) +
|
||||
'" aria-label="删除任务 ' +
|
||||
esc(t.title) +
|
||||
'" ' +
|
||||
(!canWrite(t) ? 'disabled' : '') +
|
||||
'>删除</button></div>' +
|
||||
(t.status !== 'active'
|
||||
? '<small class="text-secondary">已结束的任务保留记录,可删除或新建任务。</small>'
|
||||
: '') +
|
||||
'</article>',
|
||||
)
|
||||
.join('')
|
||||
: settled
|
||||
? '<div class="aw-task-empty"><h3>' +
|
||||
(tasks.length ? '没有匹配的任务' : '还没有定时任务') +
|
||||
'</h3><p class="text-secondary">' +
|
||||
(tasks.length
|
||||
? '调整搜索内容、状态或所属会话筛选。'
|
||||
: '点击右上角“新建定时任务”,选择会话、任务内容和触发规则。') +
|
||||
'</p></div>'
|
||||
: '';
|
||||
for (const [selector, run] of [
|
||||
['detail', details],
|
||||
[
|
||||
'edit',
|
||||
(t) => {
|
||||
target(t);
|
||||
void editor.edit(nativeTask(t));
|
||||
},
|
||||
],
|
||||
[
|
||||
'delete',
|
||||
(t) => {
|
||||
target(t);
|
||||
editor.remove(nativeTask(t));
|
||||
},
|
||||
],
|
||||
])
|
||||
page.querySelectorAll('[data-task-' + selector + ']').forEach(
|
||||
(b) =>
|
||||
(b.onclick = () => {
|
||||
const t = tasks.find(
|
||||
(t) => t.id === b.dataset['task' + selector[0].toUpperCase() + selector.slice(1)],
|
||||
);
|
||||
if (t) run(t);
|
||||
}),
|
||||
);
|
||||
}
|
||||
async function refresh() {
|
||||
if (loading || !alive()) return;
|
||||
loading = true;
|
||||
const at = generation;
|
||||
try {
|
||||
const data = await api('/assistant/schedules');
|
||||
if (!alive() || at !== generation) return;
|
||||
tasks = data.tasks;
|
||||
history = data.history;
|
||||
conversations = data.conversations;
|
||||
settled = true;
|
||||
failed = false;
|
||||
const select = page.querySelector('#aw-task-session'),
|
||||
old = select.value;
|
||||
const all = new Map([
|
||||
...conversations.map((c) => [c.id, c.title]),
|
||||
...tasks.map((t) => [t.sessionId, t.conversationTitle]),
|
||||
]);
|
||||
select.innerHTML =
|
||||
'<option value="">全部会话</option>' +
|
||||
[...all]
|
||||
.map(([id, title]) => '<option value="' + esc(id) + '">' + esc(title) + '</option>')
|
||||
.join('');
|
||||
select.value = all.has(old) ? old : '';
|
||||
conversationFilter = select.value;
|
||||
draw();
|
||||
if (data.error) {
|
||||
failed = true;
|
||||
message.textContent = data.error;
|
||||
draw();
|
||||
}
|
||||
} catch (e) {
|
||||
if (alive() && at === generation) {
|
||||
failed = true;
|
||||
message.textContent =
|
||||
'任务列表读取失败:' + e.message + '。请刷新;上次读取的任务保留,暂不允许修改。';
|
||||
draw();
|
||||
}
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
function details(t) {
|
||||
const d = document.createElement('dialog');
|
||||
d.className = 'page-leave-dialog aw-schedule-dialog';
|
||||
d.setAttribute('aria-label', '定时任务详情');
|
||||
const row = (name, value) => '<dt>' + name + '</dt><dd>' + esc(value) + '</dd>',
|
||||
records = history.filter((h) => h.taskId === t.id);
|
||||
d.innerHTML =
|
||||
'<h2 class="h3">定时任务详情</h2><dl>' +
|
||||
row('任务名称', t.title) +
|
||||
row('任务编号', t.id) +
|
||||
row('所属会话', t.conversationTitle || t.sessionId) +
|
||||
row('触发规则', frequency(t)) +
|
||||
row(t.status === 'active' ? '下次触发' : '最后触发时间', formatDate(t.scheduledAt)) +
|
||||
row('状态', t.status === 'active' ? '进行中' : '已结束') +
|
||||
row('任务内容', t.prompt) +
|
||||
'</dl><h3 class="h4">调用记录</h3>' +
|
||||
(records.length
|
||||
? records
|
||||
.map(
|
||||
(h) =>
|
||||
'<p>' +
|
||||
esc(formatDate(h.scheduledAt)) +
|
||||
' · ' +
|
||||
esc(
|
||||
{
|
||||
queued: '等待调用',
|
||||
running: '正在调用',
|
||||
success: '已回复',
|
||||
error: '调用失败',
|
||||
cancelled: '已取消',
|
||||
needs_review: '待核实',
|
||||
}[h.status] || h.status,
|
||||
) +
|
||||
(h.error ? '<br>' + esc(h.error) : '') +
|
||||
'</p>',
|
||||
)
|
||||
.join('')
|
||||
: '<p class="text-secondary">最近调用记录中没有此任务的记录;不代表更早的调用从未发生。</p>') +
|
||||
'<button type="button" class="btn" data-close-detail>关闭</button>';
|
||||
root.append(d);
|
||||
d.querySelector('[data-close-detail]').onclick = () => d.close();
|
||||
d.onclose = () => d.remove();
|
||||
d.showModal();
|
||||
}
|
||||
newButton.onclick = async () => {
|
||||
if (!canWrite()) return;
|
||||
try {
|
||||
const current = getConversation(),
|
||||
chosen = conversations.find((c) => c.id === current?.id) || conversations[0];
|
||||
if (chosen) selectedConversation = chosen;
|
||||
else {
|
||||
const created = await ensureConversation();
|
||||
if (!created || !alive()) return;
|
||||
selectedConversation = { id: created.id };
|
||||
await refresh();
|
||||
}
|
||||
editor.update(selectedConversation);
|
||||
await editor.edit();
|
||||
} catch (e) {
|
||||
if (alive()) message.textContent = e.message;
|
||||
}
|
||||
};
|
||||
page.querySelector('[data-task-refresh]').onclick = () => void refresh();
|
||||
page.querySelector('#aw-task-search').oninput = (e) => {
|
||||
query = e.target.value.trim().toLowerCase();
|
||||
draw();
|
||||
};
|
||||
page.querySelector('#aw-task-session').onchange = (e) => {
|
||||
conversationFilter = e.target.value;
|
||||
draw();
|
||||
};
|
||||
page.querySelectorAll('[data-task-status]').forEach(
|
||||
(b) =>
|
||||
(b.onclick = () => {
|
||||
status = b.dataset.taskStatus;
|
||||
draw();
|
||||
}),
|
||||
);
|
||||
function close() {
|
||||
if (!visible) return;
|
||||
visible = false;
|
||||
generation++;
|
||||
clearInterval(timer);
|
||||
page.hidden = true;
|
||||
body.hidden = false;
|
||||
root.querySelector('#assistant-schedules').focus();
|
||||
}
|
||||
page.querySelector('[data-task-back]').onclick = close;
|
||||
const navButtons = [...root.querySelectorAll('[data-aw-left],[data-aw-right]')];
|
||||
navButtons.forEach((b) => b.addEventListener('click', close));
|
||||
return {
|
||||
open() {
|
||||
if (disposed) return;
|
||||
visible = true;
|
||||
page.hidden = false;
|
||||
body.hidden = true;
|
||||
void refresh();
|
||||
clearInterval(timer);
|
||||
timer = setInterval(() => {
|
||||
if (!root.querySelector('dialog[open]')) void refresh();
|
||||
}, 4000);
|
||||
page.querySelector('#aw-task-search').focus();
|
||||
},
|
||||
close,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
generation++;
|
||||
clearInterval(timer);
|
||||
editor.dispose();
|
||||
navButtons.forEach((b) => b.removeEventListener('click', close));
|
||||
body.hidden = false;
|
||||
page.remove();
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,440 @@
|
||||
'use strict';
|
||||
window.AssistantSchedules = {
|
||||
mount(
|
||||
host,
|
||||
{
|
||||
api,
|
||||
esc,
|
||||
formatDate,
|
||||
user,
|
||||
getConversation,
|
||||
ensureConversation,
|
||||
onChanged,
|
||||
isActive,
|
||||
getConversations,
|
||||
},
|
||||
) {
|
||||
let cid = '',
|
||||
generation = 0,
|
||||
busy = false,
|
||||
disposed = false,
|
||||
visible = false,
|
||||
tasks = [],
|
||||
history = [],
|
||||
timer = null,
|
||||
loading = false,
|
||||
lastSignature = '';
|
||||
const root = host.closest('.assistant-workspace');
|
||||
host.innerHTML =
|
||||
'<h3>定时任务</h3><p class="small text-secondary">使用 DSH 原生调度,在原会话中定时调用模型。关闭页面后仍可运行,服务停止期间不会调用模型。</p><div class="btn-list"><button type="button" class="btn btn-primary btn-sm" data-schedule-new>新建定时任务</button><button type="button" class="btn btn-sm" data-schedule-refresh>刷新任务</button></div><p role="alert" class="small text-danger" data-schedule-error></p><div data-schedule-tasks></div><h4 class="mt-3">最近调用</h4><div data-schedule-history></div>';
|
||||
const error = host.querySelector('[data-schedule-error]'),
|
||||
create = host.querySelector('[data-schedule-new]');
|
||||
const writable = () =>
|
||||
user.role !== 'viewer' && !getConversation()?.archived && !getConversation()?.deletedAt;
|
||||
function timing(t) {
|
||||
return (
|
||||
{
|
||||
after: '延时 ' + t.afterSeconds + ' 秒',
|
||||
at: '指定时间',
|
||||
every: '每隔 ' + t.everySeconds + ' 秒',
|
||||
daily: '每天 ' + t.time,
|
||||
weekly: '每周 ' + t.weekdays?.join('、') + ' · ' + t.time,
|
||||
cron: 'Cron ' + t.expression,
|
||||
}[t.kind] + (t.timeZone ? ' · ' + t.timeZone : '')
|
||||
);
|
||||
}
|
||||
function draw() {
|
||||
create.disabled = busy || !writable();
|
||||
const signature = JSON.stringify([tasks, history, busy, writable()]);
|
||||
if (signature === lastSignature) return;
|
||||
lastSignature = signature;
|
||||
host.querySelector('[data-schedule-tasks]').innerHTML = tasks.length
|
||||
? tasks
|
||||
.map(
|
||||
(t) =>
|
||||
'<article class="assistant-action"><strong>' +
|
||||
esc(t.title) +
|
||||
'</strong><p class="small text-secondary mt-2">' +
|
||||
esc(timing(t)) +
|
||||
'<br>' +
|
||||
esc(
|
||||
t.status === 'active'
|
||||
? '下次触发:' + formatDate(t.scheduledAt)
|
||||
: '已触发(不再重复)',
|
||||
) +
|
||||
'</p><p class="aw-schedule-prompt">' +
|
||||
esc(t.prompt) +
|
||||
'</p>' +
|
||||
(t.lastError ? '<p class="text-danger">' + esc(t.lastError) + '</p>' : '') +
|
||||
'<div class="btn-list"><button type="button" class="btn btn-sm" data-schedule-edit="' +
|
||||
esc(t.id) +
|
||||
'" aria-label="编辑任务 ' +
|
||||
esc(t.title) +
|
||||
'" ' +
|
||||
(busy || !writable() || t.status !== 'active' ? 'disabled' : '') +
|
||||
'>编辑</button><button type="button" class="btn btn-sm btn-outline-danger" data-schedule-delete="' +
|
||||
esc(t.id) +
|
||||
'" aria-label="删除任务 ' +
|
||||
esc(t.title) +
|
||||
'" ' +
|
||||
(busy || !writable() ? 'disabled' : '') +
|
||||
'>删除</button></div></article>',
|
||||
)
|
||||
.join('')
|
||||
: '<p class="small text-secondary mt-3">当前会话暂无定时任务。</p>';
|
||||
host.querySelector('[data-schedule-history]').innerHTML = history.length
|
||||
? history
|
||||
.map(
|
||||
(h) =>
|
||||
'<div class="aw-event"><strong>' +
|
||||
esc(h.title) +
|
||||
'</strong> · <span>' +
|
||||
esc(
|
||||
{
|
||||
queued: '等待调用',
|
||||
running: '正在调用',
|
||||
success: '已回复',
|
||||
error: '调用失败',
|
||||
cancelled: '已取消',
|
||||
needs_review: '待核实',
|
||||
}[h.status] || h.status,
|
||||
) +
|
||||
'</span><br><time>' +
|
||||
esc(formatDate(h.scheduledAt)) +
|
||||
'</time>' +
|
||||
(h.error ? '<p class="text-danger">' + esc(h.error) + '</p>' : '') +
|
||||
'</div>',
|
||||
)
|
||||
.join('')
|
||||
: '<p class="small text-secondary">尚无调用记录。任务触发不代表其他操作已执行。</p>';
|
||||
host
|
||||
.querySelectorAll('[data-schedule-edit]')
|
||||
.forEach(
|
||||
(b) => (b.onclick = () => edit(tasks.find((t) => t.id === b.dataset.scheduleEdit))),
|
||||
);
|
||||
host
|
||||
.querySelectorAll('[data-schedule-delete]')
|
||||
.forEach(
|
||||
(b) => (b.onclick = () => remove(tasks.find((t) => t.id === b.dataset.scheduleDelete))),
|
||||
);
|
||||
}
|
||||
async function refresh() {
|
||||
if (loading || disposed || !isActive() || !cid) return;
|
||||
const id = cid,
|
||||
at = generation;
|
||||
loading = true;
|
||||
try {
|
||||
const data = await api('/assistant/conversations/' + id + '/schedules');
|
||||
if (disposed || !isActive() || id !== cid || at !== generation) return;
|
||||
tasks = data.tasks;
|
||||
history = data.history;
|
||||
error.textContent = data.error || '';
|
||||
draw();
|
||||
} catch (e) {
|
||||
if (id === cid && at === generation && isActive()) error.textContent = e.message;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
function dialog(title) {
|
||||
const d = document.createElement('dialog');
|
||||
d.className = 'page-leave-dialog aw-schedule-dialog';
|
||||
d.setAttribute('aria-label', title);
|
||||
root.append(d);
|
||||
d.addEventListener('close', () => d.remove(), { once: true });
|
||||
return d;
|
||||
}
|
||||
async function mutate(d, button, path, body, owner) {
|
||||
busy = true;
|
||||
button.disabled = true;
|
||||
draw();
|
||||
const note = d.querySelector('[data-form-error]');
|
||||
try {
|
||||
await api(path, body, { managedOutcome: true });
|
||||
if (disposed || !isActive()) return;
|
||||
d.close();
|
||||
await onChanged(owner);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
if (!disposed && d.isConnected) {
|
||||
const uncertain = !e.status || e.status >= 500;
|
||||
note.textContent =
|
||||
e.message + (uncertain ? ' 请关闭窗口并刷新任务列表核实,勿重复提交。' : '');
|
||||
button.disabled = uncertain;
|
||||
d.dataset.uncertain = uncertain ? 'true' : '';
|
||||
if (e.status === 409) {
|
||||
d.dataset.uncertain = 'true';
|
||||
button.disabled = true;
|
||||
note.textContent += ' 请关闭后刷新任务,再重新编辑。';
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
busy = false;
|
||||
if (!disposed) draw();
|
||||
}
|
||||
}
|
||||
async function edit(task) {
|
||||
if (busy || !writable()) return;
|
||||
const id = cid;
|
||||
let owner = id;
|
||||
try {
|
||||
if (!owner) {
|
||||
const c = await ensureConversation();
|
||||
if (!c) return;
|
||||
owner = c.id;
|
||||
cid = owner;
|
||||
await onChanged(owner);
|
||||
}
|
||||
} catch (e) {
|
||||
error.textContent = e.message;
|
||||
return;
|
||||
}
|
||||
if (!isActive() || disposed) return;
|
||||
const d = dialog(task ? '编辑定时任务' : '新建定时任务'),
|
||||
kind = task?.kind === 'after' ? 'at' : task?.kind || 'after';
|
||||
d.innerHTML =
|
||||
'<form><h2 class="h3">' +
|
||||
(task ? '编辑定时任务' : '新建定时任务') +
|
||||
'</h2><label class="form-label">任务名称<input name="title" class="form-control" maxlength="120" required></label><label class="form-label">任务内容<textarea name="prompt" class="form-control" rows="3" maxlength="3000" required></textarea></label><label class="form-label">时间规则<select name="kind" class="form-select">' +
|
||||
[
|
||||
['after', '延时一次'],
|
||||
['at', '指定时间'],
|
||||
['every', '固定间隔'],
|
||||
['daily', '每天'],
|
||||
['weekly', '每周'],
|
||||
['cron', 'Cron 表达式'],
|
||||
]
|
||||
.filter(([k]) => !task || k !== 'after')
|
||||
.map(([k, v]) => '<option value="' + k + '">' + v + '</option>')
|
||||
.join('') +
|
||||
'</select></label><div data-time-fields></div><p class="small text-secondary">到点会使用当前模型、原会话历史及附件,消耗调用额度并可能产生费用。关闭页面不会取消任务。修改设置、邮件等操作仍须另行审查授权。</p><label class="form-check my-3"><input type="checkbox" class="form-check-input" name="consent"><span class="form-check-label">我确认按此规则定时调用模型,其他操作仍需另行授权</span></label><p role="alert" class="text-danger small" data-form-error></p><div class="btn-list"><button type="button" class="btn" data-cancel>取消</button><button type="submit" class="btn btn-primary" disabled>确认保存</button></div></form>';
|
||||
if (!task && getConversations) {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'form-label';
|
||||
label.innerHTML =
|
||||
'所属会话<select name=targetConversation class=form-select aria-label="所属会话" required>' +
|
||||
getConversations()
|
||||
.map(
|
||||
(c) => '<option value="' + esc(c.id) + '">' + esc(c.title || '新对话') + '</option>',
|
||||
)
|
||||
.join('') +
|
||||
'</select>';
|
||||
d.querySelector('h2').after(label);
|
||||
const select = label.querySelector('select');
|
||||
select.value = owner;
|
||||
select.onchange = () => {
|
||||
owner = select.value;
|
||||
cid = owner;
|
||||
};
|
||||
}
|
||||
const form = d.querySelector('form'),
|
||||
fields = form.elements,
|
||||
save = form.querySelector('[type=submit]');
|
||||
fields.title.value = task?.title || '';
|
||||
fields.prompt.value = task?.prompt || '';
|
||||
fields.kind.value = kind;
|
||||
function timeFields() {
|
||||
const k = fields.kind.value,
|
||||
field = (label, name, type, value, extra = '') =>
|
||||
'<label class="form-label">' +
|
||||
label +
|
||||
'<input class="form-control" name="' +
|
||||
name +
|
||||
'" type="' +
|
||||
type +
|
||||
'" value="' +
|
||||
esc(value) +
|
||||
'" ' +
|
||||
extra +
|
||||
' required></label>';
|
||||
let html = '';
|
||||
if (k === 'after')
|
||||
html = field('延时(秒)', 'seconds', 'number', '3600', 'min="1" step="1"');
|
||||
if (k === 'every')
|
||||
html = field(
|
||||
'间隔(秒)',
|
||||
'seconds',
|
||||
'number',
|
||||
task?.everySeconds || 3600,
|
||||
'min="60" step="1"',
|
||||
);
|
||||
if (k === 'at') {
|
||||
const local = task?.scheduledAt
|
||||
? new Date(
|
||||
Date.parse(task.scheduledAt) -
|
||||
new Date(task.scheduledAt).getTimezoneOffset() * 60000,
|
||||
)
|
||||
.toISOString()
|
||||
.slice(0, 19)
|
||||
: '';
|
||||
html = field('指定日期时间', 'at', 'datetime-local', local, 'step="1"');
|
||||
}
|
||||
if (['daily', 'weekly'].includes(k))
|
||||
html = field(
|
||||
'触发时间',
|
||||
'time',
|
||||
'time',
|
||||
task?.time?.slice(0, 8) || '09:00:00',
|
||||
'step="1"',
|
||||
);
|
||||
if (k === 'weekly')
|
||||
html +=
|
||||
'<fieldset><legend class="form-label">每周日期</legend>' +
|
||||
['一', '二', '三', '四', '五', '六', '日']
|
||||
.map(
|
||||
(n, i) =>
|
||||
'<label class="me-2"><input type="checkbox" name="weekday" value="' +
|
||||
(i + 1) +
|
||||
'" ' +
|
||||
((task?.weekdays || [1]).includes(i + 1) ? 'checked' : '') +
|
||||
'> 周' +
|
||||
n +
|
||||
'</label>',
|
||||
)
|
||||
.join('') +
|
||||
'</fieldset>';
|
||||
if (k === 'cron')
|
||||
html = field(
|
||||
'Cron 表达式(分 时 日 月 周)',
|
||||
'expression',
|
||||
'text',
|
||||
task?.expression || '0 9 * * *',
|
||||
);
|
||||
if (['at', 'daily', 'weekly', 'cron'].includes(k))
|
||||
html += field(
|
||||
'时区(IANA)',
|
||||
'zone',
|
||||
'text',
|
||||
k === 'at'
|
||||
? Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
: task?.timeZone || 'Asia/Shanghai',
|
||||
);
|
||||
form.querySelector('[data-time-fields]').innerHTML = html;
|
||||
}
|
||||
function selector() {
|
||||
const k = fields.kind.value,
|
||||
time = fields.time?.value,
|
||||
zone = fields.zone?.value.trim();
|
||||
if (k === 'after') return { after_seconds: Number(fields.seconds.value) };
|
||||
if (k === 'every') return { every_seconds: Number(fields.seconds.value) };
|
||||
if (k === 'at') {
|
||||
const [date, t] = fields.at.value.split('T');
|
||||
return { at: { date, time: t.length === 5 ? t + ':00' : t, time_zone: zone } };
|
||||
}
|
||||
const value = { time: time?.length === 5 ? time + ':00' : time, time_zone: zone };
|
||||
if (k === 'weekly')
|
||||
value.weekdays = [...form.querySelectorAll('[name=weekday]:checked')].map((x) =>
|
||||
Number(x.value),
|
||||
);
|
||||
return {
|
||||
[k]:
|
||||
k === 'cron' ? { expression: fields.expression.value.trim(), time_zone: zone } : value,
|
||||
};
|
||||
}
|
||||
timeFields();
|
||||
let timingChanged = false;
|
||||
fields.kind.onchange = () => {
|
||||
timingChanged = true;
|
||||
timeFields();
|
||||
};
|
||||
form.querySelector('[data-time-fields]').oninput = () => {
|
||||
timingChanged = true;
|
||||
};
|
||||
fields.consent.onchange = () => {
|
||||
save.disabled = !fields.consent.checked || d.dataset.uncertain === 'true';
|
||||
};
|
||||
form.querySelector('[data-cancel]').onclick = () => {
|
||||
if (!busy) d.close();
|
||||
};
|
||||
d.oncancel = (e) => {
|
||||
if (busy) e.preventDefault();
|
||||
};
|
||||
form.onsubmit = (e) => {
|
||||
e.preventDefault();
|
||||
if (busy || !fields.consent.checked || d.dataset.uncertain === 'true' || cid !== owner)
|
||||
return;
|
||||
try {
|
||||
const request = {
|
||||
title: fields.title.value.trim(),
|
||||
prompt: fields.prompt.value.trim(),
|
||||
...selector(),
|
||||
};
|
||||
let body = { confirm: true, request },
|
||||
url = '/assistant/conversations/' + owner + '/schedules';
|
||||
if (task) {
|
||||
const { sessionId, status, lastDelivery, lastError, ...expected } = task;
|
||||
const changes = { title: request.title, prompt: request.prompt };
|
||||
if (timingChanged) changes.change = { kind: fields.kind.value, ...selector() };
|
||||
body = { confirm: true, expected, changes };
|
||||
url += '/' + task.id + '/update';
|
||||
}
|
||||
void mutate(d, save, url, body, owner);
|
||||
} catch (err) {
|
||||
form.querySelector('[data-form-error]').textContent = err.message;
|
||||
}
|
||||
};
|
||||
d.showModal();
|
||||
}
|
||||
function remove(task) {
|
||||
if (busy || !writable() || !task) return;
|
||||
const owner = cid,
|
||||
d = dialog('删除定时任务');
|
||||
d.innerHTML =
|
||||
'<h2 class="h3">删除定时任务</h2><p>确认停止“' +
|
||||
esc(task.title) +
|
||||
'”的未来触发?已经投递的消息和正在进行的模型回复保留。</p><p role="alert" class="text-danger" data-form-error></p><div class="btn-list"><button type="button" class="btn" data-cancel>取消</button><button type="button" class="btn btn-danger" data-delete>确认删除任务</button></div>';
|
||||
d.querySelector('[data-cancel]').onclick = () => {
|
||||
if (!busy) d.close();
|
||||
};
|
||||
d.oncancel = (e) => {
|
||||
if (busy) e.preventDefault();
|
||||
};
|
||||
const b = d.querySelector('[data-delete]');
|
||||
b.onclick = () => {
|
||||
if (!busy && cid === owner)
|
||||
void mutate(
|
||||
d,
|
||||
b,
|
||||
'/assistant/conversations/' + owner + '/schedules/' + task.id + '/delete',
|
||||
{ confirm: true },
|
||||
owner,
|
||||
);
|
||||
};
|
||||
d.showModal();
|
||||
}
|
||||
create.onclick = () => void edit();
|
||||
host.querySelector('[data-schedule-refresh]').onclick = () => void refresh();
|
||||
draw();
|
||||
return {
|
||||
edit,
|
||||
remove,
|
||||
update(c) {
|
||||
if (cid !== c?.id) {
|
||||
generation++;
|
||||
cid = c?.id || '';
|
||||
tasks = [];
|
||||
history = [];
|
||||
error.textContent = '';
|
||||
draw();
|
||||
if (visible) void refresh();
|
||||
} else create.disabled = busy || !writable();
|
||||
},
|
||||
show(value) {
|
||||
visible = value;
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
if (value) {
|
||||
void refresh();
|
||||
timer = setInterval(() => {
|
||||
if (root.classList.contains('aw-right-open') && !busy) void refresh();
|
||||
}, 1500);
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
generation++;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,105 @@
|
||||
'use strict';
|
||||
window.AssistantSettingsReview = {
|
||||
async open(root, { api, id, actionId, isActive }) {
|
||||
const review = await api(
|
||||
'/assistant/conversations/' + id + '/actions/' + actionId + '/review',
|
||||
{},
|
||||
);
|
||||
if (!isActive()) return null;
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.className = 'aw-settings-review';
|
||||
dialog.setAttribute('aria-label', '审查设置修改');
|
||||
dialog.innerHTML =
|
||||
'<header><h2>审查设置修改</h2><p data-review-label></p></header><div class="aw-review-body"><h3>本次修改</h3><div class="aw-review-diff"></div><h3>风险与影响</h3><ul class="aw-review-risks"></ul><p class="text-secondary" data-review-expiry></p><label class="form-check"><input class="form-check-input" type="checkbox"><span class="form-check-label">我已阅读以上差异和风险,授权本次修改</span></label><div role="alert" class="text-danger mt-2"></div></div><footer><button type="button" class="btn" data-review-cancel>取消</button><button type="button" class="btn btn-outline-danger" data-review-reject>拒绝本次修改</button><button type="button" class="btn btn-primary" data-review-approve disabled>授权并保存</button></footer>';
|
||||
dialog.querySelector('[data-review-label]').textContent = review.label;
|
||||
for (const d of review.diff) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'aw-review-change';
|
||||
const label = document.createElement('strong');
|
||||
label.textContent = d.label;
|
||||
row.append(label);
|
||||
for (const [heading, value] of [
|
||||
['修改前', d.before],
|
||||
['修改后', d.after],
|
||||
]) {
|
||||
const p = document.createElement('p');
|
||||
p.textContent =
|
||||
heading +
|
||||
':' +
|
||||
(Array.isArray(value)
|
||||
? value.join('、')
|
||||
: typeof value === 'boolean'
|
||||
? value
|
||||
? '开启'
|
||||
: '关闭'
|
||||
: String(value ?? '未配置'));
|
||||
row.append(p);
|
||||
}
|
||||
dialog.querySelector('.aw-review-diff').append(row);
|
||||
}
|
||||
for (const risk of review.risks) {
|
||||
const li = document.createElement('li');
|
||||
li.textContent = risk;
|
||||
dialog.querySelector('.aw-review-risks').append(li);
|
||||
}
|
||||
dialog.querySelector('[data-review-expiry]').textContent =
|
||||
'授权仅适用于以上修改,有效至 ' +
|
||||
new Date(review.expiresAt).toLocaleTimeString('zh-CN') +
|
||||
'。配置变化后须重新审查。保存不会立即发信;单独执行收信或发信请到邮箱管理。';
|
||||
if (review.kind === 'manage_schedule') {
|
||||
dialog.setAttribute('aria-label', '审查定时任务');
|
||||
dialog.querySelector('h2').textContent = '审查定时任务';
|
||||
dialog.querySelector('[data-review-expiry]').textContent =
|
||||
'授权仅适用于以上任务与当前会话,配置或任务变化后须重新审查。任务到点会调用模型,但其他操作建议仍需另行授权。';
|
||||
}
|
||||
root.append(dialog);
|
||||
const previous = document.activeElement;
|
||||
dialog.showModal();
|
||||
return new Promise((resolve) => {
|
||||
let done = false,
|
||||
timer;
|
||||
const finish = (value) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearInterval(timer);
|
||||
dialog.close();
|
||||
dialog.remove();
|
||||
if (previous?.isConnected) previous.focus();
|
||||
resolve(value);
|
||||
};
|
||||
const approve = dialog.querySelector('[data-review-approve]'),
|
||||
check = dialog.querySelector('input'),
|
||||
expired = () => Date.now() >= review.expiresAt;
|
||||
timer = setInterval(() => {
|
||||
if (!isActive()) finish(null);
|
||||
else if (expired()) {
|
||||
approve.disabled = true;
|
||||
dialog.querySelector('[role=alert]').textContent = '授权已过期,请关闭并重新审查。';
|
||||
}
|
||||
}, 1000);
|
||||
check.onchange = () => (approve.disabled = !check.checked || expired());
|
||||
approve.onclick = () => {
|
||||
if (!check.checked || expired() || !isActive()) return;
|
||||
finish({ approvalToken: review.approvalToken });
|
||||
};
|
||||
dialog.querySelector('[data-review-cancel]').onclick = () => finish(null);
|
||||
dialog.oncancel = (e) => {
|
||||
e.preventDefault();
|
||||
finish(null);
|
||||
};
|
||||
dialog.onclose = () => finish(null);
|
||||
dialog.querySelector('[data-review-reject]').onclick = async (event) => {
|
||||
event.target.disabled = true;
|
||||
approve.disabled = true;
|
||||
try {
|
||||
await api('/assistant/conversations/' + id + '/actions/' + actionId + '/reject', {});
|
||||
finish(null);
|
||||
} catch (error) {
|
||||
dialog.querySelector('[role=alert]').textContent = error.message;
|
||||
event.target.disabled = false;
|
||||
approve.disabled = !check.checked || expired();
|
||||
}
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
+810
-52
@@ -1,58 +1,816 @@
|
||||
(() => {
|
||||
'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 disposed=false,currentId=sessionStorage.getItem(key)||'',conversation=null,events=[],revision=0,listRevision=0,loadChain=Promise.resolve(),listPage=1,listTotal=0,scope='active',managing=false,creating=false,watchTimer=null,eventClient=null,searchTimer=null,pendingRequest=null;
|
||||
const live=()=>!disposed&&isActive()&&container.isConnected;
|
||||
const layout=window.AssistantLayout.mount(container,{settings:data.settings,usage:data.usage,esc}),root=layout.root;
|
||||
let picker;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});
|
||||
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.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,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();}});
|
||||
function updateComposer(){const running=conversation?.turns.some(t=>t.status==='running');send.disabled=creating||!!running||!data.settings.enabled||!picker.usable||!!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.enabled){hint.append('助手已暂停,');const link=document.createElement('a');link.href='#assistant-settings';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.textContent='前往助手设置添加供应商或模型';hint.append(link);}else if(conversation?.archived||conversation?.deletedAt)hint.textContent='当前会话只读,请恢复或新建对话。';else if(conversation?.turns.length>=100)hint.textContent='当前会话已达 100 轮,请继续新对话。';}stop.hidden=!running;stop.disabled=!!conversation?.turns.some(t=>t.status==='running'&&t.cancelRequested);stop.textContent=stop.disabled?'正在停止…':'停止回复';}
|
||||
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轮。':'';}
|
||||
'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);}
|
||||
function loadCurrent(){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':''));if(!live()||currentId!==id||revision!==at)return;conversation=next;draw();return next;});loadChain=work;return work;}
|
||||
function drawList(){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 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() {
|
||||
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' : ''),
|
||||
);
|
||||
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;error.textContent='';root.querySelector('#assistant-search-note').textContent=next.search?.truncated?'仅搜索最近 '+next.search.maximum+' 个归档会话。':'';drawList();return true;}catch(e){if(owned()){root.querySelector('#assistant-scope').value=scope;showError(e);}return false;}finally{if(owned())drawPager();}}
|
||||
async function select(id){
|
||||
if(currentId)drafts.set(currentId,{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;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);}}
|
||||
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();
|
||||
taskManager.dispose();
|
||||
panel.dispose();
|
||||
layout.dispose();
|
||||
drafts.clear();
|
||||
pendingActions.clear();
|
||||
input.value = '';
|
||||
}
|
||||
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 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='';watch();try{await api('/assistant/conversations/'+id+'/actions/'+actionId+'/execute',{});}catch(e){if(live()&&id===currentId&&revision===at)showError(e);}finally{pendingActions.delete(actionId);if(live()&&id===currentId&&revision===at)await loadCurrent();}}
|
||||
async function sendMessage(event){event.preventDefault();if(await commands.consume())return;if(send.disabled||!input.value.trim())return;send.disabled=true;error.textContent='';const text=input.value,diagnostic=input.dataset.diagnostic?JSON.parse(input.dataset.diagnostic):undefined;let owner={id:currentId,at:revision};const owns=()=>live()&¤tId===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]);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}, {managedOutcome:true});if(!owns())return;if(input.value===text){input.value='';input.dataset.diagnostic='';}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();}}
|
||||
}
|
||||
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';});
|
||||
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.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();root.querySelectorAll('dialog').forEach(d=>{d.close();d.remove();});transcript.dispose();panel.dispose();layout.dispose();drafts.clear();pendingActions.clear();input.value='';}
|
||||
window.PageLifecycle?.onDispose(dispose);
|
||||
await Promise.all([refreshList(1),picker.refresh()]);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};
|
||||
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,
|
||||
};
|
||||
})();
|
||||
@@ -5,3 +5,45 @@
|
||||
|
||||
/* Provider and lifecycle controls, adapted to the DSH workspace. */
|
||||
.provider-row{display:flex;align-items:center;gap:10px;padding:16px 0;border-bottom:1px solid #e7ece7}.provider-row:last-child{border-bottom:0}.provider-editor{padding:20px;background:#f7faf6;border:1px solid #dce6dc;border-radius:12px}.provider-editor h3{font-size:16px;margin-bottom:16px}.assistant-provider-settings #provider-default{min-width:200px;max-width:100%}.assistant-provider-settings #provider-models{resize:vertical;min-height:120px}.assistant-workspace .aw-header{height:62px;min-height:62px}.assistant-workspace .aw-back,.tools-return{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;min-width:110px;padding:9px 14px!important;font-size:14px!important;font-weight:650;background:#eaf3ed;border:1px solid #8fb99c;color:#225e3c;border-radius:8px;text-decoration:none}.assistant-workspace .aw-back:hover,.tools-return:hover{background:#dbece0;color:#174c2c;border-color:#5c9971}.aw-narrow .aw-back{display:inline-flex!important;min-width:110px}.aw-narrow .aw-model{display:none}.aw-narrow .aw-header{gap:6px}.aw-narrow .aw-header strong{font-size:12px;white-space:nowrap}.aw-compose-tools{position:relative}.aw-model-picker{max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#326347}.aw-narrow .aw-model-picker{max-width:125px;font-size:10px}.aw-model-popup{position:absolute;bottom:calc(100% + 12px);left:0;width:min(430px,calc(100vw - 32px));max-height:340px;padding:12px;border:1px solid #dce6dc;border-radius:12px;background:#fff;box-shadow:0 8px 32px #24452b22;z-index:25}.aw-model-options{max-height:250px;overflow:auto;margin-top:8px}.aw-model-option{display:block;width:100%;text-align:left;border:0;border-radius:7px;background:transparent;padding:9px 12px;color:#355e43;font-size:13px}.aw-model-option:hover,.aw-model-option[aria-selected=true]{background:#edf5ed}.aw-conversation-row{position:relative}.aw-conversation-row>[data-assistant-conversation]{padding-right:38px!important}.aw-conversation-menu{position:absolute;top:8px;right:8px;z-index:4}.aw-conversation-menu summary{display:grid;place-items:center;cursor:pointer;list-style:none;width:28px;height:28px;border-radius:6px;font-size:21px;color:#54785e}.aw-conversation-menu summary::-webkit-details-marker{display:none}.aw-conversation-menu summary:hover{background:#dfebe1}.aw-conversation-menu>div{position:absolute;right:0;top:30px;width:155px;padding:5px;border:1px solid #dce5dc;border-radius:8px;background:#fff;box-shadow:0 5px 18px #234a2920}.aw-conversations .aw-conversation-menu button{font-size:12px;padding:8px!important;white-space:nowrap;margin:0;border-radius:5px}.aw-conversation-menu[open]{z-index:10}@media(max-width:767px){.provider-editor{padding:14px}.provider-row{gap:5px}.provider-row strong{overflow-wrap:anywhere}.provider-row .btn{padding:6px}.assistant-provider-settings .card-body{padding:16px}.aw-narrow .aw-compose-tools{gap:5px}.aw-narrow .aw-compose-tools>.small{display:none}}
|
||||
/* Composer and scoped settings review */
|
||||
#assistant-compose{border:1px solid #dce3df;border-radius:22px;background:#f8faf9;padding:6px 10px 10px;box-shadow:0 2px 8px #13271b05}
|
||||
#assistant-compose:focus-within{border-color:#a3b3aa;box-shadow:0 0 0 3px #26392b08}
|
||||
#assistant-compose .aw-input-wrap textarea{background:transparent;border:0;box-shadow:none;padding:10px 8px;min-height:58px;border-radius:16px}
|
||||
#assistant-compose .aw-compose-tools{margin-top:2px;padding:0 2px}
|
||||
.aw-submit-icon{margin-left:auto;display:inline-flex;align-items:center;justify-content:center;flex:0 0 42px;width:42px;height:42px;border:0;border-radius:50%;background:#202522;color:#fff;cursor:pointer;transition:background .15s,transform .15s}
|
||||
.aw-submit-icon:hover:enabled{background:#3c4941}.aw-submit-icon:active:enabled{transform:scale(.95)}.aw-submit-icon:disabled{background:#e3e8e5;color:#a1aaa5;cursor:default}.aw-submit-icon:focus-visible{outline:3px solid #6b9980;outline-offset:3px}.aw-submit-icon[hidden]{display:none!important}
|
||||
.aw-settings-review{width:min(680px,calc(100vw - 24px));max-height:calc(100dvh - 32px);padding:0;border:1px solid #dce5de;border-radius:18px;color:#253b36;box-shadow:0 24px 80px #12261b40}
|
||||
.aw-settings-review::backdrop{background:#14281e66}.aw-settings-review header,.aw-settings-review footer{padding:18px 22px;background:#f7faf7}.aw-settings-review h2{font-size:19px;margin:0 0 8px}.aw-settings-review h3{font-size:14px;margin:10px 0}.aw-settings-review header p{margin:0}.aw-review-body{padding:12px 22px;overflow:auto;max-height:calc(100dvh - 230px)}.aw-review-change{padding:12px;border:1px solid #e0e7e1;border-radius:10px;margin-bottom:8px;overflow-wrap:anywhere}.aw-review-change p{margin:6px 0;font-size:13px}.aw-review-change p:last-child{color:#28613e}.aw-review-risks{padding:12px 12px 12px 32px;background:#fff7e9;border:1px solid #e9d5ac;border-radius:10px;color:#73551e;font-size:13px}.aw-review-risks li{margin:6px 0}.aw-settings-review footer{display:flex;gap:8px;justify-content:flex-end;border-top:1px solid #e2e9e3;flex-wrap:wrap}.aw-config-summary{padding:10px;background:#f6faf6;border:1px solid #dee8df;border-radius:8px;margin:10px 0;overflow-wrap:anywhere}.aw-config-summary p{margin-bottom:6px}.aw-config-summary ul{padding-left:18px}.aw-context details{overflow-wrap:anywhere}.aw-context details pre{font-size:11px}
|
||||
@media(max-width:600px){.aw-settings-review header,.aw-settings-review footer{padding:14px}.aw-review-body{padding:10px 14px}.aw-submit-icon{flex-basis:42px;width:42px;height:42px}}
|
||||
/* Full model labels and jump to latest message */
|
||||
.aw-compose-tools .aw-model-picker,.aw-narrow .aw-compose-tools .aw-model-picker{max-width:none;min-width:0;flex:0 1 auto;white-space:normal;overflow:visible;text-overflow:clip;overflow-wrap:anywhere;word-break:break-word;text-align:left;line-height:1.5}
|
||||
#assistant-new-progress.aw-scroll-latest{display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;padding:0;border-radius:50%;border:1px solid #d4ddd7;background:#fff;color:#38483e;box-shadow:0 2px 10px #1735221a}
|
||||
#assistant-new-progress[hidden]{display:none!important}#assistant-new-progress:focus-visible{outline:3px solid #85a68d;outline-offset:2px}
|
||||
.aw-attachments{display:grid;gap:6px;max-height:170px;overflow:auto}.aw-attachment{display:flex;align-items:center;gap:6px;padding:8px;background:#fff;border:1px solid #dde6df;border-radius:10px;font-size:11px}.aw-attachment>div{flex:1;min-width:0;overflow-wrap:anywhere}.aw-attachment strong,.aw-attachment span{display:block}.aw-attachment span{color:#77847c;margin-top:3px}.aw-attachment .btn{padding:4px 7px}.aw-attach-button{display:inline-flex;align-items:center;justify-content:center;min-width:30px;min-height:30px}#assistant-attachment-note{font-size:10px;margin:6px 0;line-height:1.5}.aw-sent-attachments{display:grid;gap:5px;margin-top:8px;font-size:11px;color:#5d7567}.aw-attachment-preview pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px;line-height:1.7}
|
||||
.aw-image-preview{display:block;max-width:100%;max-height:55vh;object-fit:contain;border-radius:8px}.aw-attachment-icon{display:inline-flex;flex:0 0 18px;color:#688273}.aw-remove-attachment{display:inline-flex;align-items:center;justify-content:center}.aw-attach-button>svg{width:20px;height:20px}.aw-sent-image{display:block;max-width:min(320px,100%);max-height:240px;object-fit:contain;border-radius:10px;margin-top:8px}
|
||||
/* Unified workspace controls and an in-panel collapse affordance. */
|
||||
.assistant-workspace{--aw-control-size:40px}
|
||||
.assistant-workspace .aw-header{height:60px;min-height:60px;padding:9px 14px;gap:10px}
|
||||
.assistant-workspace .aw-header>.btn{display:inline-flex;align-items:center;justify-content:center;height:var(--aw-control-size);min-height:var(--aw-control-size);padding:0;flex-shrink:0}
|
||||
.assistant-workspace .aw-header>[data-aw-left],.assistant-workspace .aw-header>[data-aw-right]{width:var(--aw-control-size);border:0;border-radius:10px;background:transparent;color:#597164}
|
||||
.assistant-workspace .aw-header>.aw-back{height:var(--aw-control-size);min-height:var(--aw-control-size);padding:0 12px!important;gap:7px;border-radius:10px;line-height:20px}
|
||||
#assistant-compose .aw-compose-tools{display:grid;grid-template-columns:var(--aw-control-size) var(--aw-control-size) minmax(0,1fr) var(--aw-control-size);gap:6px;align-items:center;padding:0;margin-top:4px}
|
||||
#assistant-attach,#assistant-commands{width:var(--aw-control-size);height:var(--aw-control-size);min-height:var(--aw-control-size);padding:0;display:inline-flex;align-items:center;justify-content:center;border:0;border-radius:10px;background:transparent;color:#5f7368;box-shadow:none}
|
||||
#assistant-attach svg{width:18px;height:18px}#assistant-commands{font-size:18px;font-weight:400;line-height:1}
|
||||
#assistant-model-picker{width:100%;min-height:var(--aw-control-size);padding:4px 8px;border:0;border-radius:10px;background:transparent;color:#3d5d4a;box-shadow:none;font-size:12px;line-height:16px}
|
||||
#assistant-attach:hover:enabled,#assistant-commands:hover:enabled,#assistant-model-picker:hover:enabled,.assistant-workspace .aw-header>[data-aw-right]:hover,.assistant-workspace .aw-header>[data-aw-left]:hover{background:#eaf0ec}
|
||||
#assistant-send,#assistant-stop{grid-column:4;grid-row:1;width:var(--aw-control-size);height:var(--aw-control-size);min-height:var(--aw-control-size);margin:0;justify-self:end}
|
||||
.aw-shortcut-note{font-size:10px;line-height:14px;color:#8b978f;text-align:right;margin:5px 4px 0}
|
||||
.aw-context-header{display:flex;align-items:center;gap:4px;position:sticky;top:0;z-index:3;background:#fafbf9;border-bottom:1px solid var(--aw-border);padding-right:6px;flex:0 0 auto}
|
||||
.aw-context-header .aw-context-tabs{position:static;flex:1;min-width:0;border:0;padding:8px 4px;gap:0}
|
||||
.aw-context-close{display:inline-flex;align-items:center;justify-content:center;flex:0 0 32px;width:32px;height:32px;padding:0;border:0;border-radius:8px;background:transparent;color:#637c6c;cursor:pointer}.aw-context-close:hover{background:#e6eee7}.aw-context-close:focus-visible{outline:2px solid #6f9a7e;outline-offset:2px}
|
||||
.aw-narrow #assistant-model-picker{font-size:11px;line-height:16px;max-width:none}.aw-narrow .aw-shortcut-note{display:none}
|
||||
.aw-narrow .aw-header{padding:9px 10px;gap:6px}
|
||||
#assistant-model-picker{justify-content:flex-start;text-align:left}
|
||||
.aw-narrow .aw-header>[data-aw-right]{margin-left:auto}
|
||||
|
||||
.aw-schedule-dialog{width:min(560px,calc(100vw - 24px));max-height:90dvh;overflow:auto}.aw-schedule-dialog .form-label{display:block;margin-bottom:12px}.aw-schedule-prompt{white-space:pre-wrap;overflow-wrap:anywhere}.aw-context-tabs{min-width:0}.aw-context-tabs button{padding-inline:9px}
|
||||
|
||||
.aw-body[hidden],.aw-task-page[hidden]{display:none!important}.aw-task-page{flex:1;min-height:0;overflow:auto;padding:24px clamp(16px,4vw,48px);background:#fafbf9}.aw-task-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;max-width:1200px;margin:0 auto 20px}.aw-task-heading h2{margin:16px 0 8px;font-size:22px}.aw-task-heading p{margin:0}.aw-task-filters{display:flex;gap:12px;flex-wrap:wrap;max-width:1200px;margin:0 auto 16px}.aw-task-filters [role=group]{display:flex;gap:4px}.aw-task-filters [aria-pressed=true]{background:#e1ece5;color:#245c3d}.aw-task-filters input{flex:1 1 220px;width:auto;min-width:0}.aw-task-filters select{flex:0 1 240px;width:auto;min-width:0}.aw-task-page>[data-task-message]{max-width:1200px;margin:0 auto 16px}.aw-task-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,340px),1fr));gap:16px;max-width:1200px;margin:auto}.aw-task-row{padding:20px;border:1px solid #dfe7e0;border-radius:14px;background:white;min-width:0;overflow-wrap:anywhere}.aw-task-row-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:12px}.aw-task-row-heading strong{font-size:15px}.aw-task-row-heading .aw-state{white-space:nowrap}.aw-task-excerpt{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;white-space:pre-wrap}.aw-task-empty{grid-column:1/-1;padding:50px 16px;text-align:center}.aw-task-row .btn-list{margin-bottom:8px}.aw-schedule-dialog dd{white-space:pre-wrap;overflow-wrap:anywhere;margin-bottom:12px}@media(max-width:600px){.aw-task-heading{align-items:flex-start;flex-direction:column}.aw-task-heading>.btn-list{width:100%}.aw-task-heading>.btn-list>.btn{flex:1}.aw-task-filters{flex-direction:column}.aw-task-filters input,.aw-task-filters select{flex:auto;width:100%}}
|
||||
|
||||
.aw-permissions-dialog{width:min(900px,calc(100vw - 24px));max-height:90dvh;overflow:auto}.aw-permissions-dialog td,.aw-permissions-dialog p{overflow-wrap:anywhere}
|
||||
Reference in new issue
Block a user