Agent Zero AI framework
Add inspectable parallel tool calls
Alessandrob704a0e3f59b
diff --git a/extensions/python/message_loop_prompts_after/AGENTS.md b/extensions/python/message_loop_prompts_after/AGENTS.mdindex c19db6eb0..441540972 100644--- a/extensions/python/message_loop_prompts_after/AGENTS.md+++ b/extensions/python/message_loop_prompts_after/AGENTS.md@@ -6,7 +6,7 @@## Ownership-- Ordered Python files own current datetime, skill recall/load context, agent info, and workdir extras injection.+- Ordered Python files own current datetime, skill recall/load context, agent info, parallel job status, and workdir extras injection.## Local Contractsdiff --git a/extensions/python/message_loop_prompts_after/_72_include_parallel_jobs.py b/extensions/python/message_loop_prompts_after/_72_include_parallel_jobs.pynew file mode 100644index 000000000..70bc0ce4e--- /dev/null+++ b/extensions/python/message_loop_prompts_after/_72_include_parallel_jobs.py@@ -0,0 +1,13 @@+from helpers.extension import Extension+from agent import LoopData+from helpers import parallel_tools+++class IncludeParallelJobs(Extension):+ async def execute(self, loop_data: LoopData = LoopData(), **kwargs):+ if not self.agent:+ return++ extras = await parallel_tools.build_parallel_jobs_extras(self.agent)+ if extras:+ loop_data.extras_temporary["parallel_jobs"] = extrasdiff --git a/extensions/python/tool_execute_before/AGENTS.md b/extensions/python/tool_execute_before/AGENTS.mdindex 6d5f6f8bf..e9f11e78a 100644--- a/extensions/python/tool_execute_before/AGENTS.md+++ b/extensions/python/tool_execute_before/AGENTS.md@@ -6,7 +6,7 @@## Ownership-- Ordered Python files own prior tool-output replacement and secret unmasking before execution.+- Ordered Python files own prior tool-output replacement, parallel recursion guards, and secret unmasking before execution.## Local Contractsdiff --git a/extensions/python/tool_execute_before/_20_block_parallel_recursion.py b/extensions/python/tool_execute_before/_20_block_parallel_recursion.pynew file mode 100644index 000000000..a5547ed8f--- /dev/null+++ b/extensions/python/tool_execute_before/_20_block_parallel_recursion.py@@ -0,0 +1,15 @@+from helpers.extension import Extension+from helpers.errors import RepairableException+from helpers import parallel_tools+++class BlockParallelRecursion(Extension):+ async def execute(self, tool_name: str = "", **kwargs) -> None:+ if tool_name != "parallel":+ return+ if not parallel_tools.is_parallel_worker(self.agent):+ return+ raise RepairableException(+ "The `parallel` tool cannot be used inside a parallel worker. "+ "Finish the current worker task sequentially and return its result."+ )diff --git a/helpers/parallel_tools.py b/helpers/parallel_tools.pynew file mode 100644index 000000000..c1514a025--- /dev/null+++ b/helpers/parallel_tools.py@@ -0,0 +1,652 @@+from __future__ import annotations++import asyncio+import json+import time+import uuid+from dataclasses import dataclass, field, replace+from typing import Any, Literal, TYPE_CHECKING++from helpers import extract_tools+from helpers.defer import DeferredTask, THREAD_BACKGROUND+from helpers.extension import call_extensions_async+from helpers.print_style import PrintStyle++if TYPE_CHECKING:+ from agent import Agent, AgentConfig, AgentContext+ from helpers.log import LogItem+++PARALLEL_JOBS_KEY = "_parallel_jobs"+PARALLEL_WORKER_PARENT_CONTEXT_KEY = "_parallel_parent_context_id"+PARALLEL_WORKER_JOB_KEY = "_parallel_job_id"++CHILD_PARENT_CONTEXT_ID_KEY = "parent_context_id"+CHILD_PARENT_CONTEXT_KIND_KEY = "parent_context_kind"+CHILD_PARENT_CONTEXT_LABEL_KEY = "parent_context_label"+CHILD_PARALLEL_JOB_ID_KEY = "parallel_job_id"+CHILD_PARALLEL_TOOL_NAME_KEY = "parallel_tool_name"++DEFAULT_MAX_CALLS = 8+DEFAULT_TIMEOUT_SECONDS = 300+POLL_INTERVAL_SECONDS = 0.5++TERMINAL_STATES = {"success", "error", "cancelled", "timeout"}+JobState = Literal["pending", "running", "success", "error", "cancelled", "timeout"]+JobKind = Literal["tool", "subordinate"]+++@dataclass+class NormalizedToolCall:+ index: int+ tool_name: str+ tool_args: dict[str, Any]+++@dataclass+class ParallelJob:+ id: str+ parent_context_id: str+ index: int+ tool_name: str+ tool_args: dict[str, Any]+ kind: JobKind+ state: JobState = "pending"+ created_at: float = field(default_factory=time.time)+ started_at: float | None = None+ completed_at: float | None = None+ result: str | None = None+ error: str | None = None+ worker_context_id: str | None = None+ log_id: str = field(default_factory=lambda: str(uuid.uuid4()))+ log_item: "LogItem | None" = field(default=None, repr=False)+ deferred_task: DeferredTask | None = field(default=None, repr=False)++ def elapsed(self) -> float:+ end = self.completed_at or time.time()+ start = self.started_at or self.created_at+ return max(0.0, end - start)+++def extract_tool_calls(args: dict[str, Any]) -> Any:+ for key in ("tool_calls", "calls", "items"):+ if key in args:+ return args.get(key)+ return None+++def normalize_parallel_tool_calls(raw_calls: Any) -> list[NormalizedToolCall]:+ if not isinstance(raw_calls, list):+ raise ValueError("`tool_calls` must be an array of normal tool-call objects.")+ if not raw_calls:+ raise ValueError("`tool_calls` must contain at least one tool call.")+ if len(raw_calls) > DEFAULT_MAX_CALLS:+ raise ValueError(f"`tool_calls` supports at most {DEFAULT_MAX_CALLS} items.")++ calls: list[NormalizedToolCall] = []+ for index, raw_call in enumerate(raw_calls):+ try:+ tool_name, tool_args = extract_tools.normalize_tool_request(raw_call)+ except ValueError as exc:+ raise ValueError(f"tool_calls[{index}] is not a valid tool call: {exc}") from exc++ if tool_name == "parallel":+ raise ValueError("`parallel` cannot be nested inside another `parallel` call.")++ calls.append(+ NormalizedToolCall(+ index=index,+ tool_name=tool_name,+ tool_args=dict(tool_args),+ )+ )+ return calls+++def normalize_job_ids(raw_job_ids: Any) -> list[str]:+ if raw_job_ids is None:+ return []+ if isinstance(raw_job_ids, str):+ return [raw_job_ids]+ if isinstance(raw_job_ids, list):+ return [str(item) for item in raw_job_ids if str(item).strip()]+ raise ValueError("`job_ids` must be a string or an array of strings.")+++def coerce_bool(value: Any, default: bool) -> bool:+ if value is None:+ return default+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ normalized = value.strip().lower()+ if normalized in {"1", "true", "yes", "on"}:+ return True+ if normalized in {"0", "false", "no", "off"}:+ return False+ return bool(value)+++def coerce_timeout(value: Any) -> int:+ if value in (None, ""):+ return DEFAULT_TIMEOUT_SECONDS+ try:+ timeout = int(value)+ except (TypeError, ValueError) as exc:+ raise ValueError(f"`timeout` must be an integer number of seconds, got {value!r}.") from exc+ if timeout <= 0:+ raise ValueError("`timeout` must be greater than 0.")+ return timeout+++def is_parallel_worker(agent: "Agent | None") -> bool:+ context = getattr(agent, "context", None)+ if not context:+ return False+ return bool(context.get_data(PARALLEL_WORKER_JOB_KEY))+++def _jobs_for_context(context: "AgentContext") -> dict[str, ParallelJob]:+ jobs = context.get_data(PARALLEL_JOBS_KEY)+ if not isinstance(jobs, dict):+ jobs = {}+ context.set_data(PARALLEL_JOBS_KEY, jobs)+ return jobs+++def _get_job(parent_context_id: str, job_id: str) -> ParallelJob | None:+ from agent import AgentContext++ context = AgentContext.get(parent_context_id)+ if not context:+ return None+ job = _jobs_for_context(context).get(job_id)+ return job if isinstance(job, ParallelJob) else None+++def _new_job_id(tool_name: str) -> str:+ prefix = "".join(ch for ch in tool_name if ch.isalnum())[:12] or "job"+ return f"{prefix}-{uuid.uuid4().hex[:8]}"+++async def start_parallel_jobs(+ agent: "Agent",+ calls: list[NormalizedToolCall],+) -> list[ParallelJob]:+ jobs: list[ParallelJob] = []+ context = agent.context+ job_store = _jobs_for_context(context)++ for call in calls:+ kind: JobKind = "subordinate" if call.tool_name == "call_subordinate" else "tool"+ job = ParallelJob(+ id=_new_job_id(call.tool_name),+ parent_context_id=context.id,+ index=call.index,+ tool_name=call.tool_name,+ tool_args=call.tool_args,+ kind=kind,+ )+ job_store[job.id] = job+ jobs.append(job)+ _log_parallel_child_started(agent, job)++ try:+ job.state = "running"+ job.started_at = time.time()+ task = DeferredTask(thread_name=THREAD_BACKGROUND)+ job.deferred_task = task+ task.start_task(_run_parallel_job, context.id, job.id)+ except Exception as exc:+ _finish_job(job, "error", error=str(exc))++ return jobs+++async def await_parallel_jobs(+ agent: "Agent",+ job_ids: list[str],+ timeout: int = DEFAULT_TIMEOUT_SECONDS,+ *,+ collect: bool = True,+) -> list[dict[str, Any]]:+ if not job_ids:+ raise ValueError("No `job_ids` were provided to await.")++ deadline = time.time() + timeout+ known_job_ids = set(job_ids)+ while True:+ await refresh_parallel_jobs(agent)+ jobs = [_jobs_for_context(agent.context).get(job_id) for job_id in job_ids]+ missing = [job_id for job_id, job in zip(job_ids, jobs) if job is None]+ if missing:+ raise ValueError(f"Unknown parallel job id(s): {', '.join(missing)}")++ active = [job for job in jobs if job and job.state not in TERMINAL_STATES]+ if not active:+ break++ if time.time() >= deadline:+ for job in active:+ await _timeout_job(job)+ break++ await asyncio.sleep(POLL_INTERVAL_SECONDS)++ snapshots = []+ for job_id in job_ids:+ job = _jobs_for_context(agent.context).get(job_id)+ if job:+ snapshots.append(_job_snapshot(job, include_result=True))++ if collect:+ for job_id in known_job_ids:+ job = _jobs_for_context(agent.context).get(job_id)+ if job and job.state in TERMINAL_STATES:+ await cleanup_parallel_job(agent, job)+ _jobs_for_context(agent.context).pop(job_id, None)++ return snapshots+++async def cancel_parallel_jobs(agent: "Agent", job_ids: list[str]) -> list[dict[str, Any]]:+ if not job_ids:+ raise ValueError("No `job_ids` were provided to cancel.")++ await refresh_parallel_jobs(agent)+ snapshots = []+ for job_id in job_ids:+ job = _jobs_for_context(agent.context).get(job_id)+ if not job:+ raise ValueError(f"Unknown parallel job id: {job_id}")+ await _cancel_job(job)+ snapshots.append(_job_snapshot(job, include_result=True))+ await cleanup_parallel_job(agent, job)+ _jobs_for_context(agent.context).pop(job_id, None)+ return snapshots+++async def refresh_parallel_jobs(agent: "Agent") -> list[ParallelJob]:+ jobs = list(_jobs_for_context(agent.context).values())+ for job in jobs:+ if job.state in TERMINAL_STATES:+ continue+ task = job.deferred_task+ if not task:+ continue+ if task.is_ready():+ try:+ await task.result()+ except asyncio.CancelledError:+ _finish_job(job, "cancelled", error="Parallel job was cancelled.")+ except Exception as exc:+ _finish_job(job, "error", error=str(exc))+ elif task.is_alive():+ job.state = "running"+ if job.started_at is None:+ job.started_at = time.time()+ return jobs+++async def cleanup_parallel_job(agent: "Agent", job: ParallelJob) -> None:+ if job.deferred_task and job.deferred_task.is_alive():+ job.deferred_task.kill()+ if job.kind == "tool":+ await _remove_context(job.worker_context_id)+++async def build_parallel_jobs_extras(agent: "Agent") -> str:+ await refresh_parallel_jobs(agent)+ jobs = [+ job+ for job in _jobs_for_context(agent.context).values()+ if isinstance(job, ParallelJob) and job.state not in {"cancelled", "timeout"}+ ]+ if not jobs:+ return ""++ active = [job for job in jobs if job.state not in TERMINAL_STATES]+ ready = [job for job in jobs if job.state in TERMINAL_STATES]+ if not active and not ready:+ return ""++ lines = ["parallel jobs:"]+ if active:+ lines.append("running:")+ for job in active:+ lines.append(+ f"- {job.id}: {job.tool_name} [{job.state}], running for {job.elapsed():.1f}s"+ )+ if ready:+ lines.append("ready to collect with `parallel` and `job_ids`:")+ for job in ready:+ lines.append(+ f"- {job.id}: {job.tool_name} [{job.state}], duration {job.elapsed():.1f}s"+ )+ lines.append("call the `parallel` tool with `job_ids` to await/collect results or `action: \"cancel\"` to cancel.")+ return "\n".join(lines)+++def format_started_jobs(jobs: list[ParallelJob]) -> str:+ payload = {+ "status": "started",+ "jobs": [_job_snapshot(job, include_result=False) for job in jobs],+ "instruction": "Use the parallel tool with job_ids to await or cancel these background jobs.",+ }+ return json.dumps(payload, indent=2, ensure_ascii=False)+++def format_parallel_results(results: list[dict[str, Any]]) -> str:+ states = [result.get("state") for result in results]+ if states and all(state == "success" for state in states):+ status = "success"+ elif any(state == "success" for state in states):+ status = "partial"+ else:+ status = "error"++ payload = {+ "status": status,+ "jobs": results,+ }+ return json.dumps(payload, indent=2, ensure_ascii=False)+++async def _run_parallel_job(parent_context_id: str, job_id: str) -> None:+ job = _get_job(parent_context_id, job_id)+ if not job:+ return+ try:+ if job.kind == "subordinate":+ result = await _run_subordinate_context_job(parent_context_id, job)+ else:+ result = await _run_direct_tool_job(parent_context_id, job)+ _finish_job(job, "success", result=result)+ except asyncio.CancelledError:+ _finish_job(job, "cancelled", error="Parallel job was cancelled.")+ raise+ except Exception as exc:+ _finish_job(job, "error", error=str(exc))+ PrintStyle.error(f"Parallel job {job.id} failed: {exc}")+++async def _run_subordinate_context_job(parent_context_id: str, job: ParallelJob) -> str:+ from agent import AgentContext, AgentContextType, UserMessage+ from helpers import message_queue, persist_chat++ parent_context = AgentContext.get(parent_context_id)+ if not parent_context:+ raise ValueError("Parent context not found.")++ args = job.tool_args+ message = str(args.get("message") or "").strip()+ if not message:+ raise ValueError("call_subordinate requires `tool_args.message`.")++ profile = str(args.get("profile") or args.get("agent_profile") or "").strip()+ attachments = args.get("attachments") if isinstance(args.get("attachments"), list) else []+ attachments = [str(item) for item in attachments]++ child_name = _subordinate_context_name(job)+ worker_context = AgentContext(+ config=_clone_config(parent_context.config, profile=profile),+ name=child_name,+ type=AgentContextType.USER,+ )+ job.worker_context_id = worker_context.id+ if job.deferred_task:+ worker_context.task = job.deferred_task++ worker_context.set_data(PARALLEL_WORKER_PARENT_CONTEXT_KEY, parent_context.id)+ worker_context.set_data(PARALLEL_WORKER_JOB_KEY, job.id)+ worker_context.set_output_data(CHILD_PARENT_CONTEXT_ID_KEY, parent_context.id)+ worker_context.set_output_data(CHILD_PARENT_CONTEXT_KIND_KEY, "parallel")+ worker_context.set_output_data(CHILD_PARENT_CONTEXT_LABEL_KEY, child_name)+ worker_context.set_output_data(CHILD_PARALLEL_JOB_ID_KEY, job.id)+ worker_context.set_output_data(CHILD_PARALLEL_TOOL_NAME_KEY, job.tool_name)+ _copy_project(parent_context, worker_context)++ system_prompt = _subordinate_worker_system_prompt(profile)+ message_queue.log_user_message(worker_context, message, attachments, source=" (parallel)")+ worker_context.agent0.hist_add_user_message(+ UserMessage(+ message=message,+ attachments=attachments,+ system_message=[system_prompt],+ )+ )+ persist_chat.save_tmp_chat(worker_context)++ try:+ result = await worker_context.agent0.monologue()+ worker_context.agent0.history.new_topic()+ return result+ finally:+ persist_chat.save_tmp_chat(worker_context)+++async def _run_direct_tool_job(parent_context_id: str, job: ParallelJob) -> str:+ from agent import AgentContext, AgentContextType, LoopData++ parent_context = AgentContext.get(parent_context_id)+ if not parent_context:+ raise ValueError("Parent context not found.")++ worker_context: AgentContext | None = None+ try:+ worker_context = AgentContext(+ config=_clone_config(parent_context.config),+ name=f"parallel:{job.tool_name}",+ type=AgentContextType.BACKGROUND,+ )+ worker_context.set_data(PARALLEL_WORKER_PARENT_CONTEXT_KEY, parent_context_id)+ worker_context.set_data(PARALLEL_WORKER_JOB_KEY, job.id)+ job.worker_context_id = worker_context.id+ _copy_project(parent_context, worker_context)++ worker_agent = worker_context.agent0+ worker_agent.loop_data = LoopData()+ return await execute_tool_call(worker_agent, job.tool_name, job.tool_args)+ finally:+ if worker_context:+ await _remove_context(worker_context.id)+++async def execute_tool_call(agent: "Agent", tool_name: str, tool_args: dict[str, Any]) -> str:+ if tool_name == "parallel":+ raise ValueError("`parallel` cannot be nested inside a parallel worker.")++ tool = None+ try:+ import helpers.mcp_handler as mcp_helper++ tool = mcp_helper.MCPConfig.get_instance().get_tool(agent, tool_name)+ except ImportError:+ tool = None+ except Exception as exc:+ PrintStyle.warning(f"Failed to initialize MCP tool '{tool_name}' for parallel job: {exc}")++ if not tool:+ tool = agent.get_tool(+ name=tool_name,+ method=None,+ args=tool_args,+ message=json.dumps({"tool_name": tool_name, "tool_args": tool_args}),+ loop_data=agent.loop_data,+ )+ if not tool:+ raise ValueError(f"Tool '{tool_name}' not found or could not be initialized.")++ agent.loop_data.current_tool = tool+ try:+ await agent.handle_intervention()+ await tool.before_execution(**tool_args)+ await agent.handle_intervention()+ await call_extensions_async(+ "tool_execute_before",+ agent,+ tool_args=tool_args or {},+ tool_name=tool_name,+ )+ response = await tool.execute(**tool_args)+ await agent.handle_intervention()+ await call_extensions_async(+ "tool_execute_after",+ agent,+ response=response,+ tool_name=tool_name,+ )+ await tool.after_execution(response)+ await agent.handle_intervention()+ return response.message+ finally:+ agent.loop_data.current_tool = None+++async def _timeout_job(job: ParallelJob) -> None:+ await _cancel_job(job, state="timeout", message="Parallel job timed out.")+++async def _cancel_job(+ job: ParallelJob,+ *,+ state: JobState = "cancelled",+ message: str = "Parallel job was cancelled.",+) -> None:+ if job.deferred_task and job.deferred_task.is_alive():+ job.deferred_task.kill()+ _finish_job(job, state, error=message)+++def _finish_job(+ job: ParallelJob,+ state: JobState,+ *,+ result: str | None = None,+ error: str | None = None,+) -> None:+ job.state = state+ job.completed_at = time.time()+ if job.started_at is None:+ job.started_at = job.created_at+ if result is not None:+ job.result = result+ if error is not None:+ job.error = error+ _update_parallel_child_log(job)+++async def _remove_context(context_id: str | None) -> None:+ if not context_id:+ return+ from agent import AgentContext++ context = AgentContext.get(context_id)+ if context:+ try:+ context.reset()+ except Exception:+ pass+ AgentContext.remove(context_id)+++def _log_parallel_child_started(agent: "Agent", job: ParallelJob) -> None:+ if job.kind == "subordinate":+ job.log_item = agent.context.log.log(+ type="subagent",+ heading=f"icon://communication {agent.agent_name}: Calling Subordinate Agent",+ content="",+ kvps=job.tool_args,+ id=job.log_id,+ )+ return++ heading = f"icon://construction {agent.agent_name}: Using tool '{job.tool_name}'"+ job.log_item = agent.context.log.log(+ type="tool",+ heading=heading,+ content="",+ kvps=job.tool_args,+ id=job.log_id,+ _tool_name=job.tool_name,+ )+++def _update_parallel_child_log(job: ParallelJob) -> None:+ if not job.log_item:+ return+ if job.state == "success":+ content = job.result if job.result else "(completed without textual output)"+ else:+ content = f"Error: {job.error or job.state}"+ try:+ job.log_item.update(content=content)+ except Exception:+ pass+++def _job_snapshot(job: ParallelJob, *, include_result: bool) -> dict[str, Any]:+ data: dict[str, Any] = {+ "job_id": job.id,+ "tool_name": job.tool_name,+ "state": job.state,+ "duration_seconds": round(job.elapsed(), 3),+ }+ if job.worker_context_id:+ data["context_id"] = job.worker_context_id+ if include_result:+ if job.result is not None:+ data["result"] = job.result+ if job.error is not None:+ data["error"] = job.error+ return data+++def _clone_config(config: "AgentConfig", *, profile: str = "") -> "AgentConfig":+ try:+ cloned = replace(+ config,+ knowledge_subdirs=list(config.knowledge_subdirs),+ additional=dict(config.additional),+ )+ if profile:+ cloned.profile = profile+ return cloned+ except Exception:+ return config+++def _copy_project(parent_context: "AgentContext", worker_context: "AgentContext") -> None:+ try:+ from helpers import projects++ project_name = projects.get_context_project_name(parent_context)+ if project_name:+ projects.activate_project(worker_context.id, project_name, mark_dirty=False)+ except Exception:+ pass+++def _subordinate_worker_system_prompt(profile: str) -> str:+ lines = [+ "You are running as an isolated parallel worker for a parent Agent Zero chat.",+ "Return a concise final textual summary for the parent. Artifacts and files are supplementary, not a substitute for the textual result.",+ "Do not call the `parallel` tool from this worker.",+ ]+ if profile:+ lines.append(f"Act with the `{profile}` profile's expertise and priorities.")+ return "\n".join(lines)+++def _subordinate_context_name(job: ParallelJob) -> str:+ name = str(job.tool_args.get("name") or "").strip()+ if name:+ return name+ message = str(job.tool_args.get("message") or "").strip()+ label = _short_label(message)+ return label or f"Parallel subordinate {job.index + 1}"+++def _short_label(text: str, limit: int = 80) -> str:+ compact = " ".join(text.split())+ return compact[:limit].rstrip()diff --git a/helpers/parallel_tools.py.dox.md b/helpers/parallel_tools.py.dox.mdnew file mode 100644index 000000000..f3949a678--- /dev/null+++ b/helpers/parallel_tools.py.dox.md@@ -0,0 +1,53 @@+# parallel_tools.py DOX++## Purpose++- Own the shared runtime for parallel tool-call jobs.+- Normalize wrapped tool-call payloads, start background jobs, await or cancel jobs, and render prompt extras for active parallel work.+- Keep this file-level DOX profile synchronized with `parallel_tools.py` because this directory is intentionally flat.++## Ownership++- `parallel_tools.py` owns the runtime implementation.+- `parallel_tools.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.+- Public concepts:+- `NormalizedToolCall`+- `ParallelJob`+- `start_parallel_jobs(...)`+- `await_parallel_jobs(...)`+- `cancel_parallel_jobs(...)`+- `build_parallel_jobs_extras(...)`+- `format_parallel_results(...)`++## Runtime Contracts++- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.+- Wrapped tool-call items must use the same shape as normal tool calls: a tool name plus arguments.+- `call_subordinate` jobs run in isolated child chat contexts tagged with parent-chat metadata; they must not be added to the scheduler task list.+- Direct tool jobs run in isolated background contexts and are blocked from recursively invoking `parallel`.+- Parent-visible child log items are created for each wrapped call so the WebUI can inspect concurrent children separately while the wrapper result remains model-history-only.+- Child tool logs mirror normal tool-call visible args; job ids remain available through wrapper results and prompt extras rather than visible process-step args.+- Job IDs are stable handles for later await, collect, or cancel operations.+- Prompt extras must stay bounded and expose only job IDs, tool names, status, and compact result/error summaries.++## Key Concepts++- The parent context stores in-flight jobs under a private data key; collected terminal jobs are removed from that registry.+- `wait=True` starts jobs and awaits them before returning; `wait=False` returns job IDs immediately.+- `collect` returns already-finished job results without waiting; `await` waits for requested job IDs.+- Canceled jobs should be marked terminal and should stop their background `DeferredTask` when cancellation is possible.++## Work Guidance++- Keep normalization compatible with provider tool-call envelopes and direct JSON objects.+- Avoid importing heavy runtime modules at import time unless startup behavior is verified.+- Coordinate argument, output, or status changes with `tools/parallel.py`, prompt instructions, and tests.++## Verification++- Run targeted tests for normalization, recursion guard, prompt extras, and tool result formatting.+- Run a live Agent Zero chat when changing parallel execution, child chat metadata, or subordinate task behavior.++## Child DOX Index++No child DOX files.diff --git a/prompts/agent.system.main.communication.md b/prompts/agent.system.main.communication.mdindex fde41cdbb..0e2af514d 100644--- a/prompts/agent.system.main.communication.md+++ b/prompts/agent.system.main.communication.md@@ -10,7 +10,8 @@- tool_name: use tool name- tool_args: key value pairs tool arguments- `tool_name` must be one listed tool name, never an action name such as `read`, `write`, `terminal`, or `multi`-- To do two operations, call one tool now, then call the next tool after the first result+- To do dependent operations, call one tool now, then call the next tool after the first result+- To do independent operations concurrently, use only the listed `parallel` tool- No text output before or after the JSON objectdiff --git a/prompts/agent.system.tool.parallel.md b/prompts/agent.system.tool.parallel.mdnew file mode 100644index 000000000..53d2d1e64--- /dev/null+++ b/prompts/agent.system.tool.parallel.md@@ -0,0 +1,32 @@+### parallel+run independent tool calls concurrently, or await/cancel background parallel jobs.++Use only for independent work. Each `tool_calls` item is a normal tool request object: `{ "tool_name": "...", "tool_args": { ... } }`.++Rules:+- do not use for one simple call, dependent steps, ordered steps, or shared mutable state+- never nest `parallel`+- `call_subordinate` inside `parallel` starts an isolated child chat under the parent chat, not a scheduler task+- use `wait: false` only when you will collect results later with `job_ids`+- if extras list running or ready parallel jobs, collect them before final synthesis++Args: `tool_calls`, `job_ids`, `wait` default `true`, `action` as `start|await|collect|cancel`, `timeout`.++Start and wait:+~~~json+{+ "tool_name": "parallel",+ "tool_args": {+ "tool_calls": [+ {"tool_name": "call_subordinate", "tool_args": {"message": "Research option A.", "reset": true}},+ {"tool_name": "call_subordinate", "tool_args": {"message": "Research option B.", "reset": true}}+ ],+ "wait": true+ }+}+~~~++Collect existing jobs:+~~~json+{"tool_name": "parallel", "tool_args": {"action": "await", "job_ids": ["job-id"], "timeout": 300}}+~~~diff --git a/prompts/agent.system.tools.md b/prompts/agent.system.tools.mdindex 2a083963c..4031730f1 100644--- a/prompts/agent.system.tools.md+++ b/prompts/agent.system.tools.md@@ -1,4 +1,4 @@## available toolsuse ONLY the tools listed below. match names exactly. do NOT invent tool names.-Action names are not tool names. There is no top-level `multi` or batch tool; call one listed tool at a time. If a tool has an action named `multi`, keep that action inside `tool_args.action` for that specific tool.+Action names are not tool names. Do not invent top-level `multi` or generic batch tools. The only listed wrapper for independent concurrent calls is `parallel`; otherwise call one listed tool at a time. If a tool has an action named `multi`, keep that action inside `tool_args.action` for that specific tool.{{tools}}diff --git a/tests/test_default_prompt_budget.py b/tests/test_default_prompt_budget.pyindex 764294e4f..ec9d1ea97 100644--- a/tests/test_default_prompt_budget.py+++ b/tests/test_default_prompt_budget.py@@ -50,10 +50,12 @@ async def test_default_agent0_prompt_budget_and_guardrails():# surface plus skill metadata. Keep the guardrail close to the observed# budget so prompt creep remains visible without pretending this surface is# a tiny single-tool prompt.- assert tokens.approximate_tokens(system_text) <= 10500+ assert tokens.approximate_tokens(system_text) <= 12000assert "`tool_name` must be one listed tool name" in system_textassert "- tool_args: key value pairs tool arguments" in system_textassert '"tool_name": "call_subordinate"' in system_text+ assert '"tool_name": "parallel"' in system_text+ assert "Each `tool_calls` item is a normal tool request object" in system_textassert '"reset": true' in system_textassert '"tool_name": "text_editor"' in system_textassert '"action": "read"' in system_textdiff --git a/tests/test_parallel_tool.py b/tests/test_parallel_tool.pynew file mode 100644index 000000000..40a1459fd--- /dev/null+++ b/tests/test_parallel_tool.py@@ -0,0 +1,315 @@+from __future__ import annotations++import time+import sys+from types import SimpleNamespace+from pathlib import Path++import pytest++PROJECT_ROOT = Path(__file__).resolve().parents[1]+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++from helpers import parallel_tools+from helpers.tool import Response+++class _FakeLogItem:+ def __init__(self, type_, heading="", content="", kvps=None, id_=None, **kwargs) -> None:+ self.type = type_+ self.heading = heading+ self.content = content+ self.kvps = dict(kvps or {})+ self.kvps.update(kwargs)+ self.id = id_++ def update(self, content=None, kvps=None, **kwargs):+ if content is not None:+ self.content = content+ if kvps:+ self.kvps.update(kvps)+ self.kvps.update(kwargs)+++class _FakeLog:+ def __init__(self) -> None:+ self.items = []++ def log(self, type, heading="", content="", kvps=None, id=None, **kwargs):+ item = _FakeLogItem(type, heading, content, kvps, id, **kwargs)+ self.items.append(item)+ return item+++class _FakeContext:+ def __init__(self) -> None:+ self.id = "ctx"+ self.data = {}+ self.log = _FakeLog()++ def get_data(self, key: str, recursive: bool = True):+ return self.data.get(key)++ def set_data(self, key: str, value, recursive: bool = True):+ self.data[key] = value+++class _FakeAgent:+ def __init__(self) -> None:+ self.context = _FakeContext()+ self.agent_name = "A0"+++def test_normalize_parallel_tool_calls_accepts_normal_tool_request_shapes() -> None:+ calls = parallel_tools.normalize_parallel_tool_calls(+ [+ {+ "tool_name": "text_editor:read",+ "tool_args": {"path": "README.md"},+ },+ {+ "tool": "scheduler",+ "args": {"method": "list_tasks"},+ },+ ]+ )++ assert calls[0].tool_name == "text_editor"+ assert calls[0].tool_args == {"path": "README.md", "action": "read"}+ assert calls[1].tool_name == "scheduler"+ assert calls[1].tool_args == {"method": "list_tasks", "action": "list_tasks"}+++def test_normalize_parallel_tool_calls_rejects_nested_parallel() -> None:+ with pytest.raises(ValueError, match="cannot be nested"):+ parallel_tools.normalize_parallel_tool_calls(+ [{"tool_name": "parallel", "tool_args": {"tool_calls": []}}]+ )+++async def test_parallel_jobs_extras_lists_running_and_ready_jobs() -> None:+ agent = _FakeAgent()+ running = parallel_tools.ParallelJob(+ id="search-1234abcd",+ parent_context_id="ctx",+ index=0,+ tool_name="search_engine",+ tool_args={"query": "Agent Zero"},+ kind="tool",+ state="running",+ started_at=time.time() - 2,+ )+ ready = parallel_tools.ParallelJob(+ id="callsubordin-5678efgh",+ parent_context_id="ctx",+ index=1,+ tool_name="call_subordinate",+ tool_args={"message": "Summarize"},+ kind="subordinate",+ state="success",+ started_at=time.time() - 4,+ completed_at=time.time() - 1,+ result="done",+ )+ agent.context.set_data(+ parallel_tools.PARALLEL_JOBS_KEY,+ {running.id: running, ready.id: ready},+ )++ extras = await parallel_tools.build_parallel_jobs_extras(agent) # type: ignore[arg-type]++ assert "search-1234abcd" in extras+ assert "callsubordin-5678efgh" in extras+ assert "ready to collect" in extras+++async def test_parallel_subordinate_jobs_are_visible_child_logs_not_scheduler_tasks(monkeypatch) -> None:+ class FakeDeferredTask:+ def __init__(self, thread_name=None) -> None:+ self.thread_name = thread_name+ self.started = None++ def start_task(self, func, *args):+ self.started = (func, args)+ return self++ def is_ready(self):+ return False++ def is_alive(self):+ return True++ def kill(self):+ pass++ monkeypatch.setattr(parallel_tools, "DeferredTask", FakeDeferredTask)+ agent = _FakeAgent()++ jobs = await parallel_tools.start_parallel_jobs(+ agent, # type: ignore[arg-type]+ [+ parallel_tools.NormalizedToolCall(+ index=0,+ tool_name="call_subordinate",+ tool_args={+ "profile": "developer",+ "message": "Return ALPHA=1",+ "reset": True,+ },+ )+ ],+ )++ assert jobs[0].kind == "subordinate"+ snapshot = parallel_tools._job_snapshot(jobs[0], include_result=False)+ assert "scheduler_task_uuid" not in snapshot+ assert agent.context.log.items[0].type == "subagent"+ assert agent.context.log.items[0].kvps == {+ "profile": "developer",+ "message": "Return ALPHA=1",+ "reset": True,+ }+ assert "id" not in agent.context.log.items[0].kvps+ assert "tool_name" not in agent.context.log.items[0].kvps+ assert "parallel_child" not in agent.context.log.items[0].kvps+++async def test_parallel_direct_tool_jobs_log_normal_tool_metadata(monkeypatch) -> None:+ class FakeDeferredTask:+ def __init__(self, thread_name=None) -> None:+ self.thread_name = thread_name+ self.started = None++ def start_task(self, func, *args):+ self.started = (func, args)+ return self++ def is_ready(self):+ return False++ def is_alive(self):+ return True++ def kill(self):+ pass++ monkeypatch.setattr(parallel_tools, "DeferredTask", FakeDeferredTask)+ agent = _FakeAgent()++ jobs = await parallel_tools.start_parallel_jobs(+ agent, # type: ignore[arg-type]+ [+ parallel_tools.NormalizedToolCall(+ index=0,+ tool_name="wait",+ tool_args={"seconds": 1},+ )+ ],+ )++ assert jobs[0].kind == "tool"+ assert agent.context.log.items[0].type == "tool"+ assert agent.context.log.items[0].kvps == {"seconds": 1, "_tool_name": "wait"}++ parallel_tools._finish_job(jobs[0], "success", result="done")++ assert agent.context.log.items[0].content == "done"+ assert agent.context.log.items[0].kvps == {"seconds": 1, "_tool_name": "wait"}+++async def test_parallel_tool_keeps_wrapper_out_of_visible_log() -> None:+ from tools.parallel import ParallelTool++ class HistoryAgent(_FakeAgent):+ def __init__(self) -> None:+ super().__init__()+ self.tool_results = []++ def hist_add_tool_result(self, tool_name, tool_result, **kwargs):+ self.tool_results.append((tool_name, tool_result, kwargs))++ agent = HistoryAgent()+ tool = ParallelTool(agent, "parallel", None, {}, "", None) # type: ignore[arg-type]++ await tool.before_execution()+ await tool.after_execution(Response(message="done", break_loop=False, additional={"extra": "value"}))++ assert agent.context.log.items == []+ assert agent.tool_results == [("parallel", "done", {"extra": "value"})]+++async def test_parallel_child_contexts_are_chats_not_tasks(monkeypatch) -> None:+ from agent import AgentContext+ from initialize import initialize_agent+ from helpers import state_snapshot++ class NoTaskScheduler:+ def get_task_by_uuid(self, _task_id):+ return None++ monkeypatch.setattr(+ state_snapshot,+ "TaskScheduler",+ SimpleNamespace(get=lambda: NoTaskScheduler()),+ )++ parent_id = "ctx-par-parent"+ child_id = "ctx-par-child"+ parent = AgentContext(config=initialize_agent(), id=parent_id, name="Parent", set_current=False)+ child = AgentContext(config=initialize_agent(), id=child_id, name="Child", set_current=False)+ try:+ child.set_output_data(parallel_tools.CHILD_PARENT_CONTEXT_ID_KEY, parent.id)+ child.set_output_data(parallel_tools.CHILD_PARENT_CONTEXT_KIND_KEY, "parallel")+ child.set_output_data(parallel_tools.CHILD_PARENT_CONTEXT_LABEL_KEY, "Child task")+ child.set_output_data(parallel_tools.CHILD_PARALLEL_JOB_ID_KEY, "job-123")++ payload = await state_snapshot.build_snapshot(+ context=parent.id,+ log_from=0,+ notifications_from=0,+ timezone="UTC",+ )++ contexts_by_id = {ctx["id"]: ctx for ctx in payload["contexts"]}+ task_ids = {task["id"] for task in payload["tasks"]}+ assert parent_id in contexts_by_id+ assert child_id in contexts_by_id+ assert contexts_by_id[child_id]["parent_context_id"] == parent_id+ assert child_id not in task_ids+ finally:+ AgentContext.remove(parent_id)+ AgentContext.remove(child_id)+++def test_chats_sidebar_projects_parallel_children_as_indented_accordion() -> None:+ store = (PROJECT_ROOT / "webui/components/sidebar/chats/chats-store.js").read_text(+ encoding="utf-8"+ )+ html = (PROJECT_ROOT / "webui/components/sidebar/chats/chats-list.html").read_text(+ encoding="utf-8"+ )++ assert "parent_context_id" in store+ assert "const nextExpandedParents = { ...this.expandedParents };" in store+ assert "nextExpandedParents[selectedId] === undefined" in store+ assert "nextExpandedParents[selectedId] = true;" in store+ assert "topLevelContexts()" in html+ assert "childContexts(context.id)" in html+ assert "chat-child-container" in html+ assert "keyboard_arrow_up" in html+ assert "keyboard_arrow_down" in html+ assert ".chats-config-list .chat-tree-item" in html+ assert ".chats-config-list .chat-child-list > li" in html+ assert 'x-show="$store.chats.hasChildren(context.id)"' in html+ assert "'chat-has-children': $store.chats.hasChildren(context.id)" in html+ assert ".chat-container.chat-has-children .chat-list-button" in html+ assert "left: 2px" in html+ assert "padding-left: 24px" in html+ assert "color: var(--color-text-muted)" in html+ assert "padding: 8px;" in htmldiff --git a/tests/test_tool_action_contracts.py b/tests/test_tool_action_contracts.pyindex de98f259f..8bd638ecb 100644--- a/tests/test_tool_action_contracts.py+++ b/tests/test_tool_action_contracts.py@@ -353,8 +353,10 @@ def test_tool_prompts_prevent_top_level_multi_tool():encoding="utf-8")- assert "There is no top-level `multi` or batch tool" in tools_prompt+ assert "Do not invent top-level `multi` or generic batch tools" in tools_prompt+ assert "listed wrapper for independent concurrent calls is `parallel`" in tools_promptassert "never an action name such as `read`, `write`, `terminal`, or `multi`" in communication_prompt+ assert "independent operations concurrently" in communication_promptassert 'Never use `tool_name: "multi"`' in browser_promptdiff --git a/tools/parallel.py b/tools/parallel.pynew file mode 100644index 000000000..abb783a6c--- /dev/null+++ b/tools/parallel.py@@ -0,0 +1,78 @@+from helpers.tool import Tool, Response+from helpers import parallel_tools+from helpers.strings import sanitize_string+++class ParallelTool(Tool):+ async def before_execution(self, **kwargs):+ self.log = None++ async def after_execution(self, response: Response, **kwargs):+ text = sanitize_string(response.message.strip())+ self.agent.hist_add_tool_result(+ self.name,+ text,+ **(response.additional or {}),+ )++ async def execute(self, **kwargs) -> Response:+ args = {**self.args, **kwargs}+ action = str(args.get("action") or "").strip().lower()++ try:+ timeout = parallel_tools.coerce_timeout(args.get("timeout"))+ job_ids = parallel_tools.normalize_job_ids(args.get("job_ids"))++ if action == "cancel":+ results = await parallel_tools.cancel_parallel_jobs(self.agent, job_ids)+ return Response(+ message=parallel_tools.format_parallel_results(results),+ break_loop=False,+ )++ raw_calls = parallel_tools.extract_tool_calls(args)+ started_jobs = []+ if raw_calls is not None:+ calls = parallel_tools.normalize_parallel_tool_calls(raw_calls)+ started_jobs = await parallel_tools.start_parallel_jobs(self.agent, calls)++ started_job_ids = [job.id for job in started_jobs]+ all_job_ids = [*job_ids, *started_job_ids]++ if not all_job_ids:+ return Response(+ message=(+ "Error: provide `tool_calls` to start parallel jobs, "+ "or `job_ids` to await/cancel existing jobs."+ ),+ break_loop=False,+ )++ wait_default = action not in {"start", "background"}+ wait = parallel_tools.coerce_bool(args.get("wait"), wait_default)+ if action in {"await", "wait", "collect"}:+ wait = True++ if not wait:+ if not started_jobs:+ return Response(+ message="Error: `wait: false` requires `tool_calls` to start new jobs.",+ break_loop=False,+ )+ return Response(+ message=parallel_tools.format_started_jobs(started_jobs),+ break_loop=False,+ )++ results = await parallel_tools.await_parallel_jobs(+ self.agent,+ all_job_ids,+ timeout=timeout,+ collect=True,+ )+ return Response(+ message=parallel_tools.format_parallel_results(results),+ break_loop=False,+ )+ except ValueError as exc:+ return Response(message=f"Error: {exc}", break_loop=False)diff --git a/tools/parallel.py.dox.md b/tools/parallel.py.dox.mdnew file mode 100644index 000000000..aec0a4ffc--- /dev/null+++ b/tools/parallel.py.dox.md@@ -0,0 +1,51 @@+# parallel.py DOX++## Purpose++- Own the `parallel.py` agent tool.+- This tool wraps independent tool calls so they can be started together, awaited by job ID, collected, or canceled.+- Keep this file-level DOX profile synchronized with `parallel.py` because this directory is intentionally flat.++## Ownership++- `parallel.py` owns the runtime implementation.+- `parallel.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.+- Classes:+- `ParallelTool` (`Tool`)+ - `async execute(self, tool_calls=..., calls=..., items=..., job_ids=..., wait=..., action=..., timeout=..., **kwargs)`+ - `async before_execution(self, **kwargs)`+ - `async after_execution(self, response, **kwargs)`++## Runtime Contracts++- Tool modules must define `helpers.tool.Tool` subclasses and return `helpers.tool.Response` from `execute(...)`.+- Wrapped items use the same schema as normal tool calls: a tool name plus arguments.+- The tool is intended for independent calls only; dependent operations remain sequential.+- `action="start"` starts calls and optionally waits according to `wait`.+- `action="await"` waits for requested job IDs.+- `action="collect"` returns completed job results without waiting.+- `action="cancel"` requests cancellation for requested job IDs.+- Recursive use of `parallel` from inside a parallel worker is blocked before execution.+- The wrapper tool does not create its own visible process-step log; each wrapped child call owns the visible log row, and the wrapper result is recorded only in model history.++## Key Concepts++- `tool_calls`, `calls`, and `items` are accepted aliases for the wrapped call list.+- `job_ids` can be supplied as a string or list when awaiting, collecting, or canceling existing jobs.+- The response is compact JSON intended for the model to read and continue with.+- Visible child rows are emitted by `helpers/parallel_tools.py` before each background job starts.++## Work Guidance++- Keep output concise enough for message history while preserving job IDs, statuses, and results.+- Coordinate tool argument or output changes with `prompts/agent.system.tool.parallel.md`, prompt contract tests, and helper tests.+- Avoid adding tool-specific execution logic here; shared execution behavior belongs in `helpers/parallel_tools.py`.++## Verification++- Run targeted tool and prompt-contract tests after changing behavior.+- Run a live WebUI or CLI chat that invokes `parallel` with multiple subordinate jobs.++## Child DOX Index++No child DOX files.diff --git a/webui/components/sidebar/AGENTS.md b/webui/components/sidebar/AGENTS.mdindex 5cacb10d9..9ad7c7a16 100644--- a/webui/components/sidebar/AGENTS.md+++ b/webui/components/sidebar/AGENTS.md@@ -16,6 +16,10 @@- Preserve responsive sidebar behavior and collapsed/expanded state.- Keep chat and task list updates compatible with WebSocket state sync.+- Contexts with `parent_context_id` render as indented children beneath their parent chat; they must remain selectable while hidden from the top-level chat list.+- 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.- Avoid text or controls overflowing fixed sidebar widths.## Work Guidancediff --git a/webui/components/sidebar/chats/chats-list.html b/webui/components/sidebar/chats/chats-list.htmlindex 2c13755fc..bae6793bc 100644--- a/webui/components/sidebar/chats/chats-list.html+++ b/webui/components/sidebar/chats/chats-list.html@@ -22,25 +22,53 @@- <ul class="config-list chats-config-list no-scrollbar" x-show="$store.chats.contexts.length > 0">- <template x-for="context in $store.chats.contexts" :key="context.id">- <li>- <div :class="{'chat-container': true, 'chat-selected': context.id === $store.chats.selected}"+ <ul class="config-list chats-config-list no-scrollbar" x-show="$store.chats.topLevelContexts().length > 0">+ <template x-for="context in $store.chats.topLevelContexts()" :key="context.id">+ <li class="chat-tree-item">+ <div :class="{'chat-container': true, 'chat-has-children': $store.chats.hasChildren(context.id), 'chat-selected': context.id === $store.chats.selected}"@click="$store.chats.selectChat(context.id)">+ <button class="chat-expand-btn"+ x-show="$store.chats.hasChildren(context.id)"+ :class="{ 'is-visible': $store.chats.hasChildren(context.id), 'is-expanded': $store.chats.isExpanded(context.id) }"+ :aria-expanded="$store.chats.isExpanded(context.id)"+ :aria-label="$store.chats.isExpanded(context.id) ? 'Collapse chat children' : 'Expand chat children'"+ @click.stop="$store.chats.toggleChildren(context.id)">+ <span class="material-symbols-outlined"+ x-text="$store.chats.isExpanded(context.id) ? 'keyboard_arrow_up' : 'keyboard_arrow_down'"></span>+ </button><div class="chat-list-button"><span :class="{'project-color-ball': true, 'heartbeat': context.running}":style="context.project?.color ? { backgroundColor: context.project.color } : { border: '1px solid var(--color-border)' }"></span><span class="chat-name"- x-text="context.name ? context.name : 'Chat #' + context.no"></span>+ x-text="$store.chats.displayName(context)"></span></div><button class="btn-icon-action chat-list-action-btn" title="Close chat" @click.stop="$confirmClick($event, () => $store.chats.killChat(context.id))"><span class="material-symbols-outlined">close</span></button></div>+ <ul class="chat-child-list" x-show="$store.chats.isExpanded(context.id) && $store.chats.hasChildren(context.id)">+ <template x-for="child in $store.chats.childContexts(context.id)" :key="child.id">+ <li>+ <div :class="{'chat-container': true, 'chat-child-container': true, 'chat-selected': child.id === $store.chats.selected}"+ @click="$store.chats.selectChat(child.id)">+ <div class="chat-child-indent"></div>+ <div class="chat-list-button">+ <span :class="{'project-color-ball': true, 'heartbeat': child.running}"+ :style="child.project?.color ? { backgroundColor: child.project.color } : { border: '1px solid var(--color-border)' }"></span>+ <span class="chat-name"+ x-text="$store.chats.displayName(child)"></span>+ </div>+ <button class="btn-icon-action chat-list-action-btn" title="Close chat" @click.stop="$confirmClick($event, () => $store.chats.killChat(child.id))">+ <span class="material-symbols-outlined">close</span>+ </button>+ </div>+ </li>+ </template>+ </ul></li></template></ul>- <div class="empty-list-message" x-show="$store.chats.contexts.length === 0">+ <div class="empty-list-message" x-show="$store.chats.topLevelContexts().length === 0"><p><i>No chats to list.</i></p></div><x-extension id="sidebar-chats-list-end"></x-extension>@@ -93,6 +121,72 @@cursor: pointer;}+ .chats-config-list .chat-tree-item {+ display: block;+ align-items: stretch;+ justify-content: flex-start;+ }++ .chat-child-list {+ list-style: none;+ padding: 0;+ margin: 0;+ width: 100%;+ }++ .chats-config-list .chat-child-list > li {+ display: block;+ padding: 0;+ }++ .chat-child-container {+ min-height: 34px;+ }++ .chat-child-indent {+ width: 18px;+ flex-shrink: 0;+ }++ .chat-expand-btn {+ position: absolute;+ left: 2px;+ top: 50%;+ transform: translateY(-50%);+ width: 18px;+ height: 32px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+ border: 0;+ background: transparent;+ color: var(--color-text-muted);+ opacity: 0;+ pointer-events: none;+ padding: 0;+ margin: 0;+ z-index: 1;+ }++ .chat-expand-btn.is-visible {+ opacity: 0.95;+ pointer-events: auto;+ }++ .chat-expand-btn.is-visible:hover {+ color: var(--color-text);+ opacity: 1;+ }++ .chat-expand-btn .material-symbols-outlined {+ font-size: 18px;+ }++ .chat-container.chat-has-children .chat-list-button {+ padding-left: 24px;+ }+.chat-list-button {display: flex;align-items: center;@@ -174,4 +268,4 @@</style></body>-</html>\ No newline at end of file+</html>diff --git a/webui/components/sidebar/chats/chats-store.js b/webui/components/sidebar/chats/chats-store.jsindex 580185975..1469c08d2 100644--- a/webui/components/sidebar/chats/chats-store.js+++ b/webui/components/sidebar/chats/chats-store.js@@ -19,6 +19,7 @@ const model = {selected: "",selectedContext: null,loggedIn: false,+ expandedParents: {},// for conveniencegetSelectedChatId() {@@ -53,7 +54,7 @@ const model = {// Update contexts from pollingapplyContexts(contextsList) {// Sort by created_at time (newer first)- this.contexts = contextsList.sort(+ this.contexts = [...contextsList].sort((a, b) => (b.created_at || 0) - (a.created_at || 0));@@ -64,10 +65,49 @@ const model = {const updated = this.contexts.find((ctx) => ctx.id === selectedId);if (updated) {this.selectedContext = updated;+ const nextExpandedParents = { ...this.expandedParents };+ if (updated.parent_context_id) {+ nextExpandedParents[updated.parent_context_id] = true;+ } else if (+ this.hasChildren(selectedId) &&+ nextExpandedParents[selectedId] === undefined+ ) {+ nextExpandedParents[selectedId] = true;+ }+ this.expandedParents = nextExpandedParents;}}},+ topLevelContexts() {+ return this.contexts.filter((ctx) => !ctx?.parent_context_id);+ },++ childContexts(parentId) {+ return this.contexts.filter((ctx) => ctx?.parent_context_id === parentId);+ },++ hasChildren(parentId) {+ return this.childContexts(parentId).length > 0;+ },++ isExpanded(parentId) {+ return Boolean(this.expandedParents?.[parentId]);+ },++ toggleChildren(parentId) {+ if (!parentId || !this.hasChildren(parentId)) return;+ this.expandedParents = {+ ...this.expandedParents,+ [parentId]: !this.expandedParents?.[parentId],+ };+ },++ displayName(context) {+ if (!context) return "";+ return context.parent_context_label || context.name || `Chat #${context.no}`;+ },+// Select a chatasync selectChat(id) {const currentContext = getContext();