mirror of
https://github.com/agent0ai/agent-zero.git
synced 2026-12-04 17:38:45 +00:00
Use the compact editor, memory recall, and notification layouts for saved calls. Summarize default skill listings and configured vision analysis, and keep skill instructions and reference bodies in View details. Preserve recorded headings, Action fields, and full recorded results and arguments. Verify both saved and current card formats with WebUI regression coverage.
283 lines
16 KiB
Python
283 lines
16 KiB
Python
"""Render real modules without a backend, sidebar mount, or user state."""
|
|
import mimetypes
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse
|
|
|
|
import pytest
|
|
|
|
playwright = pytest.importorskip("playwright.sync_api")
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
@pytest.fixture
|
|
def page():
|
|
def serve(route):
|
|
path = urlparse(route.request.url).path
|
|
if path == "/":
|
|
route.fulfill(content_type="text/html", body='''<!doctype html>
|
|
<script>globalThis.runtimeInfo = {webuiExtensions: {js: {}, html: {}}};</script>
|
|
<div id="chat-history"></div>''')
|
|
return
|
|
asset = ROOT / (path.lstrip("/") if path.startswith(("/plugins/", "/extensions/")) else "webui/" + path.lstrip("/"))
|
|
if asset.is_file():
|
|
route.fulfill(path=asset, content_type=mimetypes.guess_type(asset)[0])
|
|
else:
|
|
route.abort()
|
|
with playwright.sync_playwright() as p:
|
|
try:
|
|
browser = p.chromium.launch()
|
|
except playwright.Error as error:
|
|
if "Executable doesn't exist" in str(error):
|
|
pytest.skip("An installed Playwright Chromium is required.")
|
|
raise
|
|
page = browser.new_page()
|
|
page.route("**/*", serve)
|
|
page.goto("http://compat.test/")
|
|
yield page
|
|
browser.close()
|
|
|
|
|
|
def test_first_snapshot_retains_tasks_and_selection_before_sidebar_mount(page):
|
|
result = page.evaluate('''async () => {
|
|
const ui = await import('/index.js');
|
|
const {getStore} = await import('/js/AlpineStore.js');
|
|
const registeredBeforeSnapshot = !!getStore('tasks');
|
|
ui.setContext('saved-task');
|
|
const snapshot = {context:'saved-task', contexts:[{id:'ordinary-chat', created_at:1}],
|
|
tasks:[{id:'saved-task', created_at:2}], logs:[], log_version:0, log_guid:'fixture'};
|
|
await ui.applySnapshot(snapshot);
|
|
await ui.applySnapshot({...snapshot, contexts:null, tasks:null});
|
|
const tasks = getStore('tasks');
|
|
const chats = getStore('chats');
|
|
return {registeredBeforeSnapshot, ids:tasks?.tasks.map(t => t.id),
|
|
context:ui.getContext(), selected:tasks?.selected, selectedChat:chats.selectedContext?.id};
|
|
}''')
|
|
assert result == {"registeredBeforeSnapshot": True, "ids": ["saved-task"], "context": "saved-task", "selected": "saved-task", "selectedChat": "saved-task"}
|
|
|
|
|
|
@pytest.mark.parametrize("attachments", [False, True])
|
|
@pytest.mark.parametrize("during_render", [False, True])
|
|
def test_welcome_send_survives_first_snapshot_until_backend_log_arrives(page, attachments, during_render):
|
|
page.route("**/hold-first-render.js", lambda route: route.fulfill(
|
|
content_type="text/javascript", body='''export default async () => {
|
|
const hold = globalThis.holdFirstRender;
|
|
if (hold) {
|
|
globalThis.holdFirstRender = null;
|
|
globalThis.renderStarted();
|
|
await hold;
|
|
}
|
|
};'''))
|
|
result = page.evaluate('''async ({attachments, duringRender}) => {
|
|
const ui = await import('/index.js');
|
|
const {getStore} = await import('/js/AlpineStore.js');
|
|
const input = getStore('chatInput');
|
|
const originalFetch = globalThis.fetch;
|
|
let completeSend, messageId, requestStarted;
|
|
const sending = new Promise(resolve => { requestStarted = resolve; });
|
|
let releaseRender;
|
|
const rendering = new Promise(resolve => { globalThis.renderStarted = resolve; });
|
|
if (duringRender) {
|
|
globalThis.holdFirstRender = new Promise(resolve => { releaseRender = resolve; });
|
|
runtimeInfo.webuiExtensions.js.get_process_step_types = ['/hold-first-render.js'];
|
|
}
|
|
globalThis.fetch = (url, options) => {
|
|
if (url === '/api/csrf_token') return Promise.resolve(Response.json({ok:true, token:'fixture'}));
|
|
if (url === '/api/chat_create') return Promise.resolve(Response.json({ok:true, ctxid:'new-chat'}));
|
|
if (url === '/api/message_async') {
|
|
messageId = options.body instanceof FormData
|
|
? options.body.get('message_id') : JSON.parse(options.body).message_id;
|
|
requestStarted();
|
|
return new Promise(resolve => { completeSend = resolve; });
|
|
}
|
|
return originalFetch(url, options);
|
|
};
|
|
input.message = 'First Welcome prompt';
|
|
if (attachments) getStore('chatAttachments').getAttachmentsForSending = () => [
|
|
{file:new File(['fixture'], 'fixture.txt')}];
|
|
const send = input.sendMessage();
|
|
await (duringRender ? rendering : sending);
|
|
const snapshot = {context:'new-chat', contexts:[{id:'new-chat'}], tasks:[],
|
|
logs:[{no:0, id:'greeting', type:'response', content:'Hello!'}],
|
|
log_version:1, log_guid:'fixture'};
|
|
const userRows = () => document.querySelectorAll('#chat-history .message-user').length;
|
|
const applying = ui.applySnapshot(snapshot);
|
|
if (duringRender) releaseRender();
|
|
await applying;
|
|
await sending;
|
|
const whileSending = userRows();
|
|
const order = [...document.querySelectorAll('#chat-history .message-container')]
|
|
.map(element => element.id);
|
|
completeSend(Response.json({context:'new-chat'}));
|
|
await send;
|
|
const confirmed = {no:1, id:messageId, type:'user', content:'Server confirmed prompt', kvps:{}};
|
|
await ui.applySnapshot({...snapshot, logs:[confirmed], log_version:2});
|
|
const afterConfirmation = userRows();
|
|
const confirmedText = document.querySelector('#chat-history .message-user .message-text')?.textContent;
|
|
await ui.applySnapshot({...snapshot, log_version:3});
|
|
return {whileSending, greetingFirst:order[0] === 'message-greeting',
|
|
userLast:order.at(-1) === `message-${messageId}`, afterConfirmation,
|
|
confirmedText, afterRemoval:userRows()};
|
|
}''', {"attachments": attachments, "duringRender": during_render})
|
|
assert result == {"whileSending": 1, "greetingFirst": True, "userLast": True,
|
|
"afterConfirmation": 1, "confirmedText": "Server confirmed prompt",
|
|
"afterRemoval": 0}
|
|
|
|
|
|
@pytest.mark.parametrize("tool_name,code", [("skills_tool", "SKL"), ("vision_load", "EYE"), ("search_engine", "SRC"), ("memory_load", "MEM"), ("memory_save", "MEM"), ("memory_delete", "MEM"), ("memory_forget", "MEM")])
|
|
def test_saved_tool_logs_keep_their_specialized_renderer(page, tool_name, code):
|
|
result = page.evaluate('''async ({tool_name}) => {
|
|
runtimeInfo.webuiExtensions.js.get_tool_message_handler = [
|
|
'/extensions/webui/get_tool_message_handler/skills-handler.js',
|
|
'/extensions/webui/get_tool_message_handler/vision-handler.js',
|
|
'/plugins/_search_engine/extensions/webui/get_tool_message_handler/search-engine-handler.js',
|
|
'/plugins/_memory/extensions/webui/get_tool_message_handler/memory-handler.js'];
|
|
const {drawMessageTool} = await import('/js/messages.js');
|
|
const log = {id:'legacy', no:0, type:'tool', heading:'Saved tool call', content:'Saved result',
|
|
kvps:{_tool_name:tool_name, query:'original query'}};
|
|
const {element} = await drawMessageTool(log);
|
|
document.getElementById('chat-history').append(element);
|
|
return {badge:element.getAttribute('data-step-code'),
|
|
text:element.textContent, originalTool:log.kvps._tool_name};
|
|
}''', {"tool_name": tool_name})
|
|
assert result["badge"] == code
|
|
assert "Saved tool call" in result["text"]
|
|
assert result["originalTool"] == tool_name
|
|
|
|
|
|
def test_skill_cards_keep_instruction_and_reference_bodies_in_details(page):
|
|
result = page.evaluate(r'''async () => {
|
|
const path = '/extensions/webui/';
|
|
runtimeInfo.webuiExtensions.js.get_tool_message_handler = [path + 'get_tool_message_handler/skills-handler.js'];
|
|
runtimeInfo.webuiExtensions.js.get_message_handler = [path + 'get_message_handler/skills-handler.js'];
|
|
runtimeInfo.webuiExtensions.js.get_process_step_types = [path + 'get_process_step_types/skills-types.js'];
|
|
const {setMessages} = await import('/js/messages.js');
|
|
const {getStore} = await import('/js/AlpineStore.js');
|
|
getStore('preferences').detailMode = 'expanded';
|
|
const header = 'Skill: demo\nPath: /skills/demo\n\n';
|
|
const body = '\nContent (SKILL.md body):\nDescription: Body text';
|
|
const legacyContent = header + 'Description:\nShort description\n' + body;
|
|
const currentContent = header + body;
|
|
const filePath = 'references/guide.md';
|
|
const referenceContent = 'Skill file: demo/' + filePath + '\n\nFull reference text.';
|
|
const error = 'Error: skill file not found.';
|
|
const logs = [
|
|
{no:0, id:'legacy-load', type:'tool', heading:'Loading skill: demo',
|
|
content:legacyContent, kvps:{_tool_name:'skills_tool'}},
|
|
{no:1, id:'current-load', type:'skills_tool', heading:'icon://school Loading skill: demo',
|
|
content:currentContent, kvps:{action:'load', skill_name:'demo'}},
|
|
{no:2, id:'reference', type:'skills_tool', heading:'icon://school Reading skill: demo/' + filePath,
|
|
content:referenceContent, kvps:{action:'read_file', skill_name:'demo', file_path:filePath}},
|
|
{no:3, id:'missing-reference', type:'skills_tool', heading:'icon://school Reading skill: demo/missing.md',
|
|
content:error, kvps:{action:'read_file', skill_name:'demo', file_path:'missing.md'}},
|
|
];
|
|
await setMessages(logs);
|
|
const steps = [...document.querySelectorAll('.process-step.SKL')];
|
|
const details = getStore('stepDetail');
|
|
const showStepDetail = details.showStepDetail;
|
|
const recorded = [];
|
|
details.showStepDetail = log => recorded.push(log.content);
|
|
try {
|
|
steps.forEach(step => step.querySelector('.action-detail').click());
|
|
} finally {
|
|
details.showStepDetail = showStepDetail;
|
|
}
|
|
return {
|
|
summaries: steps.map(step => step.querySelector('.process-step-detail-content')?.textContent || ''),
|
|
action: steps[1].querySelector('.kvps-key')?.textContent,
|
|
referenceHasPath: steps[2].querySelector('.msg-kvps').textContent.includes(filePath),
|
|
fullDetails: recorded.length === logs.length && logs.every((log, index) => recorded[index] === log.content),
|
|
};
|
|
}
|
|
''')
|
|
assert result == {
|
|
"summaries": ["Short description", "", "", "Error: skill file not found."],
|
|
"action": "Action",
|
|
"referenceHasPath": True,
|
|
"fullDetails": True,
|
|
}
|
|
|
|
|
|
def test_tool_card_summaries_keep_recorded_headings_actions_and_details(page):
|
|
page.evaluate(r'''async () => {
|
|
const core = '/extensions/webui/';
|
|
const plugin = (name, point, file) => '/plugins/_' + name + '/extensions/webui/' + point + '/' + file;
|
|
Object.assign(runtimeInfo.webuiExtensions.js, {
|
|
get_tool_message_handler: [
|
|
plugin('text_editor', 'get_tool_message_handler', 'text-editor-handler.js'),
|
|
plugin('memory', 'get_tool_message_handler', 'memory-handler.js'),
|
|
plugin('notify_user', 'get_tool_message_handler', 'notify-user-handler.js'),
|
|
],
|
|
get_message_handler: [
|
|
plugin('memory', 'get_message_handler', 'memory-handler.js'),
|
|
core + 'get_message_handler/skills-handler.js',
|
|
core + 'get_message_handler/vision-handler.js',
|
|
],
|
|
get_process_step_types: [
|
|
plugin('memory', 'get_process_step_types', 'memory-types.js'),
|
|
core + 'get_process_step_types/skills-types.js',
|
|
core + 'get_process_step_types/vision-types.js',
|
|
],
|
|
});
|
|
const {cleanStepTitle, setMessages} = await import('/js/messages.js');
|
|
const {getStore} = await import('/js/AlpineStore.js');
|
|
getStore('preferences').detailMode = 'expanded';
|
|
const path = '/workspace/demo.txt';
|
|
const text = '\n>>>\n1 File text.\n2 More file text.\n<<<';
|
|
const memories = 'id: one\nContent: First match.\nLong excerpt.\n\nid: two\nContent: Second match.';
|
|
const catalogue = 'Available skills (4):\n- One\n- Two\n- Three\n- Four\n\nTip: load a skill.';
|
|
const visionStatus = 'Analyzed 1 image(s); 0 skipped.';
|
|
const cases = [
|
|
['tool', 'Reading ' + path, path + ' 2 lines' + text,
|
|
{_tool_name:'text_editor', action:'read', path}, '2 lines', ['Action', 'Path']],
|
|
['tool', 'Reading ' + path + ' (remote)', path + ' 2 lines' + text,
|
|
{_tool_name:'text_editor_remote', action:'read', path}, '2 lines', ['Action', 'Path']],
|
|
['tool', 'Writing ' + path, path + ' written 2 lines' + text,
|
|
{_tool_name:'text_editor', action:'write', path, content:'File text.\nMore file text.'},
|
|
'2 lines written', ['Action', 'Path']],
|
|
['tool', 'Patching ' + path, path + ' patched 1 edits applied 2 lines now' + text,
|
|
{_tool_name:'text_editor', action:'patch', path, edits:[{from:1, to:1, content:'File text.'}]},
|
|
'1 edit applied', ['Action', 'Path']],
|
|
['tool', "Using tool 'memory_load'", memories,
|
|
{_tool_name:'memory_load', query:'demo', limit:5},
|
|
'2 memories found\nFirst match.', ['Query']],
|
|
['memory', 'icon://saved_search Searching memories: demo', memories,
|
|
{query:'demo', limit:5}, '2 memories found\nFirst match.', ['Query']],
|
|
['tool', "Using tool 'notify_user'", 'The notification has been sent to the user.',
|
|
{_tool_name:'notify_user', action:'send', message:'Ready', priority:'normal', title:'Demo', type:'info'},
|
|
'The notification has been sent to the user.', ['Action', 'Message', 'Priority']],
|
|
['skills_tool', 'icon://school Listing skills', catalogue,
|
|
{}, '4 skills found\n- One\n- Two\n- Three', []],
|
|
['vision_load', 'icon://imagesmode Loading images: demo.png', visionStatus + '\n\nFull analysis.',
|
|
{paths:['/workspace/demo.png'], query:'Describe the image'},
|
|
visionStatus, ['Paths', 'Query']],
|
|
];
|
|
const logs = cases.map(([type, heading, content, kvps], no) =>
|
|
({no, id:'card-' + no, type, heading, content, kvps}));
|
|
await setMessages(logs);
|
|
const details = getStore('stepDetail');
|
|
const showStepDetail = details.showStepDetail;
|
|
try {
|
|
for (const log of logs) {
|
|
const step = document.querySelector('.process-step[data-log-no="' + log.no + '"]');
|
|
const [, , , , summary, keys] = cases[log.no];
|
|
const check = (condition, name) => {
|
|
if (!condition) throw new Error(log.heading + ' changed ' + name);
|
|
};
|
|
check(step.querySelector('.step-title').textContent === cleanStepTitle(log.heading), 'heading');
|
|
check(step.querySelector('.process-step-detail-content').textContent === summary, 'summary');
|
|
const rows = [...step.querySelectorAll('.kvps-row')];
|
|
check(rows.map(row => row.querySelector('.kvps-key').textContent).join() === keys.join(), 'fields');
|
|
if (log.kvps.action) {
|
|
check(rows[0].querySelector('.kvps-val').textContent === log.kvps.action, 'action');
|
|
}
|
|
let detail;
|
|
details.showStepDetail = data => { detail = data; };
|
|
step.querySelector('.action-detail').click();
|
|
check(detail?.content === log.content, 'recorded output');
|
|
check(JSON.stringify(detail.kvps) === JSON.stringify(log.kvps), 'recorded arguments');
|
|
}
|
|
} finally {
|
|
details.showStepDetail = showStepDetail;
|
|
}
|
|
}''')
|