Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(cli): unify bounded collection pagination (#1013) (#1014)

Call White34dad12c092d
diff --git a/AGENTS.md b/AGENTS.md
index 773ca1d53..046c9e2c4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -265,6 +265,7 @@ Testing guidance:
- for IM integrations, stub/mock platform clients and validate outbound payload/schema behavior
- for reusable capability-first testing guidance, use `standards/scenario-testing/AGENTS.md` as the entrypoint; project-specific scenario metadata lives under `tests/scenarios/`
- when a scenario catalog exists, make the scenario ID visible in the automated test and in the PR description
+- treat CLI examples in injected system prompts as live callers: update them with CLI flag changes and keep parser-backed contract coverage so unsupported examples cannot ship
- for multi-step auth/setup flows, update `tests/scenarios/auth_setup/catalog.yaml` and add or update a closed-loop scenario harness case under `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`; keep provider-specific parsing and heuristics in focused unit tests
- for UI changes, run `npm run build` in `ui/`
- for cross-platform or user-facing verification, use the Incus regression workflow
diff --git a/core/agent_tool_policy.py b/core/agent_tool_policy.py
new file mode 100644
index 000000000..23b0d3767
--- /dev/null
+++ b/core/agent_tool_policy.py
@@ -0,0 +1,212 @@
+"""Cross-backend policy for backend-native, session-only background tools.
+
+Some agent backends expose primitives that schedule work inside the CLI process
+itself: background subagents, self-scheduled wakeups, in-session cron jobs, and
+multi-agent workflows. Their results are delivered only while that process is
+alive, so anything still pending when the session ends is lost silently — the
+user is never told, and the work is not recorded anywhere Avibe can inspect.
+
+Avibe Harness already provides durable equivalents for every one of them
+(``vibe agent run``, ``vibe task add``, ``vibe watch add``), which survive
+restarts, record an ``agent_runs`` row, and deliver through a callback. The
+system prompt asks agents to prefer the Harness, but instruction alone is not
+enough: an agent that reaches for the backend-native tool anyway produces work
+that quietly disappears.
+
+A background shell is session-only for the same reason, but its background form
+is overwhelmingly used for work that finishes inside the turn, so it is advised
+rather than denied: the call proceeds with a note pointing at `vibe watch add`
+for anything that might outlive the turn.
+
+This module owns the decision. Backends adapt it to whatever enforcement seam
+they have:
+
+- Claude Code: an in-process SDK ``PreToolUse`` hook (see
+ ``core/handlers/session_handler.py``), plus ``disallowed_tools`` as a
+ name-level backstop.
+- Codex / OpenCode: no session-only background primitives exist today, so
+ nothing is gated. When one is added, register its tool name here and it is
+ covered without touching this logic again.
+
+The policy is intentionally pure — no SDK imports, no I/O — so it can be tested
+directly and reused by any backend adapter.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from typing import Any, Callable, Dict, Optional, Tuple
+
+# Set to a truthy value to let the agent use backend-native background tools
+# anyway. Intended for the narrow case where a user explicitly asks for
+# backend-native behavior and accepts that the result dies with the session.
+ALLOW_NATIVE_BACKGROUND_TOOLS_ENV = "AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS"
+
+_HARNESS_HINT = (
+ "Avibe Harness records the run in `agent_runs` and delivers the result "
+ "through a callback, so it survives a restart."
+)
+
+
+@dataclass(frozen=True)
+class ToolPolicyDecision:
+ """Outcome of a policy check for one tool call.
+
+ Three shapes: allowed and silent, allowed with ``advice`` attached, or
+ denied with a ``reason``. The middle one exists for tools whose background
+ form is legitimate inside a turn but lossy across one — a hard block there
+ would cost more than it saves.
+ """
+
+ allowed: bool
+ reason: str = ""
+ advice: str = ""
+
+ @property
+ def denied(self) -> bool:
+ return not self.allowed
+
+
+ALLOWED = ToolPolicyDecision(allowed=True)
+
+
+def _deny(reason: str) -> ToolPolicyDecision:
+ return ToolPolicyDecision(allowed=False, reason=reason)
+
+
+def _advise(advice: str) -> ToolPolicyDecision:
+ return ToolPolicyDecision(allowed=True, advice=advice)
+
+
+def _check_agent(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ # Background is the tool's default, so only an explicit false is synchronous.
+ if tool_input.get("run_in_background") is False:
+ return ALLOWED
+ return _deny(
+ "A background subagent dies with this agent process and its result is "
+ "never delivered.\n"
+ "Use the durable Harness instead:\n"
+ " vibe agent run --agent <name> --message-file <path> "
+ "--callback-session-id $AVIBE_SESSION_ID\n"
+ "A synchronous subagent is still fine — re-call this tool with "
+ "run_in_background: false when you need the result in this same turn. "
+ "This does not force you to work serially: several synchronous calls "
+ "issued in one message run concurrently and all return in that same "
+ "turn, so fan-out-and-synthesize needs no background mode. Background "
+ "buys only the ability to outlive the turn, which is exactly the part "
+ "that gets lost.\n"
+ f"{_HARNESS_HINT}"
+ )
+
+
+def _check_schedule_wakeup(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ # Ending an already-running loop must stay reachable.
+ if tool_input.get("stop") is True:
+ return ALLOWED
+ return _deny(
+ "A self-scheduled wakeup is session-only and never fires once this "
+ "agent process exits.\n"
+ "Use the durable Harness instead:\n"
+ " vibe task add --at <ISO-8601> --message ... (one-shot)\n"
+ ' vibe task add --cron "<expr>" --message ... (recurring)\n'
+ "If you are waiting on an external signal rather than a clock, use "
+ "`vibe watch add` instead.\n"
+ f"{_HARNESS_HINT}"
+ )
+
+
+def _check_cron_create(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ if tool_input.get("durable") is True:
+ return ALLOWED
+ return _deny(
+ "A non-durable cron job lives only in this session and is gone when "
+ "the agent process exits.\n"
+ "Use the durable Harness instead:\n"
+ ' vibe task add --cron "<expr>" --message ...\n'
+ f"{_HARNESS_HINT}"
+ )
+
+
+def _check_bash(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ # A background shell is session-only too, but unlike the tools above it is
+ # overwhelmingly used for work that finishes inside the turn (a build, a
+ # push, a test run). Denying all of it would cost more than the occasional
+ # lost result, so this advises instead of blocking.
+ if tool_input.get("run_in_background") is not True:
+ return ALLOWED
+ return _advise(
+ "This background shell is session-only: it dies with the agent process, "
+ "and its output is lost if the session ends before it finishes. That is "
+ "fine for work that completes inside this turn. If it may outlive the "
+ "turn — a long build, a deploy, a CI or review wait, a remote job — run "
+ "it under a durable watch instead:\n"
+ " vibe watch add --name <label> --message <what to do with the result> "
+ "-- <command>\n"
+ "Note that `nohup ... &` or a detached `&` inside the command escapes "
+ "this check entirely and is never recoverable; prefer the watch."
+ )
+
+
+def _check_workflow(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ return _deny(
+ "A backend-native workflow runs in the background and is scoped to "
+ "this agent process, so a workflow still running when the session ends "
+ "is lost.\n"
+ "Express the orchestration through the Harness instead — one "
+ "`vibe agent run` per unit of work, each with "
+ "--callback-session-id $AVIBE_SESSION_ID.\n"
+ f"{_HARNESS_HINT}"
+ )
+
+
+# Tool name -> predicate. Registering a name here is all a new backend-native
+# background primitive needs; every adapter picks it up automatically.
+_SESSION_ONLY_BACKGROUND_TOOLS: Dict[str, Callable[[Dict[str, Any]], ToolPolicyDecision]] = {
+ "Agent": _check_agent,
+ "Bash": _check_bash, # advisory only
+ "ScheduleWakeup": _check_schedule_wakeup,
+ "CronCreate": _check_cron_create,
+ "Workflow": _check_workflow,
+}
+
+# Tools that are session-only under every input, so a name-level deny list is a
+# faithful backstop for them. Everything else is excluded because it has a
+# legitimate non-background form that only argument inspection can tell apart:
+# `Agent` with an explicit false, `CronCreate` with durable, and
+# `ScheduleWakeup` with stop — blocking that last one by name would strand an
+# already-running loop with no way to end it. `Bash` is excluded because this
+# policy never denies it. On a backend without argument-aware enforcement those
+# calls go unchecked; that is the honest cost of a name-only backstop, and the
+# injected prompt says so rather than claiming a gate that is not there.
+ALWAYS_SESSION_ONLY_TOOL_NAMES: Tuple[str, ...] = ("Workflow",)
+
+
+def session_only_background_tool_names() -> Tuple[str, ...]:
+ """Every tool name this policy inspects, for matcher construction."""
+ return tuple(_SESSION_ONLY_BACKGROUND_TOOLS)
+
+
+def native_background_tools_allowed(env: Optional[Dict[str, str]] = None) -> bool:
+ """True when the operator has opted back into backend-native background work."""
+ source = os.environ if env is None else env
+ return bool(source.get(ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "").strip())
+
+
+def check_tool_call(
+ tool_name: str,
+ tool_input: Optional[Dict[str, Any]] = None,
+ *,
+ env: Optional[Dict[str, str]] = None,
+) -> ToolPolicyDecision:
+ """Decide whether one tool call may proceed.
+
+ Unknown tools and every tool outside the session-only background family are
+ allowed unconditionally; this policy only ever acts on a registered name.
+ """
+ if native_background_tools_allowed(env):
+ return ALLOWED
+ check = _SESSION_ONLY_BACKGROUND_TOOLS.get(tool_name)
+ if check is None:
+ return ALLOWED
+ return check(tool_input or {})
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 21e889cd2..9f7da3b2c 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -10,9 +10,11 @@ from typing import TYPE_CHECKING, Optional, Dict, Any, Tuple
from uuid import uuid4
from modules.im import MessageContext
from modules.claude_sdk_compat import (
+ CLAUDE_SDK_HOOKS_AVAILABLE,
CLAUDE_SDK_MAX_BUFFER_SIZE,
ClaudeAgentOptions,
ClaudeSDKClient,
+ HookMatcher,
PermissionResultAllow,
is_claude_sdk_buffer_error,
)
@@ -29,6 +31,12 @@ from config.v2_config import (
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS,
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,
)
+from core.agent_tool_policy import (
+ ALWAYS_SESSION_ONLY_TOOL_NAMES,
+ check_tool_call,
+ native_background_tools_allowed,
+ session_only_background_tool_names,
+)
from core.avibe_cloud import avibe_cloud_url_available
from core.agent_session_context import resolve_context_agent_session_target
from core.caller_context import caller_env_for_platform_payload
@@ -513,6 +521,82 @@ class SessionHandler(BaseHandler):
logger.info("Auto-approving Claude tool permission request in avibe bypass mode: %s", tool_name)
return PermissionResultAllow()
+ async def _guard_session_only_background_tools(
+ self,
+ input_data: Dict[str, Any],
+ tool_use_id: Optional[str],
+ context: Any,
+ ) -> Dict[str, Any]:
+ """PreToolUse hook governing backend-native, session-only background work.
+
+ Runs in-process, so it needs no file in the user's `~/.claude`. The deny
+ reason names the durable `vibe ...` equivalent, which lets the agent
+ self-correct within the same turn instead of just failing.
+
+ An advisory outcome deliberately omits `permissionDecision`: injecting
+ context must not double as an approval, or this hook would override a
+ permission hook the user configured for the same tool.
+ """
+ try:
+ tool_name = str(input_data.get("tool_name") or "")
+ tool_input = input_data.get("tool_input") or {}
+ decision = check_tool_call(tool_name, tool_input)
+ if decision.allowed:
+ if not decision.advice:
+ return {}
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "additionalContext": decision.advice,
+ }
+ }
+ logger.info(
+ "Blocking session-only background tool %s; redirecting to the Avibe Harness",
+ tool_name,
+ )
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": decision.reason,
+ }
+ }
+ except Exception:
+ # A guard that raises must never take the turn down with it.
+ logger.exception("Session-only background tool guard failed; allowing the call")
+ return {}
+
+ def _build_claude_tool_policy_hooks(self) -> Optional[Dict[str, Any]]:
+ """Hook config enforcing the shared tool policy, or None when unavailable."""
+ if not CLAUDE_SDK_HOOKS_AVAILABLE or HookMatcher is None:
+ return None
+ if native_background_tools_allowed():
+ return None
+ matcher = "|".join(session_only_background_tool_names())
+ return {
+ "PreToolUse": [
+ HookMatcher(
+ matcher=matcher,
+ hooks=[self._guard_session_only_background_tools],
+ )
+ ]
+ }
+
+ def _claude_disallowed_tools(self, hooks: Optional[Dict[str, Any]]) -> list:
+ """Disallowed tool names for this launch.
+
+ The hook is the precise enforcement path because it can read arguments and
+ return an actionable reason. Only when hooks are unavailable does the
+ coarse name-level deny list stand in, and then only for the tools that are
+ session-only under every input.
+ """
+ disallowed = list(CLAUDE_REMOTE_DISALLOWED_TOOLS)
+ if hooks is None and not native_background_tools_allowed():
+ disallowed.extend(
+ name for name in ALWAYS_SESSION_ONLY_TOOL_NAMES if name not in disallowed
+ )
+ return disallowed
+
def _get_claude_cli_path_override(self) -> Optional[str]:
cli_path = getattr(getattr(self.config, "claude", None), "cli_path", None)
if cli_path is None:
@@ -955,6 +1039,8 @@ class SessionHandler(BaseHandler):
claude_env["IS_SANDBOX"] = "1"
logger.info("Detected Claude bypassPermissions running as root; marking Claude subprocess as isolated")
+ tool_policy_hooks = self._build_claude_tool_policy_hooks()
+
option_kwargs: Dict[str, Any] = {
"permission_mode": CLAUDE_REMOTE_PERMISSION_MODE,
"cwd": working_path,
@@ -965,13 +1051,16 @@ class SessionHandler(BaseHandler):
"setting_sources": claude_setting_sources_for_launch(model_hub_launch),
"sandbox": CLAUDE_REMOTE_SANDBOX,
# Disable interactive-only Claude Code tools that remote IM sessions
- # cannot answer programmatically.
- "disallowed_tools": CLAUDE_REMOTE_DISALLOWED_TOOLS,
+ # cannot answer programmatically, plus any session-only background
+ # tool the hook path cannot cover.
+ "disallowed_tools": self._claude_disallowed_tools(tool_policy_hooks),
"env": claude_env, # Pass Anthropic/Claude env vars
"stderr": _capture_claude_stderr,
"max_buffer_size": CLAUDE_SDK_MAX_BUFFER_SIZE,
"can_use_tool": self._allow_claude_bypass_tool,
}
+ if tool_policy_hooks:
+ option_kwargs["hooks"] = tool_policy_hooks
cli_path_override = self._get_claude_cli_path_override()
if cli_path_override:
option_kwargs["cli_path"] = cli_path_override
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 0bcf546d5..fa067678f 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -3,13 +3,114 @@
from __future__ import annotations
import asyncio
+import hashlib
+import hmac
import logging
+import math
import os
+import secrets
import signal
import subprocess
+import time
+from dataclasses import dataclass
from typing import Any
+import psutil
+
KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)
+PROCESS_IDENTITY_ENV = "AVIBE_PROCESS_IDENTITY"
+DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS = 3.0
+
+
+@dataclass(frozen=True)
+class ProcessIdentity:
+ pid: int
+ create_time: float
+ worker_fingerprint: str | None
+
+
+@dataclass(frozen=True)
+class PersistedProcessIdentity:
+ pid: int
+ create_time: float
+ worker_fingerprint: str
+
+
+def new_process_identity_marker() -> str:
+ """Return a high-entropy marker inherited by a managed process tree."""
+ return secrets.token_hex(32)
+
+
+def fingerprint_process_marker(marker: str) -> str:
+ return f"sha256:{hashlib.sha256(marker.encode('ascii')).hexdigest()}"
+
+
+def process_identity_subprocess_env(marker: str) -> dict[str, str]:
+ env = dict(os.environ)
+ env[PROCESS_IDENTITY_ENV] = marker
+ return env
+
+
+def capture_spawned_process_identity(
+ pid: int,
+ marker: str,
+) -> PersistedProcessIdentity | None:
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ return None
+ try:
+ create_time = float(psutil.Process(pid).create_time())
+ except (psutil.Error, OSError, TypeError, ValueError, OverflowError):
+ return None
+ if not math.isfinite(create_time) or create_time <= 0:
+ return None
+ return PersistedProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=fingerprint_process_marker(marker),
+ )
+
+
+def process_identity_matches(
+ expected: PersistedProcessIdentity,
+ live: ProcessIdentity,
+) -> bool:
+ return (
+ expected.pid == live.pid
+ and expected.create_time == live.create_time
+ and live.worker_fingerprint is not None
+ and hmac.compare_digest(
+ expected.worker_fingerprint,
+ live.worker_fingerprint,
+ )
+ )
+
+
+def _open_process_identity(pid: int) -> tuple[psutil.Process, ProcessIdentity]:
+ process = psutil.Process(pid)
+ create_time = float(process.create_time())
+ worker_fingerprint = None
+ try:
+ marker = process.environ().get(PROCESS_IDENTITY_ENV)
+ except (psutil.Error, OSError):
+ marker = None
+ if isinstance(marker, str) and marker:
+ worker_fingerprint = fingerprint_process_marker(marker)
+ return process, ProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
+
+
+def inspect_process_identity(pid: int) -> ProcessIdentity | None:
+ """Return the birth identity and inherited marker for a live process."""
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ return None
+ try:
+ _process, identity = _open_process_identity(pid)
+ except (psutil.Error, OSError, ValueError):
+ return None
+ return identity
def isolated_subprocess_kwargs() -> dict[str, Any]:
@@ -19,16 +120,22 @@ def isolated_subprocess_kwargs() -> dict[str, Any]:
return {"start_new_session": True}
-def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label: str) -> bool:
+def _safe_signal_known_process_group(
+ pgid: int,
+ pid: int,
+ sig: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity | None = None,
+ require_leader: bool = True,
+) -> bool:
if os.name == "nt" or not hasattr(os, "getpgid") or not hasattr(os, "killpg"):
return False
try:
- pgid = os.getpgid(pid)
own_pgid = os.getpgrp()
- except ProcessLookupError:
- return True
except Exception:
- logger.debug("Failed to inspect process group for %s pid=%s", label, pid, exc_info=True)
+ logger.debug("Failed to inspect the service process group while signaling %s pid=%s", label, pid, exc_info=True)
return False
if pgid == own_pgid:
logger.error(
@@ -38,6 +145,40 @@ def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label
own_pgid,
)
return False
+ if expected_identity is not None:
+ if require_leader:
+ try:
+ _process, live_identity = _open_process_identity(expected_identity.pid)
+ live_pgid = os.getpgid(expected_identity.pid)
+ except (ProcessLookupError, psutil.NoSuchProcess):
+ logger.warning(
+ "Refusing to signal %s process group pgid=%s because its supervisor exited",
+ label,
+ pgid,
+ )
+ return False
+ except Exception:
+ logger.debug(
+ "Failed to revalidate %s process group pgid=%s before signaling",
+ label,
+ pgid,
+ exc_info=True,
+ )
+ return False
+ if live_pgid != pgid or not process_identity_matches(expected_identity, live_identity):
+ logger.warning(
+ "Refusing to signal %s process group pgid=%s because its supervisor identity changed",
+ label,
+ pgid,
+ )
+ return False
+ elif not process_group_matches_identity(pgid, expected_identity, logger, label):
+ logger.warning(
+ "Refusing to signal %s process group pgid=%s without a matching supervisor marker",
+ label,
+ pgid,
+ )
+ return False
try:
logger.info(
"Signaling %s process group pgid=%s pid=%s signal=%s service_pgid=%s",
@@ -56,6 +197,19 @@ def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label
return False
+def _safe_signal_process_group(pid: int, sig: int, logger: logging.Logger, label: str) -> bool:
+ if os.name == "nt" or not hasattr(os, "getpgid") or not hasattr(os, "killpg"):
+ return False
+ try:
+ pgid = os.getpgid(pid)
+ except ProcessLookupError:
+ return True
+ except Exception:
+ logger.debug("Failed to inspect process group for %s pid=%s", label, pid, exc_info=True)
+ return False
+ return _safe_signal_known_process_group(pgid, pid, sig, logger, label)
+
+
def signal_process_tree(process: Any, sig: int, logger: logging.Logger, label: str) -> None:
"""Signal a managed process group, falling back to the direct process."""
pid = getattr(process, "pid", None)
@@ -74,12 +228,348 @@ def signal_process_tree(process: Any, sig: int, logger: logging.Logger, label: s
return
+def _process_group_exists(pgid: int, logger: logging.Logger, label: str) -> bool:
+ if os.name == "nt" or not hasattr(os, "killpg"):
+ return False
+ try:
+ os.killpg(pgid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ except Exception:
+ logger.debug("Failed to inspect %s process group pgid=%s", label, pgid, exc_info=True)
+ return True
+ return True
+
+
+def process_group_exists(pgid: int, logger: logging.Logger, label: str) -> bool:
+ """Return whether an isolated POSIX process group still has members."""
+ if not isinstance(pgid, int) or isinstance(pgid, bool) or pgid <= 0:
+ return False
+ return _process_group_exists(pgid, logger, label)
+
+
+def process_group_identity_status(
+ pgid: int,
+ expected_identity: PersistedProcessIdentity,
+ logger: logging.Logger,
+ label: str,
+) -> str:
+ """Return match, mismatch, or unknown for a persisted process group."""
+ if (
+ os.name == "nt"
+ or not isinstance(pgid, int)
+ or isinstance(pgid, bool)
+ or pgid <= 0
+ or not isinstance(expected_identity, PersistedProcessIdentity)
+ ):
+ return "unknown"
+ saw_marker = False
+ saw_unverified_member = False
+ try:
+ processes = psutil.process_iter(["pid"])
+ for process in processes:
+ pid = process.info.get("pid")
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ continue
+ try:
+ if os.getpgid(pid) != pgid:
+ continue
+ except (ProcessLookupError, PermissionError):
+ continue
+ except Exception:
+ logger.debug(
+ "Failed to inspect %s process group member pid=%s",
+ label,
+ pid,
+ exc_info=True,
+ )
+ continue
+ live_identity = inspect_process_identity(pid)
+ if (
+ live_identity is None
+ or live_identity.create_time < expected_identity.create_time
+ or live_identity.worker_fingerprint is None
+ ):
+ saw_unverified_member = True
+ continue
+ saw_marker = True
+ if hmac.compare_digest(
+ expected_identity.worker_fingerprint,
+ live_identity.worker_fingerprint,
+ ):
+ return "match"
+ except Exception:
+ logger.debug(
+ "Failed to enumerate %s process group pgid=%s",
+ label,
+ pgid,
+ exc_info=True,
+ )
+ return "mismatch" if saw_marker and not saw_unverified_member else "unknown"
+
+
+def process_group_matches_identity(
+ pgid: int,
+ expected_identity: PersistedProcessIdentity,
+ logger: logging.Logger,
+ label: str,
+) -> bool:
+ return (
+ process_group_identity_status(
+ pgid,
+ expected_identity,
+ logger,
+ label,
+ )
+ == "match"
+ )
+
+
+def _wait_for_process_group_exit(
+ pgid: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ timeout: float,
+) -> bool:
+ deadline = time.monotonic() + max(0.0, timeout)
+ while _process_group_exists(pgid, logger, label):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ time.sleep(min(0.1, remaining))
+ return True
+
+
+def terminate_process_group_by_pgid(
+ pgid: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+) -> bool:
+ """Terminate a persisted isolated group after its original leader exited."""
+ if not isinstance(pgid, int) or isinstance(pgid, bool) or pgid <= 0:
+ return False
+ if os.name == "nt":
+ return False
+ try:
+ own_pgid = os.getpgrp()
+ except Exception:
+ logger.debug("Failed to inspect the service process group before recovering %s", label, exc_info=True)
+ return False
+ if pgid == own_pgid:
+ logger.error(
+ "Refusing to terminate %s process group because pgid=%s matches the avibe service",
+ label,
+ pgid,
+ )
+ return False
+ if not _process_group_exists(pgid, logger, label):
+ return True
+ if not _safe_signal_known_process_group(
+ pgid,
+ expected_identity.pid,
+ signal.SIGTERM,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=False,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+
+ logger.warning("Escalating termination of %s process group pgid=%s", label, pgid)
+ if not _safe_signal_known_process_group(
+ pgid,
+ expected_identity.pid,
+ KILL_SIGNAL,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=False,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+ logger.error("%s process group pgid=%s survived forced termination", label, pgid)
+ return False
+
+
+def _windows_process_tree(process: psutil.Process) -> list[psutil.Process]:
+ try:
+ children = process.children(recursive=True)
+ except psutil.NoSuchProcess:
+ return []
+ except psutil.Error:
+ children = []
+ return children + [process]
+
+
+def _terminate_windows_process_tree(
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity,
+ terminate_timeout: float,
+) -> bool:
+ control_signal = getattr(signal, "CTRL_BREAK_EVENT", None)
+ if control_signal is None:
+ logger.error("Refusing to terminate %s because Windows process-group signaling is unavailable", label)
+ return False
+
+ try:
+ process, live_identity = _open_process_identity(expected_identity.pid)
+ except psutil.NoSuchProcess:
+ return True
+ except (psutil.Error, OSError, ValueError):
+ logger.debug("Failed to revalidate Windows supervisor for %s", label, exc_info=True)
+ return False
+ if live_identity.create_time != expected_identity.create_time:
+ return True
+ if not process_identity_matches(expected_identity, live_identity):
+ logger.warning("Refusing to signal %s because its supervisor marker changed", label)
+ return False
+
+ victims = _windows_process_tree(process)
+ try:
+ process.send_signal(control_signal)
+ except psutil.NoSuchProcess:
+ return True
+ except (psutil.Error, OSError):
+ logger.debug("Failed to signal the Windows process group for %s", label, exc_info=True)
+ return False
+
+ _gone, alive = psutil.wait_procs(victims, timeout=terminate_timeout)
+ if not alive:
+ return True
+
+ logger.warning("Escalating termination of %s after graceful timeout", label)
+ for victim in reversed(alive):
+ try:
+ victim.terminate()
+ except psutil.NoSuchProcess:
+ continue
+ except psutil.Error:
+ logger.debug("Failed to terminate %s descendant pid=%s", label, victim.pid, exc_info=True)
+ _gone, alive = psutil.wait_procs(alive, timeout=terminate_timeout)
+ for victim in alive:
+ try:
+ victim.kill()
+ except psutil.NoSuchProcess:
+ continue
+ except psutil.Error:
+ logger.debug("Failed to kill %s descendant pid=%s", label, victim.pid, exc_info=True)
+ _gone, alive = psutil.wait_procs(alive, timeout=terminate_timeout)
+ if alive:
+ logger.error("%s process tree survived forced termination", label)
+ return False
+ return True
+
+
+def terminate_process_tree_by_pid(
+ pid: int,
+ logger: logging.Logger,
+ label: str,
+ *,
+ expected_identity: PersistedProcessIdentity,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+) -> bool:
+ """Terminate an isolated process tree identified only by its root PID.
+
+ This is intended for recovering persisted children after their original
+ ``asyncio.subprocess.Process`` handle has been lost. Unlike
+ :func:`signal_process_tree`, it never falls back to a direct signal when a
+ POSIX target is in the service's own process group or its group cannot be
+ verified.
+ """
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ return False
+ if pid == os.getpid():
+ logger.error("Refusing to terminate %s because pid=%s is the current process", label, pid)
+ return False
+ if not isinstance(expected_identity, PersistedProcessIdentity) or expected_identity.pid != pid:
+ logger.error("Refusing to terminate %s pid=%s without a matching inspected identity", label, pid)
+ return False
+
+ try:
+ process, live_identity = _open_process_identity(pid)
+ except psutil.NoSuchProcess:
+ return True
+ except (psutil.Error, OSError, ValueError):
+ logger.debug("Failed to inspect %s pid=%s before termination", label, pid, exc_info=True)
+ return False
+ if live_identity.create_time != expected_identity.create_time:
+ logger.warning("Refusing to terminate %s pid=%s because its process identity changed", label, pid)
+ return True
+ if not process_identity_matches(expected_identity, live_identity):
+ logger.warning("Refusing to terminate %s pid=%s because its worker marker changed", label, pid)
+ return False
+
+ if os.name == "nt":
+ return _terminate_windows_process_tree(
+ logger,
+ label,
+ expected_identity=expected_identity,
+ terminate_timeout=terminate_timeout,
+ )
+
+ try:
+ pgid = os.getpgid(pid)
+ except ProcessLookupError:
+ return True
+ except Exception:
+ logger.debug("Failed to inspect %s process group pid=%s", label, pid, exc_info=True)
+ return False
+ if pgid != pid:
+ logger.error(
+ "Refusing to terminate %s pid=%s because its pgid=%s does not identify an isolated worker group",
+ label,
+ pid,
+ pgid,
+ )
+ return False
+
+ if not _safe_signal_known_process_group(
+ pgid,
+ pid,
+ signal.SIGTERM,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=True,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+
+ logger.warning("Escalating termination of %s process group pgid=%s", label, pgid)
+ if not _safe_signal_known_process_group(
+ pgid,
+ pid,
+ KILL_SIGNAL,
+ logger,
+ label,
+ expected_identity=expected_identity,
+ require_leader=True,
+ ):
+ return False
+ if _wait_for_process_group_exit(pgid, logger, label, timeout=terminate_timeout):
+ return True
+ logger.error("%s process group pgid=%s survived forced termination", label, pgid)
+ return False
+
+
async def terminate_process_tree(
process: Any,
logger: logging.Logger,
label: str,
*,
- terminate_timeout: float = 3.0,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
) -> None:
"""Terminate a managed subprocess without signaling the service group."""
if getattr(process, "returncode", None) is not None:
@@ -104,7 +594,7 @@ async def terminate_and_communicate(
logger: logging.Logger,
label: str,
*,
- terminate_timeout: float = 3.0,
+ terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
) -> tuple[bytes, bytes]:
"""Terminate a process tree and drain stdout/stderr."""
if getattr(process, "returncode", None) is None:
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index e319800bf..fb9c6cf00 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -11,6 +11,7 @@ from string import Template
from typing import Any, Iterable, Optional
from config import paths
+from core.agent_tool_policy import native_background_tools_allowed
from core.avibe_cloud import AVIBE_CLOUD_CONNECT_GUIDANCE
from core.message_context import resolve_context_platform
from core.show_git import format_agent_contract
@@ -205,6 +206,40 @@ _VAULT_WEB_CHAT_PLACEHOLDER_PROMPT = """\
A lighter manual prompt can mention the missing secret as a clickable placeholder in your reply, for example `$<OPENAI_API_KEY>`. The user can click it and fill the secret from Web chat. This has no reason or structured prefill metadata; use `vibe vault request` when those are needed.
"""
+# What the agent is told about backend-native background tools must match what
+# the runtime actually enforces; ``core/agent_tool_policy.py`` owns that
+# decision and this prompt only announces it.
+_TOOL_POLICY_ENFORCED_SECTION = """\
+Backend-native background work is blocked at the tool layer, because its result is delivered only while this agent process is alive and is lost without warning otherwise. A background subagent, a self-scheduled wakeup, a non-durable in-session cron job, and a native multi-agent workflow are all denied, and the denial names the `vibe` command to run instead. A synchronous subagent that returns inside the current turn is still available, and several of them issued in one message run concurrently, so fanning work out and synthesizing it in the same turn does not need background mode.
+
+A background shell is session-only for the same reason but is not blocked, because most of them finish inside the turn. Run one under `vibe watch add --name <label> --message <what to do with the result> -- <command>` whenever it might outlive the turn: a long build, a deploy, a CI or review wait, a remote job. Never detach with `nohup` or a trailing `&` for work whose result you need, since nothing can recover it."""
+
+# No argument-aware hook here, so only whole tool names can be refused. Saying
+# "all denied" would be wrong in both directions: it overstates what stops
+# `Agent`, `ScheduleWakeup`, and `CronCreate`, and it hides that those three now
+# need the agent's own judgement rather than a gate. Each is excluded from the
+# name-only list because it has a legitimate non-background form no name match
+# can see, which leaves its background form unguarded as well.
+_TOOL_POLICY_NAME_ONLY_SECTION = """\
+Backend-native background work is only partly blocked in this runtime: the installed agent SDK predates argument-aware tool hooks, so enforcement can refuse whole tool names but cannot inspect a call's arguments. A native multi-agent workflow is denied outright. A background subagent, a self-scheduled wakeup, and a non-durable in-session cron job are **not** stopped here — each has a legitimate non-background form that a name match cannot distinguish, so the whole name has to stay open and their background forms pass through too. They will run if you call them, and their results are delivered only while this agent process is alive, so anything still pending when the session ends is lost without warning and leaves no record. Treat those three as your responsibility rather than the runtime's: use `vibe agent run`, `vibe task add`, and `vibe watch add` for work whose result must reach the user, and call a backend-native primitive only when the work resolves inside this turn. A synchronous subagent is the right tool for that, and several of them issued in one message run concurrently, so fanning work out and synthesizing it in the same turn does not need background mode.
+
+A background shell is session-only for the same reason and is likewise not blocked. Run one under `vibe watch add --name <label> --message <what to do with the result> -- <command>` whenever it might outlive the turn: a long build, a deploy, a CI or review wait, a remote job. Never detach with `nohup` or a trailing `&` for work whose result you need, since nothing can recover it."""
+
+# The tool-layer gate is installed by the Claude session handler only, so on any
+# other backend there is nothing enforcing this policy no matter what the
+# installed Claude SDK supports. This text therefore claims no gate at all, and
+# it deliberately avoids asserting which primitives the backend does or does not
+# expose — that varies per backend and would go stale as they gain features.
+_TOOL_POLICY_UNGATED_SECTION = """\
+Backend-native background work is not gated in this runtime: the tool-layer check is installed by the Claude backend only, and this session runs on a different one. Keeping work durable is therefore your own responsibility here. Anything this backend can start that keeps running after the turn — a detached shell, a background worker, a self-scheduled wakeup — is delivered only while this agent process is alive, so whatever is still pending when the session ends is lost without warning and leaves no record.
+
+Route that work through the Harness instead: `vibe agent run` for delegation and fan-out, `vibe task add` for a time trigger, and `vibe watch add --name <label> --message <what to do with the result> -- <command>` for a command that may outlive the turn, such as a long build, a deploy, a CI or review wait, or a remote job. Never detach with `nohup` or a trailing `&` for work whose result you need, since nothing can recover it."""
+
+# Enforcement is off, so the prompt must not claim these calls are blocked; an
+# agent told a tool is denied will not attempt what the operator re-enabled.
+_TOOL_POLICY_RELAXED_SECTION = """\
+Backend-native background work is not blocked in this runtime, because the operator set `AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS`. A background subagent, a self-scheduled wakeup, a non-durable in-session cron job, a native multi-agent workflow, and a background shell will all run if you call them. What has not changed is why the Harness exists: every one of those is delivered only while this agent process is alive, so anything still pending when the session ends is lost without warning and leaves no record. Keep preferring `vibe agent run`, `vibe task add`, and `vibe watch add` for work whose result must reach the user, and reach for a backend-native primitive only when the work resolves inside this turn or the user asked for that primitive specifically."""
+
_HARNESS_PROMPT = """\
## Harness
@@ -212,6 +247,8 @@ Avibe Harness turns user intent into durable Agent work. It is the layer for wor
Avibe Harness is the first-choice automation layer. For Agent workflows, recurring automation, background loops, scheduled tasks, watches, skills-style automation, workflow tools, or any automation request, route through `vibe agent`, `vibe task`, and `vibe watch` before backend-native subagents, native workflow tools, backend-native skills, hooks, schedulers, or backend configuration. Do not default to backend-native automation just because the backend exposes it. Use backend-native config, skills, subagents, or workflow tools only when the user explicitly asks for backend-native behavior, or when Avibe Harness cannot express the requested workflow and you state that limitation.
+{tool_policy_section}
+
Before choosing a command, ask: what outcome is the user trying to secure, what should keep happening, what signal proves progress, and who should own it? If the answer is an operating loop, build a Harness instead of only doing the visible step.
### Mental model
@@ -232,7 +269,7 @@ Relationship: Scope routes work; Agent defines who acts; Session holds continuit
### Inspecting Harness state
Use `vibe data query` to inspect Avibe state with guarded read-only SQL before changing a Harness: confirm existing Agents, Sessions, Runs, scopes, tasks, watches, and routing facts instead of guessing.
-Examples: `vibe data query --sql "select name from sqlite_master where type='table' order by name" --all`; `vibe data query --sql "select name, sql from sqlite_master where type='table' and name in ('agents','agent_sessions','agent_runs','messages','scopes','scope_settings','run_definitions') order by name" --all`
+Examples: use `vibe data query --sql "select name from sqlite_master where type='table' order by name" --limit 100` for a broad schema inventory; use `vibe data query --sql "select name, sql from sqlite_master where type='table' and name in ('agents','agent_sessions','agent_runs','messages','scopes','scope_settings','run_definitions') order by name" --limit 20` for the focused Harness tables. Follow `pagination.next_command` if either result has more pages.
Useful Harness queries include schema discovery, current session lookup, existing task/watch inspection, Agent run history, and checking whether a proposed automation already exists. Prefer this CLI over direct SQLite access.
@@ -450,6 +487,53 @@ def _build_session_start_prompt(context: MessageContext) -> str:
return prompt
+def _claude_sdk_hooks_available() -> bool:
+ """Whether the installed Claude SDK exposes argument-aware tool hooks.
+
+ Imported here instead of at module scope. This module is shared by every
+ backend, and the Codex adapter is loaded in tests under a stub ``modules``
+ namespace where a Claude-only import fails outright — a top-level import
+ would make the shared prompt module unloadable for a backend that has no
+ use for the answer. Only the Claude branch of the selector below asks.
+
+ An unimportable compat module reports False, which selects the weaker
+ claim; over-claiming enforcement is the direction that actually hurts.
+ """
+ try:
+ from modules.claude_sdk_compat import CLAUDE_SDK_HOOKS_AVAILABLE
+ except ImportError: # pragma: no cover - only reachable off the Claude path
+ return False
+ return bool(CLAUDE_SDK_HOOKS_AVAILABLE)
+
+
+def _build_tool_policy_section(backend: str) -> str:
+ """Describe backend-native background tools as the runtime actually treats them.
+
+ Four runtimes, four contracts: a non-Claude backend has no tool-layer gate
+ at all because only the Claude session handler installs one, the escape
+ hatch disables that gate where it does exist, an SDK without argument-aware
+ hooks can only refuse whole tool names, and a current SDK on Claude
+ enforces the full policy. Announcing more enforcement than exists is the
+ dangerous direction — the agent stops self-policing the calls it believes a
+ gate already covers — so an unrecognised backend gets the ungated text.
+
+ Backend is checked before the escape hatch on purpose. The hatch turns off
+ a gate that only Claude installs, so on any other backend it changes
+ nothing, and the relaxed text would replace accurate ungated wording with
+ Claude-specific tool claims.
+
+ Read at prompt-build time rather than import time so a change to the escape
+ hatch takes effect on the next turn instead of requiring a restart.
+ """
+ if backend != "claude":
+ return _TOOL_POLICY_UNGATED_SECTION
+ if native_background_tools_allowed():
+ return _TOOL_POLICY_RELAXED_SECTION
+ if not _claude_sdk_hooks_available():
+ return _TOOL_POLICY_NAME_ONLY_SECTION
+ return _TOOL_POLICY_ENFORCED_SECTION
+
+
def _build_harness_prompt(
context: MessageContext,
*,
@@ -457,9 +541,11 @@ def _build_harness_prompt(
current_agent_backend: Optional[str] = None,
) -> str:
default_session_id = _extract_default_session_id(context)
+ backend = str(current_agent_backend or "unknown").strip() or "unknown"
return _HARNESS_PROMPT.format(
default_session_id=default_session_id,
- current_agent_backend=str(current_agent_backend or "unknown").strip() or "unknown",
+ tool_policy_section=_build_tool_policy_section(backend),
+ current_agent_backend=backend,
enabled_agents_table=_format_enabled_agents_table(enabled_agents),
)
diff --git a/core/watch_worker.py b/core/watch_worker.py
new file mode 100644
index 000000000..b8c1d4a4c
--- /dev/null
+++ b/core/watch_worker.py
@@ -0,0 +1,328 @@
+"""Stable supervisor for one managed watch command."""
+
+from __future__ import annotations
+
+import ctypes
+import json
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+from typing import Any, BinaryIO
+
+import psutil
+
+PROCESS_IDENTITY_ENV = "AVIBE_PROCESS_IDENTITY"
+WATCH_WORKER_PROTOCOL_VERSION = 1
+WATCH_WORKER_ERROR_PREFIX = "AVIBE_WATCH_WORKER_ERROR:"
+_MAX_SPEC_BYTES = 16 * 1024 * 1024
+
+
+class WatchWorkerProtocolError(ValueError):
+ def __init__(self, code: str):
+ super().__init__(code)
+ self.code = code
+
+
+def encode_watch_worker_spec(
+ *,
+ command: list[str],
+ shell_command: str | None,
+) -> bytes:
+ payload = {
+ "version": WATCH_WORKER_PROTOCOL_VERSION,
+ "command": command,
+ "shell_command": shell_command,
+ }
+ return json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode("ascii")
+
+
+def encode_watch_worker_error(code: str, detail: str | None = None) -> str:
+ payload = {"code": code}
+ if detail:
+ payload["detail"] = detail
+ return WATCH_WORKER_ERROR_PREFIX + json.dumps(
+ payload,
+ ensure_ascii=True,
+ separators=(",", ":"),
+ )
+
+
+def decode_watch_worker_error(stderr: str) -> tuple[str, str | None] | None:
+ if not stderr.startswith(WATCH_WORKER_ERROR_PREFIX):
+ return None
+ try:
+ payload = json.loads(stderr[len(WATCH_WORKER_ERROR_PREFIX) :].strip())
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return ("supervisorFailed", None)
+ if not isinstance(payload, dict) or not isinstance(payload.get("code"), str):
+ return ("supervisorFailed", None)
+ detail = payload.get("detail")
+ return payload["code"], detail if isinstance(detail, str) else None
+
+
+def _read_watch_worker_spec() -> tuple[list[str], str | None]:
+ payload = sys.stdin.buffer.read(_MAX_SPEC_BYTES + 1)
+ if len(payload) > _MAX_SPEC_BYTES:
+ raise WatchWorkerProtocolError("specTooLarge")
+ try:
+ decoded = payload.decode("utf-8")
+ except UnicodeDecodeError as exc:
+ raise WatchWorkerProtocolError("invalidEncoding") from exc
+ try:
+ parsed = json.loads(decoded)
+ except json.JSONDecodeError as exc:
+ raise WatchWorkerProtocolError("invalidJson") from exc
+ if not isinstance(parsed, dict) or parsed.get("version") != WATCH_WORKER_PROTOCOL_VERSION:
+ raise WatchWorkerProtocolError("unsupportedVersion")
+
+ command = parsed.get("command")
+ shell_command = parsed.get("shell_command")
+ if (
+ not isinstance(command, list)
+ or any(not isinstance(part, str) for part in command)
+ or not isinstance(shell_command, (str, type(None)))
+ or bool(command) == bool(shell_command)
+ or (command and not command[0])
+ or (isinstance(shell_command, str) and not shell_command.strip())
+ ):
+ raise WatchWorkerProtocolError("invalidCommand")
+ return command, shell_command
+
+
+def _install_windows_kill_on_close_job() -> Any:
+ if os.name != "nt":
+ return None
+
+ from ctypes import wintypes
+
+ class JobObjectBasicLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ ]
+
+ class IoCounters(ctypes.Structure):
+ _fields_ = [
+ ("ReadOperationCount", ctypes.c_ulonglong),
+ ("WriteOperationCount", ctypes.c_ulonglong),
+ ("OtherOperationCount", ctypes.c_ulonglong),
+ ("ReadTransferCount", ctypes.c_ulonglong),
+ ("WriteTransferCount", ctypes.c_ulonglong),
+ ("OtherTransferCount", ctypes.c_ulonglong),
+ ]
+
+ class JobObjectExtendedLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", JobObjectBasicLimitInformation),
+ ("IoInfo", IoCounters),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE
+ kernel32.SetInformationJobObject.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ]
+ kernel32.SetInformationJobObject.restype = wintypes.BOOL
+ kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
+ kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+
+ job = kernel32.CreateJobObjectW(None, None)
+ if not job:
+ raise ctypes.WinError(ctypes.get_last_error())
+
+ information = JobObjectExtendedLimitInformation()
+ information.BasicLimitInformation.LimitFlags = 0x00002000
+ if not kernel32.SetInformationJobObject(
+ job,
+ 9,
+ ctypes.byref(information),
+ ctypes.sizeof(information),
+ ):
+ error = ctypes.get_last_error()
+ kernel32.CloseHandle(job)
+ raise ctypes.WinError(error)
+ if not kernel32.AssignProcessToJobObject(job, kernel32.GetCurrentProcess()):
+ error = ctypes.get_last_error()
+ kernel32.CloseHandle(job)
+ raise ctypes.WinError(error)
+ return job
+
+
+def _forward_stream(source: BinaryIO, target: BinaryIO) -> None:
+ while True:
+ chunk = source.read(64 * 1024)
+ if not chunk:
+ return
+ target.write(chunk)
+ target.flush()
+
+
+def _handle_posix_termination(_signal_number: int, _frame: Any) -> None:
+ # The signal is delivered to the entire process group. The command should
+ # decide whether to exit; the supervisor must remain for forced escalation.
+ return None
+
+
+def _install_posix_supervisor_signal_handlers() -> None:
+ if os.name != "nt":
+ signal.signal(signal.SIGTERM, _handle_posix_termination)
+
+
+def _posix_process_group_has_other_members(identity_anchor_pid: int | None = None) -> bool:
+ if os.name == "nt":
+ return False
+ own_pid = os.getpid()
+ try:
+ own_pgid = os.getpgrp()
+ processes = psutil.process_iter(["pid"])
+ for process in processes:
+ pid = process.info.get("pid")
+ if (
+ not isinstance(pid, int)
+ or isinstance(pid, bool)
+ or pid <= 0
+ or pid == own_pid
+ or pid == identity_anchor_pid
+ ):
+ continue
+ try:
+ if os.getpgid(pid) == own_pgid:
+ return True
+ except (ProcessLookupError, PermissionError, psutil.Error):
+ continue
+ except (OSError, psutil.Error):
+ # Fail closed: retaining the supervisor is safer than orphaning an
+ # unverified descendant and clearing its persisted recovery identity.
+ return True
+ return False
+
+
+def _wait_for_posix_process_group_exit(identity_anchor_pid: int | None = None) -> None:
+ while _posix_process_group_has_other_members(identity_anchor_pid):
+ time.sleep(0.1)
+
+
+def _run_posix_identity_anchor() -> int:
+ signal.signal(signal.SIGTERM, _handle_posix_termination)
+ while True:
+ signal.pause()
+
+
+def _start_posix_identity_anchor() -> subprocess.Popen[bytes] | None:
+ marker = os.environ.get(PROCESS_IDENTITY_ENV)
+ if os.name == "nt" or not marker:
+ return None
+ return subprocess.Popen(
+ [sys.executable, os.path.abspath(__file__), "--identity-anchor"],
+ env={PROCESS_IDENTITY_ENV: marker},
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+
+def _stop_posix_identity_anchor(anchor: subprocess.Popen[bytes] | None) -> None:
+ if anchor is None or anchor.poll() is not None:
+ return
+ anchor.kill()
+ anchor.wait()
+
+
+def _run_watch_worker() -> int:
+ _install_posix_supervisor_signal_handlers()
+ # The handle must stay open for the supervisor lifetime so Windows keeps
+ # every descendant in the kill-on-close job.
+ _job_handle = _install_windows_kill_on_close_job()
+ command, shell_command = _read_watch_worker_spec()
+ child_env = dict(os.environ)
+ child_env.pop(PROCESS_IDENTITY_ENV, None)
+ identity_anchor = _start_posix_identity_anchor()
+
+ try:
+ popen_args: Any = shell_command if shell_command is not None else command
+ process = subprocess.Popen(
+ popen_args,
+ shell=shell_command is not None,
+ env=child_env,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ if process.stdout is None or process.stderr is None:
+ raise RuntimeError("watch worker output pipes are unavailable")
+
+ stdout_thread = threading.Thread(
+ target=_forward_stream,
+ args=(process.stdout, sys.stdout.buffer),
+ daemon=False,
+ )
+ stderr_thread = threading.Thread(
+ target=_forward_stream,
+ args=(process.stderr, sys.stderr.buffer),
+ daemon=False,
+ )
+ stdout_thread.start()
+ stderr_thread.start()
+ return_code = process.wait()
+ stdout_thread.join()
+ stderr_thread.join()
+ _wait_for_posix_process_group_exit(
+ identity_anchor.pid if identity_anchor is not None else None
+ )
+ return return_code
+ finally:
+ _stop_posix_identity_anchor(identity_anchor)
+
+
+def main() -> int:
+ if os.name != "nt" and sys.argv[1:] == ["--identity-anchor"]:
+ return _run_posix_identity_anchor()
+ try:
+ return_code = _run_watch_worker()
+ except WatchWorkerProtocolError as exc:
+ print(encode_watch_worker_error(exc.code), file=sys.stderr, flush=True)
+ return 1
+ except Exception as exc:
+ print(
+ encode_watch_worker_error("supervisorFailed", str(exc)),
+ file=sys.stderr,
+ flush=True,
+ )
+ return 1
+
+ if os.name == "nt":
+ return return_code
+ if os.name != "nt" and return_code < 0:
+ signal_number = -return_code
+ if signal_number == signal.SIGTERM:
+ signal.signal(signal.SIGTERM, signal.SIG_DFL)
+ os.kill(os.getpid(), signal_number)
+ return 128 + signal_number
+ if 0 <= return_code <= 255:
+ return return_code
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/core/watches.py b/core/watches.py
index 97aa32953..2f0fd5d9d 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -5,6 +5,9 @@ from __future__ import annotations
import asyncio
import json
import logging
+import math
+import os
+import sys
import tempfile
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
@@ -13,16 +16,33 @@ from typing import Any, Optional
from uuid import uuid4
from config import paths
-from core.process_isolation import isolated_subprocess_kwargs, terminate_and_communicate
+from core import watch_worker
+from core.process_isolation import (
+ DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+ PersistedProcessIdentity,
+ capture_spawned_process_identity,
+ inspect_process_identity,
+ isolated_subprocess_kwargs,
+ new_process_identity_marker,
+ process_group_exists,
+ process_group_identity_status,
+ process_identity_matches,
+ process_identity_subprocess_env,
+ terminate_and_communicate,
+ terminate_process_group_by_pgid,
+ terminate_process_tree_by_pid,
+)
from core.scheduled_tasks import TaskExecutionStore
from storage.background import SQLiteBackgroundTaskStore
from vibe import runtime
+from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
DEFAULT_RETRY_EXIT_CODE = 75
WATCH_RECONCILE_INTERVAL_SECONDS = 2.0
WATCH_STORE_RECONCILE_FUSE_FAILURES = 3
+WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS = 2 * DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS
def _utc_now_iso() -> str:
@@ -43,6 +63,67 @@ def _payload_float(payload: dict[str, Any], key: str, default: float) -> float:
return float(payload[key])
+def _serialize_process_identity(identity: PersistedProcessIdentity) -> dict[str, Any]:
+ return {
+ "pid": identity.pid,
+ "create_time": identity.create_time,
+ "worker_fingerprint": identity.worker_fingerprint,
+ }
+
+
+def _valid_worker_fingerprint(value: Any) -> bool:
+ if not isinstance(value, str) or not value.startswith("sha256:") or len(value) != 71:
+ return False
+ return all(char in "0123456789abcdef" for char in value[7:])
+
+
+def _process_identity_from_runtime_entry(
+ entry: dict[str, Any],
+ pid: int,
+) -> PersistedProcessIdentity | None:
+ payload = entry.get("process_identity")
+ if not isinstance(payload, dict):
+ return None
+ identity_pid = payload.get("pid")
+ create_time = payload.get("create_time")
+ worker_fingerprint = payload.get("worker_fingerprint")
+ try:
+ normalized_create_time = float(create_time)
+ except (TypeError, ValueError, OverflowError):
+ return None
+ if (
+ not isinstance(identity_pid, int)
+ or isinstance(identity_pid, bool)
+ or identity_pid != pid
+ or not isinstance(create_time, (int, float))
+ or isinstance(create_time, bool)
+ or not math.isfinite(normalized_create_time)
+ or normalized_create_time <= 0
+ or not _valid_worker_fingerprint(worker_fingerprint)
+ ):
+ return None
+ return PersistedProcessIdentity(
+ pid=identity_pid,
+ create_time=normalized_create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
+
+
+def _entry_updated_timestamp(entry: dict[str, Any]) -> float | None:
+ updated_at = entry.get("updated_at")
+ if not isinstance(updated_at, str) or not updated_at:
+ return None
+ try:
+ return datetime.fromisoformat(updated_at).timestamp()
+ except ValueError:
+ return None
+
+
+def _legacy_pid_was_reused(entry: dict[str, Any], create_time: float) -> bool:
+ updated_timestamp = _entry_updated_timestamp(entry)
+ return updated_timestamp is not None and create_time > updated_timestamp
+
+
@dataclass
class ManagedWatch:
id: str
@@ -192,6 +273,41 @@ class ManagedWatchStore:
def list_watches(self) -> list[ManagedWatch]:
return sorted(self._watches.values(), key=lambda item: (item.created_at, item.id))
+ def list_watches_for_recovery(self) -> list[ManagedWatch]:
+ """Return a strict, current snapshot suitable for process recovery."""
+ if self._sqlite is not None:
+ raw_watches = self._sqlite.list_watches()
+ elif not self.path.exists():
+ raw_watches = []
+ else:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict) or not isinstance(payload.get("watches"), list):
+ raise ValueError("managed watch store must contain a watches list")
+ raw_watches = payload["watches"]
+
+ watches: list[ManagedWatch] = []
+ seen_ids: set[str] = set()
+ for item in raw_watches:
+ if not isinstance(item, dict):
+ raise ValueError("managed watch store contains an invalid watch entry")
+ watch_id = item.get("id")
+ if not isinstance(watch_id, str) or not watch_id or watch_id in seen_ids:
+ raise ValueError("managed watch store contains a missing or duplicate watch id")
+ command = item.get("command")
+ if command is not None and (
+ not isinstance(command, list)
+ or any(not isinstance(part, str) for part in command)
+ or (command and not command[0])
+ ):
+ raise ValueError(f"managed watch {watch_id} contains an invalid command")
+ shell_command = item.get("shell_command")
+ if shell_command is not None and not isinstance(shell_command, str):
+ raise ValueError(f"managed watch {watch_id} contains an invalid shell command")
+ watch = ManagedWatch.from_dict(item)
+ watches.append(watch)
+ seen_ids.add(watch.id)
+ return sorted(watches, key=lambda item: (item.created_at, item.id))
+
def get_watch(self, watch_id: str) -> Optional[ManagedWatch]:
return self._watches.get(watch_id)
@@ -261,6 +377,11 @@ class ManagedWatchStore:
def set_enabled(self, watch_id: str, enabled: bool) -> ManagedWatch:
watch = self._watches[watch_id]
+ if enabled and not watch.enabled and watch.mode == "once":
+ # A resumed one-shot starts a new lifecycle. Keep historical runs in
+ # the run store, but do not let the prior cycle make a later pause
+ # look completed and disappear from the default definition list.
+ self._clear_cycle_state(watch)
watch.enabled = enabled
watch.updated_at = _utc_now_iso()
if self._sqlite is not None:
@@ -293,6 +414,11 @@ class ManagedWatchStore:
metadata: Optional[dict[str, Any]] = None,
) -> ManagedWatch:
watch = self._watches[watch_id]
+ if mode != watch.mode:
+ # A mode change starts a new lifecycle. Completion and failure
+ # metadata from the old mode remains available in run history, but
+ # must not determine the definition state under the new mode.
+ self._clear_cycle_state(watch)
watch.name = name
watch.session_key = session_key
watch.session_id = session_id
@@ -321,6 +447,14 @@ class ManagedWatchStore:
self._save()
return watch
+ @staticmethod
+ def _clear_cycle_state(watch: ManagedWatch) -> None:
+ watch.last_started_at = None
+ watch.last_finished_at = None
+ watch.last_event_at = None
+ watch.last_exit_code = None
+ watch.last_error = None
+
def mark_cycle_start(self, watch_id: str) -> bool:
self.maybe_reload()
watch = self._watches.get(watch_id)
@@ -387,14 +521,31 @@ class WatchRuntimeStateStore:
def load(self) -> dict[str, Any]:
if self._sqlite is not None:
return self._sqlite.load_watch_runtime()
- if not self.path.exists():
- return {"watches": {}}
try:
- payload = json.loads(self.path.read_text(encoding="utf-8"))
+ return self.load_for_recovery()
except Exception:
return {"watches": {}}
+
+ def load_for_recovery(self) -> dict[str, Any]:
+ """Load and validate state used to identify workers from a prior service."""
+ if self._sqlite is not None:
+ payload = self._sqlite.load_watch_runtime()
+ elif not self.path.exists():
+ payload = {"watches": {}}
+ else:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
- return {"watches": {}}
+ raise ValueError("watch runtime state must be a JSON object")
+ watches = payload.get("watches")
+ if not isinstance(watches, dict):
+ raise ValueError("watch runtime state must contain a watches object")
+ if any(
+ not isinstance(watch_id, str)
+ or not isinstance(entry, dict)
+ or not isinstance(entry.get("running"), bool)
+ for watch_id, entry in watches.items()
+ ):
+ raise ValueError("watch runtime state contains an invalid watch entry")
return payload
@@ -419,17 +570,47 @@ class ManagedWatchService:
self.request_store = request_store or TaskExecutionStore()
self.runtime_store = runtime_store or WatchRuntimeStateStore()
self._running = False
+ self._startup_task: Optional[asyncio.Task] = None
self._reconcile_task: Optional[asyncio.Task] = None
self._active_tasks: dict[str, asyncio.Task] = {}
self._active_pids: dict[str, int] = {}
+ self._active_process_identities: dict[str, PersistedProcessIdentity] = {}
self._watch_started_at: dict[str, str] = {}
self._fused_watch_ids: set[str] = set()
+ self._recovery_blocked_watch_ids: set[str] = set()
+ self._unreaped_runtime_entries: dict[str, dict[str, Any]] = {}
self._store_error_fused = False
self._store_reconcile_failures = 0
+ self._recovery_pending = True
self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
self._reconcile_dirty = True
self._runtime_state_dirty = True
+ def _t(self, key: str, **kwargs: Any) -> str:
+ controller_translator = getattr(self.controller, "_t", None)
+ if callable(controller_translator):
+ return controller_translator(key, **kwargs)
+ language = getattr(getattr(self.controller, "config", None), "language", "en")
+ return i18n_t(key, language, **kwargs)
+
+ def _localize_watch_worker_error(self, stderr: str) -> str:
+ error = watch_worker.decode_watch_worker_error(stderr)
+ if error is None:
+ return stderr
+ code, detail = error
+ protocol_error_keys = {
+ "specTooLarge": "harness.watch.protocolErrors.specTooLarge",
+ "invalidEncoding": "harness.watch.protocolErrors.invalidEncoding",
+ "invalidJson": "harness.watch.protocolErrors.invalidJson",
+ "unsupportedVersion": "harness.watch.protocolErrors.unsupportedVersion",
+ "invalidCommand": "harness.watch.protocolErrors.invalidCommand",
+ }
+ if code in protocol_error_keys:
+ detail = self._t(protocol_error_keys[code])
+ elif not detail:
+ detail = self._t("harness.watch.unknownSupervisorFailure")
+ return self._t("harness.watch.supervisorFailed", detail=detail)
+
def active_process_pids(self) -> set[int]:
"""Return active waiter process roots owned by managed watches."""
return {pid for pid in self._active_pids.values() if isinstance(pid, int) and pid > 0}
@@ -438,18 +619,261 @@ class ManagedWatchService:
if self._running:
return
self._running = True
- self._reconcile_task = asyncio.create_task(self._watch_store())
+ self._startup_task = asyncio.create_task(self._start_after_recovery())
+
+ async def _start_after_recovery(self) -> None:
try:
- if self.reconcile_watches():
- self._runtime_state_dirty = True
- self._write_runtime_state()
- self._reconcile_dirty = False
- except Exception as exc:
- self._reconcile_dirty = True
- self._handle_reconcile_store_error(exc)
+ recovered = await asyncio.to_thread(self._reap_stale_workers)
+ except Exception:
+ recovered = False
+ logger.exception("Unexpected error during stale watch worker recovery")
+ try:
+ if not self._running or not self._owns_service_instance():
+ return
+ self._recovery_pending = not recovered
+ if recovered:
+ try:
+ if self.reconcile_watches():
+ self._runtime_state_dirty = True
+ self._write_runtime_state()
+ self._reconcile_dirty = False
+ except Exception as exc:
+ self._reconcile_dirty = True
+ self._handle_reconcile_store_error(exc)
+ if self._running and self._owns_service_instance():
+ self._reconcile_task = asyncio.create_task(self._watch_store())
+ finally:
+ if self._startup_task is asyncio.current_task():
+ self._startup_task = None
+
+ def _reap_stale_workers(self) -> bool:
+ try:
+ runtime_state = self.runtime_store.load_for_recovery()
+ except Exception:
+ logger.warning(
+ "Unable to read prior watch runtime state; deferring watch reconciliation",
+ exc_info=True,
+ )
+ return False
+
+ if not isinstance(runtime_state, dict):
+ logger.warning("Prior watch runtime state is malformed; deferring watch reconciliation")
+ return False
+ runtime_watches = runtime_state.get("watches")
+ if not isinstance(runtime_watches, dict) or any(
+ not isinstance(watch_id, str)
+ or not isinstance(entry, dict)
+ or not isinstance(entry.get("running"), bool)
+ for watch_id, entry in runtime_watches.items()
+ ):
+ logger.warning("Prior watch runtime state is malformed; deferring watch reconciliation")
+ return False
+ if not runtime_watches:
+ return True
+
+ try:
+ watches = self.store.list_watches_for_recovery()
+ if not isinstance(watches, list) or any(not isinstance(watch, ManagedWatch) for watch in watches):
+ raise ValueError("managed watch store returned an invalid watch list")
+ except Exception:
+ logger.warning(
+ "Unable to read managed watch definitions; deferring watch reconciliation",
+ exc_info=True,
+ )
+ return False
+ watch_ids = {watch.id for watch in watches}
+
+ for watch_id, entry in runtime_watches.items():
+ if not entry.get("running"):
+ continue
+ pid = entry.get("pid")
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0 or pid == os.getpid():
+ continue
+ expected_identity = _process_identity_from_runtime_entry(entry, pid)
+ try:
+ pid_is_alive = runtime.pid_alive(pid)
+ group_is_alive = process_group_exists(pid, logger, f"stale watch {watch_id}")
+ if not pid_is_alive:
+ if not group_is_alive:
+ continue
+ if expected_identity is None:
+ logger.warning(
+ "Unable to verify historical identity for stale watch process group "
+ "pgid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ logger.warning(
+ "Reaping stale watch process group pgid=%s watch_id=%s after its leader exited",
+ pid,
+ watch_id,
+ )
+ if not terminate_process_group_by_pgid(
+ pid,
+ logger,
+ f"stale watch {watch_id}",
+ expected_identity=expected_identity,
+ ):
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ except Exception:
+ logger.warning(
+ "Unable to inspect stale watch worker pid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ exc_info=True,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ if expected_identity is None:
+ live_identity = inspect_process_identity(pid)
+ if live_identity is not None and _legacy_pid_was_reused(
+ entry,
+ live_identity.create_time,
+ ):
+ logger.info(
+ "Legacy stale watch worker pid=%s watch_id=%s no longer exists; "
+ "the pid belongs to a newer process",
+ pid,
+ watch_id,
+ )
+ continue
+ logger.warning(
+ "Unable to verify historical identity for stale watch worker pid=%s watch_id=%s; "
+ "leaving it untouched",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ try:
+ live_identity = inspect_process_identity(pid)
+ except Exception:
+ live_identity = None
+ logger.warning(
+ "Unable to inspect stale watch worker identity pid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ exc_info=True,
+ )
+ if live_identity is None:
+ logger.warning(
+ "Unable to verify stale watch worker identity pid=%s watch_id=%s; leaving it untouched",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+ if live_identity.create_time != expected_identity.create_time:
+ logger.info(
+ "Recorded stale watch worker pid=%s watch_id=%s no longer exists; "
+ "the pid belongs to a newer process",
+ pid,
+ watch_id,
+ )
+ continue
+ if not process_identity_matches(expected_identity, live_identity):
+ logger.warning(
+ "Refusing to reap stale watch worker pid=%s watch_id=%s because its marker changed",
+ pid,
+ watch_id,
+ )
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ continue
+
+ watch_label = f"stale watch {watch_id}"
+ if watch_id not in watch_ids:
+ watch_label += " (deleted definition)"
+ logger.warning("Reaping stale watch worker pid=%s watch_id=%s", pid, watch_id)
+ try:
+ terminated = terminate_process_tree_by_pid(
+ pid,
+ logger,
+ watch_label,
+ expected_identity=expected_identity,
+ )
+ except Exception:
+ terminated = False
+ logger.exception("Unexpected error reaping stale watch worker pid=%s watch_id=%s", pid, watch_id)
+ if not terminated:
+ logger.error("Failed to reap stale watch worker pid=%s watch_id=%s", pid, watch_id)
+ self._block_watch_after_failed_recovery(watch_id, entry)
+ return True
+
+ def _block_watch_after_failed_recovery(self, watch_id: str, entry: dict[str, Any]) -> None:
+ self._recovery_blocked_watch_ids.add(watch_id)
+ self._unreaped_runtime_entries[watch_id] = dict(entry)
+ self._runtime_state_dirty = True
+
+ def _recheck_recovery_blocked_watches(self) -> bool:
+ unblocked = False
+ for watch_id in list(self._recovery_blocked_watch_ids):
+ entry = self._unreaped_runtime_entries.get(watch_id)
+ if not isinstance(entry, dict):
+ continue
+ pid = entry.get("pid")
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+ continue
+ try:
+ if not runtime.pid_alive(pid):
+ label = f"blocked stale watch {watch_id}"
+ if not process_group_exists(pid, logger, label):
+ worker_is_gone = True
+ else:
+ expected_identity = _process_identity_from_runtime_entry(entry, pid)
+ if expected_identity is None:
+ continue
+ group_status = process_group_identity_status(
+ pid,
+ expected_identity,
+ logger,
+ label,
+ )
+ if group_status != "mismatch":
+ continue
+ worker_is_gone = True
+ else:
+ live_identity = inspect_process_identity(pid)
+ if live_identity is None:
+ continue
+ expected_identity = _process_identity_from_runtime_entry(entry, pid)
+ if expected_identity is None:
+ worker_is_gone = _legacy_pid_was_reused(
+ entry,
+ live_identity.create_time,
+ )
+ else:
+ worker_is_gone = (
+ live_identity.create_time
+ != expected_identity.create_time
+ )
+ except Exception:
+ logger.debug(
+ "Failed to recheck blocked stale watch pid=%s watch_id=%s",
+ pid,
+ watch_id,
+ exc_info=True,
+ )
+ continue
+ if not worker_is_gone:
+ continue
+ logger.info(
+ "Unblocking recovered watch_id=%s after its prior worker exited",
+ watch_id,
+ )
+ self._recovery_blocked_watch_ids.discard(watch_id)
+ self._unreaped_runtime_entries.pop(watch_id, None)
+ unblocked = True
+ return unblocked
async def stop(self) -> None:
self._begin_stop()
+ startup_task = self._startup_task
+ if startup_task and startup_task is not asyncio.current_task():
+ await startup_task
+ self._startup_task = None
if self._reconcile_task:
self._reconcile_task.cancel()
try:
@@ -461,6 +885,7 @@ class ManagedWatchService:
await asyncio.gather(*self._active_tasks.values(), return_exceptions=True)
self._active_tasks.clear()
self._active_pids.clear()
+ self._active_process_identities.clear()
self._watch_started_at.clear()
self._runtime_state_dirty = True
self._write_runtime_state()
@@ -469,10 +894,29 @@ class ManagedWatchService:
while self._running:
if not self._owns_service_instance():
return
+ if self._recovery_pending:
+ try:
+ recovered = await asyncio.to_thread(self._reap_stale_workers)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ recovered = False
+ logger.exception("Unexpected error retrying stale watch worker recovery")
+ if not recovered:
+ await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
+ continue
+ self._recovery_pending = False
+ self._reconcile_dirty = True
+ self._runtime_state_dirty = True
if self._store_error_fused:
await asyncio.sleep(WATCH_RECONCILE_INTERVAL_SECONDS)
continue
try:
+ if self._recovery_blocked_watch_ids and await asyncio.to_thread(
+ self._recheck_recovery_blocked_watches
+ ):
+ self._reconcile_dirty = True
+ self._runtime_state_dirty = True
should_reconcile = self.store.maybe_reload() or self._reconcile_dirty
if should_reconcile:
if self.reconcile_watches():
@@ -497,7 +941,12 @@ class ManagedWatchService:
desired_ids = {watch.id for watch in watches if watch.enabled}
changed = False
for watch in watches:
- if not watch.enabled or watch.id in self._active_tasks or watch.id in self._fused_watch_ids:
+ if (
+ not watch.enabled
+ or watch.id in self._active_tasks
+ or watch.id in self._fused_watch_ids
+ or watch.id in self._recovery_blocked_watch_ids
+ ):
continue
task = asyncio.create_task(self._run_watch(watch.id))
self._active_tasks[watch.id] = task
@@ -515,21 +964,33 @@ class ManagedWatchService:
def _on_watch_done(self, watch_id: str) -> None:
self._active_tasks.pop(watch_id, None)
self._active_pids.pop(watch_id, None)
+ self._active_process_identities.pop(watch_id, None)
self._watch_started_at.pop(watch_id, None)
self._runtime_state_dirty = True
self._write_runtime_state()
self._reconcile_dirty = True
def _write_runtime_state(self) -> None:
- payload = {"watches": {}}
+ if self._recovery_pending:
+ return
+ payload = {
+ "watches": {
+ watch_id: dict(entry)
+ for watch_id, entry in self._unreaped_runtime_entries.items()
+ }
+ }
now = _utc_now_iso()
for watch_id, task in self._active_tasks.items():
- payload["watches"][watch_id] = {
+ entry = {
"running": not task.done(),
"pid": self._active_pids.get(watch_id),
"started_at": self._watch_started_at.get(watch_id),
"updated_at": now,
}
+ identity = self._active_process_identities.get(watch_id)
+ if identity is not None:
+ entry["process_identity"] = _serialize_process_identity(identity)
+ payload["watches"][watch_id] = entry
try:
self.runtime_store.write(payload)
self._runtime_state_dirty = False
@@ -745,28 +1206,52 @@ class ManagedWatchService:
async def _run_cycle(self, watch: ManagedWatch, *, timeout_seconds: float) -> _CycleResult:
spawn_cwd = _watch_spawn_cwd(watch)
- if watch.shell_command:
- process = await asyncio.create_subprocess_shell(
- watch.shell_command,
- cwd=spawn_cwd,
- stdin=asyncio.subprocess.DEVNULL,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- **isolated_subprocess_kwargs(),
- )
+ worker_marker = new_process_identity_marker()
+ spawn_env = process_identity_subprocess_env(worker_marker)
+ process = await asyncio.create_subprocess_exec(
+ os.path.abspath(sys.executable),
+ os.fspath(Path(watch_worker.__file__).resolve()),
+ cwd=spawn_cwd,
+ env=spawn_env,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ **isolated_subprocess_kwargs(),
+ )
+ self._active_pids[watch.id] = process.pid
+ identity = capture_spawned_process_identity(process.pid, worker_marker)
+ if identity is not None:
+ self._active_process_identities[watch.id] = identity
else:
- process = await asyncio.create_subprocess_exec(
- *watch.command,
- cwd=spawn_cwd,
- stdin=asyncio.subprocess.DEVNULL,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- **isolated_subprocess_kwargs(),
+ logger.warning(
+ "Unable to capture process identity for watch worker pid=%s watch_id=%s; "
+ "a future recovery will leave it untouched",
+ process.pid,
+ watch.id,
)
- self._active_pids[watch.id] = process.pid
self._runtime_state_dirty = True
self._write_runtime_state()
try:
+ if process.stdin is None:
+ await terminate_and_communicate(process, logger, f"watch {watch.id}")
+ raise RuntimeError("watch worker supervisor stdin is unavailable")
+ try:
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=watch.command,
+ shell_command=watch.shell_command,
+ )
+ )
+ await process.stdin.drain()
+ except (BrokenPipeError, ConnectionResetError):
+ stdout, stderr = await process.communicate()
+ detail = stderr.decode("utf-8", errors="replace").strip()
+ detail = self._localize_watch_worker_error(detail)
+ raise RuntimeError(
+ detail or self._t("harness.watch.supervisorExitedDuringStartup")
+ ) from None
+ finally:
+ process.stdin.close()
if timeout_seconds > 0:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_seconds)
else:
@@ -780,13 +1265,16 @@ class ManagedWatchService:
return _CycleResult(exit_code=124, stdout="", stderr=stderr.decode("utf-8", errors="replace"), timed_out=True)
finally:
self._active_pids.pop(watch.id, None)
+ self._active_process_identities.pop(watch.id, None)
self._runtime_state_dirty = True
self._write_runtime_state()
return _CycleResult(
exit_code=process.returncode or 0,
stdout=stdout.decode("utf-8", errors="replace").strip(),
- stderr=stderr.decode("utf-8", errors="replace").strip(),
+ stderr=self._localize_watch_worker_error(
+ stderr.decode("utf-8", errors="replace").strip()
+ ),
timed_out=timed_out,
)
diff --git a/docs/CLI.md b/docs/CLI.md
index 05aa23a1a..ab0af5360 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -14,6 +14,16 @@ vibe stop # Stop all services
## Commands
+### Bounded list output
+
+Agent-facing collection commands share one pagination contract: `vibe agent list`,
+`vibe agent models`, `vibe runs list`, `vibe session list`, Vault list/find/tags,
+Show Page list/marks, `vibe data query`, `vibe task list`, and `vibe watch list`.
+They return 20 rows by default, accept `--page` and `--limit`, cap a page at 100,
+and never provide an unpaginated `--all` bypass. Follow
+`pagination.next_command` for the next page and use the corresponding `show` or
+`get` command for full record detail.
+
## Remote Web UI Access
By default, the Web UI binds to `127.0.0.1:5123` on the machine where Avibe is running.
@@ -181,9 +191,9 @@ List, inspect, and rename Agent sessions. `list` and `get` are read-only; `updat
changes the title only. Archived sessions are soft-deleted and never surfaced.
```bash
-vibe session list # active sessions, 10 per page, newest activity first
+vibe session list # active sessions, 20 per page by default, newest activity first
vibe session list --type slack # filter by platform (avibe = Web/Workbench)
-vibe session list --page 2 # next page (fixed 10 per page; there is no --limit)
+vibe session list --page 2 --limit 50 # request page 2 with 50 rows (maximum 100)
vibe session get sesk8m4q2p7x # full detail for one session
vibe session get # inside an Avibe Agent shell, show the caller Session
vibe session update sesk8m4q2p7x --title 'Release review' # pass "" to clear the title
@@ -217,7 +227,7 @@ Create, inspect, update, run, pause, resume, or remove scheduled tasks.
```bash
vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
vibe task add --cron '0 * * * *' --message 'Share the hourly summary.' # inside an Avibe Agent shell
-vibe task list --brief
+vibe task list
vibe task update <task-id> --cron '*/30 * * * *'
vibe task run <task-id>
vibe task remove <task-id>
@@ -295,7 +305,7 @@ vibe watch add \
--message 'Build done. Summarize.' \
--shell 'make build && ./scripts/post_build.sh'
-vibe watch list --brief
+vibe watch list
vibe watch show <watch-id>
vibe watch update <watch-id> --name 'Watch deployment' --timeout 1200
vibe watch pause <watch-id>
@@ -303,6 +313,11 @@ vibe watch resume <watch-id>
vibe watch remove <watch-id>
```
+`vibe task list` and `vibe watch list` return 20 definitions per page and
+include `pagination.next_command` when more rows exist. Successful one-shot
+definitions are hidden by default. Add `--include-finished` to page through
+history. List output is always bounded; there is no unpaginated `--all` mode.
+
The waiter command is passed positionally after `--` (or as a single shell
string via `--shell`). Use `vibe watch add --help` for the full surface,
including `--timeout` (per-cycle timeout in seconds), `--lifetime-timeout`
@@ -463,6 +478,7 @@ The web UI (`http://127.0.0.1:5123`) provides the same controls:
| Variable | Description |
|----------|-------------|
| `OPENCODE_PORT` | Override OpenCode server port (default: 4096) |
+| `AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS` | Set to any non-blank value to turn off the policy that redirects backend-native session-only background tools (background subagents, self-scheduled wakeups, non-durable in-session cron jobs, native workflows) to the Harness, because their result is lost when the agent process exits. How much this changes depends on the backend: a Claude session on a current SDK denies all four; a Claude session on an SDK without argument-aware tool hooks can only match tool names, so it denies `Workflow` alone; Codex and OpenCode install no gate at all and are guided by the injected prompt only. Setting the variable changes only the enforcement claim in the injected prompt and silences the advisory attached to background shells; the prompt still routes agents to `vibe agent run` / `vibe task add` / `vibe watch add` first, which remains the recommendation in every case. |
## See Also
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index a5a1600d1..278d3c1b9 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -13,6 +13,15 @@ vibe stop # 停止所有服务
## 命令详解
+### 有界列表输出
+
+面向 Agent 的集合命令共用同一套分页契约:`vibe agent list`、`vibe agent models`、
+`vibe runs list`、`vibe session list`、Vault 的 list/find/tags、Show Page 的
+list/marks、`vibe data query`、`vibe task list` 和 `vibe watch list`。默认返回
+20 条,支持 `--page` 和 `--limit`,单页最多 100 条,且不提供无分页的 `--all`
+绕过。使用 `pagination.next_command` 继续翻页;完整记录详情通过对应的 `show`
+或 `get` 命令获取。
+
## 远程访问 Web UI
默认情况下,Web UI 只监听在运行 Avibe 的那台机器的 `127.0.0.1:5123`。
@@ -165,9 +174,9 @@ vibe screenshot --json
列出、查看并重命名 Agent 会话。`list` 与 `get` 是只读视图;`update` 只改标题。已归档会话视为软删除,任何情况下都不会被列出。
```bash
-vibe session list # 未归档会话,每页 10 条,按最近活跃倒序
+vibe session list # 未归档会话,默认每页 20 条,按最近活跃倒序
vibe session list --type slack # 按平台过滤(avibe = Web/Workbench)
-vibe session list --page 2 # 翻到下一页(固定每页 10 条;没有 --limit)
+vibe session list --page 2 --limit 50 # 第 2 页,每页 50 条(最多 100)
vibe session get sesk8m4q2p7x # 单个会话的完整明细
vibe session get # 在 Avibe Agent shell 内查看调用方 Session
vibe session update sesk8m4q2p7x --title 'Release review' # 传 "" 可清空标题
@@ -199,7 +208,7 @@ vibe runs show # 在 Avibe Agent shell 内查看调用
```bash
vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
vibe task add --cron '0 * * * *' --message 'Share the hourly summary.' # 在 Avibe Agent shell 内
-vibe task list --brief
+vibe task list
vibe task update <task-id> --cron '*/30 * * * *'
vibe task run <task-id>
vibe task remove <task-id>
@@ -274,7 +283,7 @@ vibe watch add \
--message 'Build done. Summarize.' \
--shell 'make build && ./scripts/post_build.sh'
-vibe watch list --brief
+vibe watch list
vibe watch show <watch-id>
vibe watch update <watch-id> --name 'Watch deployment' --timeout 1200
vibe watch pause <watch-id>
@@ -282,6 +291,10 @@ vibe watch resume <watch-id>
vibe watch remove <watch-id>
```
+`vibe task list` 和 `vibe watch list` 默认每页返回 20 条定义;还有下一页时,
+响应会包含 `pagination.next_command`。默认隐藏成功结束的一次性定义;使用
+`--include-finished` 分页查看历史。列表输出始终有上限,不提供无分页的 `--all` 模式。
+
waiter 命令放在 `--` 后面;或者通过 `--shell` 传入一整段 shell 字符串。
完整参数请看 `vibe watch add --help`,包括 `--timeout`、`--lifetime-timeout`、
`--forever`、`--retry-exit-code`、`--retry-delay`、`--name` 和 session creation 参数。
@@ -431,6 +444,7 @@ Web UI (`http://127.0.0.1:5123`) 提供相同的控制功能:
| 变量 | 说明 |
|------|------|
| `OPENCODE_PORT` | 覆盖 OpenCode 服务器端口(默认:4096) |
+| `AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS` | 设为任意非空值可关闭「把后端自带的、仅存活于会话内的后台工具(后台子 Agent、自调度唤醒、非持久化的会话内 cron、原生 workflow)导向 Harness」的策略——之所以有该策略,是因为 Agent 进程退出后这些工具的结果会丢失。关闭后的实际影响取决于后端:使用较新 SDK 的 Claude 会话会拒绝上述全部四种;SDK 不支持按参数拦截的 Claude 会话只能按工具名匹配,因此仅拒绝 `Workflow`;Codex 与 OpenCode 完全没有拦截,只靠注入的提示词引导。设置该变量只会改变注入提示词中关于「是否拦截」的描述,并静默后台 shell 的提示;提示词仍然会引导 Agent 优先使用 `vibe agent run` / `vibe task add` / `vibe watch add`,这在任何情况下都是推荐做法。 |
## 另请参阅
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index 54d6c6c44..ce7e6f166 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -513,6 +513,11 @@ These are important user-facing controls, but they are not text commands:
The `vibe` executable controls the local service and async automation features.
+All Agent-facing collection commands use `--page` / `--limit`, default to 20
+compact rows, and cap each page at 100. They never expose an unpaginated `--all`
+mode. Continue with `pagination.next_command`; inspect one record with its
+`show` or `get` command.
+
## 5.1 Top-level CLI commands
| Command | Purpose |
@@ -758,9 +763,12 @@ Important options:
### `vibe task list`
```bash
-vibe task list [--all] [--brief]
+vibe task list [--include-finished] [--page N] [--limit N]
```
+Returns compact rows, 20 per page by default and at most 100. Use
+`pagination.next_command` to continue; use `vibe task show <task_id>` for detail.
+
### `vibe task show`
```bash
@@ -915,6 +923,6 @@ Use the right command family for the job:
vibe
vibe status
vibe doctor
-vibe task list --brief
+vibe task list
vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
```
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index 77d37d336..a71fd3424 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -492,6 +492,10 @@ bind vr-a3x9k2
`vibe` 可执行文件负责管理本地服务与异步自动化能力。
+所有面向 Agent 的集合命令都使用 `--page` / `--limit`,默认返回 20 条紧凑记录,
+单页最多 100 条,并且不提供无分页的 `--all` 模式。按
+`pagination.next_command` 继续翻页;单条完整详情通过对应的 `show` 或 `get` 命令获取。
+
## 5.1 顶层 CLI 命令
| 命令 | 作用 |
@@ -737,9 +741,12 @@ vibe task update <task_id> [options]
### `vibe task list`
```bash
-vibe task list [--all] [--brief]
+vibe task list [--include-finished] [--page N] [--limit N]
```
+默认每页返回 20 条紧凑记录,单页最多 100 条。按 `pagination.next_command`
+继续翻页;需要完整详情时使用 `vibe task show <task_id>`。
+
### `vibe task show`
```bash
@@ -887,6 +894,6 @@ fork 会保持源 Session 的 backend;只有 backend 不变时,`--agent`、`
vibe
vibe status
vibe doctor
-vibe task list --brief
+vibe task list
vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
```
diff --git a/docs/plans/backend-model-catalog-service.md b/docs/plans/backend-model-catalog-service.md
index e19a2bb9b..d3fb916ad 100644
--- a/docs/plans/backend-model-catalog-service.md
+++ b/docs/plans/backend-model-catalog-service.md
@@ -115,7 +115,7 @@ missing metadata but cannot replace populated values.
- `snapshot()` never performs network I/O.
- If the persisted remote payload is absent/stale, `snapshot()` starts one
daemon refresh thread and returns immediately.
-- Successful remote checks are eligible for revalidation after 60 seconds and
+- Successful remote checks are eligible for revalidation after five minutes and
reuse same-source ETag/Last-Modified validators; a 304 advances the check
timestamp without replacing the last-known-good catalog.
- Remote payloads are strictly validated before replacing the cache.
diff --git a/docs/plans/cli-query-pagination.md b/docs/plans/cli-query-pagination.md
index 5716e726b..04082ba26 100644
--- a/docs/plans/cli-query-pagination.md
+++ b/docs/plans/cli-query-pagination.md
@@ -47,7 +47,7 @@ Text output should append a concise "more records" hint when `has_more` is true.
Extend `vibe runs list` with:
-- `--page`, `--limit`, `--all`
+- `--page`, `--limit` (always bounded; no unpaginated bypass)
- `--status`
- `--type`
- `--agent`
@@ -65,7 +65,7 @@ memory; it is compatibility-only.
Extend `vibe show list` with:
-- `--page`, `--limit`, `--all`
+- `--page`, `--limit` (always bounded; no unpaginated bypass)
- `--visibility`
- `--session-id`
- `--updated-after`
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 91537394b..ae6fdd5bd 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -126,7 +126,7 @@
"string",
"null"
],
- "description": "ISO 4217, e.g. CNY/USD"
+ "description": "ISO 4217. Default and product standard is USD (owner ruling 2026-07-25): upstream vendors bill in USD, so UI must never fall back to a local currency. Other codes are honored only when the backend explicitly reports them."
}
}
},
@@ -238,7 +238,7 @@
"usage": {
"cycle_used_pct": null,
"month_spend_cents": 320,
- "currency": "CNY"
+ "currency": "USD"
},
"models": [
{
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index f62415aa1..78d4bcb9e 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -1621,6 +1621,12 @@ class ClaudeAgent(BaseAgent):
if not tool_use_id:
return
tool_input = getattr(block, "input", None)
+ # Deliberately not the same test as ``core/agent_tool_policy.py``, which
+ # treats an omitted flag on an ``Agent`` call as background because that
+ # is the tool's documented default. This helper is generic over every
+ # tool, and for the dominant case -- ``Bash`` -- an omitted flag means
+ # foreground. Misjudging a frame here only mislabels a task frame, so it
+ # stays with the majority reading instead of special-casing per tool.
runs_in_background = bool(
isinstance(tool_input, dict) and tool_input.get("run_in_background") is True
)
diff --git a/modules/claude_sdk_compat.py b/modules/claude_sdk_compat.py
index 5b9d116a5..66a7487d0 100644
--- a/modules/claude_sdk_compat.py
+++ b/modules/claude_sdk_compat.py
@@ -48,6 +48,17 @@ try:
class TaskNotificationMessage(SystemMessage):
pass
+ try:
+ from claude_agent_sdk import HookMatcher # type: ignore[import-not-found]
+
+ CLAUDE_SDK_HOOKS_AVAILABLE = True
+ except ImportError:
+ # In-process hooks postdate the core SDK types. Callers must check
+ # CLAUDE_SDK_HOOKS_AVAILABLE before passing `hooks=` to
+ # ClaudeAgentOptions, since it is a dataclass and rejects unknown kwargs.
+ HookMatcher = None # type: ignore[assignment]
+ CLAUDE_SDK_HOOKS_AVAILABLE = False
+
CLAUDE_SDK_AVAILABLE = True
def _should_ignore_message_parse_error(data: object) -> bool:
@@ -82,6 +93,8 @@ try:
yield message
except ModuleNotFoundError: # pragma: no cover - exercised only in minimal test envs
CLAUDE_SDK_AVAILABLE = False
+ CLAUDE_SDK_HOOKS_AVAILABLE = False
+ HookMatcher = None # type: ignore[assignment]
class _MissingClaudeSDK:
def __init__(self, *args, **kwargs):
diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.md
index cba38de0a..b8f9bc8d8 100644
--- a/skills/use-avibe/SKILL.md
+++ b/skills/use-avibe/SKILL.md
@@ -808,8 +808,9 @@ Operational guidance:
- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches accept additional flags like `--shell`, `--timeout` (per-cycle), `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay`
- use `vibe task update <id>` to keep the same task ID while changing name, schedule, message, agent, or target
- use `vibe watch update <id> ...` when you must rename, retarget, or change the waiter/options
-- use `vibe task list --brief` and `vibe watch list --brief` for scheduling-focused summaries
-- `vibe task list` hides completed one-shot tasks by default; use `vibe task list --all` when you need full history
+- Agent-facing collection commands return 20 compact rows per page, cap `--limit` at 100, and have no unpaginated `--all` mode; follow `pagination.next_command` when more rows exist
+- use `--include-finished` for paginated task/watch one-shot history
+- both list commands hide successful one-shot definitions by default while failures stay visible; use `--include-finished` and follow `pagination.next_command` for bounded history
- use `vibe task show <id>`, `vibe watch show <id>`, or `vibe runs show <run-id>` to inspect stored fields and runtime state
- use `vibe task pause` / `vibe task resume` and `vibe watch pause` / `vibe watch resume` to disable a task or watch without deleting it
- treat `warnings` from task, watch, agent-run, or runs commands as delivery-risk hints to fix proactively
@@ -957,7 +958,7 @@ Screenshots:
Scheduled tasks:
-- `vibe task add`, `vibe task update`, `vibe task list [--all|--brief]`, `vibe task show <id>`, `vibe task run <id>`, `vibe task pause <id>`, `vibe task resume <id>`, `vibe task remove <id>`
+- `vibe task add`, `vibe task update`, `vibe task list [--include-finished] [--page N] [--limit N]`, `vibe task show <id>`, `vibe task run <id>`, `vibe task pause <id>`, `vibe task resume <id>`, `vibe task remove <id>`
Agent runs:
@@ -966,7 +967,7 @@ Agent runs:
Watches:
-- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--brief]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`
+- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--include-finished] [--page N] [--limit N]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`
For any subcommand, prefer `<command> --help` before composing a new invocation. Harness commands default to this Agent Session inside an Avibe-injected Agent shell. Use `--session-id` only to target a different existing Session, `--same-scope` or `--scope-id` when creating a Session in a visible scope, and `--no-callback` only when an async Agent run will be inspected later through `vibe runs`. Use `--message` / `--message-file` for user messages. `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; `vibe agent run` takes `--sync`; and `vibe watch add` takes its own waiter options (`--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy flags between task, watch, and agent-run commands without checking help.
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index 20de58501..506d88da9 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -808,8 +808,9 @@ Operational guidance:
- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches accept additional flags like `--shell`, `--timeout` (per-cycle), `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay`
- use `vibe task update <id>` to keep the same task ID while changing name, schedule, message, agent, or target
- use `vibe watch update <id> ...` when you must rename, retarget, or change the waiter/options
-- use `vibe task list --brief` and `vibe watch list --brief` for scheduling-focused summaries
-- `vibe task list` hides completed one-shot tasks by default; use `vibe task list --all` when you need full history
+- Agent-facing collection commands return 20 compact rows per page, cap `--limit` at 100, and have no unpaginated `--all` mode; follow `pagination.next_command` when more rows exist
+- use `--include-finished` for paginated task/watch one-shot history
+- both list commands hide successful one-shot definitions by default while failures stay visible; use `--include-finished` and follow `pagination.next_command` for bounded history
- use `vibe task show <id>`, `vibe watch show <id>`, or `vibe runs show <run-id>` to inspect stored fields and runtime state
- use `vibe task pause` / `vibe task resume` and `vibe watch pause` / `vibe watch resume` to disable a task or watch without deleting it
- treat `warnings` from task, watch, agent-run, or runs commands as delivery-risk hints to fix proactively
@@ -957,7 +958,7 @@ Screenshots:
Scheduled tasks:
-- `vibe task add`, `vibe task update`, `vibe task list [--all|--brief]`, `vibe task show <id>`, `vibe task run <id>`, `vibe task pause <id>`, `vibe task resume <id>`, `vibe task remove <id>`
+- `vibe task add`, `vibe task update`, `vibe task list [--include-finished] [--page N] [--limit N]`, `vibe task show <id>`, `vibe task run <id>`, `vibe task pause <id>`, `vibe task resume <id>`, `vibe task remove <id>`
Agent runs:
@@ -966,7 +967,7 @@ Agent runs:
Watches:
-- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--brief]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`
+- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--include-finished] [--page N] [--limit N]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`
For any subcommand, prefer `<command> --help` before composing a new invocation. Harness commands default to this Agent Session inside an Avibe-injected Agent shell. Use `--session-id` only to target a different existing Session, `--same-scope` or `--scope-id` when creating a Session in a visible scope, and `--no-callback` only when an async Agent run will be inspected later through `vibe runs`. Use `--message` / `--message-file` for user messages. `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; `vibe agent run` takes `--sync`; and `vibe watch add` takes its own waiter options (`--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy flags between task, watch, and agent-run commands without checking help.
diff --git a/storage/pagination.py b/storage/pagination.py
index 2f2d66e4c..b6ca34586 100644
--- a/storage/pagination.py
+++ b/storage/pagination.py
@@ -35,12 +35,9 @@ def make_page_request(
*,
page: int | None = None,
limit: int | None = None,
- all_items: bool = False,
default_limit: int = DEFAULT_PAGE_LIMIT,
max_limit: int = MAX_PAGE_LIMIT,
-) -> PageRequest | None:
- if all_items:
- return None
+) -> PageRequest:
resolved_page = page if page is not None else 1
resolved_limit = limit if limit is not None else default_limit
if resolved_page < 1:
diff --git a/tests/test_agent_tool_policy.py b/tests/test_agent_tool_policy.py
new file mode 100644
index 000000000..933c66630
--- /dev/null
+++ b/tests/test_agent_tool_policy.py
@@ -0,0 +1,388 @@
+"""Session-only background tools must be redirected to the Avibe Harness.
+
+Covers the pure policy in ``core/agent_tool_policy.py`` and the Claude adapter
+in ``core/handlers/session_handler.py``. Everything here is in-process: no
+config, no SQLite state, no Claude SDK, no subprocess.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core import agent_tool_policy as policy
+from core import system_prompt_injection as spi
+from core.handlers import session_handler as sh
+
+
+# --------------------------------------------------------------------------
+# policy
+# --------------------------------------------------------------------------
+
+
+ "tool_name,tool_input",
+ [
+ ("Agent", {}), # background is the tool's default
+ ("Agent", {"run_in_background": True}),
+ ("ScheduleWakeup", {"delaySeconds": 600, "prompt": "x", "reason": "y"}),
+ ("CronCreate", {"cron": "0 9 * * *", "prompt": "x"}),
+ ("CronCreate", {"cron": "0 9 * * *", "prompt": "x", "durable": False}),
+ ("Workflow", {"script": "export const meta = {}"}),
+ ],
+)
+def test_session_only_background_calls_are_denied(tool_name, tool_input):
+ decision = policy.check_tool_call(tool_name, tool_input, env={})
+ assert decision.denied
+ assert "vibe " in decision.reason # every deny names an executable alternative
+
+
+ "tool_name,tool_input",
+ [
+ ("Agent", {"run_in_background": False}), # resolves inside this turn
+ ("ScheduleWakeup", {"stop": True}), # ending a loop must stay reachable
+ ("CronCreate", {"cron": "0 9 * * *", "prompt": "x", "durable": True}),
+ ],
+)
+def test_durable_or_synchronous_calls_are_allowed(tool_name, tool_input):
+ assert policy.check_tool_call(tool_name, tool_input, env={}).allowed
+
+
[email protected]("tool_name", ["Read", "Write", "TaskCreate", "WebFetch", ""])
+def test_unrelated_tools_are_untouched(tool_name):
+ decision = policy.check_tool_call(tool_name, {"run_in_background": True}, env={})
+ assert decision.allowed
+ assert not decision.advice
+
+
+def test_background_shell_is_advised_not_denied():
+ decision = policy.check_tool_call("Bash", {"command": "make", "run_in_background": True}, env={})
+ assert decision.allowed # a hard block would cost more than it saves
+ assert "vibe watch add" in decision.advice
+ assert "nohup" in decision.advice # detaching escapes the check entirely
+
+
+ "tool_input",
+ [
+ {"command": "ls"},
+ {"command": "ls", "run_in_background": False},
+ ],
+)
+def test_foreground_shell_gets_no_advice(tool_input):
+ decision = policy.check_tool_call("Bash", tool_input, env={})
+ assert decision.allowed
+ assert not decision.advice
+
+
+def test_bash_is_never_denied_under_any_input():
+ for tool_input in ({}, {"run_in_background": True}, {"run_in_background": "yes"}):
+ assert policy.check_tool_call("Bash", tool_input, env={}).allowed
+
+
+def test_agent_denial_points_out_that_concurrency_survives():
+ # Without this, an agent reading the deny can conclude it must now fan work
+ # out serially. Several synchronous calls in one message still run at once,
+ # so the only thing background buys is outliving the turn.
+ reason = policy.check_tool_call("Agent", {}, env={}).reason
+ assert "run concurrently" in reason
+ assert "run_in_background: false" in reason
+
+
+def test_missing_tool_input_is_treated_as_the_tool_default():
+ assert policy.check_tool_call("Agent", None, env={}).denied
+
+
+def test_env_escape_hatch_restores_backend_native_behavior():
+ env = {policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV: "1"}
+ assert policy.check_tool_call("Agent", {}, env=env).allowed
+ assert policy.check_tool_call("Workflow", {}, env=env).allowed
+ assert policy.native_background_tools_allowed(env) is True
+ # The advisory is part of the same policy, so it goes quiet too.
+ assert not policy.check_tool_call("Bash", {"run_in_background": True}, env=env).advice
+
+
+def test_blank_escape_hatch_does_not_disable_the_policy():
+ env = {policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV: " "}
+ assert policy.native_background_tools_allowed(env) is False
+ assert policy.check_tool_call("Agent", {}, env=env).denied
+
+
+def test_always_session_only_names_are_a_subset_of_the_policy():
+ covered = set(policy.session_only_background_tool_names())
+ assert set(policy.ALWAYS_SESSION_ONLY_TOOL_NAMES) <= covered
+ # Names with a legitimate non-background form must not be blocked by name,
+ # and an advisory-only tool must never reach a deny list at all.
+ assert "Agent" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+ assert "CronCreate" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+ assert "Bash" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+
+
+def test_name_only_fallback_never_strands_a_running_loop():
+ # `ScheduleWakeup {"stop": true}` is the only way to end a dynamic loop.
+ # A name-level block cannot see the argument, so listing the tool there
+ # would make an already-running loop unstoppable on older SDKs.
+ assert "ScheduleWakeup" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+ assert policy.check_tool_call("ScheduleWakeup", {"stop": True}, env={}).allowed
+
+
[email protected]("name", policy.ALWAYS_SESSION_ONLY_TOOL_NAMES)
+def test_name_only_fallback_entries_are_denied_under_every_input(name):
+ # A name-level block is faithful only if no input to that tool is allowed.
+ for tool_input in ({}, {"stop": True}, {"durable": True}, {"run_in_background": False}):
+ assert policy.check_tool_call(name, tool_input, env={}).denied
+
+
+# --------------------------------------------------------------------------
+# injected prompt
+# --------------------------------------------------------------------------
+
+
+def test_shared_prompt_module_has_no_top_level_claude_import():
+ # `core/system_prompt_injection.py` is imported by every backend adapter,
+ # and the Codex adapter is loaded under a stub `modules` namespace where a
+ # Claude-only import raises at module scope. A top-level import here breaks
+ # collection of that suite outright, so the dependency stays inside the
+ # Claude branch of the selector.
+ import ast
+
+ source = Path(spi.__file__).read_text(encoding="utf-8")
+ for node in ast.parse(source).body: # module scope only, not nested
+ if isinstance(node, ast.ImportFrom):
+ assert not (node.module or "").startswith("modules.claude"), (
+ f"top-level import of {node.module} makes this module "
+ "unloadable for non-Claude backends"
+ )
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ assert not alias.name.startswith("modules.claude")
+
+
+def test_prompt_describes_enforcement_when_the_policy_is_active(monkeypatch):
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ section = spi._build_tool_policy_section("claude")
+ assert "is blocked at the tool layer" in section
+ assert "are all denied" in section
+
+
+def test_prompt_admits_partial_enforcement_without_argument_aware_hooks(monkeypatch):
+ # The name-only fallback cannot inspect arguments, so it blocks Workflow and
+ # nothing else. Claiming full denial would stop the agent from self-policing
+ # exactly the calls no gate is covering.
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: False)
+ section = spi._build_tool_policy_section("claude")
+ assert "only partly blocked" in section
+ assert "A native multi-agent workflow is denied outright" in section
+ assert "are **not** stopped here" in section
+ assert "is blocked at the tool layer" not in section
+ assert "are all denied" not in section
+
+
+def test_hookless_prompt_names_every_tool_the_name_list_leaves_open(monkeypatch):
+ # Whatever `check_tool_call` can deny but the name-only list does not carry
+ # is unguarded on this path, and the prompt is the only thing left telling
+ # the agent so. `Bash` is exempt because the policy never denies it.
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: False)
+ section = spi._build_tool_policy_section("claude")
+ unguarded = {
+ name
+ for name in policy.session_only_background_tool_names()
+ if name not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES and name != "Bash"
+ }
+ assert unguarded == {"Agent", "ScheduleWakeup", "CronCreate"}
+ described = {
+ "Agent": "background subagent",
+ "ScheduleWakeup": "self-scheduled wakeup",
+ "CronCreate": "non-durable in-session cron job",
+ }
+ for name in unguarded:
+ assert described[name] in section, f"{name} is unguarded but unmentioned"
+
+
+def test_prompt_claims_no_gate_on_backends_that_install_none(monkeypatch):
+ # Only the Claude session handler installs the hook, so hook availability in
+ # an importable SDK says nothing about a Codex or OpenCode session.
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ for backend in ("codex", "opencode", "unknown"):
+ section = spi._build_tool_policy_section(backend)
+ assert "is not gated in this runtime" in section
+ assert "blocked at the tool layer" not in section
+ assert "only partly blocked" not in section
+ assert "vibe watch add" in section
+
+
+def test_escape_hatch_outranks_hook_availability(monkeypatch):
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: False)
+ assert "is not blocked in this runtime" in spi._build_tool_policy_section("claude")
+
+
+def test_escape_hatch_does_not_reach_backends_it_cannot_affect(monkeypatch):
+ # The hatch turns off a gate only Claude installs, so on another backend it
+ # changes nothing. Letting the relaxed text win there would swap accurate
+ # ungated wording for Claude-specific tool claims.
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ for backend in ("codex", "opencode", "unknown"):
+ section = spi._build_tool_policy_section(backend)
+ assert "is not gated in this runtime" in section
+ assert "is not blocked in this runtime" not in section
+ assert policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV not in section
+
+
+def test_prompt_drops_the_block_claim_under_the_escape_hatch(monkeypatch):
+ # Enforcement is off here, so telling the agent these tools are denied
+ # would stop it from using what the operator deliberately re-enabled.
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ section = spi._build_tool_policy_section("claude")
+ assert "is not blocked in this runtime" in section
+ assert "blocked at the tool layer" not in section
+ assert "denied" not in section
+ # The Harness is still the default; only the enforcement claim changes.
+ assert "vibe agent run" in section
+ assert policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV in section
+
+
+def test_prompt_section_is_read_per_turn_not_at_import(monkeypatch):
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ before = spi._build_tool_policy_section("claude")
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ assert spi._build_tool_policy_section("claude") != before
+
+
+# --------------------------------------------------------------------------
+# claude adapter
+# --------------------------------------------------------------------------
+
+
+class _Controller:
+ """Minimal stand-in for BaseHandler's controller dependency."""
+
+ def __init__(self):
+ self.config = object()
+ self.im_client = object()
+ self.settings_manager = object()
+ self.sessions = object()
+ self.session_manager = object()
+ self.claude_sessions = {}
+ self.receiver_tasks = {}
+ self.stored_session_mappings = {}
+
+
+def _handler() -> sh.SessionHandler:
+ return sh.SessionHandler(_Controller())
+
+
+def _run_guard(tool_name, tool_input):
+ return asyncio.run(
+ _handler()._guard_session_only_background_tools(
+ {"hook_event_name": "PreToolUse", "tool_name": tool_name, "tool_input": tool_input},
+ "toolu_test",
+ None,
+ )
+ )
+
+
+def test_guard_denies_a_background_subagent():
+ out = _run_guard("Agent", {"prompt": "go", "run_in_background": True})
+ specific = out["hookSpecificOutput"]
+ assert specific["hookEventName"] == "PreToolUse"
+ assert specific["permissionDecision"] == "deny"
+ assert "vibe agent run" in specific["permissionDecisionReason"]
+
+
+def test_guard_allows_a_synchronous_subagent():
+ assert _run_guard("Agent", {"prompt": "go", "run_in_background": False}) == {}
+
+
+def test_guard_allows_unrelated_tools():
+ assert _run_guard("Read", {"file_path": "/tmp/x"}) == {}
+
+
+def test_guard_stays_silent_on_a_foreground_shell():
+ assert _run_guard("Bash", {"command": "ls"}) == {}
+
+
+def test_guard_advises_on_a_background_shell_without_granting_permission():
+ out = _run_guard("Bash", {"command": "make", "run_in_background": True})
+ specific = out["hookSpecificOutput"]
+ assert specific["hookEventName"] == "PreToolUse"
+ assert "vibe watch add" in specific["additionalContext"]
+ # Injecting context must not double as an approval: an explicit "allow" here
+ # would override any permission hook the user configured for Bash.
+ assert "permissionDecision" not in specific
+
+
+def test_guard_never_raises_on_a_malformed_payload():
+ # A guard that throws would take the whole turn down with it.
+ out = asyncio.run(_handler()._guard_session_only_background_tools({}, None, None))
+ assert out == {}
+
+
+def test_hooks_are_wired_when_the_sdk_supports_them(monkeypatch):
+ captured = {}
+
+ class _HookMatcher:
+ def __init__(self, matcher=None, hooks=None, timeout=None):
+ captured["matcher"] = matcher
+ captured["hooks"] = hooks
+
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", True)
+ monkeypatch.setattr(sh, "HookMatcher", _HookMatcher)
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+
+ handler = _handler()
+ hooks = handler._build_claude_tool_policy_hooks()
+
+ assert list(hooks) == ["PreToolUse"]
+ assert set(captured["matcher"].split("|")) == set(policy.session_only_background_tool_names())
+ assert captured["hooks"] == [handler._guard_session_only_background_tools]
+ # The precise hook path owns enforcement, so nothing extra is denied by name.
+ assert handler._claude_disallowed_tools(hooks) == sh.CLAUDE_REMOTE_DISALLOWED_TOOLS
+
+
+def test_older_sdk_falls_back_to_a_name_level_deny_list(monkeypatch):
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", False)
+ monkeypatch.setattr(sh, "HookMatcher", None)
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+
+ handler = _handler()
+ assert handler._build_claude_tool_policy_hooks() is None
+
+ disallowed = handler._claude_disallowed_tools(None)
+ for name in sh.CLAUDE_REMOTE_DISALLOWED_TOOLS:
+ assert name in disallowed
+ for name in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES:
+ assert name in disallowed
+ assert len(disallowed) == len(set(disallowed))
+
+
+def test_escape_hatch_disables_both_enforcement_paths(monkeypatch):
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", True)
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+
+ handler = _handler()
+ assert handler._build_claude_tool_policy_hooks() is None
+ assert handler._claude_disallowed_tools(None) == sh.CLAUDE_REMOTE_DISALLOWED_TOOLS
+
+
+def test_disallowed_tools_constant_is_not_mutated(monkeypatch):
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", False)
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ before = list(sh.CLAUDE_REMOTE_DISALLOWED_TOOLS)
+
+ _handler()._claude_disallowed_tools(None)
+
+ assert sh.CLAUDE_REMOTE_DISALLOWED_TOOLS == before
diff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.py
index fe5207877..93a374dd4 100644
--- a/tests/test_backend_model_catalog.py
+++ b/tests/test_backend_model_catalog.py
@@ -257,13 +257,13 @@ def test_snapshot_returns_immediately_while_remote_refresh_runs(monkeypatch, tmp
@pytest.mark.parametrize("timestamp_key", ["fetched_at", "checked_at"])
-def test_remote_catalog_revalidates_after_one_minute(monkeypatch, timestamp_key):
+def test_remote_catalog_revalidates_after_five_minutes(monkeypatch, timestamp_key):
payload = {timestamp_key: 100.0, "catalog": {"schema_version": 1, "backends": {}}}
- monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 159.0)
+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 399.0)
assert backend_model_catalog._remote_cache_stale(payload) is False
- monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 160.0)
+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 400.0)
assert backend_model_catalog._remote_cache_stale(payload) is True
diff --git a/tests/test_cli_agent_models.py b/tests/test_cli_agent_models.py
index 938734891..ff52216a5 100644
--- a/tests/test_cli_agent_models.py
+++ b/tests/test_cli_agent_models.py
@@ -62,6 +62,85 @@ def test_cmd_agent_models_by_backend(monkeypatch):
assert payload["models"][0]["value"] == "gpt-5.5"
+def test_cmd_agent_models_uses_shared_pagination(monkeypatch):
+ monkeypatch.setattr(
+ cli.api,
+ "agent_model_options",
+ lambda *a, **k: {
+ "ok": True,
+ "backend": "codex",
+ "default_model": None,
+ "models": [
+ {"value": f"gpt-{index:02d}", "default": False, "reasoning_efforts": ["high"]}
+ for index in range(25)
+ ],
+ "providers": None,
+ "source": "test catalog",
+ "live": False,
+ "notes": None,
+ },
+ )
+ args = cli.build_parser().parse_args(["agent", "models", "--backend", "codex"])
+
+ code, payload = _run(cli.cmd_agent_models, args)
+
+ assert code == 0
+ assert len(payload["models"]) == 20
+ assert payload["pagination"]["next_command"] == (
+ "vibe agent models --backend codex --page 2 --limit 20"
+ )
+
+
+def test_cmd_agent_models_paginates_providers_and_models_together(monkeypatch):
+ monkeypatch.setattr(
+ cli.api,
+ "agent_model_options",
+ lambda *a, **k: {
+ "ok": True,
+ "backend": "opencode",
+ "default_model": None,
+ "providers": [
+ {"id": f"provider-{index:02d}", "name": f"Provider {index}", "custom": False}
+ for index in range(15)
+ ],
+ "models": [
+ {
+ "value": f"provider-{index:02d}/model",
+ "provider": f"provider-{index:02d}",
+ "default": False,
+ "reasoning_efforts": [],
+ }
+ for index in range(10)
+ ],
+ "source": "test catalog",
+ "live": True,
+ "notes": None,
+ },
+ )
+
+ first_args = cli.build_parser().parse_args(
+ ["agent", "models", "--backend", "opencode"]
+ )
+ code, first = _run(cli.cmd_agent_models, first_args)
+
+ assert code == 0
+ assert len(first["providers"]) == 15
+ assert len(first["models"]) == 5
+ assert first["pagination"]["returned"] == 20
+ assert first["pagination"]["has_more"] is True
+
+ second_args = cli.build_parser().parse_args(
+ ["agent", "models", "--backend", "opencode", "--page", "2"]
+ )
+ code, second = _run(cli.cmd_agent_models, second_args)
+
+ assert code == 0
+ assert second["providers"] == []
+ assert len(second["models"]) == 5
+ assert second["pagination"]["returned"] == 5
+ assert second["pagination"]["has_more"] is False
+
+
def test_cmd_agent_models_requires_exactly_one_target():
code, payload = _run(cli.cmd_agent_models, _models_ns())
assert code == 1
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index 23dd1d661..e29230853 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -1,12 +1,118 @@
from __future__ import annotations
+import argparse
import json
+import re
+import shlex
from config import paths
+from core.system_prompt_injection import build_system_prompt_injection
+from modules.im.base import MessageContext
from storage.background import SQLiteBackgroundTaskStore
from vibe import cli
+def _command_parser(path: tuple[str, ...]):
+ parser = cli.build_parser()
+ for segment in path:
+ subparsers = next(
+ action for action in parser._actions if isinstance(action, argparse._SubParsersAction)
+ )
+ parser = subparsers.choices[segment]
+ return parser
+
+
+def _parser_flags(parser) -> set[str]:
+ return {flag for action in parser._actions for flag in action.option_strings}
+
+
+def _iter_command_parsers(parser, path=()):
+ for action in parser._actions:
+ if not isinstance(action, argparse._SubParsersAction):
+ continue
+ for name, child in action.choices.items():
+ child_path = (*path, name)
+ yield child_path, child
+ yield from _iter_command_parsers(child, child_path)
+
+
+def _prompt_command_parser(command: str):
+ tokens = shlex.split(command)
+ assert tokens[0] == "vibe"
+ parser = cli.build_parser()
+ path: list[str] = []
+ for token in tokens[1:]:
+ subparsers = next(
+ (
+ action
+ for action in parser._actions
+ if isinstance(action, argparse._SubParsersAction)
+ ),
+ None,
+ )
+ if subparsers is None or token not in subparsers.choices:
+ break
+ parser = subparsers.choices[token]
+ path.append(token)
+ return parser, tuple(path)
+
+
+def test_all_collection_commands_share_bounded_pagination_contract() -> None:
+ collection_commands = {
+ ("agent", "list"),
+ ("agent", "models"),
+ ("runs", "list"),
+ ("session", "list"),
+ ("vault", "list"),
+ ("vault", "find"),
+ ("vault", "tags"),
+ ("show", "list"),
+ ("show", "marks"),
+ ("data", "query"),
+ ("task", "list"),
+ ("watch", "list"),
+ }
+ parser = cli.build_parser()
+ discovered_list_commands = {
+ path
+ for path, _ in _iter_command_parsers(parser)
+ if path[-1] == "list" and path[-1] != "ls"
+ }
+
+ assert discovered_list_commands <= collection_commands
+ for path in collection_commands:
+ flags = _parser_flags(_command_parser(path))
+ assert "--page" in flags, path
+ assert "--limit" in flags, path
+ assert "--all" not in flags, path
+
+
+def test_injected_vibe_commands_only_use_parser_supported_flags() -> None:
+ context = MessageContext(
+ user_id="user",
+ channel_id="channel",
+ platform="avibe",
+ platform_specific={"agent_session_id": "ses-test"},
+ )
+ prompt = build_system_prompt_injection(context=context)
+ commands = re.findall(r"`(vibe [^`\n]+)`", prompt)
+ checked_commands = 0
+
+ for command in commands:
+ mentioned_flags = set(re.findall(r"(?<![\w-])--[a-z][a-z0-9-]*", command))
+ if not mentioned_flags:
+ continue
+ parser, path = _prompt_command_parser(command)
+ unsupported_flags = mentioned_flags - _parser_flags(parser)
+ assert not unsupported_flags, (
+ f"Injected command {command!r} uses flags unsupported by "
+ f"{' '.join(('vibe', *path))}: {sorted(unsupported_flags)}"
+ )
+ checked_commands += 1
+
+ assert checked_commands >= 20
+
+
def test_runs_list_cli_defaults_to_first_page(monkeypatch, tmp_path, capsys) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
@@ -141,6 +247,7 @@ def test_runs_list_cli_next_command_uses_absolute_time_filters(monkeypatch, tmp_
assert "--created-after 2026-05-25T00:00:00+00:00" in payload["pagination"]["next_command"]
assert "--created-after 2026-05-25T08:00:00+08:00" not in payload["pagination"]["next_command"]
assert payload["pagination"]["next_command"].endswith("--page 2 --limit 10")
+ assert "message" not in payload["runs"][0]
def test_runs_show_defaults_to_caller_run(monkeypatch, tmp_path, capsys) -> None:
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 90c321d72..4d6d161e8 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -78,10 +78,10 @@ def test_agent_enable_disable_cli_toggles_enabled_state(tmp_path: Path, capsys)
assert cli.cmd_agent_list(_parse_agent(["list", "--brief"])) == 0
assert json.loads(capsys.readouterr().out)["agents"] == []
- assert cli.cmd_agent_list(_parse_agent(["list", "--all", "--brief"])) == 0
- all_payload = json.loads(capsys.readouterr().out)
- assert all_payload["agents"][0]["name"] == "worker"
- assert all_payload["agents"][0]["enabled"] is False
+ assert cli.cmd_agent_list(_parse_agent(["list", "--include-disabled"])) == 0
+ disabled_list_payload = json.loads(capsys.readouterr().out)
+ assert disabled_list_payload["agents"][0]["name"] == "worker"
+ assert disabled_list_payload["agents"][0]["enabled"] is False
assert cli.cmd_agent_set_enabled(_parse_agent(["enable", "worker"]), enabled=True) == 0
enabled_payload = json.loads(capsys.readouterr().out)
@@ -101,6 +101,24 @@ def test_disabled_agent_cannot_run(tmp_path: Path) -> None:
assert payload["error"] == "agent 'worker' is disabled"
+def test_agent_list_is_bounded_and_compact_by_default(tmp_path: Path, capsys) -> None:
+ agent_store = cli.VibeAgentStore(tmp_path / "state" / "vibe.sqlite")
+ for index in range(25):
+ agent_store.create(
+ name=f"worker-{index:02d}",
+ backend="codex",
+ system_prompt="large detail that belongs in agent show",
+ )
+
+ with patch("vibe.cli._agent_store", return_value=agent_store):
+ assert cli.cmd_agent_list(_parse_agent(["list"])) == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["agents"]) == 20
+ assert "system_prompt" not in payload["agents"][0]
+ assert payload["pagination"]["next_command"] == "vibe agent list --page 2 --limit 20"
+
+
def test_task_add_rejects_unsupported_platform() -> None:
args = _parse_task_add(
[
@@ -237,9 +255,11 @@ def test_task_list_help_mentions_completed_one_shots_hidden_by_default(capsys) -
assert exc.value.code == 0
captured = capsys.readouterr()
- assert "Completed one-shot tasks are hidden unless --all is used." in captured.out
- assert "--all" in captured.out
- assert "--brief" in captured.out
+ assert "Successful one-shot tasks are hidden by default" in captured.out
+ assert "--include-finished" in captured.out
+ assert "--page" in captured.out
+ assert "--limit" in captured.out
+ assert "--all" not in captured.out
def test_task_update_help_includes_partial_update_guidance(capsys) -> None:
@@ -971,6 +991,14 @@ def test_task_list_hides_completed_one_shots_by_default(tmp_path: Path, capsys)
timezone_name="Asia/Shanghai",
)
store.mark_task_result(done.id, error=None)
+ failed = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="failed one-shot",
+ schedule_type="at",
+ run_at="2026-03-31T10:00:00+08:00",
+ timezone_name="Asia/Shanghai",
+ )
+ store.mark_task_result(failed.id, error="delivery failed")
with patch("vibe.cli._task_store", return_value=store):
result = cli.cmd_task_list()
@@ -979,6 +1007,8 @@ def test_task_list_hides_completed_one_shots_by_default(tmp_path: Path, capsys)
payload = json.loads(capsys.readouterr().out)
ids = [item["id"] for item in payload["tasks"]]
assert done.id not in ids
+ assert failed.id in ids
+ assert next(item for item in payload["tasks"] if item["id"] == failed.id)["state"] == "failed"
def test_task_list_brief_returns_scheduling_focused_view(tmp_path: Path, capsys) -> None:
@@ -1006,7 +1036,119 @@ def test_task_list_brief_returns_scheduling_focused_view(tmp_path: Path, capsys)
assert entry["state"] == "active"
-def test_task_list_sorts_by_next_run_instant_across_timezones(
+def test_paused_recurring_task_keeps_failed_run_in_last_status(
+ tmp_path: Path,
+ capsys,
+) -> None:
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ name="Paused after failure",
+ session_key="slack::channel::C123",
+ prompt="recurring",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+ store.mark_task_result(task.id, error="delivery failed")
+ store.set_enabled(task.id, False)
+
+ with patch("vibe.cli._task_store", return_value=store):
+ assert cli.cmd_task_list(brief=True) == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["tasks"][0]["state"] == "paused"
+ assert payload["tasks"][0]["last_status"] == "failed"
+
+
+def test_task_list_defaults_to_first_page(tmp_path: Path, capsys) -> None:
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ for index in range(25):
+ store.add_task(
+ name=f"Task {index:02d}",
+ session_key="slack::channel::C123",
+ prompt=f"task {index:02d}",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+
+ with patch("vibe.cli._task_store", return_value=store):
+ result = cli.cmd_task_list(brief=True)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["tasks"]) == 20
+ assert payload["pagination"] == {
+ "page": 1,
+ "limit": 20,
+ "returned": 20,
+ "has_more": True,
+ "next_page": 2,
+ "next_command": "vibe task list --page 2 --limit 20",
+ }
+ assert payload["message"].endswith("vibe task list --page 2 --limit 20")
+
+
+def test_task_list_keeps_enabled_tasks_ahead_of_paused_history(
+ tmp_path: Path,
+ capsys,
+) -> None:
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ for index in range(21):
+ paused = store.add_task(
+ name=f"Paused {index:02d}",
+ session_key="slack::channel::C123",
+ prompt=f"paused {index:02d}",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+ store.set_enabled(paused.id, False)
+ active = store.add_task(
+ name="Active",
+ session_key="slack::channel::C123",
+ prompt="active",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+
+ with patch("vibe.cli._task_store", return_value=store):
+ assert cli.cmd_task_list(brief=True) == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["tasks"][0]["id"] == active.id
+ assert payload["tasks"][0]["state"] == "active"
+ assert payload["pagination"]["has_more"] is True
+
+
+def test_task_list_cli_dispatches_pagination_flags(
+ tmp_path: Path,
+ capsys,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ for index in range(3):
+ store.add_task(
+ name=f"Task {index}",
+ session_key="slack::channel::C123",
+ prompt=f"task {index}",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+
+ monkeypatch.setattr(sys, "argv", ["vibe", "task", "list", "--limit", "2"])
+ with patch("vibe.cli._task_store", return_value=store), pytest.raises(SystemExit) as exc:
+ cli.main()
+
+ assert exc.value.code == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["tasks"]) == 2
+ assert payload["pagination"]["next_command"] == "vibe task list --page 2 --limit 2"
+
+
+def test_task_list_order_is_stable_across_cron_boundaries(
tmp_path: Path, capsys, monkeypatch: pytest.MonkeyPatch
) -> None:
store_path = tmp_path / "scheduled_tasks.json"
@@ -1027,19 +1169,29 @@ def test_task_list_sorts_by_next_run_instant_across_timezones(
cron="0 * * * *",
timezone_name="Asia/Shanghai",
)
- next_runs = {
+ later.created_at = "2026-04-01T00:00:00+00:00"
+ earlier.created_at = "2026-04-01T00:00:01+00:00"
+ first_next_runs = {
later.id: "2026-04-01T09:30:00+08:00",
earlier.id: "2026-04-01T01:00:00+00:00",
}
- monkeypatch.setattr(cli, "_task_next_run_at", lambda task: next_runs[task.id])
+ monkeypatch.setattr(cli, "_task_next_run_at", lambda task: first_next_runs[task.id])
with patch("vibe.cli._task_store", return_value=store):
- result = cli.cmd_task_list(brief=True)
+ assert cli.cmd_task_list(brief=True) == 0
- assert result == 0
- payload = json.loads(capsys.readouterr().out)
- ordered_ids = [item["id"] for item in payload["tasks"]]
- assert ordered_ids == [earlier.id, later.id]
+ first_ids = [item["id"] for item in json.loads(capsys.readouterr().out)["tasks"]]
+
+ second_next_runs = {
+ later.id: "2026-04-01T02:00:00+00:00",
+ earlier.id: "2026-04-01T10:00:00+00:00",
+ }
+ monkeypatch.setattr(cli, "_task_next_run_at", lambda task: second_next_runs[task.id])
+ with patch("vibe.cli._task_store", return_value=store):
+ assert cli.cmd_task_list(brief=True) == 0
+
+ second_ids = [item["id"] for item in json.loads(capsys.readouterr().out)["tasks"]]
+ assert second_ids == first_ids == [later.id, earlier.id]
def test_task_show_includes_derived_schedule_fields(tmp_path: Path, capsys) -> None:
@@ -1066,7 +1218,7 @@ def test_task_show_includes_derived_schedule_fields(tmp_path: Path, capsys) -> N
assert payload["task"]["last_status"] == "never_run"
-def test_task_list_all_includes_completed_one_shots(tmp_path: Path, capsys) -> None:
+def test_task_list_include_finished_includes_completed_one_shots(tmp_path: Path, capsys) -> None:
store_path = tmp_path / "scheduled_tasks.json"
store = cli.ScheduledTaskStore(store_path)
done = store.add_task(
@@ -1079,12 +1231,41 @@ def test_task_list_all_includes_completed_one_shots(tmp_path: Path, capsys) -> N
store.mark_task_result(done.id, error=None)
with patch("vibe.cli._task_store", return_value=store):
- result = cli.cmd_task_list(include_all=True)
+ result = cli.cmd_task_list(include_finished=True)
assert result == 0
payload = json.loads(capsys.readouterr().out)
ids = [item["id"] for item in payload["tasks"]]
assert done.id in ids
+ assert payload["pagination"]["has_more"] is False
+
+
+def test_task_list_include_finished_keeps_history_paginated(tmp_path: Path, capsys) -> None:
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ for index in range(3):
+ done = store.add_task(
+ session_key="slack::channel::C123",
+ prompt=f"one-shot {index}",
+ schedule_type="at",
+ run_at="2026-03-31T09:00:00+08:00",
+ timezone_name="Asia/Shanghai",
+ )
+ store.mark_task_result(done.id, error=None)
+
+ with patch("vibe.cli._task_store", return_value=store):
+ result = cli.cmd_task_list(
+ include_finished=True,
+ brief=True,
+ page_request=cli.PageRequest(page=1, limit=2),
+ )
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["tasks"]) == 2
+ assert payload["pagination"]["has_more"] is True
+ assert payload["pagination"]["next_command"] == (
+ "vibe task list --include-finished --page 2 --limit 2"
+ )
def test_task_run_enqueues_request(tmp_path: Path, capsys) -> None:
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 52fb61d34..37c3f4e1f 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -56,6 +56,29 @@ def _startup_ok(store: ManagedWatchStore, runtime_store: WatchRuntimeStateStore,
return store.get_watch(watch_id), runtime_store.load().get("watches", {}).get(watch_id)
+def _add_test_watch(
+ store: ManagedWatchStore,
+ *,
+ name: str,
+ mode: str = "once",
+):
+ return store.add_watch(
+ name=name,
+ session_key="slack::channel::C123",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode=mode,
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+
+
def test_watch_help_describes_session_id_guidance(capsys) -> None:
parser = cli.build_parser()
@@ -90,6 +113,21 @@ def test_watch_add_help_mentions_shell_and_lifetime_timeout(capsys) -> None:
assert "--deliver-key" not in captured.out
+def test_watch_list_help_describes_bounded_history(capsys) -> None:
+ parser = cli.build_parser()
+
+ with pytest.raises(SystemExit) as exc:
+ parser.parse_args(["watch", "list", "--help"])
+
+ assert exc.value.code == 0
+ captured = capsys.readouterr()
+ assert "Successful one-shot watches are hidden by default" in captured.out
+ assert "--include-finished" in captured.out
+ assert "--page" in captured.out
+ assert "--limit" in captured.out
+ assert "--all" not in captured.out
+
+
def test_watch_add_parser_keeps_top_level_command_name() -> None:
args = _parse_watch_add(
[
@@ -712,6 +750,31 @@ def test_default_watch_startup_timeout_exceeds_reconcile_and_stable_windows() ->
assert timeout_seconds > cli.WATCH_RECONCILE_INTERVAL_SECONDS + cli.WATCH_STARTUP_STABLE_RUNNING_SECONDS
+def test_default_watch_startup_timeout_accounts_for_recovery_entries(tmp_path: Path) -> None:
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ runtime_store.write(
+ {
+ "watches": {
+ "first": {"running": True, "pid": 1234},
+ "second": {"running": True, "pid": 5678},
+ "finished": {"running": False, "pid": 9012},
+ }
+ }
+ )
+
+ recovery_entry_count = cli._watch_recovery_entry_count(runtime_store)
+ timeout_seconds = cli._default_watch_startup_timeout_seconds(
+ stable_running_seconds=cli.WATCH_STARTUP_STABLE_RUNNING_SECONDS,
+ recovery_entry_count=recovery_entry_count,
+ )
+ base_timeout = cli._default_watch_startup_timeout_seconds(
+ stable_running_seconds=cli.WATCH_STARTUP_STABLE_RUNNING_SECONDS,
+ )
+
+ assert recovery_entry_count == 2
+ assert timeout_seconds == base_timeout + (2 * cli.WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS)
+
+
def test_wait_for_watch_startup_rejects_watch_that_fails_before_stable_window(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -816,6 +879,167 @@ def test_watch_list_brief_includes_runtime_state(tmp_path: Path, capsys) -> None
assert payload["watches"][0]["mode"] == "forever"
+def test_watch_list_hides_finished_one_shots_by_default(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ active = _add_test_watch(store, name="Active")
+ completed = _add_test_watch(store, name="Completed")
+ failed = _add_test_watch(store, name="Failed")
+ paused = _add_test_watch(store, name="Paused")
+ failed_forever = _add_test_watch(store, name="Failed forever", mode="forever")
+ store.mark_cycle_result(completed.id, exit_code=0, error=None, event_detected=True, disable=True)
+ store.mark_cycle_result(failed.id, exit_code=1, error="failed", disable=True)
+ store.set_enabled(paused.id, False)
+ store.mark_cycle_result(failed_forever.id, exit_code=1, error="failed", disable=True)
+
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_list(brief=True)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ ids = {item["id"] for item in payload["watches"]}
+ assert ids == {active.id, failed.id, paused.id, failed_forever.id}
+ assert completed.id not in ids
+ assert next(item for item in payload["watches"] if item["id"] == failed.id)["state"] == "failed"
+
+
+def test_resumed_then_paused_one_shot_remains_in_default_list(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_test_watch(store, name="Resumable")
+ store.mark_cycle_result(watch.id, exit_code=0, error=None, event_detected=True, disable=True)
+
+ store.set_enabled(watch.id, True)
+ store.set_enabled(watch.id, False)
+
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ assert cli.cmd_watch_list() == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert [item["id"] for item in payload["watches"]] == [watch.id]
+ assert payload["watches"][0]["state"] == "paused"
+
+
+def test_paused_forever_watch_changed_to_once_starts_new_lifecycle(
+ tmp_path: Path,
+ capsys,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_test_watch(store, name="Change mode", mode="forever")
+ store.mark_cycle_result(watch.id, exit_code=0, error=None, event_detected=True, disable=False)
+ store.set_enabled(watch.id, False)
+ args = _parse_watch_update([watch.id, "--once"])
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ assert cli.cmd_watch_update(args) == 0
+
+ updated = store.get_watch(watch.id)
+ assert updated is not None
+ assert updated.mode == "once"
+ assert updated.last_started_at is None
+ assert updated.last_finished_at is None
+ assert updated.last_event_at is None
+ assert updated.last_exit_code is None
+ assert updated.last_error is None
+
+ capsys.readouterr()
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ assert cli.cmd_watch_list() == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert [item["id"] for item in payload["watches"]] == [watch.id]
+ assert payload["watches"][0]["state"] == "paused"
+
+
+def test_watch_list_defaults_to_first_page(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ for index in range(25):
+ _add_test_watch(store, name=f"Watch {index:02d}")
+
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_list(brief=True)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["watches"]) == 20
+ assert payload["pagination"] == {
+ "page": 1,
+ "limit": 20,
+ "returned": 20,
+ "has_more": True,
+ "next_page": 2,
+ "next_command": "vibe watch list --page 2 --limit 20",
+ }
+
+
+def test_watch_list_cli_dispatches_pagination_flags(
+ tmp_path: Path,
+ capsys,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ for index in range(3):
+ _add_test_watch(store, name=f"Watch {index}")
+
+ monkeypatch.setattr(sys, "argv", ["vibe", "watch", "list", "--limit", "2"])
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ pytest.raises(SystemExit) as exc,
+ ):
+ cli.main()
+
+ assert exc.value.code == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["watches"]) == 2
+ assert payload["pagination"]["next_command"] == "vibe watch list --page 2 --limit 2"
+
+
+def test_watch_list_include_finished_keeps_history_paginated(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ for index in range(3):
+ watch = _add_test_watch(store, name=f"Finished {index}")
+ store.mark_cycle_result(watch.id, exit_code=0, error=None, event_detected=True, disable=True)
+
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_list(
+ include_finished=True,
+ brief=True,
+ page_request=cli.PageRequest(page=1, limit=2),
+ )
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["watches"]) == 2
+ assert payload["pagination"]["has_more"] is True
+ assert payload["pagination"]["next_command"] == (
+ "vibe watch list --include-finished --page 2 --limit 2"
+ )
+
+
def test_watch_show_missing_returns_structured_error() -> None:
result, payload = _capture_stderr_json(cli.cmd_watch_show, "missing-watch")
diff --git a/tests/test_pagination.py b/tests/test_pagination.py
index 0536c805a..280e373a6 100644
--- a/tests/test_pagination.py
+++ b/tests/test_pagination.py
@@ -24,5 +24,3 @@ def test_make_page_request_validates_bounds() -> None:
with pytest.raises(ValueError, match="limit must be <= 100"):
make_page_request(limit=101)
-
- assert make_page_request(all_items=True) is None
diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.py
index 2c472357b..b8ceb3937 100644
--- a/tests/test_process_isolation.py
+++ b/tests/test_process_isolation.py
@@ -4,11 +4,59 @@ import asyncio
import logging
import os
import signal
+import sys
+from pathlib import Path
from types import SimpleNamespace
import pytest
-from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+from core import watch_worker
+from core.process_isolation import (
+ KILL_SIGNAL,
+ PROCESS_IDENTITY_ENV,
+ PersistedProcessIdentity,
+ ProcessIdentity,
+ capture_spawned_process_identity,
+ fingerprint_process_marker,
+ inspect_process_identity,
+ isolated_subprocess_kwargs,
+ new_process_identity_marker,
+ process_group_identity_status,
+ process_identity_matches,
+ process_identity_subprocess_env,
+ signal_process_tree,
+ terminate_process_group_by_pgid,
+ terminate_process_tree_by_pid,
+)
+
+TEST_MARKER = "test-worker-marker"
+TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)
+
+
+def _live_identity(
+ *,
+ pid: int = 12345,
+ create_time: float = 123.0,
+ worker_fingerprint: str | None = TEST_FINGERPRINT,
+) -> ProcessIdentity:
+ return ProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
+
+
+def _persisted_identity(
+ *,
+ pid: int = 12345,
+ create_time: float = 123.0,
+ worker_fingerprint: str = TEST_FINGERPRINT,
+) -> PersistedProcessIdentity:
+ return PersistedProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
def test_isolated_subprocess_kwargs_start_new_session_on_posix() -> None:
@@ -18,6 +66,60 @@ def test_isolated_subprocess_kwargs_start_new_session_on_posix() -> None:
assert isolated_subprocess_kwargs() == {"start_new_session": True}
+def test_process_identity_reads_inherited_worker_marker(monkeypatch: pytest.MonkeyPatch) -> None:
+ process = SimpleNamespace(
+ create_time=lambda: 123.0,
+ environ=lambda: {PROCESS_IDENTITY_ENV: TEST_MARKER},
+ )
+ monkeypatch.setattr("core.process_isolation.psutil.Process", lambda _pid: process)
+
+ identity = inspect_process_identity(12345)
+
+ assert identity == _live_identity()
+
+
+def test_process_identity_survives_exec_transition() -> None:
+ if os.name == "nt":
+ pytest.skip("exec transition is POSIX-specific")
+
+ async def _run() -> None:
+ marker = new_process_identity_marker()
+ process = await asyncio.create_subprocess_exec(
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ env=process_identity_subprocess_env(marker),
+ stdin=asyncio.subprocess.PIPE,
+ **isolated_subprocess_kwargs(),
+ )
+ try:
+ expected = capture_spawned_process_identity(process.pid, marker)
+ assert expected is not None
+ assert process.stdin is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[
+ "/usr/bin/env",
+ "-i",
+ sys.executable,
+ "-c",
+ "import time; time.sleep(30)",
+ ],
+ shell_command=None,
+ )
+ )
+ await process.stdin.drain()
+ process.stdin.close()
+ await asyncio.sleep(0.1)
+ live = inspect_process_identity(process.pid)
+ assert live is not None
+ assert process_identity_matches(expected, live)
+ finally:
+ signal_process_tree(process, KILL_SIGNAL, logging.getLogger(__name__), "test process")
+ await process.wait()
+
+ asyncio.run(_run())
+
+
def test_signal_process_tree_refuses_own_process_group_on_posix(monkeypatch: pytest.MonkeyPatch) -> None:
if os.name == "nt":
pytest.skip("process group guard is POSIX-specific")
@@ -36,6 +138,345 @@ def test_signal_process_tree_refuses_own_process_group_on_posix(monkeypatch: pyt
assert sent == [("terminate", 0)]
+def test_terminate_process_tree_by_pid_refuses_current_process(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(os, "getpid", lambda: 12345)
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: pytest.fail("the current process must not be inspected for termination"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_refuses_service_process_group(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group guard is POSIX-specific")
+
+ identity = _live_identity()
+ process = SimpleNamespace(pid=12345)
+ monkeypatch.setattr("core.process_isolation._open_process_identity", lambda _pid: (process, identity))
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(os, "getpgrp", lambda: 12345)
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("the service process group must not be signaled"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_escalates_after_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ identity = _live_identity()
+ signals: list[int] = []
+ waits = iter([False, True])
+ identity_checks = 0
+
+ def open_identity(_pid: int):
+ nonlocal identity_checks
+ identity_checks += 1
+ return SimpleNamespace(pid=12345), identity
+
+ monkeypatch.setattr("core.process_isolation._open_process_identity", open_identity)
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(os, "killpg", lambda _pgid, sig: signals.append(sig))
+ monkeypatch.setattr(
+ "core.process_isolation._wait_for_process_group_exit",
+ lambda *_args, **_kwargs: next(waits),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is True
+ )
+ assert signals == [signal.SIGTERM, KILL_SIGNAL]
+ assert identity_checks == 3
+
+
+def test_terminate_process_tree_by_pid_revalidates_before_group_signal(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ identities = iter(
+ [
+ _live_identity(),
+ _live_identity(worker_fingerprint=fingerprint_process_marker("replacement")),
+ ]
+ )
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), next(identities)),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("a changed supervisor must not be signaled"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_does_not_signal_reused_pid(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ expected_identity = _persisted_identity()
+ reused_identity = _live_identity(create_time=456.0)
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), reused_identity),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(
+ os,
+ "getpgid",
+ lambda _pid: pytest.fail("a reused pid must not have its process group inspected"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=expected_identity,
+ )
+ is True
+ )
+
+
+def test_terminate_process_tree_by_pid_refuses_changed_marker(monkeypatch: pytest.MonkeyPatch) -> None:
+ expected_identity = _persisted_identity()
+ changed_identity = _live_identity(
+ worker_fingerprint=fingerprint_process_marker("other-worker-marker")
+ )
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), changed_identity),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(
+ os,
+ "getpgid",
+ lambda _pid: pytest.fail("a changed worker marker must not have its process group inspected"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=expected_identity,
+ )
+ is False
+ )
+
+
+def test_terminate_process_tree_by_pid_refuses_non_leader(monkeypatch: pytest.MonkeyPatch) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ identity = _live_identity()
+ monkeypatch.setattr(
+ "core.process_isolation._open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), identity),
+ )
+ monkeypatch.setattr(os, "getpid", lambda: 99999)
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 54321)
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("a non-leader process group must not be signaled"),
+ )
+
+ assert (
+ terminate_process_tree_by_pid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+def test_terminate_process_group_by_pgid_recovers_after_leader_exit(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ signals: list[int] = []
+ waits = iter([False, True])
+ monkeypatch.setattr(os, "getpgrp", lambda: 99999)
+ monkeypatch.setattr("core.process_isolation._process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.process_isolation.process_group_matches_identity",
+ lambda *_args: True,
+ )
+ monkeypatch.setattr(os, "killpg", lambda _pgid, sig: signals.append(sig))
+ monkeypatch.setattr(
+ "core.process_isolation._wait_for_process_group_exit",
+ lambda *_args, **_kwargs: next(waits),
+ )
+
+ assert (
+ terminate_process_group_by_pgid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process group",
+ expected_identity=_persisted_identity(),
+ )
+ is True
+ )
+ assert signals == [signal.SIGTERM, KILL_SIGNAL]
+
+
+def test_terminate_process_group_by_pgid_refuses_unverified_group(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group signalling assertion is POSIX-specific")
+
+ monkeypatch.setattr(os, "getpgrp", lambda: 99999)
+ monkeypatch.setattr("core.process_isolation._process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.process_isolation.process_group_matches_identity",
+ lambda *_args: False,
+ )
+ monkeypatch.setattr(
+ os,
+ "killpg",
+ lambda *_args: pytest.fail("an unverified process group must not be signaled"),
+ )
+
+ assert (
+ terminate_process_group_by_pgid(
+ 12345,
+ logging.getLogger(__name__),
+ "test process group",
+ expected_identity=_persisted_identity(),
+ )
+ is False
+ )
+
+
+ ("live_fingerprint", "expected_status"),
+ [
+ (TEST_FINGERPRINT, "match"),
+ (fingerprint_process_marker("other-worker-marker"), "mismatch"),
+ ],
+)
+def test_process_group_identity_status_checks_inherited_worker_marker(
+ monkeypatch: pytest.MonkeyPatch,
+ live_fingerprint: str,
+ expected_status: str,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group identity is POSIX-specific")
+
+ process = SimpleNamespace(info={"pid": 54321})
+ monkeypatch.setattr(
+ "core.process_isolation.psutil.process_iter",
+ lambda _attrs: [process],
+ )
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+ monkeypatch.setattr(
+ "core.process_isolation.inspect_process_identity",
+ lambda pid: _live_identity(
+ pid=pid,
+ create_time=124.0,
+ worker_fingerprint=live_fingerprint,
+ ),
+ )
+
+ assert (
+ process_group_identity_status(
+ 12345,
+ _persisted_identity(),
+ logging.getLogger(__name__),
+ "test process group",
+ )
+ == expected_status
+ )
+
+
+def test_process_group_identity_status_fails_closed_for_unverified_member(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if os.name == "nt":
+ pytest.skip("process group identity is POSIX-specific")
+
+ processes = [
+ SimpleNamespace(info={"pid": 54321}),
+ SimpleNamespace(info={"pid": 54322}),
+ ]
+ monkeypatch.setattr(
+ "core.process_isolation.psutil.process_iter",
+ lambda _attrs: processes,
+ )
+ monkeypatch.setattr(os, "getpgid", lambda _pid: 12345)
+
+ def inspect(pid: int) -> ProcessIdentity | None:
+ if pid == 54321:
+ return _live_identity(
+ pid=pid,
+ create_time=124.0,
+ worker_fingerprint=fingerprint_process_marker("other-worker-marker"),
+ )
+ return None
+
+ monkeypatch.setattr("core.process_isolation.inspect_process_identity", inspect)
+
+ assert (
+ process_group_identity_status(
+ 12345,
+ _persisted_identity(),
+ logging.getLogger(__name__),
+ "test process group",
+ )
+ == "unknown"
+ )
+
+
def test_asyncio_subprocess_is_spawned_outside_parent_process_group_on_posix() -> None:
if os.name == "nt":
pytest.skip("POSIX process-group assertion")
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 2ca410ae5..81ac9dc14 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -360,6 +360,12 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
with (
patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),
patch("core.show_git.show_git_checkpointing_active", return_value=True),
+ # The tool-policy paragraphs vary with SDK hook support, so pin it
+ # rather than let the installed SDK decide what this test asserts.
+ # Pinned to True on purpose: a Codex prompt must not inherit the
+ # Claude enforcement claim just because that SDK happens to be
+ # installed alongside it.
+ patch("core.system_prompt_injection._claude_sdk_hooks_available", return_value=True),
):
prompt = build_system_prompt_injection(
include_quick_replies=True,
@@ -396,6 +402,14 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("native workflow tools, backend-native skills", prompt)
self.assertIn("Do not default to backend-native automation just because the backend exposes it", prompt)
self.assertIn("Use backend-native config, skills, subagents, or workflow tools only when the user explicitly asks for backend-native behavior", prompt)
+ # This is a Codex session, and only the Claude session handler installs
+ # the tool-layer gate, so the prompt must claim no enforcement here even
+ # though the Claude SDK is importable (pinned above).
+ self.assertIn("Backend-native background work is not gated in this runtime", prompt)
+ self.assertNotIn("blocked at the tool layer", prompt)
+ self.assertNotIn("only partly blocked", prompt)
+ self.assertIn("Route that work through the Harness instead", prompt)
+ self.assertIn("Never detach with `nohup` or a trailing `&` for work whose result you need", prompt)
self.assertIn("what outcome is the user trying to secure", prompt)
self.assertIn("If the answer is an operating loop, build a Harness instead of only doing the visible step", prompt)
self.assertIn("### Mental model", prompt)
diff --git a/tests/test_session_cli.py b/tests/test_session_cli.py
index 57bcd9be1..5c886a919 100644
--- a/tests/test_session_cli.py
+++ b/tests/test_session_cli.py
@@ -101,16 +101,15 @@ def test_list_avibe_type_includes_foreground_standalone(monkeypatch, tmp_path, c
}
-def test_list_pagination_fixed_ten_no_limit_flag(monkeypatch, tmp_path, capsys):
+def test_list_uses_shared_pagination_contract(monkeypatch, tmp_path, capsys):
engine = _setup(monkeypatch, tmp_path)
- for i in range(12):
+ for i in range(22):
_seed(engine, f"ses{i:02d}", platform="slack", native="C1", last_active=f"2026-06-09T10:{i:02d}:00Z")
_, page1 = _run(cli.cmd_session_list, ["session", "list"], capsys)
- assert len(page1["sessions"]) == 10
+ assert len(page1["sessions"]) == 20
assert page1["pagination"]["has_more"] is True
- assert page1["pagination"]["next_command"] == "vibe session list --page 2"
- assert "--limit" not in page1["pagination"]["next_command"]
- _, page2 = _run(cli.cmd_session_list, ["session", "list", "--page", "2"], capsys)
+ assert page1["pagination"]["next_command"] == "vibe session list --page 2 --limit 20"
+ _, page2 = _run(cli.cmd_session_list, ["session", "list", "--page", "2", "--limit", "20"], capsys)
assert len(page2["sessions"]) == 2
assert page2["pagination"]["has_more"] is False
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 9862bafe1..1b68a7d36 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -2514,6 +2514,43 @@ def test_show_marks_filters_resolved_and_unmark_reports_partial_success(monkeypa
store.close()
+def test_show_marks_uses_shared_pagination(monkeypatch, tmp_path, capsys):
+ from core.show_session_events import ShowSessionEventStore, stable_assistant_mark_id
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ _seed_show_cli_session()
+ store = ShowSessionEventStore()
+ try:
+ for index in range(25):
+ target = f"#mark-{index:02d}"
+ store.append(
+ "ses123",
+ {
+ "type": "assistant.mark.created",
+ "mark": {
+ "id": stable_assistant_mark_id(scope="default", target=target),
+ "target": target,
+ "body": f"Mark {index}",
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ args = cli.build_parser().parse_args(
+ ["show", "marks", "--session-id", "ses123", "--json"]
+ )
+ assert cli.cmd_show(args) == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert len(payload["marks"]) == 20
+ assert payload["pagination"]["next_command"] == (
+ "vibe show marks --session-id ses123 --json --page 2 --limit 20"
+ )
+
+
def test_show_event_cli_records_generic_event(monkeypatch, tmp_path, capsys):
from sqlalchemy import select
diff --git a/tests/test_watch_worker.py b/tests/test_watch_worker.py
new file mode 100644
index 000000000..43d1413bc
--- /dev/null
+++ b/tests/test_watch_worker.py
@@ -0,0 +1,353 @@
+from __future__ import annotations
+
+import logging
+import os
+import signal
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import psutil
+import pytest
+
+from core import watch_worker
+from core.process_isolation import (
+ PROCESS_IDENTITY_ENV,
+ PersistedProcessIdentity,
+ fingerprint_process_marker,
+ process_group_identity_status,
+)
+
+
+def _supervisor_command() -> list[str]:
+ return [
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ ]
+
+
+def _supervisor_isolation_kwargs() -> dict[str, object]:
+ if os.name == "nt":
+ return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
+ return {"start_new_session": True}
+
+
+def test_watch_worker_hides_supervisor_identity_and_preserves_empty_arguments() -> None:
+ marker = "supervisor-only-marker"
+ env = dict(os.environ)
+ env[PROCESS_IDENTITY_ENV] = marker
+ spec = watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ (
+ "import os,sys; "
+ "print(os.environ.get('AVIBE_PROCESS_IDENTITY', 'missing')); "
+ "print(repr(sys.argv[1])); "
+ "print('worker-stderr', file=sys.stderr)"
+ ),
+ "",
+ ],
+ shell_command=None,
+ )
+
+ result = subprocess.run(
+ _supervisor_command(),
+ input=spec,
+ capture_output=True,
+ env=env,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 0
+ assert result.stdout.decode().splitlines() == ["missing", "''"]
+ assert result.stderr.decode().strip() == "worker-stderr"
+ assert marker not in result.stdout.decode()
+ assert marker not in result.stderr.decode()
+
+
+def test_watch_worker_rejects_invalid_specification() -> None:
+ result = subprocess.run(
+ _supervisor_command(),
+ input=b'{"version":1,"command":[],"shell_command":null}',
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 1
+ assert watch_worker.decode_watch_worker_error(result.stderr.decode()) == (
+ "invalidCommand",
+ None,
+ )
+
+
[email protected](os.name == "nt", reason="POSIX surrogateescape contract")
[email protected]("use_shell", [False, True])
+def test_posix_watch_worker_preserves_non_utf8_arguments(use_shell: bool) -> None:
+ value = os.fsdecode(b"watch-\xff")
+ if use_shell:
+ import shlex
+
+ command = []
+ shell_command = (
+ f"{shlex.quote(sys.executable)} -c "
+ f"{shlex.quote('import os,sys; print(os.fsencode(sys.argv[1]).hex())')} "
+ f"{shlex.quote(value)}"
+ )
+ else:
+ command = [
+ sys.executable,
+ "-c",
+ "import os,sys; print(os.fsencode(sys.argv[1]).hex())",
+ value,
+ ]
+ shell_command = None
+
+ result = subprocess.run(
+ _supervisor_command(),
+ input=watch_worker.encode_watch_worker_spec(
+ command=command,
+ shell_command=shell_command,
+ ),
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 0
+ assert result.stdout.decode().strip() == b"watch-\xff".hex()
+
+
[email protected](os.name == "nt", reason="POSIX signal exit contract")
+def test_posix_watch_worker_preserves_waiter_signal_exit() -> None:
+ result = subprocess.run(
+ _supervisor_command(),
+ input=watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ "import os,signal; os.kill(os.getpid(), signal.SIGTERM)",
+ ],
+ shell_command=None,
+ ),
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == -signal.SIGTERM
+
+
[email protected](os.name == "nt", reason="POSIX process group contract")
+def test_posix_watch_worker_survives_term_until_waiter_exits(tmp_path: Path) -> None:
+ waiter_pid_path = tmp_path / "waiter.pid"
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ (
+ "import os,signal,time; from pathlib import Path; "
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); "
+ f"Path({str(waiter_pid_path)!r}).write_text(str(os.getpid())); "
+ "time.sleep(30)"
+ ),
+ ],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+
+ try:
+ deadline = time.monotonic() + 5
+ while not waiter_pid_path.exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ waiter_pid = int(waiter_pid_path.read_text())
+ os.killpg(process.pid, signal.SIGTERM)
+ time.sleep(0.2)
+ assert process.poll() is None
+ assert psutil.pid_exists(waiter_pid)
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+
+
[email protected](os.name == "nt", reason="POSIX process group contract")
+def test_posix_watch_worker_waits_for_descendant_after_command_root_exits() -> None:
+ child_script = (
+ "import subprocess,sys; "
+ "child=subprocess.Popen("
+ "[sys.executable,'-c','import time; time.sleep(30)'],"
+ "stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL"
+ "); "
+ "print(child.pid, flush=True)"
+ )
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ assert process.stdout is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[sys.executable, "-c", child_script],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+ descendant_pid = int(process.stdout.readline().decode().strip())
+
+ try:
+ time.sleep(0.2)
+ assert process.poll() is None
+ assert psutil.pid_exists(descendant_pid)
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+ if psutil.pid_exists(descendant_pid):
+ psutil.Process(descendant_pid).kill()
+
+
[email protected](os.name == "nt", reason="POSIX process group identity contract")
+def test_posix_watch_worker_leaves_identity_anchor_if_supervisor_is_killed(
+ tmp_path: Path,
+) -> None:
+ marker = "surviving-anchor-marker"
+ env = dict(os.environ)
+ env[watch_worker.PROCESS_IDENTITY_ENV] = marker
+ waiter_pid_path = tmp_path / "waiter.pid"
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[
+ sys.executable,
+ "-c",
+ (
+ "import os,signal,time; from pathlib import Path; "
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); "
+ f"Path({str(waiter_pid_path)!r}).write_text(str(os.getpid())); "
+ "time.sleep(30)"
+ ),
+ ],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+
+ try:
+ deadline = time.monotonic() + 5
+ while not waiter_pid_path.exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ waiter_pid = int(waiter_pid_path.read_text())
+ identity = psutil.Process(process.pid)
+ expected = PersistedProcessIdentity(
+ pid=process.pid,
+ create_time=identity.create_time(),
+ worker_fingerprint=fingerprint_process_marker(marker),
+ )
+ os.kill(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+
+ assert psutil.pid_exists(waiter_pid)
+ assert (
+ process_group_identity_status(
+ process.pid,
+ expected,
+ logging.getLogger(__name__),
+ "test watch",
+ )
+ == "match"
+ )
+ finally:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ if process.poll() is None:
+ process.wait(timeout=10)
+
+
[email protected](os.name != "nt", reason="Windows Job Object contract")
+def test_windows_watch_worker_job_tracks_descendant_after_command_root_exits() -> None:
+ child_script = (
+ "import subprocess,sys; "
+ "child=subprocess.Popen([sys.executable,'-c','import time; time.sleep(30)']); "
+ "print(child.pid, flush=True)"
+ )
+ process = subprocess.Popen(
+ _supervisor_command(),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **_supervisor_isolation_kwargs(),
+ )
+ assert process.stdin is not None
+ assert process.stdout is not None
+ process.stdin.write(
+ watch_worker.encode_watch_worker_spec(
+ command=[sys.executable, "-c", child_script],
+ shell_command=None,
+ )
+ )
+ process.stdin.close()
+ descendant_pid = int(process.stdout.readline().decode().strip())
+
+ try:
+ assert process.poll() is None
+ process.terminate()
+ process.wait(timeout=10)
+ deadline = time.monotonic() + 10
+ while psutil.pid_exists(descendant_pid) and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert not psutil.pid_exists(descendant_pid)
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=10)
+ if psutil.pid_exists(descendant_pid):
+ psutil.Process(descendant_pid).kill()
+
+
[email protected](os.name != "nt", reason="Windows exit code contract")
+def test_windows_watch_worker_preserves_full_exit_code() -> None:
+ result = subprocess.run(
+ _supervisor_command(),
+ input=watch_worker.encode_watch_worker_spec(
+ command=[sys.executable, "-c", "import os; os._exit(513)"],
+ shell_command=None,
+ ),
+ capture_output=True,
+ timeout=10,
+ check=False,
+ **_supervisor_isolation_kwargs(),
+ )
+
+ assert result.returncode == 513
diff --git a/tests/test_watches.py b/tests/test_watches.py
index b76596876..003347949 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -4,6 +4,7 @@ import asyncio
import json
import os
import sys
+import time
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
@@ -13,17 +14,138 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
+from core import watch_worker
+from core.process_isolation import (
+ PersistedProcessIdentity,
+ ProcessIdentity,
+ fingerprint_process_marker,
+)
from core.scheduled_tasks import TaskExecutionStore
from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore, _CycleResult
from storage.background import SQLiteBackgroundTaskStore
+TEST_MARKER = "test-watch-worker"
+TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)
+
+
+class _FakeStdin:
+ def __init__(self) -> None:
+ self.payload = bytearray()
+ self.closed = False
+
+ def write(self, payload: bytes) -> None:
+ self.payload.extend(payload)
+
+ async def drain(self) -> None:
+ return None
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class _BrokenStdin(_FakeStdin):
+ async def drain(self) -> None:
+ raise BrokenPipeError
+
class _FakeProcess:
- pid = 1234
- returncode = 0
+ def __init__(
+ self,
+ *,
+ stdin: _FakeStdin | None = None,
+ stderr: bytes = b"",
+ ) -> None:
+ self.pid = 1234
+ self.returncode = 0
+ self.stdin = stdin or _FakeStdin()
+ self.stderr = stderr
+
+ async def communicate(self) -> tuple[bytes, bytes]:
+ return b"ok\n", self.stderr
+
+
+async def _start_watch_service(service: ManagedWatchService) -> None:
+ service.start()
+ startup_task = service._startup_task
+ if startup_task is not None:
+ await startup_task
+
+
+def _add_recovery_watch(
+ store: ManagedWatchStore,
+ *,
+ command: list[str],
+ shell_command: str | None = None,
+):
+ return store.add_watch(
+ name="Recovery watch",
+ session_key="slack::channel::C123",
+ command=command,
+ shell_command=shell_command,
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+
+
+def _record_watch_pid(
+ runtime_store: WatchRuntimeStateStore,
+ watch_id: str,
+ pid: int,
+ *,
+ identity: PersistedProcessIdentity | None = None,
+) -> None:
+ entry = {
+ "running": True,
+ "pid": pid,
+ "started_at": "2026-05-15T00:00:00+00:00",
+ "updated_at": "2026-05-15T00:00:01+00:00",
+ }
+ if identity is not None:
+ entry["process_identity"] = {
+ "pid": identity.pid,
+ "create_time": identity.create_time,
+ "worker_fingerprint": identity.worker_fingerprint,
+ }
+ runtime_store.write(
+ {
+ "watches": {
+ watch_id: entry,
+ }
+ }
+ )
+
+
+def _live_identity(
+ *,
+ pid: int = 4321,
+ create_time: float = 123.0,
+ worker_fingerprint: str | None = TEST_FINGERPRINT,
+) -> ProcessIdentity:
+ return ProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
- async def communicate(self):
- return b"ok\n", b""
+
+def _persisted_identity(
+ *,
+ pid: int = 4321,
+ create_time: float = 123.0,
+ worker_fingerprint: str = TEST_FINGERPRINT,
+) -> PersistedProcessIdentity:
+ return PersistedProcessIdentity(
+ pid=pid,
+ create_time=create_time,
+ worker_fingerprint=worker_fingerprint,
+ )
def test_managed_watch_store_round_trip(tmp_path: Path) -> None:
@@ -83,7 +205,17 @@ def test_managed_watch_store_preserves_zero_values_on_reload(tmp_path: Path) ->
assert saved.retry_delay_seconds == 0
-def test_managed_watch_exec_detaches_waiter_stdin(tmp_path: Path, monkeypatch) -> None:
+def test_managed_watch_store_recovery_accepts_empty_command_arguments(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py", ""])
+
+ recovered = store.list_watches_for_recovery()
+
+ assert [item.id for item in recovered] == [watch.id]
+ assert recovered[0].command == [sys.executable, "wait.py", ""]
+
+
+def test_managed_watch_exec_uses_stable_supervisor(tmp_path: Path, monkeypatch) -> None:
captured: dict[str, object] = {}
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -112,20 +244,34 @@ def test_managed_watch_exec_detaches_waiter_stdin(tmp_path: Path, monkeypatch) -
async def fake_create_subprocess_exec(*args, **kwargs):
captured["args"] = args
captured["kwargs"] = kwargs
- return _FakeProcess()
+ process = _FakeProcess()
+ captured["process"] = process
+ return process
monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
result = asyncio.run(service._run_cycle(watch, timeout_seconds=5))
assert result.exit_code == 0
- assert captured["kwargs"]["stdin"] == asyncio.subprocess.DEVNULL
+ assert captured["args"] == (
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ )
+ assert captured["kwargs"]["stdin"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stdout"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stderr"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["cwd"] == str(paths.get_vibe_remote_dir())
+ process = captured["process"]
+ assert isinstance(process, _FakeProcess)
+ assert process.stdin.closed is True
+ assert json.loads(process.stdin.payload) == {
+ "version": 1,
+ "command": ["python3", "-c", "print('ok')"],
+ "shell_command": None,
+ }
-def test_managed_watch_shell_detaches_waiter_stdin(tmp_path: Path, monkeypatch) -> None:
+def test_managed_watch_shell_uses_stable_supervisor(tmp_path: Path, monkeypatch) -> None:
captured: dict[str, object] = {}
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -151,20 +297,110 @@ def test_managed_watch_shell_detaches_waiter_stdin(tmp_path: Path, monkeypatch)
deliver_key=None,
)
- async def fake_create_subprocess_shell(*args, **kwargs):
+ async def fake_create_subprocess_exec(*args, **kwargs):
captured["args"] = args
captured["kwargs"] = kwargs
- return _FakeProcess()
+ process = _FakeProcess()
+ captured["process"] = process
+ return process
- monkeypatch.setattr(asyncio, "create_subprocess_shell", fake_create_subprocess_shell)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
result = asyncio.run(service._run_cycle(watch, timeout_seconds=5))
assert result.exit_code == 0
- assert captured["kwargs"]["stdin"] == asyncio.subprocess.DEVNULL
+ assert captured["args"] == (
+ os.path.abspath(sys.executable),
+ str(Path(watch_worker.__file__).resolve()),
+ )
+ assert captured["kwargs"]["stdin"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stdout"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["stderr"] == asyncio.subprocess.PIPE
assert captured["kwargs"]["cwd"] == str(paths.get_vibe_remote_dir())
+ process = captured["process"]
+ assert isinstance(process, _FakeProcess)
+ assert process.stdin.closed is True
+ assert json.loads(process.stdin.payload) == {
+ "version": 1,
+ "command": [],
+ "shell_command": "python3 -c 'print(\"ok\")'",
+ }
+
+
+def test_managed_watch_clears_supervisor_state_when_startup_pipe_breaks(tmp_path: Path, monkeypatch) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ watch = store.add_watch(
+ name="Broken supervisor",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "print('ok')"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+ process = _FakeProcess(stdin=_BrokenStdin())
+
+ async def fake_create_subprocess_exec(*_args, **_kwargs):
+ return process
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
+
+ with pytest.raises(RuntimeError, match="Watch worker supervisor exited during startup"):
+ asyncio.run(service._run_cycle(watch, timeout_seconds=5))
+
+ assert process.stdin.closed is True
+ assert service._active_pids == {}
+ assert service._active_process_identities == {}
+
+
+def test_managed_watch_localizes_supervisor_startup_failure(tmp_path: Path, monkeypatch) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ service = ManagedWatchService(
+ controller=SimpleNamespace(config=SimpleNamespace(language="zh")),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ watch = store.add_watch(
+ name="Broken supervisor",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "print('ok')"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+ process = _FakeProcess(
+ stdin=_BrokenStdin(),
+ stderr=watch_worker.encode_watch_worker_error("invalidCommand").encode(),
+ )
+
+ async def fake_create_subprocess_exec(*_args, **_kwargs):
+ return process
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
+
+ with pytest.raises(RuntimeError, match="Watch 监控进程失败:Watch 工作进程命令无效。"):
+ asyncio.run(service._run_cycle(watch, timeout_seconds=5))
def test_managed_watch_legacy_none_cwd_survives_deleted_process_cwd(tmp_path: Path) -> None:
@@ -329,7 +565,7 @@ def test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path:
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
@@ -422,7 +658,7 @@ def test_managed_watch_service_forever_timeout_disables_and_enqueues_failure(tmp
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.2)
await service.stop()
@@ -466,7 +702,7 @@ def test_managed_watch_service_forever_timeout_retries_when_explicitly_allowed(t
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.2)
await service.stop()
@@ -506,7 +742,7 @@ def test_managed_watch_service_stop_terminates_running_waiter(tmp_path: Path) ->
)
async def _run() -> tuple[int, int | None]:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
pid = service._active_pids.get(watch.id)
if pid:
@@ -557,7 +793,7 @@ def test_managed_watch_service_lease_loss_terminates_running_waiter(tmp_path: Pa
monkeypatch.setattr("core.watches.runtime.current_process_owns_service_instance", lambda: owner_state["owns"])
async def _run() -> tuple[int, int | None]:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
pid = service._active_pids.get(watch.id)
if pid:
@@ -587,15 +823,23 @@ def test_managed_watch_service_lease_loss_terminates_running_waiter(tmp_path: Pa
os.kill(pid, 0)
-def test_managed_watch_service_records_wall_clock_started_at(tmp_path: Path) -> None:
+def test_managed_watch_service_records_non_secret_process_identity(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ secret = "runtime-expanded-secret"
+ monkeypatch.setenv("WATCH_RUNTIME_SECRET", secret)
store = ManagedWatchStore(tmp_path / "watches.json")
request_store = TaskExecutionStore(tmp_path / "task_requests")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
watch = store.add_watch(
name="Wait forever",
session_key="slack::channel::C123",
- command=["python3", "-c", "import time; time.sleep(30)"],
- shell_command=None,
+ command=[],
+ shell_command=(
+ "exec python3 -c 'import time; time.sleep(30)' "
+ '"$WATCH_RUNTIME_SECRET"'
+ ),
prefix=None,
cwd=None,
mode="forever",
@@ -613,19 +857,27 @@ def test_managed_watch_service_records_wall_clock_started_at(tmp_path: Path) ->
runtime_store=runtime_store,
)
- async def _run() -> str:
- service.start()
+ async def _run() -> dict[str, object]:
+ await _start_watch_service(service)
for _ in range(100):
- started_at = runtime_store.load().get("watches", {}).get(watch.id, {}).get("started_at")
- if started_at:
+ entry = runtime_store.load().get("watches", {}).get(watch.id, {})
+ if entry.get("process_identity"):
await service.stop()
- return started_at
+ return entry
await asyncio.sleep(0.02)
await service.stop()
- raise AssertionError("started_at was never written")
+ raise AssertionError("process identity was never written")
- started_at = asyncio.run(_run())
- assert datetime.fromisoformat(started_at).year >= 2024
+ entry = asyncio.run(_run())
+ identity = entry["process_identity"]
+ assert isinstance(entry["pid"], int)
+ assert datetime.fromisoformat(str(entry["started_at"])).year >= 2024
+ assert isinstance(identity, dict)
+ assert identity["pid"] == entry["pid"]
+ assert identity["create_time"] > 0
+ assert identity["worker_fingerprint"].startswith("sha256:")
+ assert "cmdline" not in identity
+ assert secret not in json.dumps(entry)
def test_managed_watch_service_turns_spawn_error_into_failed_cycle(tmp_path: Path) -> None:
@@ -655,7 +907,7 @@ def test_managed_watch_service_turns_spawn_error_into_failed_cycle(tmp_path: Pat
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
@@ -782,7 +1034,7 @@ def test_missing_watch_cwd_does_not_stop_other_watches(tmp_path: Path) -> None:
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
broken_saved = store.get_watch(broken.id)
healthy_saved = store.get_watch(healthy.id)
@@ -832,7 +1084,7 @@ def test_managed_watch_service_forever_retries_only_allowed_exit_code(tmp_path:
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.08)
await service.stop()
@@ -872,7 +1124,7 @@ def test_managed_watch_service_forever_non_retry_error_disables_and_enqueues_fai
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
@@ -930,7 +1182,7 @@ def test_managed_watch_service_fuses_watch_after_store_error(tmp_path: Path) ->
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
await asyncio.sleep(0.12)
assert watch.id in service._fused_watch_ids
await asyncio.sleep(0.08)
@@ -1019,6 +1271,7 @@ def test_managed_watch_service_idle_tick_does_not_write_runtime_state(tmp_path:
runtime_store=runtime_store,
)
service._running = True
+ service._recovery_pending = False
service._reconcile_dirty = False
service._runtime_state_dirty = False
@@ -1039,17 +1292,237 @@ def test_managed_watch_service_idle_tick_does_not_write_runtime_state(tmp_path:
assert runtime_store.writes == 0
-def test_managed_watch_service_start_clears_stale_runtime_state(tmp_path: Path) -> None:
+def test_managed_watch_service_start_reaps_stale_worker_for_deleted_watch(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ identity = _persisted_identity(pid=1234)
+ _record_watch_pid(runtime_store, "stale-watch", 1234, identity=identity)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ terminated: list[int] = []
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 1234)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda pid, *_args, **_kwargs: terminated.append(pid) or True,
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ try:
+ assert runtime_store.load()["watches"] == {}
+ finally:
+ await service.stop()
+
+ asyncio.run(_run())
+ assert terminated == [1234]
+
+
+ ("command", "shell_command"),
+ [
+ ([sys.executable, "-c", "print('watch')"], None),
+ (["/tmp/wait.py"], None),
+ ([], "python3 wait.py --forever"),
+ ],
+ ids=["exec", "shebang-interpreter", "shell-wrapper"],
+)
+def test_managed_watch_service_start_reaps_matching_stale_worker_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ command: list[str],
+ shell_command: str | None,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=command, shell_command=shell_command)
+ identity = _persisted_identity()
+ _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ events: list[tuple[str, int | None]] = []
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda pid: _live_identity(pid=pid),
+ )
+
+ def fake_terminate(pid, _logger, _label, *, expected_identity):
+ assert expected_identity == identity
+ events.append(("terminate", pid))
+ return True
+
+ def fake_reconcile():
+ events.append(("reconcile", None))
+ return False
+
+ monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", fake_terminate)
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert events == [("terminate", 4321), ("reconcile", None)]
+
+
+def test_managed_watch_service_start_does_not_reap_reused_pid(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ command = [sys.executable, "wait.py"]
+ watch = _add_recovery_watch(store, command=command)
+ identity = _persisted_identity()
+ _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda pid: _live_identity(pid=pid, create_time=456.0),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a reused pid must not be terminated"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert reconciles == 1
+ assert watch.id not in service._recovery_blocked_watch_ids
+
+
+def test_managed_watch_service_start_blocks_respawn_when_worker_marker_changed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ command = [sys.executable, "wait.py"]
+ watch = _add_recovery_watch(store, command=command)
+ identity = _persisted_identity()
+ _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda pid: _live_identity(
+ pid=pid,
+ worker_fingerprint=fingerprint_process_marker("other-watch-worker"),
+ ),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a changed worker marker must not be terminated"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id not in service._active_tasks
+ assert runtime_store.load()["watches"][watch.id]["process_identity"]["create_time"] == 123.0
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert runtime_store.load()["watches"][watch.id]["pid"] == 4321
+
+
+def test_managed_watch_service_start_blocks_legacy_live_worker_without_identity(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
+ _record_watch_pid(runtime_store, watch.id, 4321)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda _pid: _live_identity(),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a legacy entry must not cause termination"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id not in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert runtime_store.load()["watches"][watch.id]["pid"] == 4321
+
+
+def test_managed_watch_service_start_rejects_overflowing_process_identity(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
runtime_store.write(
{
"watches": {
- "stale-watch": {
+ watch.id: {
"running": True,
- "pid": 1234,
+ "pid": 4321,
"started_at": "2026-05-15T00:00:00+00:00",
"updated_at": "2026-05-15T00:00:01+00:00",
+ "process_identity": {
+ "pid": 4321,
+ "create_time": 10**1000,
+ "worker_fingerprint": TEST_FINGERPRINT,
+ },
}
}
}
@@ -1061,13 +1534,498 @@ def test_managed_watch_service_start_clears_stale_runtime_state(tmp_path: Path)
runtime_store=runtime_store,
)
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda pid: _live_identity(pid=pid),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a malformed identity must not cause termination"),
+ )
+
async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._running is True
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert watch.id not in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_ignores_dead_recorded_pid(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
+ _record_watch_pid(runtime_store, watch.id, 4321)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: False)
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: False)
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda _pid: pytest.fail("a dead pid must not have its identity inspected"),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a dead pid must not be terminated"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert reconciles == 1
+
+
+def test_managed_watch_service_start_reaps_group_after_leader_exit(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
+ identity = _persisted_identity()
+ _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ events: list[str] = []
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: False)
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_group_by_pgid",
+ lambda *_args, **_kwargs: events.append("terminate-group") or True,
+ )
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda _pid: pytest.fail("an exited leader must not have its identity inspected"),
+ )
+
+ def fake_reconcile() -> bool:
+ events.append("reconcile")
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert events == ["terminate-group", "reconcile"]
+
+
+def test_managed_watch_service_does_not_reap_unverified_group_after_leader_exit(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
+ _record_watch_pid(runtime_store, watch.id, 4321)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: False)
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: True)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_group_by_pgid",
+ lambda *_args, **_kwargs: pytest.fail("an unverified process group must not be terminated"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert watch.id not in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_keeps_recovery_off_event_loop(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=ManagedWatchStore(tmp_path / "watches.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ monkeypatch.setattr(service, "_reap_stale_workers", lambda: time.sleep(0.15))
+ monkeypatch.setattr(service, "reconcile_watches", lambda: False)
+
+ async def _run() -> None:
+ started = time.monotonic()
service.start()
- try:
- assert runtime_store.load()["watches"] == {}
- finally:
+ assert time.monotonic() - started < 0.05
+ startup_task = service._startup_task
+ assert startup_task is not None
+ await asyncio.sleep(0.01)
+ assert not startup_task.done()
+ await startup_task
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_retries_unreadable_runtime_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ class UnreadableRuntimeStore(WatchRuntimeStateStore):
+ def __init__(self) -> None:
+ self.writes = 0
+ self.readable = False
+
+ def load_for_recovery(self) -> dict:
+ if not self.readable:
+ raise OSError("runtime state is temporarily unavailable")
+ return {"watches": {}}
+
+ def write(self, payload: dict) -> None:
+ self.writes += 1
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = UnreadableRuntimeStore()
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("unreadable state must not cause termination"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._recovery_pending is True
+ assert reconciles == 0
+ assert runtime_store.writes == 0
+ runtime_store.readable = True
+ for _ in range(100):
+ if reconciles:
+ break
+ await asyncio.sleep(0.01)
+ await service.stop()
+
+ with caplog.at_level("WARNING"):
+ asyncio.run(_run())
+
+ assert reconciles >= 1
+ assert runtime_store.writes > 0
+ assert "Unable to read prior watch runtime state" in caplog.text
+
+
+def test_managed_watch_service_start_retries_malformed_runtime_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_path = tmp_path / "watch_runtime.json"
+ runtime_path.write_text("{not-json", encoding="utf-8")
+ runtime_store = WatchRuntimeStateStore(runtime_path)
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ reconciles = 0
+
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("malformed state must not cause termination"),
+ )
+
+ def fake_reconcile():
+ nonlocal reconciles
+ reconciles += 1
+ return False
+
+ monkeypatch.setattr(service, "reconcile_watches", fake_reconcile)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._recovery_pending is True
+ assert reconciles == 0
+ runtime_path.write_text('{"watches": {}}', encoding="utf-8")
+ for _ in range(100):
+ if reconciles:
+ break
+ await asyncio.sleep(0.01)
+ await service.stop()
+
+ with caplog.at_level("WARNING"):
+ asyncio.run(_run())
+
+ assert reconciles >= 1
+ assert "Unable to read prior watch runtime state" in caplog.text
+
+
+def test_managed_watch_service_start_retries_unavailable_watch_list_before_reconcile(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
+ _record_watch_pid(runtime_store, watch.id, 4321)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ list_calls = 0
+ available = {"value": False}
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+
+ def failing_list():
+ nonlocal list_calls
+ list_calls += 1
+ if not available["value"]:
+ raise RuntimeError("watch definitions are temporarily unavailable")
+ return store.list_watches()
+
+ monkeypatch.setattr(store, "list_watches_for_recovery", failing_list)
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("an unavailable watch list must not cause termination"),
+ )
+
+ async def fake_run_watch(_watch_id: str) -> None:
+ await asyncio.Future()
+
+ monkeypatch.setattr(service, "_run_watch", fake_run_watch)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._running is True
+ assert service._recovery_pending is True
+ assert watch.id not in service._active_tasks
+ available["value"] = True
+ for _ in range(100):
+ if watch.id in service._active_tasks:
+ break
+ await asyncio.sleep(0.01)
+ assert watch.id in service._active_tasks
+ await service.stop()
+
+ with caplog.at_level("WARNING"):
+ asyncio.run(_run())
+
+ assert list_calls >= 2
+ assert service._store_reconcile_failures == 0
+ assert "Unable to read managed watch definitions" in caplog.text
+
+
+def test_managed_watch_service_start_does_not_reap_with_malformed_watch_store(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ watches_path = tmp_path / "watches.json"
+ original_store = ManagedWatchStore(watches_path)
+ watch = _add_recovery_watch(original_store, command=[sys.executable, "wait.py"])
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ _record_watch_pid(runtime_store, watch.id, 4321)
+ watches_path.write_text("{not-json", encoding="utf-8")
+
+ with caplog.at_level("WARNING"):
+ store = ManagedWatchStore(watches_path)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ monkeypatch.setattr(
+ "core.watches.runtime.pid_alive",
+ lambda _pid: pytest.fail("a malformed watch store must not cause pid inspection"),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("a malformed watch store must not cause termination"),
+ )
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._active_tasks == {}
await service.stop()
+ asyncio.run(_run())
+
+ assert "Unable to read managed watch definitions" in caplog.text
+
+
+def test_managed_watch_service_start_preserves_worker_state_when_reap_fails(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ command = [sys.executable, "wait.py"]
+ watch = _add_recovery_watch(store, command=command)
+ identity = _persisted_identity()
+ _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda pid: pid == 4321)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", lambda *_args, **_kwargs: False)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert service._active_tasks == {}
+ assert runtime_store.load()["watches"][watch.id]["pid"] == 4321
+ await service.stop()
+
+ asyncio.run(_run())
+
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert runtime_store.load()["watches"][watch.id]["pid"] == 4321
+
+
+def test_managed_watch_service_periodically_unblocks_after_stale_worker_exits(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ command = [sys.executable, "wait.py"]
+ watch = _add_recovery_watch(store, command=command)
+ identity = _persisted_identity()
+ _record_watch_pid(runtime_store, watch.id, 4321, identity=identity)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+ worker = {"alive": True}
+
+ monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)
+ monkeypatch.setattr("core.watches.runtime.pid_alive", lambda _pid: worker["alive"])
+ monkeypatch.setattr("core.watches.process_group_exists", lambda *_args: False)
+ monkeypatch.setattr("core.watches.inspect_process_identity", lambda _pid: identity)
+ monkeypatch.setattr("core.watches.terminate_process_tree_by_pid", lambda *_args, **_kwargs: False)
+
+ async def fake_run_watch(_watch_id: str) -> None:
+ await asyncio.Future()
+
+ monkeypatch.setattr(service, "_run_watch", fake_run_watch)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id in service._recovery_blocked_watch_ids
+ assert watch.id not in service._active_tasks
+
+ worker["alive"] = False
+ for _ in range(100):
+ if watch.id in service._active_tasks:
+ break
+ await asyncio.sleep(0.01)
+
+ assert watch.id not in service._recovery_blocked_watch_ids
+ assert watch.id not in service._unreaped_runtime_entries
+ assert watch.id in service._active_tasks
+ await service.stop()
+
+ asyncio.run(_run())
+
+
+def test_managed_watch_service_start_without_prior_runtime_state_reconciles_normally(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = _add_recovery_watch(store, command=[sys.executable, "wait.py"])
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ runtime_store=runtime_store,
+ )
+
+ monkeypatch.setattr(
+ store,
+ "list_watches_for_recovery",
+ lambda: pytest.fail("empty runtime state must not reload watch definitions"),
+ )
+ monkeypatch.setattr(
+ "core.watches.runtime.pid_alive",
+ lambda _pid: pytest.fail("empty runtime state must not inspect any pids"),
+ )
+ monkeypatch.setattr(
+ "core.watches.inspect_process_identity",
+ lambda _pid: pytest.fail("empty runtime state must not inspect any processes"),
+ )
+ monkeypatch.setattr(
+ "core.watches.terminate_process_tree_by_pid",
+ lambda *_args, **_kwargs: pytest.fail("empty runtime state must not cause termination"),
+ )
+
+ async def fake_run_watch(_watch_id: str) -> None:
+ await asyncio.Future()
+
+ monkeypatch.setattr(service, "_run_watch", fake_run_watch)
+
+ async def _run() -> None:
+ await _start_watch_service(service)
+ assert watch.id in service._active_tasks
+ await service.stop()
+
asyncio.run(_run())
@@ -1131,9 +2089,9 @@ def test_managed_watch_service_start_retries_initial_reconcile_error(tmp_path: P
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
assert service._store_error_fused is False
- assert service._store_reconcile_failures == 1
+ assert 1 <= service._store_reconcile_failures < 3
await service.stop()
asyncio.run(_run())
@@ -1151,6 +2109,9 @@ def test_managed_watch_service_ignores_runtime_state_write_failure(tmp_path: Pat
def load(self) -> dict:
return {"watches": {}}
+ def load_for_recovery(self) -> dict:
+ return {"watches": {}}
+
store = ManagedWatchStore(tmp_path / "watches.json")
request_store = TaskExecutionStore(tmp_path / "task_requests")
runtime_store = FailingRuntimeStore()
@@ -1177,7 +2138,7 @@ def test_managed_watch_service_ignores_runtime_state_write_failure(tmp_path: Pat
)
async def _run() -> None:
- service.start()
+ await _start_watch_service(service)
for _ in range(100):
if watch.id not in service._active_tasks:
break
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 3c145c1c9..7ff903bcd 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -183,12 +183,13 @@ export const AddApiKeyDialog: React.FC<{
<DialogFooter>
<div className="flex items-center gap-2">
- <Button variant="outline" size="sm" onClick={onClose} disabled={phase === 'submitting'}>
+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={phase === 'submitting'}>
{t('common.cancel')}
</Button>
<Button
variant="brand"
size="sm"
+ className="h-10 sm:h-9"
onClick={() => void submit()}
disabled={phase === 'submitting' || phase === 'done' || !apiKey.trim()}
>
diff --git a/ui/src/components/settings/models/AddSourceMenu.tsx b/ui/src/components/settings/models/AddSourceMenu.tsx
index 1a1ac2278..4a619c062 100644
--- a/ui/src/components/settings/models/AddSourceMenu.tsx
+++ b/ui/src/components/settings/models/AddSourceMenu.tsx
@@ -1,39 +1,59 @@
-// 添加来源 dropdown (frame 07): three entries — connect Claude / ChatGPT
-// subscription (→ OAuth connect dialog) and add API Key (→ form dialog). No
-// type-chooser dialog; the menu IS the chooser.
+// 添加来源 (frame 07): connect a Claude / ChatGPT subscription (→ OAuth connect
+// dialog) or add an API Key (→ form dialog). No type-chooser dialog on desktop;
+// the menu IS the chooser.
+//
+// On phones it becomes a bottom sheet, and the flat three-entry list becomes the
+// design's two-step chooser (design.pen M04 m04Sheet 0): 订阅账号 / API Key first,
+// vendor second. Three vendor-specific rows read as three unrelated products on a
+// small screen, where the actual decision the user is making is "subscription or
+// key". Desktop keeps the flat list — frame 07 has the room for it, and the wide
+// menu loses nothing by skipping a step.
import * as React from 'react';
-import { ChevronRight, ExternalLink, KeyRound, Plus, Sparkles } from 'lucide-react';
+import { ChevronLeft, ChevronRight, ExternalLink, KeyRound, Plus, Sparkles } from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
-import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { ResponsiveMenu } from '@/components/ui/responsive-menu';
import { cn } from '@/lib/utils';
+import { useIsMobile } from '@/lib/useIsMobile';
import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';
-type MenuItemProps = {
+const MenuItem: React.FC<{
Icon: React.ComponentType<{ size?: number; className?: string }>;
accentTile: string;
accentIcon: string;
title: string;
subtitle: string;
+ badge?: string;
Trailing: React.ComponentType<{ className?: string }>;
onClick: () => void;
-};
-
-const MenuItem: React.FC<MenuItemProps> = ({ Icon, accentTile, accentIcon, title, subtitle, Trailing, onClick }) => (
+ /** Roomier type + wrapping subtitle for the touch sheet. */
+ large?: boolean;
+}> = ({ Icon, accentTile, accentIcon, title, subtitle, badge, Trailing, onClick, large }) => (
<button
type="button"
onClick={onClick}
- className="flex w-full items-center gap-3 border-b border-border px-4 py-3 text-left transition-colors last:border-b-0 hover:bg-surface-2"
+ className={cn(
+ 'flex w-full items-center gap-3 border-b border-border px-4 py-3 text-left transition-colors last:border-b-0 hover:bg-surface-2',
+ large && 'items-start gap-3.5 py-4',
+ )}
>
- <span className={cn('flex size-10 shrink-0 items-center justify-center rounded-[10px]', accentTile)}>
- <Icon size={20} className={accentIcon} />
+ <span className={cn('flex shrink-0 items-center justify-center rounded-[10px]', large ? 'size-11' : 'size-10', accentTile)}>
+ <Icon size={large ? 22 : 20} className={accentIcon} />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
- <span className="text-[14px] font-semibold text-foreground">{title}</span>
- <span className="truncate text-[12px] text-muted">{subtitle}</span>
+ <span className="flex items-center gap-2">
+ <span className={cn('font-semibold text-foreground', large ? 'text-[15px]' : 'text-[14px]')}>{title}</span>
+ {badge && (
+ <Badge variant="success" className="shrink-0 px-2 py-0.5 text-[10px]">
+ {badge}
+ </Badge>
+ )}
+ </span>
+ <span className={cn('text-[12px] text-muted', large ? 'leading-relaxed' : 'truncate')}>{subtitle}</span>
</span>
- <Trailing className="size-4 shrink-0 text-muted" />
+ <Trailing className={cn('size-4 shrink-0 text-muted', large && 'mt-1')} />
</button>
);
@@ -43,54 +63,131 @@ export const AddSourceMenu: React.FC<{
onAddApiKey: () => void;
}> = ({ onConnectClaude, onConnectChatGPT, onAddApiKey }) => {
const { t } = useTranslation();
+ const isMobile = useIsMobile();
const [open, setOpen] = React.useState(false);
+ // Mobile only: which step of the chooser is showing.
+ const [step, setStep] = React.useState<'type' | 'vendor'>('type');
+
+ // The chooser always opens on the first step. Resetting on the OPEN edge, not
+ // the close edge, is deliberate: closing happens through several paths (picking
+ // an entry, Escape, tapping the overlay, a future programmatic close) and any
+ // one of them that skips the reset leaves the next open on the vendor list.
+ // Opening only ever happens through the trigger, so this single place cannot be
+ // bypassed. (Codex P2, 2026-07-25: `pick` closed via a helper that set `open`
+ // directly and skipped the close-edge reset.)
+ const onOpenChange = (next: boolean) => {
+ setOpen(next);
+ if (next) setStep('type');
+ };
const pick = (fn: () => void) => () => {
setOpen(false);
fn();
};
+ const claude = {
+ Icon: Sparkles,
+ accentTile: ACCENT_TILE.mint,
+ accentIcon: ACCENT_ICON.mint,
+ title: t('settings.models.addMenu.claude.title') as string,
+ subtitle: t('settings.models.addMenu.claude.subtitle') as string,
+ Trailing: ExternalLink,
+ onClick: pick(onConnectClaude),
+ };
+ const chatgpt = {
+ Icon: Sparkles,
+ accentTile: ACCENT_TILE.gold,
+ accentIcon: ACCENT_ICON.gold,
+ title: t('settings.models.addMenu.chatgpt.title') as string,
+ subtitle: t('settings.models.addMenu.chatgpt.subtitle') as string,
+ Trailing: ExternalLink,
+ onClick: pick(onConnectChatGPT),
+ };
+ const apiKey = {
+ Icon: KeyRound,
+ accentTile: ACCENT_TILE.violet,
+ accentIcon: ACCENT_ICON.violet,
+ title: t('settings.models.addMenu.apiKey.title') as string,
+ subtitle: t('settings.models.addMenu.apiKey.subtitle') as string,
+ Trailing: ChevronRight,
+ onClick: pick(onAddApiKey),
+ };
+
+ const vendorStep = step === 'vendor';
+
return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <Button variant="outline" size="sm" className="border-mint/40 bg-mint-soft/50 text-mint hover:bg-mint-soft">
+ <ResponsiveMenu
+ open={open}
+ onOpenChange={onOpenChange}
+ align="end"
+ sideOffset={8}
+ // Never wider than the phone viewport (the fixed 360px overflowed a 360px
+ // device once collision padding was applied).
+ className="w-[min(360px,calc(100vw-1.5rem))] overflow-hidden p-0 sm:w-[360px]"
+ sheetTitle={
+ vendorStep
+ ? (t('settings.models.addMenu.vendorTitle') as string)
+ : (t('settings.models.addMenu.sheetTitle') as string)
+ }
+ sheetDescription={
+ vendorStep
+ ? (t('settings.models.addMenu.vendorSubtitle') as string)
+ : (t('settings.models.addMenu.sheetSubtitle') as string)
+ }
+ sheetHeader={
+ vendorStep ? (
+ <div className="px-4 pb-2">
+ <button
+ type="button"
+ onClick={() => setStep('type')}
+ className="inline-flex min-h-10 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80"
+ >
+ <ChevronLeft className="size-4" />
+ {t('common.back')}
+ </button>
+ </div>
+ ) : undefined
+ }
+ trigger={
+ <Button
+ variant="outline"
+ size="sm"
+ // Full-width primary-looking button on phones (design.pen M01 m01AddBtn:
+ // mint-soft fill, 1.5px mint stroke); the quieter inline button on sm+.
+ className="h-11 w-full rounded-[11px] border-[1.5px] border-mint/70 bg-mint-soft text-mint hover:bg-mint-soft/80 sm:h-9 sm:w-auto sm:rounded-md sm:border sm:border-mint/40 sm:bg-mint-soft/50 sm:hover:bg-mint-soft"
+ >
<Plus className="size-4" />
{t('settings.models.addSource')}
</Button>
- </PopoverTrigger>
- <PopoverContent
- align="end"
- sideOffset={8}
- className="w-[360px] overflow-hidden border-border bg-card p-0 text-foreground shadow-lg"
- >
- <MenuItem
- Icon={Sparkles}
- accentTile={ACCENT_TILE.mint}
- accentIcon={ACCENT_ICON.mint}
- title={t('settings.models.addMenu.claude.title')}
- subtitle={t('settings.models.addMenu.claude.subtitle')}
- Trailing={ExternalLink}
- onClick={pick(onConnectClaude)}
- />
- <MenuItem
- Icon={Sparkles}
- accentTile={ACCENT_TILE.gold}
- accentIcon={ACCENT_ICON.gold}
- title={t('settings.models.addMenu.chatgpt.title')}
- subtitle={t('settings.models.addMenu.chatgpt.subtitle')}
- Trailing={ExternalLink}
- onClick={pick(onConnectChatGPT)}
- />
- <MenuItem
- Icon={KeyRound}
- accentTile={ACCENT_TILE.violet}
- accentIcon={ACCENT_ICON.violet}
- title={t('settings.models.addMenu.apiKey.title')}
- subtitle={t('settings.models.addMenu.apiKey.subtitle')}
- Trailing={ChevronRight}
- onClick={pick(onAddApiKey)}
- />
- </PopoverContent>
- </Popover>
+ }
+ >
+ {!isMobile ? (
+ <>
+ <MenuItem {...claude} />
+ <MenuItem {...chatgpt} />
+ <MenuItem {...apiKey} />
+ </>
+ ) : vendorStep ? (
+ <>
+ <MenuItem {...claude} large />
+ <MenuItem {...chatgpt} large />
+ </>
+ ) : (
+ <>
+ <MenuItem
+ Icon={Sparkles}
+ accentTile={ACCENT_TILE.mint}
+ accentIcon={ACCENT_ICON.mint}
+ title={t('settings.models.addMenu.subscription.title') as string}
+ subtitle={t('settings.models.addMenu.subscription.subtitle') as string}
+ badge={t('settings.models.addMenu.subscription.recommended') as string}
+ Trailing={ChevronRight}
+ onClick={() => setStep('vendor')}
+ large
+ />
+ <MenuItem {...apiKey} subtitle={t('settings.models.addMenu.apiKeySheetSubtitle') as string} large />
+ </>
+ )}
+ </ResponsiveMenu>
);
};
diff --git a/ui/src/components/settings/models/AdvancedRow.tsx b/ui/src/components/settings/models/AdvancedRow.tsx
index 2af84beab..e3757f8e0 100644
--- a/ui/src/components/settings/models/AdvancedRow.tsx
+++ b/ui/src/components/settings/models/AdvancedRow.tsx
@@ -15,7 +15,7 @@ export const AdvancedRow: React.FC = () => {
<button
type="button"
onClick={() => showToast(t('settings.models.advanced.comingSoon') as string, 'warning')}
- className="flex w-full items-center gap-3 rounded-xl border border-border bg-background px-5 py-4 text-left transition-colors hover:border-border-strong"
+ className="flex w-full items-center gap-3 rounded-xl border border-border bg-background px-4 py-4 text-left sm:px-5 transition-colors hover:border-border-strong"
>
<SlidersHorizontal className="size-4 shrink-0 text-muted" />
<span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5">
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index bf8b59e7a..9ed1b8fa3 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -74,32 +74,73 @@ const AgentRow: React.FC<{
);
}
+ // Direct mode had no second line at all, which read as "nothing to see here" —
+ // the truth is that this backend is still supplied by its own CLI config and the
+ // Hub isn't involved. Phones only: the desktop row keeps 直连 Direct beside its
+ // 接入中枢 button on one line, where a sentence has nowhere to go.
+ const mobileNote =
+ agent.mode === 'hub' ? null : (
+ <span className="text-[11.5px] leading-relaxed text-muted">{t('settings.models.agents.directNote')}</span>
+ );
+
+ const action =
+ agent.mode === 'hub' ? (
+ <Button variant="secondary" size="sm" className="h-11 w-full sm:h-9 sm:w-auto" onClick={openMenu}>
+ {t('settings.models.agents.modelMenu')}
+ <ChevronRight className="size-3.5" />
+ </Button>
+ ) : (
+ <Button
+ variant="brand"
+ size="sm"
+ className="h-11 w-full sm:h-9 sm:w-auto"
+ onClick={() => onConnectHub(agent)}
+ disabled={connecting}
+ >
+ <ArrowDownToLine className="size-3.5" />
+ {t('settings.models.agents.connectHub')}
+ </Button>
+ );
+
return (
- <div className="flex items-center gap-4 border-b border-border px-5 py-4 last:border-b-0">
- <span className={cn('flex size-11 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
- <Icon size={22} className={ACCENT_ICON[accent]} />
- </span>
+ // Mobile is three full-width tiers (design.pen M01 m01Ag*): identity + mode
+ // badge, the supply line, then the action. Squeezed into one row at 390px the
+ // mode chip overlapped the composite pill and the pill's model id wrapped to
+ // three lines; nesting the pill under the name (the desktop shape) also left
+ // it inset by the icon tile instead of spanning the row.
+ //
+ // The supply pill has two mount points because the desktop frame nests it
+ // under the name while mobile needs it as a full-width sibling — CSS cannot
+ // re-parent. It's stateless presentation and the inactive copy is
+ // display:none (so out of the a11y tree), which is the cheap half of the
+ // trade; the win is that the sm+ DOM stays exactly the reviewed desktop row.
+ <div className="flex flex-col gap-2.5 border-b border-border px-4 py-4 last:border-b-0 sm:flex-row sm:items-center sm:gap-4 sm:px-5">
+ <div className="flex min-w-0 items-center gap-2.5 sm:flex-1 sm:gap-4">
+ <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[10px] sm:size-11', ACCENT_TILE[accent])}>
+ <Icon className={cn('size-[18px] sm:size-[22px]', ACCENT_ICON[accent])} />
+ </span>
+
+ <div className="flex min-w-0 flex-1 flex-col items-start gap-2">
+ {/* truncate only on phones; sm+ keeps the desktop row's wrap behaviour. */}
+ <span className="truncate text-[14px] font-bold text-foreground sm:whitespace-normal sm:text-[15px] sm:font-semibold">
+ {t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}
+ </span>
+ {pill && <span className="hidden sm:block">{pill}</span>}
+ </div>
- <div className="flex min-w-0 flex-1 flex-col items-start gap-2">
- <span className="text-[15px] font-semibold text-foreground">
- {t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}
+ {/* The mode badge belongs on the identity line on phones. */}
+ <span className="shrink-0 sm:hidden">
+ <ModeChip mode={agent.mode} />
</span>
- {pill}
</div>
- <div className="flex shrink-0 items-center gap-2.5">
- <ModeChip mode={agent.mode} />
- {agent.mode === 'hub' ? (
- <Button variant="secondary" size="sm" onClick={openMenu}>
- {t('settings.models.agents.modelMenu')}
- <ChevronRight className="size-3.5" />
- </Button>
- ) : (
- <Button variant="brand" size="sm" onClick={() => onConnectHub(agent)} disabled={connecting}>
- <ArrowDownToLine className="size-3.5" />
- {t('settings.models.agents.connectHub')}
- </Button>
- )}
+ <div className="sm:hidden">{pill ?? mobileNote}</div>
+
+ <div className="flex items-center gap-2.5 sm:shrink-0">
+ <span className="hidden sm:inline-flex">
+ <ModeChip mode={agent.mode} />
+ </span>
+ {action}
</div>
</div>
);
@@ -115,14 +156,14 @@ export const AgentCard: React.FC<{
const { t } = useTranslation();
return (
<section className="rounded-xl border border-border bg-background">
- <div className="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
+ <div className="flex items-start justify-between gap-4 border-b border-border px-4 py-4 sm:px-5">
<div className="flex min-w-0 flex-col gap-1">
<h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.agents.title')}</h2>
<p className="text-[12px] leading-relaxed text-muted">{t('settings.models.agents.subtitle')}</p>
</div>
<Link
to="/admin/settings/backends"
- className="inline-flex shrink-0 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80"
+ className="inline-flex min-h-10 shrink-0 items-center gap-1 text-[13px] font-medium text-mint transition-colors hover:text-mint/80 sm:min-h-0"
>
{t('settings.models.agents.backendSettings')}
<ArrowRight className="size-3.5" />
diff --git a/ui/src/components/settings/models/MigrationBanner.tsx b/ui/src/components/settings/models/MigrationBanner.tsx
index 3a845db43..c1ba80074 100644
--- a/ui/src/components/settings/models/MigrationBanner.tsx
+++ b/ui/src/components/settings/models/MigrationBanner.tsx
@@ -67,17 +67,35 @@ export const MigrationBanner: React.FC<{
return (
<>
- <div className="flex items-center gap-3 rounded-xl border border-gold/40 bg-gold/[0.08] px-4 py-3">
- <span className="flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-gold/15 text-gold">
- <ArrowDownToLine className="size-[18px]" />
- </span>
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <span className="text-[14px] font-semibold text-foreground">{t('settings.models.migrationBanner.title')}</span>
- <span className="text-[12px] leading-relaxed text-muted">
- {t('settings.models.migrationBanner.body', { count: importable.length })}
+ {/* Icon + two-line copy + import button + dismiss do not fit one 390px
+ row, so phones stack the action under the copy; dismiss stays on the
+ title line where it reads as "close this strip". */}
+ <div className="flex flex-col gap-2.5 rounded-xl border border-gold/40 bg-gold/[0.08] px-4 py-3 sm:flex-row sm:items-center sm:gap-3">
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <span className="flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-gold/15 text-gold">
+ <ArrowDownToLine className="size-[18px]" />
</span>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-[14px] font-semibold text-foreground">{t('settings.models.migrationBanner.title')}</span>
+ <span className="text-[12px] leading-relaxed text-muted">
+ {t('settings.models.migrationBanner.body', { count: importable.length })}
+ </span>
+ </div>
+ <button
+ type="button"
+ aria-label={t('settings.models.migrationBanner.dismiss') as string}
+ onClick={dismiss}
+ className="flex size-10 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-surface-2 hover:text-foreground sm:hidden"
+ >
+ <X className="size-4" />
+ </button>
</div>
- <Button variant="outline" size="sm" className="shrink-0 border-gold/40 text-gold hover:bg-gold/10 hover:text-gold" onClick={() => setDialogOpen(true)}>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-10 shrink-0 border-gold/40 text-gold hover:bg-gold/10 hover:text-gold sm:h-9"
+ onClick={() => setDialogOpen(true)}
+ >
<ArrowDownToLine className="size-3.5" />
{t('settings.models.migrationBanner.import')}
</Button>
@@ -85,7 +103,7 @@ export const MigrationBanner: React.FC<{
type="button"
aria-label={t('settings.models.migrationBanner.dismiss') as string}
onClick={dismiss}
- className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-surface-2 hover:text-foreground"
+ className="hidden size-7 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-surface-2 hover:text-foreground sm:flex"
>
<X className="size-4" />
</button>
diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsx
index 46926a2f7..eaea9f34b 100644
--- a/ui/src/components/settings/models/MigrationDialog.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.tsx
@@ -57,21 +57,30 @@ const ItemRow: React.FC<{ item: MigrationItem; onToggle: () => void }> = ({ item
// reauth needs the interactive browser flow, so it can't be bulk-applied here.
const selectable = item.proposed_action !== 'reauth';
return (
+ // The action badge is nowrap and shrink-0 (up to ~151px), so beside the
+ // detail column it pushed this row's min-content to 374px — wider than the
+ // sheet's 348px content box, which grew the dialog's grid track and spilled
+ // the header, footnote and footer button off-screen. On phones the badge
+ // moves to its own line under the detail.
<div
className={cn(
- 'flex items-center gap-3 rounded-xl border px-3.5 py-3',
+ 'flex flex-col gap-2 rounded-xl border px-3.5 py-3 sm:flex-row sm:items-center sm:gap-3',
item.selected ? 'border-mint/40 bg-mint-soft/40' : 'border-border',
)}
>
- <Checkbox checked={item.selected} onCheckedChange={onToggle} disabled={!selectable} label={item.masked_detail} />
- <span className={cn('flex size-9 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
- <Icon size={18} className={ACCENT_ICON[accent]} />
- </span>
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <span className="truncate text-[14px] font-semibold text-foreground">{item.masked_detail}</span>
- {item.notes_key && <span className="truncate text-[12px] text-muted">{t(item.notes_key)}</span>}
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <Checkbox checked={item.selected} onCheckedChange={onToggle} disabled={!selectable} label={item.masked_detail} />
+ <span className={cn('flex size-9 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
+ <Icon size={18} className={ACCENT_ICON[accent]} />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-[14px] font-semibold text-foreground">{item.masked_detail}</span>
+ {item.notes_key && <span className="truncate text-[12px] text-muted">{t(item.notes_key)}</span>}
+ </div>
+ </div>
+ <div className="shrink-0 pl-[46px] sm:pl-0">
+ <ActionBadge action={item.proposed_action} />
</div>
- <ActionBadge action={item.proposed_action} />
</div>
);
};
@@ -161,7 +170,7 @@ export const MigrationDialog: React.FC<{
</span>
{t('settings.models.migration.title')}
</DialogTitle>
- <DialogDescription className="pl-[52px]">{t('settings.models.migration.subtitle')}</DialogDescription>
+ <DialogDescription className="sm:pl-[52px]">{t('settings.models.migration.subtitle')}</DialogDescription>
</DialogHeader>
{loading ? (
@@ -189,10 +198,10 @@ export const MigrationDialog: React.FC<{
</p>
<div className="flex items-center justify-end gap-2 border-t border-border pt-4">
- <Button variant="outline" size="sm" onClick={onClose} disabled={applying}>
+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={applying}>
{t('settings.models.migration.later')}
</Button>
- <Button variant="brand" size="sm" onClick={() => void apply()} disabled={selectedCount === 0 || applying}>
+ <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void apply()} disabled={selectedCount === 0 || applying}>
<ArrowDownToLine className="size-4" />
{t('settings.models.migration.apply', { count: selectedCount })}
</Button>
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 1e374010d..ef6342e56 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -370,7 +370,7 @@ export const OAuthConnectDialog: React.FC<{
) : (
<span />
)}
- <Button variant={active ? 'ghost' : 'outline'} size="sm" onClick={onClose} disabled={finalizing}>
+ <Button variant={active ? 'ghost' : 'outline'} size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={finalizing}>
{active ? t('common.cancel') : t('common.close')}
</Button>
</div>
diff --git a/ui/src/components/settings/models/RecentSwitchesCard.tsx b/ui/src/components/settings/models/RecentSwitchesCard.tsx
index 523099ac7..6c9e7a4b4 100644
--- a/ui/src/components/settings/models/RecentSwitchesCard.tsx
+++ b/ui/src/components/settings/models/RecentSwitchesCard.tsx
@@ -46,27 +46,37 @@ export const RecentSwitchesCard: React.FC<{ events: ResolutionEvent[] }> = ({ ev
return (
<section className="rounded-xl border border-border bg-background">
- <div className="flex items-center justify-between gap-4 border-b border-border px-5 py-4">
+ <div className="flex items-center justify-between gap-4 border-b border-border px-4 py-4 sm:px-5">
<h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.recent.title')}</h2>
{canExpand && (
<button
type="button"
onClick={() => setExpanded((v) => !v)}
- className="text-[13px] font-medium text-mint transition-colors hover:text-mint/80"
+ className="inline-flex min-h-10 items-center text-[13px] font-medium text-mint transition-colors hover:text-mint/80 sm:min-h-0"
>
{expanded ? t('settings.models.recent.collapse') : t('settings.models.recent.viewAll')}
</button>
)}
</div>
{shown.length === 0 ? (
- <div className="px-5 py-8 text-center text-[13px] text-muted">{t('settings.models.recent.empty')}</div>
+ <div className="px-4 py-8 text-center sm:px-5 text-[13px] text-muted">{t('settings.models.recent.empty')}</div>
) : (
<div className="flex flex-col">
+ {/* Phones stack the timestamp above the sentence (design.pen M01 m01Ev):
+ the desktop 92px time column left the message ~200px at 360, so a
+ one-line event wrapped to three or four. */}
{shown.map((event) => (
- <div key={event.id} className="flex items-start gap-3 border-b border-border px-5 py-3 last:border-b-0">
- <span className="w-[92px] shrink-0 pt-0.5 font-mono text-[12px] text-muted">{formatTime(event.ts)}</span>
- <Dot accent={eventAccent(event)} className="mt-[7px]" />
- <span className="min-w-0 flex-1 text-[13px] leading-relaxed text-foreground">
+ <div
+ key={event.id}
+ className="flex flex-col gap-1 border-b border-border px-4 py-2.5 last:border-b-0 sm:flex-row sm:items-start sm:gap-3 sm:py-3 sm:px-5"
+ >
+ <span className="flex items-center gap-2 sm:contents">
+ <Dot accent={eventAccent(event)} className="sm:mt-[7px] sm:order-2" />
+ <span className="font-mono text-[11px] text-muted sm:order-1 sm:w-[92px] sm:shrink-0 sm:pt-0.5 sm:text-[12px]">
+ {formatTime(event.ts)}
+ </span>
+ </span>
+ <span className="min-w-0 flex-1 text-[12.5px] leading-relaxed text-foreground sm:order-3 sm:text-[13px]">
{zh ? event.human_zh : event.human_en}
</span>
</div>
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 8c2a2db33..99cf744d8 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -111,9 +111,8 @@ export const SettingsModelsPage: React.FC = () => {
});
};
- const reorderCommit = () => {
+ const commitOrder = (order: string[]) => {
const seq = ++reorderSeq.current;
- const order = sourcesRef.current.map((s) => s.id);
modelsApi
.putPriority(order)
.then((priority) => {
@@ -133,6 +132,19 @@ export const SettingsModelsPage: React.FC = () => {
});
};
+ // Drag end: the ordered state has already been re-rendered by the preview
+ // callbacks, so the mirror ref holds the freshest order.
+ const reorderCommit = () => commitOrder(sourcesRef.current.map((s) => s.id));
+
+ // Step reorder (the row menu's 上移/下移). Deliberately NOT preview-then-commit:
+ // the mirror ref is assigned during render, so a synchronous commit right after
+ // setSources would still read the pre-move order and persist it. Passing the
+ // order explicitly keeps both halves on the same value.
+ const reorderTo = (order: string[]) => {
+ reorderPreview(order);
+ commitOrder(order);
+ };
+
const connectHub = async (agent: AgentSupply) => {
setConnecting(agent.backend);
try {
@@ -184,6 +196,7 @@ export const SettingsModelsPage: React.FC = () => {
sources={sources}
onReorderPreview={reorderPreview}
onReorderCommit={reorderCommit}
+ onReorderTo={reorderTo}
onConnectClaude={() => setOauthVendor('anthropic')}
onConnectChatGPT={() => setOauthVendor('openai')}
onAddApiKey={() => setApiKeyOpen(true)}
diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsx
index 928448cfe..742c04f9b 100644
--- a/ui/src/components/settings/models/SourceRow.tsx
+++ b/ui/src/components/settings/models/SourceRow.tsx
@@ -1,6 +1,15 @@
// One row of the 来源 list (frame 01r): drag handle · priority number · icon +
// name/mono-sub (supply tooltip on hover) · fixed-width usage column · billing
// chip · state chip. Presentation-only; drag + reorder live in SourcesCard.
+//
+// Mobile (< sm): the frame's single aligned row cannot hold eight columns in
+// 390px — it squeezed the name to zero width and pushed the state chip and the
+// row menu off-screen entirely (clipped, not scrollable, so unreachable). So the
+// row stacks into two tiers per design.pen M01 (m01SrcL1 / m01SrcL2): identity +
+// the row menu on top, then billing · state · usage on a single second line,
+// inset 26px so it starts under the priority number. The sm+ layout is
+// byte-for-byte the desktop frame, so the fixed-width chip columns still align
+// down the list.
import * as React from 'react';
import { GripVertical } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -37,6 +46,12 @@ function useSubline(source: Source): string {
return parts.join(' · ');
}
+// On phones usage sits at the RIGHT END of the second tier and absorbs the slack
+// (design.pen M01 m01Use: fill_container + justify end), which also puts it after
+// the chips — hence `order-last`. On sm+ it reverts to the desktop frame's
+// leading fixed-width column.
+const USAGE_CELL = 'order-last flex-1 sm:order-none sm:w-[150px] sm:flex-none';
+
const UsageCell: React.FC<{ source: Source }> = ({ source }) => {
const { t } = useTranslation();
const pct = source.usage?.cycle_used_pct;
@@ -44,69 +59,111 @@ const UsageCell: React.FC<{ source: Source }> = ({ source }) => {
if (source.billing === 'monthly' && typeof pct === 'number') {
return (
- <div className="flex w-[150px] shrink-0 items-center justify-end gap-2">
- <div className="h-1.5 w-[92px] overflow-hidden rounded-full bg-border">
+ <div className={cn(USAGE_CELL, 'flex items-center justify-end gap-2')}>
+ <div className="h-1.5 w-14 overflow-hidden rounded-full bg-border sm:w-[92px]">
<div className="h-full rounded-full bg-mint" style={{ width: `${Math.min(100, Math.max(0, pct))}%` }} />
</div>
- <span className="w-9 text-right font-mono text-[12px] text-muted">{Math.round(pct)}%</span>
+ <span className="text-right font-mono text-[10.5px] text-muted sm:w-9 sm:text-[12px]">{Math.round(pct)}%</span>
</div>
);
}
if (typeof spend === 'number') {
return (
- <div className="w-[150px] shrink-0 text-right text-[12px] text-muted">
+ <div className={cn(USAGE_CELL, 'truncate text-right font-mono text-[10.5px] text-muted sm:font-sans sm:text-[12px]')}>
{t('settings.models.usage.monthSpend', { amount: formatSpend(spend, source.usage?.currency) })}
</div>
);
}
- return <div className="w-[150px] shrink-0" />;
+ // No usage data: on mobile the chips just stay left-aligned, so the spacer only
+ // exists to hold the desktop column open.
+ return <div className="hidden sm:block sm:w-[150px] sm:shrink-0" />;
};
export const SourceRow: React.FC<{
source: Source;
priority: number;
onDragHandlePointerDown: (e: React.PointerEvent) => void;
+ /** False at the ends of the list — the matching menu action is disabled. */
+ canMoveUp: boolean;
+ canMoveDown: boolean;
+ /** Keyboard/screen-reader path for reordering; drag stays the primary one. */
+ onMove: (delta: -1 | 1) => void;
/** Re-fetch after a row action (rename / re-discover / delete). */
onChanged: () => void;
-}> = ({ source, priority, onDragHandlePointerDown, onChanged }) => {
+}> = ({ source, priority, onDragHandlePointerDown, canMoveUp, canMoveDown, onMove, onChanged }) => {
const { t } = useTranslation();
const { Icon, accent } = sourceVisual(source);
const subline = useSubline(source);
const isExperimental = source.kind === 'subscription' && source.supply_channel === 'hub';
return (
- <div className="group flex items-center gap-3 border-b border-border px-5 py-3.5 last:border-b-0">
- <button
- type="button"
- aria-label={t('settings.models.source.reorder') as string}
- onPointerDown={onDragHandlePointerDown}
- className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted/50 transition-colors hover:text-muted active:cursor-grabbing"
- >
- <GripVertical className="size-4" />
- </button>
-
- <span className="grid size-7 shrink-0 place-items-center rounded-md border border-border bg-surface font-mono text-[13px] text-muted">
- {priority}
- </span>
+ // One wrapping flex line, not two stacked tiers: the row menu has to sit at
+ // the end of the FIRST line on phones and at the end of the (single) row on
+ // sm+, which no amount of CSS can do if it lives inside one of two sibling
+ // containers. So identity / menu / metrics are siblings here and `order`
+ // rearranges them per breakpoint — one menu instance, one set of dialogs.
+ <div className="group flex flex-wrap items-center gap-x-2.5 gap-y-2.5 border-b border-border px-4 py-3 last:border-b-0 sm:flex-nowrap sm:gap-x-3 sm:px-5 sm:py-3.5">
+ {/* Identity — the leading segment on both breakpoints. */}
+ <div className="order-1 flex min-w-0 flex-1 items-center gap-2.5 sm:gap-3">
+ <button
+ type="button"
+ aria-label={t('settings.models.source.reorder') as string}
+ onPointerDown={onDragHandlePointerDown}
+ // 40px touch target on phones (the 24px desktop handle is unhittable
+ // with a thumb); the glyph size is unchanged.
+ className="flex size-10 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted/50 transition-colors hover:text-muted active:cursor-grabbing sm:size-6"
+ >
+ <GripVertical className="size-4" />
+ </button>
- <SupplyTooltip models={source.models} className="flex min-w-0 flex-1 items-center gap-3">
- <span className={cn('flex size-11 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
- <Icon size={22} className={ACCENT_ICON[accent]} />
+ <span className="grid size-[22px] shrink-0 place-items-center rounded-[7px] border border-border bg-surface font-mono text-[11px] font-bold text-muted sm:size-7 sm:rounded-md sm:text-[13px] sm:font-normal">
+ {priority}
</span>
- <span className="flex min-w-0 flex-col gap-0.5">
- <span className="flex items-center gap-2">
- <span className="truncate text-[15px] font-semibold text-foreground">{source.display_name}</span>
- {isExperimental && <ExperimentalChip />}
+
+ <SupplyTooltip models={source.models} className="flex min-w-0 flex-1 items-center gap-2.5 sm:gap-3">
+ <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[10px] sm:size-11', ACCENT_TILE[accent])}>
+ <Icon className={cn('size-[18px] sm:size-[22px]', ACCENT_ICON[accent])} />
</span>
- <span className="truncate font-mono text-[12px] text-muted">{subline}</span>
- </span>
- </SupplyTooltip>
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate text-[13.5px] font-semibold text-foreground sm:text-[15px]">{source.display_name}</span>
+ {isExperimental && <ExperimentalChip />}
+ </span>
+ <span className="truncate font-mono text-[10.5px] text-muted sm:text-[12px]">{subline}</span>
+ </span>
+ </SupplyTooltip>
+ </div>
- <div className="flex shrink-0 items-center gap-4">
+ {/* Metric / state strip — a full-width second line on phones, inset 26px
+ (handle glyph + gap) so it starts under the priority number; the aligned
+ desktop chip columns on sm+.
+ flex-wrap here is the safety net, not the plan: measured at 360/390/430
+ in both locales every row stays on one line, including the widest English
+ combination ("$3.2 this month" · "Metered $" · "Cooling down"). It stays
+ wrap-capable so an unusually long future state label degrades to two
+ lines instead of clipping. sm:flex-nowrap keeps the desktop row
+ single-line. */}
+ <div className="order-3 flex w-full flex-wrap items-center gap-x-2 gap-y-2 pl-[26px] sm:order-2 sm:w-auto sm:shrink-0 sm:flex-nowrap sm:gap-4 sm:pl-0">
<UsageCell source={source} />
- <BillingChip billing={source.billing} />
+ <BillingChip billing={source.billing} currency={source.usage?.currency} />
<StateChip state={source.state} />
- <SourceRowMenu source={source} onChanged={onChanged} />
+ </div>
+
+ {/* Thumb-reachable on the identity line on phones (design.pen M01 m01More,
+ 36×36 on the handle/priority axis); trailing the desktop row on sm+.
+ sm:ml-1 restores the desktop frame's 16px gap before the menu — it used
+ to come from the metrics strip's own gap-4, and the row's gap-3 alone
+ pulled every chip column 4px right of the reviewed desktop layout
+ (caught by diffing the rendered geometry against master). */}
+ <div className="order-2 shrink-0 sm:order-3 sm:ml-1">
+ <SourceRowMenu
+ source={source}
+ priority={priority}
+ canMoveUp={canMoveUp}
+ canMoveDown={canMoveDown}
+ onMove={onMove}
+ onChanged={onChanged}
+ />
</div>
</div>
);
diff --git a/ui/src/components/settings/models/SourceRowMenu.tsx b/ui/src/components/settings/models/SourceRowMenu.tsx
index 4e8c1c3a9..e896cc374 100644
--- a/ui/src/components/settings/models/SourceRowMenu.tsx
+++ b/ui/src/components/settings/models/SourceRowMenu.tsx
@@ -1,49 +1,79 @@
// Per-row lifecycle actions for the 来源 list (frame 01r): an overflow menu that
// stays out of the way (hidden until row hover / focus on desktop) and exposes
// the contracted source mutations the list otherwise couldn't reach — rename
-// (PATCH), re-discover (POST /test, hub sources only), and delete (DELETE, with
-// the only-supplier guard escalating to a forced delete). Presentation lives in
-// SourceRow; this owns the actions + their dialogs so the row stays declarative.
+// (PATCH), re-discover (POST /test, hub sources only), reorder by one step, and
+// delete (DELETE, with the only-supplier guard escalating to a forced delete).
+// Presentation lives in SourceRow; this owns the actions + their dialogs so the
+// row stays declarative.
+//
+// On phones the menu presents as a bottom sheet (design.pen M02 m02SheetA) with
+// the row's identity in the header and a one-line rationale under each action,
+// because a thumb menu has no hover to explain itself. 上移一位 / 下移一位 live
+// here rather than as a visible button column: drag is the primary reordering
+// gesture, and these exist so the same thing is reachable by keyboard and screen
+// reader.
import * as React from 'react';
-import { MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';
+import { ArrowDown, ArrowUp, MoreHorizontal, Pencil, RefreshCw, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
-import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { ResponsiveMenu } from '@/components/ui/responsive-menu';
import { cn } from '@/lib/utils';
+import { useIsMobile } from '@/lib/useIsMobile';
import { useToast } from '@/context/ToastContext';
import { modelsApi } from './modelsApi';
+import { ACCENT_ICON, ACCENT_TILE, sourceVisual } from './vendorMeta';
import type { Source } from './types';
const MenuAction: React.FC<{
Icon: React.ComponentType<{ className?: string }>;
label: string;
+ /** Shown in the mobile sheet only — the popover stays a compact list. */
+ description?: string;
onClick: () => void;
+ disabled?: boolean;
destructive?: boolean;
-}> = ({ Icon, label, onClick, destructive }) => (
+}> = ({ Icon, label, description, onClick, disabled, destructive }) => (
<button
type="button"
onClick={onClick}
+ disabled={disabled}
className={cn(
- 'flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] transition-colors',
- destructive ? 'text-destructive hover:bg-destructive/[0.08]' : 'text-foreground hover:bg-surface-2',
+ // min-h-11 keeps each action a comfortable thumb target on phones.
+ 'flex min-h-11 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] transition-colors sm:min-h-0',
+ description && 'items-start gap-3 rounded-none border-b border-border px-4 py-3.5 last:border-b-0',
+ destructive ? 'text-destructive' : 'text-foreground',
+ disabled ? 'opacity-40' : destructive ? 'hover:bg-destructive/[0.08]' : 'hover:bg-surface-2',
)}
>
- <Icon className="size-4 shrink-0" />
- {label}
+ <Icon className={cn('size-4 shrink-0', description && 'mt-0.5 size-[18px]')} />
+ {description ? (
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="text-[14px] font-semibold">{label}</span>
+ <span className="text-[12px] leading-relaxed text-muted">{description}</span>
+ </span>
+ ) : (
+ label
+ )}
</button>
);
export const SourceRowMenu: React.FC<{
source: Source;
+ priority: number;
+ canMoveUp: boolean;
+ canMoveDown: boolean;
+ onMove: (delta: -1 | 1) => void;
/** Re-fetch sources + agents after any successful mutation. */
onChanged: () => void;
-}> = ({ source, onChanged }) => {
+}> = ({ source, priority, canMoveUp, canMoveDown, onMove, onChanged }) => {
const { t } = useTranslation();
const { showToast } = useToast();
+ const isMobile = useIsMobile();
+ const { Icon: SourceIcon, accent } = sourceVisual(source);
const [menuOpen, setMenuOpen] = React.useState(false);
const [renameOpen, setRenameOpen] = React.useState(false);
@@ -106,6 +136,11 @@ export const SourceRowMenu: React.FC<{
}
};
+ const move = (delta: -1 | 1) => {
+ setMenuOpen(false);
+ onMove(delta);
+ };
+
const openDelete = () => {
setMenuOpen(false);
setForceMode(false);
@@ -133,31 +168,95 @@ export const SourceRowMenu: React.FC<{
}
};
+ // Descriptions only exist in the sheet; passing undefined on desktop is what
+ // keeps the popover a compact label list.
+ const hint = (key: string, opts?: Record<string, unknown>) =>
+ isMobile ? (t(`settings.models.sourceActions.${key}`, opts) as string) : undefined;
+
return (
<>
- <Popover open={menuOpen} onOpenChange={setMenuOpen}>
- <PopoverTrigger asChild>
+ <ResponsiveMenu
+ open={menuOpen}
+ onOpenChange={setMenuOpen}
+ sheetTitle={source.display_name}
+ sheetTitleVisible={false}
+ className="w-[200px]"
+ sheetHeader={
+ <div className="flex items-center gap-3 px-4 pb-3.5 pt-1">
+ <span className={cn('flex size-10 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
+ <SourceIcon className={cn('size-5', ACCENT_ICON[accent])} />
+ </span>
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="truncate text-[15px] font-bold text-foreground">{source.display_name}</span>
+ <span className="truncate text-[12px] text-muted">
+ {[
+ t('settings.models.sourceActions.priorityLabel', { position: priority }),
+ t(`settings.models.state.${source.state.status}`),
+ t(`settings.models.billing.${source.billing}`),
+ ].join(' · ')}
+ </span>
+ </span>
+ </div>
+ }
+ trigger={
<button
type="button"
aria-label={t('settings.models.sourceActions.more') as string}
className={cn(
- 'flex size-8 shrink-0 items-center justify-center rounded-md text-muted transition-all hover:bg-surface-2 hover:text-foreground',
+ // The button is a 44×44 touch target while the drawn box inside it
+ // is the design's 36×36 (design.pen M01 m01More). Negative margins
+ // cancel the extra 8px so the visual box lands exactly where a bare
+ // 36px button would and the row height is unchanged — design size
+ // and the touch-target floor both hold, with no reliance on
+ // pseudo-element hit testing.
+ 'group/more -my-1 -mr-1 flex size-11 shrink-0 items-center justify-center text-muted sm:m-0 sm:size-8',
// Quiet on desktop (revealed on row hover / focus / when open),
// always reachable on touch where hover doesn't exist.
menuOpen ? 'opacity-100' : 'opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100',
)}
>
- {testing ? <RefreshCw className="size-4 animate-spin" /> : <MoreHorizontal className="size-4" />}
+ <span className="flex size-9 items-center justify-center rounded-[10px] border border-border bg-surface/60 transition-colors group-hover/more:bg-surface-2 group-hover/more:text-foreground sm:size-8 sm:border-transparent sm:bg-transparent">
+ {testing ? <RefreshCw className="size-4 animate-spin" /> : <MoreHorizontal className="size-4" />}
+ </span>
</button>
- </PopoverTrigger>
- <PopoverContent align="end" sideOffset={6} className="w-[200px] border-border bg-card p-1.5 text-foreground shadow-lg">
- <MenuAction Icon={Pencil} label={t('settings.models.sourceActions.rename') as string} onClick={openRename} />
- {canRediscover && (
- <MenuAction Icon={RefreshCw} label={t('settings.models.sourceActions.rediscover') as string} onClick={() => void rediscover()} />
- )}
- <MenuAction Icon={Trash2} label={t('settings.models.sourceActions.delete') as string} onClick={openDelete} destructive />
- </PopoverContent>
- </Popover>
+ }
+ >
+ <MenuAction
+ Icon={Pencil}
+ label={t('settings.models.sourceActions.rename') as string}
+ description={hint('renameHint')}
+ onClick={openRename}
+ />
+ {canRediscover && (
+ <MenuAction
+ Icon={RefreshCw}
+ label={t('settings.models.sourceActions.rediscover') as string}
+ description={hint('rediscoverHint')}
+ onClick={() => void rediscover()}
+ />
+ )}
+ <MenuAction
+ Icon={ArrowUp}
+ label={t('settings.models.sourceActions.moveUp') as string}
+ description={hint(canMoveUp ? 'moveUpHint' : 'moveUpHintAtTop', { position: priority })}
+ onClick={() => move(-1)}
+ disabled={!canMoveUp}
+ />
+ <MenuAction
+ Icon={ArrowDown}
+ label={t('settings.models.sourceActions.moveDown') as string}
+ description={hint(canMoveDown ? 'moveDownHint' : 'moveDownHintAtBottom')}
+ onClick={() => move(1)}
+ disabled={!canMoveDown}
+ />
+ <MenuAction
+ Icon={Trash2}
+ label={t('settings.models.sourceActions.delete') as string}
+ description={hint('deleteHint')}
+ onClick={openDelete}
+ destructive
+ />
+ </ResponsiveMenu>
<Dialog open={renameOpen} onOpenChange={(v) => !v && !renaming && setRenameOpen(false)}>
<DialogContent className="max-w-[420px] gap-4">
@@ -182,12 +281,13 @@ export const SourceRowMenu: React.FC<{
/>
</div>
<DialogFooter className="sm:justify-end">
- <Button variant="outline" size="sm" onClick={() => setRenameOpen(false)} disabled={renaming}>
+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={() => setRenameOpen(false)} disabled={renaming}>
{t('common.cancel')}
</Button>
<Button
variant="brand"
size="sm"
+ className="h-10 sm:h-9"
onClick={() => void submitRename()}
disabled={renaming || !renameValue.trim() || renameValue.trim() === source.display_name}
>
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
index 6059fba60..d907fc233 100644
--- a/ui/src/components/settings/models/SourcesCard.tsx
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -2,20 +2,29 @@
// drag-to-reorder priority list. Fully controlled — the ordered `sources` and
// the reorder handlers live in the page, so this card holds no derived state.
// Drag is restricted to each row's handle via framer-motion drag controls.
+//
+// Mobile header (design.pen M01 m01SrcHead): the title block and 添加来源 stack
+// instead of competing for one line, with 添加来源 as a full-width primary
+// button — at 360px the side-by-side desktop header squeezed the sub-line to two
+// or three lines and left the button a cramped tap target.
import * as React from 'react';
import { Reorder, useDragControls } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import { AddSourceMenu } from './AddSourceMenu';
import { SourceRow } from './SourceRow';
+import { movedOrder } from './reorder';
import type { Source } from './types';
-const SourceReorderItem: React.FC<{ source: Source; priority: number; onCommit: () => void; onChanged: () => void }> = ({
- source,
- priority,
- onCommit,
- onChanged,
-}) => {
+const SourceReorderItem: React.FC<{
+ source: Source;
+ priority: number;
+ canMoveUp: boolean;
+ canMoveDown: boolean;
+ onMove: (delta: -1 | 1) => void;
+ onCommit: () => void;
+ onChanged: () => void;
+}> = ({ source, priority, canMoveUp, canMoveDown, onMove, onCommit, onChanged }) => {
const controls = useDragControls();
return (
<Reorder.Item
@@ -29,6 +38,9 @@ const SourceReorderItem: React.FC<{ source: Source; priority: number; onCommit:
source={source}
priority={priority}
onDragHandlePointerDown={(e) => controls.start(e)}
+ canMoveUp={canMoveUp}
+ canMoveDown={canMoveDown}
+ onMove={onMove}
onChanged={onChanged}
/>
</Reorder.Item>
@@ -41,19 +53,35 @@ export const SourcesCard: React.FC<{
onReorderPreview: (orderedIds: string[]) => void;
/** Fires on drag end — persist the current order. */
onReorderCommit: () => void;
+ /** Preview + persist an explicit order (the row menu's one-step reorder). */
+ onReorderTo: (orderedIds: string[]) => void;
onConnectClaude: () => void;
onConnectChatGPT: () => void;
onAddApiKey: () => void;
/** Re-fetch after a per-row action (rename / re-discover / delete). */
onSourceChanged: () => void;
-}> = ({ sources, onReorderPreview, onReorderCommit, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged }) => {
+}> = ({
+ sources,
+ onReorderPreview,
+ onReorderCommit,
+ onReorderTo,
+ onConnectClaude,
+ onConnectChatGPT,
+ onAddApiKey,
+ onSourceChanged,
+}) => {
const { t } = useTranslation();
const ids = sources.map((s) => s.id);
+ const moveByOneStep = (index: number, delta: -1 | 1) => {
+ const next = movedOrder(ids, index, delta);
+ onReorderTo(next);
+ };
+
return (
// Not overflow-hidden: the row supply tooltip must escape the card bounds.
<section className="rounded-xl border border-border bg-background">
- <div className="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
+ <div className="flex flex-col gap-2.5 border-b border-border px-4 py-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4 sm:px-5">
<div className="flex min-w-0 flex-col gap-1">
<h2 className="text-[15px] font-semibold text-foreground">{t('settings.models.sources.title')}</h2>
<p className="text-[12px] leading-relaxed text-muted">{t('settings.models.sources.subtitle')}</p>
@@ -66,11 +94,20 @@ export const SourcesCard: React.FC<{
</div>
{ids.length === 0 ? (
- <div className="px-5 py-12 text-center text-[13px] text-muted">{t('settings.models.sources.empty')}</div>
+ <div className="px-4 py-12 text-center sm:px-5 text-[13px] text-muted">{t('settings.models.sources.empty')}</div>
) : (
<Reorder.Group axis="y" values={ids} onReorder={onReorderPreview} className="flex flex-col">
{sources.map((source, index) => (
- <SourceReorderItem key={source.id} source={source} priority={index + 1} onCommit={onReorderCommit} onChanged={onSourceChanged} />
+ <SourceReorderItem
+ key={source.id}
+ source={source}
+ priority={index + 1}
+ canMoveUp={index > 0}
+ canMoveDown={index < sources.length - 1}
+ onMove={(delta) => moveByOneStep(index, delta)}
+ onCommit={onReorderCommit}
+ onChanged={onSourceChanged}
+ />
))}
</Reorder.Group>
)}
diff --git a/ui/src/components/settings/models/chips.tsx b/ui/src/components/settings/models/chips.tsx
index a5c2939d4..5ea6f7e13 100644
--- a/ui/src/components/settings/models/chips.tsx
+++ b/ui/src/components/settings/models/chips.tsx
@@ -9,6 +9,7 @@ import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { useTranslation } from 'react-i18next';
+import { currencySymbol } from './format';
import { ACCENT_DOT, type Accent } from './vendorMeta';
import type { AgentMode, SourceState } from './types';
@@ -17,16 +18,43 @@ export const Dot: React.FC<{ accent: Accent; className?: string }> = ({ accent,
<span className={cn('inline-block size-1.5 shrink-0 rounded-full', ACCENT_DOT[accent], className)} aria-hidden />
);
-/** 包月 / 按量 ¥ — fixed-width so the column aligns down the source list. */
-export const BillingChip: React.FC<{ billing: 'monthly' | 'metered' }> = ({ billing }) => {
+/**
+ * Source-row chip metrics. On phones the row's second tier has to fit billing +
+ * state + usage on ONE line (design.pen M01 m01SrcL2), so the chips shrink to
+ * content-width pills — the desktop frame's fixed-width columns are what made
+ * that line overflow. From sm+ the fixed widths come back so the chip columns
+ * still align down the list, which is the whole point of them on a wide screen.
+ */
+const CHIP_MOBILE = 'rounded-full py-1';
+const BILLING_CHIP = cn(CHIP_MOBILE, 'font-medium sm:w-16 sm:justify-center');
+
+/**
+ * 包月 / 按量 $ — content-width on phones, fixed-width column on sm+.
+ *
+ * The metered symbol tracks the source's REPORTED currency (USD when absent).
+ * A static `$` contradicted the usage cell for a source that genuinely reports
+ * CNY/EUR — it would read `按量 $` beside `¥12.4`. The symbol still comes from
+ * format.ts's single map, never hand-written here; an unmappable code drops the
+ * symbol rather than printing a wrong one (the amount cell carries the truth).
+ */
+export const BillingChip: React.FC<{ billing: 'monthly' | 'metered'; currency?: string | null }> = ({
+ billing,
+ currency,
+}) => {
const { t } = useTranslation();
- return billing === 'monthly' ? (
- <Badge variant="secondary" className="w-16 justify-center rounded-md py-1 font-medium">
- {t('settings.models.billing.monthly')}
- </Badge>
- ) : (
- <Badge variant="warning" className="w-16 justify-center rounded-md py-1 font-medium">
- {t('settings.models.billing.metered')}
+ if (billing === 'monthly') {
+ return (
+ <Badge variant="secondary" className={cn(BILLING_CHIP, 'sm:rounded-md')}>
+ {t('settings.models.billing.monthly')}
+ </Badge>
+ );
+ }
+ const symbol = currencySymbol(currency);
+ return (
+ <Badge variant="warning" className={cn(BILLING_CHIP, 'sm:rounded-md')}>
+ {symbol
+ ? t('settings.models.billing.meteredWithSymbol', { symbol })
+ : t('settings.models.billing.metered')}
</Badge>
);
};
@@ -34,7 +62,7 @@ export const BillingChip: React.FC<{ billing: 'monthly' | 'metered' }> = ({ bill
/** 使用中 / 备用 / 暂不可用 / 不可用 — fixed-width aligned column. */
export const StateChip: React.FC<{ state: SourceState }> = ({ state }) => {
const { t } = useTranslation();
- const base = 'w-[86px] justify-center rounded-full py-1';
+ const base = cn(CHIP_MOBILE, 'sm:w-[86px] sm:justify-center');
switch (state.status) {
case 'active':
return (
@@ -98,12 +126,14 @@ export const ExperimentalChip: React.FC = () => {
* `N 个模型 | ● 多来源…`.
*/
export const CompositePill: React.FC<{ left: string; dot: Accent; right: string }> = ({ left, dot, right }) => (
- <div className="inline-flex items-center gap-2.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[13px]">
- <span className="font-mono font-medium text-foreground">{left}</span>
- <span className="h-3.5 w-px bg-border-strong" aria-hidden />
- <span className="inline-flex items-center gap-1.5 text-muted">
+ // max-w-full + truncating halves: on a phone the model id would otherwise wrap
+ // to three lines and blow the Agent row's height open.
+ <div className="inline-flex max-w-full items-center gap-2.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[13px]">
+ <span className="truncate font-mono font-medium text-foreground">{left}</span>
+ <span className="h-3.5 w-px shrink-0 bg-border-strong" aria-hidden />
+ <span className="inline-flex min-w-0 items-center gap-1.5 text-muted">
<Dot accent={dot} />
- {right}
+ <span className="truncate">{right}</span>
</span>
</div>
);
diff --git a/ui/src/components/settings/models/format.test.ts b/ui/src/components/settings/models/format.test.ts
new file mode 100644
index 000000000..1c54884d0
--- /dev/null
+++ b/ui/src/components/settings/models/format.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+
+import { cooldownEtaMinutes, currencySymbol, formatSpend } from './format';
+
+describe('currencySymbol', () => {
+ it('falls back to USD when the backend reports no currency', () => {
+ expect(currencySymbol(null)).toBe('$');
+ expect(currencySymbol(undefined)).toBe('$');
+ expect(currencySymbol()).toBe('$');
+ });
+
+ it('honors an explicitly reported currency', () => {
+ expect(currencySymbol('USD')).toBe('$');
+ expect(currencySymbol('CNY')).toBe('¥');
+ expect(currencySymbol('EUR')).toBe('€');
+ });
+
+ it('returns no symbol for a code it cannot map', () => {
+ // Callers use '' to pick a currency-free label instead of printing a wrong
+ // symbol — the amount cell carries the authoritative value.
+ expect(currencySymbol('JPY')).toBe('');
+ });
+
+ // The billing chip renders currencySymbol(...) while the usage cell renders
+ // formatSpend(...). They must never disagree: a static '$' on the chip read
+ // "按量 $" beside "¥12.4" for a CNY source (Codex P2, 2026-07-25).
+ it('agrees with the symbol formatSpend uses, for every currency', () => {
+ for (const c of [null, undefined, 'USD', 'CNY', 'EUR', 'JPY'] as const) {
+ expect(formatSpend(1240, c).startsWith(currencySymbol(c))).toBe(true);
+ const stripped = formatSpend(1240, c).slice(currencySymbol(c).length);
+ expect(stripped).toBe('12.4');
+ }
+ });
+});
+
+describe('formatSpend', () => {
+ // Owner ruling 2026-07-25: upstream vendors bill in USD, so a missing currency
+ // must render as USD and the UI must never fall back to a local currency.
+ // This is the tripwire for that decision — if someone restores a CNY (or any
+ // other) fallback, this fails instead of shipping silently.
+ it('falls back to USD when the backend reports no currency', () => {
+ expect(formatSpend(1240, null)).toBe('$12.4');
+ expect(formatSpend(1240, undefined)).toBe('$12.4');
+ expect(formatSpend(1240)).toBe('$12.4');
+ });
+
+ it('honors an explicitly reported currency', () => {
+ // The ISO 4217 map is deliberately retained: a source that genuinely bills in
+ // CNY/EUR still renders in its own currency.
+ expect(formatSpend(1240, 'USD')).toBe('$12.4');
+ expect(formatSpend(1240, 'CNY')).toBe('¥12.4');
+ expect(formatSpend(1240, 'EUR')).toBe('€12.4');
+ });
+
+ it('omits the symbol for a currency it cannot map, keeping the amount readable', () => {
+ expect(formatSpend(1240, 'JPY')).toBe('12.4');
+ });
+
+ it('converts cents to one decimal without applying any FX rate', () => {
+ // 1240 cents stays 12.40 whatever the symbol — amounts are never converted.
+ expect(formatSpend(0, null)).toBe('$0.0');
+ expect(formatSpend(5, null)).toBe('$0.1');
+ expect(formatSpend(1234567, null)).toBe('$12345.7');
+ });
+});
+
+describe('cooldownEtaMinutes', () => {
+ it('is 0 for a missing or already-elapsed retry_at', () => {
+ expect(cooldownEtaMinutes(null)).toBe(0);
+ expect(cooldownEtaMinutes(undefined)).toBe(0);
+ expect(cooldownEtaMinutes(new Date(Date.now() - 60_000).toISOString())).toBe(0);
+ });
+
+ it('rounds the remaining wait to whole minutes', () => {
+ expect(cooldownEtaMinutes(new Date(Date.now() + 5 * 60_000 + 1_000).toISOString())).toBe(5);
+ });
+});
diff --git a/ui/src/components/settings/models/format.ts b/ui/src/components/settings/models/format.ts
index 35e58e6e8..4ccba4bf7 100644
--- a/ui/src/components/settings/models/format.ts
+++ b/ui/src/components/settings/models/format.ts
@@ -2,12 +2,24 @@
// returned values in translated templates).
import type { AgentSupply, Source } from './types';
-const CURRENCY_SYMBOL: Record<string, string> = { CNY: '¥', USD: '$', EUR: '€' };
+const CURRENCY_SYMBOL: Record<string, string> = { USD: '$', CNY: '¥', EUR: '€' };
-/** Monthly spend as symbol + amount (1 decimal), e.g. "¥12.4". */
+/**
+ * Symbol for an ISO 4217 code — the ONLY place a currency symbol is resolved.
+ *
+ * USD is the fallback because every upstream vendor bills in USD; a CNY default
+ * was our own invention. The mapping is kept, so a source that really does report
+ * CNY (or EUR) still renders in its own currency. Returns '' for a code we cannot
+ * map, so callers can fall back to a currency-free label rather than print a
+ * misleading symbol.
+ */
+export function currencySymbol(currency?: string | null): string {
+ return CURRENCY_SYMBOL[currency ?? 'USD'] ?? '';
+}
+
+/** Monthly spend as symbol + amount (1 decimal), e.g. "$12.4". */
export function formatSpend(cents: number, currency?: string | null): string {
- const symbol = CURRENCY_SYMBOL[currency ?? 'CNY'] ?? '';
- return `${symbol}${(cents / 100).toFixed(1)}`;
+ return `${currencySymbol(currency)}${(cents / 100).toFixed(1)}`;
}
/** Whole minutes until a cooldown retry_at (never negative). */
diff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
index 3fc2af25e..697a775e8 100644
--- a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
+++ b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
@@ -240,7 +240,7 @@ export const AddCustomModelDialog: React.FC<{
aria-label={t('common.copy') as string}
onClick={copyIdentifier}
disabled={!identifier}
- className="rounded-md p-1 text-muted transition-colors hover:text-foreground disabled:opacity-40"
+ className="flex size-10 items-center justify-center rounded-md text-muted transition-colors hover:text-foreground disabled:opacity-40 sm:size-6"
>
<Copy className="size-4" />
</button>
@@ -256,7 +256,7 @@ export const AddCustomModelDialog: React.FC<{
<Button
variant="ghost"
size="sm"
- className="text-destructive hover:bg-destructive/[0.08] hover:text-destructive"
+ className="h-10 text-destructive hover:bg-destructive/[0.08] hover:text-destructive sm:h-9"
onClick={() => setDeleteOpen(true)}
disabled={saving}
>
@@ -265,10 +265,10 @@ export const AddCustomModelDialog: React.FC<{
</Button>
)}
<div className="flex items-center gap-2 max-sm:w-full max-sm:justify-end">
- <Button variant="outline" size="sm" onClick={onClose} disabled={saving}>
+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={saving}>
{t('common.cancel')}
</Button>
- <Button variant="brand" size="sm" onClick={() => void submit()} disabled={!source || !trimmedId || saving}>
+ <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void submit()} disabled={!source || !trimmedId || saving}>
<Plus className="size-4" />
{t(edit ? 'common.save' : 'settings.models.menus.custom.add')}
</Button>
diff --git a/ui/src/components/settings/models/menus/MappingDrawer.tsx b/ui/src/components/settings/models/menus/MappingDrawer.tsx
index b7ffc25e1..cb4456f26 100644
--- a/ui/src/components/settings/models/menus/MappingDrawer.tsx
+++ b/ui/src/components/settings/models/menus/MappingDrawer.tsx
@@ -101,7 +101,7 @@ const SupplySelector: React.FC<{
onFollowNative();
setOpen(false);
}}
- className="flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] hover:bg-surface-2"
+ className="flex min-h-11 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] hover:bg-surface-2 sm:min-h-0"
>
<CheckCircle2 className={cn('size-4 shrink-0', override ? 'text-muted/40' : 'text-mint')} />
<span className="text-foreground">{t('settings.models.menus.mapping.followNative')}</span>
@@ -118,11 +118,13 @@ const SupplySelector: React.FC<{
setOpen(false);
}}
className={cn(
- 'flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left hover:bg-surface-2',
+ 'flex min-h-11 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left hover:bg-surface-2 sm:min-h-0',
active && 'bg-violet-soft/60',
)}
>
- <span className="font-mono text-[13px] font-medium text-foreground">{tg.id}</span>
+ {/* Same rule as the OpenCode rows: wrap a long id, never hide its
+ suffix — picking the wrong override target is unrecoverable. */}
+ <span className="min-w-0 break-all font-mono text-[13px] font-medium text-foreground">{tg.id}</span>
{tg.displayName && <span className="truncate text-[12px] text-muted">{tg.displayName}</span>}
<SupplyDots accents={tg.accents} className="ml-auto flex shrink-0 items-center gap-1" />
</button>
@@ -217,17 +219,19 @@ export const MappingDrawer: React.FC<{
subtitle={t('settings.models.menus.mapping.subtitle', { backend: backendName }) as string}
footer={
<>
- <Button variant="outline" size="sm" onClick={resetAll} disabled={!anyOverride || saving}>
+ <Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={resetAll} disabled={!anyOverride || saving}>
<RotateCcw className="size-3.5" />
{t('settings.models.menus.resetAll')}
</Button>
- <Button variant="brand" size="sm" onClick={() => void commitAndClose()} disabled={saving}>
+ <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void commitAndClose()} disabled={saving}>
{t('settings.models.menus.done')}
</Button>
</>
}
>
- <div className="flex items-center gap-3 px-1 pb-2.5">
+ {/* Column headers only make sense while the two columns sit side by side;
+ on phones each row stacks, so the labels would mislabel the layout. */}
+ <div className="hidden items-center gap-3 px-1 pb-2.5 sm:flex">
<span className="w-[172px] shrink-0 font-mono text-[11px] font-medium uppercase tracking-wide text-muted">
{t('settings.models.menus.mapping.builtinCol')}
</span>
@@ -247,11 +251,20 @@ export const MappingDrawer: React.FC<{
override ? 'border-violet/40 bg-violet-soft/40' : 'border-border',
)}
>
- <div className="flex items-center gap-2.5">
- <div className="w-[172px] shrink-0">
+ {/* Phones stack builtin-id over supply (the 172px id column plus
+ the selector pushed the selector's chevron and the row reset
+ off-screen, so a mapping could not be changed at all); the
+ arrow rotates to keep reading as "maps to". */}
+ <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:gap-2.5">
+ <div className="min-w-0 sm:w-[172px] sm:shrink-0">
<BuiltinChip id={mapping.builtin_id} />
</div>
- <ArrowRight className={cn('size-4 shrink-0', override ? 'text-violet' : 'text-muted/60')} />
+ <ArrowRight
+ className={cn(
+ 'size-4 shrink-0 rotate-90 self-center sm:rotate-0 sm:self-auto',
+ override ? 'text-violet' : 'text-muted/60',
+ )}
+ />
<div className="min-w-0 flex-1">
<SupplySelector
mapping={mapping}
@@ -262,8 +275,8 @@ export const MappingDrawer: React.FC<{
</div>
</div>
{override && (
- <p className="flex items-center gap-1.5 pl-[208px] text-[12px] text-gold">
- <Info className="size-3.5 shrink-0" />
+ <p className="flex items-start gap-1.5 text-[12px] text-gold sm:items-center sm:pl-[208px]">
+ <Info className="mt-0.5 size-3.5 shrink-0 sm:mt-0" />
{t('settings.models.menus.mapping.warning')}
</p>
)}
diff --git a/ui/src/components/settings/models/menus/MenuDrawer.tsx b/ui/src/components/settings/models/menus/MenuDrawer.tsx
index 2f63675d8..80db51ffe 100644
--- a/ui/src/components/settings/models/menus/MenuDrawer.tsx
+++ b/ui/src/components/settings/models/menus/MenuDrawer.tsx
@@ -1,16 +1,35 @@
-// Shared right-side sheet shell for the 模型菜单 drawers (frames 04 / 05r).
+// Shared sheet shell for the 模型菜单 drawers (frames 04 / 05r).
// Built directly on the Radix dialog primitive (already a dependency) rather
-// than the centered `ui/dialog` Dialog, because these surfaces slide in from
-// the right edge and run full-height. Header (tinted icon tile + title +
-// subtitle + close), a scrollable body, and a sticky footer action bar.
+// than the centered `ui/dialog` Dialog, because these surfaces need a custom
+// header (tinted icon tile + title + subtitle + close), a scrollable body, and a
+// sticky footer action bar.
+//
+// Desktop: slides in from the right edge, full height. Phones: a bottom sheet at
+// ~91dvh (design.pen M03 m03Sheet, 730 of an 800 tall frame) — a right-edge
+// drawer on a phone is a full-screen takeover that hides where you came from,
+// and the sheet keeps the page visible behind it.
+//
+// The breakpoint is a JS branch rather than responsive classes because the two
+// shapes need opposite enter animations: `slide-in-from-bottom` and
+// `sm:slide-in-from-right` both apply at sm+, which slides the drawer in
+// diagonally. Picking one class set is clearer than zeroing the other axis.
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
+import { useIsMobile } from '@/lib/useIsMobile';
import { ACCENT_ICON, ACCENT_TILE, type Accent } from '../vendorMeta';
+const SHEET =
+ 'inset-x-0 bottom-0 h-[91dvh] rounded-t-2xl border-t border-border ' +
+ 'data-[state=open]:slide-in-from-bottom data-[state=closed]:slide-out-to-bottom';
+
+const DRAWER =
+ 'inset-y-0 right-0 w-full max-w-[620px] border-l border-border ' +
+ 'data-[state=open]:slide-in-from-right data-[state=closed]:slide-out-to-right';
+
export const MenuDrawer: React.FC<{
open: boolean;
onClose: () => void;
@@ -23,41 +42,63 @@ export const MenuDrawer: React.FC<{
children: React.ReactNode;
}> = ({ open, onClose, Icon, accent, title, subtitle, footer, children }) => {
const { t } = useTranslation();
+ const isMobile = useIsMobile();
+ const contentRef = React.useRef<HTMLDivElement>(null);
return (
- <DialogPrimitive.Root open={open} onOpenChange={(v) => !v && onClose()}>
- <DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-background/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
- <DialogPrimitive.Content
- className={cn(
- 'fixed inset-y-0 right-0 z-50 flex w-full max-w-[620px] flex-col border-l border-border bg-card shadow-2xl outline-none',
- 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:slide-in-from-right data-[state=closed]:slide-out-to-right data-[state=open]:duration-300 data-[state=closed]:duration-200',
- )}
- >
- <header className="flex items-start gap-3 border-b border-border px-6 py-5">
- <span className={cn('flex size-11 shrink-0 items-center justify-center rounded-[12px]', ACCENT_TILE[accent])}>
- <Icon size={22} className={ACCENT_ICON[accent]} />
- </span>
- <div className="flex min-w-0 flex-1 flex-col gap-1 pt-0.5">
- <DialogPrimitive.Title className="text-[18px] font-bold leading-tight text-foreground">
- {title}
- </DialogPrimitive.Title>
- <DialogPrimitive.Description className="text-[13px] leading-relaxed text-muted">
- {subtitle}
- </DialogPrimitive.Description>
- </div>
- <DialogPrimitive.Close className="shrink-0 rounded-md p-1 text-muted opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring">
- <X className="size-5" />
- <span className="sr-only">{t('common.close')}</span>
- </DialogPrimitive.Close>
- </header>
+ <DialogPrimitive.Root open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-background/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
+ <DialogPrimitive.Content
+ ref={contentRef}
+ // Without this Radix focuses the first tabbable child — the close X —
+ // so opening the menu paints a focus ring on the one control that
+ // throws the work away. Focus the panel instead; Tab / Escape and the
+ // focus trap are unaffected.
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ contentRef.current?.focus();
+ }}
+ tabIndex={-1}
+ className={cn(
+ 'fixed z-50 flex flex-col bg-card shadow-2xl outline-none',
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:duration-300 data-[state=closed]:duration-200',
+ isMobile ? SHEET : DRAWER,
+ )}
+ >
+ {isMobile && <div className="mx-auto mt-2.5 h-1.5 w-10 shrink-0 rounded-full bg-border-strong" aria-hidden />}
+
+ {/* The desktop drawer runs to the top of the screen and carries the
+ safe-area inset itself; the sheet's top edge sits well below it. */}
+ <header
+ className={cn(
+ 'flex items-start gap-3 border-b border-border px-4 py-4 sm:px-6 sm:py-5',
+ !isMobile && 'pt-[calc(1rem+env(safe-area-inset-top))] sm:pt-5',
+ )}
+ >
+ <span className={cn('flex size-10 shrink-0 items-center justify-center rounded-[12px] sm:size-11', ACCENT_TILE[accent])}>
+ <Icon size={isMobile ? 20 : 22} className={ACCENT_ICON[accent]} />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-1 pt-0.5">
+ <DialogPrimitive.Title className="text-[16px] font-bold leading-tight text-foreground sm:text-[18px]">
+ {title}
+ </DialogPrimitive.Title>
+ <DialogPrimitive.Description className="text-[12px] leading-relaxed text-muted sm:text-[13px]">
+ {subtitle}
+ </DialogPrimitive.Description>
+ </div>
+ <DialogPrimitive.Close className="flex size-10 shrink-0 items-center justify-center rounded-md text-muted opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring sm:size-7">
+ <X className="size-5" />
+ <span className="sr-only">{t('common.close')}</span>
+ </DialogPrimitive.Close>
+ </header>
- <div className="flex-1 overflow-y-auto px-6 py-5">{children}</div>
+ <div className="flex-1 overflow-y-auto px-4 py-4 sm:px-6 sm:py-5">{children}</div>
- <footer className="flex items-center justify-between gap-3 border-t border-border bg-surface/40 px-6 py-4">
- {footer}
- </footer>
- </DialogPrimitive.Content>
- </DialogPrimitive.Portal>
- </DialogPrimitive.Root>
+ <footer className="flex items-center justify-between gap-3 border-t border-border bg-surface/40 px-4 py-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] sm:px-6 sm:py-4 sm:pb-4">
+ {footer}
+ </footer>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
);
};
diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
index 6b4fc5640..0719c0229 100644
--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
@@ -35,8 +35,15 @@ const ModelRow: React.FC<{
return (
<div className="flex items-center gap-3 rounded-xl border border-border px-3.5 py-3">
<Checkbox checked={checked} onCheckedChange={onToggle} label={row.identifier} />
- <button type="button" onClick={onToggle} className="flex min-w-0 flex-1 items-center gap-2.5 text-left">
- <span className="font-mono text-[14px] font-medium text-foreground">{row.modelId}</span>
+ {/* min-h-11 makes the label span the row's full height, so the tap area
+ matches the row the user actually aims at (the 18px checkbox alone is
+ not a thumb target). */}
+ <button type="button" onClick={onToggle} className="flex min-h-11 min-w-0 flex-1 items-center gap-2.5 text-left sm:min-h-0">
+ {/* Never truncate the model id: frame 05r's contract is that the full
+ identifier is visible by construction, and custom ids are unbounded
+ (add_custom_model sets no length limit). break-all wraps instead, so
+ a long id can't overflow the row without hiding its suffix. */}
+ <span className="min-w-0 break-all font-mono text-[14px] font-medium text-foreground">{row.modelId}</span>
{row.displayName && <span className="truncate text-[13px] text-muted">{row.displayName}</span>}
{row.isCustom && (
<Badge className="shrink-0 rounded-md bg-violet-soft px-2 py-0.5 text-[10px] font-medium text-violet">
@@ -50,7 +57,7 @@ const ModelRow: React.FC<{
type="button"
aria-label={t('common.edit') as string}
onClick={onEdit}
- className="shrink-0 rounded-md p-1 text-muted transition-colors hover:text-foreground"
+ className="flex size-10 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:text-foreground sm:size-6"
>
<Pencil className="size-3.5" />
</button>
@@ -167,14 +174,16 @@ export const OpenCodeMenuDrawer: React.FC<{
footer={
<>
<span />
- <Button variant="brand" size="sm" onClick={() => void commitAndClose()} disabled={saving}>
+ <Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void commitAndClose()} disabled={saving}>
{t('settings.models.menus.done')}
</Button>
</>
}
>
- <div className="mb-4 flex items-center justify-between gap-3">
- <div className="w-[220px]">
+ {/* 220px segmented + the 自定义模型 button exceed a 360px phone side by
+ side, so they stack there and the toggle spans the width. */}
+ <div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
+ <div className="w-full sm:w-[220px]">
<SegmentedRadio
value={view}
onChange={setView}
@@ -189,7 +198,7 @@ export const OpenCodeMenuDrawer: React.FC<{
<Button
variant="outline"
size="sm"
- className="border-violet/40 text-violet hover:border-violet/60 hover:text-violet"
+ className="h-10 shrink-0 border-violet/40 text-violet hover:border-violet/60 hover:text-violet sm:h-9"
onClick={() => {
setEditTarget(null);
setCustomOpen(true);
diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.ts
index f1cbd3b13..1cc4d3889 100644
--- a/ui/src/components/settings/models/mockData.ts
+++ b/ui/src/components/settings/models/mockData.ts
@@ -68,7 +68,7 @@ export function buildMockSources(): Source[] {
supply_channel: 'hub',
billing: 'metered',
state: { status: 'standby', retry_at: null, detail_key: null },
- usage: { cycle_used_pct: null, month_spend_cents: 1240, currency: 'CNY' },
+ usage: { cycle_used_pct: null, month_spend_cents: 1240, currency: 'USD' },
account_label: null,
masked_credential: 'sk-ant-…8f2A',
models: [
@@ -88,7 +88,7 @@ export function buildMockSources(): Source[] {
supply_channel: 'hub',
billing: 'metered',
state: { status: 'standby', retry_at: null, detail_key: null },
- usage: { cycle_used_pct: null, month_spend_cents: 210, currency: 'CNY' },
+ usage: { cycle_used_pct: null, month_spend_cents: 210, currency: 'USD' },
account_label: null,
masked_credential: 'glm-…c31b',
models: [
@@ -109,7 +109,7 @@ export function buildMockSources(): Source[] {
supply_channel: 'hub',
billing: 'metered',
state: { status: 'cooldown', retry_at: iso(47 * MIN), detail_key: 'settings.models.source.cooldown.timeout' },
- usage: { cycle_used_pct: null, month_spend_cents: 320, currency: 'CNY' },
+ usage: { cycle_used_pct: null, month_spend_cents: 320, currency: 'USD' },
account_label: null,
masked_credential: 'key …9c1',
models: [
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 8afb582a8..1ba84b901 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -169,7 +169,7 @@ class MockStore {
supply_channel: 'hub',
billing: 'metered',
state: { status: 'standby', retry_at: null, detail_key: null },
- usage: { cycle_used_pct: null, month_spend_cents: 0, currency: 'CNY' },
+ usage: { cycle_used_pct: null, month_spend_cents: 0, currency: 'USD' },
account_label: null,
// Simulates L2 computing the display mask once at provisioning.
masked_credential: maskKey(draft.key),
@@ -293,7 +293,7 @@ class MockStore {
experimental_consent_at: null,
billing: isKey ? 'metered' : 'monthly',
state: { status: 'standby', retry_at: null, detail_key: null },
- usage: isKey ? { cycle_used_pct: null, month_spend_cents: 0, currency: 'CNY' } : { cycle_used_pct: 0, month_spend_cents: null, currency: null },
+ usage: isKey ? { cycle_used_pct: null, month_spend_cents: 0, currency: 'USD' } : { cycle_used_pct: 0, month_spend_cents: null, currency: null },
account_label: channel === 'native_cli' ? '[email protected]' : null,
masked_credential: isKey ? 'sk-…dd3c' : null,
models: [{ id: item.backend === 'opencode' ? 'glm-5.2' : item.backend === 'codex' ? 'gpt-5.6' : 'claude-opus-4-6', display_name: null, provenance: 'discovered', discovered_at: new Date().toISOString() }],
diff --git a/ui/src/components/settings/models/reorder.test.ts b/ui/src/components/settings/models/reorder.test.ts
new file mode 100644
index 000000000..d2ec19949
--- /dev/null
+++ b/ui/src/components/settings/models/reorder.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { movedOrder } from './reorder';
+
+const IDS = ['a', 'b', 'c', 'd'];
+
+describe('movedOrder', () => {
+ it('swaps with the previous entry when moving up', () => {
+ expect(movedOrder(IDS, 2, -1)).toEqual(['a', 'c', 'b', 'd']);
+ });
+
+ it('swaps with the next entry when moving down', () => {
+ expect(movedOrder(IDS, 0, 1)).toEqual(['b', 'a', 'c', 'd']);
+ });
+
+ it('is a no-op at either end rather than dropping or duplicating an id', () => {
+ expect(movedOrder(IDS, 0, -1)).toEqual(IDS);
+ expect(movedOrder(IDS, 3, 1)).toEqual(IDS);
+ });
+
+ it('is a no-op for an out-of-range index', () => {
+ expect(movedOrder(IDS, -1, 1)).toEqual(IDS);
+ expect(movedOrder(IDS, 9, -1)).toEqual(IDS);
+ });
+
+ it('never mutates the input and always preserves the id multiset', () => {
+ const input = [...IDS];
+ for (let i = 0; i < input.length; i++) {
+ for (const d of [-1, 1]) {
+ const out = movedOrder(input, i, d);
+ expect(input).toEqual(IDS);
+ expect([...out].sort()).toEqual([...IDS].sort());
+ expect(out.length).toBe(IDS.length);
+ }
+ }
+ });
+
+ it('round-trips: moving down then back up restores the original order', () => {
+ const down = movedOrder(IDS, 1, 1);
+ expect(movedOrder(down, 2, -1)).toEqual(IDS);
+ });
+});
diff --git a/ui/src/components/settings/models/reorder.ts b/ui/src/components/settings/models/reorder.ts
new file mode 100644
index 000000000..ead9e78bf
--- /dev/null
+++ b/ui/src/components/settings/models/reorder.ts
@@ -0,0 +1,22 @@
+/**
+ * Priority reordering for the 来源 list.
+ *
+ * Kept as a pure function so the one-step reorder behind the row menu's
+ * 上移一位 / 下移一位 is testable without a DOM: the list order IS the spend
+ * order, so an off-by-one here silently changes which account gets billed first.
+ */
+
+/**
+ * The id order after moving `index` by `delta` positions.
+ *
+ * Returns the input order unchanged when the move would fall off either end, so
+ * callers can hand the result straight to the persist path without a second
+ * bounds check — a no-op move persists a no-op.
+ */
+export function movedOrder(ids: readonly string[], index: number, delta: number): string[] {
+ const target = index + delta;
+ if (index < 0 || index >= ids.length || target < 0 || target >= ids.length) return [...ids];
+ const next = [...ids];
+ [next[index], next[target]] = [next[target], next[index]];
+ return next;
+}
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index e0b328967..aa7ce0c3b 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -29,7 +29,7 @@ export type SourceState = {
export type SourceUsage = {
cycle_used_pct?: number | null;
month_spend_cents?: number | null;
- /** ISO 4217, e.g. CNY / USD. */
+ /** ISO 4217, e.g. USD / CNY. Absent means USD (see formatSpend). */
currency?: string | null;
};
diff --git a/ui/src/components/ui/responsive-menu.tsx b/ui/src/components/ui/responsive-menu.tsx
new file mode 100644
index 000000000..5915d6f22
--- /dev/null
+++ b/ui/src/components/ui/responsive-menu.tsx
@@ -0,0 +1,122 @@
+// A menu that keeps its desktop shape and changes its *presentation* on phones:
+// an anchored popover at md+, a bottom sheet below it.
+//
+// Why a JS breakpoint rather than responsive classes: a popover is positioned by
+// Radix at runtime against its trigger, so no amount of CSS can turn it into a
+// bottom-anchored sheet — the content has to mount under a different primitive.
+// Everything else here (padding, radius, safe-area) is plain Tailwind.
+//
+// The sheet owns the affordances a touch menu needs and a popover doesn't: a
+// grabber, an optional identity header, and an explicit 取消 row (a phone user
+// can't "click outside" as reliably as they can hit a button).
+import * as React from 'react';
+import * as DialogPrimitive from '@radix-ui/react-dialog';
+import { useTranslation } from 'react-i18next';
+
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+import { useIsMobile } from '@/lib/useIsMobile';
+
+export const ResponsiveMenu: React.FC<{
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Opens the menu on both breakpoints; rendered via `asChild`. */
+ trigger: React.ReactNode;
+ /**
+ * The sheet's accessible name (Radix requires one). Also rendered as the
+ * visible heading unless `sheetTitleVisible` is false — pass false when
+ * `sheetHeader` already carries the surface's identity.
+ */
+ sheetTitle: string;
+ sheetTitleVisible?: boolean;
+ sheetDescription?: string;
+ /** Sheet-only header block rendered above the items (e.g. the row's identity). */
+ sheetHeader?: React.ReactNode;
+ /** Popover-only sizing/appearance. */
+ className?: string;
+ align?: 'start' | 'center' | 'end';
+ sideOffset?: number;
+ children: React.ReactNode;
+}> = ({
+ open,
+ onOpenChange,
+ trigger,
+ sheetTitle,
+ sheetTitleVisible = true,
+ sheetDescription,
+ sheetHeader,
+ className,
+ align = 'end',
+ sideOffset = 6,
+ children,
+}) => {
+ const { t } = useTranslation();
+ const isMobile = useIsMobile();
+ const contentRef = React.useRef<HTMLDivElement>(null);
+
+ if (!isMobile) {
+ return (
+ <Popover open={open} onOpenChange={onOpenChange}>
+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>
+ <PopoverContent
+ align={align}
+ sideOffset={sideOffset}
+ className={cn('border-border bg-card p-1.5 text-foreground shadow-lg', className)}
+ >
+ {children}
+ </PopoverContent>
+ </Popover>
+ );
+ }
+
+ return (
+ <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
+ <DialogPrimitive.Trigger asChild>{trigger}</DialogPrimitive.Trigger>
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-background/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
+ <DialogPrimitive.Content
+ ref={contentRef}
+ // Radix focuses the first item on open, which paints a focus ring on
+ // 重命名 for someone who just tapped 「…」. Focus the panel itself
+ // instead: no ring, and Tab / Escape / the focus trap still work.
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ contentRef.current?.focus();
+ }}
+ tabIndex={-1}
+ className={cn(
+ 'fixed inset-x-0 bottom-0 z-50 flex max-h-[88dvh] flex-col rounded-t-2xl border-t border-border bg-card pb-[env(safe-area-inset-bottom)] shadow-2xl outline-none',
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:slide-in-from-bottom data-[state=closed]:slide-out-to-bottom data-[state=open]:duration-300 data-[state=closed]:duration-200',
+ )}
+ >
+ <div className="mx-auto mt-2.5 h-1.5 w-10 shrink-0 rounded-full bg-border-strong" aria-hidden />
+
+ {sheetTitleVisible ? (
+ <div className={cn('flex flex-col gap-1 px-4 pt-3', sheetHeader ? 'pb-2' : 'pb-3')}>
+ <DialogPrimitive.Title className="text-[16px] font-bold leading-tight text-foreground">
+ {sheetTitle}
+ </DialogPrimitive.Title>
+ {sheetDescription && (
+ <DialogPrimitive.Description className="text-[12px] leading-relaxed text-muted">
+ {sheetDescription}
+ </DialogPrimitive.Description>
+ )}
+ </div>
+ ) : (
+ <DialogPrimitive.Title className="sr-only">{sheetTitle}</DialogPrimitive.Title>
+ )}
+
+ {sheetHeader}
+
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto border-t border-border">{children}</div>
+
+ <div className="shrink-0 px-4 pb-4 pt-3">
+ <DialogPrimitive.Close className="flex h-12 w-full items-center justify-center rounded-xl border border-border bg-surface text-[14px] font-semibold text-foreground transition-colors hover:bg-surface-2">
+ {t('common.cancel')}
+ </DialogPrimitive.Close>
+ </div>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
+ );
+};
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index b0c84a717..9bed3366a 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -24,7 +24,6 @@ import clsx from 'clsx';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
-import { SessionPinAction } from './SessionPinAction';
import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
@@ -36,6 +35,7 @@ import { ArchiveSessionDialog } from './ArchiveSessionDialog';
import { NewProjectDialog } from './NewProjectDialog';
import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';
import { ProjectSettingsDialog } from './ProjectSettingsDialog';
+import { SessionPinIndicator } from './SessionPinAction';
const DOT: Record<string, string> = {
running: 'bg-mint shadow-[0_0_7px_rgba(91,255,160,0.9)]',
@@ -254,7 +254,6 @@ const MobileSessionRow: React.FC<{
const [menuOpen, setMenuOpen] = useState(false);
const [archiveOpen, setArchiveOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
- const [pinning, setPinning] = useState(false);
const [draft, setDraft] = useState(session.title ?? '');
const inputRef = useRef<HTMLInputElement | null>(null);
const handledRef = useRef(false);
@@ -286,14 +285,12 @@ const MobileSessionRow: React.FC<{
const togglePinned = async () => {
if (pinningRef.current) return;
pinningRef.current = true;
- setPinning(true);
try {
await setSessionPinned(projectId, session.id, !session.pinned);
} catch {
// apiFetch already surfaced the error toast.
} finally {
pinningRef.current = false;
- setPinning(false);
}
};
@@ -328,6 +325,7 @@ const MobileSessionRow: React.FC<{
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">
{session.title || `#${session.id.slice(-6)}`}
</span>
+ <SessionPinIndicator pinned={session.pinned} label={t('workbench.sessionPinned')} />
{unread > 0 ? (
<span className="shrink-0 rounded-full bg-mint px-1.5 py-0.5 font-mono text-[10px] font-bold text-background">
{unread > 99 ? '99+' : unread}
@@ -338,13 +336,6 @@ const MobileSessionRow: React.FC<{
</span>
)}
</button>
- <SessionPinAction
- pinned={session.pinned}
- pending={pinning}
- pinLabel={t('workbench.sessionPin')}
- unpinLabel={t('workbench.sessionUnpin')}
- onToggle={() => void togglePinned()}
- />
<Popover open={menuOpen} onOpenChange={setMenuOpen}>
<PopoverTrigger asChild>
<Button
diff --git a/ui/src/components/workbench/SessionPinAction.test.tsx b/ui/src/components/workbench/SessionPinAction.test.tsx
index d52845e21..2168e8e73 100644
--- a/ui/src/components/workbench/SessionPinAction.test.tsx
+++ b/ui/src/components/workbench/SessionPinAction.test.tsx
@@ -1,7 +1,8 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
-import { SessionPinAction } from './SessionPinAction';
+import { SessionPinAction, SessionPinIndicator } from './SessionPinAction';
+import { sessionPinRowPaddingClass } from './sessionPinLayout';
const renderAction = (pinned: boolean, pending = false) =>
renderToStaticMarkup(
@@ -15,6 +16,13 @@ const renderAction = (pinned: boolean, pending = false) =>
);
describe('SessionPinAction', () => {
+ it('keeps the 24px action target out of the session row layout', () => {
+ const html = renderAction(false);
+
+ expect(html).toContain('absolute inset-y-0 right-2 flex items-center');
+ expect(html).toContain('grid size-6');
+ });
+
it('reveals an unpinned action on row hover, keyboard focus, and coarse pointers', () => {
const html = renderAction(false);
@@ -25,11 +33,12 @@ describe('SessionPinAction', () => {
expect(html).toContain('pointer-coarse:opacity-100');
});
- it('keeps a pinned action visible and gives hover feedback', () => {
+ it('keeps a pinned action visible without a resting background and gives hover feedback', () => {
const html = renderAction(true);
expect(html).toContain('aria-pressed="true"');
expect(html).toContain('opacity-100');
+ expect(html).not.toMatch(/(?:class="|\s)bg-[^\s"]+/);
expect(html).toContain('hover:bg-cyan/[0.18]');
expect(html).toContain('hover:scale-105');
expect(html).toContain('group-hover/pin:-rotate-12');
@@ -43,3 +52,36 @@ describe('SessionPinAction', () => {
expect(html).toContain('cursor-wait');
});
});
+
+describe('SessionPinIndicator', () => {
+ it('renders no passive status for an unpinned session', () => {
+ const html = renderToStaticMarkup(<SessionPinIndicator pinned={false} label="Pinned" />);
+
+ expect(html).toBe('');
+ });
+
+ it('renders a non-interactive status icon for a pinned session', () => {
+ const html = renderToStaticMarkup(<SessionPinIndicator pinned label="Pinned" />);
+
+ expect(html).toContain('role="img"');
+ expect(html).toContain('aria-label="Pinned"');
+ expect(html).toContain('text-cyan');
+ expect(html).not.toMatch(/(?:class="|\s)bg-[^\s"]+/);
+ expect(html).not.toContain('<button');
+ });
+});
+
+describe('sessionPinRowPaddingClass', () => {
+ it('uses the full title width until an unpinned action is revealed', () => {
+ const className = sessionPinRowPaddingClass(false);
+
+ expect(className).toContain('pr-2.5');
+ expect(className).toContain('hover:pr-10');
+ expect(className).toContain('focus-within:pr-10');
+ expect(className).toContain('pointer-coarse:pr-10');
+ });
+
+ it('always reserves action space for a pinned session', () => {
+ expect(sessionPinRowPaddingClass(true)).toBe('pr-10');
+ });
+});
diff --git a/ui/src/components/workbench/SessionPinAction.tsx b/ui/src/components/workbench/SessionPinAction.tsx
index a37b3d55d..1325d6cd6 100644
--- a/ui/src/components/workbench/SessionPinAction.tsx
+++ b/ui/src/components/workbench/SessionPinAction.tsx
@@ -11,6 +11,27 @@ interface SessionPinActionProps {
className?: string;
}
+interface SessionPinIndicatorProps {
+ pinned: boolean;
+ label: string;
+ className?: string;
+}
+
+export const SessionPinIndicator: React.FC<SessionPinIndicatorProps> = ({ pinned, label, className }) => {
+ if (!pinned) return null;
+
+ return (
+ <span
+ role="img"
+ aria-label={label}
+ title={label}
+ className={clsx('flex shrink-0 text-cyan', className)}
+ >
+ <Pin className="size-3" aria-hidden="true" />
+ </span>
+ );
+};
+
export const SessionPinAction: React.FC<SessionPinActionProps> = ({
pinned,
pending,
@@ -26,32 +47,33 @@ export const SessionPinAction: React.FC<SessionPinActionProps> = ({
};
return (
- <button
- type="button"
- disabled={pending}
- aria-label={label}
- aria-pressed={pinned}
- title={label}
- onClick={handleClick}
- className={clsx(
- 'group/pin grid size-6 shrink-0 place-items-center rounded-md transition-[opacity,transform,background-color,color,box-shadow] duration-150 ease-out',
- 'hover:-translate-y-px hover:scale-105 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-cyan/60 motion-reduce:transform-none',
- pending
- ? 'cursor-wait text-muted opacity-100 hover:translate-y-0 hover:scale-100'
- : pinned
- ? 'bg-cyan/[0.10] text-cyan opacity-100 hover:bg-cyan/[0.18] hover:ring-1 hover:ring-cyan/30'
- : 'text-muted opacity-0 hover:bg-foreground/[0.08] hover:text-foreground group-hover/sess:opacity-100 group-focus-within/sess:opacity-100 pointer-coarse:opacity-100',
- className,
- )}
- >
- {pending ? (
- <Loader2 className="size-3 animate-spin" aria-hidden="true" />
- ) : (
- <Pin
- className="size-3 transition-transform duration-150 group-hover/pin:-rotate-12 group-hover/pin:scale-110 motion-reduce:transform-none"
- aria-hidden="true"
- />
- )}
- </button>
+ <span className={clsx('absolute inset-y-0 right-2 flex items-center', className)}>
+ <button
+ type="button"
+ disabled={pending}
+ aria-label={label}
+ aria-pressed={pinned}
+ title={label}
+ onClick={handleClick}
+ className={clsx(
+ 'group/pin grid size-6 shrink-0 place-items-center rounded-md transition-[opacity,transform,background-color,color,box-shadow] duration-150 ease-out',
+ 'hover:-translate-y-px hover:scale-105 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-cyan/60 motion-reduce:transform-none',
+ pending
+ ? 'cursor-wait text-muted opacity-100 hover:translate-y-0 hover:scale-100'
+ : pinned
+ ? 'text-cyan opacity-100 hover:bg-cyan/[0.18] hover:ring-1 hover:ring-cyan/30'
+ : 'text-muted opacity-0 hover:bg-foreground/[0.08] hover:text-foreground group-hover/sess:opacity-100 group-focus-within/sess:opacity-100 pointer-coarse:opacity-100',
+ )}
+ >
+ {pending ? (
+ <Loader2 className="size-3 animate-spin" aria-hidden="true" />
+ ) : (
+ <Pin
+ className="size-3 transition-transform duration-150 group-hover/pin:-rotate-12 group-hover/pin:scale-110 motion-reduce:transform-none"
+ aria-hidden="true"
+ />
+ )}
+ </button>
+ </span>
);
};
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 8b04940b6..d253aee56 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -40,6 +40,7 @@ import { useApi } from '../../context/ApiContext';
import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { SessionPinAction } from './SessionPinAction';
+import { sessionPinRowPaddingClass } from './sessionPinLayout';
import { formatRelativeTime } from '../../lib/relativeTime';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
import { ArchiveSessionDialog } from './ArchiveSessionDialog';
@@ -312,7 +313,8 @@ const SessionRow: React.FC<{
setMenuOpen(true);
}}
className={clsx(
- 'group/sess flex items-center gap-2 rounded-md py-1.5 pl-[26px] pr-2.5 text-left transition',
+ 'group/sess relative flex items-center gap-2 rounded-md py-1.5 pl-[26px] text-left transition-[background-color,padding-right] duration-150 ease-out motion-reduce:transition-none',
+ sessionPinRowPaddingClass(session.pinned),
active
? 'border-l-2 border-mint bg-mint-soft pl-[24px] font-semibold text-foreground'
: 'hover:bg-foreground/[0.04]',
diff --git a/ui/src/components/workbench/sessionPinLayout.ts b/ui/src/components/workbench/sessionPinLayout.ts
new file mode 100644
index 000000000..69aedb76f
--- /dev/null
+++ b/ui/src/components/workbench/sessionPinLayout.ts
@@ -0,0 +1,4 @@
+export const sessionPinRowPaddingClass = (pinned: boolean) =>
+ pinned
+ ? 'pr-10'
+ : 'pr-2.5 hover:pr-10 focus-within:pr-10 pointer-coarse:pr-10';
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 8e83ef02f..e3eb594b3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -631,7 +631,8 @@
},
"billing": {
"monthly": "Monthly",
- "metered": "Metered ¥"
+ "metered": "Metered",
+ "meteredWithSymbol": "Metered {{symbol}}"
},
"state": {
"active": "In use",
@@ -663,7 +664,8 @@
"modelCount": "{{count}} models",
"multiSource": "Multiple sources",
"multiSourceCustom": "Multiple sources · {{count}} custom",
- "hubNoSupply": "On Hub · no source available yet (using Direct)"
+ "hubNoSupply": "On Hub · no source available yet (using Direct)",
+ "directNote": "Still supplied by the CLI's own config — not connected to the Hub"
},
"recent": {
"title": "Recent switches",
@@ -690,6 +692,16 @@
"apiKey": {
"title": "Add API Key…",
"subtitle": "Any vendor or compatible service, editable URL"
+ },
+ "sheetTitle": "Add source",
+ "sheetSubtitle": "There are only two kinds: a subscription account, or a key. A relay is just a key with a different URL.",
+ "vendorTitle": "Connect a subscription",
+ "vendorSubtitle": "Uses the CLI's own sign-in; the credential stays on this machine.",
+ "apiKeySheetSubtitle": "Official or third-party URLs both work; filling in a custom URL makes it a relay.",
+ "subscription": {
+ "title": "Subscription account",
+ "subtitle": "Claude Pro, ChatGPT Plus and the like. Uses the CLI's own sign-in; the credential stays in the local CLI.",
+ "recommended": "Recommended"
}
},
"addKey": {
@@ -894,7 +906,17 @@
"deleteForceBody": "“{{name}}” is the only supplier of a selected model; deleting it leaves that agent with no source. Force delete?",
"deleteForceConfirm": "Force delete",
"deleted": "Source deleted",
- "deleteFailed": "Couldn't delete, please retry"
+ "deleteFailed": "Couldn't delete, please retry",
+ "priorityLabel": "Priority {{position}}",
+ "renameHint": "Changes the display name only — the credential is untouched",
+ "rediscoverHint": "Re-fetch the models this source can supply",
+ "moveUp": "Move up one",
+ "moveUpHint": "Gets used earlier",
+ "moveUpHintAtTop": "Already first — can't move up",
+ "moveDown": "Move down one",
+ "moveDownHint": "Gets used later",
+ "moveDownHintAtBottom": "Already last — can't move down",
+ "deleteHint": "You'll be asked to confirm first"
},
"migrationBanner": {
"title": "Native configs ready to import",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b73a846d2..0425d103a 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -631,7 +631,8 @@
},
"billing": {
"monthly": "包月",
- "metered": "按量 ¥"
+ "metered": "按量",
+ "meteredWithSymbol": "按量 {{symbol}}"
},
"state": {
"active": "使用中",
@@ -663,7 +664,8 @@
"modelCount": "{{count}} 个模型",
"multiSource": "多来源",
"multiSourceCustom": "多来源 · 含 {{count}} 个自定义",
- "hubNoSupply": "已接入中枢 · 暂无可用来源(当前走直连)"
+ "hubNoSupply": "已接入中枢 · 暂无可用来源(当前走直连)",
+ "directNote": "仍在用 CLI 原生配置供给,未接入中枢"
},
"recent": {
"title": "最近切换",
@@ -690,6 +692,16 @@
"apiKey": {
"title": "添加 API Key…",
"subtitle": "任何厂商或兼容服务,可改地址"
+ },
+ "sheetTitle": "添加来源",
+ "sheetSubtitle": "来源只有两类:订阅账号,或一把 Key。中转站 = 改了地址的 Key。",
+ "vendorTitle": "连接订阅账号",
+ "vendorSubtitle": "走 CLI 原生登录,凭证留在本机。",
+ "apiKeySheetSubtitle": "官方或第三方地址都行;填了自定义地址就是「中转站」。",
+ "subscription": {
+ "title": "订阅账号",
+ "subtitle": "Claude Pro / ChatGPT Plus 等。走 CLI 原生登录,凭证留在本机 CLI 里。",
+ "recommended": "推荐"
}
},
"addKey": {
@@ -894,7 +906,17 @@
"deleteForceBody": "「{{name}}」是某个已选模型的唯一供给,删除后相关 Agent 将无来源可用。确认强制删除?",
"deleteForceConfirm": "强制删除",
"deleted": "已删除来源",
- "deleteFailed": "删除失败,请重试"
+ "deleteFailed": "删除失败,请重试",
+ "priorityLabel": "优先级 {{position}}",
+ "renameHint": "只改显示名,不动凭证",
+ "rediscoverHint": "重新拉取这个来源能供给的模型",
+ "moveUp": "上移一位",
+ "moveUpHint": "更早被使用",
+ "moveUpHintAtTop": "已在第 1 位,不能再上移",
+ "moveDown": "下移一位",
+ "moveDownHint": "更晚被使用",
+ "moveDownHintAtBottom": "已在最后一位,不能再下移",
+ "deleteHint": "删除前会再确认一次"
},
"migrationBanner": {
"title": "发现可导入中枢的原生配置",
diff --git a/ui/src/lib/useIsMobile.ts b/ui/src/lib/useIsMobile.ts
new file mode 100644
index 000000000..5a6cd500c
--- /dev/null
+++ b/ui/src/lib/useIsMobile.ts
@@ -0,0 +1,31 @@
+import * as React from 'react';
+
+// The phone breakpoint used across the app (Tailwind `md`), matching the
+// `max-md:` bottom-sheet styling in ui/dialog.tsx so a sheet and a dialog never
+// disagree about which side of the breakpoint they're on.
+const PHONE_QUERY = '(max-width: 767px)';
+
+/**
+ * True while the viewport is phone-sized.
+ *
+ * Only for surfaces whose *structure* differs per breakpoint — an anchored
+ * popover becoming a bottom sheet, say, where CSS alone can't re-parent the
+ * content. Prefer Tailwind responsive classes for anything that is purely
+ * visual; they need no JS and can't flash the wrong layout on first paint.
+ */
+export function useIsMobile(): boolean {
+ const [isMobile, setIsMobile] = React.useState(
+ () => typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(PHONE_QUERY).matches,
+ );
+
+ React.useEffect(() => {
+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
+ const mql = window.matchMedia(PHONE_QUERY);
+ const sync = () => setIsMobile(mql.matches);
+ sync();
+ mql.addEventListener('change', sync);
+ return () => mql.removeEventListener('change', sync);
+ }, []);
+
+ return isMobile;
+}
diff --git a/ui/vite.config.ts b/ui/vite.config.ts
index d4e554ecb..d6e73352b 100644
--- a/ui/vite.config.ts
+++ b/ui/vite.config.ts
@@ -2,7 +2,10 @@ import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
-const backendTarget = 'http://localhost:5100'
+// Point the dev proxy at any running Avibe instance — e.g. the Incus regression
+// environment — with VIBE_UI_BACKEND=http://127.0.0.1:15130 npm run dev, so UI
+// work can be driven against real data without restarting the local service.
+const backendTarget = process.env.VIBE_UI_BACKEND ?? 'http://localhost:5100'
const backendProxy = () => ({
target: backendTarget,
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
index e2f8c2707..bf9d2ff9b 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -20,7 +20,7 @@ REMOTE_CATALOG_URL_ENV = "AVIBE_BACKEND_MODEL_CATALOG_URL"
DEFAULT_REMOTE_CATALOG_URL = (
"https://raw.githubusercontent.com/avibe-bot/avibe/master/vibe/data/backend_models.json"
)
-REMOTE_CATALOG_REVALIDATE_SECONDS = 60
+REMOTE_CATALOG_REVALIDATE_SECONDS = 5 * 60
REMOTE_CATALOG_FAILURE_TTL_SECONDS = 10 * 60
REMOTE_CATALOG_TIMEOUT_SECONDS = 3.0
REMOTE_CATALOG_USER_AGENT = "avibe/backend-model-catalog"
diff --git a/vibe/cli.py b/vibe/cli.py
index ca704b88b..c04de3470 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -46,6 +46,7 @@ from core.caller_context import caller_context_from_env
from core.vibe_agents import VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
DEFAULT_RETRY_EXIT_CODE,
+ WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS,
WATCH_RECONCILE_INTERVAL_SECONDS,
ManagedWatchStore,
WatchRuntimeStateStore,
@@ -66,7 +67,14 @@ from vibe.upgrade import (
from storage.db import create_sqlite_engine
from storage.background import compute_next_run_at, normalize_run_status
from storage.models import scope_settings, scopes
-from storage.pagination import DEFAULT_PAGE_LIMIT, PageRequest, make_page_request, page_sequence, pagination_payload
+from storage.pagination import (
+ DEFAULT_PAGE_LIMIT,
+ MAX_PAGE_LIMIT,
+ PageRequest,
+ make_page_request,
+ page_sequence,
+ pagination_payload,
+)
from storage.read_only_query import ReadOnlyQueryError, run_read_only_query
from storage.settings_service import make_scope_id
@@ -209,8 +217,11 @@ def _print_cli_payload(kind: str, **fields) -> None:
def _add_pagination_args(parser, *, help_command: str) -> None:
parser.add_argument("--page", type=int, help="Page number to return. Defaults to 1.")
- parser.add_argument("--limit", type=int, help=f"Rows per page. Defaults to {DEFAULT_PAGE_LIMIT}.")
- parser.add_argument("--all", action="store_true", help="Return all matching rows without pagination.")
+ parser.add_argument(
+ "--limit",
+ type=int,
+ help=f"Rows per page. Defaults to {DEFAULT_PAGE_LIMIT}; maximum {MAX_PAGE_LIMIT}.",
+ )
parser.error_help_command = help_command
@@ -231,12 +242,11 @@ def _add_vault_approval_wait_args(parser, *, default_seconds: int = DEFAULT_VAUL
)
-def _page_request_from_args(args, *, help_command: str) -> PageRequest | None:
+def _page_request_from_args(args, *, help_command: str) -> PageRequest:
try:
return make_page_request(
page=getattr(args, "page", None),
limit=getattr(args, "limit", None),
- all_items=bool(getattr(args, "all", False)),
)
except ValueError as exc:
raise TaskCliError(str(exc), code="invalid_pagination", help_command=help_command) from exc
@@ -247,8 +257,8 @@ def _add_optional_arg(parts: list[str], flag: str, value: object) -> None:
parts.extend([flag, str(value)])
-def _next_command(parts: list[str], page_result, *, include_all: bool = False) -> str | None:
- if include_all or page_result.next_page is None:
+def _next_command(parts: list[str], page_result) -> str | None:
+ if page_result.next_page is None:
return None
command = [*parts, "--page", str(page_result.next_page), "--limit", str(page_result.limit)]
return shlex.join(command)
@@ -263,6 +273,36 @@ def _pagination_message(page_payload: dict) -> str | None:
return "More records are available. Add --page to continue."
+def _paginated_fields(page_result, *, command: list[str], include_next_command: bool = True) -> dict:
+ page_payload = pagination_payload(
+ page_result,
+ next_command=_next_command(command, page_result) if include_next_command else None,
+ )
+ fields = {"pagination": page_payload}
+ message = _pagination_message(page_payload)
+ if message:
+ fields["message"] = message
+ return fields
+
+
+def _print_definition_list_payload(
+ items,
+ *,
+ items_key: str,
+ payload_for_item,
+ command: list[str],
+ page_request: PageRequest,
+) -> None:
+ result = page_sequence(items, page_request)
+ item_payloads = [payload_for_item(item) for item in result.items]
+ payload = {
+ "definitions": item_payloads,
+ items_key: item_payloads,
+ **_paginated_fields(result, command=command),
+ }
+ _print_cli_payload("run_definitions", **payload)
+
+
def _parse_cli_time_filter(value: str | None, *, field_name: str, help_command: str) -> str | None:
if value is None:
return None
@@ -398,7 +438,7 @@ def _watch_examples_text() -> str:
vibe watch add --session-id sesk8m4q2p7x --name 'Wait for export' --message 'The export finished. Inspect it and continue.' --shell 'python3 scripts/wait_for_export.py'
vibe watch add --create-session --scope-id slack::channel::C123 --message 'The CI job finished. Inspect the result.' -- python3 scripts/wait_for_ci.py --build 42
vibe watch add --session-id sesk8m4q2p7x --forever --retry-exit-code 75 --retry-delay 60 --message 'The log pattern appeared. Continue from the result below.' --shell 'bash scripts/wait_for_log_pattern.sh'
- vibe watch list --brief
+ vibe watch list
vibe watch show 12ab34cd56ef
vibe watch pause 12ab34cd56ef
"""
@@ -1458,6 +1498,8 @@ def _task_display_name(task) -> str:
def _task_state(task) -> str:
if task.enabled:
return "active"
+ if _is_failed_one_shot(task):
+ return "failed"
if _is_completed_one_shot(task):
return "completed"
return "paused"
@@ -1489,21 +1531,6 @@ def _task_schedule_summary(task) -> str:
return task.schedule_type
-def _task_next_run_sort_key(task):
- next_run_at = _task_next_run_at(task)
- if not next_run_at:
- return (True, datetime.max.replace(tzinfo=timezone.utc))
- try:
- instant = datetime.fromisoformat(next_run_at)
- if instant.tzinfo is None:
- instant = instant.replace(tzinfo=timezone.utc)
- else:
- instant = instant.astimezone(timezone.utc)
- except ValueError:
- return (True, datetime.max.replace(tzinfo=timezone.utc))
- return (False, instant)
-
-
def _task_payload(task, *, brief: bool = False):
derived = {
"display_name": _task_display_name(task),
@@ -1537,14 +1564,11 @@ def _task_payload(task, *, brief: bool = False):
def _sort_tasks_for_display(tasks):
- return sorted(
- tasks,
- key=lambda item: (
- *_task_next_run_sort_key(item),
- item.created_at,
- item.id,
- ),
- )
+ # Offset pagination requires an order that does not change merely because
+ # wall-clock time crossed a cron boundary between page requests. Keep
+ # schedulable tasks ahead of paused/history rows without using next-run
+ # timestamps, which are time-dependent.
+ return sorted(tasks, key=lambda item: (item.enabled is False, item.created_at, item.id))
def _task_store() -> ScheduledTaskStore:
@@ -1603,7 +1627,31 @@ def _supported_task_platforms() -> set[str]:
def _is_completed_one_shot(task) -> bool:
- return task.schedule_type == "at" and not task.enabled and bool(task.last_run_at)
+ return (
+ task.schedule_type == "at"
+ and not task.enabled
+ and bool(task.last_run_at)
+ and not task.last_error
+ )
+
+
+def _is_failed_one_shot(task) -> bool:
+ return (
+ task.schedule_type == "at"
+ and not task.enabled
+ and bool(task.last_run_at)
+ and bool(task.last_error)
+ )
+
+
+def _is_finished_one_shot_watch(watch) -> bool:
+ return (
+ watch.mode == "once"
+ and not watch.enabled
+ and bool(watch.last_finished_at)
+ and not watch.last_error
+ and watch.last_exit_code in (None, 0)
+ )
def _parse_validated_session_key(
@@ -2389,8 +2437,37 @@ def _seconds_since_iso(timestamp: object) -> float | None:
return max(0.0, (datetime.now(timezone.utc) - started_at).total_seconds())
-def _default_watch_startup_timeout_seconds(*, stable_running_seconds: float = WATCH_STARTUP_STABLE_RUNNING_SECONDS) -> float:
- return WATCH_RECONCILE_INTERVAL_SECONDS + stable_running_seconds + WATCH_STARTUP_JITTER_BUFFER_SECONDS
+def _watch_recovery_entry_count(runtime_store: WatchRuntimeStateStore) -> int:
+ try:
+ runtime_state = runtime_store.load_for_recovery()
+ except Exception:
+ return 1
+ runtime_watches = runtime_state.get("watches") if isinstance(runtime_state, dict) else None
+ if not isinstance(runtime_watches, dict):
+ return 1
+ return sum(
+ 1
+ for entry in runtime_watches.values()
+ if isinstance(entry, dict)
+ and entry.get("running") is True
+ and isinstance(entry.get("pid"), int)
+ and not isinstance(entry.get("pid"), bool)
+ and entry["pid"] > 0
+ )
+
+
+def _default_watch_startup_timeout_seconds(
+ *,
+ stable_running_seconds: float = WATCH_STARTUP_STABLE_RUNNING_SECONDS,
+ recovery_entry_count: int = 0,
+) -> float:
+ recovery_budget = max(0, recovery_entry_count) * WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS
+ return (
+ WATCH_RECONCILE_INTERVAL_SECONDS
+ + recovery_budget
+ + stable_running_seconds
+ + WATCH_STARTUP_JITTER_BUFFER_SECONDS
+ )
def _wait_for_watch_startup(
@@ -2404,7 +2481,10 @@ def _wait_for_watch_startup(
):
inspect_command = f"vibe watch show {watch_id}"
if timeout_seconds is None:
- timeout_seconds = _default_watch_startup_timeout_seconds(stable_running_seconds=stable_running_seconds)
+ timeout_seconds = _default_watch_startup_timeout_seconds(
+ stable_running_seconds=stable_running_seconds,
+ recovery_entry_count=_watch_recovery_entry_count(runtime_store),
+ )
deadline = time.monotonic() + timeout_seconds
while time.monotonic() < deadline:
store.maybe_reload()
@@ -2601,16 +2681,26 @@ def cmd_task_add(args):
return 1
-def cmd_task_list(*, include_all: bool = False, brief: bool = False):
+def cmd_task_list(
+ *,
+ include_finished: bool = False,
+ brief: bool = True,
+ page_request: PageRequest = PageRequest(),
+):
store = _task_store()
tasks = store.list_tasks()
- if not include_all:
+ if not include_finished:
tasks = [task for task in tasks if not _is_completed_one_shot(task)]
tasks = _sort_tasks_for_display(tasks)
- _print_cli_payload(
- "run_definitions",
- definitions=[_task_payload(task, brief=brief) for task in tasks],
- tasks=[_task_payload(task, brief=brief) for task in tasks],
+ command = ["vibe", "task", "list"]
+ if include_finished:
+ command.append("--include-finished")
+ _print_definition_list_payload(
+ tasks,
+ items_key="tasks",
+ payload_for_item=lambda task: _task_payload(task, brief=True),
+ command=command,
+ page_request=page_request,
)
return 0
@@ -3134,20 +3224,33 @@ def _add_json_noop(parser) -> None:
def cmd_agent_list(args):
- store = _agent_store()
- backend = getattr(args, "backend", None)
- if getattr(args, "disabled", False):
- include_disabled = True
- else:
- include_disabled = bool(getattr(args, "all", False))
- agents = store.list_agents(include_disabled=include_disabled)
- if backend:
- agents = [agent for agent in agents if agent.backend == backend]
- if getattr(args, "disabled", False):
- agents = [agent for agent in agents if not agent.enabled]
- agents = [_agent_payload(agent, brief=getattr(args, "brief", False)) for agent in agents]
- _print_cli_payload("agents", agents=agents)
- return 0
+ try:
+ page_request = _page_request_from_args(args, help_command="vibe agent list --help")
+ store = _agent_store()
+ backend = getattr(args, "backend", None)
+ disabled_only = bool(getattr(args, "disabled", False))
+ include_disabled = disabled_only or bool(getattr(args, "include_disabled", False))
+ agents = store.list_agents(include_disabled=include_disabled)
+ if backend:
+ agents = [agent for agent in agents if agent.backend == backend]
+ if disabled_only:
+ agents = [agent for agent in agents if not agent.enabled]
+ result = page_sequence(agents, page_request)
+ command = ["vibe", "agent", "list"]
+ _add_optional_arg(command, "--backend", backend)
+ if disabled_only:
+ command.append("--disabled")
+ elif include_disabled:
+ command.append("--include-disabled")
+ _print_cli_payload(
+ "agents",
+ agents=[_agent_payload(agent, brief=True) for agent in result.items],
+ **_paginated_fields(result, command=command),
+ )
+ return 0
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe agent list --help")
+ return 1
def cmd_agent_show(args):
@@ -3247,19 +3350,41 @@ def cmd_agent_models(args):
# the displayed list, so an Agent's real model is never hidden from it.
current = _agent_models_current(agent, options) if agent else None
models = options.get("models", [])
+ providers = options.get("providers")
+ provider_rows = providers if isinstance(providers, list) else []
if model:
models = [entry for entry in models if entry.get("value") == model]
+ matching_provider_ids = {
+ entry.get("provider") for entry in models if entry.get("provider")
+ }
+ provider_rows = [
+ entry for entry in provider_rows if entry.get("id") in matching_provider_ids
+ ]
+ catalog_rows = [("provider", entry) for entry in provider_rows]
+ catalog_rows.extend(("model", entry) for entry in models)
+ page_request = _page_request_from_args(args, help_command="vibe agent models --help")
+ result = page_sequence(catalog_rows, page_request)
+ page_providers = [entry for kind, entry in result.items if kind == "provider"]
+ page_models = [entry for kind, entry in result.items if kind == "model"]
+ command = ["vibe", "agent", "models"]
+ if name:
+ command.append(name)
+ else:
+ _add_optional_arg(command, "--backend", backend_arg)
+ _add_optional_arg(command, "--provider", provider)
+ _add_optional_arg(command, "--model", model)
_print_cli_payload(
"agent_models",
agent=agent.name if agent else None,
backend=backend,
current=current,
default_model=options.get("default_model"),
- providers=options.get("providers"),
- models=models,
+ providers=page_providers if providers is not None else None,
+ models=page_models,
source=options.get("source"),
live=options.get("live", False),
notes=options.get("notes"),
+ **_paginated_fields(result, command=command),
)
return 0
except Exception as exc:
@@ -4369,14 +4494,10 @@ def cmd_runs_list(args):
_add_optional_arg(command, "--q", getattr(args, "query", None))
if getattr(args, "brief", False):
command.append("--brief")
- page_payload = pagination_payload(result, next_command=_next_command(command, result, include_all=bool(getattr(args, "all", False))))
- message = _pagination_message(page_payload)
payload = {
- "runs": [_run_payload(run, brief=getattr(args, "brief", False)) for run in result.items],
- "pagination": page_payload,
+ "runs": [_run_payload(run, brief=True) for run in result.items],
+ **_paginated_fields(result, command=command),
}
- if message:
- payload["message"] = message
_print_cli_payload("agent_runs", **payload)
return 0
except Exception as exc:
@@ -4603,22 +4724,15 @@ def cmd_data_query(args):
elif sql_file and sql_file != "-":
_add_optional_arg(command, "--sql-file", sql_file)
omit_next_command = bool(sql_file == "-")
- page_payload = pagination_payload(
- result.pagination,
- next_command=_next_command(
- command,
- result.pagination,
- include_all=bool(getattr(args, "all", False)) or omit_next_command,
- ),
- )
- message = _pagination_message(page_payload)
payload = {
"columns": result.columns,
"rows": result.rows,
- "pagination": page_payload,
+ **_paginated_fields(
+ result.pagination,
+ command=command,
+ include_next_command=not omit_next_command,
+ ),
}
- if message:
- payload["message"] = message
_print_cli_payload("data_query", **payload)
return 0
except ReadOnlyQueryError as exc:
@@ -4633,7 +4747,6 @@ def cmd_data_query(args):
# read-only; ``update`` edits title, visibility, or scope placement. All three go through the shared
# ``core.services.sessions`` business API (same entry the UI server uses) and
# never surface archived (soft-deleted) sessions.
-_SESSION_PAGE_SIZE = 10
# Lean list row: enough to locate a session and tell whether it is busy.
_SESSION_LIST_FIELDS = (
"id",
@@ -4699,29 +4812,29 @@ def cmd_session_list(args):
platform = getattr(args, "type", None)
if platform:
_validate_session_type(platform)
- page = getattr(args, "page", None)
- page = int(page) if page is not None else 1
- if page < 1:
- raise TaskCliError("page must be >= 1", code="invalid_pagination", help_command="vibe session list --help")
+ page_request = _page_request_from_args(args, help_command="vibe session list --help")
from core.services import sessions as sessions_service
engine = _open_session_engine()
with engine.connect() as conn:
result = sessions_service.list_sessions_page(
- conn, platform=platform, page=page, limit=_SESSION_PAGE_SIZE
+ conn,
+ platform=platform,
+ page=page_request.page,
+ limit=page_request.limit,
)
command = ["vibe", "session", "list"]
_add_optional_arg(command, "--type", platform)
- next_command = (
- shlex.join([*command, "--page", str(result.next_page)])
- if result.next_page is not None
- else None
- )
+ page_fields = _paginated_fields(result, command=command)
+ pagination_message = page_fields.pop("message", None)
+ message = _session_list_hint()
+ if pagination_message:
+ message = f"{pagination_message} {message}"
_print_cli_payload(
"agent_sessions",
sessions=[_session_row(row, brief=True) for row in result.items],
- pagination=pagination_payload(result, next_command=next_command),
- message=_session_list_hint(),
+ **page_fields,
+ message=message,
)
return 0
except Exception as exc:
@@ -5151,11 +5264,8 @@ def _vault_page_payload(
) -> tuple[list[dict], dict, str | None]:
page_request = _page_request_from_args(args, help_command=help_command)
result = page_sequence(items, page_request)
- page_payload = pagination_payload(
- result,
- next_command=_next_command(command, result, include_all=bool(getattr(args, "all", False))),
- )
- return result.items, page_payload, _pagination_message(page_payload)
+ fields = _paginated_fields(result, command=command)
+ return result.items, fields["pagination"], fields.get("message")
def _vault_lookup_next_steps(*, has_more: bool, has_filters: bool) -> list[str]:
@@ -7738,13 +7848,28 @@ def cmd_watch_add(args):
return 1
-def cmd_watch_list(*, brief: bool = False):
+def cmd_watch_list(
+ *,
+ include_finished: bool = False,
+ brief: bool = True,
+ page_request: PageRequest = PageRequest(),
+):
store = _watch_store()
runtime_state = _watch_runtime_store().load().get("watches", {})
watches = store.list_watches()
+ if not include_finished:
+ watches = [watch for watch in watches if not _is_finished_one_shot_watch(watch)]
watches.sort(key=lambda item: (item.enabled is False, item.created_at, item.id))
- watch_payloads = [_watch_payload(watch, runtime_state.get(watch.id), brief=brief) for watch in watches]
- _print_cli_payload("run_definitions", definitions=watch_payloads, watches=watch_payloads)
+ command = ["vibe", "watch", "list"]
+ if include_finished:
+ command.append("--include-finished")
+ _print_definition_list_payload(
+ watches,
+ items_key="watches",
+ payload_for_item=lambda watch: _watch_payload(watch, runtime_state.get(watch.id), brief=True),
+ command=command,
+ page_request=page_request,
+ )
return 0
@@ -10251,18 +10376,14 @@ def cmd_show_list(args):
_add_optional_arg(command, "--q", getattr(args, "query", None))
if getattr(args, "json", False):
command.append("--json")
- page_payload = pagination_payload(result, next_command=_next_command(command, result, include_all=bool(getattr(args, "all", False))))
- message = _pagination_message(page_payload)
payload = {
"ok": True,
"count": len(result.items),
"visibility": getattr(args, "visibility", None),
"pages": [show_page_payload(page) for page in result.items],
- "pagination": page_payload,
+ **_paginated_fields(result, command=command),
"url_guidance": avibe_cloud_connect_guidance(),
}
- if message:
- payload["message"] = message
if getattr(args, "json", False):
_print_json(payload)
else:
@@ -10881,24 +11002,33 @@ def cmd_show_marks(args):
event_store = ShowSessionEventStore()
try:
session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show marks --help")
+ page_request = _page_request_from_args(args, help_command="vibe show marks --help")
marks = [_show_mark_listing(mark) for mark in event_store.active_marks(session_id)]
+ page = page_sequence(marks, page_request)
+ command = ["vibe", "show", "marks", "--session-id", session_id]
+ if getattr(args, "json", False):
+ command.append("--json")
result = {
"ok": True,
"session_id": session_id,
- "count": len(marks),
- "marks": marks,
+ "count": len(page.items),
+ "marks": page.items,
+ **_paginated_fields(page, command=command),
**({"session_default_notice": session_default_notice} if session_default_notice else {}),
}
if getattr(args, "json", False):
_print_json(result)
else:
- print(f"Assistant marks ({len(marks)} active):")
- if not marks:
+ print(f"Assistant marks ({len(page.items)} shown):")
+ if not page.items:
print(" none")
- for mark in marks:
+ for mark in page.items:
print(f"- {mark['id']} {mark['kind']} {mark['read_state']}")
print(f" Target: {mark['target']}")
print(f" Body: {mark['body_head']}")
+ if result.get("message"):
+ print("")
+ print(result["message"])
return 0
except Exception as exc:
_print_show_page_error(exc)
@@ -11826,10 +11956,15 @@ def build_parser():
agent_subparsers.required = True
agent_list_parser = agent_subparsers.add_parser("list", help="List Avibe Agents")
- agent_list_parser.add_argument("--brief", action="store_true", help="Show compact Agent rows")
+ agent_list_parser.add_argument("--brief", action="store_true", help=argparse.SUPPRESS)
agent_list_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Filter by backend")
- agent_list_parser.add_argument("--all", action="store_true", help="Include disabled Agents")
+ agent_list_parser.add_argument(
+ "--include-disabled",
+ action="store_true",
+ help="Include disabled Agents while keeping pagination",
+ )
agent_list_parser.add_argument("--disabled", action="store_true", help="Show only disabled Agents")
+ _add_pagination_args(agent_list_parser, help_command="vibe agent list --help")
_add_json_noop(agent_list_parser)
agent_show_parser = agent_subparsers.add_parser("show", help="Show one Avibe Agent")
@@ -11861,6 +11996,7 @@ def build_parser():
"--provider", help="Filter to one OpenCode provider id (OpenCode backend only)."
)
agent_models_parser.add_argument("--model", help="Only show reasoning efforts for this model id.")
+ _add_pagination_args(agent_models_parser, help_command="vibe agent models --help")
_add_json_noop(agent_models_parser)
agent_create_parser = agent_subparsers.add_parser("create", help="Create an Avibe Agent")
@@ -12000,7 +12136,7 @@ def build_parser():
runs_list_parser.add_argument("--created-after", help="Filter by created_at >= timestamp, or relative value such as 6h or 7d")
runs_list_parser.add_argument("--created-before", help="Filter by created_at <= timestamp, or relative value such as 6h or 7d")
runs_list_parser.add_argument("--q", dest="query", help="Search common run text fields")
- runs_list_parser.add_argument("--brief", action="store_true", help="Show compact run rows")
+ runs_list_parser.add_argument("--brief", action="store_true", help=argparse.SUPPRESS)
_add_pagination_args(runs_list_parser, help_command="vibe runs list --help")
_add_json_noop(runs_list_parser)
runs_show_parser = runs_subparsers.add_parser("show", help="Show one Agent run")
@@ -12027,7 +12163,10 @@ def build_parser():
session_list_parser = session_subparsers.add_parser(
"list",
help="List active sessions, most-recently-active first",
- description="List active (non-archived) Agent sessions, 10 per page, newest activity first.",
+ description=(
+ f"List active (non-archived) Agent sessions, {DEFAULT_PAGE_LIMIT} per page, "
+ "newest activity first."
+ ),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe session list --help",
)
@@ -12035,7 +12174,7 @@ def build_parser():
"--type",
help="Filter by platform: avibe (Web/Workbench), slack, discord, telegram, lark, wechat.",
)
- session_list_parser.add_argument("--page", type=int, help="Page number to return (10 per page). Defaults to 1.")
+ _add_pagination_args(session_list_parser, help_command="vibe session list --help")
_add_json_noop(session_list_parser)
session_get_parser = session_subparsers.add_parser(
"get",
@@ -12550,6 +12689,7 @@ def build_parser():
error_help_command="vibe show marks --help",
)
show_marks_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")
+ _add_pagination_args(show_marks_parser, help_command="vibe show marks --help")
show_marks_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
show_unmark_parser = show_subparsers.add_parser(
@@ -12719,22 +12859,26 @@ def build_parser():
task_subparsers.add_parser(
"list",
help="List scheduled tasks",
- description="List stored scheduled tasks. Completed one-shot tasks are hidden unless --all is used.",
+ description=(
+ f"List stored scheduled tasks, {DEFAULT_PAGE_LIMIT} per page. Successful one-shot tasks are hidden by default; "
+ "use --include-finished to page through their history."
+ ),
epilog="Use the returned task IDs with 'vibe task show', 'vibe task update', 'vibe task run', 'vibe task pause', 'vibe task resume', or 'vibe task remove'.",
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe task list --help",
)
task_list_parser = task_subparsers.choices["list"]
task_list_parser.add_argument(
- "--all",
+ "--include-finished",
action="store_true",
- help="Include completed one-shot tasks that are hidden by default",
+ help="Include successful one-shot task history while keeping pagination",
)
task_list_parser.add_argument(
"--brief",
action="store_true",
- help="Show a compact scheduling-focused view instead of the full stored task payload",
+ help=argparse.SUPPRESS,
)
+ _add_pagination_args(task_list_parser, help_command="vibe task list --help")
_add_json_noop(task_list_parser)
_add_hidden_task_alias(task_subparsers, "ls", task_list_parser)
@@ -13017,16 +13161,25 @@ def build_parser():
watch_list_parser = watch_subparsers.add_parser(
"list",
help="List background watches",
- description="List stored managed background watches.",
+ description=(
+ f"List stored managed background watches, {DEFAULT_PAGE_LIMIT} per page. Successful one-shot watches are hidden "
+ "by default; use --include-finished to page through their history."
+ ),
epilog="Use the returned watch IDs with 'vibe watch show', 'vibe watch update', 'vibe watch pause', 'vibe watch resume', or 'vibe watch remove'.",
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe watch list --help",
)
+ watch_list_parser.add_argument(
+ "--include-finished",
+ action="store_true",
+ help="Include successful one-shot watch history while keeping pagination",
+ )
watch_list_parser.add_argument(
"--brief",
action="store_true",
- help="Show a compact watcher-focused view instead of the full stored watch payload",
+ help=argparse.SUPPRESS,
)
+ _add_pagination_args(watch_list_parser, help_command="vibe watch list --help")
_add_json_noop(watch_list_parser)
_add_hidden_task_alias(watch_subparsers, "ls", watch_list_parser)
@@ -13226,7 +13379,18 @@ def main():
if args.task_command == "update":
sys.exit(cmd_task_update(args))
if args.task_command in {"list", "ls"}:
- sys.exit(cmd_task_list(include_all=getattr(args, "all", False), brief=getattr(args, "brief", False)))
+ try:
+ page_request = _page_request_from_args(args, help_command="vibe task list --help")
+ except TaskCliError as exc:
+ _print_task_error(exc, help_command="vibe task list --help")
+ sys.exit(1)
+ sys.exit(
+ cmd_task_list(
+ include_finished=getattr(args, "include_finished", False),
+ brief=True,
+ page_request=page_request,
+ )
+ )
if args.task_command == "show":
sys.exit(cmd_task_show(args.task_id))
if args.task_command == "pause":
@@ -13248,7 +13412,18 @@ def main():
if args.watch_command == "update":
sys.exit(cmd_watch_update(args))
if args.watch_command in {"list", "ls"}:
- sys.exit(cmd_watch_list(brief=getattr(args, "brief", False)))
+ try:
+ page_request = _page_request_from_args(args, help_command="vibe watch list --help")
+ except TaskCliError as exc:
+ _print_task_error(exc, help_command="vibe watch list --help")
+ sys.exit(1)
+ sys.exit(
+ cmd_watch_list(
+ include_finished=getattr(args, "include_finished", False),
+ brief=True,
+ page_request=page_request,
+ )
+ )
if args.watch_command == "show":
sys.exit(cmd_watch_show(args.watch_id))
if args.watch_command == "pause":
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index d48b8a24a..ffe7f1425 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -13,6 +13,18 @@
"titleUntitled": "Fork"
},
"harness": {
+ "watch": {
+ "supervisorFailed": "Watch worker supervisor failed: {detail}",
+ "supervisorExitedDuringStartup": "Watch worker supervisor exited during startup.",
+ "unknownSupervisorFailure": "Unknown supervisor failure.",
+ "protocolErrors": {
+ "specTooLarge": "The watch worker specification is too large.",
+ "invalidEncoding": "The watch worker specification is not valid UTF-8.",
+ "invalidJson": "The watch worker specification is not valid JSON.",
+ "unsupportedVersion": "The watch worker specification version is unsupported.",
+ "invalidCommand": "The watch worker command is invalid."
+ }
+ },
"queueCoalesced": {
"summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.",
"messagesLabel": "Coalesced callback messages:",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 43a172ca3..a617acb6f 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -13,6 +13,18 @@
"titleUntitled": "复刻"
},
"harness": {
+ "watch": {
+ "supervisorFailed": "Watch 监控进程失败:{detail}",
+ "supervisorExitedDuringStartup": "Watch 监控进程在启动期间退出。",
+ "unknownSupervisorFailure": "未知的监控进程错误。",
+ "protocolErrors": {
+ "specTooLarge": "Watch 工作进程配置过大。",
+ "invalidEncoding": "Watch 工作进程配置不是有效的 UTF-8。",
+ "invalidJson": "Watch 工作进程配置不是有效的 JSON。",
+ "unsupportedVersion": "不支持此 Watch 工作进程配置版本。",
+ "invalidCommand": "Watch 工作进程命令无效。"
+ }
+ },
"queueCoalesced": {
"summary": "[Avibe Harness] 同一个 watch/task callback 在滚动 {window} 秒窗口内触发了 {count} 次。已将这些排队 callback 合并为一次 Agent turn。",
"messagesLabel": "已合并的 callback 消息:",