mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip tasks and comments now store channel, key-value, claim lease, profile attribution, and structured schema fields on existing issue and comment tables (`channelId`, `kvLabels`, `schemaBlocks`, `resultSchemaRef`, `createdByProfile`, `actorProfile`, and claim lease fields). > - Existing board task views (`IssueProperties`, `MarkdownBody`, `CommentThread`, `IssueChatThread`, and `IssueDetail`) do not yet display these fields, and canonical `/api/issues/:id` routes do not resolve `channelPath` or strip `claimTokenHash` at serialization time. > - Users and reviewers cannot see channel provenance, key-values, active or expired claim leases, `--as <profile>` attribution, or structured `schema=<name>@<version>` blocks when they open a task in the UI. > - This pull request synchronizes the shared `Issue` and `IssueComment` contracts, resolves `channelPath` only when channel access and actor scopes allow it, strips `claimTokenHash` from issue responses, renders channel, key-values, lease, result schema, and structured schema cards across existing task views (only when set), and adds production-component Storybooks. > - The benefit is that existing task surfaces show channel, lease, key-value, profile, and schema state cleanly in place without cluttering standard tasks or adding a separate Channels navigation item, while preserving secret isolation on claim tokens. ## Linked Issues or Issue Description Refs #23329 Refs #23330 **What existing behavior does this improve?** Existing task detail, properties, Markdown body, comment thread, chat thread, and `/api/issues` HTTP serialization for tasks that carry channel, claim lease, key-value, profile attribution, or structured schema data. **Subsystem affected** Cross-cutting (`packages/shared`, `server/`, `ui/`, `ui/storybook/`, and `docs/api/`) **Current behavior** Canonical `/api/issues` routes return raw issue columns without a resolved `channelPath` and include `claimTokenHash: null` on the response shape. In `ui/`, `IssueProperties` omits channel provenance, `Key-values` editing, claim lease status, `resultSchemaRef` verification, and `--as <profile>` creator attribution. `MarkdownBody` renders ```` ```json schema=<name>@<version> ```` blocks only as plain code blocks, and comment threads show `local-board` or generic user labels instead of `actorProfile` and omit comment-level key-values. **Proposed behavior** `Issue` and `IssueComment` expose safe coordination and schema fields in `@paperclipai/shared`. Server issue routes strip `claimTokenHash` from serialized issue objects and resolve `channelPath` in batch via `findInaccessibleChannelIds` only when actor scopes and channel membership succeed (with zero extra SQL queries when `channelId` is null). `IssueProperties` mounts cohesive task property rows (`structured-task-rows.tsx`) strictly when set: `#<channelPath>` badge on `Channel`, inline `Key-values` add/edit/remove with CAS preconditions (`PATCH /api/issues/:id/kv-labels`), active vs expired `Lease` status with inline status dot and live countdown, `Result schema` matching status, and creator `--as <profile>` attribution. `MarkdownBody` and task discussion/chat threads render token-styled `SchemaBlockCard` views (`finding@1`, `test-report@1`, `git-commit@1`, `pull-request@1`, and custom `<name>@<version>` schemas) with a `Structured` / `JSON` toggle, deduplicated standalone `schemaBlocks`, `--as <actorProfile>` attribution, and comment key-value pills. Four production-component Storybooks document these states under `tasks-channels-leases-and-schemas`. **Reason and benefit** Agents and CLI workflows coordinate through existing Paperclip tasks and comments. Surfacing channel provenance, claim leases, key-values, profile attribution, and typed schema blocks directly on existing task views (and hiding those rows completely when unset) lets people inspect and edit structured task state in place without introducing new top-level navigation, while guaranteeing that `claimTokenHash` never leaves the server. **Breaking changes** None for external callers. `claimTokenHash` is omitted from serialized `/api/issues` JSON responses as a security invariant, and `channelPath` (`string | null`) is added on canonical issue read and update responses. ## What Changed - `packages/shared/src/types/issue.ts` and `tests/runner-e2e/source-sdk-public-inputs.json`: expose safe fields on `Issue` (`channelId`, `channelPath`, `createdByProfile`, `kvLabels`, `schemaBlocks`, `resultSchemaRef`, `claimEpoch`, `claimHolderAgentId`, `claimHolderUserId`, `claimHolderProfile`, `claimLeasedAt`, `claimLeaseExpiresAt`, `claimAttemptCount`) and `IssueComment` (`actorProfile`, `kvLabels`, `schemaBlocks`), never `claimTokenHash`, and synchronize the SDK public input registry pin. - `server/src/services/issues.ts`, `server/src/routes/issues.ts`, and `docs/api/issues.md`: omit `claim_token_hash` from SQL issue selections and `withIssueLabels`, strip `claimTokenHash` on HTTP serialization across issue routes, clear `kvLabels` and `schemaBlocks` on tombstoned comments, resolve `channelPath` in batch via `resolveHeadlessActor` and `findInaccessibleChannelIds` (zero extra SQL queries when `channelId` is `null`), and document the API response contract. - `server/src/__tests__/fixtures/issue-detail-response.json`, `server/src/__tests__/issue-activity-events-routes.test.ts`, and `server/src/__tests__/headless-channels-schemas-batch.test.ts`: update issue detail and update response snapshots (`channelPath: null`, no `claimTokenHash`) and add route contract coverage for `channelPath` visibility, scope enforcement, comment fields, and `claimTokenHash` omission. - `ui/src/api/issues.ts` and `ui/src/api/issues.test.ts`: add `issuesApi.updateKvLabels` targeting `PATCH /api/issues/:id/kv-labels` with CAS precondition normalization (`set`, `unset`, `if`) and unit test coverage. - `ui/src/components/issue-properties/structured-task-rows.tsx` and `IssueProperties.tsx`: add `IssueChannelRow`, `IssueKvLabelsRow` (`Key-values` with inline edit, remove, `+ Add`, CAS preconditions, touch-safe 16px inputs, and complete omission when empty), `IssueClaimLeaseRow` (inline status dot, live countdown, and omission when unset or released), `IssueResultSchemaRow` (unwrapping `InfiniteData` and identifier-keyed comment query caches, plus distinguishing `"unverified"` truncated scans from `"missing"`), and `IssueProfileAttributionRow`. - `ui/src/components/SchemaBlockCard.tsx`, `ui/src/lib/schema-block-utils.ts`, and `ui/src/components/MarkdownBody.tsx`: parse ```` ```json schema=<name>@<version> ```` fences (plus `{ schema, data }` JSON envelopes) via a static remark plugin and a bounded linear $O(N)$ single-pass CommonMark fence scanner (no multi-line backtracking regexes); render semantic-token cards for `finding@1`, `test-report@1`, `git-commit@1`, `pull-request@1`, and custom `<name>@<version>` blocks with `Structured` / `JSON` toggle, `https://`-only link safety, malformed-JSON code-block fallback, and iterative stack-safe `schemaBlocks` deduplication. - `ui/src/components/CommentStructuredMeta.tsx`, `CommentThread.tsx`, `IssueChatThread.tsx`, `TaskChatBubble.tsx`, `TaskChatDescriptionBubble.tsx`, `IssueDetail.tsx`, and chat adapters: render `--as <actorProfile>` attribution, comment-level key-value chips, and unfenced `schemaBlocks` across classic and chat task threads. - `ui/storybook/stories/tasks/channels-leases-and-schemas.stories.tsx`: add `ChannelTaskPropertiesActiveLease`, `ExpiredLeaseProperties`, `BuiltInAndCustomSchemaBlocks`, and `ChannelTaskThreadEndToEnd` stories registered under `tasks-channels-leases-and-schemas`. - `ui/src/components/issue-properties/structured-task-rows.test.tsx` and `ui/src/components/SchemaBlockCard.test.tsx`: add unit tests covering unset-row omission on standard tasks, single-badge channel provenance, CAS key-value mutations and `409` conflict rollback, inline lease status dots and countdown expiry, `InfiniteData` comment unwrapping, structured schema cards, malformed JSON fallback, linear $O(N)$ scanning on 5,000 unterminated JSON fences, newline-clamped markdown bounds, and deep deduplication. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `cd server && node scripts/typecheck-layers.mjs` — passed (0 errors across all layers and test trees). - `cd server && npx vitest run src/__tests__/service-read-disconnect-retry.test.ts src/__tests__/issue-activity-events-routes.test.ts src/__tests__/issue-detail-statements.test.ts src/__tests__/headless-channels-schemas-batch.test.ts` — passed (54/54 tests). - `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors). - `cd ui && npx vitest run src/components/issue-properties/structured-task-rows.test.tsx src/components/SchemaBlockCard.test.tsx src/api/issues.test.ts src/lib/issue-chat-messages.test.ts src/components/task-chat/task-chat-adapter.test.ts` — passed (115/115 tests). - `node scripts/check-token-gates.mjs`, `node scripts/check-test-budget.mjs`, `node scripts/check-module-boundaries.mjs`, and `node scripts/check-query-error-rendering.mjs` — all passed. - `node scripts/storybook-catalog.mjs && node scripts/storybook-catalog.mjs --check` and `node --test scripts/check-maps.test.mjs scripts/storybook-catalog.test.mjs scripts/storybook-feature-index.test.mjs` — passed (30/30 tests). - `pnpm --filter @paperclipai/ui build-storybook` — passed and verified built story IDs (`tasks-channels-leases-and-schemas--channel-task-properties-active-lease`, `tasks-channels-leases-and-schemas--expired-lease-properties`, `tasks-channels-leases-and-schemas--built-in-and-custom-schema-blocks`, `tasks-channels-leases-and-schemas--channel-task-thread-end-to-end`). ## Risks - Low risk. Standard board tasks with unset `Channel`, `Key-values`, `Lease`, and `Result schema` omit all four property rows completely, preserving existing `IssueProperties` layout and SQL query count (`0` extra queries when `channelId` is `null`). - Fenced code blocks without `schema=<name>@<version>` metadata (or with invalid JSON) fall back directly to the existing `CodeBlock` renderer. ## Model Used - Google Gemini (`gemini-3.1-pro` / Antigravity agentic coding runtime with extended thinking, code search, file editing, and terminal verification tools). ## 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>
751 lines
26 KiB
TypeScript
751 lines
26 KiB
TypeScript
import {
|
|
memo,
|
|
useCallback,
|
|
useEffect,
|
|
useMemo,
|
|
useRef,
|
|
useState,
|
|
type CSSProperties,
|
|
} from "react";
|
|
import {
|
|
AlertTriangle,
|
|
Braces,
|
|
Check,
|
|
CheckCircle2,
|
|
Clock,
|
|
Copy,
|
|
ExternalLink,
|
|
FileCode2,
|
|
GitBranch,
|
|
GitCommitHorizontal,
|
|
GitMerge,
|
|
GitPullRequest,
|
|
Info,
|
|
ShieldAlert,
|
|
XCircle,
|
|
} from "lucide-react";
|
|
import type { SchemaBlock } from "@paperclipai/shared";
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { copyTextToClipboard } from "../lib/clipboard";
|
|
import {
|
|
EMPTY_SCHEMA_BLOCKS,
|
|
canonicalSchemaBlockKey,
|
|
extractFencedSchemaBlocks,
|
|
getUnfencedSchemaBlocks,
|
|
hasMatchingSchemaBlock,
|
|
isPlainRecord,
|
|
parseJsonSchemaBlock,
|
|
parseSchemaFenceMeta,
|
|
safeHttpsUrl,
|
|
type ParsedFencedSchemaBlock,
|
|
} from "../lib/schema-block-utils";
|
|
import { cn } from "../lib/utils";
|
|
|
|
export {
|
|
EMPTY_SCHEMA_BLOCKS,
|
|
canonicalSchemaBlockKey,
|
|
extractFencedSchemaBlocks,
|
|
getUnfencedSchemaBlocks,
|
|
hasMatchingSchemaBlock,
|
|
parseJsonSchemaBlock,
|
|
parseSchemaFenceMeta,
|
|
safeHttpsUrl,
|
|
type ParsedFencedSchemaBlock,
|
|
};
|
|
|
|
function scStyle(cssVar: string): CSSProperties {
|
|
return { "--sc": `var(${cssVar})` } as CSSProperties;
|
|
}
|
|
|
|
function asNonEmptyString(value: unknown): string | null {
|
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
}
|
|
|
|
function asFiniteNumber(value: unknown): number | null {
|
|
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
}
|
|
|
|
function formatDurationValue(data: Record<string, unknown>): string | null {
|
|
const rawDuration = data.duration;
|
|
if (typeof rawDuration === "string" && rawDuration.trim()) return rawDuration.trim();
|
|
const durationMs = asFiniteNumber(data.durationMs) ?? asFiniteNumber(rawDuration);
|
|
if (durationMs === null || durationMs < 0) return null;
|
|
if (durationMs < 1000) return `${Math.round(durationMs)}ms`;
|
|
const seconds = durationMs / 1000;
|
|
return seconds < 60
|
|
? `${seconds.toFixed(seconds < 10 ? 2 : 1)}s`
|
|
: `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
|
|
}
|
|
|
|
function severityPresentation(rawSeverity: string | null) {
|
|
const normalized = rawSeverity?.toLowerCase() ?? "info";
|
|
switch (normalized) {
|
|
case "critical":
|
|
return {
|
|
label: "critical",
|
|
badgeClass: "border-destructive/40 bg-destructive/15 text-destructive",
|
|
statusVar: null as string | null,
|
|
Icon: ShieldAlert,
|
|
};
|
|
case "high":
|
|
return {
|
|
label: "high",
|
|
badgeClass: "status-chip",
|
|
statusVar: "--status-task-blocked",
|
|
Icon: AlertTriangle,
|
|
};
|
|
case "medium":
|
|
return {
|
|
label: "medium",
|
|
badgeClass: "status-chip",
|
|
statusVar: "--status-task-todo",
|
|
Icon: AlertTriangle,
|
|
};
|
|
case "low":
|
|
return {
|
|
label: "low",
|
|
badgeClass: "status-chip",
|
|
statusVar: "--status-task-in_progress",
|
|
Icon: Info,
|
|
};
|
|
default:
|
|
return {
|
|
label: normalized || "info",
|
|
badgeClass: "border-border bg-muted text-muted-foreground",
|
|
statusVar: null as string | null,
|
|
Icon: Info,
|
|
};
|
|
}
|
|
}
|
|
|
|
function FindingCardBody({ data }: { data: Record<string, unknown> }) {
|
|
const severity = severityPresentation(asNonEmptyString(data.severity));
|
|
const SeverityIcon = severity.Icon;
|
|
const title = asNonEmptyString(data.title) ?? asNonEmptyString(data.summary) ?? "Untitled finding";
|
|
const summary = asNonEmptyString(data.title) ? asNonEmptyString(data.summary) : null;
|
|
const details = asNonEmptyString(data.details);
|
|
const recommendation = asNonEmptyString(data.recommendation) ?? asNonEmptyString(data.remediation);
|
|
const filePath = asNonEmptyString(data.path) ?? asNonEmptyString(data.file);
|
|
const line = asFiniteNumber(data.line);
|
|
const column = asFiniteNumber(data.column);
|
|
const category = asNonEmptyString(data.category);
|
|
const cve = asNonEmptyString(data.cve);
|
|
const location = filePath
|
|
? `${filePath}${line !== null ? `:${line}${column !== null ? `:${column}` : ""}` : ""}`
|
|
: null;
|
|
|
|
return (
|
|
<div className="space-y-2 p-3">
|
|
<div className="flex flex-wrap items-center gap-1.5">
|
|
<Badge
|
|
variant="outline"
|
|
className={cn("gap-1 font-mono text-xs uppercase", severity.badgeClass)}
|
|
style={severity.statusVar ? scStyle(severity.statusVar) : undefined}
|
|
>
|
|
<SeverityIcon className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
{severity.label}
|
|
</Badge>
|
|
{category ? (
|
|
<Badge variant="outline" className="font-mono text-xs text-muted-foreground">
|
|
{category}
|
|
</Badge>
|
|
) : null}
|
|
{cve ? (
|
|
<Badge variant="outline" className="font-mono text-xs text-foreground">
|
|
{cve}
|
|
</Badge>
|
|
) : null}
|
|
{location ? (
|
|
<span
|
|
className="inline-flex min-w-0 items-center gap-1 rounded-sm border border-border bg-muted/40 px-1.5 py-0.5 font-mono text-xs text-muted-foreground"
|
|
title={location}
|
|
>
|
|
<FileCode2 className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
<span className="truncate">{location}</span>
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
|
|
<div className="text-sm font-medium text-foreground">{title}</div>
|
|
|
|
{summary ? <p className="text-sm text-muted-foreground">{summary}</p> : null}
|
|
{details ? <p className="text-xs text-muted-foreground">{details}</p> : null}
|
|
|
|
{recommendation ? (
|
|
<div className="rounded-sm border-l-2 border-border bg-muted/40 px-2.5 py-1.5 text-xs">
|
|
<span className="font-medium text-foreground">Recommendation: </span>
|
|
<span className="text-muted-foreground">{recommendation}</span>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function TestReportCardBody({ data }: { data: Record<string, unknown> }) {
|
|
const failedCount = asFiniteNumber(data.failed);
|
|
const skippedCount = asFiniteNumber(data.skipped);
|
|
const totalCount = asFiniteNumber(data.total);
|
|
const explicitPassedCount =
|
|
typeof data.passed === "number" && Number.isFinite(data.passed)
|
|
? data.passed
|
|
: asFiniteNumber(data.passedCount);
|
|
|
|
const isPassed =
|
|
typeof data.passed === "boolean"
|
|
? data.passed
|
|
: typeof data.status === "string"
|
|
? data.status.toLowerCase() === "passed" || data.status.toLowerCase() === "pass"
|
|
: (failedCount ?? 0) === 0;
|
|
|
|
const passedCount =
|
|
explicitPassedCount !== null
|
|
? explicitPassedCount
|
|
: totalCount !== null
|
|
? Math.max(0, totalCount - (failedCount ?? 0) - (skippedCount ?? 0))
|
|
: null;
|
|
|
|
const computedTotal =
|
|
totalCount !== null
|
|
? totalCount
|
|
: passedCount !== null || failedCount !== null || skippedCount !== null
|
|
? (passedCount ?? 0) + (failedCount ?? 0) + (skippedCount ?? 0)
|
|
: null;
|
|
|
|
const duration = formatDurationValue(data);
|
|
const command = asNonEmptyString(data.command);
|
|
const summary = asNonEmptyString(data.summary);
|
|
const rawFailures = Array.isArray(data.failures) ? data.failures : [];
|
|
const failures = rawFailures
|
|
.map((entry) => {
|
|
if (typeof entry === "string" && entry.trim()) {
|
|
return { name: entry.trim(), message: null as string | null };
|
|
}
|
|
if (isPlainRecord(entry)) {
|
|
const name = asNonEmptyString(entry.name) ?? asNonEmptyString(entry.test);
|
|
if (!name) return null;
|
|
return { name, message: asNonEmptyString(entry.message) ?? asNonEmptyString(entry.error) };
|
|
}
|
|
return null;
|
|
})
|
|
.filter((item): item is { name: string; message: string | null } => Boolean(item));
|
|
|
|
return (
|
|
<div className="space-y-2.5 p-3">
|
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
|
<div className="flex flex-wrap items-center gap-1.5">
|
|
<Badge
|
|
variant="outline"
|
|
className={cn(
|
|
"gap-1 font-mono text-xs",
|
|
isPassed ? "status-chip" : "border-destructive/40 bg-destructive/15 text-destructive",
|
|
)}
|
|
style={isPassed ? scStyle("--status-task-done") : undefined}
|
|
>
|
|
{isPassed ? (
|
|
<CheckCircle2 className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
) : (
|
|
<XCircle className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
)}
|
|
{isPassed ? "Passed" : "Failed"}
|
|
</Badge>
|
|
{command ? (
|
|
<span className="truncate rounded-sm border border-border bg-muted/40 px-1.5 py-0.5 font-mono text-xs text-muted-foreground">
|
|
{command}
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
{duration ? (
|
|
<span className="inline-flex items-center gap-1 font-mono text-xs text-muted-foreground">
|
|
<Clock className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
{duration}
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
|
|
{passedCount !== null || failedCount !== null || skippedCount !== null || computedTotal !== null ? (
|
|
<div className="grid grid-cols-2 gap-1.5 sm:grid-cols-4">
|
|
<div className="rounded-sm border border-border bg-muted/30 px-2.5 py-1.5">
|
|
<div className="text-xs text-muted-foreground">Passed</div>
|
|
<div className="font-mono text-sm font-semibold text-(--diff-add-fg)">
|
|
{passedCount ?? 0}
|
|
</div>
|
|
</div>
|
|
<div className="rounded-sm border border-border bg-muted/30 px-2.5 py-1.5">
|
|
<div className="text-xs text-muted-foreground">Failed</div>
|
|
<div
|
|
className={cn(
|
|
"font-mono text-sm font-semibold",
|
|
(failedCount ?? 0) > 0 ? "text-destructive" : "text-foreground",
|
|
)}
|
|
>
|
|
{failedCount ?? 0}
|
|
</div>
|
|
</div>
|
|
<div className="rounded-sm border border-border bg-muted/30 px-2.5 py-1.5">
|
|
<div className="text-xs text-muted-foreground">Skipped</div>
|
|
<div className="font-mono text-sm font-semibold text-muted-foreground">
|
|
{skippedCount ?? 0}
|
|
</div>
|
|
</div>
|
|
<div className="rounded-sm border border-border bg-muted/30 px-2.5 py-1.5">
|
|
<div className="text-xs text-muted-foreground">Total</div>
|
|
<div className="font-mono text-sm font-semibold text-foreground">
|
|
{computedTotal ?? 0}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
|
|
{summary ? <p className="text-xs text-muted-foreground">{summary}</p> : null}
|
|
|
|
{failures.length > 0 ? (
|
|
<div className="space-y-1.5 rounded-sm border border-destructive/30 bg-destructive/5 p-2">
|
|
<div className="text-xs font-medium text-destructive">
|
|
Failing tests ({failures.length})
|
|
</div>
|
|
<ul className="space-y-1">
|
|
{failures.map((failure, idx) => (
|
|
<li key={`${failure.name}:${idx}`} className="text-xs">
|
|
<div className="font-mono font-medium text-foreground">{failure.name}</div>
|
|
{failure.message ? (
|
|
<div className="font-mono text-muted-foreground">{failure.message}</div>
|
|
) : null}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function GitCommitCardBody({ data }: { data: Record<string, unknown> }) {
|
|
const sha = asNonEmptyString(data.sha) ?? "unknown";
|
|
const shortSha = sha.length > 8 ? sha.slice(0, 7) : sha;
|
|
const branch = asNonEmptyString(data.branch);
|
|
const repo = asNonEmptyString(data.repo);
|
|
const rawMessage = asNonEmptyString(data.message) ?? asNonEmptyString(data.subject);
|
|
const [subject, ...restLines] = rawMessage ? rawMessage.split(/\r?\n/) : [];
|
|
const bodyText = restLines.join("\n").trim();
|
|
const filesChanged = asFiniteNumber(data.filesChanged) ?? asFiniteNumber(data.files);
|
|
const insertions = asFiniteNumber(data.insertions) ?? asFiniteNumber(data.additions);
|
|
const deletions = asFiniteNumber(data.deletions);
|
|
|
|
return (
|
|
<div className="space-y-2 p-3">
|
|
<div className="flex flex-wrap items-center gap-1.5">
|
|
<span
|
|
className="inline-flex items-center gap-1 rounded-sm border border-border bg-muted/50 px-1.5 py-0.5 font-mono text-xs font-medium text-foreground"
|
|
title={sha}
|
|
>
|
|
<GitCommitHorizontal className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
|
{shortSha}
|
|
</span>
|
|
{branch ? (
|
|
<Badge variant="outline" className="gap-1 font-mono text-xs font-normal">
|
|
<GitBranch className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />
|
|
{branch}
|
|
</Badge>
|
|
) : null}
|
|
{repo ? (
|
|
<span className="font-mono text-xs text-muted-foreground">{repo}</span>
|
|
) : null}
|
|
</div>
|
|
|
|
{subject ? <div className="text-sm font-medium text-foreground">{subject}</div> : null}
|
|
{bodyText ? (
|
|
<pre className="whitespace-pre-wrap font-mono text-xs text-muted-foreground">{bodyText}</pre>
|
|
) : null}
|
|
|
|
{filesChanged !== null || insertions !== null || deletions !== null ? (
|
|
<div className="flex flex-wrap items-center gap-2 font-mono text-xs text-muted-foreground">
|
|
{filesChanged !== null ? (
|
|
<span>
|
|
{filesChanged} {filesChanged === 1 ? "file" : "files"} changed
|
|
</span>
|
|
) : null}
|
|
{insertions !== null ? (
|
|
<span className="text-(--diff-add-fg)">+{insertions}</span>
|
|
) : null}
|
|
{deletions !== null ? (
|
|
<span className="text-(--diff-remove-fg)">-{deletions}</span>
|
|
) : null}
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function pullRequestStateStyle(state: string) {
|
|
switch (state) {
|
|
case "merged":
|
|
return {
|
|
badgeClass: "status-chip",
|
|
statusVar: "--status-task-in_review" as string | null,
|
|
Icon: GitMerge,
|
|
};
|
|
case "open":
|
|
return {
|
|
badgeClass: "status-chip",
|
|
statusVar: "--status-task-done" as string | null,
|
|
Icon: GitPullRequest,
|
|
};
|
|
case "closed":
|
|
return {
|
|
badgeClass: "border-destructive/40 bg-destructive/15 text-destructive",
|
|
statusVar: null as string | null,
|
|
Icon: GitPullRequest,
|
|
};
|
|
default:
|
|
return {
|
|
badgeClass: "border-border bg-muted text-muted-foreground",
|
|
statusVar: null as string | null,
|
|
Icon: GitPullRequest,
|
|
};
|
|
}
|
|
}
|
|
|
|
function PullRequestCardBody({ data }: { data: Record<string, unknown> }) {
|
|
const number = asFiniteNumber(data.number);
|
|
const state = (asNonEmptyString(data.state) ?? "open").toLowerCase();
|
|
const { badgeClass, statusVar, Icon: StateIcon } = pullRequestStateStyle(state);
|
|
const title = asNonEmptyString(data.title);
|
|
const repo = asNonEmptyString(data.repo);
|
|
const head = asNonEmptyString(data.head) ?? asNonEmptyString(data.branch);
|
|
const base = asNonEmptyString(data.base) ?? asNonEmptyString(data.baseBranch);
|
|
const safeUrl = safeHttpsUrl(data.url);
|
|
const rawUrl = asNonEmptyString(data.url);
|
|
|
|
return (
|
|
<div className="space-y-2 p-3">
|
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
|
<div className="flex flex-wrap items-center gap-1.5">
|
|
<Badge
|
|
variant="outline"
|
|
className={cn("gap-1 font-mono text-xs capitalize", badgeClass)}
|
|
style={statusVar ? scStyle(statusVar) : undefined}
|
|
>
|
|
<StateIcon className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
{number !== null ? `#${number} · ${state}` : state}
|
|
</Badge>
|
|
{repo ? <span className="font-mono text-xs text-muted-foreground">{repo}</span> : null}
|
|
{head ? (
|
|
<span className="inline-flex items-center gap-1 rounded-sm border border-border bg-muted/40 px-1.5 py-0.5 font-mono text-xs text-muted-foreground">
|
|
<GitBranch className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
{base ? `${head} -> ${base}` : head}
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
{safeUrl ? (
|
|
<a
|
|
href={safeUrl}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="inline-flex items-center gap-1 font-mono text-xs text-primary hover:underline"
|
|
>
|
|
Open PR
|
|
<ExternalLink className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
</a>
|
|
) : null}
|
|
</div>
|
|
|
|
{title ? <div className="text-sm font-medium text-foreground">{title}</div> : null}
|
|
|
|
{safeUrl ? (
|
|
<a
|
|
href={safeUrl}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="block truncate font-mono text-xs text-muted-foreground hover:text-foreground hover:underline"
|
|
>
|
|
{safeUrl}
|
|
</a>
|
|
) : rawUrl ? (
|
|
<span className="block truncate font-mono text-xs text-muted-foreground">{rawUrl}</span>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function CustomValueView({ value, depth = 0 }: { value: unknown; depth?: number }) {
|
|
if (value === null || value === undefined) {
|
|
return <span className="font-mono text-xs text-muted-foreground">null</span>;
|
|
}
|
|
if (typeof value === "boolean") {
|
|
return (
|
|
<Badge variant="outline" className="font-mono text-xs font-normal">
|
|
{value ? "true" : "false"}
|
|
</Badge>
|
|
);
|
|
}
|
|
if (typeof value === "number") {
|
|
return <span className="font-mono text-xs text-foreground">{String(value)}</span>;
|
|
}
|
|
if (typeof value === "string") {
|
|
const safeUrl = safeHttpsUrl(value);
|
|
if (safeUrl) {
|
|
return (
|
|
<a
|
|
href={safeUrl}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="inline-flex max-w-full items-center gap-1 truncate font-mono text-xs text-primary hover:underline"
|
|
>
|
|
<span className="truncate">{safeUrl}</span>
|
|
<ExternalLink className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
</a>
|
|
);
|
|
}
|
|
const looksMachine =
|
|
value.length <= 64 &&
|
|
(/^[0-9a-f]{7,64}$/i.test(value) ||
|
|
/^\d{4}-\d{2}-\d{2}T/.test(value) ||
|
|
/^[a-z0-9_./:@-]+$/i.test(value));
|
|
return (
|
|
<span className={cn("break-words text-xs text-foreground", looksMachine && "font-mono")}>
|
|
{value}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
if (depth >= 3) {
|
|
let serialized = "[Complex value]";
|
|
try {
|
|
serialized = JSON.stringify(value);
|
|
} catch {
|
|
// Fall back to static label on non-serializable values.
|
|
}
|
|
return (
|
|
<code className="block overflow-x-auto rounded-sm bg-muted/40 px-1.5 py-1 font-mono text-xs text-muted-foreground">
|
|
{serialized}
|
|
</code>
|
|
);
|
|
}
|
|
|
|
if (Array.isArray(value)) {
|
|
if (value.length === 0) {
|
|
return <span className="font-mono text-xs text-muted-foreground">[]</span>;
|
|
}
|
|
const allPrimitives = value.every(
|
|
(item) =>
|
|
item === null ||
|
|
typeof item === "string" ||
|
|
typeof item === "number" ||
|
|
typeof item === "boolean",
|
|
);
|
|
if (allPrimitives) {
|
|
return (
|
|
<div className="flex flex-wrap gap-1">
|
|
{value.map((item, idx) => (
|
|
<span
|
|
key={idx}
|
|
className="rounded-sm border border-border bg-muted/40 px-1.5 py-0.5 font-mono text-xs text-foreground"
|
|
>
|
|
{String(item)}
|
|
</span>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
return (
|
|
<div className="space-y-1.5">
|
|
{value.map((item, idx) => (
|
|
<div key={idx} className="rounded-sm border border-border bg-muted/20 p-2">
|
|
<CustomValueView value={item} depth={depth + 1} />
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (isPlainRecord(value)) {
|
|
const entries = Object.entries(value).filter(([, entry]) => entry !== undefined);
|
|
if (entries.length === 0) {
|
|
return <span className="font-mono text-xs text-muted-foreground">{"{}"}</span>;
|
|
}
|
|
return (
|
|
<dl
|
|
className={cn(
|
|
"divide-y divide-border/60",
|
|
depth > 0 && "rounded-sm border border-border/60 bg-muted/20 px-2.5 py-1",
|
|
)}
|
|
>
|
|
{entries.map(([key, entryValue]) => (
|
|
<div
|
|
key={key}
|
|
className="grid grid-cols-1 gap-1 py-1.5 sm:grid-cols-3 sm:items-start sm:gap-3"
|
|
>
|
|
<dt className="truncate font-mono text-xs text-muted-foreground" title={key}>
|
|
{key}
|
|
</dt>
|
|
<dd className="min-w-0 sm:col-span-2">
|
|
<CustomValueView value={entryValue} depth={depth + 1} />
|
|
</dd>
|
|
</div>
|
|
))}
|
|
</dl>
|
|
);
|
|
}
|
|
|
|
return <span className="font-mono text-xs text-muted-foreground">{String(value)}</span>;
|
|
}
|
|
|
|
function renderSchemaBody(block: SchemaBlock) {
|
|
const ref = `${block.schema.toLowerCase()}@${block.version}`;
|
|
switch (ref) {
|
|
case "finding@1":
|
|
return <FindingCardBody data={block.data} />;
|
|
case "test-report@1":
|
|
return <TestReportCardBody data={block.data} />;
|
|
case "git-commit@1":
|
|
return <GitCommitCardBody data={block.data} />;
|
|
case "pull-request@1":
|
|
return <PullRequestCardBody data={block.data} />;
|
|
default:
|
|
return (
|
|
<div className="px-3 py-2">
|
|
<CustomValueView value={block.data} />
|
|
</div>
|
|
);
|
|
}
|
|
}
|
|
|
|
export interface SchemaBlockCardProps {
|
|
block: SchemaBlock;
|
|
rawJson?: string;
|
|
defaultView?: "structured" | "json";
|
|
className?: string;
|
|
}
|
|
|
|
export const SchemaBlockCard = memo(function SchemaBlockCard({
|
|
block,
|
|
rawJson,
|
|
defaultView = "structured",
|
|
className,
|
|
}: SchemaBlockCardProps) {
|
|
const [viewMode, setViewMode] = useState<"structured" | "json">(defaultView);
|
|
const [copied, setCopied] = useState(false);
|
|
const copyTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
|
|
|
|
useEffect(() => () => clearTimeout(copyTimerRef.current), []);
|
|
|
|
const schemaRefLabel = `${block.schema}@${block.version}`;
|
|
const formattedJson = useMemo(
|
|
() => rawJson ?? JSON.stringify(block.data, null, 2),
|
|
[block.data, rawJson],
|
|
);
|
|
|
|
const handleCopyJson = useCallback(async () => {
|
|
try {
|
|
await copyTextToClipboard(formattedJson);
|
|
setCopied(true);
|
|
clearTimeout(copyTimerRef.current);
|
|
copyTimerRef.current = setTimeout(() => setCopied(false), 1500);
|
|
} catch {
|
|
// Ignore clipboard failures in restricted contexts.
|
|
}
|
|
}, [formattedJson]);
|
|
|
|
return (
|
|
<div
|
|
data-testid="schema-block-card"
|
|
data-schema-ref={schemaRefLabel}
|
|
className={cn(
|
|
"not-prose my-2 overflow-hidden rounded-md border border-border bg-card text-card-foreground",
|
|
className,
|
|
)}
|
|
>
|
|
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/40 px-3 py-1.5">
|
|
<div className="flex min-w-0 items-center gap-1.5">
|
|
<Braces className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
|
<span className="truncate font-mono text-xs font-medium text-foreground">
|
|
{schemaRefLabel}
|
|
</span>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-1">
|
|
<div
|
|
role="group"
|
|
aria-label={`View mode for ${schemaRefLabel}`}
|
|
className="inline-flex items-center rounded-sm border border-border bg-background p-0.5"
|
|
>
|
|
<button
|
|
type="button"
|
|
aria-pressed={viewMode === "structured"}
|
|
onClick={() => setViewMode("structured")}
|
|
className={cn(
|
|
"rounded-sm px-2 py-0.5 text-xs font-medium transition-colors",
|
|
viewMode === "structured"
|
|
? "bg-accent text-accent-foreground"
|
|
: "text-muted-foreground hover:text-foreground",
|
|
)}
|
|
>
|
|
Structured
|
|
</button>
|
|
<button
|
|
type="button"
|
|
aria-pressed={viewMode === "json"}
|
|
onClick={() => setViewMode("json")}
|
|
className={cn(
|
|
"rounded-sm px-2 py-0.5 font-mono text-xs transition-colors",
|
|
viewMode === "json"
|
|
? "bg-accent text-accent-foreground"
|
|
: "text-muted-foreground hover:text-foreground",
|
|
)}
|
|
>
|
|
JSON
|
|
</button>
|
|
</div>
|
|
{viewMode === "json" ? (
|
|
<button
|
|
type="button"
|
|
onClick={() => void handleCopyJson()}
|
|
aria-label={`Copy ${schemaRefLabel} JSON`}
|
|
title={copied ? "Copied" : "Copy JSON"}
|
|
className="inline-flex items-center gap-1 rounded-sm border border-border bg-background px-1.5 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
|
|
>
|
|
{copied ? (
|
|
<Check className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
) : (
|
|
<Copy className="h-3 w-3 shrink-0" aria-hidden="true" />
|
|
)}
|
|
</button>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
|
|
{viewMode === "json" ? (
|
|
<pre className="max-h-80 overflow-auto bg-muted/20 p-3 font-mono text-xs text-foreground">
|
|
<code>{formattedJson}</code>
|
|
</pre>
|
|
) : (
|
|
renderSchemaBody(block)
|
|
)}
|
|
</div>
|
|
);
|
|
});
|
|
|
|
export const StandaloneSchemaBlockList = memo(function StandaloneSchemaBlockList({
|
|
markdown,
|
|
schemaBlocks,
|
|
className,
|
|
}: {
|
|
markdown?: string | null;
|
|
schemaBlocks?: readonly SchemaBlock[] | null;
|
|
className?: string;
|
|
}) {
|
|
const unfenced = useMemo(
|
|
() => getUnfencedSchemaBlocks(markdown, schemaBlocks),
|
|
[markdown, schemaBlocks],
|
|
);
|
|
if (unfenced.length === 0) return null;
|
|
|
|
return (
|
|
<div className={cn("space-y-2", className)} data-testid="standalone-schema-blocks">
|
|
{unfenced.map((block, idx) => (
|
|
<SchemaBlockCard key={`${block.schema}@${block.version}:${idx}`} block={block} />
|
|
))}
|
|
</div>
|
|
);
|
|
});
|