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,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);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user