Files
PaperClipAI/ui/src/pages/apps/gateways/panels/TokensPanel.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

441 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { type FormEvent, type ReactNode, useEffect, useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Copy, KeyRound, Plus } from "lucide-react";
import type {
ToolMcpGatewayToken,
ToolMcpGatewayTokenAction,
ToolMcpGatewayTokenCreated,
ToolMcpGatewayWithTokens,
} from "@paperclipai/shared";
import { toolsApi } from "@/api/tools";
import { Button } from "@/components/ui/button";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
import { useToast } from "@/context/ToastContext";
import { copyTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { RelativeTime } from "@/pages/tools/shared";
import { gatewaysQueryKey } from "../NewGatewayDialog";
import {
defaultGatewayTokenName,
maskedTokenLabel,
TOKEN_STATUS_LABEL,
toDate,
tokenStatus,
type TokenStatus,
} from "../gateway-helpers";
import { describeError } from "@/api/errors";
const DEFAULT_ACTIONS: ToolMcpGatewayTokenAction[] = ["tools/list", "tools/call"];
const TOKEN_PAGE_SIZE = 10;
function defaultExpiry(): string {
return new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
}
const STATUS_CLASS: Record<TokenStatus, string> = {
active: "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
expiring: "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
expired: "border-border bg-muted text-muted-foreground",
revoked: "border-foreground bg-foreground text-background",
};
function StatusBadge({ status }: { status: TokenStatus }) {
return (
<span
className={cn(
"inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-xs font-medium",
STATUS_CLASS[status],
)}
>
{TOKEN_STATUS_LABEL[status]}
</span>
);
}
function TokenField({ label, value }: { label: string; value: ReactNode }) {
return (
<div className="min-w-0">
<dt className="text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">{label}</dt>
<dd className="mt-0.5 truncate text-foreground">{value}</dd>
</div>
);
}
function ExpiryValue({ token }: { token: ToolMcpGatewayToken }) {
const expiresAt = toDate(token.expiresAt);
if (!expiresAt) return <>No expiry</>;
if (expiresAt.getTime() <= Date.now()) {
return <><span className="font-medium text-foreground">Expired</span> <RelativeTime value={token.expiresAt} /></>;
}
return <>Expires <RelativeTime value={token.expiresAt} /></>;
}
export function TokensPanel({
companyId,
gateway,
onTokenCreated,
}: {
companyId: string;
gateway: ToolMcpGatewayWithTokens;
onTokenCreated?: (token: ToolMcpGatewayTokenCreated) => void;
}) {
const queryClient = useQueryClient();
const { pushToast } = useToast();
const [minting, setMinting] = useState(false);
const [name, setName] = useState("");
const [ownerNote, setOwnerNote] = useState("");
const [expiresAt, setExpiresAt] = useState(defaultExpiry());
const [created, setCreated] = useState<ToolMcpGatewayTokenCreated | null>(null);
const [revealed, setRevealed] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
const [historyPage, setHistoryPage] = useState(1);
const [revokeName, setRevokeName] = useState("");
const [confirmToken, setConfirmToken] = useState<{ id: string; name: string } | null>(null);
const invalidate = () => queryClient.invalidateQueries({ queryKey: gatewaysQueryKey(companyId) });
const tokens = useMemo(
() => [...gateway.tokens].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()),
[gateway.tokens],
);
const pageCount = Math.max(1, Math.ceil(tokens.length / TOKEN_PAGE_SIZE));
const visibleTokens = tokens.slice((historyPage - 1) * TOKEN_PAGE_SIZE, historyPage * TOKEN_PAGE_SIZE);
useEffect(() => {
setHistoryPage((current) => Math.min(current, pageCount));
}, [pageCount]);
const createMutation = useMutation({
mutationFn: () =>
toolsApi.createGatewayToken(companyId, gateway.id, {
name: name.trim(),
clientLabel: name.trim(),
ownerNote: ownerNote.trim(),
allowedActions: DEFAULT_ACTIONS,
expiresAt: expiresAt ? `${expiresAt}T23:59:59.000Z` : null,
}),
onSuccess: async (token) => {
setCreated(token);
setRevealed(true);
setMinting(false);
setName("");
setOwnerNote("");
setExpiresAt(defaultExpiry());
pushToast({
title: "Token issued",
body: "Copy it now — you won’t see the full value again after leaving this page.",
tone: "success",
});
onTokenCreated?.(token);
await invalidate();
},
onError: (error) =>
pushToast({
title: "Token was not issued",
body: describeError(error).body,
tone: "error",
}),
});
const revokeMutation = useMutation({
mutationFn: (tokenId: string) => toolsApi.revokeGatewayToken(companyId, tokenId),
onSuccess: async (token) => {
setConfirmToken(null);
setRevokeName("");
pushToast({ title: "Token revoked", body: `${token.name} can no longer connect.`, tone: "success" });
await invalidate();
},
onError: (error) =>
pushToast({
title: "Token was not revoked",
body: describeError(error).body,
tone: "error",
}),
});
async function copyToken(value: string) {
try {
await copyTextToClipboard(value);
pushToast({ title: "Copied", body: "Access token", tone: "success" });
} catch (error) {
pushToast({
title: "Copy failed",
body: describeError(error).body,
tone: "error",
});
}
}
function startIssuing() {
if (!minting && !name.trim()) setName(defaultGatewayTokenName(gateway));
setMinting((value) => !value);
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!name.trim()) return;
createMutation.mutate();
}
function startRevoke(token: ToolMcpGatewayToken) {
setConfirmToken({ id: token.id, name: token.name });
setRevokeName("");
}
return (
<div className="space-y-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="max-w-2xl space-y-1">
<p className="text-sm text-muted-foreground">
Issue a reusable token for an external client. Its name is also used as the client label.
</p>
<p className="text-xs text-muted-foreground">
Paperclip creates a fresh one-hour runtime token when an agent run starts, then revokes it when the
run ends. Codex can receive the same gateway through both an app connection and the managed-gateway
path, so one run may leave two revoked rows. These are audit history, not repeated manual tokens.
</p>
</div>
<Button size="sm" onClick={startIssuing}>
<Plus className="mr-1.5 h-3.5 w-3.5" />
Issue token
</Button>
</div>
{minting ? (
<form className="space-y-3" onSubmit={submit}>
<div className="grid gap-3 md:grid-cols-[1fr_auto]">
<label className="space-y-1.5 text-sm">
<span className="text-xs font-medium text-muted-foreground">Token name</span>
<Input value={name} onChange={(event) => setName(event.target.value)} required autoFocus />
<span className="text-xs text-muted-foreground">Also used as the client label.</span>
</label>
<label className="space-y-1.5 text-sm">
<span className="text-xs font-medium text-muted-foreground">Expires</span>
<Input type="date" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} required />
</label>
</div>
<label className="block space-y-1.5 text-sm">
<span className="text-xs font-medium text-muted-foreground">Owner note (optional)</span>
<Input
value={ownerNote}
onChange={(event) => setOwnerNote(event.target.value)}
placeholder="Who uses this token or why it exists"
/>
</label>
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" size="sm" onClick={() => setMinting(false)}>
Cancel
</Button>
<Button type="submit" size="sm" disabled={createMutation.isPending || !name.trim()}>
{createMutation.isPending ? "Issuing…" : "Issue token"}
</Button>
</div>
</form>
) : null}
{created ? (
<div className="space-y-2 border-y border-border py-4">
<div className="flex items-center justify-between gap-2">
<div>
<div className="text-sm font-semibold text-foreground">New token — copy now</div>
<div className="text-xs text-muted-foreground">
It is now available in Client snippets for a copy-ready configuration.
</div>
</div>
<Button variant="ghost" size="sm" onClick={() => setCreated(null)} aria-label="Dismiss new token">
Dismiss
</Button>
</div>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 truncate rounded bg-muted px-3 py-2 font-mono text-xs text-foreground">
{revealed ? created.token : maskedTokenLabel(created)}
</code>
{revealed ? (
<Button variant="outline" size="sm" onClick={() => void copyToken(created.token)}>
<Copy className="mr-1 h-3.5 w-3.5" />
Copy
</Button>
) : (
<Button variant="outline" size="sm" onClick={() => setRevealed(true)}>Show</Button>
)}
</div>
</div>
) : null}
<Collapsible open={historyOpen} onOpenChange={setHistoryOpen}>
<CollapsibleTrigger asChild>
<Button variant="ghost" className="h-auto w-full justify-between px-0 py-1 hover:bg-transparent">
<span className="flex items-center gap-2 text-sm font-semibold text-foreground">
<KeyRound className="h-4 w-4 text-muted-foreground" />
Token history
<span className="font-normal text-muted-foreground">{tokens.length}</span>
</span>
{historyOpen ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="space-y-3 pt-3">
{tokens.length === 0 ? (
<p className="py-4 text-sm text-muted-foreground">No tokens have been issued for this gateway.</p>
) : (
<>
<div className="hidden overflow-x-auto rounded-lg border border-border sm:block">
<table className="w-full min-w-(--sz-44rem) text-sm">
<thead>
<tr className="border-b border-border bg-muted/40 text-left text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">
<th className="px-4 py-2.5">Token</th>
<th className="px-4 py-2.5">Owner</th>
<th className="px-4 py-2.5">Created</th>
<th className="px-4 py-2.5">Last used</th>
<th className="px-4 py-2.5">Expiry</th>
<th className="px-4 py-2.5">Status</th>
<th className="px-4 py-2.5 text-right" />
</tr>
</thead>
<tbody>
{visibleTokens.map((token) => {
const status = tokenStatus(token);
return (
<tr key={token.id} className="border-b border-border last:border-0">
<td className="px-4 py-3">
<div className="font-medium text-foreground">{token.name}</div>
<div className="font-mono text-xs text-muted-foreground">{maskedTokenLabel(token)}</div>
</td>
<td className="px-4 py-3 text-muted-foreground">{token.clientLabel || token.ownerNote || "—"}</td>
<td className="px-4 py-3 text-muted-foreground"><RelativeTime value={token.createdAt} /></td>
<td className="px-4 py-3 text-muted-foreground">
{token.lastUsedAt ? <RelativeTime value={token.lastUsedAt} /> : "—"}
</td>
<td className="px-4 py-3 text-muted-foreground"><ExpiryValue token={token} /></td>
<td className="px-4 py-3"><StatusBadge status={status} /></td>
<td className="px-4 py-3 text-right">
{status !== "revoked" ? (
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-xs text-destructive hover:text-destructive"
onClick={() => startRevoke(token)}
>
Revoke
</Button>
) : null}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<div className="space-y-3 sm:hidden">
{visibleTokens.map((token) => {
const status = tokenStatus(token);
return (
<div key={token.id} className="border-b border-border py-3 last:border-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="font-medium text-foreground">{token.name}</div>
<div className="font-mono text-xs text-muted-foreground">{maskedTokenLabel(token)}</div>
</div>
<StatusBadge status={status} />
</div>
<dl className="mt-3 grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
<TokenField label="Owner" value={token.clientLabel || token.ownerNote || "—"} />
<TokenField label="Created" value={<RelativeTime value={token.createdAt} />} />
<TokenField label="Last used" value={token.lastUsedAt ? <RelativeTime value={token.lastUsedAt} /> : "—"} />
<TokenField label="Expiry" value={<ExpiryValue token={token} />} />
</dl>
{status !== "revoked" ? (
<Button
variant="ghost"
size="sm"
className="mt-3 w-full text-xs text-destructive hover:text-destructive"
onClick={() => startRevoke(token)}
>
Revoke
</Button>
) : null}
</div>
);
})}
</div>
{pageCount > 1 ? (
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">
Page {historyPage} of {pageCount} · {tokens.length} tokens
</p>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
disabled={historyPage === 1}
onClick={() => setHistoryPage((page) => Math.max(1, page - 1))}
aria-label="Previous token page"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
disabled={historyPage === pageCount}
onClick={() => setHistoryPage((page) => Math.min(pageCount, page + 1))}
aria-label="Next token page"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
) : null}
</>
)}
</CollapsibleContent>
</Collapsible>
{confirmToken ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true">
<div className="w-full max-w-md space-y-3 rounded-lg border border-border bg-card p-5 shadow-lg">
<div>
<h3 className="text-sm font-semibold text-foreground">Revoke this token?</h3>
<p className="mt-1 text-sm text-muted-foreground">
Any client using <span className="font-medium text-foreground">{confirmToken.name}</span> goes
silent immediately. This can’t be undone. Type the token name to confirm.
</p>
</div>
<Input
value={revokeName}
onChange={(event) => setRevokeName(event.target.value)}
placeholder={confirmToken.name}
aria-label="Type the token name to confirm"
autoFocus
/>
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => {
setConfirmToken(null);
setRevokeName("");
}}
>
Cancel
</Button>
<Button
variant="destructive"
size="sm"
disabled={revokeName.trim() !== confirmToken.name || revokeMutation.isPending}
onClick={() => revokeMutation.mutate(confirmToken.id)}
>
{revokeMutation.isPending ? "Revoking…" : "Revoke token"}
</Button>
</div>
</div>
</div>
) : null}
</div>
);
}