diff --git a/agent_core/core/hooks/usage.py b/agent_core/core/hooks/usage.py new file mode 100644 index 000000000..ebfd31399 --- /dev/null +++ b/agent_core/core/hooks/usage.py @@ -0,0 +1,121 @@ +"""Deliver async hooks in the request's context and drain them at shutdown. + +The loop belongs to a request, not to a long-lived model instance. Worker +threads inherit that ownership through ContextVars, including session context. +""" + +from __future__ import annotations + +import asyncio +import concurrent.futures +from contextvars import ContextVar +import logging +import threading + +_loop = ContextVar("usage_owner_loop", default=None) +_request_pending = ContextVar("usage_request_pending", default=None) +_pending: set = set() +_lock = threading.Lock() +_logger = logging.getLogger(__name__) + + +def _track(future): + # A Task is bound to its loop. Track a thread-safe completion handle so + # application shutdown can also drain workers owned by other running loops. + completion = concurrent.futures.Future() + with _lock: + _pending.add(completion) + + def done(item): + cancelled = item.cancelled() + error = None if cancelled else item.exception() + with _lock: + _pending.discard(completion) + if cancelled: + completion.cancel() + elif error is not None: + completion.set_exception(error) + _logger.error( + "Usage delivery failed", + exc_info=(type(error), error, error.__traceback__), + ) + else: + completion.set_result(None) + + future.add_done_callback(done) + return future + + +def dispatch_usage(hook, event) -> None: + """Submit once; failed hooks are observable and never automatically retried.""" + + async def deliver(): + await hook(event) + + try: + running = asyncio.get_running_loop() + except RuntimeError: + running = None + owner = _loop.get() or running + if owner is None: + # Synchronous callers have no event loop to own delivery. Finish the + # hook before returning. Local reporters must be safe across loops. + asyncio.run(deliver()) + return + if owner.is_closed(): + raise RuntimeError("Usage request's event loop is closed") + future = ( + owner.create_task(deliver()) + if owner is running + else asyncio.run_coroutine_threadsafe(deliver(), owner) + ) + _track(future) + request = _request_pending.get() + if request is not None: + request.append(future) + + +async def _join(futures): + if futures: + await asyncio.gather( + *( + asyncio.shield(asyncio.wrap_future(f)) + if isinstance(f, concurrent.futures.Future) + else asyncio.shield(f) + for f in futures + ), + return_exceptions=True, + ) + + +async def to_thread_with_usage(function, /, *args, **kwargs): + """Like to_thread, but delivery completes before a successful call returns. + + Cancellation leaves the worker tracked: shutdown drains it before closing + the reporter. No request is resubmitted after an uncertain outcome. + """ + request = [] + owner_token = _loop.set(asyncio.get_running_loop()) + pending_token = _request_pending.set(request) + try: + worker = _track( + asyncio.create_task(asyncio.to_thread(function, *args, **kwargs)) + ) + try: + return await asyncio.shield(worker) + finally: + if worker.done(): + await _join(request) + finally: + _request_pending.reset(pending_token) + _loop.reset(owner_token) + + +async def drain_usage() -> None: + """Wait for workers and hooks, including hooks submitted by finishing workers.""" + while True: + with _lock: + pending = list(_pending) + if not pending: + return + await _join(pending) diff --git a/agent_core/core/impl/image_gen/interface.py b/agent_core/core/impl/image_gen/interface.py index 08c85704e..f6bc19c39 100644 --- a/agent_core/core/impl/image_gen/interface.py +++ b/agent_core/core/impl/image_gen/interface.py @@ -18,6 +18,7 @@ if TYPE_CHECKING: from agent_core.core.errors import ClassifiedError +from agent_core.core.hooks.usage import dispatch_usage, to_thread_with_usage import asyncio import base64 import io @@ -197,9 +198,7 @@ def _report_usage_async( ) -> None: """Report image-generation usage if the hook is set (mirrors VLM). - Best-effort: scheduling onto the running loop can fail when invoked - from a worker thread without one, in which case the usage is dropped - with a warning rather than breaking generation. + Delivery uses the request's owning loop and is drained at shutdown. """ if not self._report_usage: return @@ -212,10 +211,7 @@ def _report_usage_async( output_tokens=output_tokens, cached_tokens=cached_tokens, ) - if self._main_loop is not None: - self._main_loop.call_soon_threadsafe( - lambda: asyncio.create_task(self._report_usage(event)) - ) + dispatch_usage(self._report_usage, event) except Exception as e: logger.warning(f"[IMAGE_GEN] Failed to report usage: {e}") @@ -307,8 +303,7 @@ def generate_image( async def generate_image_async(self, **kwargs) -> List[str]: """Async wrapper — runs generate_image in a thread pool.""" - loop = asyncio.get_event_loop() - return await loop.run_in_executor(None, lambda: self.generate_image(**kwargs)) + return await to_thread_with_usage(self.generate_image, **kwargs) # ──────────────────────── OpenAI provider ──────────────────────────────── diff --git a/agent_core/core/impl/llm/interface.py b/agent_core/core/impl/llm/interface.py index 77249329c..dffb53375 100644 --- a/agent_core/core/impl/llm/interface.py +++ b/agent_core/core/impl/llm/interface.py @@ -13,7 +13,7 @@ from __future__ import annotations -import asyncio +from agent_core.core.hooks.usage import dispatch_usage, to_thread_with_usage import contextvars import re import time @@ -614,13 +614,7 @@ def _report_usage_async( output_tokens=output_tokens, cached_tokens=cached_tokens, ) - # Schedule the async hook on the event loop - try: - loop = asyncio.get_running_loop() - loop.create_task(self._report_usage(event)) - except RuntimeError: - # No running event loop - create one for this call - asyncio.run(self._report_usage(event)) + dispatch_usage(self._report_usage, event) except Exception as e: logger.warning(f"[LLM] Failed to report usage: {e}") @@ -1260,7 +1254,7 @@ async def generate_response_async( ) token = _active_session_key.set(usage_key) try: - return await asyncio.to_thread( + return await to_thread_with_usage( self._generate_response_sync, system_prompt, user_prompt, @@ -2335,7 +2329,7 @@ async def generate_response_with_session_async( self._begin_call(prompt_name=prompt_name, call_type=call_type, task_id=task_id) token = _active_session_key.set(f"{task_id}:{call_type}") try: - return await asyncio.to_thread( + return await to_thread_with_usage( self._generate_response_with_session_sync, task_id, call_type, diff --git a/agent_core/core/impl/video_gen/interface.py b/agent_core/core/impl/video_gen/interface.py index d621985c6..84b4d8eb7 100644 --- a/agent_core/core/impl/video_gen/interface.py +++ b/agent_core/core/impl/video_gen/interface.py @@ -24,6 +24,7 @@ if TYPE_CHECKING: from agent_core.core.errors import ClassifiedError +from agent_core.core.hooks.usage import dispatch_usage, to_thread_with_usage import asyncio import base64 import json @@ -244,10 +245,7 @@ def _report_usage_async( output_tokens=output_tokens, cached_tokens=cached_tokens, ) - if self._main_loop is not None: - self._main_loop.call_soon_threadsafe( - lambda: asyncio.create_task(self._report_usage(event)) - ) + dispatch_usage(self._report_usage, event) except Exception as e: logger.warning(f"[VIDEO_GEN] Failed to report usage: {e}") @@ -396,8 +394,7 @@ def generate_video( async def generate_video_async(self, **kwargs) -> List[str]: """Async wrapper — runs generate_video in a thread pool.""" - loop = asyncio.get_running_loop() - return await loop.run_in_executor(None, lambda: self.generate_video(**kwargs)) + return await to_thread_with_usage(self.generate_video, **kwargs) # ──────────────────────── OpenAI / Sora 2 ──────────────────────────────── diff --git a/agent_core/core/impl/vlm/interface.py b/agent_core/core/impl/vlm/interface.py index 5e23001be..f08663ea4 100644 --- a/agent_core/core/impl/vlm/interface.py +++ b/agent_core/core/impl/vlm/interface.py @@ -12,7 +12,7 @@ from __future__ import annotations -import asyncio +from agent_core.core.hooks.usage import dispatch_usage, to_thread_with_usage import base64 import os import re @@ -28,6 +28,7 @@ ReasoningDecision, resolve_reasoning, ) +from agent_core.core.models.output import OutputIntent from agent_core.utils.token import billable_tokens from agent_core.core.hooks import ( GetTokenCountHook, @@ -235,6 +236,8 @@ def describe_image( system_prompt: str | None = None, user_prompt: str | None = "Describe this image in detail.", log_response: bool = True, + *, + output_intent: OutputIntent | None = None, ) -> str: """Read an image from disk and describe it using the VLM. @@ -258,6 +261,7 @@ def describe_image( system_prompt=system_prompt, user_prompt=user_prompt, log_response=log_response, + output_intent=output_intent, ) def describe_image_bytes( @@ -266,7 +270,9 @@ def describe_image_bytes( system_prompt: str | None = None, user_prompt: str | None = "Describe this image in detail.", log_response: bool = True, - json_mode: bool = True, + json_mode: bool | None = None, + *, + output_intent: OutputIntent | None = None, ) -> str: """Describe an image from raw bytes using the VLM. @@ -279,6 +285,12 @@ def describe_image_bytes( Returns: Textual description of the image. """ + intent = output_intent or OutputIntent("json" if json_mode else "text") + if json_mode is not None and bool(json_mode) != (intent.format == "json"): + raise ValueError("json_mode conflicts with output_intent") + system_prompt = intent.system_prompt(system_prompt) + user_prompt = user_prompt or "Describe this image in detail." + json_mode = intent.format == "json" try: if log_response: logger.info(f"[LLM SEND] system={system_prompt} | user={user_prompt}") @@ -305,7 +317,7 @@ def describe_image_bytes( ) elif self.provider == "gemini": response = self._gemini_describe_bytes( - image_bytes, system_prompt, user_prompt + image_bytes, system_prompt, user_prompt, json_mode=json_mode ) elif self.provider == "byteplus": response = self._byteplus_describe_bytes( @@ -338,7 +350,7 @@ def describe_image_bytes( if log_response: logger.info(f"[LLM RECV] {cleaned}") - return cleaned + return intent.validate(cleaned) except Exception as e: from agent_core.core.errors import ClassifiedError from agent_core.core.impl.llm.errors import classify_llm_error @@ -354,6 +366,8 @@ async def generate_response_async( user_prompt: Optional[str] = None, debug: bool = False, log_response: bool = True, + *, + output_intent: OutputIntent | None = None, ) -> str: """Async wrapper that defers the blocking call to a worker thread.""" if debug: @@ -364,12 +378,13 @@ async def generate_response_async( f.write(image_bytes) logger.info(f"[DEBUG] Image saved to {file_name}") - return await asyncio.to_thread( + return await to_thread_with_usage( self.describe_image_bytes, image_bytes, system_prompt, user_prompt, log_response, + output_intent=output_intent, ) def describe_image_ocr( @@ -506,10 +521,7 @@ def _report_usage_async( output_tokens=output_tokens, cached_tokens=cached_tokens, ) - # Schedule async reporting - asyncio.get_event_loop().call_soon( - lambda: asyncio.create_task(self._report_usage(event)) - ) + dispatch_usage(self._report_usage, event) except Exception as e: logger.warning(f"[VLM] Failed to report usage: {e}") @@ -574,7 +586,7 @@ def _reasoning(self) -> Optional[ReasoningDecision]: ) def _openai_describe_bytes( - self, image_bytes: bytes, sys: str | None, usr: str, json_mode: bool = True + self, image_bytes: bytes, sys: str | None, usr: str, json_mode: bool = False ) -> Dict[str, Any]: """OpenAI/Grok vision request with automatic prompt caching metrics.""" img_b64 = base64.b64encode(image_bytes).decode() @@ -703,10 +715,17 @@ def _ollama_describe_bytes( token_count_output = result.get("eval_count", 0) total_tokens = token_count_input + token_count_output + self._report_usage_async( + "vlm_remote", + self.provider, + self.model, + token_count_input, + token_count_output, + ) return {"tokens_used": total_tokens or 0, "content": content or ""} def _gemini_describe_bytes( - self, image_bytes: bytes, sys: str | None, usr: str + self, image_bytes: bytes, sys: str | None, usr: str, json_mode: bool = False ) -> Dict[str, Any]: """Gemini vision request with implicit caching metrics.""" if not self._gemini_client: @@ -718,7 +737,7 @@ def _gemini_describe_bytes( image_bytes_list=[image_bytes], system_prompt=sys, temperature=self.temperature, - json_mode=False, + json_mode=json_mode, ) # Record cache metrics @@ -801,9 +820,26 @@ def _byteplus_describe_bytes( or choices[0].get("delta", {}).get("content", "") or "" ).strip() - total_tokens = result.get("usage", {}).get("total_tokens", 0) - - return {"tokens_used": total_tokens or 0, "content": content or ""} + usage = result.get("usage") or {} + input_tokens = usage.get("prompt_tokens", 0) + output_tokens = usage.get("completion_tokens", 0) + cached_tokens = (usage.get("prompt_tokens_details") or {}).get( + "cached_tokens", 0 + ) + total_tokens = usage.get("total_tokens", input_tokens + output_tokens) + self._report_usage_async( + "vlm_byteplus", + self.provider, + self.model, + input_tokens, + output_tokens, + cached_tokens, + ) + return { + "tokens_used": total_tokens or 0, + "content": content or "", + "cached_tokens": cached_tokens, + } return {"tokens_used": 0, "content": ""} diff --git a/agent_core/core/models/output.py b/agent_core/core/models/output.py new file mode 100644 index 000000000..9bbbd3881 --- /dev/null +++ b/agent_core/core/models/output.py @@ -0,0 +1,51 @@ +"""Output contracts independent of a provider's wire format.""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +from typing import Any, Literal + + +@dataclass(frozen=True) +class OutputIntent: + format: Literal["text", "ocr", "json"] = "text" + schema: dict[str, Any] | None = None + + def __post_init__(self): + if self.format not in ("text", "ocr", "json"): + raise ValueError(f"Unsupported output format: {self.format}") + if self.schema is not None: + if self.format != "json": + raise ValueError("A JSON schema requires JSON output") + from jsonschema.validators import validator_for + + validator_for(self.schema).check_schema(self.schema) + + def system_prompt(self, original: str | None) -> str | None: + if self.format == "text": + return original + instruction = ( + "Extract all text exactly as it appears, preserving line breaks. " + "Return only raw text without commentary or markdown." + ) + if self.format == "json": + instruction = ( + "Return a valid JSON object only, without markdown or commentary." + ) + if self.schema is not None: + instruction += " The JSON must satisfy this schema: " + json.dumps( + self.schema + ) + return "\n\n".join(part for part in (original, instruction) if part) + + def validate(self, content: str) -> str: + if self.format == "json": + value = json.loads(content) + if not isinstance(value, dict): + raise ValueError("Expected a JSON object from the model") + if self.schema is not None: + from jsonschema import validate + + validate(value, self.schema) + return content diff --git a/app/agent_app/manager.py b/app/agent_app/manager.py index ee1bf7ade..e33f1ea0e 100644 --- a/app/agent_app/manager.py +++ b/app/agent_app/manager.py @@ -4136,61 +4136,94 @@ def uses(name: str) -> bool: return new_start, new_env - async def _wait_for_server(self, port: int, timeout: int = 10) -> bool: - """Wait for a server to start listening on a port.""" - for _ in range(timeout * 2): - if self._is_port_in_use(port): - return True - await asyncio.sleep(0.5) - return False - - async def _wait_for_health_check(self, url: str, timeout: int = 15) -> bool: - """Wait for a server's health endpoint to respond with HTTP 200.""" - import urllib.request - import urllib.error - - for _ in range(timeout * 2): + async def _probe_ready(self, probe, timeout: float, process=None) -> bool: + """Bound retries by elapsed time, keep the loop responsive, stop on exit.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + max(0.0, float(timeout)) + while loop.time() < deadline: + if process is not None and process.poll() is not None: + return False + task = asyncio.create_task(probe()) try: - req = urllib.request.Request(url, method="GET") - with urllib.request.urlopen(req, timeout=2) as response: - if response.status == 200: - return True - except ( - urllib.error.URLError, - urllib.error.HTTPError, - TimeoutError, - OSError, - ): + # Poll child exit without cancelling a healthy but slow probe. + # A single operation may use the remaining overall deadline. + while not task.done(): + remaining = deadline - loop.time() + if remaining <= 0 or ( + process is not None and process.poll() is not None + ): + return False + await asyncio.wait({task}, timeout=min(0.1, remaining)) + ready = task.result() + if ready and (process is None or process.poll() is None): + return True + except (OSError, asyncio.TimeoutError): pass - await asyncio.sleep(0.5) + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + remaining = deadline - loop.time() + if remaining > 0: + await asyncio.sleep(min(0.1, remaining)) return False + async def _wait_for_server( + self, port: int, timeout: float = 10, process=None + ) -> bool: + async def probe(): + reader, writer = await asyncio.open_connection("127.0.0.1", port) + writer.close() + await writer.wait_closed() + return True + + return await self._probe_ready(probe, timeout, process) + + async def _wait_for_health_check( + self, url: str, timeout: float = 15, process=None + ) -> bool: + """Read-only HTTP probes with a total deadline; never block the event loop.""" + import aiohttp + + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=2)) as client: + + async def probe(): + try: + async with client.get(url) as response: + return response.status == 200 + except aiohttp.ClientError: + return False + + return await self._probe_ready(probe, timeout, process) + async def _check_health_with_strategy( - self, health_cfg, port: int, process, timeout: int = 30 + self, health_cfg, port: int, process, timeout: float = 30 ) -> bool: - """Check health using configured strategy (http_get, tcp, process_alive, or URL string).""" + """All strategies share deadline, cancellation and process-exit handling.""" if isinstance(health_cfg, str): - # Backward compat: plain URL string - return await self._wait_for_health_check(health_cfg, timeout=timeout) - + return await self._wait_for_health_check( + health_cfg, timeout=timeout, process=process + ) if not isinstance(health_cfg, dict): - # No health config — just check if port is listening - return await self._wait_for_server(port, timeout=timeout) - + return await self._wait_for_server(port, timeout=timeout, process=process) strategy = health_cfg.get("strategy", "tcp") - timeout = health_cfg.get("timeout", timeout) - + timeout = float(health_cfg.get("timeout", timeout)) if strategy == "http_get": - url = health_cfg.get("url", f"http://localhost:{port}") - url = url.replace("{{PORT}}", str(port)) - return await self._wait_for_health_check(url, timeout=timeout) - elif strategy == "tcp": - return await self._wait_for_server(port, timeout=timeout) - elif strategy == "process_alive": - await asyncio.sleep(2) - return process.poll() is None - - return await self._wait_for_server(port, timeout=timeout) + url = health_cfg.get("url", f"http://localhost:{port}").replace( + "{{PORT}}", str(port) + ) + return await self._wait_for_health_check( + url, timeout=timeout, process=process + ) + if strategy == "process_alive": + loop = asyncio.get_running_loop() + stable_at = loop.time() + 2 + + async def probe(): + return loop.time() >= stable_at + + return await self._probe_ready(probe, timeout, process) + return await self._wait_for_server(port, timeout=timeout, process=process) def validate_bridge_token(self, token: str) -> Optional[str]: """ diff --git a/app/agent_app/op_smoke.py b/app/agent_app/op_smoke.py index f763148c1..5f6990ec8 100644 --- a/app/agent_app/op_smoke.py +++ b/app/agent_app/op_smoke.py @@ -241,6 +241,10 @@ def _invoke( request = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_S) as response: + # Complete bounded response handling before closing the connection. + # A transport failure after a write has an uncertain outcome: report + # it once; never resubmit a potentially mutating operation. + response.read(64 * 1024) return OpSmokeResult(name=name, ok=True, status=response.status, detail="") except urllib.error.HTTPError as e: try: diff --git a/app/agent_app/test_data_safety.py b/app/agent_app/test_data_safety.py index 0675c1f7c..ab1cc59b7 100644 --- a/app/agent_app/test_data_safety.py +++ b/app/agent_app/test_data_safety.py @@ -1965,14 +1965,15 @@ async def _scenario(): class _Gate26(_http26.BaseHTTPRequestHandler): def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) SEEN26["token"] = self.headers.get("X-A2App-Token") ok = SEEN26["token"] == "tok-26-secret" + body = b'{"ok": true}' if ok else b'{"error": "agent token required"}' self.send_response(200 if ok else 401) self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) self.end_headers() - self.wfile.write( - b'{"ok": true}' if ok else b'{"error": "agent token required"}' - ) + self.wfile.write(body) def log_message(self, *a): pass @@ -1990,6 +1991,7 @@ def log_message(self, *a): assert SEEN26["token"] == "tok-26-secret", "X-A2App-Token never crossed the wire" assert result.ok and result.status == 200, (result.status, result.detail) server26.shutdown() + server26.server_close() print("§26 changed-op smoke agent token: OK") print("\nData-safety acceptance: ALL GREEN") diff --git a/app/agent_base.py b/app/agent_base.py index e545a0284..e0fbf63c5 100644 --- a/app/agent_base.py +++ b/app/agent_base.py @@ -559,8 +559,8 @@ async def clear_session(self, session_id: str) -> bool: Chat-message rows are cleared by the adapter (chat storage is a UI concern); this handles the agent-side state. """ - if session_id in self.busy_sessions: - await self.request_run_stop(session_id) + # Runs can exist as queued continuations without a UI busy marker. + await self.request_run_stop(session_id) if not self.session_manager.clear_session(session_id): return False self._persist_llm_session(session_id) @@ -1737,7 +1737,7 @@ async def request_run_stop(self, session_id: str) -> bool: stopped = await self.session_runtime.request_stop(session_id) except Exception: logger.error(f"[RUN] request_stop failed for {session_id}", exc_info=True) - stopped = False + raise if not stopped: # Nothing was running (stale UI state) — settle the UI to idle. self._emit_run_state(session_id, "idle") diff --git a/app/config/settings.json b/app/config/settings.json index c9bd15ffa..8a6f992e3 100644 --- a/app/config/settings.json +++ b/app/config/settings.json @@ -1,5 +1,5 @@ { - "version": "1.4.3", + "version": "1.4.4", "general": { "agent_name": "CraftBot", "os_language": "en", diff --git a/app/console.py b/app/console.py new file mode 100644 index 000000000..25c86dec5 --- /dev/null +++ b/app/console.py @@ -0,0 +1,19 @@ +"""Consistent Unicode console output for source and installed entry points.""" + +import os +import sys + + +def configure_console() -> None: + if sys.platform != "win32": + return + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is not None: + try: + reconfigure(encoding="utf-8", errors="replace") + except (OSError, ValueError): + pass + # Child interpreters must agree when their output is redirected to a log. + os.environ["PYTHONIOENCODING"] = "utf-8" + os.environ["PYTHONUTF8"] = "1" diff --git a/app/data/action/render_ui.py b/app/data/action/render_ui.py index ded289775..bb647bcc9 100644 --- a/app/data/action/render_ui.py +++ b/app/data/action/render_ui.py @@ -15,7 +15,9 @@ "responsive 360-900px wide, full-height page; the host shows the title. " "Colors must follow host light/dark: only --cb-{bg,surface,text,muted,border,accent,font} " "or light-dark(light,dark), not prefers-color-scheme; redraw canvas on window " - "'craftbot-theme'. Restore window.craftbot.state and " + "'craftbot-theme'. Static native input/select/textarea controls persist automatically: give " + "each a stable id (or data-craftbot-state key). Use persistence='manual' for dynamic/custom " + "canvas/3D/application state: restore window.craftbot.state and " "call window.craftbot.saveState(obj) on change (JSON, 64KB; store deadlines and " "timestamps). Fetched data needs loading/error states, real timestamps and checked " "units. Keep code compact. Afterwards send at most one short sentence; don't ask for " @@ -37,6 +39,10 @@ "type": "string", "description": "Optional: earlier render_ui id in this session, to revise with complete new HTML (keep state keys).", }, + "persistence": { + "type": "string", + "description": "controls (default): persist static native controls by stable id/data-craftbot-state, hydrated before scripts run; manual: explicitly restore/save dynamic DOM or custom state with craftbot.state/saveState; none: stateless output. Never persist secrets.", + }, "libraries": { "type": "array", "items": {"type": "string"}, @@ -76,6 +82,7 @@ async def render_ui(input_data: dict) -> dict: from app.generative_ui import make_artifact, read_images try: + input_data = {"persistence": "controls", **input_data} artifact = make_artifact(input_data) except ValueError as exc: return {"status": "error", "message": str(exc)} diff --git a/app/generative_ui.py b/app/generative_ui.py index 9712d62b7..98230a564 100644 --- a/app/generative_ui.py +++ b/app/generative_ui.py @@ -2,6 +2,7 @@ import re import uuid +from html.parser import HTMLParser from pathlib import Path MAX_HTML_BYTES = 512_000 @@ -15,6 +16,45 @@ IMAGE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,39}") +def persistence_contract(html: str, mode: object) -> str: + """Validate a declared persistence strategy, without inspecting JS wording.""" + if mode not in ("controls", "manual", "none"): + raise ValueError("persistence must be controls, manual or none.") + if mode != "controls": + return mode + + class Controls(HTMLParser): + keys: dict[str, str] = {} + + def handle_starttag(self, tag, attrs): + attrs = dict(attrs) + kind = (attrs.get("type") or "text").lower() + if tag not in ("input", "select", "textarea") or ( + tag == "input" and kind in ("button", "submit", "reset", "image") + ): + return + if kind in ("password", "file", "hidden"): + raise ValueError( + "Sensitive/file/hidden controls require manual persistence; never save secrets." + ) + key = attrs.get("data-craftbot-state") or attrs.get("id") + if ( + not key + or not re.fullmatch(r"[A-Za-z0-9_-]{1,80}", key) + or key in ("__proto__", "constructor", "prototype") + ): + raise ValueError( + "Every persisted control needs a stable id or data-craftbot-state key." + ) + if key in self.keys and not (kind == "radio" and self.keys[key] == "radio"): + raise ValueError(f"Duplicate persistence key: {key}") + self.keys[key] = kind + + parser = Controls() + parser.feed(html) + return mode + + def normalize_origins(value: object, field: str) -> list[str]: """Accept exact public HTTPS origins, never CSP expressions or local hosts.""" if not isinstance(value, list) or len(value) > MAX_ORIGINS: @@ -146,4 +186,5 @@ def make_artifact(data: dict, revision: int = 1) -> dict: "connect_origins": connect_origins, "image_origins": image_origins, "libraries": libraries, + "persistence": persistence_contract(html, data.get("persistence", "manual")), } diff --git a/app/mini_browser/core.py b/app/mini_browser/core.py index a64c6e0a3..79dcfc29b 100644 --- a/app/mini_browser/core.py +++ b/app/mini_browser/core.py @@ -418,6 +418,7 @@ def __init__( # the saved pages reopen at a launch, nothing is saved. self._restoring = False self._reopening: Set[str] = set() # tabs whose reopened page has not loaded + self._reopen_tasks: Dict[str, asyncio.Task] = {} self._pages_saved: Optional[resume.Pages] = None self._pages_handle: Optional[asyncio.TimerHandle] = None self._frame_unsaved: Optional[resume.LastFrame] = None @@ -858,6 +859,10 @@ async def _teardown(self) -> None: self._watchdog_task = None self._cancel_saves() self._reopening.clear() + for task in self._reopen_tasks.values(): + if not task.done(): + task.cancel() + self._reopen_tasks.clear() self._pages_saved = None self._nav_refresh.clear() self._nav_dirty.clear() @@ -1330,7 +1335,7 @@ async def _reopen_pages(self, profile: Path) -> None: tab.url, tab.title, tab.loading = url, page.title, True self._reopening.add(tab.id) reopened[index] = tab - self.spawn(self._reopen(tab, url)) + self._reopen_tasks[tab.id] = self.spawn(self._reopen(tab, url)) viewed = reopened.get(saved.viewed) or next(iter(reopened.values()), None) if viewed is not None: self.viewed_tab_id = viewed.id @@ -1340,11 +1345,38 @@ async def _reopen_pages(self, profile: Path) -> None: async def _reopen(self, tab: Tab, url: str) -> None: try: - await self._open_in_background(tab, url) + await self._goto(tab, url) finally: self._reopening.discard(tab.id) self._schedule_nav_refresh(tab) + async def _wait_for_reopen(self, tab: Tab) -> None: + """Metadata can be restored before Chromium commits the document. + + Only operations on this tab wait. Shield the shared navigation from + cancellation of an individual agent operation; teardown still cancels it. + """ + task = self._reopen_tasks.get(tab.id) + if task is not None: + try: + await asyncio.shield(task) + except asyncio.CancelledError: + if tab.closed: + raise self._closed_error(tab) from None + if not task.cancelled(): + raise + finally: + if task.done() and self._reopen_tasks.get(tab.id) is task: + self._reopen_tasks.pop(tab.id, None) + if tab.closed: + raise self._closed_error(tab) + + def _cancel_reopen(self, tab: Tab) -> None: + restore = self._reopen_tasks.pop(tab.id, None) + if restore is not None and not restore.done(): + restore.cancel() + self._reopening.discard(tab.id) + # ═════════════════════════════════════════════════════════════════════════ # Streaming # ═════════════════════════════════════════════════════════════════════════ @@ -1596,6 +1628,7 @@ async def ui_control(self, tab_id: str, take: bool) -> None: return tab.user_control = take if take: + self._cancel_reopen(tab) tab.touch_user() self._agent_notice( tab, @@ -1737,6 +1770,8 @@ def _note_user_input(self, tab: Tab, takes_control: bool = True) -> None: Runs BEFORE the input is dispatched to the page: an agent operation in flight on the tab sees ``user_control`` at its next step and stops. """ + if takes_control: + self._cancel_reopen(tab) tab.touch_user() self._touch() if ( @@ -1818,6 +1853,7 @@ async def agent_op(self, owner: str, op: str, params: dict) -> dict: try: async with tab.lock: if self.tabs.get(tab.id) is tab: + await self._wait_for_reopen(tab) refused = self._control_refusal(tab, op, params) if refused is not None: return self._finish(refused, tab, owner=owner) @@ -3072,7 +3108,7 @@ def _remove_tab(self, tab: Tab) -> None: position = order.index(tab.id) del self.tabs[tab.id] tab.mark_closed(CLOSED_TAB) # an operation on it ends at once - self._reopening.discard(tab.id) + self._cancel_reopen(tab) self._retire_secrets(tab) self._cuts.pop(tab.id, None) self._stream.forget_tab(tab.id) diff --git a/app/triggers/runtime.py b/app/triggers/runtime.py index 612b7fdd8..0877e68de 100644 --- a/app/triggers/runtime.py +++ b/app/triggers/runtime.py @@ -54,10 +54,9 @@ def remove_session_log_sink(session_id: str) -> None: # type: ignore[misc] # cross-session parallelism (LLM rate limits, local resource pressure). DEFAULT_MAX_CONCURRENT_TURNS = 3 -# How long a user force-stop waits for the cancelled turn to settle before -# finalizing anyway. Cancellation is normally near-instant (LLM HTTP calls -# and async actions unwind at the next await); this guard only exists so a -# stuck await can never leave the UI on "stopping" forever. +# How long a stop/clear request waits before reporting failure. Timed-out +# turns remain stopping until they actually settle; callers must not reset +# context while old work can still write to it. STOP_SETTLE_TIMEOUT_S = 15.0 ReactFn = Callable[[Trigger], Awaitable[None]] @@ -73,11 +72,12 @@ class _StopSignal: await full shutdown (the UI's stop-spinner ends on this). """ - __slots__ = ("requested", "settled") + __slots__ = ("requested", "settled", "processes_stopped") def __init__(self) -> None: self.requested = False self.settled = asyncio.Event() + self.processes_stopped = asyncio.Event() # Sources that must never be folded into another trigger's turn. @@ -322,50 +322,70 @@ async def request_stop(self, session_id: str) -> bool: Returns True when there was a run to stop. Awaits full settlement (bounded by STOP_SETTLE_TIMEOUT_S) before returning, so the caller - can treat the return as "everything is shut". + can treat a successful return as "everything is shut". Raises on + timeout or process-shutdown failure instead of claiming success. """ + signal = self._stops.get(session_id) + if signal is not None: + # Repeated stop/clear requests join the same cancellation. A + # second cancel could interrupt the first turn's cleanup. + await asyncio.wait_for(signal.settled.wait(), STOP_SETTLE_TIMEOUT_S) + return True purged = await self._purge_continuations(session_id) + signal = self._stops.get(session_id) + if signal is not None: + await asyncio.wait_for(signal.settled.wait(), STOP_SETTLE_TIMEOUT_S) + return True turn = self._turns.get(session_id) turn_inflight = turn is not None and not turn.done() if not turn_inflight: - if purged and self._on_stopped: - # The run lived only as queued continuation rows. - await self._on_stopped(session_id) + if purged: + # Fence fresh work while the parked run's async finalizer + # settles. Overlapping requests join this stop as well. + signal = self._stops[session_id] = _StopSignal() + try: + if self._on_stopped: + await self._on_stopped(session_id) + finally: + self._stops.pop(session_id, None) + signal.settled.set() return bool(purged) signal = self._stops.setdefault(session_id, _StopSignal()) signal.requested = True + turn.cancel() - # Kill real OS work first so pool threads blocked on a child process - # unblock, then cancel the turn's await chain. Blocking kill runs in - # a worker thread to keep the event loop free. + # Cancel before yielding so a naturally finishing turn cannot escape + # settlement. The consumer holds this lane until OS work is shut down. try: from agent_core.core.impl.action.cancellation import ( kill_session_processes, ) - await asyncio.get_running_loop().run_in_executor( + kill = asyncio.get_running_loop().run_in_executor( None, kill_session_processes, session_id ) + # A disconnected caller must not release the lane while the + # process-kill worker can still affect this session's next run. + kill.add_done_callback(lambda _: signal.processes_stopped.set()) + await asyncio.shield(kill) except Exception as e: + signal.processes_stopped.set() logger.warning(f"[SessionRuntime] Process kill failed: {e}") + raise - turn.cancel() try: await asyncio.wait_for(signal.settled.wait(), STOP_SETTLE_TIMEOUT_S) except asyncio.TimeoutError: - # The turn is stuck in a non-cancellable await. Finalize anyway: - # the UI must reach idle, and the abandoned coroutine can no - # longer enqueue continuations once its triggers settle. + # Keep the lane stopping: resetting context while the old turn + # can still write would resurrect cleared work. A retry joins + # this signal, and normal settlement still finalizes it once. logger.error( f"[SessionRuntime] Stop settlement timed out for {session_id}; " - "finalizing forcefully." + "the turn is still stopping." ) - self._stops.pop(session_id, None) - await self._purge_continuations(session_id) - if self._on_stopped: - await self._on_stopped(session_id) + raise return True async def _purge_continuations(self, session_id: str) -> int: @@ -421,6 +441,20 @@ def _ensure_loop(self, session_id: str) -> None: name=f"session-loop-{session_id}", ) + async def _run_turn(self, session_id: str, trig: Trigger) -> None: + signal = self._stops.get(session_id) + if signal is not None: + await signal.settled.wait() + try: + async with self._turn_semaphore: + await self._react(trig) + finally: + signal = self._stops.get(session_id) + if signal is not None and signal.requested: + # Also settle a turn that swallowed cancellation or returned + # while cancellation was requested. + raise asyncio.CancelledError + async def _consume(self, session_id: str, queue: SessionTriggerQueue) -> None: """The serial agent loop for one session: claim → react → settle. @@ -490,21 +524,20 @@ async def _consume(self, session_id: str, queue: SessionTriggerQueue) -> None: trig = _merge_triggers(trig, extras) try: - async with self._turn_semaphore: - # The turn runs as its own task so request_stop can - # cancel exactly this turn without tearing down the - # session loop. - turn = asyncio.create_task( - self._react(trig), name=f"turn-{session_id}" - ) - self._turns[session_id] = turn - try: - await turn - finally: - self._turns.pop(session_id, None) + # Track capacity waits too: claimed work must not start + # after a stop/clear simply because another lane was busy. + turn = asyncio.create_task( + self._run_turn(session_id, trig), name=f"turn-{session_id}" + ) + self._turns[session_id] = turn + try: + await turn + finally: + self._turns.pop(session_id, None) except asyncio.CancelledError: signal = self._stops.get(session_id) if signal is not None and signal.requested and self._running: + await signal.processes_stopped.wait() # User force-stop, not process shutdown: the rows were # consumed by user intent — ack them (nack would # redeliver and restart the very work the user diff --git a/app/ui_layer/adapters/base.py b/app/ui_layer/adapters/base.py index c61949f9c..dc5e2011f 100644 --- a/app/ui_layer/adapters/base.py +++ b/app/ui_layer/adapters/base.py @@ -260,9 +260,9 @@ def _subscribe_events(self) -> None: # Default event handlers - subclasses can override for custom behavior # ───────────────────────────────────────────────────────────────────── - def _handle_user_message(self, event: UIEvent) -> None: + def _handle_user_message(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle user message event.""" - asyncio.create_task( + return asyncio.create_task( self._display_chat_message( "You", event.data.get("message", ""), @@ -272,7 +272,7 @@ def _handle_user_message(self, event: UIEvent) -> None: ) ) - def _handle_agent_message(self, event: UIEvent) -> None: + def _handle_agent_message(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle agent message event.""" from app.onboarding import onboarding_manager @@ -302,7 +302,7 @@ def _handle_agent_message(self, event: UIEvent) -> None: ChatMessageOption(label=str(o), value=str(o)) for o in question["options"] ] - asyncio.create_task( + return asyncio.create_task( self._display_chat_message( agent_name, event.data.get("message", ""), @@ -316,9 +316,9 @@ def _handle_agent_message(self, event: UIEvent) -> None: ) ) - def _handle_system_message(self, event: UIEvent) -> None: + def _handle_system_message(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle system message event.""" - asyncio.create_task( + return asyncio.create_task( self._display_chat_message( "System", event.data.get("message", ""), @@ -328,9 +328,9 @@ def _handle_system_message(self, event: UIEvent) -> None: ) ) - def _handle_error_message(self, event: UIEvent) -> None: + def _handle_error_message(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle error message event.""" - asyncio.create_task( + return asyncio.create_task( self._display_chat_message( "Error", event.data.get("message", ""), @@ -339,9 +339,9 @@ def _handle_error_message(self, event: UIEvent) -> None: ) ) - def _handle_info_message(self, event: UIEvent) -> None: + def _handle_info_message(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle info message event.""" - asyncio.create_task( + return asyncio.create_task( self._display_chat_message( "Info", event.data.get("message", ""), @@ -350,11 +350,11 @@ def _handle_info_message(self, event: UIEvent) -> None: ) ) - def _handle_action_start(self, event: UIEvent) -> None: + def _handle_action_start(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle action start event.""" if self.action_panel: session_id = event.data.get("session_id") or "main" - asyncio.create_task( + return asyncio.create_task( self.action_panel.add_item( ActionItem( id=event.data.get("action_id", ""), @@ -367,7 +367,7 @@ def _handle_action_start(self, event: UIEvent) -> None: ) ) - def _handle_action_end(self, event: UIEvent) -> None: + def _handle_action_end(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle action end event.""" if self.action_panel: status = "error" if event.data.get("error") else "completed" @@ -378,7 +378,7 @@ def _handle_action_end(self, event: UIEvent) -> None: # Get output and error data output = event.data.get("output") error_message = event.data.get("error_message") - asyncio.create_task( + return asyncio.create_task( self.action_panel.update_item_by_name( action_name=action_name, session_id=session_id, @@ -394,10 +394,10 @@ def _handle_reasoning(self, event: UIEvent) -> None: it into the session's inline activity feed.""" pass - def _handle_state_change(self, event: UIEvent) -> None: + def _handle_state_change(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle agent state change event.""" if self.status_bar: - asyncio.create_task( + return asyncio.create_task( self.status_bar.set_status(event.data.get("status_message", "")) ) @@ -412,25 +412,25 @@ def _handle_gui_mode_change(self, event: UIEvent) -> None: if self.footage_component: self.footage_component.set_visible(event.data.get("gui_mode", False)) - def _handle_footage_update(self, event: UIEvent) -> None: + def _handle_footage_update(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle footage update event.""" if self.footage_component: - asyncio.create_task( + return asyncio.create_task( self.footage_component.update(event.data.get("image_bytes", b"")) ) - def _handle_footage_clear(self, event: UIEvent) -> None: + def _handle_footage_clear(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle footage clear event.""" if self.footage_component: - asyncio.create_task(self.footage_component.clear()) + return asyncio.create_task(self.footage_component.clear()) def _handle_show_menu(self, event: UIEvent) -> None: """Handle show menu event. Override in Browser adapter.""" pass - def _handle_shutdown(self, event: UIEvent) -> None: + def _handle_shutdown(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle shutdown event. Override in adapters for specific cleanup.""" - asyncio.create_task(self.stop()) + return asyncio.create_task(self.stop()) # ───────────────────────────────────────────────────────────────────── # Helper methods diff --git a/app/ui_layer/adapters/browser_adapter.py b/app/ui_layer/adapters/browser_adapter.py index bf1740473..dd6499394 100644 --- a/app/ui_layer/adapters/browser_adapter.py +++ b/app/ui_layer/adapters/browser_adapter.py @@ -1086,13 +1086,13 @@ async def _handle_enhance_prompt(self, data: Dict[str, Any], ws) -> None: except Exception as e: logger.warning(f"[BROWSER ADAPTER] enhance_prompt failed: {e}") - def _handle_reasoning(self, event: UIEvent) -> None: + def _handle_reasoning(self, event: UIEvent) -> Optional[asyncio.Task]: """Handle reasoning event — add it to the session's activity feed.""" session_id = event.data.get("session_id") or "main" reasoning_id = event.data.get("reasoning_id", "") content = event.data.get("content", "") - asyncio.create_task( + return asyncio.create_task( self._action_panel.add_item( ActionItem( id=reasoning_id, @@ -1105,7 +1105,7 @@ def _handle_reasoning(self, event: UIEvent) -> None: ) ) - def _handle_run_state_change(self, event: UIEvent) -> None: + def _handle_run_state_change(self, event: UIEvent) -> Optional[asyncio.Task]: """Broadcast a session's run state (typing indicator + stop button). ``state`` is "running" | "stopping" | "idle"; ``busy`` is the @@ -1114,7 +1114,7 @@ def _handle_run_state_change(self, event: UIEvent) -> None: session_id = event.data.get("session_id") or "main" busy = bool(event.data.get("busy", False)) state = event.data.get("state") or ("running" if busy else "idle") - asyncio.create_task( + return asyncio.create_task( self._broadcast( { "type": "session_busy", @@ -4573,7 +4573,9 @@ async def _handle_session_clear(self, data: Dict[str, Any]) -> None: # Agent side first: it stops a run in flight, whose last rows # must go with the conversation rather than land after the clear. - await self._controller.agent.clear_session(session_id) + if not await self._controller.agent.clear_session(session_id): + return + await self._controller.event_bus.drain(session_id) try: # Ordered storage worker: runs after any insert still queued # for this session, so no message resurfaces after the clear. diff --git a/app/ui_layer/browser/frontend/src/components/Chat/QuestionBox.tsx b/app/ui_layer/browser/frontend/src/components/Chat/QuestionBox.tsx index 8f6b7e9d5..0cf2d99f5 100644 --- a/app/ui_layer/browser/frontend/src/components/Chat/QuestionBox.tsx +++ b/app/ui_layer/browser/frontend/src/components/Chat/QuestionBox.tsx @@ -61,7 +61,12 @@ export function QuestionBox({ question, queueTotal, onAnswer, onDismiss }: Quest } return ( -