Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .agents/skills/custom-codereview-guide.mdAdded+201
- .agents/skills/pr-design-doc/SKILL.mdAdded+168
- .agents/skills/pr-design-doc/references/html-craft.mdAdded+322
- .agents/skills/release.mdAdded+110
- .gitattributes+8
- .github/pr-assets/pr-16268-02-lightbox-open.pngAdded
- .github/pr-assets/pr-16605-test-results.pngAdded
- .github/pr-assets/pr-16676-01-list.pngAdded
- .github/pr-assets/pr-16676-02-templates.pngAdded
- .github/pr-assets/pr-16676-04-edit-modal.pngAdded
- .github/pr-assets/pr-16860-01-skills-default.pngAdded
- .github/pr-assets/pr-16860-02-recommended-facet.pngAdded
- __tests__/api/acp-service/acp-service.api.test.tsAdded+130
- __tests__/api/agent-profiles-service/profile-field-support.test.tsAdded+59
- __tests__/api/backend-registry/active-store.test.tsAdded+263
- __tests__/api/backend-registry/health-store.test.tsAdded+111
- __tests__/api/backend-registry/last-conversation-store.test.tsAdded+67
- __tests__/api/backend-registry/storage.test.tsAdded+365
- __tests__/api/backend-registry/url-selection.test.tsAdded+166
- __tests__/api/cloud/conversation-create.test.tsAdded+128
- __tests__/api/cloud/conversation-delete.test.tsAdded+51
- __tests__/api/cloud/conversation-download.test.tsAdded+63
- __tests__/api/cloud/conversation-pause.test.tsAdded+93
- __tests__/api/cloud/conversation-public-flag.test.tsAdded+73
- __tests__/api/cloud/conversation-runtime-info.test.tsAdded+135
- __tests__/api/cloud/conversation-title.test.tsAdded+84
- __tests__/api/cloud/fetch-test-utils.tsAdded+33
- __tests__/api/cloud/git-service.test.tsAdded+69
- __tests__/api/cloud/organization-me.test.tsAdded+88
- __tests__/api/cloud/organization-service.test.tsAdded+144
- __tests__/api/cloud/profiles-service.test.tsAdded+217
- __tests__/api/cloud/provider-connections-service.test.tsAdded+140
- __tests__/api/cloud/proxy.test.tsAdded+272
- __tests__/api/cloud/sandbox-service.test.tsAdded+59
- __tests__/api/cloud/secrets-service.test.tsAdded+179
- __tests__/api/cloud/settings-service.test.tsAdded+200
- __tests__/api/cloud/skills-service.test.tsAdded+136
- __tests__/api/mcp-health/mcp-health-store.test.tsAdded+64
- __tests__/api/mcp-health/probe-mcp-server-health.test.tsAdded+179
- __tests__/api/mcp-service/mcp-service.api.test.tsAdded+395
- __tests__/api/runtime-service/agent-server-runtime-service.test.tsAdded+307
- __tests__/components/analytics/telemetry-consent-banner.test.tsxAdded+198
- __tests__/components/automations/add-automation-modal.test.tsxAdded+107
- __tests__/components/automations/automation-card.test.tsxAdded+368
- __tests__/components/automations/automation-list-row.permissions.test.tsxAdded+145
- __tests__/components/automations/automation-list-row.test.tsxAdded+225
- __tests__/components/automations/automation-view-toggle.test.tsxAdded+46
- __tests__/components/automations/backend-not-configured.test.tsxAdded+49
- __tests__/components/automations/build-automation-pills.test.tsxAdded+82
- __tests__/components/automations/create-instructions.test.tsxAdded+123
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201---name: custom-codereview-guidedescription: Repository-specific review rules for the OpenHands Agent Canvas frontend.triggers: - /codereview---
# OpenHands Agent Canvas Code Review Guidelines
This guide supplements the public `code-review` skill with rules specific to`OpenHands/OpenHands`, the Agent Canvas frontend. Read `AGENTS.md` first; it isthe detailed source of truth for current architecture and test conventions.
Be direct and constructive. Review correctness and architecture, not formattingthat lint or the compiler already checks.
## Review Decision
- Submit exactly one review: **APPROVE** or **COMMENT**. Never use **REQUEST_CHANGES**.- Default to **APPROVE** when there are no important findings. Nitpicks and optional cleanup are not reasons to withhold approval.- Use **COMMENT** for correctness, security, architecture, missing evidence, or unmet acceptance criteria. Let a human maintainer make the blocking decision.- Do not approve changes that can affect agent or benchmark behavior—prompts, tool selection, conversation payloads, terminal behavior, planning, memory, or evaluation paths—without human review and appropriate lightweight evals.- Read the linked issue and include a compact checklist covering each acceptance criterion. Meeting the checklist is necessary but does not replace review for regressions, security, or maintainability.
## Repository Ownership
Put behavior in the repository that owns it:
| Repository | Owns || ------------------------------ | --------------------------------------------------------------------------------------------------------------- || `OpenHands/OpenHands` | Agent Canvas UI, frontend state, backend selection, frontend service integration, and local-stack orchestration || `OpenHands/software-agent-sdk` | Agent Server, agents, tools, conversations, events, workspaces, and the canonical server API || `OpenHands/typescript-client` | Browser-compatible typed access to the Agent Server API || `OpenHands/extensions` | Reusable skills, plugins, and integrations || `OpenHands/automation` | Scheduling, webhooks, run history, and automation dispatch |
The normal dependency direction is Agent Server contract → TypeScript client →Canvas. Flag raw endpoint reimplementations, Canvas-local copies of servercontracts, and changes opened in the wrong repository.
## Architecture That Guides Agents
Agents tend to copy the nearest pattern and choose the shortest compiling path.Review the codebase as part of the product surface that guides those choices:
1. **Make the conventional path cheapest.** New work should naturally reuse a named hook, service, store, or feature module instead of adding another branch to a shared root.2. **Fail forbidden dependencies mechanically.** Repeated review guidance should become a lint rule, compiler boundary, or architecture test. Do not grow this document when a small executable guard would be clearer.3. **Give durable state one obvious writer.** A backend setting, consent value, conversation cache entry, or persisted browser value should have one named owner. Flag second writers and component-local mirrors of authoritative state.4. **Prefer owned feature files over shared switches.** Product work should usually extend a feature-owned module. Shared registries and root conditionals need a concrete reason.5. **Keep exceptions narrow and visible.** Exceptions belong in a small allowlist next to the guard that enforces the rule and should be reviewed as architecture changes.
Treat “deep module” as a design heuristic, not a line-count target. A good modulehas a narrow, stable interface and hides cohesive complexity. Do not split a filemerely because it is long, and do not create layers that only rename or forwardarguments. Prefer a small pure seam when it removes duplicated decisions, makesownership explicit, or enables focused tests.
### React effects
`useEffect` is for synchronizing React with an external system. Flag effects usedto:
- derive render data from props or state;- respond to a user action that can run in the event handler;- initialize a value that belongs in a lazy state initializer;- mirror one store or cache into another component state value; or- repair ordering created by competing writers.
An effect is not automatically wrong. Subscription, browser API, timer, andnetwork synchronization still belong in effects when cleanup and dependencysemantics are explicit.
## Blocking Architecture Checkpoints
### Agent Server and Cloud API access
`src/api/no-direct-agent-server-calls.test.ts` is the executable source of truth.Do not approve new raw `fetch`, `axios`, shared `openHands`, or low-level HTTPclient access to Agent Server endpoints. Use `@openhands/typescript-client` withthe options from `src/api/agent-server-client-options.ts`.
Cloud and runtime-sandbox requests must go through `callCloudProxy`; runtimerequests must provide the correct `hostOverride` and authentication mode. Reviewchanges to the guard's allowlist as architecture changes. Do not copy its currententries into this guide—the test should remain the one authoritative list.
### Event wire contracts
The SDK event model is the wire authority, the TypeScript client mirrors it, andCanvas consumes the published client type. Do not approve Canvas-localredeclarations, partial intersections, module augmentation, or presentationfields added to wire-event interfaces.
A contract change should land in this order:
1. SDK model/schema and serialization coverage.2. TypeScript-client mirror derived from the SDK payload.3. Published client release.4. Canvas consumption and rendering/telemetry coverage.
Canvas-only presentation state belongs in a separate view model keyed by eventidentity.
### Telemetry and durable frontend state
- `src/services/telemetry.ts` is the only owner of the Canvas PostHog client.- React events go through typed functions in `src/hooks/use-tracking.ts`; components must not call PostHog directly.- Consent rendering uses the telemetry consent external store, not mirrored local state. `setTelemetryConsent` remains the single consent controller.- A business milestone has one canonical capture. Flag duplicate conditional captures.- For other durable values, prefer the existing named service/store/hook and flag new storage writes from arbitrary components.
## Dependencies and Releases
- Direct dependencies are exact-pinned. Keep `package.json` and `package-lock.json` synchronized through npm; do not hand-edit one side only.- Treat changes to dependency exemptions, git pins, and security overrides as reviewable policy changes. `__tests__/package-library.test.ts` is the executable source of truth for allowed specs.- Scrutinize newly published third-party dependency versions for supply-chain risk. First-party OpenHands packages are exempt from a waiting period but not from contract and release-order review.- Package version changes belong in explicit release PRs and must match the release workflow expectations.
## Testing and Evidence
- Require evidence proportional to the behavior changed. For UI behavior, use a screenshot or video from the real app. For CLI, API, or scripts, require the exact runtime command and observed result.- Runtime and user-visible bug fixes require before-and-after evidence through the real production-facing path. The before evidence must reproduce the bug on the base branch or released version; the after evidence must repeat the same setup on the PR head and show the corrected behavior. Include exact commands, relevant output, and screenshots or video when the behavior is visual.- For lifecycle fixes, evidence must also verify the resulting process or resource state—for example, the parent exit code and whether child services or listening ports remain after shutdown.- Unit and integration tests are regression proof, not a substitute for live evidence. If required live evidence is missing, submit **COMMENT**, not **APPROVE**, and identify the exact production-facing verification still needed.- Prefer tests that exercise real logic and observable state. Do not reward mocks that only prove another mock was called.- Keep tests focused: one meaningful assertion path per behavior, no duplicated coverage of library behavior, and no brittle presentation-only snapshots.- Follow the test routing in `AGENTS.md`. The mock-LLM, Docker mock-LLM, and live LLM-backed E2E suites run after changes reach `main`, not from PR labels. If a risky PR needs pre-merge E2E evidence, recommend manually dispatching the relevant workflow against the PR branch.- Never broaden live E2E triggers or secret exposure for convenience.
## Review Context Integrity
Before submitting the review, compare its summary and every finding against thecurrent PR title, changed-file manifest, linked issues, and acceptance criteria.If the review describes files, behavior, issues, or release paths that are not inthat context, stop and re-read the PR rather than submitting stale or mismatchedfeedback. Do not approve until this final context check passes.
## What Not to Comment On
Do not leave review comments for:
- formatting or minor style that tooling handles;- optional “nice to have” refactors unrelated to the change;- praise-only observations—approve instead;- extra tests for straightforward data/config changes when existing checks cover the risk; or- temporary `.pr/` artifacts, which are cleaned up by repository automation.
When raising a finding, trace the relevant call or data flow far enough to showthe concrete failure mode. Prefer one high-signal comment over several symptomsof the same ownership problem.
## Communication Style
- Be concise, specific, and friendly.- Explain the user-visible or architectural consequence.- Suggest the smallest viable correction.- Use GitHub suggestion syntax for local fixes.- If the PR is sound, approve it without manufacturing feedback.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168---name: pr-design-docdescription: > For a non-trivial pull request, write a self-contained HTML design doc under the temporary `.pr/` directory and link a visibility-appropriate preview in the PR description, so maintainers grasp the proposal at a glance - code/API design, and the before/after of the change, grounded to real code. Use when opening or updating a non-trivial PR, or when the user says "add a design doc", "document this PR for reviewers", "show the before/after", "make the design reviewable", or "write the .pr/ page".triggers:- /pr-design-doc- /design-doclicense: MITmetadata: tags: pull-request, design-doc, html, review, before-after, htmlpreview---
# pr-design-doc - a reviewable design doc for a non-trivial PR
A diff shows *what changed line by line*. It does not show *the design*: the shape of thechange, the API before and after, and why this approach. Reviewers reconstruct that byhand, slowly. The scarce resource is the maintainer's attention and trust budget - not theagent's effort. Spend extra effort to hand them **one self-contained HTML page** thatconveys the **big picture** and the **before → after core difference**, with every claim**clickable back to the real code**, then link it from the PR description.
This is the same craft as a "show me this change" explainer, aimed at one job: making anon-trivial PR easy to review.
## When to use it
- Opening or updating a **non-trivial** PR: new/changed public API, a new module or subsystem, a behavior change in core logic, a migration, or anything a reviewer can't fully judge from the diff in a couple of minutes.- **Skip it** for trivial PRs - a typo, a one-line guard, a dependency bump, a docs tweak, a simple bug fix. A design doc adds more to review. Use judgment; if the diff *is* the explanation, don't add a page.
## The `.pr/` workflow
Use the temporary **`.pr/`** directory for PR-only artifacts. Before relying on automaticcleanup, verify that the target repository has an enabled`.github/workflows/pr-artifacts.yml` workflow that removes `.pr/` after approval.
- Same-repository PR with verified cleanup workflow: the workflow removes `.pr/` after approval.- Fork PR, or repository without a verified cleanup workflow: remove `.pr/` manually before merge.
The design doc is a review aid that lives with the branch while the PR is open. It must notship in the merged tree.
## Workflow
1. **Check out and verify the PR head.** Do not write or commit the design doc from the base branch or an unrelated checkout. Start with a clean worktree, then inspect and check out the PR: ```bash gh pr view <n> --json title,body,url,baseRefName,baseRefOid,headRefName,headRefOid,headRepository,headRepositoryOwner,isCrossRepository,files,additions,deletions gh pr checkout <n> git rev-parse HEAD gh pr view <n> --json headRefOid --jq .headRefOid ``` The final two SHAs must match before you continue. If they do not, stop and fix the checkout. Compute the merge-base SHA with `git merge-base <baseRefOid> <headRefOid>`. Group changed files by area and keep both the merge-base SHA and head SHA for source links.
2. **Read both sides of each logical file.** Compare `git show <merge-base-sha>:<path>` with the verified head. Capture the **function-level** behavioral difference - what the code *did* vs *does now*. - new file → no "before"; one "after" diagram + a line on the role it adds. - deleted file → "before" diagram + who/what takes over. - edited file → a before/after pair, with the delta highlighted.
3. **Classify each file.** *Logic* change (behavior moved) → draw before/after. *Mechanical* change (rename, constant, config, import move) → a one-line `before → after` row, no diagram. Don't dilute the signal by drawing mechanical edits.
4. **If the change is an API change, lead with the API.** Show the signature/schema/type **before and after** side by side (function signature, endpoint + payload, config field, event shape). Name the compatibility impact plainly: additive, breaking, or behind a flag.
5. **Find the cross-file story.** If one call chain threads several files, draw a single **overview** before/after at the top; per-file cards drill in.
6. **Build the page** per [`references/html-craft.md`](references/html-craft.md) - one self-contained, offline, editorial HTML file with hand-drawn SVG figures. Save it to the repo's `.pr/` directory, e.g. `.pr/design.html` (or `.pr/<topic>.html`). Before writing, reject a symlink at `.pr` or at the exact output path; never follow a branch-controlled symlink outside the worktree. ```bash test ! -L .pr && test ! -L .pr/design.html mkdir -p .pr ```
7. **Commit under `.pr/`, push to the verified PR head, and link it.** Confirm that the push remote resolves to `headRepository.nameWithOwner`; never push the artifact to the base repository's default branch. ```bash git add .pr/design.html git commit -m "docs(.pr): design doc for <PR topic>" git push <head-repo-remote> HEAD:<headRefName> ``` Query the base repository's visibility before choosing the link: ```bash gh repo view <base-owner>/<base-repo> --json visibility,url ``` - **Public repository:** add an htmlpreview link near the top of the PR description, pointing at the **fork and branch the PR is opened from** (it renders before merge): ``` 📄 Design doc: https://htmlpreview.github.io/?https://github.com/<fork-owner>/<repo>/blob/<pr-branch>/.pr/design.html ``` - **Private or internal repository:** link the access-controlled GitHub blob and include local download/open instructions, or use an existing access-controlled artifact service. Never send the document through htmlpreview or another public host.
## What the page contains
1. **What changed (decision first)** - one paragraph: the intent, net effect, and why the reviewer should care. Put the highest-impact conclusion, risk, or API-compat note in a `★` callout, with the most important changed `path:line` nearby. Stats (`N files · +A / −D`) are context, not the lead. If there's a cross-file flow, the **overview before/after SVG** goes here.2. **API before → after** (when the PR changes an interface) - signatures/schemas/types side by side, with the compatibility verdict stated.3. **Left rail / index** - changed files grouped by area, each tagged (🟢 added · 🔴 removed · ✏️ changed · ⚙️ mechanical) with +/− counts; click to jump.4. **Per-file cards** - for each logical file: a claim-carrying title, a one-line summary of how its behavior changed, **before/after** diagrams with real symbol names + `file:line` (changed nodes in orange), and the diff in a collapsed `<details>`. Mechanical files get a small `before → after` table, no diagram.5. **(optional) Risk / follow-ups** - only if grounded in what you read.
## Non-negotiable principles
1. **Optimize for scarce reviewer attention.** The first screen answers, in ~15 seconds: what this PR does, whether it's risky, where to look first, and what evidence backs the claim. Lead with the conclusion, not your process.2. **Show the difference, not just the after.** For any logic or API change, draw **before** and **after** and make the *delta* visually loud (color + line style). The contrast is the product.3. **Ground everything to code, beside the claim.** Every box, node, and sentence names a real symbol + `path:line`, and links to the correct source revision where possible: the merge-base SHA for before-state evidence and the verified head SHA for after-state evidence. One click from "this changed" to the exact code.4. **Hand-draw the carrying diagrams.** Prefer bespoke inline SVG for the before/after that makes the argument; Mermaid is fine only for quick auxiliary graphs.5. **Self-contained & offline.** One HTML file, inline CSS/SVG, no external scripts or assets, opens by double-click, and survives being copied to another machine.6. **`.pr/` only, and temporary.** The doc is a review aid, not project docs. Keep it in `.pr/` and ensure it is removed before merge. Rely on automatic cleanup only when the repository's workflow has been verified; otherwise remove it manually. Do not move design HTML into `docs/` or ship it in the merged tree.
## Anti-patterns
- ❌ Dumping the raw diff / file tree and calling it a "design doc" - adds nothing over the PR page.- ❌ Empty nodes ("process data", "handle request") - every node is a real symbol + location.- ❌ Only the after-state when something changed - reviewers want the *contrast*.- ❌ A design doc on a trivial PR - noise. Skip it.- ❌ Committing the HTML outside `.pr/` (e.g. `docs/`), where it would merge into `main`.- ❌ Publishing a private-repository design doc through htmlpreview, GitHub Pages, or another public host. Use the private/local preview path in the craft reference. Use GitHub Pages only with explicit user authorization after verifying private Pages access control.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322# html-craft - how to build the page
Shared craft for every show-me dimension. One self-contained, offline, editorial HTMLpage with hand-drawn SVG figures and code-grounded claims.
## The look (editorial document, light theme)
Calm, readable, document-like - not a dark dashboard. Skeleton:
```html<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{{Title}}</title><style> :root{ /* single source of truth - prose AND inline-SVG fills both read these (see SVG section) */ --fg:#1a1a1a; --muted:#5a5a5a; --subtle:#8a8a82; /* 3 text weights: title · detail · sublabel */ --bg:#fdfdfb; --card:#ffffff; --elevated:#f7f6f1; /* page · node fill · raised band/pill */ --accent:#2b4eaa; --accent-soft:#e6ecfa; --rule:#e2e2dc; --rule-strong:#bdbcb4; /* hairline · emphasized border */ --code-bg:#f3f1ec; --warn:#b25b0e; --ok:#2f7a3a; --crit:#a02020; --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; --sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,Helvetica,Arial,sans-serif; } *{box-sizing:border-box} html,body{margin:0;background:var(--bg);color:var(--fg);font-family:var(--sans)} body{line-height:1.6;font-size:16px} .wrap{display:grid;grid-template-columns:240px minmax(0,1fr);gap:48px;max-width:1180px;margin:0 auto;padding:32px 28px 96px} nav.toc{position:sticky;top:24px;align-self:start;font-size:13px} nav.toc h2{font-size:11px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;color:var(--muted);margin:0 0 10px} nav.toc ol{list-style:none;padding:0;margin:0;counter-reset:toc} nav.toc li{counter-increment:toc;margin:4px 0} nav.toc li::before{content:counter(toc) ". ";color:var(--muted)} nav.toc a{color:var(--fg);text-decoration:none} nav.toc a:hover{color:var(--accent)} header.title{border-bottom:1px solid var(--rule);padding-bottom:22px;margin-bottom:28px} header.title .eyebrow{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--accent);font-weight:700} header.title h1{font-size:34px;margin:6px 0 4px;letter-spacing:-.01em} header.title .sub{color:var(--muted);max-width:740px} h2{font-size:22px;margin:44px 0 10px} h2 .num{color:var(--muted);font-weight:500;margin-right:8px} h3{font-size:16px;margin:22px 0 8px} code{font-family:var(--mono);font-size:.88em;background:var(--code-bg);padding:1px 5px;border-radius:3px} pre{font-family:var(--mono);font-size:13px;background:var(--code-bg);padding:14px 16px;border-radius:6px;overflow-x:auto;border:1px solid var(--rule)} pre code{background:transparent;padding:0} .kw{color:#7048a8}.str{color:var(--ok)}.com{color:var(--subtle);font-style:italic} table{border-collapse:collapse;width:100%;font-size:14px;margin:12px 0} th,td{text-align:left;padding:8px 10px;border-bottom:1px solid var(--rule);vertical-align:top} th{font-weight:600;background:var(--code-bg)} .callout{border-left:3px solid var(--accent);background:var(--accent-soft);padding:10px 14px;margin:14px 0;border-radius:0 4px 4px 0;font-size:14.5px} .callout.warn{border-color:var(--warn);background:#fbf1e6} .callout.note{border-color:var(--muted);background:#f3f1ec} .fig{margin:18px 0 22px} .fig svg{display:block;max-width:100%;height:auto;background:#fff;border:1px solid var(--rule);border-radius:6px} .fig figcaption{font-size:13px;color:var(--muted);margin-top:6px;text-align:center} a.src{font-family:var(--mono);font-size:12px;color:var(--accent);text-decoration:none;border-bottom:1px dotted var(--accent)} details{border:1px solid var(--rule);border-radius:6px;margin:12px 0} details>summary{cursor:pointer;padding:8px 12px;color:var(--muted);font-size:13px;list-style:none} details>summary::-webkit-details-marker{display:none} details>summary::before{content:"▸ "} details[open]>summary::before{content:"▾ "} .ba{display:grid;grid-template-columns:1fr 1fr;gap:16px;align-items:start} @media(max-width:760px){.wrap{grid-template-columns:1fr}.ba{grid-template-columns:1fr}}</style></head><body><div class="wrap"> <nav class="toc"><h2>Contents</h2><ol> <li><a href="#sec1">…</a></li> </ol></nav> <main> <header class="title"><div class="eyebrow">{{kind}}</div><h1>{{Title}}</h1> <p class="sub">{{one-paragraph mental model - the big picture in 2-3 sentences}}</p></header> <section id="sec1"><h2><span class="num">1</span>…</h2> … </section> </main></div></body></html>```
Numbered sticky TOC + one-paragraph mental model up top + sectioned body. No JS neededfor this shell.
## First screen: 15-second orientation
The reader's attention is the budget. The first viewport should answer four questionswithout requiring a full read:
1. **What is this?** A one-paragraph mental model in the title subtitle.2. **Why does it matter?** The highest-impact conclusion, risk, or action in a `★` callout near the top.3. **Where should I jump?** A numbered sticky TOC whose labels carry information, not just categories.4. **Why should I trust it?** Nearby source links (`path:line`, test, command, commit, or fixture) for the first substantive claim.
Do not open with "I read these files" or a chronological work log. Start with thereader's decision: what changed, how the system works, what path matters, or where tolook next. Put methods, command output, and raw diffs behind `<details>` unless theyare the point of the report.
## Skimmable structure
Design the page so a busy reader can scan headings, captions, callouts, and tablesbefore choosing where to dive:
- **Headings make claims.** Prefer "Writes only cross the queue" over "Architecture", when the section has a specific finding. Generic labels are acceptable only when the title/subtitle already carries the finding.- **One paragraph, one judgment.** Keep paragraphs short; split when a sentence starts proving a different point.- **Number parallel points.** If you say "three rules" or "two risks", number them so the reader can reconcile the claim with the list.- **Use tables only for stable comparison axes.** A table should reduce cognitive work, not force subtle judgments into neat boxes.- **Make captions do work.** A caption states the takeaway of the figure, not merely its type.
## Callouts (give them semantic types)
The `.callout` / `.callout.warn` / `.callout.note` styles aren't interchangeable - assigneach a fixed job and the reader learns to skim by them:
- **`★` key takeaway** (accent) - the one load-bearing sentence of a section. At most one per section; it's what the reader should remember if they read nothing else.- **`ⓘ` note** (`.note`, muted) - a reading hint for a figure, an aside, a "why we did it this way" that isn't on the critical path.- **`⚠` warning** (`.warn`) - a boundary, a risk, a gotcha, a guardrail: trust boundaries, "this does NOT do X", "never commit the secret". Reserve it for things that bite.
Don't let callouts become wallpaper - if every paragraph is a colored box, none of them carryweight. A glyph prefix (`★ ⓘ ⚠`) makes the type legible before the reader parses the text.
## Hand-drawn SVG figures (the diagrams that carry the argument)
Draw bespoke inline `<svg viewBox="0 0 W H">` with a `<defs>` for arrow markers and ascoped `<style>`. You place every box → before/after stays aligned, legible, and thedelta is unmistakable. Semantic class system:
```html<svg viewBox="0 0 960 460" role="img" aria-labelledby="f1-t f1-d"> <title id="f1-t">moduleA call path - before vs after</title> <desc id="f1-d">Old direct call is replaced by a routed path through the new resolver.</desc> <defs> <!-- one marker per semantic color; marker fills read the page palette --> <marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"> <path d="M0,0 L10,5 L0,10 Z" fill="var(--subtle)"/></marker> <marker id="arr-chg" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"> <path d="M0,0 L10,5 L0,10 Z" fill="var(--warn)"/></marker> <!-- subtle "elevated" wash for the box that is the figure's subject --> <linearGradient id="subj" x1="0" y1="0" x2="0" y2="1"> <stop offset="0" stop-color="var(--accent)" stop-opacity=".10"/> <stop offset="1" stop-color="var(--accent)" stop-opacity=".02"/></linearGradient> <style> /* every fill/stroke is a --token: the palette lives once, in :root - prose & figures can't drift */ .existing{fill:var(--code-bg);stroke:var(--subtle);stroke-width:1.4;stroke-dasharray:5 3} /* before */ .ex-title{font:700 13px var(--sans);fill:var(--muted)} .ex-detail{font:11.5px var(--mono);fill:var(--subtle)} .new{fill:var(--accent-soft);stroke:var(--accent);stroke-width:2} /* after / added */ .new-title{font:800 13px var(--sans);fill:var(--accent)} .detail{font:11.5px var(--mono);fill:var(--fg)} .edge{stroke:var(--subtle);stroke-width:1.5;stroke-dasharray:5 3;fill:none} .edge-chg{stroke:var(--warn);stroke-width:1.8;fill:none;stroke-dasharray:5 3} /* the delta */ .lbl{font:600 10.5px var(--mono);fill:var(--accent)} .gap{font:700 11.5px var(--mono);fill:var(--warn)} </style> </defs> <!-- ===== BEFORE: direct call ===== --> <g> <rect class="existing" x="40" y="60" width="180" height="74" rx="6"/> <text class="ex-title" x="130" y="90" text-anchor="middle">moduleA.fn()</text> <text class="ex-detail" x="130" y="110" text-anchor="middle">old behavior · a.py:42</text> </g> <!-- ===== AFTER: routed call (the change) ===== --> <g> <rect class="new" x="300" y="60" width="180" height="74" rx="6"/> <text class="new-title" x="390" y="90" text-anchor="middle">moduleA.fn()</text> <path class="edge-chg" d="M220,97 L300,97" marker-end="url(#arr-chg)"/> <!-- pill behind an on-edge label so it stays legible over the line --> <rect x="236" y="79" width="48" height="16" rx="5" fill="var(--elevated)" stroke="var(--rule)"/> <text class="gap" x="260" y="91" text-anchor="middle">new path</text> </g></svg>```
**Five craft moves in that skeleton - they're what make a figure read like a designeddiagram instead of a sketch:**- **Drive every fill/stroke from `var(--token)`.** Define the palette once in `:root`; the SVG references it. One source of truth - prose and figures stay in lockstep, and a palette tweak reflows every diagram. Never paste a raw hex into a figure.- **Three text weights, always the same three.** `--fg` for the node title (the real symbol), `--muted` for the detail line, `--subtle` for sublabels/`path:line`. The eye sorts the hierarchy without reading. Mixing weights ad-hoc is what makes a diagram look noisy.- **`<title>` + `<desc>` with `aria-labelledby`.** Not decoration: it's the figure's own caption-of-record (screen readers, and a note-to-self of what the figure claims).- **A gradient wash marks the subject.** The one container the figure is *about* gets the `#subj` wash (accent 10%→2%); everything else is flat. The reader's eye lands on the protagonist before reading a word.- **`<g>` groups + `<!-- section -->` comments + on-edge label pills.** Author the SVG like code: one `<g>` per logical unit, a comment naming it, and a small `rect` pill behind any label that sits on a line (a bare label over an edge turns to mush). It stays editable when you revise the layout three times.
**The before/after encoding (use consistently):**- **dashed gray** (`.existing`, `.edge` muted) = what was there before / unchanged context.- **solid accent** (`.new`) = what this change adds / the after-state.- **orange dashed** (`.edge-chg`, `.gap`) = the *delta* - the new/changed flow, the gap being filled. This is what the eye should land on.
Node boxes carry a **title (real symbol) + a detail line (behavior + `file:line`)**, so thediagram is already half-grounded to code.
Two ways to show before/after:1. **Side-by-side figures** in a `.ba` grid - `<figure>` "Before" | `<figure>` "After". Best when layouts differ a lot.2. **One overlaid figure** - existing nodes dashed-gray, new nodes/edges solid-accent + orange delta, in the same coordinate space. Best when the change is *additive* to an existing structure (most legible "what's new" read).
## Caption every figure, and hint how to read the hard ones
A figure with no caption makes the reader reverse-engineer your intent. Two cheap habitsfix it:
- **The `<figcaption>` states the takeaway, not a label.** Not "Architecture diagram" - *"Requests never touch the DB directly; every write goes through the queue."* The caption is the one sentence you'd say pointing at the figure. Number them (`Fig 3 ·`) and **cross-reference between figures** (`state machine in Fig 2`, `evolve timing in Fig 5`) so a multi-figure report reads as one system at different altitudes, not five loose pictures.- **For a figure with a non-obvious convention, add a one-line reading hint** in a `.callout.note` right under it, naming the single thing that unlocks it: *"Every arrow enters or leaves the bus - there are no agent-to-agent arrows, because the protocol is 'read/write the bus'."* One sentence that says *how to look* saves the reader a minute of squinting. Put the hint in the figure too when you can - an in-diagram `→ §3.2 / Fig 2` link (accent mono) turns the picture into a table of contents.
## Ground every claim to code (clickable)
A picture the human can't verify is a liability. Make claims droppable to source:
- Resolve both repository web bases explicitly. For a fork PR, before-state evidence belongs to the base repository and merge-base SHA; after-state evidence belongs to the head repository and verified head SHA. Query each with `gh repo view <owner>/<repo> --json url`, then build links as `https://github.com/<o>/<r>/blob/<sha>/<path>#L<n>`. A deleted file must link to the base repository at the merge-base SHA; a newly added file has no before-state link.- Render locations as `<a class="src" href="{{blobURL}}">path:line</a>` in node detail lines, section text, and a per-component "source" link.- Rule: if a box can't be tied to a symbol+location, it's a *concept* box - style it differently and say so; don't fake a link.- Put evidence beside the claim it supports. The reader should not have to scroll to a bibliography to verify a behavior statement, edge, risk, metric, or test result.- Commands count as evidence when behavior must be observed: show the command and the relevant result near the claim, with full logs collapsed if noisy.
### Grounding discipline (borrowed from DeepWiki)
DeepWiki-style wikis enforce grounding hard - worth copying:
- **Source manifest per section.** Open each major section / component card with a small collapsed list of the exact files it's built from: `<details><summary>Sources</summary> path/a.py · path/b.py …</details>`. The reader sees what the claim rests on before trusting it.- **Cite after every substantive claim, diagram, table, and snippet.** Inline format: `Sources: [path:start-end]` (range) or `[path:line]` (single), multiple allowed. A section with no citations is a smell - either ground it or cut it.- **Solely from the code. Do not invent.** Every statement, box, edge, and number must be derived from files you actually read - not from how "similar systems usually work." If something important isn't in the code, say so explicitly rather than guessing. Mark genuine inferences as inferences.- **Breadth check.** Decide if necessary, depending on PR. A "comprehensive" page that cites only 1-2 files is probably shallow - pull in the related files (callers, callees, config, tests) until the picture is real.
## Code excerpts (when shown)
Keep them short and hand-highlight with spans (no JS highlighter): wrap keywords`<span class="kw">`, strings `<span class="str">`, comments `<span class="com">`.**Escape for the insertion context before wrapping** - source text is untrusted. In textnodes, escape `&`, `<`, and `>`. In quoted HTML or SVG attributes, additionally escape `"`as `"` and `'` as `'`; always quote attributes. For source URLs, percent-encode thedynamic owner, repository, and ref as URL path segments; encode each source-path segmentseparately and rejoin with `/`. Then attribute-escape the completed URL. Put long diffs/codeinside `<details>` (collapsed). Escape every source-derived valueinserted into HTML or SVG, including titles, symbol names, paths, labels, link text, andattribute values. Never treat source-derived text as markup.
## Self-contained
- One `.html` file. Inline all CSS and SVG. No build, no framework.- No external scripts, styles, fonts, images, or other assets. Besides breaking offline use, third-party active content can read and disclose a private design document opened locally.
## Mermaid (quick / auxiliary only)
For drafting a throwaway or simple auxiliary graph, locally installed Mermaid can be fasterthan hand-SVG. Render it locally to static SVG, inspect and sanitize the output, then inlinethat SVG. Never ship a Mermaid runtime or CDN script in the page. For the **carrying**before/after diagram, hand-SVG wins - auto-layout drifts and breaks the side-by-side alignmentthat makes the delta readable.
### Public repositories: commit under `.pr/` and use an htmlpreview link
Because the page is **self-contained**, GitHub can render it through `htmlpreview.github.io`(it fetches the raw HTML and serves it with the right content-type - plain `raw.githubusercontent.com`won't, it returns `text/plain`). Commit the file to the PR branch under the temporary `.pr/`directory, then build the link and paste it in the PR description:
```bash# commit the html under .pr/ on your PR branch (this dir is temporary, see the skill)git add .pr/design.html && git commit -m "docs(.pr): design doc" && git push <your-fork> <branch># link template - use YOUR fork + PR branch, so it renders before the PR is merged:# https://htmlpreview.github.io/?https://github.com/<fork-owner>/<repo>/blob/<pr-branch>/.pr/design.html```
Example shape:`https://htmlpreview.github.io/?https://github.com/FORK_OWNER/REPO/blob/PR_BRANCH/.pr/design.html`
`<pr-branch>` can be any branch or commit - `raw.githubusercontent.com` serves it regardlessof merge state, so the doc renders while the PR is still open. Point the URL at the **forkand branch the PR is opened from**, not `main`.
For public repositories, anyone can open the rendered page without a download or local server.This works with self-contained pages containing only inline CSS and SVG.
### Private repositories: keep the preview private
`htmlpreview` cannot fetch private repository content. Do not work around that by publishingthe design doc to GitHub Pages or another public host. Keep the document free of externalscripts and assets: opening a local file does not make third-party active content private.
- Link authorized reviewers to the committed GitHub blob and ask them to download and open the self-contained HTML file locally; or use an existing access-controlled artifact service.- For a local browser preview, open `.pr/design.html` directly. If the browser needs HTTP, serve only on loopback: ```bash python -m http.server 8000 --bind 127.0.0.1 --directory .pr # open http://127.0.0.1:8000/design.html ```- Use GitHub Pages only when the user explicitly authorizes publication and an administrator confirms that private Pages access control is enabled for this repository.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110---name: releasedescription: Guide the release process for @openhands/agent-canvas — review the release-please draft PR, mark it ready, merge it; the tag push publishes to npm and Docker.triggers:- release- new release- cut a release- publish release- bump version---
# Release Process for @openhands/agent-canvas
## Overview
Releases are **trunk-based and automated by release-please**, via the shared reusableworkflows in [`OpenHands/release-actions`](https://github.com/OpenHands/release-actions):
1. PRs merge to `main` with **Conventional Commit titles** (`feat`, `fix`, `perf`, `docs`, `chore`, `build`, `ci`, `refactor`, `style`, `test`, `revert`). `.github/workflows/pr.yml` lints the title and applies the matching `type:` label; squash merge uses the PR title as the commit message.2. On every push to `main`, `.github/workflows/release.yml` runs release-please, which maintains a **draft release PR** titled `chore(main): release X.Y.Z` accumulating everything merged since the last release.3. The release PR pre-stages **every version bump**: `package.json`, `package-lock.json`, `config/defaults.json` (`versions.agentCanvas`), and the Docker image pins in `README.md` / `README.windows.md` (lines annotated with `x-release-please-version`).4. Marking the release PR **Ready for review** is the explicit cut-a-release signal: `.github/workflows/release-ready.yml` notifies `#proj-agent-canvas` on Slack and labels the PR `release: ready`.5. Merging the release PR makes release-please push the `vX.Y.Z` tag (using the org release App token) and create the GitHub Release. The same tag push triggers `npm-publish.yml` (npm) and `docker.yml` (multi-arch GHCR images).
The next version is derived from the conventional-commit types merged since the last release: `fix` → patch, `feat` → minor, any `!` suffix or `BREAKING CHANGE` footer → major. Other types (`docs`, `chore`, `refactor`, …) appear in the release notes but do not by themselves produce a release PR. Release notes are grouped by the `type:` labels via `.github/release.yml`; there is no `CHANGELOG.md` file — GitHub Releases are the changelog.
Configuration lives in `release-please-config.json` (version surfaces, draft PR) and `.release-please-manifest.json` (current released version). Maintenance releases for an older line use `release/**` branches (`release.yml` triggers there too).
**Never commit to the release PR's branch by hand** — release-please owns it and force-pushes it on every push to `main`.
---
## Step 1: Find the Release PR
```bashgh pr list --state open --label "autorelease: pending"```
If no release PR is open, nothing releasable (`feat`/`fix`/breaking) has merged since the last release — or `release.yml` is failing on `main`:
```bashgh run list --workflow=release.yml --limit=3```
---
## Step 2: Review It
Open the release PR and confirm:
- **The version** in the title matches expectations. It is computed from the merged commit types — if it looks wrong, check the conventional types of the PR titles merged since the last release. To force a specific version, merge a commit to `main` whose message contains a `Release-As: X.Y.Z` footer.- **The staged bumps** cover all version surfaces (`package.json`, `package-lock.json`, `config/defaults.json`, `README.md`, `README.windows.md`) and the notes list the expected changes.
---
## Step 3: Cut the Release
**STOP HERE and confirm with the user before proceeding.** Marking the PR ready and merging it publishes to npm and GHCR.
```bashgh pr ready <release-pr-number>```
This fires the release-ready gate: a Slack notification lands in `#proj-agent-canvas` and the PR is labeled `release: ready`. Then merge the release PR (squash, like any other PR).
---
## Step 4: Watch the Pipeline
Merging the release PR triggers `release.yml` on `main`, which pushes the `vX.Y.Z` tag and creates the GitHub Release; the tag push then fires the publish workflows:
```bashgh run list --workflow=release.yml --limit=3gh run list --workflow=npm-publish.yml --limit=3gh run list --workflow=docker.yml --limit=3```
---
## Step 5: Verify the Release
```bash# GitHub releasegh release view v<version>
# npm (allow ~2 min for publish to propagate)npm view @openhands/agent-canvas@<version>npm view @openhands/agent-canvas dist-tags # stable releases get `latest`
# Dockerdocker pull ghcr.io/openhands/agent-canvas:<version>```
External install docs on docs.openhands.dev are maintained separately; update them there when closing #1073.
---
## Troubleshooting
### No release PR appears after merging to mainOnly `feat`, `fix`, and breaking changes produce a release PR. Also check `release.yml` runs on `main` — the workflow fails by design if the org secrets `RELEASE_APP_ID` / `RELEASE_APP_PRIVATE_KEY` are unavailable (a `GITHUB_TOKEN` fallback would create a tag that never triggers the publish workflows).
### The proposed version is wrongThe version comes from the conventional-commit history since the last release. Fix forward: merge a commit to `main` with a `Release-As: X.Y.Z` footer to pin the next version.
### No Slack message when the PR was marked ready`SLACK_BOT_TOKEN` is optional by design — the gate still applies the `release: ready` label and the release proceeds normally.
### package.json version doesn't match the tagThis cannot happen in the normal flow: release-please bumps `package.json` in the release PR and tags the resulting merge commit, and `npm-publish.yml` validates they match. If it ever fails, someone pushed a tag by hand — delete the tag and let release-please own tagging.3 unmodified lines45678910111213143 unmodified lines*.png binary*.ico binary*.icns binaryelectron/build-resources/icon.icns filter=lfs diff=lfs merge=lfs -text.github/pr-assets/pr-16268-02-lightbox-open.png filter=lfs diff=lfs merge=lfs -text.github/pr-assets/pr-16860-01-skills-default.png filter=lfs diff=lfs merge=lfs -text.github/pr-assets/pr-16676-01-list.png filter=lfs diff=lfs merge=lfs -text.github/pr-assets/pr-16605-test-results.png filter=lfs diff=lfs merge=lfs -text.github/pr-assets/pr-16676-02-templates.png filter=lfs diff=lfs merge=lfs -text.github/pr-assets/pr-16860-02-recommended-facet.png filter=lfs diff=lfs merge=lfs -text.github/pr-assets/pr-16676-04-edit-modal.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import { beforeEach, describe, expect, it, vi } from "vitest";import type { BashOutput } from "@openhands/typescript-client";import AcpService from "#/api/acp-service/acp-service.api";
// Capture the command the service runs and control the BashOutput it sees.const executeCommand = vi.hoisted(() => vi.fn());vi.mock("@openhands/typescript-client/clients", () => ({ BashClient: class { executeCommand = executeCommand; },}));vi.mock("#/api/agent-server-client-options", () => ({ getAgentServerClientOptions: () => ({ host: "http://localhost", workingDir: "/", }),}));
function bashOutput(partial: Partial<BashOutput>): BashOutput { return { id: "1", timestamp: "2026-01-01T00:00:00Z", command_id: "c1", order: 0, exit_code: 0, stdout: null, stderr: null, kind: "BashOutput", ...partial, } as BashOutput;}
beforeEach(() => vi.clearAllMocks());
describe("AcpService.getAuthStatus", () => { describe("claude-code (claude auth status --json)", () => { it("runs the right command and maps loggedIn:true → authenticated", async () => { executeCommand.mockResolvedValue( bashOutput({ stdout: JSON.stringify({ loggedIn: true, authMethod: "claude.ai" }), }), ); await expect(AcpService.getAuthStatus("claude-code")).resolves.toBe( "authenticated", ); expect(executeCommand).toHaveBeenCalledWith( "claude auth status --json", undefined, expect.any(Number), ); });
it("maps loggedIn:false (even with a non-zero exit) → unauthenticated", async () => { executeCommand.mockResolvedValue( bashOutput({ stdout: JSON.stringify({ loggedIn: false }), exit_code: 1, }), ); await expect(AcpService.getAuthStatus("claude-code")).resolves.toBe( "unauthenticated", ); });
it("→ unknown when the CLI is missing (exit 127, no JSON on stdout)", async () => { // The "no available ACP process / CLI not installed" path. executeCommand.mockResolvedValue( bashOutput({ exit_code: 127, stderr: "env: claude: No such file or directory", }), ); await expect(AcpService.getAuthStatus("claude-code")).resolves.toBe( "unknown", ); }); });
describe("codex (codex login status)", () => { it("→ authenticated even though the CLI writes to stderr", async () => { executeCommand.mockResolvedValue( bashOutput({ stderr: "Logged in using ChatGPT\n" }), ); await expect(AcpService.getAuthStatus("codex")).resolves.toBe( "authenticated", ); });
it("→ unauthenticated on 'Not logged in'", async () => { executeCommand.mockResolvedValue( bashOutput({ stderr: "Not logged in\n" }), ); await expect(AcpService.getAuthStatus("codex")).resolves.toBe( "unauthenticated", ); });
it("→ unknown when the CLI is missing", async () => { executeCommand.mockResolvedValue( bashOutput({ exit_code: 127, stderr: "codex: command not found" }), ); await expect(AcpService.getAuthStatus("codex")).resolves.toBe("unknown"); }); });
describe("gemini-cli (credentials file check)", () => { it("→ authenticated when the creds file is present", async () => { executeCommand.mockResolvedValue(bashOutput({ stdout: "present\n" })); await expect(AcpService.getAuthStatus("gemini-cli")).resolves.toBe( "authenticated", ); // Probes the OAuth creds file, not a (nonexistent) gemini status command. expect(executeCommand.mock.calls[0][0]).toContain("oauth_creds.json"); });
it("→ unauthenticated when the creds file is absent", async () => { executeCommand.mockResolvedValue(bashOutput({ stdout: "absent\n" })); await expect(AcpService.getAuthStatus("gemini-cli")).resolves.toBe( "unauthenticated", ); }); });
it("→ unknown for an unprobeable provider, without running any command", async () => { await expect(AcpService.getAuthStatus("openhands")).resolves.toBe( "unknown", ); expect(executeCommand).not.toHaveBeenCalled(); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import { beforeEach, describe, expect, it, vi } from "vitest";import { MIN_AGENT_SERVER_VERSION_FOR_PROFILE_SWITCH_LLM_TOOL, agentProfileSupportsSwitchLlmTool,} from "#/api/agent-profiles-service/profile-field-support";
const mockGetCachedAgentServerVersion = vi.fn<() => string | null>();
// Only the version *lookup* is mocked — the comparison stays the real one so// these cases exercise the same parser the boot-time compatibility check uses.vi.mock("#/api/agent-server-compatibility", async (importOriginal) => { const actual = await importOriginal<typeof import("#/api/agent-server-compatibility")>(); return { ...actual, getCachedAgentServerVersion: () => mockGetCachedAgentServerVersion(), };});
describe("agentProfileSupportsSwitchLlmTool", () => { beforeEach(() => { mockGetCachedAgentServerVersion.mockReset(); });
it("pins the gate to the release that added the profile field", () => { expect(MIN_AGENT_SERVER_VERSION_FOR_PROFILE_SWITCH_LLM_TOOL).toBe("1.31.0"); });
it.each(["1.29.0", "1.29.3", "1.30.0"])( "reports no support on %s, where agent profiles exist but the field does not", (version) => { mockGetCachedAgentServerVersion.mockReturnValue(version); expect(agentProfileSupportsSwitchLlmTool()).toBe(false); }, );
it.each(["1.31.0", "1.31.2", "1.36.1", "2.0.0"])( "reports support on %s", (version) => { mockGetCachedAgentServerVersion.mockReturnValue(version); expect(agentProfileSupportsSwitchLlmTool()).toBe(true); }, );
it("treats a prerelease of the gating version as older", () => { mockGetCachedAgentServerVersion.mockReturnValue("1.31.0-rc.1"); expect(agentProfileSupportsSwitchLlmTool()).toBe(false); });
it("assumes support when no version is cached (cloud backends)", () => { mockGetCachedAgentServerVersion.mockReturnValue(null); expect(agentProfileSupportsSwitchLlmTool()).toBe(true); });
it("assumes support when the reported version does not parse", () => { mockGetCachedAgentServerVersion.mockReturnValue("main"); expect(agentProfileSupportsSwitchLlmTool()).toBe(true); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, getActiveBackend, getEffectiveLocalBackend, NO_BACKEND_ID, setActiveSelection, setRegisteredBackends, subscribeActiveBackend,} from "#/api/backend-registry/active-store";import { SEEDED_DEFAULT_BACKEND_ID } from "#/api/backend-registry/default-backend";import { MAX_CONSECUTIVE_FAILURES } from "#/api/backend-registry/health-storage";import { __resetHealthStoreForTests, recordBackendFailure,} from "#/api/backend-registry/health-store";import { ACTIVE_BACKEND_STORAGE_KEY, BACKENDS_STORAGE_KEY,} from "#/api/backend-registry/storage";import { BACKEND_QUERY_PARAM, ORG_QUERY_PARAM,} from "#/api/backend-registry/url-selection";import type { Backend } from "#/api/backend-registry/types";
beforeEach(() => { window.localStorage.clear(); window.sessionStorage.clear(); __resetHealthStoreForTests(); __resetActiveStoreForTests();});
afterEach(() => { window.localStorage.clear(); window.sessionStorage.clear(); vi.unstubAllEnvs(); __resetHealthStoreForTests(); __resetActiveStoreForTests();});
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-key", kind: "cloud",};
const localBackend: Backend = { id: "local-1", name: "Local 1", host: "http://localhost:9000", apiKey: "k", kind: "local",};
const secondLocalBackend: Backend = { id: "local-2", name: "Local 2", host: "http://localhost:9001", apiKey: "k2", kind: "local",};
function markBackendUnhealthy(id: string): void { for (let i = 0; i < MAX_CONSECUTIVE_FAILURES; i += 1) { recordBackendFailure(id, new Error("connection failed")); }}
describe("active-store", () => { it("uses the no-backend sentinel when no backend details are available", () => { window.localStorage.clear(); window.sessionStorage.clear(); vi.stubEnv("VITE_SESSION_API_KEY", ""); __resetActiveStoreForTests();
const { backend, orgId } = getActiveBackend(); expect(backend.id).toBe(NO_BACKEND_ID); expect(orgId).toBeNull(); });
it("seeds the registry with a default local backend when host and API key are available", () => { vi.stubEnv("VITE_BACKEND_BASE_URL", "http://localhost:9000"); vi.stubEnv("VITE_SESSION_API_KEY", "session-key"); __resetActiveStoreForTests();
const { backend, orgId } = getActiveBackend(); expect(backend.id).toBe(SEEDED_DEFAULT_BACKEND_ID); expect(backend.kind).toBe("local"); expect(orgId).toBeNull(); });
it("returns the registered backend matching the active selection", () => { setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id, orgId: "org-2" });
const { backend, orgId } = getActiveBackend(); expect(backend).toEqual(cloudBackend); expect(orgId).toBe("org-2"); });
it("falls back to the first local backend when the active selection points at a removed entry", () => { setRegisteredBackends([cloudBackend, localBackend]); setActiveSelection({ backendId: cloudBackend.id, orgId: null }); setRegisteredBackends([localBackend]);
expect(getActiveBackend().backend).toEqual(localBackend); expect(getActiveBackend().orgId).toBeNull(); });
it("falls back to a healthy local backend when a cloud backend is registered first", () => { setRegisteredBackends([cloudBackend, localBackend]); setActiveSelection(null);
expect(getActiveBackend().backend).toEqual(localBackend); });
it("skips an unhealthy local backend in favor of a healthy one further down", () => { markBackendUnhealthy(localBackend.id); setRegisteredBackends([localBackend, secondLocalBackend]); setActiveSelection(null);
expect(getActiveBackend().backend).toEqual(secondLocalBackend); });
it("still selects a local backend when every local backend is unhealthy", () => { markBackendUnhealthy(localBackend.id); markBackendUnhealthy(secondLocalBackend.id); setRegisteredBackends([cloudBackend, localBackend, secondLocalBackend]); setActiveSelection(null);
const { backend } = getActiveBackend(); expect(backend.kind).toBe("local"); expect(backend.id).not.toBe(NO_BACKEND_ID); // Deterministic: first local backend in insertion order. expect(backend).toEqual(localBackend); });
it("selects a single healthy local backend at the first registry position", () => { setRegisteredBackends([localBackend]); setActiveSelection(null);
expect(getActiveBackend().backend).toEqual(localBackend); });
it("falls back to the first registered backend when the registry has no local entry", () => { setRegisteredBackends([cloudBackend]); setActiveSelection(null);
expect(getActiveBackend().backend).toEqual(cloudBackend); });
it("uses the active local backend as the effective local backend", () => { setRegisteredBackends([localBackend, cloudBackend]); setActiveSelection({ backendId: localBackend.id });
expect(getEffectiveLocalBackend()).toEqual(localBackend); });
it("does not borrow a registered local backend when the active backend is cloud", () => { setRegisteredBackends([localBackend, cloudBackend]); setActiveSelection({ backendId: cloudBackend.id });
expect(getEffectiveLocalBackend()).toBeNull(); });
it("keeps an explicit cloud selection even when a healthy local backend exists", () => { setRegisteredBackends([localBackend, cloudBackend]); setActiveSelection({ backendId: cloudBackend.id, orgId: "org-2" });
const { backend, orgId } = getActiveBackend(); expect(backend).toEqual(cloudBackend); expect(orgId).toBe("org-2"); });
it("notifies subscribers when selection changes", () => { const listener = vi.fn(); const unsubscribe = subscribeActiveBackend(listener);
setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id });
expect(listener).toHaveBeenCalled();
unsubscribe(); listener.mockClear(); setActiveSelection(null); expect(listener).not.toHaveBeenCalled(); });});
describe("backend pinned in the URL", () => { function seedRegistry(backends: Backend[], selection: string) { window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify(backends)); window.localStorage.setItem( ACTIVE_BACKEND_STORAGE_KEY, JSON.stringify({ backendId: selection, orgId: null }), ); }
function bootAt(search: string) { window.history.replaceState({}, "", `/conversations/abc${search}`); __resetActiveStoreForTests(); }
afterEach(() => { window.history.replaceState({}, "", "/"); });
it("boots on the backend named in the URL instead of the stored one", () => { seedRegistry([localBackend, secondLocalBackend], localBackend.id);
bootAt(`?${BACKEND_QUERY_PARAM}=${secondLocalBackend.id}`);
expect(getActiveBackend().backend).toEqual(secondLocalBackend); });
it("persists the pinned selection so later in-tab navigation keeps it", () => { seedRegistry([localBackend, secondLocalBackend], localBackend.id);
bootAt(`?${BACKEND_QUERY_PARAM}=${secondLocalBackend.id}`);
expect( JSON.parse( window.sessionStorage.getItem(ACTIVE_BACKEND_STORAGE_KEY) ?? "null", ), ).toEqual({ backendId: secondLocalBackend.id, orgId: null }); });
it("carries the org id for a cloud backend", () => { seedRegistry([localBackend, cloudBackend], localBackend.id);
bootAt( `?${BACKEND_QUERY_PARAM}=${cloudBackend.id}&${ORG_QUERY_PARAM}=org-9`, );
const { backend, orgId } = getActiveBackend(); expect(backend).toEqual(cloudBackend); expect(orgId).toBe("org-9"); });
it("falls back to the stored selection when the URL names an unknown backend", () => { seedRegistry([localBackend, secondLocalBackend], secondLocalBackend.id);
bootAt(`?${BACKEND_QUERY_PARAM}=removed-backend`);
expect(getActiveBackend().backend).toEqual(secondLocalBackend); });
it("prefers the URL over a tab-scoped sessionStorage selection", () => { seedRegistry([localBackend, secondLocalBackend], localBackend.id); window.sessionStorage.setItem( ACTIVE_BACKEND_STORAGE_KEY, JSON.stringify({ backendId: localBackend.id, orgId: null }), );
bootAt(`?${BACKEND_QUERY_PARAM}=${secondLocalBackend.id}`);
expect(getActiveBackend().backend).toEqual(secondLocalBackend); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import { afterEach, beforeEach, describe, expect, it } from "vitest";import { BACKEND_HEALTH_STORAGE_KEY, MAX_CONSECUTIVE_FAILURES,} from "#/api/backend-registry/health-storage";import { __resetHealthStoreForTests, getBackendHealthEntry, recordBackendFailure, recordBackendSuccess, resetBackendHealth, subscribeBackendHealth,} from "#/api/backend-registry/health-store";
const BACKEND_ID = "backend-under-test";
beforeEach(() => { window.localStorage.clear(); __resetHealthStoreForTests();});
afterEach(() => { window.localStorage.clear(); __resetHealthStoreForTests();});
describe("backend health store", () => { it("increments the failure count and persists to localStorage without disabling polling below the cap", () => { // Arrange / Act recordBackendFailure(BACKEND_ID, new Error("ECONNREFUSED")); recordBackendFailure(BACKEND_ID, new Error("ECONNREFUSED"));
// Assert const entry = getBackendHealthEntry(BACKEND_ID); expect(entry).toMatchObject({ consecutiveFailures: 2, disabled: false, lastError: "ECONNREFUSED", });
const persisted = JSON.parse( window.localStorage.getItem(BACKEND_HEALTH_STORAGE_KEY) ?? "{}", ); expect(persisted[BACKEND_ID]).toMatchObject({ consecutiveFailures: 2, disabled: false, }); });
it("flips disabled=true once consecutive failures hit the cap and persists that flag", () => { // Arrange / Act for (let i = 0; i < MAX_CONSECUTIVE_FAILURES; i += 1) { recordBackendFailure(BACKEND_ID, new Error("timeout")); }
// Assert — the cap is reached; polling-consumers will see disabled. const entry = getBackendHealthEntry(BACKEND_ID); expect(entry?.consecutiveFailures).toBe(MAX_CONSECUTIVE_FAILURES); expect(entry?.disabled).toBe(true);
const persisted = JSON.parse( window.localStorage.getItem(BACKEND_HEALTH_STORAGE_KEY) ?? "{}", ); expect(persisted[BACKEND_ID].disabled).toBe(true); });
it("caps the failure count at the max when a disabled backend fails another recheck", () => { for (let i = 0; i < MAX_CONSECUTIVE_FAILURES; i += 1) { recordBackendFailure(BACKEND_ID, new Error("timeout")); }
recordBackendFailure(BACKEND_ID, new Error("still down"));
const entry = getBackendHealthEntry(BACKEND_ID); expect(entry).toMatchObject({ consecutiveFailures: MAX_CONSECUTIVE_FAILURES, disabled: true, lastError: "still down", });
const persisted = JSON.parse( window.localStorage.getItem(BACKEND_HEALTH_STORAGE_KEY) ?? "{}", ); expect(persisted[BACKEND_ID].consecutiveFailures).toBe( MAX_CONSECUTIVE_FAILURES, ); });
it("clears the entry (and storage) and notifies subscribers when the backend recovers or the user edits its config", () => { // Arrange — record one failure so there is something to clear, and // subscribe so we can confirm listeners get notified. recordBackendFailure(BACKEND_ID, new Error("boom")); let notifications = 0; const unsubscribe = subscribeBackendHealth(() => { notifications += 1; });
// Act — `recordBackendSuccess` (probe recovers) and // `resetBackendHealth` (user edits host/apiKey) share the same // clear-entry semantics, so we cover both in one go. recordBackendSuccess(BACKEND_ID); recordBackendFailure(BACKEND_ID, new Error("again")); resetBackendHealth(BACKEND_ID); unsubscribe();
// Assert expect(getBackendHealthEntry(BACKEND_ID)).toBeNull(); expect(window.localStorage.getItem(BACKEND_HEALTH_STORAGE_KEY)).toBeNull(); expect(notifications).toBeGreaterThanOrEqual(3); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { afterEach, beforeEach, describe, expect, it } from "vitest";import { clearLastConversationId, getLastConversationId, LAST_CONVERSATION_STORAGE_KEY, setLastConversationId,} from "#/api/backend-registry/last-conversation-store";
beforeEach(() => { window.localStorage.clear();});
afterEach(() => { window.localStorage.clear();});
describe("last-conversation-store", () => { it("returns null when nothing has been remembered for a backend", () => { expect(getLastConversationId("backend-a", null)).toBeNull(); });
it("remembers and reads back the most recently selected conversation per backend", () => { setLastConversationId("backend-a", null, "convo-a-1"); setLastConversationId("backend-b", null, "convo-b-1");
expect(getLastConversationId("backend-a", null)).toBe("convo-a-1"); expect(getLastConversationId("backend-b", null)).toBe("convo-b-1");
// The most recent selection wins. setLastConversationId("backend-a", null, "convo-a-2"); expect(getLastConversationId("backend-a", null)).toBe("convo-a-2"); // …without affecting other backends. expect(getLastConversationId("backend-b", null)).toBe("convo-b-1"); });
it("keys cloud backends by (backendId, orgId) so each org gets its own slot", () => { setLastConversationId("cloud-x", "org-1", "convo-org-1"); setLastConversationId("cloud-x", "org-2", "convo-org-2");
expect(getLastConversationId("cloud-x", "org-1")).toBe("convo-org-1"); expect(getLastConversationId("cloud-x", "org-2")).toBe("convo-org-2"); expect(getLastConversationId("cloud-x", null)).toBeNull(); });
it("clears a backend's slot without touching others", () => { setLastConversationId("backend-a", null, "convo-a"); setLastConversationId("backend-b", null, "convo-b");
clearLastConversationId("backend-a", null);
expect(getLastConversationId("backend-a", null)).toBeNull(); expect(getLastConversationId("backend-b", null)).toBe("convo-b"); });
it("ignores empty conversation ids on write", () => { setLastConversationId("backend-a", null, ""); expect(getLastConversationId("backend-a", null)).toBeNull(); });
it("survives malformed JSON in storage", () => { window.localStorage.setItem(LAST_CONVERSATION_STORAGE_KEY, "not-json"); expect(getLastConversationId("backend-a", null)).toBeNull(); // A subsequent write recovers the storage shape. setLastConversationId("backend-a", null, "convo-a"); expect(getLastConversationId("backend-a", null)).toBe("convo-a"); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365import { afterEach, describe, expect, it, vi } from "vitest";import { ACTIVE_BACKEND_STORAGE_KEY, BACKENDS_STORAGE_KEY, readStoredActiveBackend, readStoredBackends, writeStoredActiveBackend, writeStoredBackends,} from "#/api/backend-registry/storage";import type { Backend } from "#/api/backend-registry/types";
const ORIGINAL_LOCATION = window.location;
function mockWindowLocation(url: string) { Object.defineProperty(window, "location", { configurable: true, value: new URL(url), });}
afterEach(() => { window.localStorage.clear(); window.sessionStorage.clear(); delete (window as unknown as Record<string, unknown>) .__AGENT_CANVAS_LOCK_TO_CLOUD__; Object.defineProperty(window, "location", { configurable: true, value: ORIGINAL_LOCATION, }); window.history.pushState({}, "", "/"); vi.unstubAllEnvs();});
describe("backend-registry storage", () => { it("round-trips a list of backends", () => { const backends: Backend[] = [ { id: "abc", name: "Local 1", host: "http://127.0.0.1:9000", apiKey: "key-1", kind: "local", }, { id: "xyz", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-2", kind: "cloud", }, ];
writeStoredBackends(backends);
expect(readStoredBackends()).toEqual(backends); });
it("returns empty list when storage is malformed", () => { window.localStorage.setItem(BACKENDS_STORAGE_KEY, "{not-json"); expect(readStoredBackends()).toEqual([]); });
it("does not seed the default Local backend when launcher details are missing", () => { vi.stubEnv("VITE_SESSION_API_KEY", ""); expect(window.localStorage.getItem(BACKENDS_STORAGE_KEY)).toBeNull();
expect(readStoredBackends()).toEqual([]); expect(window.localStorage.getItem(BACKENDS_STORAGE_KEY)).toBeNull(); });
it("seeds the default Local backend when host and API key are available", () => { vi.stubEnv("VITE_BACKEND_BASE_URL", "http://localhost:9000"); vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key");
const result = readStoredBackends();
expect(result).toHaveLength(1); expect(result[0]).toMatchObject({ id: "default-local", host: "http://localhost:9000", apiKey: "fresh-session-key", kind: "local", }); expect(window.localStorage.getItem(BACKENDS_STORAGE_KEY)).not.toBeNull(); expect(readStoredBackends()).toEqual(result); });
it("seeds a cookie-auth Cloud backend when locked to the current origin", () => { ( window as unknown as Record<string, unknown> ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = window.location.origin; window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([ { id: "stale-local", name: "Stale Local", host: "http://localhost:18000", apiKey: "stale-session", kind: "local", }, ]), );
const result = readStoredBackends();
expect(result).toEqual([ { id: "locked-cloud", name: "OpenHands Cloud", host: window.location.origin, apiKey: "", kind: "cloud", authMode: "cookie", }, ]); expect(readStoredActiveBackend()).toEqual({ backendId: "locked-cloud", orgId: null, }); });
it("seeds the cookie-auth Cloud backend on the current origin when the locked host is an equivalent transition domain", () => { mockWindowLocation("https://pr-254.staging.openhands.dev/canvas"); ( window as unknown as Record<string, unknown> ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = "https://pr-254.staging.all-hands.dev";
expect(readStoredBackends()).toEqual([ { id: "locked-cloud", name: "OpenHands Cloud", host: "https://pr-254.staging.openhands.dev", apiKey: "", kind: "cloud", authMode: "cookie", }, ]); });
it("preserves an existing locked Cloud org selection while reseeding", () => { ( window as unknown as Record<string, unknown> ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = window.location.origin; writeStoredActiveBackend({ backendId: "locked-cloud", orgId: "org-1" });
expect(readStoredBackends()[0]).toMatchObject({ id: "locked-cloud" }); expect(readStoredActiveBackend()).toEqual({ backendId: "locked-cloud", orgId: "org-1", }); });
it("does not seed a cookie-auth Cloud backend when locked cross-origin", () => { ( window as unknown as Record<string, unknown> ).__AGENT_CANVAS_LOCK_TO_CLOUD__ = "https://app.all-hands.dev"; vi.stubEnv("VITE_SESSION_API_KEY", "");
expect(readStoredBackends()).toEqual([]); });
it("re-seeds the default Local backend when storage holds an empty array and launcher details are available", () => { vi.stubEnv("VITE_BACKEND_BASE_URL", "http://localhost:9000"); vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key"); window.localStorage.setItem(BACKENDS_STORAGE_KEY, JSON.stringify([]));
const result = readStoredBackends();
expect(result).toHaveLength(1); expect(result[0]).toMatchObject({ id: "default-local", kind: "local" }); });
it("re-seeds the default Local backend when every stored entry is invalid and launcher details are available", () => { vi.stubEnv("VITE_BACKEND_BASE_URL", "http://localhost:9000"); vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key"); window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([{ kind: "cloud" }, "not-an-object"]), );
const result = readStoredBackends();
expect(result).toHaveLength(1); expect(result[0]).toMatchObject({ id: "default-local", kind: "local" }); });
it("filters out backends with invalid shape", () => { window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([ { id: "ok", name: "x", host: "y", apiKey: "z", kind: "local" }, { id: "missing-kind", name: "x", host: "y", apiKey: "z" }, { kind: "cloud" }, "not-an-object", ]), );
expect(readStoredBackends()).toEqual([ { id: "ok", name: "x", host: "y", apiKey: "z", kind: "local" }, ]); });
it("preserves stored backends without API keys", () => { vi.stubEnv("VITE_SESSION_API_KEY", ""); const storedBackend: Backend = { id: "default-local", name: "Local", host: window.location.origin, apiKey: "", kind: "local", }; window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([storedBackend]), );
expect(readStoredBackends()).toEqual([storedBackend]); });
it("syncs a stale default Local API key from env defaults", () => { vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key"); window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([ { id: "default-local", name: "Local", host: window.location.origin, apiKey: "stored-session-key", kind: "local", }, ]), );
expect(readStoredBackends()[0]).toMatchObject({ id: "default-local", apiKey: "fresh-session-key", }); });
it("syncs a stale default Local API key across localhost and 127.0.0.1", () => { vi.stubEnv("VITE_BACKEND_BASE_URL", "http://127.0.0.1:8000"); vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key"); window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([ { id: "default-local", name: "Local", host: "http://localhost:8000", apiKey: "stored-session-key", kind: "local", }, ]), );
expect(readStoredBackends()[0]).toMatchObject({ id: "default-local", host: "http://localhost:8000", apiKey: "fresh-session-key", }); });
it("preserves a custom backend API key instead of syncing from env defaults", () => { vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key"); const storedBackend: Backend = { id: "custom-local", name: "Custom Local", host: window.location.origin, apiKey: "stored-session-key", kind: "local", }; window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([storedBackend]), );
expect(readStoredBackends()[0]).toMatchObject({ id: "custom-local", apiKey: "stored-session-key", }); });
it("preserves a user-edited non-loopback default Local backend API key", () => { vi.stubEnv("VITE_SESSION_API_KEY", "fresh-session-key"); const storedBackend: Backend = { id: "default-local", name: "Edited Local", host: "https://example.com", apiKey: "stored-session-key", kind: "local", }; window.localStorage.setItem( BACKENDS_STORAGE_KEY, JSON.stringify([storedBackend]), );
expect(readStoredBackends()[0]).toMatchObject({ id: "default-local", host: "https://example.com", apiKey: "stored-session-key", }); });
it("round-trips active selection with orgId", () => { writeStoredActiveBackend({ backendId: "xyz", orgId: "org-1" }); expect(readStoredActiveBackend()).toEqual({ backendId: "xyz", orgId: "org-1", }); });
it("normalizes missing orgId to null", () => { writeStoredActiveBackend({ backendId: "xyz" }); expect(readStoredActiveBackend()).toEqual({ backendId: "xyz", orgId: null, }); });
it("prefers the tab-scoped active selection over the global fallback", () => { window.localStorage.setItem( ACTIVE_BACKEND_STORAGE_KEY, JSON.stringify({ backendId: "global-backend", orgId: null }), ); window.sessionStorage.setItem( ACTIVE_BACKEND_STORAGE_KEY, JSON.stringify({ backendId: "tab-backend", orgId: "org-1" }), );
expect(readStoredActiveBackend()).toEqual({ backendId: "tab-backend", orgId: "org-1", }); });
it("falls back to the global active selection for new tabs", () => { window.localStorage.setItem( ACTIVE_BACKEND_STORAGE_KEY, JSON.stringify({ backendId: "global-backend", orgId: null }), );
expect(readStoredActiveBackend()).toEqual({ backendId: "global-backend", orgId: null, }); });
it("clears storage when active selection is set to null", () => { writeStoredActiveBackend({ backendId: "xyz", orgId: "o" }); writeStoredActiveBackend(null);
expect( window.sessionStorage.getItem(ACTIVE_BACKEND_STORAGE_KEY), ).toBeNull(); expect(window.localStorage.getItem(ACTIVE_BACKEND_STORAGE_KEY)).toBeNull(); expect(readStoredActiveBackend()).toBeNull(); });
it("returns null active selection when storage is malformed", () => { window.localStorage.setItem(ACTIVE_BACKEND_STORAGE_KEY, "{broken"); expect(readStoredActiveBackend()).toBeNull(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import { describe, expect, it } from "vitest";import { BACKEND_QUERY_PARAM, ORG_QUERY_PARAM, readBackendSelectionFromUrl, withBackendSelectionParams,} from "#/api/backend-registry/url-selection";import type { Backend } from "#/api/backend-registry/types";
const localBackend: Backend = { id: "local-1", name: "Local 1", host: "http://localhost:9000", apiKey: "k", kind: "local",};
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-key", kind: "cloud",};
const backends = [localBackend, cloudBackend];
describe("withBackendSelectionParams", () => { it("pins the active backend id onto the path", () => { const path = withBackendSelectionParams("/conversations/abc", { backend: localBackend, orgId: null, });
expect(path).toBe(`/conversations/abc?${BACKEND_QUERY_PARAM}=local-1`); });
it("includes the org id for a cloud backend", () => { const path = withBackendSelectionParams("/conversations/abc", { backend: cloudBackend, orgId: "org-7", });
expect(path).toBe( `/conversations/abc?${BACKEND_QUERY_PARAM}=prod&${ORG_QUERY_PARAM}=org-7`, ); });
it("omits the org id when there is none", () => { const path = withBackendSelectionParams("/conversations/abc", { backend: cloudBackend, orgId: null, });
expect(path).not.toContain(ORG_QUERY_PARAM); });
it("preserves query parameters already on the path", () => { const path = withBackendSelectionParams("/conversations/abc?tab=files", { backend: localBackend, orgId: null, });
expect(path).toBe( `/conversations/abc?tab=files&${BACKEND_QUERY_PARAM}=local-1`, ); });
it("keeps a fragment after existing query parameters intact and after the query", () => { const path = withBackendSelectionParams( "/conversations/abc?tab=files#detail", { backend: localBackend, orgId: null, }, );
expect(path).toBe( `/conversations/abc?tab=files&${BACKEND_QUERY_PARAM}=local-1#detail`, ); });
it("keeps a fragment on a path without query parameters after the query", () => { const path = withBackendSelectionParams("/conversations/abc#detail", { backend: localBackend, orgId: null, });
expect(path).toBe( `/conversations/abc?${BACKEND_QUERY_PARAM}=local-1#detail`, ); });
it("does not treat a ? inside the fragment as a query separator", () => { const path = withBackendSelectionParams("/conversations/abc#detail?x=1", { backend: localBackend, orgId: null, });
expect(path).toBe( `/conversations/abc?${BACKEND_QUERY_PARAM}=local-1#detail?x=1`, ); });
it("round-trips an empty fragment verbatim", () => { const path = withBackendSelectionParams("/conversations/abc#", { backend: localBackend, orgId: null, });
expect(path).toBe(`/conversations/abc?${BACKEND_QUERY_PARAM}=local-1#`); });
it("keeps the org id and the fragment together", () => { const path = withBackendSelectionParams("/conversations/abc#detail", { backend: cloudBackend, orgId: "org-7", });
expect(path).toBe( `/conversations/abc?${BACKEND_QUERY_PARAM}=prod&${ORG_QUERY_PARAM}=org-7#detail`, ); });
it("keeps query data that itself contains a ?", () => { const path = withBackendSelectionParams("/conversations/abc?next=/a?b=1", { backend: localBackend, orgId: null, });
expect(path).toBe( `/conversations/abc?next=%2Fa%3Fb%3D1&${BACKEND_QUERY_PARAM}=local-1`, ); });});
describe("readBackendSelectionFromUrl", () => { it("reads a registered backend id", () => { expect( readBackendSelectionFromUrl(backends, `?${BACKEND_QUERY_PARAM}=local-1`), ).toEqual({ backendId: "local-1", orgId: null }); });
it("reads the org id alongside the backend id", () => { expect( readBackendSelectionFromUrl( backends, `?${BACKEND_QUERY_PARAM}=prod&${ORG_QUERY_PARAM}=org-7`, ), ).toEqual({ backendId: "prod", orgId: "org-7" }); });
it("ignores a backend id that is not registered", () => { expect( readBackendSelectionFromUrl(backends, `?${BACKEND_QUERY_PARAM}=gone`), ).toBeNull(); });
it("ignores an empty or absent parameter", () => { expect(readBackendSelectionFromUrl(backends, "")).toBeNull(); expect(readBackendSelectionFromUrl(backends, "?tab=files")).toBeNull(); expect( readBackendSelectionFromUrl(backends, `?${BACKEND_QUERY_PARAM}=`), ).toBeNull(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("AgentServerConversationService cloud branch", () => { it("createConversation POSTs the cloud payload directly and returns a WORKING task", async () => { fetchMock.mockResolvedValue( mockJsonResponse({ id: "task-123", created_by_user_id: null, status: "WORKING", detail: null, app_conversation_id: null, agent_server_url: null, request: {}, created_at: "2026-05-06T00:00:00Z", updated_at: "2026-05-06T00:00:00Z", }), );
const result = await AgentServerConversationService.createConversation({ initialUserMsg: "fix the bug", conversationInstructions: "Optional title", metadata: { selected_repository: "user/repo", selected_branch: "main", // eslint-disable-next-line @typescript-eslint/no-explicit-any git_provider: "github" as any, }, });
expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/app-conversations`); expect(init).toMatchObject({ method: "POST", headers: { Authorization: "Bearer bearer-token" }, }); const requestBody = getJsonBody(init);
// cloud payload shape — flat fields, NO encrypted-settings round-trip. expect(requestBody.selected_repository).toBe("user/repo"); expect(requestBody.selected_branch).toBe("main"); expect(requestBody.git_provider).toBe("github"); expect(requestBody.title).toBe("Optional title"); expect(requestBody.initial_message).toEqual({ role: "user", content: [{ type: "text", text: "fix the bug" }], }); // The local-only encrypted-settings keys must NOT be present. expect(requestBody).not.toHaveProperty("agent_settings_encrypted"); expect(requestBody).not.toHaveProperty("conversation_settings_encrypted");
// The returned task is the upstream task — WORKING, no app_conversation_id yet. expect(result.id).toBe("task-123"); expect(result.status).toBe("WORKING"); expect(result.app_conversation_id).toBeNull(); });
it("getStartTask polls /api/v1/app-conversations/start-tasks?ids= directly", async () => { fetchMock.mockResolvedValue( mockJsonResponse([ { id: "task-123", created_by_user_id: null, status: "READY", detail: null, app_conversation_id: "conv-456", agent_server_url: "https://runtime-456.app.all-hands.dev", request: {}, created_at: "2026-05-06T00:00:00Z", updated_at: "2026-05-06T00:00:00Z", }, ]), );
const result = await AgentServerConversationService.getStartTask("task-123");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe( `${cloudBackend.host}/api/v1/app-conversations/start-tasks?ids=task-123`, ); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(result?.status).toBe("READY"); expect(result?.app_conversation_id).toBe("conv-456"); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { getFetchCall, mockJsonResponse } from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({ success: true })); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("AgentServerConversationService.deleteConversation cloud branch", () => { it("calls the cloud DELETE app-conversations endpoint directly", async () => { await AgentServerConversationService.deleteConversation("conv-abc");
expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/app-conversations/conv-abc`); expect(init).toMatchObject({ method: "DELETE", headers: { Authorization: "Bearer bearer-token" }, }); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { getFetchCall, mockBlobResponse, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({})); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("AgentServerConversationService.downloadConversation cloud branch", () => { it("calls the cloud download endpoint directly with responseType blob and returns the Blob", async () => { fetchMock.mockResolvedValueOnce( mockBlobResponse("zip-bytes", "application/zip"), );
const result = await AgentServerConversationService.downloadConversation("conv-abc");
expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toBe( `${cloudBackend.host}/api/v1/app-conversations/conv-abc/download`, ); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); await expect(result.text()).resolves.toBe("zip-bytes"); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";import { pauseConversation } from "#/hooks/mutation/conversation-mutation-utils";import { ExecutionStatus } from "#/types/agent-server/core/base/common";import { getFetchCall, mockJsonResponse } from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const buildConversation = ( overrides: Partial<AppConversation> = {},): AppConversation => ({ id: "conv-abc", created_by_user_id: null, selected_repository: null, selected_branch: null, git_provider: null, title: "Test", trigger: null, pr_number: [], llm_model: null, metrics: null, created_at: "2026-04-16T00:00:00Z", updated_at: "2026-04-16T00:00:00Z", execution_status: ExecutionStatus.RUNNING, conversation_url: null, session_api_key: null, sandbox_id: "sandbox-xyz", sub_conversation_ids: [], ...overrides,});
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({ success: true })); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch; vi.restoreAllMocks();});
describe("pauseConversation cloud branch", () => { it("POSTs directly to the cloud sandbox pause endpoint", async () => { vi.spyOn( AgentServerConversationService, "batchGetAppConversations", ).mockResolvedValue([buildConversation({ sandbox_id: "sandbox-xyz" })]);
await pauseConversation("conv-abc");
expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/sandboxes/sandbox-xyz/pause`); expect(init).toMatchObject({ method: "POST", headers: { Authorization: "Bearer bearer-token" }, }); });
it("throws and does not call the cloud API when the cloud conversation has no sandbox_id", async () => { vi.spyOn( AgentServerConversationService, "batchGetAppConversations", ).mockResolvedValue([buildConversation({ sandbox_id: null })]);
await expect(pauseConversation("conv-abc")).rejects.toThrow(/sandbox_id/); expect(fetchMock).not.toHaveBeenCalled(); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); fetchMock.mockResolvedValue( mockJsonResponse({ id: "conv-abc", public: true }), ); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("AgentServerConversationService.updateConversationPublicFlag", () => { it("PATCHes /api/v1/app-conversations/{id} directly on a cloud backend", async () => { setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id });
await AgentServerConversationService.updateConversationPublicFlag( "conv-abc", true, );
expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/app-conversations/conv-abc`); expect(init).toMatchObject({ method: "PATCH", headers: { Authorization: "Bearer bearer-token" }, }); expect(getJsonBody(init)).toEqual({ public: true }); });
it("rejects without calling the cloud API when the active backend is local", async () => { // Default state after reset is the bundled local backend. await expect( AgentServerConversationService.updateConversationPublicFlag( "conv-abc", true, ), ).rejects.toThrow(/cloud backend/); expect(fetchMock).not.toHaveBeenCalled(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const localBackend: Backend = { id: "self-hosted", name: "Self-hosted", host: "http://192.168.1.99:9999", apiKey: "local-key", kind: "local",};
const runtimeResponse = { id: "conv-abc", title: "Test conversation", created_at: "2026-04-16T00:00:00Z", updated_at: "2026-04-16T00:00:00Z", execution_status: "idle", metrics: null, stats: { usage_to_metrics: { agent: { model_name: "test-model", accumulated_cost: 1.23, max_budget_per_task: null, accumulated_token_usage: null, costs: [], response_latencies: [], token_usages: [], }, }, },};
const fetchMock = vi.fn();
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); vi.unstubAllGlobals(); vi.restoreAllMocks();});
describe("AgentServerConversationService.getRuntimeConversation", () => { describe("cloud mode", () => { beforeEach(() => { __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); vi.stubGlobal("fetch", fetchMock); });
it("targets the conversation runtime host directly and forwards X-Session-API-Key", async () => { // Arrange fetchMock.mockResolvedValue(mockJsonResponse(runtimeResponse)); const conversationUrl = "http://abc123.runtime.all-hands.dev/api/conversations/conv-abc";
// Act const result = await AgentServerConversationService.getRuntimeConversation( "conv-abc", conversationUrl, "session-xyz", );
// Assert — fetch goes directly to the runtime host, not through // /api/cloud-proxy (which was removed from the agent-server). expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toContain("abc123.runtime.all-hands.dev"); expect(url).toContain("/api/conversations/conv-abc"); expect(url).not.toMatch(/\/api\/cloud-proxy$/); expect(init.headers).toMatchObject({ "X-Session-API-Key": "session-xyz", }); expect(result.stats.usage_to_metrics.agent?.accumulated_cost).toBe(1.23); }); });
describe("local mode", () => { beforeEach(() => { __resetActiveStoreForTests(); setRegisteredBackends([localBackend]); setActiveSelection({ backendId: localBackend.id }); fetchMock.mockReset(); vi.stubGlobal("fetch", fetchMock); });
it("targets the conversation_url host (not the active backend host) and forwards X-Session-API-Key", async () => { // Arrange fetchMock.mockResolvedValue(mockJsonResponse(runtimeResponse)); const conversationUrl = "http://192.168.1.42:8888/api/conversations/conv-abc";
// Act const result = await AgentServerConversationService.getRuntimeConversation( "conv-abc", conversationUrl, "session-xyz", );
// Assert expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toContain("192.168.1.42:8888"); expect(url).not.toContain(localBackend.host); expect(init.headers).toMatchObject({ "X-Session-API-Key": "session-xyz", }); expect(result.id).toBe("conv-abc"); }); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
vi.mock("@openhands/typescript-client/clients", async (importOriginal) => { const actual = await importOriginal< typeof import("@openhands/typescript-client/clients") >();
return { ...actual, ConversationClient: vi.fn().mockImplementation(() => ({ updateConversation: vi .fn() .mockRejectedValue( new Error("Cloud title updates must not use ConversationClient"), ), })), };});
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); fetchMock.mockResolvedValue( mockJsonResponse({ id: "conv-abc", title: "Renamed conversation" }), ); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("AgentServerConversationService.updateConversationTitle", () => { it("PATCHes the app-conversation directly on a cloud backend", async () => { setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id });
const result = await AgentServerConversationService.updateConversationTitle( "conv-abc", "Renamed conversation", );
expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/app-conversations/conv-abc`); expect(init).toMatchObject({ method: "PATCH", headers: { Authorization: "Bearer bearer-token" }, }); expect(getJsonBody(init)).toEqual({ title: "Renamed conversation" }); expect(result).toMatchObject({ id: "conv-abc", title: "Renamed conversation", }); });});123456789101112131415161718192021222324252627282930313233import { vi } from "vitest";
type FetchMock = ReturnType<typeof vi.fn>;
export function mockJsonResponse(data: unknown, status = 200): Response { return new Response(JSON.stringify(data), { status, statusText: status === 200 ? "OK" : "Error", headers: { "content-type": "application/json" }, });}
export function mockBlobResponse( body: BodyInit, contentType: string,): Response { return new Response(body, { status: 200, headers: { "content-type": contentType }, });}
export function getFetchCall( fetchMock: FetchMock, index = 0,): [string, RequestInit] { const [url, init] = fetchMock.mock.calls[index] as [string, RequestInit]; return [url, init ?? {}];}
export function getJsonBody(init: RequestInit): Record<string, unknown> { return JSON.parse(String(init.body ?? "{}")) as Record<string, unknown>;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import { getCloudRepositoryBranches } from "#/api/cloud/git-service.api";import { getFetchCall, mockJsonResponse } from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const emptyBranchPage = { items: [], next_page_id: null };const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse(emptyBranchPage)); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("getCloudRepositoryBranches", () => { it("includes an empty query parameter when listing all branches so the upstream schema is satisfied", async () => { // Act await getCloudRepositoryBranches({ provider: "github", repository: "hieptl/hieptl", });
// Assert const [url, init] = getFetchCall(fetchMock); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(url).toMatch(/[?&]query=(&|$)/); });
it("forwards a non-empty query parameter when searching branches", async () => { // Act await getCloudRepositoryBranches({ provider: "github", repository: "hieptl/hieptl", query: "feature/login", });
// Assert const [url] = getFetchCall(fetchMock); expect(url).toContain("query=feature%2Flogin"); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import { getCloudOrganizationMe } from "#/api/cloud/organization-service.api";import { getFetchCall, mockJsonResponse } from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("cloud organization /me", () => { it("calls /api/organizations/{orgId}/me directly and returns user_id", async () => { const orgId = "0b93b5f2-5396-49f2-8d98-61f906184270"; fetchMock.mockResolvedValue( mockJsonResponse({ org_id: orgId, user_id: orgId, email: "hieptl.developer@gmail.com", role: "owner", permissions: ["view_org_settings", "edit_org_settings"], }), );
const result = await getCloudOrganizationMe(orgId);
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/organizations/${orgId}/me`); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(result).toEqual({ orgId, userId: orgId, role: "owner", permissions: ["view_org_settings", "edit_org_settings"], }); });
it("returns null permissions when the app-server omits them (older version)", async () => { const orgId = "0b93b5f2-5396-49f2-8d98-61f906184270"; fetchMock.mockResolvedValue( mockJsonResponse({ org_id: orgId, user_id: orgId, email: "x@example.com", role: "member", }), );
const result = await getCloudOrganizationMe(orgId);
// Absent `permissions` → null, so callers fall back to the role check. expect(result).toEqual({ orgId, userId: orgId, role: "member", permissions: null, }); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { HttpError } from "@openhands/typescript-client";import { __resetActiveStoreForTests, setRegisteredBackends,} from "#/api/backend-registry/active-store";import { getCloudOrganizationMember, getCloudOrganizations, getCurrentCloudApiKey,} from "#/api/cloud/organization-service.api";import type { Backend } from "#/api/backend-registry/types";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
function mockJsonResponse(data: unknown, status = 200): Response { return new Response(JSON.stringify(data), { status, statusText: status === 200 ? "OK" : "Error", headers: { "content-type": "application/json" }, });}
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([]); fetchMock.mockReset(); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("cloud organization-service", () => { it("getCloudOrganizations calls the cloud API directly and returns normalized data", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ items: [{ id: "org-1", name: "Personal" }], current_org_id: "org-1", }), );
const result = await getCloudOrganizations(cloudBackend);
expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = fetchMock.mock.calls[0]!;
expect(url).toBe(`${cloudBackend.host}/api/organizations`); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, });
expect(result).toEqual({ items: [{ id: "org-1", name: "Personal" }], currentOrgId: "org-1", }); });
it("getCurrentCloudApiKey hits /api/keys/current and returns the bound orgId", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ id: "key-1", name: "k", org_id: "org-bound", user_id: "user-1", auth_type: "bearer", }), );
const result = await getCurrentCloudApiKey(cloudBackend);
const [url, init] = fetchMock.mock.calls[0]!; expect(url).toBe(`${cloudBackend.host}/api/keys/current`); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(result).toEqual({ orgId: "org-bound", isLegacyKey: false }); });
it("getCurrentCloudApiKey treats an upstream 400 as a legacy key (no binding)", async () => { fetchMock.mockResolvedValueOnce(mockJsonResponse({ detail: "bad" }, 400));
const result = await getCurrentCloudApiKey(cloudBackend);
expect(result).toEqual({ orgId: null, isLegacyKey: true }); });
it("getCurrentCloudApiKey rethrows non-400 upstream errors (e.g. revoked key)", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ detail: "unauthorized" }, 401), );
await expect(getCurrentCloudApiKey(cloudBackend)).rejects.toBeInstanceOf( HttpError, ); });
it("getCloudOrganizationMember hits /api/organizations/{orgId}/members/{userId} and returns the member", async () => { // Arrange const member = { org_id: "org-1", user_id: "user-1", email: "jdoe@acme.com", role: "member", status: "active", }; fetchMock.mockResolvedValueOnce(mockJsonResponse(member));
// Act const result = await getCloudOrganizationMember( "org-1", "user-1", cloudBackend, );
// Assert expect(fetchMock).toHaveBeenCalledOnce(); const [url, init] = fetchMock.mock.calls[0]!; expect(url).toBe( `${cloudBackend.host}/api/organizations/org-1/members/user-1`, ); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(result).toEqual(member); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import ProfilesService, { type SaveProfileRequest,} from "#/api/profiles-service/profiles-service.api";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const ORG_ID = "org-1";const ORG_BASE = `https://app.all-hands.dev/api/organizations/${ORG_ID}/profiles`;const SETTINGS_BASE = "https://app.all-hands.dev/api/v1/settings/profiles";const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({})); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
// With an org bound, profile CRUD goes through the org-gated routes so the// server enforces EDIT_ORG_SETTINGS (a member's mutation 403s, not just hidden).describe("ProfilesService against a cloud org (gated org routes)", () => { beforeEach(() => { setActiveSelection({ backendId: cloudBackend.id, orgId: ORG_ID }); });
it("lists profiles via GET /api/organizations/{orgId}/profiles", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ profiles: [ { name: "gpt", model: "gpt-4o", base_url: null, api_key_set: true }, ], active_profile: "gpt", }), );
const res = await ProfilesService.listProfiles();
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(ORG_BASE); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(res.active_profile).toBe("gpt"); });
it("fetches a profile and maps the org `llm` onto `config`", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ name: "my profile", llm: { model: "gpt-4o", api_key: null }, }), );
const res = await ProfilesService.getProfile("my profile");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${ORG_BASE}/my%20profile`); expect(init).toMatchObject({ method: "GET", }); expect(res).toEqual({ name: "my profile", config: { model: "gpt-4o", api_key: null }, api_key_set: false, }); });
it("saves a profile via POST .../{name} forwarding the request body", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ name: "gpt", message: "Profile 'gpt' saved" }), );
await ProfilesService.saveProfile("gpt", { llm: { model: "gpt-4o" } as SaveProfileRequest["llm"], include_secrets: true, });
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${ORG_BASE}/gpt`); expect(init).toMatchObject({ method: "POST", }); expect(getJsonBody(init)).toEqual({ llm: { model: "gpt-4o" }, include_secrets: true, }); });
it("deletes a profile via DELETE .../{name}", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ name: "gpt", message: "Profile 'gpt' deleted" }), );
await ProfilesService.deleteProfile("gpt");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${ORG_BASE}/gpt`); expect(init).toMatchObject({ method: "DELETE" }); });
it("renames a profile via POST .../{name}/rename with new_name", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ name: "new", message: "renamed" }), );
await ProfilesService.renameProfile("old", "new");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${ORG_BASE}/old/rename`); expect(init).toMatchObject({ method: "POST", }); expect(getJsonBody(init)).toEqual({ new_name: "new" }); });
it("activates a profile and maps the org `llm` onto `llm_applied`", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ name: "gpt", message: "Switched to profile 'gpt'", llm: { model: "gpt-4o" }, }), );
const res = await ProfilesService.activateProfile("gpt");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${ORG_BASE}/gpt/activate`); expect(init).toMatchObject({ method: "POST", }); expect(res).toEqual({ name: "gpt", message: "Switched to profile 'gpt'", llm_applied: true, }); });});
// Legacy API keys have no org bound; CRUD falls back to the per-user settings// route (ungated — there is no org role to enforce against).describe("ProfilesService on a cloud backend with no org (fallback)", () => { beforeEach(() => { setActiveSelection({ backendId: cloudBackend.id }); });
it("lists via the per-user settings route", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ profiles: [], active_profile: null }), );
await ProfilesService.listProfiles();
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(SETTINGS_BASE); expect(init).toMatchObject({ method: "GET" }); });
it("saves via the per-user settings route", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ name: "gpt", message: "saved" }), );
await ProfilesService.saveProfile("gpt", { llm: { model: "gpt-4o" } as SaveProfileRequest["llm"], include_secrets: true, });
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${SETTINGS_BASE}/gpt`); expect(init).toMatchObject({ method: "POST" }); });
it("activates via the per-user settings route and maps `model`", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ name: "gpt", message: "ok", model: "gpt-4o" }), );
const res = await ProfilesService.activateProfile("gpt");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${SETTINGS_BASE}/gpt/activate`); expect(init).toMatchObject({ method: "POST", }); expect(res.llm_applied).toBe(true); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import ProviderConnectionsService from "#/api/provider-connections-service/provider-connections-service.api";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const ORG_ID = "org-1";const BASE = `https://app.all-hands.dev/api/organizations/${ORG_ID}/provider-connections`;const originalFetch = global.fetch;const fetchMock = vi.fn();
const connection = { id: "conn-1", display_name: "My OpenAI", provider: "openai", base_url: null, created_at: 1, updated_at: 2, api_key_set: true,};
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({})); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
// With an org bound, provider-connection CRUD goes through the org-gated routes// so the server enforces EDIT_ORG_SETTINGS / VIEW_ORG_SETTINGS.describe("ProviderConnectionsService against a cloud org", () => { beforeEach(() => { setActiveSelection({ backendId: cloudBackend.id, orgId: ORG_ID }); });
it("lists connections and unwraps the { connections } envelope", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ connections: [connection] }), );
const res = await ProviderConnectionsService.list();
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(BASE); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(res).toEqual([connection]); });
it("returns [] when the org has no connections", async () => { fetchMock.mockResolvedValueOnce(mockJsonResponse({ connections: [] }));
const res = await ProviderConnectionsService.list();
expect(res).toEqual([]); });
it("creates a connection via POST with the request body", async () => { fetchMock.mockResolvedValueOnce(mockJsonResponse(connection));
const request = { display_name: "My OpenAI", provider: "openai", api_key: "sk-123", base_url: null, }; const res = await ProviderConnectionsService.create(request);
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(BASE); expect(init).toMatchObject({ method: "POST" }); expect(getJsonBody(init)).toEqual(request); expect(res).toEqual(connection); });
it("updates a connection via PATCH at the id-scoped path", async () => { fetchMock.mockResolvedValueOnce(mockJsonResponse(connection));
const res = await ProviderConnectionsService.update("conn-1", { display_name: "Renamed", });
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${BASE}/conn-1`); expect(init).toMatchObject({ method: "PATCH" }); expect(getJsonBody(init)).toEqual({ display_name: "Renamed" }); expect(res).toEqual(connection); });
it("url-encodes the id when deleting", async () => { fetchMock.mockResolvedValueOnce(mockJsonResponse(connection));
await ProviderConnectionsService.delete("a b/c");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${BASE}/a%20b%2Fc`); expect(init).toMatchObject({ method: "DELETE" }); });});
// Without an org bound (legacy API keys), the org-scoped route is unaddressable.describe("ProviderConnectionsService on a cloud backend with no org", () => { beforeEach(() => { setActiveSelection({ backendId: cloudBackend.id }); });
it("throws rather than firing an unaddressable request", async () => { await expect(ProviderConnectionsService.list()).rejects.toThrow( /organization-bound/i, ); expect(fetchMock).not.toHaveBeenCalled(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import { callCloudProxy } from "#/api/cloud/proxy";import type { Backend } from "#/api/backend-registry/types";
const cloudPersonal: Backend = { id: "cloud-personal", name: "Production - Personal", host: "https://app.all-hands.dev", apiKey: "personal-key", kind: "cloud",};
const cloudAcme: Backend = { id: "cloud-acme", name: "Production - Acme", host: "https://app.all-hands.dev", apiKey: "acme-key", kind: "cloud",};
const cookieCloud: Backend = { id: "cloud-cookie", name: "Production - Cookie", host: "https://app.all-hands.dev", apiKey: "", kind: "cloud", authMode: "cookie",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
function mockJsonResponse(data: unknown, status = 200): Response { return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" }, });}
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({})); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("callCloudProxy X-Org-Id injection", () => { it("sends X-Org-Id when targeting the active cloud backend with a selected orgId", async () => { // Arrange — active selection points at the cloud backend with a // resolved orgId. This is the steady-state case after the user picks // an org row in the BackendSelector. setRegisteredBackends([cloudPersonal]); setActiveSelection({ backendId: cloudPersonal.id, orgId: "org-personal-uuid", });
// Act await callCloudProxy({ backend: cloudPersonal, method: "GET", path: "/api/v1/app-conversations/search", });
// Assert — the request carries the X-Org-Id of the active selection so the // cloud backend can scope this request to the user's locally-chosen org // without depending on user.current_org_id. const [url, init] = fetchMock.mock.calls[0]!; expect(url).toBe(`${cloudPersonal.host}/api/v1/app-conversations/search`); expect(init).toMatchObject({ method: "GET", }); expect( (init as { headers: Record<string, string> }).headers["X-Org-Id"], ).toBe("org-personal-uuid"); });
it("omits X-Org-Id when targeting a different cloud backend than the active one", async () => { // Arrange — the BackendSelector fan-out (e.g. useAllCloudOrganizations) // calls callCloudProxy(b) for every registered cloud backend. Sending // the active backend's orgId across an unrelated API key would cause // the cloud backend to 403 on api_key_org_id / X-Org-Id mismatch. setRegisteredBackends([cloudPersonal, cloudAcme]); setActiveSelection({ backendId: cloudPersonal.id, orgId: "org-personal-uuid", });
// Act — request targets the non-active backend. await callCloudProxy({ backend: cloudAcme, method: "GET", path: "/api/keys/current", });
// Assert const [, init] = fetchMock.mock.calls[0]!; expect( (init as { headers: Record<string, string> }).headers, ).not.toHaveProperty("X-Org-Id"); });});
describe("callCloudProxy cookie auth", () => { it("omits bearer auth for same-origin cookie-backed Cloud requests", async () => { setRegisteredBackends([cookieCloud]); setActiveSelection({ backendId: cookieCloud.id, orgId: null });
await callCloudProxy({ backend: cookieCloud, method: "GET", path: "/api/v1/users/me", });
const [url, init] = fetchMock.mock.calls[0]!; expect(url).toBe(`${cookieCloud.host}/api/v1/users/me`); expect(init).toMatchObject({ method: "GET" }); expect( (init as { headers: Record<string, string> }).headers, ).not.toHaveProperty("Authorization"); });
it("omits bearer auth in runtime proxy envelope requests", async () => { setRegisteredBackends([cookieCloud]); setActiveSelection({ backendId: cookieCloud.id, orgId: null });
await callCloudProxy({ backend: cookieCloud, method: "GET", path: "/api/bash/bash_events/search", hostOverride: "https://abc123.prod-runtime.all-hands.dev", });
const [, init] = fetchMock.mock.calls[0]!; const envelope = JSON.parse((init as { body: string }).body); expect( (envelope as { headers: Record<string, string> }).headers, ).not.toHaveProperty("Authorization"); });});
describe("callCloudProxy automation direct routing", () => { it("sends automation requests straight to the cloud host with the API key instead of the /api/cloud-proxy envelope", async () => { // Arrange — the automation service grants permissive CORS to API-key // requests (automation#185), so app-host automation calls no longer // need the same-origin proxy hop through the bundled agent-server. setRegisteredBackends([cloudPersonal]); setActiveSelection({ backendId: cloudPersonal.id, orgId: null }); const page = { automations: [], total: 0 }; fetchMock.mockResolvedValueOnce(mockJsonResponse(page));
// Act const result = await callCloudProxy({ backend: cloudPersonal, method: "GET", path: "/api/automation/v1?limit=50&offset=0", });
// Assert — the browser calls the automation API on the cloud host // directly, authenticated by the backend's API key, and no envelope // POST reaches /api/cloud-proxy. const [url, init] = fetchMock.mock.calls[0]!; expect(url).toBe( `${cloudPersonal.host}/api/automation/v1?limit=50&offset=0`, ); expect(init).toMatchObject({ method: "GET", }); expect( (init as { headers: Record<string, string> }).headers.Authorization, ).toBe(`Bearer ${cloudPersonal.apiKey}`); expect(result).toEqual(page); });
it("forwards the blob responseType and fail-fast timeout to the direct request", async () => { // Arrange — tarball downloads and health probes rely on these // per-request options surviving the switch from the proxy envelope to // the direct call. setRegisteredBackends([cloudPersonal]); setActiveSelection({ backendId: cloudPersonal.id, orgId: null });
// Act await callCloudProxy({ backend: cloudPersonal, method: "GET", path: "/api/automation/v1/auto-1/tarball", responseType: "blob", timeoutSeconds: 5, });
// Assert const [url, init] = fetchMock.mock.calls[0]!; expect(url).toBe(`${cloudPersonal.host}/api/automation/v1/auto-1/tarball`); expect(init).toMatchObject({ method: "GET" }); });});
describe("callCloudProxy hostOverride routing", () => { const runtimeHost = "https://abc123.prod-runtime.all-hands.dev";
it("routes through the local /api/cloud-proxy instead of the upstream host when hostOverride is set", async () => { // Arrange — runtime-sandbox endpoints need the proxy hop because the // per-conversation runtime hosts reject browser requests from the // local GUI origin. setRegisteredBackends([cloudPersonal]); setActiveSelection({ backendId: cloudPersonal.id, orgId: null }); fetchMock.mockResolvedValueOnce(mockJsonResponse({ items: [] }));
// Act const result = await callCloudProxy({ backend: cloudPersonal, method: "GET", path: "/api/bash/bash_events/search", hostOverride: runtimeHost, });
// Assert — the browser only makes a same-origin POST to the bundled // agent-server's proxy endpoint carrying the upstream call as an // envelope, and the upstream payload is unwrapped for the caller. const [url, init] = fetchMock.mock.calls[0]!; expect(url).toMatch(/\/api\/cloud-proxy$/); const envelope = JSON.parse((init as { body: string }).body); expect(envelope).toMatchObject({ host: runtimeHost, method: "GET", path: "/api/bash/bash_events/search", }); expect(result).toEqual({ items: [] }); });
it("carries bearer auth and X-Org-Id inside the proxy envelope", async () => { // Arrange — org scoping must survive the server-side hop: the envelope // headers are what the agent-server attaches to the upstream call in // place of the headers a direct browser request would have sent. setRegisteredBackends([cloudPersonal]); setActiveSelection({ backendId: cloudPersonal.id, orgId: "org-personal-uuid", });
// Act await callCloudProxy({ backend: cloudPersonal, method: "GET", path: "/api/bash/bash_events/search", hostOverride: runtimeHost, });
// Assert const [, init] = fetchMock.mock.calls[0]!; const envelope = JSON.parse((init as { body: string }).body); expect( (envelope as { headers: Record<string, string> }).headers, ).toMatchObject({ Authorization: `Bearer ${cloudPersonal.apiKey}`, "X-Org-Id": "org-personal-uuid", }); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import { batchGetCloudSandboxes } from "#/api/cloud/sandbox-service.api";import type { Backend } from "#/api/backend-registry/types";import { getFetchCall, mockJsonResponse } from "./fetch-test-utils";
const cloudBackend: Backend = { id: "cloud-prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse([])); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("batchGetCloudSandboxes", () => { it("targets /api/v1/sandboxes with one id query param per sandbox id", async () => { // Arrange — multiple ids exercises the URLSearchParams.append path, // which is the cloud contract for batch-fetching sandboxes (the GUI // reads sandbox.exposed_urls from the response to find the VSCODE // URL instead of asking the runtime for a localhost address). const ids = ["sandbox-a", "sandbox-b"];
// Act await batchGetCloudSandboxes(ids);
const [url, init] = getFetchCall(fetchMock); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(url).toBe( `${cloudBackend.host}/api/v1/sandboxes?id=sandbox-a&id=sandbox-b`, ); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import { SecretsService } from "#/api/secrets-service";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({})); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("SecretsService against cloud backend", () => { it("paginates getSecrets directly and returns the merged list", async () => { fetchMock .mockResolvedValueOnce( mockJsonResponse({ items: [ { name: "ALPHA", description: "first" }, { name: "BETA", description: "second" }, ], next_page_id: "BETA", }), ) .mockResolvedValueOnce( mockJsonResponse({ items: [{ name: "GAMMA", description: "third" }], next_page_id: null, }), );
const secrets = await SecretsService.getSecrets();
expect(fetchMock).toHaveBeenCalledTimes(2);
const [firstUrl, firstInit] = getFetchCall(fetchMock, 0); expect(firstInit).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(firstUrl).toMatch( /^https:\/\/app\.all-hands\.dev\/api\/v1\/secrets\/search\?/, ); expect(firstUrl).not.toContain("page_id=");
const [secondUrl] = getFetchCall(fetchMock, 1); expect(secondUrl).toContain("page_id=BETA");
expect(secrets.map((s) => s.name)).toEqual(["ALPHA", "BETA", "GAMMA"]); });
it("creates a secret via direct POST /api/v1/secrets", async () => { await SecretsService.createSecret( "OPENAI_API_KEY", "sk-test", "OpenAI key", );
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/secrets`); expect(init).toMatchObject({ method: "POST", headers: { Authorization: "Bearer bearer-token" }, }); expect(getJsonBody(init)).toEqual({ name: "OPENAI_API_KEY", value: "sk-test", description: "OpenAI key", }); });
it("updates a secret via PUT /api/v1/secrets/{id} with name + description only", async () => { // The form/hook calls updateSecret(secretToEdit, newName, description). await SecretsService.updateSecret("OLD_NAME", "NEW_NAME", "renamed");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/secrets/OLD_NAME`); expect(init).toMatchObject({ method: "PUT", headers: { Authorization: "Bearer bearer-token" }, }); expect(getJsonBody(init)).toEqual({ name: "NEW_NAME", description: "renamed", }); // No value supplied, so nothing overwrites the stored one. expect(fetchMock).toHaveBeenCalledTimes(1); });
it("overwrites the value with a POST following the PUT", async () => { // Fresh Response per call: a Response body can only be consumed once. fetchMock.mockImplementation(() => Promise.resolve(mockJsonResponse({})));
await SecretsService.updateSecret( "API_KEY", "API_KEY", "Demo secret", "new-value", );
expect(fetchMock).toHaveBeenCalledTimes(2);
const [putUrl, putInit] = getFetchCall(fetchMock, 0); expect(putUrl).toBe(`${cloudBackend.host}/api/v1/secrets/API_KEY`); expect(putInit).toMatchObject({ method: "PUT" });
const [postUrl, postInit] = getFetchCall(fetchMock, 1); expect(postUrl).toBe(`${cloudBackend.host}/api/v1/secrets`); expect(postInit).toMatchObject({ method: "POST" }); expect(getJsonBody(postInit)).toEqual({ name: "API_KEY", value: "new-value", description: "Demo secret", }); });
it("deletes a secret via direct DELETE /api/v1/secrets/{id}", async () => { await SecretsService.deleteSecret("token with space");
const [url, init] = getFetchCall(fetchMock); expect(url).toBe( `${cloudBackend.host}/api/v1/secrets/token%20with%20space`, ); expect(init).toMatchObject({ method: "DELETE", headers: { Authorization: "Bearer bearer-token" }, }); });
it("treats a delete 404 as success (secret already gone)", async () => { // Fresh Response per attempt: the retry helper re-fetches and a // Response body can only be consumed once. Fake timers skip the // retry backoff sleeps. fetchMock.mockImplementation(() => Promise.resolve(mockJsonResponse({ detail: "Secret not found" }, 404)), ); vi.useFakeTimers();
try { const assertion = expect( SecretsService.deleteSecret("ALREADY_GONE"), ).resolves.toBeUndefined(); await vi.runAllTimersAsync(); await assertion; } finally { vi.useRealTimers(); } });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import { fetchCloudSettings, saveCloudSettings,} from "#/api/cloud/settings-service.api";import SettingsService from "#/api/settings-service/settings-service.api";import { getFetchCall, getJsonBody, mockJsonResponse,} from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); fetchMock.mockResolvedValue(mockJsonResponse({})); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("cloud settings", () => { it("fetchCloudSettings preserves provider_tokens_set so the repo chain can fire", async () => { fetchMock.mockResolvedValueOnce( mockJsonResponse({ llm_model: "anthropic/claude-3-5-sonnet", llm_base_url: "https://api.anthropic.com", llm_api_key_set: true, agent: "CodeActAgent", confirmation_mode: true, security_analyzer: "llm", max_iterations: 30, provider_tokens_set: { github: "***" }, }), );
const result = await fetchCloudSettings();
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/settings`); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, });
// provider_tokens_set must round-trip — it's what drives // useUserProviders → useAppInstallations → useGitRepositories. expect(result.provider_tokens_set).toEqual({ github: "***" });
// Top-level cloud fields are preserved as-is. expect(result.llm_model).toBe("anthropic/claude-3-5-sonnet"); expect(result.llm_api_key_set).toBe(true); expect(result.agent).toBe("CodeActAgent");
// Nested shape derived for the local-mode settings page. expect(result.agent_settings?.agent).toBe("CodeActAgent"); expect(result.agent_settings?.llm).toEqual({ model: "anthropic/claude-3-5-sonnet", base_url: "https://api.anthropic.com", }); expect(result.conversation_settings?.confirmation_mode).toBe(true); expect(result.conversation_settings?.security_analyzer).toBe("llm"); expect(result.conversation_settings?.max_iterations).toBe(30); });
it("saveCloudSettings forwards diffs verbatim and omits the legacy keys the cloud rejects", async () => { const agentDiff = { llm: { model: "openai/gpt-4o", base_url: "https://api.openai.com" }, agent: "CodeActAgent", }; const conversationDiff = { max_iterations: 50 };
await saveCloudSettings({ agent_settings_diff: agentDiff, conversation_settings_diff: conversationDiff, });
const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/settings`); expect(init).toMatchObject({ method: "POST", headers: { Authorization: "Bearer bearer-token" }, }); const requestBody = getJsonBody(init); expect(requestBody).toEqual({ agent_settings_diff: agentDiff, conversation_settings_diff: conversationDiff, }); expect(requestBody).not.toHaveProperty("agent_settings"); expect(requestBody).not.toHaveProperty("conversation_settings"); });
it("SettingsService.saveSettings forwards disabled_skills to cloud when active backend is cloud", async () => { // Act: save a skills-only update — previously this short-circuited and // sent nothing at all, leaving the toggle un-persisted. await SettingsService.saveSettings({ disabled_skills: ["SSH Microagent"], });
// Assert: a single POST /api/v1/settings reached the wire with // disabled_skills as a top-level field. expect(fetchMock).toHaveBeenCalledTimes(1); const [url, init] = getFetchCall(fetchMock); expect(url).toBe(`${cloudBackend.host}/api/v1/settings`); expect(init).toMatchObject({ method: "POST", headers: { Authorization: "Bearer bearer-token" }, }); expect(getJsonBody(init)).toEqual({ disabled_skills: ["SSH Microagent"], }); });
it("saveCloudSettings omits an empty conversation_settings_diff (LLM-only save)", async () => { await saveCloudSettings({ agent_settings_diff: { llm: { model: "anthropic/claude-sonnet-4-20250514" }, }, conversation_settings_diff: {}, });
const [, init] = getFetchCall(fetchMock); const requestBody = getJsonBody(init); expect(requestBody).toEqual({ agent_settings_diff: { llm: { model: "anthropic/claude-sonnet-4-20250514" }, }, }); });});
describe("saveCloudSettings drops agent_context: null (agent-canvas#981)", () => { it("strips a null agent_context while preserving sibling agent settings", async () => { // Act await saveCloudSettings({ agent_settings_diff: { llm: { model: "anthropic/claude-sonnet-4-20250514" }, agent_context: null, }, });
// Assert: agent_context never reaches the wire, but the real llm change does. const [, init] = getFetchCall(fetchMock); const requestBody = getJsonBody(init); expect(requestBody).toEqual({ agent_settings_diff: { llm: { model: "anthropic/claude-sonnet-4-20250514" }, }, }); });
it("preserves a null mcp_config so clearing MCP servers still round-trips", async () => { // Act await saveCloudSettings({ agent_settings_diff: { mcp_config: null }, });
// Assert: the null mcp_config must survive (don't over-strip nulls). const [, init] = getFetchCall(fetchMock); const requestBody = getJsonBody(init); expect(requestBody).toEqual({ agent_settings_diff: { mcp_config: null } }); });
it("omits agent_settings_diff when agent_context: null is its only key", async () => { // Act await saveCloudSettings({ agent_settings_diff: { agent_context: null }, });
// Assert: nothing is left to send, so no agent_settings_diff goes on the wire. const [, init] = getFetchCall(fetchMock); const requestBody = getJsonBody(init); expect(requestBody).toEqual({}); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import SkillsService from "#/api/skills-service";import { getFetchCall, mockJsonResponse } from "./fetch-test-utils";
const cloudBackend: Backend = { id: "prod", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-token", kind: "cloud",};
const originalFetch = global.fetch;const fetchMock = vi.fn();
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id }); fetchMock.mockReset(); global.fetch = fetchMock as typeof fetch;});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); fetchMock.mockReset(); global.fetch = originalFetch;});
describe("SkillsService.getSkills against cloud backend", () => { it("paginates /api/v1/skills/search directly and returns the merged list", async () => { fetchMock .mockResolvedValueOnce( mockJsonResponse({ items: [ { name: "alpha", type: "knowledge", source: "global" }, { name: "beta", type: "task", source: "user", triggers: ["foo"], }, ], next_page_id: "beta", }), ) .mockResolvedValueOnce( mockJsonResponse({ items: [{ name: "gamma", type: "knowledge", source: "user" }], next_page_id: null, }), );
const skills = await SkillsService.getSkills();
expect(fetchMock).toHaveBeenCalledTimes(2);
const [firstUrl, firstInit] = getFetchCall(fetchMock, 0); expect(firstInit).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(firstUrl).toMatch( /^https:\/\/app\.all-hands\.dev\/api\/v1\/skills\/search\?/, ); expect(firstUrl).not.toContain("page_id=");
const [secondUrl] = getFetchCall(fetchMock, 1); expect(secondUrl).toContain("page_id=beta");
expect(skills.map((s) => s.name)).toEqual(["alpha", "beta", "gamma"]); expect(skills[1]).toMatchObject({ triggers: ["foo"] }); });});
describe("SkillsService.getConversationSkills against cloud backend", () => { it("reads the conversation's own skills route and maps entries to SkillInfo", async () => { // Arrange fetchMock.mockResolvedValueOnce( mockJsonResponse({ skills: [ { name: "release-notes", type: "agentskills", content: "# Release notes", triggers: ["/release-notes"], }, { name: "repo", type: "repo", content: "Repository instructions", triggers: [], }, ], }), );
// Act const skills = await SkillsService.getConversationSkills("conv-1");
// Assert expect(fetchMock).toHaveBeenCalledTimes(1); const [url, init] = getFetchCall(fetchMock, 0); expect(url).toBe( "https://app.all-hands.dev/api/v1/app-conversations/conv-1/skills", ); expect(init).toMatchObject({ method: "GET", headers: { Authorization: "Bearer bearer-token" }, }); expect(skills).toEqual([ { name: "release-notes", type: "agentskills", content: "# Release notes", triggers: ["/release-notes"], source: null, }, { name: "repo", type: "repo", content: "Repository instructions", triggers: [], source: null, }, ]); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { beforeEach, describe, expect, it } from "vitest";import { __resetMcpHealthStoreForTests, beginMcpHealthCheck, clearMcpServerHealth, getMcpHealthSnapshot, resolveMcpHealthCheck,} from "#/api/mcp-health/mcp-health-store";import type { McpServerHealth } from "#/types/mcp-health";
const HEALTHY: McpServerHealth = { status: "healthy", verification: "verified", toolCount: 3, checkedAt: 1,};
const FAILED: McpServerHealth = { status: "failed", kind: "connection", error: "refused", checkedAt: 2,};
describe("mcp-health-store", () => { beforeEach(() => { __resetMcpHealthStoreForTests(); });
it("marks a check as in flight and commits its result", () => { const checkId = beginMcpHealthCheck("key"); expect(getMcpHealthSnapshot().key).toEqual({ status: "checking", checkId });
resolveMcpHealthCheck("key", checkId, HEALTHY);
expect(getMcpHealthSnapshot().key).toEqual(HEALTHY); });
it("drops a stale result that was superseded by a newer check", () => { const staleId = beginMcpHealthCheck("key"); const freshId = beginMcpHealthCheck("key");
// The slow older probe must not overwrite the newer probe's lifecycle. resolveMcpHealthCheck("key", staleId, HEALTHY); expect(getMcpHealthSnapshot().key).toEqual({ status: "checking", checkId: freshId, });
resolveMcpHealthCheck("key", freshId, FAILED); expect(getMcpHealthSnapshot().key).toEqual(FAILED); });
it("drops a result whose entry was cleared mid-flight", () => { // e.g. the server was edited or deleted while its probe was running — // the late result must not resurrect a verdict for a gone config. const checkId = beginMcpHealthCheck("key"); clearMcpServerHealth("key");
resolveMcpHealthCheck("key", checkId, HEALTHY);
expect(getMcpHealthSnapshot().key).toBeUndefined(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179import { beforeEach, describe, expect, it, vi } from "vitest";import { __resetMcpHealthStoreForTests, getMcpHealthSnapshot, setMcpServerHealth,} from "#/api/mcp-health/mcp-health-store";import { interpretMcpTestResponse, probeMcpServerHealth, seedMcpServerHealth,} from "#/api/mcp-health/probe-mcp-server-health";import McpService from "#/api/mcp-service/mcp-service.api";import type { ExtendedMCPTestResponse, MCPServerConfig } from "#/types/mcp-server";import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";
/** Matches the catalog `github` entry, so the `get_me` probe spec applies. */const GITHUB: MCPServerConfig = { id: "shttp-0", type: "shttp", name: "github", url: "https://api.githubcopilot.com/mcp/", auth: { strategy: "api_key", value: "github_pat_x" },};
/** Matches no catalog entry, so no probe spec exists. */const CUSTOM: MCPServerConfig = { id: "shttp-1", type: "shttp", name: "custom", url: "https://mcp.example.com/mcp",};
describe("interpretMcpTestResponse", () => { it("passes a non-auth connection failure through with its kind", () => { const health = interpretMcpTestResponse(CUSTOM, { ok: false, error: "connection refused", error_kind: "connection", });
expect(health).toMatchObject({ status: "failed", kind: "connection", error: "connection refused", }); });
it("reclassifies a connection failure with auth-rejection text as a credentials failure", () => { // Hosted servers reject bad tokens at the HTTP handshake, which the // backend can only report as a connection failure. const health = interpretMcpTestResponse(GITHUB, { ok: false, error: "Client error '401 Unauthorized' for url …", error_kind: "connection", });
expect(health).toMatchObject({ status: "failed", kind: "credentials" }); });
it("reports verified health when the read-only probe tool ran cleanly", () => { const health = interpretMcpTestResponse(GITHUB, { ok: true, tools: ["get_me", "search_code"], tool_result: { is_error: false, text: '{"login":"octocat"}' }, });
expect(health).toMatchObject({ status: "healthy", verification: "verified", toolCount: 2, }); });
it("downgrades to connectivity-only when the probe tool is not advertised", () => { const health = interpretMcpTestResponse(GITHUB, { ok: true, tools: ["search_code"], tool_result: { is_error: true, text: "Tool 'get_me' not advertised by server", }, });
expect(health).toMatchObject({ status: "healthy", verification: "connectivity-only", }); });
it("reports connectivity-only for servers without a probe spec", () => { const health = interpretMcpTestResponse(CUSTOM, { ok: true, tools: ["a"], });
expect(health).toMatchObject({ status: "healthy", verification: "connectivity-only", toolCount: 1, }); });});
describe("probeMcpServerHealth", () => { beforeEach(() => { __resetMcpHealthStoreForTests(); vi.restoreAllMocks(); });
it("publishes checking while the probe runs, then the interpreted result", async () => { let resolveProbe!: (value: ExtendedMCPTestResponse) => void; vi.spyOn(McpService, "testServer").mockReturnValue( new Promise((resolve) => { resolveProbe = resolve; }), ); const key = getMcpServerHealthKey(CUSTOM);
const probe = probeMcpServerHealth(CUSTOM); expect(getMcpHealthSnapshot()[key]).toMatchObject({ status: "checking" });
resolveProbe({ ok: true, tools: ["a", "b"] }); await probe;
expect(getMcpHealthSnapshot()[key]).toMatchObject({ status: "healthy", verification: "connectivity-only", toolCount: 2, }); });
it("converts a thrown transport error into a failed verdict", async () => { vi.spyOn(McpService, "testServer").mockRejectedValue( new Error("network down"), );
await probeMcpServerHealth(CUSTOM);
expect(getMcpHealthSnapshot()[getMcpServerHealthKey(CUSTOM)]).toMatchObject( { status: "failed", kind: "unknown", error: "network down" }, ); });});
describe("seedMcpServerHealth", () => { beforeEach(() => { __resetMcpHealthStoreForTests(); });
it("publishes the saved server's health from its pre-save test result", () => { seedMcpServerHealth(CUSTOM, { ok: true, tools: ["a"] }, []);
expect(getMcpHealthSnapshot()[getMcpServerHealthKey(CUSTOM)]).toMatchObject( { status: "healthy" }, ); });
it("skips seeding when another installed server shares the health key", () => { // A second install of the same catalog entry collides on the key until // the save suffixes its name; it must not overwrite the first card. const existingVerdict = { status: "failed", kind: "credentials", error: "bad token", checkedAt: 1, } as const; setMcpServerHealth(getMcpServerHealthKey(GITHUB), existingVerdict);
seedMcpServerHealth( { ...GITHUB, id: "shttp-9" }, { ok: true, tools: ["get_me"] }, [GITHUB], );
expect(getMcpHealthSnapshot()[getMcpServerHealthKey(GITHUB)]).toEqual( existingVerdict, ); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395import { describe, it, expect, vi, beforeEach } from "vitest";import McpService from "#/api/mcp-service/mcp-service.api";import SettingsService, { type SettingsApiResponse,} from "#/api/settings-service/settings-service.api";import * as activeStore from "#/api/backend-registry/active-store";import type { MCPServerConfig } from "#/types/mcp-server";import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";
// vi.mock factories are hoisted before imports, so spy functions must be// created with vi.hoisted() to be in scope inside the factory.const { mockTestServer } = vi.hoisted(() => ({ mockTestServer: vi.fn(),}));
vi.mock("@openhands/typescript-client/clients", () => ({ // Real class so `new MCPClient(...)` works; testServer delegates to the // shared spy so each test can configure the return value independently. MCPClient: class { // eslint-disable-next-line class-methods-use-this testServer = mockTestServer;
// eslint-disable-next-line class-methods-use-this close = vi.fn(); },}));
vi.mock("#/api/agent-server-client-options", () => ({ getAgentServerClientOptions: () => ({ host: "http://localhost:3000", apiKey: "test-key", }),}));
vi.mock("#/api/backend-registry/active-store", () => ({ getActiveBackend: vi.fn(),}));
const mockGetActiveBackend = vi.mocked(activeStore.getActiveBackend);
const localActive = () => mockGetActiveBackend.mockReturnValue({ backend: { id: "local-1", name: "Local", host: "http://localhost:3000", apiKey: "test-key", kind: "local", }, orgId: null, });
const cloudActive = () => mockGetActiveBackend.mockReturnValue({ backend: { id: "cloud-1", name: "Cloud", host: "https://app.all-hands.dev", apiKey: "cloud-key", kind: "cloud", }, orgId: null, });
const SERVER: MCPServerConfig = { id: "shttp-1", type: "shttp", url: "https://mcp.example.com/mcp",};
describe("McpService.testServer", () => { beforeEach(() => { vi.clearAllMocks(); localActive(); });
it("passes success responses through unchanged", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: ["search", "fetch"] });
const result = await McpService.testServer(SERVER);
expect(result).toEqual({ ok: true, tools: ["search", "fetch"] }); });
it("passes failure responses through unchanged (no server-side escaping)", async () => { // The backend returns plain text; HTML-escaping of {{-error}} is handled // by the i18next no-escape prefix in the translation string, not here. mockTestServer.mockResolvedValue({ ok: false, error: "Client error '401 Unauthorized' for url https://mcp.example.com/mcp", error_kind: "unknown", });
const result = await McpService.testServer(SERVER);
expect(result).toEqual({ ok: false, error: "Client error '401 Unauthorized' for url https://mcp.example.com/mcp", error_kind: "unknown", }); });
it("maps a stdio config to a StdioMCPServerSpec", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: [] }); const stdio: MCPServerConfig = { id: "my-server", type: "stdio", name: "my-server", command: "npx", args: ["-y", "@my/mcp-server"], env: { API_KEY: "secret" }, };
await McpService.testServer(stdio);
// Exact match also guards that non-catalog servers get no `tool_call`. expect(mockTestServer).toHaveBeenCalledWith({ server: { type: "stdio", command: "npx", args: ["-y", "@my/mcp-server"], env: { API_KEY: "secret" }, }, name: "my-server", }); });
// ------------------------------------------------------------------------- // Credential verification for marketplace servers (Slack) // // The Slack MCP server lists its tools with any credentials and reports // upstream auth failures as ordinary text content, so the service attaches // a read-only verification tool call and interprets its payload. // -------------------------------------------------------------------------
const SLACK_SERVER: MCPServerConfig = { id: "slack", type: "stdio", name: "slack", command: "npx", args: ["-y", "@zencoderai/slack-mcp-server"], env: { SLACK_TEAM_ID: "T01", SLACK_BOT_TOKEN: "xoxb-abc" }, };
const slackToolResult = (text: string, isError = false) => ({ ok: true, tools: ["slack_list_channels"], tool_result: { is_error: isError, text }, });
it("attaches the read-only Slack verification tool call to the request", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: [] });
await McpService.testServer(SLACK_SERVER);
expect(mockTestServer).toHaveBeenCalledWith( expect.objectContaining({ tool_call: { name: "slack_list_channels", arguments: { limit: 1 } }, }), ); });
it("maps an in-band Slack auth error to a credentials failure", async () => { mockTestServer.mockResolvedValue( slackToolResult('{"ok":false,"error":"invalid_auth"}'), );
const result = await McpService.testServer(SLACK_SERVER);
expect(result).toEqual({ ok: false, error: "invalid_auth", error_kind: "credentials", }); });
it("does not flag non-auth Slack errors (missing_scope) as bad credentials", async () => { // A valid token lacking a scope authenticated successfully — failing it // would block correctly-configured installs. const response = slackToolResult('{"ok":false,"error":"missing_scope"}'); mockTestServer.mockResolvedValue(response);
const result = await McpService.testServer(SLACK_SERVER);
expect(result).toEqual(response); });
it("passes a succeeding Slack payload through unchanged", async () => { const response = slackToolResult('{"ok":true,"channels":[]}'); mockTestServer.mockResolvedValue(response);
const result = await McpService.testServer(SLACK_SERVER);
expect(result).toEqual(response); });
it("maps an errored verification call to a credentials failure", async () => { mockTestServer.mockResolvedValue( slackToolResult("Tool 'slack_list_channels' call timed out", true), );
const result = await McpService.testServer(SLACK_SERVER);
expect(result).toEqual({ ok: false, error: "Tool 'slack_list_channels' call timed out", error_kind: "credentials", }); });
it("returns the response unchanged when an older backend omits tool_result", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: ["a", "b"] });
const result = await McpService.testServer(SLACK_SERVER);
expect(result).toEqual({ ok: true, tools: ["a", "b"] }); });
it("skips credential interpretation when the probe tool is not advertised", async () => { // A server variant that doesn't expose the probe tool (e.g. Slack's // hosted MCP) returns a deterministic "not advertised" tool error; that // proves nothing about credentials and must not block the install. const response = { ok: true, tools: ["conversations_history"], tool_result: { is_error: true, text: "Tool 'slack_list_channels' not advertised by server", }, }; mockTestServer.mockResolvedValue(response);
const result = await McpService.testServer(SLACK_SERVER);
expect(result).toEqual(response); });
// ------------------------------------------------------------------------- // Read-only credential probes for the hosted GitHub and Linear servers // -------------------------------------------------------------------------
const GITHUB_SERVER: MCPServerConfig = { id: "shttp-0", type: "shttp", name: "github", url: "https://api.githubcopilot.com/mcp/", auth: { strategy: "api_key", value: "github_pat_LIVETOKENVALUE" }, };
const LINEAR_SERVER: MCPServerConfig = { id: "shttp-1", type: "shttp", name: "linear", url: "https://mcp.linear.app/mcp", auth: { strategy: "bearer", value: "lin_api_LIVETOKEN" }, };
it("attaches the read-only GitHub probe (get_me) to matching servers", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: [] });
await McpService.testServer(GITHUB_SERVER);
expect(mockTestServer).toHaveBeenCalledWith( expect.objectContaining({ tool_call: { name: "get_me", arguments: {} }, }), ); });
it("attaches the read-only Linear probe (list_teams) to matching servers", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: [] });
await McpService.testServer(LINEAR_SERVER);
expect(mockTestServer).toHaveBeenCalledWith( expect.objectContaining({ tool_call: { name: "list_teams", arguments: {} }, }), ); });
it("maps an errored GitHub probe call to a redacted credentials failure", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: ["get_me"], tool_result: { is_error: true, text: "401 for token github_pat_LIVETOKENVALUE", }, });
const result = await McpService.testServer(GITHUB_SERVER);
// Interpretation runs on already-redacted text, so the surfaced // credentials error never contains the configured secret. expect(result).toEqual({ ok: false, error: `401 for token ${REDACTED_MCP_SECRET_VALUE}`, error_kind: "credentials", }); });
it("redacts configured secrets from failure error text", async () => { mockTestServer.mockResolvedValue({ ok: false, error: "handshake rejected Bearer github_pat_LIVETOKENVALUE", error_kind: "connection", });
const result = await McpService.testServer(GITHUB_SERVER);
expect(result).toMatchObject({ ok: false, error_kind: "connection" }); expect(JSON.stringify(result)).not.toContain("github_pat_LIVETOKENVALUE"); });
// ------------------------------------------------------------------------- // Redacted-secret round-trip for the edit flow // // The MCP page reads settings with redacted secrets, so unchanged env // values arrive as the literal redaction placeholder. The service swaps // them for the stored values in encrypted form (decrypted server-side) so // the test exercises the real credentials. // -------------------------------------------------------------------------
const REDACTED_SLACK_SERVER: MCPServerConfig = { ...SLACK_SERVER, env: { SLACK_TEAM_ID: "T01", SLACK_BOT_TOKEN: REDACTED_MCP_SECRET_VALUE }, };
it("substitutes redacted env values with encrypted stored values", async () => { mockTestServer.mockResolvedValue({ ok: true, tools: [] }); vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({ agent_settings: { mcp_config: { slack: { env: { SLACK_BOT_TOKEN: "gAAAAA-encrypted-token" } }, }, }, } as unknown as SettingsApiResponse);
await McpService.testServer(REDACTED_SLACK_SERVER);
expect(SettingsService.fetchSettingsFromApi).toHaveBeenCalledWith( "encrypted", ); expect(mockTestServer).toHaveBeenCalledWith( expect.objectContaining({ server: expect.objectContaining({ // Placeholder replaced by ciphertext; typed value left untouched. env: { SLACK_TEAM_ID: "T01", SLACK_BOT_TOKEN: "gAAAAA-encrypted-token", }, }), }), ); });
it("keeps the placeholder when encrypted settings cannot be fetched", async () => { // e.g. HTTP 503 from a backend without a cipher — the test must still // run (and fail the credential check honestly) instead of crashing. mockTestServer.mockResolvedValue({ ok: true, tools: [] }); vi.spyOn(SettingsService, "fetchSettingsFromApi").mockRejectedValue( new Error("503 no cipher"), );
await McpService.testServer(REDACTED_SLACK_SERVER);
expect(mockTestServer).toHaveBeenCalledWith( expect.objectContaining({ server: expect.objectContaining({ env: { SLACK_TEAM_ID: "T01", SLACK_BOT_TOKEN: REDACTED_MCP_SECRET_VALUE, }, }), }), ); });
it("short-circuits with a synthetic ok response on cloud backends", async () => { // Regression: when the active backend is cloud, the local agent-server's // /api/mcp/test endpoint is not reachable. Previously, the helper threw // `NoBackendAvailableError("No backend is configured.")` which surfaced // in the install modal and blocked users from creating any MCP server // (e.g. Slack) on a cloud session. cloudActive();
const result = await McpService.testServer(SERVER);
expect(result).toEqual({ ok: true, tools: [] }); expect(mockTestServer).not.toHaveBeenCalled(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307import { FileClient } from "@openhands/typescript-client/clients";import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";import { callCloudProxy } from "#/api/cloud/proxy";import type { Backend } from "#/api/backend-registry/types";
// ─── SDK client mocks ───────────────────────────────────────────────────────
const { executeCommandMock, downloadFileMock } = vi.hoisted(() => ({ executeCommandMock: vi.fn(), downloadFileMock: vi.fn(),}));
vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({ RemoteWorkspace: vi.fn(function RemoteWorkspaceMock() { return { executeCommand: executeCommandMock }; }),}));
vi.mock("@openhands/typescript-client/clients", () => ({ FileClient: vi.fn(function FileClientMock() { return { downloadFile: downloadFileMock }; }),}));
vi.mock("#/api/agent-server-client-options", () => ({ getAgentServerClientOptions: vi.fn(() => ({ host: "http://local-agent.example.com", apiKey: "local-key", workingDir: "/workspace/project", })),}));
vi.mock("#/api/cloud/proxy", () => ({ callCloudProxy: vi.fn(),}));
// ─── Backend fixtures ────────────────────────────────────────────────────────
const cloudBackend: Backend = { id: "cloud-1", name: "Production", host: "https://app.all-hands.dev", apiKey: "cloud-api-key", kind: "cloud",};
const CLOUD_CONVERSATION_URL = "https://runtime.example.com/api/conversations/conv-1";const SESSION_KEY = "session-key-abc";
// ─── Helpers ─────────────────────────────────────────────────────────────────
function activateCloud() { setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id, orgId: null });}
// ─── Setup ───────────────────────────────────────────────────────────────────
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); vi.mocked(RemoteWorkspace).mockClear(); vi.mocked(FileClient).mockClear(); executeCommandMock.mockReset(); downloadFileMock.mockReset(); vi.mocked(callCloudProxy).mockReset();});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests();});
// ─── executeCommand ──────────────────────────────────────────────────────────
describe("AgentServerRuntimeService.executeCommand", () => { describe("local backend", () => { it("creates RemoteWorkspace with resolved options and delegates", async () => { executeCommandMock.mockResolvedValue({ exit_code: 0, stdout: "main\n", stderr: "", });
const result = await AgentServerRuntimeService.executeCommand( "http://local-agent.example.com/api/conversations/conv-1", SESSION_KEY, "git rev-parse --abbrev-ref HEAD", "/workspace/project", 10, );
expect(RemoteWorkspace).toHaveBeenCalledTimes(1); expect(executeCommandMock).toHaveBeenCalledWith( "git rev-parse --abbrev-ref HEAD", "/workspace/project", 10, ); expect(result).toEqual({ exit_code: 0, stdout: "main\n", stderr: "" }); });
it("does not call callCloudProxy for local backends", async () => { executeCommandMock.mockResolvedValue({ exit_code: 0, stdout: "", stderr: "", });
await AgentServerRuntimeService.executeCommand(null, null, "ls", "/", 5);
expect(callCloudProxy).not.toHaveBeenCalled(); }); });
describe("cloud backend", () => { beforeEach(activateCloud);
it("routes through callCloudProxy with correct path, body, and auth", async () => { vi.mocked(callCloudProxy).mockResolvedValue({ exit_code: 0, stdout: "src/index.ts\n", stderr: "", });
const result = await AgentServerRuntimeService.executeCommand( CLOUD_CONVERSATION_URL, SESSION_KEY, "find . -type f", "/workspace/project", 30, );
const proxyCall = vi.mocked(callCloudProxy).mock.calls[0][0]; expect(proxyCall.method).toBe("POST"); expect(proxyCall.path).toBe("/api/bash/execute_bash_command"); expect(proxyCall.hostOverride).toBe("https://runtime.example.com"); expect(proxyCall.body).toEqual({ command: "find . -type f", cwd: "/workspace/project", timeout: 30, }); expect(proxyCall.authMode).toBe("session-api-key"); expect(proxyCall.sessionApiKey).toBe(SESSION_KEY); expect(proxyCall.timeoutSeconds).toBe(40); expect(result).toEqual({ exit_code: 0, stdout: "src/index.ts\n", stderr: "", }); });
it("omits cwd from proxy body when not provided", async () => { vi.mocked(callCloudProxy).mockResolvedValue({ exit_code: 0 });
await AgentServerRuntimeService.executeCommand( CLOUD_CONVERSATION_URL, SESSION_KEY, "echo hi", undefined, 10, );
const proxyBody = vi.mocked(callCloudProxy).mock.calls[0][0].body as Record<string, unknown>; expect(proxyBody).not.toHaveProperty("cwd"); expect(proxyBody.command).toBe("echo hi"); });
it("normalises missing stdout/stderr fields to empty strings", async () => { vi.mocked(callCloudProxy).mockResolvedValue({ exit_code: 1 });
const result = await AgentServerRuntimeService.executeCommand( CLOUD_CONVERSATION_URL, SESSION_KEY, "false", undefined, 5, );
expect(result).toEqual({ exit_code: 1, stdout: "", stderr: "" }); });
it("does not create a RemoteWorkspace for cloud calls", async () => { vi.mocked(callCloudProxy).mockResolvedValue({ exit_code: 0 });
await AgentServerRuntimeService.executeCommand( CLOUD_CONVERSATION_URL, SESSION_KEY, "echo ok", );
expect(RemoteWorkspace).not.toHaveBeenCalled(); });
it("falls back to local path when conversationUrl is null", async () => { executeCommandMock.mockResolvedValue({ exit_code: 0, stdout: "", stderr: "", });
await AgentServerRuntimeService.executeCommand( null, SESSION_KEY, "echo ok", );
expect(callCloudProxy).not.toHaveBeenCalled(); expect(RemoteWorkspace).toHaveBeenCalledTimes(1); }); });});
// ─── downloadFile ─────────────────────────────────────────────────────────────
describe("AgentServerRuntimeService.downloadFile", () => { describe("local backend", () => { it("creates FileClient with resolved options and returns the ArrayBuffer", async () => { const fileBytes = new TextEncoder().encode("# README"); downloadFileMock.mockResolvedValue(fileBytes.buffer);
const result = await AgentServerRuntimeService.downloadFile( "http://local-agent.example.com/api/conversations/conv-1", SESSION_KEY, "/workspace/project/README.md", );
expect(FileClient).toHaveBeenCalledTimes(1); expect(downloadFileMock).toHaveBeenCalledWith( "/workspace/project/README.md", ); expect(result).toBe(fileBytes.buffer); });
it("does not call callCloudProxy for local backends", async () => { downloadFileMock.mockResolvedValue(new ArrayBuffer(0));
await AgentServerRuntimeService.downloadFile( null, null, "/workspace/file.txt", );
expect(callCloudProxy).not.toHaveBeenCalled(); }); });
describe("cloud backend", () => { beforeEach(activateCloud);
it("routes through callCloudProxy with GET and URL-encoded path", async () => { const blob = new Blob([new TextEncoder().encode("file content")]); vi.mocked(callCloudProxy).mockResolvedValue(blob);
const result = await AgentServerRuntimeService.downloadFile( CLOUD_CONVERSATION_URL, SESSION_KEY, "/workspace/project/src/main.ts", );
const proxyCall = vi.mocked(callCloudProxy).mock.calls[0][0]; expect(proxyCall.method).toBe("GET"); expect(proxyCall.path).toBe( "/api/file/download?path=%2Fworkspace%2Fproject%2Fsrc%2Fmain.ts", ); expect(proxyCall.hostOverride).toBe("https://runtime.example.com"); expect(proxyCall.authMode).toBe("session-api-key"); expect(proxyCall.sessionApiKey).toBe(SESSION_KEY); expect(proxyCall.responseType).toBe("blob");
// Blob.arrayBuffer() round-trip: decoded text should match the original. expect(new TextDecoder().decode(result)).toBe("file content"); });
it("does not create a FileClient for cloud calls", async () => { vi.mocked(callCloudProxy).mockResolvedValue(new Blob());
await AgentServerRuntimeService.downloadFile( CLOUD_CONVERSATION_URL, SESSION_KEY, "/workspace/file.txt", );
expect(FileClient).not.toHaveBeenCalled(); });
it("falls back to local path when conversationUrl is null", async () => { downloadFileMock.mockResolvedValue(new ArrayBuffer(0));
await AgentServerRuntimeService.downloadFile( null, SESSION_KEY, "/workspace/file.txt", );
expect(callCloudProxy).not.toHaveBeenCalled(); expect(FileClient).toHaveBeenCalledTimes(1); }); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { TelemetryConsentBanner } from "#/components/features/analytics/telemetry-consent-banner";
const useActiveBackendMock = vi.fn();const useSettingsMock = vi.fn();const useBackendsHealthMock = vi.fn();const saveSettingsMock = vi.fn();const getLockedCloudHostMock = vi.fn();const setTelemetryConsentMock = vi.fn();
vi.mock("react-i18next", () => ({ useTranslation: () => ({ ready: true, t: (key: string, options?: Record<string, string>) => key === "TELEMETRY$BACKEND_SCOPE" ? `This preference is saved for ${options?.name} at ${options?.host}.` : key, }),}));
vi.mock("#/i18n", () => ({ OPENHANDS_I18N_NAMESPACE: "openhands",}));
vi.mock("#/api/agent-server-config", () => ({ getLockedCloudHost: () => getLockedCloudHostMock(),}));
vi.mock("#/contexts/active-backend-context", () => ({ useActiveBackend: () => useActiveBackendMock(),}));
vi.mock("#/hooks/query/use-settings", () => ({ useSettings: () => useSettingsMock(),}));
vi.mock("#/hooks/query/use-backends-health", () => ({ useBackendsHealth: (...args: unknown[]) => useBackendsHealthMock(...args),}));
vi.mock("#/hooks/mutation/use-save-settings", () => ({ useSaveSettings: () => ({ mutateAsync: saveSettingsMock, isPending: false, }),}));
vi.mock("#/services/telemetry", () => ({ setTelemetryConsent: (...args: unknown[]) => setTelemetryConsentMock(...args),}));
describe("TelemetryConsentBanner", () => { beforeEach(() => { vi.clearAllMocks(); saveSettingsMock.mockResolvedValue(undefined); getLockedCloudHostMock.mockReturnValue(null); useActiveBackendMock.mockReturnValue({ backend: { id: "local", kind: "local", name: "Local Dev", host: "http://localhost:12000", }, }); useBackendsHealthMock.mockReturnValue({ local: { isConnected: true }, });
useSettingsMock.mockReturnValue({ data: { user_consents_to_analytics: null }, isSuccess: true, }); });
it("renders in local mode when agent-server consent is null", async () => { render(<TelemetryConsentBanner />);
expect( await screen.findByTestId("telemetry-consent-form"), ).toBeInTheDocument(); expect( screen.getByText( "This preference is saved for Local Dev at http://localhost:12000.", ), ).toBeInTheDocument(); });
it("does not render until the local backend settings are connected", async () => { useSettingsMock.mockReturnValue({ data: { user_consents_to_analytics: null }, isSuccess: false, });
render(<TelemetryConsentBanner />);
await waitFor(() => { expect( screen.queryByTestId("telemetry-consent-form"), ).not.toBeInTheDocument(); }); });
it("does not render when the active local backend is unhealthy", async () => { useBackendsHealthMock.mockReturnValue({ local: { isConnected: false }, }); useSettingsMock.mockReturnValue({ data: { user_consents_to_analytics: null }, isSuccess: true, });
render(<TelemetryConsentBanner />);
await waitFor(() => { expect( screen.queryByTestId("telemetry-consent-form"), ).not.toBeInTheDocument(); }); });
it.each([true, false])( "does not render when agent-server consent is %s", async (serverConsent) => { useSettingsMock.mockReturnValue({ data: { user_consents_to_analytics: serverConsent }, isSuccess: true, });
render(<TelemetryConsentBanner />);
await waitFor(() => { expect( screen.queryByTestId("telemetry-consent-form"), ).not.toBeInTheDocument(); }); }, );
it("does not render for cloud backends", async () => { useActiveBackendMock.mockReturnValue({ backend: { id: "cloud", kind: "cloud" }, });
render(<TelemetryConsentBanner />);
await waitFor(() => { expect( screen.queryByTestId("telemetry-consent-form"), ).not.toBeInTheDocument(); }); });
it("does not render in locked Cloud mode", async () => { getLockedCloudHostMock.mockReturnValue("https://app.all-hands.dev");
render(<TelemetryConsentBanner />);
await waitFor(() => { expect( screen.queryByTestId("telemetry-consent-form"), ).not.toBeInTheDocument(); }); });
it("persists the user's local-mode consent choice without useTelemetry", async () => { const user = userEvent.setup(); render(<TelemetryConsentBanner />);
const checkbox = await screen.findByRole("checkbox"); await user.click(checkbox); await user.click(screen.getByTestId("confirm-telemetry-preferences"));
expect(setTelemetryConsentMock).toHaveBeenCalledWith("denied"); expect(saveSettingsMock).toHaveBeenCalledWith({ user_consents_to_analytics: false, }); });
it("does not persist browser consent when the backend save fails", async () => { const user = userEvent.setup(); saveSettingsMock.mockRejectedValue(new Error("unauthorized")); render(<TelemetryConsentBanner />);
await screen.findByTestId("telemetry-consent-form"); await user.click(screen.getByTestId("confirm-telemetry-preferences"));
await waitFor(() => { expect(saveSettingsMock).toHaveBeenCalledWith({ user_consents_to_analytics: true, }); }); expect(setTelemetryConsentMock).not.toHaveBeenCalled(); expect(screen.getByTestId("telemetry-consent-form")).toBeInTheDocument(); });
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import React from "react";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it, vi } from "vitest";import { NavigationProvider, type NavigationContextValue,} from "#/context/navigation-context";import { AddAutomationModal } from "#/components/features/automations/add-automation-modal";import { I18nKey } from "#/i18n/declaration";
vi.mock("#/hooks/query/use-settings", () => ({ useSettings: () => ({ data: { user_consents_to_analytics: true } }),}));
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key, }), Trans: ({ i18nKey, components, children, }: { i18nKey: string; components?: Record<string, React.ReactElement>; children?: React.ReactNode; }) => { if (i18nKey !== I18nKey.AUTOMATIONS$EMPTY_OPTION_CONVERSATION_DESC) { return children ?? i18nKey; }
return ( <> Start a new conversation and tell OpenHands to{" "} {components?.example ? React.cloneElement( components.example, {}, <> {components.cmd ? React.cloneElement( components.cmd, {}, "Create an automation", ) : null} {components.punct ? React.cloneElement(components.punct, {}, ".") : null} </>, ) : null} </> ); },}));
function renderModal(isOpen = true) { const onClose = vi.fn(); const navigation: NavigationContextValue = { currentPath: "/automations", conversationId: null, isNavigating: false, navigate: vi.fn(), };
render( <NavigationProvider value={navigation}> <AddAutomationModal isOpen={isOpen} onClose={onClose} /> </NavigationProvider>, );
return { onClose };}
describe("AddAutomationModal", () => { it("renders the create instructions content when open", () => { renderModal();
expect(screen.getByTestId("add-automation-modal")).toBeInTheDocument(); expect( screen.getByTestId("automations-create-instructions-example"), ).toHaveTextContent("Create an automation"); expect( screen.getByTestId("automations-create-automation"), ).toHaveTextContent(I18nKey.AUTOMATIONS$CREATE_AUTOMATION_BUTTON); expect( screen.queryByText(I18nKey.AUTOMATIONS$EMPTY_OPTION_PLUGIN_TITLE), ).not.toBeInTheDocument(); });
it("does not render when closed", () => { renderModal(false);
expect(screen.queryByTestId("add-automation-modal")).not.toBeInTheDocument(); });
it("calls onClose when the close button is clicked", async () => { const user = userEvent.setup(); const { onClose } = renderModal();
await user.click(screen.getByTestId("add-automation-modal-close"));
expect(onClose).toHaveBeenCalledTimes(1); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { http, HttpResponse } from "msw";import { AutomationCard } from "#/components/features/automations/automation-card";import { AutomationRunStatus, type Automation, type AutomationRun,} from "#/types/automation";import { useAutomationRunSummaries } from "#/hooks/query/use-automation-run-summaries";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import type { Backend } from "#/api/backend-registry/types";import { server } from "#/mocks/node";import { I18nKey } from "#/i18n/declaration";import type { InterfaceListInsights } from "#/manifests/types";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" }, }),}));
vi.mock("#/context/navigation-context", () => ({ useNavigation: () => ({ navigate: vi.fn(), currentPath: "/" }),}));
vi.mock("#/hooks/use-automation-permissions", () => ({ useAutomationPermissions: () => ({ canView: true, canManage: true, isLoading: false, }), useIsAutomationOwner: () => true,}));
// The pinned package predates the `impact` field, so an entry carrying one is// appended to the real catalog.vi.mock("@openhands/extensions/automations", async (importOriginal) => { const actual = await importOriginal<typeof import("@openhands/extensions/automations")>(); return { ...actual, AUTOMATION_CATALOG: [ ...actual.AUTOMATION_CATALOG, { id: "widget-checker", impact: { basis: "completed-runs", one: "1 widget check completed", other: "{{count}} widget checks completed", }, }, ] as typeof actual.AUTOMATION_CATALOG, };});
const automation: Automation = { id: "automation-1", name: "Async Standup Digest", prompt: "Generate an async standup digest from Slack activity.", enabled: true, trigger: { type: "cron", schedule_human: "Mondays at 09:00" }, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z",};
const insightsSpec = { health: { healthy: "Healthy", failing: "Failing", running: "Running", disabled: "Disabled", neverRun: "Never run", checking: "Checking", }, lastRun: { label: "Last run", never: "Never", justNow: "Just now" }, stats: { runs: "Runs", recentSuccess: "Success", averageDuration: "Avg" },};
function createRun(overrides: Partial<AutomationRun> = {}): AutomationRun { return { id: "run-1", status: AutomationRunStatus.COMPLETED, conversation_id: null, bash_command_id: null, error_detail: null, started_at: "2026-01-02T00:00:00Z", completed_at: "2026-01-02T00:02:00Z", ...overrides, };}
describe("AutomationCard", () => { it("uses the shared extension module interactive class without a resting border", () => { render( <AutomationCard automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} />, );
const card = screen.getByTestId("automation-card-automation-1"); expect(card.className).toContain("extension-module-card-interactive"); expect(card.className).toContain("bg-base-secondary"); expect(card.className).not.toContain("border-[var(--oh-border)]"); });
it("renders title, description, and overflow pills", () => { render( <AutomationCard automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} />, );
expect(screen.getByText("Async Standup Digest")).toBeInTheDocument(); expect( screen.getByText("Generate an async standup digest from Slack activity."), ).toBeInTheDocument(); expect(screen.getByText("Mondays at 09:00")).toBeInTheDocument(); expect( screen.getByTestId("automation-pills-automation-1"), ).toBeInTheDocument(); });
it("renders a play run button and menu actions instead of a toggle switch", async () => { const user = userEvent.setup();
render( <AutomationCard automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} />, );
expect( screen.getByTestId("automation-run-now-automation-1"), ).toHaveAttribute("aria-label", "AUTOMATIONS$RUN_NOW"); expect(screen.getByTestId("automation-run-now-automation-1")).toHaveClass( "size-8", ); expect(screen.queryByRole("switch")).not.toBeInTheDocument();
await user.click( screen.getByRole("button", { name: "AUTOMATIONS$ACTIONS_MENU" }), );
expect(screen.getByText("COMMON$VIEW")).toBeInTheDocument(); expect(screen.getByText("AUTOMATIONS$RUN_NOW")).toBeInTheDocument(); });
it("shows a status strip and sparkline when insights are present", () => { const latestRun = createRun({ started_at: new Date(Date.now() - 10 * 60_000).toISOString(), completed_at: new Date(Date.now() - 8 * 60_000).toISOString(), });
render( <AutomationCard automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} insights={{ spec: insightsSpec satisfies InterfaceListInsights, state: { summary: { total: 4, completedTotal: 4, latestRun, recentRuns: [latestRun], recentSuccessRate: 1, averageDurationMs: 120_000, }, isLoading: false, isError: false, }, }} />, );
expect( screen.queryByTestId("automation-health-badge"), ).not.toBeInTheDocument(); expect( screen.getByTestId("automation-last-run-automation-1"), ).toHaveTextContent("AUTOMATIONS$DETAIL$TIME_MINUTES_AGO"); expect(screen.getByTestId("run-status-icon-completed")).toBeInTheDocument(); expect( screen.getByTestId("automation-activity-automation-1"), ).toBeInTheDocument(); expect(screen.getByTestId("automation-run-stats")).toBeInTheDocument(); expect(screen.getByText("4")).toBeInTheDocument(); expect(screen.getByText("100%")).toBeInTheDocument(); });
it("shows the value statement for its completed runs", () => { // Arrange — provenance joining back to a catalog entry with an impact // declaration, and a summary carrying the lifetime completed count. const latestRun = createRun();
// Act render( <AutomationCard automation={{ ...automation, preset_metadata: { template: { id: "widget-checker", version: "1.0.0", config: {} }, }, }} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} insights={{ spec: insightsSpec satisfies InterfaceListInsights, state: { summary: { total: 5, completedTotal: 4, latestRun, recentRuns: [latestRun], recentSuccessRate: 1, averageDurationMs: 120_000, }, isLoading: false, isError: false, }, }} />, );
// Assert expect( screen.getByTestId("automation-impact-automation-1"), ).toHaveTextContent("4 widget checks completed"); });});
describe("AutomationCard — run phase", () => { const localBackend: Backend = { id: "local-1", name: "Local 1", host: "http://localhost:8000", apiKey: "k", kind: "local", };
const insightAutomation: Automation = { id: "auto-with-active-run", name: "Digest", prompt: null, enabled: true, trigger: { type: "cron", schedule_human: "cron" }, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", };
const insightsSpec: InterfaceListInsights = { health: { healthy: "Healthy", failing: "Failing", running: "Running", disabled: "Disabled", neverRun: "Never run", checking: "Checking", }, lastRun: { label: "Last run", never: "Never", justNow: "Just now" }, stats: { runs: "Runs", recentSuccess: "Success", averageDuration: "Duration", }, };
beforeEach(() => { __resetActiveStoreForTests(); setRegisteredBackends([localBackend]); setActiveSelection({ backendId: localBackend.id }); });
afterEach(() => { __resetActiveStoreForTests(); });
function Harness() { const byId = useAutomationRunSummaries([insightAutomation]); return ( <AutomationCard automation={insightAutomation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} insights={{ spec: insightsSpec, state: byId.get(insightAutomation.id) }} /> ); }
function renderHarness() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); return render( <QueryClientProvider client={queryClient}> <ActiveBackendProvider> <Harness /> </ActiveBackendProvider> </QueryClientProvider>, ); }
it("shows the active run's phase using only the run-summaries fetch insights already makes — no extra request", async () => { // Arrange: count every hit to the runs endpoint the card's insights // already fetch (via useAutomationRunSummaries) �� if displaying the // phase required a second request, this would be > 1. let callCount = 0; server.use( http.get("*/api/automation/v1/:id/runs", () => { callCount += 1; return HttpResponse.json({ runs: [ { id: "run-active", status: AutomationRunStatus.RUNNING, conversation_id: null, bash_command_id: null, error_detail: null, phase_code: "running_agent", phase_label: null, phase_updated_at: null, started_at: "2026-01-01T09:00:00Z", completed_at: null, }, ], total: 1, }); }), );
// Act renderHarness();
// Assert: the phase renders ... await screen.findByText(I18nKey.AUTOMATIONS$DETAIL$PHASE_RUNNING_AGENT); // ... and exactly one request was made — the pre-existing insights // fetch, not a new one just for the phase. expect(callCount).toBe(1); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __resetActiveStoreForTests, setActiveSelection, setRegisteredBackends,} from "#/api/backend-registry/active-store";import type { Backend } from "#/api/backend-registry/types";import { getCloudOrganizationMe, getCloudOrganizations,} from "#/api/cloud/organization-service.api";import { AutomationListRow } from "#/components/features/automations/automation-list-row";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import { I18nKey } from "#/i18n/declaration";import type { Automation } from "#/types/automation";
// `automation-list-row.test.tsx` mocks the permission hooks wholesale. These// tests run the real hooks against a mocked `/me` service so the// creator-vs-manager rule for the enabled toggle is exercised end to end.vi.mock("#/api/cloud/organization-service.api", async (importOriginal) => ({ ...(await importOriginal< typeof import("#/api/cloud/organization-service.api") >()), getCloudOrganizations: vi.fn(), getCloudOrganizationMe: vi.fn(),}));
vi.mock("#/context/navigation-context", () => ({ useNavigation: () => ({ navigate: vi.fn(), currentPath: "/" }),}));
const ORG_ID = "org-1";
const cloudBackend: Backend = { id: "cloud-1", name: "Production", host: "https://app.all-hands.dev", apiKey: "bearer-key", kind: "cloud",};
function makeAutomation(overrides: Partial<Automation> = {}): Automation { return { id: "auto-1", name: "Teammate digest", prompt: "Summarize", trigger: { type: "cron", schedule: "0 9 * * *", schedule_human: "Daily at 09:00", }, enabled: true, user_id: "creator-user", created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", ...overrides, };}
function renderRow(automation: Automation) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); return render( <QueryClientProvider client={queryClient}> <ActiveBackendProvider> <AutomationListRow automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} /> </ActiveBackendProvider> </QueryClientProvider>, );}
async function openActionsMenu(user: ReturnType<typeof userEvent.setup>) { // Run now only renders once the caller's permissions have resolved. await screen.findByTestId("automation-run-now-auto-1"); await user.click(screen.getByLabelText(I18nKey.AUTOMATIONS$ACTIONS_MENU));}
beforeEach(() => { window.localStorage.clear(); __resetActiveStoreForTests(); setRegisteredBackends([cloudBackend]); setActiveSelection({ backendId: cloudBackend.id, orgId: ORG_ID }); vi.mocked(getCloudOrganizations).mockResolvedValue({ items: [], currentOrgId: null, }); // A manager (has manage_automations) who did not create the automation. vi.mocked(getCloudOrganizationMe).mockResolvedValue({ orgId: ORG_ID, userId: "manager-user", role: "admin", permissions: ["view_automations", "manage_automations"], });});
afterEach(() => { window.localStorage.clear(); __resetActiveStoreForTests();});
describe("AutomationListRow — non-creator manager", () => { it("offers Turn off and Delete on an enabled automation", async () => { // Arrange const user = userEvent.setup(); renderRow(makeAutomation({ enabled: true }));
// Act await openActionsMenu(user);
// Assert expect( screen.getByRole("button", { name: I18nKey.AUTOMATIONS$TURN_OFF }), ).toBeInTheDocument(); expect( screen.getByRole("button", { name: I18nKey.AUTOMATIONS$DELETE }), ).toBeInTheDocument(); });
it("hides Turn on but keeps Delete on a disabled automation", async () => { // Arrange const user = userEvent.setup(); renderRow(makeAutomation({ enabled: false }));
// Act await openActionsMenu(user);
// Assert expect( screen.queryByRole("button", { name: I18nKey.AUTOMATIONS$TURN_ON }), ).not.toBeInTheDocument(); expect( screen.getByRole("button", { name: I18nKey.AUTOMATIONS$DELETE }), ).toBeInTheDocument(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it, vi } from "vitest";import { AutomationListRow } from "#/components/features/automations/automation-list-row";import { AutomationRunStatus, type Automation, type AutomationRun,} from "#/types/automation";import type { InterfaceListInsights } from "#/manifests/types";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" }, }),}));
vi.mock("#/context/navigation-context", () => ({ useNavigation: () => ({ navigate: vi.fn(), currentPath: "/" }),}));
vi.mock("#/hooks/use-automation-permissions", () => ({ useAutomationPermissions: () => ({ canView: true, canManage: true, isLoading: false, }), useIsAutomationOwner: () => true,}));
// The pinned package predates the `impact` field, so an entry carrying one is// appended to the real catalog.vi.mock("@openhands/extensions/automations", async (importOriginal) => { const actual = await importOriginal<typeof import("@openhands/extensions/automations")>(); return { ...actual, AUTOMATION_CATALOG: [ ...actual.AUTOMATION_CATALOG, { id: "widget-checker", impact: { basis: "completed-runs", one: "1 widget check completed", other: "{{count}} widget checks completed", }, }, ] as typeof actual.AUTOMATION_CATALOG, };});
const automation: Automation = { id: "automation-1", name: "GitHub PR Reviewer", prompt: "Review pull requests.", enabled: true, trigger: { type: "event", on: "pull_request.opened", source: "github", }, repository: "acme/repo", model: "Claude", created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z",};
const insightsSpec = { health: { healthy: "Healthy", failing: "Failing", running: "Running", disabled: "Disabled", neverRun: "Never run", checking: "Checking", }, lastRun: { label: "Last run", never: "Never", justNow: "Just now" }, stats: { runs: "Runs", recentSuccess: "Success", averageDuration: "Avg" },};
function createRun(overrides: Partial<AutomationRun> = {}): AutomationRun { return { id: "run-1", status: AutomationRunStatus.COMPLETED, conversation_id: null, bash_command_id: null, error_detail: null, started_at: "2026-01-02T00:00:00Z", completed_at: "2026-01-02T00:02:00Z", ...overrides, };}
describe("AutomationListRow", () => { it("renders title, trigger meta, and action icons in a two-line list row", () => { render( <AutomationListRow automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} />, );
expect( screen.getByTestId("automation-list-row-automation-1"), ).toBeInTheDocument(); expect(screen.getByText("GitHub PR Reviewer")).toBeInTheDocument(); expect(screen.getByText("pull_request.opened")).toBeInTheDocument(); expect(screen.getByText("GitHub")).toBeInTheDocument(); expect( screen.queryByTestId("automation-pills-automation-1"), ).not.toBeInTheDocument(); expect( screen.getByTestId("automation-run-now-automation-1"), ).toHaveAttribute("aria-label", "AUTOMATIONS$RUN_NOW"); expect(screen.getByTestId("automation-run-now-automation-1")).toHaveClass( "size-8", ); });
it("shows last-run status, relative time, and a sparkline when insights are present", () => { const latestRun = createRun({ started_at: new Date(Date.now() - 10 * 60_000).toISOString(), completed_at: new Date(Date.now() - 8 * 60_000).toISOString(), });
render( <AutomationListRow automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} insights={{ spec: insightsSpec satisfies InterfaceListInsights, state: { summary: { total: 4, completedTotal: 4, latestRun, recentRuns: [latestRun], recentSuccessRate: 1, averageDurationMs: 120_000, }, isLoading: false, isError: false, }, }} />, );
expect( screen.getByTestId("automation-last-run-automation-1"), ).toHaveTextContent("AUTOMATIONS$DETAIL$TIME_MINUTES_AGO"); expect(screen.getByTestId("run-status-icon-completed")).toBeInTheDocument(); expect( screen.getByTestId("automation-activity-automation-1"), ).toBeInTheDocument(); });
it("shows the value statement in the meta line", () => { // Arrange — provenance joining back to a catalog entry with an impact // declaration, and a summary carrying the lifetime completed count. const latestRun = createRun();
// Act render( <AutomationListRow automation={{ ...automation, preset_metadata: { template: { id: "widget-checker", version: "1.0.0", config: {} }, }, }} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} insights={{ spec: insightsSpec satisfies InterfaceListInsights, state: { summary: { total: 5, completedTotal: 4, latestRun, recentRuns: [latestRun], recentSuccessRate: 1, averageDurationMs: 120_000, }, isLoading: false, isError: false, }, }} />, );
// Assert expect( screen.getByTestId("automation-impact-automation-1"), ).toHaveTextContent("4 widget checks completed"); });
it("opens the actions menu without triggering row navigation handlers", async () => { const user = userEvent.setup();
render( <AutomationListRow automation={automation} onToggle={vi.fn()} onRunNow={vi.fn()} onExport={vi.fn()} onDelete={vi.fn()} />, );
await user.click( screen.getByRole("button", { name: "AUTOMATIONS$ACTIONS_MENU" }), );
expect(screen.getByText("COMMON$VIEW")).toBeInTheDocument(); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it, vi } from "vitest";import { AutomationViewToggle } from "#/components/features/automations/automation-view-toggle";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }),}));
describe("AutomationViewToggle", () => { it("opens a menu from the icon trigger and switches to list view", async () => { const user = userEvent.setup(); const onChange = vi.fn();
render(<AutomationViewToggle view="grid" onChange={onChange} />);
const trigger = screen.getByTestId("automations-view-toggle"); expect(trigger).toHaveClass("size-9"); expect(trigger).toHaveAttribute("aria-haspopup", "menu");
await user.click(trigger); await user.click(screen.getByTestId("automations-view-toggle-list"));
expect(onChange).toHaveBeenCalledWith("list"); });
it("does not open the menu or fire onChange when disabled", async () => { // Arrange const user = userEvent.setup(); const onChange = vi.fn(); render( <AutomationViewToggle view="grid" onChange={onChange} disabled />, ); const trigger = screen.getByTestId("automations-view-toggle");
// Act — try to open the menu await user.click(trigger);
// Assert — menu items never render and onChange stays untouched expect(trigger).toBeDisabled(); expect( screen.queryByTestId("automations-view-toggle-list"), ).not.toBeInTheDocument(); expect(onChange).not.toHaveBeenCalled(); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import { describe, it, expect, vi } from "vitest";import { render, screen, fireEvent } from "@testing-library/react";import { BackendUnavailable } from "#/components/features/automations/backend-not-configured";import { I18nKey } from "#/i18n/declaration";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => { const translations: Record<string, string> = { [I18nKey.AUTOMATIONS$BACKEND_UNAVAILABLE_TITLE]: "Automations Unavailable", [I18nKey.AUTOMATIONS$BACKEND_UNAVAILABLE_MESSAGE]: "The automations backend is not available right now.", [I18nKey.AUTOMATIONS$BACKEND_UNAVAILABLE_RETRY]: "Retry", }; return translations[key] || key; }, }),}));
describe("BackendUnavailable", () => { it("renders the unavailable message", () => { const onRetry = vi.fn(); render(<BackendUnavailable onRetry={onRetry} />);
expect(screen.getByText("Automations Unavailable")).toBeInTheDocument(); expect( screen.getByText("The automations backend is not available right now."), ).toBeInTheDocument(); });
it("displays the retry button", () => { const onRetry = vi.fn(); render(<BackendUnavailable onRetry={onRetry} />);
const retryButton = screen.getByRole("button", { name: "Retry" }); expect(retryButton).toBeInTheDocument(); });
it("calls onRetry when retry button is clicked", () => { const onRetry = vi.fn(); render(<BackendUnavailable onRetry={onRetry} />);
const retryButton = screen.getByRole("button", { name: "Retry" }); fireEvent.click(retryButton);
expect(onRetry).toHaveBeenCalledTimes(1); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import { render, screen } from "@testing-library/react";import { describe, expect, it } from "vitest";import { buildAutomationMetadataPills } from "#/components/features/automations/build-automation-pills";import type { SkillCardPill } from "#/components/features/skills/skill-card-pill-row";import type { Automation } from "#/types/automation";
function buildAutomation(overrides: Partial<Automation> = {}): Automation { return { id: "automation-1", name: "Triage", prompt: "Triage the issue.", enabled: true, trigger: { type: "event", on: "issue.updated", source: "linear" }, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", ...overrides, };}
function renderPills(pills: SkillCardPill[]) { render( <div> {pills.map((pill) => ( <span key={pill.id} data-testid={`pill-${pill.id}`}> {pill.node} </span> ))} </div>, );}
describe("buildAutomationMetadataPills", () => { it("puts the event and source on separate pills", () => { const pills = buildAutomationMetadataPills(buildAutomation(), "unused");
expect(pills.map((pill) => pill.id)).toEqual([ "event-trigger", "event-source", ]);
renderPills(pills);
expect(screen.getByTestId("pill-event-trigger")).toHaveTextContent( "issue.updated", ); expect(screen.getByTestId("pill-event-trigger")).not.toHaveTextContent( "linear", ); expect(screen.getByTestId("pill-event-source")).toHaveTextContent("Linear"); expect(screen.getByTestId("pill-event-source").firstElementChild).toHaveClass( "py-0.5", ); expect(screen.getByTestId("automation-source-logo")).toBeInTheDocument(); });
it("renders a fallback icon when the source is not in the catalog", () => { renderPills( buildAutomationMetadataPills( buildAutomation({ trigger: { type: "event", on: "alert.fired", source: "custom-pager" }, }), "unused", ), );
expect(screen.getByTestId("pill-event-source")).toHaveTextContent( "Custom-Pager", ); expect(screen.getByTestId("automation-source-logo")).toBeInTheDocument(); });
it("omits the source pill when the event has no source", () => { const pills = buildAutomationMetadataPills( buildAutomation({ trigger: { type: "event", on: "pull_request.opened" }, }), "unused", );
expect(pills.map((pill) => pill.id)).toEqual(["event-trigger"]); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import React from "react";import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { NavigationProvider, type NavigationContextValue,} from "#/context/navigation-context";import { CreateInstructions } from "#/components/features/automations/create-instructions";import { I18nKey } from "#/i18n/declaration";import { useConversationStore } from "#/stores/conversation-store";import * as telemetry from "#/services/telemetry";
vi.mock("#/hooks/query/use-settings", () => ({ useSettings: () => ({ data: { user_consents_to_analytics: true } }),}));
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => { const translations: Record<string, string> = { [I18nKey.AUTOMATIONS$CREATE_AUTOMATION_BUTTON]: "Create Automation", [I18nKey.AUTOMATIONS$CREATE_AUTOMATION_PROMPT]: "Create an automation", [I18nKey.AUTOMATIONS$CREATE_INSTRUCTIONS_GUIDANCE]: "Include what the automation should do, when it should run, and where to send the results.", }; return translations[key] || key; }, }), Trans: ({ i18nKey, components, }: { i18nKey: string; components?: Record<string, React.ReactElement>; }) => { if (i18nKey !== I18nKey.AUTOMATIONS$EMPTY_OPTION_CONVERSATION_DESC) { return i18nKey; }
return ( <> Start a new conversation and tell OpenHands to{" "} {components?.example ? React.cloneElement( components.example, {}, <> {components.cmd ? React.cloneElement( components.cmd, {}, "Create an automation", ) : null} {components.punct ? React.cloneElement(components.punct, {}, ".") : null} </>, ) : null} </> ); },}));
function renderCreateInstructions() { const value: NavigationContextValue = { currentPath: "/automations", conversationId: null, isNavigating: false, navigate: vi.fn(), };
const result = render( <NavigationProvider value={value}> <CreateInstructions /> </NavigationProvider>, );
return { ...result, navigate: value.navigate };}
describe("CreateInstructions", () => { let captureMock: ReturnType<typeof vi.spyOn>;
beforeEach(() => { captureMock = vi .spyOn(telemetry, "trackEvent") .mockResolvedValue(undefined); useConversationStore.setState({ messageToSend: null }); });
afterEach(() => { captureMock.mockRestore(); });
it("captures automation_created_button with the active backend kind when Create Automation is clicked", async () => { const user = userEvent.setup(); renderCreateInstructions();
await user.click(screen.getByTestId("automations-create-automation"));
expect(captureMock).toHaveBeenCalledWith( "automation_created_button", expect.objectContaining({ backend_kind: "local" }), ); });
it("navigates to conversations with a prefilled prompt when Create Automation is clicked", async () => { const user = userEvent.setup(); const setMessageToSend = vi.fn(); useConversationStore.setState({ setMessageToSend }); const { navigate } = renderCreateInstructions();
await user.click(screen.getByTestId("automations-create-automation"));
expect(navigate).toHaveBeenCalledWith("/conversations"); await waitFor(() => { expect(setMessageToSend).toHaveBeenCalledWith("Create an automation"); }); });});.agents/skills/custom-codereview-guide.mdAdded+201
.agents/skills/pr-design-doc/SKILL.mdAdded+168
.agents/skills/pr-design-doc/references/html-craft.mdAdded+322
.agents/skills/release.mdAdded+110
.gitattributes+8
.github/pr-assets/pr-16268-02-lightbox-open.pngAdded

Large File Pointer Details
- SHA256: 290462f47a19b9068b50dd239d134728acadf719356f8822ff6cece05c7d16f7
- Pointer size: 131 Bytes
- Size of remote file: 323 kB
.github/pr-assets/pr-16605-test-results.pngAdded

Large File Pointer Details
- SHA256: 21d841229bb786493fcc05019f5c80d30d8e159df437691c0010699e7a9d4335
- Pointer size: 131 Bytes
- Size of remote file: 223 kB
.github/pr-assets/pr-16676-01-list.pngAdded

Large File Pointer Details
- SHA256: eb03768fbc1ae545cbbd9729b3cc2b47bac81ac060a42a3a45fe1e3859529766
- Pointer size: 131 Bytes
- Size of remote file: 132 kB
.github/pr-assets/pr-16676-02-templates.pngAdded

Large File Pointer Details
- SHA256: 944b74529e6354b31e1f11a603b27bec1a5b3dd9d4ef3c426844b630159aa681
- Pointer size: 131 Bytes
- Size of remote file: 141 kB
.github/pr-assets/pr-16676-04-edit-modal.pngAdded

Large File Pointer Details
- SHA256: 9cd4a0f47d9e1160f6af61c085a2aa7c8ba3e95bdd5aa28005a45917936c091e
- Pointer size: 131 Bytes
- Size of remote file: 103 kB
.github/pr-assets/pr-16860-01-skills-default.pngAdded

Large File Pointer Details
- SHA256: dd2806c5c395b80901182cbbaceeb72ff0c50dba4ed1b7c5883f20f71c891c62
- Pointer size: 131 Bytes
- Size of remote file: 202 kB
.github/pr-assets/pr-16860-02-recommended-facet.pngAdded

Large File Pointer Details
- SHA256: fb6cb1e3c785167c74e21d4585fb4905b09c285f48a3dec65fc435548f043731
- Pointer size: 131 Bytes
- Size of remote file: 204 kB
__tests__/api/acp-service/acp-service.api.test.tsAdded+130
__tests__/api/agent-profiles-service/profile-field-support.test.tsAdded+59
__tests__/api/backend-registry/active-store.test.tsAdded+263
__tests__/api/backend-registry/health-store.test.tsAdded+111
__tests__/api/backend-registry/last-conversation-store.test.tsAdded+67
__tests__/api/backend-registry/storage.test.tsAdded+365
__tests__/api/backend-registry/url-selection.test.tsAdded+166
__tests__/api/cloud/conversation-create.test.tsAdded+128
__tests__/api/cloud/conversation-delete.test.tsAdded+51
__tests__/api/cloud/conversation-download.test.tsAdded+63
__tests__/api/cloud/conversation-pause.test.tsAdded+93
__tests__/api/cloud/conversation-public-flag.test.tsAdded+73
__tests__/api/cloud/conversation-runtime-info.test.tsAdded+135
__tests__/api/cloud/conversation-title.test.tsAdded+84
__tests__/api/cloud/fetch-test-utils.tsAdded+33
__tests__/api/cloud/git-service.test.tsAdded+69
__tests__/api/cloud/organization-me.test.tsAdded+88
__tests__/api/cloud/organization-service.test.tsAdded+144
__tests__/api/cloud/profiles-service.test.tsAdded+217
__tests__/api/cloud/provider-connections-service.test.tsAdded+140
__tests__/api/cloud/proxy.test.tsAdded+272
__tests__/api/cloud/sandbox-service.test.tsAdded+59
__tests__/api/cloud/secrets-service.test.tsAdded+179
__tests__/api/cloud/settings-service.test.tsAdded+200
__tests__/api/cloud/skills-service.test.tsAdded+136
__tests__/api/mcp-health/mcp-health-store.test.tsAdded+64
__tests__/api/mcp-health/probe-mcp-server-health.test.tsAdded+179
__tests__/api/mcp-service/mcp-service.api.test.tsAdded+395
__tests__/api/runtime-service/agent-server-runtime-service.test.tsAdded+307
__tests__/components/analytics/telemetry-consent-banner.test.tsxAdded+198
__tests__/components/automations/add-automation-modal.test.tsxAdded+107
__tests__/components/automations/automation-card.test.tsxAdded+368
__tests__/components/automations/automation-list-row.permissions.test.tsxAdded+145
__tests__/components/automations/automation-list-row.test.tsxAdded+225
__tests__/components/automations/automation-view-toggle.test.tsxAdded+46
__tests__/components/automations/backend-not-configured.test.tsxAdded+49
__tests__/components/automations/build-automation-pills.test.tsxAdded+82
__tests__/components/automations/create-instructions.test.tsxAdded+123