Files
PaperClipAI/ui/src/pages/CompanyEnvironments.test.tsx
T
Devin FoleyandPaperclip 21bf7ebcee feat(connectors): connect Tailscale networks to SSH environments (#20617)
## Thinking Path

> - Paperclip manages work for AI agents.
> - SSH environments run tasks on computers that users own.
> - A Paperclip server needs network access before it can reach a
private computer.
> - A reusable Tailscale connection belongs in Connectors.
> - Connected machines should become choices in the existing SSH
environment form.
> - This change connects a tailnet and resolves selected machines
through a private network client.
> - Agents retain their choice of harness and AI account.

## Linked Issues or Issue Description

**Subsystem affected**

Connectors, environment settings, SSH execution, company secret storage,
and runtime packaging.

**Problem or motivation**

Entering a Tailscale address in the SSH form does not connect the
Paperclip server to that tailnet. Requiring a separate device key for
every environment also duplicates network setup.

**Proposed solution**

Add a Tailscale Connector with **Connect Tailscale Network**. Use
brokered OAuth consent to enroll one private network client per
connection. Let SSH environments select a connected network and stable
machine identity. Preserve the enrolled node state through the company
vault so a restart does not reuse the one-time token.

**Alternatives considered**

A separate Tailscale environment type would duplicate SSH behavior and
mix network access with harness selection. This change uses the existing
`ssh` driver. Related #15648 adds OAuth client credentials and a health
check; this change uses user consent and supplies outbound task
execution. Related #11743 concerns HTTPS brokering.

**Roadmap alignment**

This extends the existing Connected Apps, environment, and Personal &
Shared AI Accounts capabilities. This PR is stacked on #21248, which
provides SSH account selection independently of Tailscale. The hosted
OAuth broker is a companion control-plane change.

## What Changed

- Preserve Cloud reauthentication in the current browser tab. Explain
canceled or failed consent in the connector and offer a retry of the
same authorized saved connection.
- Record Cloud enrollment starts initiated through the Tailscale
connector in the company activity log.
- Check install-preparation descendant liveness through the kernel
process table in the Runner support test. Keep the direct child’s strict
reaping assertion and reject any non-zombie descendant.
- Align the application image stage contract with the Tailscale client
stage after the upstream Runner-image refactor. Keep the exact stage
list and check every application stage, including `tailscale-client`,
for prohibited Runner compiler commands.
- Group Tailscale consent, discovery, daemon lifecycle, pairing, and
deletion under `server/src/services/connectors/tailscale/`, with their
service tests. Update existing route, runtime, environment, vault, and
company-deletion imports. Keep the existing contracts, authorization,
audit, and transaction owners.
- Handle early stdin closure in the Kubernetes real-shell test helper.
Stop the input stream on `EPIPE`, preserve nonzero child exits, and
reject a zero exit when input was lost. Add two real-process regression
cases. Production transfer code and confinement checks are unchanged.
- Read configured Tailscale executable paths when a client starts, after
supported `.env` loading. Keep explicit command overrides available.
- Discard pending pairing results after switching to Direct SSH or
closing the form. Retain the existing company, connection, machine, and
port checks.
- Store network credentials with an immutable server-owned purpose from
their first vault row. Exclude them from generic catalogs, bindings,
environment projection, and value reads. Use a dedicated audited server
consumer for pinned connector reads. Block unclassified legacy
serialized node state at the same value boundary. Keep SSH private-key
binding separate from connector credentials.
- Gate network queries and setup on verified local-implicit or
instance-admin access. Hide Tailscale catalog rows for other members,
show an admin requirement on direct setup navigation, and avoid device
discovery before management access is known.
- Keep failed-client cleanup in the network manager. A failed request
cannot disconnect a newer retry for the same identity; explicit
connector disconnect and enrollment retirement still stop their
networks.
- Check for readable Ed25519, ECDSA, or RSA host public keys before
pairing edits `authorized_keys`. Print a known-hosts entry for every
available key, or fail before changing authorized keys if none are
available.
- Return self-hosted Cloud enrollment to the Tailscale connector. Save
the unprefixed setup path and let the shared callback add the verified
company prefix. Keep external and unrelated destinations rejected.
- Hide pairing instructions after an SSH port change. Ignore late
key-selection results for the old port. Operators prepare again for
matching known-hosts output.
- Retire connector references before deleting a company or its vault
credential. Stop company daemons after the database commit. Keep failed
secret retirement retryable and prevent late node-state writes from
restoring deleted connections. Discard retired state without blocking
behind the vault deletion lock.
- Reload a mismatched credential before replacing a ready daemon.
Recheck the active entry and manager generation after the read. An older
request cannot stop a newer healthy socket or cross shutdown.
- Pin connector credentials to the exact vault version and SHA-256
digest recorded by trusted enrollment and node-state writes. Ignore
generic secret rotations. Advance both fields with a compare-and-set
guard. Reject unpinned or tampered credentials before network startup.
- Save an explicit Direct SSH selection and clear old Tailscale fields
after config merging. Preserve the operator's entered direct host.
- Route all Tailscale SSH runtime access through the connection service
after SSH-key loading. Pin access to the environment's saved connector
identity and recheck after device discovery. Remove standalone key-based
daemon startup and reject raw enrollment keys or credential-only network
configurations. Align the shared config type and SDK pins.
- Correct two E2E assumptions exposed during connector qualification.
Keep the two-window chat fixture stale until its own mutation. Validate
the original failed run and its permitted write-revocation timestamp in
the legacy recovery browser test.
- Add the Tailscale Connector page, catalog entry, OAuth return flow,
connected-network management, device discovery, and disconnect. Document
all six routes in OpenAPI and the API reference, including their
instance-admin requirement.
- Add company-scoped connection storage in `0480_lazy_lethal_legion`,
trusted credential version/digest fields in `0481_round_pet_avengers`,
and server-owned secret purpose/backfill in
`0482_aberrant_rumiko_fujikawa`. Generate all three migrations through
the maintained command and retain the five newest snapshots.
- Add machine pairing that generates a fresh SSH key per request, stores
its private half in the company vault, and uses the generated public
half in the install command. Do not trust editable saved metadata.
Preserve existing authorized keys, including a file without a final
newline. Keep SSH username, workspace, and trusted host keys explicit.
- Use the existing SSH driver. Resolve the machine's current address
from its stable device ID. Reject disconnected, removed, offline, and
wrong-company selections.
- Hide Network when Direct is the only option. Select a sole connected
tailnet automatically and hide its selector. Remove the requested setup
helper copy. Do not restrict the harness to Claude.
- Run a private userspace Tailscale daemon with a separate socket.
Persist its node state before execution. Restore it after restart, bound
startup, serialize reconnect cleanup, and close it during server
shutdown.
- Guard OAuth completion with a durable attempt marker. Disconnect and
newer authorization invalidate older callbacks. Close replaced daemons
and remove cancelled enrollment secrets without changing newer
connection state.
- Preserve SSH host verification and tailnet-specific session identity.
Honor the configured Tailscale executable path, including spaces and
OpenSSH percent escaping.
- Package checksum-pinned Tailscale clients and their license in the
standard runtime image. Exercise the client build stage in PR CI and
include it in image smoke checks.

## Verification

- Merge status: all CI and image checks pass, and current-head Apex is
5/5 with no unresolved comments. GitHub rejected a direct merge because
the active master ruleset requires code-owner approval for
`.github/workflows/pr-trusted.yml`. The [CODEOWNERS workflow
pattern](https://github.com/paperclipai/paperclip/blob/master/.github/CODEOWNERS#L3)
applies; eligible maintainers already have review requests. Auto-merge
is enabled with the squash method for the verified head. The PR remains
open pending that required approval; no branch policy was bypassed.
- Final revision: `fdb29b2cc366f4945b7f4c3e2b2d25070329a21b`, including
master `999709b0a6dd416af335b5debded13e1de7fcb7a`. [Final CI
verification
passed](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132213508320).
All required checks pass, all applicable test/build gates are green, and
the branch is mergeable against master. SSH prerequisite #21248 and
Cloud broker paperclipai/paperclip-cloud#1314 are already merged.
- [Apex reviewed this exact revision at
5/5](https://github.com/paperclipai/paperclip/pull/20617#issuecomment-6776629437).
There are no unresolved review threads. The PR is classified as Critical
impact.
- Final image qualification passes for the [application Runner
path](https://github.com/paperclipai/paperclip/actions/runs/43518584522/job/132206784267),
[amd64 Runner
image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296198),
and [arm64 Runner
image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296156).
Typechecks, Runner support, native/Rust tests, provider tests,
serialized-server suites, browser shards, and the remaining applicable
CI checks pass. This is source/image CI qualification, not a production
rollout.
- The last master conflict affected only Docker stage declarations and
their boundary test. Both the checksum-pinned Tailscale stage and
upstream `runner-lockfile` guard are retained, including the upstream
`deps` inheritance. The Tailscale client stage is byte-identical. All
180 cases across five Docker/image contract suites pass locally, along
with server and UI typechecks. The maintained 543-input SDK check has no
drift. Runtime and lock pins are unchanged. Secret/PII and whitespace
scans pass.
- Seven OAuth regression cases failed before the fixes. The current-tab
test uses the real handoff helper, checks that the session is stored
before reauthentication navigation, mounts the shared return page,
resumes consent, and verifies handoff cleanup. Callback tests check
trusted saved-connection context, fixed safe outcomes, failure audit
metadata, denied membership and expired-state rejection, JSON API
errors, and no provider text in browser returns. UI retries require a
connection in the current company's catalog. All 80 OAuth
route/service/UI/shared-handoff cases pass; server and UI source/test
typechecks pass.
- [Server shard 4/12 on the prior
refresh](https://github.com/paperclipai/paperclip/actions/runs/43510727031/job/132180301436)
passed 2,784 cases and skipped 21, then failed a reassignment fixture's
`TRUNCATE companies CASCADE` cleanup with PostgreSQL `40P01`. Its
automatic retry found the surviving `REA` prefix. The unchanged test
passes all three cases locally. A controlled reader/cleanup overlap
reproduces the same deadlock, but the exact competing CI query was not
logged. Each case now has a distinct company prefix and identifier; the
owned database is removed at suite end. The three test bodies and
assertions are byte-identical. Eight local reassignment/lock-release
cases pass, and the [final server shard 4/12
passes](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132207159392).
Production reassignment logic, deadlines, and retries are unchanged.
- The initial master integration passed 330 cases across 17 suites.
Coverage includes connector state, device discovery, network lifecycle,
pairing, routes, SSH binding and exports, environment persistence, and
connector UI. All three unpublished migrations were regenerated after
master's `0479_short_darkstar`: `0480_lazy_lethal_legion`,
`0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa`. Each SQL
body is byte-identical to its earlier unpublished migration. Generated
snapshots preserve existing master tables and add only the intended
Tailscale table and secret-purpose column. Exactly five snapshots
remain, 0478–0482. Numbering, safety, compatibility, and snapshot-drift
checks pass. The later Docker refresh did not alter this migration
sequence.
- Earlier attempts remain part of the verification record. On `1c020a0`,
Rust cache restoration and server shard 5/12 were interrupted by
shutdown signals, Runner shard 2/3 lost communication with no
retrievable log, and an amd64 provider download failed with npm
`ECONNRESET`. Same-head retries recovered, without establishing the
cause of the communication loss. Later superseded runs also had
cancellations with incomplete logs. These interrupted attempts are not
counted as passes. The final revision has fresh successful CI.
- Local platform limits remain recorded. The Kubernetes suite on macOS
passed 191 cases, failed 12 Linux `/proc/self/fd` transfer cases, and
skipped four Linux-only cases. Unchanged source reproduced the same 12
failures. An initial run also lacked provider dependencies until the
maintained preparation command installed them. Those local attempts are
not green qualification. Final Linux provider CI passes. Local Docker
qualification was unavailable; final image checks passed in CI.
- Before PR separation, a live tailnet/SSH Claude Code task completed on
Ubuntu ARM64 without provider login for the remote user. The selected
Paperclip subscription ran it, wrote the expected file, posted
completion, and marked the task done. File contents and private runtime
cleanup were checked. This is prior live evidence; the final revision
was not live-retested. Other providers have automated coverage only.
Hosted registration for unrelated tailnets and production concurrency
remain qualification limits below.
- The Superagent security and supply-chain reports remain neutral and
inconclusive. Earlier attempts to restart the failed security scan
returned HTTP 404. Supply-chain intelligence lacked coverage for
extracted pinned dependencies and the shared workflow reference. These
reports do not establish successful security qualification. The required
CI and review gates pass; this external coverage gap remains disclosed.

## Risks

- The Superagent security and supply-chain reports are inconclusive. The
security scan re-run request returned HTTP 404, and the supply-chain
scanner lacks coverage for the extracted dependencies and shared
workflow reference. These neutral results are not successful security
qualification.
- The server-owned secret purpose is internal database metadata, not an
HTTP-writable field. The generic secret service owns enforcement so
direct API reads and runtime projection share the same restriction.
Previously copied node state remains valid outside Paperclip until the
enrolled device is revoked in Tailscale; a local disconnect cannot stop
an external copy.
- Tailscale network configurations now require a connected Connector and
selected machine. The unreleased key-only path is removed; any saved
configuration from that path needs Connector setup.
- The connector remains a pilot. The local test used an OAuth app
registered in the consenting user's tailnet. Qualify hosted app
registration for unrelated customer tailnets before general
availability.
- This implementation supports one serving process per instance.
Concurrent replicas need exclusive ownership of the persisted network
identity before production rollout. Preserve the database and company
vault master key across restarts.
- Each machine-pairing preparation creates a new vault secret. Unused
generated keys follow the existing secret deletion lifecycle. A saved
SSH key remains available as an explicit choice.
- Apply additive migrations `0480_lazy_lethal_legion`,
`0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa` before
application rollout. The new credential version and digest columns are
nullable. Existing unpinned connections require fresh OAuth consent; the
migration deliberately does not trust or backfill a generic secret
value. Regenerate or renumber migrations if master advances the sequence
before merge.
- The target needs an SSH server, its chosen harness, and allowed
tailnet access. A reachable network does not grant SSH or provider
authorization. Pairing reads standard `/etc/ssh` host-public-key files;
custom host-key locations require manual known-hosts configuration.
- Roll back the application revision to remove new entry points.
Existing connection secrets and registered Tailscale nodes retain their
separate lifecycle. Do not drop the table or delete node state as part
of an application rollback.
- Production qualification still needs denied-policy, revocation,
cancellation, and deployment-overlap checks. Local Docker and a
production deployment were not performed.

## Model Used

OpenAI Codex, gpt-6.1-sol, xhigh reasoning, with local code execution
and tool use.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used
- [x] I have checked ROADMAP.md and this extends existing connector and
environment features
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR using the feature request fields
- [x] I have not referenced internal issues, local URLs, or private
machine identifiers
- [x] My branch name describes the change
- [x] I have run focused tests locally and they pass
- [x] I have added tests for new behavior and failure paths
- [x] I have updated documentation
- [x] I have documented migration and runtime risks
- [x] All Paperclip CI gates are green
- [ ] Required code-owner approval received for the workflow change
- [x] Greptile Apex is 5/5 on the final head with no unresolved comments
- [x] I will address CI and review findings before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-13 15:15:43 -08:00

2045 lines
83 KiB
TypeScript

// @vitest-environment jsdom
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { CompanyEnvironments } from "./CompanyEnvironments";
import { ApiError } from "@/api/client";
import { tailscaleApi } from "@/api/tailscale";
vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: async () => ({ source: "local_implicit", isInstanceAdmin: false }) } }));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: {
list: vi.fn(async () => [{ id: "tailnet-connection", companyId: "company-1", name: "Home tailnet", status: "connected" }]),
devices: vi.fn(async () => [{ id: "stable-device", name: "Home Mac", address: "100.64.0.1", os: "macOS", online: true }]),
connect: vi.fn(),
} }));
const xtermMocks = vi.hoisted(() => {
class MockTerminal {
readonly options: Record<string, unknown>;
cols: number;
rows: number;
writes: string[] = [];
focused = false;
disposed = false;
openedElement: HTMLElement | null = null;
private readonly dataHandlers: Array<(data: string) => void> = [];
constructor(options: Record<string, unknown> = {}) {
this.options = options;
this.cols = typeof options.cols === "number" ? options.cols : 80;
this.rows = typeof options.rows === "number" ? options.rows : 24;
xtermMocks.terminalInstances.push(this);
}
loadAddon(addon: { activate?: (terminal: MockTerminal) => void }) {
addon.activate?.(this);
}
open(element: HTMLElement) {
this.openedElement = element;
element.dataset.mockXtermOpen = "true";
}
onData(handler: (data: string) => void) {
this.dataHandlers.push(handler);
return {
dispose: () => {
const index = this.dataHandlers.indexOf(handler);
if (index >= 0) this.dataHandlers.splice(index, 1);
},
};
}
emitData(data: string) {
for (const handler of this.dataHandlers) handler(data);
}
write(data: string) {
this.writes.push(data);
if (!this.openedElement) return;
const chunk = document.createElement("span");
// Keep test DOM readable without reimplementing xterm's ANSI parser.
chunk.textContent = data.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "");
this.openedElement.appendChild(chunk);
}
resize(cols: number, rows: number) {
this.cols = cols;
this.rows = rows;
}
focus() {
this.focused = true;
this.openedElement?.focus();
}
reset() {
this.writes = [];
if (this.openedElement) this.openedElement.textContent = "";
}
clear() {
if (this.openedElement) this.openedElement.textContent = "";
}
dispose() {
this.disposed = true;
}
}
class MockFitAddon {
fitCalls = 0;
terminal: MockTerminal | null = null;
constructor() {
xtermMocks.fitAddonInstances.push(this);
}
activate(terminal: MockTerminal) {
this.terminal = terminal;
}
fit() {
this.fitCalls += 1;
this.terminal?.resize(120, 32);
}
}
return {
MockTerminal,
MockFitAddon,
terminalInstances: [] as MockTerminal[],
fitAddonInstances: [] as MockFitAddon[],
reset() {
this.terminalInstances.length = 0;
this.fitAddonInstances.length = 0;
},
};
});
vi.mock("@xterm/xterm", () => ({
Terminal: xtermMocks.MockTerminal,
}));
vi.mock("@xterm/addon-fit", () => ({
FitAddon: xtermMocks.MockFitAddon,
}));
vi.mock("@xterm/xterm/css/xterm.css", () => ({}));
const mockEnvironmentsApi = vi.hoisted(() => ({
list: vi.fn(),
capabilities: vi.fn(),
secretRefs: vi.fn(),
probe: vi.fn(),
probeConfig: vi.fn(),
create: vi.fn(),
update: vi.fn(),
remove: vi.fn(),
deleteBlastRadius: vi.fn(),
setDefault: vi.fn(),
customImageTemplate: vi.fn(),
startCustomImageSetupSession: vi.fn(),
customImageSetupSession: vi.fn(),
createCustomImageTerminalSessionToken: vi.fn(),
finishCustomImageSetupSession: vi.fn(),
cancelCustomImageSetupSession: vi.fn(),
rollbackCustomImageTemplate: vi.fn(),
relinkCustomImageTemplate: vi.fn(),
disableCustomImageTemplate: vi.fn(),
}));
const mockInstanceSettingsApi = vi.hoisted(() => ({
get: vi.fn(),
getExperimental: vi.fn(),
}));
const mockSecretsApi = vi.hoisted(() => ({
list: vi.fn(),
}));
const mockAgentsApi = vi.hoisted(() => ({
list: vi.fn(),
update: vi.fn(),
}));
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({
selectedCompanyId: "company-1",
selectedCompany: null,
}),
}));
vi.mock("@/context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
}));
vi.mock("@/context/ToastContext", () => ({
useToast: () => ({ pushToast: vi.fn() }),
useToastActions: () => ({ pushToast: vi.fn() }),
useOptionalToastActions: () => ({ pushToast: vi.fn() }),
}));
vi.mock("@/api/environments", () => ({
environmentsApi: mockEnvironmentsApi,
}));
vi.mock("@/api/instanceSettings", () => ({
instanceSettingsApi: mockInstanceSettingsApi,
}));
vi.mock("@/api/secrets", () => ({
secretsApi: mockSecretsApi,
}));
vi.mock("@/api/agents", () => ({
agentsApi: mockAgentsApi,
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
// Minimal browser APIs for jsdom.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).ResizeObserver = class {
observe() {}
unobserve() {}
disconnect() {}
};
class FakeWebSocket {
static CONNECTING = 0;
static OPEN = 1;
static CLOSING = 2;
static CLOSED = 3;
static instances: FakeWebSocket[] = [];
readonly url: string;
readyState = FakeWebSocket.CONNECTING;
sent: string[] = [];
onopen: ((event: Event) => void) | null = null;
onmessage: ((event: MessageEvent) => void) | null = null;
onclose: ((event: CloseEvent) => void) | null = null;
onerror: ((event: Event) => void) | null = null;
constructor(url: string) {
this.url = url;
FakeWebSocket.instances.push(this);
}
send(data: string) {
this.sent.push(data);
}
close() {
this.readyState = FakeWebSocket.CLOSED;
this.onclose?.(new Event("close") as CloseEvent);
}
open() {
this.readyState = FakeWebSocket.OPEN;
this.onopen?.(new Event("open"));
}
emitMessage(data: string) {
this.onmessage?.(new MessageEvent("message", { data }));
}
}
async function act(callback: () => void | Promise<void>) {
await callback();
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
async function flushReact() {
for (let i = 0; i < 3; i += 1) {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
}
async function waitForAssertion(assertion: () => void) {
let lastError: unknown;
for (let i = 0; i < 20; i += 1) {
await flushReact();
try {
assertion();
return;
} catch (error) {
lastError = error;
}
}
throw lastError;
}
function testProviderButtons(container: HTMLElement): HTMLButtonElement[] {
return Array.from(container.querySelectorAll("button")).filter((button) => {
const label = button.textContent?.trim();
return label === "Test provider" || label === "Testing...";
});
}
function findButton(root: ParentNode, label: string): HTMLButtonElement | undefined {
return Array.from(root.querySelectorAll("button")).find((button) => button.textContent?.trim() === label);
}
function findAction(root: ParentNode, label: string): HTMLElement | undefined {
return Array.from(root.querySelectorAll<HTMLElement>("button,a")).find((element) => element.textContent?.trim() === label);
}
function editButtons(root: ParentNode): HTMLElement[] {
return Array.from(root.querySelectorAll<HTMLElement>("button,a")).filter((element) => element.textContent?.trim() === "Edit");
}
function click(element: Element | null | undefined) {
element?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
}
function setInputValue(input: HTMLInputElement, value: string) {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
setter?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
}
function setSelectValue(select: HTMLSelectElement, value: string) {
const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")?.set;
setter?.call(select, value);
select.dispatchEvent(new Event("change", { bubbles: true }));
}
const ENVIRONMENTS_PATH = "/company/settings/instance/environments";
function getEnvironmentFormPage(): HTMLElement | null {
return document.body.querySelector("[data-testid='environment-form-page']");
}
// Opens the edit page for the environment at `index`. The environment list
// depends on an async query. Under a loaded test worker that query can resolve
// after the first flush, so a direct click can miss the Edit control and never
// open the form page. This helper first waits for the control, then clicks it,
// then waits for the form page.
async function openEnvironmentEditPage(container: HTMLElement, index = 0) {
await waitForAssertion(() => {
expect(editButtons(container)[index]).toBeTruthy();
});
await act(async () => click(editButtons(container)[index]));
await waitForAssertion(() => {
expect(getEnvironmentFormPage()).not.toBeNull();
});
}
function renderCompanyEnvironments(queryClient: QueryClient, initialPath = ENVIRONMENTS_PATH) {
return (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialPath]}>
<TooltipProvider>
<Routes>
<Route path={ENVIRONMENTS_PATH} element={<CompanyEnvironments />} />
<Route path={`${ENVIRONMENTS_PATH}/new`} element={<CompanyEnvironments mode="create" />} />
<Route path={`${ENVIRONMENTS_PATH}/:environmentId/edit`} element={<CompanyEnvironments mode="edit" />} />
</Routes>
</TooltipProvider>
</MemoryRouter>
</QueryClientProvider>
);
}
function createSession(overrides: Record<string, unknown> = {}) {
return {
id: "session-1",
environmentId: "env-1",
templateId: null,
promotedTemplateId: null,
provider: "daytona",
providerLeaseId: "lease-redacted",
environmentLeaseId: null,
status: "waiting_for_user",
startedByUserId: "user-1",
startedByAgentId: null,
baseTemplateRef: null,
expiresAt: "2026-06-25T21:00:00.000Z",
finishedAt: null,
failureReason: null,
connectionSummary: {
type: "ssh",
username: "sandbox",
hostRedacted: true,
portRedacted: true,
},
connectionSecretRef: "secret-redacted",
metadata: null,
createdAt: "2026-06-25T20:00:00.000Z",
updatedAt: "2026-06-25T20:00:00.000Z",
...overrides,
};
}
function createTemplate(overrides: Record<string, unknown> = {}) {
return {
id: "template-1",
environmentId: "env-1",
provider: "daytona",
templateKind: "snapshot",
templateRef: "redacted-template-ref",
sourceTemplateRef: null,
sourceEnvironmentConfigFingerprint: "fingerprint",
status: "active",
createdByUserId: "user-1",
createdByAgentId: null,
capturedAt: "2026-06-25T20:00:00.000Z",
lastUsedAt: null,
supersededByTemplateId: null,
metadata: null,
createdAt: "2026-06-25T20:00:00.000Z",
updatedAt: "2026-06-25T20:00:00.000Z",
...overrides,
};
}
function createDeleteBlastRadius(overrides: {
canDelete?: boolean;
deleteBlockedReasons?: string[];
staticReferences?: Record<string, unknown>;
activeRuntimeUse?: Record<string, unknown>;
pendingCleanupLeaseCount?: number;
reusableSandboxLeaseCount?: number;
reusableSandboxLeaseHolders?: Array<Record<string, unknown>>;
} = {}) {
return {
environmentId: "env-1",
canDelete: overrides.canDelete ?? true,
deleteBlockedReasons: overrides.deleteBlockedReasons ?? [],
reusableSandboxLeaseHolders: overrides.reusableSandboxLeaseHolders ?? [],
staticReferences: {
isManagedLocal: false,
isInstanceDefault: false,
agentDefaultCount: 0,
executionWorkspaceSelectionCount: 0,
issueSelectionCount: 0,
projectSelectionCount: 0,
secretBindingCount: 0,
...overrides.staticReferences,
},
activeRuntimeUse: {
activeLeaseCount: 0,
activeCustomImageSetupSessionCount: 0,
hasActiveRuntimeUse: false,
...overrides.activeRuntimeUse,
},
pendingCleanupLeaseCount: overrides.pendingCleanupLeaseCount ?? 0,
reusableSandboxLeaseCount: overrides.reusableSandboxLeaseCount ?? 0,
};
}
function supportedDaytonaCapabilities() {
return {
adapters: [],
drivers: { local: "supported", ssh: "supported", sandbox: "supported", plugin: "unsupported" },
sandboxProviders: {
daytona: {
status: "supported",
supportsSavedProbe: true,
supportsUnsavedProbe: true,
supportsRunExecution: true,
supportsReusableLeases: true,
supportsInteractiveSetup: true,
interactiveSetupConnectionTypes: ["ssh"],
supportsTemplateCapture: true,
supportsTemplateDelete: true,
displayName: "Daytona",
},
},
};
}
describe("CompanyEnvironments — test provider button", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot> | null;
let probeResolvers: Map<string, () => void>;
let originalWebSocket: typeof WebSocket | undefined;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = null;
probeResolvers = new Map();
originalWebSocket = globalThis.WebSocket;
FakeWebSocket.instances = [];
xtermMocks.reset();
globalThis.WebSocket = FakeWebSocket as unknown as typeof WebSocket;
mockInstanceSettingsApi.get.mockResolvedValue({ defaultEnvironmentId: null });
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableEnvironments: true });
mockEnvironmentsApi.capabilities.mockResolvedValue({ adapters: [], sandboxProviders: {} });
mockEnvironmentsApi.secretRefs.mockResolvedValue({ refs: [] });
mockSecretsApi.list.mockResolvedValue([]);
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: null,
activeSession: null,
latestSession: null,
});
mockEnvironmentsApi.startCustomImageSetupSession.mockResolvedValue({
session: createSession(),
connectionPayload: { type: "ssh", command: "ssh sandbox@setup.example.invalid" },
});
mockEnvironmentsApi.customImageSetupSession.mockResolvedValue({
session: createSession(),
connectionPayload: { type: "ssh", command: "ssh sandbox@setup.example.invalid" },
});
mockEnvironmentsApi.createCustomImageTerminalSessionToken.mockResolvedValue({
id: "terminal-session-1",
token: "terminal-token-terminal-token-123456",
expiresAt: "2026-06-25T20:05:00.000Z",
setupSessionId: "session-1",
environmentId: "env-1",
connectionType: "ssh",
websocketPath:
"/api/environment-custom-image-setup-sessions/session-1/terminal/ws?terminalSessionId=terminal-session-1",
});
mockEnvironmentsApi.finishCustomImageSetupSession.mockResolvedValue({
session: createSession({ status: "promoted", promotedTemplateId: "template-1", finishedAt: "2026-06-25T20:10:00.000Z" }),
template: createTemplate(),
connectionPayload: null,
});
mockEnvironmentsApi.cancelCustomImageSetupSession.mockResolvedValue(
createSession({ status: "cancelled", finishedAt: "2026-06-25T20:10:00.000Z" }),
);
mockEnvironmentsApi.rollbackCustomImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: "template-previous" }),
supersededTemplate: createTemplate({ id: "template-current", status: "superseded" }),
});
mockEnvironmentsApi.relinkCustomImageTemplate.mockResolvedValue({
template: createTemplate({ id: "template-relinked" }),
classification: "knob_only",
});
mockEnvironmentsApi.disableCustomImageTemplate.mockResolvedValue(
createTemplate({ status: "revoked" }),
);
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Alpha", driver: "sandbox", description: null, config: { provider: "e2b" } },
{ id: "env-2", name: "Beta", driver: "sandbox", description: null, config: { provider: "e2b" } },
]);
mockEnvironmentsApi.create.mockImplementation(async (_companyId: string, body: { name: string }) => ({
id: "env-new",
name: body.name,
driver: "ssh",
description: null,
config: {},
}));
mockEnvironmentsApi.update.mockImplementation(async (environmentId: string, body: { name: string }) => ({
id: environmentId,
name: body.name,
driver: "sandbox",
description: null,
config: { provider: "e2b" },
}));
mockEnvironmentsApi.deleteBlastRadius.mockResolvedValue(createDeleteBlastRadius());
mockEnvironmentsApi.remove.mockImplementation(async (environmentId: string) => ({
id: environmentId,
name: environmentId === "env-1" ? "Alpha" : "Beta",
driver: "sandbox",
description: null,
config: { provider: "e2b" },
}));
mockAgentsApi.list.mockResolvedValue([]);
mockAgentsApi.update.mockResolvedValue({});
// Each probe stays pending until its resolver is called, so the testing
// state remains observable and can be settled per environment.
mockEnvironmentsApi.probe.mockImplementation(
(environmentId: string) =>
new Promise<{ ok: boolean; driver: string; summary: string; details: null }>((resolve) => {
probeResolvers.set(environmentId, () =>
resolve({ ok: true, driver: "sandbox", summary: "ok", details: null }),
);
}),
);
});
afterEach(() => {
root?.unmount();
root = null;
container.remove();
document.body.innerHTML = "";
if (originalWebSocket) {
globalThis.WebSocket = originalWebSocket;
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (globalThis as any).WebSocket;
}
vi.restoreAllMocks();
vi.clearAllMocks();
});
it("shows the testing state only on the clicked environment's button", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
const buttonsBefore = testProviderButtons(container);
expect(buttonsBefore).toHaveLength(2);
expect(buttonsBefore.every((button) => button.textContent?.trim() === "Test provider")).toBe(true);
expect(buttonsBefore.every((button) => !button.disabled)).toBe(true);
await act(async () => {
buttonsBefore[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
const buttonsAfter = testProviderButtons(container);
expect(buttonsAfter).toHaveLength(2);
expect(buttonsAfter[0].textContent?.trim()).toBe("Testing...");
expect(buttonsAfter[0].disabled).toBe(true);
expect(buttonsAfter[1].textContent?.trim()).toBe("Test provider");
expect(buttonsAfter[1].disabled).toBe(false);
expect(mockEnvironmentsApi.probe).toHaveBeenCalledExactlyOnceWith("env-1", "company-1");
});
it("explains that successful sandbox provider tests use a temporary sandbox", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.probe.mockResolvedValue({
ok: true,
driver: "sandbox",
summary: "Connected to Daytona sandbox paperclip-probe.",
details: {
provider: "daytona",
diagnostics: [],
metadata: {
provider: "daytona",
sandboxId: "473167E9",
sandboxName: "paperclip-probe",
},
},
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await act(async () => {
testProviderButtons(container)[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
expect(mockEnvironmentsApi.probe).toHaveBeenCalledExactlyOnceWith("env-1", "company-1");
expect(container.textContent).toContain("Connected to Daytona sandbox paperclip-probe.");
expect(container.textContent).not.toContain("Verified temporary daytona sandbox");
expect(container.textContent).not.toContain("Test probes clean up the validation sandbox after the check");
expect(container.textContent).not.toContain("provider dashboard");
});
it("does not show sandbox lifecycle success copy for failed sandbox provider tests", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.probe.mockResolvedValue({
ok: false,
driver: "sandbox",
summary: "Daytona sandbox probe failed.",
details: {
provider: "daytona",
error: "Sandbox image was not found.",
metadata: {
provider: "daytona",
sandboxId: "473167E9",
sandboxName: "paperclip-probe",
},
},
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await act(async () => {
testProviderButtons(container)[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
expect(container.textContent).toContain("Daytona sandbox probe failed.");
expect(container.textContent).toContain("Sandbox image was not found.");
expect(container.textContent).not.toContain("Verified temporary daytona sandbox");
expect(container.textContent).not.toContain("Test probes clean up the validation sandbox after the check");
});
it("keeps the second environment's testing state when an earlier probe settles", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
// Click both rows in quick succession while both probes are still pending.
await act(async () => {
testProviderButtons(container)[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
await act(async () => {
testProviderButtons(container)[1].dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
// Settle only the first environment's probe.
await act(async () => {
probeResolvers.get("env-1")?.();
});
await flushReact();
const buttons = testProviderButtons(container);
expect(buttons[1].textContent?.trim()).toBe("Testing...");
expect(buttons[1].disabled).toBe(true);
});
it("defaults new SSH environments to the agent's Paperclip account", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => {
const toggle = getEnvironmentFormPage()?.querySelector('[aria-label="Use authentication configured on the remote machine"]');
expect(toggle?.getAttribute("aria-checked")).toBe("false");
expect(toggle?.closest("details")?.open).toBe(false);
});
});
it.each([undefined, true, false])("preserves the remote-auth option when editing an existing SSH environment (saved=%s)", async useHostAuth => {
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-existing-ssh", name: "Existing SSH", driver: "ssh", description: null, envVars: {},
config: { ...(useHostAuth !== undefined ? { useHostAuth } : {}), host: "ssh.example.test", username: "developer", port: 22, remoteWorkspacePath: "/workspace", strictHostKeyChecking: true } }]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-existing-ssh/edit`)); });
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.querySelector('[aria-label="Use authentication configured on the remote machine"]')?.getAttribute("aria-checked")).toBe(String(useHostAuth !== false));
});
await act(async () => { click(findButton(getEnvironmentFormPage()!, "Save environment")); });
await waitForAssertion(() => {
expect(mockEnvironmentsApi.update).toHaveBeenCalledWith("env-existing-ssh", expect.objectContaining({ config: expect.objectContaining({ useHostAuth: useHostAuth !== false }) }), "company-1");
});
});
it("opens the add-environment form on a standalone page and closes it on cancel", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
const options = Array.from(container.querySelectorAll("option"));
expect(options.some((option) => option.textContent?.trim() === "Local")).toBe(true);
await act(async () => {
click(container.querySelector('[aria-label="Add environment"]'));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Add environment");
});
await act(async () => {
findButton(document.body, "Cancel")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
expect(getEnvironmentFormPage()).toBeNull();
});
it("defaults new SSH environments to the agent's Paperclip account", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => {
const toggle = getEnvironmentFormPage()?.querySelector('[aria-label="Use authentication configured on the remote machine"]');
expect(toggle?.getAttribute("aria-checked")).toBe("false");
expect(toggle?.closest("details")?.open).toBe(false);
});
});
it.each([undefined, true, false])("preserves the remote-auth option when editing an existing SSH environment (saved=%s)", async useHostAuth => {
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-existing-ssh", name: "Existing SSH", driver: "ssh", description: null, envVars: {},
config: { ...(useHostAuth !== undefined ? { useHostAuth } : {}), host: "ssh.example.test", username: "developer", port: 22, remoteWorkspacePath: "/workspace", strictHostKeyChecking: true } }]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-existing-ssh/edit`)); });
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.querySelector('[aria-label="Use authentication configured on the remote machine"]')?.getAttribute("aria-checked")).toBe(String(useHostAuth !== false));
});
await act(async () => { click(findButton(getEnvironmentFormPage()!, "Save environment")); });
await waitForAssertion(() => {
expect(mockEnvironmentsApi.update).toHaveBeenCalledWith("env-existing-ssh", expect.objectContaining({ config: expect.objectContaining({ useHostAuth: useHostAuth !== false }) }), "company-1");
});
});
it("offers tailnet setup through Connectors and hides the SSH network option until connected", async () => {
vi.mocked(tailscaleApi.list).mockResolvedValueOnce([]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.querySelector('a[href="/apps/tailscale"]')).not.toBeNull(); });
expect(getEnvironmentFormPage()!.querySelector('select[aria-label="SSH network"]')).toBeNull();
expect(findButton(getEnvironmentFormPage()!, "Connect Tailscale Network")).toBeUndefined();
});
it("keeps cached tailnet setup available when a background refresh fails", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const key = ["tailscale-connections", "company-1"];
queryClient.setQueryData(key, []);
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.querySelector('a[href="/apps/tailscale"]')).not.toBeNull(); });
vi.mocked(tailscaleApi.list).mockRejectedValueOnce(new ApiError("Network unavailable", 503, {}));
await act(async () => { await queryClient.refetchQueries({ queryKey: key }); });
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.querySelector('[role="alert"]')).not.toBeNull();
expect(getEnvironmentFormPage()?.querySelector('a[href="/apps/tailscale"]')).not.toBeNull();
});
});
it("automatically uses the sole connected tailnet without showing a connection selector", async () => {
vi.mocked(tailscaleApi.list).mockResolvedValueOnce([
{ id: "tailnet-connection", companyId: "company-1", name: "Home tailnet", status: "connected" },
{ id: "unfinished", companyId: "company-1", name: "Unfinished connection", status: "pending" },
]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`)); });
await waitForAssertion(() => {
const network = getEnvironmentFormPage()!.querySelector<HTMLSelectElement>('select[aria-label="SSH network"]')!;
expect([...network.options].map(option => option.value)).toEqual(["direct", "tailscale"]);
});
await act(async () => setSelectValue(getEnvironmentFormPage()!.querySelector('select[aria-label="SSH network"]')!, "tailscale"));
await waitForAssertion(() => {
const page = getEnvironmentFormPage()!;
expect(page.textContent).toContain("Home Mac");
expect(page.textContent).not.toContain("Tailnet connection");
expect(vi.mocked(tailscaleApi.devices)).toHaveBeenCalledWith("company-1", "tailnet-connection");
});
});
it("retains the tailnet selector when multiple connected networks are available", async () => {
vi.mocked(tailscaleApi.list).mockResolvedValueOnce([
{ id: "tailnet-connection", companyId: "company-1", name: "Home tailnet", status: "connected" },
{ id: "work-tailnet", companyId: "company-1", name: "Work tailnet", status: "connected" },
]);
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-tailnet", name: "My workstation", driver: "ssh", description: null, envVars: {},
config: { network: "tailscale", host: "100.64.0.1", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device", strictHostKeyChecking: true } }]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-tailnet/edit`)); });
await waitForAssertion(() => {
const page = getEnvironmentFormPage()!;
expect(page.textContent).toContain("Tailnet connection");
expect(page.textContent).toContain("Home tailnet");
expect(page.textContent).toContain("Work tailnet");
});
});
it("saves a connected Tailscale machine as an SSH environment without a separate driver or harness restriction", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-tailnet", name: "My workstation", driver: "ssh", description: null, envVars: {},
config: { network: "tailscale", host: "100.64.0.1", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device", strictHostKeyChecking: true } }]);
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-tailnet/edit`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.textContent).toContain("Home Mac"); });
const page = getEnvironmentFormPage()!;
expect(page.textContent).not.toContain("Tailnet connection");
const driver = Array.from(page.querySelectorAll("select")).find(select => select.querySelector('option[value="ssh"]'))!;
expect(driver.value).toBe("ssh");
expect(driver.querySelector('option[value="tailscale"]')).toBeNull();
expect(findButton(page, "Connect Tailscale Network")).toBeUndefined();
expect(page.textContent).not.toContain("Claude");
expect(page.querySelector('input[aria-label="Tailscale connection key"]')).toBeNull();
await act(async () => { click(findButton(page, "Save environment")); });
await waitForAssertion(() => { expect(mockEnvironmentsApi.update).toHaveBeenCalledWith("env-tailnet", expect.objectContaining({ driver: "ssh", config: expect.objectContaining({
network: "tailscale", host: "100.64.0.1", username: "developer", remoteWorkspacePath: "/workspace", tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device",
}) }), "company-1"); });
});
it("sends an explicit Direct selection when switching away from a saved tailnet", async () => {
mockEnvironmentsApi.list.mockResolvedValue([{ id: "env-tailnet", name: "My workstation", driver: "ssh", description: null, envVars: {},
config: { network: "tailscale", host: "100.64.0.1", port: 22, username: "developer", remoteWorkspacePath: "/workspace",
tailscaleConnectionId: "tailnet-connection", tailscaleDeviceId: "stable-device", strictHostKeyChecking: true } }]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => { root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-tailnet/edit`)); });
await waitForAssertion(() => { expect(getEnvironmentFormPage()?.textContent).toContain("Home Mac"); });
const page = getEnvironmentFormPage()!;
const host = Array.from(page.querySelectorAll<HTMLInputElement>("input")).find(input => input.value === "100.64.0.1")!;
await act(async () => setSelectValue(page.querySelector('select[aria-label="SSH network"]')!, "direct"));
await act(async () => setInputValue(host, "direct.example.test"));
await act(async () => click(findButton(page, "Save environment")));
await waitForAssertion(() => { expect(mockEnvironmentsApi.update).toHaveBeenCalledWith("env-tailnet", expect.objectContaining({ driver: "ssh", config: expect.objectContaining({ network: "direct", host: "direct.example.test" }) }), "company-1"); });
});
it("opens the edit form on a standalone page with existing values and closes after save", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await act(async () => {
click(findAction(container, "Edit"));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
const page = getEnvironmentFormPage();
expect(document.body.querySelector("[role='dialog']")).toBeNull();
expect(
Array.from(page?.querySelectorAll("input") ?? []).some((input) => (input as HTMLInputElement).value === "Alpha"),
).toBe(true);
await act(async () => click(findButton(page!, "Add variable")));
await flushReact();
const variableName = page!.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!;
const variableValue = page!.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
await act(async () => {
setInputValue(variableName, "API_TOKEN");
setInputValue(variableValue, "draft-token");
});
await flushReact();
await act(async () => {
findButton(document.body, "Save environment")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
expect(mockEnvironmentsApi.update).toHaveBeenCalledExactlyOnceWith(
"env-1",
expect.objectContaining({
name: "Alpha",
driver: "sandbox",
envVars: { API_TOKEN: { type: "plain", value: "draft-token" } },
}),
// The secret-context company must ride along so the server can scope
// bindings even when the environment has none yet.
"company-1",
);
// Saving awaits query invalidation before navigating away. A single flush
// can observe the API call before that asynchronous success path settles.
await waitForAssertion(() => {
expect(getEnvironmentFormPage()).toBeNull();
});
});
it("confirms before cancelling the edit page with unsaved environment variable drafts", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false);
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await act(async () => {
click(findAction(container, "Edit"));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
const page = getEnvironmentFormPage()!;
await act(async () => click(findButton(page, "Add variable")));
await flushReact();
const variableName = page.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!;
const variableValue = page.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
await act(async () => {
setInputValue(variableName, "API_TOKEN");
setInputValue(variableValue, "draft-token");
});
await flushReact();
await act(async () => click(findButton(document.body, "Cancel")));
await flushReact();
expect(confirmSpy).toHaveBeenCalledWith("Discard unsaved environment changes?");
expect(getEnvironmentFormPage()).not.toBeNull();
confirmSpy.mockReturnValue(true);
await act(async () => click(findButton(document.body, "Cancel")));
await flushReact();
expect(getEnvironmentFormPage()).toBeNull();
});
it("keeps unload and in-app link warnings after env var changes are staged into the form", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false);
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await act(async () => {
click(findAction(container, "Edit"));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
const page = getEnvironmentFormPage()!;
await act(async () => click(findButton(page, "Add variable")));
await flushReact();
const variableName = page.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!;
const variableValue = page.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
await act(async () => {
setInputValue(variableName, "API_TOKEN");
setInputValue(variableValue, "draft-token");
});
await flushReact();
await act(async () => click(findButton(page, "Save")));
await flushReact();
expect(page.textContent).not.toContain("Unsaved changes");
const beforeUnload = new Event("beforeunload", { cancelable: true });
window.dispatchEvent(beforeUnload);
expect(beforeUnload.defaultPrevented).toBe(true);
const link = document.createElement("a");
link.href = "/agents/dashboard";
document.body.appendChild(link);
const clickEvent = new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 });
link.dispatchEvent(clickEvent);
expect(confirmSpy).toHaveBeenCalledWith("Discard unsaved environment changes?");
expect(clickEvent.defaultPrevented).toBe(true);
expect(getEnvironmentFormPage()).not.toBeNull();
link.remove();
});
it("shows image setup controls only for providers advertising setup and capture support", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
{ id: "env-2", name: "E2B", driver: "sandbox", description: null, config: { provider: "e2b" } },
{ id: "env-3", name: "Policy", driver: "sandbox", description: null, config: { provider: "policy" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue({
adapters: [],
drivers: { local: "supported", ssh: "supported", sandbox: "supported", plugin: "unsupported" },
sandboxProviders: {
daytona: supportedDaytonaCapabilities().sandboxProviders.daytona,
e2b: {
status: "supported",
supportsSavedProbe: true,
supportsUnsavedProbe: true,
supportsRunExecution: true,
supportsReusableLeases: true,
supportsInteractiveSetup: false,
interactiveSetupConnectionTypes: [],
supportsTemplateCapture: false,
supportsTemplateDelete: false,
displayName: "E2B",
},
policy: {
status: "supported",
supportsSavedProbe: true,
supportsUnsavedProbe: true,
supportsRunExecution: true,
supportsReusableLeases: true,
supportsInteractiveSetup: true,
interactiveSetupConnectionTypes: ["ssh"],
supportsTemplateCapture: false,
supportsTemplateDelete: false,
displayName: "Policy Sandbox",
},
},
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
// Daytona supports setup + capture -> "Configure image" on its edit page.
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Configure image");
});
expect(mockEnvironmentsApi.customImageTemplate).toHaveBeenCalledExactlyOnceWith("env-1", "company-1");
await act(async () => click(findButton(document.body, "Cancel")));
await waitForAssertion(() => expect(getEnvironmentFormPage()).toBeNull());
// E2B does not advertise interactive setup.
await openEnvironmentEditPage(container, 1);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Unsupported provider");
});
expect(getEnvironmentFormPage()?.textContent).not.toContain("Configure image");
await act(async () => click(findButton(document.body, "Cancel")));
await waitForAssertion(() => expect(getEnvironmentFormPage()).toBeNull());
// Provider advertises setup but cannot capture an image.
await openEnvironmentEditPage(container, 2);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Setup capture unavailable");
});
expect(getEnvironmentFormPage()?.textContent).not.toContain("Configure image");
});
it("shows a live connect command and removes it after cancellation", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const command = "ssh sandbox@setup.example.invalid -p 2222";
let activeSession: ReturnType<typeof createSession> | null = createSession();
let latestSession: ReturnType<typeof createSession> | null = activeSession;
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockImplementation(async () => ({
activeTemplate: null,
activeSession,
latestSession,
}));
mockEnvironmentsApi.customImageSetupSession.mockResolvedValue({
session: createSession(),
connectionPayload: { type: "ssh", command },
});
mockEnvironmentsApi.cancelCustomImageSetupSession.mockImplementation(async () => {
activeSession = null;
latestSession = createSession({ status: "cancelled", finishedAt: "2026-06-25T20:10:00.000Z" });
return latestSession;
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain(command);
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Cancel")));
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Setup cancelled");
});
expect(mockEnvironmentsApi.cancelCustomImageSetupSession).toHaveBeenCalledExactlyOnceWith(
"session-1",
{ reason: "operator cancelled" },
);
expect(getEnvironmentFormPage()?.textContent).not.toContain(command);
});
it("opens an embedded browser terminal automatically while preserving the SSH command fallback", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const command = "ssh sandbox@setup.example.invalid -p 2222";
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: null,
activeSession: createSession(),
latestSession: createSession(),
});
mockEnvironmentsApi.customImageSetupSession.mockResolvedValue({
session: createSession(),
connectionPayload: { type: "ssh", command },
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain(command);
expect(getEnvironmentFormPage()?.textContent).toContain("Browser terminal");
expect(getEnvironmentFormPage()?.textContent).toContain("SSH command fallback");
expect(mockEnvironmentsApi.createCustomImageTerminalSessionToken).toHaveBeenCalledExactlyOnceWith("session-1", {});
expect(FakeWebSocket.instances).toHaveLength(1);
});
expect(FakeWebSocket.instances[0].url).toContain(
"/api/environment-custom-image-setup-sessions/session-1/terminal/ws?terminalSessionId=terminal-session-1",
);
expect(FakeWebSocket.instances[0].url).not.toContain("token=");
expect(FakeWebSocket.instances[0].url).not.toContain("terminal-token-terminal-token-123456");
expect(FakeWebSocket.instances[0].url).toContain("cols=120");
expect(FakeWebSocket.instances[0].url).toContain("rows=32");
expect(xtermMocks.terminalInstances[0].options.cursorBlink).toBe(true);
expect(xtermMocks.terminalInstances[0].options.cursorInactiveStyle).toBe("bar");
expect(xtermMocks.terminalInstances[0].options.cursorStyle).toBe("bar");
expect(xtermMocks.terminalInstances[0].options.cursorWidth).toBe(2);
expect(xtermMocks.terminalInstances[0].options.customGlyphs).toBe(true);
expect(xtermMocks.terminalInstances[0].options.letterSpacing).toBe(0);
expect(xtermMocks.terminalInstances[0].options.theme).toMatchObject({
cursor: "#22d3ee",
cursorAccent: "#020617",
});
expect(String(xtermMocks.terminalInstances[0].options.fontFamily)).toContain("Nerd Font");
await act(async () => {
FakeWebSocket.instances[0].open();
FakeWebSocket.instances[0].emitMessage(JSON.stringify({ type: "ready" }));
FakeWebSocket.instances[0].emitMessage(JSON.stringify({ type: "output", data: "\u001b[?2004hsetup shell\r\n$ " }));
});
const terminalScreen = getEnvironmentFormPage()?.querySelector<HTMLElement>(
"[data-testid='custom-image-terminal-screen-session-1']",
);
await waitForAssertion(() => {
expect(terminalScreen?.dataset.mockXtermOpen).toBe("true");
expect(xtermMocks.terminalInstances[0].writes.join("")).toContain("setup shell");
expect(xtermMocks.terminalInstances[0].focused).toBe(true);
expect(document.activeElement).toBe(terminalScreen);
expect(getEnvironmentFormPage()?.textContent).toContain(command);
});
expect(FakeWebSocket.instances[0].sent).toContain(JSON.stringify({
type: "auth",
token: "terminal-token-terminal-token-123456",
}));
expect(FakeWebSocket.instances[0].sent).toContain(JSON.stringify({ type: "resize", cols: 120, rows: 32 }));
await act(async () => {
xtermMocks.terminalInstances[0].emitData("l");
xtermMocks.terminalInstances[0].emitData("\r");
});
expect(FakeWebSocket.instances[0].sent).toContain(JSON.stringify({ type: "input", data: "l" }));
expect(FakeWebSocket.instances[0].sent).toContain(JSON.stringify({ type: "input", data: "\r" }));
});
it("keeps the environment edit page open when Escape is pressed in setup terminal", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const command = "ssh sandbox@setup.example.invalid -p 2222";
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: null,
activeSession: createSession(),
latestSession: createSession(),
});
mockEnvironmentsApi.customImageSetupSession.mockResolvedValue({
session: createSession(),
connectionPayload: { type: "ssh", command },
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
let terminalScreen: HTMLElement | null = null;
await waitForAssertion(() => {
terminalScreen = getEnvironmentFormPage()?.querySelector<HTMLElement>(
"[data-testid='custom-image-terminal-screen-session-1']",
) ?? null;
expect(terminalScreen).toBeTruthy();
expect(document.body.querySelector("[role='dialog']")).toBeNull();
});
await act(async () => {
terminalScreen?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
});
await flushReact();
expect(getEnvironmentFormPage()?.textContent).toContain(command);
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
it("does not render connect details when an active session refreshes as expired", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const command = "ssh sandbox@setup.example.invalid -p 2222";
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: null,
activeSession: createSession(),
latestSession: createSession(),
});
mockEnvironmentsApi.customImageSetupSession.mockResolvedValue({
session: createSession({ status: "timed_out", finishedAt: "2026-06-25T20:10:00.000Z" }),
connectionPayload: { type: "ssh", command },
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Setup expired");
});
expect(getEnvironmentFormPage()?.textContent).not.toContain(command);
});
it("shows a setup connection refresh fallback without breaking finish or cancel", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: null,
activeSession: createSession(),
latestSession: createSession(),
});
mockEnvironmentsApi.customImageSetupSession.mockRejectedValue(new Error("proxy unavailable"));
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Setup connection details could not be refreshed.");
});
const dialog = getEnvironmentFormPage()!;
expect(findButton(dialog, "Finished")?.disabled).toBe(false);
expect(findButton(dialog, "Cancel")?.disabled).toBe(false);
await act(async () => click(findButton(dialog, "Finished")));
await flushReact();
expect(mockEnvironmentsApi.finishCustomImageSetupSession).toHaveBeenCalledExactlyOnceWith("session-1", {});
});
it("shows provider fallback messaging for unsupported setup connection payloads", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: null,
activeSession: createSession(),
latestSession: createSession(),
});
mockEnvironmentsApi.customImageSetupSession.mockResolvedValue({
session: createSession(),
connectionPayload: { type: "browser_terminal", command: null },
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Browser terminal is not available for this provider connection.");
});
const dialog = getEnvironmentFormPage()!;
expect(findButton(dialog, "Finished")?.disabled).toBe(false);
expect(findButton(dialog, "Cancel")?.disabled).toBe(false);
});
it("shows active template controls for refresh, rollback, and disable", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const activeTemplateId = "12345678-90ab-cdef-1234-567890abcdef";
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: activeTemplateId }),
activeSession: null,
latestSession: null,
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage();
expect(dialog?.textContent).toContain("Active template");
expect(dialog?.textContent).toContain("redacted-template-ref");
expect(dialog?.textContent).not.toContain("id 12345678-90a");
expect(
dialog?.querySelector(
"[title='Provider snapshot ref redacted-template-ref (Paperclip template 12345678-90ab-cdef-1234-567890abcdef)']",
),
).toBeTruthy();
expect(findButton(dialog!, "Refresh")).toBeTruthy();
expect(findButton(dialog!, "Rollback")).toBeTruthy();
expect(findButton(dialog!, "Disable")).toBeTruthy();
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Refresh")));
await flushReact();
expect(mockEnvironmentsApi.startCustomImageSetupSession).toHaveBeenCalledWith(
"env-1",
"company-1",
{ templateId: activeTemplateId },
);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Browser terminal");
expect(getEnvironmentFormPage()?.textContent).toContain("SSH command fallback");
expect(mockEnvironmentsApi.createCustomImageTerminalSessionToken).toHaveBeenCalledExactlyOnceWith("session-1", {});
expect(FakeWebSocket.instances).toHaveLength(1);
});
});
it("allows stale capturing setup sessions to be cancelled back to active template controls", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const activeTemplate = createTemplate({ id: "template-active" });
let activeSession: ReturnType<typeof createSession> | null = createSession({ status: "capturing" });
let latestSession: ReturnType<typeof createSession> | null = activeSession;
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockImplementation(async () => ({
activeTemplate,
activeSession,
latestSession,
}));
mockEnvironmentsApi.customImageSetupSession.mockResolvedValue({
session: activeSession,
connectionPayload: null,
});
mockEnvironmentsApi.cancelCustomImageSetupSession.mockImplementation(async () => {
activeSession = null;
latestSession = createSession({ status: "cancelled", finishedAt: "2026-06-25T20:10:00.000Z" });
return latestSession;
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage()!;
expect(dialog.textContent).toContain("Capturing template");
expect(dialog.textContent).toContain("Capture is in progress.");
expect(findButton(dialog, "Finished")?.disabled).toBe(true);
expect(findButton(dialog, "Cancel")?.disabled).toBe(false);
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Cancel")));
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage()!;
expect(dialog.textContent).toContain("Active template");
expect(findButton(dialog, "Refresh")).toBeTruthy();
});
expect(mockEnvironmentsApi.cancelCustomImageSetupSession).toHaveBeenCalledExactlyOnceWith(
"session-1",
{ reason: "operator cancelled" },
);
});
it("shows an out-of-sync warning when the active template no longer matches the saved config", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: "template-active" }),
activeTemplateMatchesConfig: false,
activeSession: null,
latestSession: null,
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage()!;
expect(dialog.textContent).toContain("Active template");
expect(dialog.textContent).toContain("Not in use — the environment configuration changed");
});
});
it("names the changed boot-source field in the out-of-sync banner for a boot-source drift", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: "template-active" }),
activeTemplateMatchesConfig: false,
activeTemplateDrift: {
classification: "boot_source_drift",
driftedPaths: [{ path: "snapshot", from: "a", to: "b" }],
},
activeSession: null,
latestSession: null,
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage()!;
expect(dialog.textContent).toContain("Not in use — Base image changed: snapshot `a` -> `b`");
expect(dialog.textContent).not.toContain("the environment configuration changed");
});
});
it("keeps the generic out-of-sync banner for an unclassified drift", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: "template-active" }),
activeTemplateMatchesConfig: false,
activeTemplateDrift: { classification: "unclassified", driftedPaths: [{ path: "apiUrl" }] },
activeSession: null,
latestSession: null,
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage()!;
expect(dialog.textContent).toContain("Not in use — the environment configuration changed");
expect(dialog.textContent).not.toContain("Base image changed");
});
});
it("does not show the out-of-sync warning when the active template matches the saved config", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: "template-active" }),
activeTemplateMatchesConfig: true,
activeSession: null,
latestSession: null,
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage()!;
expect(dialog.textContent).toContain("Active template");
expect(dialog.textContent).not.toContain("Not in use");
});
});
it("passes company context when rolling back and disabling an active template", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: "template-active" }),
activeSession: null,
latestSession: null,
});
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage();
expect(dialog?.textContent).toContain("Active template");
expect(findButton(dialog!, "Rollback")).toBeTruthy();
expect(findButton(dialog!, "Disable")).toBeTruthy();
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Rollback")));
await waitForAssertion(() => {
expect(mockEnvironmentsApi.rollbackCustomImageTemplate).toHaveBeenCalledExactlyOnceWith("env-1", "company-1");
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Disable")));
await waitForAssertion(() => {
expect(mockEnvironmentsApi.disableCustomImageTemplate).toHaveBeenCalledExactlyOnceWith("env-1", "company-1");
});
});
function setupOutOfSyncTemplatePanel() {
mockEnvironmentsApi.list.mockResolvedValue([
{ id: "env-1", name: "Daytona", driver: "sandbox", description: null, config: { provider: "daytona" } },
]);
mockEnvironmentsApi.capabilities.mockResolvedValue(supportedDaytonaCapabilities());
mockEnvironmentsApi.customImageTemplate.mockResolvedValue({
activeTemplate: createTemplate({ id: "template-active" }),
activeTemplateMatchesConfig: false,
activeSession: null,
latestSession: null,
});
}
it("relinks an out-of-sync template and names both remedies in the copy", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
setupOutOfSyncTemplatePanel();
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
const dialog = getEnvironmentFormPage()!;
expect(dialog.textContent).toContain("relink this image or capture a new one");
expect(findButton(dialog, "Relink")).toBeTruthy();
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Relink")));
await waitForAssertion(() => {
expect(mockEnvironmentsApi.relinkCustomImageTemplate).toHaveBeenCalledExactlyOnceWith("env-1", "company-1");
});
});
it("confirms boot-source drift before re-sending the relink with the flag", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
setupOutOfSyncTemplatePanel();
mockEnvironmentsApi.relinkCustomImageTemplate
.mockRejectedValueOnce(new ApiError("Confirm the relink.", 409, {
error: "Confirm the relink.",
details: {
classification: "boot_source_drift",
driftedPaths: [{ path: "image", from: "fake:base", to: "fake:other" }],
},
}))
.mockResolvedValueOnce({
template: createTemplate({ id: "template-relinked" }),
classification: "boot_source_drift",
});
const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true);
try {
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(findButton(getEnvironmentFormPage()!, "Relink")).toBeTruthy();
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Relink")));
await waitForAssertion(() => {
expect(mockEnvironmentsApi.relinkCustomImageTemplate).toHaveBeenNthCalledWith(1, "env-1", "company-1");
expect(mockEnvironmentsApi.relinkCustomImageTemplate).toHaveBeenNthCalledWith(
2,
"env-1",
"company-1",
{ confirmBootSourceDrift: true },
);
});
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(confirmSpy.mock.calls[0]![0]).toContain("image fake:base -> fake:other");
} finally {
confirmSpy.mockRestore();
}
});
it("does not re-send the relink when the operator declines the confirmation", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
setupOutOfSyncTemplatePanel();
mockEnvironmentsApi.relinkCustomImageTemplate.mockRejectedValueOnce(new ApiError("Cannot verify.", 409, {
error: "Cannot verify.",
details: { classification: "unclassified", driftedPaths: [{ path: "apiUrl" }] },
}));
const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false);
try {
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
await openEnvironmentEditPage(container);
await waitForAssertion(() => {
expect(findButton(getEnvironmentFormPage()!, "Relink")).toBeTruthy();
});
await act(async () => click(findButton(getEnvironmentFormPage()!, "Relink")));
await waitForAssertion(() => {
expect(confirmSpy).toHaveBeenCalledTimes(1);
});
expect(confirmSpy.mock.calls[0]![0]).toContain("cannot verify the boot source");
expect(mockEnvironmentsApi.relinkCustomImageTemplate).toHaveBeenCalledTimes(1);
expect(mockEnvironmentsApi.relinkCustomImageTemplate).toHaveBeenCalledWith("env-1", "company-1");
} finally {
confirmSpy.mockRestore();
}
});
it("hides the implicit Local option in the default picker under managed-sandbox-only", async () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableEnvironments: true,
enableManagedSandboxOnly: true,
});
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await flushReact();
const options = Array.from(container.querySelectorAll("option"));
expect(options.some((option) => option.textContent?.trim() === "Local")).toBe(false);
// Saved non-local environments remain selectable defaults.
expect(options.some((option) => option.textContent?.includes("Alpha"))).toBe(true);
});
it("reassigns this company's active agents to the chosen environment before deleting", async () => {
mockAgentsApi.list.mockResolvedValue([
{ id: "agent-1", name: "Iris", status: "active", defaultEnvironmentId: "env-1" },
{ id: "agent-2", name: "Miles", status: "active", defaultEnvironmentId: "env-2" },
{ id: "agent-3", name: "Retired", status: "terminated", defaultEnvironmentId: "env-1" },
]);
mockEnvironmentsApi.deleteBlastRadius.mockResolvedValue(
createDeleteBlastRadius({ staticReferences: { agentDefaultCount: 2 } }),
);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-1/edit`));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
const deleteButton = document.body.querySelector<HTMLButtonElement>("[data-testid='environment-delete-button']");
expect(deleteButton).not.toBeNull();
await act(async () => click(deleteButton));
await waitForAssertion(() => {
expect(
document.body.querySelector("[data-testid='environment-delete-dialog']")?.textContent,
).toContain("1 agent uses this environment as their default");
});
const dialog = document.body.querySelector<HTMLElement>("[data-testid='environment-delete-dialog']")!;
// Only this company's active agents are reassignable; the terminated one is
// left to the FK fallback and surfaces through the impact note instead.
expect(dialog.textContent).toContain("Iris");
expect(dialog.textContent).not.toContain("Retired");
expect(dialog.textContent).toContain("Other references to this environment");
const reassignSelect = dialog.querySelector<HTMLSelectElement>(
"[data-testid='environment-delete-reassign-select']",
)!;
const optionLabels = Array.from(reassignSelect.querySelectorAll("option")).map((option) =>
option.textContent?.trim(),
);
expect(optionLabels).toEqual(["Default: Local", "Beta · sandbox"]);
await act(async () => setSelectValue(reassignSelect, "env-2"));
await act(async () =>
click(document.body.querySelector("[data-testid='environment-delete-confirm']")),
);
await flushReact();
expect(mockAgentsApi.update).toHaveBeenCalledExactlyOnceWith(
"agent-1",
{ defaultEnvironmentId: "env-2" },
"company-1",
);
expect(mockEnvironmentsApi.remove).toHaveBeenCalledExactlyOnceWith("env-1");
expect(mockAgentsApi.update.mock.invocationCallOrder[0]).toBeLessThan(
mockEnvironmentsApi.remove.mock.invocationCallOrder[0],
);
await waitForAssertion(() => {
expect(getEnvironmentFormPage()).toBeNull();
});
});
it("deletes without any reassignment when no agents use the environment", async () => {
mockAgentsApi.list.mockResolvedValue([
{ id: "agent-2", name: "Miles", status: "active", defaultEnvironmentId: "env-2" },
]);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-1/edit`));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
await act(async () =>
click(document.body.querySelector("[data-testid='environment-delete-button']")),
);
await waitForAssertion(() => {
expect(
document.body.querySelector("[data-testid='environment-delete-dialog']")?.textContent,
).toContain("permanently deleted");
});
expect(
document.body.querySelector("[data-testid='environment-delete-reassign-select']"),
).toBeNull();
await act(async () =>
click(document.body.querySelector("[data-testid='environment-delete-confirm']")),
);
await flushReact();
expect(mockAgentsApi.update).not.toHaveBeenCalled();
expect(mockEnvironmentsApi.remove).toHaveBeenCalledExactlyOnceWith("env-1");
await waitForAssertion(() => {
expect(getEnvironmentFormPage()).toBeNull();
});
});
it("disables the delete confirmation while the server would block the delete", async () => {
mockEnvironmentsApi.deleteBlastRadius.mockResolvedValue(
createDeleteBlastRadius({
canDelete: false,
deleteBlockedReasons: ["instance_default"],
staticReferences: { isInstanceDefault: true },
}),
);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-1/edit`));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
await act(async () =>
click(document.body.querySelector("[data-testid='environment-delete-button']")),
);
await waitForAssertion(() => {
expect(
document.body.querySelector("[data-testid='environment-delete-dialog']")?.textContent,
).toContain("Cannot delete the current instance default environment");
});
const confirm = document.body.querySelector<HTMLButtonElement>(
"[data-testid='environment-delete-confirm']",
)!;
expect(confirm.disabled).toBe(true);
expect(
document.body.querySelector("[data-testid='environment-delete-reassign-select']"),
).toBeNull();
expect(mockEnvironmentsApi.remove).not.toHaveBeenCalled();
});
it("links the workspaces holding blocking sandbox leases in the delete dialog", async () => {
mockEnvironmentsApi.deleteBlastRadius.mockResolvedValue(
createDeleteBlastRadius({
canDelete: false,
deleteBlockedReasons: ["reusable_sandbox_lease"],
reusableSandboxLeaseCount: 3,
reusableSandboxLeaseHolders: [
{
leaseId: "lease-1",
executionWorkspaceId: "ws-1",
executionWorkspaceName: "ACME-7-fix-the-thing",
issueId: "issue-1",
issueIdentifier: "ACME-7",
issueTitle: "Fix the thing",
},
{
leaseId: "lease-2",
executionWorkspaceId: "ws-1",
executionWorkspaceName: "ACME-7-fix-the-thing",
issueId: "issue-2",
issueIdentifier: "ACME-9",
issueTitle: "Follow-up",
},
{
leaseId: "lease-3",
executionWorkspaceId: null,
executionWorkspaceName: null,
issueId: null,
issueIdentifier: null,
issueTitle: null,
},
],
}),
);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/env-1/edit`));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Edit environment");
});
await act(async () =>
click(document.body.querySelector("[data-testid='environment-delete-button']")),
);
await waitForAssertion(() => {
expect(
document.body.querySelector("[data-testid='environment-delete-lease-holders']"),
).not.toBeNull();
});
const holders = document.body.querySelector<HTMLElement>(
"[data-testid='environment-delete-lease-holders']",
)!;
const workspaceLink = holders.querySelector<HTMLAnchorElement>("a[href='/execution-workspaces/ws-1']");
expect(workspaceLink?.textContent).toBe("ACME-7-fix-the-thing");
// The two leases on ws-1 collapse into one row naming both issues.
expect(holders.querySelectorAll("li")).toHaveLength(2);
expect(holders.textContent).toContain("2 sandbox leases");
expect(holders.textContent).toContain("ACME-7, ACME-9");
expect(holders.textContent).toContain("Workspace no longer on record");
// Leases as the only blocker are consentable: the confirm stays enabled
// and destroys the sandboxes as part of the delete.
const confirm = document.body.querySelector<HTMLButtonElement>(
"[data-testid='environment-delete-confirm']",
)!;
expect(confirm.disabled).toBe(false);
expect(confirm.textContent?.trim()).toBe("Destroy 3 sandboxes and delete");
await act(async () => click(confirm));
await flushReact();
expect(mockEnvironmentsApi.remove).toHaveBeenCalledExactlyOnceWith("env-1", {
destroyReusableSandboxLeases: true,
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()).toBeNull();
});
});
it("does not offer delete on the add-environment page", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient, `${ENVIRONMENTS_PATH}/new`));
});
await waitForAssertion(() => {
expect(getEnvironmentFormPage()?.textContent).toContain("Add environment");
});
expect(document.body.querySelector("[data-testid='environment-delete-button']")).toBeNull();
});
it("keeps the loaded environments list visible when a refetch fails transiently", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await waitForAssertion(() => {
expect(container.textContent).toContain("Alpha");
expect(container.textContent).toContain("Beta");
});
mockEnvironmentsApi.list.mockRejectedValue(
new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }),
);
await act(async () => {
await queryClient.invalidateQueries();
});
await waitForAssertion(() => {
expect(mockEnvironmentsApi.list.mock.calls.length).toBeGreaterThan(1);
});
expect(container.textContent).toContain("Alpha");
expect(container.textContent).toContain("Beta");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
expect(container.textContent).not.toContain("Paperclip is restarting.");
expect(container.textContent).not.toContain("tenant_app_unavailable");
});
it("shows readable copy and a Retry button when the environments list fails to load", async () => {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockEnvironmentsApi.list.mockRejectedValueOnce(new ApiError("Boom", 500, { error: "Boom" }));
await act(async () => {
root!.render(renderCompanyEnvironments(queryClient));
});
await waitForAssertion(() => {
expect(container.querySelector('[data-query-view="error"]')).not.toBeNull();
});
expect(container.textContent).toContain("Couldn't load environments");
expect(container.textContent).not.toContain("Alpha");
const retry = findButton(container, "Retry");
expect(retry).toBeTruthy();
await act(async () => click(retry));
await waitForAssertion(() => {
expect(container.textContent).toContain("Alpha");
});
expect(mockEnvironmentsApi.list).toHaveBeenCalledTimes(2);
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
});
});