Skip to content

Agent Zero AI framework

typed messages.js, unified returns from message handlers

frdeld358deda64d1
diff --git a/jsconfig.json b/jsconfig.json
index 4132a955e..17f9b2537 100644
--- a/jsconfig.json
+++ b/jsconfig.json
@@ -1,5 +1,11 @@
{
"compilerOptions": {
+ "checkJs": true,
+ "allowJs": true,
+ "strict": true,
+ "noImplicitAny": false,
+ "module": "esnext",
+ "target": "es2022",
"baseUrl": ".",
"paths": {
"*": ["webui/*"],
diff --git a/webui/components/messages/action-buttons/simple-action-buttons.js b/webui/components/messages/action-buttons/simple-action-buttons.js
index 59cb35cbe..57d595984 100644
--- a/webui/components/messages/action-buttons/simple-action-buttons.js
+++ b/webui/components/messages/action-buttons/simple-action-buttons.js
@@ -59,10 +59,14 @@ export function showButtonFeedback(button, success, originalIcon) {
/**
* Create action button element
+ *
+ * @param {string} icon
+ * @param {string} [text]
+ * @param {(() => (any | Promise<any>)) | null} [handler]
+ * @returns {HTMLButtonElement}
*/
export function createActionButton(icon, text = "", handler = null) {
const iconName = resolveActionIcon(icon);
- if (!iconName) return null;
const button = document.createElement("button");
button.type = "button";
@@ -72,12 +76,17 @@ export function createActionButton(icon, text = "", handler = null) {
button.setAttribute("aria-label", label);
button.setAttribute("title", label);
}
- button.innerHTML = `<span class="material-symbols-outlined">${iconName}</span>`;
+
+ if (iconName) {
+ button.innerHTML = `<span class="material-symbols-outlined">${iconName}</span>`;
+ } else if (text) {
+ button.textContent = text;
+ }
if (typeof handler === "function") {
button.addEventListener("click", async (event) => {
event.stopPropagation();
- const shouldShowFeedback = true; // icon === "copy" || icon === "speak";
+ const shouldShowFeedback = Boolean(iconName); // icon === "copy" || icon === "speak";
try {
await handler();
if (shouldShowFeedback) {
diff --git a/webui/js/initFw.js b/webui/js/initFw.js
index 658fbc89a..15e915ecb 100644
--- a/webui/js/initFw.js
+++ b/webui/js/initFw.js
@@ -8,8 +8,11 @@ import { registerAlpineMagic } from "./confirmClick.js";
await initializer.initialize();
// import alpine library
+// @ts-ignore
await import("../vendor/alpine/alpine.min.js");
+const Alpine = globalThis.Alpine;
+
// register $confirmClick magic helper for inline button confirmations
registerAlpineMagic();
diff --git a/webui/js/messages.js b/webui/js/messages.js
index 758fad830..cfdd3bf1c 100644
--- a/webui/js/messages.js
+++ b/webui/js/messages.js
@@ -29,11 +29,61 @@ let _chatHistory = null;
let _massRender = false;
let _scrollOnNextProcessGroup = null;
+/**
+ * @typedef {object} MessageHandlerArgs
+ * @property {number} [no]
+ * @property {string | number} id
+ * @property {string} type
+ * @property {string | undefined} [heading]
+ * @property {string | undefined} [content]
+ * @property {object | undefined} [kvps]
+ * @property {number | undefined} [timestamp]
+ * @property {number} [agentno]
+ */
+
+/**
+ * @typedef {{ element: Element } & Record<string, any>} MessageHandlerResult
+ */
+
+/**
+ * @typedef {object} SetMessageResult
+ * @property {IArguments} args
+ * @property {MessageHandlerResult} result
+ */
+
+/**
+ * @typedef {(args: MessageHandlerArgs & Record<string, any>) => MessageHandlerResult} MessageHandler
+ */
+
+/**
+ * @typedef {object} ProcessStepArgs
+ * @property {string | number} id
+ * @property {string} title
+ * @property {string} code
+ * @property {string[] | undefined} [classes]
+ * @property {any} [kvps]
+ * @property {string | undefined} [content]
+ * @property {string[] | undefined} [contentClasses]
+ * @property {Element[] | undefined} [actionButtons]
+ * @property {any} log
+ * @property {boolean} [allowCompletedGroup]
+ */
+
+
export function scrollOnNextProcessGroup() {
_scrollOnNextProcessGroup = "wait";
}
// handlers for log message rendering
+/**
+ * Returns a message renderer for a given log message type.
+ *
+ * The returned handler has the same input object shape as `setMessage(...)` passes through
+ * and may return a rich object `{ element, actionButtons?, ...additional }`.
+ *
+ * @param {string} type
+ * @returns {MessageHandler}
+ */
export function getMessageHandler(type) {
switch (type) {
case "user":
@@ -87,7 +137,9 @@ export async function setMessages(messages) {
reapplyDelayMs: 1000,
applyStabilization: true,
},
+ /** @type {Scroller | null} */
mainScroller: null,
+ /** @type {SetMessageResult[]} */
results: [],
};
@@ -99,12 +151,13 @@ export async function setMessages(messages) {
await callJsExtensions("set_messages_before_loop", context);
+ //@ts-ignore
context.mainScroller = new Scroller(context.history, context.scrollerOptions);
// process messages
for (let i = 0; i < context.messages.length; i++) {
_massRender = context.historyEmpty || (context.isLargeAppend && i < context.cutoff);
- context.results.push(setMessage(context.messages[i]) || {});
+ context.results.push(setMessage(context.messages[i]));
}
await callJsExtensions("set_messages_after_loop", context);
@@ -112,13 +165,13 @@ export async function setMessages(messages) {
// reset _massRender flag
_massRender = false;
- const shouldScroll = context.historyEmpty || !context.results[context.results.length - 1]?.dontScroll;
+ const shouldScroll = context.historyEmpty || !context.results[context.results.length - 1]?.result?.dontScroll;
- if (shouldScroll) context.mainScroller.reApplyScroll();
+ if (shouldScroll) context.mainScroller?.reApplyScroll();
if (_scrollOnNextProcessGroup === "scroll") {
requestAnimationFrame(() => {
- context.mainScroller.scrollToBottom();
+ context.mainScroller?.scrollToBottom();
_scrollOnNextProcessGroup = null;
});
}
@@ -126,6 +179,10 @@ export async function setMessages(messages) {
// entrypoint called from poll/WS communication, this is how all messages are rendered and updated
// input is raw log format
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {SetMessageResult}
+ */
export function setMessage({
no,
id,
@@ -139,8 +196,9 @@ export function setMessage({
}) {
const handler = getMessageHandler(type);
// prefer log ID if set to match user message created on frontend with backend updates
- return handler({
- id: id || no,
+ const handlerResult = handler({
+ no,
+ id: id || String(no) || "",
type,
heading,
content,
@@ -149,6 +207,10 @@ export function setMessage({
agentno,
...additional,
});
+ return {
+ args: arguments[0],
+ result: handlerResult,
+ }
}
function getOrCreateMessageContainer(
@@ -255,6 +317,10 @@ function buildDetailPayload(stepData, extras = {}) {
};
}
+/**
+ * @param {ProcessStepArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
function drawProcessStep({
id,
title,
@@ -289,7 +355,7 @@ function drawProcessStep({
group.setAttribute("data-start-timestamp", String(log.timestamp));
}
- if (isNewStep) {
+ if (!step) {
// create the base DOM element for the step
step = document.createElement("div");
step.id = stepId;
@@ -297,7 +363,7 @@ function drawProcessStep({
// set data attributes of the step
step.setAttribute("data-log-type", log.type);
- step.setAttribute("data-step-id", id);
+ step.setAttribute("data-step-id", String(id));
step.setAttribute("data-agent-number", log.agentno);
// set timestamp attribute (convert to milliseconds for duration calculation)
@@ -409,7 +475,6 @@ function drawProcessStep({
if (prevCode) step.classList.remove(prevCode);
step.setAttribute("data-step-code", code);
step.classList.add(code);
- step.querySelector(".step-badge").textContent = code;
badge.innerText = code;
}
@@ -471,12 +536,13 @@ function drawProcessStep({
// return anything useful
return {
+ element: step,
+ actionButtons,
step,
detail: stepDetail,
content: stepDetailContent,
contentScroller: detailScroller,
kvpsTable,
- actionButtons: stepActionBtns,
isExpanded,
};
}
@@ -645,7 +711,7 @@ export function _drawMessage({
// KaTeX rendering for markdown
if (latex) {
contentDiv.querySelectorAll("latex").forEach((element) => {
- katex.render(element.innerHTML, element, {
+ globalThis.katex.render(element.innerHTML, element, {
throwOnError: false,
});
});
@@ -715,6 +781,10 @@ export function addBlankTargetsToLinks(str) {
return doc.body.innerHTML;
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageDefault({
id,
heading,
@@ -730,7 +800,7 @@ export function drawMessageDefault({
].filter(Boolean)
: [];
- return drawStandaloneMessage({
+ const element = drawStandaloneMessage({
id,
heading,
content,
@@ -742,15 +812,21 @@ export function drawMessageDefault({
kvps,
actionButtons,
});
+
+ return { element };
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageAgent({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps = undefined,
+ timestamp = undefined,
agentno = 0,
...additional
}) {
@@ -783,20 +859,24 @@ export function drawMessageAgent({
id,
title,
code: "GEN",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
actionButtons,
log: arguments[0],
});
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageResponse({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps = undefined,
+ timestamp = undefined,
agentno = 0,
...additional
}) {
@@ -858,9 +938,9 @@ export function drawMessageResponse({
const messageDiv = _drawMessage({
messageContainer: container,
- heading: null,
+ heading: undefined,
content,
- kvps: null,
+ kvps: undefined,
messageClasses: [],
contentClasses: [],
markdown: true,
@@ -886,9 +966,13 @@ export function drawMessageResponse({
if (group) updateProcessGroupHeader(group);
- return container;
+ return { element: container };
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageUser({
id,
heading,
@@ -988,6 +1072,7 @@ export function drawMessageUser({
attachmentDiv.addEventListener("click", displayInfo.clickHandler);
+ // @ts-ignore
attachmentsContainer.appendChild(attachmentDiv);
});
} else {
@@ -1025,15 +1110,21 @@ export function drawMessageUser({
userActionButtons.forEach((button) =>
actionButtonsContainer.appendChild(button),
);
+
+ return { element: messageContainer };
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageTool({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1056,13 +1147,17 @@ export function drawMessageTool({
}
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageToolSimple({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
code,
displayKvps,
@@ -1090,7 +1185,7 @@ export function drawMessageToolSimple({
id,
title,
code: code || "USE",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
content,
// contentClasses: [],
@@ -1099,13 +1194,18 @@ export function drawMessageToolSimple({
});
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageCodeExe({
id,
type,
heading,
+ test,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1135,41 +1235,51 @@ export function drawMessageCodeExe({
// render the standard step
const commandText = String(kvps?.code ?? "");
const outputText = String(content ?? "");
- const actionButtons = [
+
+ const actionButtons = [];
+ actionButtons.push(
createActionButton("detail", "", () =>
stepDetailStore.showStepDetail(
buildDetailPayload(arguments[0], { headerLabels }),
),
),
- commandText.trim()
- ? createActionButton("copy", "Command", () =>
- copyToClipboard(commandText),
- )
- : null,
- outputText.trim()
- ? createActionButton("copy", "Output", () => copyToClipboard(outputText))
- : null,
- ].filter(Boolean);
+ );
+ if (commandText.trim()) {
+ actionButtons.push(
+ createActionButton("copy", "Command", () => copyToClipboard(commandText)),
+ );
+ }
+ if (outputText.trim()) {
+ actionButtons.push(
+ createActionButton("copy", "Output", () => copyToClipboard(outputText)),
+ );
+ }
const stepData = drawProcessStep({
id,
title,
code: "EXE",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
content,
contentClasses: ["terminal-output"],
actionButtons,
log: arguments[0],
});
+
+ return stepData;
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageBrowser({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1192,7 +1302,7 @@ export function drawMessageBrowser({
id,
title,
code: "WWW",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
content,
// contentClasses: [],
@@ -1201,13 +1311,17 @@ export function drawMessageBrowser({
});
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageMcp({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1233,7 +1347,7 @@ export function drawMessageMcp({
id,
title,
code: "MCP",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
content,
// contentClasses: [],
@@ -1242,13 +1356,17 @@ export function drawMessageMcp({
});
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageSubagent({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1274,7 +1392,7 @@ export function drawMessageSubagent({
id,
title,
code: "SUB",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
content,
// contentClasses: [],
@@ -1283,11 +1401,15 @@ export function drawMessageSubagent({
});
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageInfo({
id,
heading,
content,
- kvps = null,
+ kvps,
...additional
}) {
const title = cleanStepTitle(heading || content);
@@ -1304,7 +1426,7 @@ export function drawMessageInfo({
id,
title,
code: "INF",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
content,
// contentClasses: [],
@@ -1313,13 +1435,17 @@ export function drawMessageInfo({
});
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageUtil({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1348,13 +1474,17 @@ export function drawMessageUtil({
return result;
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageHint({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1367,28 +1497,33 @@ export function drawMessageHint({
].filter(Boolean)
: [];
- return drawStandaloneMessage({
+ const element = drawStandaloneMessage({
id,
- title,
+ heading: title,
// statusClass,
- statusCode: "HNT",
+ // statusCode: "HNT",
kvps,
- type,
- heading,
+ // type,
content,
- timestamp,
- agentno,
+ // timestamp,
+ // agentno,
actionButtons,
});
+
+ return { element };
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageProgress({
id,
type,
heading,
content,
- kvps = null,
- timestamp = null,
+ kvps,
+ timestamp,
agentno = 0,
...additional
}) {
@@ -1399,7 +1534,7 @@ export function drawMessageProgress({
id,
title,
code: "HDL",
- classes: null,
+ classes: undefined,
kvps: displayKvps,
content,
// contentClasses: [],
@@ -1408,6 +1543,10 @@ export function drawMessageProgress({
});
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageWarning({
id,
type,
@@ -1443,9 +1582,9 @@ export function drawMessageWarning({
}
// if no process group is running, draw as standalone
- return drawStandaloneMessage({
+ const element = drawStandaloneMessage({
id,
- title,
+ heading: title,
content,
position: "mid",
containerClasses: ["ai-container", "center-container"],
@@ -1453,8 +1592,14 @@ export function drawMessageWarning({
kvps: displayKvps,
actionButtons,
});
+
+ return { element };
}
+/**
+ * @param {MessageHandlerArgs & Record<string, any>} param0
+ * @returns {MessageHandlerResult}
+ */
export function drawMessageError({
id,
type,
@@ -1466,18 +1611,22 @@ export function drawMessageError({
const contentText = String(content ?? "");
let title = getStepTitle(heading, content, type);
let displayKvps = { ...kvps };
- const actionButtons = [
+
+ const actionButtons = [];
+ actionButtons.push(
createActionButton("detail", "", () =>
stepDetailStore.showStepDetail(
buildDetailPayload(arguments[0], { headerLabels: [] }),
),
),
- contentText.trim()
- ? createActionButton("copy", "", () => copyToClipboard(contentText))
- : null,
- ].filter(Boolean);
+ );
+ if (contentText.trim()) {
+ actionButtons.push(
+ createActionButton("copy", "", () => copyToClipboard(contentText)),
+ );
+ }
- return drawStandaloneMessage({
+ const element = drawStandaloneMessage({
id,
heading: title,
content: contentText,
@@ -1487,6 +1636,8 @@ export function drawMessageError({
kvps: displayKvps,
actionButtons,
});
+
+ return { element };
}
function drawKvpsIncremental(container, kvps, latex) {
@@ -1589,7 +1740,7 @@ function drawKvpsIncremental(container, kvps, latex) {
// KaTeX rendering for markdown
if (latex) {
span.querySelectorAll("latex").forEach((element) => {
- katex.render(element.innerHTML, element, {
+ globalThis.katex.render(element.innerHTML, element, {
throwOnError: false,
});
});
@@ -2161,8 +2312,16 @@ function truncateText(text, maxLength) {
}
// gets or creates a child DOM element
+/**
+ * @param {Element} parent
+ * @param {string} selector
+ * @param {string} tagName
+ * @param {...string} classNames
+ * @returns {HTMLElement}
+ */
function ensureChild(parent, selector, tagName, ...classNames) {
- let el = parent.querySelector(selector);
+ /** @type {HTMLElement | null} */
+ let el = /** @type {any} */ (parent.querySelector(selector));
if (!el) {
el = document.createElement(tagName);
if (classNames.length) el.classList.add(...classNames);