Files
buzz/desktop/src/testing/e2eBridgeCustomHarnesses.ts
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

128 lines
4.2 KiB
TypeScript

/**
* In-memory custom harness store for the e2e bridge.
*
* Extracted as a separate module so the handler logic can be unit-tested
* independently of the full e2eBridge.ts context (which requires a browser
* environment and full Playwright setup).
*/
import type { RawAcpRuntimeCatalogEntry } from "../shared/api/tauri.ts";
/** In-memory store for custom harnesses saved via `save_custom_harness`. */
export const mockCustomHarnesses = new Map<string, RawAcpRuntimeCatalogEntry>();
/**
* Ids removed via `delete_custom_harness` (or vacated by a rename).
*
* Needed because a test's `acpRuntimesCatalog` seed is static config, not the
* mutation store: deleting a seeded row leaves nothing to remove from
* `mockCustomHarnesses`, so without a tombstone the row would survive the
* delete and the mock would report success while the UI still shows it.
*/
export const mockDeletedCustomHarnesses = new Set<string>();
/** Reset the store between tests. */
export function resetMockCustomHarnesses(): void {
mockCustomHarnesses.clear();
mockDeletedCustomHarnesses.clear();
}
/**
* Overlay the mutation store onto a seeded catalog.
*
* Deleted ids drop out, saved ids replace their seeded entry in place (so a
* same-id edit updates rather than duplicates), and newly added ids append.
*/
export function mergeMockCustomHarnesses(
base: RawAcpRuntimeCatalogEntry[],
): RawAcpRuntimeCatalogEntry[] {
const merged = base.filter(
(entry) => !mockDeletedCustomHarnesses.has(entry.id),
);
for (const entry of mockCustomHarnesses.values()) {
const index = merged.findIndex((existing) => existing.id === entry.id);
if (index === -1) {
merged.push(entry);
} else {
merged[index] = entry;
}
}
return merged;
}
/**
* Handle `save_custom_harness`.
*
* Persists the definition into `mockCustomHarnesses` so that the next
* `discover_acp_providers` call includes it. Mirrors the Rust command's
* return shape: an `AcpRuntimeCatalogEntry` for the saved harness.
*/
export function handleSaveCustomHarness(args: {
definition?: {
id?: string;
label?: string;
command?: string;
args?: string[];
env?: Record<string, string>;
installInstructionsUrl?: string;
installHint?: string;
};
originalId?: string | null;
}): RawAcpRuntimeCatalogEntry {
const def = args.definition ?? {};
const id = def.id ?? "";
const originalId = args.originalId ?? null;
// On rename: remove the old entry so the old id is no longer in the catalog.
if (originalId && originalId !== id) {
mockCustomHarnesses.delete(originalId);
mockDeletedCustomHarnesses.add(originalId);
}
// A save resurrects an id that an earlier test step deleted.
mockDeletedCustomHarnesses.delete(id);
const entry: RawAcpRuntimeCatalogEntry = {
id,
label: def.label ?? id,
avatar_url: "",
availability: "not_installed", // PATH not probed in e2e mock
command: def.command ?? null,
binary_path: null,
default_args: def.args ?? [],
mcp_command: null,
install_hint: def.installHint ?? "",
install_instructions_url: def.installInstructionsUrl ?? "",
can_auto_install: false,
requires_external_cli: true,
underlying_cli_path: null,
node_required: false,
auth_status: { status: "not_applicable" },
source: "custom",
// Omit definition_env when the env map is empty — mirrors Rust's BTreeMap
// serialization which skips empty maps so the field is absent on the wire.
definition_env:
def.env && Object.keys(def.env).length > 0 ? def.env : undefined,
login_hint: undefined,
};
mockCustomHarnesses.set(id, entry);
return entry;
}
/**
* Handle `delete_custom_harness`.
* Removes the harness from the in-memory store. Idempotent (not-found is OK).
* When `config?.mock?.deleteCustomHarnessError` is set, throws with that message
* to exercise the UI's inline error path.
*/
export function handleDeleteCustomHarness(
args: { id?: string },
config?: { mock?: { deleteCustomHarnessError?: string } } | undefined,
): void {
const errorMsg = config?.mock?.deleteCustomHarnessError;
if (errorMsg) {
throw new Error(errorMsg);
}
const id = args.id ?? "";
mockCustomHarnesses.delete(id);
mockDeletedCustomHarnesses.add(id);
}