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>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-13 15:15:43 -08:00
1 parent 1d112a504f
commit 21bf7ebcee
72 files changed
+5105 -73

No files matched your search

+2
View File
@@ -108,6 +108,7 @@ const AdvancedToolsRoute = lazy(() => import("./pages/tools/AdvancedToolsRoute")
const ProfileWizardRoute = lazy(() => import("./pages/tools/profiles/ProfileWizardRoute").then((module) => ({ default: module.ProfileWizardRoute })));
const ProfileDetailRoute = lazy(() => import("./pages/tools/profiles/ProfileDetailRoute").then((module) => ({ default: module.ProfileDetailRoute })));
const Browse = lazy(() => import("./pages/apps/Browse").then((module) => ({ default: module.Browse })));
const TailscaleConnector = lazy(() => import("./pages/apps/TailscaleConnector").then((module) => ({ default: module.TailscaleConnector })));
const AppsConnect = lazy(() => import("./pages/apps/AppsConnect").then((module) => ({ default: module.AppsConnect })));
const ChatEndpointSetup = lazy(() => import("./pages/apps/chat/ChatEndpointSetup").then((module) => ({ default: module.ChatEndpointSetup })));
const ChatEndpointDetail = lazy(() => import("./pages/apps/chat/ChatEndpointDetail").then((module) => ({ default: module.ChatEndpointDetail })));
@@ -199,6 +200,7 @@ function boardRoutes(streamlinedUiEnabled: boolean, combinedInboxTasksEnabled: b
<Route path="tools" element={<LegacyToolsRedirect />} />
<Route path="tools/:tab" element={<LegacyToolsRedirect />} />
<Route path="apps" element={<Browse />} />
<Route path="apps/tailscale" element={<TailscaleConnector />} />
<Route path="apps/assistant-connection" element={<AssistantConnection />} />
<Route path="apps/browse" element={<Navigate to="/apps" replace />} />
<Route path="apps/connections" element={<Navigate to="/apps" replace />} />
+12
View File
@@ -0,0 +1,12 @@
import type { ToolOAuthStartResult } from "@paperclipai/shared";
import { api } from "./client";
export type TailscaleConnection = { id: string; companyId: string; name: string; status: string };
export type TailscaleDevice = { id: string; name: string; hostname: string; address: string; os: string; online: boolean };
export const tailscaleApi = {
list: (companyId: string) => api.get<TailscaleConnection[]>(`/companies/${companyId}/tailscale-connections`),
connect: (companyId: string, connectionId?: string) => api.post<ToolOAuthStartResult>(`/companies/${companyId}/tailscale-connections`, { name: "My tailnet", ...(connectionId ? { connectionId } : {}) }),
devices: (companyId: string, id: string) => api.get<TailscaleDevice[]>(`/companies/${companyId}/tailscale-connections/${id}/devices`),
disconnect: (companyId: string, id: string) => api.delete<TailscaleConnection>(`/companies/${companyId}/tailscale-connections/${id}`),
pairing: (companyId: string, id: string, deviceId: string, port: number) => api.post<{ privateKeySecretId: string; publicKey: string; command: string }>(`/companies/${companyId}/tailscale-connections/${id}/pairing`, { deviceId, port }),
};
@@ -0,0 +1,77 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TailscaleSshMachine } from "./TailscaleSshMachine";
const pairing = vi.hoisted(() => vi.fn());
vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: async () => ({ source: "local_implicit", isInstanceAdmin: false }) } }));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: {
list: async () => [{ id: "connection", companyId: "company", name: "Home tailnet", status: "connected" }],
devices: async () => [{ id: "device", name: "Workstation", address: "100.64.0.1", os: "linux", online: true }],
pairing,
} }));
vi.mock("@/lib/router", () => ({ Link: ({ to, children }: { to: string; children: React.ReactNode }) => <a href={to}>{children}</a> }));
const result = (port: number) => ({ privateKeySecretId: `key-${port}`, publicKey: "fixture public key", command: `pair workstation on port ${port}` });
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
const onPrivateKey = vi.fn<(secretId: string) => void>();
function render(port: number, visible = true) {
flushSync(() => root.render(<QueryClientProvider client={client}>
{visible ? <TailscaleSshMachine companyId="company" connectionId="connection" deviceId="device" port={port}
onPrivateKey={onPrivateKey} onChange={() => {}} /> : <p>Direct SSH configuration</p>}
</QueryClientProvider>));
}
function prepare() {
const button = [...container.querySelectorAll("button")].find(button => button.textContent === "Prepare machine pairing");
expect(button).toBeDefined();
flushSync(() => button!.click());
}
const command = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Machine pairing command"]');
async function settle() {
for (let i = 0; i < 6; i++) await new Promise(resolve => setTimeout(resolve, 0));
}
describe("Tailscale SSH pairing selection", () => {
beforeEach(() => {
pairing.mockReset().mockImplementation(async (_company, _connection, _device, port) => result(port));
onPrivateKey.mockReset();
container = document.createElement("div"); document.body.append(container);
root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.remove(); });
it("ignores a pending pairing response after switching to Direct", async () => {
let finish!: (value: ReturnType<typeof result>) => void;
pairing.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(22); await settle(); prepare(); await settle();
render(22, false);
finish(result(22)); await settle();
expect(onPrivateKey).not.toHaveBeenCalled();
expect(command()).toBeNull();
});
it.each([false, true])("requires current-port pairing after a port edit (old request pending=%s)", async pending => {
let finish!: (value: ReturnType<typeof result>) => void;
if (pending) pairing.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(22); await settle(); prepare(); await settle();
expect(pairing).toHaveBeenLastCalledWith("company", "connection", "device", 22);
if (!pending) {
expect(command()?.value).toBe(result(22).command);
expect(onPrivateKey).toHaveBeenCalledWith("key-22");
}
onPrivateKey.mockClear();
render(2222); await settle();
if (pending) { finish(result(22)); await settle(); }
expect(command()).toBeNull();
expect(onPrivateKey).not.toHaveBeenCalled();
prepare(); await settle();
expect(pairing).toHaveBeenLastCalledWith("company", "connection", "device", 2222);
expect(command()?.value).toBe(result(2222).command);
expect(onPrivateKey).toHaveBeenCalledExactlyOnceWith("key-2222");
});
});
+62
View File
@@ -0,0 +1,62 @@
import { useEffect, useRef } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { tailscaleApi } from "@/api/tailscale";
import { describeError } from "@/api/errors";
import { useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import { Link } from "@/lib/router";
import { Button } from "./ui/button";
import { Field } from "./agent-config-primitives";
export function TailscaleSshMachine(props: {
companyId: string; connectionId: string; deviceId: string;
port: number; onPrivateKey: (secretId: string) => void;
onChange: (selection: { connectionId: string; deviceId: string; host: string }) => void;
}) {
const mounted = useRef(false);
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const connections = useTailscaleConnections(props.companyId);
const connected = (connections.data ?? []).filter(connection => connection.status === "connected");
const onlyConnectionId = connected.length === 1 ? connected[0]!.id : null;
const showConnectionSelector = connected.length > 1 || Boolean(props.connectionId && onlyConnectionId && props.connectionId !== onlyConnectionId);
useEffect(() => {
if (!props.connectionId && onlyConnectionId) props.onChange({ connectionId: onlyConnectionId, deviceId: "", host: "" });
}, [props.connectionId, onlyConnectionId, props.onChange]);
const devices = useQuery({ queryKey: ["tailscale-devices", props.companyId, props.connectionId], queryFn: () => tailscaleApi.devices(props.companyId, props.connectionId), enabled: Boolean(props.connectionId) && connections.canManage });
const pairing = useMutation({ mutationFn: (selection: { companyId: string; connectionId: string; deviceId: string; port: number }) => tailscaleApi.pairing(selection.companyId, selection.connectionId, selection.deviceId, selection.port),
onSuccess: (result, selection) => {
if (mounted.current && selection.companyId === props.companyId && selection.connectionId === props.connectionId && selection.deviceId === props.deviceId && selection.port === props.port) props.onPrivateKey(result.privateKeySecretId);
} });
const error = pairing.error ?? connections.error ?? devices.error;
if (!connections.canManage) return <p className="text-sm text-muted-foreground">An instance administrator must configure this Tailscale machine.</p>;
return <div className="grid gap-3">
<p className="text-sm text-muted-foreground"><Link className="underline" to="/apps/tailscale">Manage Tailscale connector</Link></p>
{showConnectionSelector ? <div className="flex items-center gap-3">
<Field label="Tailnet connection">
<select className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm" value={props.connectionId}
onChange={event => props.onChange({ connectionId: event.target.value, deviceId: "", host: "" })}>
<option value="">Choose a connection</option>
{props.connectionId && !connected.some(connection => connection.id === props.connectionId) ? <option value={props.connectionId} disabled>Unavailable connection</option> : null}
{connected.map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)}
</select>
</Field>
</div> : null}
{props.connectionId ? <Field label="Machine">
<select className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm" value={props.deviceId}
disabled={devices.isPending} onChange={event => {
const device = devices.data?.find(device => device.id === event.target.value);
props.onChange({ connectionId: props.connectionId, deviceId: device?.id ?? "", host: device?.address ?? "" });
}}>
<option value="">{devices.isPending ? "Loading machines…" : "Choose a machine"}</option>
{(devices.data ?? []).map(device => <option key={device.id} value={device.id} disabled={!device.online}>{device.name}{device.hostname ? ` — ${device.hostname}` : ""} ({device.os}){device.online ? "" : " — Offline"}</option>)}
</select>
</Field> : null}
{props.deviceId ? <div className="grid gap-3">
<Button type="button" variant="outline" disabled={pairing.isPending} onClick={() => pairing.mutate({ companyId: props.companyId, connectionId: props.connectionId, deviceId: props.deviceId, port: props.port })}>Prepare machine pairing</Button>
{pairing.data && pairing.variables?.companyId === props.companyId && pairing.variables?.deviceId === props.deviceId && pairing.variables?.connectionId === props.connectionId && pairing.variables?.port === props.port ? <>
<p className="text-sm text-muted-foreground">Run this on the selected computer as the user who will run tasks. Enter the printed username, workspace, and known hosts below. Paperclip keeps the private key in its vault.</p>
<textarea aria-label="Machine pairing command" readOnly rows={8} className="w-full rounded-md border border-border bg-transparent p-3 font-mono text-sm" value={pairing.data.command} />
</> : null}
</div> : null}
{error ? <p role="alert" className="text-sm text-destructive">{describeError(error, { action: "connect Tailscale" }).body}</p> : null}
</div>;
}
+19
View File
@@ -0,0 +1,19 @@
import { useQuery } from "@tanstack/react-query";
import { tailscaleApi } from "@/api/tailscale";
import { accessApi } from "@/api/access";
import { queryKeys } from "@/lib/queryKeys";
export const tailscaleConnectionsKey = (companyId: string | null) => ["tailscale-connections", companyId] as const;
export function useTailscaleConnections(companyId: string | null) {
const access = useQuery({ queryKey: queryKeys.access.currentBoardAccess,
queryFn: () => accessApi.getCurrentBoardAccess(), enabled: Boolean(companyId), staleTime: 30_000 });
const canManage = access.data?.source === "local_implicit" || access.data?.isInstanceAdmin === true;
const connections = useQuery({
queryKey: tailscaleConnectionsKey(companyId),
queryFn: () => tailscaleApi.list(companyId!),
enabled: Boolean(companyId) && canManage,
staleTime: 30_000,
});
return { ...connections, data: canManage ? connections.data : undefined, canManage, access };
}
+137
View File
@@ -7,6 +7,14 @@ 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 {
@@ -750,6 +758,135 @@ describe("CompanyEnvironments — test provider button", () => {
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 } } });
+58 -8
View File
@@ -27,6 +27,8 @@ import {
type EnvironmentCustomImageSetupSessionResult,
type EnvironmentUpdateResult,
} from "@/api/environments";
import { TailscaleSshMachine } from "@/components/TailscaleSshMachine";
import { useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import { agentsApi } from "@/api/agents";
import { ApiError } from "@/api/client";
import { describeError } from "@/api/errors";
@@ -70,7 +72,11 @@ type EnvironmentFormState = {
name: string;
description: string;
driver: "local" | "ssh" | "sandbox";
sshNetwork: "direct" | "tailscale";
sshUseHostAuth: boolean;
tailscaleConnectionId: string;
tailscaleDeviceId: string;
tailscaleAuthKeySecretId: string;
sshHost: string;
sshPort: string;
sshUsername: string;
@@ -128,6 +134,10 @@ function buildEnvironmentPayload(form: EnvironmentFormState) {
form.driver === "ssh"
? {
useHostAuth: form.sshUseHostAuth,
...(form.sshNetwork === "tailscale" ? { network: "tailscale" as const,
...(form.tailscaleConnectionId ? { tailscaleConnectionId: form.tailscaleConnectionId, tailscaleDeviceId: form.tailscaleDeviceId } :
{ tailscaleAuthKeySecretRef: form.tailscaleAuthKeySecretId ? { type: "secret_ref" as const, secretId: form.tailscaleAuthKeySecretId, version: "latest" as const } : null }),
} : { network: "direct" as const }),
host: form.sshHost.trim(),
port: Number.parseInt(form.sshPort || "22", 10) || 22,
username: form.sshUsername.trim(),
@@ -150,11 +160,17 @@ function buildEnvironmentPayload(form: EnvironmentFormState) {
}
function createEmptyEnvironmentForm(): EnvironmentFormState {
const connectionId = typeof window === "undefined" ? "" : new URLSearchParams(window.location.search).get("tailscale_connection") ?? "";
const tailscaleSetup = Boolean(connectionId) || (typeof window !== "undefined" && new URLSearchParams(window.location.search).has("tailscale_setup"));
return {
name: "",
description: "",
driver: "ssh",
sshUseHostAuth: false,
sshNetwork: tailscaleSetup ? "tailscale" : "direct",
tailscaleConnectionId: connectionId,
tailscaleDeviceId: "",
tailscaleAuthKeySecretId: "",
sshHost: "",
sshPort: "22",
sshUsername: "",
@@ -186,6 +202,9 @@ function readSshConfig(environment: Environment) {
const config = environment.config ?? {};
return {
useHostAuth: config.useHostAuth !== false,
network: config.network === "tailscale" ? "tailscale" as const : "direct" as const,
tailscaleAuthKeySecretId: typeof (config.tailscaleAuthKeySecretRef as { secretId?: unknown } | null)?.secretId === "string"
? (config.tailscaleAuthKeySecretRef as { secretId: string }).secretId : "",
host: typeof config.host === "string" ? config.host : "",
port:
typeof config.port === "number"
@@ -231,7 +250,11 @@ function createEnvironmentFormFromEnvironment(environment: Environment): Environ
name: environment.name,
description: environment.description ?? "",
driver: "ssh",
tailscaleConnectionId: typeof environment.config.tailscaleConnectionId === "string" ? environment.config.tailscaleConnectionId : "",
tailscaleDeviceId: typeof environment.config.tailscaleDeviceId === "string" ? environment.config.tailscaleDeviceId : "",
sshUseHostAuth: ssh.useHostAuth,
sshNetwork: ssh.network,
tailscaleAuthKeySecretId: ssh.tailscaleAuthKeySecretId,
sshHost: ssh.host,
sshPort: ssh.port,
sshUsername: ssh.username,
@@ -1311,12 +1334,14 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
const { environmentId: routeEnvironmentId } = useParams<{ environmentId?: string }>();
const navigate = useNavigate();
const { selectedCompanyId } = useCompany();
const tailscaleConnections = useTailscaleConnections(selectedCompanyId);
const { setBreadcrumbs } = useBreadcrumbs();
const { pushToast } = useToast();
const queryClient = useQueryClient();
const isEnvironmentFormPage = mode === "create" || mode === "edit";
const editingEnvironmentId = mode === "edit" ? routeEnvironmentId ?? null : null;
const [environmentForm, setEnvironmentForm] = useState<EnvironmentFormState>(createEmptyEnvironmentForm);
const hasConnectedTailnet = tailscaleConnections.data?.some(connection => connection.status === "connected") ?? false;
const environmentVariablesEditorRef = useRef<EnvironmentVariablesEditorHandle | null>(null);
const initializedFormKeyRef = useRef<string | null>(null);
// Fingerprint of the form as initialized; null until the form page has loaded its data.
@@ -1855,7 +1880,8 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
(
environmentForm.sshHost.trim().length > 0 &&
environmentForm.sshUsername.trim().length > 0 &&
environmentForm.sshRemoteWorkspacePath.trim().length > 0
environmentForm.sshRemoteWorkspacePath.trim().length > 0 &&
(environmentForm.sshNetwork !== "tailscale" || Boolean(environmentForm.tailscaleConnectionId && environmentForm.tailscaleDeviceId))
)) &&
(environmentForm.driver !== "sandbox" ||
environmentForm.sandboxProvider.trim().length > 0 &&
@@ -2049,7 +2075,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
<span>
{environment.name}
{isPlatformManagedEnvironment(environment) ? null : (
<span className="text-muted-foreground"> · {environment.driver}</span>
<span className="text-muted-foreground"> · {environment.driver === "ssh" && environment.config.network === "tailscale" ? "ssh via Tailscale" : environment.driver}</span>
)}
</span>
{isPlatformManagedEnvironment(environment) ? (
@@ -2186,6 +2212,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
>
<EnvironmentVariablesEditor
ref={environmentVariablesEditorRef}
footerHint={null}
value={environmentForm.envVars}
secrets={secrets ?? []}
onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}
@@ -2249,9 +2276,6 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
) : null}
</div>
<h1 className="text-lg font-semibold">{editingEnvironmentId ? "Edit environment" : "Add environment"}</h1>
<p className="mt-1 max-w-3xl text-sm text-muted-foreground">
Configure a reusable execution target for your agents. Saved changes affect future runs; Paperclip may start fresh sessions or sandbox leases after environment config changes.
</p>
</div>
<div className="py-4">
@@ -2272,7 +2296,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
onChange={(e) => setEnvironmentForm((current) => ({ ...current, description: e.target.value }))}
/>
</Field>
<Field label="Driver" hint="Sandbox stores plugin-backed provider config on the shared environment seam. SSH stores a remote machine target.">
<Field label="Driver" hint="Choose where agent tasks run. SSH connects to a machine you own.">
<select
className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none"
value={environmentForm.driver}
@@ -2308,11 +2332,35 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
{environmentForm.driver === "ssh" ? (
<div className="grid gap-3 md:grid-cols-2">
<Field label="Host" hint="DNS name or IP address for the remote machine.">
<div className="md:col-span-2">
{environmentForm.sshNetwork === "tailscale" || hasConnectedTailnet ? <Field label="Network" hint="Choose how Paperclip reaches this SSH server.">
<select aria-label="SSH network" className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm" value={environmentForm.sshNetwork}
onChange={event => setEnvironmentForm(current => ({ ...current, sshNetwork: event.target.value === "tailscale" ? "tailscale" : "direct",
tailscaleConnectionId: "", tailscaleDeviceId: "", tailscaleAuthKeySecretId: "", sshHost: "", sshPrivateKey: "", sshPrivateKeySecretId: "", sshKnownHosts: "" }))}>
<option value="direct">Direct connection</option>
<option value="tailscale">Tailscale</option>
</select>
</Field> : null}
{tailscaleConnections.error ? <p role="alert" className="text-sm text-destructive">{describeError(tailscaleConnections.error, { action: "load Tailscale connections" }).body}</p> : null}
{tailscaleConnections.data !== undefined && !hasConnectedTailnet && environmentForm.sshNetwork === "direct" ?
<p className="text-sm text-muted-foreground"><Link className="underline" to="/apps/tailscale">Connect Tailscale Network</Link> to choose machines from your tailnet.</p> : null}
</div>
{environmentForm.sshNetwork === "tailscale" && selectedCompanyId ? (
<div className="md:col-span-2">
<TailscaleSshMachine companyId={selectedCompanyId} connectionId={environmentForm.tailscaleConnectionId} deviceId={environmentForm.tailscaleDeviceId}
port={Number(environmentForm.sshPort) || 22} onPrivateKey={secretId => {
setEnvironmentForm(current => ({ ...current, sshPrivateKey: "", sshPrivateKeySecretId: secretId }));
void queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) });
}}
onChange={selection => setEnvironmentForm(current => ({ ...current, tailscaleConnectionId: selection.connectionId, tailscaleDeviceId: selection.deviceId, sshHost: selection.host, sshPrivateKey: "", sshPrivateKeySecretId: "", sshKnownHosts: "" }))} />
</div>
) : null}
<Field label="Host" hint={environmentForm.sshNetwork === "tailscale" ? "Tailscale IP address or MagicDNS name of your machine." : "DNS name or IP address for the remote machine."}>
<input
className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm outline-none"
type="text"
value={environmentForm.sshHost}
readOnly={environmentForm.sshNetwork === "tailscale" && Boolean(environmentForm.tailscaleConnectionId)}
onChange={(e) => setEnvironmentForm((current) => ({ ...current, sshHost: e.target.value }))}
/>
</Field>
@@ -2490,6 +2538,7 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
>
<EnvironmentVariablesEditor
ref={environmentVariablesEditorRef}
footerHint={null}
value={environmentForm.envVars}
secrets={secrets ?? []}
onCreateSecret={async (name, value) => await createSecret.mutateAsync({ name, value })}
@@ -2524,7 +2573,8 @@ export function CompanyEnvironments({ mode = "list" }: CompanyEnvironmentsProps)
<Button
variant="outline"
onClick={() => draftEnvironmentProbeMutation.mutate(flushEnvironmentForm())}
disabled={draftEnvironmentProbeMutation.isPending || !environmentFormValid}
disabled={draftEnvironmentProbeMutation.isPending || !environmentFormValid || (environmentForm.driver === "ssh" && environmentForm.sshNetwork === "tailscale")}
title={environmentForm.driver === "ssh" && environmentForm.sshNetwork === "tailscale" ? "Save this environment, then test its connection from the list." : undefined}
>
{draftEnvironmentProbeMutation.isPending ? "Testing..." : "Test"}
</Button>
+1 -1
View File
@@ -215,7 +215,7 @@ describe("CompanyEnvironments", () => {
});
});
it("omits the Local driver option and lists Sandbox before SSH", async () => {
it("omits the Local driver option and lists Sandbox before SSH and Tailscale", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
+35
View File
@@ -55,6 +55,8 @@ vi.mock("@/api/ai-connection-pools", () => ({ aiConnectionPoolsApi: { list: pool
const assistantConnectionsMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/publicMcp", () => ({ publicMcpApi: { connections: assistantConnectionsMock } }));
const tailscaleConnectionsMock = vi.hoisted(() => vi.fn(async () => [] as Array<{ id: string; companyId: string; name: string; status: string }>));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: { list: tailscaleConnectionsMock } }));
const listGalleryMock = vi.hoisted(() => vi.fn());
const listApplicationsMock = vi.hoisted(() => vi.fn());
@@ -63,6 +65,7 @@ const listAiConnectionsMock = vi.hoisted(() => vi.fn());
const setAiDefaultMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { list: listAiConnectionsMock, setDefault: setAiDefaultMock } }));
const listUserDirectoryMock = vi.hoisted(() => vi.fn());
const boardAccessMock = vi.hoisted(() => vi.fn());
const archiveConnectionMock = vi.hoisted(() => vi.fn());
const pushToastMock = vi.hoisted(() => vi.fn());
const navigateMock = vi.hoisted(() => vi.fn());
@@ -99,6 +102,7 @@ vi.mock("@/api/tools", () => ({
vi.mock("@/api/access", () => ({
accessApi: {
listUserDirectory: (companyId: string) => listUserDirectoryMock(companyId),
getCurrentBoardAccess: boardAccessMock,
},
}));
@@ -199,6 +203,7 @@ describe("Connectors landing page", () => {
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
boardAccessMock.mockReset().mockResolvedValue({ source: "session", isInstanceAdmin: true });
accountIdentity.userId = "board-user"; accountIdentity.settled = true;
assistantConnectionsMock.mockReset().mockResolvedValue([]);
syncComposioAppsMock.mockReset().mockImplementation((...args) => listComposioAppsMock(...args));
@@ -304,6 +309,35 @@ describe("Connectors landing page", () => {
expect(chatSetupMock).not.toHaveBeenCalled();
});
it("finds Tailscale in Connectors and opens network setup without creating a tool connection", async () => {
await renderBrowse(false);
await search("Tailscale");
const button = container.querySelector<HTMLButtonElement>('[aria-label="Connect Tailscale"]');
expect(button).not.toBeNull();
await act(() => button!.click());
expect(navigateMock).toHaveBeenCalledWith("/apps/tailscale");
expect(container.textContent).not.toContain("No connectors match");
});
it("does not advertise Tailscale setup or request tailnets for non-instance-admin members", async () => {
boardAccessMock.mockResolvedValue({ source: "session", isInstanceAdmin: false });
await renderBrowse(false);
await search("Tailscale");
expect(container.querySelector('[aria-label="Connect Tailscale"]')).toBeNull();
expect(container.querySelector('[data-app-slug="tailscale"]')).toBeNull();
expect(tailscaleConnectionsMock).not.toHaveBeenCalled();
});
it("shows a connected tailnet in Installed and removes it when disconnected", async () => {
tailscaleConnectionsMock.mockResolvedValueOnce([{ id: "tailnet", companyId: "company-1", name: "Home tailnet", status: "connected" }]);
const client = await renderBrowse(false);
await clickButton("Installed", container);
expect(container.querySelector('[data-app-slug="tailscale"]')?.textContent).toContain("Home tailnet");
await act(async () => { await client.invalidateQueries({ queryKey: ["tailscale-connections", "company-1"] }); });
await flushReact();
expect(container.querySelector('[data-app-slug="tailscale"]')).toBeNull();
});
it("keeps assistant setup in the Paperclip catalog when filtering connection sources", async () => {
await renderBrowse(false);
const assistantButton = () => container.querySelector('[aria-label="Set up Assistant Connection (MCP)"]');
@@ -1388,6 +1422,7 @@ describe("Connectors landing page", () => {
"notion",
"slack",
"speko",
"tailscale",
"telegram",
"custom-mcp",
]);
+14 -2
View File
@@ -12,6 +12,9 @@ import {
RETIRED_COMPOSIO_MESSAGE,
} from "@paperclipai/shared";
import { AssistantConnectionCard, useAssistantConnections } from "./AssistantConnection";
import { TailscaleConnectorCard } from "./TailscaleConnector";
import { useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import type { TailscaleConnection } from "@/api/tailscale";
import { ManagedAiConnectionRow } from "@/components/ai-connections/ManagedAiConnectionDetails";
import { useAiConnectionDefaults } from "@/components/ai-connections/useAiConnectionDefaults";
import { AiDefaultCrown, AiDefaultError, AiDefaultMenuItem } from "@/components/ai-connections/AiConnectionDefault";
@@ -130,6 +133,7 @@ type ConnectorRowModel = {
applications: ToolApplication[];
connections: ToolConnection[];
chatEndpoints: ChatEndpoint[];
networkConnections?: TailscaleConnection[];
aggregatorApp?: AggregatorAppCatalogEntry;
upstreamApps?: (ComposioAppSnapshot & Partial<Pick<AggregatorAppSnapshot, "provider" | "appSlug" | "appName" | "freshness">>)[];
upstreamCatalogApp?: AggregatorAppCatalogEntry;
@@ -288,6 +292,7 @@ function rowRank(row: ConnectorRowModel): number {
if (
row.chatEndpoints.some((endpoint) => endpoint.status !== "draft") ||
row.connections.some((connection) => connectionRank(connection) === 1) ||
row.networkConnections?.some(connection => connection.status === "connected") ||
row.upstreamApps?.some((app) => app.status === "connected")
)
return 2;
@@ -295,7 +300,7 @@ function rowRank(row: ConnectorRowModel): number {
}
function isInstalled(row: ConnectorRowModel) {
return row.connections.length > 0 || row.chatEndpoints.length > 0 || Boolean(row.upstreamApps?.some(app => app.accounts.length > 0));
return row.connections.length > 0 || row.chatEndpoints.length > 0 || Boolean(row.upstreamApps?.some(app => app.accounts.length > 0)) || Boolean(row.networkConnections?.some(connection => connection.status === "connected"));
}
function connectorAction(
@@ -390,6 +395,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
const { pushToast } = useToast();
const { selectedCompanyId } = useCompany();
const assistantConnections = useAssistantConnections();
const tailscaleConnections = useTailscaleConnections(selectedCompanyId);
const { userId: viewingUserId, settled: identitySettled } = useAccountIdentity();
const { enabled: chatConnectorsEnabled, githubEnabled } = useChatConnectorsEnabled();
const { enabled: memoryConnectorsEnabled } = useMemoryConnectorsEnabled();
@@ -634,6 +640,9 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
]),
);
const rowsBySlug = new Map<string, ConnectorRowModel>();
if (tailscaleConnections.canManage) rowsBySlug.set("tailscale", { key: "network:tailscale", slug: "tailscale", name: "Tailscale",
description: "Connect your tailnet to use its machines in SSH environments.", brandKey: "tailscale", entry: null,
applications: [], connections: [], chatEndpoints: [], networkConnections: tailscaleConnections.data ?? [] });
for (const entry of gallery) {
const slug = appDefinitionSlug(entry);
rowsBySlug.set(slug, {
@@ -899,6 +908,8 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
chatConnectorsEnabled,
githubEnabled,
connectionsQuery.data,
tailscaleConnections.data,
tailscaleConnections.canManage,
gallery,
galleryQuery.data,
googleWorkspaceConnectorEnabled,
@@ -925,6 +936,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
return scoped.filter((row) => {
const text = normalizeConnectionQuery([row.name, row.slug, row.description,
...(row.aggregatorApp?.aliases ?? []), ...row.connections.map((connection) => connection.name),
...(row.networkConnections ?? []).map(connection => connection.name),
...(row.upstreamApps ?? []).flatMap(app => app.accounts.map(account => account.alias)),
...row.chatEndpoints.map((endpoint) => endpoint.assignedAgentName)].join(" "));
return terms.every((term) => text.includes(term));
@@ -1039,7 +1051,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
<div className="space-y-3" role="list" aria-label="Connector list">
{showAssistantConnection && <AssistantConnectionCard onNavigate={navigate} />}
{paginatedRows.map((row) => (
<ConnectorCard
row.networkConnections ? <TailscaleConnectorCard key={row.key} onNavigate={navigate} /> : <ConnectorCard
renderAccountDetails={renderAccountDetails}
aiDefaults={aiDefaults}
key={row.key}
@@ -0,0 +1,169 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TailscaleConnector, TailscaleConnectorCard } from "./TailscaleConnector";
import { ApiError } from "@/api/client";
import { readPendingCloudHandoff } from "@/lib/oauthHandoff";
import { PaperclipCloudOAuthHandoffPage } from "./PaperclipCloudOAuthHandoff";
const fixture = vi.hoisted(() => ({ companyId: "company-1", search: "", navigate: vi.fn(), access: vi.fn(), list: vi.fn(), connect: vi.fn(), disconnect: vi.fn(), breadcrumbs: vi.fn() }));
vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: fixture.access } }));
vi.mock("@/api/tailscale", () => ({ tailscaleApi: { list: fixture.list, connect: fixture.connect, disconnect: fixture.disconnect } }));
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: fixture.companyId }) }));
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }) }));
vi.mock("./AppLogo", () => ({ AppLogo: () => null }));
vi.mock("@/lib/router", () => ({ Link: ({ to, children, ...props }: { to: string; children: React.ReactNode }) => <a href={to} {...props}>{children}</a>, useSearchParams: () => [new URLSearchParams(fixture.search)] }));
vi.mock("@/lib/browserNavigation", () => ({ navigateTopLevel: (url: string) => fixture.navigate(url) }));
const connected = { id: "tailnet-1", companyId: "company-1", name: "Home tailnet", status: "connected" };
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
const render = () => flushSync(() => root.render(<QueryClientProvider client={client}><TailscaleConnector /></QueryClientProvider>));
async function settle() {
for (let i = 0; i < 6; i++) await new Promise(resolve => setTimeout(resolve, 0));
}
function button(label: string) {
const result = [...container.querySelectorAll("button")].find(element => element.textContent === label);
expect(result).toBeDefined();
return result!;
}
describe("Tailscale network connector", () => {
beforeEach(() => {
vi.clearAllMocks();
fixture.companyId = "company-1";
fixture.search = "";
window.sessionStorage.clear();
fixture.access.mockResolvedValue({ source: "session", isInstanceAdmin: true, companyIds: ["company-1", "company-2"] });
fixture.list.mockResolvedValue([connected]);
fixture.connect.mockImplementation(() => new Promise(() => {}));
fixture.disconnect.mockResolvedValue({ ...connected, status: "disconnected" });
container = document.createElement("div");document.body.append(container);
root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => { flushSync(() => root.unmount());client.clear();container.remove();vi.unstubAllGlobals(); });
it("does not offer setup or request tailnets to a company member without instance-admin rights", async () => {
fixture.access.mockResolvedValue({ source: "session", isInstanceAdmin: false, companyIds: ["company-1"] });
flushSync(() => root.render(<QueryClientProvider client={client}><TailscaleConnectorCard onNavigate={vi.fn()} /></QueryClientProvider>));
await settle();
expect(fixture.list).not.toHaveBeenCalled();
expect(container.querySelector("button")).toBeNull();
render();await settle();
expect(container.textContent).toContain("instance administrator");
expect(container.querySelector("button")).toBeNull();
expect(fixture.list).not.toHaveBeenCalled();
});
it("waits for management access before requesting network data", async () => {
fixture.access.mockImplementationOnce(() => new Promise(() => {}));
render();await settle();
expect(container.textContent).toContain("Checking Tailscale management access");
expect(fixture.list).not.toHaveBeenCalled();
expect(fixture.connect).not.toHaveBeenCalled();
});
it("allows a local implicit board to manage its network", async () => {
fixture.access.mockResolvedValue({ source: "local_implicit", isInstanceAdmin: false });
render();await settle();
expect(fixture.list).toHaveBeenCalledWith("company-1");
expect(button("Connect Tailscale Network").disabled).toBe(false);
});
it("reuses an approved tailnet and links to an ordinary SSH environment", async () => {
render();await settle();
expect(fixture.list).toHaveBeenCalledWith("company-1");
expect(container.textContent).toContain("Home tailnet");
expect(container.textContent).toContain("any harness supported");
expect(container.textContent).not.toContain("Claude");
expect(container.querySelector('a[href="/company/settings/instance/environments/new?tailscale_connection=tailnet-1"]')?.textContent).toBe("Create SSH environment");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("starts OAuth from Connectors only when the user clicks Connect", async () => {
render();await settle();
flushSync(() => button("Connect Tailscale Network").click());await settle();
expect(fixture.connect).toHaveBeenCalledWith("company-1", undefined);
expect(button("Connecting…").disabled).toBe(true);
});
it("reconnects the existing connection instead of creating another record", async () => {
fixture.list.mockResolvedValue([{ ...connected, status: "disconnected" }]);
render();await settle();
flushSync(() => button("Reconnect Home tailnet").click());await settle();
expect(fixture.connect).toHaveBeenCalledWith("company-1", "tailnet-1");
});
it("preserves the current tab's Cloud handoff through reauthentication and resumes consent", async () => {
const session = "tailscale_handoff_session_abcdefghijklmnop";
const reauthenticationUrl = new URL(`/cloud/connections/reauth?session=${session}`, window.location.origin).toString();
fixture.connect.mockResolvedValue({ authorizationUrl: "", handoff: { kind: "paperclip_cloud", session } });
vi.stubGlobal("fetch", vi.fn()
.mockResolvedValueOnce(Response.json({ error: "RECENT_LOGIN_REQUIRED", reauthenticationUrl }, { status: 401 }))
.mockResolvedValueOnce(Response.json({ authorizationUrl: "https://login.tailscale.com/a/oauth_authorize" })));
fixture.navigate.mockImplementationOnce(() => {
expect(readPendingCloudHandoff()).toEqual({ kind: "paperclip_cloud", session });
});
render();await settle();
flushSync(() => button("Connect Tailscale Network").click());await settle();
expect(readPendingCloudHandoff()).toEqual({ kind: "paperclip_cloud", session });
expect(fixture.navigate).toHaveBeenCalledWith(reauthenticationUrl);
flushSync(() => root.render(<PaperclipCloudOAuthHandoffPage />));await settle();
expect(fixture.navigate).toHaveBeenLastCalledWith("https://login.tailscale.com/a/oauth_authorize");
expect(readPendingCloudHandoff()).toBeNull();
expect(container.textContent).not.toContain("expired");
});
it.each(["cancelled", "failed"])("explains %s consent and retries the same saved connection", async outcome => {
fixture.search = `tailscale_connection=tailnet-1&tailscale_error=${outcome}`;
fixture.list.mockResolvedValue([{ ...connected, status: "pending" }]);
render();await settle();
expect(container.querySelector('[role="alert"]')?.textContent).toContain(outcome === "cancelled" ? "was canceled" : "could not be completed");
flushSync(() => button("Try again").click());await settle();
expect(fixture.connect).toHaveBeenCalledExactlyOnceWith("company-1", "tailnet-1");
});
it("does not offer a saved-connection retry for a connection outside the current company", async () => {
fixture.search = "tailscale_connection=foreign-connection&tailscale_error=cancelled";
render();await settle();
expect([...container.querySelectorAll("button")].some(element => element.textContent === "Try again")).toBe(false);
expect(fixture.connect).not.toHaveBeenCalled();
});
it("does not display untrusted error text from the return URL", async () => {
fixture.search = new URLSearchParams({ tailscale_connection: "tailnet-1", tailscale_error: "untrusted-provider-error<script>" }).toString();
render();await settle();
expect(container.textContent).not.toContain("untrusted-provider-error");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("refreshes connector status after a deliberate disconnect", async () => {
fixture.list.mockResolvedValueOnce([connected]).mockResolvedValue([{ ...connected, status: "disconnected" }]);
render();await settle();
flushSync(() => button("Disconnect Home tailnet").click());await settle();
expect(fixture.disconnect).toHaveBeenCalledWith("company-1", "tailnet-1");
expect(container.textContent).toContain("Disconnected");
expect(container.textContent).not.toContain("Create SSH environment");
});
it("reports access failure without presenting a usable connection or starting OAuth", async () => {
fixture.list.mockRejectedValue(new ApiError("Instance admin access required", 403, { error: "forbidden" }));
render();await settle();
expect(container.querySelector('[role="alert"]')).not.toBeNull();
expect(button("Connect Tailscale Network").disabled).toBe(true);
expect(container.textContent).not.toContain("Home tailnet");
expect(fixture.connect).not.toHaveBeenCalled();
});
it("does not retain another company's tailnets when the organization changes", async () => {
fixture.list.mockImplementation(async companyId => companyId === "company-1" ? [connected] : []);
render();await settle();
expect(container.textContent).toContain("Home tailnet");
fixture.companyId = "company-2";render();await settle();
expect(container.textContent).not.toContain("Home tailnet");
expect(fixture.list).toHaveBeenCalledWith("company-2");
});
});
+80
View File
@@ -0,0 +1,80 @@
import { useEffect } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { tailscaleApi } from "@/api/tailscale";
import { describeError } from "@/api/errors";
import { Button } from "@/components/ui/button";
import { useCompany } from "@/context/CompanyContext";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { tailscaleConnectionsKey, useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import { Link, useSearchParams } from "@/lib/router";
import { prepareOAuthNavigation, savePendingCloudHandoff } from "@/lib/oauthHandoff";
import { navigateTopLevel } from "@/lib/browserNavigation";
import { AppLogo } from "./AppLogo";
export const TAILSCALE_CONNECTOR_PATH = "/apps/tailscale";
export function TailscaleConnectorCard({ onNavigate }: { onNavigate: (href: string) => void }) {
const { selectedCompanyId } = useCompany();
const connections = useTailscaleConnections(selectedCompanyId);
const connected = connections.data?.filter(connection => connection.status === "connected") ?? [];
if (!connections.canManage) return null;
return <div role="listitem" data-app-slug="tailscale" data-connected={String(connected.length > 0)} className="overflow-hidden rounded-xl border border-border">
<div className="flex flex-wrap items-center gap-3 px-4 py-4">
<AppLogo name="Tailscale" brandKey="tailscale" size={36} />
<div className="min-w-0 flex-1">
<h2 className="text-sm font-semibold text-foreground">Tailscale</h2>
<p className="mt-0.5 text-xs text-muted-foreground">Connect your tailnet to use its machines in SSH environments.</p>
</div>
<Button type="button" size="sm" variant="outline" onClick={() => onNavigate(TAILSCALE_CONNECTOR_PATH)} aria-label={`${connected.length ? "Manage" : "Connect"} Tailscale`}>{connected.length ? "Manage" : "Connect"}</Button>
</div>
{connected.length > 0 && <p className="border-t border-border px-4 py-3 text-sm text-muted-foreground">{connected.map(connection => connection.name).join(", ")} · Connected</p>}
{connections.error && <p role="alert" className="border-t border-border px-4 py-3 text-sm text-destructive">{describeError(connections.error, { action: "load Tailscale connections" }).body}</p>}
</div>;
}
export function TailscaleConnector() {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const client = useQueryClient();
const [searchParams] = useSearchParams();
const connections = useTailscaleConnections(selectedCompanyId);
const connect = useMutation({ mutationFn: async (connectionId?: string) => {
const result = await tailscaleApi.connect(selectedCompanyId!, connectionId);
const target = await prepareOAuthNavigation(result);
if (target.kind === "reauthentication" && result.handoff) savePendingCloudHandoff(result.handoff.session);
navigateTopLevel(target.url);
} });
const disconnect = useMutation({ mutationFn: (connectionId: string) => tailscaleApi.disconnect(selectedCompanyId!, connectionId),
onSuccess: () => client.invalidateQueries({ queryKey: tailscaleConnectionsKey(selectedCompanyId) }) });
useEffect(() => {
setBreadcrumbs([{ label: "Connectors", href: "/apps" }, { label: "Tailscale" }]);
return () => setBreadcrumbs([]);
}, [setBreadcrumbs]);
if (!selectedCompanyId) return <p className="text-sm text-muted-foreground">Select an organization to connect Tailscale.</p>;
if (connections.access.isPending) return <p className="text-sm text-muted-foreground">Checking Tailscale management access…</p>;
if (connections.access.error) return <p role="alert" className="text-sm text-destructive">{describeError(connections.access.error, { action: "check Tailscale management access" }).body}</p>;
if (!connections.canManage) return <p className="text-sm text-muted-foreground">Ask an instance administrator to connect or manage Tailscale networks.</p>;
const error = connect.error ?? disconnect.error ?? connections.error;
const outcome = searchParams.get("tailscale_error");
const returnError = outcome === "cancelled" ? "Tailscale authorization was canceled. Try again to connect your network."
: outcome === "failed" ? "Tailscale authorization could not be completed. Try again." : null;
const retryConnection = connections.data?.find(connection => connection.id === searchParams.get("tailscale_connection"));
return <div className="max-w-3xl space-y-6 pb-8">
<header className="flex items-center gap-3"><AppLogo name="Tailscale" brandKey="tailscale" size={36} /><h1 className="text-xl font-semibold">Tailscale</h1></header>
<p className="text-sm text-muted-foreground">Give Paperclip access to your tailnet, then choose one of its machines when creating an SSH environment. Agents can use any harness supported by that environment.</p>
{connections.isPending && <p className="text-sm text-muted-foreground">Loading tailnet connections…</p>}
{returnError && <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{returnError}</p>{retryConnection && <Button variant="outline" disabled={connect.isPending} onClick={() => connect.mutate(retryConnection.id)}>Try again</Button>}</div>}
{error && <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{describeError(error, { action: "connect Tailscale" }).body}</p><Button variant="outline" onClick={() => void connections.refetch()}>Refresh connections</Button></div>}
<div className="divide-y divide-border">{(connections.data ?? []).map(connection => <div key={connection.id} className="flex flex-wrap items-center justify-between gap-3 py-3">
<div className="min-w-0 flex-1 space-y-1"><p className="font-medium">{connection.name}</p><p className="text-sm text-muted-foreground">{connection.status === "connected" ? "Connected" : connection.status === "connecting" ? "Connecting" : connection.status === "disconnected" ? "Disconnected" : "Authorization not completed"}</p></div>
{connection.status === "connected" ? <>
<Button variant="outline" asChild><Link to={`/company/settings/instance/environments/new?tailscale_connection=${encodeURIComponent(connection.id)}`}>Create SSH environment</Link></Button>
<Button variant="ghost" disabled={disconnect.isPending} onClick={() => disconnect.mutate(connection.id)}>Disconnect {connection.name}</Button>
</> : <Button variant="outline" disabled={connect.isPending} onClick={() => connect.mutate(connection.id)}>Reconnect {connection.name}</Button>}
</div>)}</div>
<footer className="flex items-center justify-between gap-3 border-t border-border pt-4">
<Button variant="ghost" asChild><Link to="/apps">Back to connectors</Link></Button>
<Button disabled={connect.isPending || connections.isError} onClick={() => connect.mutate(undefined)}>{connect.isPending ? "Connecting…" : "Connect Tailscale Network"}</Button>
</footer>
</div>;
}