Agent Zero AI framework
Add /stop API and stop-button UI/behavior
frdel2ec52e196810
diff --git a/api/stop.py b/api/stop.pynew file mode 100644index 000000000..45bbe78d2--- /dev/null+++ b/api/stop.py@@ -0,0 +1,35 @@+from agent import AgentContext+from helpers.api import ApiHandler, Request, Response+++class Stop(ApiHandler):+ async def process(self, input: dict, request: Request) -> dict | Response:+ ctxid = input.get("context", "")+ if not isinstance(ctxid, str) or not ctxid.strip():+ return Response(+ '{"error": "context is required"}',+ status=400,+ mimetype="application/json",+ )++ context = AgentContext.use(ctxid.strip())+ if not context:+ return Response(+ '{"error": "Chat context not found"}',+ status=404,+ mimetype="application/json",+ )+ was_running = context.is_running()++ context.kill_process()+ context.paused = False+ context.log.set_progress("", active=False)++ msg = "Agent process stopped."+ context.log.log(type="info", content=msg, finished=True)++ return {+ "message": msg,+ "context": context.id,+ "stopped": was_running,+ }diff --git a/api/stop.py.dox.md b/api/stop.py.dox.mdnew file mode 100644index 000000000..242a39d59--- /dev/null+++ b/api/stop.py.dox.md@@ -0,0 +1,29 @@+# stop.py DOX++## Purpose++- Own the authenticated WebUI endpoint that stops an active agent run without deleting or resetting its chat context.++## Ownership++- `stop.py` resolves the requested in-memory context and cancels its current process.++## Runtime Contracts++- `Stop` derives from `ApiHandler`, retaining the default authentication and CSRF protections.+- Input uses the selected chat ID in `context`; the endpoint never creates a missing context.+- Stopping cancels the context task through `AgentContext.kill_process()`, clears pause state, preserves chat history and queued messages, and does not start another run.+- The endpoint clears active progress and logs a terminal `Agent process stopped.` info step so the WebUI closes the interrupted process group.+- The response contains `message`, `context`, and a `stopped` boolean indicating whether the context was running when requested.++## Work Guidance++- Keep this endpoint aligned with the composer stop-button state and the existing `AgentContext` task lifecycle.++## Verification++- Run `pytest tests/test_stop_agent.py` and smoke-test stopping during model streaming and tool execution.++## Child DOX Index++No child DOX files.diff --git a/helpers/git.py b/helpers/git.pyindex 609db2bbb..a56f5f4b3 100644--- a/helpers/git.py+++ b/helpers/git.py@@ -1,6 +1,6 @@from git import Git, Repofrom giturlparse import parse-from datetime import datetime+from datetime import datetime, timezonefrom dataclasses import dataclassimport osimport subprocess@@ -101,8 +101,8 @@ class GitRepoReleaseInfo:def _format_git_timestamp(timestamp: int) -> str:return datetime.fromtimestamp(timestamp,- tz=Localization.get().get_tzinfo(),- ).strftime('%Y-%m-%d %H:%M:%S %Z')+ tz=timezone.utc,+ ).strftime('%Y-%m-%d %H:%M:%S')def _split_describe_version(describe: str) -> tuple[str, int]:diff --git a/helpers/git.py.dox.md b/helpers/git.py.dox.mdindex 857c3966c..2437ef854 100644--- a/helpers/git.py.dox.md+++ b/helpers/git.py.dox.md@@ -37,6 +37,7 @@## Runtime Contracts- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.+- Git commit and release timestamp strings produced by `_format_git_timestamp` use UTC and omit a timezone suffix.- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change.- Observed side-effect areas: filesystem writes, filesystem deletion, network calls, subprocess/runtime control, plugin state, settings/state persistence, secret handling.- Imported dependency areas include: `base64`, `dataclasses`, `datetime`, `git`, `giturlparse`, `helpers`, `helpers.localization`, `os`, `re`, `subprocess`, `urllib.parse`.diff --git a/tests/test_chat_working_animation.py b/tests/test_chat_working_animation.pynew file mode 100644index 000000000..1978d25f8--- /dev/null+++ b/tests/test_chat_working_animation.py@@ -0,0 +1,60 @@+from pathlib import Path+++PROJECT_ROOT = Path(__file__).resolve().parents[1]+++def test_running_chat_bubble_morphs_and_rotates_on_a_1500ms_cycle() -> None:+ chats_list = (+ PROJECT_ROOT / "webui/components/sidebar/chats/chats-list.html"+ ).read_text(encoding="utf-8")++ assert ".chats-list-container .project-color-ball.heartbeat" in chats_list+ assert (+ "animation: chat-working-bubble 1500ms ease-in-out infinite;" in chats_list+ )+ assert "@keyframes chat-working-bubble" in chats_list+ assert "border-radius: 0;" in chats_list+ assert "transform: rotate(45deg) scale(0.9);" in chats_list+ assert "transform: rotate(405deg) scale(0.9);" in chats_list+ assert "transform: rotate(405deg) scale(1);" in chats_list+++def test_chat_and_task_rows_reclaim_left_space_without_shifting_headers() -> None:+ chats_list = (+ PROJECT_ROOT / "webui/components/sidebar/chats/chats-list.html"+ ).read_text(encoding="utf-8")+ left_sidebar = (+ PROJECT_ROOT / "webui/components/sidebar/left-sidebar.html"+ ).read_text(encoding="utf-8")++ assert "margin-inline-start: calc(0px - var(--spacing-md));" not in chats_list+ assert left_sidebar.count(+ "margin-inline-start: calc(0px - var(--spacing-sm));"+ ) == 2+ assert left_sidebar.count("width: calc(100% + var(--spacing-sm));") == 2+ assert (+ "#chats-section .section-header-row,\n"+ " #tasks-section .section-header {\n"+ " margin-inline-start: var(--spacing-sm);"+ ) in left_sidebar+ assert "flex: 1 1 auto;" in chats_list+ assert "min-width: 0;" in chats_list+ assert "padding: 8px 6px;" in chats_list+++def test_only_visible_chat_actions_take_width() -> None:+ chats_list = (+ PROJECT_ROOT / "webui/components/sidebar/chats/chats-list.html"+ ).read_text(encoding="utf-8")++ assert ".device-pointer .chat-container .chat-list-action-btn" in chats_list+ assert (+ ".device-touch .chat-container:not(.chat-selected) .chat-list-action-btn"+ in chats_list+ )+ assert ".device-pointer .chat-container:hover .chat-list-action-btn" in chats_list+ assert (+ ".device-touch .chat-container.chat-selected .chat-list-action-btn"+ in chats_list+ )diff --git a/tests/test_git_version_label.py b/tests/test_git_version_label.pyindex 11c64641d..4127c2b19 100644--- a/tests/test_git_version_label.py+++ b/tests/test_git_version_label.py@@ -47,6 +47,18 @@ def add_commit(repo_dir: Path, content: str) -> None:run_git(repo_dir, "commit", "-m", "update")+def test_git_timestamp_is_utc_without_a_timezone_suffix():+ assert git._format_git_timestamp(0) == "1970-01-01 00:00:00"+++def test_sidebar_version_timestamp_stays_on_one_line():+ sidebar_bottom = (+ PROJECT_ROOT / "webui/components/sidebar/bottom/sidebar-bottom.html"+ ).read_text(encoding="utf-8")++ assert "white-space: nowrap;" in sidebar_bottom++def test_git_version_label_shows_commit_distance_on_development(tmp_path):init_repo_with_tag(tmp_path, "development")add_commit(tmp_path, "two\n")diff --git a/tests/test_stop_agent.py b/tests/test_stop_agent.pynew file mode 100644index 000000000..479a93305--- /dev/null+++ b/tests/test_stop_agent.py@@ -0,0 +1,109 @@+import threading+from pathlib import Path++import pytest+from flask import Response++from agent import AgentContext+from api.stop import Stop+++PROJECT_ROOT = Path(__file__).resolve().parents[1]+++class _Log:+ def __init__(self) -> None:+ self.progress_calls = []+ self.entries = []++ def set_progress(self, progress: str, *, active: bool) -> None:+ self.progress_calls.append((progress, active))++ def log(self, **kwargs) -> None:+ self.entries.append(kwargs)+++class _Context:+ id = "chat-1"++ def __init__(self) -> None:+ self.paused = True+ self.killed = False+ self.log = _Log()++ def is_running(self) -> bool:+ return True++ def kill_process(self) -> None:+ self.killed = True+++async def test_stop_endpoint_cancels_without_replacing_the_run(monkeypatch) -> None:+ context = _Context()+ handler = Stop(app=None, thread_lock=threading.RLock()) # type: ignore[arg-type]++ def use_context(ctxid: str):+ assert ctxid == context.id+ return context++ monkeypatch.setattr(AgentContext, "use", use_context)++ result = await handler.process(+ {"context": context.id}, request=None # type: ignore[arg-type]+ )++ assert context.killed is True+ assert context.paused is False+ assert context.log.progress_calls == [("", False)]+ assert context.log.entries == [+ {+ "type": "info",+ "content": "Agent process stopped.",+ "finished": True,+ }+ ]+ assert result == {+ "message": "Agent process stopped.",+ "context": context.id,+ "stopped": True,+ }+++async def test_stop_endpoint_requires_an_explicit_context() -> None:+ handler = Stop(app=None, thread_lock=threading.RLock()) # type: ignore[arg-type]++ result = await handler.process({}, request=None) # type: ignore[arg-type]++ assert isinstance(result, Response)+ assert result.status_code == 400+ assert Stop.requires_auth() is True+ assert Stop.requires_csrf() is True+++def test_composer_stop_button_preserves_queue_keyboard_behavior() -> None:+ input_store = (+ PROJECT_ROOT / "webui/components/chat/input/input-store.js"+ ).read_text(encoding="utf-8")+ chat_bar = (+ PROJECT_ROOT / "webui/components/chat/input/chat-bar-input.html"+ ).read_text(encoding="utf-8")++ assert 'if (running && !hasInput) return "stop";' in input_store+ assert 'if (state === "stop") return "Stop agent";' in input_store+ assert 'await globalThis.sendJsonData("/stop", { context });' in input_store+ assert '$store.chatInput.activateSendButton()' in chat_bar+ assert ':aria-label="$store.chatInput.sendButtonTitle"' in chat_bar+ assert "#send-button.stop" in chat_bar++ # Enter keeps using sendMessage(), whose empty-input path sends the queue.+ assert "$event.preventDefault();\n this.sendMessage();" in input_store+ assert 'return "Press Enter to send queued messages";' in input_store+++def test_terminal_stop_info_closes_the_active_process_group() -> None:+ messages_js = (PROJECT_ROOT / "webui/js/messages.js").read_text(encoding="utf-8")++ assert "delete displayKvps.finished;" in messages_js+ assert "if (kvps?.finished) completeLastProcessGroup();" in messages_jsdiff --git a/tests/test_welcome_composer_static.py b/tests/test_welcome_composer_static.pyindex 9000f356d..6c7eed1ce 100644--- a/tests/test_welcome_composer_static.py+++ b/tests/test_welcome_composer_static.py@@ -153,7 +153,8 @@ def test_welcome_composer_can_create_a_chat_before_sending() -> None:def test_welcome_composer_does_not_overlap_idle_progress_placeholder() -> None:input_store = _read("webui/components/chat/input/input-store.js")- assert "!!chatsStore.selected &&\n this._getSendState() !== \"all\"" in input_store+ assert "!!chatsStore.selected &&\n state !== \"all\"" in input_store+ assert '!(state === "stop" && messageQueueStore?.hasQueue)' in input_storedef test_welcome_composer_buttons_keep_target_geometry_without_glow() -> None:diff --git a/webui/components/chat/AGENTS.md b/webui/components/chat/AGENTS.mdindex 6363a86b6..382677df7 100644--- a/webui/components/chat/AGENTS.md+++ b/webui/components/chat/AGENTS.md@@ -26,6 +26,7 @@- A connected OAuth account without Main/Utility model selection is its own gate state; route to model configuration and do not select models automatically.- Model setup surfaces that change readiness must notify the gate with `model-setup-changed`, `model-configured`, or an existing modal/onboarding completion signal so the pending prompt can retry automatically.- The top-section project selector, clock, and connection indicator must respect the instance-level mobile/desktop visibility preferences.+- While the selected context is running, an empty composer makes the primary button stop the active run; typed text still adds to the queue, and Enter with an empty composer still sends queued messages.## Work Guidancediff --git a/webui/components/chat/input/chat-bar-input.html b/webui/components/chat/input/chat-bar-input.htmlindex 7f9bbab62..51f34e53f 100644--- a/webui/components/chat/input/chat-bar-input.html+++ b/webui/components/chat/input/chat-bar-input.html@@ -45,8 +45,9 @@<div id="chat-buttons-wrapper"><!-- Send button -->- <button class="chat-button" id="send-button" aria-label="Send message" @click="$store.chatInput.sendMessage()"- :class="$store.chatInput.sendButtonClass" :title="$store.chatInput.sendButtonTitle">+ <button class="chat-button" id="send-button" @click="$store.chatInput.activateSendButton()"+ :class="$store.chatInput.sendButtonClass" :title="$store.chatInput.sendButtonTitle"+ :aria-label="$store.chatInput.sendButtonTitle"><span class="material-symbols-outlined" x-text="$store.chatInput.sendButtonIcon"></span></button></div>@@ -369,6 +370,11 @@box-shadow: none;}+ #send-button.stop {+ background-color: var(--color-error-text);+ box-shadow: none;+ }+#send-button:hover {background-color: #353bc5;filter: none;@@ -380,12 +386,21 @@filter: none;}+ #send-button.stop:hover {+ background-color: color-mix(in srgb, var(--color-error-text) 82%, black);+ filter: none;+ }+#send-button:active {background-color: #2b309c;transform: translateY(1px) scale(0.98);filter: brightness(0.96);}+ #send-button.stop:active {+ background-color: color-mix(in srgb, var(--color-error-text) 68%, black);+ }+.chat-button svg {width: 1.5rem;height: 1.5rem;diff --git a/webui/components/chat/input/input-store.js b/webui/components/chat/input/input-store.jsindex 1d09b9b13..a06cd6e7e 100644--- a/webui/components/chat/input/input-store.js+++ b/webui/components/chat/input/input-store.js@@ -83,6 +83,7 @@ const model = {const hasQueue = !!messageQueueStore?.hasQueue;const running = !!chatsStore.selectedContext?.running;+ if (running && !hasInput) return "stop";if (hasQueue && !hasInput) return "all";if ((running || hasQueue) && hasInput) return "queue";return "normal";@@ -91,15 +92,19 @@ const model = {get inputPlaceholder() {if (!chatsStore.selected) return "Ask anything to start a new chat";const state = this._getSendState();- if (state === "all") return "Press Enter to send queued messages";+ if ((state === "all" || state === "stop") && messageQueueStore?.hasQueue) {+ return "Press Enter to send queued messages";+ }if (this.showProgressPlaceholder) return "";return "Type your message here...";},get showProgressPlaceholder() {+ const state = this._getSendState();return (!!chatsStore.selected &&- this._getSendState() !== "all" &&+ state !== "all" &&+ !(state === "stop" && messageQueueStore?.hasQueue) &&!!this.progressText &&!this.message);@@ -112,6 +117,7 @@ const model = {// Computed: send button icon typeget sendButtonIcon() {const state = this._getSendState();+ if (state === "stop") return "stop";if (state === "all") return "send_and_archive";if (state === "queue") return "schedule_send";return "arrow_forward";@@ -120,6 +126,7 @@ const model = {// Computed: send button CSS classget sendButtonClass() {const state = this._getSendState();+ if (state === "stop") return "stop";if (state === "all") return "send-queue send-all";if (state === "queue") return "send-queue queue";return "";@@ -128,6 +135,7 @@ const model = {// Computed: send button titleget sendButtonTitle() {const state = this._getSendState();+ if (state === "stop") return "Stop agent";if (state === "all") return "Send all queued messages";if (state === "queue") return "Add to queue";return "Send message";@@ -155,6 +163,15 @@ const model = {}},+ async activateSendButton() {+ this._syncMessageFromEditor();+ if (this._getSendState() === "stop") {+ await this.stopAgent();+ return;+ }+ await this.sendMessage();+ },+mountEditor(editor) {this._editorEl = editor;this._renderEditorFromText(this._message);@@ -416,6 +433,18 @@ const model = {}},+ async stopAgent() {+ try {+ const context = globalThis.getContext?.();+ if (!context || !globalThis.sendJsonData) return;+ await globalThis.sendJsonData("/stop", { context });+ } catch (e) {+ if (globalThis.toastFetchError) {+ globalThis.toastFetchError("Error stopping agent", e);+ }+ }+ },+async nudge() {try {const context = globalThis.getContext();diff --git a/webui/components/sidebar/AGENTS.md b/webui/components/sidebar/AGENTS.mdindex c0d277a76..d865df2dd 100644--- a/webui/components/sidebar/AGENTS.md+++ b/webui/components/sidebar/AGENTS.md@@ -20,6 +20,10 @@- Chat tree expand/collapse controls use a parent-only leading slot and must not consume normal chat row text margin.- A restored selected parent chat with children auto-expands once during context hydration unless the user has already toggled it.- The Tasks list is reserved for scheduler-backed task contexts and must not be used for chat-bound parallel children.+- Running parent and child chats share the chat-list working-bubble animation; keep it scoped away from task and connection-status indicators.+- Chat and task lists reclaim the same part of the sidebar's left content inset so their project bubbles align, while their section headers retain the standard sidebar inset.+- Chat-row action buttons consume layout width only while a pointer row is hovered or while that row is selected on a touch device.+- Bottom version information shows its commit timestamp in UTC without a timezone suffix and remains on one line.- Avoid text or controls overflowing fixed sidebar widths.- Instance-level interface visibility preferences own independent mobile and desktop states for the chat-top controls and right canvas rail; mobile uses the shared 768px breakpoint.diff --git a/webui/components/sidebar/bottom/sidebar-bottom.html b/webui/components/sidebar/bottom/sidebar-bottom.htmlindex 800c701cd..cb10b175c 100644--- a/webui/components/sidebar/bottom/sidebar-bottom.html+++ b/webui/components/sidebar/bottom/sidebar-bottom.html@@ -44,8 +44,8 @@opacity: 0.7;font-size: 0.7rem;user-select: all;+ white-space: nowrap;}</style></body></html>-diff --git a/webui/components/sidebar/chats/chats-list.html b/webui/components/sidebar/chats/chats-list.htmlindex bae6793bc..755dd98e4 100644--- a/webui/components/sidebar/chats/chats-list.html+++ b/webui/components/sidebar/chats/chats-list.html@@ -190,8 +190,9 @@.chat-list-button {display: flex;align-items: center;- flex-grow: 1;- padding: 8px;+ flex: 1 1 auto;+ min-width: 0;+ padding: 8px 6px;overflow: hidden;gap: 0.5em;}@@ -205,7 +206,33 @@flex-shrink: 0;}+ .chats-list-container .project-color-ball.heartbeat {+ animation: chat-working-bubble 1500ms ease-in-out infinite;+ transform-origin: center;+ will-change: border-radius, transform;+ }++ @keyframes chat-working-bubble {+ 0% {+ border-radius: 50%;+ transform: rotate(0deg) scale(1);+ }+ 25% {+ border-radius: 0;+ transform: rotate(45deg) scale(0.9);+ }+ 75% {+ border-radius: 0;+ transform: rotate(405deg) scale(0.9);+ }+ 100% {+ border-radius: 50%;+ transform: rotate(405deg) scale(1);+ }+ }+.chat-name {+ min-width: 0;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;@@ -221,23 +248,14 @@background-color: var(--color-background-hover);}- .device-pointer .chat-container .chat-list-action-btn {- opacity: 0;- visibility: hidden;- pointer-events: none;- transition: opacity 0s;+ .device-pointer .chat-container .chat-list-action-btn,+ .device-touch .chat-container:not(.chat-selected) .chat-list-action-btn {+ display: none;}- .device-pointer .chat-container:hover .chat-list-action-btn {- opacity: 1;- visibility: visible;- pointer-events: auto;- }-- .device-touch .chats-list-container .chat-list-action-btn {- opacity: 1;- visibility: visible;- pointer-events: auto;+ .device-pointer .chat-container:hover .chat-list-action-btn,+ .device-touch .chat-container.chat-selected .chat-list-action-btn {+ display: inline-flex;}.empty-list-message {diff --git a/webui/components/sidebar/left-sidebar.html b/webui/components/sidebar/left-sidebar.htmlindex 6eb256e54..6616305ef 100644--- a/webui/components/sidebar/left-sidebar.html+++ b/webui/components/sidebar/left-sidebar.html@@ -108,6 +108,8 @@flex: 1 1 auto;/* Take all available space */max-height: 100%;+ margin-inline-start: calc(0px - var(--spacing-sm));+ width: calc(100% + var(--spacing-sm));overflow: hidden;}@@ -122,10 +124,17 @@max-height: 40%;/* Limit to 40% of viewport height when expanded */margin-top: 0;+ margin-inline-start: calc(0px - var(--spacing-sm));+ width: calc(100% + var(--spacing-sm));padding-top: var(--spacing-md);overflow: hidden;}+ #chats-section .section-header-row,+ #tasks-section .section-header {+ margin-inline-start: var(--spacing-sm);+ }+/* Flatten wrapper elements to maintain flex chain for inner scroll containers */#chats-section>x-component,#chats-section>x-component>div[x-data],@@ -203,4 +212,4 @@</style></body>-</html>\ No newline at end of file+</html>diff --git a/webui/js/AGENTS.md b/webui/js/AGENTS.mdindex ac6490801..5517a6354 100644--- a/webui/js/AGENTS.md+++ b/webui/js/AGENTS.md@@ -44,6 +44,7 @@- Convert standard TeX delimiters before Markdown parsing without touching inline or fenced code. Keep thought-card math rendering local to the agent-message handler rather than adding math flags to generic process-step or key/value rendering.- Do not expose secrets in localStorage, console logs, URLs, or WebSocket payloads.- Full message snapshots that start at backend log `no` 0 must replace the current message DOM before rendering; incremental snapshots should keep patching existing messages.+- Info log entries with `kvps.finished` complete the active process group and clear its running treatment.## Work Guidancediff --git a/webui/js/messages.js b/webui/js/messages.jsindex 4910efe0e..bccc3443d 100644--- a/webui/js/messages.js+++ b/webui/js/messages.js@@ -1321,6 +1321,7 @@ export function drawMessageInfo({}) {const title = cleanStepTitle(heading || content);let displayKvps = { ...kvps };+ delete displayKvps.finished;const contentText = String(content ?? "");const actionButtons = contentText.trim()? [@@ -1329,7 +1330,7 @@ export function drawMessageInfo({].filter(Boolean): [];- return drawProcessStep({+ const result = drawProcessStep({id,title,code: "INF",@@ -1340,6 +1341,9 @@ export function drawMessageInfo({actionButtons,log: arguments[0],});++ if (kvps?.finished) completeLastProcessGroup();+ return result;}/**