Files
PaperClipAI/ui/src/components/AgentContextualSidebar.tsx
T
Nicky LeachandPaperclip 42715d459f Support authenticated WebSocket routes and agent views in plugins (#17111)
## Thinking Path

> - Paperclip manages agents and their work.
> - Plugins provide optional views and connect to external runtimes.
> - A live runtime view needs a binary browser connection.
> - The current plugin API supports JSON routes but cannot proxy that
connection.
> - Agent detail tabs are declared in the plugin contract but are not
mounted on agent pages.
> - This PR completes those two host capabilities and keeps upstream
credentials on the server.

## Linked Issues or Issue Description

**Subsystem affected**

Plugin scoped API routes and agent detail views.

**Problem or motivation**

Plugins cannot expose a binary or text stream through a browser session
without exposing an upstream credential or adding a separate browser
gateway. Agent-scoped detail contributions also have no mount on the
agent page.

**Proposed solution**

Allow declared board GET routes to select a server-only WSS upstream.
Run upgrades through the existing HTTP authentication pipeline and
trusted Origin check. Add agent company resolution with the existing
`agent:read` decision. Mount contributed detail views in agent
navigation.

**Alternatives considered**

A separately hosted viewer needs its own browser credentials and
cross-origin policy. JSON or SSE transport adds encoding and buffering
to a binary protocol.

**Roadmap alignment**

This extends the existing plugin API and detail-tab contract. It adds no
desktop provider to Core. I checked ROADMAP.md and searched related open
PRs; I found no equivalent transport and agent view change.

## What Changed

- Add declared WebSocket routes requiring board authentication, GET, and
`http.outbound`. Reject body-based company resolution because browser
upgrades cannot send a body.
- Keep worker-selected upstream URLs and headers out of browser JSON
responses. Strip browser cookies and Origin. Preserve binary frames and
socket backpressure.
- Close both sockets on disconnect or worker shutdown. Reauthorize on
reconnect after a five-minute connection lifetime. Preserve HTTP
idle-work accounting for the stream lifetime.
- Resolve agent scope through `agent:read` and mount generic agent
plugin detail views, with current agent/view breadcrumbs and browser
titles.

## Verification

- Final head `9d8d269040acf9dc7bb65524876406af522dacb5`: CI passes
(including Runner Rust, build, and browser E2E); Greptile 5/5; no
unresolved review threads; no merge conflicts. Verified 2026-10-21.
- Core server TypeScript check: `node node_modules/typescript/bin/tsc -p
server/tsconfig.json --noEmit`.
- Focused server suites: 17 passing tests
(`server/src/__tests__/plugin-scoped-api-routes.test.ts` and
`server/src/http/server.test.ts`), including arbitrary build-output and
metrics channels with real local text and binary WebSocket round trips,
disconnect cleanup, denied actors and origins, credential exclusion,
agent-read denial, and cross-company 404 equivalence. The test replaces
TLS with local HTTP while retaining the real upgrade and binary stream.
- UI suites: 9 passing tests for independent Insights and Notes
contributions, removed contributions, built-in route preservation,
sidebar links, direct plugin entry and heading updates after tab
navigation. These contributions do not require the WebSocket transport.
- Shared validator suite: 42 passing tests, including rejecting
body-based WebSocket resolution while retaining ordinary HTTP body
resolution and accepting query/entity scopes.
- UI token gates pass.
- UI TypeScript check: `node ../scripts/storybook-catalog.mjs` then `tsc
-b`.
- Shared and plugin SDK builds pass.
- Full Runner build reached its unrelated Rust step and stopped because
cargo is unavailable. Runner TypeScript build was run separately. No
live remote VM was used.

## Risks

- This adds a browser ingress path for trusted installed plugins. The
plugin must select its upstream from a trusted binding. HTTP requests
cannot retrieve the upstream descriptor.
- Membership or binding changes are rechecked on reconnect. Connections
last at most five minutes, and worker shutdown is checked every five
seconds.
- Initial CI caught a missing cross-company 404 guard and an old test
that assumed exactly one upgrade listener. Both were corrected.
Greptile's body-resolution and stale-heading findings are fixed with
regression coverage; latest-head CI passes and Greptile scored 5/5 with
no unresolved findings.
- No schema migration. Rollback restores the previous Core image;
plugins using this transport must be disabled or rolled back first.

## Model Used

OpenAI Codex, based on GPT-6, with reasoning and code/tool execution.
The exact runtime model ID and context-window size are not exposed in
this session.

## Checklist

- [x] Thinking path and issue description included
- [x] Model described
- [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] No internal issues, private links, or runtime credentials included
- [x] Descriptive branch name
- [x] Focused tests and relevant typechecks run
- [x] Tests and documentation updated
- [x] Risks documented
- [x] All CI gates green
- [x] Greptile 5/5 with no unresolved findings
- [x] I will address review findings before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-21 10:10:00 -07:00

145 lines
5.0 KiB
TypeScript

import { useQuery } from "@tanstack/react-query";
import {
Activity,
BadgeDollarSign,
BookOpenText,
History,
KeyRound,
Library,
MessageSquare,
PlayCircle,
ReceiptText,
Settings2,
ShieldCheck,
Sparkles,
Wrench,
} from "lucide-react";
import { usePluginSlots } from "@/plugins/slots";
import { agentsApi } from "@/api/agents";
import { useCompany } from "@/context/CompanyContext";
import { queryKeys } from "@/lib/queryKeys";
import { ContextualSidebarFrame } from "./ContextualSidebarFrame";
import { SidebarNavItem } from "./SidebarNavItem";
import { contextualSidebarStyles } from "./contextual-sidebar-styles";
import {
AGENT_DETAIL_NAVIGATION,
agentDetailHref,
agentScopedAuditHref,
type AgentLocalDetailView,
} from "@/pages/agent-detail-navigation";
const localIcons = {
overview: Sparkles,
instructions: BookOpenText,
skills: Library,
runtime: Settings2,
secrets: ShieldCheck,
tools: Wrench,
channels: MessageSquare,
permissions: ShieldCheck,
"api-keys": KeyRound,
revisions: History,
} satisfies Record<AgentLocalDetailView, typeof Sparkles>;
const auditItems = [
{ section: "activity", label: "Activity", icon: Activity },
{ section: "runs", label: "Runs", icon: PlayCircle },
{ section: "costs", label: "Costs", icon: ReceiptText },
{ section: "budgets", label: "Budgets", icon: BadgeDollarSign },
] as const;
export function AgentContextualSidebar({
agentRef,
agentId,
agentName,
labels = { secrets: "Secrets & variables" },
}: {
agentRef: string;
agentId?: string;
agentName?: string;
labels?: Partial<Record<AgentLocalDetailView, string>>;
}) {
const { selectedCompanyId } = useCompany();
const shouldResolveAgent = !agentId || !agentName;
const { data: resolvedAgent } = useQuery({
queryKey: [...queryKeys.agents.detail(agentRef), selectedCompanyId ?? null, "contextual-sidebar"],
queryFn: () => agentsApi.get(agentRef, selectedCompanyId ?? undefined),
enabled: shouldResolveAgent && Boolean(agentRef && selectedCompanyId),
});
const resolvedId = agentId ?? resolvedAgent?.id;
const { slots: pluginTabs } = usePluginSlots({ slotTypes: ["detailTab"], entityType: "agent", companyId: resolvedAgent?.companyId ?? selectedCompanyId, enabled: Boolean(resolvedId) });
const resolvedName = agentName ?? resolvedAgent?.name ?? "Agent";
return (
<ContextualSidebarFrame
surface="agent"
title={resolvedName}
fallbackTo="/agents/all"
showHeader={false}
className="border-r border-border bg-background"
>
<nav
aria-label={`${resolvedName} navigation`}
data-slot="contextual-sidebar-nav"
className={contextualSidebarStyles.nav}
>
{AGENT_DETAIL_NAVIGATION.map((section) => (
<div
key={section.label}
data-slot="contextual-sidebar-section"
className={contextualSidebarStyles.section}
>
<p
data-slot="contextual-sidebar-section-label"
className={contextualSidebarStyles.sectionLabel}
>
{section.label}
</p>
<div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
{section.items
.map((item) => {
const href = agentDetailHref(agentRef, item.value);
return (
<SidebarNavItem
key={item.value}
to={href}
label={labels?.[item.value] ?? item.label}
icon={localIcons[item.value]}
/>
);
})}
</div>
</div>
))}
{pluginTabs.length > 0 && <div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>
<p className={contextualSidebarStyles.sectionLabel}>Apps</p>
<div className={contextualSidebarStyles.group}>
{pluginTabs.map(slot => <SidebarNavItem key={`${slot.pluginKey}:${slot.id}`} to={`/agents/${encodeURIComponent(agentRef)}/${encodeURIComponent(`plugin:${slot.pluginKey}:${slot.id}`)}`} label={slot.displayName} icon={Wrench} />)}
</div>
</div>}
<div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>
<p
data-slot="contextual-sidebar-section-label"
className={contextualSidebarStyles.sectionLabel}
>
Audit
</p>
<div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
{resolvedId ? auditItems.map((item) => (
<SidebarNavItem
key={item.section}
to={agentScopedAuditHref(resolvedId, item.section)}
label={item.label}
icon={item.icon}
/>
)) : (
<p className="px-2 py-1.5 text-xs text-muted-foreground">Loading audit links…</p>
)}
</div>
</div>
</nav>
</ContextualSidebarFrame>
);
}