Skip to content

Agent Zero AI framework

fix: take durationms from backend

3clyp505844e58b83bb
diff --git a/python/helpers/log.py b/python/helpers/log.py
index 7a9a6f16b..19f9e1e8d 100644
--- a/python/helpers/log.py
+++ b/python/helpers/log.py
@@ -138,12 +138,7 @@ class LogItem:
def __post_init__(self):
self.guid = self.log.guid
- self.timestamp = time.time() # Record creation time
- # Capture agent number from context if available
- if self.log.context and self.log.context.streaming_agent:
- self.agent_number = self.log.context.streaming_agent.number
- else:
- self.agent_number = 0 # Default to main agent
+ self.timestamp = time.time()
def update(
self,
diff --git a/python/helpers/persist_chat.py b/python/helpers/persist_chat.py
index 55867e6fe..9e4c20b6c 100644
--- a/python/helpers/persist_chat.py
+++ b/python/helpers/persist_chat.py
@@ -262,17 +262,19 @@ def _deserialize_log(data: dict[str, Any]) -> "Log":
# Deserialize the list of LogItem objects
i = 0
for item_data in data.get("logs", []):
- log.logs.append(
- LogItem(
- log=log, # restore the log reference
- no=i, # item_data["no"],
- type=item_data["type"],
- heading=item_data.get("heading", ""),
- content=item_data.get("content", ""),
- kvps=OrderedDict(item_data["kvps"]) if item_data["kvps"] else None,
- temp=item_data.get("temp", False),
- )
- )
+ log.logs.append(LogItem(
+ log=log, # restore the log reference
+ no=i, # item_data["no"],
+ type=item_data["type"],
+ heading=item_data.get("heading", ""),
+ content=item_data.get("content", ""),
+ kvps=OrderedDict(item_data["kvps"]) if item_data["kvps"] else None,
+ temp=item_data.get("temp", False),
+ # Pass metrics directly to constructor
+ timestamp=item_data.get("timestamp", 0.0),
+ duration_ms=item_data.get("duration_ms"),
+ agent_number=item_data.get("agent_number", 0),
+ ))
log.updates.append(i)
i += 1
diff --git a/webui/components/messages/process-group/process-group.css b/webui/components/messages/process-group/process-group.css
index 29049137a..654eb9ff9 100644
--- a/webui/components/messages/process-group/process-group.css
+++ b/webui/components/messages/process-group/process-group.css
@@ -669,13 +669,6 @@
height: 0;
}
-
- }
- #chat-input::-webkit-scrollbar { width: 6px; height: 6px; }
- #chat-input::-webkit-scrollbar-track { background: transparent; margin: 4px 0; border-radius: 6px; }
- #chat-input::-webkit-scrollbar-thumb { background-color: rgba(155,155,155,0.5); border-radius: 6px; -webkit-transition: background-color 0.2s ease; transition: background-color 0.2s ease; }
- #chat-input::-webkit-scrollbar-thumb:hover { background-color: rgba(155,155,155,0.7); }
-
/* Light mode terminal */
.light-mode .process-step-detail-content .terminal-output {
background: rgba(0, 0, 0, 0.05);
diff --git a/webui/css/messages.css b/webui/css/messages.css
index 13926b522..eef5897b7 100644
--- a/webui/css/messages.css
+++ b/webui/css/messages.css
@@ -96,6 +96,8 @@
.message-user .message-text pre {
font-family: var(--font-family-main);
+ text-align: right;
+ margin-left: 25%;
}
.message-ai {
diff --git a/webui/index.js b/webui/index.js
index bc4cf5e0e..e6b62735c 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -10,7 +10,6 @@ import { store as inputStore } from "/components/chat/input/input-store.js";
import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";
import { store as tasksStore } from "/components/sidebar/tasks/tasks-store.js";
import { store as chatTopStore } from "/components/chat/top-section/chat-top-store.js";
-import { store as processGroupStore } from "/components/messages/process-group/process-group-store.js";
globalThis.fetchApi = api.fetchApi; // TODO - backward compatibility for non-modular scripts, remove once refactored to alpine
diff --git a/webui/js/messages.js b/webui/js/messages.js
index e17db6d83..0082dbf43 100644
--- a/webui/js/messages.js
+++ b/webui/js/messages.js
@@ -6,6 +6,7 @@ import { store as attachmentsStore } from "/components/chat/attachments/attachme
import { addActionButtonsToElement } from "/components/messages/action-buttons/simple-action-buttons.js";
import { store as processGroupStore } from "/components/messages/process-group/process-group-store.js";
import { store as preferencesStore } from "/components/sidebar/bottom/preferences/preferences-store.js";
+import { formatDuration } from "./time-utils.js";
const chatHistory = document.getElementById("chat-history");
@@ -13,11 +14,11 @@ let messageGroup = null;
let currentProcessGroup = null; // Track current process group for collapsible UI
// Process types that should be grouped into collapsible sections
-const PROCESS_TYPES = ['agent', 'tool', 'code_exe', 'browser', 'info', 'hint', 'util', 'warning'];
+const PROCESS_TYPES = ['agent', 'tool', 'code_exe', 'browser', 'progress', 'info', 'hint', 'util', 'warning'];
// Main types that should always be visible (not collapsed)
const MAIN_TYPES = ['user', 'response', 'error', 'rate_limit'];
-export function setMessage(id, type, heading, content, temp, kvps = null, timestamp = null, durationMs = null, /* tokensIn = 0, tokensOut = 0, */ agentNumber = 0) {
+export function setMessage(id, type, heading, content, temp, kvps = null, timestamp = null, durationMs = null, agentNumber = 0) {
// Check if this is a process type message
const isProcessType = PROCESS_TYPES.includes(type);
const isMainType = MAIN_TYPES.includes(type);
@@ -36,7 +37,7 @@ export function setMessage(id, type, heading, content, temp, kvps = null, timest
if (isProcessType) {
if (processStepElement) {
// Update existing process step
- updateProcessStep(processStepElement, id, type, heading, content, kvps, durationMs /*, tokensIn, tokensOut */);
+ updateProcessStep(processStepElement, id, type, heading, content, kvps, durationMs);
return processStepElement;
}
@@ -47,7 +48,7 @@ export function setMessage(id, type, heading, content, temp, kvps = null, timest
}
// Add step to current process group
- processStepElement = addProcessStep(currentProcessGroup, id, type, heading, content, kvps, timestamp, durationMs /*, tokensIn, tokensOut */);
+ processStepElement = addProcessStep(currentProcessGroup, id, type, heading, content, kvps, timestamp, durationMs);
return processStepElement;
}
@@ -55,7 +56,7 @@ export function setMessage(id, type, heading, content, temp, kvps = null, timest
// agentNumber: 0 = main agent, 1+ = subordinate agents
if (type === "response" && agentNumber !== 0) {
if (processStepElement) {
- updateProcessStep(processStepElement, id, "agent", heading, content, kvps, durationMs /*, tokensIn, tokensOut */);
+ updateProcessStep(processStepElement, id, "agent", heading, content, kvps, durationMs);
return processStepElement;
}
@@ -66,7 +67,7 @@ export function setMessage(id, type, heading, content, temp, kvps = null, timest
}
// Add subordinate response as a step (type "agent" for appropriate styling)
- processStepElement = addProcessStep(currentProcessGroup, id, "agent", heading, content, kvps, timestamp, durationMs /*, tokensIn, tokensOut */);
+ processStepElement = addProcessStep(currentProcessGroup, id, "agent", heading, content, kvps, timestamp, durationMs);
return processStepElement;
}
@@ -1140,7 +1141,6 @@ function createProcessGroup(id) {
<span class="metric-time" title="Start time"><span class="material-symbols-outlined">schedule</span><span class="metric-value">--:--</span></span>
<span class="metric-steps" title="Steps"><span class="material-symbols-outlined">list_alt</span><span class="metric-value">0</span></span>
<span class="metric-duration" title="Duration"><span class="material-symbols-outlined">timer</span><span class="metric-value">0s</span></span>
- <!-- <span class="metric-tokens" title="Tokens"><span class="material-symbols-outlined">data_object</span><span class="metric-value">--</span></span> -->
</span>
`;
@@ -1170,7 +1170,7 @@ function createProcessGroup(id) {
/**
* Add a step to a process group
*/
-function addProcessStep(group, id, type, heading, content, kvps, timestamp = null, durationMs = null /*, tokensIn = 0, tokensOut = 0 */) {
+function addProcessStep(group, id, type, heading, content, kvps, timestamp = null, durationMs = null) {
const groupId = group.getAttribute("data-group-id");
const stepsContainer = group.querySelector(".process-steps");
const isGroupCompleted = group.classList.contains("process-group-completed");
@@ -1181,8 +1181,6 @@ function addProcessStep(group, id, type, heading, content, kvps, timestamp = nul
step.classList.add("process-step");
step.setAttribute("data-type", type);
step.setAttribute("data-step-id", id);
- // step.setAttribute("data-tokens-in", tokensIn || 0);
- // step.setAttribute("data-tokens-out", tokensOut || 0);
// Store timestamp for duration calculation
if (timestamp) {
@@ -1199,6 +1197,11 @@ function addProcessStep(group, id, type, heading, content, kvps, timestamp = nul
}
}
+ // Store duration from backend (used for final duration calculation)
+ if (durationMs != null) {
+ step.setAttribute("data-duration-ms", durationMs);
+ }
+
// Add message-util class for utility/info types (controlled by showUtils preference)
if (type === "util" || type === "info" || type === "hint") {
step.classList.add("message-util");
@@ -1272,7 +1275,7 @@ function addProcessStep(group, id, type, heading, content, kvps, timestamp = nul
/**
* Update an existing process step
*/
-function updateProcessStep(stepElement, id, type, heading, content, kvps, durationMs = null /*, tokensIn = 0, tokensOut = 0 */) {
+function updateProcessStep(stepElement, id, type, heading, content, kvps, durationMs = null) {
// Update title
const titleEl = stepElement.querySelector(".step-title");
if (titleEl) {
@@ -1280,13 +1283,10 @@ function updateProcessStep(stepElement, id, type, heading, content, kvps, durati
titleEl.textContent = title;
}
- // Update token data (use the latest values)
- // if (tokensIn > 0) {
- // stepElement.setAttribute("data-tokens-in", tokensIn);
- // }
- // if (tokensOut > 0) {
- // stepElement.setAttribute("data-tokens-out", tokensOut);
- // }
+ // Update duration from backend
+ if (durationMs != null) {
+ stepElement.setAttribute("data-duration-ms", durationMs);
+ }
// Update detail content
const detailContent = stepElement.querySelector(".process-step-detail-content");
@@ -1590,8 +1590,15 @@ function updateProcessGroupHeader(group) {
const metricsEl = group.querySelector(".group-metrics");
const isCompleted = group.classList.contains("process-group-completed");
+ // If completed, only remove active badges and exit early (don't update metrics)
+ if (isCompleted) {
+ const activeBadges = group.querySelectorAll(".status-badge.status-active");
+ activeBadges.forEach(badge => badge.classList.remove("status-active"));
+ return;
+ }
+
// Update group title with the latest agent step heading
- if (titleEl && !isCompleted) {
+ if (titleEl) {
// Find the last "agent" type step
const agentSteps = Array.from(steps).filter(step => step.getAttribute("data-type") === "agent");
if (agentSteps.length > 0) {
@@ -1622,44 +1629,28 @@ function updateProcessGroupHeader(group) {
timeMetricEl.textContent = `${hours}:${minutes}`;
}
- // Update duration metric (elapsed time since start) - but only if not completed
+ // Update duration metric
const durationMetricEl = metricsEl?.querySelector(".metric-duration .metric-value");
- if (durationMetricEl && startTimestamp && !isCompleted) {
- const startMs = parseFloat(startTimestamp) * 1000;
- const elapsedMs = Date.now() - startMs;
- if (elapsedMs < 60000) {
- durationMetricEl.textContent = `${Math.round(elapsedMs / 1000)}s`;
- } else {
- const mins = Math.floor(elapsedMs / 60000);
- const secs = Math.round((elapsedMs % 60000) / 1000);
- durationMetricEl.textContent = `${mins}m${secs}s`;
+ if (durationMetricEl && steps.length > 0) {
+ // Calculate accumulated duration from backend data
+ let accumulatedMs = 0;
+ steps.forEach(step => {
+ accumulatedMs += parseInt(step.getAttribute("data-duration-ms") || "0", 10);
+ });
+
+ // Check if last step is still in progress (no duration_ms set yet)
+ const lastStep = steps[steps.length - 1];
+ const lastStepDuration = lastStep.getAttribute("data-duration-ms");
+ const lastStepTimestamp = lastStep.getAttribute("data-timestamp");
+
+ if (lastStepDuration == null && lastStepTimestamp) {
+ // Last step is in progress - add live elapsed time for this step only
+ const lastStepStartMs = parseFloat(lastStepTimestamp) * 1000;
+ const liveElapsedMs = Math.max(0, Date.now() - lastStepStartMs);
+ accumulatedMs += liveElapsedMs;
}
- }
-
- // Update tokens metric (aggregate from all steps)
- // const tokensMetricEl = metricsEl?.querySelector(".metric-tokens .metric-value");
- // if (tokensMetricEl) {
- // let totalTokensIn = 0;
- // let totalTokensOut = 0;
- // steps.forEach(step => {
- // totalTokensIn += parseInt(step.getAttribute("data-tokens-in") || 0, 10);
- // totalTokensOut += parseInt(step.getAttribute("data-tokens-out") || 0, 10);
- // });
- // const totalTokens = totalTokensIn + totalTokensOut;
- // if (totalTokens > 0) {
- // // Format as compact notation (e.g., 20k/3k for input/output)
- // tokensMetricEl.textContent = formatTokenCount(totalTokensIn, totalTokensOut);
- // } else {
- // tokensMetricEl.textContent = "--";
- // }
- // }
-
- // Once a group is completed, never re-enable any loading spinners (status-active).
- // This prevents late util/tool messages from making a completed group look "running".
- if (isCompleted) {
- const activeBadges = group.querySelectorAll(".status-badge.status-active");
- activeBadges.forEach(badge => badge.classList.remove("status-active"));
- return;
+
+ durationMetricEl.textContent = formatDuration(accumulatedMs);
}
if (steps.length > 0) {
@@ -1741,20 +1732,19 @@ function markProcessGroupComplete(group, responseTitle) {
// Add completed class to group
group.classList.add("process-group-completed");
- // Update duration to final value
+ // Calculate final duration from backend data (sum of all step durations)
+ const steps = group.querySelectorAll(".process-step");
+ let totalDurationMs = 0;
+ steps.forEach(step => {
+ const durationMs = parseInt(step.getAttribute("data-duration-ms") || "0", 10);
+ totalDurationMs += durationMs;
+ });
+
+ // Update duration metric with final value from backend
const metricsEl = group.querySelector(".group-metrics");
const durationMetricEl = metricsEl?.querySelector(".metric-duration .metric-value");
- const startTimestamp = group.getAttribute("data-start-timestamp");
- if (durationMetricEl && startTimestamp) {
- const startMs = parseFloat(startTimestamp) * 1000;
- const elapsedMs = Date.now() - startMs;
- if (elapsedMs < 60000) {
- durationMetricEl.textContent = `${Math.round(elapsedMs / 1000)}s`;
- } else {
- const mins = Math.floor(elapsedMs / 60000);
- const secs = Math.round((elapsedMs % 60000) / 1000);
- durationMetricEl.textContent = `${mins}m${secs}s`;
- }
+ if (durationMetricEl && totalDurationMs > 0) {
+ durationMetricEl.textContent = formatDuration(totalDurationMs);
}
}
@@ -1766,27 +1756,6 @@ export function resetProcessGroups() {
messageGroup = null;
}
-/**
- * Format token counts in compact notation (e.g., "12k/3k" for input/output)
- * (Currently disabled - token tracking not implemented)
- */
-// function formatTokenCount(tokensIn, tokensOut) {
-// const formatCompact = (n) => {
-// if (n >= 1000000) return `${(n / 1000000).toFixed(1)}m`;
-// if (n >= 1000) return `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k`;
-// return n.toString();
-// };
-//
-// if (tokensIn > 0 && tokensOut > 0) {
-// return `${formatCompact(tokensIn)}/${formatCompact(tokensOut)}`;
-// } else if (tokensIn > 0) {
-// return `${formatCompact(tokensIn)}↓`;
-// } else if (tokensOut > 0) {
-// return `${formatCompact(tokensOut)}↑`;
-// }
-// return "--";
-// }
-
/**
* Format Unix timestamp as date-time string (YYYY-MM-DD HH:MM:SS)
*/
diff --git a/webui/js/time-utils.js b/webui/js/time-utils.js
index 9baba7fa6..4f74f00ca 100644
--- a/webui/js/time-utils.js
+++ b/webui/js/time-utils.js
@@ -69,3 +69,20 @@ export function formatDateTime(utcIsoString, format = 'full') {
export function getUserTimezone() {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
+
+/**
+ * Format a duration in milliseconds to a human-readable string
+ * @param {number} durationMs - Duration in milliseconds
+ * @returns {string} Formatted duration (e.g., '45s', '2m30s')
+ */
+export function formatDuration(durationMs) {
+ if (durationMs == null || durationMs < 0) return '0s';
+
+ if (durationMs < 60000) {
+ return `${Math.round(durationMs / 1000)}s`;
+ }
+
+ const mins = Math.floor(durationMs / 60000);
+ const secs = Math.round((durationMs % 60000) / 1000);
+ return `${mins}m${secs}s`;
+}