Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,309 @@
|
||||
'use strict';
|
||||
|
||||
(() => {
|
||||
const card = document.getElementById('aiReviewCard');
|
||||
if (!card) return;
|
||||
const heading = document.getElementById('aiReviewHeading');
|
||||
const summary = document.getElementById('aiReviewSummary');
|
||||
const plan = document.getElementById('aiReviewPlan');
|
||||
const before = document.getElementById('aiReviewBefore');
|
||||
const after = document.getElementById('aiReviewAfter');
|
||||
const diff = document.getElementById('aiReviewDiff');
|
||||
const status = document.getElementById('aiReviewStatus');
|
||||
const apply = document.getElementById('aiReviewApply');
|
||||
const applyLabel = document.getElementById('aiReviewApplyLabel');
|
||||
const dismiss = document.getElementById('aiReviewDismiss');
|
||||
const dismissLabel = document.getElementById('aiReviewDismissLabel');
|
||||
const retry = document.getElementById('aiReviewRetry');
|
||||
const server = document.documentElement.dataset.bot;
|
||||
const labels = {
|
||||
start: 'Start server', stop: 'Stop server', restart: 'Restart server', kill: 'Force stop server',
|
||||
console_command: 'Run console command', write_file: 'Edit file', replace_file: 'Replace entire file', create_file: 'Create file',
|
||||
revert_file: 'Revert file edit',
|
||||
create_folder: 'Create folder', delete_file: 'Delete file', create_backup: 'Create backup',
|
||||
restore_backup: 'Restore backup', delete_backup: 'Delete backup',
|
||||
};
|
||||
const actionStatuses = { applied: 'Confirmed', dismissed: 'Declined', refused: 'Refused', unknown: 'Unconfirmed' };
|
||||
const acknowledgementActions = new Set(['start', 'stop', 'restart', 'kill', 'console_command']);
|
||||
let selected = null;
|
||||
let preview = null;
|
||||
let loading = false;
|
||||
let version = 0;
|
||||
const resolved = new Set();
|
||||
const pending = new Set();
|
||||
|
||||
function bind(jobId, thread, messages) {
|
||||
if (messages) bindActivity(thread, messages);
|
||||
const last = thread?.lastElementChild;
|
||||
const host = last?.classList.contains('ai') && last.querySelector(':scope > .ai-message-body');
|
||||
const next = host && /^\d{1,20}$/.test(String(jobId)) && !resolved.has(String(jobId)) ? String(jobId) : null;
|
||||
if (next && card.parentElement !== host) host.append(card);
|
||||
card.hidden = !next;
|
||||
if (next === selected) return;
|
||||
selected = next;
|
||||
version += 1;
|
||||
loading = false;
|
||||
preview = null;
|
||||
if (selected) return loadPreview();
|
||||
}
|
||||
|
||||
function visibleText(value) {
|
||||
return value.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff]/gu,
|
||||
(character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
||||
}
|
||||
|
||||
function renderActivity(host, actions, append = false) {
|
||||
if (!host || !actions?.length) return;
|
||||
let activity = host.querySelector(':scope > .agent-action-log');
|
||||
if (!activity) {
|
||||
activity = document.createElement('section');
|
||||
activity.className = 'agent-action-log';
|
||||
activity.setAttribute('aria-label', 'Agent actions');
|
||||
const title = document.createElement('h3');
|
||||
title.textContent = 'Actions';
|
||||
activity.append(title);
|
||||
activity.append(document.createElement('ol'));
|
||||
host.prepend(activity);
|
||||
}
|
||||
const list = activity.lastElementChild;
|
||||
if (!append) list.textContent = '';
|
||||
for (const entry of actions) {
|
||||
if (!Object.hasOwn(labels, entry.action) || !Object.hasOwn(actionStatuses, entry.status)) continue;
|
||||
const item = document.createElement('li');
|
||||
const headline = document.createElement('strong');
|
||||
headline.textContent = `${labels[entry.action]}: ${visibleText(entry.target)}`;
|
||||
const outcome = document.createElement('span');
|
||||
outcome.className = 'agent-action-status';
|
||||
outcome.textContent = entry.status === 'applied' && acknowledgementActions.has(entry.action) ? 'Sent' : actionStatuses[entry.status];
|
||||
item.append(headline, outcome);
|
||||
if (typeof entry.command === 'string') {
|
||||
const command = document.createElement('code');
|
||||
command.textContent = visibleText(entry.command);
|
||||
item.append(command);
|
||||
}
|
||||
const detail = document.createElement('span');
|
||||
const counts = Number.isInteger(entry.addedLines) && Number.isInteger(entry.removedLines)
|
||||
? ` +${entry.addedLines} / -${entry.removedLines} lines.` : '';
|
||||
detail.className = 'agent-action-detail';
|
||||
detail.textContent = `${typeof entry.detail === 'string' ? visibleText(entry.detail) : ''}${counts}`;
|
||||
item.append(detail);
|
||||
list.append(item);
|
||||
}
|
||||
}
|
||||
|
||||
function bindActivity(thread, messages) {
|
||||
if (!thread?.children) return;
|
||||
for (const [index, message] of messages.entries()) {
|
||||
if (message.role === 'ai' && message.agentActions?.length) {
|
||||
renderActivity(thread.children[index]?.querySelector(':scope > .ai-message-body'), message.agentActions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setBlock(block, value) {
|
||||
block.parentElement.hidden = typeof value !== 'string';
|
||||
block.textContent = typeof value === 'string' ? visibleText(value) || '(empty)' : '';
|
||||
}
|
||||
|
||||
function setDiff(block, value) {
|
||||
block.textContent = '';
|
||||
block.parentElement.hidden = typeof value !== 'string';
|
||||
if (typeof value !== 'string') return;
|
||||
const lines = value.split('\n');
|
||||
let inHunk = false;
|
||||
for (const line of lines.slice(0, 600)) {
|
||||
const row = document.createElement('span');
|
||||
const hunk = line.startsWith('@@');
|
||||
inHunk ||= hunk;
|
||||
const kind = hunk ? 'hunk' : inHunk && line.startsWith('+') ? 'add' : inHunk && line.startsWith('-') ? 'remove' : '';
|
||||
row.className = `agent-review-line${kind ? ` agent-review-line-${kind}` : ''}`;
|
||||
row.textContent = visibleText(line);
|
||||
block.append(row);
|
||||
}
|
||||
if (lines.length > 600) block.append('\nOpen the full file previews to see the remaining lines.');
|
||||
}
|
||||
|
||||
function describe(proposal, showServer = true) {
|
||||
const lines = showServer ? [`Server: ${server}`] : [];
|
||||
if (proposal.path) lines.push(`Path: ${proposal.path}`);
|
||||
if (proposal.command) lines.push(`Command: ${proposal.command}`);
|
||||
if (proposal.name) lines.push(`Name: ${proposal.name}`);
|
||||
if (proposal.description) lines.push(`Description: ${proposal.description}`);
|
||||
if (proposal.backup) lines.push(`Backup ID: ${proposal.backup}`);
|
||||
if (proposal.action === 'restore_backup') lines.push(proposal.deleteOldFiles ? 'Replace existing server files.' : 'Merge backup into existing files.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function appendFileDetails(item, label, value, render, open = false) {
|
||||
if (typeof value !== 'string') return;
|
||||
const details = document.createElement('details');
|
||||
details.open = open;
|
||||
const title = document.createElement('summary');
|
||||
title.textContent = label;
|
||||
const block = document.createElement('pre');
|
||||
details.append(title);
|
||||
details.append(block);
|
||||
item.append(details);
|
||||
render(block, value);
|
||||
}
|
||||
|
||||
function showPlan(steps) {
|
||||
for (const step of steps) {
|
||||
const item = document.createElement('li');
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = labels[step.proposal.action];
|
||||
const target = document.createElement('pre');
|
||||
target.className = 'agent-review-target';
|
||||
target.textContent = describe(step.proposal, false);
|
||||
item.append(title);
|
||||
item.append(target);
|
||||
appendFileDetails(item, 'Changes', step.diff, setDiff, true);
|
||||
appendFileDetails(item, 'Current file', step.before, setBlock);
|
||||
appendFileDetails(item, 'Proposed file', step.proposedText ?? step.proposal.content, setBlock, !step.diff);
|
||||
plan.append(item);
|
||||
}
|
||||
plan.hidden = false;
|
||||
}
|
||||
|
||||
function route(jobId) { return `/api/ai/jobs/${jobId}/review`; }
|
||||
|
||||
async function readResponse(response) {
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw Object.assign(new Error(body.error || 'Action review is unavailable.'), { status: response.status });
|
||||
return body;
|
||||
}
|
||||
|
||||
function refreshChat(result) {
|
||||
if (/^\d{1,20}$/.test(String(result.chatId))) {
|
||||
document.dispatchEvent(new CustomEvent('adpanel:agent-review-settled', { detail: {
|
||||
chatId: result.chatId, conclusionJobId: result.conclusionJobId,
|
||||
} }));
|
||||
}
|
||||
}
|
||||
|
||||
function showResult(jobId, result, recovered = false) {
|
||||
resolved.add(jobId);
|
||||
if (resolved.size > 64) resolved.delete(resolved.values().next().value);
|
||||
if (selected === jobId) {
|
||||
renderActivity(card.parentElement, serverAgentHistory.readActions(result.activity), !recovered);
|
||||
if ((result.state === 'applied' || result.state === 'dismissed') && result.receiptSaved !== false) bind(null);
|
||||
else {
|
||||
status.textContent = result.receipt || serverAgentHistory.reviewOutcomeMessage(result.code || result.state) || serverAgentHistory.reviewOutcomeMessage('unknown');
|
||||
if (result.receiptSaved === false) status.textContent += ' The panel could not save this result to the chat.';
|
||||
}
|
||||
}
|
||||
refreshChat(result);
|
||||
}
|
||||
|
||||
async function recoverResult(jobId) {
|
||||
const deadline = AbortSignal.timeout(30_000);
|
||||
for (let delay = 500; !deadline.aborted; delay = Math.min(delay * 2, 4_000)) {
|
||||
const { job } = await readResponse(await fetch(`/api/ai/jobs/${jobId}`, {
|
||||
cache: 'no-store', signal: AbortSignal.any([deadline, AbortSignal.timeout(10_000)]),
|
||||
}));
|
||||
if (String(job?.id) !== jobId || job.review_server !== server || !job.review_state) return false;
|
||||
if (job.review_state !== 'applying') {
|
||||
const receipt = job.review_state === 'expired' || serverAgentHistory.isProposalMessage(job.content) ? undefined : job.content;
|
||||
showResult(jobId, { state: job.review_state, chatId: job.chat_id, conclusionJobId: job.review_conclusion_job_id,
|
||||
receipt, activity: job.agent_actions }, true);
|
||||
return true;
|
||||
}
|
||||
if (selected !== jobId) return true;
|
||||
status.textContent = 'Waiting for the action result...';
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function loadPreview() {
|
||||
if (!selected || loading) return;
|
||||
const jobId = selected;
|
||||
const view = version;
|
||||
loading = true;
|
||||
preview = null;
|
||||
apply.disabled = true;
|
||||
dismiss.disabled = true;
|
||||
applyLabel.textContent = 'Accept';
|
||||
dismissLabel.textContent = 'Decline';
|
||||
retry.hidden = true;
|
||||
heading.textContent = 'Proposed action';
|
||||
summary.textContent = '';
|
||||
plan.hidden = true;
|
||||
plan.textContent = '';
|
||||
setBlock(before, null);
|
||||
setBlock(after, null);
|
||||
setDiff(diff, null);
|
||||
status.textContent = pending.has(jobId) ? 'Waiting for the action result...' : 'Loading preview...';
|
||||
if (pending.has(jobId)) { loading = false; return; }
|
||||
try {
|
||||
const data = await readResponse(await fetch(`${route(jobId)}?${new URLSearchParams({ server })}`, {
|
||||
cache: 'no-store', signal: AbortSignal.timeout(15000),
|
||||
}));
|
||||
if (view !== version) return;
|
||||
const grouped = Array.isArray(data.plan);
|
||||
const steps = grouped ? data.plan : [data];
|
||||
const versions = grouped ? data.expectedSha256 : [data.expectedSha256];
|
||||
if (data.server !== server || !data.token || (grouped && (steps.length < 2 || steps.length > 5)) ||
|
||||
steps.some((step) => !Object.hasOwn(labels, step?.proposal?.action)) || (data.expectedSha256 !== null &&
|
||||
(!Array.isArray(versions) || versions.length !== steps.length || versions.some((value) => typeof value !== 'string')))) {
|
||||
throw new Error('Invalid action review.');
|
||||
}
|
||||
if (grouped) {
|
||||
heading.textContent = `File plan (${steps.length} steps)`;
|
||||
summary.textContent = `Server: ${server}`;
|
||||
applyLabel.textContent = 'Accept plan';
|
||||
dismissLabel.textContent = 'Decline plan';
|
||||
showPlan(steps);
|
||||
} else {
|
||||
heading.textContent = labels[data.proposal.action] + (Number.isInteger(data.remaining) && data.remaining > 0 ? ` (${data.remaining} more after this)` : '');
|
||||
summary.textContent = describe(data.proposal);
|
||||
setBlock(before, data.before);
|
||||
setBlock(after, data.proposedText ?? data.proposal.content);
|
||||
setDiff(diff, data.diff);
|
||||
}
|
||||
const notices = [];
|
||||
if (steps.some(({ proposal }) => proposal.action === 'replace_file')) notices.push('Replacement removes settings not present in the proposed file.');
|
||||
if (grouped) notices.push('A failure stops the plan. Changes already applied are kept.');
|
||||
status.textContent = data.previewError || notices.join(' ');
|
||||
preview = { jobId, view, token: data.token, expectedSha256: data.expectedSha256, grouped };
|
||||
apply.disabled = data.expectedSha256 === null;
|
||||
dismiss.disabled = false;
|
||||
} catch (error) {
|
||||
if (view === version) {
|
||||
status.textContent = error.message || 'Could not load the preview.';
|
||||
retry.hidden = false;
|
||||
}
|
||||
} finally {
|
||||
if (view === version) loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function decide(event, decision) {
|
||||
if (!event.isTrusted || !preview || preview.view !== version || pending.has(preview.jobId)) return;
|
||||
if (decision === 'apply' && preview.expectedSha256 === null) return;
|
||||
const { jobId, token, expectedSha256, grouped } = preview;
|
||||
preview = null;
|
||||
pending.add(jobId);
|
||||
apply.disabled = dismiss.disabled = true;
|
||||
status.textContent = decision === 'apply' ? (grouped ? 'Applying plan...' : 'Applying...') : 'Declining...';
|
||||
try {
|
||||
const result = await readResponse(await fetch(route(jobId), {
|
||||
method: 'POST', cache: 'no-store', signal: AbortSignal.timeout(31 * 60_000),
|
||||
headers: { 'Content-Type': 'application/json', 'x-action-token': token },
|
||||
body: JSON.stringify({ server, decision, expectedSha256 }),
|
||||
}));
|
||||
showResult(jobId, result);
|
||||
} catch (error) {
|
||||
if ((!error.status || error.status >= 500 || error.status === 409) && await recoverResult(jobId).catch(() => false)) return;
|
||||
if (selected === jobId) {
|
||||
status.textContent = !error.status || error.status >= 500 ? serverAgentHistory.reviewOutcomeMessage('unknown') : error.message;
|
||||
if (error.status === 403 || error.status === 429) retry.hidden = false;
|
||||
}
|
||||
} finally { pending.delete(jobId); }
|
||||
}
|
||||
|
||||
apply.addEventListener('click', (event) => decide(event, 'apply'));
|
||||
dismiss.addEventListener('click', (event) => decide(event, 'dismiss'));
|
||||
retry.addEventListener('click', (event) => { if (event.isTrusted) void loadPreview(); });
|
||||
window.adpanelAgentReview = Object.freeze({ bind });
|
||||
})();
|
||||
Reference in new issue
Block a user