[codex] Roll up May 17 branch changes (#6210)

## Thinking Path

> - Paperclip is the control plane for autonomous AI companies, so agent
work needs visible ownership, recovery, and operator controls.
> - This local branch had accumulated several related control-plane
reliability and operator-experience fixes across recovery actions,
watchdog folding, model-profile defaults, mentions, markdown editing,
plugin launchers, and small UI polish.
> - The branch needed to be converted into a PR against the current
`origin/master` without losing dirty work or including lockfile/workflow
churn.
> - The safest standalone shape is a single rollup PR because the
recovery/server/UI files overlap heavily across the local commits and
splitting would create avoidable conflicts.
> - This pull request replays the local branch onto latest
`origin/master`, preserves the uncommitted work as logical commits, and
adds a Zod 4 validator compatibility fix found during verification.
> - The benefit is that the May 17 local branch can be reviewed and
merged as one coherent, conflict-free branch under the 100-file Greptile
limit.

## What Changed

- Rebased the local May 17 branch work onto current `origin/master` in a
dedicated worktree.
- Preserved and committed previously dirty changes for recovery retry
handling, plugin/sidebar launcher polish, and `.herenow` ignores.
- Added recovery-action behavior for returning source issues to `todo`
when retrying source-scoped recovery.
- Included the existing local recovery/liveness/watchdog fold, Codex
cheap-profile, markdown/mention, duplicate-agent, and UI polish commits
from the branch.
- Normalized shared validator `z.record(...)` schemas to explicit
string-key records for Zod 4 compatibility.
- Confirmed the PR has no `pnpm-lock.yaml` or `.github/workflows/*`
changes and stays below the 100-file Greptile limit.

## Verification

- `pnpm install --frozen-lockfile --ignore-scripts`
- `npm run install` in
`node_modules/.pnpm/sqlite3@5.1.7/node_modules/sqlite3` to build the
local native sqlite3 binding after installing with scripts disabled
- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts
packages/shared/src/project-mentions.test.ts
packages/adapter-utils/src/server-utils.test.ts
server/src/__tests__/heartbeat-model-profile.test.ts
server/src/__tests__/issue-recovery-actions.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
server/src/__tests__/heartbeat-active-run-output-watchdog.test.ts
server/src/__tests__/plugin-local-folders.test.ts
ui/src/components/IssueRecoveryActionCard.test.tsx
ui/src/components/Sidebar.test.tsx
ui/src/components/SidebarAccountMenu.test.tsx
ui/src/components/IssueProperties.test.tsx
ui/src/components/MarkdownEditor.test.tsx
ui/src/components/MarkdownBody.test.tsx
ui/src/lib/duplicate-agent-payload.test.ts
ui/src/pages/Routines.test.tsx`
- First pass: 13 files passed with 201 passing tests; 3 server files
failed before sqlite3 native binding was built.
- After rebuilding sqlite3:
`server/src/__tests__/heartbeat-model-profile.test.ts`,
`server/src/__tests__/issue-recovery-actions.test.ts`, and
`server/src/__tests__/heartbeat-active-run-output-watchdog.test.ts`
passed/loaded; embedded Postgres tests were skipped by the local host
guard.
- `pnpm --filter @paperclipai/shared typecheck`
- `pnpm --filter @paperclipai/adapter-utils typecheck`
- `pnpm --filter @paperclipai/server typecheck`
- `pnpm --filter @paperclipai/ui typecheck`

## Risks

- Medium risk: this is a broad rollup PR across recovery semantics,
server tests, shared validators, and UI surfaces.
- Some embedded Postgres tests skipped locally due the host guard, so CI
should provide the stronger database-backed signal.
- UI changes were covered by component tests, but no browser screenshot
was captured in this PR creation pass.
- This branch may overlap with existing recovery/liveness PR work; merge
this PR independently or restack/close overlapping branches rather than
merging duplicate implementations together.

> 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, tool-enabled local repository
and GitHub workflow, medium reasoning effort.

## 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 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
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta 2026-05-17 17:15:06 -05:00 committed by GitHub
parent 705c1b8d81
commit d734bd43d1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
83 changed files with 3675 additions and 180 deletions

View file

@ -131,7 +131,7 @@ export const issuesApi = {
data: {
actionId?: string;
outcome: "restored" | "false_positive" | "blocked" | "cancelled";
sourceIssueStatus: "done" | "in_review" | "blocked";
sourceIssueStatus: "todo" | "done" | "in_review" | "blocked";
resolutionNote?: string | null;
},
) => api.post<ResolveRecoveryActionResponse>(`/issues/${id}/recovery-actions/resolve`, data),

View file

@ -121,6 +121,22 @@ async function flush() {
});
}
async function waitForAssertion(assertion: () => void, attempts = 20) {
let lastError: unknown;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
assertion();
return;
} catch (error) {
lastError = error;
await flush();
}
}
throw lastError;
}
function createIssue(overrides: Partial<Issue> = {}): Issue {
return {
id: "issue-1",
@ -476,6 +492,60 @@ describe("IssueProperties", () => {
act(() => root.unmount());
});
it("searches all company issues when adding a blocker", async () => {
const onUpdate = vi.fn();
const loadedIssue = createIssue({ id: "issue-3", identifier: "PAP-3", title: "Loaded issue", status: "todo" });
const remoteIssue = createIssue({ id: "issue-99", identifier: "PAP-99", title: "Remote blocker", status: "in_progress" });
mockIssuesApi.list.mockImplementation((_companyId: string, filters?: { q?: string; limit?: number }) => {
if (filters?.q === "remote") return Promise.resolve([remoteIssue]);
return Promise.resolve([loadedIssue]);
});
const root = renderProperties(container, {
issue: createIssue(),
childIssues: [],
onUpdate,
inline: true,
});
await flush();
const addButton = Array.from(container.querySelectorAll("button"))
.find((button) => button.textContent?.includes("Add blocker"));
expect(addButton).not.toBeUndefined();
await act(async () => {
addButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flush();
const searchInput = container.querySelector('input[aria-label="Search issues to add as blockers"]') as HTMLInputElement | null;
expect(searchInput).not.toBeNull();
await act(async () => {
const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
nativeSetter?.call(searchInput, "remote");
searchInput!.dispatchEvent(new Event("input", { bubbles: true }));
});
await waitForAssertion(() => {
expect(mockIssuesApi.list).toHaveBeenCalledWith("company-1", { q: "remote", limit: 50 });
expect(container.textContent).toContain("PAP-99 Remote blocker");
expect(container.textContent).not.toContain("PAP-3 Loaded issue");
});
const candidateButton = Array.from(container.querySelectorAll("button"))
.find((button) => button.textContent?.includes("PAP-99 Remote blocker"));
expect(candidateButton).not.toBeUndefined();
await act(async () => {
candidateButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
expect(onUpdate).toHaveBeenCalledWith({ blockedByIssueIds: ["issue-99"] });
act(() => root.unmount());
});
it("removes a blocked-by issue from the chip remove action after confirmation", async () => {
const onUpdate = vi.fn();
const root = renderProperties(container, {

View file

@ -145,6 +145,8 @@ interface IssuePropertiesProps {
inline?: boolean;
}
const ISSUE_BLOCKER_SEARCH_LIMIT = 50;
function PropertyRow({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex items-start gap-3 py-1.5">
@ -405,6 +407,7 @@ export function IssueProperties({
const [monitorAtInput, setMonitorAtInput] = useState(() => toDateTimeLocalValue(issue.executionPolicy?.monitor?.nextCheckAt));
const [monitorNotesInput, setMonitorNotesInput] = useState(issue.executionPolicy?.monitor?.notes ?? "");
const [monitorServiceInput, setMonitorServiceInput] = useState(issue.executionPolicy?.monitor?.serviceName ?? "");
const normalizedBlockedBySearch = blockedBySearch.trim();
const { data: session } = useQuery({
queryKey: queryKeys.auth.session,
@ -443,10 +446,21 @@ export function IssueProperties({
enabled: !!companyId,
});
const { data: allIssues } = useQuery({
const { data: allIssues, isFetching: isFetchingIssuePickerIssues } = useQuery({
queryKey: queryKeys.issues.list(companyId!),
queryFn: () => issuesApi.list(companyId!),
enabled: !!companyId && (blockedByOpen || parentOpen),
enabled: !!companyId && (parentOpen || (blockedByOpen && normalizedBlockedBySearch.length === 0)),
});
const { data: searchedBlockedByIssues, isFetching: isFetchingSearchedBlockedByIssues } = useQuery({
queryKey: companyId
? queryKeys.issues.search(companyId, normalizedBlockedBySearch, undefined, ISSUE_BLOCKER_SEARCH_LIMIT)
: ["issues", "blocker-search", normalizedBlockedBySearch, ISSUE_BLOCKER_SEARCH_LIMIT],
queryFn: () => issuesApi.list(companyId!, {
q: normalizedBlockedBySearch,
limit: ISSUE_BLOCKER_SEARCH_LIMIT,
}),
enabled: !!companyId && blockedByOpen && normalizedBlockedBySearch.length > 0,
});
const createLabel = useMutation({
@ -1648,27 +1662,28 @@ export function IssueProperties({
</>
);
const blockingIssues = issue.blocks ?? [];
const blockerOptions = (allIssues ?? [])
.filter((candidate) => candidate.id !== issue.id)
.filter((candidate) => {
if (!blockedBySearch.trim()) return true;
const query = blockedBySearch.toLowerCase();
return (
(candidate.identifier ?? "").toLowerCase().includes(query) ||
candidate.title.toLowerCase().includes(query)
);
})
.sort((a, b) => {
const blockerSearchActive = normalizedBlockedBySearch.length > 0;
const blockerSourceIssues = blockerSearchActive ? searchedBlockedByIssues : allIssues;
const blockerOptions = (blockerSourceIssues ?? [])
.filter((candidate) => candidate.id !== issue.id);
if (!blockerSearchActive) {
blockerOptions.sort((a, b) => {
const aLabel = `${a.identifier ?? ""} ${a.title}`.trim();
const bLabel = `${b.identifier ?? ""} ${b.title}`.trim();
return aLabel.localeCompare(bLabel);
});
}
const blockerOptionsLoading = blockedByOpen && (
blockerSearchActive ? isFetchingSearchedBlockedByIssues : isFetchingIssuePickerIssues
);
const toggleBlockedBy = (blockedByIssueId: string) => {
const nextBlockedByIds = blockedByIds.includes(blockedByIssueId)
? blockedByIds.filter((candidate) => candidate !== blockedByIssueId)
: [...blockedByIds, blockedByIssueId];
onUpdate({ blockedByIssueIds: nextBlockedByIds });
setBlockedByOpen(false);
setBlockedBySearch("");
};
const removeBlockedBy = (blockedByIssueId: string) => {
onUpdate({ blockedByIssueIds: blockedByIds.filter((candidate) => candidate !== blockedByIssueId) });
@ -1682,6 +1697,7 @@ export function IssueProperties({
value={blockedBySearch}
onChange={(e) => setBlockedBySearch(e.target.value)}
autoFocus={!inline}
aria-label="Search issues to add as blockers"
/>
<div className="max-h-48 overflow-y-auto overscroll-contain">
<button
@ -1689,7 +1705,11 @@ export function IssueProperties({
"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
blockedByIds.length === 0 && "bg-accent",
)}
onClick={() => onUpdate({ blockedByIssueIds: [] })}
onClick={() => {
onUpdate({ blockedByIssueIds: [] });
setBlockedByOpen(false);
setBlockedBySearch("");
}}
>
No blockers
</button>
@ -1709,9 +1729,15 @@ export function IssueProperties({
{candidate.identifier ? `${candidate.identifier} ` : ""}
{candidate.title}
</span>
{selected && <Check className="ml-auto h-3.5 w-3.5 shrink-0 text-foreground" aria-hidden="true" />}
</button>
);
})}
{blockerOptionsLoading ? (
<div className="px-2 py-2 text-xs text-muted-foreground">Searching issues...</div>
) : blockerOptions.length === 0 ? (
<div className="px-2 py-2 text-xs text-muted-foreground">No matching issues.</div>
) : null}
</div>
</>
);

View file

@ -165,19 +165,20 @@ describe("IssueRecoveryActionCard", () => {
expect(node.textContent).toContain("Resolved as restored");
});
it("calls resolve with done and does not offer delegated recovery", () => {
it("calls resolve with todo and does not offer delegated recovery", () => {
const onResolve = vi.fn();
const node = render(
<IssueRecoveryActionCard action={buildAction()} onResolve={onResolve} />,
);
click(node.querySelector("[data-testid='recovery-action-resolve-trigger']"));
expect(document.body.textContent).toContain("Try again");
expect(document.body.textContent).toContain("Mark issue done");
expect(document.body.textContent).not.toContain("Mark blocked");
expect(document.body.textContent).not.toContain("Delegate follow-up issue");
click([...document.body.querySelectorAll("button")].find((button) => button.textContent?.includes("Mark issue done")) ?? null);
click([...document.body.querySelectorAll("button")].find((button) => button.textContent?.includes("Try again")) ?? null);
expect(onResolve).toHaveBeenCalledWith("done");
expect(onResolve).toHaveBeenCalledWith("todo");
});
it("does not offer blocked recovery resolution without a blocker selection flow", () => {
@ -186,6 +187,7 @@ describe("IssueRecoveryActionCard", () => {
);
click(node.querySelector("[data-testid='recovery-action-resolve-trigger']"));
expect(document.body.textContent).toContain("Try again");
expect(document.body.textContent).toContain("Mark issue done");
expect(document.body.textContent).toContain("Send for review");
expect(document.body.textContent).toContain("False positive, done");

View file

@ -25,6 +25,7 @@ export type RecoveryCardCardState = RecoveryDisplayState;
export const deriveRecoveryCardState = deriveRecoveryDisplayState;
export type RecoveryResolveOutcome =
| "todo"
| "done"
| "in_review"
| "false_positive_done"
@ -292,6 +293,11 @@ const RESOLVE_OPTIONS: Array<{
destructive?: boolean;
boardOnly?: boolean;
}> = [
{
outcome: "todo",
label: "Try again",
description: "Dismiss recovery and return the source issue to todo.",
},
{
outcome: "done",
label: "Mark issue done",

View file

@ -238,6 +238,7 @@ describe("IssueRow", () => {
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
expect(link).not.toBeNull();
expect(link?.textContent).toContain("Planning");
expect(link?.textContent?.match(/Planning/g)).toHaveLength(1);
act(() => {
root.unmount();

View file

@ -126,7 +126,6 @@ export function IssueRow({
<span className="flex shrink-0 items-center gap-1 pt-px sm:hidden">
{mobileLeading ?? <StatusIcon status={issue.status} blockerAttention={issue.blockerAttention} className={selectedStatusClass} />}
{productivityReviewIndicator}
{planningModeIndicator}
{parkedBlockerIndicator}
{recoveryIndicator}
</span>
@ -153,11 +152,11 @@ export function IssueRow({
<span className="shrink-0 font-mono text-xs text-muted-foreground">
{identifier}
</span>
{planningModeIndicator}
{parkedBlockerIndicator}
{recoveryIndicator}
</>
)}
{planningModeIndicator}
{mobileMeta ? (
<>
<span className="text-xs text-muted-foreground sm:hidden" aria-hidden="true">

View file

@ -16,6 +16,8 @@ import { cn, relativeTime } from "../lib/utils";
import { queryKeys } from "../lib/queryKeys";
import { keepPreviousDataForSameQueryTail } from "../lib/query-placeholder-data";
import { describeRunRetryState } from "../lib/runRetryState";
import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";
import { SourceResolvedFoldBadge } from "./SourceResolvedFoldBadge";
type IssueRunLedgerProps = {
issueId: string;
@ -693,6 +695,7 @@ export function IssueRunLedgerContent({
const continuation = continuationLabel(run);
const retryState = describeRunRetryState(run);
const agentName = compactAgentName(run, agentMap);
const sourceResolvedFold = readSourceResolvedWatchdogFold(run.resultJson);
return (
<article
key={`run:${run.runId}`}
@ -773,6 +776,7 @@ export function IssueRunLedgerContent({
</span>
);
})()}
{sourceResolvedFold ? <SourceResolvedFoldBadge /> : null}
<span className="ml-auto shrink-0">{relativeTime(item.timestamp)}</span>
</div>

View file

@ -1250,7 +1250,9 @@ export function IssuesList({
}
else if (viewState.groupBy === "project" && groupKey !== "__no_project") defaults.projectId = groupKey;
else if (viewState.groupBy === "workspace" && groupKey !== "__no_workspace") {
const representativeIssue = group?.items.find((issue) => issue.executionWorkspaceId === groupKey) ?? null;
const representativeIssue = group?.items.find((issue) =>
issue.executionWorkspaceId === groupKey || issue.projectWorkspaceId === groupKey,
) ?? null;
const executionWorkspace = executionWorkspaceById.get(groupKey);
if (executionWorkspace) {
defaults.executionWorkspaceId = groupKey;

View file

@ -8,6 +8,7 @@ import {
buildAgentMentionHref,
buildIssueReferenceHref,
buildProjectMentionHref,
buildRoutineMentionHref,
buildSkillMentionHref,
buildUserMentionHref,
} from "@paperclipai/shared";
@ -92,12 +93,12 @@ describe("MarkdownBody", () => {
expect(html).toContain('alt="Org chart"');
});
it("renders user, agent, project, and skill mentions as chips", () => {
it("renders user, agent, project, skill, and routine mentions as chips", () => {
const html = renderToStaticMarkup(
<QueryClientProvider client={new QueryClient()}>
<ThemeProvider>
<MarkdownBody>
{`[@Taylor](${buildUserMentionHref("user-123")}) [@CodexCoder](${buildAgentMentionHref("agent-123", "code")}) [@Paperclip App](${buildProjectMentionHref("project-456", "#336699")}) [/release-changelog](${buildSkillMentionHref("skill-789", "release-changelog")})`}
{`[@Taylor](${buildUserMentionHref("user-123")}) [@CodexCoder](${buildAgentMentionHref("agent-123", "code")}) [@Paperclip App](${buildProjectMentionHref("project-456", "#336699")}) [/release-changelog](${buildSkillMentionHref("skill-789", "release-changelog")}) [/routine:Weekly review](${buildRoutineMentionHref("routine-123")})`}
</MarkdownBody>
</ThemeProvider>
</QueryClientProvider>,
@ -113,6 +114,8 @@ describe("MarkdownBody", () => {
expect(html).toContain("--paperclip-mention-project-color:#336699");
expect(html).toContain('href="/skills/skill-789"');
expect(html).toContain('data-mention-kind="skill"');
expect(html).toContain('href="/routines/routine-123"');
expect(html).toContain('data-mention-kind="routine"');
});
it("sanitizes unsafe javascript markdown links", () => {

View file

@ -586,11 +586,13 @@ export function MarkdownBody({
? `/projects/${parsed.projectId}`
: parsed.kind === "issue"
? `/issues/${parsed.identifier}`
: parsed.kind === "skill"
? `/skills/${parsed.skillId}`
: parsed.kind === "user"
? "/company/settings/access"
: `/agents/${parsed.agentId}`;
: parsed.kind === "skill"
? `/skills/${parsed.skillId}`
: parsed.kind === "routine"
? `/routines/${parsed.routineId}`
: parsed.kind === "user"
? "/company/settings/access"
: `/agents/${parsed.agentId}`;
return (
<a
href={targetHref}

View file

@ -3,7 +3,7 @@
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { buildProjectMentionHref, buildSkillMentionHref } from "@paperclipai/shared";
import { buildProjectMentionHref, buildRoutineMentionHref, buildSkillMentionHref } from "@paperclipai/shared";
import {
computeMentionMenuPosition,
findClosestAutocompleteAnchor,
@ -553,6 +553,16 @@ describe("MarkdownEditor", () => {
expect(findMentionMatch("/open issue", "/open issue".length)).toBeNull();
});
it("keeps routine slash queries active across spaces", () => {
expect(findMentionMatch("/routine:Weekly release review", "/routine:Weekly release review".length)).toEqual({
trigger: "skill",
marker: "/",
query: "routine:Weekly release review",
atPos: 0,
endPos: "/routine:Weekly release review".length,
});
});
it("does not treat Enter as skill autocomplete accept", () => {
expect(shouldAcceptAutocompleteKey("Enter", "skill")).toBe(false);
expect(shouldAcceptAutocompleteKey("Enter", "skill", true)).toBe(true);
@ -623,6 +633,26 @@ describe("MarkdownEditor", () => {
expect(found).toBe(skillLink);
});
it("finds routine anchors by mention metadata instead of visible text", () => {
const editable = document.createElement("div");
const routineLink = document.createElement("a");
routineLink.setAttribute("href", buildRoutineMentionHref("routine-123"));
routineLink.textContent = "/routine:Weekly release review ";
editable.appendChild(routineLink);
const found = findClosestAutocompleteAnchor(editable, {
id: "routine:routine-123",
kind: "routine",
routineId: "routine-123",
name: "Weekly release review",
status: "active",
href: buildRoutineMentionHref("routine-123"),
aliases: ["routine:Weekly release review", "Weekly release review"],
});
expect(found).toBe(routineLink);
});
it("places the caret after the mention's trailing space when present", () => {
const editable = document.createElement("div");
editable.contentEditable = "true";

View file

@ -31,8 +31,13 @@ import {
thematicBreakPlugin,
type RealmPlugin,
} from "@mdxeditor/editor";
import { buildAgentMentionHref, buildProjectMentionHref, buildUserMentionHref } from "@paperclipai/shared";
import { Boxes, User } from "lucide-react";
import {
buildAgentMentionHref,
buildProjectMentionHref,
buildRoutineMentionHref,
buildUserMentionHref,
} from "@paperclipai/shared";
import { Boxes, CalendarClock, User } from "lucide-react";
import { AgentIcon } from "./AgentIconPicker";
import { applyMentionChipDecoration, clearMentionChipDecoration, parseMentionChipHref } from "../lib/mention-chips";
import { MentionAwareLinkNode, mentionAwareLinkNodeReplacement } from "../lib/mention-aware-link-node";
@ -41,7 +46,7 @@ import { looksLikeMarkdownPaste } from "../lib/markdownPaste";
import { normalizeMarkdown } from "../lib/normalize-markdown";
import { pasteNormalizationPlugin } from "../lib/paste-normalization";
import { cn } from "../lib/utils";
import { useEditorAutocomplete, type SkillCommandOption } from "../context/EditorAutocompleteContext";
import { useEditorAutocomplete, type SlashCommandOption } from "../context/EditorAutocompleteContext";
/* ---- Mention types ---- */
@ -188,7 +193,7 @@ interface MentionState {
endPos: number;
}
type AutocompleteOption = MentionOption | SkillCommandOption;
type AutocompleteOption = MentionOption | SlashCommandOption;
interface MentionMenuViewport {
offsetLeft: number;
@ -260,7 +265,9 @@ export function findMentionMatch(
if (atPos === -1) return null;
const query = text.slice(atPos + 1, offset);
if (trigger === "skill" && /\s/.test(query)) return null;
if (trigger === "skill" && /\s/.test(query) && !query.toLowerCase().startsWith("routine:")) {
return null;
}
return {
trigger: trigger ?? "mention",
@ -423,12 +430,21 @@ function mentionMarkdown(option: MentionOption): string {
return `[@${option.name}](${buildAgentMentionHref(agentId, option.agentIcon ?? null)}) `;
}
function skillMarkdown(option: SkillCommandOption): string {
function slashCommandLabel(option: SlashCommandOption): string {
return option.kind === "routine" ? `/routine:${option.name}` : `/${option.slug}`;
}
function slashCommandMarkdown(option: SlashCommandOption): string {
if (option.kind === "routine") {
return `[${slashCommandLabel(option)}](${buildRoutineMentionHref(option.routineId)}) `;
}
return `[/${option.slug}](${option.href}) `;
}
function autocompleteMarkdown(option: AutocompleteOption): string {
return option.kind === "skill" ? skillMarkdown(option) : mentionMarkdown(option);
return option.kind === "skill" || option.kind === "routine"
? slashCommandMarkdown(option)
: mentionMarkdown(option);
}
export function shouldAcceptAutocompleteKey(
@ -461,6 +477,9 @@ function autocompleteOptionMatchesLink(option: AutocompleteOption, href: string)
if (option.kind === "skill") {
return parsed.kind === "skill" && parsed.skillId === option.skillId;
}
if (option.kind === "routine") {
return parsed.kind === "routine" && parsed.routineId === option.routineId;
}
if (option.kind === "project" && option.projectId) {
return parsed.kind === "project" && parsed.projectId === option.projectId;
@ -785,7 +804,7 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
continue;
}
if (parsed.kind === "skill") {
if (parsed.kind === "skill" || parsed.kind === "routine") {
applyMentionChipDecoration(link, parsed);
continue;
}
@ -1256,7 +1275,9 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
setMentionIndex(i);
}}
>
{option.kind === "skill" ? (
{option.kind === "routine" ? (
<CalendarClock className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
) : option.kind === "skill" ? (
<Boxes className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
) : option.kind === "project" && option.projectId ? (
<span
@ -1271,7 +1292,11 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
className="h-3.5 w-3.5 shrink-0 text-muted-foreground"
/>
)}
<span>{option.kind === "skill" ? `/${option.slug}` : option.name}</span>
<span>
{option.kind === "skill" || option.kind === "routine"
? slashCommandLabel(option)
: option.name}
</span>
{option.kind === "project" && option.projectId && (
<span className="ml-auto text-[10px] uppercase tracking-wide text-muted-foreground">
Project
@ -1287,6 +1312,11 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
Skill
</span>
)}
{option.kind === "routine" && (
<span className="ml-auto text-[10px] uppercase tracking-wide text-muted-foreground">
Routine
</span>
)}
</button>
))}
</div>,

View file

@ -134,7 +134,7 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
<div className="flex items-center gap-3" onClick={(event) => { event.preventDefault(); event.stopPropagation(); }}>
{runNowButton ? (
<Button
variant="ghost"
variant="outline"
size="sm"
disabled={runDisabled}
onClick={() => onRunNow(routine)}

View file

@ -70,6 +70,12 @@ vi.mock("@/plugins/slots", () => ({
PluginSlotOutlet: () => null,
}));
vi.mock("@/plugins/launchers", () => ({
PluginLauncherOutlet: ({ placementZones }: { placementZones: string[] }) => (
<div data-plugin-launcher-zone={placementZones.join(",")}>Plugin launcher outlet</div>
),
}));
vi.mock("./SidebarCompanyMenu", () => ({
SidebarCompanyMenu: () => <div>Company menu</div>,
}));
@ -129,7 +135,7 @@ describe("Sidebar", () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });
const root = await renderSidebar();
const topSearchLink = container.querySelector('a[aria-label="Search"]');
const topSearchLink = container.querySelector('a[aria-label="Open search"]');
expect(topSearchLink?.getAttribute("href")).toBe("/search");
const workLinks = [...container.querySelectorAll("nav a")].map((anchor) => anchor.textContent?.trim());
expect(workLinks).not.toContain("Search");
@ -139,6 +145,23 @@ describe("Sidebar", () => {
});
});
it("renders plugin sidebar launchers inside the Work section", async () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });
const root = await renderSidebar();
const workSection = [...container.querySelectorAll("nav [data-plugin-launcher-zone]")]
.find((node) => node.getAttribute("data-plugin-launcher-zone") === "sidebar");
expect(workSection?.textContent).toContain("Plugin launcher outlet");
const workSectionContainer = workSection?.parentElement?.parentElement;
expect(workSectionContainer?.textContent).toContain("Work");
expect(workSectionContainer?.textContent).toContain("Issues");
expect(workSectionContainer?.textContent).toContain("Goals");
await act(async () => {
root.unmount();
});
});
it("does not flash the Workspaces link while experimental settings are loading", async () => {
mockInstanceSettingsApi.getExperimental.mockImplementation(() => new Promise(() => {}));
const root = await renderSidebar();

View file

@ -27,6 +27,7 @@ import { queryKeys } from "../lib/queryKeys";
import { useInboxBadge } from "../hooks/useInboxBadge";
import { Button } from "@/components/ui/button";
import { PluginSlotOutlet } from "@/plugins/slots";
import { PluginLauncherOutlet } from "@/plugins/launchers";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
export function Sidebar() {
@ -61,8 +62,8 @@ export function Sidebar() {
variant="ghost"
size="icon-sm"
className="text-muted-foreground shrink-0"
aria-label="Search"
title="Search"
aria-label="Open search"
title="Open search"
>
<NavLink to="/search">
<Search className="h-4 w-4" />
@ -101,6 +102,12 @@ export function Sidebar() {
<SidebarSection label="Work">
<SidebarNavItem to="/issues" label="Issues" icon={CircleDot} />
<SidebarNavItem to="/routines" label="Routines" icon={Repeat} />
<PluginLauncherOutlet
placementZones={["sidebar"]}
context={pluginContext}
className="flex flex-col gap-0.5"
itemClassName="text-[13px] font-medium"
/>
<SidebarNavItem to="/goals" label="Goals" icon={Target} />
{showWorkspacesLink ? (
<SidebarNavItem to="/workspaces" label="Workspaces" icon={GitBranch} />

View file

@ -110,7 +110,7 @@ describe("SidebarAccountMenu", () => {
expect(document.body.textContent).toContain("Paperclip v1.2.3");
expect(document.body.textContent).toContain("jane@example.com");
expect(document.body.querySelector('[data-slot="popover-content"]')?.className)
.toContain("w-[var(--radix-popover-trigger-width)]");
.toContain("w-[277px]");
await act(async () => {
root.unmount();

View file

@ -160,7 +160,7 @@ export function SidebarAccountMenu({
side="top"
align="start"
sideOffset={10}
className="w-[var(--radix-popover-trigger-width)] max-w-[calc(100vw-1rem)] overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl"
className="w-[277px] max-w-[calc(100vw-1rem)] overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl"
>
<div className="h-24 bg-[linear-gradient(135deg,hsl(var(--primary))_0%,hsl(var(--accent))_55%,hsl(var(--muted))_100%)]" />
<div className="-mt-8 px-4 pb-4">

View file

@ -0,0 +1,33 @@
import { Sparkles } from "lucide-react";
import { cn } from "@/lib/utils";
export interface SourceResolvedFoldBadgeProps {
className?: string;
title?: string;
/** When true (default) the leading sparkles icon is rendered. */
showIcon?: boolean;
}
export function SourceResolvedFoldBadge({
className,
title = "System folded this run as a source-resolved false positive.",
showIcon = true,
}: SourceResolvedFoldBadgeProps) {
return (
<span
className={cn(
"inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[11px] font-medium",
"border-emerald-300/60 bg-emerald-50/80 text-emerald-900",
"dark:border-emerald-500/30 dark:bg-emerald-500/10 dark:text-emerald-200",
className,
)}
title={title}
aria-label="Source-resolved watchdog fold"
>
{showIcon ? <Sparkles className="h-3 w-3 text-emerald-700 dark:text-emerald-300" aria-hidden /> : null}
Source-resolved
</span>
);
}
export default SourceResolvedFoldBadge;

View file

@ -0,0 +1,177 @@
import { Sparkles } from "lucide-react";
import { Link } from "@/lib/router";
import { cn, relativeTime } from "@/lib/utils";
import {
type SourceResolvedWatchdogFold,
formatCleanupOutcome,
formatSilenceAgeMs,
shortenEvidenceId,
} from "@/lib/source-resolved-watchdog-fold";
export interface SourceResolvedFoldCalloutProps {
fold: SourceResolvedWatchdogFold;
/** Time the run was finalized — used for the "system audit · {when}" header chip. */
finalizedAt?: string | Date | null;
className?: string;
}
function isoOrLocaleString(value: string | null | undefined): string | null {
if (!value) return null;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return date.toLocaleString();
}
function issueLink(id: string, identifier: string | null) {
return `/issues/${identifier ?? id}`;
}
function MetaRow({
label,
children,
}: {
label: string;
children: React.ReactNode;
}) {
return (
<div className="grid grid-cols-[10rem_1fr] gap-x-3 gap-y-0 py-1 text-xs sm:grid-cols-[12rem_1fr]">
<dt className="truncate text-[11px] font-medium uppercase tracking-[0.08em] text-emerald-900/70 dark:text-emerald-200/70">
{label}
</dt>
<dd className="min-w-0 break-words text-emerald-950 dark:text-emerald-100">{children}</dd>
</div>
);
}
export function SourceResolvedFoldCallout({
fold,
finalizedAt,
className,
}: SourceResolvedFoldCalloutProps) {
const sourceLabel = fold.sourceIssueIdentifier ?? fold.sourceIssueId.slice(0, 8);
const evidenceShort = shortenEvidenceId(fold.sameRunEvidenceId);
const evidenceAt = isoOrLocaleString(fold.sameRunEvidenceAt);
const silenceAgeLabel = formatSilenceAgeMs(fold.silenceAgeMs);
const silenceStartedLabel = isoOrLocaleString(fold.silenceStartedAt);
const cleanupLabel = formatCleanupOutcome(fold.cleanup.outcome);
const finalizedRelative = finalizedAt ? relativeTime(finalizedAt) : null;
const evaluationLabel = fold.evaluationIssueIdentifier ?? fold.evaluationIssueId?.slice(0, 8);
return (
<section
role="status"
aria-label="Source-resolved watchdog fold"
data-source-resolved-fold
className={cn(
"relative w-full overflow-hidden rounded-lg border text-sm shadow-[0_1px_0_rgba(15,23,42,0.02)]",
"border-emerald-300/70 bg-emerald-50/80 text-emerald-950",
"dark:border-emerald-500/40 dark:bg-emerald-500/10 dark:text-emerald-100",
className,
)}
>
<header className="flex items-start gap-3 px-3 py-2.5 sm:px-4">
<span
className={cn(
"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",
"bg-emerald-100 text-emerald-800 dark:bg-emerald-500/20 dark:text-emerald-200",
)}
aria-hidden
>
<Sparkles className="h-4 w-4 text-emerald-700 dark:text-emerald-300" />
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] font-semibold uppercase tracking-[0.14em]">
<span className="text-emerald-900 dark:text-emerald-200">SOURCE-RESOLVED FOLD</span>
<span className="text-muted-foreground/60" aria-hidden>·</span>
<span className="font-medium normal-case tracking-normal text-muted-foreground">
system audit
</span>
{finalizedRelative ? (
<>
<span className="text-muted-foreground/60" aria-hidden>·</span>
<span className="font-medium normal-case tracking-normal text-muted-foreground">
{finalizedRelative}
</span>
</>
) : null}
</div>
<p className="mt-1 text-[14px] leading-6">
This run was folded as a source-resolved false positive.
</p>
</div>
</header>
<dl
className={cn(
"divide-y border-t bg-background/40 px-3 py-2 sm:px-4 dark:bg-background/20",
"border-emerald-300/60 dark:border-emerald-500/30",
"[&>*]:border-emerald-300/40 dark:[&>*]:border-emerald-500/20",
)}
>
<MetaRow label="Source issue">
<span className="inline-flex flex-wrap items-center gap-1.5">
<Link
to={issueLink(fold.sourceIssueId, fold.sourceIssueIdentifier)}
className="rounded-sm font-medium underline-offset-2 hover:underline"
>
{sourceLabel}
</Link>
<span className="rounded-md border border-emerald-300/60 bg-background/60 px-1.5 py-0.5 text-[11px] font-medium text-emerald-900 dark:border-emerald-500/30 dark:text-emerald-200">
{fold.sourceIssueStatus}
</span>
</span>
</MetaRow>
<MetaRow label="Same-run evidence">
<span className="inline-flex flex-wrap items-baseline gap-1.5">
<span className="rounded bg-background/70 px-1.5 py-0.5 font-mono text-[11px] text-emerald-900 dark:bg-background/40 dark:text-emerald-100">
{fold.sameRunEvidenceKind}
</span>
<code
className="rounded bg-background/70 px-1.5 py-0.5 font-mono text-[11px] text-emerald-900 dark:bg-background/40 dark:text-emerald-100"
title={fold.sameRunEvidenceId}
>
{evidenceShort}
</code>
{evidenceAt ? (
<span className="text-[11px] text-muted-foreground">at {evidenceAt}</span>
) : null}
</span>
</MetaRow>
<MetaRow label="Silence age before fold">
{silenceAgeLabel ? (
<span>
{silenceAgeLabel}
{silenceStartedLabel ? (
<span className="text-muted-foreground"> (silence started {silenceStartedLabel})</span>
) : null}
</span>
) : (
<span className="text-muted-foreground">unknown</span>
)}
</MetaRow>
<MetaRow label="Process cleanup">
<span
className="inline-flex flex-wrap items-baseline gap-1.5"
title={fold.cleanup.outcome}
>
<span>{cleanupLabel}</span>
{fold.cleanup.error ? (
<span className="text-muted-foreground"> {fold.cleanup.error}</span>
) : null}
</span>
</MetaRow>
{fold.evaluationIssueId ? (
<MetaRow label="Evaluation issue">
<Link
to={issueLink(fold.evaluationIssueId, fold.evaluationIssueIdentifier)}
className="rounded-sm font-medium underline-offset-2 hover:underline"
>
{evaluationLabel}
</Link>
</MetaRow>
) : null}
</dl>
</section>
);
}
export default SourceResolvedFoldCallout;

View file

@ -59,7 +59,7 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-[0.97] data-[state=open]:zoom-in-[0.97] data-[state=closed]:slide-out-to-top-[1%] data-[state=open]:slide-in-from-top-[1%] fixed top-[max(1rem,env(safe-area-inset-top))] md:top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-0 md:translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-150 ease-[cubic-bezier(0.16,1,0.3,1)] outline-none sm:max-w-lg",
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-[0.97] data-[state=open]:zoom-in-[0.97] data-[state=closed]:slide-out-to-top-[1%] data-[state=open]:slide-in-from-top-[1%] fixed top-[max(1rem,env(safe-area-inset-top))] md:top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-0 md:translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-150 ease-[cubic-bezier(0.16,1,0.3,1)] outline-none sm:max-w-lg [&>*]:min-w-0",
className
)}
{...props}

View file

@ -1,7 +1,8 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { buildSkillMentionHref } from "@paperclipai/shared";
import { buildRoutineMentionHref, buildSkillMentionHref } from "@paperclipai/shared";
import { companySkillsApi } from "../api/companySkills";
import { routinesApi } from "../api/routines";
import { useCompany } from "./CompanyContext";
import { queryKeys } from "../lib/queryKeys";
@ -17,8 +18,20 @@ export interface SkillCommandOption {
aliases: string[];
}
export interface RoutineCommandOption {
id: string;
kind: "routine";
routineId: string;
name: string;
status: string;
href: string;
aliases: string[];
}
export type SlashCommandOption = SkillCommandOption | RoutineCommandOption;
interface EditorAutocompleteContextValue {
slashCommands: SkillCommandOption[];
slashCommands: SlashCommandOption[];
}
const EditorAutocompleteContext = createContext<EditorAutocompleteContextValue>({
@ -34,20 +47,41 @@ export function EditorAutocompleteProvider({ children }: { children: ReactNode }
queryFn: () => companySkillsApi.list(selectedCompanyId!),
enabled: Boolean(selectedCompanyId),
});
const { data: routines = [] } = useQuery({
queryKey: selectedCompanyId
? queryKeys.routines.list(selectedCompanyId)
: ["routines", "__none__", "__all-projects__"],
queryFn: () => routinesApi.list(selectedCompanyId!),
enabled: Boolean(selectedCompanyId),
});
const value = useMemo<EditorAutocompleteContextValue>(() => ({
slashCommands: companySkills.map((skill) => ({
id: `skill:${skill.id}`,
kind: "skill",
skillId: skill.id,
key: skill.key,
name: skill.name,
slug: skill.slug,
description: skill.description ?? null,
href: buildSkillMentionHref(skill.id, skill.slug),
aliases: [skill.slug, skill.name, skill.key],
})),
}), [companySkills]);
slashCommands: [
...companySkills.map((skill) => ({
id: `skill:${skill.id}`,
kind: "skill" as const,
skillId: skill.id,
key: skill.key,
name: skill.name,
slug: skill.slug,
description: skill.description ?? null,
href: buildSkillMentionHref(skill.id, skill.slug),
aliases: [skill.slug, skill.name, skill.key],
})),
...routines
.filter((routine) => routine.status !== "archived")
.sort((left, right) => left.title.localeCompare(right.title))
.map((routine) => ({
id: `routine:${routine.id}`,
kind: "routine" as const,
routineId: routine.id,
name: routine.title,
status: routine.status,
href: buildRoutineMentionHref(routine.id),
aliases: [`routine:${routine.title}`, routine.title, routine.id],
})),
],
}), [companySkills, routines]);
return (
<EditorAutocompleteContext.Provider value={value}>

View file

@ -61,6 +61,8 @@ const ACTIVITY_ROW_VERBS: Record<string, string> = {
"agent.runtime_session_reset": "reset session for",
"heartbeat.invoked": "invoked heartbeat for",
"heartbeat.cancelled": "cancelled heartbeat for",
"heartbeat.output_stale_source_resolved": "system-folded stale run on",
"heartbeat.output_stale_recovery_recursion_refused": "refused recovery-on-recovery for",
"approval.created": "requested approval",
"approval.approved": "approved",
"approval.rejected": "rejected",
@ -115,6 +117,8 @@ const ISSUE_ACTIVITY_LABELS: Record<string, string> = {
"agent.terminated": "terminated the agent",
"heartbeat.invoked": "invoked a heartbeat",
"heartbeat.cancelled": "cancelled a heartbeat",
"heartbeat.output_stale_source_resolved": "System folded a stale run",
"heartbeat.output_stale_recovery_recursion_refused": "Refused recovery-on-recovery escalation",
"approval.created": "requested approval",
"approval.approved": "approved",
"approval.rejected": "rejected",

View file

@ -0,0 +1,85 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { buildDuplicateAgentPayload, duplicateAgentName } from "./duplicate-agent-payload";
import type { AgentDetail } from "@paperclipai/shared";
const baseAgent: AgentDetail = {
id: "agent-1",
companyId: "company-1",
name: "Senior Product Engineer",
urlKey: "senior-product-engineer",
role: "engineer",
title: "Senior Product Engineer",
icon: "code",
status: "idle",
reportsTo: "manager-1",
capabilities: "Builds product features.",
adapterType: "codex_local",
adapterConfig: {
model: "gpt-5.3-codex",
instructionsBundleMode: "managed",
instructionsRootPath: "/tmp/original/instructions",
instructionsEntryFile: "AGENTS.md",
instructionsFilePath: "/tmp/original/instructions/AGENTS.md",
promptTemplate: "legacy prompt",
bootstrapPromptTemplate: "legacy bootstrap",
},
runtimeConfig: {
heartbeat: { enabled: true },
},
defaultEnvironmentId: "environment-1",
budgetMonthlyCents: 500,
spentMonthlyCents: 123,
pauseReason: null,
pausedAt: null,
permissions: { canCreateAgents: true },
lastHeartbeatAt: null,
metadata: { source: "test" },
createdAt: new Date("2026-05-10T00:00:00.000Z"),
updatedAt: new Date("2026-05-10T00:00:00.000Z"),
chainOfCommand: [],
access: {
canAssignTasks: true,
taskAssignSource: "explicit_grant",
membership: null,
grants: [],
},
};
describe("duplicate agent payload", () => {
it("suffixes duplicate names", () => {
expect(duplicateAgentName("Senior Product Engineer")).toBe("Senior Product Engineer Copy");
expect(duplicateAgentName(" ")).toBe("Agent Copy");
});
it("copies agent fields while removing original instruction paths", () => {
const payload = buildDuplicateAgentPayload(baseAgent, {
entryFile: "AGENTS.md",
files: {
"AGENTS.md": "You are a copy.",
},
});
expect(payload).toMatchObject({
name: "Senior Product Engineer Copy",
role: "engineer",
title: "Senior Product Engineer",
icon: "code",
reportsTo: "manager-1",
capabilities: "Builds product features.",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.3-codex" },
runtimeConfig: { heartbeat: { enabled: true } },
defaultEnvironmentId: "environment-1",
budgetMonthlyCents: 500,
permissions: { canCreateAgents: true },
metadata: { source: "test" },
instructionsBundle: {
entryFile: "AGENTS.md",
files: { "AGENTS.md": "You are a copy." },
},
});
expect(payload.adapterConfig).not.toHaveProperty("instructionsFilePath");
expect(payload.adapterConfig).not.toHaveProperty("promptTemplate");
});
});

View file

@ -0,0 +1,78 @@
import type { AgentDetail } from "@paperclipai/shared";
const INSTRUCTION_CONFIG_KEYS = [
"instructionsBundleMode",
"instructionsRootPath",
"instructionsEntryFile",
"instructionsFilePath",
"agentsMdPath",
"promptTemplate",
"bootstrapPromptTemplate",
] as const;
export type DuplicateInstructionsBundle = {
entryFile: string;
files: Record<string, string>;
};
type DuplicateAgentSource = Pick<
AgentDetail,
| "name"
| "role"
| "title"
| "icon"
| "reportsTo"
| "capabilities"
| "adapterType"
| "adapterConfig"
| "runtimeConfig"
| "defaultEnvironmentId"
| "budgetMonthlyCents"
| "permissions"
| "metadata"
>;
function cloneRecord(value: Record<string, unknown> | null | undefined): Record<string, unknown> {
if (!value) return {};
return JSON.parse(JSON.stringify(value)) as Record<string, unknown>;
}
export function duplicateAgentName(name: string): string {
const trimmed = name.trim();
return `${trimmed || "Agent"} Copy`;
}
export function buildDuplicateAgentPayload(
agent: DuplicateAgentSource,
instructionsBundle?: DuplicateInstructionsBundle | null,
): Record<string, unknown> {
const adapterConfig = cloneRecord(agent.adapterConfig);
for (const key of INSTRUCTION_CONFIG_KEYS) {
delete adapterConfig[key];
}
const payload: Record<string, unknown> = {
name: duplicateAgentName(agent.name),
role: agent.role,
adapterType: agent.adapterType,
adapterConfig,
runtimeConfig: cloneRecord(agent.runtimeConfig),
defaultEnvironmentId: agent.defaultEnvironmentId ?? null,
budgetMonthlyCents: agent.budgetMonthlyCents ?? 0,
permissions: {
canCreateAgents: Boolean(agent.permissions?.canCreateAgents),
},
};
if (agent.title) payload.title = agent.title;
if (agent.icon) payload.icon = agent.icon;
if (agent.reportsTo) payload.reportsTo = agent.reportsTo;
if (agent.capabilities) payload.capabilities = agent.capabilities;
if (agent.metadata) payload.metadata = cloneRecord(agent.metadata);
if (instructionsBundle && Object.keys(instructionsBundle.files).length > 0) {
payload.instructionsBundle = instructionsBundle;
}
return payload;
}

View file

@ -3,6 +3,7 @@ import {
parseAgentMentionHref,
parseIssueReferenceHref,
parseProjectMentionHref,
parseRoutineMentionHref,
parseSkillMentionHref,
parseUserMentionHref,
} from "@paperclipai/shared";
@ -32,6 +33,10 @@ export type ParsedMentionChip =
kind: "skill";
skillId: string;
slug: string | null;
}
| {
kind: "routine";
routineId: string;
};
const iconMaskCache = new Map<string, string>();
@ -84,6 +89,14 @@ export function parseMentionChipHref(href: string): ParsedMentionChip | null {
};
}
const routine = parseRoutineMentionHref(href);
if (routine) {
return {
kind: "routine",
routineId: routine.routineId,
};
}
return null;
}
@ -135,6 +148,7 @@ export function clearMentionChipDecoration(element: HTMLElement) {
"paperclip-mention-chip--agent",
"paperclip-mention-chip--issue",
"paperclip-mention-chip--project",
"paperclip-mention-chip--routine",
"paperclip-mention-chip--user",
"paperclip-mention-chip--skill",
"paperclip-project-mention-chip",

View file

@ -0,0 +1,134 @@
import type { HeartbeatRun } from "@paperclipai/shared";
export type SourceResolvedFoldCleanupOutcome =
| "terminated"
| "termination_sent_still_running"
| "failed"
| "not_running"
| "no_process_metadata"
| "skipped_non_local_adapter"
| string;
export interface SourceResolvedFoldCleanup {
attempted: boolean;
outcome: SourceResolvedFoldCleanupOutcome;
adapterType: string | null;
pid: number | null;
processGroupId: number | null;
error: string | null;
}
export interface SourceResolvedWatchdogFold {
sourceIssueId: string;
sourceIssueIdentifier: string | null;
sourceIssueStatus: string;
sameRunEvidenceKind: string;
sameRunEvidenceId: string;
sameRunEvidenceAt: string;
silenceStartedAt: string | null;
silenceAgeMs: number | null;
evaluationIssueId: string | null;
evaluationIssueIdentifier: string | null;
cleanup: SourceResolvedFoldCleanup;
}
function asRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function asFiniteNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function asBoolean(value: unknown): boolean {
return value === true;
}
function parseCleanup(value: unknown): SourceResolvedFoldCleanup {
const record = asRecord(value);
if (!record) {
return {
attempted: false,
outcome: "no_process_metadata",
adapterType: null,
pid: null,
processGroupId: null,
error: null,
};
}
return {
attempted: asBoolean(record.attempted),
outcome: asString(record.outcome) ?? "no_process_metadata",
adapterType: asString(record.adapterType),
pid: asFiniteNumber(record.pid),
processGroupId: asFiniteNumber(record.processGroupId),
error: asString(record.error),
};
}
export function parseSourceResolvedWatchdogFold(value: unknown): SourceResolvedWatchdogFold | null {
const record = asRecord(value);
if (!record) return null;
const sourceIssueId = asString(record.sourceIssueId);
const sourceIssueStatus = asString(record.sourceIssueStatus);
if (!sourceIssueId || !sourceIssueStatus) return null;
const evidenceKind = asString(record.sameRunEvidenceKind);
const evidenceId = asString(record.sameRunEvidenceId);
const evidenceAt = asString(record.sameRunEvidenceAt);
if (!evidenceKind || !evidenceId || !evidenceAt) return null;
return {
sourceIssueId,
sourceIssueIdentifier: asString(record.sourceIssueIdentifier),
sourceIssueStatus,
sameRunEvidenceKind: evidenceKind,
sameRunEvidenceId: evidenceId,
sameRunEvidenceAt: evidenceAt,
silenceStartedAt: asString(record.silenceStartedAt),
silenceAgeMs: asFiniteNumber(record.silenceAgeMs),
evaluationIssueId: asString(record.evaluationIssueId),
evaluationIssueIdentifier: asString(record.evaluationIssueIdentifier),
cleanup: parseCleanup(record.cleanup),
};
}
export function readSourceResolvedWatchdogFold(
resultJson: HeartbeatRun["resultJson"] | Record<string, unknown> | null | undefined,
): SourceResolvedWatchdogFold | null {
const record = asRecord(resultJson);
if (!record) return null;
return parseSourceResolvedWatchdogFold(record.sourceResolvedWatchdogFold);
}
const CLEANUP_OUTCOME_LABELS: Record<string, string> = {
terminated: "terminated",
termination_sent_still_running: "termination sent (still running)",
failed: "failed",
not_running: "not running",
no_process_metadata: "no process metadata",
skipped_non_local_adapter: "skipped (non-local adapter)",
};
export function formatCleanupOutcome(outcome: string): string {
return CLEANUP_OUTCOME_LABELS[outcome] ?? outcome.replace(/_/g, " ");
}
export function formatSilenceAgeMs(ms: number | null | undefined): string | null {
if (!ms || ms <= 0) return null;
const totalMinutes = Math.floor(ms / 60_000);
if (totalMinutes < 1) return "under 1 minute";
if (totalMinutes < 60) return `${totalMinutes} minute${totalMinutes === 1 ? "" : "s"}`;
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
if (minutes === 0) return `${hours} hour${hours === 1 ? "" : "s"}`;
return `${hours}h ${minutes}m`;
}
export function shortenEvidenceId(id: string): string {
if (id.length <= 12) return id;
return id.slice(0, 8);
}

View file

@ -42,9 +42,13 @@ import { RunButton, PauseResumeButton } from "../components/AgentActionButtons";
import { BudgetPolicyCard } from "../components/BudgetPolicyCard";
import { FileTree, buildFileTree } from "../components/FileTree";
import { ScrollToBottom } from "../components/ScrollToBottom";
import { SourceResolvedFoldCallout } from "../components/SourceResolvedFoldCallout";
import { SourceResolvedFoldBadge } from "../components/SourceResolvedFoldBadge";
import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";
import { formatCents, formatDate, relativeTime, formatTokens, visibleRunCostUsd } from "../lib/utils";
import { cn } from "../lib/utils";
import { describeRunRetryState } from "../lib/runRetryState";
import { buildDuplicateAgentPayload, duplicateAgentName, type DuplicateInstructionsBundle } from "../lib/duplicate-agent-payload";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs } from "@/components/ui/tabs";
@ -83,6 +87,8 @@ import { RunTranscriptView, type TranscriptMode } from "../components/transcript
import {
isUuidLike,
type Agent,
type AgentInstructionsBundle,
type AgentInstructionsFileSummary,
type AgentSkillEntry,
type AgentSkillSnapshot,
type AgentDetail as AgentDetailRecord,
@ -101,6 +107,34 @@ import {
isReadOnlyUnmanagedSkillEntry,
} from "../lib/agent-skills-state";
async function loadDuplicateInstructionsBundle(
agentId: string,
companyId?: string,
): Promise<DuplicateInstructionsBundle | null> {
const bundle = await agentsApi.instructionsBundle(agentId, companyId);
const files: Record<string, string> = {};
for (const summary of bundle.files) {
const path = duplicateInstructionFilePath(bundle, summary);
if (!path) continue;
const file = await agentsApi.instructionsFile(agentId, summary.path, companyId);
files[path] = file.content;
}
const entryFile = Object.prototype.hasOwnProperty.call(files, bundle.entryFile)
? bundle.entryFile
: Object.keys(files)[0] ?? "AGENTS.md";
return Object.keys(files).length > 0 ? { entryFile, files } : null;
}
function duplicateInstructionFilePath(
_bundle: AgentInstructionsBundle,
summary: AgentInstructionsFileSummary,
): string | null {
if (summary.deprecated || summary.virtual) return null;
return summary.path;
}
const runStatusIcons: Record<string, { icon: typeof CheckCircle2; color: string }> = {
succeeded: { icon: CheckCircle2, color: "text-green-600 dark:text-green-400" },
failed: { icon: XCircle, color: "text-red-600 dark:text-red-400" },
@ -635,6 +669,7 @@ export function AgentDetail() {
const { companies, selectedCompanyId, setSelectedCompanyId } = useCompany();
const { closePanel } = usePanel();
const { openNewIssue } = useDialogActions();
const { pushToast } = useToastActions();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
const navigate = useNavigate();
@ -805,6 +840,57 @@ export function AgentDetail() {
},
});
const duplicateAgent = useMutation({
mutationFn: async () => {
if (!agent?.id || !resolvedCompanyId) {
throw new Error("Agent is not ready to duplicate");
}
const instructionsBundle = await loadDuplicateInstructionsBundle(agent.id, resolvedCompanyId);
const payload = buildDuplicateAgentPayload(agent, instructionsBundle);
try {
return await agentsApi.create(resolvedCompanyId, payload);
} catch (error) {
if (error instanceof ApiError && error.status === 409 && error.message.includes("requires board approval")) {
const hire = await agentsApi.hire(resolvedCompanyId, payload);
return hire.agent;
}
throw error;
}
},
onSuccess: async (createdAgent) => {
setActionError(null);
if (resolvedCompanyId) {
await queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(resolvedCompanyId) });
}
pushToast({
title: "Agent duplicated",
body: createdAgent.name,
tone: "success",
});
navigate(`/agents/${agentRouteRef(createdAgent)}/dashboard`);
},
onError: (err) => {
const message = err instanceof Error ? err.message : "Failed to duplicate agent";
setActionError(message);
pushToast({
title: "Could not duplicate agent",
body: message,
tone: "error",
});
},
});
const handleDuplicateAgent = useCallback(() => {
if (!agent || duplicateAgent.isPending) return;
const nextName = duplicateAgentName(agent.name);
const confirmed = window.confirm(`Duplicate ${agent.name} as ${nextName}?`);
setMoreOpen(false);
if (!confirmed) return;
duplicateAgent.mutate();
}, [agent, duplicateAgent]);
const budgetMutation = useMutation({
mutationFn: (amount: number) =>
budgetsApi.upsertPolicy(resolvedCompanyId!, {
@ -977,6 +1063,18 @@ export function AgentDetail() {
</Button>
</PopoverTrigger>
<PopoverContent className="w-44 p-1" align="end">
<button
className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"
disabled={duplicateAgent.isPending}
onClick={handleDuplicateAgent}
>
{duplicateAgent.isPending ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Copy className="h-3 w-3" />
)}
Duplicate Agent
</button>
<button
className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"
onClick={() => {
@ -2899,6 +2997,7 @@ function RunListItem({ run, isSelected, agentId }: { run: HeartbeatRun; isSelect
const summary = run.resultJson
? String((run.resultJson as Record<string, unknown>).summary ?? (run.resultJson as Record<string, unknown>).result ?? "")
: run.error ?? "";
const sourceResolvedFold = readSourceResolvedWatchdogFold(run.resultJson);
return (
<Link
@ -2922,6 +3021,7 @@ function RunListItem({ run, isSelected, agentId }: { run: HeartbeatRun; isSelect
)}>
{sourceLabels[run.invocationSource] ?? run.invocationSource}
</span>
{sourceResolvedFold ? <SourceResolvedFoldBadge showIcon={false} className="shrink-0 text-[10px] py-0" /> : null}
<span className="ml-auto text-[11px] text-muted-foreground shrink-0">
{relativeTime(run.createdAt)}
</span>
@ -3474,6 +3574,13 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig }
</div>
)}
{(() => {
const fold = readSourceResolvedWatchdogFold(run.resultJson);
if (!fold) return null;
if (run.status === "failed" || run.status === "timed_out") return null;
return <SourceResolvedFoldCallout fold={fold} finalizedAt={run.finishedAt} />;
})()}
{/* Log viewer */}
<LogViewer run={run} adapterType={adapterType} />
<ScrollToBottom />

View file

@ -1770,7 +1770,7 @@ export function IssueDetail() {
mutationFn: (data: {
actionId?: string;
outcome: ResolveRecoveryActionOutcome;
sourceIssueStatus: "done" | "in_review" | "blocked";
sourceIssueStatus: "todo" | "done" | "in_review" | "blocked";
resolutionNote?: string | null;
}) => issuesApi.resolveRecoveryAction(issueId!, data),
onSuccess: ({ issue: nextIssue }) => {
@ -3000,6 +3000,9 @@ export function IssueDetail() {
const actionId = activeRecoveryActionId;
if (!actionId) return;
switch (outcome) {
case "todo":
void resolveRecoveryAction.mutateAsync({ actionId, outcome: "restored", sourceIssueStatus: "todo" });
return;
case "done":
void resolveRecoveryAction.mutateAsync({ actionId, outcome: "restored", sourceIssueStatus: "done" });
return;

View file

@ -456,7 +456,7 @@ describe("Routines page", () => {
});
});
it("shows a row-level run now button on the routines table", async () => {
it("shows an outlined row-level run now button on the routines table", async () => {
routinesListMock.mockResolvedValue([createRoutine({ id: "routine-1", title: "Morning sync" })]);
issuesListMock.mockResolvedValue([]);
@ -489,6 +489,7 @@ describe("Routines page", () => {
}
expect(runNowButton).toBeTruthy();
expect(runNowButton?.getAttribute("data-variant")).toBe("outline");
await act(async () => {
root.unmount();

View file

@ -158,6 +158,32 @@ function focusFirstElement(container: HTMLElement | null): void {
container.focus();
}
function resolveLauncherNavigationTarget(target: string, hostContext: PluginLauncherContext): string {
if (/^https?:\/\//.test(target) || target.startsWith("/") || target.startsWith("#") || target.startsWith(".") || target.startsWith("?")) {
return target;
}
const companyPrefix = hostContext.companyPrefix?.trim();
return companyPrefix ? `/${companyPrefix}/${target}` : target;
}
function launcherRoutePath(launcher: ResolvedPluginLauncher): string | null {
if (launcher.action.type !== "navigate" && launcher.action.type !== "deepLink") return null;
if (/^https?:\/\//.test(launcher.action.target)) return null;
const [pathOnly] = launcher.action.target.split(/[?#]/, 1);
const segment = pathOnly?.split("/").filter(Boolean).at(-1);
return segment ? segment.toLowerCase() : null;
}
function launcherDisplayName(launcher: ResolvedPluginLauncher, contribution: PluginUiContribution | undefined): string {
if (launcher.placementZone !== "sidebar" || !contribution) return launcher.displayName;
const routePath = launcherRoutePath(launcher);
if (!routePath) return launcher.displayName;
const routeSidebar = contribution.slots.find((slot) =>
slot.type === "routeSidebar" && slot.routePath?.toLowerCase() === routePath
);
return routeSidebar?.displayName ?? launcher.displayName;
}
function trapFocus(container: HTMLElement, event: KeyboardEvent): void {
if (event.key !== "Tab") return;
const focusable = Array.from(
@ -652,13 +678,13 @@ export function PluginLauncherProvider({ children }: { children: ReactNode }) {
) => {
switch (launcher.action.type) {
case "navigate":
navigate(launcher.action.target);
navigate(resolveLauncherNavigationTarget(launcher.action.target, hostContext));
return;
case "deepLink":
if (/^https?:\/\//.test(launcher.action.target)) {
window.open(launcher.action.target, "_blank", "noopener,noreferrer");
} else {
navigate(launcher.action.target);
navigate(resolveLauncherNavigationTarget(launcher.action.target, hostContext));
}
return;
case "performAction":
@ -725,10 +751,12 @@ export function usePluginLauncherRuntime(): PluginLauncherRuntimeContextValue {
}
function DefaultLauncherTrigger({
displayName,
launcher,
placementZone,
onClick,
}: {
displayName?: string;
launcher: ResolvedPluginLauncher;
placementZone: PluginLauncherPlacementZone;
onClick: (event: ReactMouseEvent<HTMLButtonElement>) => void;
@ -741,7 +769,7 @@ function DefaultLauncherTrigger({
className={launcherTriggerClassName(placementZone)}
onClick={onClick}
>
{launcher.displayName}
{displayName ?? launcher.displayName}
</Button>
);
}
@ -786,6 +814,7 @@ export function PluginLauncherOutlet({
{launchers.map((launcher) => (
<div key={`${launcher.pluginKey}:${launcher.id}`} className={itemClassName}>
<DefaultLauncherTrigger
displayName={launcherDisplayName(launcher, contributionsByPluginId.get(launcher.pluginId))}
launcher={launcher}
placementZone={launcher.placementZone}
onClick={(event) => {