Files
buzz/desktop/src/app/postOnboardingNav.test.mjs
Will Pfleger 95fdf97880 feat(acp): bring your own harness (BYOH) — generic ACP runtime seam + settings gallery (#2773)
## What

Implements a "bring your own harness" (BYOH) generic ACP mechanism —
replacing per-harness backend code with a data-driven 3-tier system:

- **Tier 1 (compiled-in builtins):** goose, claude, codex, buzz-agent —
unchanged behavior
- **Tier 2 (bundled presets):** cursor, omp, grok, opencode, kimi, amp,
hermes, openclaw, and any future additions — defined in
`PRESET_HARNESSES`, no code duplication, icons stay
TerminalSquare/bundled-asset-only
- **Tier 3 (user-defined custom):** JSON definitions saved to
`custom_harnesses/` under app data; managed via Settings → Agents UI

## Changes

### Core data model
- `HarnessDefinition` — id, label, command, args, env, install URL/hint
- `PRESET_HARNESSES` static table — single source of truth for all
presets; `preset_harness_ids()` derives reserved IDs (D-11: no
hand-maintained copy)
- `source: "builtin" | "preset" | "custom"` tagging on every catalog
entry

### Persistence (B-4, B-6)
- `save_custom_harness_to_dir(dir, definition, rename_old_id)` —
backup-swap atomic write (backs up target → .bak, commits temp → target,
restores .bak on failure, removes .bak on success); safe on Windows
where `fs::rename` over an existing file is "access denied"
- `save_and_warm` / `delete_and_warm` — hold `PERSIST_MUTEX` for the
write + registry-warm pair, eliminating the lost-update race (B-6) where
two concurrent saves could interleave their warm calls and leave a stale
registry snapshot
- Validate-before-mutate: both IDs and env validated before any
filesystem mutation

### Env validation boundary (B-3)
- `validate_harness_definition_pub` calls `validate_user_env_keys` on
definition env at save AND load
- Rejects malformed keys (BUZZ_AUTH_TAG=x forgery shape), reserved keys
(BUZZ_MANAGED_AGENT etc.), NUL bytes, oversized values

### TypeScript boundary (B-2 / Thufir CRITICAL)
- `RawAcpRuntimeCatalogEntry` now declares `definition_env?:
Record<string,string>` and `source: "builtin" | "preset" | "custom"`
- `fromRawAcpRuntimeCatalogEntry` maps `definition_env → definitionEnv`
(camelCase); absent field defaults to `{}`
- Edit form reads `entry.definitionEnv` — env no longer erased on
save-then-edit cycle

### Unified descriptor (Phase A / Thufir F4)
- `EffectiveHarnessDescriptor { command, args, env }` in `readiness.rs`
- `resolve_effective_harness_descriptor()` — single resolver used by
spawn, spawn_hash, summary, get_agent_models (both saved and unsaved),
and readiness
- No competing arg-resolution forms

### Other fixes
- B-5: stop freezing `runtime.defaultArgs` into `record.agent_args` on
normal create paths
- B-7: readiness exec-check — `MissingBinary` variant for custom
commands not found on PATH
- B-8: onboarding transition — `setTimeout(0)` removed, parent-owned
route intent via `navigateAfterComplete` prop
- C-9: collector-discriminating sweep tests with injectable filters
- C-10: `HarnessManagementCard` uses `harnessGalleryLogic` helpers
(killed duplicate filter/sort)
- D-11: `BUILTIN_IDS` derived from `PRESET_HARNESSES` (no
hand-maintained copy)
- D-12: `mobile/pubspec.lock` churn reverted
- D-13: false ownership fast-path comment fixed
- D-14: URL scheme validation for `installInstructionsUrl`
- D-15: OpenClaw Gateway env-locus README line

### Tests added
**B-4 persistence (6 tests):**
`save_to_dir_create_writes_file_and_loads_back`,
`save_to_dir_same_id_edit_replaces_content`,
`save_to_dir_backup_is_cleaned_up_after_same_id_edit`,
`save_to_dir_rename_removes_old_file_and_creates_new`,
`save_to_dir_rename_nonexistent_old_id_is_non_fatal`,
`save_to_dir_roundtrip_with_env_preserves_values`

**B-3 env validation (6 tests):**
`validate_rejects_malformed_key_with_equals_sign`,
`validate_rejects_reserved_key_buzz_managed_agent`,
`validate_rejects_reserved_key_case_insensitive`,
`validate_rejects_nul_byte_in_value`,
`validate_rejects_value_over_per_value_size_limit`,
`validate_accepts_well_formed_env`

**B-2 API boundary (4 TS tests in tauri.test.mjs):**
`fromRawAcpRuntimeCatalogEntry maps definition_env to definitionEnv`,
`defaults definitionEnv to {} when absent`, `preserves source preset`,
`env round-trips through edit payload shape`

## Preset catalog

| ID | Label | Command |
|----|-------|---------|
| `cursor` | Cursor | `cursor-agent acp` |
| `omp` | Oh My Pi | `omp acp` |
| `grok` | Grok Build | `grok agent --always-approve stdio` |
| `opencode` | OpenCode | `opencode acp` |
| `kimi` | Kimi Code | `kimi acp` |
| `amp` | Amp | `amp-acp` |
| `hermes` | Hermes Agent | `hermes-acp` |
| `openclaw` | OpenClaw | `openclaw acp` |

## Review-fix pass (2026-07-26, Eva)

Fixes from the three-way review (Wren / Dawn / Eva) in the
buzz-generic-acp-harnesses thread, pushed as new commits (no rewrite):

1. **installHint edit round-trip** — form seeding extracted to
`formValuesFromCatalogEntry` (single source of truth), input rendered,
full-definition lossless round-trip regression.
2. **Dangling-delete coherence** — delete allowed; confirm counts
referencing agents (direct pin + persona-inherited); summary rows render
`harness (deleted): <id>`; spawn errors become actionable sentences
(`user_facing_harness_error`); composed delete→summary→start test.
3. **Comma-in-args** — rejected at `validate_harness_definition` (shared
by save AND disk load), mirrored inline in the form.
4. **Registry publish race** — collision/dup filtering moved into
`load_custom_harnesses` (both loaders inherit shadowing rules);
discovery publishes by re-reading the dir under `persist_mutex` (lock
scoped to publish only); deterministic interleaving regressions for
save-during-discovery and delete-during-discovery.
5. **Mechanical** — discarded `belongs_to_us` sweep arg deleted,
`load_global_agent_config` hoisted out of the per-record summary loop,
duplicated doc paragraph + stray SAFETY comment removed.
6. **PGID test de-flaked** — leader kept alive through the assertion.

Known follow-up (filed in review, not blocking): file-size split-outs
queued in `check-file-sizes.mjs` entries.

## Gate table — head `bf53f1d60`

| Gate | Result |
|------|--------|
| `cargo test --lib` (desktop/src-tauri) | **1701 passed**, 0 failed, 14
ignored |
| desktop JS suite (`pnpm test`) | **3605 passed**, 0 failed |
| `tsc --noEmit` | clean |
| `biome check` + file-size/px/pubkey checks | clean |
| `cargo clippy --lib -- -D warnings` | clean |
| `cargo fmt --check` | clean |

PR head: `bf53f1d60e3cbd07392e1287b83bb37ba90d0d33` — includes merge of
origin/main (`c2a4ee711`, conflicts in agent_models composed with
#2890's live Databricks discovery)

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: tlongwell-block <109685178+tlongwell-block@users.noreply.github.com>
Signed-off-by: Tyler Longwell <tlongwell@block.xyz>
Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: tlongwell-block <109685178+tlongwell-block@users.noreply.github.com>
Co-authored-by: Dawn (sprout agent) <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: Tyler Longwell <tlongwell@block.xyz>
Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
2026-07-26 20:06:20 -04:00

124 lines
4.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Tests for the post-onboarding navigation contract (Thufir F8).
*
* When the user clicks "Set up agents" during machine onboarding,
* MachineOnboardingFlow calls complete() then navigateAfterComplete({to, search}).
* App.tsx records the pending nav and fires it only when machine.stage === "ready"
* (i.e. once RouterProvider is mounted), never before.
*
* These are pure-logic tests — they simulate the App.tsx useEffect predicate
* directly. No React rendering needed; the behavior under test is:
* pendingNav × stage → navigate() call count.
*/
import assert from "node:assert/strict";
import test from "node:test";
// ── Simulate the App.tsx postOnboardingNav useEffect logic ──────────────────
//
// The production code:
// useEffect(() => {
// if (machine.stage === "ready" && postOnboardingNav) {
// void router.navigate({ to: postOnboardingNav.to, search: ... });
// setPostOnboardingNav(null);
// }
// }, [machine.stage, postOnboardingNav]);
//
// We simulate this as a pure function and drive it through stage transitions.
function runEffect(stage, nav, navigate) {
if (stage === "ready" && nav !== null) {
navigate({ to: nav.to, search: nav.search ?? {} });
return null; // cleared
}
return nav; // unchanged
}
test("navigate does not fire before stage reaches ready", () => {
const calls = [];
const navigate = (args) => calls.push(args);
const nav = { to: "/settings", search: { section: "agents" } };
// Drive through non-ready stages — navigate must not fire.
for (const stage of ["loading", "onboarding", "blocking"]) {
runEffect(stage, nav, navigate);
}
assert.equal(calls.length, 0, "navigate must not be called before ready");
});
test("navigate fires exactly once when stage transitions to ready", () => {
const calls = [];
const navigate = (args) => calls.push(args);
const nav = { to: "/settings", search: { section: "agents" } };
// Pre-ready stages — no call.
let pending = nav;
pending = runEffect("onboarding", pending, navigate);
// Stage reaches ready — navigate fires once.
pending = runEffect("ready", pending, navigate);
assert.equal(calls.length, 1, "navigate must fire exactly once on ready");
assert.equal(calls[0].to, "/settings");
assert.deepStrictEqual(calls[0].search, { section: "agents" });
});
test("navigate does not fire again after nav is cleared", () => {
const calls = [];
const navigate = (args) => calls.push(args);
const nav = { to: "/settings", search: { section: "agents" } };
let pending = nav;
// First ready transition fires and clears.
pending = runEffect("ready", pending, navigate);
assert.equal(calls.length, 1);
assert.equal(pending, null, "pending nav must be cleared after firing");
// Re-running the effect with null nav must not fire again.
pending = runEffect("ready", pending, navigate);
assert.equal(
calls.length,
1,
"navigate must not fire again after being cleared",
);
});
test("navigate fires immediately if nav is set while already ready", () => {
// Edge case: nav arrives after the machine is already ready (e.g. hot reload).
const calls = [];
const navigate = (args) => calls.push(args);
const nav = { to: "/settings", search: { section: "agents" } };
// Start with no pending nav while ready.
let pending = runEffect("ready", null, navigate);
assert.equal(calls.length, 0, "no nav pending → no call");
// Nav arrives (complete() called while already ready).
pending = runEffect("ready", nav, navigate);
assert.equal(calls.length, 1, "nav must fire immediately when already ready");
assert.equal(pending, null);
});
test("navigate intent carries exact to and search from navigateToAgentSettings", () => {
// Verifies the specific shape emitted by MachineOnboardingFlow's
// navigateToAgentSettings action: { to: '/settings', search: { section: 'agents' } }
const calls = [];
const navigate = (args) => calls.push(args);
// Simulate MachineOnboardingFlow calling navigateAfterComplete.
const nav = { to: "/settings", search: { section: "agents" } };
runEffect("ready", nav, navigate);
assert.equal(calls.length, 1);
assert.equal(calls[0].to, "/settings", "must navigate to /settings");
assert.equal(
calls[0].search.section,
"agents",
"must include section=agents",
);
});