Skip to content

The agent that grows with you

merge: reconcile upstream main with pm audit closeout

ethernetce49cdbc592f
diff --cc apps/desktop/electron/preload.ts
index 28cc94cd5c5,ca8bb45a282..32d17e48dee
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@@ -15,8 -15,10 +15,8 @@@ const featureFlags = ipcRenderer.sendSy
contextBridge.exposeInMainWorld('hermesDesktop', {
glassSupported: translucencySupport?.glass === true,
translucencySupported: translucencySupport?.translucency === true,
- // Launch-flag fact: the app was started with --local, so the renderer may
- // show the local-models surfaces. Static for the window's lifetime.
- localModelsEnabled: launchFlags?.localModels === true,
+ localModelsEnabled: featureFlags?.localModels === true,
- getConnection: profile => ipcRenderer.invoke('hermes:connection', profile),
+ getConnection: (profile, opts) => ipcRenderer.invoke('hermes:connection', profile, opts),
// Registry-scoped backend resolution: { connectionId, profile } → descriptor.
getConnectionFor: payload => ipcRenderer.invoke('hermes:connection:for', payload),
getProfileRoutes: profiles => ipcRenderer.invoke('hermes:plugin-profile-routes', profiles),
diff --cc apps/desktop/src/i18n/ar.ts
index a162eae3f98,c0f108b2dc6..c3dcc9d1653
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@@ -1,13 -1,39 +1,46 @@@
import { defineLocale } from './define-locale'
export const ar = defineLocale({
+ externalOpenFailed: {
+ title: 'تعذّر فتح هذا الرابط',
+ message: 'لا يوجد متصفح مسجل لفتح هذا العنوان. انسخ الرابط وافتحه يدويًا.',
+ copyUrl: 'نسخ الرابط',
+ close: 'إغلاق'
+ },
+
+ sessionImport: {
+ title: 'المتابعة من تطبيق آخر',
+ subtitle: 'انقل محادثة إلى Hermes وتابع من حيث توقفت.',
+ action: 'استيراد جلسة',
+ readingFrom: 'القراءة من',
+ connectedComputer: 'الكمبيوتر المتصل',
+ destination: 'الاستيراد إلى',
+ all: 'الكل',
+ search: 'البحث في الجلسات المحملة',
+ scanning: 'جارٍ البحث عن المحادثات',
+ scanError: 'تعذر العثور على الجلسات',
+ scanHelp: 'تحقق من اتصال الخادم ثم أعد المحاولة. قد تحتاج الخوادم القديمة إلى تحديث.',
+ empty: 'لا توجد محادثات',
+ emptyHelp: 'ستظهر هنا جلسات Claude Code وCodex الموجودة على هذا الخادم.',
+ noMatches: 'لا توجد محادثات مطابقة',
+ searchHelp: 'جرّب عنوانًا أو مجلدًا آخر، أو حمّل المزيد من الجلسات.',
+ skipped: 'تم تجاوز بعض السجلات الفارغة أو غير المقروءة أو الكبيرة جدًا.',
+ more: 'تحميل المزيد من الجلسات',
+ messages: 'رسائل',
+ choose: 'محادثة تستحق المتابعة',
+ chooseHelp: 'اختر جلسة لقراءة سجلها قبل نقلها إلى Hermes.',
+ previewLoading: 'جارٍ فتح المعاينة',
+ previewError: 'المعاينة غير متاحة',
+ previewHelp: 'ربما تم نقل الملف الأصلي أو تغييره. حدّث القائمة وحاول مرة أخرى.',
+ previewLimit: 'تم اختصار المعاينة لتسهيل القراءة. يتم استيراد المحادثة كاملة.',
+ you: 'أنت',
+ snapshot: 'هذه المحادثة موجودة بالفعل في Hermes. افتح نسختك الحالية للمتابعة.',
+ copyNotice: 'ينسخ نص المحادثة دون تغيير الملفات الأصلية. لا يشمل مخرجات الأدوات أو الاستدلال.',
+ importing: 'جارٍ الاستيراد…',
+ open: 'فتح في Hermes',
+ continue: 'المتابعة في Hermes',
+ importError: 'تعذر استيراد هذه المحادثة.'
+ },
sendDiagnostics: {
title: 'إرسال التشخيصات إلى Nous',
privacyNotice:
diff --cc apps/desktop/src/i18n/en.ts
index 44ce4af8c76,fb22b4ed983..e6e47fc05fa
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -3,12 -3,40 +3,46 @@@ import { FIELD_DESCRIPTIONS, FIELD_LABE
import type { Translations } from './types'
export const en: Translations = {
+ externalOpenFailed: {
+ title: 'Couldn’t open this link',
+ message: 'No browser is registered to open this address. Copy the link and open it manually.',
+ copyUrl: 'Copy link',
+ close: 'Close'
+ },
+ sessionImport: {
+ title: 'Continue from another app',
+ subtitle: 'Bring a conversation into Hermes and pick up where you left off.',
+ action: 'Import session',
+ readingFrom: 'Reading from',
+ connectedComputer: 'the connected computer',
+ destination: 'Import into',
+ all: 'All',
+ search: 'Search loaded sessions',
+ scanning: 'Finding conversations',
+ scanError: 'Could not find sessions',
+ scanHelp: 'Check your backend connection, then try again. Older backends may need an update.',
+ empty: 'No conversations found',
+ emptyHelp: 'Claude Code and Codex sessions on this backend will appear here.',
+ noMatches: 'No matching conversations',
+ searchHelp: 'Try another title or folder, or load more sessions.',
+ skipped: 'Some logs were empty, unreadable, or too large to preview.',
+ more: 'Load more sessions',
+ messages: 'messages',
+ choose: 'A conversation worth continuing',
+ chooseHelp: 'Choose a session to read its history before bringing it into Hermes.',
+ previewLoading: 'Opening preview',
+ previewError: 'Preview unavailable',
+ previewHelp: 'The source may have moved or changed. Refresh the list and try again.',
+ previewLimit: 'Preview shortened for readability. The complete conversation is imported.',
+ you: 'You',
+ snapshot: 'This conversation is already in Hermes. Open your existing copy to continue.',
+ copyNotice:
+ 'Copies conversation text. Source files stay unchanged. Tool output and reasoning are not carried over.',
+ importing: 'Importing…',
+ open: 'Open in Hermes',
+ continue: 'Continue in Hermes',
+ importError: 'Could not import this conversation.'
+ },
common: {
apply: 'Apply',
back: 'Back',
diff --cc apps/desktop/src/i18n/ja.ts
index feb0b9f9a2a,024d272414e..6e1e68e9001
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -3,12 -3,39 +3,45 @@@ import { defineFieldCopy } from '@/app/
import { defineLocale } from './define-locale'
export const ja = defineLocale({
+ externalOpenFailed: {
+ title: 'このリンクを開けませんでした',
+ message: 'このアドレスを開くブラウザが登録されていません。リンクをコピーして手動で開いてください。',
+ copyUrl: 'リンクをコピー',
+ close: '閉じる'
+ },
+ sessionImport: {
+ title: '別のアプリから続ける',
+ subtitle: '会話をHermesに取り込み、続きを始めましょう。',
+ action: 'セッションを取り込む',
+ readingFrom: '読み込み元',
+ connectedComputer: '接続先のコンピューター',
+ destination: '取り込み先',
+ all: 'すべて',
+ search: '読み込み済みのセッションを検索',
+ scanning: '会話を検索中',
+ scanError: 'セッションを取得できません',
+ scanHelp: 'バックエンドの接続を確認して再試行してください。古いバックエンドは更新が必要な場合があります。',
+ empty: '会話が見つかりません',
+ emptyHelp: 'このバックエンドのClaude CodeとCodexのセッションがここに表示されます。',
+ noMatches: '一致する会話がありません',
+ searchHelp: '別のタイトルやフォルダーを検索するか、セッションを追加で読み込んでください。',
+ skipped: '空、読み込み不可、または大きすぎるログをスキップしました。',
+ more: 'さらに読み込む',
+ messages: 'メッセージ',
+ choose: '会話の続きを始めましょう',
+ chooseHelp: 'セッションを選び、取り込む前に履歴を確認できます。',
+ previewLoading: 'プレビューを開いています',
+ previewError: 'プレビューできません',
+ previewHelp: '元のファイルが移動または変更された可能性があります。一覧を更新してください。',
+ previewLimit: '読みやすいようにプレビューを省略しています。取り込み時は会話全体をコピーします。',
+ you: 'あなた',
+ snapshot: 'この会話は取り込み済みです。既存のコピーを開いて続けられます。',
+ copyNotice: '会話のテキストをコピーします。元のファイルは変更されません。ツール出力と推論は含まれません。',
+ importing: '取り込み中…',
+ open: 'Hermesで開く',
+ continue: 'Hermesで続ける',
+ importError: '会話を取り込めませんでした。'
+ },
common: {
apply: '適用',
back: '戻る',
diff --cc apps/desktop/src/i18n/types.ts
index f7aaf9c7e32,08ab95ffbad..6b48a62b32c
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@@ -51,12 -51,39 +51,45 @@@ interface AuxTaskCopy
}
export interface Translations {
+ externalOpenFailed: {
+ title: string
+ message: string
+ copyUrl: string
+ close: string
+ }
+ sessionImport: {
+ title: string
+ subtitle: string
+ action: string
+ readingFrom: string
+ connectedComputer: string
+ destination: string
+ all: string
+ search: string
+ scanning: string
+ scanError: string
+ scanHelp: string
+ empty: string
+ emptyHelp: string
+ noMatches: string
+ searchHelp: string
+ skipped: string
+ more: string
+ messages: string
+ choose: string
+ chooseHelp: string
+ previewLoading: string
+ previewError: string
+ previewHelp: string
+ previewLimit: string
+ you: string
+ snapshot: string
+ copyNotice: string
+ importing: string
+ open: string
+ continue: string
+ importError: string
+ }
common: {
apply: string
back: string
diff --cc apps/desktop/src/i18n/zh-hant.ts
index 7300eadbcbd,7d68fda36ad..05c5790046c
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -3,12 -3,39 +3,45 @@@ import { defineFieldCopy } from '@/app/
import { defineLocale } from './define-locale'
export const zhHant = defineLocale({
+ externalOpenFailed: {
+ title: '無法開啟此連結',
+ message: '沒有註冊用於開啟此位址的瀏覽器。請複製連結並手動開啟。',
+ copyUrl: '複製連結',
+ close: '關閉'
+ },
+ sessionImport: {
+ title: '從其他應用程式繼續',
+ subtitle: '將對話匯入 Hermes,接著上次的進度繼續。',
+ action: '匯入工作階段',
+ readingFrom: '讀取自',
+ connectedComputer: '已連線的電腦',
+ destination: '匯入至',
+ all: '全部',
+ search: '搜尋已載入的工作階段',
+ scanning: '正在尋找對話',
+ scanError: '無法尋找工作階段',
+ scanHelp: '請檢查後端連線並重試。舊版後端可能需要更新。',
+ empty: '找不到對話',
+ emptyHelp: '此後端上的 Claude Code 和 Codex 工作階段將顯示在這裡。',
+ noMatches: '沒有符合的對話',
+ searchHelp: '嘗試其他標題或資料夾,或載入更多工作階段。',
+ skipped: '部分記錄為空白、無法讀取或過大,已略過。',
+ more: '載入更多工作階段',
+ messages: '則訊息',
+ choose: '繼續一段對話',
+ chooseHelp: '選擇工作階段,在匯入 Hermes 前查看歷程記錄。',
+ previewLoading: '正在開啟預覽',
+ previewError: '無法預覽',
+ previewHelp: '來源檔案可能已移動或變更。請重新整理清單後重試。',
+ previewLimit: '預覽已縮短,方便閱讀。匯入時會複製完整對話。',
+ you: '你',
+ snapshot: '此對話已匯入 Hermes。開啟現有副本即可繼續。',
+ copyNotice: '複製對話文字,不變更來源檔案。不包含工具輸出和推理內容。',
+ importing: '正在匯入…',
+ open: '在 Hermes 中開啟',
+ continue: '在 Hermes 中繼續',
+ importError: '無法匯入此對話。'
+ },
common: {
apply: '套用',
back: '返回',
diff --cc apps/desktop/src/i18n/zh.ts
index 1f7e72f3256,db3473c0cb2..4899b197919
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@@ -3,12 -3,39 +3,45 @@@ import { defineFieldCopy } from '@/app/
import type { Translations } from './types'
export const zh: Translations = {
+ externalOpenFailed: {
+ title: '无法打开此链接',
+ message: '没有注册用于打开此地址的浏览器。请复制链接并手动打开。',
+ copyUrl: '复制链接',
+ close: '关闭'
+ },
+ sessionImport: {
+ title: '从其他应用继续',
+ subtitle: '将对话导入 Hermes,接着上次的进度继续。',
+ action: '导入会话',
+ readingFrom: '读取自',
+ connectedComputer: '已连接的计算机',
+ destination: '导入到',
+ all: '全部',
+ search: '搜索已加载的会话',
+ scanning: '正在查找对话',
+ scanError: '无法查找会话',
+ scanHelp: '请检查后端连接并重试。旧版后端可能需要更新。',
+ empty: '未找到对话',
+ emptyHelp: '此后端上的 Claude Code 和 Codex 会话将显示在这里。',
+ noMatches: '没有匹配的对话',
+ searchHelp: '尝试其他标题或文件夹,或加载更多会话。',
+ skipped: '部分日志为空、无法读取或过大,已跳过。',
+ more: '加载更多会话',
+ messages: '条消息',
+ choose: '继续一段对话',
+ chooseHelp: '选择会话,在导入 Hermes 前查看历史记录。',
+ previewLoading: '正在打开预览',
+ previewError: '预览不可用',
+ previewHelp: '源文件可能已移动或更改。请刷新列表后重试。',
+ previewLimit: '预览已缩短,便于阅读。导入时会复制完整对话。',
+ you: '你',
+ snapshot: '此对话已导入 Hermes。打开现有副本即可继续。',
+ copyNotice: '复制对话文本,不更改源文件。不包含工具输出和推理内容。',
+ importing: '正在导入…',
+ open: '在 Hermes 中打开',
+ continue: '在 Hermes 中继续',
+ importError: '无法导入此对话。'
+ },
common: {
apply: '应用',
back: '返回',
diff --cc hermes_cli/update_receipt.py
index 8e108f073f8,85135e712a0..0c6ae7da9de
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@@ -44,37 -19,11 +44,38 @@@ from typing import Any, Optiona
logger = logging.getLogger(__name__)
_RECEIPT_KEEP = 20 # keep the last N receipts per profile home
+ COMMAND_BOUNDARY_STOP_REASON = "completed at command boundary"
-# ``hermes update`` is a single-threaded CLI command; a module singleton lets the 7k-line updater
-# record steps from any depth without threading a handle through every helper.
-_current: Optional["UpdateReceipt"] = None
+# Receipt state is per-CONTEXT, not a module global: a nested
+# ``hermes update`` receipt (or one in another thread) must never clobber
+# the outer one, and the boundary finalize must see exactly its own
+# process's receipt. Same pattern as pm.receipt's ContextVars — no
+# manager object.
+_current: contextvars.ContextVar[Optional["UpdateReceipt"]] = contextvars.ContextVar(
+ "update_receipt_current", default=None
+)
+
+
+@contextmanager
+def update_receipt_scope():
+ """Keep the command's finalization guard away from an enclosing update."""
+ token = _current.set(None)
+ try:
+ yield
+ finally:
+ _current.reset(token)
+
+
+def current_correlation_id() -> Optional[str]:
+ """The update correlation id in force in this context, or None.
+
+ Derived from the OPEN update receipt itself — one source of truth, no
+ duplicate id variable: a nested update's begin replaces the current
+ receipt (so syncs begun under it capture the nested id), and its
+ finalize RESTORES the outer receipt via the ContextVar token (so the
+ outer id comes back for the rest of the outer update)."""
+ current = _current.get()
+ return current.correlation_id if current is not None else None
def _utc_now_iso() -> str:
diff --cc tests/hermes_cli/test_serve_parent_watchdog_live_macos.py
index 00000000000,80ba358154f..15a73814d43
mode 000000,100644..100644
--- a/tests/hermes_cli/test_serve_parent_watchdog_live_macos.py
+++ b/tests/hermes_cli/test_serve_parent_watchdog_live_macos.py
@@@ -1,0 -1,120 +1,120 @@@
+ """#95693 / #93958 — live macOS proof for the parent-death watchdog.
+
+ The unit tests in ``test_serve_parent_watchdog.py`` pin ``_is_serve_orphaned``
+ as a pure function. The bug itself lived one layer up: a daemon thread that
+ calls ``os._exit(0)`` ~5ms after ``HERMES_BACKEND_READY``, which no in-process
+ test can observe. This file runs the REAL ``start_server`` in a subprocess, on
+ the host ``ps``, with the marker the Desktop would hand it rendered in a
+ different timezone than the backend's own probe.
+
+ Contract:
+
+ * live parent + TZ-drifted ``ps:`` marker → backend announces READY and is
+ still alive well past several watchdog polls;
+ * that same backend still exits once the parent actually dies (the marker
+ degrade did not turn the watchdog off).
+ """
+
+ import os
+ import subprocess
+ import sys
+ import threading
+ import time
+ from pathlib import Path
+
+ import pytest
+
+ REPO_ROOT = Path(__file__).resolve().parents[2]
+
-pytestmark = pytest.mark.macos_only
++pytestmark = pytest.mark.platforms("macos")
+
+
+ def _lstart(pid: int, tz: str) -> str:
+ env = dict(os.environ, TZ=tz)
+ out = subprocess.run(
+ ["ps", "-p", str(pid), "-o", "lstart="], capture_output=True, text=True, env=env, check=True
+ ).stdout
+ return " ".join(out.split())
+
+
+ def _read_until(proc: subprocess.Popen, token: str, timeout: float = 120.0) -> bool:
+ hit = threading.Event()
+
+ def _pump():
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ if token in line:
+ hit.set()
+ return
+
+ threading.Thread(target=_pump, daemon=True).start()
+ return hit.wait(timeout)
+
+
+ def _wait_exit(proc: subprocess.Popen, timeout: float) -> bool:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if proc.poll() is not None:
+ return True
+ time.sleep(0.1)
+ return False
+
+
+ def test_live_backend_survives_timezone_drifted_parent_marker(tmp_path):
+ # Stand-in for the Electron parent: a long-lived process we control.
+ parent = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(600)"])
+ serve = None
+ try:
+ backend_tz = "America/New_York"
+ cached_tz = "Europe/Paris"
+ drifted_marker = f"ps:{_lstart(parent.pid, cached_tz)}"
+ assert drifted_marker != f"ps:{_lstart(parent.pid, backend_tz)}", (
+ "precondition: the two TZ renderings of the same instant must differ"
+ )
+
+ home = tmp_path / "hermes_home"
+ home.mkdir()
+ env = dict(os.environ)
+ env.update(
+ TZ=backend_tz,
+ HERMES_HOME=str(home),
+ HERMES_SERVE_HEADLESS="1",
+ PYTHONUNBUFFERED="1",
+ HERMES_PARENT_PID=str(parent.pid),
+ HERMES_PARENT_START_MARKER=drifted_marker,
+ HERMES_PARENT_NONCE="nonce-95693",
+ HERMES_SERVE_WATCHDOG_POLL_S="0.5",
+ )
+ env.pop("HERMES_DESKTOP", None)
+ code = (
+ "from hermes_cli.web_server import start_server\n"
+ "start_server(host='127.0.0.1', port=0, open_browser=False, headless=True)\n"
+ )
+ serve = subprocess.Popen(
+ [sys.executable, "-c", code],
+ cwd=str(REPO_ROOT),
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ )
+
+ assert _read_until(serve, "HERMES_BACKEND_READY"), "backend never announced READY"
+
+ # Before the fix the watchdog fired on its very first poll. Several
+ # polls later the backend must still be here.
+ assert not _wait_exit(serve, timeout=4.0), (
+ f"backend exited (code {serve.returncode}) with a live parent; "
+ f"TZ-drifted marker {drifted_marker!r} was treated as proof of death"
+ )
+
+ # The degrade to PID liveness must still reap a genuinely dead parent.
+ parent.kill()
+ parent.wait(timeout=10)
+ assert _wait_exit(serve, timeout=15.0), "backend outlived its dead parent"
+ assert serve.returncode == 0
+ finally:
+ for proc in (serve, parent):
+ if proc is not None and proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=10)
diff --cc tests/hermes_cli/test_win_pty_bridge.py
index 87e6a222ab2,465880055cd..3d4269b1527
--- a/tests/hermes_cli/test_win_pty_bridge.py
+++ b/tests/hermes_cli/test_win_pty_bridge.py
@@@ -23,11 -27,12 +27,12 @@@ import pytes
# WinPtyBridge can be imported on every platform — ``is_available`` just
# returns False when pywinpty isn't usable. Importing the module itself
# must never raise, otherwise the web_server import branch becomes a trap.
+ from hermes_cli import win_pty_bridge
from hermes_cli.win_pty_bridge import PtyUnavailableError, WinPtyBridge
-# ``pytest.mark.windows_only`` rather than a local ``skipif`` alias: the
+# ``pytest.mark.platforms("windows")`` rather than a local ``skipif`` alias: the
# dedicated Windows CI job selects its files by grepping for the marker name
-# and then filters with ``-m windows_only``. A file-local skipif alias matched
+# and then filters with ``-m platforms("windows")``. A file-local skipif alias matched
# the grep (so the file was listed) but carried no marker, so every test below
# was deselected — the lane looked like it covered ConPTY and ran none of it.
@@@ -98,10 -230,11 +230,11 @@@ class TestWinPtyBridgeSpawn
WinPtyBridge.spawn([bogus])
[email protected]("windows")
class TestWinPtyBridgeIO:
- def test_write_sends_to_child_stdin(self):
+ @pytest.mark.asyncio
+ async def test_write_sends_to_child_stdin(self):
# python -c reads stdin, echoes a marker, exits. More reliable than
# ``cat`` (not on Windows) and doesn't depend on a particular shell.
script = (
diff --cc tests/test_desktop_update_windows_ui_delivery.py
index 00000000000,dcd7b17c968..ef7fe7d0f1e
mode 000000,100644..100644
--- a/tests/test_desktop_update_windows_ui_delivery.py
+++ b/tests/test_desktop_update_windows_ui_delivery.py
@@@ -1,0 -1,92 +1,92 @@@
+ """The real Windows update server retains terminal events until acknowledged."""
+
+ from __future__ import annotations
+
+ import json
+ import os
+ import re
+ import shutil
+ import subprocess
+ import time
+ from contextlib import contextmanager
+ from pathlib import Path
+ from urllib.error import HTTPError
+ from urllib.request import Request, urlopen
+
+ import pytest
+
-pytestmark = pytest.mark.windows_only
++pytestmark = pytest.mark.platforms("windows")
+ SCRIPT = Path(__file__).resolve().parents[1] / "scripts/desktop-update/windows.ps1"
+
+
+ @contextmanager
+ def _server(tmp_path: Path, *, failed: bool = False):
+ powershell = shutil.which("powershell.exe")
+ assert powershell, "Windows updater tests require Windows PowerShell."
+ env = os.environ.copy()
+ env.update(TEMP=str(tmp_path), TMP=str(tmp_path), HERMES_SELFTEST_HOLD_SECONDS="0")
+ env.pop("HERMES_SELFTEST_FAIL", None)
+ if failed:
+ env["HERMES_SELFTEST_FAIL"] = "1"
+ output_path = tmp_path / "ui-delivery.log"
+ with output_path.open("wb") as output:
+ process = subprocess.Popen(
+ [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), "-SelfTestUi", "-NoUi"],
+ env=env,
+ stdout=output,
+ stderr=subprocess.STDOUT,
+ creationflags=subprocess.CREATE_NO_WINDOW,
+ )
+ try:
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ text = output_path.read_text(encoding="utf-8", errors="replace")
+ match = re.search(r"SELF-TEST: shim at (http://127\.0\.0\.1:\d+/)", text)
+ if match:
+ yield process, match.group(1)
+ return
+ if process.poll() is not None:
+ break
+ time.sleep(0.05)
+ pytest.fail(f"Update server did not publish a serving URL: {text}")
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=5)
+
+
+ def _request(url: str, *, post: bool = False):
+ request = Request(url, data=b"" if post else None, method="POST" if post else "GET")
+ return urlopen(request, timeout=3)
+
+
+ @pytest.mark.parametrize("failed", [False, True], ids=["complete", "failed"])
+ def test_delayed_client_receives_terminal_state_before_acknowledging(tmp_path: Path, failed: bool) -> None:
+ with _server(tmp_path, failed=failed) as (process, url):
+ # A background browser can miss the former 900ms terminal-state window.
+ time.sleep(2)
+ assert process.poll() is None, "the updater discarded its final state before the delayed client received it"
+ with _request(url + "progress") as response:
+ state = json.load(response)
+ assert state["status"] == ("error" if failed else "done")
+ receipt = state["receipt"]
+ assert isinstance(receipt, str) and receipt
+
+ with pytest.raises(HTTPError) as wrong:
+ _request(url + "ack/not-the-published-receipt", post=True)
+ assert wrong.value.code == 409
+ assert process.poll() is None, "an unrelated acknowledgement must not dispose the window's state"
+
+ for route, post in [("progress-other", False), ("ack/" + receipt, False), ("ack/" + receipt + "/extra", True)]:
+ with pytest.raises(HTTPError) as invalid:
+ _request(url + route, post=post)
+ assert invalid.value.code == 404
+
+ with _request(url + "ack/" + receipt, post=True) as response:
+ assert response.status == 204
+ assert process.wait(timeout=15) == 0
+
+
+ def test_no_client_does_not_keep_the_update_process_alive_forever(tmp_path: Path) -> None:
+ with _server(tmp_path) as (process, _url):
+ assert process.wait(timeout=25) == 0
diff --cc tests/tools/test_file_sync_back.py
index 5b290107959,5075dd3aeaf..14f9dd4f17b
--- a/tests/tools/test_file_sync_back.py
+++ b/tests/tools/test_file_sync_back.py
@@@ -457,3 -457,44 +457,44 @@@ class TestSyncBackSizeCap
# Default cap (2 GiB) is far above our tiny tar; extraction should proceed
mgr.sync_back(hermes_home=tmp_path / ".hermes")
assert Path(host_file).read_bytes() == b"remote_version"
+
+
+ class TestSyncBackWindowsHost:
+ """#76267: sync_back on a Windows host. The staging tar must be reopenable for writing by
+ the backend (NamedTemporaryFile held an exclusive handle → PermissionError), and remote
+ keys/parents must stay POSIX (relpath/Path stringify with backslashes on Windows, so no
+ staged file ever matched its mapping and every edit was dropped as "no host mapping")."""
+
+ def test_backend_can_reopen_the_tar_path_for_writing(self, tmp_path):
+ """Contract on every host: the download callback receives a path nothing else holds open."""
+ seen = {}
+
+ def download(dest: Path) -> None:
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w") as tar:
+ info = tarfile.TarInfo(name="root/.hermes/skill.py")
+ info.size = 2
+ tar.addfile(info, io.BytesIO(b"v2"))
+ with open(dest, "wb") as fh: # the SSH/Modal backends write exactly like this
+ fh.write(buf.getvalue())
+ seen["dest"] = dest
+
+ host_file = tmp_path / "host" / "skill.py"
+ _write_file(host_file, b"v1")
+ mgr = _make_manager(tmp_path, [(str(host_file), "/root/.hermes/skill.py")], bulk_download_fn=download)
+ mgr._pushed_hashes["/root/.hermes/skill.py"] = _sha256_bytes(b"v1")
+ mgr.sync_back(hermes_home=tmp_path / ".hermes")
+ assert host_file.read_bytes() == b"v2"
+ assert not seen["dest"].exists() # staging tar removed after use
+
- @pytest.mark.windows_only
++ @pytest.mark.platforms("windows")
+ def test_posix_remote_keys_match_on_windows(self, tmp_path):
+ host_file = tmp_path / "host" / "skill.py"
+ _write_file(host_file, b"v1")
+ mapping = [(str(host_file), "/root/.hermes/skills/a/skill.py")]
+ mgr = _make_manager(tmp_path, mapping, bulk_download_fn=_make_download_fn({
+ "root/.hermes/skills/a/skill.py": b"v2", "root/.hermes/skills/a/new.md": b"new"}))
+ mgr._pushed_hashes["/root/.hermes/skills/a/skill.py"] = _sha256_bytes(b"v1")
+ mgr.sync_back(hermes_home=tmp_path / ".hermes")
+ assert host_file.read_bytes() == b"v2" # relpath key was 'root\\.hermes\\...' → skipped
+ assert (tmp_path / "host" / "new.md").read_bytes() == b"new" # _infer_host_path parent match
diff --cc tests/tools/test_terminal_yield_to_background.py
index 00000000000,1dec580af73..959c241b811
mode 000000,100644..100644
--- a/tests/tools/test_terminal_yield_to_background.py
+++ b/tests/tools/test_terminal_yield_to_background.py
@@@ -1,0 -1,88 +1,88 @@@
+ """A user message sent while a foreground terminal command runs must not wait for the command.
+
+ ``AIAgent.redirect()`` during tool execution degrades to ``steer()``, whose delivery rides
+ the tool result — so a long foreground command (a 5-minute ``sleep`` poller, a build) parked
+ the user's message until it exited. Now redirect() also asks the tool workers to YIELD: the
+ local terminal backend hands the still-running process to the process registry as a
+ notify-on-complete background session and returns immediately, without killing it.
+ """
+ import json
+ import os
+ import threading
+ import time
+
+ import pytest
+
+ from agent.interrupt_control import InterruptControlMixin
+ from tools import interrupt as interrupt_mod
+ from tools.process_registry import process_registry
+ from tools.terminal_tool import terminal_tool
+
-pytestmark = pytest.mark.linux_only
++pytestmark = pytest.mark.platforms("linux")
+
+
+ class _Agent(InterruptControlMixin):
+ _executing_tools = True
+ _interrupt_requested = False
+ _pending_steer = None
+ _pending_redirect = None
+ api_mode = "chat_completions"
+
+ def __init__(self):
+ self._pending_steer_lock = threading.Lock()
+ self._pending_redirect_lock = threading.Lock()
+ self._tool_worker_threads = set()
+ self._tool_worker_threads_lock = threading.Lock()
+ self._execution_thread_id = None
+
+
+ def test_redirect_mid_command_yields_it_to_background_without_killing_it(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ agent = _Agent()
+ res = {}
+
+ def worker():
+ with agent._tool_worker_threads_lock:
+ agent._tool_worker_threads.add(threading.current_thread().ident)
+ t0 = time.monotonic()
+ res["result"] = json.loads(terminal_tool("echo started; sleep 60; echo done", task_id="yield-test", timeout=90))
+ res["elapsed"] = time.monotonic() - t0
+
+ t = threading.Thread(target=worker, daemon=True)
+ t.start()
+ time.sleep(1.5)
+ assert agent.redirect("also, check the session ids") is True
+ assert agent._pending_steer == "also, check the session ids" # still delivered as a steer
+
+ t.join(timeout=15)
+ assert not t.is_alive(), "terminal tool still blocked on the command after redirect()"
+ r = res["result"]
+ try:
+ assert r["status"] == "yielded_to_background"
+ assert r["exit_code"] is None and "started" in r["output"]
+ assert r["notify_on_complete"] is True
+ # The process is alive and tracked: poll/wait/kill and the completion notification work.
+ assert os.path.exists(f"/proc/{r['pid']}")
+ assert process_registry.poll(r["session_id"])["status"] == "running"
+ assert not interrupt_mod.is_thread_yield_requested(t.ident)
+ finally:
+ killed = process_registry.kill_process(r["session_id"])
+ assert killed["status"] == "killed"
+ evt = process_registry.completion_queue.get(timeout=5)
+ assert evt["session_id"] == r["session_id"]
+
+
+ def test_yield_request_without_steer_leaves_foreground_wait_alone():
+ """No yield handler (internal env.execute consumers) -> the request is ignored and the
+ command runs to completion; an unrelated stale yield bit must not leak into it either."""
+ from tools.environments.local import LocalEnvironment
+
+ env = LocalEnvironment()
+ try:
+ interrupt_mod.request_yield(threading.current_thread().ident)
+ result = env.execute("echo alpha; sleep 0.3; echo omega", timeout=10)
+ assert result["returncode"] == 0
+ assert "omega" in result["output"]
+ finally:
+ interrupt_mod.consume_yield(threading.current_thread().ident)
+ env.cleanup()
diff --cc tests/verify/test_environment_and_runner.py
index e8d486aa2b4,89905d14a83..2778e5898a4
--- a/tests/verify/test_environment_and_runner.py
+++ b/tests/verify/test_environment_and_runner.py
@@@ -2,11 -2,13 +2,15 @@@
import http.server
import json
+ import subprocess
import threading
import time
+ from unittest.mock import MagicMock, patch
+
+ import pytest
+import pytest
+
from agent.verify.environment import (
load_manifest,
load_or_detect,
diff --cc tools/environments/base.py
index afaa57fdd78,47998cd27b7..6e88caf6427
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@@ -17,10 -16,10 +17,10 @@@ import tim
import uuid
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import Callable, Iterable
+from typing import Callable, IO, Iterable, Protocol
from hermes_constants import get_hermes_home
- from tools.interrupt import is_interrupted, is_thread_interrupted
+ from tools.interrupt import consume_yield, is_interrupted, is_thread_interrupted
from tools.environments.base_output import (
ProcessHandle, _finalize_wait_result, _new_output_collector, _start_drain_thread,
)
@@@ -484,8 -338,12 +530,12 @@@ class BaseEnvironment(ABC)
def _wait_for_process(
self, proc: ProcessHandle, timeout: int = 120, *,
bounded_capture: bool = False, watch_interrupt_tid: int | None = None,
- output=None) -> dict:
- yield_handler: Callable[[ProcessHandle, str], dict] | None = None) -> dict:
++ output=None, yield_handler: Callable[[ProcessHandle, str], dict] | None = None) -> dict:
"""Poll-based wait with interrupt checking and stdout draining (shared, not overridden).
+ ``yield_handler(proc, output_so_far)``: when the tool thread is asked to yield
+ (``tools.interrupt.request_yield`` — a user message arrived mid-command), the drain
+ thread is stopped, the still-running process is handed to the handler and its dict
+ is returned as the result; the process is NOT killed.
``bounded_capture=True`` (foreground terminal-tool path only) retains at most
``tool_output.max_bytes`` in a head/tail window so a verbose subprocess cannot OOM the
process; the default keeps full fidelity for internal consumers. Fires the activity
@@@ -500,9 -358,9 +550,10 @@@
reads feeding the patch engine, code-execution RPC reads, log reads — where truncation would corrupt
data. See #64435.
"""
- output = _new_output_collector(proc, bounded_capture)
+ if output is None:
+ output = _new_output_collector(proc, bounded_capture)
- drain_thread = _start_drain_thread(proc, output)
+ drain_stop = threading.Event() if yield_handler is not None else None
+ drain_thread = _start_drain_thread(proc, output, drain_stop)
_now = time.monotonic()
deadline = _now + timeout
_activity_state = {"last_touch": _now, "start": _now}
@@@ -657,11 -528,10 +722,12 @@@
set_activity_callback(parent_activity_cb)
spawned = self._run_bash(wrapped, login=login, timeout=effective_timeout, stdin_data=effective_stdin)
proc_holder.append(spawned)
+ output = _new_output_collector(spawned, bounded_capture)
+ output_holder.append(output)
return self._wait_for_process(
spawned, timeout=effective_timeout, bounded_capture=bounded_capture,
- watch_interrupt_tid=parent_tid, output=output)
- watch_interrupt_tid=parent_tid,
++ watch_interrupt_tid=parent_tid, output=output,
+ **({"yield_handler": yield_handler} if yield_handler is not None else {}))
def _on_timeout() -> None:
if proc_holder: