Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(e2e): backfill coverage for the flush latch, scope rendering, erased tool extensions and theme import\n\nFour recently merged PRs changed behaviour that no e2e test drives. Each\ntest below was mutation-checked: with the fix reverted it fails naming its\nown assertion.\n\n- #5779 `flush_source_tree`'s re-entrancy latch. A failing flush used to\n latch its scope out for the life of the process, so the natural retry\n answered "already running" forever. Reverted, the retry comes back\n `Ok(seals_fired: 0)` with that log line and the test fails.\n\n- #5854 `as_bus_scope`, the host->bus join the retrieval handlers were\n rewired onto. `None` means unrestricted and must stay `None`; an empty\n `SourceScope` denies every source-attributed item, so collapsing the two\n inverts the policy and silently blanks recall. Nothing asserted it —\n every occurrence in the tree was a call site or a comment.\n\n- #5841 the erased `dyn Any` host extensions. Both the e2e and unit lanes\n only asserted `is_none()`, which is also the silent-downcast failure\n mode, so the failure and the only tested state were the same value.\n Adds the `Some` side, plus the MCP error-flag orientation the PR itself\n flagged as easy to get backwards.\n\n- #5946 theme import validation, in the Playwright lane. `typeof null` and\n `typeof []` are both `'object'`, so malformed pastes were stored; a\n non-string token value then threw in `channelsToCss`, crashing the panel\n on an already-stored theme.\n\nThe empty-`colors` case is asserted as ACCEPTED on purpose: CLASSIC_LIGHT\nand CLASSIC_DARK both carry `colors: {}`, so rejecting it would break the\npanel's own export -> import round trip.\n

M3gA-Mind697bd7d3012a
diff --git a/app/test/playwright/specs/settings-theme-import-validation.spec.ts b/app/test/playwright/specs/settings-theme-import-validation.spec.ts
new file mode 100644
index 0000000000..9679e37ded
--- /dev/null
+++ b/app/test/playwright/specs/settings-theme-import-validation.spec.ts
@@ -0,0 +1,118 @@
+import { expect, type Page, test } from '@playwright/test';
+
+import {
+ bootAuthenticatedPage,
+ dismissWalkthroughIfPresent,
+ waitForAppReady,
+} from '../helpers/core-rpc';
+
+/**
+ * Theme Studio import validation (#5946 / #5901), asserted in a real engine.
+ *
+ * `handleImport` used to gate on `typeof parsed.colors !== 'object'`. Both
+ * `typeof null` and `typeof []` are `'object'`, so a paste carrying
+ * `"colors": null` or `"colors": []` passed the check; `{ ...null }` and
+ * `{ ...[] }` each spread to `{}`, and the malformed paste was stored as a
+ * theme. A non-string token value got further still — `swatchChannels` falls
+ * back only on null/undefined, so `{"surface": 42}` reached `channelsToCss`,
+ * which calls `.trim()` on it and throws, crashing the panel on a theme that
+ * was by then already in the store.
+ *
+ * The panel is reached at `/settings/appearance`, which embeds
+ * `ThemeStudioPanel` (`AppearancePanel.tsx:98`); the standalone
+ * `/settings/theme` route redirects there.
+ *
+ * The observable signal for accept-vs-reject is the textarea. `handleImport`
+ * clears `importText` only on the success path, and sets `importError` only on
+ * the failure path — so "the error is shown AND the pasted text is still
+ * there" is a state the accepting build cannot produce.
+ */
+
+const importBox = (page: Page) => page.getByLabel('Import theme');
+const importButton = (page: Page) => page.getByRole('button', { name: 'Import', exact: true });
+const importError = (page: Page) => page.getByText('Could not parse that theme JSON.');
+
+async function openAppearance(page: Page) {
+ await page.goto('/#/settings/appearance');
+ await waitForAppReady(page);
+ await dismissWalkthroughIfPresent(page);
+ await expect(page.getByRole('heading', { level: 1 })).toHaveText('Appearance', {
+ timeout: 20_000,
+ });
+ await expect(importBox(page)).toBeVisible({ timeout: 20_000 });
+}
+
+/** Paste `json` into the import box and click Import. */
+async function attemptImport(page: Page, json: string) {
+ await importBox(page).fill(json);
+ await importButton(page).click();
+}
+
+test.describe('Theme Studio — import validation', () => {
+ test.beforeEach(async ({ page }) => {
+ await bootAuthenticatedPage(page, 'pw-w8-theme-import', '/settings/appearance');
+ await openAppearance(page);
+ });
+
+ // Each of these reached the store before #5946. `null` and `[]` are the two
+ // that `typeof x === 'object'` waves through; the rest are token values that
+ // survive to `channelsToCss` and throw there rather than here.
+ const malformed: ReadonlyArray<readonly [string, string]> = [
+ ['null colors', JSON.stringify({ name: 'Malformed', isDark: false, colors: null })],
+ ['an array of colors', JSON.stringify({ name: 'Malformed', isDark: false, colors: [] })],
+ [
+ 'a numeric token value',
+ JSON.stringify({ name: 'Malformed', isDark: false, colors: { surface: 42 } }),
+ ],
+ [
+ 'a null token value',
+ JSON.stringify({ name: 'Malformed', isDark: false, colors: { surface: null } }),
+ ],
+ [
+ 'one bad value among good ones',
+ JSON.stringify({
+ name: 'Malformed',
+ isDark: false,
+ colors: { surface: '1 2 3', content: 7 },
+ }),
+ ],
+ ];
+
+ for (const [label, json] of malformed) {
+ test(`refuses a theme with ${label}`, async ({ page }) => {
+ await attemptImport(page, json);
+
+ await expect(importError(page)).toBeVisible();
+ // The success path clears the box. Still holding the paste is what
+ // separates "refused" from "accepted and stored".
+ await expect(importBox(page)).toHaveValue(json);
+ });
+ }
+
+ test('still accepts a theme carrying a single colour token', async ({ page }) => {
+ const valid = JSON.stringify({
+ name: 'Minimal',
+ isDark: false,
+ colors: { surface: '1 2 3' },
+ });
+
+ await attemptImport(page, valid);
+
+ await expect(importError(page)).toBeHidden();
+ await expect(importBox(page)).toHaveValue('');
+ });
+
+ test('still accepts a theme whose colors object is empty', async ({ page }) => {
+ // Deliberately allowed, and the reason is load-bearing: CLASSIC_LIGHT and
+ // CLASSIC_DARK both carry `colors: {}` (`lib/theme/presets.ts`), inheriting
+ // the base stylesheet tokens and carrying their meaning in `isDark`.
+ // Rejecting `{}` would break the panel's own export -> import round trip
+ // for the two most common themes, and refuse font- or backdrop-only themes.
+ const emptyColors = JSON.stringify({ name: 'Inherits', isDark: true, colors: {} });
+
+ await attemptImport(page, emptyColors);
+
+ await expect(importError(page)).toBeHidden();
+ await expect(importBox(page)).toHaveValue('');
+ });
+});
diff --git a/tests/raw_coverage/memory_flush_latch_raw_coverage_e2e.rs b/tests/raw_coverage/memory_flush_latch_raw_coverage_e2e.rs
new file mode 100644
index 0000000000..356cad711d
--- /dev/null
+++ b/tests/raw_coverage/memory_flush_latch_raw_coverage_e2e.rs
@@ -0,0 +1,70 @@
+//! Raw integration coverage for the `flush_source_tree` re-entrancy latch
+//! (#5779).
+//!
+//! `flush_source_tree_rpc` keeps a process-global `ACTIVE` set so a second
+//! concurrent call for the same scope is answered "already running" instead of
+//! being run twice. The version this replaced removed the scope from that set
+//! only after a *successful* flush, so any failing call left its scope latched
+//! for the life of the process: the retry a caller would naturally make came
+//! back "already running" forever, and that source could never be flushed
+//! again without a restart. #5779 made the release an RAII guard that drops on
+//! every exit, error paths included.
+//!
+//! The test drives a failing flush and then retries the same scope. What is
+//! asserted is that the retry is *attempted* — it must come back as a failure
+//! from the driver lookup again, never as the latch's "already running"
+//! success. Nothing here asserts which error the driver gives, only that the
+//! second call got as far as asking.
+
+use std::sync::OnceLock;
+
+use openhuman_core::openhuman::config::Config;
+use openhuman_core::openhuman::memory::read_rpc;
+use tempfile::TempDir;
+
+static WORKSPACE: OnceLock<TempDir> = OnceLock::new();
+
+/// A scope string unique to this test.
+///
+/// `ACTIVE` is a process-global `static`, and every `raw_coverage` suite now
+/// shares one test binary, so a scope another test also used would make this
+/// one's result depend on run order.
+const SCOPE: &str = "memory_flush_latch_raw_coverage_e2e::retry-after-failure";
+
+/// A flush that fails must not latch its scope out of every later attempt.
+///
+/// Both calls are expected to fail: an integration test has no memory module
+/// bound, so the handler cannot reach a driver serving `Tree`. That is exactly
+/// the shape the bug needed — a flush that does not reach a successful return.
+/// With the pre-#5779 latch the first failure would leave `SCOPE` in `ACTIVE`,
+/// and the second call would short-circuit to `Ok` before touching the driver.
+#[tokio::test]
+async fn a_failed_flush_source_tree_can_be_retried_for_the_same_scope() {
+ let workspace = WORKSPACE.get_or_init(|| TempDir::new().expect("workspace tempdir"));
+ let mut config = Config::default();
+ config.workspace_dir = workspace.path().to_path_buf();
+
+ let first = read_rpc::flush_source_tree_rpc(&config, SCOPE).await;
+ assert!(
+ first.is_err(),
+ "this test needs a flush that does not succeed, so the latch release is \
+ exercised on an error path; got {first:?}"
+ );
+
+ let second = read_rpc::flush_source_tree_rpc(&config, SCOPE).await;
+
+ // The failure mode being pinned: `Ok` here is the latch answering
+ // "already running" for a flush that is not running, which is what the
+ // pre-#5779 handler did for every scope whose first flush failed.
+ assert!(
+ second.is_err(),
+ "a retry after a failed flush must reach the driver again, not be \
+ short-circuited by the re-entrancy latch; got {second:?}"
+ );
+ assert_eq!(
+ format!("{first:?}"),
+ format!("{second:?}"),
+ "the retry must fail the same way the first attempt did — a different \
+ answer means it took a different path"
+ );
+}
diff --git a/tests/raw_coverage/memory_source_scope_bus_raw_coverage_e2e.rs b/tests/raw_coverage/memory_source_scope_bus_raw_coverage_e2e.rs
new file mode 100644
index 0000000000..c65b8e2a51
--- /dev/null
+++ b/tests/raw_coverage/memory_source_scope_bus_raw_coverage_e2e.rs
@@ -0,0 +1,112 @@
+//! Raw integration coverage for the host→bus source-scope rendering that the
+//! retrieval handlers rewired onto in #5854.
+//!
+//! #5854 moved `read_rpc/chunks.rs`'s recall and the `tree/retrieval/rpc.rs`
+//! handlers off a direct engine call and onto
+//! `binding.provider().as_retrieval()` with an **explicit**
+//! `source_scope::as_bus_scope()` argument. The scope used to be a task-local
+//! the engine read for itself; once memory is a separately compiled module
+//! with its own statics, a task-local set on this side is invisible on the
+//! other, so the value has to cross the bus.
+//!
+//! `as_bus_scope` is the join, and its contract has one asymmetry that is easy
+//! to get backwards and impossible to see from a passing build:
+//!
+//! - **`None` means unrestricted** and must stay `None`.
+//! - **`Some(SourceScope)` with an empty allow list denies every
+//! source-attributed item** (`SourceScope`'s own fail-closed rule).
+//!
+//! So collapsing "no restriction" onto `Some(SourceScope::default())` inverts
+//! the policy: recall silently returns nothing instead of everything. Both
+//! values are well-formed, both type-check, and the handlers report an empty
+//! page as a legitimate answer — so the failure surfaces as "memory forgot
+//! everything", with nothing in the logs.
+//!
+//! Nothing asserted this before: every occurrence of `as_bus_scope` in the tree
+//! is a call site or a comment.
+
+use std::collections::HashSet;
+
+use openhuman_core::openhuman::memory::source_scope::{as_bus_scope, with_source_scope};
+
+/// Outside any scope, and for an explicit `None`, the rendering stays `None`.
+///
+/// This is the inversion guard. `Some(empty)` here would be a scope that denies
+/// everything, which is the exact opposite of what an unscoped turn means.
+#[tokio::test]
+async fn unrestricted_recall_renders_as_no_scope_not_an_empty_allowlist() {
+ assert!(
+ as_bus_scope().is_none(),
+ "outside any scope the bus argument must be None (unrestricted); \
+ Some(empty) is SourceScope's deny-all and would blank recall"
+ );
+
+ with_source_scope(None, async {
+ assert!(
+ as_bus_scope().is_none(),
+ "an explicit None allowlist must render as None, not as an empty \
+ SourceScope"
+ );
+ })
+ .await;
+}
+
+/// A profile that selected no sources is a real restriction, and must NOT be
+/// flattened into the unrestricted `None`.
+///
+/// The mirror of the test above: these two inputs are the ones that must not be
+/// confused, in either direction.
+#[tokio::test]
+async fn an_empty_allowlist_renders_as_a_scope_that_denies_every_source() {
+ with_source_scope(Some(vec![]), async {
+ let scope = as_bus_scope().expect(
+ "an empty allowlist is a restriction the driver must be told about, \
+ not the absence of one",
+ );
+ assert!(
+ scope.is_empty(),
+ "an empty allowlist must cross the bus as an empty SourceScope"
+ );
+ assert!(
+ !scope.allows_source_id("mem_src:anything:item-1"),
+ "an empty scope denies all source-attributed content"
+ );
+ })
+ .await;
+}
+
+/// The allowlist reaches the driver intact, and matches by the bus's own rule.
+///
+/// `SourceScope::allows_source_id` accepts an outright id match or the
+/// `mem_src:<allowed>:<item>` composite the reader-based sources emit. Asserting
+/// through that predicate — rather than comparing the `allow` vector — is what
+/// ties the host's rendering to the matching the driver will actually perform.
+#[tokio::test]
+async fn the_allowlist_crosses_the_bus_and_matches_by_the_drivers_rule() {
+ let allowed = vec!["gmail:work".to_string(), "src-abc".to_string()];
+
+ with_source_scope(Some(allowed.clone()), async {
+ let scope = as_bus_scope().expect("a non-empty allowlist must render as Some");
+
+ let carried: HashSet<&str> = scope.allow.iter().map(String::as_str).collect();
+ assert_eq!(
+ carried,
+ allowed.iter().map(String::as_str).collect::<HashSet<_>>(),
+ "every allowlisted source must reach the driver, and no others"
+ );
+
+ assert!(
+ scope.allows_source_id("src-abc"),
+ "an outright id match is in scope"
+ );
+ assert!(
+ scope.allows_source_id("mem_src:src-abc:item-1"),
+ "the mem_src composite the reader-based sources emit is in scope"
+ );
+ assert!(
+ !scope.allows_source_id("src-xyz"),
+ "a source outside the allowlist stays out"
+ );
+ })
+ .await;
+}
diff --git a/tests/raw_coverage/tools_erased_host_extension_raw_coverage_e2e.rs b/tests/raw_coverage/tools_erased_host_extension_raw_coverage_e2e.rs
new file mode 100644
index 0000000000..3faa615f3a
--- /dev/null
+++ b/tests/raw_coverage/tools_erased_host_extension_raw_coverage_e2e.rs
@@ -0,0 +1,182 @@
+//! Raw integration coverage for the erased host-extension seam #5841 created.
+//!
+//! #5841 moved the `Tool` vocabulary into the shared `tinytools` crate. Two
+//! trait methods named host-only types and could not go with it, so they now
+//! ride `Tool::host_extension` / `Tool::host_call_extension` as
+//! `dyn Any`, read back through typed free functions in
+//! `openhuman::tools::traits`.
+//!
+//! That trade is invisible to the compiler in one direction. A producer that
+//! stores a different concrete type still builds; the `downcast_ref` /
+//! `downcast` in the reader simply returns `None`, and every consumer treats
+//! `None` as "this tool has no such context". For
+//! `generated_runtime_context` that consumer is
+//! `agent::tinyagents::middleware::generated_context`, which feeds
+//! `tool_policy::GeneratedToolRuntimeContext` — so a silent `None` means the
+//! provider / capability / risk rules for a generated tool are simply not
+//! applied.
+//!
+//! Every assertion that existed on this seam — in the e2e lane
+//! (`tools_approval_channels_raw_coverage_e2e.rs`) and in the unit lane
+//! (`tools/traits_tests.rs`) — asserts `is_none()`. The failure mode and the
+//! only tested state were the same value. These tests assert the `Some` side.
+
+use std::any::Any;
+
+use async_trait::async_trait;
+use serde_json::{json, Value};
+
+use openhuman_core::openhuman::agent::tool_policy::{
+ GeneratedToolRuntimeContext, GeneratedToolRuntimeRisk,
+};
+use openhuman_core::openhuman::skills::types::tool_result_from_mcp;
+use openhuman_core::openhuman::tools::toolpacks::tools::{LoadSkillTool, PackRegistryHandle};
+use openhuman_core::openhuman::tools::traits::{
+ generated_runtime_context, pack_registry_handle, PermissionLevel, Tool, ToolResult,
+};
+
+/// A production pack tool's registry handle survives the round trip through
+/// `dyn Any`.
+///
+/// `LoadSkillTool` is one of the two real producers in the tree. If its
+/// `host_extension` ever stored something other than a `PackRegistryHandle`,
+/// this is the only place that would notice: `toolpacks::ops` reads the handle
+/// back through the same free function and, on `None`, silently skips the pack
+/// registry rather than failing.
+#[test]
+fn a_pack_tools_registry_handle_reads_back_through_the_erased_extension() {
+ let tool = LoadSkillTool::new(PackRegistryHandle::default());
+
+ assert!(
+ pack_registry_handle(&tool).is_some(),
+ "a pack tool must yield its PackRegistryHandle through the erased \
+ host extension; None here is the silent-downcast failure that makes \
+ toolpacks::ops skip the registry"
+ );
+}
+
+/// A generated tool's per-call runtime context survives the round trip, field
+/// for field.
+///
+/// The context is carried by value through `Box<dyn Any>`, so this asserts the
+/// fields the policy layer actually reads rather than only that *something*
+/// came back — a downcast to a same-shaped but different type would satisfy
+/// `is_some()` and still lose the policy inputs.
+///
+/// The producer here is a local fixture on purpose: no production tool
+/// implements `host_call_extension` (see `W8-test-findings.md`), so there is no
+/// shipped tool to drive this through. What is pinned is the seam itself.
+#[test]
+fn a_generated_tools_runtime_context_reads_back_with_its_policy_fields() {
+ let context = generated_runtime_context(&GeneratedTool, &json!({"to": "someone"}))
+ .expect("a tool that supplies a per-call context must yield it back");
+
+ assert_eq!(context.provider_id, "mail.runtime");
+ assert_eq!(context.capability_id, "email.send");
+ assert_eq!(
+ context.risk,
+ GeneratedToolRuntimeRisk::ExternalWrite,
+ "risk is what the policy layer gates on; losing it downgrades an \
+ external write to the default"
+ );
+ assert_eq!(context.source_digest.as_deref(), Some("sha256:abc"));
+ assert_eq!(context.approval_id.as_deref(), Some("approval-1"));
+}
+
+/// The MCP → host result conversion keeps the error flag the right way round.
+///
+/// #5841 turned this from a `From` impl into the free function
+/// `skills::types::tool_result_from_mcp`, because `ToolResult` became a foreign
+/// type and the orphan rule forbade the impl. The PR's own note gives the
+/// reason it stays written exactly once: spelled out at each of its three call
+/// sites, it would be three chances to get the error flag backwards. Nothing
+/// asserted the orientation.
+#[test]
+fn an_mcp_error_result_stays_an_error_through_the_conversion() {
+ let failed = tool_result_from_mcp(tinymcp_bus::McpToolResult {
+ content: vec![tinymcp_bus::McpToolContent::Text {
+ text: "server refused".to_string(),
+ }],
+ is_error: true,
+ ..Default::default()
+ });
+ assert!(
+ failed.is_error,
+ "an MCP result flagged as an error must stay an error; inverting this \
+ reports a failed tool call to the model as a success"
+ );
+
+ let ok = tool_result_from_mcp(tinymcp_bus::McpToolResult {
+ content: vec![tinymcp_bus::McpToolContent::Text {
+ text: "done".to_string(),
+ }],
+ is_error: false,
+ ..Default::default()
+ });
+ assert!(
+ !ok.is_error,
+ "a successful MCP result must not be reported as an error"
+ );
+}
+
+// ── fixtures ──────────────────────────────────────────────────────────────
+
+struct PlainTool;
+
+#[async_trait]
+impl Tool for PlainTool {
+ fn name(&self) -> &str {
+ "plain_tool"
+ }
+
+ fn description(&self) -> &str {
+ "A tool that stores nothing on either erased extension."
+ }
+
+ fn parameters_schema(&self) -> Value {
+ json!({"type": "object"})
+ }
+
+ async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("ok"))
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::ReadOnly
+ }
+}
+
+struct GeneratedTool;
+
+#[async_trait]
+impl Tool for GeneratedTool {
+ fn name(&self) -> &str {
+ "generated_tool"
+ }
+
+ fn description(&self) -> &str {
+ "Stands in for a generated tool carrying a per-call runtime context."
+ }
+
+ fn parameters_schema(&self) -> Value {
+ json!({"type": "object"})
+ }
+
+ async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("sent"))
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::ReadOnly
+ }
+
+ fn host_call_extension(&self, _args: &Value) -> Option<Box<dyn Any + Send + Sync>> {
+ Some(Box::new(GeneratedToolRuntimeContext {
+ provider_id: "mail.runtime".to_string(),
+ capability_id: "email.send".to_string(),
+ risk: GeneratedToolRuntimeRisk::ExternalWrite,
+ source_digest: Some("sha256:abc".to_string()),
+ approval_id: Some("approval-1".to_string()),
+ }))
+ }
+}