Merge latest upstream into hybrid remote Bot routing
Carry the reviewed hybrid Bot routing branch through current main at
4a5b6dd45 without rewriting prior signed commits.
This commit is contained in:
@@ -48,6 +48,9 @@ outputs:
|
||||
installer:
|
||||
description: Run the PowerShell installer tests on a Windows runner.
|
||||
value: ${{ steps.classify.outputs.installer }}
|
||||
rust:
|
||||
description: Run `cargo test` for the Tauri bootstrap installer.
|
||||
value: ${{ steps.classify.outputs.rust }}
|
||||
mcp_catalog:
|
||||
description: Require MCP catalog security review label.
|
||||
value: ${{ steps.classify.outputs.mcp_catalog }}
|
||||
|
||||
@@ -49,6 +49,7 @@ jobs:
|
||||
uv_lock: ${{ steps.classify.outputs.uv_lock }}
|
||||
npm_lock: ${{ steps.classify.outputs.npm_lock }}
|
||||
installer: ${{ steps.classify.outputs.installer }}
|
||||
rust: ${{ steps.classify.outputs.rust }}
|
||||
docker_meta: ${{ steps.classify.outputs.docker_meta }}
|
||||
mcp_catalog: ${{ steps.classify.outputs.mcp_catalog }}
|
||||
ci_review: ${{ steps.classify.outputs.ci_review }}
|
||||
@@ -105,6 +106,14 @@ jobs:
|
||||
if: needs.detect.outputs.installer == 'true'
|
||||
uses: ./.github/workflows/installer-tests.yml
|
||||
|
||||
rust-tests:
|
||||
name: Rust tests
|
||||
needs: detect
|
||||
# Only for PRs that touch a Rust crate. `.rs` is under apps/, so these
|
||||
# changes used to run the TypeScript matrix and nothing that compiles them.
|
||||
if: needs.detect.outputs.rust == 'true'
|
||||
uses: ./.github/workflows/rust-tests.yml
|
||||
|
||||
e2e-desktop:
|
||||
name: Desktop E2E
|
||||
needs: detect
|
||||
@@ -213,6 +222,7 @@ jobs:
|
||||
- lint
|
||||
- js-tests
|
||||
- installer-tests
|
||||
- rust-tests
|
||||
- e2e-desktop
|
||||
- docs-site
|
||||
- history-check
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# .github/workflows/rust-tests.yml
|
||||
name: Rust tests
|
||||
|
||||
# `cargo test` for the Tauri bootstrap installer (Hermes-Setup). Nothing in CI
|
||||
# compiled this crate before: `.rs` lives under `apps/`, so the change
|
||||
# classifier matched it as `frontend` and ran the TypeScript matrix, which
|
||||
# cannot notice a Rust error. The crate's unit tests existed in the tree and had
|
||||
# never run.
|
||||
#
|
||||
# Linux runner on purpose. The pipe-drain tests in src/powershell.rs need a real
|
||||
# process tree whose grandchild inherits the parent's stdout, and their fixture
|
||||
# is `#[cfg(unix)]`; the Windows half of that same contract is covered by
|
||||
# `-SelfTestPipeDrain` in scripts/desktop-update/windows.ps1 on the Windows
|
||||
# lane. A Windows runner here would compile them out and report green over zero
|
||||
# coverage.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: rust-tests-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
bootstrap-installer:
|
||||
name: cargo test (bootstrap installer)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/bootstrap-installer/src-tauri
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
# Tauri links against the system webkit2gtk on Linux, so the crate does
|
||||
# not compile without these even for `cargo test --lib`.
|
||||
- name: Install Tauri system dependencies
|
||||
working-directory: .
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install --no-install-recommends -y \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
libappindicator3-dev \
|
||||
librsvg2-dev \
|
||||
libxdo-dev \
|
||||
libssl-dev \
|
||||
patchelf
|
||||
|
||||
# Keyed on Cargo.toml, not Cargo.lock: apps/bootstrap-installer/.gitignore
|
||||
# excludes the lockfile (a create-tauri-app scaffold default), so there is
|
||||
# nothing pinned to hash and `--locked` cannot be used. That also means
|
||||
# this crate re-resolves its whole dependency graph on every build, which
|
||||
# is a real gap for a signed installer given the pinning policy in
|
||||
# AGENTS.md — tracking separately rather than widening this PR.
|
||||
#
|
||||
# No restore-keys: a partial hit leaves a stale target dir, and cargo
|
||||
# re-resolves correctly on top of a Cargo.toml-keyed hit anyway.
|
||||
- name: Restore cargo cache
|
||||
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
apps/bootstrap-installer/src-tauri/target
|
||||
key: cargo-${{ runner.os }}-${{ hashFiles('apps/bootstrap-installer/src-tauri/Cargo.toml') }}
|
||||
|
||||
# --lib only: the integration/bin targets would need a built frontend
|
||||
# (vite dist) that this lane deliberately does not produce.
|
||||
- name: cargo test
|
||||
run: cargo test --lib
|
||||
@@ -132,6 +132,17 @@ _NO_XHIGH_CLAUDE_SUBSTRINGS = (
|
||||
"claude-sonnet-4-6", "claude-sonnet-4.6",
|
||||
)
|
||||
|
||||
# Adaptive Claude families that REJECT a thinking disable — thinking is
|
||||
# mandatory and ``thinking: {"type": "disabled"}`` answers HTTP 400. The Portal
|
||||
# catalog flags the same families with ``reasoning.mandatory``.
|
||||
#
|
||||
# Unlike the two lists above, the failure here is asymmetric: a missing entry
|
||||
# 400s the turn, while a spurious one only leaves thinking on. When in doubt,
|
||||
# add the family.
|
||||
_MANDATORY_THINKING_CLAUDE_SUBSTRINGS = (
|
||||
"claude-fable",
|
||||
)
|
||||
|
||||
|
||||
def _is_claude_model(model: str | None) -> bool:
|
||||
return "claude" in (model or "").lower()
|
||||
@@ -298,6 +309,32 @@ def _supports_xhigh_effort(model: str) -> bool:
|
||||
return not any(v in m for v in _NO_XHIGH_CLAUDE_SUBSTRINGS)
|
||||
|
||||
|
||||
def _accepts_thinking_disable(model: str) -> bool:
|
||||
"""Return True when *model* accepts an explicit thinking disable.
|
||||
|
||||
Adaptive Claude models default to thinking ON, so "thinking off" only
|
||||
takes effect if we actively send ``thinking: {"type": "disabled"}`` —
|
||||
omitting the parameter leaves the upstream default in place and the model
|
||||
thinks anyway. Reasoning-mandatory families reject the disable outright
|
||||
with an HTTP 400, so they keep the omit-everything behavior.
|
||||
|
||||
Legacy manual-thinking Claude models are excluded because they need no
|
||||
disable: thinking is opt-in there via ``budget_tokens``, so not sending
|
||||
the block already means off.
|
||||
|
||||
Scoped to Claude deliberately. Kimi/Moonshot endpoints also speak the
|
||||
adaptive contract, but their documented disable behavior is omission
|
||||
(#13848) and they are not part of this bug; sending them a new parameter
|
||||
on the strength of Claude's contract would be a guess.
|
||||
"""
|
||||
if not _is_claude_model(model):
|
||||
return False
|
||||
if not _supports_adaptive_thinking(model):
|
||||
return False
|
||||
m = model.lower()
|
||||
return not any(v in m for v in _MANDATORY_THINKING_CLAUDE_SUBSTRINGS)
|
||||
|
||||
|
||||
def _forbids_sampling_params(model: str) -> bool:
|
||||
"""Return True for models that 400 on any non-default temperature/top_p/top_k.
|
||||
|
||||
@@ -3053,7 +3090,15 @@ def build_anthropic_kwargs(
|
||||
# request "summarized" so the reasoning blocks stay populated — matching
|
||||
# 4.6 behavior and preserving the activity-feed UX during long tool runs.
|
||||
if reasoning_config and isinstance(reasoning_config, dict):
|
||||
if reasoning_config.get("enabled") is not False and "haiku" not in model.lower():
|
||||
if reasoning_config.get("enabled") is False:
|
||||
# "Thinking off". Adaptive models think by DEFAULT, so omitting the
|
||||
# parameter is not a disable — it silently leaves thinking on and
|
||||
# the user keeps paying for it. Send the disable explicitly.
|
||||
# Mandatory-thinking models reject it with a 400, so they keep the
|
||||
# omission: a silently-ignored disable beats a dead turn.
|
||||
if _accepts_thinking_disable(model):
|
||||
kwargs["thinking"] = {"type": "disabled"}
|
||||
elif "haiku" not in model.lower():
|
||||
effort = str(reasoning_config.get("effort", "medium")).lower()
|
||||
budget = THINKING_BUDGET.get(effort, 8000)
|
||||
if _supports_adaptive_thinking(model):
|
||||
|
||||
@@ -8,10 +8,12 @@
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::process::{ExitStatus, Stdio};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::process::{Child, Command};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
/// CP1252 mapping for bytes `0x80..=0x9F` (the range that differs from Latin-1).
|
||||
/// Undefined slots keep the C1 control code points, matching Windows-1252
|
||||
@@ -129,6 +131,153 @@ pub struct ScriptResult {
|
||||
/// Cancellation signal — `cancel_tx.send(()).await` aborts the running script.
|
||||
pub type CancelRx = mpsc::Receiver<()>;
|
||||
|
||||
/// How long a child's pipes get to reach EOF AFTER the child itself has exited.
|
||||
///
|
||||
/// This is not a timeout on the child. The clock starts once the process is
|
||||
/// already gone and everything it wrote is sitting in the pipe buffer, so a
|
||||
/// 40-minute `uv pip install` is untouched — the grace only covers the final
|
||||
/// drain.
|
||||
///
|
||||
/// It exists because pipe EOF is not the child's to give. The write end of a
|
||||
/// redirected pipe is handed to the child as an inheritable handle, so every
|
||||
/// descendant spawned without its own redirection holds a duplicate, and the
|
||||
/// read side does not see EOF until the last of them closes it. `hermes update`
|
||||
/// deliberately runs its build steps with stdout inherited, so the tree under a
|
||||
/// child is arbitrarily deep and not something the caller can enumerate. When
|
||||
/// one of those descendants is a resident gateway, the pipe stays open for the
|
||||
/// life of the gateway — and every obligation downstream of the read is
|
||||
/// stranded with it.
|
||||
///
|
||||
/// Same bound `Invoke-HermesStep` grew in `scripts/desktop-update/windows.ps1`
|
||||
/// (#90455), and the same shape as Go's `exec.Cmd.WaitDelay`.
|
||||
pub(crate) const DRAIN_GRACE: Duration = Duration::from_secs(20);
|
||||
|
||||
/// What [`pump_child`] observed.
|
||||
pub(crate) struct PumpOutcome {
|
||||
pub exit_code: Option<i32>,
|
||||
/// The child was killed because the caller cancelled.
|
||||
pub killed: bool,
|
||||
/// The child exited but its pipes never reached EOF within [`DRAIN_GRACE`],
|
||||
/// so the tail of its output was dropped. Callers must say so out loud: a
|
||||
/// silently truncated log is indistinguishable from one that was empty.
|
||||
pub abandoned: bool,
|
||||
}
|
||||
|
||||
/// Stream a child's stdout/stderr line by line, then reap it.
|
||||
///
|
||||
/// The contract that matters: the exit status comes from waiting on the
|
||||
/// *process*, never from pipe EOF. See [`DRAIN_GRACE`] for why those are not
|
||||
/// the same event; callers pass it, tests pass something they can wait out.
|
||||
pub(crate) async fn pump_child<FO, FE>(
|
||||
child: &mut Child,
|
||||
mut on_stdout: FO,
|
||||
mut on_stderr: FE,
|
||||
cancel_rx: &mut Option<CancelRx>,
|
||||
grace: Duration,
|
||||
) -> Result<PumpOutcome>
|
||||
where
|
||||
FO: FnMut(&str),
|
||||
FE: FnMut(&str),
|
||||
{
|
||||
let stdout = child.stdout.take().context("stdout was piped")?;
|
||||
let stderr = child.stderr.take().context("stderr was piped")?;
|
||||
let mut out = BufReader::new(stdout);
|
||||
let mut err = BufReader::new(stderr);
|
||||
let mut out_buf = Vec::new();
|
||||
let mut err_buf = Vec::new();
|
||||
let mut out_done = false;
|
||||
let mut err_done = false;
|
||||
let mut status: Option<ExitStatus> = None;
|
||||
let mut cancelled = false;
|
||||
|
||||
// Phase 1 — the child is alive, so there is no deadline. A slow child is
|
||||
// not a stuck one, and the point of streaming is that a long build keeps
|
||||
// reporting. We leave on whichever lands first: both pipes at EOF (the
|
||||
// clean case), the process exiting (the case that used to hang here), or
|
||||
// cancellation.
|
||||
while !(out_done && err_done) {
|
||||
tokio::select! {
|
||||
line = read_decoded_line(&mut out, &mut out_buf), if !out_done => match line {
|
||||
Ok(Some(l)) => on_stdout(&l),
|
||||
Ok(None) => out_done = true,
|
||||
Err(e) => {
|
||||
tracing::warn!("stdout read error: {e}");
|
||||
out_done = true;
|
||||
}
|
||||
},
|
||||
line = read_decoded_line(&mut err, &mut err_buf), if !err_done => match line {
|
||||
Ok(Some(l)) => on_stderr(&l),
|
||||
Ok(None) => err_done = true,
|
||||
Err(e) => {
|
||||
tracing::warn!("stderr read error: {e}");
|
||||
err_done = true;
|
||||
}
|
||||
},
|
||||
reaped = child.wait() => {
|
||||
status = Some(reaped.context("waiting for child to exit")?);
|
||||
break;
|
||||
}
|
||||
_ = recv_cancel(cancel_rx) => {
|
||||
cancelled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Kill outside the loop: `child.wait()` above holds the mutable borrow for
|
||||
// as long as the select is in scope.
|
||||
if cancelled {
|
||||
tracing::warn!("cancellation received — killing child");
|
||||
let _ = child.start_kill();
|
||||
}
|
||||
|
||||
// Phase 2 — bounded. Whatever the child already wrote is still worth
|
||||
// keeping, so we keep reading; we just stop caring once a descendant is the
|
||||
// only thing still holding the pipe open. Cancelling does not rescue us
|
||||
// either: `start_kill` kills the child, not the grandchild with the handle.
|
||||
let mut abandoned = false;
|
||||
if !(out_done && err_done) {
|
||||
let drain = async {
|
||||
while !(out_done && err_done) {
|
||||
tokio::select! {
|
||||
line = read_decoded_line(&mut out, &mut out_buf), if !out_done => match line {
|
||||
Ok(Some(l)) => on_stdout(&l),
|
||||
_ => out_done = true,
|
||||
},
|
||||
line = read_decoded_line(&mut err, &mut err_buf), if !err_done => match line {
|
||||
Ok(Some(l)) => on_stderr(&l),
|
||||
_ => err_done = true,
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
abandoned = timeout(grace, drain).await.is_err();
|
||||
}
|
||||
|
||||
let status = match status {
|
||||
Some(s) => s,
|
||||
// Both pipes reached EOF while the child stayed alive. Reads are done,
|
||||
// but the process is still the authoritative terminal condition — and
|
||||
// it may never exit on its own, so this wait stays cancellable. A bare
|
||||
// `child.wait()` here would strand the caller's cancel channel exactly
|
||||
// when it is the only way out.
|
||||
None => tokio::select! {
|
||||
reaped = child.wait() => reaped.context("waiting for child to exit")?,
|
||||
_ = recv_cancel(cancel_rx) => {
|
||||
tracing::warn!("cancellation received after EOF — killing child");
|
||||
cancelled = true;
|
||||
let _ = child.start_kill();
|
||||
child.wait().await.context("waiting for killed child to exit")?
|
||||
}
|
||||
},
|
||||
};
|
||||
Ok(PumpOutcome {
|
||||
exit_code: status.code(),
|
||||
killed: cancelled,
|
||||
abandoned,
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawns install.ps1 / install.sh with the given args and streams output.
|
||||
///
|
||||
/// `hermes_home_override` propagates to the child as $HERMES_HOME so the
|
||||
@@ -171,88 +320,49 @@ pub async fn run_script(
|
||||
.spawn()
|
||||
.with_context(|| format!("spawning {} via {}", script_path.display(), interpreter_label()))?;
|
||||
|
||||
let stdout = child.stdout.take().expect("stdout was piped");
|
||||
let stderr = child.stderr.take().expect("stderr was piped");
|
||||
|
||||
// Byte-oriented readers + [`decode_console_bytes`]: do NOT use
|
||||
// `BufReader::lines()`, which requires valid UTF-8 and hides localized
|
||||
// PowerShell errors on non-English Windows (#67193).
|
||||
let mut stdout_reader = BufReader::new(stdout);
|
||||
let mut stderr_reader = BufReader::new(stderr);
|
||||
let mut stdout_buf = Vec::new();
|
||||
let mut stderr_buf = Vec::new();
|
||||
|
||||
// PowerShell errors on non-English Windows (#67193). [`pump_child`] owns
|
||||
// that, plus the rule that the exit status comes from the process and not
|
||||
// from pipe EOF.
|
||||
let mut combined_stdout = String::new();
|
||||
let mut combined_stderr = String::new();
|
||||
let mut killed = false;
|
||||
|
||||
// Loop: poll stdout, stderr, cancel, and child exit concurrently.
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = read_decoded_line(&mut stdout_reader, &mut stdout_buf) => {
|
||||
match line {
|
||||
Ok(Some(l)) => {
|
||||
(sink.on_stdout_line)(&l);
|
||||
combined_stdout.push_str(&l);
|
||||
combined_stdout.push('\n');
|
||||
}
|
||||
Ok(None) => {
|
||||
// EOF on stdout — wait for stderr + exit.
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("stdout read error: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
line = read_decoded_line(&mut stderr_reader, &mut stderr_buf) => {
|
||||
match line {
|
||||
Ok(Some(l)) => {
|
||||
(sink.on_stderr_line)(&l);
|
||||
combined_stderr.push_str(&l);
|
||||
combined_stderr.push('\n');
|
||||
}
|
||||
Ok(None) => {
|
||||
// stderr EOF — keep draining stdout.
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("stderr read error: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = recv_cancel(cancel_rx) => {
|
||||
tracing::warn!("cancellation received — killing child");
|
||||
killed = true;
|
||||
// best-effort kill; don't propagate errors
|
||||
let _ = child.start_kill();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let outcome = pump_child(
|
||||
&mut child,
|
||||
|l| {
|
||||
(sink.on_stdout_line)(l);
|
||||
combined_stdout.push_str(l);
|
||||
combined_stdout.push('\n');
|
||||
},
|
||||
|l| {
|
||||
(sink.on_stderr_line)(l);
|
||||
combined_stderr.push_str(l);
|
||||
combined_stderr.push('\n');
|
||||
},
|
||||
cancel_rx,
|
||||
DRAIN_GRACE,
|
||||
)
|
||||
.await
|
||||
.context("streaming install script output")?;
|
||||
|
||||
// Drain remaining lines after the loop exited.
|
||||
while let Ok(Some(l)) = read_decoded_line(&mut stdout_reader, &mut stdout_buf).await {
|
||||
(sink.on_stdout_line)(&l);
|
||||
combined_stdout.push_str(&l);
|
||||
combined_stdout.push('\n');
|
||||
}
|
||||
while let Ok(Some(l)) = read_decoded_line(&mut stderr_reader, &mut stderr_buf).await {
|
||||
(sink.on_stderr_line)(&l);
|
||||
combined_stderr.push_str(&l);
|
||||
if outcome.abandoned {
|
||||
let note = format!(
|
||||
"install script exited but a surviving descendant still holds its \
|
||||
stdout/stderr; gave up on the last {}s of output (#90455)",
|
||||
DRAIN_GRACE.as_secs()
|
||||
);
|
||||
tracing::warn!("{note}");
|
||||
(sink.on_stderr_line)(¬e);
|
||||
combined_stderr.push_str(¬e);
|
||||
combined_stderr.push('\n');
|
||||
}
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.await
|
||||
.context("waiting for install script to exit")?;
|
||||
|
||||
Ok(ScriptResult {
|
||||
stdout: combined_stdout,
|
||||
stderr: combined_stderr,
|
||||
exit_code: status.code(),
|
||||
killed,
|
||||
exit_code: outcome.exit_code,
|
||||
killed: outcome.killed,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -550,4 +660,183 @@ info line
|
||||
.unwrap()
|
||||
.is_none());
|
||||
}
|
||||
|
||||
/// Spawn `sh -c <script>` with both pipes redirected, the way run_script and
|
||||
/// run_streamed do.
|
||||
#[cfg(unix)]
|
||||
fn sh(script: &str) -> Child {
|
||||
Command::new("/bin/sh")
|
||||
.arg("-c")
|
||||
.arg(script)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn /bin/sh")
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn pump_collect(child: &mut Child, grace: Duration) -> (PumpOutcome, Vec<String>) {
|
||||
let mut lines = Vec::new();
|
||||
let outcome = pump_child(
|
||||
child,
|
||||
|l| lines.push(l.to_string()),
|
||||
|_| {},
|
||||
&mut None,
|
||||
grace,
|
||||
)
|
||||
.await
|
||||
.expect("pump");
|
||||
(outcome, lines)
|
||||
}
|
||||
|
||||
/// The #90455 deadlock: a child exits, but a descendant it spawned still
|
||||
/// holds the inherited write end of the pipe, so EOF never comes. The pump
|
||||
/// must return on the *process* exiting and abandon the drain.
|
||||
///
|
||||
/// The Windows half of this contract lives in `-SelfTestPipeDrain`
|
||||
/// (scripts/desktop-update/windows.ps1) and runs on the Windows CI lane; the
|
||||
/// pump logic under test here is OS-agnostic, only the fixture is not.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_returns_when_a_grandchild_still_holds_the_pipe() {
|
||||
// `sleep` inherits stdout and outlives the shell by design. Nothing
|
||||
// redirects it -- redirecting is what would close the handle and stop
|
||||
// the bug from reproducing at all.
|
||||
let mut child = sh("sleep 30 & echo hello; exit 7");
|
||||
let started = std::time::Instant::now();
|
||||
let (outcome, lines) = pump_collect(&mut child, Duration::from_millis(300)).await;
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(outcome.abandoned, "drain should have been abandoned");
|
||||
assert_eq!(
|
||||
outcome.exit_code,
|
||||
Some(7),
|
||||
"exit code must survive an abandoned drain"
|
||||
);
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec!["hello"],
|
||||
"output written before the pipe was stranded must survive"
|
||||
);
|
||||
assert!(!outcome.killed);
|
||||
// Far below the grandchild's 30s: a pass cannot be it exiting on its own.
|
||||
assert!(elapsed < Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
|
||||
/// The other cliff: a child that leaks nothing must not pay the grace. This
|
||||
/// is what fails if the pump ever waits on the deadline unconditionally
|
||||
/// instead of only when a pipe outlives its process.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_does_not_pay_the_grace_when_pipes_close_cleanly() {
|
||||
let mut child = sh("echo one; echo two >&2; echo three; exit 3");
|
||||
let started = std::time::Instant::now();
|
||||
let (outcome, lines) = pump_collect(&mut child, Duration::from_secs(30)).await;
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(!outcome.abandoned);
|
||||
assert_eq!(outcome.exit_code, Some(3));
|
||||
assert_eq!(lines, vec!["one", "three"]);
|
||||
assert!(elapsed < Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
|
||||
/// A chatty child must stream at pipe speed, not at one buffer per tick.
|
||||
/// The PowerShell port of this pump regressed exactly here: idling after
|
||||
/// every chunk it *did* read metered the drain and backpressured the running
|
||||
/// child. `hermes update` is this shape -- the Electron build alone is
|
||||
/// megabytes.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_streams_a_flood_without_metering_it() {
|
||||
let mut child = sh("i=0; while [ $i -lt 20000 ]; do echo line$i; i=$((i+1)); done; exit 0");
|
||||
let started = std::time::Instant::now();
|
||||
let (outcome, lines) = pump_collect(&mut child, Duration::from_secs(30)).await;
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert_eq!(outcome.exit_code, Some(0));
|
||||
assert!(!outcome.abandoned);
|
||||
assert_eq!(lines.len(), 20000, "every line must survive");
|
||||
assert_eq!(lines.last().unwrap(), "line19999");
|
||||
// Loose on purpose: this catches per-chunk sleeping (which would put
|
||||
// this in the tens of seconds), not small scheduler variance.
|
||||
assert!(elapsed < Duration::from_secs(20), "took {elapsed:?}");
|
||||
}
|
||||
|
||||
/// Cancelling kills the child, but not a grandchild holding the pipe --
|
||||
/// `start_kill` only reaches the child. The bounded drain is what actually
|
||||
/// lets a cancel return, so cancellation and the grace are one mechanism.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_cancellation_returns_even_with_the_pipe_stranded() {
|
||||
let mut child = sh("sleep 30 & echo working; sleep 30");
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let mut cancel = Some(rx);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let _ = tx.send(()).await;
|
||||
});
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let outcome = pump_child(
|
||||
&mut child,
|
||||
|l| lines.push(l.to_string()),
|
||||
|_| {},
|
||||
&mut cancel,
|
||||
Duration::from_millis(300),
|
||||
)
|
||||
.await
|
||||
.expect("pump");
|
||||
|
||||
assert!(outcome.killed, "cancellation should report killed");
|
||||
assert!(outcome.abandoned, "the grandchild still holds the pipe");
|
||||
assert_eq!(lines, vec!["working"]);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"took {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
/// The reverse topology of the test above: the pipes die and the *process*
|
||||
/// outlives them. Phase 1 leaves on EOF with no exit status, so the final
|
||||
/// wait is the only thing left holding the turn -- and it has to stay
|
||||
/// cancellable. A bare `child.wait()` there strands the cancel channel
|
||||
/// against a child that may never exit on its own.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_cancellation_returns_after_both_pipes_reach_eof() {
|
||||
// Closes fd 1 and 2, then lingers: both reads hit EOF immediately while
|
||||
// the process stays alive far past any plausible test duration.
|
||||
let mut child = sh("echo bye; exec 1>&- 2>&-; sleep 30");
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let mut cancel = Some(rx);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let _ = tx.send(()).await;
|
||||
});
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let outcome = pump_child(
|
||||
&mut child,
|
||||
|l| lines.push(l.to_string()),
|
||||
|_| {},
|
||||
&mut cancel,
|
||||
Duration::from_millis(300),
|
||||
)
|
||||
.await
|
||||
.expect("pump");
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(outcome.killed, "cancellation should report killed");
|
||||
assert!(
|
||||
!outcome.abandoned,
|
||||
"both pipes reached EOF, so nothing was abandoned"
|
||||
);
|
||||
assert_eq!(lines, vec!["bye"], "output written before EOF must survive");
|
||||
// Far below the child's 30s: a pass cannot be it exiting on its own.
|
||||
assert!(elapsed < Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,11 +31,10 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::events::{BootstrapEvent, LogStream, StageInfo, StageState};
|
||||
use crate::powershell::read_decoded_line;
|
||||
use crate::powershell::{pump_child, DRAIN_GRACE};
|
||||
|
||||
/// `hermes update` exit code meaning "another hermes process is holding the
|
||||
/// venv shim open / dirty precondition" — see _cmd_update_impl in
|
||||
@@ -134,17 +133,13 @@ struct MarkerOwner {
|
||||
age_secs: u64,
|
||||
}
|
||||
|
||||
/// Read the marker and report a live *foreign* owner, if any. `None` for every
|
||||
/// "no live update" case — absent, unreadable, malformed, dead pid, past the
|
||||
/// ceiling, or a marker whose pid is **this** process — matching
|
||||
/// `readLiveUpdateMarker` in the Electron gate. Never panics.
|
||||
/// Read the marker and report a live owner, if any. `None` for every "no live
|
||||
/// update" case — absent, unreadable, malformed, dead pid, or past the ceiling
|
||||
/// — matching `readLiveUpdateMarker` in the Electron gate. Never panics.
|
||||
///
|
||||
/// Self-PID is treated as non-ownership on purpose (#74761): since #50238 the
|
||||
/// desktop pre-writes this marker with the spawned updater's pid before the
|
||||
/// updater reaches `acquire`. Without the exclusion, `acquire` sees a live
|
||||
/// owner that is itself and aborts ("Another Hermes update is already
|
||||
/// running"), then the desktop relaunches and retries forever. A foreign live
|
||||
/// pid (e.g. a dashboard-spawned `hermes update`) still blocks.
|
||||
/// Self-PID is returned so `acquire` can adopt the desktop's pre-written claim
|
||||
/// without refreshing its acquisition time (#74761). A foreign live pid (e.g.
|
||||
/// a dashboard-spawned `hermes update`) still blocks.
|
||||
fn live_marker_owner(path: &Path) -> Option<MarkerOwner> {
|
||||
let raw = std::fs::read_to_string(path).ok()?;
|
||||
let mut lines = raw.lines();
|
||||
@@ -158,11 +153,6 @@ fn live_marker_owner(path: &Path) -> Option<MarkerOwner> {
|
||||
if age_secs > UPDATE_MARKER_MAX_AGE_SECS || !pid_is_alive(pid) {
|
||||
return None;
|
||||
}
|
||||
// Desktop `writeUpdateMarker(hermesHome, child.pid)` races ahead of us;
|
||||
// adopt that pre-claim rather than refusing our own marker.
|
||||
if pid == std::process::id() {
|
||||
return None;
|
||||
}
|
||||
Some(MarkerOwner { pid, age_secs })
|
||||
}
|
||||
|
||||
@@ -208,10 +198,18 @@ impl UpdateMarkerGuard {
|
||||
/// behavior), so we log and carry on with a guard that still attempts
|
||||
/// cleanup of whatever may exist at the path.
|
||||
fn acquire(path: PathBuf) -> Result<Self, MarkerOwner> {
|
||||
let pid = std::process::id();
|
||||
if let Some(owner) = live_marker_owner(&path) {
|
||||
if owner.pid == pid {
|
||||
// Repeated acquisition in this process is intentionally
|
||||
// re-entrant because the desktop may have pre-written our pid.
|
||||
// The desktop races ahead and pre-writes our pid. Adopt that
|
||||
// claim verbatim: rewriting started_at here lets retries reset
|
||||
// a wedged updater's age before the stale ceiling can clear it.
|
||||
return Ok(Self { path, owned: true });
|
||||
}
|
||||
return Err(owner);
|
||||
}
|
||||
let pid = std::process::id();
|
||||
let started_at = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
@@ -825,39 +823,34 @@ async fn run_streamed(
|
||||
.spawn()
|
||||
.map_err(|e| anyhow!("spawning {} {:?}: {e}", program.display(), args))?;
|
||||
|
||||
let stdout = child.stdout.take().expect("stdout piped");
|
||||
let stderr = child.stderr.take().expect("stderr piped");
|
||||
// Same non-UTF-8-safe decode path as powershell::run_script (#67193).
|
||||
let mut out = BufReader::new(stdout);
|
||||
let mut err = BufReader::new(stderr);
|
||||
let mut out_buf = Vec::new();
|
||||
let mut err_buf = Vec::new();
|
||||
|
||||
// Same non-UTF-8-safe decode path as powershell::run_script (#67193), and
|
||||
// the same rule about pipe EOF: `hermes update` is precisely the shape that
|
||||
// leaves resident descendants holding an inherited stdout handle, and every
|
||||
// stage this drives sits downstream of the read.
|
||||
let stage_owned = stage.map(|s| s.to_string());
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = read_decoded_line(&mut out, &mut out_buf) => match line {
|
||||
Ok(Some(l)) => emit_log(app, stage_owned.as_deref(), LogStream::Stdout, &l),
|
||||
Ok(None) => break,
|
||||
Err(e) => { tracing::warn!("stdout read error: {e}"); break; }
|
||||
},
|
||||
line = read_decoded_line(&mut err, &mut err_buf) => match line {
|
||||
Ok(Some(l)) => emit_log(app, stage_owned.as_deref(), LogStream::Stderr, &l),
|
||||
Ok(None) => {}
|
||||
Err(e) => { tracing::warn!("stderr read error: {e}"); }
|
||||
},
|
||||
}
|
||||
}
|
||||
while let Ok(Some(l)) = read_decoded_line(&mut out, &mut out_buf).await {
|
||||
emit_log(app, stage_owned.as_deref(), LogStream::Stdout, &l);
|
||||
}
|
||||
while let Ok(Some(l)) = read_decoded_line(&mut err, &mut err_buf).await {
|
||||
emit_log(app, stage_owned.as_deref(), LogStream::Stderr, &l);
|
||||
let outcome = pump_child(
|
||||
&mut child,
|
||||
|l| emit_log(app, stage_owned.as_deref(), LogStream::Stdout, l),
|
||||
|l| emit_log(app, stage_owned.as_deref(), LogStream::Stderr, l),
|
||||
&mut None,
|
||||
DRAIN_GRACE,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| anyhow!("streaming {} {:?}: {e}", program.display(), args))?;
|
||||
|
||||
if outcome.abandoned {
|
||||
let note = format!(
|
||||
"{} exited but a surviving descendant still holds its stdout/stderr; \
|
||||
gave up on the last {}s of output (#90455)",
|
||||
program.display(),
|
||||
DRAIN_GRACE.as_secs()
|
||||
);
|
||||
tracing::warn!("{note}");
|
||||
emit_log(app, stage_owned.as_deref(), LogStream::Stderr, ¬e);
|
||||
}
|
||||
|
||||
let status = child.wait().await.map_err(|e| anyhow!("waiting for child: {e}"))?;
|
||||
Ok(CmdResult {
|
||||
exit_code: status.code(),
|
||||
exit_code: outcome.exit_code,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1327,8 +1320,8 @@ mod tests {
|
||||
|
||||
/// Spawn a short-lived sibling process whose pid stands in for a foreign
|
||||
/// updater. Same-process double-acquire no longer models contention: since
|
||||
/// #74761 `live_marker_owner` treats our own pid as adoptable (desktop
|
||||
/// pre-writes it), so a second acquire in *this* process would succeed.
|
||||
/// #74761 `acquire` treats our own pid as adoptable (desktop pre-writes it),
|
||||
/// so a second acquire in *this* process would succeed.
|
||||
fn spawn_foreign_holder() -> std::process::Child {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
@@ -1385,7 +1378,8 @@ mod tests {
|
||||
fn acquire_adopts_a_marker_prewritten_with_our_own_pid() {
|
||||
// #74761: desktop writeUpdateMarker(hermesHome, child.pid) races ahead
|
||||
// of UpdateMarkerGuard::acquire. The marker names US; refusing it made
|
||||
// every in-app desktop update loop forever. Adopt and rewrite.
|
||||
// every in-app desktop update loop forever. Adopt it without resetting
|
||||
// the holder age, so a wedged updater still reaches the stale ceiling.
|
||||
let dir = unique_tmp_dir("marker-own-pid");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let marker = dir.join(".hermes-update-in-progress");
|
||||
@@ -1408,7 +1402,12 @@ mod tests {
|
||||
assert_eq!(
|
||||
body.lines().next().unwrap().trim().parse::<u32>().unwrap(),
|
||||
std::process::id(),
|
||||
"acquire rewrites the marker with our pid + fresh started_at"
|
||||
"acquire keeps the adopted marker owner"
|
||||
);
|
||||
assert_eq!(
|
||||
body.lines().nth(1).unwrap().trim().parse::<u64>().unwrap(),
|
||||
started_at,
|
||||
"adopting an own-pid marker must preserve its original holder age"
|
||||
);
|
||||
drop(guard);
|
||||
assert!(
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { describe, test } from 'vitest'
|
||||
|
||||
import {
|
||||
fallbackIconCandidates,
|
||||
type FaviconIo,
|
||||
iconCandidatesFromHtml,
|
||||
iconCandidatesFromManifest,
|
||||
imageMime,
|
||||
isPublicHttpUrl,
|
||||
largestDeclaredSize,
|
||||
manifestUrlFromHtml,
|
||||
rankCandidates,
|
||||
resolveFavicon,
|
||||
sniffImageMime
|
||||
} from './favicon'
|
||||
|
||||
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...new Array(60).fill(0)])
|
||||
const HTML_BYTES = new Uint8Array([...Buffer.from('<!doctype html><html>nope</html>'), ...new Array(40).fill(0x20)])
|
||||
|
||||
/** An IO that serves fixed text per URL and images only for listed URLs,
|
||||
* recording what was asked for and in what order. */
|
||||
function fakeIo(options: {
|
||||
images?: Record<string, { bytes: Uint8Array; mime: string }>
|
||||
text?: Record<string, string>
|
||||
}): { asked: string[]; io: FaviconIo } {
|
||||
const asked: string[] = []
|
||||
|
||||
return {
|
||||
asked,
|
||||
io: {
|
||||
fetchImage: async url => {
|
||||
asked.push(url)
|
||||
|
||||
return options.images?.[url] ?? null
|
||||
},
|
||||
fetchText: async url => options.text?.[url] ?? ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('which hosts we will ask at all', () => {
|
||||
test('a public https host is fair game', () => {
|
||||
assert.equal(isPublicHttpUrl('https://linear.app'), true)
|
||||
})
|
||||
|
||||
test.each([
|
||||
['loopback by name', 'http://localhost:8000/mcp'],
|
||||
['loopback by address', 'http://127.0.0.1:3000'],
|
||||
['RFC1918 class A', 'http://10.1.2.3'],
|
||||
['RFC1918 class B', 'http://172.16.0.9'],
|
||||
['RFC1918 class C', 'http://192.168.1.5'],
|
||||
['link-local', 'http://169.254.1.1'],
|
||||
['mDNS', 'http://nas.local'],
|
||||
['a bare hostname', 'http://buildbox'],
|
||||
['a non-http scheme', 'file:///etc/passwd']
|
||||
])('%s is refused', (_label, url) => {
|
||||
// A private endpoint has no logo out there to find, and asking would
|
||||
// announce an internal hostname.
|
||||
assert.equal(isPublicHttpUrl(url), false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reading a page for the marks it declares', () => {
|
||||
test('declared icons come back absolute against the page', () => {
|
||||
const found = iconCandidatesFromHtml('<link rel="icon" href="/assets/mark.png">', 'https://acme.test/docs/start')
|
||||
|
||||
assert.deepEqual(
|
||||
found.map(candidate => candidate.url),
|
||||
['https://acme.test/assets/mark.png']
|
||||
)
|
||||
})
|
||||
|
||||
test('a <base href> wins over the page URL, as a browser would resolve it', () => {
|
||||
const found = iconCandidatesFromHtml(
|
||||
'<base href="https://cdn.acme.test/"><link rel="icon" href="mark.png">',
|
||||
'https://acme.test/docs/'
|
||||
)
|
||||
|
||||
assert.deepEqual(
|
||||
found.map(candidate => candidate.url),
|
||||
['https://cdn.acme.test/mark.png']
|
||||
)
|
||||
})
|
||||
|
||||
test('single-quoted and unquoted attributes parse too', () => {
|
||||
const found = iconCandidatesFromHtml(
|
||||
`<link rel='icon' href='/a.png'><link rel=icon href=/b.png>`,
|
||||
'https://acme.test'
|
||||
)
|
||||
|
||||
assert.deepEqual(found.map(candidate => candidate.url).sort(), [
|
||||
'https://acme.test/a.png',
|
||||
'https://acme.test/b.png'
|
||||
])
|
||||
})
|
||||
|
||||
test('non-icon links are left alone', () => {
|
||||
const found = iconCandidatesFromHtml(
|
||||
'<link rel="stylesheet" href="/app.css"><link rel="canonical" href="/">',
|
||||
'https://acme.test'
|
||||
)
|
||||
|
||||
assert.deepEqual(found, [])
|
||||
})
|
||||
|
||||
test('a linked manifest is found', () => {
|
||||
assert.equal(
|
||||
manifestUrlFromHtml('<link rel="manifest" href="/site.webmanifest">', 'https://acme.test/x'),
|
||||
'https://acme.test/site.webmanifest'
|
||||
)
|
||||
})
|
||||
|
||||
test('a page with no manifest says so rather than guessing one', () => {
|
||||
assert.equal(manifestUrlFromHtml('<link rel="icon" href="/a.png">', 'https://acme.test'), '')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ranking, so the best mark is fetched first', () => {
|
||||
test('the largest declared square wins', () => {
|
||||
assert.equal(largestDeclaredSize('32x32 180x180 16x16'), 180)
|
||||
})
|
||||
|
||||
test('scalable outranks every raster size', () => {
|
||||
const [best] = rankCandidates(
|
||||
iconCandidatesFromHtml(
|
||||
'<link rel="icon" sizes="256x256" href="/big.png"><link rel="icon" type="image/svg+xml" href="/mark.svg">',
|
||||
'https://acme.test'
|
||||
)
|
||||
)
|
||||
|
||||
assert.equal(best.url, 'https://acme.test/mark.svg')
|
||||
})
|
||||
|
||||
test('an apple-touch link with no sizes still beats a guessed path', () => {
|
||||
const declared = iconCandidatesFromHtml('<link rel="apple-touch-icon" href="/touch.png">', 'https://acme.test')
|
||||
const ranked = rankCandidates([...fallbackIconCandidates('https://acme.test'), ...declared])
|
||||
|
||||
assert.equal(ranked[0].url, 'https://acme.test/touch.png')
|
||||
})
|
||||
|
||||
test('a manifest icon is ranked on its declared size', () => {
|
||||
const found = iconCandidatesFromManifest(
|
||||
JSON.stringify({
|
||||
icons: [
|
||||
{ sizes: '512x512', src: '/pwa-512.png' },
|
||||
{ sizes: '48x48', src: '/pwa-48.png' }
|
||||
]
|
||||
}),
|
||||
'https://acme.test/site.webmanifest'
|
||||
)
|
||||
|
||||
assert.equal(rankCandidates(found)[0].url, 'https://acme.test/pwa-512.png')
|
||||
})
|
||||
|
||||
test('unparseable manifest JSON is not an error, just no candidates', () => {
|
||||
assert.deepEqual(iconCandidatesFromManifest('<!doctype html>', 'https://acme.test/m.json'), [])
|
||||
})
|
||||
|
||||
test('the same URL declared twice is fetched once, at its best score', () => {
|
||||
const ranked = rankCandidates([
|
||||
{ score: 32, url: 'https://acme.test/a.png' },
|
||||
{ score: 180, url: 'https://acme.test/a.png' }
|
||||
])
|
||||
|
||||
assert.deepEqual(ranked, [{ score: 180, url: 'https://acme.test/a.png' }])
|
||||
})
|
||||
|
||||
test('a page declaring many icons cannot turn one card into many requests', () => {
|
||||
const many = Array.from({ length: 40 }, (_unused, index) => ({
|
||||
score: index,
|
||||
url: `https://acme.test/${index}.png`
|
||||
}))
|
||||
|
||||
assert.equal(rankCandidates(many).length, 6)
|
||||
})
|
||||
|
||||
test('the apex is tried as well as the subdomain', () => {
|
||||
// Vendors routinely serve icons from example.com and nothing from
|
||||
// api.example.com.
|
||||
const urls = fallbackIconCandidates('https://mcp.acme.test/sse').map(candidate => candidate.url)
|
||||
|
||||
assert.ok(urls.includes('https://mcp.acme.test/favicon.ico'))
|
||||
assert.ok(urls.includes('https://acme.test/favicon.ico'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('deciding whether bytes are actually an image', () => {
|
||||
test.each([
|
||||
['png', [0x89, 0x50, 0x4e, 0x47], 'image/png'],
|
||||
['jpeg', [0xff, 0xd8, 0xff], 'image/jpeg'],
|
||||
['gif', [0x47, 0x49, 0x46, 0x38], 'image/gif'],
|
||||
['ico', [0x00, 0x00, 0x01, 0x00], 'image/x-icon']
|
||||
])('%s is recognised from its magic bytes', (_label, signature, expected) => {
|
||||
assert.equal(sniffImageMime(new Uint8Array([...signature, ...new Array(60).fill(0)])), expected)
|
||||
})
|
||||
|
||||
test('webp needs both its RIFF header and its WEBP tag', () => {
|
||||
const riff = [0x52, 0x49, 0x46, 0x46]
|
||||
const webp = [0x57, 0x45, 0x42, 0x50]
|
||||
|
||||
assert.equal(sniffImageMime(new Uint8Array([...riff, 0, 0, 0, 0, ...webp, ...new Array(48).fill(0)])), 'image/webp')
|
||||
assert.equal(sniffImageMime(new Uint8Array([...riff, ...new Array(60).fill(0)])), '')
|
||||
})
|
||||
|
||||
test('the bytes overrule the server', () => {
|
||||
// A blocked request answers 200 with an HTML challenge page under
|
||||
// content-type: image/png often enough that believing the header is how
|
||||
// you end up rendering a broken-image box.
|
||||
assert.equal(imageMime('image/png', HTML_BYTES), '')
|
||||
})
|
||||
|
||||
test('an SVG whose opening tag is past the sniff window is trusted on its header', () => {
|
||||
const padded = new Uint8Array([...Buffer.from(`<!--${'x'.repeat(2000)}--><svg/>`)])
|
||||
|
||||
assert.equal(imageMime('image/svg+xml', padded), 'image/svg+xml')
|
||||
})
|
||||
|
||||
test('a response too short to be an image is refused', () => {
|
||||
assert.equal(imageMime('image/png', new Uint8Array([0x89, 0x50])), '')
|
||||
})
|
||||
})
|
||||
|
||||
describe('walking the ladder', () => {
|
||||
test('a private host is never fetched at all', async () => {
|
||||
const { asked, io } = fakeIo({})
|
||||
|
||||
assert.equal(await resolveFavicon('http://127.0.0.1:8000/mcp', io), '')
|
||||
assert.deepEqual(asked, [])
|
||||
})
|
||||
|
||||
test('a declared icon is preferred over the well-known path', async () => {
|
||||
const { io } = fakeIo({
|
||||
images: {
|
||||
'https://acme.test/declared.png': { bytes: PNG, mime: 'image/png' },
|
||||
'https://acme.test/favicon.ico': { bytes: PNG, mime: 'image/x-icon' }
|
||||
},
|
||||
text: { 'https://acme.test': '<link rel="icon" sizes="180x180" href="/declared.png">' }
|
||||
})
|
||||
|
||||
const icon = await resolveFavicon('https://acme.test', io)
|
||||
|
||||
assert.ok(icon.startsWith('data:image/png;base64,'))
|
||||
})
|
||||
|
||||
test('a site that declares nothing still gets its guessed favicon', async () => {
|
||||
const { io } = fakeIo({ images: { 'https://acme.test/favicon.ico': { bytes: PNG, mime: '' } } })
|
||||
|
||||
assert.ok((await resolveFavicon('https://acme.test', io)).startsWith('data:image/png;base64,'))
|
||||
})
|
||||
|
||||
test('a candidate that answers with a challenge page is skipped for the next one', async () => {
|
||||
const { io } = fakeIo({
|
||||
images: {
|
||||
'https://acme.test/apple-touch-icon.png': { bytes: HTML_BYTES, mime: 'image/png' },
|
||||
'https://acme.test/favicon.ico': { bytes: PNG, mime: 'image/x-icon' }
|
||||
}
|
||||
})
|
||||
|
||||
assert.ok((await resolveFavicon('https://acme.test', io)).startsWith('data:image/png;base64,'))
|
||||
})
|
||||
|
||||
test('a site nobody can read keeps its monogram rather than asking a third party', async () => {
|
||||
const { asked, io } = fakeIo({})
|
||||
|
||||
assert.equal(await resolveFavicon('https://walled.test', io), '')
|
||||
// Every attempt was against the site itself. No icon service, because
|
||||
// asking one means telling it which connector someone is wiring up.
|
||||
assert.ok(asked.length > 0)
|
||||
assert.ok(asked.every(url => url.includes('walled.test')))
|
||||
})
|
||||
|
||||
test('a page that throws on read falls through to the guessed paths', async () => {
|
||||
const io: FaviconIo = {
|
||||
fetchImage: async url => (url.endsWith('/favicon.ico') ? { bytes: PNG, mime: '' } : null),
|
||||
fetchText: async () => {
|
||||
throw new Error('ECONNRESET')
|
||||
}
|
||||
}
|
||||
|
||||
assert.ok((await resolveFavicon('https://acme.test', io)).startsWith('data:image/png;base64,'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,347 @@
|
||||
/**
|
||||
* Favicon resolution, the thorough way.
|
||||
*
|
||||
* `<origin>/favicon.ico` answers for maybe half the web. Everyone else
|
||||
* declares their marks in the page head (`<link rel="icon">`, apple-touch,
|
||||
* SVG mask icons) or in a web app manifest, at paths that are frequently
|
||||
* hashed build artifacts on a CDN — unguessable. So: read the page, collect
|
||||
* every declared icon, rank them, and only then fall back to the well-known
|
||||
* paths.
|
||||
*
|
||||
* Only ever the site's own marks. A public icon service would answer for the
|
||||
* hosts that hide behind a bot wall, but asking one means telling a third
|
||||
* party which connector a user is wiring up — so a site we can't read keeps
|
||||
* its monogram instead.
|
||||
*
|
||||
* This lives in the main process because none of it is possible from the
|
||||
* renderer: cross-origin HTML is unreadable under CORS, and the whole point
|
||||
* is reading someone else's markup.
|
||||
*
|
||||
* Everything here is pure — URL math, parsing, ranking. The I/O is injected
|
||||
* so the ladder can be tested without a network.
|
||||
*/
|
||||
|
||||
export interface IconCandidate {
|
||||
url: string
|
||||
/** Rough pixel edge, or a synthetic rank for scalable/unsized marks. */
|
||||
score: number
|
||||
}
|
||||
|
||||
export interface FaviconIo {
|
||||
/** Page/manifest text, or '' when it can't be read. */
|
||||
fetchText: (url: string) => Promise<string>
|
||||
/** Image bytes plus the server's content type, or null on any refusal. */
|
||||
fetchImage: (url: string) => Promise<null | { bytes: Uint8Array; mime: string }>
|
||||
}
|
||||
|
||||
/** Scalable beats every raster size; below it, bigger wins up to a point. */
|
||||
const SCORE_SVG = 1024
|
||||
/** `sizes="any"` — usually an SVG or a multi-res ICO. */
|
||||
const SCORE_ANY = 512
|
||||
/** Apple's spec size, which is what unsized apple-touch links almost always are. */
|
||||
const SCORE_APPLE_TOUCH = 180
|
||||
/** A declared icon with no size at all still beats a guessed path. */
|
||||
const SCORE_UNSIZED = 96
|
||||
/** Guessed well-known paths, tried only after everything declared. */
|
||||
const SCORE_GUESS = 48
|
||||
|
||||
/** Past this the file is a download, not an icon. */
|
||||
const SCORE_CEILING = 512
|
||||
|
||||
/**
|
||||
* A host worth asking for an icon.
|
||||
*
|
||||
* Loopback and RFC1918 addresses serve MCP endpoints, not brands, and an
|
||||
* icon service can't see them anyway. Refusing them here is also what keeps
|
||||
* a private hostname from being handed to that service.
|
||||
*/
|
||||
export function isPublicHttpUrl(raw: string): boolean {
|
||||
let url: URL
|
||||
|
||||
try {
|
||||
url = new URL(raw)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
return false
|
||||
}
|
||||
|
||||
const host = url.hostname.toLowerCase()
|
||||
|
||||
return !(
|
||||
host === 'localhost' ||
|
||||
host === '::1' ||
|
||||
host.endsWith('.local') ||
|
||||
host.endsWith('.internal') ||
|
||||
!host.includes('.') ||
|
||||
/^127\./.test(host) ||
|
||||
/^10\./.test(host) ||
|
||||
/^192\.168\./.test(host) ||
|
||||
/^169\.254\./.test(host) ||
|
||||
/^172\.(1[6-9]|2\d|3[01])\./.test(host)
|
||||
)
|
||||
}
|
||||
|
||||
const absolute = (href: string, base: string): string => {
|
||||
try {
|
||||
const url = new URL(href.trim(), base)
|
||||
|
||||
return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** "180x180 32x32" → 180. Takes the largest declared square edge. */
|
||||
export function largestDeclaredSize(sizes: string): number {
|
||||
let best = 0
|
||||
|
||||
for (const token of sizes.toLowerCase().split(/\s+/)) {
|
||||
if (token === 'any') {
|
||||
best = Math.max(best, SCORE_ANY)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
const edge = Number(token.split('x')[0])
|
||||
|
||||
if (Number.isFinite(edge)) {
|
||||
best = Math.max(best, edge)
|
||||
}
|
||||
}
|
||||
|
||||
return best
|
||||
}
|
||||
|
||||
const attr = (tag: string, name: string): string =>
|
||||
tag
|
||||
.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s"'>]+))`, 'i'))
|
||||
?.slice(2)
|
||||
.find(Boolean) ?? ''
|
||||
|
||||
const scoreFor = (rel: string, type: string, sizes: string): number => {
|
||||
if (type.includes('svg') || rel.includes('mask-icon')) {
|
||||
return SCORE_SVG
|
||||
}
|
||||
|
||||
const declared = largestDeclaredSize(sizes)
|
||||
|
||||
if (declared > 0) {
|
||||
return Math.min(declared, SCORE_CEILING)
|
||||
}
|
||||
|
||||
return rel.includes('apple-touch-icon') ? SCORE_APPLE_TOUCH : SCORE_UNSIZED
|
||||
}
|
||||
|
||||
/** Every icon the page declares, absolute and ranked. */
|
||||
export function iconCandidatesFromHtml(html: string, pageUrl: string): IconCandidate[] {
|
||||
const base = absolute(attr(html.match(/<base\b[^>]*>/i)?.[0] ?? '', 'href'), pageUrl) || pageUrl
|
||||
const candidates: IconCandidate[] = []
|
||||
|
||||
for (const tag of html.match(/<link\b[^>]*>/gi) ?? []) {
|
||||
const rel = attr(tag, 'rel').toLowerCase()
|
||||
|
||||
if (!/\b(icon|shortcut icon|apple-touch-icon|apple-touch-icon-precomposed|fluid-icon|mask-icon)\b/.test(rel)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const url = absolute(attr(tag, 'href'), base)
|
||||
|
||||
if (url) {
|
||||
candidates.push({ score: scoreFor(rel, attr(tag, 'type').toLowerCase(), attr(tag, 'sizes')), url })
|
||||
}
|
||||
}
|
||||
|
||||
return candidates
|
||||
}
|
||||
|
||||
/** The page's web app manifest, if it links one. */
|
||||
export function manifestUrlFromHtml(html: string, pageUrl: string): string {
|
||||
for (const tag of html.match(/<link\b[^>]*>/gi) ?? []) {
|
||||
if (/\bmanifest\b/i.test(attr(tag, 'rel'))) {
|
||||
return absolute(attr(tag, 'href'), pageUrl)
|
||||
}
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
/** PWA manifests carry the best assets a site has — 192px and 512px marks
|
||||
* designed to stand alone on a home screen, which is exactly our use. */
|
||||
export function iconCandidatesFromManifest(raw: string, manifestUrl: string): IconCandidate[] {
|
||||
let parsed: unknown
|
||||
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
||||
const icons = (parsed as { icons?: unknown })?.icons
|
||||
|
||||
if (!Array.isArray(icons)) {
|
||||
return []
|
||||
}
|
||||
|
||||
const candidates: IconCandidate[] = []
|
||||
|
||||
for (const icon of icons) {
|
||||
const src = typeof icon?.src === 'string' ? absolute(icon.src, manifestUrl) : ''
|
||||
|
||||
if (!src) {
|
||||
continue
|
||||
}
|
||||
|
||||
const type = typeof icon?.type === 'string' ? icon.type.toLowerCase() : ''
|
||||
const sizes = typeof icon?.sizes === 'string' ? icon.sizes : ''
|
||||
|
||||
candidates.push({ score: scoreFor('', type, sizes), url: src })
|
||||
}
|
||||
|
||||
return candidates
|
||||
}
|
||||
|
||||
/** The well-known paths, on the origin and on its apex — vendors routinely
|
||||
* serve icons from `example.com` and nothing from `api.example.com`. */
|
||||
export function fallbackIconCandidates(pageUrl: string): IconCandidate[] {
|
||||
let url: URL
|
||||
|
||||
try {
|
||||
url = new URL(pageUrl)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
||||
const labels = url.hostname.split('.')
|
||||
const apex = labels.length > 2 ? `${url.protocol}//${labels.slice(-2).join('.')}` : url.origin
|
||||
const origins = [...new Set([url.origin, apex])]
|
||||
|
||||
return origins.flatMap(origin => [
|
||||
{ score: SCORE_GUESS + 2, url: `${origin}/apple-touch-icon.png` },
|
||||
{ score: SCORE_GUESS + 1, url: `${origin}/apple-touch-icon-precomposed.png` },
|
||||
{ score: SCORE_GUESS, url: `${origin}/favicon.ico` },
|
||||
{ score: SCORE_GUESS - 1, url: `${origin}/favicon.png` }
|
||||
])
|
||||
}
|
||||
|
||||
/** Highest-ranked first, one entry per URL, capped so a page declaring
|
||||
* twenty icons can't turn one card into twenty requests. */
|
||||
export function rankCandidates(candidates: IconCandidate[], limit = 6): IconCandidate[] {
|
||||
const best = new Map<string, number>()
|
||||
|
||||
for (const candidate of candidates) {
|
||||
best.set(candidate.url, Math.max(best.get(candidate.url) ?? 0, candidate.score))
|
||||
}
|
||||
|
||||
return [...best.entries()]
|
||||
.map(([url, score]) => ({ score, url }))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, limit)
|
||||
}
|
||||
|
||||
/** Magic bytes, because plenty of servers hand back an icon as
|
||||
* `application/octet-stream` — and an HTML error page as `image/png`. */
|
||||
export function sniffImageMime(bytes: Uint8Array): string {
|
||||
const at = (offset: number, ...signature: number[]) =>
|
||||
signature.every((byte, index) => bytes[offset + index] === byte)
|
||||
|
||||
if (at(0, 0x89, 0x50, 0x4e, 0x47)) {
|
||||
return 'image/png'
|
||||
}
|
||||
|
||||
if (at(0, 0xff, 0xd8, 0xff)) {
|
||||
return 'image/jpeg'
|
||||
}
|
||||
|
||||
if (at(0, 0x47, 0x49, 0x46, 0x38)) {
|
||||
return 'image/gif'
|
||||
}
|
||||
|
||||
if (at(0, 0x00, 0x00, 0x01, 0x00)) {
|
||||
return 'image/x-icon'
|
||||
}
|
||||
|
||||
if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) {
|
||||
return 'image/webp'
|
||||
}
|
||||
|
||||
const head = new TextDecoder().decode(bytes.subarray(0, 1024)).toLowerCase()
|
||||
|
||||
return head.includes('<svg') ? 'image/svg+xml' : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* The mime to trust for these bytes, or '' if they aren't an image.
|
||||
*
|
||||
* The bytes decide, never the header. A blocked request answers 200 with an
|
||||
* HTML challenge page under `content-type: image/png` often enough that
|
||||
* believing the server is how you end up rendering a broken-image box.
|
||||
*/
|
||||
export function imageMime(declared: string, bytes: Uint8Array): string {
|
||||
if (bytes.length < 48) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const sniffed = sniffImageMime(bytes)
|
||||
|
||||
// An SVG that opens with a license comment long enough to push `<svg` past
|
||||
// the sniff window is still an SVG if the server said so.
|
||||
return sniffed || (declared.toLowerCase().includes('svg') ? 'image/svg+xml' : '')
|
||||
}
|
||||
|
||||
export const toDataUrl = (mime: string, bytes: Uint8Array): string =>
|
||||
`data:${mime};base64,${Buffer.from(bytes).toString('base64')}`
|
||||
|
||||
/**
|
||||
* Walk the ladder and return the first real image, as a data URL.
|
||||
*
|
||||
* Data URL rather than a link so the renderer paints without a second
|
||||
* network trip, the icon survives a site going down, and one cached string
|
||||
* covers every surface showing that connector.
|
||||
*/
|
||||
export async function resolveFavicon(pageUrl: string, io: FaviconIo): Promise<string> {
|
||||
if (!isPublicHttpUrl(pageUrl)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const candidates: IconCandidate[] = []
|
||||
const html = await io.fetchText(pageUrl).catch(() => '')
|
||||
|
||||
if (html) {
|
||||
candidates.push(...iconCandidatesFromHtml(html, pageUrl))
|
||||
|
||||
const manifestUrl = manifestUrlFromHtml(html, pageUrl)
|
||||
|
||||
if (manifestUrl) {
|
||||
const manifest = await io.fetchText(manifestUrl).catch(() => '')
|
||||
|
||||
if (manifest) {
|
||||
candidates.push(...iconCandidatesFromManifest(manifest, manifestUrl))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
candidates.push(...fallbackIconCandidates(pageUrl))
|
||||
|
||||
// Only the site's own marks. A third-party icon service would answer for
|
||||
// the hosts that serve nothing readable, but asking it means naming a
|
||||
// connector's host to someone else — so a site that won't show us its icon
|
||||
// simply keeps its monogram.
|
||||
for (const candidate of rankCandidates(candidates)) {
|
||||
const image = await io.fetchImage(candidate.url).catch(() => null)
|
||||
|
||||
if (!image) {
|
||||
continue
|
||||
}
|
||||
|
||||
const mime = imageMime(image.mime, image.bytes)
|
||||
|
||||
if (mime) {
|
||||
return toDataUrl(mime, image.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
@@ -141,6 +141,7 @@ import {
|
||||
terminalScriptExtension,
|
||||
tuiResumeArgs
|
||||
} from './external-terminal'
|
||||
import { type FaviconIo, resolveFavicon } from './favicon'
|
||||
import { findGitBash as _findGitBash } from './find-git-bash'
|
||||
import {
|
||||
installFindShortcut,
|
||||
@@ -3641,6 +3642,8 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {
|
||||
let child
|
||||
|
||||
if (scriptHandoff) {
|
||||
const updateStartedAt = Math.floor(Date.now() / 1000)
|
||||
|
||||
// A bare detached+hidden powershell spawn silently dies before -File
|
||||
// processing (console-subsystem init failure — see
|
||||
// wrapHandoffForDetachedConsole). Route through `cmd start` so the
|
||||
@@ -3664,6 +3667,7 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {
|
||||
env: {
|
||||
...process.env,
|
||||
HERMES_HOME,
|
||||
HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
|
||||
PATH: pathWithHermesManagedNode(venvBin)
|
||||
},
|
||||
detached: true,
|
||||
@@ -3678,7 +3682,7 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {
|
||||
// The `hermes update` child adopts the SCRIPT's claim via
|
||||
// update_lock.py's process-ancestry rule; no mtime heuristics needed.
|
||||
if (Number.isInteger(child.pid)) {
|
||||
writeUpdateMarker(HERMES_HOME, child.pid)
|
||||
writeUpdateMarker(HERMES_HOME, child.pid, { startedAt: updateStartedAt })
|
||||
}
|
||||
|
||||
rememberLog(
|
||||
@@ -4021,6 +4025,7 @@ async function applyUpdatesPosixHandoff(opts: any) {
|
||||
}
|
||||
|
||||
const args = [...handoff.args, '--install-root', updateRoot, '--branch', branch, '--desktop-pid', String(process.pid)]
|
||||
const updateStartedAt = Math.floor(Date.now() / 1000)
|
||||
|
||||
// Relaunch target: the running .app bundle on mac (script swaps the
|
||||
// rebuilt bundle over it), the running binary elsewhere. The script's gate
|
||||
@@ -4053,6 +4058,7 @@ async function applyUpdatesPosixHandoff(opts: any) {
|
||||
env: {
|
||||
...process.env,
|
||||
HERMES_HOME,
|
||||
HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
|
||||
PATH: pathWithHermesManagedNode(path.join(updateRoot, 'venv', 'bin'))
|
||||
},
|
||||
detached: true,
|
||||
@@ -4063,7 +4069,7 @@ async function applyUpdatesPosixHandoff(opts: any) {
|
||||
// until the script claims the marker with its own pid as step 0. If the
|
||||
// script never starts, the dead pid reads as stale and self-deletes.
|
||||
if (Number.isInteger(child.pid)) {
|
||||
writeUpdateMarker(HERMES_HOME, child.pid)
|
||||
writeUpdateMarker(HERMES_HOME, child.pid, { startedAt: updateStartedAt })
|
||||
}
|
||||
|
||||
rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (branch ${branch}); quitting to hand off`)
|
||||
@@ -5369,6 +5375,159 @@ function fetchLinkTitle(rawUrl) {
|
||||
return pending
|
||||
}
|
||||
|
||||
// ─── Favicon resolution ──────────────────────────────────────────────────────
|
||||
// The ladder itself is electron/favicon.ts; this is its I/O, its cache, and
|
||||
// the one rule that belongs to the app rather than the algorithm: one icon
|
||||
// per host. A connector's mark doesn't vary by path, and hosting the cache on
|
||||
// the host key means Linear's docs page and Linear's MCP endpoint cost one
|
||||
// lookup between them.
|
||||
|
||||
const FAVICON_CACHE_PATH = path.join(app.getPath('userData'), 'favicon-cache.json')
|
||||
const FAVICON_CACHE_LIMIT = 400
|
||||
const FAVICON_TTL_MS = 30 * 24 * 60 * 60 * 1000
|
||||
// A miss is cheap to re-check and expensive to be wrong about (a site that
|
||||
// was behind a captcha yesterday has a logo today), so it expires fast.
|
||||
const FAVICON_MISS_TTL_MS = 12 * 60 * 60 * 1000
|
||||
const FAVICON_TIMEOUT_MS = 6000
|
||||
const FAVICON_MAX_BYTES = 256 * 1024
|
||||
const FAVICON_WRITE_DEBOUNCE_MS = 3000
|
||||
|
||||
let faviconCache: Map<string, { at: number; icon: string }> | null = null
|
||||
let faviconWriteTimer: null | ReturnType<typeof setTimeout> = null
|
||||
const faviconInflight = new Map<string, Promise<string>>()
|
||||
|
||||
function faviconCacheKey(rawUrl: string): string {
|
||||
try {
|
||||
return new URL(rawUrl).hostname.replace(/^www\./i, '').toLowerCase()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function loadFaviconCache(): Map<string, { at: number; icon: string }> {
|
||||
if (faviconCache) {
|
||||
return faviconCache
|
||||
}
|
||||
|
||||
faviconCache = new Map()
|
||||
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(FAVICON_CACHE_PATH, 'utf8'))
|
||||
|
||||
for (const [host, entry] of Object.entries(raw?.icons ?? {})) {
|
||||
const at = Number((entry as { at?: number })?.at)
|
||||
const icon = String((entry as { icon?: string })?.icon ?? '')
|
||||
|
||||
if (Number.isFinite(at) && Date.now() - at < (icon ? FAVICON_TTL_MS : FAVICON_MISS_TTL_MS)) {
|
||||
faviconCache.set(host, { at, icon })
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// No cache yet, or it's unreadable — resolving again is the whole cost.
|
||||
}
|
||||
|
||||
return faviconCache
|
||||
}
|
||||
|
||||
function saveFaviconCacheSoon() {
|
||||
if (faviconWriteTimer) {
|
||||
return
|
||||
}
|
||||
|
||||
faviconWriteTimer = setTimeout(() => {
|
||||
faviconWriteTimer = null
|
||||
|
||||
try {
|
||||
const icons = Object.fromEntries(loadFaviconCache())
|
||||
|
||||
fs.writeFileSync(FAVICON_CACHE_PATH, JSON.stringify({ icons }), 'utf8')
|
||||
} catch {
|
||||
// Cache is an optimization; failing to persist it costs one refetch.
|
||||
}
|
||||
}, FAVICON_WRITE_DEBOUNCE_MS)
|
||||
|
||||
faviconWriteTimer.unref?.()
|
||||
}
|
||||
|
||||
async function faviconFetch(url: string, accept: string) {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), FAVICON_TIMEOUT_MS)
|
||||
|
||||
try {
|
||||
return await electronNet.fetch(url, {
|
||||
// Same browser-shaped identity the title fetcher uses: a plain Electron
|
||||
// UA gets a challenge page from anything behind a bot wall.
|
||||
headers: { Accept: accept, 'Accept-Language': 'en-US,en;q=0.7', 'User-Agent': TITLE_USER_AGENT },
|
||||
redirect: 'follow',
|
||||
signal: controller.signal
|
||||
})
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
const faviconIo: FaviconIo = {
|
||||
fetchImage: async url => {
|
||||
const response = await faviconFetch(url, 'image/avif,image/webp,image/svg+xml,image/*;q=0.8,*/*;q=0.5')
|
||||
|
||||
if (!response.ok) {
|
||||
return null
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer()
|
||||
|
||||
if (buffer.byteLength === 0 || buffer.byteLength > FAVICON_MAX_BYTES) {
|
||||
return null
|
||||
}
|
||||
|
||||
return { bytes: new Uint8Array(buffer), mime: response.headers.get('content-type') ?? '' }
|
||||
},
|
||||
fetchText: async url => {
|
||||
const response = await faviconFetch(url, 'text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.5')
|
||||
|
||||
return response.ok ? (await response.text()).slice(0, TITLE_BYTE_BUDGET * 2) : ''
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFaviconCached(rawUrl: string): Promise<string> {
|
||||
const key = faviconCacheKey(String(rawUrl || '').trim())
|
||||
|
||||
if (!key) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
|
||||
const cache = loadFaviconCache()
|
||||
const hit = cache.get(key)
|
||||
|
||||
if (hit && Date.now() - hit.at < (hit.icon ? FAVICON_TTL_MS : FAVICON_MISS_TTL_MS)) {
|
||||
return Promise.resolve(hit.icon)
|
||||
}
|
||||
|
||||
const inflight = faviconInflight.get(key)
|
||||
|
||||
if (inflight) {
|
||||
return inflight
|
||||
}
|
||||
|
||||
const pending = resolveFavicon(rawUrl, faviconIo)
|
||||
.catch(() => '')
|
||||
.then(icon => {
|
||||
if (cache.size >= FAVICON_CACHE_LIMIT) {
|
||||
cache.delete(cache.keys().next().value)
|
||||
}
|
||||
|
||||
cache.set(key, { at: Date.now(), icon })
|
||||
saveFaviconCacheSoon()
|
||||
faviconInflight.delete(key)
|
||||
|
||||
return icon
|
||||
})
|
||||
|
||||
faviconInflight.set(key, pending)
|
||||
|
||||
return pending
|
||||
}
|
||||
|
||||
async function resourceBufferFromUrl(rawUrl) {
|
||||
if (!rawUrl) {
|
||||
throw new Error('Missing URL')
|
||||
@@ -14323,6 +14482,8 @@ ipcMain.handle('hermes:setting:defaultProjectDir:pick', async () => {
|
||||
|
||||
ipcMain.handle('hermes:fetchLinkTitle', (_event, url) => fetchLinkTitle(url))
|
||||
|
||||
ipcMain.handle('hermes:resolveFavicon', (_event, url) => resolveFaviconCached(url))
|
||||
|
||||
ipcMain.handle('hermes:logs:reveal', async () => {
|
||||
try {
|
||||
await fs.promises.mkdir(path.dirname(DESKTOP_LOG_PATH), { recursive: true })
|
||||
|
||||
@@ -236,6 +236,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
|
||||
openPreviewInBrowser: url => ipcRenderer.invoke('hermes:openPreviewInBrowser', url),
|
||||
reachPreviewUrl: url => ipcRenderer.invoke('hermes:preview:reach', url),
|
||||
fetchLinkTitle: url => ipcRenderer.invoke('hermes:fetchLinkTitle', url),
|
||||
resolveFavicon: url => ipcRenderer.invoke('hermes:resolveFavicon', url),
|
||||
sanitizeWorkspaceCwd: cwd => ipcRenderer.invoke('hermes:workspace:sanitize', cwd),
|
||||
settings: {
|
||||
getDefaultProjectDir: () => ipcRenderer.invoke('hermes:setting:defaultProjectDir:get'),
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { test } from 'vitest'
|
||||
|
||||
const REPO_ROOT = path.resolve(__dirname, '..', '..', '..')
|
||||
const POSIX_SCRIPT = path.join(REPO_ROOT, 'scripts', 'desktop-update', 'posix.sh')
|
||||
const WINDOWS_SCRIPT = path.join(REPO_ROOT, 'scripts', 'desktop-update', 'windows.ps1')
|
||||
|
||||
function sandbox(tag: string) {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), `hermes-handoff-marker-${tag}-`))
|
||||
const installRoot = path.join(home, 'hermes-agent')
|
||||
fs.mkdirSync(installRoot)
|
||||
|
||||
return { home, installRoot }
|
||||
}
|
||||
|
||||
function markerStartedAt(home: string): number {
|
||||
const [, startedAt] = fs.readFileSync(path.join(home, '.hermes-update-in-progress'), 'utf8').split('\n')
|
||||
|
||||
return Number.parseInt(startedAt, 10)
|
||||
}
|
||||
|
||||
function runPosix(installRoot: string, startedAt?: string) {
|
||||
const env = { ...process.env }
|
||||
|
||||
if (startedAt === undefined) {
|
||||
delete env.HERMES_UPDATE_STARTED_AT
|
||||
} else {
|
||||
env.HERMES_UPDATE_STARTED_AT = startedAt
|
||||
}
|
||||
|
||||
return spawnSync('/bin/bash', [POSIX_SCRIPT, '--daemonized', '--install-root', installRoot, '--self-test-marker'], {
|
||||
env,
|
||||
encoding: 'utf8'
|
||||
})
|
||||
}
|
||||
|
||||
function runWindows(installRoot: string, startedAt?: string) {
|
||||
const env = { ...process.env }
|
||||
|
||||
if (startedAt === undefined) {
|
||||
delete env.HERMES_UPDATE_STARTED_AT
|
||||
} else {
|
||||
env.HERMES_UPDATE_STARTED_AT = startedAt
|
||||
}
|
||||
|
||||
return spawnSync(
|
||||
'powershell.exe',
|
||||
[
|
||||
'-NoProfile',
|
||||
'-ExecutionPolicy',
|
||||
'Bypass',
|
||||
'-File',
|
||||
WINDOWS_SCRIPT,
|
||||
'-InstallRoot',
|
||||
installRoot,
|
||||
'-NoUi',
|
||||
'-NoMarkerCleanup',
|
||||
'-SelfTestMarker'
|
||||
],
|
||||
{ env, encoding: 'utf8' }
|
||||
)
|
||||
}
|
||||
|
||||
function assertScriptHandoff(run: (installRoot: string, startedAt?: string) => ReturnType<typeof spawnSync>) {
|
||||
const preserved = sandbox('preserved')
|
||||
const acquiredAt = Math.floor(Date.now() / 1000) - 300
|
||||
const preservedResult = run(preserved.installRoot, String(acquiredAt))
|
||||
|
||||
assert.equal(preservedResult.status, 0, String(preservedResult.stderr || preservedResult.stdout))
|
||||
assert.equal(markerStartedAt(preserved.home), acquiredAt, 'the script must preserve the Desktop acquisition time')
|
||||
|
||||
const refreshed = sandbox('refreshed')
|
||||
fs.writeFileSync(path.join(refreshed.home, '.hermes-update-in-progress'), '999999\n1\n')
|
||||
const before = Math.floor(Date.now() / 1000)
|
||||
const refreshedResult = run(refreshed.installRoot, 'malformed')
|
||||
const after = Math.floor(Date.now() / 1000)
|
||||
|
||||
assert.equal(refreshedResult.status, 0, String(refreshedResult.stderr || refreshedResult.stdout))
|
||||
assert.ok(
|
||||
markerStartedAt(refreshed.home) >= before && markerStartedAt(refreshed.home) <= after,
|
||||
'an invalid hand-off timestamp must start a fresh claim'
|
||||
)
|
||||
|
||||
const oversized = sandbox('oversized')
|
||||
const oversizedBefore = Math.floor(Date.now() / 1000)
|
||||
const oversizedResult = run(oversized.installRoot, '99999999999999999999')
|
||||
const oversizedAfter = Math.floor(Date.now() / 1000)
|
||||
|
||||
assert.equal(oversizedResult.status, 0, String(oversizedResult.stderr || oversizedResult.stdout))
|
||||
assert.ok(
|
||||
markerStartedAt(oversized.home) >= oversizedBefore && markerStartedAt(oversized.home) <= oversizedAfter,
|
||||
'an oversized hand-off timestamp must start a fresh claim'
|
||||
)
|
||||
}
|
||||
|
||||
test.skipIf(process.platform === 'win32')('POSIX hand-off preserves the Desktop marker acquisition time', () => {
|
||||
assertScriptHandoff(runPosix)
|
||||
})
|
||||
|
||||
test.skipIf(process.platform !== 'win32')('PowerShell hand-off preserves the Desktop marker acquisition time', () => {
|
||||
assertScriptHandoff(runWindows)
|
||||
})
|
||||
@@ -115,6 +115,30 @@ test('writeUpdateMarker writes a marker that readLiveUpdateMarker accepts', () =
|
||||
assert.ok(fs.existsSync(markerPath(home)), 'marker file should exist after write')
|
||||
})
|
||||
|
||||
test('writeUpdateMarker preserves a live holder age across pid hand-off', () => {
|
||||
const home = tmpHome('write-handoff-age')
|
||||
const now = 1_000_000_000_000
|
||||
const startedAt = Math.floor(now / 1000) - 300
|
||||
|
||||
writeMarker(home, 1010, startedAt)
|
||||
writeUpdateMarker(home, 2020, { kill: ALIVE, now: () => now })
|
||||
|
||||
const [pidLine, startedLine] = fs.readFileSync(markerPath(home), 'utf8').split('\n')
|
||||
assert.equal(Number.parseInt(pidLine, 10), 2020, 'the hand-off records the new owner')
|
||||
assert.equal(Number.parseInt(startedLine, 10), startedAt, 'the holder age must not restart during hand-off')
|
||||
})
|
||||
|
||||
test('writeUpdateMarker uses the acquisition time passed to a detached script', () => {
|
||||
const home = tmpHome('write-script-acquired-at')
|
||||
const now = 1_000_000_000_000
|
||||
const startedAt = Math.floor(now / 1000) - 300
|
||||
|
||||
writeUpdateMarker(home, 2020, { now: () => now, startedAt })
|
||||
|
||||
const [, startedLine] = fs.readFileSync(markerPath(home), 'utf8').split('\n')
|
||||
assert.equal(Number.parseInt(startedLine, 10), startedAt)
|
||||
})
|
||||
|
||||
test('writeUpdateMarker is best-effort (no throw on bad path)', () => {
|
||||
// A non-existent directory should not throw.
|
||||
const badHome = path.join(os.tmpdir(), 'hermes-marker-nonexistent-' + Date.now())
|
||||
|
||||
@@ -119,18 +119,41 @@ export function readLiveUpdateMarker(
|
||||
*
|
||||
* Fix: the desktop writes the marker itself, using the spawned updater's
|
||||
* PID, immediately after `spawn()`. The updater's `UpdateMarkerGuard` will
|
||||
* later overwrite it with its own PID — that's fine, the marker body is
|
||||
* the same format and `readLiveUpdateMarker` only cares that *some* live
|
||||
* pid owns it. When the updater finishes it deletes the marker as before.
|
||||
* later adopt it or another hand-off stage may replace the PID. A live
|
||||
* holder's original timestamp is preserved across those transfers so retries
|
||||
* cannot keep resetting the 20-minute stale ceiling. When the updater finishes
|
||||
* it deletes the marker as before.
|
||||
* If the updater never starts (spawn failure) the marker still contains a
|
||||
* real PID, so `readLiveUpdateMarker` will self-heal once that PID exits.
|
||||
*/
|
||||
export function writeUpdateMarker(hermesHome, pid, { now = Date.now } = {}) {
|
||||
export function writeUpdateMarker(
|
||||
hermesHome,
|
||||
pid,
|
||||
{
|
||||
kill,
|
||||
now = Date.now,
|
||||
maxAgeMs = UPDATE_MARKER_MAX_AGE_MS,
|
||||
startedAt
|
||||
}: {
|
||||
now?: () => number
|
||||
maxAgeMs?: number
|
||||
kill?: typeof process.kill
|
||||
startedAt?: number
|
||||
} = {}
|
||||
) {
|
||||
const file = markerPath(hermesHome)
|
||||
const startedAt = Math.floor(now() / 1000)
|
||||
const nowMs = now()
|
||||
const owner = readLiveUpdateMarker(hermesHome, { kill, maxAgeMs, now: () => nowMs })
|
||||
|
||||
const acquiredAt =
|
||||
typeof startedAt === 'number' && Number.isInteger(startedAt)
|
||||
? startedAt
|
||||
: owner
|
||||
? Math.floor((nowMs - owner.ageMs) / 1000)
|
||||
: Math.floor(nowMs / 1000)
|
||||
|
||||
try {
|
||||
fs.writeFileSync(file, `${pid}\n${startedAt}\n`, 'utf8')
|
||||
fs.writeFileSync(file, `${pid}\n${acquiredAt}\n`, 'utf8')
|
||||
} catch {
|
||||
// Best-effort: if we can't write the marker, proceed anyway. The
|
||||
// updater will write its own when it reaches run_update.
|
||||
|
||||
@@ -23,9 +23,19 @@ export function SidebarSectionMeta({ children }: { children: React.ReactNode })
|
||||
// Height lives ONLY on SidebarRowShell (min-h-[1.625rem]). Inset children
|
||||
// stretch to fill the cell and center content internally — never items-center
|
||||
// on the shell grid, or short clusters (projects) float 1–2px off sessions.
|
||||
//
|
||||
// `rowPadX` is the BODY's padding: the lead's inset, plus the gap the label
|
||||
// keeps from the actions column, both inside the row's click target.
|
||||
// `rowPadTrail` is the row's own trailing inset and belongs to the SHELL — the
|
||||
// only box containing both the actions column AND the card's in-body cluster,
|
||||
// so one class insets every trailing thing a row can render. Owned anywhere
|
||||
// else, the age / chips / kebab sit flush on the border box, which is exactly
|
||||
// where a working row paints its arc (`.arc-row` has zero standoff) — the ring
|
||||
// ran through the text.
|
||||
|
||||
const rowMinH = 'min-h-[1.625rem]'
|
||||
const rowPadX = 'pl-2 pr-1'
|
||||
const rowPadX = 'pl-2 pr-2'
|
||||
const rowPadTrail = 'pr-2'
|
||||
const rowGap = 'gap-1.5'
|
||||
const rowLead = 'grid size-3.5 shrink-0 place-items-center'
|
||||
const rowInset = cn(rowPadX, rowGap, 'flex h-full min-w-0 items-center self-stretch py-0.5')
|
||||
@@ -71,9 +81,11 @@ export function SidebarDateDivider({
|
||||
)
|
||||
}
|
||||
|
||||
/** Outer grid — sole owner of row height. The trailing `actions` slot is
|
||||
* marked `data-row-actions` so a row-wide drag gesture can exclude it with
|
||||
* one selector: it holds real controls, never grab surface. */
|
||||
/** Outer grid — sole owner of row height and of the trailing inset. The
|
||||
* `actions` slot is marked `data-row-actions` so a row-wide drag gesture can
|
||||
* exclude it with one selector: it holds real controls, never grab surface.
|
||||
* It stretches so that exclusion covers the column, not just its tallest
|
||||
* control. */
|
||||
export function SidebarRowShell({
|
||||
actions,
|
||||
actionsClassName,
|
||||
@@ -82,10 +94,13 @@ export function SidebarRowShell({
|
||||
...props
|
||||
}: React.ComponentProps<'div'> & { actions?: React.ReactNode; actionsClassName?: string }) {
|
||||
return (
|
||||
<div className={cn(rowMinH, 'grid grid-cols-[minmax(0,1fr)_auto] items-stretch rounded-md', className)} {...props}>
|
||||
<div
|
||||
className={cn(rowMinH, rowPadTrail, 'grid grid-cols-[minmax(0,1fr)_auto] items-stretch rounded-md', className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{actions ? (
|
||||
<div className={cn('flex shrink-0 items-center self-center', actionsClassName)} data-row-actions>
|
||||
<div className={cn('flex shrink-0 items-center self-stretch', actionsClassName)} data-row-actions>
|
||||
{actions}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -23,6 +23,7 @@ import type { CronJob } from '@/types/hermes'
|
||||
import { jobState, jobTitle, STATE_DOT } from '../../cron/job-state'
|
||||
import { SidebarPanelLabel } from '../../shell/sidebar-label'
|
||||
|
||||
import { SidebarRowBody, SidebarRowLabel, SidebarRowLead, SidebarRowShell } from './chrome'
|
||||
import { SidebarLoadMoreRow } from './load-more-row'
|
||||
|
||||
const INACTIVE_STATES = new Set(['completed', 'disabled', 'error', 'paused'])
|
||||
@@ -304,21 +305,57 @@ function CronJobSidebarRow({
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* The shared row chrome, not a copy of it: a cron job and a session sit
|
||||
in the same list, so they line up only if one place owns the geometry. */}
|
||||
<ActionsContextMenu ariaLabel={c.actionsTitle} contentClassName="w-44" items={items}>
|
||||
<div className="group/cron relative grid min-h-[1.625rem] grid-cols-[minmax(0,1fr)_auto] items-center rounded-md hover:bg-(--chrome-action-hover)">
|
||||
{/* Lead with the dot in the same w-3.5 cell + pl-2 the session rows use
|
||||
so the cron dots line up with the sessions above; the caret sits next
|
||||
to the label (matching the other sidebar disclosures) and the whole
|
||||
label area toggles the run peek. */}
|
||||
<SidebarRowShell
|
||||
actions={
|
||||
/* Trailing cluster: countdown by default, quick actions on hover. */
|
||||
<div className="flex items-center gap-0.5">
|
||||
<span className="text-[0.6875rem] text-(--ui-text-tertiary) tabular-nums group-hover/cron:hidden">
|
||||
{meta}
|
||||
</span>
|
||||
<div className="hidden items-center gap-0.5 group-hover/cron:flex">
|
||||
<Tip label={c.triggerNow}>
|
||||
<button
|
||||
aria-label={c.triggerNow}
|
||||
className="grid size-5 place-items-center rounded-sm text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground disabled:cursor-wait disabled:opacity-60"
|
||||
disabled={busy}
|
||||
onClick={onTrigger}
|
||||
type="button"
|
||||
>
|
||||
{busy ? (
|
||||
<GlyphSpinner ariaLabel={c.triggerNow} className="text-[0.75rem]" />
|
||||
) : (
|
||||
<Codicon name="zap" size="0.75rem" />
|
||||
)}
|
||||
</button>
|
||||
</Tip>
|
||||
<Tip label={c.manage}>
|
||||
<button
|
||||
aria-label={c.manage}
|
||||
className="grid size-5 place-items-center rounded-sm text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground"
|
||||
onClick={onManage}
|
||||
type="button"
|
||||
>
|
||||
<Codicon name="watch" size="0.75rem" />
|
||||
</button>
|
||||
</Tip>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
className="group/cron relative hover:bg-(--chrome-action-hover)"
|
||||
>
|
||||
{/* The caret sits next to the label (matching the other sidebar
|
||||
disclosures) and the whole label area toggles the run peek. */}
|
||||
<Tip label={label}>
|
||||
<button
|
||||
<SidebarRowBody
|
||||
aria-expanded={expanded}
|
||||
aria-label={expanded ? c.hideRuns : c.showRuns}
|
||||
className="flex min-w-0 items-center gap-1.5 bg-transparent py-0.5 pl-2 pr-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||
className="focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||
onClick={onTogglePeek}
|
||||
type="button"
|
||||
>
|
||||
<span className="grid w-3.5 shrink-0 place-items-center">
|
||||
<SidebarRowLead>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
@@ -327,10 +364,8 @@ function CronJobSidebarRow({
|
||||
state === 'running' && 'size-1.5 animate-pulse'
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
<span className="min-w-0 truncate text-[0.8125rem] text-(--ui-text-secondary) group-hover/cron:text-foreground">
|
||||
{label}
|
||||
</span>
|
||||
</SidebarRowLead>
|
||||
<SidebarRowLabel className="group-hover/cron:text-foreground">{label}</SidebarRowLabel>
|
||||
<DisclosureCaret
|
||||
className={cn(
|
||||
'shrink-0 text-(--ui-text-tertiary) transition',
|
||||
@@ -338,42 +373,9 @@ function CronJobSidebarRow({
|
||||
)}
|
||||
open={expanded}
|
||||
/>
|
||||
</button>
|
||||
</SidebarRowBody>
|
||||
</Tip>
|
||||
{/* Trailing cluster: countdown by default, quick actions on hover. */}
|
||||
<div className="flex items-center gap-0.5 justify-self-end pr-1">
|
||||
<span className="text-[0.6875rem] text-(--ui-text-tertiary) tabular-nums group-hover/cron:hidden">
|
||||
{meta}
|
||||
</span>
|
||||
<div className="hidden items-center gap-0.5 group-hover/cron:flex">
|
||||
<Tip label={c.triggerNow}>
|
||||
<button
|
||||
aria-label={c.triggerNow}
|
||||
className="grid size-5 place-items-center rounded-sm text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground disabled:cursor-wait disabled:opacity-60"
|
||||
disabled={busy}
|
||||
onClick={onTrigger}
|
||||
type="button"
|
||||
>
|
||||
{busy ? (
|
||||
<GlyphSpinner ariaLabel={c.triggerNow} className="text-[0.75rem]" />
|
||||
) : (
|
||||
<Codicon name="zap" size="0.75rem" />
|
||||
)}
|
||||
</button>
|
||||
</Tip>
|
||||
<Tip label={c.manage}>
|
||||
<button
|
||||
aria-label={c.manage}
|
||||
className="grid size-5 place-items-center rounded-sm text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground"
|
||||
onClick={onManage}
|
||||
type="button"
|
||||
>
|
||||
<Codicon name="watch" size="0.75rem" />
|
||||
</button>
|
||||
</Tip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarRowShell>
|
||||
</ActionsContextMenu>
|
||||
{expanded && <CronJobSidebarRuns jobId={job.id} onOpenRun={onOpenRun} />}
|
||||
</div>
|
||||
|
||||
@@ -11,7 +11,9 @@ interface SidebarLoadMoreRowProps {
|
||||
|
||||
// Compact "load more" affordance shared by recents, messaging, and cron. Kept
|
||||
// intentionally identical to workspace "show more" controls (ellipsis button)
|
||||
// so pagination reads as one interaction everywhere.
|
||||
// so pagination reads as one interaction everywhere. It hangs off the list
|
||||
// instead of sitting in a row, so it repeats the row's trailing inset
|
||||
// (SidebarRowShell's `pr-2`) to stay on the edge the rows stop at.
|
||||
export function SidebarLoadMoreRow({ step, onClick, loading = false }: SidebarLoadMoreRowProps) {
|
||||
const { t } = useI18n()
|
||||
const label = loading ? t.sidebar.loading : step > 0 ? t.sidebar.loadCount(step) : t.sidebar.loadMore
|
||||
@@ -20,7 +22,7 @@ export function SidebarLoadMoreRow({ step, onClick, loading = false }: SidebarLo
|
||||
<Tip label={label}>
|
||||
<button
|
||||
aria-label={label}
|
||||
className="ml-auto grid size-5 place-items-center rounded-sm bg-transparent text-(--ui-text-tertiary) transition-colors hover:bg-(--ui-control-hover-background) hover:text-foreground disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent disabled:hover:text-(--ui-text-tertiary)"
|
||||
className="mr-2 ml-auto grid size-5 place-items-center rounded-sm bg-transparent text-(--ui-text-tertiary) transition-colors hover:bg-(--ui-control-hover-background) hover:text-foreground disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent disabled:hover:text-(--ui-text-tertiary)"
|
||||
disabled={loading}
|
||||
onClick={onClick}
|
||||
type="button"
|
||||
|
||||
@@ -48,6 +48,8 @@ export function WorkspaceAddButton({ label, onClick }: { label: string; onClick:
|
||||
}
|
||||
|
||||
// Reveals the next page of already-loaded rows within a workspace/worktree.
|
||||
// Hangs off the lane instead of sitting in a row, so it repeats the row's
|
||||
// trailing inset (SidebarRowShell's `pr-2`) to stay on the edge the rows stop at.
|
||||
export function WorkspaceShowMoreButton({
|
||||
count,
|
||||
label,
|
||||
@@ -64,7 +66,7 @@ export function WorkspaceShowMoreButton({
|
||||
<Tip label={text}>
|
||||
<button
|
||||
aria-label={text}
|
||||
className="ml-auto grid size-5 place-items-center rounded-sm bg-transparent text-(--ui-text-tertiary) transition-colors hover:bg-(--ui-control-hover-background) hover:text-foreground"
|
||||
className="mr-2 ml-auto grid size-5 place-items-center rounded-sm bg-transparent text-(--ui-text-tertiary) transition-colors hover:bg-(--ui-control-hover-background) hover:text-foreground"
|
||||
onClick={onClick}
|
||||
type="button"
|
||||
>
|
||||
|
||||
@@ -4,19 +4,22 @@ import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useI18n } from '@/i18n'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { SidebarRowCluster, SidebarRowShell, SidebarRowStack } from './chrome'
|
||||
|
||||
// Stands in for session rows, so it borrows their chrome instead of copying
|
||||
// the grid — a placeholder on a different edge than the rows it resolves into
|
||||
// makes the list step sideways on load.
|
||||
export function SidebarSessionSkeletons() {
|
||||
return (
|
||||
<div aria-hidden="true" className="grid gap-px">
|
||||
<SidebarRowStack aria-hidden="true">
|
||||
{['w-32', 'w-40', 'w-28', 'w-36', 'w-24'].map((width, i) => (
|
||||
<div
|
||||
className="grid min-h-[1.625rem] grid-cols-[minmax(0,1fr)_1.375rem] items-center rounded-md pl-2"
|
||||
key={`${width}-${i}`}
|
||||
>
|
||||
<Skeleton className={cn('h-3 rounded-sm', width)} />
|
||||
<Skeleton className="mx-auto size-3.5 rounded-sm opacity-60" />
|
||||
</div>
|
||||
<SidebarRowShell actions={<Skeleton className="size-3.5 rounded-sm opacity-60" />} key={`${width}-${i}`}>
|
||||
<SidebarRowCluster>
|
||||
<Skeleton className={cn('h-3 rounded-sm', width)} />
|
||||
</SidebarRowCluster>
|
||||
</SidebarRowShell>
|
||||
))}
|
||||
</div>
|
||||
</SidebarRowStack>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -405,9 +405,13 @@ function SidebarSessionRowImpl({
|
||||
<SidebarRowBody
|
||||
// Every trailing figure lives in the actions slot, which the row
|
||||
// measures — so the title needs a gap from it and nothing else. Hover
|
||||
// changes what you can see in that slot, never how wide it is.
|
||||
// changes what you can see in that slot, never how wide it is. The
|
||||
// card has no such column to clear (its cluster is INSIDE the body,
|
||||
// ending at the shell's own trailing inset), and keeping the gap
|
||||
// would pull the header in past every line below it.
|
||||
className={cn(
|
||||
'z-0 pr-2',
|
||||
'z-0',
|
||||
card && 'pr-0',
|
||||
branchStem && 'pl-3.5',
|
||||
// The card is a grid with ONE spacing knob: --card-gap. Every row
|
||||
// gap is gap-y-(--card-gap); the title/preview group opts out
|
||||
|
||||
@@ -15,8 +15,8 @@ import {
|
||||
import type { ComponentPropsWithoutRef, ComponentType, SVGProps } from 'react'
|
||||
import { forwardRef, memo } from 'react'
|
||||
|
||||
import { AvatarChip } from '@/components/ui/avatar-chip'
|
||||
import { Globe, Link as LinkIcon, MessageSquareText } from '@/lib/icons'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Photon brand icon — three diagonal rounded bars (the Photon logo mark).
|
||||
@@ -84,48 +84,18 @@ interface PlatformAvatarProps extends Omit<ComponentPropsWithoutRef<'span'>, 'ch
|
||||
// silently — the tooltip renders but never opens (#67500).
|
||||
export const PlatformAvatar = memo(
|
||||
forwardRef<HTMLSpanElement, PlatformAvatarProps>(function PlatformAvatar(
|
||||
{ className, platformId, platformName, style, ...rest },
|
||||
{ className, platformId, platformName, ...rest },
|
||||
ref
|
||||
) {
|
||||
const spec = PLATFORM_ICONS[platformId]
|
||||
|
||||
const baseClass = cn(
|
||||
'inline-grid size-6 shrink-0 place-items-center rounded-md text-[length:var(--conversation-caption-font-size)] font-medium',
|
||||
className
|
||||
)
|
||||
|
||||
if (!spec) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(baseClass, 'bg-(--ui-bg-tertiary) text-(--ui-text-tertiary)')}
|
||||
ref={ref}
|
||||
style={style}
|
||||
{...rest}
|
||||
>
|
||||
{platformName.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const { Icon, color } = spec
|
||||
|
||||
return (
|
||||
<span
|
||||
<AvatarChip
|
||||
aria-hidden="true"
|
||||
className={baseClass}
|
||||
brand={PLATFORM_ICONS[platformId]}
|
||||
className={className}
|
||||
name={platformName}
|
||||
ref={ref}
|
||||
style={{
|
||||
// 16% tint of the brand color so the glyph reads against any surface
|
||||
// without the avatar dominating the row.
|
||||
backgroundColor: `color-mix(in srgb, ${color} 16%, transparent)`,
|
||||
color,
|
||||
...style
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
{Icon ? <Icon className="size-3.5" /> : spec.monogram || platformName.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
/>
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { type CodeEditorApi } from '@/components/chat/code-editor'
|
||||
import { JsonDocumentEditor } from '@/components/chat/json-document-editor'
|
||||
import { LogTail } from '@/components/chat/log-tail'
|
||||
import { PageLoader } from '@/components/page-loader'
|
||||
import { AvatarChip } from '@/components/ui/avatar-chip'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Codicon } from '@/components/ui/codicon'
|
||||
import { ErrorBanner } from '@/components/ui/error-state'
|
||||
@@ -33,7 +34,7 @@ import {
|
||||
} from '@/hermes'
|
||||
import { type Translations, useI18n } from '@/i18n'
|
||||
import { compactNumber } from '@/lib/format'
|
||||
import { brandFor, brandGlyphStyle } from '@/lib/mcp-brands'
|
||||
import { brandFor } from '@/lib/mcp-brands'
|
||||
import { estimateServerTokens, serverUsageCount } from '@/lib/mcp-cost'
|
||||
import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'
|
||||
import { type McpImportEntry, parseMcpImport } from '@/lib/mcp-import'
|
||||
@@ -1757,41 +1758,28 @@ function McpLogs({
|
||||
// Avatars + list rows
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Brand glyphs for well-known MCP providers, exactly the Messaging avatar
|
||||
// treatment (simpleicons on a 16% brand tint) — shared with the composer
|
||||
// suggestion pills and inline setup card via lib/mcp-brands. Unknown servers
|
||||
// fall back to the same letter monogram Messaging uses.
|
||||
|
||||
// PlatformAvatar (messaging), copied 1:1 — same size, radius, type scale, and
|
||||
// brand-tint treatment — plus a status dot overlay. Identity ladder: curated
|
||||
// brand glyph → letter monogram. We deliberately do NOT fetch remote favicons:
|
||||
// a configured MCP URL can be a private/internal host, and hitting Google's
|
||||
// favicon service for it would leak that hostname off-box.
|
||||
// The shared identity chip (`ui/avatar-chip`) plus a status dot. Identity
|
||||
// ladder: curated brand glyph (lib/mcp-brands, shared with the composer
|
||||
// suggestion pills and the inline setup card) → letter monogram. Nothing here
|
||||
// reaches the network for a mark: a configured MCP URL can be a private host,
|
||||
// and the connector card's favicon rung only ever reads a public site's own
|
||||
// markup, never a third-party icon service.
|
||||
function McpAvatar({ className, name, status }: { className?: string; name: string; status: ServerStatus }) {
|
||||
const brand = brandFor(name)
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'relative inline-grid size-6 shrink-0 place-items-center rounded-md text-[length:var(--conversation-caption-font-size)] font-medium',
|
||||
!brand && 'bg-(--ui-bg-tertiary) text-(--ui-text-tertiary)',
|
||||
className
|
||||
)}
|
||||
style={brand ? { backgroundColor: `color-mix(in srgb, ${brand.color} 16%, transparent)` } : undefined}
|
||||
>
|
||||
{brand ? (
|
||||
<brand.Icon aria-hidden className="size-3.5" style={brandGlyphStyle(brand)} />
|
||||
) : (
|
||||
name.charAt(0).toUpperCase()
|
||||
)}
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'absolute -bottom-0.5 -right-0.5 size-2 rounded-full ring-2 ring-(--ui-chat-surface-background)',
|
||||
STATUS_DOT[status]
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
<AvatarChip
|
||||
brand={brandFor(name)}
|
||||
className={className}
|
||||
name={name}
|
||||
overlay={
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'absolute -bottom-0.5 -right-0.5 size-2 rounded-full ring-2 ring-(--ui-chat-surface-background)',
|
||||
STATUS_DOT[status]
|
||||
)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { AvatarChip, monogramFor } from './avatar-chip'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const Glyph = () => <svg data-testid="glyph" />
|
||||
|
||||
describe('the identity ladder', () => {
|
||||
it('paints a brand glyph on a tint of its own color', () => {
|
||||
render(<AvatarChip brand={{ Icon: Glyph, color: '#5E6AD2' }} data-testid="chip" name="Linear" />)
|
||||
|
||||
const background = screen.getByTestId('chip').style.backgroundColor
|
||||
|
||||
expect(screen.getByTestId('glyph')).toBeTruthy()
|
||||
// jsdom normalises the hex, so assert the tint rather than the literal.
|
||||
expect(background).toContain('rgb(94, 106, 210)')
|
||||
expect(background).toContain('16%')
|
||||
})
|
||||
|
||||
it('falls back to a letter when we have no mark for the name', () => {
|
||||
render(<AvatarChip name="Zulip" />)
|
||||
|
||||
expect(screen.getByText('Z')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('prefers a brand-supplied monogram over the first letter', () => {
|
||||
render(<AvatarChip brand={{ color: '#000', monogram: 'n8' }} name="n8n" />)
|
||||
|
||||
expect(screen.getByText('n8')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('lets a caller replace the mark entirely, which is how a resolved favicon gets in', () => {
|
||||
render(
|
||||
<AvatarChip brand={{ Icon: Glyph, color: '#000' }} name="Acme">
|
||||
<img alt="" data-testid="favicon" src="data:image/png;base64,iVBOR" />
|
||||
</AvatarChip>
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('favicon')).toBeTruthy()
|
||||
expect(screen.queryByTestId('glyph')).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves a monochrome mark to follow the surrounding text color rather than vanish into the theme', () => {
|
||||
render(<AvatarChip brand={{ Icon: Glyph, color: '#0E1128', monochrome: true }} data-testid="chip" name="Unreal" />)
|
||||
|
||||
expect(screen.getByTestId('chip').style.color).toBe('')
|
||||
})
|
||||
|
||||
it('carries an overlay for a status dot', () => {
|
||||
render(<AvatarChip name="Acme" overlay={<span data-testid="dot" />} />)
|
||||
|
||||
expect(screen.getByTestId('dot')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the monogram', () => {
|
||||
it.each([
|
||||
['linear', 'L'],
|
||||
[' spaced', 'S'],
|
||||
['', '']
|
||||
])('%s → %s', (name, expected) => {
|
||||
expect(monogramFor(name)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { ComponentPropsWithoutRef, ComponentType, ReactNode, SVGProps } from 'react'
|
||||
import { forwardRef } from 'react'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* The square identity chip: a brand glyph on a 16% tint of its own color, or
|
||||
* a letter monogram when we have no mark for the thing.
|
||||
*
|
||||
* One treatment, three surfaces — messaging platforms, the MCP servers tab,
|
||||
* connector cards — which is one more than it took for the copies to drift.
|
||||
* They had already diverged on radius, on glyph size, and on what an unknown
|
||||
* name looks like. Size and radius are the caller's call (`className`);
|
||||
* everything else is fixed here so a Slack row and a Linear card wear the
|
||||
* same chip.
|
||||
*/
|
||||
export interface AvatarChipBrand {
|
||||
Icon?: ComponentType<SVGProps<SVGSVGElement>>
|
||||
color: string
|
||||
/** Marks that are black or white by design (GitHub, Notion, Unreal) follow
|
||||
* the surrounding text color instead of vanishing into the theme. */
|
||||
monochrome?: boolean
|
||||
monogram?: string
|
||||
}
|
||||
|
||||
interface AvatarChipProps extends Omit<ComponentPropsWithoutRef<'span'>, 'children'> {
|
||||
brand?: AvatarChipBrand | null
|
||||
/** Replaces the mark entirely — a resolved favicon, a spinner. */
|
||||
children?: ReactNode
|
||||
/** The monogram's source, and what a screen reader gets. */
|
||||
name: string
|
||||
/** Painted over the mark: a status dot, a badge. */
|
||||
overlay?: ReactNode
|
||||
}
|
||||
|
||||
/** Proportional to the chip so one glyph size serves every size the chip is
|
||||
* used at — 14px inside the 24px row chip, matching what it replaced. */
|
||||
const GLYPH_CLASS = 'size-[58%]'
|
||||
|
||||
export const AvatarChip = forwardRef<HTMLSpanElement, AvatarChipProps>(function AvatarChip(
|
||||
{ brand, children, className, name, overlay, style, ...rest },
|
||||
ref
|
||||
) {
|
||||
const Icon = brand?.Icon
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
// Not `overflow-hidden`: an overlay dot sits proud of the corner. A
|
||||
// caller painting a raster mark clips at its own layer.
|
||||
'relative inline-grid size-6 shrink-0 place-items-center rounded-md text-[length:var(--conversation-caption-font-size)] font-medium',
|
||||
!brand && 'bg-(--ui-bg-tertiary) text-(--ui-text-tertiary)',
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
style={
|
||||
brand
|
||||
? {
|
||||
backgroundColor: `color-mix(in srgb, ${brand.color} 16%, transparent)`,
|
||||
color: brand.monochrome ? undefined : brand.color,
|
||||
...style
|
||||
}
|
||||
: style
|
||||
}
|
||||
{...rest}
|
||||
>
|
||||
{children ?? (Icon ? <Icon aria-hidden className={GLYPH_CLASS} /> : (brand?.monogram ?? monogramFor(name)))}
|
||||
{overlay}
|
||||
</span>
|
||||
)
|
||||
})
|
||||
|
||||
export const monogramFor = (name: string): string => name.trim().charAt(0).toUpperCase()
|
||||
@@ -0,0 +1,258 @@
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
ConnectorCard,
|
||||
type ConnectorCardCopy,
|
||||
type ConnectorCardProps,
|
||||
type ConnectorCardSubject
|
||||
} from './connector-card'
|
||||
import { connectorLogoSource } from './connector-logo'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const COPY: ConnectorCardCopy = {
|
||||
connectAction: 'Connect',
|
||||
decline: 'Not now',
|
||||
envRequired: 'Fill in the required credentials first',
|
||||
grantAction: 'Grant access',
|
||||
retryAction: 'Retry',
|
||||
stateConnected: 'Connected',
|
||||
stateDeclined: 'Skipped',
|
||||
stateDisabled: 'currently off',
|
||||
stateFailed: 'Failed',
|
||||
stateNeedsAuth: 'signed out',
|
||||
toolCount: count => (count === 1 ? '1 tool' : `${count} tools`),
|
||||
trustCommunity: 'unreviewed',
|
||||
trustCommunityTip: host => `Nobody has verified who runs ${host}`,
|
||||
trustVerified: publisher => `verified · ${publisher}`,
|
||||
trustVerifiedTip: publisher => `The publisher proved it owns ${publisher}`
|
||||
}
|
||||
|
||||
const LINEAR: ConnectorCardSubject = {
|
||||
description: 'Issues and projects.',
|
||||
homepage: 'https://linear.app',
|
||||
name: 'linear',
|
||||
title: 'Linear',
|
||||
trust: 'catalog'
|
||||
}
|
||||
|
||||
function renderCard(overrides: Partial<ConnectorCardProps> = {}) {
|
||||
const onConnect = vi.fn()
|
||||
const onDismiss = vi.fn()
|
||||
|
||||
render(
|
||||
<ConnectorCard
|
||||
connector={LINEAR}
|
||||
copy={COPY}
|
||||
onConnect={onConnect}
|
||||
onDismiss={onDismiss}
|
||||
state="not_configured"
|
||||
{...overrides}
|
||||
/>
|
||||
)
|
||||
|
||||
return { onConnect, onDismiss }
|
||||
}
|
||||
|
||||
describe('the resting offer', () => {
|
||||
it('leads with what the thing is, not with a question about it', () => {
|
||||
renderCard()
|
||||
|
||||
// Scoped to a span: the brand glyph is an <svg> carrying its own
|
||||
// <title>Linear</title>, which is the mark's accessible name rather than
|
||||
// the card's copy.
|
||||
expect(screen.getByText('Linear', { selector: 'span' })).toBeTruthy()
|
||||
expect(screen.getByText('Issues and projects.')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('offers a connect and a way out', () => {
|
||||
const { onConnect, onDismiss } = renderCard()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Connect' }))
|
||||
expect(onConnect).toHaveBeenCalledOnce()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Not now' }))
|
||||
expect(onDismiss).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('says how a configured connector currently stands', () => {
|
||||
renderCard({ state: 'needs_auth' })
|
||||
|
||||
expect(screen.getByText('signed out')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('while it is working', () => {
|
||||
it('shows the phase instead of the resting state, because the browser tab that just took focus is otherwise unexplained', () => {
|
||||
renderCard({ phase: 'Signing in…', state: 'needs_auth' })
|
||||
|
||||
expect(screen.getByText('Signing in…')).toBeTruthy()
|
||||
expect(screen.queryByText('signed out')).toBeNull()
|
||||
})
|
||||
|
||||
it('holds its own action but never the way out', () => {
|
||||
// While a connect is in flight, decline is the escape from a stuck
|
||||
// sign-in tab or a hung install.
|
||||
renderCard({ phase: 'Installing…' })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Not now' }).hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('holds its action while a sibling is mid-flight, so two sign-in tabs never race for focus', () => {
|
||||
renderCard({ otherBusy: true })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Connect' }).hasAttribute('disabled')).toBe(true)
|
||||
expect(screen.getByRole('button', { name: 'Not now' }).hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('once it is answered', () => {
|
||||
it('collapses to a single line reporting what came of it', () => {
|
||||
renderCard({ outcome: { status: 'connected', tools: ['a', 'b', 'c'] } })
|
||||
|
||||
expect(screen.getByText('Connected · 3 tools')).toBeTruthy()
|
||||
// The offer is spent; the space belongs to whatever is still asking.
|
||||
expect(screen.queryByRole('button', { name: 'Connect' })).toBeNull()
|
||||
})
|
||||
|
||||
it('collapses the same way when waved off, still naming the thing', () => {
|
||||
renderCard({ dismissed: true })
|
||||
|
||||
expect(screen.getByText('Linear', { selector: 'span' })).toBeTruthy()
|
||||
expect(screen.getByText('Skipped')).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: 'Not now' })).toBeNull()
|
||||
})
|
||||
|
||||
it('does not claim a tool count it does not have', () => {
|
||||
renderCard({ outcome: { status: 'connected' } })
|
||||
|
||||
expect(screen.getByText('Connected')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('after a failure', () => {
|
||||
it('stays live with the reason and a retry', () => {
|
||||
renderCard({ outcome: { detail: 'Connection refused', status: 'error' } })
|
||||
|
||||
expect(screen.getByText('Connection refused')).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('asks for access rather than a retry when the credential was refused', () => {
|
||||
// Repeating a refused grant just gets refused again; the fix is to ask.
|
||||
renderCard({ outcome: { detail: 'insufficient scope', needsAuth: true, status: 'error' } })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Grant access' })).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()
|
||||
})
|
||||
|
||||
it('brings the setup steps back, because the failure was usually caused by one of them', () => {
|
||||
const withSetup: ConnectorCardSubject = { ...LINEAR, setup: ['Enable the API'] }
|
||||
|
||||
renderCard({ connector: withSetup, outcome: { status: 'error' }, state: 'connected' })
|
||||
|
||||
expect(screen.getByText('Enable the API')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the work only the user can do', () => {
|
||||
it('numbers the steps, because their order matters', () => {
|
||||
renderCard({ connector: { ...LINEAR, setup: ['Create a project', 'Enable the API'] } })
|
||||
|
||||
expect(screen.getByText('1.')).toBeTruthy()
|
||||
expect(screen.getByText('2.')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('turns a markdown link into a real link, because the whole cost of a step is finding the page', () => {
|
||||
renderCard({ connector: { ...LINEAR, setup: ['Create a token at [Settings](https://linear.app/settings/api)'] } })
|
||||
|
||||
const link = screen.getByRole('link', { name: 'Settings' })
|
||||
|
||||
expect(link.getAttribute('href')).toBe('https://linear.app/settings/api')
|
||||
})
|
||||
|
||||
it('does not repeat console instructions at a connector that already works', () => {
|
||||
renderCard({ connector: { ...LINEAR, setup: ['Enable the API'] }, state: 'disabled' })
|
||||
|
||||
expect(screen.queryByText('Enable the API')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('credentials', () => {
|
||||
const withEnv: ConnectorCardSubject = {
|
||||
...LINEAR,
|
||||
requiredEnv: [{ name: 'LINEAR_API_KEY', prompt: 'API key', required: true }]
|
||||
}
|
||||
|
||||
it('stays out of the way until the card asks for it', () => {
|
||||
renderCard({ connector: withEnv })
|
||||
|
||||
expect(screen.queryByText('API key *')).toBeNull()
|
||||
})
|
||||
|
||||
it('reports each keystroke so the caller owns the draft', () => {
|
||||
const onEnvChange = vi.fn()
|
||||
|
||||
renderCard({ connector: withEnv, envOpen: true, onEnvChange })
|
||||
|
||||
fireEvent.change(screen.getByLabelText('API key *'), { target: { value: 'lin_abc' } })
|
||||
expect(onEnvChange).toHaveBeenCalledWith('LINEAR_API_KEY', 'lin_abc')
|
||||
})
|
||||
|
||||
it('masks the value, since these are secrets', () => {
|
||||
renderCard({ connector: withEnv, envOpen: true })
|
||||
|
||||
expect(screen.getByLabelText('API key *').getAttribute('type')).toBe('password')
|
||||
})
|
||||
})
|
||||
|
||||
describe('how much the source vouches for it', () => {
|
||||
it('says nothing for a reviewed source, so the badge that matters is not trained away', () => {
|
||||
renderCard()
|
||||
|
||||
expect(screen.queryByText('unreviewed')).toBeNull()
|
||||
expect(screen.queryByText(/verified/)).toBeNull()
|
||||
})
|
||||
|
||||
it('names the domain a publisher proved it owns, rather than claiming trust', () => {
|
||||
renderCard({ connector: { ...LINEAR, publisher: 'notion.com', trust: 'verified' } })
|
||||
|
||||
expect(screen.getByText('verified · notion.com')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('flags a publisher nobody has vouched for', () => {
|
||||
renderCard({ connector: { ...LINEAR, trust: 'community', url: 'https://random.test/mcp' } })
|
||||
|
||||
expect(screen.getByText('unreviewed')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('where a mark is read from', () => {
|
||||
it('prefers the product site over the endpoint it talks to', () => {
|
||||
expect(
|
||||
connectorLogoSource({ homepage: 'https://linear.app', name: 'linear', url: 'https://mcp.linear.app/sse' })
|
||||
).toBe('https://linear.app')
|
||||
})
|
||||
|
||||
it('falls back to the endpoint, then to the docs', () => {
|
||||
expect(connectorLogoSource({ name: 'linear', url: 'https://mcp.linear.app/sse' })).toBe('https://mcp.linear.app')
|
||||
expect(connectorLogoSource({ docs: 'https://docs.stripe.com/x', name: 'stripe' })).toBe('https://docs.stripe.com')
|
||||
})
|
||||
|
||||
it('reads the origin, never the path, so an endpoint is not fetched just to draw a logo', () => {
|
||||
expect(connectorLogoSource({ name: 'acme', url: 'https://acme.test/deep/mcp?token=1' })).toBe('https://acme.test')
|
||||
})
|
||||
|
||||
it('refuses a code host, because a bridge published on GitHub is not GitHub', () => {
|
||||
expect(connectorLogoSource({ name: 'n8n-bridge', url: 'https://github.com/someone/n8n-mcp' })).toBe('')
|
||||
})
|
||||
|
||||
it('refuses a private host, which has no logo to find and should not be named aloud', () => {
|
||||
expect(connectorLogoSource({ name: 'unreal-engine', url: 'http://127.0.0.1:8000/mcp' })).toBe('')
|
||||
})
|
||||
|
||||
it('shrugs at something that is not a URL at all', () => {
|
||||
expect(connectorLogoSource({ docs: 'see the README', name: 'local' })).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,348 @@
|
||||
import { SCAFFOLD_META_CLASS, ScaffoldRow } from '@/components/chat/scaffold-row'
|
||||
import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Codicon } from '@/components/ui/codicon'
|
||||
import { ConnectorLogo, type ConnectorLogoSubject } from '@/components/ui/connector-logo'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Tip } from '@/components/ui/tooltip'
|
||||
import { MarkdownLinkText } from '@/lib/external-link'
|
||||
import { Loader2 } from '@/lib/icons'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* The consent card for connecting a thing to Hermes, as pure presentation.
|
||||
*
|
||||
* Deliberately knows nothing about MCP. It renders a subject, a state, and an
|
||||
* outcome, and it calls back — what a connector IS, how one connects, and
|
||||
* where the strings come from all belong to the caller. That boundary is the
|
||||
* point: the transcript's inline setup card and any other surface that has to
|
||||
* ask "connect this?" should look identical without sharing a data layer.
|
||||
*
|
||||
* Consent vocabulary follows the tool approval bar: primary-tinted action,
|
||||
* quiet ghost decline, the same `mt-2` stand-off.
|
||||
*/
|
||||
|
||||
/** Where the subject stands before anything is attempted. */
|
||||
export type ConnectorCardState = 'connected' | 'disabled' | 'needs_auth' | 'not_configured'
|
||||
|
||||
/** How much the source vouches for the subject. */
|
||||
export type ConnectorCardTrust = 'catalog' | 'community' | 'verified'
|
||||
|
||||
/** One credential the subject declares it needs. */
|
||||
export interface ConnectorCardField {
|
||||
name: string
|
||||
prompt?: string
|
||||
required?: boolean
|
||||
}
|
||||
|
||||
/** What the card renders. Structural, so a caller's richer type satisfies it
|
||||
* without this file importing that type. */
|
||||
export interface ConnectorCardSubject extends ConnectorLogoSubject {
|
||||
description?: string
|
||||
/** Named by the publisher and checked against the serving domain. */
|
||||
publisher?: string
|
||||
requiredEnv?: ConnectorCardField[]
|
||||
/** Ordered work only the user can do, elsewhere, before this can connect. */
|
||||
setup?: string[]
|
||||
title: string
|
||||
trust?: ConnectorCardTrust
|
||||
}
|
||||
|
||||
/** How an attempt ended. */
|
||||
export interface ConnectorCardOutcome {
|
||||
detail?: string
|
||||
/** The failure was a refusal, not a fault: wrong key, expired grant, or a
|
||||
* grant that never covered the tools. Asking again is the fix, so the card
|
||||
* offers access rather than a retry. */
|
||||
needsAuth?: boolean
|
||||
status: 'connected' | 'declined' | 'error'
|
||||
tools?: unknown[]
|
||||
}
|
||||
|
||||
/** Every string the card shows. Passed in rather than read from i18n so the
|
||||
* card stays a leaf that anything can render, tests included. */
|
||||
export interface ConnectorCardCopy {
|
||||
connectAction: string
|
||||
decline: string
|
||||
envRequired: string
|
||||
grantAction: string
|
||||
retryAction: string
|
||||
stateConnected: string
|
||||
stateDeclined: string
|
||||
stateDisabled: string
|
||||
stateFailed: string
|
||||
stateNeedsAuth: string
|
||||
toolCount: (count: number) => string
|
||||
trustCommunity: string
|
||||
trustCommunityTip: (host: string) => string
|
||||
trustVerified: (publisher: string) => string
|
||||
trustVerifiedTip: (publisher: string) => string
|
||||
}
|
||||
|
||||
const SHELL_CLASS = `${WIDGET_SHELL_CLASS} text-[length:var(--conversation-text-font-size)] text-(--ui-text-primary)`
|
||||
|
||||
const hostOf = (url: null | string | undefined): string => {
|
||||
if (!url) {
|
||||
return ''
|
||||
}
|
||||
|
||||
try {
|
||||
return new URL(url).hostname
|
||||
} catch {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
/** What trails a settled subject's name: how it ended, and the useful number
|
||||
* or reason behind that. */
|
||||
export function outcomeMeta(outcome: ConnectorCardOutcome, copy: ConnectorCardCopy): string {
|
||||
if (outcome.status === 'connected') {
|
||||
const toolCount = Array.isArray(outcome.tools) ? outcome.tools.length : 0
|
||||
|
||||
return toolCount > 0 ? `${copy.stateConnected} · ${copy.toolCount(toolCount)}` : copy.stateConnected
|
||||
}
|
||||
|
||||
if (outcome.status === 'error') {
|
||||
return outcome.detail || copy.stateFailed
|
||||
}
|
||||
|
||||
return copy.stateDeclined
|
||||
}
|
||||
|
||||
/**
|
||||
* A subject that no longer needs anything: connected, skipped, failed.
|
||||
*
|
||||
* Not a card. An answered offer is transcript scaffolding — the same kind of
|
||||
* line as a settled tool run — so it renders through `ScaffoldRow` and reads
|
||||
* like everything else already done. The name keeps full contrast because
|
||||
* that's the content; the verdict trails it as meta.
|
||||
*/
|
||||
export function ConnectorSummary({
|
||||
connector,
|
||||
meta,
|
||||
tone
|
||||
}: {
|
||||
connector: ConnectorLogoSubject
|
||||
meta?: string
|
||||
tone?: 'error'
|
||||
}) {
|
||||
// The scaffold mark goes on the row, never on a container holding several:
|
||||
// opacity opens a stacking context and would pin every sibling to one level.
|
||||
return (
|
||||
<div data-conversation-scaffold="" data-slot="connector-card">
|
||||
<ScaffoldRow>
|
||||
<ConnectorLogo className="size-4 rounded-[0.25rem]" connector={connector} />
|
||||
<span className="truncate text-[length:var(--conversation-tool-font-size)] text-(--ui-text-primary)">
|
||||
{connector.title || connector.name}
|
||||
</span>
|
||||
{meta ? <span className={cn(SCAFFOLD_META_CLASS, tone === 'error' && 'text-destructive')}>{meta}</span> : null}
|
||||
</ScaffoldRow>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* How much the source vouches for this subject.
|
||||
*
|
||||
* Only the exceptions get a badge. Something we shipped in a reviewed catalog
|
||||
* is the ordinary case — badging it "reviewed" spends a word on every card to
|
||||
* say "normal", and a label whose meaning nobody can guess teaches the user to
|
||||
* ignore the one that matters.
|
||||
*
|
||||
* So: nothing for vetted sources. A publisher that proved it owns the serving
|
||||
* domain says "verified · notion.com" — checkable identity, not an
|
||||
* endorsement, which is why it names the domain instead of claiming trust.
|
||||
* Everything else gets the amber "unreviewed" with the host in its tooltip:
|
||||
* the card doesn't spend a line on an endpoint nobody reads, but for a
|
||||
* publisher nobody has vouched for, the host is the whole question.
|
||||
*/
|
||||
function TrustBadge({ connector, copy }: { connector: ConnectorCardSubject; copy: ConnectorCardCopy }) {
|
||||
if (!connector.trust || connector.trust === 'catalog') {
|
||||
return null
|
||||
}
|
||||
|
||||
if (connector.trust === 'verified') {
|
||||
// No publisher domain means a curated directory of vendor remotes, which
|
||||
// is the ordinary case again — nothing to say.
|
||||
if (!connector.publisher) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Tip label={copy.trustVerifiedTip(connector.publisher)}>
|
||||
<span className="text-[0.6875rem] text-(--ui-text-tertiary)">{copy.trustVerified(connector.publisher)}</span>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Tip label={copy.trustCommunityTip(hostOf(connector.url))}>
|
||||
<span className="inline-flex items-center gap-1 text-[0.6875rem] text-amber-500">
|
||||
<Codicon name="warning" size="0.6875rem" />
|
||||
{copy.trustCommunity}
|
||||
</span>
|
||||
</Tip>
|
||||
)
|
||||
}
|
||||
|
||||
export interface ConnectorCardProps {
|
||||
connector: ConnectorCardSubject
|
||||
copy: ConnectorCardCopy
|
||||
/** Waved off by the user. Collapses to the same settled line as success. */
|
||||
dismissed?: boolean
|
||||
envDraft?: Record<string, string>
|
||||
/** Whether the credential fields are revealed. The caller owns this because
|
||||
* a refused credential should reveal them without a second click. */
|
||||
envOpen?: boolean
|
||||
onConnect: () => void
|
||||
onDismiss: () => void
|
||||
onEnvChange?: (key: string, value: string) => void
|
||||
/** A sibling card is mid-flight. Two sign-in tabs racing for focus is
|
||||
* hostile, so the action waits — but the decline never does. */
|
||||
otherBusy?: boolean
|
||||
outcome?: ConnectorCardOutcome
|
||||
/** Present only while working; replaces the resting state label. */
|
||||
phase?: string
|
||||
state: ConnectorCardState
|
||||
}
|
||||
|
||||
/**
|
||||
* One subject's consent card.
|
||||
*
|
||||
* Owns everything about that subject and nothing about its siblings: its own
|
||||
* trust badge, credential fields, failure reason, and its own action. A
|
||||
* connected card collapses to a single confirmed line, because its offer is
|
||||
* spent and the space belongs to the ones still asking.
|
||||
*/
|
||||
export function ConnectorCard({
|
||||
connector,
|
||||
copy,
|
||||
dismissed = false,
|
||||
envDraft = {},
|
||||
envOpen = false,
|
||||
onConnect,
|
||||
onDismiss,
|
||||
onEnvChange,
|
||||
otherBusy = false,
|
||||
outcome,
|
||||
phase,
|
||||
state
|
||||
}: ConnectorCardProps) {
|
||||
const working = phase !== undefined
|
||||
const connected = outcome?.status === 'connected'
|
||||
const failed = outcome?.status === 'error'
|
||||
|
||||
// Answered: the offer is spent, so the card collapses to a scaffold line and
|
||||
// gives the space back to whatever is still asking.
|
||||
if (connected || dismissed) {
|
||||
return <ConnectorSummary connector={connector} meta={outcomeMeta(outcome ?? { status: 'declined' }, copy)} />
|
||||
}
|
||||
|
||||
const stateLabel = state === 'disabled' ? copy.stateDisabled : state === 'needs_auth' ? copy.stateNeedsAuth : null
|
||||
|
||||
// Before the first connect, and again after a failed one. Something that
|
||||
// connected doesn't need its console instructions repeated — but a failure
|
||||
// usually happened BECAUSE of that console: an API left un-enabled, the
|
||||
// wrong client type, a secret copied one character short. Withdrawing the
|
||||
// steps and the fields at the moment they're finally needed is backwards,
|
||||
// and it leaves a wrong credential with nowhere to be corrected.
|
||||
const fixable = state === 'not_configured' || failed
|
||||
const envFields = fixable ? (connector.requiredEnv ?? []) : []
|
||||
const steps = fixable ? (connector.setup ?? []) : []
|
||||
|
||||
// Logo owns the left rail; everything the card says and every control it
|
||||
// offers shares the one text column, so the buttons sit on the copy's grid
|
||||
// line instead of hanging off the card's edge under the mark.
|
||||
return (
|
||||
<div className={cn(SHELL_CLASS, 'flex items-start gap-3')} data-slot="connector-card">
|
||||
<ConnectorLogo connector={connector} />
|
||||
|
||||
<div className="grid min-w-0 flex-1 gap-0.5">
|
||||
<div className="flex flex-wrap items-baseline gap-x-1.5">
|
||||
<span className="font-medium">{connector.title}</span>
|
||||
{/* While the card is working its phase replaces the resting state —
|
||||
"Signing in…" is the one the user needs, because the browser tab
|
||||
that just took focus is otherwise unexplained. */}
|
||||
{working ? (
|
||||
<span className="text-[0.6875rem] text-(--ui-text-tertiary)">{phase}</span>
|
||||
) : (
|
||||
stateLabel && <span className="text-[0.6875rem] text-(--ui-text-tertiary)">{stateLabel}</span>
|
||||
)}
|
||||
<TrustBadge connector={connector} copy={copy} />
|
||||
</div>
|
||||
|
||||
{connector.description ? <p className="text-(--ui-text-secondary)">{connector.description}</p> : null}
|
||||
|
||||
{failed && outcome.detail ? <p className="text-[0.6875rem] text-destructive">{outcome.detail}</p> : null}
|
||||
|
||||
{/* The part we cannot do. Numbered because order matters, linked
|
||||
because the whole cost of these steps is finding the page. */}
|
||||
{steps.length > 0 && (
|
||||
<ol className="mt-1.5 grid gap-1" data-slot="connector-card-steps">
|
||||
{steps.map((step, index) => (
|
||||
<li className="flex gap-1.5 text-[0.6875rem] text-(--ui-text-secondary)" key={step}>
|
||||
<span className="tabular-nums text-(--ui-text-tertiary)">{index + 1}.</span>
|
||||
<MarkdownLinkText text={step} />
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
{envOpen && envFields.length > 0 && (
|
||||
<div className="mt-1 grid gap-2" data-slot="connector-card-env">
|
||||
<p className="text-[0.6875rem] text-(--ui-text-tertiary)">{copy.envRequired}</p>
|
||||
{envFields.map(env => (
|
||||
<label className="grid gap-1" key={env.name}>
|
||||
<span className="text-[0.6875rem] text-(--ui-text-secondary)">
|
||||
{env.prompt || env.name}
|
||||
{env.required ? ' *' : ''}
|
||||
</span>
|
||||
<Input
|
||||
className="h-7 text-xs"
|
||||
onChange={event => onEnvChange?.(env.name, event.currentTarget.value)}
|
||||
type="password"
|
||||
value={envDraft[env.name] ?? ''}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Same strip as the tool approval bar (tool/approval.tsx), down to its
|
||||
`mt-2` stand-off: a bordered primary-tinted action plus a quiet
|
||||
ghost decline. One consent vocabulary across the transcript. */}
|
||||
<div className="mt-2 flex items-center gap-2.5">
|
||||
<div className="inline-flex h-6 items-stretch overflow-hidden rounded-md border border-primary/25 bg-primary/10 text-primary">
|
||||
<Button
|
||||
className="h-full gap-1 rounded-none px-2 text-xs font-medium text-primary hover:bg-primary/15 hover:text-primary"
|
||||
disabled={working || otherBusy}
|
||||
onClick={onConnect}
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
>
|
||||
{working ? (
|
||||
<Loader2 className="size-3 animate-spin" />
|
||||
) : outcome?.needsAuth ? (
|
||||
copy.grantAction
|
||||
) : failed ? (
|
||||
copy.retryAction
|
||||
) : (
|
||||
copy.connectAction
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{/* Never disabled: while a connect is in flight this is the way out
|
||||
of a stuck sign-in tab or a hung install. */}
|
||||
<Button
|
||||
className="h-6 gap-1.5 rounded-md px-1.5 text-xs font-normal text-(--ui-text-tertiary) hover:text-foreground"
|
||||
onClick={onDismiss}
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
>
|
||||
{copy.decline}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { brandFor } from '@/lib/mcp-brands'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { AvatarChip, monogramFor } from './avatar-chip'
|
||||
import { Favicon } from './favicon'
|
||||
|
||||
/** The least a mark needs: something to name it, and somewhere a logo might
|
||||
* live. Structural on purpose — a caller's richer connector type satisfies
|
||||
* this without the visual layer knowing that type exists. */
|
||||
export interface ConnectorLogoSubject {
|
||||
docs?: string
|
||||
homepage?: string
|
||||
name: string
|
||||
title?: string
|
||||
url?: null | string
|
||||
}
|
||||
|
||||
/** Hosts whose favicon would name the wrong thing: a bridge published on
|
||||
* GitHub is not GitHub, and a package page is not the product. */
|
||||
const NOT_A_LOGO =
|
||||
/(^|\.)(github\.com|githubusercontent\.com|gitlab\.com|bitbucket\.org|npmjs\.com|pypi\.org|readthedocs\.io)$/
|
||||
|
||||
const isLoopback = (host: string) =>
|
||||
host === 'localhost' || host === '::1' || /^127\./.test(host) || /^(10|192\.168)\./.test(host)
|
||||
|
||||
/**
|
||||
* Where to read this subject's mark from.
|
||||
*
|
||||
* The product's own site first (the only source that is certainly the right
|
||||
* logo), then the endpoint it talks to — `mcp.linear.app` is Linear — then
|
||||
* vendor docs, which for most entries is `docs.stripe.com` and friends.
|
||||
* Nothing for a private or loopback host: there is no logo out there to find,
|
||||
* and asking would announce an internal hostname.
|
||||
*/
|
||||
export function connectorLogoSource(subject: ConnectorLogoSubject): string {
|
||||
for (const candidate of [subject.homepage, subject.url, subject.docs]) {
|
||||
if (!candidate) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const { hostname, origin } = new URL(candidate)
|
||||
|
||||
if (!NOT_A_LOGO.test(hostname) && !isLoopback(hostname)) {
|
||||
// The origin, never the path: the icon lives on the site, and this
|
||||
// way a not-yet-connected endpoint is never fetched just to draw a
|
||||
// logo.
|
||||
return origin
|
||||
}
|
||||
} catch {
|
||||
// Not a URL (a bare repo path, a note) — nothing to read a mark from.
|
||||
}
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* A connector's mark, resolved as far as it goes.
|
||||
*
|
||||
* Curated brand glyph → the product's own favicon → the monogram every other
|
||||
* unknown name in the app falls back to. The middle rung is what keeps the
|
||||
* long tail from all looking alike: a curated icon set is a couple dozen names
|
||||
* and a public registry is thousands, so something we ship no icon for still
|
||||
* arrives wearing its own logo.
|
||||
*/
|
||||
export function ConnectorLogo({ className, connector }: { className?: string; connector: ConnectorLogoSubject }) {
|
||||
const label = connector.title || connector.name
|
||||
const brand = brandFor(connector.name)
|
||||
const site = brand ? '' : connectorLogoSource(connector)
|
||||
|
||||
return (
|
||||
<AvatarChip brand={brand} className={cn(site && 'overflow-hidden', className)} name={label} title={connector.title}>
|
||||
{site ? <Favicon fallback={monogramFor(label)} url={site} /> : undefined}
|
||||
</AvatarChip>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { type ReactNode, useEffect, useState } from 'react'
|
||||
|
||||
import { Loader2 } from '@/lib/icons'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* A site's icon, resolved the thorough way.
|
||||
*
|
||||
* The work happens in the main process (`electron/favicon.ts`): read the
|
||||
* page, collect every declared `<link rel="icon">` and web-app-manifest
|
||||
* icon, rank them, then fall back to the well-known paths. None of that is
|
||||
* reachable from here — cross-origin HTML is unreadable under CORS — so this
|
||||
* component is just the request, the wait, and the placeholder.
|
||||
*
|
||||
* `fallback` holds the box before and after: a spinner marks the lookup, and
|
||||
* a site with no readable icon keeps the caller's own glyph rather than
|
||||
* flashing a broken image.
|
||||
*/
|
||||
|
||||
/** url → data URL, or '' for a site we've already failed to read. The main
|
||||
* process caches across restarts; this keeps a remount from crossing the
|
||||
* IPC boundary at all. */
|
||||
const resolved = new Map<string, string>()
|
||||
|
||||
export function Favicon({
|
||||
className,
|
||||
fallback,
|
||||
title,
|
||||
url
|
||||
}: {
|
||||
className?: string
|
||||
fallback: ReactNode
|
||||
title?: string
|
||||
url: null | string | undefined
|
||||
}) {
|
||||
const [icon, setIcon] = useState(() => (url ? (resolved.get(url) ?? '') : ''))
|
||||
const [pending, setPending] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const resolveFavicon = window.hermesDesktop?.resolveFavicon
|
||||
|
||||
if (!url || !resolveFavicon) {
|
||||
setIcon('')
|
||||
setPending(false)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const cached = resolved.get(url)
|
||||
|
||||
if (cached !== undefined) {
|
||||
setIcon(cached)
|
||||
setPending(false)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
let live = true
|
||||
|
||||
setPending(true)
|
||||
|
||||
void resolveFavicon(url)
|
||||
.catch(() => '')
|
||||
.then(found => {
|
||||
resolved.set(url, found)
|
||||
|
||||
if (live) {
|
||||
setIcon(found)
|
||||
setPending(false)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [url])
|
||||
|
||||
return (
|
||||
<span className={cn('inline-grid size-full place-items-center', className)} title={title}>
|
||||
{icon ? (
|
||||
<img alt="" aria-hidden className="size-full object-contain" src={icon} />
|
||||
) : pending ? (
|
||||
<Loader2 aria-hidden className="h-1/2 w-1/2 animate-spin opacity-60" />
|
||||
) : (
|
||||
fallback
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
Vendored
+3
@@ -262,6 +262,9 @@ declare global {
|
||||
openExternal: (url: string) => Promise<void>
|
||||
openPreviewInBrowser?: (url: string) => Promise<void>
|
||||
fetchLinkTitle: (url: string) => Promise<string>
|
||||
/** A site's icon as a data URL, or '' when it has none we can read.
|
||||
* Resolved and cached in the main process (electron/favicon.ts). */
|
||||
resolveFavicon?: (url: string) => Promise<string>
|
||||
sanitizeWorkspaceCwd: (cwd?: null | string) => Promise<{ cwd: string; sanitized: boolean }>
|
||||
settings: {
|
||||
getDefaultProjectDir: () => Promise<{ defaultLabel: string; dir: null | string; resolvedCwd: string }>
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
hostPathLabel,
|
||||
isTitleFetchable,
|
||||
LinkifiedText,
|
||||
MarkdownLinkText,
|
||||
PrettyLink,
|
||||
urlSlugTitleLabel
|
||||
} from './external-link'
|
||||
@@ -134,6 +135,21 @@ describe('external link helpers', () => {
|
||||
expect($previewTabs.get()).toHaveLength(0)
|
||||
})
|
||||
|
||||
// A setup step sends you to a console you are signed into in your own
|
||||
// browser, to fill in a form and copy a secret back. The in-app pane has
|
||||
// none of that session and is the wrong destination even for web URLs.
|
||||
it('sends a setup-step link straight to the OS browser', () => {
|
||||
const openExternal = vi.fn().mockResolvedValue(undefined)
|
||||
installDesktopBridge({ openExternal: openExternal as unknown as Window['hermesDesktop']['openExternal'] })
|
||||
|
||||
render(<MarkdownLinkText text="Enable the [Docs API](https://console.cloud.google.com/apis/library) first." />)
|
||||
|
||||
fireEvent.click(screen.getByRole('link', { name: 'Docs API' }))
|
||||
|
||||
expect(openExternal).toHaveBeenCalledWith('https://console.cloud.google.com/apis/library')
|
||||
expect($previewTabs.get()).toHaveLength(0)
|
||||
})
|
||||
|
||||
// A webview can't do anything useful with these, so they always hand off.
|
||||
it('hands a non-web scheme to the OS', () => {
|
||||
const openExternal = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
@@ -247,6 +247,9 @@ export function openLink(href: string, options: { native?: boolean } = {}): void
|
||||
interface ExternalLinkProps extends Omit<ComponentProps<'a'>, 'href' | 'target'> {
|
||||
href: string
|
||||
children?: ReactNode
|
||||
/** Skip the in-app pane. For links whose whole point is the session you are
|
||||
* signed into over there — a cloud console, an account page. */
|
||||
native?: boolean
|
||||
showExternalIcon?: boolean
|
||||
}
|
||||
|
||||
@@ -274,6 +277,7 @@ export function ExternalLink({
|
||||
children,
|
||||
className,
|
||||
href,
|
||||
native = false,
|
||||
onClick,
|
||||
showExternalIcon = false,
|
||||
...rest
|
||||
@@ -307,7 +311,7 @@ export function ExternalLink({
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
openLink(target, { native: wantsNativeBrowser(event.nativeEvent) })
|
||||
openLink(target, { native: native || wantsNativeBrowser(event.nativeEvent) })
|
||||
}}
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
@@ -381,6 +385,49 @@ export function LinkifiedText({ className, explicitOnly = false, pretty = true,
|
||||
return <span className={className}>{nodes.length ? nodes : text}</span>
|
||||
}
|
||||
|
||||
const MD_LINK_RE = /\[([^\]]+)]\((https?:\/\/[^\s)]+)\)/g
|
||||
|
||||
/**
|
||||
* Inline `[label](url)` and nothing else.
|
||||
*
|
||||
* For short authored strings — a catalog entry's setup steps — where the
|
||||
* label carries the meaning ("enable the Docs API") and the URL is a console
|
||||
* page whose own title is useless or, behind a login wall, actively wrong.
|
||||
* `LinkifiedText` can't serve this: it finds bare URLs and guesses a label.
|
||||
* Full markdown is the other extreme, a block renderer inside a card row.
|
||||
*
|
||||
* These open in the real browser. The destination is a console the user is
|
||||
* already signed into there, and the work is a form to fill in and a secret to
|
||||
* copy back — none of which the in-app pane is for.
|
||||
*/
|
||||
export function MarkdownLinkText({ className, text }: { className?: string; text: string }) {
|
||||
const nodes: ReactNode[] = []
|
||||
let cursor = 0
|
||||
|
||||
for (const match of text.matchAll(MD_LINK_RE)) {
|
||||
const [raw, label, href] = match
|
||||
const index = match.index ?? 0
|
||||
|
||||
if (index > cursor) {
|
||||
nodes.push(text.slice(cursor, index))
|
||||
}
|
||||
|
||||
nodes.push(
|
||||
<ExternalLink href={href} key={`${href}-${index}`} native title={href}>
|
||||
{label}
|
||||
</ExternalLink>
|
||||
)
|
||||
|
||||
cursor = index + raw.length
|
||||
}
|
||||
|
||||
if (cursor < text.length) {
|
||||
nodes.push(text.slice(cursor))
|
||||
}
|
||||
|
||||
return <span className={className}>{nodes.length ? nodes : text}</span>
|
||||
}
|
||||
|
||||
export function __resetLinkTitleCache(): void {
|
||||
titleCache.clear()
|
||||
titleInflight.clear()
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
/**
|
||||
* Curated brand glyphs for MCP server names — extracted from the mcp-tab's
|
||||
* avatar (its `MCP_BRAND_ICONS`) the moment a second surface (the composer
|
||||
* suggestion pills / inline setup card) needed the same identity ladder:
|
||||
* curated brand glyph → letter monogram. We deliberately do NOT fetch remote
|
||||
* favicons: a configured MCP URL can be a private/internal host, and hitting
|
||||
* a favicon service for it would leak that hostname off-box.
|
||||
* suggestion pills / inline setup card) needed the same identity ladder.
|
||||
*
|
||||
* This is the first rung only. Everything below it — the endpoint's own
|
||||
* favicon, then the initial — lives in `components/ui/connector-logo`, which
|
||||
* is what a surface should render when it wants a mark rather than a glyph.
|
||||
* Either way we never ask a third-party favicon service: an MCP URL can be a
|
||||
* private host, and that lookup would leak the hostname off-box.
|
||||
*/
|
||||
import {
|
||||
SiAirtable,
|
||||
@@ -17,6 +20,7 @@ import {
|
||||
SiHuggingface,
|
||||
SiIntercom,
|
||||
SiLinear,
|
||||
SiN8n,
|
||||
SiNetlify,
|
||||
SiNotion,
|
||||
SiPaypal,
|
||||
@@ -25,6 +29,7 @@ import {
|
||||
SiSquare,
|
||||
SiStripe,
|
||||
SiSupabase,
|
||||
SiUnrealengine,
|
||||
SiVercel,
|
||||
SiWebflow,
|
||||
SiZapier
|
||||
@@ -52,6 +57,7 @@ export const MCP_BRAND_ICONS: Record<string, McpBrand> = {
|
||||
huggingface: { Icon: SiHuggingface, color: '#FFD21E' },
|
||||
intercom: { Icon: SiIntercom, color: '#6AFDEF' },
|
||||
linear: { Icon: SiLinear, color: '#5E6AD2' },
|
||||
n8n: { Icon: SiN8n, color: '#EA4B71' },
|
||||
netlify: { Icon: SiNetlify, color: '#00C7B7' },
|
||||
notion: { Icon: SiNotion, color: '#000000', monochrome: true },
|
||||
paypal: { Icon: SiPaypal, color: '#003087' },
|
||||
@@ -61,6 +67,7 @@ export const MCP_BRAND_ICONS: Record<string, McpBrand> = {
|
||||
square: { Icon: SiSquare, color: '#3E4348', monochrome: true },
|
||||
stripe: { Icon: SiStripe, color: '#635BFF' },
|
||||
supabase: { Icon: SiSupabase, color: '#3FCF8E' },
|
||||
'unreal-engine': { Icon: SiUnrealengine, color: '#0E1128', monochrome: true },
|
||||
vercel: { Icon: SiVercel, color: '#000000', monochrome: true },
|
||||
webflow: { Icon: SiWebflow, color: '#146EF5' },
|
||||
zapier: { Icon: SiZapier, color: '#FF4A00' }
|
||||
@@ -71,8 +78,23 @@ export const MCP_BRAND_ICONS: Record<string, McpBrand> = {
|
||||
export const brandGlyphStyle = (brand: McpBrand): { color: string } | undefined =>
|
||||
brand.monochrome ? undefined : { color: brand.color }
|
||||
|
||||
export const brandFor = (name: string): McpBrand | null => {
|
||||
const lower = name.toLowerCase()
|
||||
/** The same brand under every spelling a connector arrives with: catalog slug
|
||||
* (`unreal-engine`), registry id (`unreal_engine`), display name (`Unreal
|
||||
* Engine`). Compare on letters and digits alone so none of them miss. */
|
||||
const squash = (value: string): string => value.toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||
|
||||
return MCP_BRAND_ICONS[lower] ?? Object.entries(MCP_BRAND_ICONS).find(([key]) => lower.includes(key))?.[1] ?? null
|
||||
export const brandFor = (name: string): McpBrand | null => {
|
||||
const target = squash(name)
|
||||
|
||||
if (!target) {
|
||||
return null
|
||||
}
|
||||
|
||||
const entries = Object.entries(MCP_BRAND_ICONS)
|
||||
|
||||
return (
|
||||
entries.find(([key]) => squash(key) === target)?.[1] ??
|
||||
entries.find(([key]) => target.includes(squash(key)))?.[1] ??
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1191,8 +1191,14 @@ export {
|
||||
oklchToSrgb255,
|
||||
readableOn
|
||||
} from '@/themes/color'
|
||||
/** The painted theme, its name, and the appearance it resolved to. */
|
||||
/** The painted theme, its name, and the appearance it resolved to — plus
|
||||
* `setTheme` / `setMode` to change it from a component. */
|
||||
export { useTheme } from '@/themes/context'
|
||||
/** Switch the theme from outside React (a gateway event, a connection coming
|
||||
* up, any callback with no component around it). Returns false and leaves the
|
||||
* appearance alone when the name doesn't resolve, so it doubles as the "is
|
||||
* this theme installed?" check. */
|
||||
export { requestTheme } from '@/themes/request'
|
||||
export { retintTheme, themeHue } from '@/themes/retint'
|
||||
export type { DesktopTheme, DesktopThemeColors } from '@/themes/types'
|
||||
export { THEMES_AREA } from '@/themes/user-themes'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export { ingestBackendSkin } from './backend-sync'
|
||||
export { ThemeProvider, useTheme } from './context'
|
||||
export { BUILTIN_THEME_LIST, BUILTIN_THEMES, DEFAULT_SKIN_NAME } from './presets'
|
||||
export { requestTheme } from './request'
|
||||
export { skinToDesktopTheme } from './skin'
|
||||
export type { DesktopTheme, DesktopThemeColors, DesktopThemeTypography } from './types'
|
||||
export type { HermesSkin } from '@hermes/shared/skin'
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { act, cleanup, render } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { registry } from '@/contrib/registry'
|
||||
|
||||
import { __resetBackendSkinSync } from './backend-sync'
|
||||
import { skinPref, ThemeProvider, useTheme } from './context'
|
||||
import { midnightTheme } from './presets'
|
||||
import { requestTheme } from './request'
|
||||
import type { DesktopTheme } from './types'
|
||||
import { THEMES_AREA } from './user-themes'
|
||||
|
||||
const cssVar = (name: string) => window.document.documentElement.style.getPropertyValue(name)
|
||||
|
||||
describe('requestTheme', () => {
|
||||
let ctx: ReturnType<typeof useTheme>
|
||||
|
||||
function Probe() {
|
||||
ctx = useTheme()
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const renderProbe = () =>
|
||||
render(
|
||||
<ThemeProvider>
|
||||
<Probe />
|
||||
</ThemeProvider>
|
||||
)
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear()
|
||||
__resetBackendSkinSync()
|
||||
})
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
it('switches the painted theme from outside React', () => {
|
||||
renderProbe()
|
||||
|
||||
let accepted = false
|
||||
act(() => {
|
||||
accepted = requestTheme('mono')
|
||||
})
|
||||
|
||||
expect(accepted).toBe(true)
|
||||
expect(ctx.themeName).toBe('mono')
|
||||
})
|
||||
|
||||
// The imperative door must land in the same place the React one does, or a
|
||||
// plugin-driven switch would evaporate on the next profile read.
|
||||
it('persists per profile like a manual pick', () => {
|
||||
renderProbe()
|
||||
|
||||
act(() => void requestTheme('midnight'))
|
||||
|
||||
expect(skinPref.resolve('default')).toBe('midnight')
|
||||
})
|
||||
|
||||
it('refuses a name that does not resolve, leaving the appearance untouched', () => {
|
||||
renderProbe()
|
||||
|
||||
act(() => void requestTheme('mono'))
|
||||
const painted = cssVar('--theme-foreground')
|
||||
|
||||
let accepted = true
|
||||
act(() => {
|
||||
accepted = requestTheme('a-theme-nobody-installed')
|
||||
})
|
||||
|
||||
expect(accepted).toBe(false)
|
||||
expect(ctx.themeName).toBe('mono')
|
||||
expect(cssVar('--theme-foreground')).toBe(painted)
|
||||
})
|
||||
|
||||
// The whole plugin loop: contribute a palette through THEMES_AREA, then
|
||||
// activate it on an event with no component in scope.
|
||||
it('activates a theme contributed through the registry', () => {
|
||||
const zeus: DesktopTheme = { ...midnightTheme, description: 'Zeus', label: 'Zeus', name: 'zeus' }
|
||||
const dispose = registry.register({ area: THEMES_AREA, data: zeus, id: 'zeus' })
|
||||
|
||||
renderProbe()
|
||||
|
||||
let accepted = false
|
||||
act(() => {
|
||||
accepted = requestTheme('zeus')
|
||||
})
|
||||
|
||||
expect(accepted).toBe(true)
|
||||
expect(ctx.themeName).toBe('zeus')
|
||||
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Imperative theme switching, for callers with no component to hang a hook on.
|
||||
*
|
||||
* `useTheme().setTheme` is the React door and covers every in-app surface, but
|
||||
* not every switch happens during a render. The backend announces a `/skin`
|
||||
* change over the gateway, and a plugin may want to repaint when a connection
|
||||
* comes up or a background event fires. Those callers write a name to
|
||||
* `$pendingSkinApply`; the ThemeProvider drains it through `setTheme`, so an
|
||||
* imperative switch normalizes, persists per profile, and drops any preview
|
||||
* exactly like a manual pick — one policy, one owner.
|
||||
*/
|
||||
|
||||
import { $pendingSkinApply } from './backend-sync'
|
||||
import { resolveTheme } from './user-themes'
|
||||
|
||||
/**
|
||||
* Ask for a theme switch from outside React. Returns whether the name resolved.
|
||||
*
|
||||
* An unknown name is refused rather than coerced. `setTheme` falls back to the
|
||||
* default skin for anything it can't resolve, which is right for a person
|
||||
* picking from a list but wrong for code reacting to an event: a gateway naming
|
||||
* a theme the user never installed would silently reset their appearance
|
||||
* instead of leaving it alone. The boolean doubles as the availability check,
|
||||
* so a caller needs no separate lookup to know it got what it asked for.
|
||||
*/
|
||||
export function requestTheme(name: string): boolean {
|
||||
if (!resolveTheme(name)) {
|
||||
return false
|
||||
}
|
||||
|
||||
$pendingSkinApply.set(name)
|
||||
|
||||
return true
|
||||
}
|
||||
+78
-11
@@ -258,6 +258,55 @@ def _capture_head_sha(git_cmd, cwd) -> str | None:
|
||||
except (subprocess.CalledProcessError, OSError):
|
||||
return None
|
||||
|
||||
# Files that define the editable install. A pull that touches none of them
|
||||
# cannot have invalidated it.
|
||||
_INSTALL_DEFINING_FILES = (
|
||||
"pyproject.toml",
|
||||
"setup.py",
|
||||
"setup.cfg",
|
||||
"MANIFEST.in",
|
||||
"uv.lock",
|
||||
)
|
||||
|
||||
def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool:
|
||||
"""True when the pulled commits cannot have invalidated the editable install.
|
||||
|
||||
``uv pip install -e .`` never audits an editable target — it reinstalls on
|
||||
every invocation, and every reinstall rewrites the console-script shims.
|
||||
On Windows that rewrite is the only reason the running ``hermes.exe`` has
|
||||
to be quarantined, and a quarantine that loses its race is the whole
|
||||
``os error 32`` family. Not reinstalling when the reinstall provably
|
||||
cannot change anything removes that risk outright for the common update,
|
||||
rather than trying to make the rename win more often.
|
||||
|
||||
Skipping is safe because Hermes pins its editable finder to a *static*
|
||||
module list (``[tool.setuptools] py-modules`` plus
|
||||
``packages.find.include``). The one source-only change that would stale
|
||||
that finder is a new top-level module or package, and it cannot land
|
||||
without a ``pyproject.toml`` diff. Dependencies and ``[project.scripts]``
|
||||
live there too. New submodules inside an already-mapped package resolve
|
||||
through the real package directory and need no reinstall.
|
||||
|
||||
Fails closed: an unresolvable pre-pull SHA (shallow checkout, ZIP swap)
|
||||
or a failed ``git diff`` returns False and the install runs as before.
|
||||
"""
|
||||
if not pre_pull_sha:
|
||||
return False
|
||||
try:
|
||||
result = subprocess.run(
|
||||
git_cmd
|
||||
+ ["diff", "--name-only", f"{pre_pull_sha}..HEAD", "--"]
|
||||
+ list(_INSTALL_DEFINING_FILES),
|
||||
cwd=cwd,
|
||||
capture_output=True,
|
||||
text=True, encoding="utf-8", errors="replace",
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
if result.returncode != 0:
|
||||
return False
|
||||
return not result.stdout.strip()
|
||||
|
||||
def _validate_critical_files_syntax(root) -> tuple[bool, str | None, str | None]:
|
||||
"""Compile each file in ``_UPDATE_CRITICAL_FILES`` to catch SyntaxErrors.
|
||||
|
||||
@@ -5698,7 +5747,13 @@ def _cmd_update_impl(args, gateway_mode: bool):
|
||||
# via ``_recover_from_interrupted_install``. Cleared after the core
|
||||
# ``.[all]`` install completes — lazy refresh uses a separate marker.
|
||||
_write_update_incomplete_marker()
|
||||
print("→ Updating Python dependencies...")
|
||||
deps_current = _editable_install_is_current(
|
||||
git_cmd, _m().PROJECT_ROOT, pre_pull_sha
|
||||
)
|
||||
if deps_current:
|
||||
print("→ Python dependencies unchanged — skipping reinstall")
|
||||
else:
|
||||
print("→ Updating Python dependencies...")
|
||||
from hermes_cli.managed_uv import ensure_uv, update_managed_uv
|
||||
|
||||
# Keep managed uv current — runs `uv self update` if we already have one.
|
||||
@@ -5718,12 +5773,13 @@ def _cmd_update_impl(args, gateway_mode: bool):
|
||||
uv_env.pop("PYTHONHOME", None)
|
||||
install_group = "termux-all"
|
||||
print(" → Termux detected: using uv + curated termux-all optional profile...")
|
||||
if _m()._is_termux_env(uv_env) and _is_android_python():
|
||||
print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")
|
||||
_install_psutil_android_compat([uv_bin, "pip"], env=uv_env)
|
||||
_m()._install_python_dependencies_with_optional_fallback(
|
||||
[uv_bin, "pip"], env=uv_env, group=install_group
|
||||
)
|
||||
if not deps_current:
|
||||
if _m()._is_termux_env(uv_env) and _is_android_python():
|
||||
print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")
|
||||
_install_psutil_android_compat([uv_bin, "pip"], env=uv_env)
|
||||
_m()._install_python_dependencies_with_optional_fallback(
|
||||
[uv_bin, "pip"], env=uv_env, group=install_group
|
||||
)
|
||||
else:
|
||||
# Use sys.executable to explicitly call the venv's pip module,
|
||||
# avoiding PEP 668 'externally-managed-environment' errors on Debian/Ubuntu.
|
||||
@@ -5746,14 +5802,25 @@ def _cmd_update_impl(args, gateway_mode: bool):
|
||||
if _m()._is_termux_env():
|
||||
install_group = "termux-all"
|
||||
print(" → Termux detected: using curated termux-all optional profile...")
|
||||
if _m()._is_termux_env() and _is_android_python():
|
||||
print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")
|
||||
_install_psutil_android_compat(pip_cmd)
|
||||
_m()._install_python_dependencies_with_optional_fallback(pip_cmd, group=install_group)
|
||||
if not deps_current:
|
||||
if _m()._is_termux_env() and _is_android_python():
|
||||
print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")
|
||||
_install_psutil_android_compat(pip_cmd)
|
||||
_m()._install_python_dependencies_with_optional_fallback(pip_cmd, group=install_group)
|
||||
|
||||
install_prefix = [uv_bin, "pip"] if uv_bin else pip_cmd
|
||||
lazy_env = uv_env if uv_bin else None
|
||||
|
||||
if deps_current:
|
||||
# The verification normally runs inside the install we just
|
||||
# skipped. Run it here so a wrong skip self-heals into a real
|
||||
# install (both verifiers reinstall what they find missing)
|
||||
# instead of leaving a venv nobody checked.
|
||||
_m()._verify_core_dependencies_installed(
|
||||
install_prefix, env=lazy_env, group=install_group
|
||||
)
|
||||
_m()._verify_console_scripts_installed(install_prefix, env=lazy_env)
|
||||
|
||||
# Core ``.[all]`` install finished. Clear the generic core breadcrumb
|
||||
# before the lazy-refresh phase — that phase uses its own marker so a
|
||||
# later lazy failure cannot be "healed" by clearing the core marker
|
||||
|
||||
@@ -25,6 +25,9 @@ Lanes:
|
||||
must not run it.
|
||||
* ``npm_lock`` — semantic package-lock.json diff PR comment.
|
||||
* ``installer`` — PowerShell installer tests (Windows runner).
|
||||
* ``rust`` — ``cargo test`` for the Tauri bootstrap installer. ``.rs``
|
||||
lives under ``apps/``, so without this lane a Rust change matched ``frontend``
|
||||
and only the TypeScript matrix ran.
|
||||
* ``mcp_catalog`` — bundled MCP catalog / installer review.
|
||||
|
||||
Docker is not a lane — it builds on push-to-main and release only,
|
||||
@@ -106,6 +109,13 @@ _MCP_CATALOG_FILES = {"hermes_cli/mcp_catalog.py"}
|
||||
_INSTALLER_PATHS = ("scripts/tests/",)
|
||||
_INSTALLER_FILES = {"scripts/install.ps1", "scripts/install.cmd"}
|
||||
|
||||
# Rust crates — currently just the Tauri bootstrap installer (Hermes-Setup).
|
||||
# These live under ``apps/``, so before this lane existed a ``.rs`` edit matched
|
||||
# ``frontend`` and nothing more: the TypeScript matrix built, cargo never ran,
|
||||
# and the crate's unit tests had never executed in CI at all.
|
||||
_RUST_PATHS = ("apps/bootstrap-installer/src-tauri/",)
|
||||
_RUST_FILENAMES = {"Cargo.toml", "Cargo.lock"}
|
||||
|
||||
def _is_docs(p: str) -> bool:
|
||||
if p.startswith(("skills/", "optional-skills/")):
|
||||
return False
|
||||
@@ -152,6 +162,14 @@ def _is_installer(p: str) -> bool:
|
||||
return p.startswith(_INSTALLER_PATHS) or p in _INSTALLER_FILES
|
||||
|
||||
|
||||
def _is_rust(p: str) -> bool:
|
||||
return (
|
||||
p.endswith(".rs")
|
||||
or p.startswith(_RUST_PATHS)
|
||||
or os.path.basename(p) in _RUST_FILENAMES
|
||||
)
|
||||
|
||||
|
||||
def _is_ci_review(p: str) -> bool:
|
||||
if p in _CI_REVIEW_FILES or p.startswith(_CI_REVIEW_PATHS):
|
||||
return True
|
||||
@@ -187,6 +205,7 @@ def classify(files: list[str]) -> dict[str, bool]:
|
||||
"uv_lock": any(f in ("pyproject.toml", "uv.lock") for f in files),
|
||||
"npm_lock": npm_lock,
|
||||
"installer": any(_is_installer(f) for f in files),
|
||||
"rust": any(_is_rust(f) for f in files),
|
||||
"mcp_catalog": any(_is_mcp_catalog(f) for f in files),
|
||||
"ci_review": any(_is_ci_review(f) for f in files),
|
||||
"nix": python_prod or frontend or any(_is_nix(f) for f in files)
|
||||
@@ -203,6 +222,7 @@ def classify(files: list[str]) -> dict[str, bool]:
|
||||
ret["uv_lock"] = True
|
||||
ret["npm_lock"] = True
|
||||
ret["installer"] = True
|
||||
ret["rust"] = True
|
||||
ret["nix"] = True
|
||||
ret["ci_review"] = True
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
# [--sandbox-fallback] linux: the caller vouches for a sandbox opt-out
|
||||
# (ELECTRON_DISABLE_SANDBOX / --no-sandbox launch)
|
||||
# [--no-ui] [--no-marker-cleanup] [--self-test-ui] [--self-test-gate]
|
||||
# [--self-test-marker]
|
||||
# [-- <args...>] linux: filtered launch args to replay
|
||||
#
|
||||
# The shim (ui.html in a chromeless browser app window) is decoration: it
|
||||
@@ -37,7 +38,8 @@ set -u
|
||||
ORIGINAL_ARGS=("$@")
|
||||
INSTALL_ROOT="" BRANCH="main" DESKTOP_PID=0 RELAUNCH_TARGET=""
|
||||
RELAUNCH_CWD="" SANDBOX_FALLBACK=0 RELAUNCH_ARGS=()
|
||||
NO_UI=0 NO_MARKER_CLEANUP=0 SELF_TEST_UI=0 SELF_TEST_GATE=0 HANDOFF_DAEMONIZED=0
|
||||
NO_UI=0 NO_MARKER_CLEANUP=0 SELF_TEST_UI=0 SELF_TEST_GATE=0 SELF_TEST_MARKER=0
|
||||
HANDOFF_DAEMONIZED=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--install-root) INSTALL_ROOT="$2"; shift 2 ;;
|
||||
@@ -51,6 +53,7 @@ while [ $# -gt 0 ]; do
|
||||
--self-test-ui) SELF_TEST_UI=1; shift ;;
|
||||
--self-test-gate) SELF_TEST_GATE=1; shift ;;
|
||||
--daemonized) HANDOFF_DAEMONIZED=1; shift ;;
|
||||
--self-test-marker) SELF_TEST_MARKER=1; NO_UI=1; NO_MARKER_CLEANUP=1; shift ;;
|
||||
--) shift; RELAUNCH_ARGS=("$@"); shift $# ;;
|
||||
*) echo "unknown arg: $1" >&2; exit 64 ;;
|
||||
esac
|
||||
@@ -466,7 +469,23 @@ rm -f "$RESULT" 2>/dev/null || true
|
||||
|
||||
# Marker claim: same cross-process lock contract as windows.ps1 /
|
||||
# update_lock.py (the `hermes update` child adopts it via process ancestry).
|
||||
printf '%s\n%s\n' "$$" "$(date +%s)" > "$MARKER" 2>/dev/null || log "WARNING: could not write update marker"
|
||||
# The Desktop supplies one acquisition time for the whole ownership chain.
|
||||
NOW="$(date +%s)"
|
||||
STARTED_AT="${HERMES_UPDATE_STARTED_AT:-$NOW}"
|
||||
case "$STARTED_AT" in ''|*[!0-9]*) STARTED_AT="$NOW" ;; esac
|
||||
MIN_STARTED_AT=$((NOW - 1200))
|
||||
# Compare the validated decimal strings before doing arithmetic. Shell integer
|
||||
# expansion can wrap on an attacker-controlled value wider than signed 64-bit.
|
||||
if [ "${#STARTED_AT}" -ne "${#NOW}" ] \
|
||||
|| [[ "$STARTED_AT" > "$NOW" || "$STARTED_AT" < "$MIN_STARTED_AT" ]]; then
|
||||
STARTED_AT="$NOW"
|
||||
fi
|
||||
printf '%s\n%s\n' "$$" "$STARTED_AT" > "$MARKER" 2>/dev/null || log "WARNING: could not write update marker"
|
||||
|
||||
if [ "$SELF_TEST_MARKER" -eq 1 ]; then
|
||||
trap - EXIT
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Wait out the Desktop (FAIL CLOSED: updating under live backends bricks).
|
||||
if [ "$DESKTOP_PID" -gt 0 ] 2>/dev/null; then
|
||||
|
||||
@@ -35,7 +35,8 @@
|
||||
#
|
||||
# Marker: we claim HERMES_HOME\.hermes-update-in-progress with OUR pid as
|
||||
# step 0 (the wrapper cmd.exe pid the Desktop saw is useless -- it exits
|
||||
# immediately). hermes_cli/update_lock.py's ancestry rule lets our
|
||||
# immediately), retaining HERMES_UPDATE_STARTED_AT from the Desktop hand-off.
|
||||
# hermes_cli/update_lock.py's ancestry rule lets our
|
||||
# `hermes update` child adopt the claim; electron/update-marker.ts parks a
|
||||
# relaunched Desktop on it. Cleanup only removes the marker while WE still
|
||||
# own it (a handoff partner that rewrote it keeps its claim).
|
||||
@@ -47,12 +48,14 @@ param(
|
||||
[string]$RelaunchExe = "",
|
||||
[switch]$NoUi,
|
||||
[switch]$NoMarkerCleanup,
|
||||
[switch]$SelfTestUi
|
||||
[switch]$SelfTestUi,
|
||||
[switch]$SelfTestPipeDrain,
|
||||
[switch]$SelfTestMarker
|
||||
)
|
||||
|
||||
if (-not $SelfTestUi -and -not $InstallRoot) {
|
||||
# Mandatory in spirit; relaxed in the signature only so -SelfTestUi can
|
||||
# drive the UI without a checkout.
|
||||
if (-not $SelfTestUi -and -not $SelfTestPipeDrain -and -not $InstallRoot) {
|
||||
# Mandatory in spirit; relaxed in the signature only so the self-test
|
||||
# switches can drive the UI / the pipe drain without a checkout.
|
||||
throw "-InstallRoot is required"
|
||||
}
|
||||
|
||||
@@ -583,6 +586,59 @@ function Start-DesktopRelaunch {
|
||||
return $spawned
|
||||
}
|
||||
|
||||
# How long a step's pipes get to reach EOF AFTER the step process itself has
|
||||
# exited (#90455). This is not a step timeout -- the step is already gone by
|
||||
# the time the clock starts, and everything it wrote is sitting in the pipe
|
||||
# buffer ready to read, so the grace only has to cover the final drain.
|
||||
#
|
||||
# It exists because pipe EOF is not the child's to give. Windows hands the
|
||||
# write end of a redirected pipe to the child as an INHERITABLE handle, so
|
||||
# every descendant that is spawned without its own redirection gets a
|
||||
# duplicate -- and the read side does not see EOF until the last of them
|
||||
# closes it. `hermes update` deliberately runs its build steps with stdout
|
||||
# inherited (hermes_cli/main.py, the tee-stderr runner), so the tree under a
|
||||
# step is arbitrarily deep and not something this script can enumerate. When
|
||||
# one of those descendants is a resident gateway, the pipe stays open for the
|
||||
# life of the gateway, i.e. forever.
|
||||
#
|
||||
# Overridable so the pipe-drain self-test does not have to sit out the real
|
||||
# grace; not documented as a user knob.
|
||||
$script:StepDrainGraceSeconds = 20
|
||||
if ($env:HERMES_UPDATE_PIPE_DRAIN_SECONDS) {
|
||||
$parsedGrace = 0
|
||||
if ([int]::TryParse($env:HERMES_UPDATE_PIPE_DRAIN_SECONDS, [ref]$parsedGrace) -and $parsedGrace -ge 0) {
|
||||
$script:StepDrainGraceSeconds = $parsedGrace
|
||||
}
|
||||
}
|
||||
|
||||
function Step-PipeDrain($Reader, [ref]$Task, $Buffer, $Sink, [ref]$Moved) {
|
||||
# Advance one redirected pipe by whatever has already arrived, without
|
||||
# ever blocking. Returns $true once the pipe has reached EOF (or its read
|
||||
# faulted), $false while more may still come. Sets $Moved when this call
|
||||
# actually consumed bytes, so the caller can tell a busy pipe from a quiet
|
||||
# one and skip its idle wait.
|
||||
#
|
||||
# The chunked ReadAsync loop is the point: ReadToEndAsync().Result cannot
|
||||
# hand back a partial read, so abandoning it loses the whole step's output.
|
||||
# Draining into a StringBuilder means an abandoned pipe still yields every
|
||||
# byte that arrived before we gave up.
|
||||
if ($null -eq $Task.Value) { return $true }
|
||||
if (-not $Task.Value.IsCompleted) { return $false }
|
||||
$count = 0
|
||||
try {
|
||||
$count = $Task.Value.Result
|
||||
} catch {
|
||||
# Faulted/cancelled read: treat as EOF rather than retrying forever.
|
||||
$Task.Value = $null
|
||||
return $true
|
||||
}
|
||||
if ($count -le 0) { $Task.Value = $null; return $true }
|
||||
[void]$Sink.Append($Buffer, 0, $count)
|
||||
$Moved.Value = $true
|
||||
$Task.Value = $Reader.ReadAsync($Buffer, 0, $Buffer.Length)
|
||||
return $false
|
||||
}
|
||||
|
||||
function Invoke-HermesStep([string]$Exe, [string[]]$HermesArgs, [string]$Tag) {
|
||||
# The window does not stream child output, so no line-pump: both pipes
|
||||
# drain asynchronously (no deadlock however chatty the child) while a small
|
||||
@@ -590,6 +646,15 @@ function Invoke-HermesStep([string]$Exe, [string[]]$HermesArgs, [string]$Tag) {
|
||||
# stretches (pip installs) -- the old EndOfStream pump blocked on quiet
|
||||
# children and froze it. Full output still lands in the hand-off log
|
||||
# afterwards, where `hermes debug share` picks it up.
|
||||
#
|
||||
# The drain is bounded once the step exits (#90455). Waiting for pipe EOF
|
||||
# is waiting on the step's whole surviving descendant tree, and this
|
||||
# function sits upstream of every terminal obligation the hand-off has --
|
||||
# .hermes-update-result.json, clearing .hermes-update-in-progress,
|
||||
# relaunching the Desktop. One resident grandchild holding an inherited
|
||||
# handle used to strand all three and leave the Desktop on "Updating
|
||||
# Hermes" until the user killed something by hand. Losing the tail of a
|
||||
# log is the strictly better failure.
|
||||
# System.Diagnostics.Process directly: Start-Process's .ExitCode is
|
||||
# unreliably $null under PS 5.1 even with the Handle-touch workaround.
|
||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||||
@@ -611,15 +676,64 @@ function Invoke-HermesStep([string]$Exe, [string[]]$HermesArgs, [string]$Tag) {
|
||||
$psi.EnvironmentVariables["PYTHONUTF8"] = "1"
|
||||
$psi.CreateNoWindow = $true
|
||||
$proc = [System.Diagnostics.Process]::Start($psi)
|
||||
$outTask = $proc.StandardOutput.ReadToEndAsync()
|
||||
$errTask = $proc.StandardError.ReadToEndAsync()
|
||||
while (-not $proc.HasExited) {
|
||||
Start-Sleep -Milliseconds 150
|
||||
$outSink = New-Object System.Text.StringBuilder
|
||||
$errSink = New-Object System.Text.StringBuilder
|
||||
$outBuffer = New-Object char[] 16384
|
||||
$errBuffer = New-Object char[] 16384
|
||||
$outTask = $proc.StandardOutput.ReadAsync($outBuffer, 0, $outBuffer.Length)
|
||||
$errTask = $proc.StandardError.ReadAsync($errBuffer, 0, $errBuffer.Length)
|
||||
$abandonAt = $null
|
||||
$abandoned = $false
|
||||
while ($true) {
|
||||
$moved = $false
|
||||
$outDone = Step-PipeDrain $proc.StandardOutput ([ref]$outTask) $outBuffer $outSink ([ref]$moved)
|
||||
$errDone = Step-PipeDrain $proc.StandardError ([ref]$errTask) $errBuffer $errSink ([ref]$moved)
|
||||
if ($proc.HasExited) {
|
||||
if ($outDone -and $errDone) { break }
|
||||
# Clock starts at the step's exit, not at its start: a slow step is
|
||||
# not a stuck one, and only a pipe outliving its process is.
|
||||
if ($null -eq $abandonAt) {
|
||||
$abandonAt = (Get-Date).AddSeconds($script:StepDrainGraceSeconds)
|
||||
} elseif ((Get-Date) -ge $abandonAt) {
|
||||
$abandoned = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
# Only idle when both pipes came up empty this pass, and idle on the
|
||||
# reads themselves rather than on the clock.
|
||||
#
|
||||
# Sleeping after a chunk that DID arrive meters the drain at one buffer
|
||||
# per tick (16 KiB / 150ms ~ 107 KB/s), and because the pipe then backs
|
||||
# up that is backpressure on the running step, not just a slow read --
|
||||
# a chatty step blocks on write() waiting for us. Waiting for EOF and
|
||||
# trickling toward it are two ways to make a fast step slow, and this
|
||||
# function is upstream of the hand-off's obligations either way.
|
||||
#
|
||||
# A flat sleep is not enough on its own: a freshly issued ReadAsync is
|
||||
# rarely complete by the very next pass, so the loop would sleep 150ms
|
||||
# between chunks anyway. WaitAny returns the instant either pipe has
|
||||
# something (and immediately if one already does), and expires on its
|
||||
# own so a silent step still animates the marquee and still advances
|
||||
# the abandon deadline.
|
||||
if (-not $moved) {
|
||||
$live = @($outTask, $errTask) | Where-Object { $null -ne $_ }
|
||||
if ($live.Count -gt 0) {
|
||||
[void][System.Threading.Tasks.Task]::WaitAny([System.Threading.Tasks.Task[]]$live, 150)
|
||||
} else {
|
||||
Start-Sleep -Milliseconds 150
|
||||
}
|
||||
}
|
||||
if ($script:Ui) { [System.Windows.Forms.Application]::DoEvents() }
|
||||
}
|
||||
$proc.WaitForExit()
|
||||
$outText = $outTask.Result
|
||||
$errText = $errTask.Result
|
||||
# Bounded overload deliberately: the argument-less overload also waits on
|
||||
# redirected streams, which is the very wait we just bounded. HasExited is
|
||||
# already true here, so this call only settles ExitCode.
|
||||
[void]$proc.WaitForExit(5000)
|
||||
if ($abandoned) {
|
||||
Write-HandoffLog ("{0}!| pipe drain abandoned after {1}s: '{0}' exited but a surviving descendant still holds its stdout/stderr handles. Continuing the hand-off with the output captured so far (#90455)." -f $Tag, $script:StepDrainGraceSeconds)
|
||||
}
|
||||
$outText = $outSink.ToString()
|
||||
$errText = $errSink.ToString()
|
||||
foreach ($ln in ($outText -split "`r?`n")) {
|
||||
if ($ln.Trim()) { Write-HandoffLog ("{0}| {1}" -f $Tag, $ln) }
|
||||
}
|
||||
@@ -665,6 +779,119 @@ if ($SelfTestUi) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
# -SelfTestPipeDrain: prove Invoke-HermesStep survives a leaked pipe ------
|
||||
# The #90455 deadlock needs no update, no checkout and no Hermes install to
|
||||
# reproduce -- only a step whose grandchild outlives it holding the inherited
|
||||
# write end of the redirected pipe. That is exactly what this builds, so the
|
||||
# fix has an executable proof on Windows instead of a source-grep. Exits
|
||||
# before any marker/desktop machinery, same as -SelfTestUi; touches nothing
|
||||
# but its own temp files.
|
||||
#
|
||||
# Two arms, because the bound and the drain rate fail in opposite directions:
|
||||
#
|
||||
# leak -- a step whose grandchild outlives it. Guards the #90455 deadlock:
|
||||
# the drain must abandon rather than wait out the descendant.
|
||||
# flood -- a chatty step that leaks nothing. Guards the other cliff: a drain
|
||||
# that idles after every chunk it reads is metered at one buffer per
|
||||
# tick, which backpressures the running step. Waiting for EOF and
|
||||
# trickling toward it are both ways to make a fast step slow.
|
||||
if ($SelfTestPipeDrain) {
|
||||
New-Item -ItemType Directory -Path $LogDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
$hold = 60
|
||||
if ($env:HERMES_SELFTEST_HOLD_SECONDS) { $hold = [int]$env:HERMES_SELFTEST_HOLD_SECONDS }
|
||||
$floodKb = 8192
|
||||
if ($env:HERMES_SELFTEST_FLOOD_KB) { $floodKb = [int]$env:HERMES_SELFTEST_FLOOD_KB }
|
||||
# $PSHOME is this interpreter's own directory -- no hardcoded system path.
|
||||
$powershell = Join-Path $PSHOME "powershell.exe"
|
||||
$stamp = [Guid]::NewGuid().ToString("N")
|
||||
$childPs1 = Join-Path $TempDir "hermes-pipe-drain-$stamp.ps1"
|
||||
$floodPs1 = Join-Path $TempDir "hermes-pipe-flood-$stamp.ps1"
|
||||
$pidFile = Join-Path $TempDir "hermes-pipe-drain-$stamp.pid"
|
||||
# UseShellExecute=$false with no redirection is what makes the grandchild
|
||||
# inherit our stdout/stderr -- the whole point of the fixture. Anything
|
||||
# that redirects (Start-Process, subprocess with stdout=DEVNULL) would
|
||||
# close the handle and the deadlock would not reproduce.
|
||||
$childSource = @'
|
||||
param([int]$Hold, [string]$PidFile)
|
||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||||
$psi.FileName = Join-Path $PSHOME "powershell.exe"
|
||||
$psi.Arguments = "-NoProfile -Command Start-Sleep -Seconds $Hold"
|
||||
$psi.UseShellExecute = $false
|
||||
$psi.CreateNoWindow = $true
|
||||
$grandchild = [System.Diagnostics.Process]::Start($psi)
|
||||
[System.IO.File]::WriteAllText($PidFile, [string]$grandchild.Id)
|
||||
Write-Output "pipe-drain step output"
|
||||
[Console]::Out.Flush()
|
||||
exit 7
|
||||
'@
|
||||
# Writes straight to the console stream, holding nothing: a step that is
|
||||
# merely loud. `hermes update` is this shape -- the Electron/vite build
|
||||
# alone is megabytes. Few large lines rather than many small ones on
|
||||
# purpose: Write-HandoffLog is one Add-Content per line and runs inside the
|
||||
# measured window, so line-heavy output would time the logger instead of
|
||||
# the drain.
|
||||
$floodSource = @'
|
||||
param([int]$Kb)
|
||||
$chunk = "x" * (131072 - 1)
|
||||
for ($i = 0; $i -lt [Math]::Ceiling($Kb / 128); $i++) { [Console]::Out.Write($chunk + "`n") }
|
||||
[Console]::Out.Flush()
|
||||
exit 5
|
||||
'@
|
||||
[System.IO.File]::WriteAllText($childPs1, $childSource)
|
||||
[System.IO.File]::WriteAllText($floodPs1, $floodSource)
|
||||
$sw = [System.Diagnostics.Stopwatch]::StartNew()
|
||||
$res = Invoke-HermesStep $powershell @(
|
||||
"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $childPs1,
|
||||
"-Hold", [string]$hold, "-PidFile", $pidFile
|
||||
) "pipedrain"
|
||||
$sw.Stop()
|
||||
$elapsed = [Math]::Round($sw.Elapsed.TotalSeconds, 2)
|
||||
|
||||
$leakPid = 0
|
||||
if (Test-Path -LiteralPath $pidFile) {
|
||||
[void][int]::TryParse((Get-Content -LiteralPath $pidFile -Raw).Trim(), [ref]$leakPid)
|
||||
}
|
||||
$leakAlive = $false
|
||||
if ($leakPid -gt 0) {
|
||||
$leakAlive = [bool](Get-Process -Id $leakPid -ErrorAction SilentlyContinue)
|
||||
Stop-Process -Id $leakPid -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
$floodSw = [System.Diagnostics.Stopwatch]::StartNew()
|
||||
$flood = Invoke-HermesStep $powershell @(
|
||||
"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $floodPs1,
|
||||
"-Kb", [string]$floodKb
|
||||
) "pipeflood"
|
||||
$floodSw.Stop()
|
||||
$floodElapsed = [Math]::Round($floodSw.Elapsed.TotalSeconds, 2)
|
||||
$floodBytes = $flood.Output.Length
|
||||
|
||||
Remove-Item -LiteralPath $childPs1, $floodPs1, $pidFile -Force -ErrorAction SilentlyContinue
|
||||
|
||||
# The grandchild still being alive at return is what makes this a proof
|
||||
# rather than a timing coincidence: the pipe was demonstrably still open.
|
||||
$budget = $script:StepDrainGraceSeconds + 30
|
||||
# A sleep-per-chunk drain moves 16 KiB/150ms ~ 107 KB/s, so 8 MiB takes
|
||||
# ~76s. Generous enough for a loaded CI runner, far under the trickle.
|
||||
$floodBudget = 25
|
||||
$problems = @()
|
||||
if (-not $leakAlive) { $problems += "handle-holding grandchild was not alive on return (fixture did not reproduce the leak)" }
|
||||
if ($elapsed -ge $budget) { $problems += "leak arm returned in ${elapsed}s, over the ${budget}s budget" }
|
||||
if ($res.Code -ne 7) { $problems += "leak arm exit code $($res.Code), expected 7" }
|
||||
if ($res.Output -notmatch "pipe-drain step output") { $problems += "leak arm step output was lost" }
|
||||
if ($floodElapsed -ge $floodBudget) { $problems += "flood arm returned in ${floodElapsed}s, over the ${floodBudget}s budget -- the drain is metering itself, which backpressures the step" }
|
||||
if ($flood.Code -ne 5) { $problems += "flood arm exit code $($flood.Code), expected 5" }
|
||||
if ($floodBytes -lt ($floodKb * 1024)) { $problems += "flood arm captured $floodBytes bytes of $($floodKb * 1024)" }
|
||||
|
||||
$detail = "leak: elapsed=${elapsed}s budget=${budget}s code=$($res.Code) grandchildAlive=$leakAlive | flood: ${floodKb}KB in ${floodElapsed}s budget=${floodBudget}s bytes=$floodBytes code=$($flood.Code)"
|
||||
if ($problems.Count -gt 0) {
|
||||
Write-Host "PIPE-DRAIN SELF-TEST: FAIL $detail -- $($problems -join '; ')"
|
||||
exit 1
|
||||
}
|
||||
Write-Host "PIPE-DRAIN SELF-TEST: PASS $detail"
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
New-Item -ItemType Directory -Path $LogDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
Remove-Item -LiteralPath $ResultPath -Force -ErrorAction SilentlyContinue
|
||||
@@ -674,14 +901,25 @@ try {
|
||||
# -- 0. Claim the update marker with OUR pid ---------------------------
|
||||
try {
|
||||
$epoch = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
|
||||
$startedAt = 0L
|
||||
$hasStartedAt = [int64]::TryParse($env:HERMES_UPDATE_STARTED_AT, [ref]$startedAt)
|
||||
if (-not $hasStartedAt -or $startedAt -gt $epoch -or ($epoch - $startedAt) -gt 1200) {
|
||||
$startedAt = $epoch
|
||||
}
|
||||
# WriteAllText for byte-exact LF framing: Set-Content emits CRLF and
|
||||
# the marker contract (Rust/TS/Python readers) is "<pid>\n<ts>\n".
|
||||
[System.IO.File]::WriteAllText($MarkerPath, "$PID`n$epoch`n")
|
||||
[System.IO.File]::WriteAllText($MarkerPath, "$PID`n$startedAt`n")
|
||||
Write-HandoffLog "claimed update marker (pid $PID)"
|
||||
} catch {
|
||||
Write-HandoffLog "WARNING: could not write update marker: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
if ($SelfTestMarker) {
|
||||
$finalCode = 0
|
||||
$finalMsg = "marker self-test complete"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# -- 1. Wait for the Desktop to exit (FAIL CLOSED) ----------------------
|
||||
Publish-UiProgress "Waiting for Hermes to close"
|
||||
if ($DesktopPid -gt 0) {
|
||||
|
||||
@@ -81,7 +81,13 @@ The ONLY import surface is `@hermes/plugin-sdk` (plus `react` /
|
||||
`'panes'` (layout zones — set `title` and
|
||||
`data: { placement, dock?, width?, height? }`; the pane auto-joins a
|
||||
matching zone), `PALETTE_AREA` (⌘K commands), `KEYBINDS_AREA` (rebindable
|
||||
actions).
|
||||
actions), `THEMES_AREA` (`data` is a full `DesktopTheme`).
|
||||
- THEMES: registering one only lists it in the picker. Select it with
|
||||
`useTheme().setTheme(name)` from a component, or `requestTheme(name)` from a
|
||||
callback with no component around it (a gateway event, a socket handler).
|
||||
`requestTheme` returns `false` for a name that doesn't resolve and leaves the
|
||||
appearance alone, so use it as the availability check instead of coercing the
|
||||
user back to the default skin.
|
||||
- Pane placement: `placement: 'left'|'right'|'bottom'|'main'` is the
|
||||
semantic role — the pane stacks (tabs) with existing panes of that role.
|
||||
To land on a specific EDGE instead, add `dock: { pane, pos }` — the same
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""'Thinking off' on the native Anthropic Messages wire.
|
||||
|
||||
Adaptive Claude models (4.6+) think by DEFAULT. Omitting the ``thinking``
|
||||
parameter is therefore NOT a disable — it leaves the upstream default in
|
||||
place and the model keeps thinking, which is exactly what a user who turned
|
||||
thinking off is trying to stop paying for. The disable has to be sent:
|
||||
|
||||
thinking: {"type": "disabled"}
|
||||
|
||||
Reasoning-mandatory families (claude-fable) reject that with an HTTP 400
|
||||
("Thinking is mandatory for this model"), so they keep the omission — a
|
||||
silently-ignored disable is a much better failure than a dead turn.
|
||||
|
||||
Legacy manual-thinking Claude (<= 4.5) needs no disable at all: thinking is
|
||||
opt-in there via ``budget_tokens``, so sending nothing already means off.
|
||||
|
||||
Sibling contract on the chat_completions wire: hermes-agent#90412.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.anthropic_adapter import build_anthropic_kwargs
|
||||
|
||||
MESSAGES = [{"role": "user", "content": "hello"}]
|
||||
|
||||
# Portal ids and their bare Anthropic equivalents: the disable verdict is a
|
||||
# property of the model family, not of which route serves it.
|
||||
ADAPTIVE_DISABLEABLE = [
|
||||
"anthropic/claude-opus-5",
|
||||
"anthropic/claude-sonnet-5",
|
||||
"anthropic/claude-opus-4.8",
|
||||
"anthropic/claude-opus-4.7",
|
||||
"anthropic/claude-opus-4.6",
|
||||
"anthropic/claude-sonnet-4.6",
|
||||
"claude-opus-4-6",
|
||||
]
|
||||
|
||||
|
||||
def _kwargs(model: str, reasoning_config: dict | None, **extra):
|
||||
return build_anthropic_kwargs(
|
||||
model=model,
|
||||
messages=MESSAGES,
|
||||
tools=None,
|
||||
max_tokens=4096,
|
||||
reasoning_config=reasoning_config,
|
||||
**extra,
|
||||
)
|
||||
|
||||
|
||||
class TestThinkingOffIsSentExplicitly:
|
||||
@pytest.mark.parametrize("model", ADAPTIVE_DISABLEABLE)
|
||||
def test_adaptive_models_receive_an_explicit_disable(self, model: str) -> None:
|
||||
"""The whole point: omission would leave thinking ON for these."""
|
||||
kwargs = _kwargs(model, {"enabled": False})
|
||||
assert kwargs["thinking"] == {"type": "disabled"}
|
||||
|
||||
@pytest.mark.parametrize("model", ADAPTIVE_DISABLEABLE)
|
||||
def test_disable_carries_no_effort_dial(self, model: str) -> None:
|
||||
"""``output_config.effort`` describes how hard to think — meaningless
|
||||
alongside a disable, and it is what the enable path sets."""
|
||||
kwargs = _kwargs(model, {"enabled": False, "effort": "high"})
|
||||
assert kwargs["thinking"] == {"type": "disabled"}
|
||||
assert "output_config" not in kwargs
|
||||
|
||||
def test_mandatory_thinking_models_keep_the_omission(self) -> None:
|
||||
"""claude-fable answers a disable with HTTP 400, so don't send one."""
|
||||
kwargs = _kwargs("anthropic/claude-fable-5", {"enabled": False})
|
||||
assert "thinking" not in kwargs
|
||||
|
||||
def test_legacy_manual_thinking_models_keep_the_omission(self) -> None:
|
||||
"""Pre-4.6 thinking is opt-in via budget_tokens: absence IS off."""
|
||||
kwargs = _kwargs("claude-sonnet-4-5", {"enabled": False})
|
||||
assert "thinking" not in kwargs
|
||||
|
||||
def test_haiku_keeps_the_omission(self) -> None:
|
||||
"""Haiku is legacy-manual, so absence already means off."""
|
||||
kwargs = _kwargs("anthropic/claude-haiku-4.5", {"enabled": False})
|
||||
assert "thinking" not in kwargs
|
||||
|
||||
def test_kimi_keeps_its_documented_omission(self) -> None:
|
||||
"""Kimi speaks the adaptive contract but is out of scope here (#13848)."""
|
||||
kwargs = _kwargs(
|
||||
"kimi-k2.5", {"enabled": False}, base_url="https://api.kimi.com/coding"
|
||||
)
|
||||
assert "thinking" not in kwargs
|
||||
|
||||
|
||||
class TestEnablePathIsUnchanged:
|
||||
"""The disable branch must not disturb the thinking-ON contract."""
|
||||
|
||||
def test_adaptive_enable_still_sends_adaptive_plus_effort(self) -> None:
|
||||
kwargs = _kwargs("anthropic/claude-opus-5", {"enabled": True, "effort": "high"})
|
||||
assert kwargs["thinking"] == {"type": "adaptive", "display": "summarized"}
|
||||
assert kwargs["output_config"] == {"effort": "high"}
|
||||
|
||||
def test_mandatory_model_still_thinks_when_asked_to(self) -> None:
|
||||
kwargs = _kwargs("anthropic/claude-fable-5", {"enabled": True, "effort": "max"})
|
||||
assert kwargs["thinking"] == {"type": "adaptive", "display": "summarized"}
|
||||
assert kwargs["output_config"] == {"effort": "max"}
|
||||
|
||||
def test_legacy_enable_still_sends_budget_tokens(self) -> None:
|
||||
kwargs = _kwargs("claude-sonnet-4-5", {"enabled": True, "effort": "high"})
|
||||
assert kwargs["thinking"] == {"type": "enabled", "budget_tokens": 16000}
|
||||
|
||||
def test_haiku_still_never_gets_thinking_on_the_enable_path(self) -> None:
|
||||
kwargs = _kwargs("anthropic/claude-haiku-4.5", {"enabled": True, "effort": "high"})
|
||||
assert "thinking" not in kwargs
|
||||
|
||||
def test_no_reasoning_config_sends_no_thinking_field(self) -> None:
|
||||
assert "thinking" not in _kwargs("anthropic/claude-opus-5", None)
|
||||
|
||||
|
||||
class TestDisableVerdictHelper:
|
||||
"""``_accepts_thinking_disable`` is the single source of the verdict."""
|
||||
|
||||
def test_verdict_matches_the_mandatory_flag_the_catalog_publishes(self) -> None:
|
||||
from agent.anthropic_adapter import _accepts_thinking_disable
|
||||
|
||||
# Portal catalog: reasoning.mandatory is true for fable, false for these.
|
||||
assert _accepts_thinking_disable("anthropic/claude-opus-5") is True
|
||||
assert _accepts_thinking_disable("anthropic/claude-sonnet-5") is True
|
||||
assert _accepts_thinking_disable("anthropic/claude-fable-5") is False
|
||||
|
||||
def test_non_claude_models_are_left_alone(self) -> None:
|
||||
from agent.anthropic_adapter import _accepts_thinking_disable
|
||||
|
||||
for model in ("minimax-m2.7", "qwen3-max", "kimi-k2.5"):
|
||||
assert _accepts_thinking_disable(model) is False, model
|
||||
|
||||
def test_unknown_claude_releases_default_to_disableable(self) -> None:
|
||||
"""Mirrors _supports_adaptive_thinking: new Claude gets the modern
|
||||
contract without a code change."""
|
||||
from agent.anthropic_adapter import _accepts_thinking_disable
|
||||
|
||||
assert _accepts_thinking_disable("anthropic/claude-opus-6") is True
|
||||
@@ -8,6 +8,7 @@ change could have broken.
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -34,12 +35,13 @@ DEFAULT = {
|
||||
"uv_lock": True,
|
||||
"npm_lock": True,
|
||||
"installer": True,
|
||||
"rust": True,
|
||||
"mcp_catalog": False,
|
||||
"ci_review": True,
|
||||
}
|
||||
|
||||
|
||||
def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_lock=False, npm_lock=False, installer=False, mcp_catalog=False, docker_meta=False, ci_review=False, python_prod=None, nix=None, docker=None) -> dict[str, bool]:
|
||||
def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_lock=False, npm_lock=False, installer=False, rust=False, mcp_catalog=False, docker_meta=False, ci_review=False, python_prod=None, nix=None, docker=None) -> dict[str, bool]:
|
||||
# python_prod tracks python except for tests-only diffs; default it to
|
||||
# python so the majority of cases don't need to spell it out.
|
||||
#
|
||||
@@ -61,6 +63,7 @@ def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_
|
||||
"uv_lock": uv_lock,
|
||||
"npm_lock": npm_lock,
|
||||
"installer": installer,
|
||||
"rust": rust,
|
||||
"mcp_catalog": mcp_catalog,
|
||||
"ci_review": ci_review,
|
||||
}
|
||||
@@ -132,6 +135,26 @@ CASES = {
|
||||
_lanes(python=True, installer=True),
|
||||
),
|
||||
"python source alone → no installer lane": (["run_agent.py"], _lanes(python=True, scan=True)),
|
||||
# `.rs` lives under apps/, so it matches `frontend` too. That lane builds
|
||||
# TypeScript and cannot notice a Rust error — before `rust` existed it was
|
||||
# the ONLY lane a Rust change ran, and the crate's tests never executed.
|
||||
"rust source → rust": (
|
||||
["apps/bootstrap-installer/src-tauri/src/powershell.rs"],
|
||||
_lanes(frontend=True, rust=True),
|
||||
),
|
||||
"cargo lockfile → rust": (
|
||||
["apps/bootstrap-installer/src-tauri/Cargo.lock"],
|
||||
_lanes(frontend=True, rust=True),
|
||||
),
|
||||
# Non-.rs files in the crate still change what cargo builds.
|
||||
"tauri config → rust": (
|
||||
["apps/bootstrap-installer/src-tauri/tauri.conf.json"],
|
||||
_lanes(frontend=True, rust=True),
|
||||
),
|
||||
"ts source alone → no rust lane": (
|
||||
["apps/bootstrap-installer/src/main.tsx"],
|
||||
_lanes(frontend=True),
|
||||
),
|
||||
# Unknown top-level file keeps Python on rather than risk a silent skip.
|
||||
"unknown toplevel → python": (["Makefile"], _lanes(python=True)),
|
||||
"mixed docs+python → python": (["README.md", "agent/x.py"], _lanes(python=True, scan=True)),
|
||||
@@ -218,6 +241,55 @@ def test_classify(files, expected):
|
||||
assert classify(files) == expected
|
||||
|
||||
|
||||
_REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _yaml(rel: str) -> dict:
|
||||
yaml = pytest.importorskip("yaml")
|
||||
return yaml.safe_load((_REPO / rel).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def test_every_lane_reaches_the_composite_action():
|
||||
"""The action is the one surface every consumer reads, so it must carry all
|
||||
of them — ci.yaml, nix.yml and docker.yml each re-export a different subset.
|
||||
"""
|
||||
lanes = set(classify(["run_agent.py"]))
|
||||
action_outputs = set(_yaml(".github/actions/detect-changes/action.yml")["outputs"])
|
||||
assert lanes - action_outputs == set(), "lane(s) missing from the composite action's outputs"
|
||||
|
||||
|
||||
def test_ci_jobs_only_gate_on_detect_outputs_that_detect_actually_declares():
|
||||
"""An ``if`` that reads an undeclared output resolves to the empty string.
|
||||
|
||||
The lane then reports "skipping" on every PR, forever, and nothing goes red
|
||||
— there is no error for referencing an output a job never declared. That is
|
||||
exactly how the ``rust`` lane shipped dead: the classifier emitted it and
|
||||
the composite action re-exported it, but ci.yaml's ``detect`` job did not,
|
||||
so ``needs.detect.outputs.rust`` was never anything but "".
|
||||
"""
|
||||
ci = _yaml(".github/workflows/ci.yaml")
|
||||
declared = set(ci["jobs"]["detect"]["outputs"])
|
||||
|
||||
referenced: set[str] = set()
|
||||
for job in ci["jobs"].values():
|
||||
for expr in _iter_if_expressions(job):
|
||||
referenced.update(re.findall(r"needs\.detect\.outputs\.(\w+)", expr))
|
||||
|
||||
assert referenced, "found no detect-gated jobs — the walk is broken, not the wiring"
|
||||
assert referenced - declared == set(), "job(s) gate on an output detect never declares"
|
||||
|
||||
|
||||
def _iter_if_expressions(job: object):
|
||||
"""Yield every ``if:`` string in a job, including inside its steps."""
|
||||
if not isinstance(job, dict):
|
||||
return
|
||||
if isinstance(cond := job.get("if"), str):
|
||||
yield cond
|
||||
for step in job.get("steps", []) or []:
|
||||
if isinstance(step, dict) and isinstance(cond := step.get("if"), str):
|
||||
yield cond
|
||||
|
||||
|
||||
def test_ci_review_files_returns_only_sensitive_paths_sorted_and_unique():
|
||||
assert ci_review_files([
|
||||
"apps/desktop/src/app.tsx",
|
||||
|
||||
@@ -193,7 +193,7 @@ def fake_subprocess_run(monkeypatch: pytest.MonkeyPatch):
|
||||
|
||||
|
||||
def test_seed_supervise_skeleton_creates_expected_layout(tmp_path) -> None:
|
||||
"""Verifies the dirs + FIFO + modes the helper lays down."""
|
||||
"""Verifies the dirs + FIFO the helper lays down."""
|
||||
import stat
|
||||
|
||||
from hermes_cli.service_manager import _seed_supervise_skeleton
|
||||
@@ -206,9 +206,6 @@ def test_seed_supervise_skeleton_creates_expected_layout(tmp_path) -> None:
|
||||
# Top-level event/ — s6-svlisten1 event subscription dir.
|
||||
event = svc_dir / "event"
|
||||
assert event.is_dir(), "missing top-level event/"
|
||||
assert stat.S_IMODE(event.stat().st_mode) == 0o3730, (
|
||||
f"event/ mode = {oct(event.stat().st_mode)}, want 03730"
|
||||
)
|
||||
|
||||
# supervise/ dir.
|
||||
supervise = svc_dir / "supervise"
|
||||
@@ -218,7 +215,6 @@ def test_seed_supervise_skeleton_creates_expected_layout(tmp_path) -> None:
|
||||
# supervise/event/.
|
||||
supervise_event = supervise / "event"
|
||||
assert supervise_event.is_dir(), "missing supervise/event/"
|
||||
assert stat.S_IMODE(supervise_event.stat().st_mode) == 0o3730
|
||||
|
||||
# supervise/control FIFO.
|
||||
control = supervise / "control"
|
||||
@@ -229,6 +225,31 @@ def test_seed_supervise_skeleton_creates_expected_layout(tmp_path) -> None:
|
||||
assert stat.S_IMODE(control.stat().st_mode) == 0o660
|
||||
|
||||
|
||||
@pytest.mark.linux_only
|
||||
def test_seed_supervise_skeleton_sets_setgid_on_event_dirs(tmp_path) -> None:
|
||||
"""The event dirs carry setgid so s6-supervise's EEXIST path leaves them alone.
|
||||
|
||||
Linux-only because the assertion is about what ``chmod`` does, and that
|
||||
differs by kernel: BSD (macOS) silently drops ``S_ISGID`` from a directory
|
||||
unless the caller is root or a member of the directory's group, so the same
|
||||
correct helper produces 01730 there. s6 only ever runs on Linux — inside
|
||||
s6-overlay's stage2 as root with umask 0 — so Linux is the host whose
|
||||
answer matters.
|
||||
"""
|
||||
import stat
|
||||
|
||||
from hermes_cli.service_manager import _seed_supervise_skeleton
|
||||
|
||||
svc_dir = tmp_path / "gateway-foo"
|
||||
svc_dir.mkdir()
|
||||
|
||||
_seed_supervise_skeleton(svc_dir)
|
||||
|
||||
for rel in ("event", "supervise/event"):
|
||||
mode = stat.S_IMODE((svc_dir / rel).stat().st_mode)
|
||||
assert mode == 0o3730, f"{rel}/ mode = {oct(mode)}, want 0o3730"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""``hermes update`` skips the editable reinstall when the pull can't affect it.
|
||||
|
||||
``uv pip install -e .`` never audits an editable target — it reinstalls on
|
||||
every invocation and rewrites the console-script shims each time. On Windows
|
||||
that rewrite is the only reason the running ``hermes.exe`` gets quarantined,
|
||||
and a quarantine that loses its race is the ``os error 32`` family. The gate
|
||||
under test removes the reinstall (and therefore the rename) for any update
|
||||
that touches none of the files defining the install.
|
||||
|
||||
These tests drive a REAL git repository. The predicate is a ``git diff``
|
||||
pathspec against the pre-pull SHA; mocking git would assert our idea of what
|
||||
git prints rather than what it does.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli.update_cmd import _editable_install_is_current
|
||||
|
||||
GIT = ["git"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo(tmp_path):
|
||||
"""A repo with one commit, standing in for the pre-pull checkout."""
|
||||
subprocess.run(GIT + ["init", "-q", "-b", "main"], cwd=tmp_path, check=True)
|
||||
subprocess.run(
|
||||
GIT + ["config", "user.email", "t@example.com"], cwd=tmp_path, check=True
|
||||
)
|
||||
subprocess.run(GIT + ["config", "user.name", "t"], cwd=tmp_path, check=True)
|
||||
(tmp_path / "pyproject.toml").write_text("[project]\nname = 'hermes'\n")
|
||||
(tmp_path / "agent").mkdir()
|
||||
(tmp_path / "agent" / "__init__.py").write_text("")
|
||||
(tmp_path / "cli.py").write_text("x = 1\n")
|
||||
subprocess.run(GIT + ["add", "-A"], cwd=tmp_path, check=True)
|
||||
subprocess.run(GIT + ["commit", "-qm", "base"], cwd=tmp_path, check=True)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _head(cwd):
|
||||
return subprocess.run(
|
||||
GIT + ["rev-parse", "HEAD"], cwd=cwd, capture_output=True, text=True, check=True
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def _commit(cwd, message):
|
||||
subprocess.run(GIT + ["add", "-A"], cwd=cwd, check=True)
|
||||
subprocess.run(GIT + ["commit", "-qm", message], cwd=cwd, check=True)
|
||||
|
||||
|
||||
def test_source_only_pull_skips_the_reinstall(repo):
|
||||
"""The common update: .py churn inside already-mapped packages."""
|
||||
before = _head(repo)
|
||||
(repo / "cli.py").write_text("x = 2\n")
|
||||
(repo / "agent" / "loop.py").write_text("y = 1\n")
|
||||
_commit(repo, "source churn")
|
||||
|
||||
assert _editable_install_is_current(GIT, repo, before) is True
|
||||
|
||||
|
||||
def test_new_submodule_in_mapped_package_skips_the_reinstall(repo):
|
||||
"""A new file inside an existing package resolves through its __path__."""
|
||||
before = _head(repo)
|
||||
(repo / "agent" / "brand_new.py").write_text("z = 1\n")
|
||||
_commit(repo, "new submodule")
|
||||
|
||||
assert _editable_install_is_current(GIT, repo, before) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"filename",
|
||||
["pyproject.toml", "setup.py", "setup.cfg", "MANIFEST.in", "uv.lock"],
|
||||
)
|
||||
def test_touching_a_file_that_defines_the_install_forces_the_reinstall(repo, filename):
|
||||
"""Dependencies, entry points and the static module list all live here."""
|
||||
before = _head(repo)
|
||||
(repo / filename).write_text("# changed\n")
|
||||
_commit(repo, f"touch {filename}")
|
||||
|
||||
assert _editable_install_is_current(GIT, repo, before) is False
|
||||
|
||||
|
||||
def test_source_churn_alongside_a_pyproject_edit_still_reinstalls(repo):
|
||||
"""The gate must not be fooled by burying the pyproject diff in noise."""
|
||||
before = _head(repo)
|
||||
(repo / "cli.py").write_text("x = 3\n")
|
||||
(repo / "pyproject.toml").write_text("[project]\nname = 'hermes'\ndeps = []\n")
|
||||
_commit(repo, "mixed")
|
||||
|
||||
assert _editable_install_is_current(GIT, repo, before) is False
|
||||
|
||||
|
||||
def test_missing_pre_pull_sha_fails_closed(repo):
|
||||
"""No SHA (ZIP swap, capture failure) means we cannot prove anything."""
|
||||
assert _editable_install_is_current(GIT, repo, None) is False
|
||||
assert _editable_install_is_current(GIT, repo, "") is False
|
||||
|
||||
|
||||
def test_unresolvable_pre_pull_sha_fails_closed(repo):
|
||||
"""A shallow checkout whose base commit isn't present reinstalls as before."""
|
||||
assert _editable_install_is_current(GIT, repo, "0" * 40) is False
|
||||
|
||||
|
||||
def test_unusable_git_fails_closed(repo):
|
||||
"""A git that cannot be executed must not be read as 'nothing changed'."""
|
||||
before = _head(repo)
|
||||
assert _editable_install_is_current(["definitely-not-git"], repo, before) is False
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Regression: the Windows Desktop update hand-off must not meter its step pipes.
|
||||
|
||||
``scripts/desktop-update/windows.ps1`` runs each update step through
|
||||
``Invoke-HermesStep``, which starts the step with ``RedirectStandardOutput`` /
|
||||
``RedirectStandardError``. Reading those pipes back has two failure modes, and
|
||||
this fixture covers both because they pull in opposite directions.
|
||||
|
||||
**Waiting for EOF (#90455).** The drain used to collect output with
|
||||
``ReadToEndAsync().Result``. That task does not return when the *step* exits --
|
||||
it returns when the *pipe* reaches EOF. On Windows the write end of a redirected
|
||||
pipe is handed to the child as an inheritable handle, so every descendant
|
||||
spawned without its own redirection holds a duplicate, and EOF waits for the
|
||||
last of them to close it. ``hermes update`` deliberately runs build steps with
|
||||
stdout inherited (the tee-stderr runner in ``hermes_cli/main.py``), so the
|
||||
process tree under a step is arbitrarily deep and not something the hand-off can
|
||||
enumerate. When one of those descendants is a resident gateway, the pipe never
|
||||
closes and ``Invoke-HermesStep`` blocks for the life of the gateway.
|
||||
|
||||
Everything the hand-off owes the Desktop is downstream of that call:
|
||||
``.hermes-update-result.json`` is never written, ``.hermes-update-in-progress``
|
||||
is never cleared, and the Desktop is never relaunched -- so the app sits on
|
||||
"Updating Hermes" until the user kills the gateway by hand, and the stale marker
|
||||
then refuses the next update too.
|
||||
|
||||
**Trickling toward EOF.** The fix reads in chunks so an abandoned pipe still
|
||||
yields what arrived. But a chunked drain that idles after every chunk it reads
|
||||
is metered at one buffer per tick (16 KiB / 150ms ~ 107 KB/s), and because the
|
||||
pipe then backs up that is backpressure on the *running* step, not just a slow
|
||||
read -- a chatty step blocks on ``write()`` waiting for the reader. Measured on
|
||||
this fixture's own flood arm: 4 MiB took 39.1s metered vs 0.09s unmetered, and a
|
||||
step writing to both pipes took 18.3s vs 0.29s. ``hermes update`` is exactly this
|
||||
shape; the Electron/vite build alone is megabytes.
|
||||
|
||||
So the contract is: bounded when a descendant holds the pipe open, and never
|
||||
slower than the step can write. Both arms live in the script's own
|
||||
``-SelfTestPipeDrain`` fixture, which is ``windows_only`` because Linux CI
|
||||
cannot execute the PowerShell hand-off.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
WINDOWS_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
|
||||
|
||||
|
||||
@pytest.mark.windows_only
|
||||
def test_pipe_drain_survives_a_leak_without_metering_a_chatty_step(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Execute the real drain against both shapes of step.
|
||||
|
||||
``-SelfTestPipeDrain`` runs two steps through the real
|
||||
``Invoke-HermesStep``:
|
||||
|
||||
*leak* -- a step that spawns a grandchild with ``UseShellExecute = $false``
|
||||
and no redirection (the shape that makes the grandchild inherit the step's
|
||||
stdout/stderr), then exits 7 while the grandchild sleeps on. The fixture
|
||||
asserts the grandchild was **still alive** when ``Invoke-HermesStep``
|
||||
returned, so a pass cannot be a timing coincidence, and that the exit code
|
||||
and the step's output both survived the abandonment.
|
||||
|
||||
*flood* -- a step that writes megabytes and holds nothing, exiting 5. It
|
||||
must complete in wall-clock far under what a sleep-per-chunk drain would
|
||||
take, and every byte must arrive.
|
||||
|
||||
Measured on Windows 11 / PowerShell 5.1: leak 4.3s (vs 47.4s waiting out the
|
||||
grandchild), flood 8 MiB in ~1s (vs ~76s metered).
|
||||
"""
|
||||
system_root = Path(os.environ.get("SystemRoot", r"C:\Windows"))
|
||||
powershell = (
|
||||
system_root / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
|
||||
)
|
||||
if not powershell.is_file():
|
||||
pytest.skip(f"Windows PowerShell not found at {powershell}")
|
||||
|
||||
env = {
|
||||
**os.environ,
|
||||
# The fixture writes its child scripts, pid file and hand-off log under
|
||||
# TEMP; point that at tmp_path so the test leaves nothing behind.
|
||||
"TEMP": str(tmp_path),
|
||||
"TMP": str(tmp_path),
|
||||
# Keep the test quick. The grace is what the fix bounds; the hold is
|
||||
# how long the leaking grandchild lives. hold >> grace is what makes a
|
||||
# regression measurable rather than lucky.
|
||||
"HERMES_UPDATE_PIPE_DRAIN_SECONDS": "3",
|
||||
"HERMES_SELFTEST_HOLD_SECONDS": "45",
|
||||
}
|
||||
|
||||
result = subprocess.run(
|
||||
[
|
||||
str(powershell),
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
str(WINDOWS_PS1),
|
||||
"-SelfTestPipeDrain",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
# Comfortably past both arms' worst cases (the 45s hold, and a metered
|
||||
# flood) so a regression fails with the fixture's own diagnosis instead
|
||||
# of an opaque timeout.
|
||||
timeout=300,
|
||||
env=env,
|
||||
cwd=str(REPO_ROOT),
|
||||
)
|
||||
|
||||
assert "PIPE-DRAIN SELF-TEST: PASS" in result.stdout, (
|
||||
"The Windows update hand-off's step drain regressed: it either waited "
|
||||
"on a descendant holding the pipe open (the Desktop parks on 'Updating "
|
||||
"Hermes' forever) or metered a chatty step (backpressure on the running "
|
||||
f"update). Fixture diagnosis follows.\n--- stdout ---\n{result.stdout}\n"
|
||||
f"--- stderr ---\n{result.stderr}"
|
||||
)
|
||||
assert result.returncode == 0, (
|
||||
f"-SelfTestPipeDrain exited {result.returncode}.\n"
|
||||
f"--- stdout ---\n{result.stdout}\n--- stderr ---\n{result.stderr}"
|
||||
)
|
||||
@@ -40,8 +40,24 @@ def _read() -> str:
|
||||
return WINDOWS_PS1.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _handoff_source() -> str:
|
||||
"""The script with its ``-SelfTest*`` fixture blocks removed.
|
||||
|
||||
Those blocks exercise the hand-off machinery deliberately -- the pipe-drain
|
||||
fixture runs a synthetic PowerShell step through ``Invoke-HermesStep`` to
|
||||
prove the drain cannot deadlock (#90455) -- so they are not update steps
|
||||
and the "must drive python.exe" rule does not apply to them. Each exits
|
||||
before any marker/venv/desktop machinery runs.
|
||||
|
||||
Scoped here rather than allow-listing a target, so the rule stays absolute
|
||||
for every real step. The non-greedy match ends at the first closing brace
|
||||
in column 0; the blocks' own braces are all indented.
|
||||
"""
|
||||
return re.sub(r"\nif \(\$SelfTest\w+\) \{.*?\n\}\n", "\n", _read(), flags=re.S)
|
||||
|
||||
|
||||
def test_invoke_hermes_step_calls_drive_python_not_the_shim() -> None:
|
||||
source = _read()
|
||||
source = _handoff_source()
|
||||
|
||||
invocations = re.findall(r"Invoke-HermesStep\s+(\$\w+)", source)
|
||||
assert invocations, (
|
||||
|
||||
@@ -342,6 +342,45 @@ import { THEMES_AREA } from '@hermes/plugin-sdk'
|
||||
ctx.register({ id: 'noir', area: THEMES_AREA, data: myDesktopTheme })
|
||||
```
|
||||
|
||||
Registering a theme lists it; it does not select it. `useTheme()` reads the
|
||||
painted appearance (`theme`, `themeName`, `availableThemes`, `resolvedMode`) and
|
||||
changes it (`setTheme`, `setMode`, `previewTheme`) from a component:
|
||||
|
||||
```javascript
|
||||
import { Button, useTheme } from '@hermes/plugin-sdk'
|
||||
|
||||
function ThemePicker() {
|
||||
const { availableThemes, setTheme, themeName } = useTheme()
|
||||
|
||||
return availableThemes.map(t => (
|
||||
<Button key={t.name} disabled={t.name === themeName} onClick={() => setTheme(t.name)}>
|
||||
{t.label}
|
||||
</Button>
|
||||
))
|
||||
}
|
||||
```
|
||||
|
||||
A switch driven by something other than a render — a gateway connecting, a
|
||||
socket event, any `host.onEvent` callback — has no component to hang the hook
|
||||
on. Use `requestTheme(name)` there. An unresolvable name is refused rather than
|
||||
coerced to the default skin, so the return value doubles as the availability
|
||||
check and a wrong name can never silently reset someone's appearance:
|
||||
|
||||
```javascript
|
||||
import { host, requestTheme } from '@hermes/plugin-sdk'
|
||||
|
||||
host.onEvent('gateway.ready', () => {
|
||||
if (!requestTheme('noir')) {
|
||||
host.notifyError('Connected, but the noir theme is not installed.')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Both doors persist per profile, so a plugin-driven switch sticks exactly like a
|
||||
manual pick. To tint the *active* theme rather than replace it, use
|
||||
`setAccentOverride(hex)` and clear it in `ctx.onDispose` — the bundled `accent`
|
||||
plugin is the worked example.
|
||||
|
||||
### Composer extensions
|
||||
|
||||
`COMPOSER_AREAS` (`top`, `bottom`, `leading`, `actions`, `attachments`,
|
||||
@@ -859,6 +898,7 @@ not treat this pipeline as a trust boundary.
|
||||
| Area constants | `PANES_AREA`, `ROUTES_AREA`, `SIDEBAR_NAV_AREA`, `STATUSBAR_AREAS`, `TITLEBAR_AREAS`, `PALETTE_AREA`, `KEYBINDS_AREA`, `THEMES_AREA`, `COMPOSER_AREAS` |
|
||||
| Area payloads | `RouteContribution`, `SidebarNavContribution`, `StatusbarItem`, `TitlebarTool`, `PaletteContribution`, `KeybindContribution`, `ComposerMiddleware`, `ComposerAttachmentProvider` |
|
||||
| React / state | `useValue`, `atom`, `computed`, `useQuery`, `useMutation`, `useQueryClient`, `queryClient`, `Contribute` |
|
||||
| Theming | `useTheme`, `requestTheme`, `setAccentOverride`, `$accentOverride`, `retintTheme`, `themeHue`, `DesktopTheme`, `DesktopThemeColors`, plus OKLCH math (`hexToOklch`, `oklchToHex`, `oklchToSrgb255`, `mixOklab`, `maxChroma`, `hueDelta`, `contrastRatio`, `readableOn`, `normalizeHex`) |
|
||||
| UI kit | `Button`, `Input`, `Textarea`, `Select*`, `Switch`, `Checkbox`, `SegmentedControl`, `Tabs*`, `Dialog*`, `ConfirmDialog`, `DropdownMenu*`, `ContextMenu*`, `Popover*`, `Tip`/`Tooltip*`, `Badge`, `Kbd`/`KbdGroup`, `SearchField`, `ScrollArea`, `Separator`, `Skeleton`, `GlyphSpinner`, `Loader`, `EmptyState`, `ErrorState`, `CopyButton`, `StatusDot`, `LogView`, `Codicon`, `DecodeText` |
|
||||
| Helpers | `cn`, `icons`, `haptic`, `useI18n`, `profileColor`, `profileColorSoft`, `relativeTime`, `fmtDateTime`, `fmtDayTime`, `coarseElapsed`, `evaluateRuntimeReadiness` |
|
||||
|
||||
|
||||
Reference in New Issue
Block a user