Files
PaperClipAI/ui/src/pages/tools/connection-dialogs.tsx
T
a3313f6944 fix(ui): complete read recovery and enforce query error rendering (#18822)
## Thinking Path

> - Paperclip lets people manage agent work through the board.
> - The board reads task, agent, settings, plugin, and run data from the
server.
> - A deploy can interrupt those reads after content is already visible.
> - Local error branches can replace that content with an error or show
raw codes.
> - This pull request moves the remaining reads to the shared recovery
behavior.
> - The query-error guard prevents new local error patterns from
returning.

## Linked Issues or Issue Description

**What happened?**
Loaded lists, settings, task panels, and manual reads could clear their
content or show errors during a server restart. Some reads also disabled
the shared retry policy.

**Expected behavior**
Keep loaded content during a temporary failure. Show the shared
connection banner. Retry reads after recovery. Replace content after a
real access denial or missing resource, with readable copy.

**Steps to reproduce**
Open a task, settings page, or run log. Return 503 with
`tenant_app_unavailable` from the API. Restore the API and check that
content refreshes. Repeat with 403 and 404 to check the failure state.

Related merged work: Refs #15754, Refs #15772, Refs #17960. This change
covers remaining reads and enforcement. Browser persistence and the
outage browser suite follow separately.

## What Changed

- Repair an existing PostgreSQL deadline fixture at UTC boundaries. A
daily cap defers a heartbeat until both its original interval and the
next UTC day allow it. Keep the counted run in its seeded day and cover
noon, just before midnight and the first second after midnight with
explicit clocks and real PostgreSQL. Production scheduling is unchanged.

- Integrate the saved list, settings, shell, task, and manual-read
recovery changes against current master. Preserve the current task,
Inbox, and run-log structure.
- Add `useResilientFetch` for component-local reads. Preserve loaded
data, cancel stale requests, and retry through the shared connectivity
policy. Keep browser and pairing capabilities in memory.
- Retain run log chunks across stream changes and catch up after
recovery without duplicate chunks or stalled requests.
- Keep genuine authorization and missing-resource failures visible.
Translate known single-word codes such as `forbidden`. Show known skills
and disconnected-app failures before sibling loading states. Keep Retry
bound to its failed request.
- Make the query-error guard enforce by default and run it in the CI
policy job. Document the narrow exceptions and the read recovery
contract.
- Invalidate pending OAuth discovery when the operator leaves setup or
its context changes. Keep reserved-popup cleanup bound to the current
attempt.

## Verification

- Current read head `09d1db29dea` is merge-ready: all 59 check runs are
completed (54 successful, three skipped, two neutral), the legacy Snyk
status is successful, and both required `ci / verify` and `ci / e2e`
gates pass. Greptile Apex reviewed this exact head at 5/5 with no
unresolved threads; the branch has no merge conflicts. The current CI
run is `41748339602`.
- Current read head `09d1db29dea` includes master `683fa4725e9`. The
latest change touches only the existing server deadline test fixture.
Application source remains the previously verified `86376fa751e`
revision: all 60 affected skills/disconnected-app tests and both
application UI typechecks passed, along with token gates and the
enforcing query-error guard. Those UI suites were not repeated for this
test-only repair.
- The fixture repair passes all seven deadline integration cases and the
complete server typecheck, including the server test layer. The old
assertion deterministically fails at 23:59:06.888 UTC; its
one-second-old run also fails the first-second-of-day probe. The
corrected fixture passes noon and both midnight probes. The permanent
three-case coverage uses seeded 2099 clocks.
- Twelve new regressions fail against the previous implementation. Both
skills variants and disconnected-app pages show either request's 403 or
429 while the sibling pauses or remains fetching. Permission failures
stay visible. Retry stays usable for its failed request and recovers
independently. An initial test-fixture query-key typo was corrected
before the passing run. The finding is replied to and resolved. Greptile
reviewed prior application revision `86376fa751e` at 5/5 with no new
actionable findings or unresolved threads. The current test-only head
has now received its own Apex 5/5 review with no unresolved threads, and
its CI is successful as recorded above.
- The preceding OAuth fix passed all 237 setup tests on both application
branches. Its ten regressions prove that Back, Cancel, unmount, or
context changes retire initial discovery without creating a connection,
caching old identities, navigating an abandoned popup, or closing a
newer attempt.
- Earlier master integration `e992f770339` passed all 309 tests across
eight affected Slack, recovery, retry, submission and task files, plus
UI typecheck, token gates, enforcing query-error scan and seven guard
tests. The integration preserves Slack workspace reconnect and shared
recovery, readable execution errors, source-inspection company scoping,
and current submission behavior. Newly inherited retained-file recovery
controls keep cached data through transient failures and hide it after
definitive denial.
- The preceding cache head `97c0bc3966f` passed 1,038 focused
cache/write/editor/account/task/API tests. All 22 built-UI
outage/write/loading cases passed in 4.7 minutes on exact browser head
`b7deaaee5da`, with strict checking of all three specs. The latest
skills/app rendering fix is covered by its affected component suites;
those broader cases were not repeated for this separate read path.
- Historical broader UI, CLI and build results and unresolved aggregate
server/DB/adapter failures remain in the PR discussion. Interrupted CI
runs were audited and recorded separately; they are not counted as
passes. Controlled local outages do not prove hosted authentication or a
real Cloud restart/deploy. Real hosted acceptance remains required after
merge and deployment.

Commands for the latest fix:

```sh
pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx
pnpm --filter @paperclipai/ui typecheck
pnpm check:token-gates
node scripts/check-query-error-rendering.mjs --enforce --summary
```

## Risks

This migration touches many read surfaces. The main risks are initial
loading, request cancellation, retained authorization state, and run-log
paging. The tests cover those states. There are no server, schema,
dependency, or API contract changes. The follow-up browser suite and
hosted deploy acceptance are required before release acceptance.

Recovered commits retain their original authors. If squash-merging,
preserve `Co-Authored-By: Bender (Fable) <bender@agents.paperclip.ing>`
and the Paperclip trailer.

## Model Used

OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool
use, and code execution. The context window size is not exposed. Saved
source commits keep their original authorship.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] The affected local tests pass; broader limitations are recorded
above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Bender (Fable) <bender@agents.paperclip.ing>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 14:07:18 -08:00

578 lines
23 KiB
TypeScript

import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { KeyRound, Stethoscope, Trash2, Vault } from "lucide-react";
import type {
CompanySecret,
McpConnectionCredentialRef,
ToolConnection,
} from "@paperclipai/shared";
import { queryKeys } from "@/lib/queryKeys";
import { toolsApi, type CreateToolConnectionInput } from "@/api/tools";
import { secretsApi } from "@/api/secrets";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/context/ToastContext";
import { redactUrlSecrets } from "@/lib/redact-url-secrets";
import {
LoadingState,
HealthBadge,
RiskBadge,
CapabilityBadges,
QuarantineBadge,
} from "./shared";
import { describeError } from "@/api/errors";
export const TRANSPORT_LABEL: Record<string, string> = {
mcp_remote: "remote http",
local_stdio: "local stdio",
};
/** Mono URL (remote) or command-template (stdio) subtitle for a connection row. */
export function connectionEndpoint(conn: ToolConnection): string | null {
const config = { ...(conn.transportConfig ?? {}), ...(conn.config ?? {}) } as Record<string, unknown>;
const url = config.url ?? config.endpoint ?? config.endpointUrl;
if (typeof url === "string" && url.trim()) return redactUrlSecrets(url);
const template = config.templateId ?? config.template ?? config.command;
if (typeof template === "string" && template.trim()) return template.trim();
if (Array.isArray(config.command)) return config.command.join(" ");
return null;
}
/**
* Display-only vault reference for a credential. The persisted shape is the
* structured {@link McpConnectionCredentialRef} (secretId + version) — this is
* just the human-readable `vault://provider/key@version` rendering of it so the
* operator can confirm *which* vault entry resolves at gateway time. Free-text
* secrets are never accepted; only references to the secret vault.
*/
function vaultRef(secret: CompanySecret | undefined, version: number | "latest" = "latest"): string {
if (!secret) return "vault://…";
const v = version === "latest" || version === undefined ? "latest" : `v${version}`;
return `vault://${secret.provider}/${secret.key}@${v}`;
}
export function CatalogDialog({ connection, onClose }: { connection: ToolConnection; onClose: () => void }) {
const catalog = useQuery({
queryKey: queryKeys.tools.catalog(connection.id),
queryFn: () => toolsApi.listCatalog(connection.id),
});
const catalogView = useQueryView(catalog);
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Tool catalog — {connection.name}</DialogTitle>
</DialogHeader>
{catalog.isLoading || catalogView.kind === "reconnecting" ? (
<LoadingState />
) : catalogView.kind === "error" ? (
<QueryErrorState
error={catalog.error}
action="load the tool catalog"
onRetry={catalogView.retry}
retrying={catalogView.isFetching}
/>
) : (catalog.data?.catalog ?? []).length === 0 ? (
<p className="py-6 text-sm text-muted-foreground">
No tools discovered yet. Use “Refresh catalog” to discover tools from this connection.
</p>
) : (
<ul className="max-h-(--sz-60vh) divide-y divide-border overflow-y-auto">
{(catalog.data?.catalog ?? []).map((entry) => (
<li key={entry.id} className="flex flex-wrap items-center gap-2 py-2.5">
<span className="font-mono text-sm text-foreground">{entry.toolName}</span>
<RiskBadge risk={entry.riskLevel} />
<CapabilityBadges
isReadOnly={entry.isReadOnly}
isWrite={entry.isWrite}
isDestructive={entry.isDestructive}
/>
{entry.status === "quarantined" ? <QuarantineBadge /> : null}
{entry.description ? (
<p className="w-full truncate text-xs text-muted-foreground">{entry.description}</p>
) : null}
</li>
))}
</ul>
)}
</DialogContent>
</Dialog>
);
}
type CredentialDraft = { secretId: string; headerName: string };
/** Probe outcome captured before activation: health + discovered tool count + round-trip latency. */
type ProbeResult = {
connection: ToolConnection;
toolCount: number | null;
quarantinedCount: number;
latencyMs: number | null;
};
/**
* New-connection dialog. Enforces secret *references* (no free-text token field)
* and runs a live gateway probe (health-check + catalog discovery) against the
* draft before the operator activates it — per the Phase 0B spec surface map.
*/
export function AddConnectionDialog({
companyId,
defaultApplicationId,
onClose,
}: {
companyId: string;
defaultApplicationId?: string | null;
onClose: () => void;
}) {
const qc = useQueryClient();
const { pushToast } = useToast();
const apps = useQuery({
queryKey: queryKeys.tools.applications(companyId),
queryFn: () => toolsApi.listApplications(companyId),
});
const secrets = useQuery({
queryKey: queryKeys.secrets.list(companyId),
queryFn: () => secretsApi.list(companyId),
});
const templates = useQuery({
queryKey: queryKeys.tools.stdioTemplates(companyId),
queryFn: () => toolsApi.listStdioTemplates(companyId),
});
const [step, setStep] = useState<1 | 2>(defaultApplicationId ? 2 : 1);
const [applicationMode, setApplicationMode] = useState<"existing" | "new">(
"existing",
);
const [applicationId, setApplicationId] = useState(defaultApplicationId ?? "");
const [applicationName, setApplicationName] = useState("");
const [name, setName] = useState("");
const [transport, setTransport] = useState<"mcp_remote" | "local_stdio">("mcp_remote");
const [endpointUrl, setEndpointUrl] = useState("");
const [templateId, setTemplateId] = useState("");
const [creds, setCreds] = useState<CredentialDraft[]>([]);
const [pendingSecretId, setPendingSecretId] = useState("");
const [pendingHeader, setPendingHeader] = useState("Authorization");
const [draft, setDraft] = useState<ToolConnection | null>(null);
const [probeResult, setProbeResult] = useState<ProbeResult | null>(null);
const secretById = (id: string) => secrets.data?.find((s) => s.id === id);
const secretName = (id: string) => secretById(id)?.name ?? id.slice(0, 8);
const credentialRefs: McpConnectionCredentialRef[] = useMemo(
() =>
creds.map((c) => ({
name: c.headerName,
secretId: c.secretId,
version: "latest",
placement: "header",
key: c.headerName,
})),
[creds],
);
// Probe runs a real gateway health-check and then a catalog discovery so the
// pre-activation panel can show status + tool count. Latency is the measured
// round-trip of the health-check (a single sample — aggregate p95 across
// traffic is surfaced on the Runtime tab once the connection is live).
const runProbe = async (id: string): Promise<ProbeResult> => {
const startedAt = performance.now();
const health = await toolsApi.checkConnectionHealth(id);
const latencyMs = Math.round(performance.now() - startedAt);
try {
const refreshed = await toolsApi.refreshCatalog(id);
return {
connection: refreshed.connection,
toolCount: refreshed.discoveredCount,
quarantinedCount: refreshed.quarantinedCount,
latencyMs,
};
} catch {
// Health may be fine while discovery is not yet possible (e.g. auth pending) —
// keep the health result and report tools as unknown rather than failing the probe.
return { connection: health.connection, toolCount: null, quarantinedCount: 0, latencyMs };
}
};
const create = useMutation({
mutationFn: () => {
const config: Record<string, unknown> =
transport === "mcp_remote" ? { url: endpointUrl.trim() } : { templateId };
const input: CreateToolConnectionInput = {
...(applicationMode === "existing" ? { applicationId } : { applicationName: applicationName.trim() }),
name: name.trim(),
transport,
status: "draft",
enabled: false,
config,
credentialRefs,
};
return toolsApi.createConnection(companyId, input);
},
onSuccess: (conn) => {
setDraft(conn);
probe.mutate(conn.id);
},
onError: (err) =>
pushToast({
title: "Could not create connection",
body: describeError(err).body,
tone: "error",
}),
});
const probe = useMutation({
mutationFn: (id: string) => runProbe(id),
onSuccess: (res) => {
setDraft(res.connection);
setProbeResult(res);
},
onError: (err) =>
pushToast({
title: "Probe failed",
body: describeError(err).body,
tone: "error",
}),
});
const activate = useMutation({
mutationFn: (id: string) => toolsApi.updateConnection(id, { status: "active", enabled: true }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: queryKeys.tools.connections(companyId) });
qc.invalidateQueries({ queryKey: queryKeys.tools.applications(companyId) });
pushToast({ title: "Connection activated", tone: "success" });
onClose();
},
onError: (err) =>
pushToast({
title: "Activation failed",
body: describeError(err).body,
tone: "error",
}),
});
const addCred = () => {
if (!pendingSecretId || !pendingHeader.trim()) return;
setCreds((c) => [...c, { secretId: pendingSecretId, headerName: pendingHeader.trim() }]);
setPendingSecretId("");
};
const transportConfigValid =
transport === "mcp_remote" ? endpointUrl.trim().length > 0 : templateId.length > 0;
const appChoiceValid = applicationMode === "existing" ? !!applicationId : applicationName.trim().length > 0;
const canCreate = appChoiceValid && name.trim().length > 0 && transportConfigValid && !create.isPending;
const locked = !!draft;
const inferredType = transport === "mcp_remote" ? "MCP HTTP" : "MCP stdio";
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-xl">
<DialogHeader>
<DialogTitle>Add application</DialogTitle>
<DialogDescription>
Choose an existing application or create one as part of the same connection flow. Credentials stay as
vault references and the connection is probed before activation.
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className={step === 1 ? "font-medium text-foreground" : ""}>1 Application</span>
<span>/</span>
<span className={step === 2 ? "font-medium text-foreground" : ""}>2 Connection</span>
</div>
{step === 1 && !locked ? (
<>
<div className="space-y-1.5">
<Label>Application</Label>
<Select value={applicationMode} onValueChange={(v) => setApplicationMode(v as "existing" | "new")}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="existing">Use existing application</SelectItem>
<SelectItem value="new">Create new application</SelectItem>
</SelectContent>
</Select>
</div>
{applicationMode === "existing" ? (
<div className="space-y-1.5">
<Label>Existing application</Label>
<Select value={applicationId} onValueChange={setApplicationId}>
<SelectTrigger>
<SelectValue placeholder="Select an application" />
</SelectTrigger>
<SelectContent>
{(apps.data?.applications ?? []).map((a) => (
<SelectItem key={a.id} value={a.id}>
{a.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : (
<div className="space-y-1.5">
<Label htmlFor="app-name">New application name</Label>
<Input
id="app-name"
value={applicationName}
onChange={(e) => setApplicationName(e.target.value)}
placeholder="e.g. GitHub Triage"
/>
<p className="text-xs text-muted-foreground">
Application type is inferred from the transport you choose next.
</p>
</div>
)}
</>
) : null}
{step === 2 || locked ? (
<>
{applicationMode === "new" ? (
<div className="rounded-md border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
<span className="font-medium text-foreground">{applicationName.trim()}</span> will be created as{" "}
{inferredType}.
</div>
) : null}
<div className="space-y-1.5">
<Label htmlFor="conn-name">Connection name</Label>
<Input
id="conn-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Production GitHub"
disabled={locked}
/>
</div>
<div className="space-y-1.5">
<Label>Transport</Label>
<Select
value={transport}
onValueChange={(v) => setTransport(v as "mcp_remote" | "local_stdio")}
disabled={locked}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="mcp_remote">Remote HTTP (no local process)</SelectItem>
<SelectItem value="local_stdio">Local stdio (approved template)</SelectItem>
</SelectContent>
</Select>
</div>
{transport === "mcp_remote" ? (
<div className="space-y-1.5">
<Label htmlFor="conn-url">Endpoint URL</Label>
<Input
id="conn-url"
value={endpointUrl}
onChange={(e) => setEndpointUrl(e.target.value)}
placeholder="https://mcp.example.com"
disabled={locked}
/>
</div>
) : (
<div className="space-y-1.5">
<Label>Command template</Label>
<Select value={templateId} onValueChange={setTemplateId} disabled={locked}>
<SelectTrigger>
<SelectValue placeholder="Select an approved template" />
</SelectTrigger>
<SelectContent>
{(templates.data?.templates ?? []).map((t) => (
<SelectItem key={t.templateId} value={t.templateId}>
{t.name ?? t.templateId}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Only board-approved command templates can run. Arbitrary commands are never accepted.
</p>
</div>
)}
{/* Vault-reference credential picker — no free-text token field. */}
<div className="space-y-1.5">
<Label>Credential references</Label>
{creds.length > 0 ? (
<ul className="space-y-1">
{creds.map((c, i) => (
<li
key={`${c.secretId}-${i}`}
className="flex items-center gap-2 rounded-md border border-border bg-muted/30 px-2 py-1.5 text-sm"
>
<KeyRound className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="font-mono text-xs">{c.headerName}</span>
<span className="truncate font-mono text-xs text-primary" title={vaultRef(secretById(c.secretId))}>
→ {vaultRef(secretById(c.secretId))}
</span>
{!locked ? (
<button
type="button"
className="ml-auto text-muted-foreground hover:text-destructive"
onClick={() => setCreds((cs) => cs.filter((_, idx) => idx !== i))}
aria-label={`Remove credential reference for ${secretName(c.secretId)}`}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
) : null}
</li>
))}
</ul>
) : null}
{!locked ? (
<>
<div className="flex items-end gap-2">
<div className="flex-1 space-y-1">
<Select value={pendingSecretId} onValueChange={setPendingSecretId}>
<SelectTrigger>
<SelectValue placeholder="Select a vault secret" />
</SelectTrigger>
<SelectContent>
{(secrets.data ?? []).map((s) => (
<SelectItem key={s.id} value={s.id}>
{s.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Input
value={pendingHeader}
onChange={(e) => setPendingHeader(e.target.value)}
placeholder="Header"
className="w-32"
aria-label="Header name"
/>
<Button type="button" size="sm" variant="outline" onClick={addCred} disabled={!pendingSecretId}>
Add
</Button>
</div>
{pendingSecretId ? (
<p className="flex items-center gap-1.5 font-mono text-xs text-muted-foreground">
<Vault className="h-3 w-3" />
{vaultRef(secretById(pendingSecretId))}
</p>
) : null}
<p className="text-xs text-muted-foreground">
Free-text secrets are not accepted — pick a vault entry; Paperclip stores only the
<span className="font-mono"> vault://</span> reference and resolves it at gateway use time.
</p>
</>
) : null}
</div>
</>
) : null}
{/* Inline probe panel — runs before activation, follows the Loading/Error rhythm. */}
{locked ? (
probe.isPending ? (
<div className="rounded-md border border-border bg-muted/40 p-3">
<LoadingState label="Probing connection…" />
</div>
) : probe.error ? (
<QueryErrorState
error={probe.error}
action="probe the connection"
onRetry={() => draft && probe.mutate(draft.id)}
/>
) : probeResult ? (
<div className="rounded-md border border-border bg-muted/40 p-3">
<div className="flex items-center gap-2 text-sm">
<span className="font-medium text-foreground">Probe result</span>
<HealthBadge status={probeResult.connection.healthStatus} />
</div>
<div className="mt-2 grid grid-cols-3 gap-2">
<div>
<p className="text-lg font-semibold tabular-nums text-foreground">
{probeResult.toolCount ?? "—"}
</p>
<p className="text-xs text-muted-foreground">tools discovered</p>
</div>
<div>
<p className="text-lg font-semibold tabular-nums text-foreground">
{probeResult.latencyMs != null ? `${probeResult.latencyMs}ms` : "—"}
</p>
<p className="text-xs text-muted-foreground">probe latency</p>
</div>
<div>
<p className="text-lg font-semibold tabular-nums text-foreground">
{probeResult.quarantinedCount}
</p>
<p className="text-xs text-muted-foreground">quarantined</p>
</div>
</div>
{probeResult.connection.healthMessage ? (
<p className="mt-2 text-xs text-muted-foreground">{probeResult.connection.healthMessage}</p>
) : null}
{probeResult.connection.lastError ? (
<p className="mt-1 text-xs text-destructive">{probeResult.connection.lastError}</p>
) : null}
<p className="mt-2 text-(length:--text-micro) text-muted-foreground">
Probe latency is a single round-trip sample. Aggregate p95 latency across traffic is tracked on
the Runtime tab once the connection is live.
</p>
</div>
) : null
) : null}
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
{step === 1 && !locked ? (
<Button disabled={!appChoiceValid} onClick={() => setStep(2)}>
Continue
</Button>
) : !locked ? (
<>
<Button variant="outline" onClick={() => setStep(1)}>
Back
</Button>
<Button disabled={!canCreate} onClick={() => create.mutate()}>
{create.isPending ? "Creating draft…" : "Create & probe"}
</Button>
</>
) : (
<>
<Button variant="outline" disabled={probe.isPending} onClick={() => draft && probe.mutate(draft.id)}>
<Stethoscope className="mr-1 h-3.5 w-3.5" />
{probe.isPending ? "Probing…" : "Re-probe"}
</Button>
<Button disabled={activate.isPending || probe.isPending} onClick={() => draft && activate.mutate(draft.id)}>
{activate.isPending ? "Activating…" : "Activate"}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}