Merge origin/main: wire-contract registry + server→client requests + screenshot dedup
Main replaced every *.request/*.respond event pair with real JSON-RPC server→client requests and made Python the single source of the wire (tui_gateway/contracts → generated TS). Bot Screen now speaks that dialect: - tui_gateway/contracts/display.py declares the eight display.* methods, the display.install.sudo server request and the four display.* events; the generated TS/OpenRPC is regenerated. - The install sudo card is a `display.install.sudo` server request (app-level, empty session); the desktop answers it through respondToServerRequest, so the respondMethod/origin plumbing that pinned a reply to its socket is gone: a JSON-RPC response cannot land elsewhere. - screen-connection.ts consumes the generated DisplayStatus/DisplayLease instead of hand-typed copies (holder named by viewer_hash only; epoch always present). - computer_use: the lease fence and main's screenshot-dedup session key ride the same read handlers; the fence fires before a frame reaches the dedup cache. - server.py keeps the display module registration a naive --theirs would have dropped.
This commit is contained in:
commit
e4f591d1b0
1787 files changed
+100600
-14153
No files matched your search
@@ -58,6 +58,11 @@ jobs:
|
||||
emit-status:
|
||||
name: Emit review status
|
||||
runs-on: ubuntu-latest
|
||||
# Downloads one small SARIF artifact and runs two inline python snippets —
|
||||
# minutes of work. Bound it so a wedged artifact download can't hold a
|
||||
# runner for GitHub's 6-hour default (the only unbounded job left in
|
||||
# .github/workflows; every other workflow already sets timeout-minutes).
|
||||
timeout-minutes: 10
|
||||
needs: scan
|
||||
if: always()
|
||||
outputs:
|
||||
|
||||
@@ -126,12 +126,23 @@ jobs:
|
||||
fi
|
||||
|
||||
# Manifest schema + declared-vs-registered capability check.
|
||||
if hermes plugins validate "$PLUGIN_DIR"; then
|
||||
echo "✅ PASS: $entry"
|
||||
else
|
||||
if ! hermes plugins validate "$PLUGIN_DIR"; then
|
||||
echo "::error file=$entry::hermes plugins validate failed"
|
||||
FAILED=1
|
||||
FAILED=1; echo "::endgroup::"; continue
|
||||
fi
|
||||
|
||||
# SELF-UPDATER GATE (README rule 3): the pin is the only update path.
|
||||
# A desktop bundle that both fetches from GitHub AND writes/renames
|
||||
# plugin files is a self-updater; either half alone is fine (a
|
||||
# plugin may read the API, or manage its own data files).
|
||||
SELF_UPDATE=$(grep -rlE 'releases/latest|raw\.githubusercontent\.com' \
|
||||
--include='*.js' --include='*.mjs' --include='*.cjs' --include='*.ts' "$PLUGIN_DIR" \
|
||||
| xargs -r grep -lE 'writeTextFile|renamePath|writeFile\(' || true)
|
||||
if [ -n "$SELF_UPDATE" ]; then
|
||||
echo "::error file=$entry::self-updating code in catalog build (fetches GitHub AND writes plugin files): $SELF_UPDATE"
|
||||
FAILED=1; echo "::endgroup::"; continue
|
||||
fi
|
||||
echo "✅ PASS: $entry"
|
||||
echo "::endgroup::"
|
||||
done <<< "$CHANGED_FILES"
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ on:
|
||||
desktop_updater:
|
||||
description: >-
|
||||
Run the Windows desktop-update hand-off integration tests
|
||||
(tests/test_desktop_update_windows_*.py). These spawn the real
|
||||
(tests/scripts/desktop_update/test_desktop_update_windows_*.py). These spawn the real
|
||||
scripts/desktop-update/windows.ps1 and poll its loopback server, so
|
||||
they carry process-timing noise a shared runner amplifies; the
|
||||
caller gates them on the classifier's desktop_updater lane so a PR
|
||||
@@ -156,7 +156,7 @@ jobs:
|
||||
# an unbound-variable error, hence the ``${arr[@]+...}`` idiom.)
|
||||
EXTRA_ARGS=()
|
||||
if [ "${{ inputs.desktop_updater }}" != "true" ]; then
|
||||
echo "desktop_updater lane off: skipping tests/test_desktop_update_windows_*.py"
|
||||
echo "desktop_updater lane off: skipping tests/scripts/desktop_update/test_desktop_update_windows_*.py"
|
||||
EXTRA_ARGS+=(--ignore-glob='*test_desktop_update_windows_*.py')
|
||||
fi
|
||||
|
||||
|
||||
@@ -330,7 +330,12 @@ scripts/run_tests.sh -v --tb=long # pytest flags pass thro
|
||||
`HERMES_TEST_FILE_RETRIES=0` disables). Pass-on-retry is green but printed under `⚠ FLAKY`
|
||||
with both outputs — a bug to fix, not noise. Timing tests must not assume a quiet runner:
|
||||
wall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)` races.
|
||||
- **Placement:** `scripts/ci/classify_changes.py` picks jobs by changed files. A Python test
|
||||
- **Placement mirrors the source tree.** A test lives in `tests/<top-level source dir>/` (`tests/hermes_cli/`,
|
||||
`tests/agent/`, `tests/hermes_state/`, `tests/gateway/relay/`, ...); installer/updater script tests
|
||||
under `tests/scripts/{install,desktop_update}/`. Only tests of root-level modules (`batch_runner`,
|
||||
`utils`, `hermes_constants`, packaging) sit directly in `tests/`. No issue numbers in filenames —
|
||||
cite the issue in the module docstring (`test_89315_x.py` → `test_x.py`, "Regression for #89315").
|
||||
- **Placement (CI lanes):** `scripts/ci/classify_changes.py` picks jobs by changed files. A Python test
|
||||
asserting about `package.json`, `package-lock.json`, `tsconfig.json`, or `.ts/.tsx/.js/
|
||||
.mjs/.cjs` sources will not run on a JS-only PR (green on PR, red on `main` where the
|
||||
classifier fails open). Such tests belong in the vitest suite, not `tests/*.py`.
|
||||
|
||||
+6
-1
@@ -261,10 +261,15 @@ RUN cd plugins/platforms/photon/sidecar && \
|
||||
# avoids the cross-platform failures that kept [matrix] out of [all]
|
||||
# while still making Matrix work in the published container. Fixes #30399.
|
||||
#
|
||||
# Google Chat's [google-chat] extra (google-cloud-pubsub + Chat API clients)
|
||||
# is baked so hosted/immutable images can enable the adapter without writing
|
||||
# the sealed venv. Runtime --install-deps still routes through lazy_deps into
|
||||
# HERMES_LAZY_INSTALL_TARGET when the extra is not present.
|
||||
#
|
||||
# The editable link is created after the source copy below.
|
||||
COPY pyproject.toml uv.lock ./
|
||||
RUN touch ./README.md
|
||||
RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock --extra azure-identity --extra hindsight --extra matrix
|
||||
RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock --extra azure-identity --extra hindsight --extra matrix --extra google-chat
|
||||
|
||||
# ---------- Frontend build (cached independently from Python source) ----------
|
||||
# Copy only the frontend source trees first so that Python-only changes don't
|
||||
|
||||
+65
-7
@@ -8,6 +8,7 @@ thread-safely onto the loop.
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
from collections import deque
|
||||
from typing import Any, Callable, Deque, Dict
|
||||
|
||||
@@ -121,22 +122,79 @@ def make_tool_progress_cb(
|
||||
return _tool_progress
|
||||
|
||||
|
||||
def _make_text_cb(conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, wrap: Callable[[str], Any]) -> Callable:
|
||||
def _cb(text: str) -> None:
|
||||
# ------------------------------------------------------------------
|
||||
# Assistant message identity
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
|
||||
class AssistantMessageIdAllocator:
|
||||
"""Allocates stable per-message ids for streamed assistant chunks.
|
||||
|
||||
ACP clients group streamed ``agent_message_chunk`` / ``agent_thought_chunk``
|
||||
deltas into one assistant reply by ``messageId`` and use a NEW id to start
|
||||
the next reply (root-reply replacement semantics). Without ids, a client
|
||||
that replaces "the current assistant message" on each chunk collapses
|
||||
separate autonomous turns into one bubble.
|
||||
|
||||
One allocator lives per ACP session; a contiguous run of deltas shares
|
||||
``current()`` and ``close()`` marks the message finished so the next delta
|
||||
allocates a fresh id. Ids are UUID4 strings because the ACP schema requires
|
||||
UUID-format message ids, and a fresh UUID can never collide with an earlier
|
||||
turn's id.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._active: str | None = None
|
||||
self._last: str | None = None
|
||||
|
||||
def current(self) -> str:
|
||||
"""Return the active message id, allocating one if none is open."""
|
||||
if self._active is None:
|
||||
self._active = self._last = str(uuid.uuid4())
|
||||
return self._active
|
||||
|
||||
def last(self) -> str | None:
|
||||
"""Return the most recently allocated id (open or closed)."""
|
||||
return self._last
|
||||
|
||||
def close(self) -> None:
|
||||
"""End the active message; the next chunk starts a new id."""
|
||||
self._active = None
|
||||
|
||||
|
||||
def _make_text_cb(
|
||||
conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, wrap: Callable[[str], Any],
|
||||
message_ids: AssistantMessageIdAllocator | None = None,
|
||||
) -> Callable:
|
||||
# ``None`` is the flush sentinel Hermes core sends between assistant messages
|
||||
# (before tool execution / at end of stream): it closes the active messageId so
|
||||
# the next delta opens a new bubble instead of merging into the previous one.
|
||||
def _cb(text: str | None) -> None:
|
||||
if text:
|
||||
_send_update(conn, session_id, loop, wrap(text))
|
||||
update = wrap(text)
|
||||
if message_ids is not None:
|
||||
update.message_id = message_ids.current()
|
||||
_send_update(conn, session_id, loop, update)
|
||||
elif text is None and message_ids is not None:
|
||||
message_ids.close()
|
||||
|
||||
return _cb
|
||||
|
||||
|
||||
def make_thinking_cb(conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop) -> Callable:
|
||||
def make_thinking_cb(
|
||||
conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop,
|
||||
message_ids: AssistantMessageIdAllocator | None = None,
|
||||
) -> Callable:
|
||||
"""Create a ``thinking_callback`` for AIAgent."""
|
||||
return _make_text_cb(conn, session_id, loop, acp.update_agent_thought_text)
|
||||
return _make_text_cb(conn, session_id, loop, acp.update_agent_thought_text, message_ids)
|
||||
|
||||
|
||||
def make_message_cb(conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop) -> Callable:
|
||||
def make_message_cb(
|
||||
conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop,
|
||||
message_ids: AssistantMessageIdAllocator | None = None,
|
||||
) -> Callable:
|
||||
"""Create a callback that streams agent response text to the editor."""
|
||||
return _make_text_cb(conn, session_id, loop, acp.update_agent_message_text)
|
||||
return _make_text_cb(conn, session_id, loop, acp.update_agent_message_text, message_ids)
|
||||
|
||||
|
||||
def make_step_cb(
|
||||
|
||||
+19
-4
@@ -28,7 +28,8 @@ from acp_adapter.auth import TERMINAL_SETUP_AUTH_METHOD_ID, build_auth_methods,
|
||||
from acp_adapter.commands import HERMES_VERSION, SlashCommandsMixin, _estimate_tokens
|
||||
from acp_adapter.content import PromptBlock, _content_blocks_to_openai_user_content, _extract_text
|
||||
from acp_adapter.events import (
|
||||
_build_plan_update_from_todo_result, make_message_cb, make_step_cb, make_thinking_cb, make_tool_progress_cb,
|
||||
AssistantMessageIdAllocator, _build_plan_update_from_todo_result, make_message_cb, make_step_cb,
|
||||
make_thinking_cb, make_tool_progress_cb,
|
||||
)
|
||||
from acp_adapter.model_catalog import build_model_state, encode_model_choice
|
||||
from acp_adapter.permissions import make_approval_callback
|
||||
@@ -849,9 +850,14 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
|
||||
cbs.tool_progress_cb = make_tool_progress_cb(
|
||||
conn, session_id, loop, tool_call_ids, tool_call_meta, edit_approval_policy_getter=policy_getter
|
||||
)
|
||||
cbs.reasoning_cb = make_thinking_cb(conn, session_id, loop)
|
||||
# Per-session allocator: a new turn must never reuse a previous turn's
|
||||
# assistant messageId (ACP clients replace the bubble with that id).
|
||||
if state.message_ids is None:
|
||||
state.message_ids = AssistantMessageIdAllocator()
|
||||
state.message_ids.close() # new turn -> next chunk opens a fresh id
|
||||
cbs.reasoning_cb = make_thinking_cb(conn, session_id, loop, state.message_ids)
|
||||
cbs.step_cb = make_step_cb(conn, session_id, loop, tool_call_ids, tool_call_meta)
|
||||
message_cb = make_message_cb(conn, session_id, loop)
|
||||
message_cb = make_message_cb(conn, session_id, loop, state.message_ids)
|
||||
|
||||
def stream_delta_cb(text: str) -> None:
|
||||
cbs.streamed = cbs.streamed or bool(text)
|
||||
@@ -907,7 +913,16 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
|
||||
suppress = interrupted and final_response.startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX)
|
||||
# Send the final text unless already streamed — or if a plugin hook transformed it after.
|
||||
if final_response and conn and not suppress and (not streamed_message or result.get("response_transformed")):
|
||||
await conn.session_update(session_id, acp.update_agent_message_text(final_response))
|
||||
update = acp.update_agent_message_text(final_response)
|
||||
if state.message_ids is not None:
|
||||
# A plugin-rewritten reply replaces the streamed bubble (same id); an
|
||||
# unstreamed final response opens its own.
|
||||
if streamed_message and result.get("response_transformed"):
|
||||
update.message_id = state.message_ids.last() or state.message_ids.current()
|
||||
else:
|
||||
update.message_id = state.message_ids.current()
|
||||
state.message_ids.close()
|
||||
await conn.session_update(session_id, update)
|
||||
|
||||
# Go idle before draining so recursive prompt() calls can acquire the session.
|
||||
with state.runtime_lock:
|
||||
|
||||
+10
-5
@@ -143,6 +143,9 @@ class SessionState:
|
||||
runtime_lock: Any = field(default_factory=threading.Lock)
|
||||
current_prompt_text: str = ""
|
||||
interrupted_prompt_text: str = ""
|
||||
# Per-session allocator for ACP assistant messageIds (lazily created by
|
||||
# the server so streamed chunks group into distinct assistant replies).
|
||||
message_ids: Any = None
|
||||
|
||||
|
||||
class SessionManager:
|
||||
@@ -266,13 +269,15 @@ class SessionManager:
|
||||
return state
|
||||
|
||||
def _get_db(self):
|
||||
"""Lazily initialise the SessionDB; ``None`` if unavailable (e.g. import error in a
|
||||
minimal test env). ``HERMES_HOME`` is resolved here, not via the import-time
|
||||
``DEFAULT_DB_PATH``, so test fixtures that change the env var later are honoured."""
|
||||
"""Lazily acquire the process-shared SessionDB; ``None`` if unavailable (e.g. import
|
||||
error in a minimal test env). ``HERMES_HOME`` is resolved here, not via the import-time
|
||||
``DEFAULT_DB_PATH``, so test fixtures that change the env var later are honoured. The
|
||||
registry handle is the one in-process tools (delegation, session_search, goals) also
|
||||
acquire, so the ACP server holds ONE writer on state.db instead of two (#100896)."""
|
||||
if self._db_instance is None:
|
||||
try:
|
||||
from hermes_state import SessionDB
|
||||
self._db_instance = SessionDB(db_path=get_hermes_home() / "state.db")
|
||||
from hermes_state_registry import acquire
|
||||
self._db_instance = acquire(get_hermes_home() / "state.db")
|
||||
except Exception:
|
||||
logger.debug("SessionDB unavailable for ACP persistence", exc_info=True)
|
||||
return self._db_instance
|
||||
|
||||
@@ -49,7 +49,7 @@ class ActivityTrackingMixin:
|
||||
kanban heartbeat when this is a dispatcher-spawned worker, and to the durable SessionDB activity
|
||||
projection. ``provenance`` names special writers (compression); ``force_persist`` bypasses the
|
||||
SessionDB rate limit. Module-level lock helper, not ``self._liveness_activity_lock()``: doubles bind
|
||||
only ``_touch_activity`` (tests/run_agent/test_session_activity_persist.py).
|
||||
only ``_touch_activity`` (tests/agent/test_session_activity_persist.py).
|
||||
|
||||
Bridge is rate-limited (60s) and best-effort — it never raises into the agent loop. See #31752.
|
||||
See #72016, #72039.
|
||||
|
||||
+6
-7
@@ -877,20 +877,19 @@ def _routed_client_kwargs(agent, fallback_model, _provider_timeout) -> Dict[str,
|
||||
)
|
||||
|
||||
|
||||
_FINE_GRAINED_BETA = "fine-grained-tool-streaming-2025-05-14"
|
||||
|
||||
|
||||
def _apply_openai_header_policy(agent, client_kwargs: Dict[str, Any]) -> None:
|
||||
"""Mutate ``client_kwargs`` (== ``agent._client_kwargs``) with header/TLS policy, in order:
|
||||
OpenRouter Claude beta header → model.default_headers → custom-provider TLS/extra_headers."""
|
||||
# Fine-grained tool streaming for Claude on OpenRouter: without the beta header
|
||||
# Anthropic buffers the whole tool call and OpenRouter's proxy times out.
|
||||
from agent.anthropic_adapter import _TOOL_STREAMING_BETA
|
||||
|
||||
_effective_base = str(client_kwargs.get("base_url", "")).lower()
|
||||
if base_url_host_matches(_effective_base, "openrouter.ai") and "claude" in (agent.model or "").lower():
|
||||
headers = client_kwargs.get("default_headers") or {}
|
||||
existing_beta = headers.get("x-anthropic-beta", "")
|
||||
if _FINE_GRAINED_BETA not in existing_beta:
|
||||
headers["x-anthropic-beta"] = ",".join(filter(None, (existing_beta, _FINE_GRAINED_BETA)))
|
||||
if _TOOL_STREAMING_BETA not in existing_beta:
|
||||
headers["x-anthropic-beta"] = ",".join(filter(None, (existing_beta, _TOOL_STREAMING_BETA)))
|
||||
client_kwargs["default_headers"] = headers
|
||||
# model.default_headers override provider/SDK defaults (WAFs rejecting SDK headers).
|
||||
agent._apply_user_default_headers()
|
||||
@@ -2163,7 +2162,7 @@ _CALLBACK_PARAMS = (
|
||||
"tool_progress_callback", "tool_start_callback", "tool_complete_callback",
|
||||
"thinking_callback", "reasoning_callback", "clarify_callback",
|
||||
"read_terminal_callback", "read_preview_callback", "drive_preview_callback",
|
||||
"read_window_below_callback", "setup_mcp_callback", "tour_callback",
|
||||
"read_window_below_callback", "connection_callback", "tour_callback",
|
||||
"step_callback", "stream_delta_callback", "interim_assistant_callback",
|
||||
"status_callback", "notice_callback", "notice_clear_callback",
|
||||
"event_callback", "reaction_callback", "tool_gen_callback",
|
||||
@@ -2186,7 +2185,7 @@ def init_agent(
|
||||
thinking_callback: callable = None, reasoning_callback: callable = None,
|
||||
clarify_callback: callable = None, read_terminal_callback: callable = None,
|
||||
read_preview_callback: callable = None, drive_preview_callback: callable = None,
|
||||
read_window_below_callback: callable = None, setup_mcp_callback: callable = None,
|
||||
read_window_below_callback: callable = None, connection_callback: callable = None,
|
||||
tour_callback: callable = None, step_callback: callable = None,
|
||||
stream_delta_callback: callable = None, interim_assistant_callback: callable = None,
|
||||
tool_gen_callback: callable = None, status_callback: callable = None,
|
||||
|
||||
@@ -79,7 +79,8 @@ def _ra():
|
||||
|
||||
AGENT_RUNTIME_POST_HOOK_TOOL_NAMES = frozenset({
|
||||
"todo_list", "session_search", "memory", "clarify", "read_terminal", "desktop_preview",
|
||||
"drive_preview", "annotate_preview", "read_window_below", "setup_mcp", "gui_tour", "delegate_task",
|
||||
"drive_preview", "annotate_preview", "read_window_below", "manage_connections", "setup_mcp", "gui_tour",
|
||||
"delegate_task",
|
||||
})
|
||||
|
||||
_TRAJECTORY_SYSTEM_PROMPT = (
|
||||
@@ -1735,7 +1736,7 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo
|
||||
return client
|
||||
# TCP keepalives so dead provider connections are detected (~60s) instead of hanging in
|
||||
# CLOSE-WAIT. Injected into the local copy only, so each client gets its own httpx.Client;
|
||||
# pinned by tests/run_agent/test_create_openai_client_reuse.py and
|
||||
# pinned by tests/agent/test_create_openai_client_reuse.py and
|
||||
# test_sequential_chats_live.py. What IS shared across those per-client wrappers is the
|
||||
# connection pool: ``build_keepalive_http_client`` mounts a process-shared ``HTTPTransport``
|
||||
# behind a per-client view whose ``close()`` is a no-op for the pool, so a closed wrapper
|
||||
@@ -2320,7 +2321,7 @@ def repair_tool_call(agent, tool_name: str) -> str | None:
|
||||
# character so the rest of the repair pipeline (lowercase / snake_case / fuzzy match) can resolve the
|
||||
# cleaned name to a real tool. Crucially we DO NOT split on whitespace: legitimate inputs like "write
|
||||
# file" must keep flowing through ``_norm`` -> ``write_file`` (covered by test_space_to_underscore in
|
||||
# tests/run_agent/test_repair_tool_call_name.py). See #33007.
|
||||
# tests/agent/test_repair_tool_call_name.py). See #33007.
|
||||
for _xml_sep in ('"', "'", "<", ">"):
|
||||
_idx = tool_name.find(_xml_sep)
|
||||
if _idx > 0:
|
||||
|
||||
@@ -624,6 +624,21 @@ def sanitize_anthropic_kwargs(api_kwargs: Any, *, log_prefix: str = "") -> Any:
|
||||
return api_kwargs
|
||||
|
||||
|
||||
def buffer_anthropic_tool_input(api_kwargs: dict[str, Any], base_url: str | None) -> None:
|
||||
"""Retry knob for a malformed fine-grained tool-JSON stream (#107830): the beta streams tool
|
||||
args unvalidated, so a model that emits ``{"names": cronjob_manage}`` breaks the SDK parser
|
||||
and an identical retry breaks identically. ``eager_input_streaming: false`` per tool restores
|
||||
Anthropic's buffered, validated args for the rest of this turn (the flag lives on the turn's
|
||||
kwargs, so a later retry of the same turn keeps it; the changed ``tools`` block costs one
|
||||
prompt-cache miss, cheaper than a dead turn). Off the happy path on purpose:
|
||||
buffering a large payload is a zero-event gap the stale-stream detector kills. No-op on
|
||||
endpoints that never get the beta (MiniMax) rather than sending them an unknown field."""
|
||||
if _TOOL_STREAMING_BETA not in _common_betas_for_base_url(base_url):
|
||||
return
|
||||
for tool in api_kwargs.get("tools") or ():
|
||||
tool["eager_input_streaming"] = False
|
||||
|
||||
|
||||
def _is_stream_unavailable_error(exc: Exception) -> bool:
|
||||
"""True when an Anthropic stream call should fall back to create()."""
|
||||
err_lower = str(exc).lower()
|
||||
|
||||
@@ -10,6 +10,11 @@ from typing import Any, Dict, Optional
|
||||
|
||||
from agent.redact import redact_sensitive_text
|
||||
|
||||
# Substrings of the plain ``ValueError`` the Anthropic SDK raises for a malformed event-stream
|
||||
# frame (wire trouble, not local validation). Read by ``AIAgent._is_provider_stream_parse_error``.
|
||||
PROVIDER_STREAM_PARSE_MARKERS = ("expected ident at line", "expected value at line")
|
||||
|
||||
|
||||
# Offline DNS failures are wrapped in a generic "Connection error" by SDKs — inspect the chain.
|
||||
_NETWORK_RESOLUTION_MARKERS = (
|
||||
"temporary failure in name resolution",
|
||||
@@ -142,7 +147,7 @@ class ApiErrorSummaryMixin:
|
||||
)
|
||||
current = current.__cause__ or current.__context__
|
||||
|
||||
if isinstance(error, ValueError) and "expected ident at line" in raw.lower():
|
||||
if isinstance(error, ValueError) and any(marker in raw.lower() for marker in PROVIDER_STREAM_PARSE_MARKERS):
|
||||
return f"Malformed provider streaming response: {raw[:300]}"
|
||||
|
||||
prefix = _http_prefix(error)
|
||||
|
||||
@@ -4548,7 +4548,17 @@ def _wrap_transport(req: _ResolveRequest, client_obj: Any, final_model_str: str,
|
||||
"(api_mode=%s, model=%s, base_url=%s)",
|
||||
req.api_mode or "auto-detected", final_model_str, base_url_str[:60] if base_url_str else "")
|
||||
return CodexAuxiliaryClient(client_obj, final_model_str)
|
||||
return _maybe_wrap_anthropic(client_obj, final_model_str, api_key_str, base_url_str, req.api_mode)
|
||||
# A profile that declares the Messages wire (commandcode-anthropic) is on it whatever the URL
|
||||
# looks like; the same declaration gates ``_reasoning_config`` in _build_call_kwargs.
|
||||
api_mode = req.api_mode or _profile_declared_messages_wire(req.provider)
|
||||
return _maybe_wrap_anthropic(client_obj, final_model_str, api_key_str, base_url_str, api_mode)
|
||||
|
||||
|
||||
def _profile_declared_messages_wire(provider: str) -> Optional[str]:
|
||||
"""``"anthropic_messages"`` when the registered profile declares that api_mode, else None."""
|
||||
from providers import get_provider_profile
|
||||
profile = get_provider_profile(str(provider or "").strip().lower())
|
||||
return "anthropic_messages" if profile is not None and profile.api_mode == "anthropic_messages" else None
|
||||
|
||||
|
||||
def _route_client(req: _ResolveRequest, client_obj: Any, final_model_str: Optional[str]) -> _ResolveResult:
|
||||
@@ -5559,6 +5569,13 @@ def _get_cached_client(
|
||||
provider, model, async_mode, explicit_base_url=base_url, explicit_api_key=effective_api_key,
|
||||
api_mode=api_mode, main_runtime=runtime, is_vision=is_vision, task=task,
|
||||
)
|
||||
if client is not None and _aux_probe_active():
|
||||
# Availability probes answer "resolvable?" and must leave the cache untouched: the
|
||||
# probe stub (bare, or wrapped in a Codex/Anthropic adapter whose leaf is the stub)
|
||||
# shares the runtime key, and a cached one is served to every later caller — the
|
||||
# next probe dies in _compat_model() on stub attribute access, so check_fns flip to
|
||||
# False and vision tools vanish for the process lifetime (#87654).
|
||||
return client, model or default_model
|
||||
if client is not None:
|
||||
with _client_cache_lock:
|
||||
if cache_key not in _client_cache:
|
||||
@@ -6052,6 +6069,7 @@ class _ProfileProjection(NamedTuple):
|
||||
reasoning_extra: Dict[str, Any]
|
||||
top_level: Dict[str, Any]
|
||||
handles_reasoning: bool
|
||||
messages_wire: bool = False
|
||||
|
||||
|
||||
def _project_provider_profile(
|
||||
@@ -6062,11 +6080,13 @@ def _project_provider_profile(
|
||||
reasoning_extra: Dict[str, Any] = {}
|
||||
top_level: Dict[str, Any] = {}
|
||||
handles_reasoning = False
|
||||
messages_wire = False
|
||||
try:
|
||||
from providers import get_provider_profile
|
||||
from providers.base import ProviderProfile
|
||||
profile = get_provider_profile(provider_norm)
|
||||
if profile is not None:
|
||||
messages_wire = profile.api_mode == "anthropic_messages"
|
||||
body = profile.build_extra_body(model=model, base_url=effective_base, reasoning_config=reasoning_config) or {}
|
||||
reasoning_extra, top_level = profile.build_api_kwargs_extras(
|
||||
reasoning_config=reasoning_config, supports_reasoning=reasoning_config is not None,
|
||||
@@ -6082,7 +6102,7 @@ def _project_provider_profile(
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug("_build_call_kwargs: provider profile projection failed for %s: %s", provider, exc)
|
||||
return _ProfileProjection(body, reasoning_extra, top_level, handles_reasoning)
|
||||
return _ProfileProjection(body, reasoning_extra, top_level, handles_reasoning, messages_wire)
|
||||
|
||||
|
||||
def _merge_aux_extra_body(
|
||||
@@ -6148,11 +6168,14 @@ def _build_call_kwargs(
|
||||
kwargs["extra_body"] = merged_extra
|
||||
# Anthropic Messages adapters take reasoning via a private kwarg that plain OpenAI SDK clients
|
||||
# would reject; Portal Claude is dual-wire, so include it only when the catalog id selects
|
||||
# /v1/messages.
|
||||
# /v1/messages. A profile declaring api_mode=anthropic_messages (commandcode-anthropic) is on
|
||||
# that wire regardless of URL shape — once it overrides build_api_kwargs_extras the generic
|
||||
# ``extra_body.reasoning`` fallback the adapter used to read is gone, so this is the adapter's
|
||||
# only path. _wrap_transport wraps such providers on the same declaration.
|
||||
if reasoning_config and isinstance(reasoning_config, dict):
|
||||
raw_base = base_url or ""
|
||||
if (
|
||||
provider_norm == "anthropic" or _nous_on_messages_wire(provider_norm, model)
|
||||
provider_norm == "anthropic" or projection.messages_wire or _nous_on_messages_wire(provider_norm, model)
|
||||
or _endpoint_speaks_anthropic_messages(raw_base) or _is_anthropic_compat_endpoint(provider_norm, raw_base)
|
||||
):
|
||||
kwargs["_reasoning_config"] = dict(reasoning_config)
|
||||
|
||||
@@ -16,6 +16,7 @@ from contextlib import contextmanager, suppress
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
||||
|
||||
from agent.prompt_cache_scope import resolve_prompt_cache_scope_safe
|
||||
from agent.thread_scoped_output import thread_scoped_silence
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -789,6 +790,30 @@ def _same_model_parity_kwargs(agent: Any) -> Dict[str, Any]:
|
||||
return kwargs
|
||||
|
||||
|
||||
def _warn_ignored_reasoning_effort(agent: Any, task_cfg: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""One-shot user-visible notice: ``auxiliary.background_review.reasoning_effort`` is IGNORED on
|
||||
the same-model path (#104116). The fork inherits the parent's ``reasoning_config`` verbatim so
|
||||
its request bytes keep the parent's prompt-cache prefix (#30532: a diverged ``thinking`` field
|
||||
on the fork-birth request re-created a large share of the cache); the no-op used to be silent,
|
||||
so a user who set the key saw no feedback at all. Gated on the parent so a nudge-per-turn
|
||||
session warns once, not per fork."""
|
||||
effort = str(_background_review_task_config(task_cfg).get("reasoning_effort") or "").strip()
|
||||
if not effort or getattr(agent, "_warned_bg_review_reasoning_effort", False):
|
||||
return
|
||||
agent._warned_bg_review_reasoning_effort = True
|
||||
message = (
|
||||
f"⚠ auxiliary.background_review.reasoning_effort='{effort}' has no effect while the review "
|
||||
"runs on the main model: the fork inherits the conversation's reasoning effort to keep the "
|
||||
"parent's prompt-cache prefix (see memory docs, same-model review reasoning). Route the "
|
||||
"review elsewhere via auxiliary.background_review.provider/model to use a different effort."
|
||||
)
|
||||
emit = getattr(agent, "_emit_warning", None)
|
||||
if callable(emit):
|
||||
with suppress(Exception):
|
||||
emit(message)
|
||||
logger.warning("%s", message)
|
||||
|
||||
|
||||
def _detach_fork_compression(review_agent: Any) -> None:
|
||||
"""Detached in-memory compaction for a fork sharing the parent's session_id. Disabling
|
||||
compression (the old guard against compacting the parent's live session) removed the only
|
||||
@@ -820,7 +845,27 @@ def _detach_fork_compression(review_agent: Any) -> None:
|
||||
review_agent._review_defer_compaction_before_first_response = True
|
||||
|
||||
|
||||
def _fork_init_kwargs(agent: Any, rt: Dict[str, Any], routed: bool, max_iterations: int) -> Dict[str, Any]:
|
||||
def _routed_reasoning_config(task_cfg: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""``reasoning_config`` for a ROUTED fork from ``auxiliary.background_review.reasoning_effort``
|
||||
(#94825). The routed branch never inherits the parent's effort (its vocabulary may be invalid for
|
||||
the routed provider), but an explicit per-task pin is the user's choice for THAT model and must
|
||||
win over provider defaults, as every other aux task already does via ``_get_task_extra_body``.
|
||||
None = unset (provider default); an unknown level warns and falls through to the default."""
|
||||
effort = _background_review_task_config(task_cfg).get("reasoning_effort")
|
||||
if effort is None or effort == "":
|
||||
return None
|
||||
from hermes_constants import VALID_REASONING_EFFORTS, parse_reasoning_effort
|
||||
parsed = parse_reasoning_effort(effort)
|
||||
if parsed is None:
|
||||
logger.warning(
|
||||
"auxiliary.background_review.reasoning_effort %r is not a valid level (none, %s) — using "
|
||||
"the routed provider's default", effort, ", ".join(VALID_REASONING_EFFORTS),
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def _fork_init_kwargs(agent: Any, rt: Dict[str, Any], routed: bool, max_iterations: int,
|
||||
task_cfg: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
"""AIAgent constructor kwargs for the review fork. skip_memory=True: an external memory plugin
|
||||
scoped to the parent's session_id would leak the harness prompt into the user's real memory
|
||||
namespace; built-in MEMORY.md/USER.md state is re-bound by the caller. Toolsets match the
|
||||
@@ -841,6 +886,8 @@ def _fork_init_kwargs(agent: Any, rt: Dict[str, Any], routed: bool, max_iteratio
|
||||
kwargs.update(acp_command=rt["command"], acp_args=rt.get("args") or [])
|
||||
if not routed:
|
||||
kwargs.update(_same_model_parity_kwargs(agent))
|
||||
elif (routed_cfg := _routed_reasoning_config(task_cfg)) is not None:
|
||||
kwargs["reasoning_config"] = routed_cfg
|
||||
return kwargs
|
||||
|
||||
|
||||
@@ -877,7 +924,12 @@ def build_cache_parity_fork(
|
||||
# OAuth-only providers, session-scoped creds and credential pools.
|
||||
_rt = _resolve_review_runtime(agent, task_cfg)
|
||||
_routed = bool(_rt.get("routed"))
|
||||
review_agent = AIAgent(**_fork_init_kwargs(agent, _rt, _routed, max_iterations))
|
||||
# A configured effort is dropped on the same-model path (cache parity) — say so once, visible,
|
||||
# instead of leaving the set-but-ignored key invisible (#104116). Routed forks honor it
|
||||
# (_routed_reasoning_config).
|
||||
if not _routed and write_origin == "background_review":
|
||||
_warn_ignored_reasoning_effort(agent, task_cfg)
|
||||
review_agent = AIAgent(**_fork_init_kwargs(agent, _rt, _routed, max_iterations, task_cfg))
|
||||
review_agent._memory_write_origin = review_agent._memory_write_context = write_origin
|
||||
review_agent._memory_store = agent._memory_store
|
||||
review_agent._memory_enabled = agent._memory_enabled
|
||||
@@ -906,6 +958,22 @@ def build_cache_parity_fork(
|
||||
if not _routed:
|
||||
review_agent._cached_system_prompt = agent._cached_system_prompt
|
||||
review_agent.session_start = agent.session_start
|
||||
# Cache-scope parity (#109964): the fork shares the parent's physical session_id and
|
||||
# byte-identical prefix, but is _persist_disabled (declared scope fails closed) and
|
||||
# _session_db=None (lineage walk skipped) — so BOTH cache-identity resolvers keyed it
|
||||
# into a different bucket than the gateway parent, costing one cold ~full-context
|
||||
# request per review. Inherit the parent's ALREADY-RESOLVED scope once, here: no DB
|
||||
# access from the fork, persistence stays fully detached, and both consumers (the
|
||||
# affinity header via set_affinity_scope and the body prompt_cache_key via
|
||||
# cache_scope_id) resolve the parent's bucket together. Routed (different-model)
|
||||
# forks do NOT inherit: their prefix is cache-cold anyway.
|
||||
inherited_scope = resolve_prompt_cache_scope_safe(agent)
|
||||
if inherited_scope:
|
||||
review_agent._inherited_cache_scope = inherited_scope
|
||||
# Same reason for the Portal ``conversation=`` tag: with no DB the fork's own
|
||||
# _conversation_root_id() falls back to the parent's PHYSICAL id, so after a compression
|
||||
# rotation the review's usage was attributed to a different conversation than its parent.
|
||||
review_agent._cached_conversation_root = agent._conversation_root_id()
|
||||
_inherit_parent_tool_surface(review_agent, agent)
|
||||
_detach_fork_compression(review_agent)
|
||||
# Compaction bounds a single request; this bounds the WHOLE review (checked in
|
||||
|
||||
@@ -37,8 +37,11 @@ from agent.gemini_native_adapter import is_native_gemini_base_url
|
||||
from agent.model_metadata import is_local_endpoint
|
||||
from agent.message_content import flatten_message_text
|
||||
from agent.message_metadata import append_message, stamp_message_timestamp
|
||||
from agent.message_sanitization import (_sanitize_surrogates, _repair_tool_call_arguments)
|
||||
from agent.reasoning_summaries import separate_glued_reasoning_blocks
|
||||
from agent.message_sanitization import (
|
||||
_sanitize_surrogates, _repair_tool_call_arguments, normalize_finish_reason as _normalize_finish_reason,
|
||||
sanitize_outbound_kwargs,
|
||||
)
|
||||
from agent.reasoning_summaries import append_streamed_reasoning_detail, separate_glued_reasoning_blocks
|
||||
from agent.stream_single_writer import claim_stream_writer, stream_writer_is_current
|
||||
from tools.terminal_tool_lifecycle import is_persistent_env
|
||||
from utils import base_url_host_matches, base_url_hostname, env_float, env_int
|
||||
@@ -2009,66 +2012,13 @@ def _managed_summary_call(agent, api_request_id: str, request, callback, *, retr
|
||||
)
|
||||
|
||||
|
||||
def _iteration_summary_chat_kwargs(agent, api_messages: list) -> dict:
|
||||
"""chat.completions.create kwargs for the summary, mirroring ChatCompletionsTransport.build_kwargs()."""
|
||||
try:
|
||||
from agent.auxiliary_client import _fixed_temperature_for_model, OMIT_TEMPERATURE as _OMIT_TEMP
|
||||
except Exception:
|
||||
_fixed_temperature_for_model = _OMIT_TEMP = None
|
||||
raw_temp = _fixed_temperature_for_model(agent.model, agent.base_url) if _fixed_temperature_for_model is not None else None
|
||||
temperature = None if raw_temp is _OMIT_TEMP else raw_temp
|
||||
provider_name = (agent.provider or "").strip().lower()
|
||||
# LM Studio uses top-level `reasoning_effort` (not extra_body.reasoning).
|
||||
is_lmstudio = provider_name == "lmstudio" and agent._supports_reasoning_extra_body()
|
||||
lm_reasoning_effort = agent._resolve_lmstudio_summary_reasoning_effort() if is_lmstudio else None
|
||||
|
||||
extra_body = {}
|
||||
if not is_lmstudio and agent._supports_reasoning_extra_body():
|
||||
extra_body["reasoning"] = agent.reasoning_config if agent.reasoning_config is not None else {"enabled": True, "effort": "medium"}
|
||||
if "nousresearch" in agent._base_url_lower:
|
||||
from agent.portal_tags import nous_portal_tags
|
||||
extra_body["tags"] = nous_portal_tags()
|
||||
|
||||
summary_kwargs = {"model": agent.model, "messages": api_messages}
|
||||
if temperature is not None:
|
||||
summary_kwargs["temperature"] = temperature
|
||||
if agent.max_tokens is not None:
|
||||
summary_kwargs.update(agent._max_tokens_param(agent.max_tokens))
|
||||
if lm_reasoning_effort is not None:
|
||||
summary_kwargs["reasoning_effort"] = lm_reasoning_effort
|
||||
|
||||
# Merge the profile's canonical body even when routing is unset (e.g. required Portal tags).
|
||||
provider_preferences = _provider_preferences_for_agent(agent)
|
||||
profile_extra_body = {}
|
||||
with contextlib.suppress(Exception):
|
||||
from providers import get_provider_profile
|
||||
provider_profile = get_provider_profile(agent.provider)
|
||||
if provider_profile is not None:
|
||||
profile_extra_body = provider_profile.build_extra_body(
|
||||
session_id=getattr(agent, "session_id", None), provider_preferences=provider_preferences or None,
|
||||
model=agent.model, base_url=agent.base_url, reasoning_config=agent.reasoning_config)
|
||||
if profile_extra_body:
|
||||
extra_body.update(profile_extra_body)
|
||||
|
||||
def _is_openrouter() -> bool:
|
||||
return provider_name == "openrouter" or agent._is_openrouter_url()
|
||||
|
||||
if provider_preferences and "provider" not in profile_extra_body and _is_openrouter():
|
||||
extra_body["provider"] = provider_preferences
|
||||
# Pareto Code router plugin — model-gated, same shape as the main-loop emission.
|
||||
_score = agent.openrouter_min_coding_score
|
||||
if agent.model == "openrouter/pareto-code" and _is_openrouter() and _score is not None and _score != "":
|
||||
with contextlib.suppress(TypeError, ValueError):
|
||||
_ps = float(_score)
|
||||
if 0.0 <= _ps <= 1.0:
|
||||
extra_body["plugins"] = [{"id": "pareto-router", "min_coding_score": _ps}]
|
||||
if extra_body:
|
||||
summary_kwargs["extra_body"] = extra_body
|
||||
return summary_kwargs
|
||||
|
||||
|
||||
def _summary_text(agent, response, **normalize_kwargs) -> str:
|
||||
return (agent._get_transport().normalize_response(response, **normalize_kwargs).content or "").strip()
|
||||
normalized = agent._get_transport().normalize_response(response, **normalize_kwargs)
|
||||
if normalized.tool_calls:
|
||||
# No summary path executes tool calls; log so a tool-only response that falls into the
|
||||
# empty-summary retry is diagnosable.
|
||||
logger.warning("Iteration summary emitted tool calls; discarding them")
|
||||
return (normalized.content or "").strip()
|
||||
|
||||
|
||||
def _codex_summary_attempt(agent, api_messages: list, api_request_id: str):
|
||||
@@ -2096,7 +2046,14 @@ def _anthropic_summary_attempt(agent, api_messages: list, api_request_id: str):
|
||||
|
||||
|
||||
def _chat_summary_attempt(agent, api_messages: list, api_request_id: str):
|
||||
summary_kwargs = _iteration_summary_chat_kwargs(agent, api_messages)
|
||||
# Same kwargs builder as the main loop so the summary keeps the cached prefix (tools,
|
||||
# prompt_cache_key, xAI alias, Moonshot sanitization). Do not omit tools or force
|
||||
# tool_choice="none" here: SGLang renders the prompt with tools=None in that mode and the KV
|
||||
# prefix diverges. (cache_control breakpoint decoration is not re-applied on this path.)
|
||||
summary_kwargs = agent._build_api_kwargs(api_messages)
|
||||
# The summary now carries ``tools``; on cache-planned routes the main loop scrubbed a deep
|
||||
# copy, so ``agent.tools`` may still hold bytes the provider 400s on.
|
||||
sanitize_outbound_kwargs(agent, summary_kwargs)
|
||||
|
||||
def _attempt(retry_count: int) -> str:
|
||||
summary_client = agent._ensure_primary_openai_client(reason="iteration_limit_summary_retry" if retry_count else "iteration_limit_summary")
|
||||
@@ -2582,6 +2539,9 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
self.stream_attempt_state["current"] += 1
|
||||
attempt_id = int(self.stream_attempt_state["current"])
|
||||
self.provider_tool_in_flight["yes"] = False
|
||||
# Attempt-local like provider_tool_in_flight: a tool name from a stream that died
|
||||
# before any text must not label a later attempt's partial stub or its retry decision.
|
||||
self.result["partial_tool_names"] = []
|
||||
return attempt_id
|
||||
|
||||
def _cancel_current_stream_attempt(self, reason: str) -> None:
|
||||
@@ -2768,6 +2728,7 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
base_timeout, read_timeout, conn_cap = self._stream_timeouts()
|
||||
content_parts: list = []
|
||||
reasoning_parts: list = []
|
||||
reasoning_details: list = [] # OpenRouter replay data (signatures, encrypted blocks)
|
||||
pending_text_parts: list[str] = []
|
||||
tool_calls = _ToolCallAccumulator()
|
||||
tool_calls_acc = tool_calls.acc
|
||||
@@ -2831,7 +2792,7 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
delta = choice.delta
|
||||
# Read finish_reason/usage BEFORE any content-shape `continue`: the SSE-echo
|
||||
# guard can swallow a merged finish chunk (vLLM standalone ':' tokens).
|
||||
finish_reason = getattr(choice, "finish_reason", None) or finish_reason
|
||||
finish_reason = _normalize_finish_reason(getattr(choice, "finish_reason", None)) or finish_reason
|
||||
if hasattr(chunk, "usage") and chunk.usage:
|
||||
usage_obj = chunk.usage
|
||||
|
||||
@@ -2842,6 +2803,15 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
reasoning_parts[-1] if reasoning_parts else "", reasoning_text)
|
||||
reasoning_parts.append(reasoning_text)
|
||||
self._emit_reasoning(reasoning_text)
|
||||
# Structured reasoning_details deltas carry the provider's replay data; the
|
||||
# non-streaming path already keeps them, so dropping them here lost
|
||||
# reasoning continuity on nearly every turn. Pydantic parks unknown fields
|
||||
# in ``model_extra``.
|
||||
rd_delta = getattr(delta, "reasoning_details", None)
|
||||
if rd_delta is None and isinstance(getattr(delta, "model_extra", None), dict):
|
||||
rd_delta = delta.model_extra.get("reasoning_details")
|
||||
for rd in rd_delta if isinstance(rd_delta, (list, tuple)) else ():
|
||||
append_streamed_reasoning_detail(reasoning_details, rd)
|
||||
|
||||
# Text (list-of-blocks deltas flattened once); possible echoed SSE is
|
||||
# buffered until it can be judged.
|
||||
@@ -2877,7 +2847,7 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
return self._adopt_final_response(stream.final_response)
|
||||
return self._finish_chat_stream(stream, role, content_parts, reasoning_parts, tool_calls_acc,
|
||||
finish_reason, model_name, usage_obj, flush_pending=_flush_pending_stream_text,
|
||||
response_id=response_id, upstream_provider=upstream_provider)
|
||||
response_id=response_id, upstream_provider=upstream_provider, reasoning_details=reasoning_details)
|
||||
|
||||
def _adopt_final_response(self, final_response):
|
||||
"""Adapter returned a completed response for ``stream=True``: switch the
|
||||
@@ -2926,7 +2896,7 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
return mock_tool_calls or None, has_truncated_tool_args
|
||||
|
||||
def _finish_chat_stream(self, stream, role, content_parts, reasoning_parts, tool_calls_acc, finish_reason,
|
||||
model_name, usage_obj, *, flush_pending, response_id=None, upstream_provider=None):
|
||||
model_name, usage_obj, *, flush_pending, response_id=None, upstream_provider=None, reasoning_details=None):
|
||||
"""Assemble the non-streaming-shaped response after the chunk loop. A
|
||||
stream ending with no finish_reason is a drop, not a completion: return a
|
||||
partial-stream stub so the loop fails fast instead of executing empty
|
||||
@@ -2948,9 +2918,11 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
_dropped_names)
|
||||
return _build_partial_stream_stub(
|
||||
role, full_content, full_reasoning, model_name, usage_obj, dropped_tool_names=_dropped_names or None)
|
||||
if finish_reason is None and content_parts and not tool_calls_acc and usage_obj is None:
|
||||
# Text-only drop: otherwise the partial text is stamped "stop" and the next step is
|
||||
# lost. A usage object proves the provider finished (include_usage's final chunk).
|
||||
if finish_reason is None and (content_parts or reasoning_parts) and not tool_calls_acc and usage_obj is None:
|
||||
# Text-only (or reasoning-only) drop: otherwise the partial text is stamped "stop"
|
||||
# and the next step is lost — for reasoning-only, the clean-stop promotion in
|
||||
# finish_text_response would then surface a truncated thought as the answer.
|
||||
# A usage object proves the provider finished (include_usage's final chunk).
|
||||
logger.warning(
|
||||
"Stream ended with no finish_reason after delivering text with no tool calls; treating as a mid-stream drop.")
|
||||
return _build_partial_stream_stub(role, full_content, full_reasoning, model_name, usage_obj)
|
||||
@@ -2961,6 +2933,10 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
raise provider_stream_error
|
||||
flush_pending()
|
||||
message = SimpleNamespace(role=role, content=full_content, tool_calls=mock_tool_calls, reasoning_content=full_reasoning)
|
||||
if reasoning_details:
|
||||
# Only when present: _build_assistant_message's passthrough persists them
|
||||
# for replay, and non-reasoning providers keep the attribute absent.
|
||||
message.reasoning_details = reasoning_details
|
||||
# The provider's id when the chunks carried one (chatcmpl-/gen-...): it is what a provider needs to
|
||||
# look a request up. Fabricated only when the stream never sent one.
|
||||
return SimpleNamespace(id=response_id or ("stream-" + str(uuid.uuid4())), model=model_name, usage=usage_obj,
|
||||
@@ -3038,6 +3014,9 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
has_tool_use = True
|
||||
if getattr(block, "name", None):
|
||||
self._emit_tool_started(block.name)
|
||||
# Same as the chat_completions wire: a stream that dies inside the
|
||||
# tool args is retried (no tool has run yet) instead of stubbed.
|
||||
self.result["partial_tool_names"].append(block.name)
|
||||
elif event_type == "content_block_delta":
|
||||
delta = getattr(event, "delta", None)
|
||||
delta_type = getattr(delta, "type", None) if delta else None
|
||||
@@ -3080,6 +3059,9 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
OpenAI primary is replaced lazily."""
|
||||
self.agent._emit_stream_drop(
|
||||
error=e, attempt=attempt + 2, max_attempts=max_retries + 1, mid_tool_call=mid_tool_call, diag=self.clients.diag)
|
||||
if self.agent._is_provider_stream_parse_error(e):
|
||||
from agent.anthropic_adapter import buffer_anthropic_tool_input
|
||||
buffer_anthropic_tool_input(self.api_kwargs, getattr(self.agent, "_anthropic_base_url", None))
|
||||
self._cancel_current_stream_attempt(reason)
|
||||
self.clients.close_once(reason)
|
||||
|
||||
@@ -3144,7 +3126,6 @@ class _StreamingCall(StreamingWaitMonitor):
|
||||
# reset the streamed-text buffer so it isn't double-recorded; fresh accumulators.
|
||||
self._quiet(self.agent._fire_stream_delta, "\n\n⚠ Connection dropped mid tool-call; reconnecting…\n\n")
|
||||
self._quiet(self.agent._reset_stream_delivery_tracking)
|
||||
self.result["partial_tool_names"] = []
|
||||
self.deltas_were_sent["yes"] = False
|
||||
self.first_delta_fired["done"] = False
|
||||
self._retry_after_drop(e, attempt, max_retries, mid_tool_call=True, reason="stream_mid_tool_retry_cleanup")
|
||||
|
||||
@@ -3040,14 +3040,19 @@ def _warn_summary_or_aux_fallback(agent: Any) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _reset_read_dedup_caches(task_id: str, *, skills: bool = True) -> None:
|
||||
def _reset_read_dedup_caches(task_id: str, *, session_id: str = "", skills: bool = True) -> None:
|
||||
"""Advance the file-read (and skill_view) repeat-read dedup to a fresh generation after a boundary.
|
||||
The mtime map is kept: the first read of each unchanged key returns full content compaction may have
|
||||
omitted; later reads return stubs, and stub-hit counters restart at the same boundary (#84857).
|
||||
The computer_use screenshot dedup is session-keyed and forgets its last frame for the same reason.
|
||||
"""
|
||||
with contextlib.suppress(Exception):
|
||||
from tools.file_tools_read_tracking import reset_file_dedup
|
||||
reset_file_dedup(task_id)
|
||||
if session_id:
|
||||
with contextlib.suppress(Exception):
|
||||
from tools.computer_use.tool import reset_screenshot_dedup
|
||||
reset_screenshot_dedup(session_id)
|
||||
if not skills:
|
||||
return
|
||||
with contextlib.suppress(Exception):
|
||||
@@ -3145,7 +3150,7 @@ def _finish_compaction_boundary(
|
||||
)
|
||||
else:
|
||||
compressor._verify_compaction_cleared_threshold = True
|
||||
_reset_read_dedup_caches(task_id)
|
||||
_reset_read_dedup_caches(task_id, session_id=agent.session_id or "")
|
||||
return _compressed_est
|
||||
|
||||
|
||||
@@ -3832,7 +3837,7 @@ def _compress_context_via_codex_app_server(
|
||||
# armed until a later turn; minimal test engines may lack update_from_response.
|
||||
if hasattr(agent.context_compressor, "update_from_response"):
|
||||
_record_codex_app_server_usage(agent, result, messages=messages)
|
||||
_reset_read_dedup_caches(task_id, skills=False)
|
||||
_reset_read_dedup_caches(task_id, session_id=agent.session_id or "", skills=False)
|
||||
logger.info(
|
||||
"codex app-server compaction done: session=%s thread=%s turn=%s", _sid,
|
||||
getattr(result, "thread_id", None) or "", getattr(result, "turn_id", None) or "",
|
||||
|
||||
+73
-24
@@ -17,6 +17,7 @@ import subprocess
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
@@ -134,10 +135,36 @@ def _jsonrpc_error(message_id: Any, code: int, message: str) -> dict[str, Any]:
|
||||
return {"jsonrpc": "2.0", "id": message_id, "error": {"code": code, "message": message}}
|
||||
|
||||
|
||||
def _enabled_ids(entries: Any, key: str) -> set[str]:
|
||||
"""Ids of ``entries`` (dicts) whose ``_meta.copilotEnablement`` is not ``disabled``."""
|
||||
return {str(e.get(key) or "").strip() for e in (entries or []) if isinstance(e, dict)
|
||||
and str((e.get("_meta") or {}).get("copilotEnablement") or "").strip().lower() != "disabled"}
|
||||
def _enabled_id_list(entries: Any, key: str) -> list[str]:
|
||||
"""Ordered ids whose ``_meta.copilotEnablement`` is not ``disabled``."""
|
||||
seen: set[str] = set()
|
||||
result: list[str] = []
|
||||
for entry in entries or []:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
value = str(entry.get(key) or "").strip()
|
||||
if (not value or value in seen
|
||||
or str((entry.get("_meta") or {}).get("copilotEnablement") or "").strip().lower() == "disabled"):
|
||||
continue
|
||||
seen.add(value)
|
||||
result.append(value)
|
||||
return result
|
||||
|
||||
|
||||
def _model_config_option(session: dict[str, Any]) -> dict[str, Any] | None:
|
||||
return next((option for option in (session.get("configOptions") or []) if isinstance(option, dict)
|
||||
and "model" in (option.get("category"), option.get("id"))), None)
|
||||
|
||||
|
||||
def _session_model_ids(session: dict[str, Any]) -> list[str]:
|
||||
"""Account-authorized model ids advertised by ``session/new`` in ACP v1 or its legacy extension."""
|
||||
if option := _model_config_option(session):
|
||||
return _enabled_id_list(option.get("options"), "value")
|
||||
return _legacy_session_model_ids(session)
|
||||
|
||||
|
||||
def _legacy_session_model_ids(session: dict[str, Any]) -> list[str]:
|
||||
return _enabled_id_list((session.get("models") or {}).get("availableModels"), "modelId")
|
||||
|
||||
|
||||
def _model_selection_request(session: dict[str, Any], requested_model: str) -> tuple[str, dict[str, str]] | None:
|
||||
@@ -149,12 +176,12 @@ def _model_selection_request(session: dict[str, Any], requested_model: str) -> t
|
||||
requested_model = str(requested_model or "").strip()
|
||||
if not session_id or not requested_model or requested_model == "copilot-acp":
|
||||
return None
|
||||
options = [o for o in (session.get("configOptions") or []) if isinstance(o, dict) and "model" in (o.get("category"), o.get("id"))]
|
||||
if options:
|
||||
if requested_model not in _enabled_ids(options[0].get("options"), "value"):
|
||||
option = _model_config_option(session)
|
||||
if option:
|
||||
if requested_model not in _enabled_id_list(option.get("options"), "value"):
|
||||
return None
|
||||
return "session/set_config_option", {"sessionId": session_id, "configId": str(options[0].get("id") or "model"), "value": requested_model}
|
||||
available = _enabled_ids((session.get("models") or {}).get("availableModels"), "modelId")
|
||||
return "session/set_config_option", {"sessionId": session_id, "configId": str(option.get("id") or "model"), "value": requested_model}
|
||||
available = _legacy_session_model_ids(session)
|
||||
return None if available and requested_model not in available else ("session/set_model", {"sessionId": session_id, "modelId": requested_model})
|
||||
|
||||
|
||||
@@ -322,10 +349,11 @@ class CopilotACPClient:
|
||||
self._active_process = proc
|
||||
return proc
|
||||
|
||||
def _run_prompt(self, prompt_text: str, *, timeout_seconds: float, model: str | None = None) -> tuple[str, str]:
|
||||
# The CLI's `--model` spawn flag is deliberately NOT used: `copilot --acp` validates it (unknown id
|
||||
# aborts the spawn) but ignores it for the session; the model is applied after session/new instead.
|
||||
requested_model = str(model or "").strip()
|
||||
@contextlib.contextmanager
|
||||
def _session(
|
||||
self, timeout_seconds: float, *, allow_file_requests: bool = True
|
||||
) -> Iterator[tuple[dict[str, Any], Callable[..., Any]]]:
|
||||
"""Start one ACP process and yield its ``session/new`` result plus request callable."""
|
||||
proc = self._spawn()
|
||||
inbox: queue.Queue[dict[str, Any]] = queue.Queue()
|
||||
stderr_tail: deque[str] = deque(maxlen=40)
|
||||
@@ -343,19 +371,24 @@ class CopilotACPClient:
|
||||
threading.Thread(target=_pump, args=(proc.stdout, lambda line: inbox.put(_decode(line))), daemon=True).start()
|
||||
threading.Thread(target=_pump, args=(proc.stderr, lambda line: stderr_tail.append(line.rstrip("\n"))), daemon=True).start()
|
||||
request_ids = iter(range(1, 1 << 62))
|
||||
# One budget for the WHOLE session (initialize + session/new + any prompt), not per
|
||||
# request: a hung CLI must not get 2x the caller's timeout on the foreground /model path.
|
||||
session_deadline = time.monotonic() + timeout_seconds
|
||||
|
||||
def _request(method: str, params: dict[str, Any], *, text_parts: list[str] | None = None, reasoning_parts: list[str] | None = None) -> Any:
|
||||
def _request(method: str, params: dict[str, Any], *, text_parts: list[str] | None = None,
|
||||
reasoning_parts: list[str] | None = None) -> Any:
|
||||
request_id = next(request_ids)
|
||||
proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}) + "\n")
|
||||
proc.stdin.flush()
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
deadline = session_deadline
|
||||
while time.monotonic() < deadline and proc.poll() is None:
|
||||
try:
|
||||
msg = inbox.get(timeout=0.1)
|
||||
except queue.Empty:
|
||||
continue
|
||||
if self._handle_server_message(
|
||||
msg, process=proc, cwd=self._acp_cwd, text_parts=text_parts, reasoning_parts=reasoning_parts
|
||||
msg, process=proc, cwd=self._acp_cwd, text_parts=text_parts,
|
||||
reasoning_parts=reasoning_parts, allow_file_requests=allow_file_requests,
|
||||
) or msg.get("id") != request_id:
|
||||
continue
|
||||
if "error" in msg:
|
||||
@@ -372,9 +405,23 @@ class CopilotACPClient:
|
||||
try:
|
||||
_request("initialize", _INITIALIZE_PARAMS)
|
||||
session = _request("session/new", {"cwd": self._acp_cwd, "mcpServers": []}) or {}
|
||||
session_id = str(session.get("sessionId") or "").strip()
|
||||
if not session_id:
|
||||
if not str(session.get("sessionId") or "").strip():
|
||||
raise RuntimeError("Copilot ACP did not return a sessionId.")
|
||||
yield session, _request
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def list_models(self, *, timeout_seconds: float = 15.0) -> list[str]:
|
||||
"""Return the enabled models advertised by a short-lived authenticated ACP session."""
|
||||
with self._session(timeout_seconds, allow_file_requests=False) as (session, _):
|
||||
return _session_model_ids(session)
|
||||
|
||||
def _run_prompt(self, prompt_text: str, *, timeout_seconds: float, model: str | None = None) -> tuple[str, str]:
|
||||
# The CLI's `--model` spawn flag is deliberately NOT used: `copilot --acp` validates it (unknown id
|
||||
# aborts the spawn) but ignores it for the session; the model is applied after session/new instead.
|
||||
requested_model = str(model or "").strip()
|
||||
with self._session(timeout_seconds) as (session, _request):
|
||||
session_id = str(session.get("sessionId") or "").strip()
|
||||
if requested_model and requested_model != "copilot-acp":
|
||||
try:
|
||||
if (selection := _model_selection_request(session, requested_model)) is not None:
|
||||
@@ -388,11 +435,10 @@ class CopilotACPClient:
|
||||
prompt = {"sessionId": session_id, "prompt": [{"type": "text", "text": prompt_text}]}
|
||||
_request("session/prompt", prompt, text_parts=text_parts, reasoning_parts=reasoning_parts)
|
||||
return "".join(text_parts), "".join(reasoning_parts)
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def _handle_server_message(
|
||||
self, msg: dict[str, Any], *, process: subprocess.Popen[str], cwd: str, text_parts: list[str] | None, reasoning_parts: list[str] | None,
|
||||
allow_file_requests: bool = True,
|
||||
) -> bool:
|
||||
"""Consume a server->client message; True when handled (notification or request answered)."""
|
||||
method = msg.get("method")
|
||||
@@ -412,10 +458,13 @@ class CopilotACPClient:
|
||||
if method == "session/request_permission":
|
||||
response = _jsonrpc_result(message_id, {"outcome": {"outcome": "cancelled"}})
|
||||
elif method in _FS_HANDLERS:
|
||||
try:
|
||||
response = _jsonrpc_result(message_id, _FS_HANDLERS[method](msg.get("params") or {}, cwd))
|
||||
except Exception as exc:
|
||||
response = _jsonrpc_error(message_id, -32602, str(exc))
|
||||
if not allow_file_requests:
|
||||
response = _jsonrpc_error(message_id, -32601, "File access is unavailable during model discovery.")
|
||||
else:
|
||||
try:
|
||||
response = _jsonrpc_result(message_id, _FS_HANDLERS[method](msg.get("params") or {}, cwd))
|
||||
except Exception as exc:
|
||||
response = _jsonrpc_error(message_id, -32602, str(exc))
|
||||
else:
|
||||
response = _jsonrpc_error(message_id, -32601, f"ACP client method '{method}' is not supported by Hermes yet.")
|
||||
process.stdin.write(json.dumps(response) + "\n")
|
||||
|
||||
@@ -113,6 +113,11 @@ _BILLING_ERROR_CODES = frozenset({
|
||||
"insufficient_quota", "billing_not_active", "payment_required", "insufficient_credits",
|
||||
"no_usable_credits", "balance_depleted", "model_not_supported_on_free_tier",
|
||||
"member_spend_cap_exceeded", "terminal_quota_exhausted", _XAI_SPENDING_LIMIT_ERROR_CODE,
|
||||
# OpenAI (and OpenAI-compatible aggregators) spend/usage-limit family:
|
||||
# a credit balance or an org/project spend or usage cap is exhausted —
|
||||
# terminal for this credential until limits are raised.
|
||||
"credit_balance_exhausted", "organization_spend_limit_exceeded",
|
||||
"organization_usage_limit_exceeded", "project_spend_limit_exceeded",
|
||||
})
|
||||
|
||||
# Transient rate limiting. Bedrock "Throttling error: Too many tokens" also
|
||||
|
||||
@@ -21,7 +21,7 @@ import httpx
|
||||
|
||||
from agent.bounded_response import read_streaming_error_body
|
||||
from agent.retry_utils import parse_retry_after_seconds
|
||||
from agent.gemini_schema import sanitize_gemini_tool_parameters
|
||||
from agent.gemini_schema import prepare_gemini_tool_parameters, sanitize_gemini_tool_parameters
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -102,6 +102,13 @@ def is_native_gemini_base_url(base_url: str) -> bool:
|
||||
return "generativelanguage.googleapis.com" in normalized and not normalized.endswith("/openai")
|
||||
|
||||
|
||||
def gemini_accepts_parameters_json_schema(base_url: str) -> bool:
|
||||
"""``FunctionDeclaration.parametersJsonSchema`` exists only in the ``v1beta`` surface of
|
||||
generativelanguage (absent from ``v1`` / ``v1alpha`` content.proto); other versions and
|
||||
unknown proxies get the legacy ``parameters`` subset."""
|
||||
return str(base_url or "").strip().rstrip("/").lower().endswith("/v1beta")
|
||||
|
||||
|
||||
def probe_gemini_tier(
|
||||
api_key: str, base_url: str = DEFAULT_GEMINI_BASE_URL, *, model: str = "gemini-3.7-flash", timeout: float = 10.0
|
||||
) -> str:
|
||||
@@ -329,7 +336,7 @@ def _build_gemini_contents(
|
||||
return _merge_alternating(contents), ({"role": "system", "parts": [{"text": joined_system}]} if joined_system else None)
|
||||
|
||||
|
||||
def _function_declaration(tool: Any) -> Optional[Dict[str, Any]]:
|
||||
def _function_declaration(tool: Any, *, json_schema: bool = False) -> Optional[Dict[str, Any]]:
|
||||
fn = (tool.get("function") or {}) if isinstance(tool, dict) else None
|
||||
if not isinstance(fn, dict) or not (isinstance(fn.get("name"), str) and fn["name"]):
|
||||
return None
|
||||
@@ -337,12 +344,18 @@ def _function_declaration(tool: Any) -> Optional[Dict[str, Any]]:
|
||||
if isinstance(fn.get("description"), str) and fn["description"]:
|
||||
decl["description"] = fn["description"]
|
||||
if isinstance(fn.get("parameters"), dict):
|
||||
decl["parameters"] = sanitize_gemini_tool_parameters(fn["parameters"])
|
||||
# Full JSON Schema where the API version has the field (unions, bare arrays,
|
||||
# $ref survive); the lossy OpenAPI subset elsewhere. Mutually exclusive on the wire.
|
||||
if json_schema:
|
||||
decl["parametersJsonSchema"] = prepare_gemini_tool_parameters(fn["parameters"])
|
||||
else:
|
||||
decl["parameters"] = sanitize_gemini_tool_parameters(fn["parameters"])
|
||||
return decl
|
||||
|
||||
|
||||
def _translate_tools_to_gemini(tools: Any) -> List[Dict[str, Any]]:
|
||||
declarations = [d for d in map(_function_declaration, tools if isinstance(tools, list) else []) if d]
|
||||
def _translate_tools_to_gemini(tools: Any, *, json_schema: bool = False) -> List[Dict[str, Any]]:
|
||||
declarations = [d for d in (_function_declaration(t, json_schema=json_schema)
|
||||
for t in (tools if isinstance(tools, list) else [])) if d]
|
||||
return [{"functionDeclarations": declarations}] if declarations else []
|
||||
|
||||
|
||||
@@ -396,13 +409,14 @@ def _effective_gemini_max_output_tokens(max_tokens: Optional[int], thinking_conf
|
||||
def build_gemini_request(
|
||||
*, messages: List[Dict[str, Any]], tools: Any = None, tool_choice: Any = None, temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None, top_p: Optional[float] = None, stop: Any = None, thinking_config: Any = None,
|
||||
model: str = "",
|
||||
model: str = "", tools_as_json_schema: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
# Gemini 3+ both requires tool-call ids and accepts multimodal functionResponse parts.
|
||||
is_gemini3 = gemini_requires_tool_call_ids(model)
|
||||
contents, system_instruction = _build_gemini_contents(messages, include_tool_call_ids=is_gemini3, is_gemini3=is_gemini3)
|
||||
optional = (
|
||||
("systemInstruction", system_instruction), ("tools", _translate_tools_to_gemini(tools)),
|
||||
("systemInstruction", system_instruction),
|
||||
("tools", _translate_tools_to_gemini(tools, json_schema=tools_as_json_schema)),
|
||||
("toolConfig", _translate_tool_choice_to_gemini(tool_choice)),
|
||||
)
|
||||
request: Dict[str, Any] = {"contents": contents, **{k: v for k, v in optional if v}}
|
||||
@@ -675,6 +689,7 @@ class GeminiNativeClient:
|
||||
request = build_gemini_request(
|
||||
messages=messages or [], tools=tools, tool_choice=tool_choice, temperature=temperature, max_tokens=max_tokens,
|
||||
top_p=top_p, stop=stop, thinking_config=extra.get("thinking_config") or extra.get("thinkingConfig"), model=model,
|
||||
tools_as_json_schema=gemini_accepts_parameters_json_schema(self.base_url),
|
||||
)
|
||||
model = bare_gemini_model_id(model)
|
||||
url = f"{self.base_url}/models/{model}:"
|
||||
|
||||
+86
-2
@@ -1,12 +1,22 @@
|
||||
"""Helpers for translating OpenAI-style tool schemas to Gemini's schema subset."""
|
||||
"""Tool-schema preparation for Gemini's native API.
|
||||
|
||||
Two wire shapes: ``parametersJsonSchema`` (plain JSON Schema, v1beta only) gets a light
|
||||
normalizer (``prepare_gemini_tool_parameters``); the legacy ``parameters`` field accepts
|
||||
only the OpenAPI ``Schema`` subset and keeps the lossy translator
|
||||
(``sanitize_gemini_tool_parameters``) for API versions without the JSON Schema field.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import math
|
||||
from typing import Any, Dict
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from tools.schema_sanitizer import _normalize_type_array
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Gemini's ``FunctionDeclaration.parameters`` accepts only a subset of OpenAPI 3.0 /
|
||||
# JSON Schema (the ``Schema`` object); everything else is stripped.
|
||||
_GEMINI_SCHEMA_ALLOWED_KEYS = {
|
||||
@@ -112,3 +122,77 @@ def sanitize_gemini_schema(schema: Any) -> Dict[str, Any]:
|
||||
def sanitize_gemini_tool_parameters(parameters: Any) -> Dict[str, Any]:
|
||||
"""Normalize tool parameters to a valid Gemini object schema."""
|
||||
return sanitize_gemini_schema(parameters) or {"type": "object", "properties": {}}
|
||||
|
||||
|
||||
# ── parametersJsonSchema (full JSON Schema) ─────────────────────────────────
|
||||
#
|
||||
# The legacy translator is lossy: anyOf unions without an outer type, bare arrays,
|
||||
# $ref/$defs and additionalProperties had to be stripped or repaired, and one
|
||||
# unrepresentable construct 400s the ENTIRE request. Through parametersJsonSchema the
|
||||
# schema goes as-is; only same-document $refs are inlined (MCP pydantic / zod emit
|
||||
# them and Google rejects reference indirection) and root ``$schema`` is dropped.
|
||||
|
||||
_EMPTY_OBJECT_SCHEMA: Dict[str, Any] = {"type": "object", "properties": {}}
|
||||
# Real tool schemas hold a handful of refs; the cap stops circular pydantic models
|
||||
# from expanding forever.
|
||||
_MAX_REF_EXPANSIONS = 256
|
||||
|
||||
|
||||
def _resolve_local_ref(root: Dict[str, Any], ref: str) -> Optional[Dict[str, Any]]:
|
||||
"""Resolve a same-document JSON pointer (``#/$defs/Foo``) against *root*."""
|
||||
if not isinstance(ref, str) or not ref.startswith("#/"):
|
||||
return None
|
||||
node: Any = root
|
||||
for raw_part in ref[2:].split("/"):
|
||||
part = raw_part.replace("~1", "/").replace("~0", "~")
|
||||
if not isinstance(node, dict) or part not in node:
|
||||
return None
|
||||
node = node[part]
|
||||
return node if isinstance(node, dict) else None
|
||||
|
||||
|
||||
def _inline_refs(node: Any, root: Dict[str, Any], budget: List[int], stack: tuple = ()) -> Any:
|
||||
"""Recursively inline same-document ``$ref`` nodes; ``ValueError`` on an unresolvable
|
||||
or circular reference or an exhausted budget (the caller then keeps the original)."""
|
||||
if isinstance(node, list):
|
||||
return [_inline_refs(item, root, budget, stack) for item in node]
|
||||
if not isinstance(node, dict):
|
||||
return node
|
||||
ref = node.get("$ref")
|
||||
if not isinstance(ref, str):
|
||||
return {key: _inline_refs(value, root, budget, stack) for key, value in node.items()}
|
||||
if ref in stack:
|
||||
raise ValueError(f"circular $ref {ref!r}")
|
||||
budget[0] -= 1
|
||||
if budget[0] < 0:
|
||||
raise ValueError("$ref expansion budget exhausted")
|
||||
target = _resolve_local_ref(root, ref)
|
||||
if target is None:
|
||||
raise ValueError(f"unresolvable $ref {ref!r}")
|
||||
inlined = _inline_refs(target, root, budget, stack + (ref,))
|
||||
# JSON Schema: siblings of $ref (description, default, ...) apply alongside the
|
||||
# referenced schema and win over it.
|
||||
siblings = {k: v for k, v in node.items() if k != "$ref"}
|
||||
return {**inlined, **_inline_refs(siblings, root, budget, stack)} if siblings else inlined
|
||||
|
||||
|
||||
def prepare_gemini_tool_parameters(parameters: Any) -> Dict[str, Any]:
|
||||
"""Full JSON Schema for ``parametersJsonSchema``: deep-copied, root ``$schema`` dropped,
|
||||
same-document ``$ref`` inlined, object root guaranteed. A schema whose references
|
||||
cannot all be resolved is sent untouched so the provider names the real problem."""
|
||||
if not isinstance(parameters, dict) or not parameters:
|
||||
return dict(_EMPTY_OBJECT_SCHEMA)
|
||||
schema = copy.deepcopy(parameters)
|
||||
schema.pop("$schema", None)
|
||||
try:
|
||||
schema = _inline_refs(schema, schema, [_MAX_REF_EXPANSIONS])
|
||||
except ValueError as exc:
|
||||
logger.debug("Gemini tool schema kept as-is ($ref inlining skipped): %s", exc)
|
||||
return schema
|
||||
schema.pop("$defs", None)
|
||||
schema.pop("definitions", None)
|
||||
if not schema:
|
||||
return dict(_EMPTY_OBJECT_SCHEMA)
|
||||
if schema.get("type") == "object" and "properties" not in schema:
|
||||
schema["properties"] = {}
|
||||
return schema
|
||||
@@ -150,6 +150,27 @@ def _desktop_preview(agent, args: dict, ctx: InlineToolContext) -> Any:
|
||||
return _handle_preview(args)
|
||||
|
||||
|
||||
def _manage_connections(agent, args: dict, ctx: InlineToolContext) -> Any:
|
||||
# The GUI callback lives on the agent; registry dispatch never forwards it.
|
||||
from tools.connectors import manage_connections
|
||||
from tools.connectors.gateway import config as gateway_config
|
||||
|
||||
return manage_connections(
|
||||
args, session_id=getattr(agent, "session_id", None), tool_call_id=ctx.tool_call_id,
|
||||
connection_callback=getattr(agent, "connection_callback", None),
|
||||
connectors_available=gateway_config.connectors_available,
|
||||
)
|
||||
|
||||
|
||||
def _setup_mcp_shim(agent, args: dict, ctx: InlineToolContext) -> Any:
|
||||
# Replay shim for conversations whose cached prompt still names setup_mcp.
|
||||
# Not in _LEGACY_TOOL_ALIASES: inline tools bypass handle_function_call.
|
||||
return _manage_connections(agent, {
|
||||
"action": args.get("action", "install"),
|
||||
"connectors": [{"name": args.get("server", ""), "mcp": True}],
|
||||
}, ctx)
|
||||
|
||||
|
||||
# Order is the historical if/elif order of ``execute_tool_calls_sequential``.
|
||||
INLINE_TOOL_EXECUTORS: Dict[str, InlineToolExecutor] = {
|
||||
"todo_list": _tool(
|
||||
@@ -192,10 +213,8 @@ INLINE_TOOL_EXECUTORS: Dict[str, InlineToolExecutor] = {
|
||||
("action", "action", ""), ("surface", "surface"), ("selector", "selector"), ("title", "title"),
|
||||
("text", "text"), ("side", "side"), ("steps", "steps"), ("step_index", "step_index"),
|
||||
),
|
||||
"setup_mcp": _callback_tool(
|
||||
"tools.setup_mcp_tool", "setup_mcp_tool", "setup_mcp_callback",
|
||||
("server", "server", ""), ("action", "action", "install"), ("reason", "reason", ""),
|
||||
),
|
||||
"manage_connections": _manage_connections,
|
||||
"setup_mcp": _setup_mcp_shim,
|
||||
"delegate_task": lambda agent, args, ctx: agent._dispatch_delegate_task(args),
|
||||
}
|
||||
|
||||
|
||||
@@ -95,6 +95,19 @@ _sanitize_messages_non_ascii = partial(_sanitize_messages, fix=_strip_non_ascii,
|
||||
_sanitize_tools_non_ascii = _sanitize_structure_non_ascii
|
||||
|
||||
|
||||
def sanitize_outbound_kwargs(agent: Any, api_kwargs: dict) -> None:
|
||||
"""Outbound-request chokepoint for every built kwargs dict (main loop and iteration summary).
|
||||
|
||||
Tool descriptions, extra_body and kwargs strings can carry invalid code points that
|
||||
providers reject with a non-retryable 400 (#50959); one in-place walk makes the whole
|
||||
payload json.dumps()-safe. The ASCII strip is opt-in via the recovery flag set after an
|
||||
ASCII-codec rejection.
|
||||
"""
|
||||
_sanitize_structure_surrogates(api_kwargs)
|
||||
if agent._force_ascii_payload:
|
||||
_sanitize_structure_non_ascii(api_kwargs)
|
||||
|
||||
|
||||
def _escape_invalid_chars_in_json_strings(raw: str) -> str:
|
||||
"""Escape literal control chars (0x00-0x1F) inside JSON string values as ``\\uXXXX``
|
||||
(for llama.cpp-style output mixing control chars with other malformations)."""
|
||||
@@ -197,6 +210,32 @@ def close_interrupted_tool_sequence(messages: list, final_response: Any = None)
|
||||
return True
|
||||
|
||||
|
||||
# finish_reason wire normalization. Some OpenAI-compatible gateways fronting
|
||||
# Gemini backends emit the native uppercase reasons (STOP, MAX_TOKENS); every
|
||||
# downstream comparison uses the lowercase OpenAI literals, so an uppercase
|
||||
# reason silently skips stop handling and length recovery. Single owner —
|
||||
# call at wire intake (transport normalize_response, stream chunk capture),
|
||||
# never re-fold at comparison sites.
|
||||
_FINISH_REASON_ALIASES = {
|
||||
"max_tokens": "length", # Gemini-native / Anthropic-style cap reason
|
||||
"end": "stop", # some gateways' clean-completion spelling
|
||||
"function_call": "tool_calls", # OpenAI legacy pre-tools spelling
|
||||
}
|
||||
|
||||
|
||||
def normalize_finish_reason(raw: Any) -> Any:
|
||||
"""Fold a wire ``finish_reason`` to the lowercase OpenAI contract value.
|
||||
|
||||
Non-string and empty values pass through unchanged (callers keep their
|
||||
``or "stop"`` defaults and the Poolside int-reason path); contract values
|
||||
are returned byte-identical.
|
||||
"""
|
||||
if not isinstance(raw, str) or not raw:
|
||||
return raw
|
||||
lowered = raw.lower()
|
||||
return _FINISH_REASON_ALIASES.get(lowered, lowered)
|
||||
|
||||
|
||||
def serialized_messages_bytes(messages: list) -> int:
|
||||
"""Exact serialized byte size of ``messages`` (HTTP 413 is a BYTE-size error the token
|
||||
estimator, pricing images flat, cannot score). Non-serializable values fall back to
|
||||
@@ -289,7 +328,7 @@ __all__ = [
|
||||
"_sanitize_surrogates", "_sanitize_structure_surrogates", "_sanitize_messages_surrogates",
|
||||
"_escape_invalid_chars_in_json_strings", "_repair_tool_call_arguments",
|
||||
"_strip_non_ascii", "_sanitize_messages_non_ascii", "_sanitize_tools_non_ascii",
|
||||
"_strip_images_from_messages", "_sanitize_structure_non_ascii",
|
||||
"_strip_images_from_messages", "_sanitize_structure_non_ascii", "sanitize_outbound_kwargs",
|
||||
# call_id policy owners
|
||||
"deterministic_call_id", "coalesce_tool_call_id", "tool_call_id_variants",
|
||||
"tool_result_id_variants", "uniquify_tool_call_ids",
|
||||
|
||||
@@ -1595,6 +1595,13 @@ def _verified_codex_ctx_for_slug(model_bare: str) -> Optional[int]:
|
||||
|
||||
_codex_oauth_context_cache: Dict[str, Tuple[Dict[str, int], float]] = {}
|
||||
_CODEX_OAUTH_CONTEXT_CACHE_TTL = 3600 # 1 hour
|
||||
# The Codex models endpoint reads ``client_version`` as a Codex CLI compatibility version and
|
||||
# hides models whose ``minimal_client_version`` is newer, so a made-up version (the old
|
||||
# "1.0.0") silently drops future models. "0.0.0" is the backend's ungated sentinel returning
|
||||
# the full account catalog; other out-of-sequence values return an empty catalog and omitting
|
||||
# the parameter is HTTP 400.
|
||||
CODEX_UNGATED_CLIENT_VERSION = "0.0.0"
|
||||
CODEX_MODELS_CATALOG_URL = f"https://chatgpt.com/backend-api/codex/models?client_version={CODEX_UNGATED_CLIENT_VERSION}"
|
||||
|
||||
|
||||
def _codex_oauth_token_fingerprint(access_token: str) -> str:
|
||||
@@ -1630,7 +1637,7 @@ def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[D
|
||||
headers["ChatGPT-Account-Id"] = acct_id
|
||||
try:
|
||||
_ensure_requests()
|
||||
resp = requests.get("https://chatgpt.com/backend-api/codex/models?client_version=1.0.0", headers=headers, timeout=(5, 10), verify=_resolve_requests_verify())
|
||||
resp = requests.get(CODEX_MODELS_CATALOG_URL, headers=headers, timeout=(5, 10), verify=_resolve_requests_verify())
|
||||
if resp.status_code != 200:
|
||||
logger.debug("Codex /models probe returned HTTP %s; falling back to hardcoded defaults", resp.status_code)
|
||||
return {}, False
|
||||
|
||||
@@ -90,7 +90,18 @@ def declared_conversation_scope(agent: Any) -> Optional[str]:
|
||||
when no key is declared, for a background-review fork (``_persist_disabled``), for an
|
||||
explicit fork child, and on any DB error (fail closed rather than merge a fork onto its
|
||||
parent's key).
|
||||
|
||||
The one sanctioned exception is a same-model cache-parity fork (#109964): its whole purpose
|
||||
is prefix parity with the parent, yet ``_persist_disabled`` + ``_session_db=None`` made both
|
||||
resolvers key it into a different bucket (one cold ~full-context request per review).
|
||||
``build_cache_parity_fork`` stamps the parent's ALREADY-RESOLVED scope as
|
||||
``_inherited_cache_scope`` (no DB access from the fork). Only a ``gwk_`` value is a declared
|
||||
scope; a physical lineage root stays out of the affinity header so the fork publishes
|
||||
exactly what its parent publishes (None → consumers fall back to the conversation root).
|
||||
"""
|
||||
inherited = getattr(agent, "_inherited_cache_scope", None)
|
||||
if isinstance(inherited, str) and inherited.startswith(_DECLARED_SCOPE_PREFIX):
|
||||
return inherited
|
||||
key = str(getattr(agent, "_gateway_session_key", "") or "").strip()
|
||||
if not key or getattr(agent, "_persist_disabled", False):
|
||||
return None
|
||||
@@ -130,8 +141,12 @@ def declared_conversation_scope(agent: Any) -> Optional[str]:
|
||||
|
||||
|
||||
def resolve_prompt_cache_scope(agent: Any) -> str:
|
||||
"""Rotation-stable cache-scope id: declared scope, else the compression-lineage root of
|
||||
``agent.session_id`` (the physical id without ancestry/DB). Memoized on the agent."""
|
||||
"""Rotation-stable cache-scope id: the inherited parent scope of a same-model cache-parity
|
||||
fork, else the declared scope, else the compression-lineage root of ``agent.session_id``
|
||||
(the physical id without ancestry/DB). Memoized on the agent."""
|
||||
inherited = getattr(agent, "_inherited_cache_scope", None)
|
||||
if isinstance(inherited, str) and inherited:
|
||||
return inherited
|
||||
sid = str(getattr(agent, "session_id", None) or "")
|
||||
if not sid:
|
||||
return ""
|
||||
|
||||
@@ -5,7 +5,6 @@ When ``reasoning`` extra_body is safe to send, LM Studio / Ollama / GitHub Model
|
||||
Extracted from ``run_agent.py``; every method resolves through ``AIAgent``'s MRO unchanged.
|
||||
"""
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from agent.lazy_forward import forward as _forward, forward_static as _forward_static
|
||||
from agent.message_sanitization import matches_reasoning_echo_family
|
||||
@@ -98,11 +97,6 @@ class ReasoningParamsMixin:
|
||||
return False
|
||||
return bool(_cached_probe(self, "_ollama_thinking_cache", ollama_model_supports_thinking, None, lambda v: v is not None))
|
||||
|
||||
def _resolve_lmstudio_summary_reasoning_effort(self) -> Optional[str]:
|
||||
"""Safe top-level ``reasoning_effort`` for LM Studio; shared with the iteration-limit summary call."""
|
||||
from agent.lmstudio_reasoning import resolve_lmstudio_effort
|
||||
return resolve_lmstudio_effort(self.reasoning_config, self._lmstudio_reasoning_options_cached())
|
||||
|
||||
def _github_models_reasoning_extra_body(self) -> dict | None:
|
||||
"""Format reasoning payload for GitHub Models/OpenAI-compatible routes."""
|
||||
try:
|
||||
|
||||
@@ -14,7 +14,7 @@ from typing import Any
|
||||
|
||||
from agent.message_content import flatten_message_text
|
||||
|
||||
__all__ = ["separate_glued_reasoning_blocks"]
|
||||
__all__ = ["append_streamed_reasoning_detail", "separate_glued_reasoning_blocks"]
|
||||
|
||||
|
||||
def separate_glued_reasoning_blocks(previous: str, delta: Any) -> str:
|
||||
@@ -29,3 +29,37 @@ def separate_glued_reasoning_blocks(previous: str, delta: Any) -> str:
|
||||
delta = flatten_message_text(delta, sep="")
|
||||
glued = previous and delta and not previous[-1].isspace() and delta.startswith("**") and "**" in delta[2:]
|
||||
return f"\n\n{delta}" if glued else delta
|
||||
|
||||
|
||||
# reasoning_details entry types whose consecutive fragments are ONE logical block.
|
||||
_MERGEABLE_DETAIL_TEXT_KEYS = {"reasoning.text": "text", "reasoning.summary": "summary"}
|
||||
_BACKFILL_DETAIL_KEYS = ("signature", "id", "format", "index")
|
||||
|
||||
|
||||
def append_streamed_reasoning_detail(details_acc: list, detail: Any) -> None:
|
||||
"""Accumulate one streamed ``reasoning_details`` delta entry into *details_acc*.
|
||||
|
||||
OpenRouter streams ``reasoning_details`` as word-level deltas: consecutive
|
||||
``reasoning.text`` / ``reasoning.summary`` entries are fragments of one logical
|
||||
block and are merged (later fragments backfill ``signature``/``id`` the first
|
||||
omitted); encrypted/opaque entries stay discrete. Unmerged, a long thought
|
||||
replays as hundreds of one-word entries and providers that validate the
|
||||
sequence shape on the next turn reject it. SDK objects are normalized to dicts.
|
||||
"""
|
||||
if not isinstance(detail, dict):
|
||||
if hasattr(detail, "model_dump"):
|
||||
detail = detail.model_dump(warnings=False)
|
||||
elif hasattr(detail, "__dict__"):
|
||||
detail = dict(detail.__dict__)
|
||||
else:
|
||||
return
|
||||
dtype = detail.get("type")
|
||||
merge_key = _MERGEABLE_DETAIL_TEXT_KEYS.get(dtype)
|
||||
last = details_acc[-1] if details_acc else None
|
||||
if last is not None and merge_key and last.get("type") == dtype and isinstance(detail.get(merge_key), str):
|
||||
last[merge_key] = (last.get(merge_key) or "") + detail[merge_key]
|
||||
for k in _BACKFILL_DETAIL_KEYS:
|
||||
if last.get(k) in (None, "") and detail.get(k) not in (None, ""):
|
||||
last[k] = detail[k]
|
||||
return
|
||||
details_acc.append(dict(detail))
|
||||
+242
-22
@@ -367,6 +367,72 @@ def _should_redact_assignment(key: str, value: str, *, check_keyword: bool) -> b
|
||||
_JSON_KEY_NAMES = r"(?:api_?[Kk]ey|token|secret|password|access_token|refresh_token|auth_token|bearer|secret_value|raw_secret|secret_input|key_material)"
|
||||
_JSON_FIELD_RE = re.compile(rf'("{_JSON_KEY_NAMES}")\s*:\s*"([^"]+)"', re.IGNORECASE)
|
||||
|
||||
# Python ``repr`` uses single-quoted mapping fields, so opaque credentials in
|
||||
# tracebacks and pytest failure introspection bypass the double-quoted JSON rule
|
||||
# above: ``{'BRAVE_API_KEY': 'opaque-value'}``. Capture identifier-shaped keys
|
||||
# here, then apply the canonical high-confidence key policy in the callback.
|
||||
_PYTHON_REPR_SECRET_KEYS = frozenset({
|
||||
"access_token",
|
||||
"refresh_token",
|
||||
"id_token",
|
||||
"auth_token",
|
||||
"token",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"client_secret",
|
||||
"secret",
|
||||
"password",
|
||||
"passwd",
|
||||
"private_key",
|
||||
"credential",
|
||||
"credentials",
|
||||
"authorization",
|
||||
"bearer",
|
||||
"secret_value",
|
||||
"raw_secret",
|
||||
"secret_input",
|
||||
"key_material",
|
||||
})
|
||||
_PYTHON_REPR_ENV_SUFFIXES = (
|
||||
"_API_KEY",
|
||||
"_TOKEN",
|
||||
"_SECRET",
|
||||
"_PASSWORD",
|
||||
"_PASSWD",
|
||||
"_CREDENTIAL",
|
||||
"_CREDENTIALS",
|
||||
)
|
||||
# Casefolded credential suffixes for mixed/camel-case key names
|
||||
# (``UserPassword``, ``sessionToken``, ``clientApiKey``). Suffix-only so
|
||||
# ``token_count`` / ``password_policy`` metadata keys never match. Widened per
|
||||
# OpenHands/software-agent-sdk#4508.
|
||||
_PYTHON_REPR_CREDENTIAL_SUFFIXES = (
|
||||
"apikey",
|
||||
"api_key",
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"passwd",
|
||||
"credential",
|
||||
"credentials",
|
||||
)
|
||||
_PYTHON_REPR_FIELD_RE = re.compile(
|
||||
r"'(?P<key>[A-Za-z_][A-Za-z0-9_]*)'(?P<sep>\s*:\s*)"
|
||||
r"(?:"
|
||||
r"(?P<single_prefix>[bB]?)'(?P<single_value>(?:\\.|[^'\\])+)'"
|
||||
r"|(?P<double_prefix>[bB]?)\"(?P<double_value>(?:\\.|[^\"\\])+)\""
|
||||
r")"
|
||||
)
|
||||
|
||||
# Terminal/process output normally uses ``code_file=True`` to preserve source.
|
||||
# Add repr masking only to high-confidence diagnostic lines: pytest assertion
|
||||
# introspection (``E ...``) and final Python exception lines.
|
||||
_PYTEST_DIAGNOSTIC_LINE_RE = re.compile(r"^(?P<prefix>[ \t]*E[ \t]{2,})(?P<body>.*)$")
|
||||
_PYTHON_EXCEPTION_LINE_RE = re.compile(
|
||||
r"^(?P<prefix>(?:[A-Za-z_]\w*\.)*[A-Za-z_]\w*"
|
||||
r"(?:Error|Exception|Warning):[ \t]*)(?P<body>.*)$"
|
||||
)
|
||||
|
||||
# Authorization / Proxy-Authorization, any scheme or bare credential; header
|
||||
# name and scheme word preserved. The credential class excludes quotes: pulling
|
||||
# a closing quote into the mask turns value corruption into SYNTAX corruption
|
||||
@@ -515,6 +581,79 @@ def _mask_token(token: str) -> str:
|
||||
return mask_secret(token, head=6, tail=4, floor=18)
|
||||
|
||||
|
||||
def _is_python_repr_secret_key(key: str) -> bool:
|
||||
"""Return True for exact secret keys or credential-suffixed key names."""
|
||||
folded = key.casefold()
|
||||
if folded in _PYTHON_REPR_SECRET_KEYS:
|
||||
return True
|
||||
if key.isupper() and key.endswith(_PYTHON_REPR_ENV_SUFFIXES):
|
||||
return True
|
||||
# Mixed/camel-case keys ending in a credential word (``UserPassword``,
|
||||
# ``sessionToken``, ``clientApiKey``) — the exact-set and uppercase-suffix
|
||||
# rules above miss these. Suffix-only matching keeps metadata names like
|
||||
# ``TOKEN_COUNT`` / ``PASSWORD_POLICY`` / ``SECRET_NAME`` untouched.
|
||||
# Class widened per OpenHands/software-agent-sdk#4508 (their dict-entry
|
||||
# redaction was uppercase-only and leaked mixed-case keys).
|
||||
return folded.endswith(_PYTHON_REPR_CREDENTIAL_SUFFIXES)
|
||||
|
||||
|
||||
def _redact_python_repr_fields(text: str) -> str:
|
||||
"""Fully mask credential fields in Python mapping ``repr`` output."""
|
||||
def _sub(match: re.Match) -> str:
|
||||
key = match.group("key")
|
||||
if not _is_python_repr_secret_key(key):
|
||||
return match.group(0)
|
||||
|
||||
single_value = match.group("single_value")
|
||||
if single_value is not None:
|
||||
prefix = match.group("single_prefix") or ""
|
||||
quote = "'"
|
||||
value = single_value
|
||||
else:
|
||||
prefix = match.group("double_prefix") or ""
|
||||
quote = '"'
|
||||
value = match.group("double_value")
|
||||
|
||||
# Mapping repr can contain code-shaped fixture values too. Preserve
|
||||
# programmatic env lookups just like the ENV/JSON/YAML passes do.
|
||||
if _ENV_LOOKUP_VALUE_RE.match(value):
|
||||
return match.group(0)
|
||||
# An upstream pass (MCP probe header scrub, _mask_token) already masked this
|
||||
# value; re-masking would erase the scheme word it deliberately kept
|
||||
# (``'Authorization': 'Digest ***'`` → ``'***'``).
|
||||
if "***" in value or value.startswith("«redacted:"):
|
||||
return match.group(0)
|
||||
# Do not retain head/tail characters here: escaped repr atoms can cross
|
||||
# a slicing boundary and leave an unescaped quote behind. A full mask is
|
||||
# parseable for both str and bytes values and leaks no opaque bytes.
|
||||
return f"'{key}'{match.group('sep')}{prefix}{quote}***{quote}"
|
||||
|
||||
return _PYTHON_REPR_FIELD_RE.sub(_sub, text)
|
||||
|
||||
|
||||
def _redact_python_diagnostic_repr_fields(text: str) -> str:
|
||||
"""Mask repr fields only on pytest/error lines in source-preserving output."""
|
||||
lines = text.splitlines(keepends=True)
|
||||
for index, line in enumerate(lines):
|
||||
ending = ""
|
||||
body_line = line
|
||||
if line.endswith("\r\n"):
|
||||
body_line, ending = line[:-2], "\r\n"
|
||||
elif line.endswith("\n") or line.endswith("\r"):
|
||||
body_line, ending = line[:-1], line[-1:]
|
||||
|
||||
match = _PYTEST_DIAGNOSTIC_LINE_RE.match(body_line)
|
||||
if match is None:
|
||||
match = _PYTHON_EXCEPTION_LINE_RE.match(body_line)
|
||||
if match is not None:
|
||||
lines[index] = (
|
||||
match.group("prefix")
|
||||
+ _redact_python_repr_fields(match.group("body"))
|
||||
+ ending
|
||||
)
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
def _redact_query_string(query: str) -> str:
|
||||
"""Replace values of sensitive ``k=v&k=v`` params with ``***``; others pass through."""
|
||||
if not query:
|
||||
@@ -624,6 +763,11 @@ def _redact_assignments(text: str) -> str:
|
||||
text = _JSON_FIELD_RE.sub(
|
||||
_assignment_sub(lambda g: f'{g[0]}: "{_mask_token(g[1])}"', check_keyword=False), text)
|
||||
|
||||
# Python mapping repr fields ({'API_KEY': '…'}): single-quoted, so the JSON rule
|
||||
# above never sees them — the traceback / pytest-introspection leak shape.
|
||||
if ":" in text and "'" in text:
|
||||
text = _redact_python_repr_fields(text)
|
||||
|
||||
# YAML after JSON: quoted values are handled there (_YAML_ASSIGN_RE skips quotes).
|
||||
if ":" in text and "://" not in text:
|
||||
text = _YAML_ASSIGN_RE.sub(
|
||||
@@ -670,6 +814,10 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F
|
||||
Every regex sits behind a cheap substring gate that its pattern requires,
|
||||
so the gates are never false-negative.
|
||||
|
||||
Set code_file=True to also skip the Python-repr mapping pass (``{'API_KEY': '…'}``
|
||||
fixtures in source); pytest/exception diagnostic lines get a narrow pass in
|
||||
redact_terminal_output instead.
|
||||
|
||||
Set file_read=True for file *content* returned to the agent (read_file / search_files / cat). The old
|
||||
mask looked like a real-but-truncated key, so an agent reading it from config.yaml and writing it back
|
||||
silently corrupted the stored credential into a dead 13-char value → 401 (issue #35519). The sentinel is
|
||||
@@ -750,35 +898,100 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = F
|
||||
# ``postgresql://{user}`` f-string templates). See issue #43025.
|
||||
_ENV_DUMP_COMMANDS = frozenset({"env", "printenv", "set", "export", "declare"})
|
||||
|
||||
# Commands that read file contents to stdout. A ``.env`` target is a credential
|
||||
# dump (per AGENTS.md ``.env`` holds only secrets), so the ENV pass must run.
|
||||
# Commands that read file contents to stdout, plus the filter readers (``grep``/``awk``/``sed``)
|
||||
# the model reaches for on config files. A secret-bearing target (``.env`` per AGENTS.md,
|
||||
# a shell rc/profile, Hermes' own ``config.yaml`` where ``hermes mcp add --env`` writes
|
||||
# tokens) is a credential dump, so the ENV/YAML assignment pass must run. Arbitrary
|
||||
# ``config.yaml`` / source files stay on the code_file path (``MAX_TOKENS: 100``).
|
||||
_FILE_READ_COMMANDS = frozenset({
|
||||
"cat", "head", "tail", "type", "bat", "less", "more", "nl",
|
||||
"zcat", "tac", "view", "batcat",
|
||||
"zcat", "tac", "view", "batcat", "grep", "awk", "sed",
|
||||
})
|
||||
_SHELL_RC_BASENAMES = frozenset({
|
||||
".bashrc", ".bash_profile", ".bash_login", ".profile",
|
||||
".zshrc", ".zprofile", ".zlogin", ".zshenv",
|
||||
})
|
||||
# Filter readers take a PATTERN/program as their first positional; only the operands after
|
||||
# it are files, so ``grep .bashrc app.py`` must not gate on the pattern.
|
||||
_PATTERN_FIRST_COMMANDS = frozenset({"grep", "awk", "sed"})
|
||||
_HERMES_HOME_PREFIXES = ("$HERMES_HOME/", "${HERMES_HOME}/")
|
||||
# ``$HOME/.hermes/config.yaml`` keeps the ``.hermes`` segment, so stripping the prefix is
|
||||
# enough to gate it; ``~/`` already survives the ``$``-bearing-path bail-out.
|
||||
_HOME_PREFIXES = ("$HOME/", "${HOME}/")
|
||||
|
||||
|
||||
def _command_segments(command: str) -> list[str]:
|
||||
"""Pipeline/sequence segments of a shell command, stripped, empties dropped."""
|
||||
return [seg.strip() for seg in re.split(r"[|;&]+", command) if seg.strip()]
|
||||
"""Pipeline/sequence segments, split only on unquoted ``| ; &`` so an
|
||||
``awk '{print $1; print $2}'`` program or ``grep 'foo|bar'`` pattern stays one
|
||||
segment. Backslash is not an escape (Windows ``C:\\Users\\...``)."""
|
||||
segments: list[str] = []
|
||||
buf: list[str] = []
|
||||
quote: str | None = None
|
||||
for ch in command:
|
||||
if quote:
|
||||
buf.append(ch)
|
||||
if ch == quote:
|
||||
quote = None
|
||||
continue
|
||||
if ch in "'\"":
|
||||
quote = ch
|
||||
buf.append(ch)
|
||||
continue
|
||||
if ch in "|;&":
|
||||
seg = "".join(buf).strip()
|
||||
if seg:
|
||||
segments.append(seg)
|
||||
buf = []
|
||||
continue
|
||||
buf.append(ch)
|
||||
seg = "".join(buf).strip()
|
||||
if seg:
|
||||
segments.append(seg)
|
||||
return segments
|
||||
|
||||
|
||||
def _command_reads_env_file(command: str | None) -> bool:
|
||||
"""True if ``command`` reads a ``.env``-style file (by basename) to stdout.
|
||||
Defense-in-depth, not a boundary: indirect reads (``sudo cat .env``, ``$(cat
|
||||
.env)``, ``sed``/``awk``) are not detected, matching ``is_env_dump_command``."""
|
||||
if not command:
|
||||
def _is_secret_file_arg(arg: str) -> bool:
|
||||
"""``.env``-style or shell rc basename anywhere; ``config.yaml`` only under a
|
||||
``.hermes`` directory or ``$HERMES_HOME`` (never arbitrary YAML)."""
|
||||
path = arg.strip("\"'").replace("\\", "/")
|
||||
hermes_home = False
|
||||
for prefix in _HERMES_HOME_PREFIXES:
|
||||
if path.startswith(prefix):
|
||||
path = path[len(prefix):]
|
||||
hermes_home = True
|
||||
break
|
||||
for prefix in _HOME_PREFIXES:
|
||||
if path.startswith(prefix):
|
||||
path = path[len(prefix):]
|
||||
break
|
||||
if "$" in path:
|
||||
return False
|
||||
parts = [part.lower() for part in path.split("/") if part]
|
||||
if not parts:
|
||||
return False
|
||||
if parts[-1] in _ENV_FILE_BASENAMES or parts[-1] in _SHELL_RC_BASENAMES:
|
||||
return True
|
||||
return parts[-1] == "config.yaml" and (hermes_home or ".hermes" in parts[:-1])
|
||||
|
||||
|
||||
def _command_reads_secret_file(command: str | None) -> bool:
|
||||
"""True if ``command`` reads a secret-bearing file (see ``_is_secret_file_arg``) to
|
||||
stdout. Defense-in-depth, not a boundary: indirect reads (``sudo cat .env``, ``$(cat
|
||||
.env)``, unresolved variable paths) are not detected, matching ``is_env_dump_command``."""
|
||||
if not command or not isinstance(command, str):
|
||||
return False
|
||||
for seg in _command_segments(command):
|
||||
tokens = seg.split() # not shlex: it mangles Windows paths (``C:\Users\...\.env``)
|
||||
if not tokens or tokens[0] not in _FILE_READ_COMMANDS:
|
||||
if not tokens:
|
||||
continue
|
||||
for arg in tokens[1:]:
|
||||
if arg.startswith("-"):
|
||||
continue
|
||||
basename = arg.strip("\"'").rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
|
||||
if basename.lower() in _ENV_FILE_BASENAMES:
|
||||
return True
|
||||
reader = tokens[0].rsplit("/", 1)[-1].lower()
|
||||
if reader not in _FILE_READ_COMMANDS:
|
||||
continue
|
||||
positional = [arg for arg in tokens[1:] if not arg.startswith("-")]
|
||||
if reader in _PATTERN_FIRST_COMMANDS:
|
||||
positional = positional[1:]
|
||||
if any(_is_secret_file_arg(arg) for arg in positional):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@@ -820,13 +1033,20 @@ def redact_for_egress(text: str) -> str:
|
||||
|
||||
|
||||
def redact_terminal_output(output: str, command: str | None = None, *, force: bool = False) -> str:
|
||||
"""Single redaction policy for ALL terminal-output surfaces: the ENV-assignment
|
||||
pass runs only when ``command`` is an env dump or reads a ``.env`` file
|
||||
(otherwise code_file=True avoids false positives on source/config dumps)."""
|
||||
"""Single redaction policy for ALL terminal-output surfaces: the ENV/YAML-assignment
|
||||
pass runs only when ``command`` is an env dump or reads a secret-bearing file (``.env``,
|
||||
shell rc, Hermes ``config.yaml``); otherwise code_file=True avoids false positives on
|
||||
source/config dumps."""
|
||||
if not output:
|
||||
return output
|
||||
code_file = not (is_env_dump_command(command) or _command_reads_env_file(command))
|
||||
return redact_sensitive_text(output, force=force, code_file=code_file)
|
||||
code_file = not (is_env_dump_command(command) or _command_reads_secret_file(command))
|
||||
redacted = redact_sensitive_text(output, force=force, code_file=code_file)
|
||||
# Source-preserving output still gets the Python-repr pass on high-confidence
|
||||
# diagnostic lines (pytest ``E `` introspection, final exception lines): that is
|
||||
# where {'BRAVE_API_KEY': '…'} leaks, not in source dumps.
|
||||
if code_file and (force or _redact_enabled()) and ":" in redacted and "'" in redacted:
|
||||
redacted = _redact_python_diagnostic_repr_fields(redacted)
|
||||
return redacted
|
||||
|
||||
|
||||
# --- Prefix pre-screen: derived from _PREFIX_PATTERNS so a new prefix can't
|
||||
|
||||
+63
-7
@@ -6,12 +6,17 @@ re-issues the unanswered call → endless "thinking"/reboot loop. These pure hel
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from agent.tool_dispatch_helpers import make_tool_result_message
|
||||
from agent.tool_result_classification import tool_may_have_side_effect
|
||||
from agent.turn_context import drop_stale_api_content
|
||||
from hermes_cli.timefmt import coerce_epoch
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -26,12 +31,32 @@ _DANGLING_NOTICES = (
|
||||
)
|
||||
|
||||
|
||||
# Every executor ends the killed run's ``output`` with a bracketed marker line: "[Command
|
||||
# interrupted]" (tools/environments/, exit 130), "[Command interrupted - Modal ...]"
|
||||
# (managed_modal.py, exit 130), "[execution interrupted ...]" (code_execution_tool.py, exit -1).
|
||||
_INTERRUPT_MARKER_LINE = re.compile(r"^\[(?:command|execution) interrupted\b[^\n]*\]\s*$", re.IGNORECASE)
|
||||
|
||||
|
||||
def is_interrupted_tool_result(content: Any) -> bool:
|
||||
"""Return True if a tool result indicates the tool was interrupted."""
|
||||
"""True only when the result has the executor's interrupt SHAPE: the marker is the last
|
||||
line of the output (JSON envelope with a non-zero exit code, or a bare text result). A
|
||||
marker quoted inside successful output — a grep hit, a doc example — is ordinary data;
|
||||
this runs on every live request, so a false positive rewrites real tool output."""
|
||||
if not isinstance(content, str):
|
||||
return False
|
||||
lowered = content.lower()
|
||||
return "[command interrupted]" in lowered or ("exit_code" in lowered and ("130" in lowered or "-1" in lowered) and "interrupt" in lowered)
|
||||
output = content
|
||||
if content.lstrip().startswith("{"):
|
||||
try:
|
||||
envelope = json.loads(content)
|
||||
except ValueError:
|
||||
return False
|
||||
if not isinstance(envelope, dict) or envelope.get("exit_code") in (0, None):
|
||||
return False
|
||||
output = envelope.get("output")
|
||||
if not isinstance(output, str):
|
||||
return False
|
||||
last_line = output.rstrip().rsplit("\n", 1)[-1]
|
||||
return _INTERRUPT_MARKER_LINE.match(last_line) is not None
|
||||
|
||||
|
||||
def _call_name(call: Dict[str, Any]) -> str:
|
||||
@@ -126,6 +151,26 @@ def sanitize_replay_history(agent_history: List[Dict[str, Any]]) -> List[Dict[st
|
||||
return strip_dangling_tool_call_tail(strip_interrupted_tool_tails(agent_history))
|
||||
|
||||
|
||||
def canonicalize_replay_history(
|
||||
agent_history: List[Dict[str, Any]], *, now: Optional[float] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Apply every destructive replay transform in the shared, fixed order.
|
||||
|
||||
Resume surfaces and the send path must serialize the same history bytes, or a
|
||||
resumed request diverges in the middle of the cached prefix.
|
||||
|
||||
The input is never modified. ``now`` is the expiry clock; the send path passes the
|
||||
turn's admission time so every request in one turn sees the same bytes.
|
||||
"""
|
||||
if not agent_history:
|
||||
return agent_history
|
||||
if now is None:
|
||||
now = time.time()
|
||||
cleaned = strip_interrupted_tool_tails(agent_history)
|
||||
cleaned = strip_dangling_tool_call_tail(cleaned)
|
||||
return strip_stale_dangerous_confirmations(cleaned, now=now)
|
||||
|
||||
|
||||
# --- Stale dangerous-confirmation text expiry ---
|
||||
|
||||
# Short on purpose: a dangerous confirmation must not survive any restart or resume gap.
|
||||
@@ -151,7 +196,10 @@ _EXPIRED_CONFIRMATION_SENTINEL = (
|
||||
|
||||
def is_dangerous_confirmation(content: Any) -> bool:
|
||||
"""True if user-message text contains a known dangerous confirmation phrase."""
|
||||
return isinstance(content, str) and any(pattern in content.strip().lower() for pattern in _DANGEROUS_CONFIRMATION_PATTERNS)
|
||||
if not isinstance(content, str):
|
||||
return False
|
||||
lowered = content.strip().lower()
|
||||
return any(pattern in lowered for pattern in _DANGEROUS_CONFIRMATION_PATTERNS)
|
||||
|
||||
|
||||
def strip_stale_dangerous_confirmations(
|
||||
@@ -174,12 +222,20 @@ def strip_stale_dangerous_confirmations(
|
||||
cleaned: List[Dict[str, Any]] = []
|
||||
for msg in agent_history:
|
||||
ts = msg.get("timestamp") if isinstance(msg, dict) and msg.get("role") == "user" else None
|
||||
if ts is None or not is_dangerous_confirmation(msg.get("content", "")) or (now - float(ts)) <= expiry_seconds:
|
||||
if ts is None or not is_dangerous_confirmation(msg.get("content", "")):
|
||||
cleaned.append(msg)
|
||||
continue
|
||||
# A present-but-untrustworthy stamp (corrupt, or issued in the future relative to
|
||||
# the admission clock) is treated as expired: its age is unknowable, and keeping the
|
||||
# text (plus its api_content sidecar) would replay a live confirmation.
|
||||
ts_f = coerce_epoch(ts, field="message timestamp")
|
||||
age = math.inf if ts_f is None else now - ts_f
|
||||
if 0 <= age <= expiry_seconds:
|
||||
cleaned.append(msg)
|
||||
continue
|
||||
logger.debug(
|
||||
"Redacting stale dangerous-confirmation text in user message (age=%.1fs, expiry=%.1fs): %r",
|
||||
now - float(ts), expiry_seconds, (msg.get("content") or "")[:80],
|
||||
age, expiry_seconds, (msg.get("content") or "")[:80],
|
||||
)
|
||||
redacted = dict(msg)
|
||||
redacted["content"] = _EXPIRED_CONFIRMATION_SENTINEL
|
||||
|
||||
@@ -39,6 +39,29 @@ MAX_DERIVED_TITLE_CHARS = 48
|
||||
# legitimate wordy titles while excluding full-sentence answers.
|
||||
_MAX_TITLE_WORDS = 12
|
||||
|
||||
# The example titles shown to the model in the prompt, and the echo-guard
|
||||
# set: when the opening message carries little topical signal, a small model
|
||||
# sometimes takes the cheapest schema-valid answer and parrots one of these
|
||||
# back verbatim — most visibly "Fix login button on mobile" naming sessions
|
||||
# that have nothing to do with a login button. The prompt's example lines are
|
||||
# rendered from these constants so the guard set and the prompt cannot drift
|
||||
# apart. Port of QwenLM/qwen-code#9709.
|
||||
_PROMPT_GOOD_EXAMPLES = (
|
||||
"Fix login button on mobile",
|
||||
"Postgres connection pool exhaustion",
|
||||
"Friendly greeting",
|
||||
)
|
||||
_PROMPT_VAGUE_EXAMPLE = "Code changes"
|
||||
|
||||
# "Friendly greeting" is deliberately NOT in the reject set: the prompt
|
||||
# instructs the model to produce it for bare greetings, so it is a legitimate
|
||||
# output, not an echo failure. The too-vague example is rejected too — a model
|
||||
# repeating the counter-example says nothing about the session, and the
|
||||
# derived title the guard falls back to is strictly more informative.
|
||||
_EXAMPLE_ECHO_REJECT = frozenset(
|
||||
t.lower() for t in _PROMPT_GOOD_EXAMPLES if t != "Friendly greeting"
|
||||
) | {_PROMPT_VAGUE_EXAMPLE.lower()}
|
||||
|
||||
_TITLE_PROMPT_TEMPLATE = (
|
||||
"You name chat sessions. Given the user's opening message, write a title "
|
||||
"that lets them find this conversation again in a list.\n\n"
|
||||
@@ -51,10 +74,8 @@ _TITLE_PROMPT_TEMPLATE = (
|
||||
"- Never answer the message. Name it.\n"
|
||||
"- Always produce something, even for a bare greeting.\n"
|
||||
"__LANGUAGE_RULE__\n"
|
||||
'Good: {"title": "Fix login button on mobile"}\n'
|
||||
'Good: {"title": "Postgres connection pool exhaustion"}\n'
|
||||
'Good: {"title": "Friendly greeting"}\n'
|
||||
'Too vague: {"title": "Code changes"}\n'
|
||||
+ "".join(f'Good: {{"title": "{t}"}}\n' for t in _PROMPT_GOOD_EXAMPLES)
|
||||
+ f'Too vague: {{"title": "{_PROMPT_VAGUE_EXAMPLE}"}}\n'
|
||||
'Too long: {"title": "Investigate and fix the issue where the login button '
|
||||
'does not respond on mobile devices"}\n\n'
|
||||
'Reply with JSON only: {"title": "..."}'
|
||||
@@ -229,6 +250,18 @@ def _notify_title(title_callback: Optional[TitleCallback], title: str, source: s
|
||||
_safe_callback(title_callback, (title, source), "%s callback failed", label)
|
||||
|
||||
|
||||
def _is_prompt_example_echo(title: str) -> bool:
|
||||
"""Return True when *title* is one of the prompt's own example titles.
|
||||
|
||||
Comparison is case-insensitive after stripping any leading/trailing run of
|
||||
non-letter/non-digit characters, so bracket/quote wrappers cannot bypass
|
||||
the guard — while ``_clean_title`` keeps brackets for real titles like
|
||||
"(WIP) Fix build". Unicode-aware so full-width wrappers are covered too.
|
||||
"""
|
||||
normalized = re.sub(r"^[\W_]+|[\W_]+$", "", title.strip(), flags=re.UNICODE).lower()
|
||||
return normalized in _EXAMPLE_ECHO_REJECT
|
||||
|
||||
|
||||
def generate_title(
|
||||
user_message: str,
|
||||
timeout: Optional[float] = None,
|
||||
@@ -285,6 +318,17 @@ def generate_title(
|
||||
# Answer-shaped output: reject (not truncate) so the caller retries next exchange.
|
||||
logger.debug("Rejecting answer-shaped title output (%d words > %d)", len(title.split()), _MAX_TITLE_WORDS)
|
||||
return None
|
||||
# Example-echo guard: a title that parrots one of the prompt's own
|
||||
# examples back verbatim says nothing about the session — reject it so
|
||||
# the instant derived title (a slice of the user's actual words)
|
||||
# survives instead. Exact match after wrapper-stripping, deliberately
|
||||
# not fuzzy, so a genuinely topical title that merely resembles an
|
||||
# example still passes. Wrappers are stripped for the comparison only
|
||||
# ("(Fix login button on mobile)" is the same canned echo as the bare
|
||||
# example). Port of QwenLM/qwen-code#9709.
|
||||
if title is not None and _is_prompt_example_echo(title):
|
||||
logger.debug("Rejecting prompt-example echo title: %r", title)
|
||||
return None
|
||||
return title
|
||||
except Exception as e:
|
||||
# WARNING so it shows in agent.log without debug mode; stack at debug.
|
||||
|
||||
@@ -786,7 +786,9 @@ def _resolve_sequential_tool_timeout() -> float | None:
|
||||
# 420 s deadline every real batch "timed out" while its children ran on as orphans, and the orchestrator
|
||||
# spent the following hours polling transcripts (measured: 332 timeouts, ~$4k of orchestrator turns in
|
||||
# one run).
|
||||
_SEQUENTIAL_DEADLINE_EXEMPT_TOOLS = frozenset({"delegate_task"})
|
||||
# ``manage_connections`` waits on the connection operation's own deadline; the generic deadline
|
||||
# would return tool_timeout while its approval card is still open.
|
||||
_SEQUENTIAL_DEADLINE_EXEMPT_TOOLS = frozenset({"delegate_task", "manage_connections"})
|
||||
|
||||
|
||||
def _abandoned_sequential_result(agent, ref: _ToolCallRef, message: str, result_cls, **outcome) -> _ManagedToolResult:
|
||||
|
||||
@@ -13,6 +13,7 @@ from agent.reasoning_effort import (
|
||||
KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES, OPENAI_COMPAT_WIRE_EFFORTS, TOKENHUB_EFFORTS, clamp_effort,
|
||||
kimi_supported_efforts, requested_effort,
|
||||
)
|
||||
from agent.message_sanitization import normalize_finish_reason as _normalize_finish_reason
|
||||
from agent.moonshot_schema import is_moonshot_model, sanitize_moonshot_tools
|
||||
from agent.prompt_builder import DEVELOPER_ROLE_MODELS
|
||||
from agent.transports.base import ProviderTransport
|
||||
@@ -512,7 +513,9 @@ class ChatCompletionsTransport(ProviderTransport):
|
||||
choice = response.choices[0]
|
||||
msg = getattr(choice, "message", None)
|
||||
_fr = getattr(choice, "finish_reason", None)
|
||||
finish_reason = (str(_fr) if isinstance(_fr, int) else _fr) or "stop" # Poolside returns int finish_reason
|
||||
# Poolside returns int finish_reason; Gemini-fronting gateways return
|
||||
# uppercase STOP / MAX_TOKENS — fold to the OpenAI contract here.
|
||||
finish_reason = _normalize_finish_reason(str(_fr) if isinstance(_fr, int) else _fr) or "stop"
|
||||
|
||||
tool_calls = None
|
||||
if getattr(msg, "tool_calls", None):
|
||||
|
||||
@@ -12,9 +12,7 @@ from dataclasses import dataclass
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from agent.message_sanitization import (
|
||||
_sanitize_structure_non_ascii, _sanitize_structure_surrogates
|
||||
)
|
||||
from agent.message_sanitization import sanitize_outbound_kwargs
|
||||
from utils import env_var_enabled
|
||||
|
||||
logger = logging.getLogger("agent.conversation_loop")
|
||||
@@ -120,17 +118,9 @@ def build_api_request(
|
||||
api_kwargs = agent._build_api_kwargs(api_messages)
|
||||
else:
|
||||
api_kwargs = agent._build_api_kwargs(api_messages, tools_for_api=tools_for_api)
|
||||
# Surrogate chokepoint: tool descriptions, extra_body and kwargs strings can carry
|
||||
# invalid code points (HTTP 400). One walk makes the payload json.dumps()-safe.
|
||||
# Outbound-request surrogate chokepoint (#50959): the messages were scrubbed above, but the rest of the
|
||||
# request body — tool/function descriptions (session_search's ±-heavy text is the recorded repro),
|
||||
# extra_body, system strings routed via kwargs — can still carry invalid code points that providers
|
||||
# reject with a non-retryable HTTP 400 ("invalid unicode code point"). One in-place walk here guarantees
|
||||
# the entire payload json.dumps()-safe regardless of which leaf produced the string. Fast no-op when the
|
||||
# payload is clean.
|
||||
_sanitize_structure_surrogates(api_kwargs)
|
||||
if agent._force_ascii_payload:
|
||||
_sanitize_structure_non_ascii(api_kwargs)
|
||||
# Messages were scrubbed above; this walk covers the rest of the payload (tool descriptions,
|
||||
# extra_body, kwargs strings) — see sanitize_outbound_kwargs for the #50959 rationale.
|
||||
sanitize_outbound_kwargs(agent, api_kwargs)
|
||||
if agent.api_mode == "codex_responses":
|
||||
api_kwargs = agent._get_transport().preflight_kwargs(
|
||||
api_kwargs, allow_stream=False, is_github_responses=agent._is_copilot_url(),
|
||||
|
||||
+25
-3
@@ -508,6 +508,11 @@ def _reset_per_turn_agent_state(agent: Any) -> None:
|
||||
_reset_consol = getattr(agent._memory_store, "reset_consolidation_failures", None)
|
||||
if callable(_reset_consol):
|
||||
_reset_consol()
|
||||
# Expiry clock for build_api_messages: admission time (not the input's platform-event
|
||||
# stamp, which can predate admission by minutes), frozen so every request this turn
|
||||
# sends identical bytes. Distinct from note_turn_start's _inflight_turn_started, a
|
||||
# tripwire slot cleared at persist.
|
||||
agent._current_turn_timestamp = time.time()
|
||||
|
||||
# Pre-turn connection health check: clean up dead TCP connections.
|
||||
if agent.api_mode != "anthropic_messages":
|
||||
@@ -1047,9 +1052,26 @@ def build_api_messages(
|
||||
replayed verbatim."""
|
||||
from agent.agent_runtime_helpers import fill_empty_non_final_wire_payload
|
||||
from agent.conversation_loop import _clone_message_for_send
|
||||
from agent.replay_cleanup import canonicalize_replay_history
|
||||
|
||||
has_current = isinstance(current_turn_user_idx, int) and 0 <= current_turn_user_idx < len(messages)
|
||||
current_turn_message = messages[current_turn_user_idx] if has_current else None
|
||||
|
||||
# Replay consumers canonicalize the persisted prefix on read; the request copy must
|
||||
# carry the same bytes or a resume diverges mid-prefix. Only the rows BEFORE this
|
||||
# turn's user message are the replayed prefix — rows this turn appended (its tool
|
||||
# calls/results) are live and must never be rewritten between iterations. The
|
||||
# expiry clock is the turn's admission time, frozen in _reset_per_turn_agent_state.
|
||||
# Without an anchor (compaction found no surviving user row) there is no provable
|
||||
# persisted prefix, so nothing is canonicalized. The clock is stamped once per turn in
|
||||
# _reset_per_turn_agent_state; a caller that skipped the prologue fails loudly here
|
||||
# rather than silently un-freezing it.
|
||||
turn_now = agent._current_turn_timestamp
|
||||
split = current_turn_user_idx if has_current else 0
|
||||
canonical_messages = canonicalize_replay_history(messages[:split], now=turn_now) + messages[split:]
|
||||
|
||||
api_messages = []
|
||||
for idx, msg in enumerate(messages):
|
||||
for idx, msg in enumerate(canonical_messages):
|
||||
# Structural clone, NOT msg.copy(): in-place transforms below must not reach
|
||||
# persisted history via nested containers; see _clone_message_for_send.
|
||||
api_msg = _clone_message_for_send(msg)
|
||||
@@ -1063,7 +1085,7 @@ def build_api_messages(
|
||||
|
||||
# Inject ephemeral context (memory prefetch + pre_llm_call user hooks)
|
||||
# at API time only; `messages` is untouched beyond the api_content stamp.
|
||||
if idx == current_turn_user_idx and msg.get("role") == "user":
|
||||
if msg is current_turn_message and msg.get("role") == "user":
|
||||
if isinstance(_api_content, str) and _api_content:
|
||||
# Reuse the prologue's stamp so sidecar and wire cannot drift
|
||||
# and every pass this turn sends identical bytes.
|
||||
@@ -1094,7 +1116,7 @@ def build_api_messages(
|
||||
# Fill empty non-final user/assistant wire copies so the pre-call sanitizer
|
||||
# stops re-healing and flooding errors.log; durable history is untouched.
|
||||
# After the reasoning copy so thinking-only turns keep payload.
|
||||
fill_empty_non_final_wire_payload(api_msg, is_final=(idx == len(messages) - 1))
|
||||
fill_empty_non_final_wire_payload(api_msg, is_final=(idx == len(canonical_messages) - 1))
|
||||
# _thinking_prefill survives intentionally: the drop pass below needs it.
|
||||
# Strip length-continuation marks; some transports keep underscore keys.
|
||||
api_msg.pop("_length_continuation_fragment", None)
|
||||
|
||||
@@ -72,6 +72,26 @@ def finish_text_response(
|
||||
result=result,
|
||||
)
|
||||
|
||||
# Reasoning-only clean stop: some reasoning parsers (vLLM nemotron_v3 past ~500K
|
||||
# prompt tokens) file the whole answer as reasoning when the model omits the closing
|
||||
# delimiter. ``finish_reason == "stop"`` means the provider considers generation
|
||||
# complete, so the empty-response ladder would only re-bill the same input to arrive
|
||||
# at a truncated preview of this text; promote the reasoning to the visible answer
|
||||
# BEFORE the ladder. ``length`` (cut off mid-thought) stays on the continuation path,
|
||||
# and the promoted text is persisted as ordinary content so the next turn replays it.
|
||||
_content = assistant_message.content
|
||||
if (
|
||||
finish_reason == "stop"
|
||||
and not assistant_message.tool_calls
|
||||
and (_content is None or (isinstance(_content, str) and not _content.strip()))
|
||||
):
|
||||
_promoted = agent._extract_reasoning(assistant_message)
|
||||
if _promoted:
|
||||
logger.info(
|
||||
"Reasoning-only clean stop (%d chars) — using reasoning as the final response",
|
||||
len(_promoted),
|
||||
)
|
||||
assistant_message.content = _promoted
|
||||
final_response = assistant_message.content or ""
|
||||
# Unmute: _mute_post_response from a housekeeping tool turn must not silence
|
||||
# empty-response warnings on the final response path.
|
||||
|
||||
@@ -271,6 +271,10 @@ so glass and message-bubble transparency do not reveal scrolling text.
|
||||
from the chip to the floating pill; leaving both dismisses it.
|
||||
- A tool result may expose an inline action that opens a preview. It must not
|
||||
open the rail automatically.
|
||||
- Tool rows reserve destructive red for explicit failures. Missing read paths and
|
||||
ambiguous exit-1 results use neutral notices, with details still available.
|
||||
Errors described inside returned data are not tool failures. Expanded failures
|
||||
show the actual explanation; supporting output keeps its normal text color.
|
||||
- Composer status groups start collapsed except todos. Progress updates and queue
|
||||
pause/resume preserve the user's disclosure choice. Error banners meet the
|
||||
stack's top edge without a blank padding strip. File and preview links remain
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
|
||||
import { expect, test } from './test'
|
||||
|
||||
// #100406: in a Bot Mode group room a teammate's `@hermes` handoff must give
|
||||
// the primary profile (internal name `default`) its turn, exactly like
|
||||
// `@hermes → @code-farmer` already does. The live roster stamps the primary
|
||||
// row's handle as the bare profile id ("default"), and the mention parser let
|
||||
// that stamped handle shadow the `@hermes` alias — so the room settled with
|
||||
// Hermes never driven. The mock inference server scripts each member's line
|
||||
// from the user's send (`E2E_SAY(<handle>)[…]`), so the assertion is on the
|
||||
// persisted room log: an entry authored by `default` saying "B".
|
||||
|
||||
let fixture: MockBackendFixture | null = null
|
||||
|
||||
type Page = MockBackendFixture['page']
|
||||
|
||||
interface RoomLogEntry {
|
||||
from?: { kind?: string; name?: string }
|
||||
text?: string
|
||||
}
|
||||
|
||||
async function openBots(page: Page): Promise<void> {
|
||||
const tab = page
|
||||
.getByRole('button', { name: 'Bots', exact: true })
|
||||
.or(page.getByRole('tab', { name: 'Bots', exact: true }))
|
||||
.first()
|
||||
|
||||
await tab.click()
|
||||
await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()
|
||||
}
|
||||
|
||||
async function createAgent(page: Page, name: string, title: string): Promise<void> {
|
||||
await page.getByRole('button', { name: 'New bot or group chat' }).click()
|
||||
await page.getByRole('menuitem', { name: 'New Bot' }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog', { name: 'New Bot' })
|
||||
await dialog.getByPlaceholder('inbox-triage').fill(name)
|
||||
await dialog.getByPlaceholder('Inbox Triage').fill(title)
|
||||
await dialog.getByRole('button', { name: 'Create Bot' }).click()
|
||||
await expect(dialog).toBeHidden({ timeout: 30_000 })
|
||||
await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
|
||||
}
|
||||
|
||||
/** The plugin's persisted room log (`hermes.plugin.hermes-bots.group-chats`). */
|
||||
async function roomLog(page: Page, group: string): Promise<RoomLogEntry[]> {
|
||||
return page.evaluate(name => {
|
||||
const raw = window.localStorage.getItem('hermes.plugin.hermes-bots.group-chats')
|
||||
const rooms = raw ? (JSON.parse(raw) as Record<string, { log?: RoomLogEntry[] }>) : {}
|
||||
|
||||
return rooms[name]?.log ?? []
|
||||
}, group)
|
||||
}
|
||||
|
||||
test.beforeAll(async () => {
|
||||
fixture = await setupMockBackend()
|
||||
await waitForAppReady(fixture, 120_000)
|
||||
})
|
||||
|
||||
// Playwright requires an object-destructured fixture argument.
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
test.afterEach(async ({}, info) => {
|
||||
if (!fixture) {
|
||||
return
|
||||
}
|
||||
|
||||
await info.attach('room-log', {
|
||||
body: JSON.stringify(await roomLog(fixture.page, 'Hermes, Code Farmer'), null, 2),
|
||||
contentType: 'application/json'
|
||||
})
|
||||
await info.attach('native-window', { body: await fixture.page.screenshot(), contentType: 'image/png' })
|
||||
await info.attach('runtime-source', {
|
||||
body: JSON.stringify(
|
||||
await fixture.app.evaluate(() => ({
|
||||
cwd: process.cwd(),
|
||||
argv: process.argv,
|
||||
root: process.env.HERMES_DESKTOP_HERMES_ROOT,
|
||||
home: process.env.HERMES_HOME
|
||||
})),
|
||||
null,
|
||||
2
|
||||
),
|
||||
contentType: 'application/json'
|
||||
})
|
||||
await info.attach('desktop-log', {
|
||||
body: readFileSync(join(fixture.sandbox.hermesHome, 'logs/desktop.log')),
|
||||
contentType: 'text/plain'
|
||||
})
|
||||
})
|
||||
|
||||
test.afterAll(async () => {
|
||||
await fixture?.cleanup()
|
||||
fixture = null
|
||||
})
|
||||
|
||||
test('a teammate handing off with @hermes drives the primary profile', async () => {
|
||||
test.setTimeout(420_000)
|
||||
const page = fixture!.page
|
||||
const group = 'Hermes, Code Farmer'
|
||||
|
||||
await openBots(page)
|
||||
await createAgent(page, 'code-farmer', 'Code Farmer')
|
||||
|
||||
await page.getByRole('button', { name: 'New bot or group chat' }).click()
|
||||
await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
|
||||
|
||||
for (const title of ['Hermes', 'Code Farmer']) {
|
||||
await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
|
||||
}
|
||||
|
||||
await dialog.getByRole('textbox', { name: 'Group name' }).fill(group)
|
||||
await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
|
||||
|
||||
const composer = page.getByRole('textbox', { name: `Message ${group}` }).filter({ visible: true })
|
||||
await expect(composer).toBeVisible({ timeout: 20_000 })
|
||||
|
||||
// Only Code Farmer is addressed by the user. Its scripted reply hands off
|
||||
// to @hermes; Hermes' scripted reply is "B". Neither script token carries
|
||||
// a literal `@`, so the user send itself never mentions Hermes.
|
||||
await composer.fill(
|
||||
'@code-farmer Please reply with one line only. ' +
|
||||
'E2E_SAY(code-farmer)[{at}hermes Please reply with the letter B.] E2E_SAY(hermes)[B]'
|
||||
)
|
||||
await composer.press('Enter')
|
||||
|
||||
// Code Farmer's handoff line lands first (the reverse direction is not in
|
||||
// question); then the room must NOT settle without Hermes' turn.
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await roomLog(page, group)).some(e => e.from?.name === 'code-farmer' && /@hermes/.test(e.text || '')),
|
||||
{
|
||||
timeout: 180_000
|
||||
}
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => (await roomLog(page, group)).some(e => e.from?.name === 'default' && (e.text || '').trim() === 'B'),
|
||||
{
|
||||
timeout: 180_000,
|
||||
message: 'the primary profile (default / @hermes) never took its turn after being @mentioned by a teammate'
|
||||
}
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
// And the transcript shows the handoff answered.
|
||||
await expect(page.getByText('B', { exact: true }).filter({ visible: true }).first()).toBeVisible()
|
||||
|
||||
await composer.fill(
|
||||
'@hermes Begin the reverse handoff. E2E_SAY(hermes)[{at}code-farmer Reply with D.] E2E_SAY(code-farmer)[D]'
|
||||
)
|
||||
await composer.press('Enter')
|
||||
await expect
|
||||
.poll(async () => (await roomLog(page, group)).some(e => e.from?.name === 'code-farmer' && e.text?.trim() === 'D'), {
|
||||
timeout: 180_000
|
||||
})
|
||||
.toBe(true)
|
||||
})
|
||||
@@ -0,0 +1,235 @@
|
||||
import { MOCK_REPLY } from '../../../tests-js/scripts/mock-server'
|
||||
|
||||
import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
|
||||
import { expect, test } from './test'
|
||||
|
||||
const FIRST_REPLY = 'FIRST_REPLY: initial work completed'
|
||||
const FOLLOWUP_REPLY = 'FOLLOWUP_REPLY: subsequent work completed'
|
||||
let fixture: MockBackendFixture | null = null
|
||||
|
||||
async function publicLog(page: MockBackendFixture['page']) {
|
||||
return page.evaluate(() => {
|
||||
const rooms = JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')
|
||||
|
||||
return (rooms['Programmer, Reviewer']?.log || []).map((entry: any) => ({
|
||||
from: entry.from.name, text: entry.text, thread: entry.thread
|
||||
})) as { from: string; text: string; thread: string }[]
|
||||
})
|
||||
}
|
||||
|
||||
async function openBots(page: MockBackendFixture['page']): Promise<void> {
|
||||
const tab = page.getByRole('button', { name: 'Bots', exact: true }).or(page.getByRole('tab', { name: 'Bots', exact: true })).first()
|
||||
await tab.click()
|
||||
await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()
|
||||
}
|
||||
|
||||
async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {
|
||||
await page.getByRole('button', { name: 'New bot or group chat' }).click()
|
||||
await page.getByRole('menuitem', { name: 'New Bot' }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog', { name: 'New Bot' })
|
||||
await dialog.getByPlaceholder('inbox-triage').fill(name)
|
||||
await dialog.getByPlaceholder('Inbox Triage').fill(title)
|
||||
await dialog.getByRole('button', { name: 'Create Bot' }).click()
|
||||
await expect(dialog).toBeHidden({ timeout: 30_000 })
|
||||
await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
|
||||
}
|
||||
|
||||
async function createRoom(page: MockBackendFixture['page']) {
|
||||
await openBots(page)
|
||||
await createAgent(page, 'programmer', 'Programmer')
|
||||
await createAgent(page, 'reviewer', 'Reviewer')
|
||||
|
||||
await page.getByRole('button', { name: 'New bot or group chat' }).click()
|
||||
await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
|
||||
|
||||
for (const title of ['Programmer', 'Reviewer']) {
|
||||
await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
|
||||
}
|
||||
|
||||
await dialog.getByRole('textbox', { name: 'Group name' }).fill('Programmer, Reviewer')
|
||||
await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
|
||||
|
||||
const groupTab = page.getByRole('tab', { name: /Programmer, Reviewer Close/ })
|
||||
const groupComposer = page.getByRole('textbox', { name: 'Message Programmer, Reviewer' }).filter({ visible: true })
|
||||
await expect(groupTab).toBeVisible({ timeout: 20_000 })
|
||||
await expect(groupTab).toHaveAttribute('aria-selected', 'true')
|
||||
await expect(groupComposer).toBeVisible()
|
||||
|
||||
|
||||
return groupComposer
|
||||
}
|
||||
|
||||
test.beforeEach(async () => {
|
||||
fixture = await setupMockBackend({ mockServer: {
|
||||
holdFirstCompletionContaining: 'LANE_A_FIRST',
|
||||
replyForPrompt: prompt => prompt.includes('LANE_A_FOLLOWUP') ? FOLLOWUP_REPLY : prompt.includes('LANE_A_FIRST') ? FIRST_REPLY : MOCK_REPLY
|
||||
} })
|
||||
await waitForAppReady(fixture, 120_000)
|
||||
})
|
||||
|
||||
test.afterEach(async () => {
|
||||
await fixture?.cleanup()
|
||||
fixture = null
|
||||
})
|
||||
|
||||
test('group follow-up waits for its active member and retains the reply', async () => {
|
||||
test.setTimeout(240_000)
|
||||
const page = fixture!.page
|
||||
const groupComposer = await createRoom(page)
|
||||
await groupComposer.fill('@programmer LANE_A_FIRST')
|
||||
await groupComposer.press('Enter')
|
||||
await fixture!.mock.waitForHeldCompletion()
|
||||
console.log('PRODUCTION CLOCK: first inference held; no second submit before provider release.')
|
||||
await page.screenshot({ path: '/tmp/botmode-campaign/lane-a-held.png' })
|
||||
await page.getByRole('button', { name: 'Reply in thread', exact: true }).click()
|
||||
const replyComposer = page.getByRole('textbox', { name: 'Reply in thread', exact: true })
|
||||
await replyComposer.fill('@programmer LANE_A_FOLLOWUP')
|
||||
await replyComposer.press('Enter')
|
||||
await page.waitForTimeout(3000)
|
||||
const overlapping = fixture!.mock.receivedPrompts.filter(p => p.includes('LANE_A_FOLLOWUP'))
|
||||
console.log('OVERLAPPING', overlapping)
|
||||
fixture!.mock.releaseHeldStream()
|
||||
expect(overlapping).toHaveLength(0)
|
||||
await expect.poll(() => fixture!.mock.receivedPrompts.some(p => p.includes('LANE_A_FOLLOWUP')), { timeout: 60000 }).toBe(true)
|
||||
const delivered = fixture!.mock.receivedPrompts.find(p => p.includes('LANE_A_FOLLOWUP'))!
|
||||
expect(delivered).toContain(FIRST_REPLY)
|
||||
expect(delivered).not.toContain('LANE_A_FIRST')
|
||||
expect(delivered.indexOf('LANE_A_FOLLOWUP')).toBeLessThan(delivered.indexOf(FIRST_REPLY))
|
||||
await expect(page.getByText(FIRST_REPLY, { exact: true }).filter({ visible: true })).toHaveCount(1)
|
||||
await expect(page.getByText(FOLLOWUP_REPLY, { exact: true }).filter({ visible: true })).toHaveCount(1)
|
||||
await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0)
|
||||
const log = await publicLog(page)
|
||||
expect(log.map(({ from, text }) => [from, text])).toEqual([
|
||||
['You', '@programmer LANE_A_FIRST'], ['You', '@programmer LANE_A_FOLLOWUP'],
|
||||
['programmer', FIRST_REPLY], ['programmer', FOLLOWUP_REPLY]
|
||||
])
|
||||
expect(new Set(log.map(entry => entry.thread)).size).toBe(1)
|
||||
expect(fixture!.mock.receivedPrompts.filter(p => p.includes('LANE_A_FIRST'))).toHaveLength(1)
|
||||
expect(fixture!.mock.receivedPrompts.filter(p => p.includes('LANE_A_FOLLOWUP'))).toHaveLength(1)
|
||||
console.log('PRODUCTION CLOCK: released; exact public log', JSON.stringify(log))
|
||||
await page.screenshot({ path: '/tmp/botmode-campaign/lane-a-followup-after.png' })
|
||||
})
|
||||
|
||||
test('quiet group still harvests a late answer after sixty observation ticks', async () => {
|
||||
test.setTimeout(240_000)
|
||||
const page = fixture!.page
|
||||
const groupComposer = await createRoom(page)
|
||||
|
||||
await groupComposer.fill('@programmer LANE_A_FIRST')
|
||||
await groupComposer.press('Enter')
|
||||
await fixture!.mock.waitForHeldCompletion()
|
||||
// Jump only the deadline clock, not WebSocket heartbeats or reconnect timers.
|
||||
await page.evaluate(() => {
|
||||
const now = Date.now
|
||||
Date.now = () => now() + 21 * 60_000
|
||||
|
||||
const timeout = window.setTimeout.bind(window)
|
||||
|
||||
;(window as any).__harvestTicks = 0
|
||||
window.setTimeout = ((handler: TimerHandler, delay?: number, ...args: any[]) => {
|
||||
if (delay === 5000) {
|
||||
return timeout(() => {
|
||||
(window as any).__harvestTicks++
|
||||
|
||||
if (typeof handler === 'function') { handler(...args) }
|
||||
}, 100)
|
||||
}
|
||||
|
||||
return timeout(handler, delay, ...args)
|
||||
}) as typeof window.setTimeout
|
||||
})
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__harvestTicks), { timeout: 60000 }).toBeGreaterThanOrEqual(60)
|
||||
await new Promise(resolve => setTimeout(resolve, 1500))
|
||||
console.log('Harvest ticks before release:', await page.evaluate(() => (window as any).__harvestTicks))
|
||||
console.log('Activity before release:', await page.getByRole('button', { name: /^Activity/ }).textContent())
|
||||
fixture!.mock.releaseHeldStream()
|
||||
await expect(page.getByText(FIRST_REPLY, { exact: true }).filter({ visible: true })).toHaveCount(1, { timeout: 5000 })
|
||||
await page.waitForTimeout(1000)
|
||||
expect((await publicLog(page)).filter(entry => entry.from === 'programmer').map(entry => entry.text)).toEqual([FIRST_REPLY])
|
||||
console.log('ACCELERATED DEADLINE/OBSERVATION CLOCK ONLY: exact late public log', JSON.stringify(await publicLog(page)))
|
||||
await page.screenshot({ path: '/tmp/botmode-campaign/lane-a-late-after.png' })
|
||||
})
|
||||
|
||||
test('a rejected member turn stays visible when the room settles', async () => {
|
||||
test.setTimeout(240_000)
|
||||
const page = fixture!.page
|
||||
await page.evaluate(() => {
|
||||
const send = WebSocket.prototype.send
|
||||
|
||||
WebSocket.prototype.send = function(data) {
|
||||
const frame = JSON.parse(String(data))
|
||||
|
||||
if (frame.method === 'prompt.submit' && JSON.stringify(frame.params).includes('LANE_A_FAILURE')) {
|
||||
(window as any).__rejected = ((window as any).__rejected || 0) + 1
|
||||
const reject = () => this.dispatchEvent(new MessageEvent('message', { data: JSON.stringify({ jsonrpc: '2.0', id: frame.id, error: { code: 4003, message: 'Controlled member admission refusal' } }) }))
|
||||
|
||||
if ((window as any).__rejected <= 3) { (window as any).__releaseRefusal = reject } else { queueMicrotask(reject) }
|
||||
} else {
|
||||
send.call(this, data)
|
||||
}
|
||||
}
|
||||
})
|
||||
const groupComposer = await createRoom(page)
|
||||
|
||||
await groupComposer.fill('@programmer LANE_A_FAILURE')
|
||||
await groupComposer.press('Enter')
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__rejected), { timeout: 30000 }).toBe(1)
|
||||
await page.getByRole('button', { name: 'Reply in thread', exact: true }).click()
|
||||
const replyComposer = page.getByRole('textbox', { name: 'Reply in thread', exact: true })
|
||||
await replyComposer.fill('@programmer prequeued LANE_A_FAILURE')
|
||||
await replyComposer.press('Enter')
|
||||
await groupComposer.fill('@programmer cross-thread LANE_A_FAILURE')
|
||||
await groupComposer.press('Enter')
|
||||
console.log('PRODUCTION CLOCK / CONTROLLED TRANSPORT: two sends queued before refusal released')
|
||||
await page.evaluate(() => (window as any).__releaseRefusal())
|
||||
await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0)
|
||||
await page.waitForTimeout(2000)
|
||||
expect(await page.evaluate(() => (window as any).__rejected)).toBe(1)
|
||||
expect((await publicLog(page)).filter(entry => entry.from !== 'You')).toEqual([])
|
||||
await expect(page.getByRole('button', { name: /^Activity/ })).toContainText('Programmer hit an error')
|
||||
await page.screenshot({ path: '/tmp/botmode-campaign/lane-a-error-after.png' })
|
||||
|
||||
// One epoch: A fails, B waits, the user retries A, then B and A fail.
|
||||
// The retry is explicit and after A's failure, unlike the prequeued sends above.
|
||||
await groupComposer.fill('@programmer LANE_A_FAILURE recency')
|
||||
await groupComposer.press('Enter')
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__rejected)).toBe(2)
|
||||
await groupComposer.fill('@reviewer LANE_A_FAILURE recency')
|
||||
await groupComposer.press('Enter')
|
||||
await page.evaluate(() => (window as any).__releaseRefusal())
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__rejected)).toBe(3)
|
||||
await groupComposer.fill('@programmer LANE_A_FAILURE explicit retry')
|
||||
await groupComposer.press('Enter')
|
||||
await page.evaluate(() => (window as any).__releaseRefusal())
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__rejected), { timeout: 30000 }).toBe(4)
|
||||
await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: /^Activity/ })).toContainText('Programmer hit an error')
|
||||
console.log('CONTROLLED REFUSAL: A failed, B failed, A failed again; newest unresolved summary:', await page.getByRole('button', { name: /^Activity/ }).textContent())
|
||||
})
|
||||
|
||||
test('Stop clears a queued follow-up and a direct mention resumes the held member', async () => {
|
||||
test.setTimeout(240_000)
|
||||
const page = fixture!.page
|
||||
const groupComposer = await createRoom(page)
|
||||
await groupComposer.fill('@programmer LANE_A_FIRST')
|
||||
await groupComposer.press('Enter')
|
||||
await fixture!.mock.waitForHeldCompletion()
|
||||
await page.getByRole('button', { name: 'Reply in thread', exact: true }).click()
|
||||
const replyComposer = page.getByRole('textbox', { name: 'Reply in thread', exact: true })
|
||||
await replyComposer.fill('@programmer LANE_A_CANCELLED')
|
||||
await replyComposer.press('Enter')
|
||||
await page.getByRole('button', { name: 'Stop', exact: true }).click()
|
||||
fixture!.mock.releaseHeldStream()
|
||||
await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0)
|
||||
await page.waitForTimeout(2000)
|
||||
expect(fixture!.mock.receivedPrompts.some(p => p.includes('LANE_A_CANCELLED'))).toBe(false)
|
||||
console.log('Stop: queued inference count = 0; paused status:', await page.getByText(/Paused:/).allTextContents())
|
||||
await groupComposer.fill('@programmer LANE_A_RESUME')
|
||||
await groupComposer.press('Enter')
|
||||
await expect.poll(() => fixture!.mock.receivedPrompts.some(p => p.includes('LANE_A_RESUME')), { timeout: 60000 }).toBe(true)
|
||||
await expect(page.getByText(MOCK_REPLY, { exact: true }).first()).toBeVisible()
|
||||
await page.screenshot({ path: '/tmp/botmode-campaign/lane-a-stop-resume.png' })
|
||||
})
|
||||
@@ -8,7 +8,8 @@ export const GUEST_ONBOARDING_ENV = 'HERMES_GUEST_ONBOARDING'
|
||||
export const GUEST_ONBOARDING_FLAG = '--guest-onboarding'
|
||||
// Skip the first-run film. A rehearsal aid: the intro is a one-time reveal,
|
||||
// so anyone iterating on the guided chat behind it otherwise sits through it
|
||||
// on every fresh HERMES_HOME. Renderer-only; the backend never sees it.
|
||||
// on every fresh HERMES_HOME. The guide still runs — only the film is
|
||||
// skipped. Renderer-only; the backend never sees it.
|
||||
export const SKIP_INTRO_ENV = 'HERMES_SKIP_INTRO'
|
||||
export const SKIP_INTRO_FLAG = '--skip-intro'
|
||||
|
||||
|
||||
@@ -378,6 +378,7 @@ import { ensureLoginShellPath } from './shell-path'
|
||||
import { createBootstrapCoordinator, sshConfigFingerprint } from './ssh-bootstrap-coordinator'
|
||||
import { collectSshConfigHosts, parseSshGOutput } from './ssh-config'
|
||||
import { createSshProbeConnection, pickLocalPort, redactSecrets, SshConnection } from './ssh-connection'
|
||||
import { createSshIsolatedKeepaliveRegistry } from './ssh-isolated-keepalive'
|
||||
import { createSshTeardownTracker } from './ssh-teardown'
|
||||
import { createStreamThrottle } from './stream-throttle'
|
||||
import { registerTerminalIpc } from './terminal-ipc'
|
||||
@@ -10107,6 +10108,9 @@ async function buildRemoteConnection(
|
||||
}
|
||||
|
||||
const sshConnections = new Map<string, any>()
|
||||
const sshIsolatedKeepalives = createSshIsolatedKeepaliveRegistry({
|
||||
log: chunk => sshRememberLog(chunk)
|
||||
})
|
||||
const desktopInstallationId = loadOrCreateInstallationId(DESKTOP_INSTALLATION_PATH)
|
||||
|
||||
// Managed SSH update lifecycle (#93042): while an update owns a registered
|
||||
@@ -10317,6 +10321,7 @@ async function sshProbeReuseProof(baseUrl, token, spawnNonce) {
|
||||
|
||||
async function teardownSshConnection(profile) {
|
||||
const scope = sshScopeKey(profile)
|
||||
sshIsolatedKeepalives.stop(scope)
|
||||
const state = sshConnections.get(scope)
|
||||
|
||||
if (!state) {
|
||||
@@ -10590,6 +10595,7 @@ async function rollbackSshBootstrapResult(ssh, result, profile, sshConfig, bound
|
||||
}
|
||||
|
||||
if (sshConnections.get(scope)?.ssh === ssh) {
|
||||
sshIsolatedKeepalives.stop(scope)
|
||||
sshConnections.delete(scope)
|
||||
}
|
||||
|
||||
@@ -10624,6 +10630,7 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc
|
||||
}
|
||||
|
||||
ssh = null
|
||||
sshIsolatedKeepalives.stop(scope)
|
||||
sshConnections.delete(scope)
|
||||
}
|
||||
|
||||
@@ -10749,6 +10756,7 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc
|
||||
// site may label a registry-qualified SSH scope as the primary backend.
|
||||
primaryRegistryScope: metadata.primaryRegistryScope === true
|
||||
})
|
||||
sshIsolatedKeepalives.start(scope, { baseUrl: result.baseUrl, token: result.token })
|
||||
},
|
||||
rollback: error => rollbackSshBootstrapResult(ssh, result, profile, sshConfig, error)
|
||||
})
|
||||
@@ -12147,6 +12155,7 @@ async function drainManagedSshScope(scope) {
|
||||
}
|
||||
|
||||
if (state && sshConnections.get(scope.key) === state) {
|
||||
sshIsolatedKeepalives.stop(scope.key)
|
||||
sshConnections.delete(scope.key)
|
||||
}
|
||||
}
|
||||
@@ -12728,7 +12737,19 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;
|
||||
const poolStopper = createPoolStopper({
|
||||
pool: backendPool,
|
||||
stopChild: child => stopBackendChild(child),
|
||||
waitForExit: child => waitForBackendExit(child)
|
||||
waitForExit: child => waitForBackendExit(child),
|
||||
// Remote / SSH-isolated pool entries keep `process: null`. Child exit is
|
||||
// immediate; hold the same in-flight fence through bootstrap drain + SSH
|
||||
// teardown so a reconnect cannot publish into a dying scope (#106935).
|
||||
afterStop: async key => {
|
||||
try {
|
||||
await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))
|
||||
} catch (err) {
|
||||
// The idle reaper calls stopPoolBackend un-awaited; a failed SSH teardown
|
||||
// must not surface as an unhandled rejection or block the pool fence.
|
||||
sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
async function stopPoolBackend(profile: string) {
|
||||
@@ -17152,6 +17173,7 @@ app.on('before-quit', () => {
|
||||
// Close the pooled keep-alive sockets on quit so lingering connections can't
|
||||
// hold the event loop open or leak FDs past app teardown.
|
||||
app.on('will-quit', () => {
|
||||
sshIsolatedKeepalives.stopAll()
|
||||
destroyKeepaliveAgents()
|
||||
})
|
||||
|
||||
|
||||
@@ -146,6 +146,57 @@ test('stopAll joins a stop whose pool entry was already evicted', async () => {
|
||||
assert.equal(stopper.hasPending(), false)
|
||||
})
|
||||
|
||||
test('afterStop holds inFlight until extra teardown finishes (process-less SSH)', async () => {
|
||||
const pool = new Map<string, PoolStopEntry>()
|
||||
const events: string[] = []
|
||||
let releaseAfter: (() => void) | undefined
|
||||
const afterGate = new Promise<void>(resolve => {
|
||||
releaseAfter = resolve
|
||||
})
|
||||
const stopper = createPoolStopper({
|
||||
pool,
|
||||
stopChild: () => {
|
||||
events.push('stop')
|
||||
},
|
||||
waitForExit: async () => {
|
||||
events.push('exit')
|
||||
},
|
||||
afterStop: async () => {
|
||||
events.push('after-start')
|
||||
await afterGate
|
||||
events.push('after-done')
|
||||
}
|
||||
})
|
||||
|
||||
pool.set('ssh', { process: null })
|
||||
const stop = stopper.stop('ssh')
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
|
||||
assert.equal(stopper.inFlight('ssh'), stop)
|
||||
assert.deepEqual(events, ['stop', 'exit', 'after-start'])
|
||||
|
||||
let spawned = false
|
||||
const respawn = (async () => {
|
||||
const dying = stopper.inFlight('ssh')
|
||||
|
||||
if (dying) {
|
||||
await dying
|
||||
}
|
||||
|
||||
spawned = true
|
||||
})()
|
||||
|
||||
await Promise.resolve()
|
||||
assert.equal(spawned, false, 'reconnect must wait for SSH teardown, not just child exit')
|
||||
releaseAfter?.()
|
||||
await stop
|
||||
await respawn
|
||||
assert.equal(spawned, true)
|
||||
assert.deepEqual(events, ['stop', 'exit', 'after-start', 'after-done'])
|
||||
assert.equal(stopper.inFlight('ssh'), undefined)
|
||||
})
|
||||
|
||||
test('a respawn can await the in-flight stop before reusing the key', async () => {
|
||||
const { addChild, exitResolvers, stopper } = harness()
|
||||
const child = addChild('selena')
|
||||
|
||||
@@ -33,6 +33,11 @@ export interface PoolStopperDeps {
|
||||
stopChild: (child: unknown) => void
|
||||
/** Bounded wait: resolves when the child exits, escalating to SIGKILL. */
|
||||
waitForExit: (child: unknown) => Promise<void>
|
||||
/**
|
||||
* Extra per-key work that must finish before a replacement may spawn.
|
||||
* Held on the same in-flight promise as child exit (SSH teardown, etc.).
|
||||
*/
|
||||
afterStop?: (key: string) => Promise<void>
|
||||
}
|
||||
|
||||
export interface PoolStopper {
|
||||
@@ -69,6 +74,9 @@ export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {
|
||||
const stopping = (async () => {
|
||||
deps.stopChild(entry.process)
|
||||
await deps.waitForExit(entry.process)
|
||||
if (deps.afterStop) {
|
||||
await deps.afterStop(key)
|
||||
}
|
||||
})().finally(() => {
|
||||
stops.delete(key)
|
||||
})
|
||||
|
||||
@@ -208,6 +208,40 @@ test('cancelAndWait force-cleans pending resources before awaiting rollback', as
|
||||
assert.equal(cleaned, 1)
|
||||
})
|
||||
|
||||
test('cancelAndWait keeps the drain up through afterCancel teardown', async () => {
|
||||
const coordinator = createBootstrapCoordinator()
|
||||
const events: string[] = []
|
||||
let releaseAfter: (() => void) | undefined
|
||||
const afterGate = new Promise<void>(resolve => {
|
||||
releaseAfter = resolve
|
||||
})
|
||||
let teardownStarted: (() => void) | undefined
|
||||
const started = new Promise<void>(resolve => {
|
||||
teardownStarted = resolve
|
||||
})
|
||||
|
||||
const drain = coordinator.cancelAndWait('scope', async () => {
|
||||
events.push('teardown-start')
|
||||
teardownStarted?.()
|
||||
await afterGate
|
||||
events.push('teardown-done')
|
||||
})
|
||||
|
||||
await started
|
||||
const next = coordinator.start('scope', 'new', async () => {
|
||||
events.push('new-start')
|
||||
|
||||
return 'new'
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
assert.deepEqual(events, ['teardown-start'])
|
||||
releaseAfter?.()
|
||||
await drain
|
||||
assert.equal(await next, 'new')
|
||||
assert.deepEqual(events, ['teardown-start', 'teardown-done', 'new-start'])
|
||||
})
|
||||
|
||||
test('a generation started during cancelAndWait cannot run before the drain completes', async () => {
|
||||
const coordinator = createBootstrapCoordinator()
|
||||
const oldGate = deferred()
|
||||
@@ -236,3 +270,39 @@ test('a generation started during cancelAndWait cannot run before the drain comp
|
||||
assert.equal(await next, 'new')
|
||||
assert.deepEqual(events, ['old-start', 'new-start'])
|
||||
})
|
||||
|
||||
test('a second cancelAndWait on the same scope composes with the teardown still in flight', async () => {
|
||||
// Pool stop is blocked in SSH teardown; a connection apply cancels the same
|
||||
// scope with no bootstrap left to drain. The apply's drain must not replace
|
||||
// and clear the barrier, or start() runs before the first teardown finishes.
|
||||
const coordinator = createBootstrapCoordinator()
|
||||
const events: string[] = []
|
||||
const teardownGate = deferred()
|
||||
const teardownStarted = deferred()
|
||||
|
||||
const poolStop = coordinator.cancelAndWait('scope', async () => {
|
||||
events.push('teardown-start')
|
||||
teardownStarted.resolve()
|
||||
await teardownGate.promise
|
||||
events.push('teardown-done')
|
||||
})
|
||||
|
||||
await teardownStarted.promise
|
||||
const apply = coordinator.cancelAndWait('scope').then(() => events.push('apply-drained'))
|
||||
const next = coordinator.start('scope', 'new', async () => {
|
||||
events.push('new-start')
|
||||
|
||||
return 'new'
|
||||
})
|
||||
|
||||
// A macrotask, not a microtask tick: nothing may run before the first teardown finishes.
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
assert.deepEqual(events, ['teardown-start'])
|
||||
teardownGate.resolve()
|
||||
await Promise.all([poolStop, apply])
|
||||
assert.equal(await next, 'new')
|
||||
// Both the apply and the new bootstrap wake on the same drained barrier; only
|
||||
// their position after teardown-done is the contract.
|
||||
assert.deepEqual(events.slice(0, 2), ['teardown-start', 'teardown-done'])
|
||||
assert.deepEqual(events.slice(2).sort(), ['apply-drained', 'new-start'])
|
||||
})
|
||||
@@ -93,14 +93,26 @@ function createBootstrapCoordinator() {
|
||||
pending.get(scope)?.controller.abort()
|
||||
}
|
||||
|
||||
async function cancelAndWait(scope) {
|
||||
async function cancelAndWait(scope, afterCancel?: () => Promise<void>) {
|
||||
let release
|
||||
|
||||
const barrier = new Promise<void>(resolve => {
|
||||
const own = new Promise<void>(resolve => {
|
||||
release = resolve
|
||||
})
|
||||
// Compose with any drain already in flight for this scope (a pool stop
|
||||
// still tearing down SSH while a connection apply cancels the same scope):
|
||||
// start() must wait for every active teardown, and the map entry is
|
||||
// cleared only once the composed barrier settles.
|
||||
const prior = drains.get(scope)
|
||||
// Drain barriers never reject, so chaining is equivalent to allSettled.
|
||||
const barrier = prior ? prior.then(() => own) : own
|
||||
|
||||
drains.set(scope, barrier)
|
||||
void barrier.finally(() => {
|
||||
if (drains.get(scope) === barrier) {
|
||||
drains.delete(scope)
|
||||
}
|
||||
})
|
||||
const entries = [...active].filter(entry => entry.scope === scope)
|
||||
|
||||
for (const entry of entries) {
|
||||
@@ -114,13 +126,18 @@ function createBootstrapCoordinator() {
|
||||
// drain barrier still prevents stale resurrection.
|
||||
await Promise.allSettled(entries.flatMap(entry => [...entry.forceCleanups]).map(cleanup => cleanup()))
|
||||
await Promise.allSettled(entries.map(entry => entry.promise))
|
||||
} finally {
|
||||
if (drains.get(scope) === barrier) {
|
||||
drains.delete(scope)
|
||||
// Keep the drain up through caller teardown (SSH keepalive / tunnel)
|
||||
// so a replacement start() cannot publish before the old scope is gone.
|
||||
if (afterCancel) {
|
||||
await afterCancel()
|
||||
}
|
||||
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
|
||||
// "Cancel and wait" means the scope is drained: callers tear down SSH right
|
||||
// after this returns, so wait for the composed barrier, not just our own.
|
||||
await barrier
|
||||
}
|
||||
|
||||
function cancelAll() {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* #106935: Desktop main must hold a long-lived keep-alive WebSocket for every
|
||||
* published SSH-isolated backend. Idle-exit (#101626) treats accepted WS as
|
||||
* ownership liveness; renderer sockets can drop while sshConnections still owns
|
||||
* the scope. Sticky artifacts (nonce / token file / lockfile) are NOT liveness.
|
||||
*
|
||||
* The pool-stop teardown fence that closes this socket is asserted in
|
||||
* pool-stop.test.ts (afterStop) — AGENTS.md forbids reading `.ts` source from tests.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
function makeFakeWs(): { FakeWs: new (url: string) => any; instances: any[] } {
|
||||
const instances: any[] = []
|
||||
|
||||
class FakeWs {
|
||||
url: string
|
||||
closed = false
|
||||
listeners: Record<string, Array<(event?: any) => void>> = {}
|
||||
|
||||
constructor(url: string) {
|
||||
this.url = url
|
||||
instances.push(this)
|
||||
}
|
||||
|
||||
addEventListener(type: string, fn: (event?: any) => void) {
|
||||
;(this.listeners[type] ||= []).push(fn)
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true
|
||||
}
|
||||
|
||||
emit(type: string, event?: any) {
|
||||
for (const fn of this.listeners[type] || []) {
|
||||
fn(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { FakeWs, instances }
|
||||
}
|
||||
|
||||
describe('ssh-isolated keep-alive registry (#106935)', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('holds an open WebSocket per scope until that scope stops, then never reconnects it', async () => {
|
||||
const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
|
||||
const { FakeWs, instances } = makeFakeWs()
|
||||
const registry = createSshIsolatedKeepaliveRegistry({
|
||||
WebSocketImpl: FakeWs,
|
||||
reconnectDelayMs: 25
|
||||
})
|
||||
|
||||
registry.start('conn:office::work', {
|
||||
baseUrl: 'http://127.0.0.1:53101',
|
||||
token: 'sess-work'
|
||||
})
|
||||
registry.start('conn:office::less', { baseUrl: 'http://127.0.0.1:53102', token: 'sess-less' })
|
||||
|
||||
expect(instances).toHaveLength(2)
|
||||
expect(instances[0].url).toBe('ws://127.0.0.1:53101/api/ws?token=sess-work')
|
||||
expect(registry.isArmed('conn:office::work')).toBe(true)
|
||||
|
||||
instances[0].emit('open')
|
||||
expect(registry.openUrl('conn:office::work')).toBe('ws://127.0.0.1:53101/api/ws?token=sess-work')
|
||||
|
||||
// A dropped socket is redialled with backoff (25 → 50 ms), so a dead tunnel is not
|
||||
// hammered every interval until the scope is torn down.
|
||||
vi.useFakeTimers()
|
||||
instances[1].emit('close', { code: 1006 })
|
||||
await vi.advanceTimersByTimeAsync(25)
|
||||
expect(instances).toHaveLength(3)
|
||||
instances[2].emit('close', { code: 1006 })
|
||||
await vi.advanceTimersByTimeAsync(25)
|
||||
expect(instances).toHaveLength(3)
|
||||
await vi.advanceTimersByTimeAsync(25)
|
||||
expect(instances).toHaveLength(4)
|
||||
vi.useRealTimers()
|
||||
|
||||
registry.stop('conn:office::work')
|
||||
expect(instances[0].closed).toBe(true)
|
||||
expect(registry.isArmed('conn:office::work')).toBe(false)
|
||||
// Tearing down one sibling must not drop the other owned scope.
|
||||
expect(instances[3].closed).toBe(false)
|
||||
expect(registry.isArmed('conn:office::less')).toBe(true)
|
||||
|
||||
instances[0].emit('close', { code: 1006 })
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
expect(instances).toHaveLength(4)
|
||||
expect(registry.openUrl('conn:office::work')).toBeNull()
|
||||
})
|
||||
|
||||
it('treats empty-string scope as the v1/global SSH primary but still requires baseUrl and token', async () => {
|
||||
const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')
|
||||
const { FakeWs, instances } = makeFakeWs()
|
||||
const registry = createSshIsolatedKeepaliveRegistry({ WebSocketImpl: FakeWs })
|
||||
|
||||
registry.start('', { baseUrl: '', token: 'tok' })
|
||||
registry.start('', { baseUrl: 'http://127.0.0.1:9', token: '' })
|
||||
expect(instances).toHaveLength(0)
|
||||
expect(registry.isArmed('')).toBe(false)
|
||||
|
||||
registry.start('', { baseUrl: 'http://127.0.0.1:53100', token: 'primary' })
|
||||
|
||||
expect(instances).toHaveLength(1)
|
||||
expect(instances[0].url).toBe('ws://127.0.0.1:53100/api/ws?token=primary')
|
||||
expect(registry.isArmed('')).toBe(true)
|
||||
|
||||
instances[0].emit('open')
|
||||
expect(registry.openUrl('')).toBe('ws://127.0.0.1:53100/api/ws?token=primary')
|
||||
|
||||
registry.stop('')
|
||||
expect(instances[0].closed).toBe(true)
|
||||
expect(registry.isArmed('')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Long-lived keep-alive WebSocket from Electron main for every published
|
||||
* SSH-isolated backend (#106935).
|
||||
*
|
||||
* `web_server_idle_exit` (#101626) treats accepted WebSockets as ownership
|
||||
* liveness. Renderer sockets can vanish (`disposeSecondary` /
|
||||
* `pruneSecondaryGateways`) while Desktop still owns the backend via
|
||||
* `sshConnections`. Sticky spawn artifacts (owner-nonce, token file, lockfile)
|
||||
* are NOT liveness and must not suppress idle-exit.
|
||||
*
|
||||
* If the socket drops the registry reconnects with capped exponential backoff;
|
||||
* while it is down the backend may idle-exit as before. This module never consults
|
||||
* nonce/lock/token files.
|
||||
*/
|
||||
import { buildGatewayWsUrl } from './connection-config'
|
||||
|
||||
export type SshIsolatedKeepaliveTarget = {
|
||||
baseUrl: string
|
||||
token: string
|
||||
}
|
||||
|
||||
export type SshIsolatedKeepaliveOptions = {
|
||||
WebSocketImpl?: any
|
||||
buildWsUrl?: (baseUrl: string, token: string) => string
|
||||
log?: (message: string) => void
|
||||
reconnectDelayMs?: number
|
||||
}
|
||||
|
||||
type KeepaliveEntry = {
|
||||
failures: number
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null
|
||||
scope: string
|
||||
socket: { close?: () => void; url?: string } | null
|
||||
target: SshIsolatedKeepaliveTarget
|
||||
}
|
||||
|
||||
const DEFAULT_RECONNECT_DELAY_MS = 2_000
|
||||
const MAX_RECONNECT_DELAY_MS = 30_000
|
||||
|
||||
function addListener(socket: any, type: string, handler: (event?: any) => void) {
|
||||
if (typeof socket?.addEventListener === 'function') {
|
||||
socket.addEventListener(type, handler)
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof socket?.on === 'function') {
|
||||
socket.on(type, handler)
|
||||
}
|
||||
}
|
||||
|
||||
export function createSshIsolatedKeepaliveRegistry(options: SshIsolatedKeepaliveOptions = {}) {
|
||||
const WebSocketImpl =
|
||||
'WebSocketImpl' in options ? options.WebSocketImpl : (globalThis as { WebSocket?: unknown }).WebSocket
|
||||
const buildWsUrl = options.buildWsUrl ?? buildGatewayWsUrl
|
||||
const log = options.log
|
||||
const reconnectDelayMs = options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS
|
||||
const entries = new Map<string, KeepaliveEntry>()
|
||||
|
||||
function clearTimer(entry: KeepaliveEntry) {
|
||||
if (entry.reconnectTimer == null) {
|
||||
return
|
||||
}
|
||||
|
||||
clearTimeout(entry.reconnectTimer)
|
||||
entry.reconnectTimer = null
|
||||
}
|
||||
|
||||
function closeSocket(entry: KeepaliveEntry) {
|
||||
const socket = entry.socket
|
||||
entry.socket = null
|
||||
|
||||
if (!socket) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
socket.close?.()
|
||||
} catch {
|
||||
// Best-effort teardown; a dead socket must not block scope cleanup.
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleReconnect(entry: KeepaliveEntry) {
|
||||
if (entries.get(entry.scope) !== entry || entry.reconnectTimer != null) {
|
||||
return
|
||||
}
|
||||
|
||||
// A dead tunnel would otherwise be redialled every 2 s until the scope is torn down.
|
||||
const delay = Math.min(reconnectDelayMs * 2 ** entry.failures, MAX_RECONNECT_DELAY_MS)
|
||||
entry.failures += 1
|
||||
entry.reconnectTimer = setTimeout(() => {
|
||||
entry.reconnectTimer = null
|
||||
connect(entry)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function connect(entry: KeepaliveEntry) {
|
||||
if (entries.get(entry.scope) !== entry) {
|
||||
return
|
||||
}
|
||||
|
||||
clearTimer(entry)
|
||||
closeSocket(entry)
|
||||
|
||||
let socket: any
|
||||
let url: string
|
||||
|
||||
try {
|
||||
url = buildWsUrl(entry.target.baseUrl, entry.target.token)
|
||||
socket = new WebSocketImpl(url)
|
||||
} catch (error) {
|
||||
log?.(`[ssh] keep-alive WS failed to open for ${entry.scope}: ${error instanceof Error ? error.message : error}`)
|
||||
scheduleReconnect(entry)
|
||||
return
|
||||
}
|
||||
|
||||
entry.socket = socket
|
||||
|
||||
// Staleness is derivable: stop() removes the entry, connect() replaces entry.socket.
|
||||
const abandonIfStale = () => {
|
||||
if (entries.get(entry.scope) !== entry || entry.socket !== socket) {
|
||||
return
|
||||
}
|
||||
|
||||
entry.socket = null
|
||||
scheduleReconnect(entry)
|
||||
}
|
||||
|
||||
addListener(socket, 'open', () => {
|
||||
if (entry.socket === socket) {
|
||||
entry.failures = 0
|
||||
}
|
||||
})
|
||||
addListener(socket, 'close', abandonIfStale)
|
||||
addListener(socket, 'error', abandonIfStale)
|
||||
}
|
||||
|
||||
function start(scope: string, target: SshIsolatedKeepaliveTarget) {
|
||||
// '' is a real published key: sshScopeKey(null) for the v1/global SSH primary.
|
||||
if (typeof scope !== 'string') {
|
||||
return
|
||||
}
|
||||
|
||||
const baseUrl = typeof target?.baseUrl === 'string' ? target.baseUrl : ''
|
||||
const token = typeof target?.token === 'string' ? target.token : ''
|
||||
|
||||
if (!baseUrl || !token) {
|
||||
return
|
||||
}
|
||||
|
||||
stop(scope)
|
||||
|
||||
const entry: KeepaliveEntry = {
|
||||
failures: 0,
|
||||
reconnectTimer: null,
|
||||
scope,
|
||||
socket: null,
|
||||
target: { baseUrl, token }
|
||||
}
|
||||
entries.set(scope, entry)
|
||||
connect(entry)
|
||||
}
|
||||
|
||||
function stop(scope: string) {
|
||||
const entry = entries.get(scope)
|
||||
|
||||
if (!entry) {
|
||||
return
|
||||
}
|
||||
|
||||
entries.delete(scope)
|
||||
clearTimer(entry)
|
||||
closeSocket(entry)
|
||||
}
|
||||
|
||||
function stopAll() {
|
||||
for (const scope of [...entries.keys()]) {
|
||||
stop(scope)
|
||||
}
|
||||
}
|
||||
|
||||
function isArmed(scope: string) {
|
||||
return entries.has(scope)
|
||||
}
|
||||
|
||||
function openUrl(scope: string) {
|
||||
const url = entries.get(scope)?.socket?.url
|
||||
return typeof url === 'string' ? url : null
|
||||
}
|
||||
|
||||
return { isArmed, openUrl, start, stop, stopAll }
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "hermes",
|
||||
"productName": "Hermes",
|
||||
"private": true,
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"description": "Native desktop shell for Hermes Agent.",
|
||||
"author": "Nous Research",
|
||||
"repository": {
|
||||
|
||||
@@ -28,8 +28,14 @@ via `/api/gateway/*`). Never re-parent the gateway under the backend — `gatewa
|
||||
- The backend already provides everything: `commands.catalog` and `complete.slash` include built-ins,
|
||||
user `quick_commands`, AND skill-derived commands. No new RPC is needed to see skills.
|
||||
- `src/lib/desktop-slash-commands.ts` is the load-bearing file: `DESKTOP_COMMAND_SPECS` (built-ins
|
||||
and their desktop surfaces) + `NO_DESKTOP_SURFACE` block-lists (terminal-only / messaging-only /
|
||||
picker-owned / settings-owned / advanced). `isDesktopSlashCommand(name)` gates **execution** (true
|
||||
and their desktop surfaces) + the block-list. A command's desktop disposition (terminal-only /
|
||||
messaging-only / settings-owned / advanced / hidden) is authored ONCE, as `desktop=` on its
|
||||
`CommandDef` in `hermes_cli/commands.py`; the live `commands.catalog` carries it, and
|
||||
`src/lib/desktop-slash-registry.json` (regenerate with `scripts/dump_desktop_slash_registry.py`;
|
||||
`tests/hermes_cli/test_desktop_slash_registry.py` + the vitest file fail on drift) is the offline
|
||||
fallback. Only names the Python registry has never heard of (`/density`, `/details`, `/logs`,
|
||||
`/mouse` — Ink-local; `/pets`) live in `TS_ONLY_NO_DESKTOP_SURFACE`. `isDesktopSlashCommand(name)`
|
||||
gates **execution** (true
|
||||
for built-ins AND any non-built-in so typed skill/quick commands run);
|
||||
`isDesktopSlashSuggestion(name)` gates **discovery** — used by BOTH completion paths in
|
||||
`app/chat/composer/hooks/use-slash-completions.ts` and by `filterDesktopCommandsCatalog`;
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import type { ModelOptionsResponse } from '@hermes/shared'
|
||||
import type { ModelOptionsResult } from '@hermes/shared'
|
||||
|
||||
import type { AnalyticsResponse, AuxiliaryModelsResponse, MoaConfigResponse, ModelAssignmentRequest, ModelAssignmentResponse, ModelInfoResponse } from '@/types/hermes'
|
||||
import type {
|
||||
AnalyticsResponse,
|
||||
AuxiliaryModelsResponse,
|
||||
MoaConfigResponse,
|
||||
ModelAssignmentRequest,
|
||||
ModelAssignmentResponse,
|
||||
ModelInfoResponse
|
||||
} from '@/types/hermes'
|
||||
|
||||
import { capabilityScoped, hermesApi, type ProfileScope, profileScoped, STARTUP_REQUEST_TIMEOUT_MS } from './client'
|
||||
|
||||
@@ -26,7 +33,7 @@ export function getGlobalModelOptions(
|
||||
explicitOnly?: boolean
|
||||
},
|
||||
profile?: null | string
|
||||
): Promise<ModelOptionsResponse> {
|
||||
): Promise<ModelOptionsResult> {
|
||||
const params = new URLSearchParams()
|
||||
|
||||
if (opts?.refresh) {
|
||||
@@ -41,7 +48,7 @@ export function getGlobalModelOptions(
|
||||
params.set('explicit_only', '1')
|
||||
}
|
||||
|
||||
return hermesApi<ModelOptionsResponse>({
|
||||
return hermesApi<ModelOptionsResult>({
|
||||
...profileScoped(profile),
|
||||
path: params.size > 0 ? `/api/model/options?${params.toString()}` : '/api/model/options',
|
||||
timeoutMs: STARTUP_REQUEST_TIMEOUT_MS
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { compactNumber } from '@hermes/shared'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import { type ReactNode, useEffect, useMemo, useState } from 'react'
|
||||
|
||||
@@ -8,7 +9,6 @@ import { Codicon } from '@/components/ui/codicon'
|
||||
import { FadeText } from '@/components/ui/fade-text'
|
||||
import { GlyphSpinner } from '@/components/ui/glyph-spinner'
|
||||
import { type Translations, useI18n } from '@/i18n'
|
||||
import { compactNumber } from '@/lib/format'
|
||||
import { AlertCircle, CheckCircle2 } from '@/lib/icons'
|
||||
import { useEnterAnimation } from '@/lib/use-enter-animation'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -7,10 +7,10 @@ import '@/store/suggestion-providers/mcp'
|
||||
import '@/store/suggestion-providers/skill'
|
||||
|
||||
import { useAui, useAuiState, useComposerRuntime } from '@assistant-ui/react'
|
||||
import { SLASH_COMMAND_RE } from '@hermes/shared'
|
||||
import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
|
||||
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
|
||||
import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
|
||||
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
|
||||
import {
|
||||
type ComposerAttachment,
|
||||
|
||||
@@ -6,7 +6,6 @@ import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
|
||||
import { $clarifyRequests } from '@/store/clarify'
|
||||
import type { ComposerAttachment } from '@/store/composer'
|
||||
import { clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
|
||||
import { $gateway } from '@/store/gateway'
|
||||
import {
|
||||
clearAllPrompts,
|
||||
hasBlockingPromptRequest,
|
||||
@@ -14,6 +13,7 @@ import {
|
||||
setSecretRequest,
|
||||
setSudoRequest
|
||||
} from '@/store/prompts'
|
||||
import { hasOpenServerRequest, rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'
|
||||
|
||||
import { type ComposerTarget, requestComposerSubmit } from '../focus'
|
||||
import { ComposerScopeProvider, ComposerSurfaceProvider, MAIN_COMPOSER_SCOPE } from '../scope'
|
||||
@@ -457,26 +457,30 @@ describe('useComposerSubmit busy-turn routing', () => {
|
||||
})
|
||||
|
||||
describe('useComposerSubmit with a clarify parked on the session', () => {
|
||||
const gatewayRequest = vi.fn(async () => ({ ok: true }))
|
||||
// The clarify is a live server→client request: skipping it answers that
|
||||
// request frame (`{ answer: '' }`), not a `clarify.respond` RPC.
|
||||
const respond = vi.fn()
|
||||
|
||||
const parkClarify = (sessionId: string) => {
|
||||
const requestId = `req-${sessionId}`
|
||||
|
||||
rememberServerRequest({ fail: vi.fn(), id: requestId, method: 'clarify', params: {}, respond })
|
||||
$clarifyRequests.set({
|
||||
[sessionId]: {
|
||||
requestId: `req-${sessionId}`,
|
||||
requestId,
|
||||
question: 'which one?',
|
||||
choices: ['a', 'b'],
|
||||
multiSelect: false,
|
||||
sessionId
|
||||
}
|
||||
})
|
||||
$gateway.set({ request: gatewayRequest } as unknown as ReturnType<typeof $gateway.get>)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
gatewayRequest.mockClear()
|
||||
respond.mockClear()
|
||||
resetServerRequestsForTests()
|
||||
$clarifyRequests.set({})
|
||||
$gateway.set(null)
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
@@ -488,16 +492,12 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
|
||||
hook.result.current.submitDraft()
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(gatewayRequest).toHaveBeenCalledWith('clarify.respond', {
|
||||
request_id: 'req-runtime-session',
|
||||
answer: ''
|
||||
})
|
||||
)
|
||||
await waitFor(() => expect(respond).toHaveBeenCalledWith({ answer: '' }))
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith('actually do this instead', expect.objectContaining({ attachments: [] }))
|
||||
)
|
||||
expect($clarifyRequests.get()['runtime-session']).toBeUndefined()
|
||||
expect(hasOpenServerRequest('req-runtime-session')).toBe(false)
|
||||
})
|
||||
|
||||
it('skips the question before steering a busy turn', async () => {
|
||||
@@ -509,7 +509,7 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
|
||||
})
|
||||
|
||||
await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))
|
||||
expect(gatewayRequest).toHaveBeenCalledWith('clarify.respond', { request_id: 'req-runtime-session', answer: '' })
|
||||
expect(respond).toHaveBeenCalledWith({ answer: '' })
|
||||
})
|
||||
|
||||
it('leaves the question alone for an empty Enter (Stop, not an answer)', () => {
|
||||
@@ -520,7 +520,8 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
|
||||
hook.result.current.submitDraft()
|
||||
})
|
||||
|
||||
expect(gatewayRequest).not.toHaveBeenCalled()
|
||||
expect(respond).not.toHaveBeenCalled()
|
||||
expect(hasOpenServerRequest('req-runtime-session')).toBe(true)
|
||||
expect($clarifyRequests.get()['runtime-session']).toBeDefined()
|
||||
expect(onCancel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
@@ -534,7 +535,8 @@ describe('useComposerSubmit with a clarify parked on the session', () => {
|
||||
})
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalled())
|
||||
expect(gatewayRequest).not.toHaveBeenCalled()
|
||||
expect(respond).not.toHaveBeenCalled()
|
||||
expect(hasOpenServerRequest('req-other-session')).toBe(true)
|
||||
expect($clarifyRequests.get()['other-session']).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { SLASH_COMMAND_RE } from '@hermes/shared'
|
||||
import { type RefObject, useLayoutEffect, useRef } from 'react'
|
||||
|
||||
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
|
||||
import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
|
||||
import { clearSessionDraft, type ComposerAttachment } from '@/store/composer'
|
||||
import { resetBrowseState } from '@/store/composer-input-history'
|
||||
import { enqueueQueuedPrompt, type QueuedPromptEntry } from '@/store/composer-queue'
|
||||
import { hasMcpSetupRequest, skipMcpSetupRequest } from '@/store/mcp-setup'
|
||||
import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'
|
||||
import { hasBlockingPromptRequest } from '@/store/prompts'
|
||||
|
||||
import { cloneAttachments, type QueueEditState } from '../composer-utils'
|
||||
@@ -234,10 +234,9 @@ export function useComposerSubmit({
|
||||
void skipClarifyRequest(sessionId)
|
||||
}
|
||||
|
||||
// Same deal for a pending MCP setup card: the agent is blocked on
|
||||
// mcp.setup.respond, so a typed message declines the card and rides on.
|
||||
if (payloadPresent && !queueEdit && hasMcpSetupRequest(sessionId)) {
|
||||
void skipMcpSetupRequest(sessionId)
|
||||
// Same for a pending connection card: typing declines every target.
|
||||
if (payloadPresent && !queueEdit && hasConnectionRequest(sessionId)) {
|
||||
void skipConnectionRequest(sessionId)
|
||||
}
|
||||
|
||||
// Approval / sudo / secret prompts also park the turn inside a tool batch,
|
||||
|
||||
@@ -88,7 +88,13 @@ import { ComposerTriggerPopover } from './trigger-popover'
|
||||
import type { ChatBarProps } from './types'
|
||||
import { isRedoShortcut, isUndoShortcut } from './undo-history'
|
||||
import { UrlDialog } from './url-dialog'
|
||||
import { chipTypedUrlOnSpace, linkifyUrls } from './url-refs'
|
||||
import {
|
||||
chipTypedUrlOnSpace,
|
||||
linkifyUrls,
|
||||
markdownLinkFor,
|
||||
resolveExactLinkPaste,
|
||||
selectionLinkLabel
|
||||
} from './url-refs'
|
||||
import { VoiceActivity, VoicePlaybackActivity } from './voice-activity'
|
||||
|
||||
export function ChatBar({
|
||||
@@ -564,6 +570,24 @@ export function ChatBar({
|
||||
|
||||
event.preventDefault()
|
||||
|
||||
// Pasting exactly one link while composer text is selected turns that text
|
||||
// into a markdown link instead of replacing it — the behavior every rich
|
||||
// editor ships (ported from block/buzz#6684). Selections that span chips
|
||||
// or lines fall through to the normal replace-with-chip path.
|
||||
const exactLink = resolveExactLinkPaste(pastedText)
|
||||
|
||||
if (exactLink) {
|
||||
const label = selectionLinkLabel(event.currentTarget)
|
||||
|
||||
if (label) {
|
||||
recordUndoPoint()
|
||||
insertComposerContentsAtCaret(event.currentTarget, markdownLinkFor(label, exactLink))
|
||||
scheduleFlushEditorToDraft(event.currentTarget)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// A paste past the large-paste threshold becomes a `.txt` attachment chip
|
||||
// instead of flooding the composer.
|
||||
// The instruction the user types stays in the input; the pasted source
|
||||
|
||||
@@ -129,9 +129,7 @@ export function ModelPill({
|
||||
) : (
|
||||
<>
|
||||
{currentModel.trim() ? (
|
||||
<span className="truncate">
|
||||
{formatModelPillLabel(currentModel, { fastMode })}
|
||||
</span>
|
||||
<span className="truncate">{formatModelPillLabel(currentModel, { fastMode })}</span>
|
||||
) : (
|
||||
<GlyphSpinner className="opacity-50" spinner="braille" />
|
||||
)}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DEFAULT_REASONING_EFFORT } from '@hermes/shared'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import { useState } from 'react'
|
||||
|
||||
@@ -9,7 +10,7 @@ import { releaseTypingFocus } from '@/components/ui/keyboard-first'
|
||||
import { Tip } from '@/components/ui/tooltip'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { ChevronDown } from '@/lib/icons'
|
||||
import { DEFAULT_REASONING_EFFORT, reasoningEffortLabel } from '@/lib/reasoning-effort'
|
||||
import { reasoningEffortLabel } from '@/lib/reasoning-effort'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { $defaultReasoningEffort } from '@/store/session'
|
||||
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import type { KeyboardEvent } from 'react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { composerPlainText, RICH_INPUT_SLOT } from './rich-editor'
|
||||
import { chipTypedUrlOnSpace, linkifyUrls } from './url-refs'
|
||||
import { composerPlainText, refChipElement, RICH_INPUT_SLOT } from './rich-editor'
|
||||
import {
|
||||
chipTypedUrlOnSpace,
|
||||
linkifyUrls,
|
||||
markdownLinkFor,
|
||||
resolveExactLinkPaste,
|
||||
selectionLinkLabel
|
||||
} from './url-refs'
|
||||
|
||||
/** An editor holding `text` with a collapsed caret at `caret`, plus the space
|
||||
* keydown the composer would hand `chipTypedUrlOnSpace`. */
|
||||
@@ -51,6 +57,95 @@ describe('linkifyUrls', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveExactLinkPaste', () => {
|
||||
it('accepts a lone bare link', () => {
|
||||
expect(resolveExactLinkPaste('https://example.dev/a/b')).toBe('https://example.dev/a/b')
|
||||
})
|
||||
|
||||
it('accepts a wrapped <link> and surrounding whitespace', () => {
|
||||
expect(resolveExactLinkPaste(' <https://example.dev/a> ')).toBe('https://example.dev/a')
|
||||
})
|
||||
|
||||
it('rejects prose around the link', () => {
|
||||
expect(resolveExactLinkPaste('see https://example.dev')).toBeNull()
|
||||
expect(resolveExactLinkPaste('https://example.dev is nice')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects multiple links', () => {
|
||||
expect(resolveExactLinkPaste('https://a.dev https://b.dev')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects trailing sentence punctuation and hostless schemes', () => {
|
||||
expect(resolveExactLinkPaste('https://example.dev.')).toBeNull()
|
||||
expect(resolveExactLinkPaste('https://')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('selectionLinkLabel', () => {
|
||||
const selectAll = (build: (editor: HTMLElement) => void) => {
|
||||
const editor = document.createElement('div')
|
||||
editor.dataset.slot = RICH_INPUT_SLOT
|
||||
build(editor)
|
||||
document.body.append(editor)
|
||||
|
||||
const selection = window.getSelection()!
|
||||
const range = document.createRange()
|
||||
|
||||
range.selectNodeContents(editor)
|
||||
selection.removeAllRanges()
|
||||
selection.addRange(range)
|
||||
|
||||
return editor
|
||||
}
|
||||
|
||||
it('returns the selected text', () => {
|
||||
const editor = selectAll(node => {
|
||||
node.textContent = 'the docs'
|
||||
})
|
||||
|
||||
expect(selectionLinkLabel(editor)).toBe('the docs')
|
||||
editor.remove()
|
||||
})
|
||||
|
||||
it('rejects a collapsed selection', () => {
|
||||
const editor = document.createElement('div')
|
||||
editor.textContent = 'text'
|
||||
document.body.append(editor)
|
||||
window.getSelection()?.removeAllRanges()
|
||||
|
||||
expect(selectionLinkLabel(editor)).toBeNull()
|
||||
editor.remove()
|
||||
})
|
||||
|
||||
it('rejects a selection containing a chip', () => {
|
||||
const editor = selectAll(node => {
|
||||
node.append(document.createTextNode('see '), refChipElement('url', '`https://a.dev`'))
|
||||
})
|
||||
|
||||
expect(selectionLinkLabel(editor)).toBeNull()
|
||||
editor.remove()
|
||||
})
|
||||
|
||||
it('rejects a multi-line selection', () => {
|
||||
const editor = selectAll(node => {
|
||||
node.append(document.createTextNode('one'), document.createElement('br'), document.createTextNode('two'))
|
||||
})
|
||||
|
||||
expect(selectionLinkLabel(editor)).toBeNull()
|
||||
editor.remove()
|
||||
})
|
||||
})
|
||||
|
||||
describe('markdownLinkFor', () => {
|
||||
it('builds a markdown link', () => {
|
||||
expect(markdownLinkFor('the docs', 'https://example.dev')).toBe('[the docs](https://example.dev)')
|
||||
})
|
||||
|
||||
it('escapes square brackets in the label', () => {
|
||||
expect(markdownLinkFor('a [b] c', 'https://example.dev')).toBe('[a \\[b\\] c](https://example.dev)')
|
||||
})
|
||||
})
|
||||
|
||||
describe('chipTypedUrlOnSpace', () => {
|
||||
it('chips a link typed right before the caret and adds the space', () => {
|
||||
const { editor, event } = spaceOn('see https://example.dev/a', 25)
|
||||
|
||||
@@ -59,6 +59,71 @@ export function linkifyUrls(text: string) {
|
||||
return out + text.slice(cursor)
|
||||
}
|
||||
|
||||
/** The href to apply when a clipboard payload is exactly ONE supported link —
|
||||
* a bare or `<…>`-wrapped `http(s)` URL with a host and nothing else. Null for
|
||||
* anything that isn't a lone link (prose, multiple links, trailing text), so
|
||||
* callers fall through to the normal paste pipeline. Ported from
|
||||
* block/buzz#6684's `resolveExactLinkPaste`. */
|
||||
export function resolveExactLinkPaste(raw: string): string | null {
|
||||
const text = raw.trim()
|
||||
const unwrapped = text.startsWith('<') && text.endsWith('>') && text.length > 2 ? text.slice(1, -1).trim() : text
|
||||
|
||||
URL_RE.lastIndex = 0
|
||||
|
||||
const match = URL_RE.exec(unwrapped)
|
||||
|
||||
if (!match || match.index !== 0 || match[0].length !== unwrapped.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const { trailing, url } = splitUrlTail(unwrapped)
|
||||
|
||||
// Trailing sentence punctuation means the user copied prose, not a link.
|
||||
if (trailing || !hasHost(url)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return url
|
||||
}
|
||||
|
||||
/** The selected composer text a link paste should hyperlink, or null when the
|
||||
* selection can't take a link mark: collapsed, outside `editor`, spanning
|
||||
* chips or line breaks, or whitespace-only. */
|
||||
export function selectionLinkLabel(editor: HTMLElement): string | null {
|
||||
const selection = window.getSelection()
|
||||
|
||||
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
|
||||
return null
|
||||
}
|
||||
|
||||
const range = selection.getRangeAt(0)
|
||||
|
||||
if (!editor.contains(range.commonAncestorContainer)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const probe = document.createElement('div')
|
||||
|
||||
probe.append(range.cloneContents())
|
||||
|
||||
// A chip inside the selection is a directive, not prose — linking over it
|
||||
// would destroy the reference. Multi-line selections don't read as a label.
|
||||
if (probe.querySelector('[data-ref-text], br')) {
|
||||
return null
|
||||
}
|
||||
|
||||
const label = probe.textContent?.replace(/\s+/g, ' ').trim() ?? ''
|
||||
|
||||
return label || null
|
||||
}
|
||||
|
||||
/** Markdown link for a paste-over-selection: the label the user selected, the
|
||||
* URL they pasted. Square brackets in the label are escaped so the link
|
||||
* survives markdown parsing downstream. */
|
||||
export function markdownLinkFor(label: string, url: string): string {
|
||||
return `[${label.replace(/([[\]])/g, '\\$1')}](${url})`
|
||||
}
|
||||
|
||||
/** A plain space finishing a typed link commits it as a chip (followed by
|
||||
* whatever punctuation ended it, then the space). Returns whether it ran, so a
|
||||
* keydown handler can fall through on anything else. */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type AppendMessage, AssistantRuntimeProvider, type ThreadMessage } from '@assistant-ui/react'
|
||||
import type { ModelOptionsResponse } from '@hermes/shared'
|
||||
import type { ModelOptionsResult } from '@hermes/shared'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { ReadableAtom } from 'nanostores'
|
||||
@@ -49,7 +49,7 @@ import {
|
||||
sessionPinId,
|
||||
shouldMigrateComposerScope
|
||||
} from '@/store/session'
|
||||
import { $focusedStoredSessionId, sessionTileDelegate } from '@/store/session-states'
|
||||
import { $focusedStoredSessionId, $sessionStates, sessionTileDelegate } from '@/store/session-states'
|
||||
import { $transcriptTailBySessionId, transcriptTailState } from '@/store/transcript-tail'
|
||||
import { isAuxiliaryWindow, isWatchWindow } from '@/store/windows'
|
||||
|
||||
@@ -420,6 +420,11 @@ const ChatViewContent = memo(function ChatViewContent({
|
||||
const composerSurfaceId = useComposerSurfaceId()
|
||||
const isPrimary = view.kind === 'primary'
|
||||
const activeSessionId = useStore(view.$runtimeId)
|
||||
|
||||
const transcriptStoredSessionId = useStoreSelector($sessionStates, states =>
|
||||
activeSessionId ? (states[activeSessionId]?.storedSessionId ?? null) : null
|
||||
)
|
||||
|
||||
const storedId = useStore(view.$storedId)
|
||||
// Multi-pane dimming: only the focused surface paints at full strength, so
|
||||
// two sessions side by side read as "this one, and that one over there".
|
||||
@@ -513,7 +518,14 @@ const ChatViewContent = memo(function ChatViewContent({
|
||||
// direct nav). Derived in render so the swap reads instantly: the same frame
|
||||
// the id changes we drop the old transcript and show the loader, instead of
|
||||
// waiting for the resume effect (which paints a frame later) to clear them.
|
||||
const routeSessionMismatch = isPrimary ? isRouteSessionMismatch(routedSessionId, selectedSessionId, sessions) : false
|
||||
const routeSessionMismatch = isPrimary
|
||||
? isRouteSessionMismatch(routedSessionId, selectedSessionId, sessions, {
|
||||
activeRuntimeId: activeSessionId,
|
||||
contextSwitching: Boolean(gatewaySwapTarget),
|
||||
messagesEmpty,
|
||||
transcriptStoredSessionId
|
||||
})
|
||||
: false
|
||||
|
||||
// The compact new-session pop-out skips the wordmark/tagline intro — it's a
|
||||
// scratch window, not the full-height empty state. The Appearance toggle
|
||||
@@ -564,7 +576,7 @@ const ChatViewContent = memo(function ChatViewContent({
|
||||
const showChatBar = !loadingSession && !resumeExhausted && !isWatchWindow()
|
||||
const threadKey = selectedSessionId || activeSessionId || (isRoutedSessionView ? location.pathname : 'new')
|
||||
|
||||
const modelOptionsQuery = useQuery<ModelOptionsResponse>({
|
||||
const modelOptionsQuery = useQuery<ModelOptionsResult>({
|
||||
queryKey: modelOptionsQueryKey(
|
||||
modelOptionsProfile || activeGatewayProfile,
|
||||
activeSessionId,
|
||||
|
||||
@@ -21,6 +21,7 @@ import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { PaneStripGlyph } from '@/components/ui/pane-tab'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { ANNOTATE_BLUE } from '@/lib/preview-annotate'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -191,7 +192,7 @@ export function PreviewBrowserBar({
|
||||
event.currentTarget.select()
|
||||
}}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') {
|
||||
if (isSubmitEnter(event)) {
|
||||
commit(event.currentTarget.value)
|
||||
event.currentTarget.blur()
|
||||
}
|
||||
|
||||
@@ -84,17 +84,14 @@ describe('RealProfileConsentDialog', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: promptCopy.enable }))
|
||||
})
|
||||
|
||||
// Saves the WHOLE merged record with only use_real_profile added — the
|
||||
// same shape the Capabilities toggle writes, through the same cache, so
|
||||
// the existing toggle flips on without a refetch.
|
||||
expect(mocks.save).toHaveBeenCalledWith(
|
||||
{
|
||||
browser: { allow_private_urls: false, use_real_profile: true },
|
||||
model: { provider: 'nous' }
|
||||
},
|
||||
undefined
|
||||
)
|
||||
expect(mocks.cache).toHaveBeenCalledWith(mocks.save.mock.calls[0][0])
|
||||
// Saves ONLY the toggled key (PUT deep-merges) — the same shape the
|
||||
// Capabilities toggle writes — while the shared cache gets the merged
|
||||
// record so the existing toggle flips on without a refetch.
|
||||
expect(mocks.save).toHaveBeenCalledWith({ browser: { use_real_profile: true } }, undefined)
|
||||
expect(mocks.cache).toHaveBeenCalledWith({
|
||||
browser: { allow_private_urls: false, use_real_profile: true },
|
||||
model: { provider: 'nous' }
|
||||
})
|
||||
expect(mocks.notify).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
|
||||
@@ -78,7 +78,9 @@ export function RealProfileConsentDialog({ tabId }: RealProfileConsentDialogProp
|
||||
setConfig(next)
|
||||
|
||||
try {
|
||||
await saveHermesConfigRecord(next)
|
||||
// Sparse patch: PUT /api/config deep-merges, and echoing the cached
|
||||
// snapshot would overwrite keys other surfaces changed since it loaded.
|
||||
await saveHermesConfigRecord({ browser: { use_real_profile: true } })
|
||||
notify({ kind: 'info', title: copy.enabledTitle, message: copy.enabledMessage })
|
||||
} catch (err) {
|
||||
setConfig(config)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { routeSessionId, sessionRoute } from '../routes'
|
||||
|
||||
import { isRouteSessionMismatch } from './route-session-state'
|
||||
|
||||
describe('isRouteSessionMismatch', () => {
|
||||
@@ -21,4 +23,58 @@ describe('isRouteSessionMismatch', () => {
|
||||
expect(isRouteSessionMismatch('same', 'same', [])).toBe(false)
|
||||
expect(isRouteSessionMismatch(null, 'same', [])).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the same-session route visible while a context switch is in flight', () => {
|
||||
const sessions = [{ id: 'a', _lineage_root_id: null }]
|
||||
|
||||
expect(
|
||||
isRouteSessionMismatch('a', 'a', sessions, {
|
||||
activeRuntimeId: 'r',
|
||||
contextSwitching: true,
|
||||
messagesEmpty: false,
|
||||
transcriptStoredSessionId: 'a'
|
||||
}),
|
||||
'a profile swap while route == selected must not blank the chat to the splash'
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps only the routed chat whose active view owns an existing transcript during selection churn', () => {
|
||||
const routedSessionId = routeSessionId(sessionRoute('session-a'))
|
||||
|
||||
const sessions = [
|
||||
{ id: 'session-a', _lineage_root_id: null },
|
||||
{ id: 'session-b', _lineage_root_id: null }
|
||||
]
|
||||
|
||||
const activeTranscript = {
|
||||
activeRuntimeId: 'runtime-a',
|
||||
contextSwitching: false,
|
||||
messagesEmpty: false,
|
||||
transcriptStoredSessionId: 'session-a'
|
||||
}
|
||||
|
||||
expect(isRouteSessionMismatch(routedSessionId, null, sessions, activeTranscript)).toBe(false)
|
||||
expect(isRouteSessionMismatch(routedSessionId, 'session-b', sessions, activeTranscript)).toBe(false)
|
||||
|
||||
expect(
|
||||
isRouteSessionMismatch('session-b', 'session-a', sessions, activeTranscript),
|
||||
'genuine navigation must suppress session A'
|
||||
).toBe(true)
|
||||
expect(
|
||||
isRouteSessionMismatch(routedSessionId, null, sessions, { ...activeTranscript, contextSwitching: true }),
|
||||
'profile or connection switches must not retain the prior context'
|
||||
).toBe(true)
|
||||
expect(
|
||||
isRouteSessionMismatch(routedSessionId, null, sessions, { ...activeTranscript, messagesEmpty: true }),
|
||||
'a route with no prior transcript must keep loading'
|
||||
).toBe(true)
|
||||
expect(
|
||||
isRouteSessionMismatch(routedSessionId, null, sessions, {
|
||||
...activeTranscript,
|
||||
activeRuntimeId: 'runtime-b',
|
||||
transcriptStoredSessionId: 'session-b'
|
||||
}),
|
||||
'a background chat must never publish into the routed foreground'
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,13 @@
|
||||
import { sessionMatchesStoredId } from '@/store/session'
|
||||
import type { SessionInfo } from '@/types/hermes'
|
||||
|
||||
interface ActiveTranscriptState {
|
||||
activeRuntimeId: null | string
|
||||
contextSwitching: boolean
|
||||
messagesEmpty: boolean
|
||||
transcriptStoredSessionId: null | string
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the route points at a different conversation than the selected view.
|
||||
*
|
||||
@@ -14,17 +21,37 @@ import type { SessionInfo } from '@/types/hermes'
|
||||
export function isRouteSessionMismatch(
|
||||
routedSessionId: null | string,
|
||||
selectedSessionId: null | string,
|
||||
sessions: readonly Pick<SessionInfo, '_lineage_root_id' | 'id'>[]
|
||||
sessions: readonly Pick<SessionInfo, '_lineage_root_id' | 'id'>[],
|
||||
activeTranscript?: ActiveTranscriptState
|
||||
): boolean {
|
||||
if (!routedSessionId || routedSessionId === selectedSessionId) {
|
||||
if (!routedSessionId) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (!selectedSessionId) {
|
||||
const matchesRoute = (storedSessionId: null | string) =>
|
||||
storedSessionId === routedSessionId ||
|
||||
Boolean(
|
||||
storedSessionId &&
|
||||
sessions.some(
|
||||
session => sessionMatchesStoredId(session, routedSessionId) && sessionMatchesStoredId(session, storedSessionId)
|
||||
)
|
||||
)
|
||||
|
||||
// The selected view already owns the routed conversation: a profile or
|
||||
// connection switch must not blank it to the splash.
|
||||
if (matchesRoute(selectedSessionId)) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Only the transcript-retention fallback below must be denied while a
|
||||
// context switch is in flight; the prior context must not be retained.
|
||||
if (activeTranscript?.contextSwitching) {
|
||||
return true
|
||||
}
|
||||
|
||||
return !sessions.some(
|
||||
session => sessionMatchesStoredId(session, routedSessionId) && sessionMatchesStoredId(session, selectedSessionId)
|
||||
return !(
|
||||
activeTranscript?.activeRuntimeId &&
|
||||
!activeTranscript.messagesEmpty &&
|
||||
matchesRoute(activeTranscript.transcriptStoredSessionId)
|
||||
)
|
||||
}
|
||||
@@ -9,12 +9,12 @@
|
||||
*/
|
||||
|
||||
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
|
||||
import { SLASH_COMMAND_RE } from '@hermes/shared'
|
||||
import { useCallback, useMemo, useRef } from 'react'
|
||||
|
||||
import type { ClientSessionState } from '@/app/types'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { textPart } from '@/lib/chat-messages'
|
||||
import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { clearClarifyRequest } from '@/store/clarify'
|
||||
import type { ComposerAttachment } from '@/store/composer'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { compactNumber } from '@hermes/shared'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import type * as React from 'react'
|
||||
|
||||
@@ -7,7 +8,6 @@ import { Codicon } from '@/components/ui/codicon'
|
||||
import { DisclosureCaret } from '@/components/ui/disclosure-caret'
|
||||
import { RowButton } from '@/components/ui/row-button'
|
||||
import { Tip } from '@/components/ui/tooltip'
|
||||
import { compactNumber } from '@/lib/format'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { $sidebarRowMeta } from '@/store/layout'
|
||||
import type { TileDock } from '@/store/session-states'
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { notify, notifyError } from '@/store/notifications'
|
||||
import {
|
||||
$remoteOverrideDialogProfile,
|
||||
@@ -242,7 +243,7 @@ export function ProfileRemoteOverrideDialog({ profileNames }: { profileNames: st
|
||||
<Input
|
||||
autoCorrect="off"
|
||||
onChange={event => setUrl(event.target.value)}
|
||||
onKeyDown={event => event.key === 'Enter' && submit()}
|
||||
onKeyDown={event => isSubmitEnter(event) && submit()}
|
||||
placeholder={p.urlPlaceholder}
|
||||
ref={urlRef}
|
||||
spellCheck={false}
|
||||
@@ -257,7 +258,7 @@ export function ProfileRemoteOverrideDialog({ profileNames }: { profileNames: st
|
||||
<Input
|
||||
autoComplete="off"
|
||||
onChange={event => setToken(event.target.value)}
|
||||
onKeyDown={event => event.key === 'Enter' && submit()}
|
||||
onKeyDown={event => isSubmitEnter(event) && submit()}
|
||||
placeholder={p.tokenPlaceholder}
|
||||
type="password"
|
||||
value={token}
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Tip } from '@/components/ui/tooltip'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { type ProjectIdeaTemplate, randomIdeaTemplates } from '@/lib/project-idea-templates'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { notifyError } from '@/store/notifications'
|
||||
@@ -191,7 +192,7 @@ export function ProjectDialog() {
|
||||
disabled={submitting}
|
||||
onChange={event => setName(event.target.value)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') {
|
||||
if (isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
void submit()
|
||||
} else if (event.key === 'Escape') {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
|
||||
import { SanitizedInput } from '@/components/ui/sanitized-input'
|
||||
import type { HermesGitBranch } from '@/global'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { gitRef } from '@/lib/sanitize'
|
||||
import { notifyError } from '@/store/notifications'
|
||||
import {
|
||||
@@ -310,7 +311,7 @@ export function WorktreeDialog() {
|
||||
autoFocus
|
||||
disabled={pending}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') {
|
||||
if (isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
void submit()
|
||||
} else if (event.key === 'Escape') {
|
||||
|
||||
@@ -27,6 +27,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { renameSession } from '@/hermes'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { PROFILE_SWATCHES } from '@/lib/profile-color'
|
||||
import { exportSession } from '@/lib/session-export'
|
||||
import { activeGateway } from '@/store/gateway'
|
||||
@@ -695,7 +696,7 @@ function RenameSessionDialog({ open, onOpenChange, sessionId, currentTitle, prof
|
||||
disabled={submitting}
|
||||
onChange={event => setValue(event.target.value)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter' && !event.nativeEvent.isComposing) {
|
||||
if (isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
void submit()
|
||||
} else if (event.key === 'Escape') {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { compactNumber } from '@hermes/shared'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import { memo } from 'react'
|
||||
import type * as React from 'react'
|
||||
@@ -15,7 +16,6 @@ import type { SessionInfo } from '@/hermes'
|
||||
import { type Translations, useI18n } from '@/i18n'
|
||||
import { sessionTitle } from '@/lib/chat-runtime'
|
||||
import { pathLeaf } from '@/lib/display-path'
|
||||
import { compactNumber } from '@/lib/format'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { middleClickHandlers } from '@/lib/middle-click'
|
||||
import { displayModelName } from '@/lib/model-status-label'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { compactNumber } from '@hermes/shared'
|
||||
import { type MouseEvent, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { LogTail } from '@/components/chat/log-tail'
|
||||
@@ -12,7 +13,6 @@ import { getActionStatus, getLogs, getStatus, getUsageAnalytics, restartGateway,
|
||||
import type { ActionStatusResponse, AnalyticsResponse, SessionInfo, StatusResponse } from '@/hermes'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { sessionTitle } from '@/lib/chat-runtime'
|
||||
import { compactNumber } from '@/lib/format'
|
||||
import {
|
||||
Activity,
|
||||
AlertCircle,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { buildToolView } from '@/components/assistant-ui/tool/fallback-model'
|
||||
import { createClientSessionState } from '@/lib/chat-runtime'
|
||||
import { $activeSessionId, $selectedStoredSessionId, $unreadFinishedSessionIds } from '@/store/session'
|
||||
import {
|
||||
@@ -111,10 +112,20 @@ describe('rehydrateLiveSessionStatuses — reaping vanished runtimes', () => {
|
||||
rehydrateLiveSessionStatuses({ sessions: [] })
|
||||
|
||||
const state = $sessionStates.get()['runtime-tools']
|
||||
const part = state.messages[0].parts[0]
|
||||
|
||||
expect(state.busy).toBe(false)
|
||||
expect(state.awaitingResponse).toBe(false)
|
||||
expect((state.messages[0].parts[0] as { result?: unknown }).result).toBeDefined()
|
||||
expect(part.type).toBe('tool-call')
|
||||
|
||||
if (part.type !== 'tool-call') {
|
||||
throw new Error('Missing tool call')
|
||||
}
|
||||
|
||||
// Reaping ends liveness without inventing evidence of a successful result.
|
||||
expect(part.completedAt).toBeDefined()
|
||||
expect(part.result).toBeUndefined()
|
||||
expect(buildToolView(part, '').status).toBe('warning')
|
||||
})
|
||||
|
||||
it('clears a session stuck awaiting a response without the busy flag', () => {
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
sessionTileOwnerRoute,
|
||||
setSessionTileDelegate
|
||||
} from '@/store/session-states'
|
||||
import type { SessionResumeResponse } from '@/types/hermes'
|
||||
import type { SessionResumeResult } from '@/types/hermes'
|
||||
|
||||
import type { usePromptActions } from '../../session/hooks/use-prompt-actions'
|
||||
import { singleFlightSessionResume } from '../../session/hooks/use-prompt-actions/single-flight-resume'
|
||||
@@ -41,7 +41,7 @@ type SessionStateCache = ReturnType<typeof useSessionStateCache>
|
||||
|
||||
function mergeTileTranscript(
|
||||
previous: ChatMessage[],
|
||||
prefetchMessages: SessionResumeResponse['messages'] | undefined,
|
||||
prefetchMessages: SessionResumeResult['messages'] | undefined,
|
||||
streamId?: null | string
|
||||
): ChatMessage[] {
|
||||
const prefetched = toChatMessages(prefetchMessages ?? [])
|
||||
@@ -339,7 +339,7 @@ export function useSessionTileDelegate({
|
||||
assertSessionOwnerResolved(owner, { method: 'session.resume', sessionId: storedSessionId })
|
||||
|
||||
return singleFlightSessionResume(storedSessionId, () =>
|
||||
requestForSessionProfile<SessionResumeResponse>(owner, requestGateway, 'session.resume', {
|
||||
requestForSessionProfile<SessionResumeResult>(owner, requestGateway, 'session.resume', {
|
||||
session_id: storedSessionId,
|
||||
cols: 96,
|
||||
omit_messages: true,
|
||||
|
||||
@@ -497,7 +497,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
|
||||
[activeSessionIdRef, busyRef, selectedStoredSessionIdRef, updateSessionState]
|
||||
)
|
||||
|
||||
const { handleGatewayEvent } = useMessageStream({
|
||||
const { handleGatewayEvent, handleServerRequest } = useMessageStream({
|
||||
activeGatewayProfile,
|
||||
activeSessionIdRef,
|
||||
hydrateFromStoredSession,
|
||||
@@ -898,6 +898,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
|
||||
closeAllTerminals()
|
||||
},
|
||||
handleGatewayEvent: handleGatewayEventWithPlugins,
|
||||
handleServerRequest,
|
||||
onConnectionReady: c => {
|
||||
connectionRef.current = c
|
||||
},
|
||||
|
||||
@@ -258,6 +258,7 @@ function Harness({
|
||||
useGatewayBoot({
|
||||
beforeConnectionSwitch,
|
||||
handleGatewayEvent: () => undefined,
|
||||
handleServerRequest: () => false,
|
||||
onConnectionReady: () => undefined,
|
||||
onGatewayReady: () => undefined,
|
||||
refreshHermesConfig,
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { type GatewayEvent, isGatewayReauthRequired, isGatewayWebSocketUrl, JsonRpcGatewayError, reconnectBackoffDelayMs, resolveGatewayWsUrl } from '@hermes/shared'
|
||||
import {
|
||||
type GatewayEvent,
|
||||
isGatewayReauthRequired,
|
||||
isGatewayWebSocketUrl,
|
||||
JSON_RPC_METHOD_NOT_FOUND,
|
||||
JsonRpcGatewayError,
|
||||
reconnectBackoffDelayMs,
|
||||
resolveGatewayWsUrl
|
||||
} from '@hermes/shared'
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
import { shouldApplyPostBootProgressError } from '@/components/boot-failure-reauth'
|
||||
@@ -24,6 +32,7 @@ import {
|
||||
closeLegacySecondaryGateways,
|
||||
closeSecondaryGateways,
|
||||
configureGatewayRegistry,
|
||||
dispatchPrimaryServerRequest,
|
||||
disposeSecondariesForConnection,
|
||||
ensureActiveGatewayOpen,
|
||||
ensureGatewayForProfile,
|
||||
@@ -33,6 +42,7 @@ import {
|
||||
pruneSecondaryGateways,
|
||||
reconnectSecondaryGateways,
|
||||
reportPrimaryGatewayState,
|
||||
type ScopedServerRequest,
|
||||
setPrimaryGateway,
|
||||
setPrimaryGatewayConnection,
|
||||
touchSecondaryGateways
|
||||
@@ -141,6 +151,8 @@ export function primaryRuntimeConnectionId(connection: Pick<HermesConnection, 'c
|
||||
interface GatewayBootOptions {
|
||||
beforeConnectionSwitch: () => void
|
||||
handleGatewayEvent: (event: GatewayEvent) => void
|
||||
/** Server→client request from any registry socket; false = no handler (the channel answers -32601). */
|
||||
handleServerRequest: (request: ScopedServerRequest) => boolean
|
||||
onConnectionReady: (
|
||||
connection: Awaited<ReturnType<NonNullable<typeof window.hermesDesktop>['getConnection']>> | null
|
||||
) => void
|
||||
@@ -152,6 +164,7 @@ interface GatewayBootOptions {
|
||||
export function useGatewayBoot({
|
||||
beforeConnectionSwitch,
|
||||
handleGatewayEvent,
|
||||
handleServerRequest,
|
||||
onConnectionReady,
|
||||
onGatewayReady,
|
||||
refreshHermesConfig,
|
||||
@@ -160,6 +173,7 @@ export function useGatewayBoot({
|
||||
const callbacksRef = useRef({
|
||||
beforeConnectionSwitch,
|
||||
handleGatewayEvent,
|
||||
handleServerRequest,
|
||||
onConnectionReady,
|
||||
onGatewayReady,
|
||||
refreshHermesConfig,
|
||||
@@ -169,6 +183,7 @@ export function useGatewayBoot({
|
||||
callbacksRef.current = {
|
||||
beforeConnectionSwitch,
|
||||
handleGatewayEvent,
|
||||
handleServerRequest,
|
||||
onConnectionReady,
|
||||
onGatewayReady,
|
||||
refreshHermesConfig,
|
||||
@@ -798,6 +813,11 @@ export function useGatewayBoot({
|
||||
// (connectionId, profile) keep-set so two sources exposing the same
|
||||
// profile name (every source has a 'default') can't collide.
|
||||
configureGatewayRegistry({
|
||||
onServerRequest: request => {
|
||||
if (!callbacksRef.current.handleServerRequest(request)) {
|
||||
request.fail(JSON_RPC_METHOD_NOT_FOUND, `Hermes Desktop cannot answer ${request.method}`)
|
||||
}
|
||||
},
|
||||
// The primary socket has no secondary entry to carry registry identity.
|
||||
// Electron's published active descriptor is authoritative after boot;
|
||||
// a true legacy primary has no connectionId and remains unqualified.
|
||||
@@ -903,6 +923,9 @@ export function useGatewayBoot({
|
||||
callbacksRef.current.handleGatewayEvent(scopedEvent)
|
||||
})
|
||||
|
||||
// Secondary sockets reach the same handler through the registry's onServerRequest.
|
||||
const offRequest = gateway.onRequest(request => dispatchPrimaryServerRequest(request, sourceProfile))
|
||||
|
||||
// Wake signals: power resume (macOS/Windows), network coming back, and the
|
||||
// window regaining focus/visibility. Each nudges an immediate reconnect.
|
||||
const forceReconnectNow = () => reconnectNow({ forceOpenSocket: true })
|
||||
@@ -1267,6 +1290,7 @@ export function useGatewayBoot({
|
||||
offActiveStateReauth()
|
||||
offState()
|
||||
offEvent()
|
||||
offRequest()
|
||||
offExit()
|
||||
offWindowState?.()
|
||||
offBootProgress()
|
||||
|
||||
@@ -171,6 +171,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .
|
||||
const settleAfterUpdate = useCallback((hotServed: boolean | undefined) => {
|
||||
if (hotServed) {
|
||||
window.setTimeout(() => void refreshPlatformsRef.current(true), 4000)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { useI18n } from '@/i18n'
|
||||
import { openExternalLink } from '@/lib/external-link'
|
||||
import { Check, ExternalLink, QrCode, Save, X } from '@/lib/icons'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { CREDENTIAL_CONTROL_CLASS } from '../settings/credential-key-ui'
|
||||
@@ -326,7 +327,7 @@ export function TelegramQrSetup({ onApplied, platform, scopeProfile }: TelegramQ
|
||||
className={CREDENTIAL_CONTROL_CLASS}
|
||||
onChange={event => setNewAllowedId(event.target.value)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') {
|
||||
if (isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
addAllowedId()
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { Loader2, PawPrint, RefreshCw } from '@/lib/icons'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { type PetInfo } from '@/store/pet'
|
||||
|
||||
import { frameCountForRow } from '../lib/frame-count'
|
||||
@@ -124,7 +125,7 @@ export function HatchPreview({ pet, adopting, error, onAdopt, onDiscard }: Hatch
|
||||
className="w-full"
|
||||
onChange={event => setName(event.target.value)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') {
|
||||
if (isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
onAdopt(name)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { Egg, ImageIcon } from '@/lib/icons'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
$petGenAvailable,
|
||||
@@ -223,7 +224,7 @@ export function PetGenerateContent() {
|
||||
className="pr-9"
|
||||
onChange={event => $petGenInput.set(event.target.value)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') {
|
||||
if (isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
generate()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { PetBubble } from '@/components/pet/pet-bubble'
|
||||
import { PetSprite } from '@/components/pet/pet-sprite'
|
||||
import { type PetZoomAnchor, usePetZoomGesture } from '@/components/pet/use-pet-zoom-gesture'
|
||||
import { Mail } from '@/lib/icons'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { $petActivity, $petInfo, setPetInfo } from '@/store/pet'
|
||||
import { overlayWindowSize } from '@/store/pet-overlay'
|
||||
import { setAwaitingResponse, setBusy } from '@/store/session'
|
||||
@@ -390,7 +391,7 @@ export function PetOverlayApp() {
|
||||
<input
|
||||
onChange={e => setDraft(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
if (isSubmitEnter(e) && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
send()
|
||||
} else if (e.key === 'Escape') {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useReducer, useRef } from 'react'
|
||||
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import {
|
||||
initialQuickComposerState,
|
||||
QUICK_TARGET_CURRENT,
|
||||
@@ -123,7 +124,7 @@ export function QuickEntryApp() {
|
||||
}}
|
||||
onChange={event => dispatch({ draft: event.target.value, type: 'edit' })}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
if (isSubmitEnter(event) && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
dispatch({ type: 'submit' })
|
||||
} else if (event.key === 'Escape') {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from '@/components/ui/context-menu'
|
||||
import { translateNow, useI18n } from '@/i18n'
|
||||
import { isDesktopFsRemoteMode } from '@/lib/desktop-fs'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { IS_MAC } from '@/lib/keybinds/combo'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
@@ -197,7 +198,7 @@ export function InlineRenameInput({ className, name, path }: InlineRenameInputPr
|
||||
onKeyDown={event => {
|
||||
event.stopPropagation()
|
||||
|
||||
if (event.key === 'Enter') {
|
||||
if (isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
void finish(true)
|
||||
} else if (event.key === 'Escape') {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { SplitButton } from '@/components/ui/split-button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Tip } from '@/components/ui/tooltip'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { isSubmitEnter } from '@/lib/ime'
|
||||
import { formatCombo } from '@/lib/keybinds/combo'
|
||||
import { notifyError } from '@/store/notifications'
|
||||
import {
|
||||
@@ -85,7 +86,7 @@ export function ReviewShipBar() {
|
||||
disabled={generating}
|
||||
onChange={event => setMessage(event.target.value)}
|
||||
onKeyDown={event => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
|
||||
if ((event.metaKey || event.ctrlKey) && isSubmitEnter(event)) {
|
||||
event.preventDefault()
|
||||
runCommit(commitDefault)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
applyThinkingSoundFromConfig,
|
||||
applyVoiceStopPhraseFromConfig
|
||||
} from '@/store/voice-prefs'
|
||||
import { setChatFontFamilyFromConfig } from '@/themes/chat-font'
|
||||
|
||||
const DEFAULT_VOICE_SECONDS = 120
|
||||
const FAST_TIERS = new Set(['fast', 'priority', 'on'])
|
||||
@@ -140,6 +141,7 @@ export function useHermesConfig({ activeSessionIdRef }: HermesConfigOptions) {
|
||||
|
||||
setDisplayTimestampsFromConfig(config.display?.timestamps)
|
||||
setTerminalFontFamilyFromConfig(config.terminal?.font_family)
|
||||
setChatFontFamilyFromConfig(config.desktop?.font_family)
|
||||
|
||||
if (!canPublish()) {
|
||||
return
|
||||
|
||||
@@ -8,7 +8,7 @@ import { onScrollToBottomRequest } from '@/store/thread-scroll'
|
||||
|
||||
import { type MessageStreamHarness, renderMessageStream } from './test-harness'
|
||||
|
||||
// A `clarify.request` must leave an answerable inline row even when the
|
||||
// A `clarify` server request must leave an answerable inline row even when the
|
||||
// `tool.start` that normally mounts it was missed (stream reconnect /
|
||||
// hydration race). Without it the sidebar says "needs input" but the
|
||||
// transcript has nowhere to render the choices, so the agent blocks forever.
|
||||
@@ -24,8 +24,8 @@ function mountStream() {
|
||||
stream = renderMessageStream(SID)
|
||||
}
|
||||
|
||||
const clarifyRequest = (payload: Record<string, unknown>) =>
|
||||
act(() => stream.handleEvent({ payload, session_id: SID, type: 'clarify.request' }))
|
||||
const clarifyRequest = ({ request_id, ...params }: Record<string, unknown>) =>
|
||||
act(() => void stream.handleRequest('clarify', { ...params, session_id: SID }, request_id as string))
|
||||
|
||||
const toolStart = (payload: Record<string, unknown>) =>
|
||||
act(() => stream.handleEvent({ payload, session_id: SID, type: 'tool.start' }))
|
||||
@@ -34,7 +34,13 @@ const toolComplete = (payload: Record<string, unknown>) =>
|
||||
act(() => stream.handleEvent({ payload, session_id: SID, type: 'tool.complete' }))
|
||||
|
||||
const clarifyExpire = (requestId: string) =>
|
||||
act(() => stream.handleEvent({ payload: { request_id: requestId }, session_id: SID, type: 'clarify.expire' }))
|
||||
act(() =>
|
||||
stream.handleEvent({
|
||||
payload: { id: requestId, method: 'clarify', reason: 'timeout' },
|
||||
session_id: SID,
|
||||
type: 'request.cancel'
|
||||
})
|
||||
)
|
||||
|
||||
function clarifyParts() {
|
||||
const messages = stream.state().messages ?? []
|
||||
@@ -49,7 +55,7 @@ function seedHydratedMessages(messages: ChatMessage[]) {
|
||||
stream.states.set(SID, state)
|
||||
}
|
||||
|
||||
describe('clarify.request stream hydration', () => {
|
||||
describe('clarify request stream hydration', () => {
|
||||
beforeEach(() => {
|
||||
clearClarifyRequest()
|
||||
scrollToBottom.mockClear()
|
||||
@@ -89,12 +95,13 @@ describe('clarify.request stream hydration', () => {
|
||||
it('does not move the active thread for a background session clarify', () => {
|
||||
mountStream()
|
||||
|
||||
act(() =>
|
||||
stream.handleEvent({
|
||||
payload: { choices: ['yes', 'no'], question: 'Ship it?', request_id: 'req-background' },
|
||||
session_id: 'session-background',
|
||||
type: 'clarify.request'
|
||||
})
|
||||
act(
|
||||
() =>
|
||||
void stream.handleRequest(
|
||||
'clarify',
|
||||
{ choices: ['yes', 'no'], question: 'Ship it?', session_id: 'session-background' },
|
||||
'req-background'
|
||||
)
|
||||
)
|
||||
|
||||
expect(scrollToBottom).not.toHaveBeenCalled()
|
||||
@@ -129,7 +136,7 @@ describe('clarify.request stream hydration', () => {
|
||||
it('merges with the real tool.start row even though its id differs from the request id', () => {
|
||||
mountStream()
|
||||
|
||||
// Reality: tool.start carries the model's tool_call_id, clarify.request a
|
||||
// Reality: tool.start carries the model's tool_call_id, the clarify request a
|
||||
// separately-generated request_id. They must still collapse to ONE card
|
||||
// (correlated by question), not two.
|
||||
toolStart({ args: { choices: ['a'], question: 'Pick' }, name: 'clarify', tool_id: 'call-abc' })
|
||||
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { $gateway } from '@/store/gateway'
|
||||
import { $toursEnabled } from '@/store/tours'
|
||||
|
||||
import { handleDesktopBridgeEvent } from './desktop-bridge'
|
||||
import type { GatewayEventContext } from './types'
|
||||
|
||||
function previewActContext({
|
||||
explicitSid,
|
||||
isActiveEvent
|
||||
}: {
|
||||
explicitSid: string
|
||||
isActiveEvent: boolean
|
||||
}): GatewayEventContext {
|
||||
return {
|
||||
event: { session_id: explicitSid || undefined, type: 'preview.act.request' },
|
||||
explicitSid,
|
||||
isActiveEvent,
|
||||
payload: { action: 'elements', request_id: 'request-1' }
|
||||
} as GatewayEventContext
|
||||
}
|
||||
|
||||
describe('preview action bridge routing', () => {
|
||||
afterEach(() => {
|
||||
$gateway.set(null)
|
||||
})
|
||||
|
||||
it('leaves a scoped action request unanswered in a window showing another session', () => {
|
||||
const request = vi.fn()
|
||||
$gateway.set({ request } as never)
|
||||
|
||||
expect(handleDesktopBridgeEvent(previewActContext({ explicitSid: 'session-a', isActiveEvent: false }))).toBe(true)
|
||||
expect(request).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the legacy fail-fast response for an unscoped inactive request', () => {
|
||||
const request = vi.fn()
|
||||
$gateway.set({ request } as never)
|
||||
|
||||
expect(handleDesktopBridgeEvent(previewActContext({ explicitSid: '', isActiveEvent: false }))).toBe(true)
|
||||
expect(request).toHaveBeenCalledWith('preview.act.respond', {
|
||||
request_id: 'request-1',
|
||||
text: JSON.stringify({
|
||||
error: 'The in-app browser only takes actions in the session the user is looking at.',
|
||||
success: false
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
function tourContext({
|
||||
explicitSid,
|
||||
isActiveEvent
|
||||
}: {
|
||||
explicitSid: string
|
||||
isActiveEvent: boolean
|
||||
}): GatewayEventContext {
|
||||
return {
|
||||
event: { session_id: explicitSid || undefined, type: 'tour.request' },
|
||||
explicitSid,
|
||||
isActiveEvent,
|
||||
payload: { action: 'discover', request_id: 'tour-request-1' }
|
||||
} as GatewayEventContext
|
||||
}
|
||||
|
||||
describe('tour bridge routing', () => {
|
||||
afterEach(() => {
|
||||
$gateway.set(null)
|
||||
$toursEnabled.set(true)
|
||||
})
|
||||
|
||||
it('leaves a scoped request unanswered in another session even when tours are disabled', () => {
|
||||
const request = vi.fn()
|
||||
$gateway.set({ request } as never)
|
||||
$toursEnabled.set(false)
|
||||
|
||||
expect(handleDesktopBridgeEvent(tourContext({ explicitSid: 'session-a', isActiveEvent: false }))).toBe(true)
|
||||
expect(request).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the legacy fail-fast response for an unscoped inactive request', () => {
|
||||
const request = vi.fn()
|
||||
$gateway.set({ request } as never)
|
||||
|
||||
expect(handleDesktopBridgeEvent(tourContext({ explicitSid: '', isActiveEvent: false }))).toBe(true)
|
||||
expect(request).toHaveBeenCalledWith('tour.respond', {
|
||||
request_id: 'tour-request-1',
|
||||
text: JSON.stringify({
|
||||
error: 'Tours only run in the session the user is looking at.',
|
||||
success: false
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
+4
-210
@@ -1,165 +1,17 @@
|
||||
import { readActivePreview } from '@/app/chat/right-rail/preview-reader'
|
||||
import { writeAgentTerminalChunk } from '@/app/right-sidebar/terminal/agent-terminal-stream'
|
||||
import { readActiveTerminal } from '@/app/right-sidebar/terminal/buffer'
|
||||
import { closeAgentTerminalByProc } from '@/app/right-sidebar/terminal/terminals'
|
||||
import type { PreviewActAction } from '@/lib/preview-act/act-in-page'
|
||||
import type { TourAction, TourStep } from '@/lib/tour'
|
||||
import { $gateway } from '@/store/gateway'
|
||||
import { applyDesktopLayoutPreset, revealDesktopPane } from '@/store/pane-focus'
|
||||
import { recordAgentReaction } from '@/store/reactions-local'
|
||||
import { setMessages } from '@/store/session'
|
||||
import { $tipsEnabled, type ActiveTip, showTip } from '@/store/tips'
|
||||
import { $toursEnabled } from '@/store/tours'
|
||||
|
||||
import type { GatewayEventContext } from './types'
|
||||
|
||||
/** The preview engine, loaded on demand so ~25KB of page-injectable source stays
|
||||
* off the boot path.
|
||||
*
|
||||
* In dev that lazy chunk is also a trap. The browser caches a dynamic import by
|
||||
* URL for the life of the page, so this bridge would hand every action to
|
||||
* whichever build of the engine loaded first, and no edit to it — or to the
|
||||
* overlay whose source it stringifies into the page — would reach the guest
|
||||
* until the whole window reloaded. Asking for a fresh copy is more reliable
|
||||
* than trusting hot-update propagation to reach a module nothing statically
|
||||
* imports; the dev server stamps the dependency URLs it has invalidated, so a
|
||||
* fresh engine pulls a fresh overlay down with it.
|
||||
*
|
||||
* The literal path is what a bare specifier can't be here, and it has to track
|
||||
* this module's real location — hence the fall back to the static import, which
|
||||
* is also the only branch production keeps, `import.meta.hot` being stripped
|
||||
* there along with everything it guards. */
|
||||
const loadPreviewEngine = () => {
|
||||
const stable = () => import('@/app/chat/right-rail/preview-act')
|
||||
|
||||
if (!import.meta.hot) {
|
||||
return stable().then(mod => mod.actOnActivePreview)
|
||||
}
|
||||
|
||||
return import(/* @vite-ignore */ '/src/app/chat/right-rail/preview-act.ts?hot=' + Date.now())
|
||||
.catch(stable)
|
||||
.then(mod => mod.actOnActivePreview as Awaited<ReturnType<typeof stable>>['actOnActivePreview'])
|
||||
}
|
||||
|
||||
/** Desktop-surface bridge events: read-back requests the agent blocks on
|
||||
* (terminal/preview/window), agent terminal streaming, pane reveal, and
|
||||
* message reactions. */
|
||||
/** Desktop-surface bridge events: agent terminal streaming, tips, pane
|
||||
* reveal, layouts and message reactions. The read-back REQUESTS the agent
|
||||
* blocks on (terminal/preview/window/tour) live in `server-requests.ts`. */
|
||||
export function handleDesktopBridgeEvent(ctx: GatewayEventContext): boolean {
|
||||
const { event, payload, explicitSid, isActiveEvent } = ctx
|
||||
|
||||
if (event.type === 'terminal.read.request') {
|
||||
// read_terminal tool: serialize the renderer's xterm buffer and answer
|
||||
// immediately (Python blocks on the respond). Empty text = no live pane.
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
const start = typeof payload?.start === 'number' ? payload.start : undefined
|
||||
const count = typeof payload?.count === 'number' ? payload.count : undefined
|
||||
const result = readActiveTerminal({ start, count })
|
||||
|
||||
void $gateway.get()?.request('terminal.read.respond', {
|
||||
request_id: requestId,
|
||||
text: result ? JSON.stringify(result) : ''
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'preview.read.request') {
|
||||
// read_preview tool: serialize the active preview tab (a Browser
|
||||
// webview's page text is async) and answer. Empty text = nothing open.
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
const start = typeof payload?.start === 'number' ? payload.start : undefined
|
||||
const count = typeof payload?.count === 'number' ? payload.count : undefined
|
||||
|
||||
void readActivePreview({ count, start }).then(result => {
|
||||
void $gateway.get()?.request('preview.read.respond', {
|
||||
request_id: requestId,
|
||||
text: result ? JSON.stringify(result) : ''
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'preview.act.request') {
|
||||
// drive_preview tool: click/type/scroll/press inside the guest page, or
|
||||
// drive the pane's history. Dynamic import keeps the injected engine off
|
||||
// the boot path. Active session only: a background turn must never reach
|
||||
// into the page the user is working in (desktop AGENTS.md: offer, don't
|
||||
// hijack).
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
// Every mounted desktop window can observe the same gateway event. A
|
||||
// scoped mismatch belongs to another window, so answering here would race
|
||||
// the owning window and could make this refusal win before its real result.
|
||||
if (explicitSid && !isActiveEvent) {
|
||||
return true
|
||||
}
|
||||
|
||||
const answer = (result: unknown) =>
|
||||
$gateway.get()?.request('preview.act.respond', {
|
||||
request_id: requestId,
|
||||
text: result ? JSON.stringify(result) : ''
|
||||
})
|
||||
|
||||
if (isActiveEvent) {
|
||||
void loadPreviewEngine()
|
||||
.then(run =>
|
||||
run({
|
||||
amount: payload?.amount,
|
||||
key: payload?.key,
|
||||
kind: payload?.action ?? '',
|
||||
max: payload?.max,
|
||||
ref: payload?.ref,
|
||||
selector: payload?.selector,
|
||||
submit: payload?.submit,
|
||||
text: payload?.text,
|
||||
to: payload?.to as PreviewActAction['to']
|
||||
})
|
||||
)
|
||||
.then(answer, error =>
|
||||
answer({ error: error instanceof Error ? error.message : String(error), success: false })
|
||||
)
|
||||
} else {
|
||||
void answer({
|
||||
error: 'The in-app browser only takes actions in the session the user is looking at.',
|
||||
success: false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'window.read.request') {
|
||||
// read_window_below tool: main owns native window enumeration, so ask
|
||||
// it over IPC and answer. Empty text = unavailable (no bridge, or
|
||||
// enumeration unsupported on this system e.g. Wayland).
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
const read = window.hermesDesktop?.readWindowBelow
|
||||
|
||||
const answer = (result: unknown) =>
|
||||
$gateway.get()?.request('window.read.respond', {
|
||||
request_id: requestId,
|
||||
text: result ? JSON.stringify(result) : ''
|
||||
})
|
||||
|
||||
// .catch: ipcRenderer.invoke rejects on an older shell without the
|
||||
// handler or a main-side throw — without an empty answer the tool
|
||||
// would stall its full 30s timeout.
|
||||
void Promise.resolve(read ? read() : null).then(answer, () => answer(null))
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
const { event, payload, isActiveEvent } = ctx
|
||||
|
||||
if (event.type === 'agent.terminal.output') {
|
||||
// Live chunk from a background process → its read-only agent terminal tab.
|
||||
@@ -176,64 +28,6 @@ export function handleDesktopBridgeEvent(ctx: GatewayEventContext): boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'tour.request') {
|
||||
// tour tool: run one guided-tour action (highlight/step/discover) via
|
||||
// driver.js — on the app's own DOM or inside the preview pane's guest
|
||||
// page — and answer with the outcome. Dynamic import keeps driver.js
|
||||
// and the preview injection payload off the boot path. Active session
|
||||
// only: a background turn must never paint overlays on the user's
|
||||
// screen (desktop AGENTS.md: offer, don't hijack).
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
// As with preview actions, only the renderer that owns an explicitly
|
||||
// scoped request may answer. Inactive windows must stay silent even when
|
||||
// tours are disabled locally, or their refusal can beat the owner.
|
||||
if (explicitSid && !isActiveEvent) {
|
||||
return true
|
||||
}
|
||||
|
||||
const answer = (result: unknown) =>
|
||||
$gateway.get()?.request('tour.respond', {
|
||||
request_id: requestId,
|
||||
text: result ? JSON.stringify(result) : ''
|
||||
})
|
||||
|
||||
if (!$toursEnabled.get()) {
|
||||
// Refused in words, not silently dropped: the agent asked for a
|
||||
// walkthrough it isn't getting, and a no-op would leave it narrating
|
||||
// a spotlight the user can't see.
|
||||
void answer({ error: 'The user has turned guided tours off.', success: false })
|
||||
} else if (isActiveEvent) {
|
||||
void import('@/lib/tour')
|
||||
.then(({ runTour }) =>
|
||||
runTour(
|
||||
{
|
||||
kind: (payload?.action ?? 'stop') as TourAction['kind'],
|
||||
selector: payload?.selector,
|
||||
side: payload?.side as TourStep['side'],
|
||||
startAt: payload?.step_index,
|
||||
steps: payload?.steps as TourStep[] | undefined,
|
||||
text: payload?.text,
|
||||
title: payload?.title
|
||||
},
|
||||
payload?.surface === 'preview' ? 'preview' : 'app'
|
||||
)
|
||||
)
|
||||
.then(answer, error =>
|
||||
answer({ error: error instanceof Error ? error.message : String(error), success: false })
|
||||
)
|
||||
} else {
|
||||
void answer({
|
||||
error: 'Tours only run in the session the user is looking at.',
|
||||
success: false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'tip.show') {
|
||||
// tip tool: point the accent bubble at something and say one line about
|
||||
// it. Fire-and-forget — a tip is not a question, and blocking the turn on
|
||||
|
||||
+24
-12
@@ -1,18 +1,23 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { $sudoRequest, clearSudoRequest } from '@/store/prompts'
|
||||
import { resetServerRequestsForTests } from '@/store/server-requests'
|
||||
import { $activeSessionId } from '@/store/session'
|
||||
|
||||
import { handleInputRequestEvent } from './input-requests'
|
||||
import { handleServerRequest } from './server-requests'
|
||||
import type { ServerRequestContext } from './server-requests'
|
||||
import type { GatewayEventContext } from './types'
|
||||
|
||||
vi.mock('@/store/native-notifications', () => ({ dispatchNativeNotification: vi.fn() }))
|
||||
|
||||
function context(type: GatewayEventContext['event']['type'], requestId: string, routedSession: string | null): GatewayEventContext {
|
||||
const payload = { request_id: requestId, profile_key: '/home/h/.hermes' }
|
||||
const deps = { updateSessionState: vi.fn(), upsertToolCall: vi.fn() } as unknown as ServerRequestContext['deps']
|
||||
|
||||
function cancel(requestId: string, routedSession: string | null): GatewayEventContext {
|
||||
const payload = { id: requestId, method: 'display.install.sudo', reason: 'timeout' }
|
||||
return {
|
||||
deps: { updateSessionState: vi.fn() } as unknown as GatewayEventContext['deps'],
|
||||
event: { payload, type },
|
||||
deps: deps as unknown as GatewayEventContext['deps'],
|
||||
event: { payload, type: 'request.cancel' },
|
||||
explicitSid: '',
|
||||
fromActiveSource: () => true,
|
||||
isActiveEvent: true,
|
||||
@@ -26,21 +31,28 @@ function context(type: GatewayEventContext['event']['type'], requestId: string,
|
||||
describe('Bot Screen install password card', () => {
|
||||
afterEach(() => {
|
||||
clearSudoRequest()
|
||||
resetServerRequestsForTests()
|
||||
$activeSessionId.set(null)
|
||||
})
|
||||
|
||||
it('belongs to the app, not to the chat that happened to be open: it survives a chat switch and its expiry finds it', () => {
|
||||
// The gateway emits the card sessionless; the stream resolver attributes an unscoped event to the
|
||||
// ambient chat. Stored under that chat, the card vanished the moment the user switched chats and
|
||||
// the expiry (routed to the NEW ambient chat) never reached it.
|
||||
it('belongs to the app, not to the chat that happened to be open: it survives a chat switch and its cancel finds it', () => {
|
||||
// The gateway sends the request sessionless. Stored under the ambient chat, the card vanished the
|
||||
// moment the user switched chats and the cancel (routed to the NEW ambient chat) never reached it.
|
||||
$activeSessionId.set('chat-a')
|
||||
expect(handleInputRequestEvent(context('display.install.sudo.request', 'req-1', 'chat-a'))).toBe(true)
|
||||
expect($sudoRequest.get()?.requestId).toBe('req-1')
|
||||
const respond = vi.fn()
|
||||
expect(
|
||||
handleServerRequest(
|
||||
{ fail: vi.fn(), id: 'srq-1', method: 'display.install.sudo', params: { profile_key: '/home/h/.hermes', session_id: '' }, profile: 'default', respond },
|
||||
deps,
|
||||
'chat-a'
|
||||
)
|
||||
).toBe(true)
|
||||
expect($sudoRequest.get()?.requestId).toBe('srq-1')
|
||||
|
||||
$activeSessionId.set('chat-b')
|
||||
expect($sudoRequest.get()?.requestId).toBe('req-1')
|
||||
expect($sudoRequest.get()?.requestId).toBe('srq-1')
|
||||
|
||||
expect(handleInputRequestEvent(context('display.install.sudo.expire', 'req-1', 'chat-b'))).toBe(true)
|
||||
expect(handleInputRequestEvent(cancel('srq-1', 'chat-b'))).toBe(true)
|
||||
expect($sudoRequest.get()).toBeNull()
|
||||
})
|
||||
})
|
||||
+78
-413
@@ -1,168 +1,62 @@
|
||||
import type { ConnectionRequestPayload, ConnectionUpdatePayload, GatewayEvent } from '@hermes/shared'
|
||||
|
||||
import { pendingClarifyToolPayload } from '@/app/session/hooks/use-session-actions/restore-pending-clarify'
|
||||
import { connectionRequestToolPayload } from '@/app/session/hooks/use-session-actions/restore-pending-connection'
|
||||
import { translateNow } from '@/i18n'
|
||||
import { restorePendingClarifyToolCall, settlePendingClarifyToolCall } from '@/lib/chat-messages'
|
||||
import {
|
||||
$clarifyRequests,
|
||||
clearClarifyRequest,
|
||||
normalizeChoices,
|
||||
normalizeQuestions,
|
||||
setClarifyRequest,
|
||||
warnDroppedChoices
|
||||
} from '@/store/clarify'
|
||||
import { $gateway } from '@/store/gateway'
|
||||
import { setMcpSetupRequest } from '@/store/mcp-setup'
|
||||
import { settlePendingClarifyToolCall } from '@/lib/chat-messages'
|
||||
import { $clarifyRequests, clearClarifyRequest } from '@/store/clarify'
|
||||
import { normalizeConnectionRequest, setConnectionRequest, updateConnectionRequest } from '@/store/connection-request'
|
||||
import { dispatchNativeNotification } from '@/store/native-notifications'
|
||||
import { $activeGatewayProfile } from '@/store/profile'
|
||||
import {
|
||||
$approvalRequests,
|
||||
$secretRequests,
|
||||
$sudoRequests,
|
||||
$vaultCodeRequests,
|
||||
$vaultSaveLoginRequests,
|
||||
$vaultUnlockRequests,
|
||||
clearApprovalRequest,
|
||||
clearSecretRequest,
|
||||
clearSudoRequest,
|
||||
clearVaultCodeRequest,
|
||||
clearVaultSaveLoginRequest,
|
||||
clearVaultUnlockRequest,
|
||||
receiveApprovalRequest,
|
||||
setSecretRequest,
|
||||
setSudoRequest,
|
||||
setVaultCodeRequest,
|
||||
setVaultSaveLoginRequest,
|
||||
setVaultUnlockRequest
|
||||
clearVaultUnlockRequest
|
||||
} from '@/store/prompts'
|
||||
import { requestScrollToBottom } from '@/store/thread-scroll'
|
||||
import { forgetServerRequest } from '@/store/server-requests'
|
||||
|
||||
import type { GatewayEventContext } from './types'
|
||||
|
||||
/** The blocking-input family: clarify / MCP setup consent / approval / sudo /
|
||||
* secret requests. The Python side is blocked on the matching *.respond, so
|
||||
* each of these must be parked per-session and surfaced. */
|
||||
type ConnectionRequestEvent = GatewayEvent<'connection.request'> & { payload: ConnectionRequestPayload }
|
||||
type ConnectionUpdateEvent = GatewayEvent<'connection.update'> & { payload: ConnectionUpdatePayload }
|
||||
|
||||
const isConnectionRequestEvent = (event: GatewayEvent): event is ConnectionRequestEvent =>
|
||||
event.type === 'connection.request' && event.payload !== undefined
|
||||
|
||||
const isConnectionUpdateEvent = (event: GatewayEvent): event is ConnectionUpdateEvent =>
|
||||
event.type === 'connection.update' && event.payload !== undefined
|
||||
|
||||
/** The blocking-input family arrives as server→client REQUESTS (see
|
||||
* `server-requests.ts`); the one EVENT in the family is `request.cancel`, the
|
||||
* backend withdrawing an open request (timeout / interrupt / session close):
|
||||
* tear down whichever parked card carries that id. Cancel is request-correlated:
|
||||
* a delayed cancel for an older prompt must not erase a newer one the same
|
||||
* session raised. */
|
||||
export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
|
||||
const { deps, event, payload, sessionId, occurredAt } = ctx
|
||||
const { activeSessionIdRef, sessionInterrupted, updateSessionState, upsertToolCall } = deps
|
||||
|
||||
if (event.type === 'clarify.request') {
|
||||
// Surface the clarify tool's overlay. The Python side is blocked on
|
||||
// `clarify.respond`, so without this handler the agent would hang
|
||||
// forever (see tools/clarify_tool.py + tui_gateway/server.py:_block).
|
||||
//
|
||||
// Store the request for whichever session raised it — even a background
|
||||
// one. clarify.request is a one-shot event; if we dropped it for an
|
||||
// unfocused session, that session would block on `clarify.respond`
|
||||
// indefinitely and re-focusing it could never recover (the event is
|
||||
// gone). Parking it per-session lets the user answer once they switch
|
||||
// over; the inline ClarifyTool reads the active session's entry.
|
||||
if (sessionId && sessionInterrupted(sessionId)) {
|
||||
return true
|
||||
}
|
||||
if (isConnectionRequestEvent(event)) {
|
||||
// Park per-session and upsert a stable tool row so the card renders even if tool.start was missed.
|
||||
const request = normalizeConnectionRequest(event.payload, sessionId ?? null)
|
||||
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const question = typeof payload?.question === 'string' ? payload.question : ''
|
||||
const rawChoices = payload?.choices
|
||||
const choices = normalizeChoices(rawChoices)
|
||||
const multiSelect = payload?.multi_select === true
|
||||
// Batch (multi-question) clarify: `questions` replaces question/choices
|
||||
// on the wire. `answers` rides along only on reconnect replay, carrying
|
||||
// the per-question locks the server already accepted.
|
||||
const questions = normalizeQuestions(payload?.questions)
|
||||
|
||||
const lockedAnswers =
|
||||
typeof payload?.answers === 'object' && payload?.answers !== null
|
||||
? Object.fromEntries(
|
||||
Object.entries(payload.answers as Record<string, unknown>).filter(
|
||||
(entry): entry is [string, string] => typeof entry[1] === 'string'
|
||||
)
|
||||
)
|
||||
: undefined
|
||||
|
||||
if (requestId && questions.length > 0) {
|
||||
const request = {
|
||||
choices: null,
|
||||
lockedAnswers,
|
||||
multiSelect: false,
|
||||
question: '',
|
||||
questions,
|
||||
receivedAt: Date.now() / 1000,
|
||||
requestId,
|
||||
sessionId: sessionId ?? null
|
||||
}
|
||||
|
||||
setClarifyRequest(request)
|
||||
if (request) {
|
||||
setConnectionRequest(request)
|
||||
|
||||
if (sessionId) {
|
||||
// A resumed/hydrated transcript may already contain this provider's
|
||||
// clarify call while carrying no live streamId. Re-arm that exact row
|
||||
// instead of letting the generic stream mutator append a second card.
|
||||
updateSessionState(sessionId, state => {
|
||||
const projection = restorePendingClarifyToolCall(
|
||||
state.messages,
|
||||
pendingClarifyToolPayload(request),
|
||||
occurredAt
|
||||
)
|
||||
|
||||
return {
|
||||
...state,
|
||||
messages: projection.messages,
|
||||
streamId: projection.streamId,
|
||||
sawAssistantPayload: true,
|
||||
awaitingResponse: false,
|
||||
needsInput: true
|
||||
}
|
||||
})
|
||||
|
||||
if (sessionId === activeSessionIdRef.current) {
|
||||
requestScrollToBottom(sessionId)
|
||||
}
|
||||
deps.upsertToolCall(sessionId, connectionRequestToolPayload(request), 'running')
|
||||
deps.updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: questions.map(q => q.question).join(' · '),
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
})
|
||||
} else if (requestId && question) {
|
||||
if (rawChoices != null && choices.length === 0) {
|
||||
warnDroppedChoices('gateway', question, rawChoices)
|
||||
}
|
||||
|
||||
const request = {
|
||||
requestId,
|
||||
question,
|
||||
choices: choices.length > 0 ? choices : null,
|
||||
multiSelect,
|
||||
receivedAt: Date.now() / 1000,
|
||||
sessionId: sessionId ?? null
|
||||
}
|
||||
|
||||
setClarifyRequest(request)
|
||||
|
||||
if (sessionId) {
|
||||
// Same provider-shape-aware repair as the batch path above. This keeps
|
||||
// the original hydrated row and provider tool id, while still seeding
|
||||
// a row when tool.start was genuinely missed.
|
||||
updateSessionState(sessionId, state => {
|
||||
const projection = restorePendingClarifyToolCall(
|
||||
state.messages,
|
||||
pendingClarifyToolPayload(request),
|
||||
occurredAt
|
||||
)
|
||||
|
||||
return {
|
||||
...state,
|
||||
messages: projection.messages,
|
||||
streamId: projection.streamId,
|
||||
sawAssistantPayload: true,
|
||||
awaitingResponse: false,
|
||||
needsInput: true
|
||||
}
|
||||
})
|
||||
|
||||
if (sessionId === activeSessionIdRef.current) {
|
||||
requestScrollToBottom(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: question,
|
||||
body: request.targets.map(target => target.name).join(', '),
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
@@ -172,300 +66,71 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'vault.code.expire') {
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const request = sessionId ? $vaultCodeRequests.get()[sessionId] : undefined
|
||||
if (isConnectionUpdateEvent(event)) {
|
||||
updateConnectionRequest(sessionId ?? null, event.payload)
|
||||
|
||||
if (requestId && request && request.requestId === requestId) {
|
||||
clearVaultCodeRequest(sessionId, requestId)
|
||||
if (event.payload.settled && sessionId) {
|
||||
deps.updateSessionState(sessionId, state => ({ ...state, needsInput: false }))
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'vault.save_login.expire') {
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const request = sessionId ? $vaultSaveLoginRequests.get()[sessionId] : undefined
|
||||
if (event.type !== 'request.cancel') {
|
||||
return false
|
||||
}
|
||||
|
||||
if (requestId && request && request.requestId === requestId) {
|
||||
clearVaultSaveLoginRequest(sessionId, requestId)
|
||||
}
|
||||
const id = typeof payload?.id === 'string' ? payload.id : ''
|
||||
|
||||
if (!id) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'vault.unlock.expire') {
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const request = sessionId ? $vaultUnlockRequests.get()[sessionId] : undefined
|
||||
forgetServerRequest(id)
|
||||
|
||||
if (requestId && request && request.requestId === requestId) {
|
||||
clearVaultUnlockRequest(sessionId, requestId)
|
||||
}
|
||||
const key = sessionId ?? ''
|
||||
|
||||
return true
|
||||
}
|
||||
if ($clarifyRequests.get()[key]?.requestId === id) {
|
||||
const request = $clarifyRequests.get()[key]
|
||||
|
||||
if (event.type === 'sudo.expire' || event.type === 'display.install.sudo.expire') {
|
||||
// The backend gave up waiting; tear the card down so a late Send cannot go anywhere. The install
|
||||
// card is app-level (stored under the null session), so its expiry must not be routed to whatever
|
||||
// chat is active now.
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const install = event.type === 'display.install.sudo.expire'
|
||||
clearSudoRequest(install ? null : sessionId ?? undefined, requestId || undefined)
|
||||
clearClarifyRequest(id, sessionId)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'clarify.expire') {
|
||||
if (!sessionId) {
|
||||
return true
|
||||
}
|
||||
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const request = $clarifyRequests.get()[sessionId]
|
||||
|
||||
// Expiry is request-correlated: a delayed event from an older prompt must
|
||||
// not erase a newer clarify raised by the same session.
|
||||
if (!requestId || !request || request.requestId !== requestId) {
|
||||
return true
|
||||
}
|
||||
|
||||
clearClarifyRequest(requestId, sessionId)
|
||||
updateSessionState(sessionId, state => {
|
||||
const projection = settlePendingClarifyToolCall(
|
||||
state.messages,
|
||||
pendingClarifyToolPayload(request),
|
||||
state.busy,
|
||||
occurredAt
|
||||
)
|
||||
|
||||
return {
|
||||
...state,
|
||||
messages: projection.messages,
|
||||
needsInput: false,
|
||||
streamId: state.busy ? (projection.streamId ?? state.streamId) : null
|
||||
}
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'mcp.setup.request') {
|
||||
// setup_mcp tool (desktop GUI): the agent proposed an MCP server and
|
||||
// the Python side is blocked on mcp.setup.respond. Park the request
|
||||
// per-session (like clarify) and upsert a stable pending tool row so
|
||||
// the inline consent card has somewhere to render even when the
|
||||
// tool.start event was missed (stream reconnect / hydration race).
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const server = typeof payload?.server === 'string' ? payload.server : ''
|
||||
const rawAction = typeof payload?.action === 'string' ? payload.action : 'install'
|
||||
const action = rawAction === 'enable' || rawAction === 'authorize' ? rawAction : 'install'
|
||||
const reason = typeof payload?.reason === 'string' ? payload.reason : ''
|
||||
|
||||
if (requestId && server) {
|
||||
setMcpSetupRequest({ action, reason, requestId, server, sessionId: sessionId ?? null })
|
||||
|
||||
if (sessionId) {
|
||||
upsertToolCall(
|
||||
sessionId,
|
||||
{ args: { action, reason, server }, name: 'setup_mcp', tool_id: requestId },
|
||||
'running'
|
||||
if (sessionId && request) {
|
||||
deps.updateSessionState(sessionId, state => {
|
||||
const projection = settlePendingClarifyToolCall(
|
||||
state.messages,
|
||||
pendingClarifyToolPayload(request),
|
||||
state.busy,
|
||||
occurredAt
|
||||
)
|
||||
updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: reason || server,
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
return {
|
||||
...state,
|
||||
messages: projection.messages,
|
||||
needsInput: false,
|
||||
streamId: state.busy ? (projection.streamId ?? state.streamId) : null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'approval.request') {
|
||||
// Dangerous-command / execute_code approval. The Python side is blocked
|
||||
// in _await_gateway_decision() until approval.respond lands; without
|
||||
// this the agent stalls until its 5-min timeout and the tool is BLOCKED.
|
||||
// Park it per-session (like clarify) so a *background* profile's turn can
|
||||
// raise it and wait — the sidebar flags "needs input" and the inline bar
|
||||
// surfaces once the user focuses that chat.
|
||||
const command = typeof payload?.command === 'string' ? payload.command : ''
|
||||
const description = typeof payload?.description === 'string' ? payload.description : 'dangerous command'
|
||||
|
||||
void receiveApprovalRequest($gateway.get(), {
|
||||
// false only when a tirith warning forbids it; backend omits the field otherwise.
|
||||
allowPermanent: payload?.allow_permanent !== false,
|
||||
choices: Array.isArray(payload?.choices)
|
||||
? payload.choices.filter(choice => typeof choice === 'string')
|
||||
: undefined,
|
||||
command,
|
||||
description,
|
||||
requestId: typeof payload?.request_id === 'string' ? payload.request_id : undefined,
|
||||
sessionId: sessionId ?? null,
|
||||
smartDenied: payload?.smart_denied === true
|
||||
}).catch(() => undefined)
|
||||
|
||||
if (sessionId) {
|
||||
updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
actions: [
|
||||
{ id: 'approve', text: translateNow('notifications.native.approveAction') },
|
||||
{ id: 'reject', text: translateNow('notifications.native.rejectAction') }
|
||||
],
|
||||
body: command || description,
|
||||
kind: 'approval',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.approvalTitle')
|
||||
})
|
||||
|
||||
return true
|
||||
if ($approvalRequests.get()[key]?.serverRequestId === id) {
|
||||
clearApprovalRequest(sessionId, $approvalRequests.get()[key]?.requestId)
|
||||
} else if ($sudoRequests.get()[key]?.requestId === id) {
|
||||
clearSudoRequest(sessionId, id)
|
||||
} else if ($sudoRequests.get()['']?.requestId === id) {
|
||||
clearSudoRequest(null, id) // the app-level Bot Screen install card: not owned by any chat
|
||||
} else if ($secretRequests.get()[key]?.requestId === id) {
|
||||
clearSecretRequest(sessionId, id)
|
||||
} else if ($vaultCodeRequests.get()[key]?.requestId === id) {
|
||||
clearVaultCodeRequest(sessionId, id)
|
||||
} else if ($vaultSaveLoginRequests.get()[key]?.requestId === id) {
|
||||
clearVaultSaveLoginRequest(sessionId, id)
|
||||
} else if ($vaultUnlockRequests.get()[key]?.requestId === id) {
|
||||
clearVaultUnlockRequest(sessionId, id)
|
||||
}
|
||||
|
||||
if (event.type === 'sudo.request' || event.type === 'display.install.sudo.request') {
|
||||
// Sudo password capture (tools/terminal_tool.py), or the Bot Screen package install
|
||||
// (tui_gateway/methods_display.py) reusing the same masked card. Blocked on
|
||||
// <method>.respond {request_id, password}.
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
const install = event.type === 'display.install.sudo.request'
|
||||
|
||||
if (requestId) {
|
||||
// The install card belongs to the app, not to a chat: the gateway emits it sessionless and the
|
||||
// stream resolver would otherwise attribute it to the ambient chat, hiding it on a chat switch.
|
||||
const owner = install ? null : sessionId ?? null
|
||||
setSudoRequest({
|
||||
requestId,
|
||||
sessionId: owner,
|
||||
origin: { connectionId: event.connectionId ?? null, profile: event.profile ?? $activeGatewayProfile.get() },
|
||||
...(install ? { respondMethod: 'display.install.sudo.respond', description: translateNow('prompts.sudoInstallDesc') } : {})
|
||||
})
|
||||
|
||||
if (owner) {
|
||||
updateSessionState(owner, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: translateNow('notifications.native.inputBody'),
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'secret.request') {
|
||||
// Skill credential capture (tools/skills_tool.py). Blocked on
|
||||
// secret.respond {request_id, value}.
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
const envVar = typeof payload?.env_var === 'string' ? payload.env_var : ''
|
||||
const promptText = typeof payload?.prompt === 'string' ? payload.prompt : ''
|
||||
|
||||
setSecretRequest({
|
||||
requestId,
|
||||
envVar,
|
||||
prompt: promptText,
|
||||
sessionId: sessionId ?? null
|
||||
})
|
||||
|
||||
if (sessionId) {
|
||||
updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: promptText || envVar || translateNow('notifications.native.inputBody'),
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'vault.code.request') {
|
||||
// Second factor: the site asked for a one-time code and no authenticator key is saved for the login.
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
const site = typeof payload?.site === 'string' ? payload.site : ''
|
||||
const hint = typeof payload?.hint === 'string' ? payload.hint : ''
|
||||
|
||||
setVaultCodeRequest({ hint, requestId, sessionId: sessionId ?? null, site })
|
||||
|
||||
if (sessionId) {
|
||||
updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: translateNow('prompts.vaultCodeTitle', site),
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'vault.save_login.request') {
|
||||
// The agent is on a sign-in page with no saved login: identifier + masked password card; the
|
||||
// answer is stored in the encrypted vault by the backend and filled at once (never shown to the model).
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
const origin = typeof payload?.origin === 'string' ? payload.origin : ''
|
||||
const site = typeof payload?.site === 'string' ? payload.site : origin
|
||||
|
||||
setVaultSaveLoginRequest({ origin, requestId, sessionId: sessionId ?? null, site })
|
||||
|
||||
if (sessionId) {
|
||||
updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: translateNow('prompts.vaultSaveTitle', site),
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.type === 'vault.unlock.request') {
|
||||
// External password-manager unlock (agent/vault_backends). Blocked on
|
||||
// vault.unlock.respond {request_id, password}; "" keeps it locked.
|
||||
const requestId = typeof payload?.request_id === 'string' ? payload.request_id : ''
|
||||
|
||||
if (requestId) {
|
||||
const backend = typeof payload?.backend === 'string' ? payload.backend : ''
|
||||
const displayName = typeof payload?.display_name === 'string' ? payload.display_name : backend
|
||||
|
||||
setVaultUnlockRequest({ backend, displayName, requestId, sessionId: sessionId ?? null })
|
||||
|
||||
if (sessionId) {
|
||||
updateSessionState(sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
|
||||
dispatchNativeNotification({
|
||||
body: translateNow('prompts.vaultUnlockTitle', displayName),
|
||||
kind: 'input',
|
||||
sessionId,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
return true
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { createClientSessionState } from '@/lib/chat-runtime'
|
||||
import { $toursEnabled } from '@/store/tours'
|
||||
|
||||
import { handleServerRequest } from './server-requests'
|
||||
import type { ServerRequestContext } from './server-requests'
|
||||
|
||||
const deps = {
|
||||
activeSessionIdRef: { current: null },
|
||||
sessionInterrupted: () => false,
|
||||
updateSessionState: (_sessionId, update) => update(createClientSessionState('stored-session')),
|
||||
upsertToolCall: () => undefined
|
||||
} as ServerRequestContext['deps']
|
||||
|
||||
function deliver(method: string, params: Record<string, unknown>, activeSessionId: null | string) {
|
||||
const respond = vi.fn()
|
||||
const fail = vi.fn()
|
||||
const handled = handleServerRequest({ fail, id: 'srq-1', method, params, profile: 'default', respond }, deps, activeSessionId)
|
||||
|
||||
return { fail, handled, respond }
|
||||
}
|
||||
|
||||
describe('connection request routing', () => {
|
||||
it('does not route connection operations through the server-request rail', () => {
|
||||
const { handled, respond } = deliver(
|
||||
'connection',
|
||||
{
|
||||
deadline_at: 1_800_000_000,
|
||||
op_id: 'op-1',
|
||||
session_id: 'session-a',
|
||||
targets: [{ action: 'install', kind: 'mcp', name: 'linear' }],
|
||||
timeout_seconds: 60,
|
||||
tool_call_id: 'call-1'
|
||||
},
|
||||
'session-a'
|
||||
)
|
||||
|
||||
expect(handled).toBe(false)
|
||||
expect(respond).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('preview action request routing', () => {
|
||||
it('leaves a scoped action request unanswered in a window showing another session', () => {
|
||||
const { handled, respond, fail } = deliver('preview.act', { action: 'elements', session_id: 'session-a' }, 'session-b')
|
||||
|
||||
expect(handled).toBe(true)
|
||||
expect(respond).not.toHaveBeenCalled()
|
||||
expect(fail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails fast for an unscoped request with no session in view', () => {
|
||||
const { respond } = deliver('preview.act', { action: 'elements' }, null)
|
||||
|
||||
expect(respond).toHaveBeenCalledWith({
|
||||
value: JSON.stringify({
|
||||
error: 'The in-app browser only takes actions in the session the user is looking at.',
|
||||
success: false
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('tour request routing', () => {
|
||||
afterEach(() => {
|
||||
$toursEnabled.set(true)
|
||||
})
|
||||
|
||||
it('leaves a scoped request unanswered in another session even when tours are disabled', () => {
|
||||
$toursEnabled.set(false)
|
||||
const { handled, respond } = deliver('tour', { action: 'discover', session_id: 'session-a' }, 'session-b')
|
||||
|
||||
expect(handled).toBe(true)
|
||||
expect(respond).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails fast for an unscoped request with no session in view', () => {
|
||||
const { respond } = deliver('tour', { action: 'discover' }, null)
|
||||
|
||||
expect(respond).toHaveBeenCalledWith({
|
||||
value: JSON.stringify({ error: 'Tours only run in the session the user is looking at.', success: false })
|
||||
})
|
||||
})
|
||||
})
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
import { readActivePreview } from '@/app/chat/right-rail/preview-reader'
|
||||
import { readActiveTerminal } from '@/app/right-sidebar/terminal/buffer'
|
||||
import { pendingClarifyToolPayload } from '@/app/session/hooks/use-session-actions/restore-pending-clarify'
|
||||
import { translateNow } from '@/i18n'
|
||||
import { restorePendingClarifyToolCall } from '@/lib/chat-messages'
|
||||
import type { PreviewActAction } from '@/lib/preview-act/act-in-page'
|
||||
import type { TourAction, TourStep } from '@/lib/tour'
|
||||
import { normalizeChoices, normalizeQuestions, setClarifyRequest, warnDroppedChoices } from '@/store/clarify'
|
||||
import type { ScopedServerRequest } from '@/store/gateway'
|
||||
import { dispatchNativeNotification } from '@/store/native-notifications'
|
||||
import {
|
||||
receiveApprovalRequest,
|
||||
setSecretRequest,
|
||||
setSudoRequest,
|
||||
setVaultCodeRequest,
|
||||
setVaultSaveLoginRequest,
|
||||
setVaultUnlockRequest
|
||||
} from '@/store/prompts'
|
||||
import { rememberServerRequest } from '@/store/server-requests'
|
||||
import { requestScrollToBottom } from '@/store/thread-scroll'
|
||||
import { $toursEnabled } from '@/store/tours'
|
||||
|
||||
import type { GatewayEventDeps } from './types'
|
||||
|
||||
/** The preview engine, loaded on demand so ~25KB of page-injectable source stays
|
||||
* off the boot path (dev: a fresh copy per action so edits reach the guest — see
|
||||
* the previous home of this loader in desktop-bridge.ts for the full story). */
|
||||
const loadPreviewEngine = () => {
|
||||
const stable = () => import('@/app/chat/right-rail/preview-act')
|
||||
|
||||
if (!import.meta.hot) {
|
||||
return stable().then(mod => mod.actOnActivePreview)
|
||||
}
|
||||
|
||||
return import(/* @vite-ignore */ '/src/app/chat/right-rail/preview-act.ts?hot=' + Date.now())
|
||||
.catch(stable)
|
||||
.then(mod => mod.actOnActivePreview as Awaited<ReturnType<typeof stable>>['actOnActivePreview'])
|
||||
}
|
||||
|
||||
const str = (v: unknown): string => (typeof v === 'string' ? v : '')
|
||||
const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined)
|
||||
|
||||
/** Answer a string-valued request with a JSON-encoded result ('' = nothing / unavailable). */
|
||||
const answerValue = (request: ScopedServerRequest, result: unknown) =>
|
||||
request.respond({ value: result ? JSON.stringify(result) : '' })
|
||||
|
||||
export interface ServerRequestContext {
|
||||
deps: Pick<GatewayEventDeps, 'activeSessionIdRef' | 'sessionInterrupted' | 'updateSessionState' | 'upsertToolCall'>
|
||||
request: ScopedServerRequest
|
||||
/** The session the request names ('' when unscoped). */
|
||||
sessionId: string
|
||||
/** The named session is the one on screen. */
|
||||
isActiveSession: boolean
|
||||
}
|
||||
|
||||
type Handler = (ctx: ServerRequestContext) => void
|
||||
|
||||
const markNeedsInput = (ctx: ServerRequestContext) => {
|
||||
if (ctx.sessionId) {
|
||||
ctx.deps.updateSessionState(ctx.sessionId, state => ({ ...state, needsInput: true }))
|
||||
}
|
||||
}
|
||||
|
||||
const notifyInput = (ctx: ServerRequestContext, body: string) => {
|
||||
if (!ctx.request.replayed) {
|
||||
dispatchNativeNotification({
|
||||
body,
|
||||
kind: 'input',
|
||||
sessionId: ctx.sessionId || null,
|
||||
title: translateNow('notifications.native.inputTitle')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Blocking-input family (clarify / approval / sudo / secret / vault / MCP setup) ──
|
||||
// Every one is parked per-session (like clarify) so a BACKGROUND session's turn can
|
||||
// raise it and wait — the sidebar flags "needs input" and the card surfaces once the
|
||||
// user focuses that chat. The Python side blocks on the response frame; without a
|
||||
// handler the channel answers -32601 and the tool fails fast instead of stalling.
|
||||
|
||||
const clarify: Handler = ctx => {
|
||||
const { deps, request, sessionId } = ctx
|
||||
const p = request.params
|
||||
|
||||
if (sessionId && deps.sessionInterrupted(sessionId)) {
|
||||
request.respond({ answer: '' })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const question = str(p.question)
|
||||
const rawChoices = p.choices
|
||||
const choices = normalizeChoices(rawChoices)
|
||||
const multiSelect = p.multi_select === true
|
||||
// Batch (multi-question) clarify: `questions` replaces question/choices on the
|
||||
// wire. `answers` rides along only on a reconnect replay (locks the server
|
||||
// already accepted).
|
||||
const questions = normalizeQuestions(p.questions)
|
||||
|
||||
const lockedAnswers =
|
||||
typeof p.answers === 'object' && p.answers !== null
|
||||
? Object.fromEntries(
|
||||
Object.entries(p.answers as Record<string, unknown>).filter(
|
||||
(entry): entry is [string, string] => typeof entry[1] === 'string'
|
||||
)
|
||||
)
|
||||
: undefined
|
||||
|
||||
if (questions.length === 0 && !question) {
|
||||
request.respond({ answer: '' })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (questions.length === 0 && rawChoices != null && choices.length === 0) {
|
||||
warnDroppedChoices('gateway', question, rawChoices)
|
||||
}
|
||||
|
||||
const clarifyRequest =
|
||||
questions.length > 0
|
||||
? {
|
||||
choices: null,
|
||||
lockedAnswers,
|
||||
multiSelect: false,
|
||||
question: '',
|
||||
questions,
|
||||
receivedAt: Date.now() / 1000,
|
||||
requestId: request.id,
|
||||
sessionId: sessionId || null
|
||||
}
|
||||
: {
|
||||
choices: choices.length > 0 ? choices : null,
|
||||
multiSelect,
|
||||
question,
|
||||
receivedAt: Date.now() / 1000,
|
||||
requestId: request.id,
|
||||
sessionId: sessionId || null
|
||||
}
|
||||
|
||||
rememberServerRequest(request)
|
||||
setClarifyRequest(clarifyRequest)
|
||||
|
||||
if (sessionId) {
|
||||
// A resumed/hydrated transcript may already contain this provider's clarify
|
||||
// call while carrying no live streamId. Re-arm that exact row instead of
|
||||
// letting the generic stream mutator append a second card.
|
||||
const occurredAt = Date.now() / 1000
|
||||
|
||||
deps.updateSessionState(sessionId, state => {
|
||||
const projection = restorePendingClarifyToolCall(
|
||||
state.messages,
|
||||
pendingClarifyToolPayload(clarifyRequest),
|
||||
occurredAt
|
||||
)
|
||||
|
||||
return {
|
||||
...state,
|
||||
messages: projection.messages,
|
||||
streamId: projection.streamId,
|
||||
sawAssistantPayload: true,
|
||||
awaitingResponse: false,
|
||||
needsInput: true
|
||||
}
|
||||
})
|
||||
|
||||
if (sessionId === deps.activeSessionIdRef.current) {
|
||||
requestScrollToBottom(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
notifyInput(ctx, questions.length > 0 ? questions.map(q => q.question).join(' · ') : question)
|
||||
}
|
||||
|
||||
const approval: Handler = ctx => {
|
||||
const { request, sessionId } = ctx
|
||||
const p = request.params
|
||||
const command = str(p.command)
|
||||
const description = str(p.description) || 'dangerous command'
|
||||
|
||||
rememberServerRequest(request)
|
||||
void receiveApprovalRequest(null, {
|
||||
// false only when a tirith warning forbids it; backend omits the field otherwise.
|
||||
allowPermanent: p.allow_permanent !== false,
|
||||
choices: Array.isArray(p.choices) ? p.choices.filter((choice): choice is string => typeof choice === 'string') : undefined,
|
||||
command,
|
||||
description,
|
||||
// The approval queue's own id — `approval.pending` / `approval.received` / `approval.respond` key on it.
|
||||
requestId: str(p.request_id) || undefined,
|
||||
serverRequestId: request.id,
|
||||
sessionId: sessionId || null,
|
||||
smartDenied: p.smart_denied === true
|
||||
}).catch(() => undefined)
|
||||
markNeedsInput(ctx)
|
||||
|
||||
if (!request.replayed) {
|
||||
dispatchNativeNotification({
|
||||
actions: [
|
||||
{ id: 'approve', text: translateNow('notifications.native.approveAction') },
|
||||
{ id: 'reject', text: translateNow('notifications.native.rejectAction') }
|
||||
],
|
||||
body: command || description,
|
||||
kind: 'approval',
|
||||
sessionId: sessionId || null,
|
||||
title: translateNow('notifications.native.approvalTitle')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const sudo: Handler = ctx => {
|
||||
rememberServerRequest(ctx.request)
|
||||
setSudoRequest({ requestId: ctx.request.id, sessionId: ctx.sessionId || null })
|
||||
markNeedsInput(ctx)
|
||||
notifyInput(ctx, translateNow('notifications.native.inputBody'))
|
||||
}
|
||||
|
||||
/** Bot Screen package install (`tui_gateway/methods_display.py`): the same masked card as `sudo`,
|
||||
* but app-level. The gateway sends it sessionless — it belongs to the connection that clicked
|
||||
* Install, not to a chat — so it is stored under the null session and survives a chat switch. */
|
||||
const displayInstallSudo: Handler = ctx => {
|
||||
rememberServerRequest(ctx.request)
|
||||
setSudoRequest({
|
||||
description: translateNow('prompts.sudoInstallDesc'),
|
||||
requestId: ctx.request.id,
|
||||
sessionId: null
|
||||
})
|
||||
notifyInput(ctx, translateNow('prompts.sudoInstallDesc'))
|
||||
}
|
||||
|
||||
const secret: Handler = ctx => {
|
||||
const p = ctx.request.params
|
||||
const envVar = str(p.env_var)
|
||||
const promptText = str(p.prompt)
|
||||
|
||||
rememberServerRequest(ctx.request)
|
||||
setSecretRequest({ envVar, prompt: promptText, requestId: ctx.request.id, sessionId: ctx.sessionId || null })
|
||||
markNeedsInput(ctx)
|
||||
notifyInput(ctx, promptText || envVar || translateNow('notifications.native.inputBody'))
|
||||
}
|
||||
|
||||
const vaultCode: Handler = ctx => {
|
||||
const p = ctx.request.params
|
||||
const site = str(p.site)
|
||||
|
||||
rememberServerRequest(ctx.request)
|
||||
setVaultCodeRequest({ hint: str(p.hint), requestId: ctx.request.id, sessionId: ctx.sessionId || null, site })
|
||||
markNeedsInput(ctx)
|
||||
notifyInput(ctx, translateNow('prompts.vaultCodeTitle', site))
|
||||
}
|
||||
|
||||
const vaultSaveLogin: Handler = ctx => {
|
||||
const p = ctx.request.params
|
||||
const origin = str(p.origin)
|
||||
const site = str(p.site) || origin
|
||||
|
||||
rememberServerRequest(ctx.request)
|
||||
setVaultSaveLoginRequest({ origin, requestId: ctx.request.id, sessionId: ctx.sessionId || null, site })
|
||||
markNeedsInput(ctx)
|
||||
notifyInput(ctx, translateNow('prompts.vaultSaveTitle', site))
|
||||
}
|
||||
|
||||
const vaultUnlockPrompt: Handler = ctx => {
|
||||
const p = ctx.request.params
|
||||
const backend = str(p.backend)
|
||||
const displayName = str(p.display_name) || backend
|
||||
|
||||
rememberServerRequest(ctx.request)
|
||||
setVaultUnlockRequest({ backend, displayName, requestId: ctx.request.id, sessionId: ctx.sessionId || null })
|
||||
markNeedsInput(ctx)
|
||||
notifyInput(ctx, translateNow('prompts.vaultUnlockTitle', displayName))
|
||||
}
|
||||
|
||||
// ── Desktop-surface bridges (answered immediately, no card) ─────────────────
|
||||
|
||||
const terminalRead: Handler = ({ request }) => {
|
||||
// read_terminal tool: serialize the renderer's xterm buffer. Empty = no live pane.
|
||||
answerValue(request, readActiveTerminal({ count: num(request.params.count), start: num(request.params.start) }))
|
||||
}
|
||||
|
||||
const previewRead: Handler = ({ request }) => {
|
||||
// read_preview tool: the active preview tab's page text is async. Empty = nothing open.
|
||||
void readActivePreview({ count: num(request.params.count), start: num(request.params.start) }).then(result =>
|
||||
answerValue(request, result)
|
||||
)
|
||||
}
|
||||
|
||||
const previewAct: Handler = ({ isActiveSession, request, sessionId }) => {
|
||||
// drive_preview tool: click/type/scroll/press inside the guest page. Active
|
||||
// session only: a background turn must never reach into the page the user is
|
||||
// working in (desktop AGENTS.md: offer, don't hijack). Every mounted window can
|
||||
// observe the same request; a scoped mismatch belongs to another window, so
|
||||
// answering here would race the owner — stay silent.
|
||||
if (sessionId && !isActiveSession) {
|
||||
return
|
||||
}
|
||||
|
||||
const p = request.params
|
||||
|
||||
if (!isActiveSession) {
|
||||
answerValue(request, {
|
||||
error: 'The in-app browser only takes actions in the session the user is looking at.',
|
||||
success: false
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
void loadPreviewEngine()
|
||||
.then(run =>
|
||||
run({
|
||||
amount: p.amount as never,
|
||||
key: p.key as never,
|
||||
kind: (str(p.action) || '') as never,
|
||||
max: p.max as never,
|
||||
ref: p.ref as never,
|
||||
selector: p.selector as never,
|
||||
submit: p.submit as never,
|
||||
text: p.text as never,
|
||||
to: p.to as PreviewActAction['to']
|
||||
})
|
||||
)
|
||||
.then(
|
||||
result => answerValue(request, result),
|
||||
error => answerValue(request, { error: error instanceof Error ? error.message : String(error), success: false })
|
||||
)
|
||||
}
|
||||
|
||||
const windowRead: Handler = ({ request }) => {
|
||||
// read_window_below tool: main owns native window enumeration. Empty =
|
||||
// unavailable (older shell without the handler, Wayland, …) — without an
|
||||
// answer the tool would stall its full 30s deadline.
|
||||
const read = window.hermesDesktop?.readWindowBelow
|
||||
|
||||
void Promise.resolve(read ? read() : null).then(
|
||||
result => answerValue(request, result),
|
||||
() => answerValue(request, null)
|
||||
)
|
||||
}
|
||||
|
||||
const tour: Handler = ({ isActiveSession, request, sessionId }) => {
|
||||
// tour tool: one guided-tour action via driver.js, app DOM or preview guest
|
||||
// page. Active session only, same window-ownership rule as preview.act.
|
||||
if (sessionId && !isActiveSession) {
|
||||
return
|
||||
}
|
||||
|
||||
const p = request.params
|
||||
|
||||
if (!$toursEnabled.get()) {
|
||||
// Refused in words, not silently dropped: a no-op would leave the agent
|
||||
// narrating a spotlight the user can't see.
|
||||
answerValue(request, { error: 'The user has turned guided tours off.', success: false })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (!isActiveSession) {
|
||||
answerValue(request, { error: 'Tours only run in the session the user is looking at.', success: false })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
void import('@/lib/tour')
|
||||
.then(({ runTour }) =>
|
||||
runTour(
|
||||
{
|
||||
kind: (str(p.action) || 'stop') as TourAction['kind'],
|
||||
selector: p.selector as never,
|
||||
side: p.side as TourStep['side'],
|
||||
startAt: p.step_index as never,
|
||||
steps: p.steps as TourStep[] | undefined,
|
||||
text: p.text as never,
|
||||
title: p.title as never
|
||||
},
|
||||
p.surface === 'preview' ? 'preview' : 'app'
|
||||
)
|
||||
)
|
||||
.then(
|
||||
result => answerValue(request, result),
|
||||
error => answerValue(request, { error: error instanceof Error ? error.message : String(error), success: false })
|
||||
)
|
||||
}
|
||||
|
||||
/** Method → handler. Every `ServerRequestMap` key the desktop answers. */
|
||||
export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {
|
||||
approval,
|
||||
clarify,
|
||||
'display.install.sudo': displayInstallSudo,
|
||||
'preview.act': previewAct,
|
||||
'preview.read': previewRead,
|
||||
secret,
|
||||
sudo,
|
||||
'terminal.read': terminalRead,
|
||||
tour,
|
||||
'vault.code': vaultCode,
|
||||
'vault.save_login': vaultSaveLogin,
|
||||
'vault.unlock_prompt': vaultUnlockPrompt,
|
||||
'window.read': windowRead
|
||||
}
|
||||
|
||||
/** Dispatch one server→client request; false when the desktop has no handler for its method. */
|
||||
export function handleServerRequest(
|
||||
request: ScopedServerRequest,
|
||||
deps: ServerRequestContext['deps'],
|
||||
activeSessionId: null | string
|
||||
): boolean {
|
||||
const handler = SERVER_REQUEST_HANDLERS[request.method]
|
||||
|
||||
if (!handler) {
|
||||
return false
|
||||
}
|
||||
|
||||
const sessionId = str(request.params.session_id)
|
||||
|
||||
handler({ deps, request, sessionId, isActiveSession: Boolean(sessionId) && sessionId === activeSessionId })
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
stripGeneratedImageEchoes
|
||||
} from '@/lib/generated-images'
|
||||
import { isTodoToolName, nextTodosFromToolEvent, parseTodoRevision } from '@/lib/todos'
|
||||
import type { ScopedServerRequest } from '@/store/gateway'
|
||||
import { dispatchNativeNotification } from '@/store/native-notifications'
|
||||
import { isDiskFullErrorMessage, notifyError } from '@/store/notifications'
|
||||
import { broadcastSessionsChanged } from '@/store/session-sync'
|
||||
@@ -33,6 +34,7 @@ import { $todosBySession, setSessionTodos } from '@/store/todos'
|
||||
import type { ClientSessionState } from '../../../types'
|
||||
|
||||
import { useGatewayEventHandler } from './gateway-event'
|
||||
import { handleServerRequest as dispatchServerRequest } from './gateway-event/server-requests'
|
||||
import { completionErrorText, delegateTaskPayloads, MAX_STREAM_FLUSH_GAP_MS, STREAM_DELTA_FLUSH_MS } from './utils'
|
||||
|
||||
interface MessageStreamOptions {
|
||||
@@ -880,11 +882,25 @@ export function useMessageStream({
|
||||
upsertToolCall
|
||||
})
|
||||
|
||||
// Server→client requests (clarify, approval, sudo, …) from every socket the
|
||||
// registry owns. The request answers itself over the socket it arrived on,
|
||||
// so no owner routing is involved here — only which card to show.
|
||||
const handleServerRequest = useCallback(
|
||||
(request: ScopedServerRequest): boolean =>
|
||||
dispatchServerRequest(
|
||||
request,
|
||||
{ activeSessionIdRef, sessionInterrupted, updateSessionState, upsertToolCall },
|
||||
activeSessionIdRef.current
|
||||
),
|
||||
[activeSessionIdRef, sessionInterrupted, updateSessionState, upsertToolCall]
|
||||
)
|
||||
|
||||
return {
|
||||
appendAssistantDelta,
|
||||
appendReasoningDelta,
|
||||
completeAssistantMessage,
|
||||
handleGatewayEvent,
|
||||
handleServerRequest,
|
||||
finalizeInterimAssistantMessage,
|
||||
upsertToolCall
|
||||
}
|
||||
|
||||
@@ -319,7 +319,9 @@ describe('useMessageStream interim text sealing', () => {
|
||||
// No payload at all
|
||||
await act(() => stream.handleEvent({ type: 'message.interim' } as GatewayEvent))
|
||||
// Empty text
|
||||
await act(() => stream.handleEvent({ payload: { text: '' }, session_id: SID, type: 'message.interim' } as GatewayEvent))
|
||||
await act(() =>
|
||||
stream.handleEvent({ payload: { text: '' }, session_id: SID, type: 'message.interim' } as GatewayEvent)
|
||||
)
|
||||
// Undefined text
|
||||
await act(() =>
|
||||
stream.handleEvent({ payload: { text: undefined }, session_id: SID, type: 'message.interim' } as GatewayEvent)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { vi } from 'vitest'
|
||||
|
||||
import type { ClientSessionState } from '@/app/types'
|
||||
import { createClientSessionState } from '@/lib/chat-runtime'
|
||||
import type { ScopedServerRequest } from '@/store/gateway'
|
||||
|
||||
import { useMessageStream } from './index'
|
||||
|
||||
@@ -17,6 +18,9 @@ export interface MessageStreamHarnessOptions extends Partial<Parameters<typeof u
|
||||
export interface MessageStreamHarness {
|
||||
/** Feed a gateway event into the mounted hook. */
|
||||
handleEvent: (event: GatewayEvent) => void
|
||||
/** Feed a server→client request (clarify, approval, …) into the mounted hook;
|
||||
* returns the `respond` spy so a test can assert the answer frame. */
|
||||
handleRequest: (method: string, params: Record<string, unknown>, id?: string) => ReturnType<typeof vi.fn>
|
||||
/** Push streaming assistant text, bypassing the event envelope. For the specs
|
||||
* about flush scheduling rather than about a particular event. */
|
||||
appendDelta: (sessionId: string, delta: string) => void
|
||||
@@ -48,6 +52,7 @@ export function renderMessageStream(
|
||||
{ states = new Map<string, ClientSessionState>(), ...overrides }: MessageStreamHarnessOptions = {}
|
||||
): MessageStreamHarness {
|
||||
let dispatch: ((event: GatewayEvent) => void) | null = null
|
||||
let dispatchRequest: ((request: ScopedServerRequest) => boolean) | null = null
|
||||
let appendDelta: ((sessionId: string, delta: string) => void) | null = null
|
||||
let latest: ClientSessionState | null = null
|
||||
|
||||
@@ -75,8 +80,9 @@ export function renderMessageStream(
|
||||
|
||||
useEffect(() => {
|
||||
dispatch = stream.handleGatewayEvent
|
||||
dispatchRequest = stream.handleServerRequest
|
||||
appendDelta = stream.appendAssistantDelta
|
||||
}, [stream.appendAssistantDelta, stream.handleGatewayEvent])
|
||||
}, [stream.appendAssistantDelta, stream.handleGatewayEvent, stream.handleServerRequest])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -93,6 +99,17 @@ export function renderMessageStream(
|
||||
|
||||
dispatch(event)
|
||||
},
|
||||
handleRequest: (method, params, id = `srq-${method}`) => {
|
||||
const respond = vi.fn()
|
||||
|
||||
if (!dispatchRequest) {
|
||||
throw new Error('renderMessageStream: the hook never mounted')
|
||||
}
|
||||
|
||||
dispatchRequest({ fail: vi.fn(), id, method, params, profile: 'default', respond })
|
||||
|
||||
return respond
|
||||
},
|
||||
appendDelta: (id, delta) => {
|
||||
if (!appendDelta) {
|
||||
throw new Error('renderMessageStream: the hook never mounted')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ModelOptionsResponse } from '@hermes/shared'
|
||||
import type { ModelOptionsResult } from '@hermes/shared'
|
||||
import { type QueryClient } from '@tanstack/react-query'
|
||||
import { useCallback, useRef } from 'react'
|
||||
|
||||
@@ -60,7 +60,7 @@ export function useModelControls({
|
||||
profile = cacheProfile || $activeGatewayProfile.get(),
|
||||
ownerConnectionId = cacheOwnerConnectionId
|
||||
) => {
|
||||
const patch = (prev: ModelOptionsResponse | undefined) => {
|
||||
const patch = (prev: ModelOptionsResult | undefined) => {
|
||||
// Selection state can update before the catalog query has resolved.
|
||||
// Keep that optimistic cache structurally complete; the composer
|
||||
// interprets a response without `providers` as an empty catalog.
|
||||
@@ -73,10 +73,10 @@ export function useModelControls({
|
||||
return { ...prev, provider, model, providers }
|
||||
}
|
||||
|
||||
queryClient.setQueryData<ModelOptionsResponse>(modelOptionsQueryKey(profile, sessionId, ownerConnectionId), patch)
|
||||
queryClient.setQueryData<ModelOptionsResult>(modelOptionsQueryKey(profile, sessionId, ownerConnectionId), patch)
|
||||
|
||||
if (includeGlobal) {
|
||||
queryClient.setQueryData<ModelOptionsResponse>(modelOptionsQueryKey(profile, null, ownerConnectionId), patch)
|
||||
queryClient.setQueryData<ModelOptionsResult>(modelOptionsQueryKey(profile, null, ownerConnectionId), patch)
|
||||
}
|
||||
},
|
||||
[cacheOwnerConnectionId, cacheProfile, queryClient]
|
||||
@@ -110,63 +110,60 @@ export function useModelControls({
|
||||
// only fills an EMPTY selection so a user's pick (plain UI state in
|
||||
// $currentModel) survives the lifecycle refreshes that fire on boot / fresh
|
||||
// draft / session events. A live session owns the footer, so skip entirely.
|
||||
const refreshCurrentModel = useCallback(
|
||||
async (force = false) => {
|
||||
// A forced profile swap opens a new intent epoch; an older in-flight
|
||||
// response for a previous profile must stand down when it resolves.
|
||||
if (force) {
|
||||
profileRefreshEpochRef.current += 1
|
||||
const refreshCurrentModel = useCallback(async (force = false) => {
|
||||
// A forced profile swap opens a new intent epoch; an older in-flight
|
||||
// response for a previous profile must stand down when it resolves.
|
||||
if (force) {
|
||||
profileRefreshEpochRef.current += 1
|
||||
}
|
||||
|
||||
const profileRefreshEpoch = profileRefreshEpochRef.current
|
||||
const profile = $activeGatewayProfile.get()
|
||||
|
||||
try {
|
||||
if ($activeSessionId.get()) {
|
||||
return
|
||||
}
|
||||
|
||||
const profileRefreshEpoch = profileRefreshEpochRef.current
|
||||
const profile = $activeGatewayProfile.get()
|
||||
// A manual pick is sticky. It is never diffed against the catalog: rows
|
||||
// are hints, and a custom slug the row lacks is still the user's choice
|
||||
// (the gateway validates it on switch).
|
||||
const keepManualPick = () => !force && Boolean($currentModel.get()) && getCurrentModelSource() === 'manual'
|
||||
|
||||
try {
|
||||
if ($activeSessionId.get()) {
|
||||
return
|
||||
}
|
||||
|
||||
// A manual pick is sticky. It is never diffed against the catalog: rows
|
||||
// are hints, and a custom slug the row lacks is still the user's choice
|
||||
// (the gateway validates it on switch).
|
||||
const keepManualPick = () => !force && Boolean($currentModel.get()) && getCurrentModelSource() === 'manual'
|
||||
|
||||
if (keepManualPick()) {
|
||||
return
|
||||
}
|
||||
|
||||
// Snapshot the selection generation before awaiting so a picker click
|
||||
// that lands while getGlobalModelInfo is in flight wins over this older
|
||||
// default — value comparisons alone miss re-selecting the same row.
|
||||
const selectionGeneration = getComposerSelectionGeneration()
|
||||
const result = await getGlobalModelInfo(profile)
|
||||
|
||||
if (
|
||||
profileRefreshEpochRef.current !== profileRefreshEpoch ||
|
||||
$activeSessionId.get() ||
|
||||
getComposerSelectionGeneration() !== selectionGeneration ||
|
||||
keepManualPick()
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof result.model === 'string') {
|
||||
setCurrentModel(result.model)
|
||||
}
|
||||
|
||||
if (typeof result.provider === 'string') {
|
||||
setCurrentProvider(result.provider)
|
||||
}
|
||||
|
||||
if (typeof result.model === 'string' || typeof result.provider === 'string') {
|
||||
setCurrentModelSource('default')
|
||||
}
|
||||
} catch {
|
||||
// The delayed session.info event still updates this once the agent is ready.
|
||||
if (keepManualPick()) {
|
||||
return
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// Snapshot the selection generation before awaiting so a picker click
|
||||
// that lands while getGlobalModelInfo is in flight wins over this older
|
||||
// default — value comparisons alone miss re-selecting the same row.
|
||||
const selectionGeneration = getComposerSelectionGeneration()
|
||||
const result = await getGlobalModelInfo(profile)
|
||||
|
||||
if (
|
||||
profileRefreshEpochRef.current !== profileRefreshEpoch ||
|
||||
$activeSessionId.get() ||
|
||||
getComposerSelectionGeneration() !== selectionGeneration ||
|
||||
keepManualPick()
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof result.model === 'string') {
|
||||
setCurrentModel(result.model)
|
||||
}
|
||||
|
||||
if (typeof result.provider === 'string') {
|
||||
setCurrentProvider(result.provider)
|
||||
}
|
||||
|
||||
if (typeof result.model === 'string' || typeof result.provider === 'string') {
|
||||
setCurrentModelSource('default')
|
||||
}
|
||||
} catch {
|
||||
// The delayed session.info event still updates this once the agent is ready.
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Returns whether the switch was applied so callers can await it before
|
||||
// applying follow-up changes. `true` means applied (or deferred/busy-queued
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
|
||||
import { JsonRpcGatewayError } from '@hermes/shared'
|
||||
import { SLASH_COMMAND_RE } from '@hermes/shared'
|
||||
import { stripAnsi } from '@hermes/shared/ansi'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
|
||||
|
||||
import { transcribeAudio } from '@/hermes'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { stripAnsi } from '@/lib/ansi'
|
||||
import { type ChatMessage, textPart } from '@/lib/chat-messages'
|
||||
import { pathLabel, SLASH_COMMAND_RE } from '@/lib/chat-runtime'
|
||||
import { pathLabel } from '@/lib/chat-runtime'
|
||||
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
|
||||
import { triggerHaptic } from '@/lib/haptics'
|
||||
import { setMutableRef } from '@/lib/mutable-ref'
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { skillInvocationText } from '@hermes/shared'
|
||||
import { parseCommandDispatch, parseSlashCommand } from '@hermes/shared'
|
||||
import { type MutableRefObject, useCallback, useRef } from 'react'
|
||||
|
||||
import { getProfiles } from '@/hermes'
|
||||
import type { Translations } from '@/i18n'
|
||||
import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'
|
||||
import { parseCommandDispatch, parseSlashCommand, sessionTitle } from '@/lib/chat-runtime'
|
||||
import { sessionTitle } from '@/lib/chat-runtime'
|
||||
import {
|
||||
type CommandsCatalogLike,
|
||||
type DesktopActionId,
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
getSession,
|
||||
type ProfileScope,
|
||||
type SessionInfo,
|
||||
type SessionResumeResponse,
|
||||
type SessionResumeResult,
|
||||
setSessionArchived
|
||||
} from '@/hermes'
|
||||
import { createClientSessionState } from '@/lib/chat-runtime'
|
||||
@@ -42,8 +42,10 @@ import {
|
||||
$selectedStoredSessionId,
|
||||
$sessions,
|
||||
$turnStartedAt,
|
||||
_resetSessionOwnerHintsForTests,
|
||||
getSessionOwnerHint,
|
||||
knownSessionOwner,
|
||||
ownerLookupSessionRows,
|
||||
sessionMatchesStoredId,
|
||||
setActiveSessionId,
|
||||
setActiveSessionStoredIdRotation,
|
||||
@@ -63,11 +65,18 @@ import {
|
||||
setResumeFailedSessionId,
|
||||
setSelectedStoredSessionId,
|
||||
setSessions,
|
||||
setTurnStartedAt
|
||||
setTurnStartedAt,
|
||||
setUnlistedSessionOwnerRows
|
||||
} from '@/store/session'
|
||||
import { assertSessionOwnerResolved } from '@/store/session-owner-resolution'
|
||||
import { $removedSessionIds, $sessionMutationsInFlight } from '@/store/session-removal'
|
||||
import { requestForSessionProfile, type SessionProfileRoute } from '@/store/session-request-router'
|
||||
import { $sessionTiles, sessionTileOwnerRoute } from '@/store/session-states'
|
||||
import {
|
||||
$sessionTiles,
|
||||
knownOwnerForSession,
|
||||
requestForOwnedSession,
|
||||
sessionTileOwnerRoute
|
||||
} from '@/store/session-states'
|
||||
import { $sessionSeenCounts, $unreadFinishedMarkers } from '@/store/session-unread'
|
||||
|
||||
import sessionResumeActiveTurn from '../../../../../../tests/fixtures/session-resume-active-turn.json'
|
||||
@@ -1127,16 +1136,26 @@ describe('resumeSession failure recovery', () => {
|
||||
|
||||
const requestGateway = vi.fn(async (method: string) => {
|
||||
if (method === 'session.resume') {
|
||||
// The channel re-delivers `open_requests` to the request handler BEFORE
|
||||
// the caller sees the result; that handler parks the card. Mirror that
|
||||
// ordering here (no channel in this harness).
|
||||
setClarifyRequest({
|
||||
choices: ['safe', 'fast'],
|
||||
multiSelect: false,
|
||||
question: 'Which path?',
|
||||
receivedAt: Date.now(),
|
||||
requestId: 'req-resumed',
|
||||
sessionId: 'runtime-1'
|
||||
})
|
||||
|
||||
return {
|
||||
info: {},
|
||||
message_count: 2,
|
||||
messages: [],
|
||||
messages_omitted: true,
|
||||
pending_clarify: {
|
||||
choices: ['safe', 'fast'],
|
||||
question: 'Which path?',
|
||||
request_id: 'req-resumed'
|
||||
},
|
||||
open_requests: [
|
||||
{ id: 'req-resumed', method: 'clarify', params: { choices: ['safe', 'fast'], question: 'Which path?' } }
|
||||
],
|
||||
resumed: 'stored-1',
|
||||
running: true,
|
||||
session_id: 'runtime-1',
|
||||
@@ -1187,21 +1206,34 @@ describe('resumeSession failure recovery', () => {
|
||||
session_id: 'stored-1'
|
||||
} as never)
|
||||
|
||||
const questions = [
|
||||
{ choices: ['Blue', 'Red'], qid: 'q0', question: 'Color?' },
|
||||
{ choices: ['Small', 'Large'], qid: 'q1', question: 'Size?' }
|
||||
]
|
||||
|
||||
const requestGateway = vi.fn(async (method: string) => {
|
||||
if (method === 'session.resume') {
|
||||
// Request handler parks the batch card (with the server-locked answer)
|
||||
// from the re-delivered open request before the result lands.
|
||||
setClarifyRequest({
|
||||
choices: null,
|
||||
lockedAnswers: { q0: 'Blue' },
|
||||
multiSelect: false,
|
||||
question: '',
|
||||
questions: questions.map(q => ({ ...q, multiSelect: false })),
|
||||
receivedAt: Date.now(),
|
||||
requestId: 'req-batch-resumed',
|
||||
sessionId: 'runtime-1'
|
||||
})
|
||||
|
||||
return {
|
||||
info: {},
|
||||
message_count: 2,
|
||||
messages: [],
|
||||
messages_omitted: true,
|
||||
pending_clarify: {
|
||||
answers: { q0: 'Blue' },
|
||||
questions: [
|
||||
{ choices: ['Blue', 'Red'], qid: 'q0', question: 'Color?' },
|
||||
{ choices: ['Small', 'Large'], qid: 'q1', question: 'Size?' }
|
||||
],
|
||||
request_id: 'req-batch-resumed'
|
||||
},
|
||||
open_requests: [
|
||||
{ id: 'req-batch-resumed', method: 'clarify', params: { answers: { q0: 'Blue' }, questions } }
|
||||
],
|
||||
resumed: 'stored-1',
|
||||
running: true,
|
||||
session_id: 'runtime-1',
|
||||
@@ -2742,7 +2774,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
|
||||
session_id: 'stored-A'
|
||||
})
|
||||
|
||||
const deferredResume = deferred<SessionResumeResponse>()
|
||||
const deferredResume = deferred<SessionResumeResult>()
|
||||
|
||||
const requestGatewayMock = vi.fn((method: string, _params?: Record<string, unknown>) => {
|
||||
if (method === 'session.resume') {
|
||||
@@ -2891,16 +2923,23 @@ describe('resumeSession warm-cache mapping integrity', () => {
|
||||
|
||||
const requestGateway = vi.fn(async (method: string) => {
|
||||
if (method === 'session.activate') {
|
||||
setClarifyRequest({
|
||||
choices: ['safe', 'fast'],
|
||||
multiSelect: false,
|
||||
question: 'Which path?',
|
||||
receivedAt: Date.now(),
|
||||
requestId: 'req-warm',
|
||||
sessionId: 'rt-A'
|
||||
})
|
||||
|
||||
return {
|
||||
info: {},
|
||||
message_count: 2,
|
||||
messages: [],
|
||||
messages_omitted: true,
|
||||
pending_clarify: {
|
||||
choices: ['safe', 'fast'],
|
||||
question: 'Which path?',
|
||||
request_id: 'req-warm'
|
||||
},
|
||||
open_requests: [
|
||||
{ id: 'req-warm', method: 'clarify', params: { choices: ['safe', 'fast'], question: 'Which path?' } }
|
||||
],
|
||||
resumed: 'stored-A',
|
||||
running: true,
|
||||
session_id: 'rt-A',
|
||||
@@ -3055,7 +3094,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
|
||||
current: new Map([['rt-A', clientState('stored-A')]])
|
||||
}
|
||||
|
||||
const activated = deferred<SessionResumeResponse>()
|
||||
const activated = deferred<SessionResumeResult>()
|
||||
|
||||
const requestGateway = vi.fn((method: string) =>
|
||||
method === 'session.activate' ? activated.promise : Promise.resolve({})
|
||||
@@ -4096,8 +4135,14 @@ describe('createBackendSessionForSend workspace target', () => {
|
||||
describe('openNewSessionTile workspace target', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
$profiles.set([])
|
||||
$newChatProfile.set(null)
|
||||
$activeGatewayProfile.set('default')
|
||||
$projectScope.set(ALL_PROJECTS)
|
||||
$projectTree.set([])
|
||||
$sessionTiles.set([])
|
||||
setConnection(null)
|
||||
setSessions([])
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
@@ -4139,6 +4184,201 @@ describe('openNewSessionTile workspace target', () => {
|
||||
|
||||
expect(createParams).not.toHaveProperty('cwd')
|
||||
})
|
||||
|
||||
it('keeps an unlisted named local legacy-profile tile owned by its bare profile', async () => {
|
||||
const storedSessionId = 'stored-unlisted-omar'
|
||||
$profiles.set([{ name: 'default' }, { name: 'omar' }] as never)
|
||||
setConnection({ mode: 'local' } as never)
|
||||
|
||||
const requestGateway = vi.fn(async (method: string) => {
|
||||
if (method === 'session.create') {
|
||||
return {
|
||||
info: { cwd: '', model: 'test-model', tools: {}, skills: {} },
|
||||
session_id: RUNTIME_SESSION_ID,
|
||||
stored_session_id: storedSessionId
|
||||
} as never
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected ambient RPC: ${method}`)
|
||||
})
|
||||
|
||||
vi.mocked(requestGatewayForProfile).mockResolvedValue({ control: {} } as never)
|
||||
|
||||
let handle: HarnessHandle | null = null
|
||||
render(<Harness onReady={value => (handle = value)} requestGateway={requestGateway} />)
|
||||
await waitFor(() => expect(handle).not.toBeNull())
|
||||
|
||||
await act(async () => {
|
||||
await handle!.openNewSessionTile('center', { listed: false, profile: 'omar' })
|
||||
})
|
||||
|
||||
expect(requestGateway).toHaveBeenCalledWith('session.create', expect.any(Object))
|
||||
expect(vi.mocked(requestGatewayForAgent)).not.toHaveBeenCalled()
|
||||
expect($sessions.get().some(session => sessionMatchesStoredId(session, storedSessionId))).toBe(false)
|
||||
expect($sessionTiles.get()).toContainEqual(expect.objectContaining({ ownerProfile: 'omar', storedSessionId }))
|
||||
expect(knownOwnerForSession(storedSessionId)).toBe('omar')
|
||||
|
||||
await expect(
|
||||
requestForOwnedSession(storedSessionId, requestGateway, 'session.control.read', {
|
||||
session_id: RUNTIME_SESSION_ID
|
||||
})
|
||||
).resolves.toEqual({ control: {} })
|
||||
expect(requestGatewayForProfile).toHaveBeenCalledWith(
|
||||
'omar',
|
||||
'session.control.read',
|
||||
{ session_id: RUNTIME_SESSION_ID },
|
||||
undefined,
|
||||
undefined
|
||||
)
|
||||
})
|
||||
|
||||
it('records the draft profile owner when tab-strip create omits profile', async () => {
|
||||
const storedSessionId = 'stored-unlisted-draft-omar'
|
||||
$profiles.set([{ name: 'default' }, { name: 'omar' }] as never)
|
||||
$newChatProfile.set('omar')
|
||||
$activeGatewayProfile.set('default')
|
||||
setConnection({ mode: 'local' } as never)
|
||||
|
||||
const requestGateway = vi.fn(async (method: string) => {
|
||||
if (method === 'session.create') {
|
||||
return {
|
||||
info: { cwd: '', model: 'test-model', tools: {}, skills: {} },
|
||||
session_id: RUNTIME_SESSION_ID,
|
||||
stored_session_id: storedSessionId
|
||||
} as never
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected ambient RPC: ${method}`)
|
||||
})
|
||||
|
||||
vi.mocked(requestGatewayForProfile).mockResolvedValue({ control: {} } as never)
|
||||
|
||||
let handle: HarnessHandle | null = null
|
||||
render(<Harness onReady={value => (handle = value)} requestGateway={requestGateway} />)
|
||||
await waitFor(() => expect(handle).not.toBeNull())
|
||||
|
||||
await act(async () => {
|
||||
await handle!.openNewSessionTile('center', { listed: false })
|
||||
})
|
||||
|
||||
expect($sessionTiles.get()).toContainEqual(expect.objectContaining({ ownerProfile: 'omar', storedSessionId }))
|
||||
expect(knownOwnerForSession(storedSessionId)).toBe('omar')
|
||||
|
||||
await expect(
|
||||
requestForOwnedSession(storedSessionId, requestGateway, 'session.control.read', {
|
||||
session_id: RUNTIME_SESSION_ID
|
||||
})
|
||||
).resolves.toEqual({ control: {} })
|
||||
expect(requestGatewayForProfile).toHaveBeenCalledWith(
|
||||
'omar',
|
||||
'session.control.read',
|
||||
{ session_id: RUNTIME_SESSION_ID },
|
||||
undefined,
|
||||
undefined
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('openNewSessionTile unlisted owner (#102792)', () => {
|
||||
const STORED_UNLISTED = 'stored-unlisted-102792'
|
||||
|
||||
function createRequestGateway(stored: string = STORED_UNLISTED) {
|
||||
return vi.fn(async (method: string) => {
|
||||
if (method === 'session.create') {
|
||||
return {
|
||||
info: { cwd: '', model: 'test-model', skills: {}, tools: {} },
|
||||
session_id: RUNTIME_SESSION_ID,
|
||||
stored_session_id: stored
|
||||
} as never
|
||||
}
|
||||
|
||||
return {} as never
|
||||
})
|
||||
}
|
||||
|
||||
async function readyHandle(requestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>) {
|
||||
let handle: HarnessHandle | null = null
|
||||
render(<Harness onReady={value => (handle = value)} requestGateway={requestGateway} />)
|
||||
await waitFor(() => expect(handle).not.toBeNull())
|
||||
|
||||
return handle!
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setSessions([])
|
||||
setMessagingSessions([])
|
||||
setCronSessions([])
|
||||
setUnlistedSessionOwnerRows([])
|
||||
_resetSessionOwnerHintsForTests()
|
||||
$profiles.set(profiles('default', 'omar'))
|
||||
$activeGatewayProfile.set('omar')
|
||||
$sessionTiles.set([])
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
setSessions([])
|
||||
setMessagingSessions([])
|
||||
setCronSessions([])
|
||||
setUnlistedSessionOwnerRows([])
|
||||
_resetSessionOwnerHintsForTests()
|
||||
$profiles.set([])
|
||||
$activeGatewayProfile.set('default')
|
||||
$sessionTiles.set([])
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('records the ambient-profile owner for an unlisted tile created on the null (legacy ambient) route', async () => {
|
||||
const handle = await readyHandle(createRequestGateway())
|
||||
|
||||
await act(async () => {
|
||||
await handle.openNewSessionTile('center', { listed: false, route: null })
|
||||
})
|
||||
|
||||
// The draft stays out of the visible sidebar list ...
|
||||
expect($sessions.get().some(s => sessionMatchesStoredId(s, STORED_UNLISTED))).toBe(false)
|
||||
// ... but its owner still resolves on the row rung (bare ambient profile),
|
||||
// so the tile's immediate session.resume passes the fail-closed gate.
|
||||
const owner = knownSessionOwner(ownerLookupSessionRows(), STORED_UNLISTED)
|
||||
expect(owner).toBe('omar')
|
||||
expect(() =>
|
||||
assertSessionOwnerResolved(owner, { method: 'session.resume', sessionId: STORED_UNLISTED })
|
||||
).not.toThrow()
|
||||
expect($sessionTiles.get().some(t => t.storedSessionId === STORED_UNLISTED)).toBe(true)
|
||||
})
|
||||
|
||||
it('resolves the ephemeral runtime id through the stub for session.control.read without hitting ambient', async () => {
|
||||
const handle = await readyHandle(createRequestGateway())
|
||||
|
||||
await act(async () => {
|
||||
await handle.openNewSessionTile('center', { listed: false, route: null })
|
||||
})
|
||||
|
||||
// The composer banner calls with the ephemeral runtime id, not the stored
|
||||
// id — it must see the same bare ambient profile as the stored-id rung.
|
||||
expect(knownOwnerForSession(RUNTIME_SESSION_ID)).toBe('omar')
|
||||
|
||||
const ambient = vi.fn(async () => ({}) as never)
|
||||
vi.mocked(requestGatewayForProfile).mockResolvedValue({ control: {} } as never)
|
||||
|
||||
await expect(
|
||||
requestForOwnedSession(RUNTIME_SESSION_ID, ambient, 'session.control.read', {
|
||||
session_id: RUNTIME_SESSION_ID
|
||||
})
|
||||
).resolves.toEqual({ control: {} })
|
||||
|
||||
// Bare profile routes through the profile-pool door, never ambient ...
|
||||
expect(ambient).not.toHaveBeenCalled()
|
||||
expect(requestGatewayForProfile).toHaveBeenCalledWith(
|
||||
'omar',
|
||||
'session.control.read',
|
||||
expect.objectContaining({ session_id: RUNTIME_SESSION_ID }),
|
||||
undefined,
|
||||
undefined
|
||||
)
|
||||
// ... and the draft stays out of the sidebar.
|
||||
expect($sessions.get().some(s => sessionMatchesStoredId(s, STORED_UNLISTED))).toBe(false)
|
||||
})
|
||||
})
|
||||
describe('selectSidebarItem', () => {
|
||||
it('fronts the workspace pane when navigating to a sidebar route (issue #72602)', async () => {
|
||||
|
||||
Loaded 100 of 1787 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user