Files
paperclip/ui/src/pages/NewAgent.tsx
T
MrBob 5f16efb3d0 fix: parse YAML block scalar skill descriptions (#5046)
## Thinking Path

> - Paperclip is the open source control plane teams use to manage AI
agents for work.
> - Company skills are imported from `SKILL.md` files and rely on YAML
frontmatter to describe what each skill does.
> - Multi-line descriptions commonly use YAML block scalars (`>` and
`|`), but the broken parser path behind #4989 reduced those descriptions
to a literal `>` or `|`.
> - The earliest contributor fix for that bug was PR #5046, so this
branch keeps that PR as the canonical merge target instead of replacing
it.
> - Follow-up work from #5071 and #8258 was then transplanted onto this
earlier branch so the final PR preserves contributor credit while still
shipping the strongest complete fix.
> - The resulting change fixes block-scalar parsing in the shared
frontmatter path, aligns server company-skill imports with that shared
parser, and prevents already-stale stored markers from rendering as junk
in the UI.

## Linked Issues or Issue Description

- Fixes #4989
- Refs #2863
- Refs #788
- Related superseded PRs: #5071, #8258

## What Changed

- Kept the original PR #5046 server-side company-skill fix and
regression coverage as the base branch history.
- Added the missing YAML chomping and indicator hardening explored
further in #5071.
- Moved frontmatter parsing to the shared parser path so
`packages/shared`, `packages/skills-catalog`, and server company-skill
imports stay aligned.
- Added UI summary sanitization and fallback handling so stale stored
`>` / `|` values no longer render as visible junk in company-skill
cards.
- Added regression coverage for shared frontmatter parsing,
skills-catalog parsing, company-skill imports, and stale-summary
fallback behavior.

## Verification

- Passed locally: `pnpm exec vitest run
packages/shared/src/frontmatter.test.ts
packages/skills-catalog/src/frontmatter.test.ts
server/src/__tests__/company-skills.test.ts
ui/src/lib/company-skill-summary.test.ts`
- Passed locally: `pnpm --filter @paperclipai/shared typecheck`
- Passed locally: `pnpm --filter @paperclipai/skills-catalog typecheck`
- Not fully runnable in this worktree: `pnpm --filter
@paperclipai/server typecheck` currently fails in `packages/plugins/sdk`
before reaching server code because local workspace `node_modules` type
deps are missing (`TS2688` for `node` / `react`).
- GitHub Actions / PR checks are rerunning on PR #5046 head
`005290b7557725abf748d00f36dd24ea0d919aba`.

## Risks

- Medium-low risk: the fix now touches shared parser code, server
company-skill imports, and UI fallback display rather than only the
server import path.
- The parser is still intentionally narrower than a full YAML
implementation; this change focuses on block-scalar correctness and the
stale-description rendering path relevant to #4989 / #2863.
- This branch intentionally supersedes narrower overlapping work from
#5071 and duplicate work from #8258 once the survivor PR is green.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex / GPT-5-based coding agent with local shell and
code-editing tools enabled.

## 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 either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] 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: Devin Foley <devin@paperclip.ing>
2026-06-18 12:01:11 -07:00

391 lines
15 KiB
TypeScript

import { useState, useEffect, useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useSearchParams } from "@/lib/router";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { agentsApi } from "../api/agents";
import { companySkillsApi } from "../api/companySkills";
import { issuesApi } from "../api/issues";
import { projectsApi } from "../api/projects";
import { queryKeys } from "../lib/queryKeys";
import { resolveSkillSummaryText } from "../lib/company-skill-summary";
import { AGENT_ROLES, type AdapterEnvironmentTestResult, type AgentPermissions } from "@paperclipai/shared";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Shield } from "lucide-react";
import { cn, agentUrl } from "../lib/utils";
import { roleLabels } from "../components/agent-config-primitives";
import {
AgentConfigForm,
AdapterEnvironmentResult,
type CreateConfigValues,
} from "../components/AgentConfigForm";
import { defaultCreateValues } from "../components/agent-config-defaults";
import { getUIAdapter, listUIAdapters } from "../adapters";
import { useDisabledAdaptersSync } from "../adapters/use-disabled-adapters";
import { isValidAdapterType } from "../adapters/metadata";
import { ReportsToPicker } from "../components/ReportsToPicker";
import { buildNewAgentHirePayload } from "../lib/new-agent-hire-payload";
import { TrustPresetSection } from "../components/TrustPresetSection";
import { buildPermissionsForTrustPreset, getTrustPreset } from "../lib/trust-policy-ui";
import { DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX } from "@paperclipai/adapter-codex-local";
import { DEFAULT_CURSOR_LOCAL_MODEL } from "@paperclipai/adapter-cursor-local";
import { DEFAULT_GEMINI_LOCAL_MODEL } from "@paperclipai/adapter-gemini-local";
import { DEFAULT_OPENCODE_LOCAL_MODEL, isValidOpenCodeModelId } from "@paperclipai/adapter-opencode-local";
function createValuesForAdapterType(
adapterType: CreateConfigValues["adapterType"],
): CreateConfigValues {
const { adapterType: _discard, ...defaults } = defaultCreateValues;
const nextValues: CreateConfigValues = { ...defaults, adapterType };
if (adapterType === "codex_local") {
nextValues.dangerouslyBypassSandbox =
DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX;
} else if (adapterType === "gemini_local") {
nextValues.model = DEFAULT_GEMINI_LOCAL_MODEL;
} else if (adapterType === "cursor") {
nextValues.model = DEFAULT_CURSOR_LOCAL_MODEL;
} else if (adapterType === "opencode_local") {
nextValues.model = DEFAULT_OPENCODE_LOCAL_MODEL;
}
return nextValues;
}
export function NewAgent() {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const presetAdapterType = searchParams.get("adapterType");
const [name, setName] = useState("");
const [title, setTitle] = useState("");
const [role, setRole] = useState("general");
const [reportsTo, setReportsTo] = useState<string | null>(null);
const [configValues, setConfigValues] = useState<CreateConfigValues>(defaultCreateValues);
const [permissions, setPermissions] = useState<Partial<AgentPermissions>>(
buildPermissionsForTrustPreset(null, "standard"),
);
const [selectedSkillKeys, setSelectedSkillKeys] = useState<string[]>([]);
const [roleOpen, setRoleOpen] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [testAgentAction, setTestAgentAction] = useState<(() => void) | null>(null);
const [testAgentState, setTestAgentState] = useState({ disabled: true, pending: false });
const [testAgentFeedback, setTestAgentFeedback] = useState<{
errorMessage: string | null;
result: AdapterEnvironmentTestResult | null;
}>({
errorMessage: null,
result: null,
});
const { data: agents } = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId!),
queryFn: () => agentsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const { data: companySkills } = useQuery({
queryKey: queryKeys.companySkills.list(selectedCompanyId ?? ""),
queryFn: () => companySkillsApi.list(selectedCompanyId!),
enabled: Boolean(selectedCompanyId),
});
const lowTrustSelected = getTrustPreset(permissions) === "low_trust_review";
const { data: boundaryProjects, isLoading: boundaryProjectsLoading } = useQuery({
queryKey: selectedCompanyId ? queryKeys.projects.list(selectedCompanyId) : ["projects", "__low-trust-disabled"],
queryFn: () => projectsApi.list(selectedCompanyId!),
enabled: Boolean(selectedCompanyId && lowTrustSelected),
});
const { data: boundaryIssues, isLoading: boundaryIssuesLoading } = useQuery({
queryKey: selectedCompanyId
? [...queryKeys.issues.list(selectedCompanyId), "low-trust-boundary-candidates"]
: ["issues", "__low-trust-disabled"],
queryFn: () => issuesApi.list(selectedCompanyId!, { limit: 100, sortField: "updated", sortDir: "desc" }),
enabled: Boolean(selectedCompanyId && lowTrustSelected),
});
const isFirstAgent = !agents || agents.length === 0;
const effectiveRole = isFirstAgent ? "ceo" : role;
useEffect(() => {
setBreadcrumbs([
{ label: "Agents", href: "/agents" },
{ label: "New Agent" },
]);
}, [setBreadcrumbs]);
useEffect(() => {
if (isFirstAgent) {
if (!name) setName("CEO");
if (!title) setTitle("CEO");
}
}, [isFirstAgent]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
const requested = presetAdapterType;
if (!requested) return;
if (!isValidAdapterType(requested)) return;
setConfigValues((prev) => {
if (prev.adapterType === requested) return prev;
return createValuesForAdapterType(requested as CreateConfigValues["adapterType"]);
});
}, [presetAdapterType]);
const createAgent = useMutation({
mutationFn: (data: Record<string, unknown>) =>
agentsApi.hire(selectedCompanyId!, data),
onSuccess: (result) => {
queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(selectedCompanyId!) });
queryClient.invalidateQueries({ queryKey: queryKeys.approvals.list(selectedCompanyId!) });
navigate(agentUrl(result.agent));
},
onError: (error) => {
setFormError(error instanceof Error ? error.message : "Failed to create agent");
},
});
function buildAdapterConfig() {
const adapter = getUIAdapter(configValues.adapterType);
return adapter.buildAdapterConfig(configValues);
}
function handleSubmit() {
if (!selectedCompanyId || !name.trim()) return;
setFormError(null);
if (configValues.adapterType === "opencode_local") {
if (!isValidOpenCodeModelId(configValues.model)) {
setFormError("OpenCode requires an explicit model in provider/model format.");
return;
}
}
createAgent.mutate(
buildNewAgentHirePayload({
name,
effectiveRole,
title,
reportsTo,
selectedSkillKeys,
configValues,
adapterConfig: buildAdapterConfig(),
permissions,
}),
);
}
const availableSkills = (companySkills ?? []).filter((skill) => !skill.key.startsWith("paperclipai/paperclip/"));
function toggleSkill(key: string, checked: boolean) {
setSelectedSkillKeys((prev) => {
if (checked) {
return prev.includes(key) ? prev : [...prev, key];
}
return prev.filter((value) => value !== key);
});
}
const handleTestAgentActionChange = useCallback((fn: (() => void) | null) => {
setTestAgentAction(() => fn);
}, []);
const handleTestAgentStateChange = useCallback((state: { disabled: boolean; pending: boolean }) => {
setTestAgentState(state);
}, []);
const handleTestAgentFeedbackChange = useCallback((feedback: {
errorMessage: string | null;
result: AdapterEnvironmentTestResult | null;
}) => {
setTestAgentFeedback(feedback);
}, []);
return (
<div className="mx-auto max-w-2xl space-y-6">
<div>
<h1 className="text-lg font-semibold">New Agent</h1>
<p className="text-sm text-muted-foreground mt-1">
Advanced agent configuration
</p>
</div>
<div className="border border-border">
{/* Name */}
<div className="px-4 pt-4 pb-2">
<input
className="w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50"
placeholder="Agent name"
value={name}
onChange={(e) => setName(e.target.value)}
autoFocus
/>
</div>
{/* Title */}
<div className="px-4 pb-2">
<input
className="w-full bg-transparent outline-none text-sm text-muted-foreground placeholder:text-muted-foreground/40"
placeholder="Title (e.g. VP of Engineering)"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
{/* Property chips: Role + Reports To */}
<div className="flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap">
<Popover open={roleOpen} onOpenChange={setRoleOpen}>
<PopoverTrigger asChild>
<button
className={cn(
"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",
isFirstAgent && "opacity-60 cursor-not-allowed"
)}
disabled={isFirstAgent}
>
<Shield className="h-3 w-3 text-muted-foreground" />
{roleLabels[effectiveRole] ?? effectiveRole}
</button>
</PopoverTrigger>
<PopoverContent className="w-36 p-1" align="start">
{AGENT_ROLES.map((r) => (
<button
key={r}
className={cn(
"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
r === role && "bg-accent"
)}
onClick={() => { setRole(r); setRoleOpen(false); }}
>
{roleLabels[r] ?? r}
</button>
))}
</PopoverContent>
</Popover>
<ReportsToPicker
agents={agents ?? []}
value={reportsTo}
onChange={setReportsTo}
disabled={isFirstAgent}
/>
</div>
<div className="border-t border-border px-4 py-4">
<TrustPresetSection
permissions={permissions}
onChange={setPermissions}
disabled={createAgent.isPending}
companyId={selectedCompanyId}
projectCandidates={(boundaryProjects ?? []).map((project) => ({
id: project.id,
label: project.name,
}))}
issueCandidates={(boundaryIssues ?? []).map((issue) => ({
id: issue.id,
label: `${issue.identifier ?? issue.id.slice(0, 8)} · ${issue.title}`,
}))}
candidatesLoading={boundaryProjectsLoading || boundaryIssuesLoading}
/>
</div>
{/* Shared config form */}
<AgentConfigForm
mode="create"
values={configValues}
onChange={(patch) => setConfigValues((prev) => ({ ...prev, ...patch }))}
onTestActionChange={handleTestAgentActionChange}
onTestActionStateChange={handleTestAgentStateChange}
onTestFeedbackChange={handleTestAgentFeedbackChange}
/>
<div className="border-t border-border px-4 py-4">
<div className="space-y-3">
<div>
<h2 className="text-sm font-medium">Company skills</h2>
<p className="mt-1 text-xs text-muted-foreground">
Optional skills from the company library. Built-in Paperclip runtime skills are added automatically.
</p>
</div>
{availableSkills.length === 0 ? (
<p className="text-xs text-muted-foreground">
No optional company skills installed yet.
</p>
) : (
<div className="space-y-3">
{availableSkills.map((skill) => {
const inputId = `skill-${skill.id}`;
const checked = selectedSkillKeys.includes(skill.key);
const summaryText = resolveSkillSummaryText(skill, { fallbackKey: true });
return (
<div key={skill.id} className="flex items-start gap-3">
<Checkbox
id={inputId}
checked={checked}
onCheckedChange={(next) => toggleSkill(skill.key, next === true)}
/>
<label htmlFor={inputId} className="grid gap-1 leading-none">
<span className="text-sm font-medium">{skill.name}</span>
{summaryText ? <span className="text-xs text-muted-foreground">{summaryText}</span> : null}
</label>
</div>
);
})}
</div>
)}
</div>
</div>
{/* Footer */}
<div className="border-t border-border px-4 py-3">
{isFirstAgent && (
<p className="text-xs text-muted-foreground mb-2">This will be the CEO</p>
)}
{formError && (
<p className="text-xs text-destructive mb-2">{formError}</p>
)}
<div className="space-y-3">
{testAgentFeedback.errorMessage && (
<div className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
{testAgentFeedback.errorMessage}
</div>
)}
{testAgentFeedback.result && (
<AdapterEnvironmentResult result={testAgentFeedback.result} />
)}
<div className="flex items-center justify-between gap-2">
<Button variant="outline" size="sm" onClick={() => navigate("/agents")}>
Cancel
</Button>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={testAgentState.disabled}
onClick={() => testAgentAction?.()}
>
{testAgentState.pending ? "Testing..." : "Test Agent"}
</Button>
<Button
size="sm"
disabled={!name.trim() || createAgent.isPending}
onClick={handleSubmit}
>
{createAgent.isPending ? "Creating…" : "Create agent"}
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}