Files
PaperClipAI/ui/src/lib/external-objects.test.ts
T
DottaandPaperclip 2dbaf4a7fa External object references across issue surfaces (#8512)
## Thinking Path

> - Paperclip is the open source control plane people use to coordinate
AI agents, issues, approvals, comments, and work products.
> - The involved subsystem is issue context: markdown links, issue
properties, related work, lists, filters, inbox/sidebar status, and
plugin-provided external context.
> - The gap is that URLs to external systems currently remain mostly
plain links, so humans and agents must manually open them to understand
status, identity, and liveness.
> - This matters because external work objects such as GitHub issues and
pull requests are part of the operational state of a Paperclip company.
> - The implementation keeps core provider-neutral: shared contracts,
storage, sync, routes, and UI surfaces live in core while providers can
contribute detection and status resolution.
> - This pull request adds the external object reference foundation,
GitHub provider support, issue-surface rendering, filters,
sidebar/list/inbox signals, and test/story coverage.
> - The benefit is that linked external work becomes inspectable
Paperclip context without hardcoding every provider directly into the
UI.

## Linked Issues or Issue Description

No public GitHub issue exists for this work.

Feature request:

- Problem: URLs in Paperclip issues, comments, documents, and related
surfaces do not expose provider status or object identity inline.
- Proposed behavior: detect supported external object URLs, persist
normalized references, refresh provider status, and render concise
status-aware links across issue surfaces.
- Users affected: board users, agents, and maintainers who triage issues
containing external work links.
- Acceptance: external object references are company-scoped,
provider-extensible, visible in key issue surfaces, filterable where
relevant, and covered by focused shared/server/UI tests.

Related PR search:

- No open duplicate PRs found for `external object references`.
- Closed related prior attempt: #4556.

## What Changed

- Added shared external-object contracts, validators, status/liveness
helpers, and plugin protocol declarations.
- Added database schema and additive migrations for external objects,
source mentions, and display metadata.
- Added server services/routes for detecting, syncing, summarizing,
refreshing, and resolving external objects across issues, documents,
comments, projects, and plugins.
- Added a GitHub external-object provider plus plugin SDK authoring
docs.
- Wired UI presentation across markdown links, comments, issue chat,
documents, properties, related work, issue rows, filters, inbox/sidebar
badges, and Storybook stories.
- Rebasing cleanup: moved the branch onto current `master`, repaired
stale worktree provision config, hardened environment-sensitive
tests/mocks, and removed committed screenshot artifacts from the PR
branch to keep the reviewable file set below tool limits.

## Verification

- `pnpm exec vitest run packages/shared/src/external-objects.test.ts
server/src/__tests__/external-object-routes.test.ts
server/src/__tests__/external-objects-service.test.ts
ui/src/components/ExternalObjectPill.test.tsx
ui/src/lib/external-objects.test.ts` passed after rebasing: 5 files, 56
tests.
- Historical branch verification before this PR creation included `pnpm
test:run`, `pnpm -r typecheck`, and `pnpm build`; this PR body does not
claim those were rerun after the final rebase.

## Risks

- Medium: this adds a new cross-surface sync path on
issue/document/comment writes. The implementation uses safe sync
wrappers so external-object failures warn instead of blocking core
mutations.
- Medium: the migrations introduce new tables and indexes. They are
additive and company-scoped.
- Medium: provider-specific URL parsing can miss or misclassify edge
cases. Shared canonicalization tests and provider tests cover current
GitHub shapes.
- Low: UI badge/filter behavior could add visual noise for object-heavy
issues; component tests and Storybook stories cover the intended
surfaces.

> Roadmap checked: `ROADMAP.md` references the plugin system as the
current extension path and does not list a duplicate core feature.
Related long-range docs discuss external references, work products,
preview URLs, and plugin extension points; this PR implements the scoped
external-object reference foundation.

## Model Used

OpenAI Codex, GPT-5 coding-agent runtime, with shell and GitHub CLI tool
use. Reasoning mode: medium. Exact deployed runtime model ID and context
window were not exposed in the environment.

## 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 not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [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 any 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: Paperclip <noreply@paperclip.ing>
2026-06-23 08:27:19 -05:00

191 lines
9.3 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import type { ExternalObjectSummary } from "@paperclipai/shared";
import { externalObjectsApi } from "../api/externalObjects";
import {
EXTERNAL_OBJECT_SUMMARY_BATCH_SIZE,
fetchIssueExternalObjectSummariesInBatches,
} from "../hooks/useIssueExternalObjects";
import {
dominantExternalObjectTone,
externalObjectCategoryLabel,
externalObjectDominantCount,
externalObjectFallbackTone,
externalObjectIconForCategory,
externalObjectIconForKey,
externalObjectLivenessLabel,
externalObjectProviderLabel,
externalObjectToneSeverity,
externalObjectTypeLabel,
sortExternalObjectsBySeverity,
} from "./external-objects";
import { normalizeExternalObjectHref } from "./external-object-href";
vi.mock("../api/externalObjects", () => ({
externalObjectsApi: {
getIssueSummaries: vi.fn(),
},
}));
const emptySummary: ExternalObjectSummary = {
total: 0,
byStatusCategory: {},
byLiveness: {},
highestSeverity: "neutral",
staleCount: 0,
authRequiredCount: 0,
unreachableCount: 0,
objects: [],
};
describe("normalizeExternalObjectHref", () => {
it("lowercases the host (case preserving the path) and drops query/fragment", () => {
expect(
normalizeExternalObjectHref("HTTPS://Github.com/Acme/Web/pull/241?token=abc#frag"),
).toBe("https://github.com/Acme/Web/pull/241");
});
it("rejects non-http(s) and userinfo-bearing URLs", () => {
expect(normalizeExternalObjectHref("javascript:alert(1)")).toBeNull();
expect(normalizeExternalObjectHref("ftp://example.com/file")).toBeNull();
expect(normalizeExternalObjectHref("https://user:pass@example.com/")).toBeNull();
expect(normalizeExternalObjectHref(null)).toBeNull();
expect(normalizeExternalObjectHref(undefined)).toBeNull();
expect(normalizeExternalObjectHref("not a url")).toBeNull();
});
it("defaults pathless URLs to /", () => {
expect(normalizeExternalObjectHref("https://example.com")).toBe("https://example.com/");
});
});
describe("fetchIssueExternalObjectSummariesInBatches", () => {
afterEach(() => {
vi.mocked(externalObjectsApi.getIssueSummaries).mockReset();
});
it("chunks bulk summary requests below the server validation cap and merges results", async () => {
const issueIds = Array.from(
{ length: EXTERNAL_OBJECT_SUMMARY_BATCH_SIZE * 2 + 3 },
(_entry, index) => `issue-${index}`,
);
vi.mocked(externalObjectsApi.getIssueSummaries).mockImplementation(async (_companyId, ids) => ({
summaries: Object.fromEntries(ids.map((id) => [id, { ...emptySummary, total: id.endsWith("-0") ? 1 : 0 }])),
}));
const result = await fetchIssueExternalObjectSummariesInBatches("company-1", issueIds);
expect(externalObjectsApi.getIssueSummaries).toHaveBeenCalledTimes(3);
expect(vi.mocked(externalObjectsApi.getIssueSummaries).mock.calls.map((call) => call[1].length)).toEqual([
EXTERNAL_OBJECT_SUMMARY_BATCH_SIZE,
EXTERNAL_OBJECT_SUMMARY_BATCH_SIZE,
3,
]);
expect(Object.keys(result.summaries)).toHaveLength(issueIds.length);
expect(result.summaries["issue-0"]?.total).toBe(1);
});
});
describe("external-objects helpers", () => {
it("labels categories with copy from the UX spec", () => {
expect(externalObjectCategoryLabel("auth_required")).toBe("Authorization required");
expect(externalObjectCategoryLabel("succeeded")).toBe("Succeeded");
expect(externalObjectCategoryLabel("unknown")).toBe("Not yet resolved");
});
it("labels liveness states with non-tech copy", () => {
expect(externalObjectLivenessLabel("stale")).toBe("Stale");
expect(externalObjectLivenessLabel("auth_required")).toBe("Requires auth");
expect(externalObjectLivenessLabel("fresh")).toBe("Fresh");
});
it("falls back to a humanised label for unknown providers and types", () => {
expect(externalObjectProviderLabel("github")).toBe("GitHub");
expect(externalObjectProviderLabel("hubspot_marketing")).toBe("Hubspot Marketing");
expect(externalObjectProviderLabel(null)).toBe("External");
expect(externalObjectTypeLabel("workflow_run")).toBe("workflow run");
expect(externalObjectTypeLabel(null)).toBe("object");
});
it("orders tones from danger down to muted", () => {
expect(externalObjectToneSeverity("danger")).toBeGreaterThan(externalObjectToneSeverity("warning"));
expect(externalObjectToneSeverity("warning")).toBeGreaterThan(externalObjectToneSeverity("info"));
expect(externalObjectToneSeverity("info")).toBeGreaterThan(externalObjectToneSeverity("success"));
expect(externalObjectToneSeverity("success")).toBeGreaterThan(externalObjectToneSeverity("muted"));
expect(externalObjectToneSeverity(null)).toBe(0);
expect(externalObjectToneSeverity("nonsense")).toBe(0);
});
it("maps every spec category to a fallback tone", () => {
expect(externalObjectFallbackTone("failed")).toBe("danger");
expect(externalObjectFallbackTone("waiting")).toBe("warning");
expect(externalObjectFallbackTone("running")).toBe("info");
expect(externalObjectFallbackTone("succeeded")).toBe("success");
expect(externalObjectFallbackTone("auth_required")).toBe("warning");
expect(externalObjectFallbackTone("unreachable")).toBe("danger");
});
it("returns the spec lucide icon names for every category", () => {
expect(externalObjectIconForCategory("succeeded").displayName ?? "").toMatch(/CheckCircle2|Check/);
expect(externalObjectIconForCategory("failed").displayName ?? "").toMatch(/XCircle|X/);
expect(externalObjectIconForCategory("auth_required").displayName ?? "").toMatch(/KeyRound|Key/);
expect(externalObjectIconForCategory("unreachable").displayName ?? "").toMatch(/CloudOff|Cloud/);
expect(externalObjectIconForCategory("running").displayName ?? "").toMatch(/Loader2|Loader/);
});
it("maps provider-controlled icon keys through host-owned icons", () => {
expect(externalObjectIconForKey("github")?.displayName ?? "").toMatch(/Github/i);
expect(externalObjectIconForKey("git-pull-request")?.displayName ?? "").toMatch(/GitPullRequest/i);
expect(externalObjectIconForKey("unknown-provider-icon")).toBeNull();
});
it("sorts items by severity first, preserving insertion order within a tone", () => {
const items = [
{ id: "a", statusTone: "info", providerKey: "github", objectType: "pull_request", displayTitle: null, statusCategory: "running", liveness: "fresh", isTerminal: false },
{ id: "b", statusTone: "danger", providerKey: "ci", objectType: "deployment", displayTitle: null, statusCategory: "failed", liveness: "fresh", isTerminal: false },
{ id: "c", statusTone: "warning", providerKey: "hubspot", objectType: "lead", displayTitle: null, statusCategory: "waiting", liveness: "fresh", isTerminal: false },
{ id: "d", statusTone: "danger", providerKey: "github", objectType: "issue", displayTitle: null, statusCategory: "blocked", liveness: "fresh", isTerminal: false },
] as const;
const sorted = sortExternalObjectsBySeverity(items as never);
expect(sorted.map((item) => item.id)).toEqual(["b", "d", "c", "a"]);
});
it("hides the rollup when every item is in a muted tone", () => {
const summary = {
total: 2,
byStatusCategory: { closed: 2 },
byLiveness: { fresh: 2 },
highestSeverity: "muted" as const,
staleCount: 0,
authRequiredCount: 0,
unreachableCount: 0,
objects: [
{ id: "a", providerKey: "x", objectType: "y", displayTitle: null, statusCategory: "closed" as const, statusTone: "muted" as const, liveness: "fresh" as const, isTerminal: true },
{ id: "b", providerKey: "x", objectType: "y", displayTitle: null, statusCategory: "closed" as const, statusTone: "muted" as const, liveness: "fresh" as const, isTerminal: true },
],
};
expect(dominantExternalObjectTone(summary)).toBeNull();
expect(externalObjectDominantCount(summary)).toBe(0);
});
it("counts only the dominant-severity items in the rollup", () => {
const summary = {
total: 5,
byStatusCategory: { failed: 3, succeeded: 2 },
byLiveness: { fresh: 5 },
highestSeverity: "danger" as const,
staleCount: 0,
authRequiredCount: 0,
unreachableCount: 0,
objects: [
{ id: "a", providerKey: "ci", objectType: "deployment", displayTitle: null, statusCategory: "failed" as const, statusTone: "danger" as const, liveness: "fresh" as const, isTerminal: false },
{ id: "b", providerKey: "ci", objectType: "deployment", displayTitle: null, statusCategory: "failed" as const, statusTone: "danger" as const, liveness: "fresh" as const, isTerminal: false },
{ id: "c", providerKey: "ci", objectType: "deployment", displayTitle: null, statusCategory: "failed" as const, statusTone: "danger" as const, liveness: "fresh" as const, isTerminal: false },
{ id: "d", providerKey: "github", objectType: "pull_request", displayTitle: null, statusCategory: "succeeded" as const, statusTone: "success" as const, liveness: "fresh" as const, isTerminal: true },
{ id: "e", providerKey: "github", objectType: "pull_request", displayTitle: null, statusCategory: "succeeded" as const, statusTone: "success" as const, liveness: "fresh" as const, isTerminal: true },
],
};
expect(dominantExternalObjectTone(summary)).toBe("danger");
expect(externalObjectDominantCount(summary)).toBe(3);
});
});