feat(ui): surface channel, key-values, lease, and schema elements on tasks (#23382)

## 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-01 17:57:33 +00:00
1 parent 51541be36f
commit ce2e6ccc00
29 files changed
+4498 -63

No files matched your search

+45
View File
@@ -350,3 +350,48 @@ describe("interaction resolution replay", () => {
expect(mockApi.get).not.toHaveBeenCalled();
});
});
describe("issuesApi.updateKvLabels", () => {
beforeEach(() => {
mockApi.patch.mockReset();
mockApi.patch.mockResolvedValue({
id: "issue-1",
kvLabels: { role: "reviewer" },
cursor: "cur-1",
});
});
it("encodes the issue id and normalizes delete -> unset and ifMatch -> if", async () => {
const result = await issuesApi.updateKvLabels("PAP-412/special?id", {
set: { role: "reviewer" },
delete: ["env"],
ifMatch: { role: "worker", env: "staging" },
});
expect(mockApi.patch).toHaveBeenCalledWith(
"/issues/PAP-412%2Fspecial%3Fid/kv-labels",
{
set: { role: "reviewer" },
unset: ["env"],
if: { role: "worker", env: "staging" },
},
);
expect(result).toEqual({
id: "issue-1",
kvLabels: { role: "reviewer" },
cursor: "cur-1",
});
});
it("forwards canonical unset and if fields directly when provided", async () => {
await issuesApi.updateKvLabels("issue-1", {
unset: ["step"],
if: { step: "fix" },
});
expect(mockApi.patch).toHaveBeenCalledWith("/issues/issue-1/kv-labels", {
unset: ["step"],
if: { step: "fix" },
});
});
});
+25
View File
@@ -828,6 +828,31 @@ export const issuesApi = {
api.post<IssueAccessGrant>(`/issues/${id}/access-grants/${grantId}/revoke`, {}),
setVisibility: (id: string, visibility: IssueVisibility) =>
api.patch<IssueUpdateResponse>(`/issues/${id}`, { visibility }),
updateKvLabels: (
id: string,
payload: {
set?: Record<string, string>;
delete?: string[];
unset?: string[];
ifMatch?: Record<string, string | null>;
if?: Record<string, string | null>;
},
) => {
const body: {
set?: Record<string, string>;
unset?: string[];
if?: Record<string, string | null>;
} = {};
if (payload.set !== undefined) body.set = payload.set;
const unset = payload.unset ?? payload.delete;
if (unset !== undefined) body.unset = unset;
const cas = payload.if ?? payload.ifMatch;
if (cas !== undefined) body.if = cas;
return api.patch<{ id: string; kvLabels: Record<string, string>; cursor: string }>(
`/issues/${encodeURIComponent(id)}/kv-labels`,
body,
);
},
listApprovals: (id: string) => api.get<Approval[]>(`/issues/${id}/approvals`),
linkApproval: (id: string, approvalId: string) =>
api.post<Approval[]>(`/issues/${id}/approvals`, { approvalId }),
+134
View File
@@ -0,0 +1,134 @@
import { memo, useMemo } from "react";
import { Terminal } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import type { CompanyUserProfile } from "../lib/company-members";
import { cn } from "../lib/utils";
function initialsForProfile(profile: string): string {
const parts = profile.trim().split(/[\s_-]+/).filter(Boolean);
if (parts.length >= 2) {
return `${parts[0]![0] ?? ""}${parts[parts.length - 1]![0] ?? ""}`.toUpperCase();
}
return profile.trim().slice(0, 2).toUpperCase() || "PR";
}
export interface ResolvedActorProfileAttribution {
profile: string;
viaUserLabel: string | null;
isEphemeralProfile: boolean;
}
/**
* Resolves `--as <profile>` comment attribution so profile-attributed comments
* render `<actorProfile> via <user>` (delegated human session) or
* `<actorProfile>` + `profile` pill (`local-board` / unauthenticated local mode)
* instead of `local-board`, `You`, or `User`.
*/
export function resolveActorProfileAttribution(input: {
actorProfile?: string | null;
authorUserId?: string | null;
userLabelMap?: ReadonlyMap<string, string> | null;
userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
}): ResolvedActorProfileAttribution | null {
const profile = input.actorProfile?.trim();
if (!profile) return null;
const rawUserId = input.authorUserId?.trim() || null;
if (!rawUserId || rawUserId === "local-board") {
return {
profile,
viaUserLabel: null,
isEphemeralProfile: true,
};
}
const mappedProfileLabel = input.userProfileMap?.get(rawUserId)?.label?.trim();
const mappedUserLabel = input.userLabelMap?.get(rawUserId)?.trim();
const fallbackUserLabel = rawUserId.startsWith("user-")
? rawUserId.slice("user-".length)
: rawUserId;
return {
profile,
viaUserLabel: mappedProfileLabel || mappedUserLabel || fallbackUserLabel,
isEphemeralProfile: false,
};
}
export const ActorProfileIdentity = memo(function ActorProfileIdentity({
attribution,
showAvatar = true,
className,
}: {
attribution: ResolvedActorProfileAttribution;
showAvatar?: boolean;
className?: string;
}) {
return (
<span
data-testid="comment-actor-profile"
className={cn("inline-flex min-w-0 items-center gap-1.5", className)}
>
{showAvatar ? (
<Avatar size="sm" className="shrink-0">
<AvatarFallback className="font-mono text-(length:--text-nano)">
{initialsForProfile(attribution.profile)}
</AvatarFallback>
</Avatar>
) : null}
<span className="truncate font-mono text-xs font-medium text-foreground">
{attribution.profile}
</span>
{attribution.viaUserLabel ? (
<span className="shrink-0 truncate text-xs text-muted-foreground">
via {attribution.viaUserLabel}
</span>
) : (
<Badge
variant="outline"
className="gap-1 px-1.5 py-0 font-mono text-(length:--text-nano) font-normal text-muted-foreground"
>
<Terminal className="h-2.5 w-2.5 shrink-0" aria-hidden="true" />
profile
</Badge>
)}
</span>
);
});
export const CommentKvLabelsBar = memo(function CommentKvLabelsBar({
kvLabels,
className,
}: {
kvLabels?: Record<string, string> | null;
className?: string;
}) {
const entries = useMemo(() => {
if (!kvLabels) return [];
return Object.entries(kvLabels).filter(
([key, value]) => typeof key === "string" && key.length > 0 && typeof value === "string",
);
}, [kvLabels]);
if (entries.length === 0) return null;
return (
<div
data-testid="comment-kv-labels"
className={cn("mt-2 flex flex-wrap items-center gap-1.5", className)}
>
{entries.map(([key, value]) => (
<span
key={key}
className="inline-flex max-w-full flex-wrap items-baseline gap-0.5 rounded-sm border border-border bg-muted/40 px-1.5 py-0.5 font-mono text-xs"
title={`${key}=${value}`}
>
<span className="break-all text-muted-foreground">{key}</span>
<span className="text-muted-foreground/70">=</span>
<span className="break-all font-medium text-foreground">{value}</span>
</span>
))}
</div>
);
});
+37 -2
View File
@@ -21,6 +21,12 @@ import { MarkdownBody, type MarkdownExternalReferenceMap } from "./MarkdownBody"
import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "./MarkdownEditor";
import { OutputFeedbackButtons } from "./OutputFeedbackButtons";
import { ApprovalCard } from "./ApprovalCard";
import {
ActorProfileIdentity,
CommentKvLabelsBar,
resolveActorProfileAttribution,
} from "./CommentStructuredMeta";
import { StandaloneSchemaBlockList } from "./SchemaBlockCard";
import { formatAssigneeUserLabel } from "../lib/assignees";
import { formatTimelineWorkspaceLabel, type IssueTimelineAssignee, type IssueTimelineEvent } from "../lib/issue-timeline-events";
import { timeAgo } from "../lib/timeAgo";
@@ -95,6 +101,7 @@ interface CommentThreadProps {
onAdd: (body: string, reopen?: boolean, reassignment?: CommentReassignment) => Promise<void>;
issueStatus?: string;
agentMap?: Map<string, Agent>;
userLabelMap?: ReadonlyMap<string, string> | null;
currentUserId?: string | null;
imageUploadHandler?: (file: File) => Promise<string>;
/** Callback to attach an image file to the parent issue (not inline in a comment). */
@@ -299,6 +306,8 @@ function CopyMarkdownButton({ text }: { text: string }) {
function CommentCard({
comment,
agentMap,
userLabelMap,
currentUserId,
companyId,
projectId,
feedbackVote = null,
@@ -312,6 +321,8 @@ function CommentCard({
}: {
comment: CommentWithRunMeta;
agentMap?: Map<string, Agent>;
userLabelMap?: ReadonlyMap<string, string> | null;
currentUserId?: string | null;
companyId?: string | null;
projectId?: string | null;
feedbackVote?: FeedbackVoteValue | null;
@@ -331,6 +342,16 @@ function CommentCard({
const isQueued = queued || comment.queueState === "queued" || comment.clientStatus === "queued";
const isDeleted = Boolean(comment.deletedAt);
const followUpRequested = comment.followUpRequested === true;
const profileAttribution = !comment.authorAgentId
? resolveActorProfileAttribution({
actorProfile: comment.actorProfile,
authorUserId: comment.authorUserId,
userLabelMap,
})
: null;
const humanLabel = !comment.authorAgentId && !profileAttribution
? formatAssigneeUserLabel(comment.authorUserId, currentUserId, userLabelMap) ?? "You"
: "You";
return (
<div
@@ -352,8 +373,10 @@ function CommentCard({
size="sm"
/>
</Link>
) : profileAttribution ? (
<ActorProfileIdentity attribution={profileAttribution} />
) : (
<Identity name="You" size="sm" />
<Identity name={humanLabel} size="sm" />
)}
<span className="flex items-center gap-1.5">
{isQueued ? (
@@ -398,7 +421,11 @@ function CommentCard({
{isDeleted ? (
<div className="text-sm italic text-muted-foreground">Comment deleted</div>
) : (
<MarkdownBody className="text-sm" softBreaks externalReferences={externalReferences}>{comment.body}</MarkdownBody>
<>
<MarkdownBody className="text-sm" softBreaks externalReferences={externalReferences}>{comment.body}</MarkdownBody>
<StandaloneSchemaBlockList markdown={comment.body} schemaBlocks={comment.schemaBlocks} />
<CommentKvLabelsBar kvLabels={comment.kvLabels} />
</>
)}
{companyId && !isPending && !isDeleted ? (
<div className="mt-2 space-y-2">
@@ -549,6 +576,7 @@ function TimelineEventCard({
const TimelineList = memo(function TimelineList({
timeline,
agentMap,
userLabelMap,
currentUserId,
companyId,
projectId,
@@ -565,6 +593,7 @@ const TimelineList = memo(function TimelineList({
}: {
timeline: TimelineItem[];
agentMap?: Map<string, Agent>;
userLabelMap?: ReadonlyMap<string, string> | null;
currentUserId?: string | null;
companyId?: string | null;
projectId?: string | null;
@@ -701,6 +730,8 @@ const TimelineList = memo(function TimelineList({
key={comment.id}
comment={comment}
agentMap={agentMap}
userLabelMap={userLabelMap}
currentUserId={currentUserId}
companyId={companyId}
projectId={projectId}
feedbackVote={feedbackVoteByTargetId?.get(comment.id) ?? null}
@@ -735,6 +766,7 @@ export function CommentThread({
onAdd,
issueStatus,
agentMap,
userLabelMap,
currentUserId,
imageUploadHandler,
onAttachImage,
@@ -968,6 +1000,7 @@ export function CommentThread({
<TimelineList
timeline={timeline}
agentMap={agentMap}
userLabelMap={userLabelMap}
currentUserId={currentUserId}
companyId={companyId}
projectId={projectId}
@@ -1009,6 +1042,8 @@ export function CommentThread({
key={comment.id}
comment={comment}
agentMap={agentMap}
userLabelMap={userLabelMap}
currentUserId={currentUserId}
companyId={companyId}
projectId={projectId}
highlightCommentId={highlightCommentId}
+48 -3
View File
@@ -279,6 +279,13 @@ import {
} from "./IssueRecoveryActionCard";
import { SourceTrustBadge } from "./SourceTrustBadge";
import { CommentAttributionChip } from "./CommentAttributionChip";
import {
ActorProfileIdentity,
CommentKvLabelsBar,
resolveActorProfileAttribution,
} from "./CommentStructuredMeta";
import { StandaloneSchemaBlockList } from "./SchemaBlockCard";
import type { SchemaBlock } from "@paperclipai/shared";
import { resolveCommentAttribution } from "../lib/comment-attribution";
import { safeExternalHttpUrl } from "../lib/safe-url";
@@ -2070,6 +2077,7 @@ function IssueChatUserMessage({
onCancelQueued,
onDeleteComment,
currentUserId,
userLabelMap,
userProfileMap,
} = useContext(IssueChatCtx);
const custom = message.metadata.custom as Record<string, unknown>;
@@ -2081,6 +2089,15 @@ function IssueChatUserMessage({
typeof custom.authorName === "string" ? custom.authorName : null;
const authorUserId =
typeof custom.authorUserId === "string" ? custom.authorUserId : null;
const actorProfile =
typeof custom.actorProfile === "string" ? custom.actorProfile : null;
const commentKvLabels =
custom.kvLabels && typeof custom.kvLabels === "object" && !Array.isArray(custom.kvLabels)
? (custom.kvLabels as Record<string, string>)
: null;
const commentSchemaBlocks = Array.isArray(custom.schemaBlocks)
? (custom.schemaBlocks as SchemaBlock[])
: null;
const queued =
custom.queueState === "queued" || custom.clientStatus === "queued";
const sourceTrust = isSourceTrustMetadata(custom.sourceTrust)
@@ -2109,9 +2126,16 @@ function IssueChatUserMessage({
} = resolveIssueChatHumanAuthor({
authorName,
authorUserId,
actorProfile,
currentUserId,
userProfileMap,
});
const profileAttribution = resolveActorProfileAttribution({
actorProfile,
authorUserId,
userLabelMap,
userProfileMap,
});
const authorAvatar = (
<Avatar size="sm" className="shrink-0">
{avatarUrl ? (
@@ -2145,9 +2169,13 @@ function IssueChatUserMessage({
isCurrentUser ? "justify-end" : "justify-start",
)}
>
<span className="text-sm font-medium text-foreground">
{resolvedAuthorName}
</span>
{profileAttribution ? (
<ActorProfileIdentity attribution={profileAttribution} showAvatar={false} />
) : (
<span className="text-sm font-medium text-foreground">
{resolvedAuthorName}
</span>
)}
<SourceTrustBadge sourceTrust={sourceTrust} artifactLabel="comment" />
{followUpRequested ? (
<Badge
@@ -2217,6 +2245,11 @@ function IssueChatUserMessage({
message={message}
onAccent={isCurrentUser && !queued}
/>
<StandaloneSchemaBlockList
markdown={getThreadMessageCopyText(message)}
schemaBlocks={commentSchemaBlocks}
/>
<CommentKvLabelsBar kvLabels={commentKvLabels} />
</div>
)}
</div>
@@ -2400,6 +2433,13 @@ function IssueChatAssistantMessage({
const agentIcon = agentId ? agentMap?.get(agentId)?.icon : undefined;
const commentId =
typeof custom.commentId === "string" ? custom.commentId : null;
const commentKvLabels =
custom.kvLabels && typeof custom.kvLabels === "object" && !Array.isArray(custom.kvLabels)
? (custom.kvLabels as Record<string, string>)
: null;
const commentSchemaBlocks = Array.isArray(custom.schemaBlocks)
? (custom.schemaBlocks as SchemaBlock[])
: null;
const sourceTrust = isSourceTrustMetadata(custom.sourceTrust)
? custom.sourceTrust
: null;
@@ -2669,6 +2709,11 @@ function IssueChatAssistantMessage({
) : (
<div className="min-w-0 max-w-full space-y-3">
<IssueChatAssistantParts message={message} hasCoT={false} />
<StandaloneSchemaBlockList
markdown={copyText}
schemaBlocks={commentSchemaBlocks}
/>
<CommentKvLabelsBar kvLabels={commentKvLabels} />
{notices.length > 0 ? (
<div className="space-y-2">
{notices.map((notice, index) => (
+66 -1
View File
@@ -1,4 +1,10 @@
import { PatchLines } from "./PatchLines";
import {
parseJsonSchemaBlock,
parseSchemaFenceMeta,
SchemaBlockCard,
type ParsedFencedSchemaBlock,
} from "./SchemaBlockCard";
import { MarkdownWordStreaming, rehypeStreamingWords } from "./MarkdownWordStreaming";
import { isValidElement, memo, useContext, useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
@@ -423,6 +429,9 @@ function flattenText(value: ReactNode): string {
if (value == null) return "";
if (typeof value === "string" || typeof value === "number") return String(value);
if (Array.isArray(value)) return value.map((item) => flattenText(item)).join("");
if (isValidElement<{ children?: ReactNode }>(value)) {
return flattenText(value.props.children);
}
return "";
}
@@ -434,6 +443,52 @@ function extractMermaidSource(children: ReactNode): string | null {
return flattenText(childProps.children).replace(/\n$/, "");
}
function extractSchemaBlockSource(children: ReactNode): ParsedFencedSchemaBlock | null {
const code = Array.isArray(children) ? children.find(isValidElement) : children;
if (!isValidElement(code)) return null;
const childProps = code.props as {
className?: unknown;
children?: ReactNode;
"data-paperclip-schema-ref"?: unknown;
};
if (typeof childProps.className !== "string") return null;
if (!/\blanguage-json\b/i.test(childProps.className)) return null;
const explicitRef =
typeof childProps["data-paperclip-schema-ref"] === "string"
? childProps["data-paperclip-schema-ref"]
: null;
const rawCode = flattenText(childProps.children).replace(/\n$/, "");
return parseJsonSchemaBlock(rawCode, explicitRef);
}
function remarkSchemaCodeBlocks() {
return (tree: MarkdownAstNode) => {
const visit = (node: MarkdownAstNode) => {
if (
node.type === "code" &&
typeof node.lang === "string" &&
node.lang.toLowerCase() === "json"
) {
const parsedMeta = parseSchemaFenceMeta(node.meta);
if (parsedMeta) {
node.data = {
...node.data,
hProperties: {
...node.data?.hProperties,
"data-paperclip-schema-ref": parsedMeta.ref,
},
};
}
}
if (!node.children) return;
for (const child of node.children) {
visit(child);
}
};
visit(tree);
};
}
function safeMarkdownUrlTransform(url: string): string {
if (url.startsWith(WORKSPACE_FILE_HREF_PREFIX)) return url;
const mention = parseMentionChipHref(url);
@@ -445,6 +500,8 @@ function safeMarkdownUrlTransform(url: string): string {
type MarkdownAstNode = {
type?: string;
value?: string;
lang?: string | null;
meta?: string | null;
children?: MarkdownAstNode[];
url?: string;
title?: string | null;
@@ -824,7 +881,11 @@ function MarkdownBodyImpl({
// parent re-renders frequently (see PAP-10767). Memoize both so re-renders
// that don't change the inputs are cheap and non-destructive.
const remarkPlugins = useMemo<NonNullable<Options["remarkPlugins"]>>(() => {
const plugins: NonNullable<Options["remarkPlugins"]> = [remarkGfm, remarkDropHtmlComments];
const plugins: NonNullable<Options["remarkPlugins"]> = [
remarkGfm,
remarkDropHtmlComments,
remarkSchemaCodeBlocks,
];
if (enableWikiLinks) {
plugins.push(createRemarkWikiLinks({ wikiLinkRoot, resolveWikiLinkHref }));
}
@@ -886,6 +947,10 @@ function MarkdownBodyImpl({
if (mermaidSource && mediaMode === "render") {
return <MermaidDiagramBlock source={mermaidSource} darkMode={theme === "dark"} />;
}
const schemaBlock = mediaMode === "render" ? extractSchemaBlockSource(preChildren) : null;
if (schemaBlock) {
return <SchemaBlockCard block={schemaBlock.block} rawJson={schemaBlock.rawJson} />;
}
return <CodeBlock preProps={preProps}>{preChildren}</CodeBlock>;
},
code: ({ node: _node, style: codeStyle, children: codeChildren, ...codeProps }) => (
+339
View File
@@ -0,0 +1,339 @@
// @vitest-environment jsdom
import { act as reactAct, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ThemeProvider } from "../context/ThemeContext";
import { TooltipProvider } from "./ui/tooltip";
import {
ActorProfileIdentity,
CommentKvLabelsBar,
resolveActorProfileAttribution,
} from "./CommentStructuredMeta";
import { MarkdownBody } from "./MarkdownBody";
import {
extractFencedSchemaBlocks,
getUnfencedSchemaBlocks,
hasMatchingSchemaBlock,
SchemaBlockCard,
StandaloneSchemaBlockList,
} from "./SchemaBlockCard";
import { resolveIssueChatHumanAuthor } from "../lib/issue-chat-human-author";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("@/lib/router", () => ({
Link: ({ to, children, className }: { to: string; children: ReactNode; className?: string }) => (
<a href={to} className={className}>{children}</a>
),
useCaseHref: () => () => "#",
}));
let container: HTMLDivElement | null = null;
let root: Root | null = null;
async function act(callback: () => void | Promise<void>) {
if (typeof reactAct === "function") {
await reactAct(callback);
return;
}
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
await new Promise((resolve) => setTimeout(resolve, 0));
}
async function renderNode(node: ReactNode) {
const queryClient = new QueryClient();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
await act(() => {
root!.render(
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<TooltipProvider>{node}</TooltipProvider>
</ThemeProvider>
</QueryClientProvider>,
);
});
return container;
}
afterEach(async () => {
if (root) {
await act(() => {
root?.unmount();
});
root = null;
}
container?.remove();
container = null;
});
describe("SchemaBlockCard and MarkdownBody schema fences", () => {
it("renders built-in finding@1, test-report@1, git-commit@1, pull-request@1, and custom schemas with JSON toggle", async () => {
const markdown = [
"```json schema=finding@1",
JSON.stringify({
severity: "critical",
title: "Missing CSRF check on token endpoint",
path: "server/src/routes/auth.ts",
line: 88,
recommendation: "Require Origin validation before issuing session cookie.",
}),
"```",
"",
"```json schema=test-report@1",
JSON.stringify({
passed: false,
total: 10,
failed: 1,
skipped: 1,
durationMs: 1450,
failures: [{ name: "rejects cross-origin POST", message: "Expected 403, got 200" }],
}),
"```",
"",
"```json schema=git-commit@1",
JSON.stringify({
sha: "abcdef1234567890",
branch: "fix/csrf",
message: "fix(auth): enforce csrf check",
filesChanged: 2,
insertions: 18,
deletions: 3,
}),
"```",
"",
"```json schema=pull-request@1",
JSON.stringify({
number: 901,
state: "open",
title: "Enforce CSRF origin check",
head: "fix/csrf",
base: "master",
url: "https://github.com/paperclipai/paperclip/pull/901",
}),
"```",
"",
"```json schema=deploy-receipt@2",
JSON.stringify({
environment: "staging",
healthy: true,
}),
"```",
].join("\n");
const dom = await renderNode(<MarkdownBody>{markdown}</MarkdownBody>);
const cards = dom.querySelectorAll('[data-testid="schema-block-card"]');
expect(cards).toHaveLength(5);
expect(dom.textContent).toContain("finding@1");
expect(dom.textContent).toContain("Missing CSRF check on token endpoint");
expect(dom.textContent).toContain("server/src/routes/auth.ts:88");
expect(dom.textContent).toContain("test-report@1");
expect(dom.textContent).toContain("rejects cross-origin POST");
expect(dom.textContent).toContain("git-commit@1");
expect(dom.textContent).toContain("abcdef1");
expect(dom.textContent).toContain("+18");
expect(dom.textContent).toContain("pull-request@1");
expect(dom.textContent).toContain("fix/csrf -> master");
const prLink = dom.querySelector('a[href="https://github.com/paperclipai/paperclip/pull/901"]');
expect(prLink).not.toBeNull();
expect(dom.textContent).toContain("deploy-receipt@2");
expect(dom.textContent).toContain("staging");
// Toggle first card to JSON view
const jsonToggle = cards[0]!.querySelectorAll("button")[1]!;
expect(jsonToggle.textContent).toBe("JSON");
await act(() => {
jsonToggle.click();
});
expect(cards[0]!.querySelector("pre")?.textContent).toContain(
'"title": "Missing CSRF check on token endpoint"',
);
});
it("rejects non-https URLs in pull-request@1 and falls back to code block on malformed JSON", async () => {
const markdown = [
"```json schema=finding@1",
"{ not valid json",
"```",
].join("\n");
const dom = await renderNode(
<>
<MarkdownBody>{markdown}</MarkdownBody>
<SchemaBlockCard
block={{
schema: "pull-request",
version: 1,
data: {
number: 12,
title: "Unsafe link test",
url: "javascript:alert(1)",
},
}}
/>
</>,
);
// Malformed JSON falls back to standard code block
expect(dom.querySelectorAll('[data-testid="schema-block-card"]')).toHaveLength(1);
expect(dom.querySelector(".paperclip-markdown-codeblock")?.textContent).toContain(
"{ not valid json",
);
// Unsafe URL is never rendered as an anchor href
expect(dom.querySelector('a[href^="javascript:"]')).toBeNull();
});
it("deduplicates standalone schemaBlocks already rendered in markdown fences", async () => {
const block = {
schema: "finding",
version: 1,
data: { severity: "low", title: "Minor lint note" },
};
const fencedMd = `Summary\n\n\`\`\`json schema=finding@1\n${JSON.stringify(block.data, null, 2)}\n\`\`\``;
expect(getUnfencedSchemaBlocks(fencedMd, [block])).toHaveLength(0);
expect(getUnfencedSchemaBlocks("Plain text body", [block])).toHaveLength(1);
const dom = await renderNode(
<div>
<MarkdownBody>{fencedMd}</MarkdownBody>
<StandaloneSchemaBlockList
markdown={fencedMd}
schemaBlocks={[
block,
{ schema: "deploy-receipt", version: 2, data: { env: "prod" } },
]}
/>
</div>,
);
expect(dom.querySelectorAll('[data-testid="schema-block-card"]')).toHaveLength(2);
// Ensure deeply nested objects neither blow the stack nor collide when leaf values differ
let deepNestedA: Record<string, unknown> = { leaf: "alpha" };
let deepNestedB: Record<string, unknown> = { leaf: "beta" };
for (let i = 0; i < 40; i += 1) {
deepNestedA = { child: deepNestedA };
deepNestedB = { child: deepNestedB };
}
const deepBlockA = { schema: "deep-test", version: 1, data: deepNestedA };
const deepBlockB = { schema: "deep-test", version: 1, data: deepNestedB };
const deepMd = `\`\`\`json schema=deep-test@1\n${JSON.stringify(deepNestedA)}\n\`\`\``;
expect(getUnfencedSchemaBlocks(deepMd, [deepBlockA])).toHaveLength(0);
expect(getUnfencedSchemaBlocks(deepMd, [deepBlockB])).toEqual([deepBlockB]);
});
it("scans thousands of repeated unterminated ```json lines in linear time without backtracking", () => {
const craftedUnterminated = "```json schema=finding@1\n".repeat(5_000);
const startMs = performance.now();
const blocks = extractFencedSchemaBlocks(craftedUnterminated);
const matched = hasMatchingSchemaBlock("finding@1", {
markdownBodies: [craftedUnterminated],
});
const elapsedMs = performance.now() - startMs;
expect(blocks).toEqual([]);
expect(matched).toBe(false);
expect(elapsedMs).toBeLessThan(100);
});
it("matches schema fences after >64 ordinary JSON fences and marks oversized bodies unverified instead of missing", async () => {
const { checkMatchingSchemaBlock } = await import("../lib/schema-block-utils");
const ordinaryFences = '```json\n{"plain":true}\n```\n'.repeat(80);
const trailingResult = '```json schema=test-report@1\n{"passed":true}\n```';
expect(
checkMatchingSchemaBlock("test-report@1", {
markdownBodies: [`${ordinaryFences}\n${trailingResult}`],
}),
).toBe("matched");
const hugePrefix = "x".repeat(600 * 1024);
expect(
checkMatchingSchemaBlock("test-report@1", {
markdownBodies: [`${hugePrefix}\n${trailingResult}`],
}),
).toBe("unverified");
// Ensure a 512 KiB cutoff landing right after ``` on a line with trailing text
// does not accept an incomplete line as a closing fence.
const openFenceAndJson = '```json schema=test-report@1\n{"passed":true}\n';
const padBeforeCutLine =
"p".repeat(512 * 1024 - openFenceAndJson.length - 4) + "\n";
const cutNonClosingLine = `${padBeforeCutLine}${openFenceAndJson}\`\`\`not-a-closing-fence\n`;
expect(extractFencedSchemaBlocks(cutNonClosingLine)).toEqual([]);
expect(
checkMatchingSchemaBlock("test-report@1", {
markdownBodies: [cutNonClosingLine],
}),
).toBe("unverified");
});
});
describe("Comment profile attribution and key-value chips", () => {
it("renders --as profile attribution (delegated user vs local-board) and comment kv_labels chips", async () => {
const userLabelMap = new Map([["user-julian", "julian"]]);
const delegated = resolveActorProfileAttribution({
actorProfile: "claude",
authorUserId: "user-julian",
userLabelMap,
});
const localProfile = resolveActorProfileAttribution({
actorProfile: "ci-bot",
authorUserId: "local-board",
userLabelMap,
});
expect(delegated).toEqual({
profile: "claude",
viaUserLabel: "julian",
isEphemeralProfile: false,
});
expect(localProfile).toEqual({
profile: "ci-bot",
viaUserLabel: null,
isEphemeralProfile: true,
});
// Ensure profile comments on local-board are NOT treated as the viewer's own blue bubble
expect(
resolveIssueChatHumanAuthor({
authorUserId: "local-board",
actorProfile: "ci-bot",
currentUserId: "local-board",
}),
).toEqual({
isCurrentUser: false,
authorName: "ci-bot",
avatarUrl: null,
});
const dom = await renderNode(
<div>
<ActorProfileIdentity attribution={delegated!} />
<ActorProfileIdentity attribution={localProfile!} />
<CommentKvLabelsBar kvLabels={{ status: "fixed", suite: "auth" }} />
</div>,
);
expect(dom.textContent).toContain("claude");
expect(dom.textContent).toContain("via julian");
expect(dom.textContent).toContain("ci-bot");
expect(dom.textContent).toContain("profile");
expect(dom.textContent).not.toContain("local-board");
expect(dom.querySelector('[data-testid="comment-kv-labels"]')?.textContent).toContain(
"status=fixed",
);
});
});
+750
View File
@@ -0,0 +1,750 @@
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>
);
});
@@ -108,6 +108,14 @@ import {
type WorkspaceRuntimeControlRequest,
} from "../WorkspaceRuntimeControls";
import { ExternalObjectRows } from "./external-object-rows";
import {
IssueChannelRow,
IssueClaimLeaseRow,
IssueKvLabelsRow,
IssueProfileAttributionRow,
IssueResultSchemaRow,
type KvLabelMutationPayload,
} from "./structured-task-rows";
import {
asRecord,
compactRecord,
@@ -220,6 +228,14 @@ interface IssuePropertiesProps {
sidePanelContentOnly?: boolean;
/** Overrides the fetched Context row (Storybook fixtures); null hides it. */
contextUsage?: import("react").ReactNode;
canEditKvLabels?: boolean;
onUpdateKvLabels?: (
payload: KvLabelMutationPayload,
) =>
| Promise<{ kvLabels?: Record<string, string> } | void>
| { kvLabels?: Record<string, string> }
| void;
leaseNowMs?: number;
}
export interface IssuePropertiesDocumentDeepLink {
@@ -259,6 +275,9 @@ export function IssueProperties({
documentDeepLink,
sidePanelContentOnly = false,
contextUsage,
canEditKvLabels = true,
onUpdateKvLabels,
leaseNowMs,
}: IssuePropertiesProps) {
const policyResult = useExecutionPolicy(issue.executionPolicy);
const policyAvailable = policyResult.success;
@@ -2472,6 +2491,14 @@ export function IssueProperties({
>
{labelsContent}
</PropertyPicker>
<IssueChannelRow issue={issue} />
<IssueKvLabelsRow
issue={issue}
canEdit={canEditKvLabels}
onUpdateKvLabels={onUpdateKvLabels}
/>
</PropertySection>
<PropertySection title="Relationships" streamlined={streamlinedPropertiesEnabled}>
@@ -2658,6 +2685,13 @@ export function IssueProperties({
</PropertySection>
<PropertySection title="Execution" streamlined={streamlinedPropertiesEnabled}>
<IssueClaimLeaseRow
issue={issue}
resolveAgentName={(id) => agentName(id)}
resolveUserName={(id) => actualUserLabel(id)}
nowMs={leaseNowMs}
/>
<IssueResultSchemaRow issue={issue} />
{/* Read-only: agents set the policy, the board does not. */}
{reviewPolicyBadge ? (
<PropertyRow label="Approvals">
@@ -2956,7 +2990,13 @@ export function IssueProperties({
) : null}
<PropertySection title="About" streamlined={streamlinedPropertiesEnabled}>
{originatingActor ? (
{issue.createdByProfile?.trim() && !issue.createdByAgentId ? (
<IssueProfileAttributionRow
createdByProfile={issue.createdByProfile}
createdByUserId={issue.createdByUserId}
resolvedHumanLabel={creatorUserLabel ?? originatingUserProfile?.label ?? null}
/>
) : originatingActor ? (
<PropertyRow label="Originating">
{originatingActor.kind === "agent" ? (
<Link
@@ -1,5 +1,13 @@
export { IssueProperties, type IssuePropertiesDocumentDeepLink } from "./IssueProperties";
export { ExternalObjectRows } from "./external-object-rows";
export {
IssueChannelRow,
IssueClaimLeaseRow,
IssueKvLabelsRow,
IssueProfileAttributionRow,
IssueResultSchemaRow,
type KvLabelMutationPayload,
} from "./structured-task-rows";
export { PropertyPicker } from "./property-picker";
export { PropertyChip, PropertyRow, PropertySection } from "./primitives";
export { ExpandRelationListButton, RemovableIssueReferencePill } from "./relation-controls";
@@ -0,0 +1,552 @@
// @vitest-environment jsdom
import { act as reactAct, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "../../api/client";
import { issuesApi } from "../../api/issues";
import { queryKeys } from "../../lib/queryKeys";
import {
formatLeaseRemaining,
IssueChannelRow,
IssueClaimLeaseRow,
IssueKvLabelsRow,
IssueProfileAttributionRow,
IssueResultSchemaRow,
type KvLabelMutationPayload,
} from "./structured-task-rows";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let container: HTMLDivElement | null = null;
let root: Root | null = null;
async function act(callback: () => void | Promise<void>) {
if (typeof reactAct === "function") {
await reactAct(callback);
return;
}
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
await new Promise((resolve) => setTimeout(resolve, 0));
}
function setNativeInputValue(input: HTMLInputElement, value: string) {
const setter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value",
)?.set;
setter?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
async function renderWithQuery(node: ReactNode, queryClient = new QueryClient()) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
await act(() => {
root!.render(<QueryClientProvider client={queryClient}>{node}</QueryClientProvider>);
});
return { container, queryClient };
}
afterEach(async () => {
vi.restoreAllMocks();
if (root) {
await act(() => {
root?.unmount();
});
root = null;
}
container?.remove();
container = null;
});
describe("Unset task rows on standard tasks", () => {
it("renders nothing for Channel, Key-values, Lease, and Result schema when unset (even when canEdit is true)", async () => {
const fixedNow = new Date("2026-12-01T15:00:00.000Z").getTime();
const { container: dom } = await renderWithQuery(
<>
<IssueChannelRow issue={{ channelPath: null }} />
<IssueKvLabelsRow issue={{ id: "issue-standard", kvLabels: {} }} canEdit={true} />
<IssueKvLabelsRow issue={{ id: "issue-standard-undef", kvLabels: undefined }} canEdit={true} />
<IssueClaimLeaseRow
issue={{
status: "todo",
claimEpoch: 0,
claimAttemptCount: 0,
claimHolderProfile: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
}}
nowMs={fixedNow}
/>
<IssueResultSchemaRow
issue={{
id: "issue-standard",
status: "todo",
resultSchemaRef: null,
description: "Ordinary manual board task",
schemaBlocks: [],
}}
/>
</>,
);
expect(dom.innerHTML).toBe("");
});
});
describe("IssueChannelRow", () => {
it("renders nothing when channelPath is absent (regardless of scope)", async () => {
const { container: dom } = await renderWithQuery(
<IssueChannelRow issue={{ channelPath: null }} />,
);
expect(dom.textContent).toBe("");
});
it("renders only the single #channelPath badge without a redundant scope badge", async () => {
const { container: dom } = await renderWithQuery(
<IssueChannelRow issue={{ channelPath: "build/auth" }} />,
);
const badge = dom.querySelector('[data-testid="issue-channel-provenance"]');
expect(badge?.textContent).toBe("build/auth");
expect(dom.querySelectorAll('[data-slot="badge"]')).toHaveLength(1);
expect(dom.textContent).not.toContain("channel");
});
});
describe("IssueKvLabelsRow", () => {
it("renders the Key-values label and supports inline add, click-to-edit value, and remove with CAS preconditions", async () => {
const calls: KvLabelMutationPayload[] = [];
const { container: dom } = await renderWithQuery(
<IssueKvLabelsRow
issue={{
id: "issue-1",
kvLabels: {
role: "worker",
env: "staging",
"paperclip.internal": "1",
},
}}
onUpdateKvLabels={(payload) => {
calls.push(payload);
}}
/>,
);
expect(dom.querySelector('[data-property-label="Key-values"]')?.textContent).toBe("Key-values");
expect(dom.textContent).toContain("role=worker");
expect(dom.textContent).toContain("env=staging");
expect(dom.textContent).toContain("paperclip.internal=1");
expect(dom.querySelector('[aria-label="Remove paperclip.internal key-value"]')).toBeNull();
// Edit `role` value
const editRoleBtn = dom.querySelector(
'[aria-label="Edit role key-value"]',
) as HTMLButtonElement;
await act(() => {
editRoleBtn.click();
});
const editInput = dom.querySelector(
'[aria-label="Value for role"]',
) as HTMLInputElement;
expect(editInput.value).toBe("worker");
await act(() => {
setNativeInputValue(editInput, "reviewer");
});
const saveRoleBtn = dom.querySelector('[aria-label="Save role"]') as HTMLButtonElement;
await act(async () => {
saveRoleBtn.click();
});
expect(calls[0]).toEqual({
set: { role: "reviewer" },
ifMatch: { role: "worker" },
});
expect(dom.textContent).toContain("role=reviewer");
// Remove `env`
const removeEnvBtn = dom.querySelector(
'[aria-label="Remove env key-value"]',
) as HTMLButtonElement;
await act(async () => {
removeEnvBtn.click();
});
expect(calls[1]).toEqual({
delete: ["env"],
ifMatch: { env: "staging" },
});
expect(dom.textContent).not.toContain("env=staging");
// Add `step=verify` via key=value auto-split
const addBtn = dom.querySelector(
'[aria-label="Add key-value"]',
) as HTMLButtonElement;
await act(() => {
addBtn.click();
});
const keyInput = dom.querySelector('[aria-label="Key"]') as HTMLInputElement;
await act(() => {
setNativeInputValue(keyInput, "step=verify");
});
const saveNewBtn = Array.from(dom.querySelectorAll("button")).find(
(btn) => btn.textContent === "Save",
)!;
await act(async () => {
saveNewBtn.click();
});
expect(calls[2]).toEqual({
set: { step: "verify" },
ifMatch: { step: null },
});
expect(dom.textContent).toContain("step=verify");
});
it("hides completely when the last key-value is deleted and renders read-only pills when canEdit is false", async () => {
const singleRender = await renderWithQuery(
<IssueKvLabelsRow
issue={{ id: "issue-single", kvLabels: { tier: "canary" } }}
onUpdateKvLabels={() => undefined}
/>,
);
expect(singleRender.container.textContent).toContain("tier=canary");
const removeTierBtn = singleRender.container.querySelector(
'[aria-label="Remove tier key-value"]',
) as HTMLButtonElement;
await act(async () => {
removeTierBtn.click();
});
expect(singleRender.container.innerHTML).toBe("");
await act(() => {
root?.unmount();
});
root = null;
container?.remove();
const readOnlyRender = await renderWithQuery(
<IssueKvLabelsRow
issue={{ id: "issue-ro", kvLabels: { tier: "canary" } }}
canEdit={false}
/>,
);
expect(readOnlyRender.container.textContent).toContain("tier=canary");
expect(readOnlyRender.container.querySelector("button")).toBeNull();
});
it("calls issuesApi.updateKvLabels by default, updates detail cache, and rolls back with conflict alert on 409", async () => {
const qc = new QueryClient();
qc.setQueryData(queryKeys.issues.detail("issue-default-api"), {
id: "issue-default-api",
kvLabels: { role: "worker" },
});
const spy = vi
.spyOn(issuesApi, "updateKvLabels")
.mockResolvedValueOnce({
id: "issue-default-api",
kvLabels: { role: "lead", server_tag: "synced" },
cursor: "cur-2",
})
.mockRejectedValueOnce(new ApiError("Conflict", 409, { code: "kv_label_conflict" }));
const { container: dom } = await renderWithQuery(
<IssueKvLabelsRow
issue={{ id: "issue-default-api", kvLabels: { role: "worker" } }}
/>,
qc,
);
const editRoleBtn = dom.querySelector(
'[aria-label="Edit role key-value"]',
) as HTMLButtonElement;
await act(() => {
editRoleBtn.click();
});
const editInput = dom.querySelector(
'[aria-label="Value for role"]',
) as HTMLInputElement;
await act(() => {
setNativeInputValue(editInput, "lead");
});
const saveRoleBtn = dom.querySelector('[aria-label="Save role"]') as HTMLButtonElement;
await act(async () => {
saveRoleBtn.click();
});
expect(spy).toHaveBeenNthCalledWith(1, "issue-default-api", {
set: { role: "lead" },
ifMatch: { role: "worker" },
});
expect(qc.getQueryData(queryKeys.issues.detail("issue-default-api"))).toEqual({
id: "issue-default-api",
kvLabels: { role: "lead", server_tag: "synced" },
});
expect(dom.textContent).toContain("role=lead");
expect(dom.textContent).toContain("server_tag=synced");
// Trigger 409 conflict and verify rollback + alert message
const editAgainBtn = dom.querySelector(
'[aria-label="Edit role key-value"]',
) as HTMLButtonElement;
await act(() => {
editAgainBtn.click();
});
const conflictInput = dom.querySelector(
'[aria-label="Value for role"]',
) as HTMLInputElement;
await act(() => {
setNativeInputValue(conflictInput, "stale");
});
const saveConflictBtn = dom.querySelector('[aria-label="Save role"]') as HTMLButtonElement;
await act(async () => {
saveConflictBtn.click();
});
expect(spy).toHaveBeenNthCalledWith(2, "issue-default-api", {
set: { role: "stale" },
ifMatch: { role: "lead" },
});
expect(dom.querySelector('[role="alert"]')?.textContent).toBe(
"Key-value changed concurrently. Refresh and retry.",
);
const cancelBtn = dom.querySelector(
'[aria-label="Cancel editing role"]',
) as HTMLButtonElement;
await act(() => {
cancelBtn.click();
});
expect(dom.textContent).toContain("role=lead");
});
});
describe("IssueClaimLeaseRow", () => {
const fixedNow = new Date("2026-12-01T15:00:00.000Z").getTime();
it("hides when no lease fields are present", async () => {
const { container: dom } = await renderWithQuery(
<IssueClaimLeaseRow
issue={{
status: "todo",
claimEpoch: 0,
claimAttemptCount: 0,
claimHolderProfile: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
}}
nowMs={fixedNow}
/>,
);
expect(dom.textContent).toBe("");
expect(formatLeaseRemaining(14 * 60_000)).toBe("14m left");
});
it("renders active lease with inline status dot on the same text flow (no flex-wrap separating dot and text)", async () => {
const { container: dom } = await renderWithQuery(
<IssueClaimLeaseRow
issue={{
status: "in_progress",
claimEpoch: 2,
claimAttemptCount: 1,
claimHolderProfile: "worker-1",
claimLeaseExpiresAt: new Date(fixedNow + 14 * 60_000).toISOString(),
}}
nowMs={fixedNow}
/>,
);
const leaseEl = dom.querySelector('[data-testid="issue-claim-lease"]') as HTMLElement;
expect(leaseEl?.getAttribute("data-lease-state")).toBe("active");
expect(leaseEl?.textContent).toBe("Claimed by worker-1 · epoch 2 · 14m left");
expect(leaseEl?.className).not.toContain("flex-wrap");
const dotEl = leaseEl?.querySelector(".status-fill") as HTMLElement;
expect(dotEl).not.toBeNull();
expect(dotEl.className).toContain("inline-block");
});
it("renders expired lease state with inline status dot, holder, and attempt count", async () => {
const { container: dom } = await renderWithQuery(
<IssueClaimLeaseRow
issue={{
status: "todo",
claimEpoch: 3,
claimAttemptCount: 3,
claimHolderProfile: "scanner-2",
claimLeaseExpiresAt: new Date(fixedNow - 5 * 60_000).toISOString(),
}}
nowMs={fixedNow}
/>,
);
const leaseEl = dom.querySelector('[data-testid="issue-claim-lease"]') as HTMLElement;
expect(leaseEl?.getAttribute("data-lease-state")).toBe("expired");
expect(leaseEl?.textContent).toBe("Expired · scanner-2 · attempt 3");
expect(leaseEl?.className).not.toContain("flex-wrap");
const dotEl = leaseEl?.querySelector(".status-fill") as HTMLElement;
expect(dotEl).not.toBeNull();
expect(dotEl.className).toContain("inline-block");
});
it("hides the lease row when a claim was released or requeued and only prior attempts remain", async () => {
const { container: dom } = await renderWithQuery(
<IssueClaimLeaseRow
issue={{
status: "todo",
claimEpoch: 2,
claimAttemptCount: 2,
claimHolderProfile: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
}}
nowMs={fixedNow}
/>,
);
expect(dom.querySelector('[data-testid="issue-claim-lease"]')).toBeNull();
expect(dom.textContent).toBe("");
});
it("ticks the countdown and flips to expired when the deadline passes without external re-renders", async () => {
vi.useFakeTimers();
try {
vi.setSystemTime(fixedNow);
const { container: dom } = await renderWithQuery(
<IssueClaimLeaseRow
issue={{
status: "in_progress",
claimEpoch: 1,
claimAttemptCount: 1,
claimHolderProfile: "worker-live",
claimLeaseExpiresAt: new Date(fixedNow + 2_000).toISOString(),
}}
/>,
);
expect(
dom.querySelector('[data-testid="issue-claim-lease"]')?.getAttribute("data-lease-state"),
).toBe("active");
expect(dom.textContent).toContain("2s left");
await act(() => {
vi.advanceTimersByTime(2_100);
});
const expiredEl = dom.querySelector('[data-testid="issue-claim-lease"]');
expect(expiredEl?.getAttribute("data-lease-state")).toBe("expired");
expect(expiredEl?.textContent).toBe("Expired · worker-live · attempt 1");
} finally {
vi.useRealTimers();
}
});
});
describe("IssueResultSchemaRow and IssueProfileAttributionRow", () => {
it("unwraps InfiniteData and identifier-keyed recent comment caches and reacts to cache updates", async () => {
const qc = new QueryClient();
qc.setQueryData(queryKeys.issues.comments("issue-res-1"), {
pages: [
[
{
id: "c1",
body: '```json schema=test-report@1\n{"passed":true,"total":12}\n```',
},
],
],
pageParams: [null],
});
qc.setQueryData([...queryKeys.issues.comments("PAP-777"), "recent"], [
{
id: "c-ident",
body: '```json schema=git-commit@1\n{"sha":"1234567","message":"fix"}\n```',
},
]);
const { container: dom } = await renderWithQuery(
<>
<IssueResultSchemaRow
issue={{
id: "issue-res-1",
status: "done",
resultSchemaRef: "test-report@1",
description: null,
schemaBlocks: [],
}}
/>
<IssueResultSchemaRow
issue={{
id: "issue-res-ident",
identifier: "PAP-777",
status: "done",
resultSchemaRef: "git-commit@1",
description: null,
schemaBlocks: [],
}}
/>
<IssueResultSchemaRow
issue={{
id: "issue-res-missing",
status: "done",
resultSchemaRef: "finding@1",
description: "No structured block here",
schemaBlocks: [],
}}
/>
</>,
qc,
);
expect(dom.textContent).toContain("test-report@1");
expect(dom.textContent).toContain("git-commit@1");
expect(dom.textContent).toContain("finding@1");
expect(dom.textContent).toContain("Missing block");
await act(() => {
qc.setQueryData(queryKeys.issues.comments("issue-res-missing"), {
pages: [
[
{
id: "c-late",
body: '```json schema=finding@1\n{"severity":"low","title":"Resolved"}\n```',
},
],
],
pageParams: [null],
});
});
expect(dom.textContent).not.toContain("Missing block");
});
it("formats createdByProfile with via human user or (profile) badge instead of local-board", async () => {
const { container: dom } = await renderWithQuery(
<>
<IssueProfileAttributionRow
createdByProfile="lead"
createdByUserId="user-ada"
resolvedHumanLabel="Ada"
/>
<IssueProfileAttributionRow
createdByProfile="triage-bot"
createdByUserId="local-board"
resolvedHumanLabel="Board"
/>
</>,
);
const rows = dom.querySelectorAll('[data-testid="issue-created-by-profile"]');
expect(rows[0]?.textContent).toContain("lead");
expect(rows[0]?.textContent).toContain("via Ada");
expect(rows[1]?.textContent).toContain("triage-bot");
expect(rows[1]?.textContent).toContain("(profile)");
expect(dom.textContent).not.toContain("local-board");
});
});
@@ -0,0 +1,868 @@
import { useEffect, useMemo, useState, type CSSProperties } from "react";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import {
AlertCircle,
Braces,
Check,
CheckCircle2,
Hash,
Plus,
Terminal,
X,
} from "lucide-react";
import {
isReservedKvLabelKey,
isValidKvLabelKey,
isValidKvLabelValue,
type Issue,
type IssueComment,
type SchemaBlock,
} from "@paperclipai/shared";
import { Badge } from "@/components/ui/badge";
import { ApiError } from "../../api/client";
import { issuesApi } from "../../api/issues";
import { queryKeys } from "../../lib/queryKeys";
import { checkMatchingSchemaBlock } from "../../lib/schema-block-utils";
import { PropertyRow } from "./primitives";
export interface KvLabelMutationPayload {
set?: Record<string, string>;
delete?: string[];
ifMatch?: Record<string, string | null>;
}
function scStyle(cssVar: string): CSSProperties {
return { "--sc": `var(${cssVar})` } as CSSProperties;
}
function isCommentRecord(
value: unknown,
): value is Pick<IssueComment, "id" | "body" | "schemaBlocks"> {
return (
typeof value === "object" &&
value !== null &&
typeof (value as { body?: unknown }).body === "string"
);
}
export function unwrapCachedIssueComments(
data: unknown,
): Array<Pick<IssueComment, "id" | "body" | "schemaBlocks">> {
if (!data) return [];
if (Array.isArray(data)) {
return data.filter(isCommentRecord);
}
if (typeof data === "object") {
if ("pages" in data && Array.isArray((data as { pages?: unknown }).pages)) {
const pages = (data as { pages: unknown[] }).pages;
const flattened: Array<Pick<IssueComment, "id" | "body" | "schemaBlocks">> = [];
for (const page of pages) {
if (Array.isArray(page)) {
for (const item of page) {
if (isCommentRecord(item)) flattened.push(item);
}
} else if (
page &&
typeof page === "object" &&
"comments" in page &&
Array.isArray((page as { comments?: unknown }).comments)
) {
for (const item of (page as { comments: unknown[] }).comments) {
if (isCommentRecord(item)) flattened.push(item);
}
}
}
return flattened;
}
if ("comments" in data && Array.isArray((data as { comments?: unknown }).comments)) {
return (data as { comments: unknown[] }).comments.filter(isCommentRecord);
}
}
return [];
}
function readCachedIssueComments(
queryClient: QueryClient,
issueId: string,
identifier?: string | null,
): Array<Pick<IssueComment, "id" | "body" | "schemaBlocks">> {
const refs = [issueId];
const trimmedIdentifier = identifier?.trim();
if (trimmedIdentifier && trimmedIdentifier !== issueId) {
refs.push(trimmedIdentifier);
}
const seenIds = new Set<string>();
const collected: Array<Pick<IssueComment, "id" | "body" | "schemaBlocks">> = [];
for (const ref of refs) {
const entries = queryClient.getQueriesData({
queryKey: queryKeys.issues.comments(ref),
});
for (const [, data] of entries) {
for (const comment of unwrapCachedIssueComments(data)) {
const key =
typeof comment.id === "string" && comment.id
? comment.id
: `${collected.length}:${comment.body}`;
if (seenIds.has(key)) continue;
seenIds.add(key);
collected.push(comment);
}
}
}
return collected;
}
export function formatLeaseRemaining(remainingMs: number): string {
const totalSeconds = Math.max(1, Math.ceil(remainingMs / 1000));
if (totalSeconds < 60) {
return `${totalSeconds}s left`;
}
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
if (minutes < 60) {
return seconds > 0 && minutes < 10
? `${minutes}m ${seconds}s left`
: `${minutes}m left`;
}
const hours = Math.floor(minutes / 60);
const remMinutes = minutes % 60;
return remMinutes > 0 ? `${hours}h ${remMinutes}m left` : `${hours}h left`;
}
export function IssueChannelRow({
issue,
}: {
issue: Pick<Issue, "channelPath">;
}) {
const channelPath = issue.channelPath?.trim().replace(/^#/, "") || null;
if (!channelPath) {
return null;
}
return (
<PropertyRow label="Channel">
<Badge
variant="outline"
data-testid="issue-channel-provenance"
className="max-w-full gap-0.5 font-mono text-xs font-normal text-foreground"
title={`#${channelPath}`}
>
<Hash className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className="truncate">{channelPath}</span>
</Badge>
</PropertyRow>
);
}
const TOUCH_SAFE_MONO_INPUT_CLASS =
"min-w-0 font-mono text-base text-foreground outline-none md:text-xs [@media(pointer:coarse)]:text-base";
export function IssueKvLabelsRow({
issue,
canEdit = true,
onUpdateKvLabels,
}: {
issue: Pick<Issue, "id" | "kvLabels">;
canEdit?: boolean;
onUpdateKvLabels?: (
payload: KvLabelMutationPayload,
) =>
| Promise<{ kvLabels?: Record<string, string> } | void>
| { kvLabels?: Record<string, string> }
| void;
}) {
const queryClient = useQueryClient();
const [labelsState, setLabelsState] = useState<Record<string, string>>(
() => issue.kvLabels ?? {},
);
const [adding, setAdding] = useState(false);
const [newKey, setNewKey] = useState("");
const [newValue, setNewValue] = useState("");
const [editingKey, setEditingKey] = useState<string | null>(null);
const [editingValue, setEditingValue] = useState("");
const [saving, setSaving] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
useEffect(() => {
setLabelsState(issue.kvLabels ?? {});
}, [issue.id, issue.kvLabels]);
const entries = useMemo(
() =>
Object.entries(labelsState).filter(
([k, v]) => typeof k === "string" && k.length > 0 && typeof v === "string",
),
[labelsState],
);
const applyMutation = async (
payload: KvLabelMutationPayload,
optimisticNext: Record<string, string>,
): Promise<boolean> => {
setSaving(true);
setErrorMessage(null);
const previous = labelsState;
setLabelsState(optimisticNext);
try {
if (onUpdateKvLabels) {
const res = await onUpdateKvLabels(payload);
if (res && typeof res === "object" && "kvLabels" in res && res.kvLabels) {
setLabelsState(res.kvLabels);
}
} else {
const res = await issuesApi.updateKvLabels(issue.id, payload);
setLabelsState(res.kvLabels);
queryClient.setQueryData<Issue | undefined>(
queryKeys.issues.detail(issue.id),
(cached) => (cached ? { ...cached, kvLabels: res.kvLabels } : cached),
);
}
return true;
} catch (err) {
setLabelsState(previous);
if (err instanceof ApiError && err.status === 409) {
setErrorMessage("Key-value changed concurrently. Refresh and retry.");
} else if (err instanceof Error && err.message) {
setErrorMessage(err.message);
} else {
setErrorMessage("Unable to update key-values.");
}
return false;
} finally {
setSaving(false);
}
};
const handleKeyInputChange = (raw: string) => {
const eqIndex = raw.indexOf("=");
if (eqIndex !== -1) {
setNewKey(raw.slice(0, eqIndex).trim());
if (!newValue) {
setNewValue(raw.slice(eqIndex + 1));
}
return;
}
setNewKey(raw);
};
const handleAddSubmit = async () => {
const key = newKey.trim();
const value = newValue.trim();
if (!isValidKvLabelKey(key)) {
setErrorMessage("Key must use lowercase letters, numbers, '.', '_', or '-'.");
return;
}
if (isReservedKvLabelKey(key)) {
setErrorMessage("Keys starting with 'paperclip.' are reserved.");
return;
}
if (!isValidKvLabelValue(value)) {
setErrorMessage("Value must be non-empty and at most 256 bytes.");
return;
}
const existingValue = Object.prototype.hasOwnProperty.call(labelsState, key)
? labelsState[key]!
: null;
const next = { ...labelsState, [key]: value };
const ok = await applyMutation(
{
set: { [key]: value },
ifMatch: { [key]: existingValue },
},
next,
);
if (ok) {
setNewKey("");
setNewValue("");
setAdding(false);
}
};
const handleEditSave = async (key: string) => {
const nextValue = editingValue.trim();
const currentValue = labelsState[key];
if (currentValue === undefined) {
setEditingKey(null);
return;
}
if (nextValue === currentValue) {
setEditingKey(null);
setErrorMessage(null);
return;
}
if (!isValidKvLabelValue(nextValue)) {
setErrorMessage("Value must be non-empty and at most 256 bytes.");
return;
}
const next = { ...labelsState, [key]: nextValue };
const ok = await applyMutation(
{
set: { [key]: nextValue },
ifMatch: { [key]: currentValue },
},
next,
);
if (ok) {
setEditingKey(null);
setEditingValue("");
}
};
const handleDelete = async (key: string) => {
const currentValue = labelsState[key];
if (currentValue === undefined) return;
const next = { ...labelsState };
delete next[key];
if (editingKey === key) {
setEditingKey(null);
setEditingValue("");
}
const ok = await applyMutation(
{
delete: [key],
ifMatch: { [key]: currentValue },
},
next,
);
if (ok && Object.keys(next).length === 0) {
setAdding(false);
}
};
// Only show Key-values when at least one key-value is set (or while an active
// inline add initiated from a populated row is still open).
if (entries.length === 0 && !adding) {
return null;
}
return (
<PropertyRow label="Key-values" wrap>
<div
className="flex w-full min-w-0 flex-col items-start gap-1.5"
data-testid="issue-kv-labels-row"
>
{entries.length > 0 ? (
<div className="flex w-full flex-wrap items-center gap-1">
{entries.map(([key, value]) => {
const editable = canEdit && !isReservedKvLabelKey(key);
const isEditingThis = editingKey === key;
if (isEditingThis) {
return (
<div
key={key}
className="inline-flex max-w-full items-center gap-1 rounded-sm border border-ring bg-background px-1.5 py-0.5 font-mono text-xs"
>
<span className="shrink-0 text-muted-foreground">{key}=</span>
<input
type="text"
aria-label={`Value for ${key}`}
value={editingValue}
onChange={(e) => setEditingValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
void handleEditSave(key);
} else if (e.key === "Escape") {
e.preventDefault();
setEditingKey(null);
setErrorMessage(null);
}
}}
autoFocus
disabled={saving}
className={`w-24 bg-transparent ${TOUCH_SAFE_MONO_INPUT_CLASS}`}
/>
<button
type="button"
aria-label={`Save ${key}`}
disabled={saving}
onClick={() => void handleEditSave(key)}
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"
>
<Check className="h-3 w-3" aria-hidden="true" />
</button>
<button
type="button"
aria-label={`Cancel editing ${key}`}
onClick={() => {
setEditingKey(null);
setErrorMessage(null);
}}
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
>
<X className="h-3 w-3" aria-hidden="true" />
</button>
</div>
);
}
return (
<span
key={key}
className="inline-flex max-w-full flex-wrap items-center gap-0.5 rounded-sm border border-border bg-muted/40 px-1.5 py-0.5 font-mono text-xs"
title={`${key}=${value}`}
>
{editable ? (
<button
type="button"
disabled={saving}
onClick={() => {
setErrorMessage(null);
setEditingKey(key);
setEditingValue(value);
}}
className="inline-flex max-w-full min-w-0 flex-wrap items-baseline gap-0.5 text-left hover:underline disabled:opacity-50"
aria-label={`Edit ${key} key-value`}
>
<span className="break-all text-muted-foreground">{key}</span>
<span className="text-muted-foreground/70">=</span>
<span className="break-all font-medium text-foreground">{value}</span>
</button>
) : (
<>
<span className="break-all text-muted-foreground">{key}</span>
<span className="text-muted-foreground/70">=</span>
<span className="break-all font-medium text-foreground">{value}</span>
</>
)}
{editable ? (
<button
type="button"
disabled={saving}
onClick={() => void handleDelete(key)}
aria-label={`Remove ${key} key-value`}
className="ml-0.5 rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
>
<X className="h-2.5 w-2.5" aria-hidden="true" />
</button>
) : null}
</span>
);
})}
{canEdit && !adding ? (
<button
type="button"
onClick={() => {
setErrorMessage(null);
setAdding(true);
}}
aria-label="Add key-value"
className="inline-flex items-center gap-0.5 rounded-sm border border-dashed border-border px-1.5 py-0.5 font-mono text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
>
<Plus className="h-3 w-3 shrink-0" aria-hidden="true" />
Add
</button>
) : null}
</div>
) : null}
{canEdit && adding ? (
<div className="flex w-full flex-col gap-1 rounded-sm border border-border bg-muted/20 p-1.5">
<div className="flex items-center gap-1">
<input
type="text"
aria-label="Key"
placeholder="key"
value={newKey}
onChange={(e) => handleKeyInputChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
void handleAddSubmit();
} else if (e.key === "Escape") {
e.preventDefault();
setAdding(false);
setErrorMessage(null);
}
}}
autoFocus
disabled={saving}
className={`w-24 rounded-sm border border-border bg-background px-1.5 py-0.5 focus-visible:ring-1 focus-visible:ring-ring ${TOUCH_SAFE_MONO_INPUT_CLASS}`}
/>
<span className="font-mono text-xs text-muted-foreground">=</span>
<input
type="text"
aria-label="Value"
placeholder="value"
value={newValue}
onChange={(e) => setNewValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
void handleAddSubmit();
} else if (e.key === "Escape") {
e.preventDefault();
setAdding(false);
setErrorMessage(null);
}
}}
disabled={saving}
className={`flex-1 rounded-sm border border-border bg-background px-1.5 py-0.5 focus-visible:ring-1 focus-visible:ring-ring ${TOUCH_SAFE_MONO_INPUT_CLASS}`}
/>
</div>
<div className="flex w-full items-center justify-between gap-1">
<button
type="button"
onClick={() => {
setAdding(false);
setNewKey("");
setNewValue("");
setErrorMessage(null);
}}
className="rounded-sm px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground"
>
Cancel
</button>
<button
type="button"
disabled={saving || !newKey.trim() || !newValue.trim()}
onClick={() => void handleAddSubmit()}
className="rounded-sm border border-border bg-background px-2 py-0.5 text-xs font-medium text-foreground hover:bg-accent/50 disabled:opacity-50"
>
Save
</button>
</div>
</div>
) : null}
{errorMessage ? (
<p role="alert" className="text-xs text-destructive">
{errorMessage}
</p>
) : null}
</div>
</PropertyRow>
);
}
export function IssueClaimLeaseRow({
issue,
resolveAgentName,
resolveUserName,
nowMs,
}: {
issue: Pick<
Issue,
| "status"
| "claimEpoch"
| "claimHolderProfile"
| "claimHolderAgentId"
| "claimHolderUserId"
| "claimLeasedAt"
| "claimLeaseExpiresAt"
| "claimAttemptCount"
>;
resolveAgentName?: (agentId: string) => string | null | undefined;
resolveUserName?: (userId: string) => string | null | undefined;
nowMs?: number;
}) {
const rawExpiresAt = issue.claimLeaseExpiresAt ?? null;
const parsedExpiresAtMs = rawExpiresAt ? new Date(rawExpiresAt).getTime() : null;
const validExpiresAtMs =
parsedExpiresAtMs !== null && Number.isFinite(parsedExpiresAtMs)
? parsedExpiresAtMs
: null;
const [clockNowMs, setClockNowMs] = useState<number>(() => nowMs ?? Date.now());
useEffect(() => {
if (nowMs !== undefined) {
setClockNowMs(nowMs);
return;
}
const currentNow = Date.now();
setClockNowMs(currentNow);
if (validExpiresAtMs === null || validExpiresAtMs <= currentNow) {
return;
}
const msUntilExpiry = validExpiresAtMs - currentNow;
const tickIntervalMs = msUntilExpiry <= 120_000 ? 1_000 : 15_000;
const interval = setInterval(() => {
const nextNow = Date.now();
setClockNowMs(nextNow);
if (nextNow >= validExpiresAtMs) {
clearInterval(interval);
}
}, tickIntervalMs);
const expiryTimer = setTimeout(() => {
setClockNowMs(Date.now());
clearInterval(interval);
}, msUntilExpiry + 10);
return () => {
clearInterval(interval);
clearTimeout(expiryTimer);
};
}, [nowMs, validExpiresAtMs]);
const holder =
issue.claimHolderProfile?.trim() ||
(issue.claimHolderAgentId
? resolveAgentName?.(issue.claimHolderAgentId)?.trim() ||
issue.claimHolderAgentId.slice(0, 8)
: null) ||
(issue.claimHolderUserId
? resolveUserName?.(issue.claimHolderUserId)?.trim() || issue.claimHolderUserId
: null);
// When a claim has been released or requeued, the server clears holder and
// claimLeaseExpiresAt while preserving earlier attempt counters. Do not
// render a stale/expired lease banner when no lease remains.
if (!holder && validExpiresAtMs === null) {
return null;
}
const attemptCount = issue.claimAttemptCount ?? 0;
const epoch = issue.claimEpoch ?? 0;
const effectiveNow = nowMs ?? clockNowMs;
const isTerminal = issue.status === "done" || issue.status === "cancelled";
const isActiveLease =
!isTerminal &&
((validExpiresAtMs !== null && validExpiresAtMs > effectiveNow) ||
(Boolean(holder) && validExpiresAtMs === null));
if (isActiveLease) {
const remainingText =
validExpiresAtMs !== null
? formatLeaseRemaining(validExpiresAtMs - effectiveNow)
: null;
const summaryParts = [
holder ? `Claimed by ${holder}` : "Claimed",
`epoch ${Math.max(1, epoch)}`,
...(remainingText ? [remainingText] : []),
];
const summary = summaryParts.join(" · ");
return (
<PropertyRow label="Lease" wrap>
<span
data-testid="issue-claim-lease"
data-lease-state="active"
className="min-w-0 break-words font-mono text-xs leading-relaxed text-foreground"
title={summary}
>
<span
className="status-fill mr-1.5 inline-block h-2 w-2 shrink-0 animate-pulse rounded-full align-middle"
style={scStyle("--status-task-in_progress")}
aria-hidden="true"
/>
{summary}
</span>
</PropertyRow>
);
}
if (isTerminal) {
if (!holder) return null;
const terminalSummary = [
`Released (${holder})`,
...(epoch > 0 ? [`epoch ${epoch}`] : []),
].join(" · ");
return (
<PropertyRow label="Lease">
<span
data-testid="issue-claim-lease"
data-lease-state="released"
className="truncate font-mono text-xs text-muted-foreground"
title={terminalSummary}
>
{terminalSummary}
</span>
</PropertyRow>
);
}
const displayAttempt = Math.max(1, attemptCount || epoch || 1);
const expiredSummary = [
"Expired",
...(holder ? [holder] : []),
`attempt ${displayAttempt}`,
].join(" · ");
return (
<PropertyRow label="Lease" wrap>
<span
data-testid="issue-claim-lease"
data-lease-state="expired"
className="min-w-0 break-words font-mono text-xs leading-relaxed text-(--status-task-icon-todo)"
title={expiredSummary}
>
<span
className="status-fill mr-1.5 inline-block h-2 w-2 shrink-0 rounded-full align-middle"
style={scStyle("--status-task-todo")}
aria-hidden="true"
/>
{expiredSummary}
</span>
</PropertyRow>
);
}
export function IssueResultSchemaRow({
issue,
commentBodies,
commentSchemaBlocks,
}: {
issue: Pick<
Issue,
"id" | "status" | "resultSchemaRef" | "description" | "schemaBlocks"
> & {
identifier?: string | null;
};
commentBodies?: ReadonlyArray<string | null | undefined>;
commentSchemaBlocks?: ReadonlyArray<readonly SchemaBlock[] | null | undefined>;
}) {
const queryClient = useQueryClient();
const ref = issue.resultSchemaRef?.trim() || null;
const [cacheVersion, setCacheVersion] = useState(0);
useEffect(() => {
if (!ref || (commentBodies !== undefined && commentSchemaBlocks !== undefined)) {
return;
}
const targetRefs = new Set([issue.id]);
const trimmedIdentifier = issue.identifier?.trim();
if (trimmedIdentifier) {
targetRefs.add(trimmedIdentifier);
}
return queryClient.getQueryCache().subscribe((event) => {
const key = event.query.queryKey;
if (
Array.isArray(key) &&
key[0] === "issues" &&
key[1] === "comments" &&
typeof key[2] === "string" &&
targetRefs.has(key[2])
) {
setCacheVersion((prev) => prev + 1);
}
});
}, [
queryClient,
ref,
issue.id,
issue.identifier,
commentBodies,
commentSchemaBlocks,
]);
const cachedComments = useMemo(() => {
if (!ref || (commentBodies !== undefined && commentSchemaBlocks !== undefined)) {
return [];
}
return readCachedIssueComments(queryClient, issue.id, issue.identifier);
}, [
queryClient,
ref,
issue.id,
issue.identifier,
commentBodies,
commentSchemaBlocks,
cacheVersion,
]);
if (!ref) return null;
const matchState = checkMatchingSchemaBlock(ref, {
schemaBlocks: issue.schemaBlocks,
markdownBodies: [
issue.description,
...(commentBodies ?? cachedComments.map((c) => c.body)),
],
commentSchemaBlocks:
commentSchemaBlocks ?? cachedComments.map((c) => c.schemaBlocks),
});
return (
<PropertyRow label="Result schema" wrap>
<div
data-testid="issue-result-schema"
className="flex flex-wrap items-center gap-1.5"
>
<Badge
variant="outline"
className="gap-1 font-mono text-xs font-normal text-foreground"
>
<Braces className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />
{ref}
</Badge>
{matchState === "matched" ? (
<Badge
variant="outline"
className="status-chip gap-1 font-mono text-(length:--text-nano) font-normal"
style={scStyle("--status-task-done")}
>
<CheckCircle2 className="h-2.5 w-2.5 shrink-0" aria-hidden="true" />
Matched
</Badge>
) : matchState === "unverified" ? (
<span className="text-xs text-muted-foreground">Scan limit reached</span>
) : issue.status === "done" ? (
<Badge
variant="outline"
className="status-chip gap-1 font-mono text-(length:--text-nano) font-normal"
style={scStyle("--status-task-todo")}
>
<AlertCircle className="h-2.5 w-2.5 shrink-0" aria-hidden="true" />
Missing block
</Badge>
) : (
<span className="text-xs text-muted-foreground">Awaiting result</span>
)}
</div>
</PropertyRow>
);
}
export function IssueProfileAttributionRow({
createdByProfile,
createdByUserId,
resolvedHumanLabel,
}: {
createdByProfile?: string | null;
createdByUserId?: string | null;
resolvedHumanLabel?: string | null;
}) {
const profile = createdByProfile?.trim();
if (!profile) return null;
const isHumanDelegated =
Boolean(createdByUserId) && createdByUserId !== "local-board";
const humanLabel = isHumanDelegated
? resolvedHumanLabel?.trim() ||
(createdByUserId!.startsWith("user-")
? createdByUserId!.slice("user-".length)
: createdByUserId!)
: null;
return (
<PropertyRow label="Originating" wrap>
<span
data-testid="issue-created-by-profile"
className="inline-flex min-w-0 flex-wrap items-center gap-1.5"
>
<span className="truncate font-mono text-xs font-medium text-foreground">
{profile}
</span>
{humanLabel ? (
<span className="truncate text-xs text-muted-foreground">
via {humanLabel}
</span>
) : (
<Badge
variant="outline"
className="gap-1 px-1.5 py-0 font-mono text-(length:--text-nano) font-normal text-muted-foreground"
>
<Terminal className="h-2.5 w-2.5 shrink-0" aria-hidden="true" />
(profile)
</Badge>
)}
</span>
</PropertyRow>
);
}
+14 -1
View File
@@ -46,6 +46,8 @@ import {
import { TaskChatBubbleActions } from "./TaskChatBubbleActions";
import { TaskChatSystemNotice } from "./TaskChatSystemNotice";
import { RunFileCardsContext } from "./RunFileCardsContext";
import { ActorProfileIdentity, CommentKvLabelsBar } from "../CommentStructuredMeta";
import { StandaloneSchemaBlockList } from "../SchemaBlockCard";
import type { TaskChatMessageItem } from "./task-chat-model";
import { safeNavigableUrl } from "@/lib/safe-url";
@@ -284,7 +286,11 @@ function TaskChatBubbleContent({
{item.chatMessage && <Link to={`/issues/${item.chatMessage.sourceTaskIdentifier}`} className="px-1 text-xs text-muted-foreground underline underline-offset-4">
From {item.chatMessage.sourceTaskIdentifier}
</Link>}
{isHuman && !item.isCurrentUser && item.authorName ? (
{isHuman && !item.isCurrentUser && item.actorProfileAttribution ? (
<span className="px-1" data-testid="task-chat-human-identity" data-author-user-id={item.authorUserId}>
<ActorProfileIdentity attribution={item.actorProfileAttribution} />
</span>
) : isHuman && !item.isCurrentUser && item.authorName ? (
<span className="px-1 text-sm font-semibold text-foreground" data-testid="task-chat-human-identity" data-author-user-id={item.authorUserId}>
<Identity name={item.authorName} avatarUrl={paperclipHumanAvatarUrl(item.authorAvatarUrl)} size="default" className="gap-2" />
</span>
@@ -326,6 +332,13 @@ function TaskChatBubbleContent({
>
{bodyText}
</MarkdownBody>
<StandaloneSchemaBlockList markdown={item.text} schemaBlocks={item.schemaBlocks} />
<CommentKvLabelsBar kvLabels={item.kvLabels} />
</div>
) : item.schemaBlocks?.length || (item.kvLabels && Object.keys(item.kvLabels).length > 0) ? (
<div className="w-full px-1 py-1">
<StandaloneSchemaBlockList markdown={item.text} schemaBlocks={item.schemaBlocks} />
<CommentKvLabelsBar kvLabels={item.kvLabels} />
</div>
) : null}
{!artifactsV1 && imageRefs.length > 0 ? (
@@ -5,6 +5,8 @@ import { cn } from "@/lib/utils";
import { FoldCurtain } from "@/components/FoldCurtain";
import { InlineEditor } from "@/components/InlineEditor";
import { MarkdownBody, type MarkdownExternalReferenceMap } from "@/components/MarkdownBody";
import { StandaloneSchemaBlockList } from "@/components/SchemaBlockCard";
import type { SchemaBlock } from "@paperclipai/shared";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import type { MentionOption } from "@/components/MarkdownEditor";
import { formatTaskChatTimestamp } from "./task-chat-adapter";
@@ -31,6 +33,7 @@ export interface TaskChatIssueBrief {
onSave: (description: string) => void | Promise<unknown>;
mentions?: MentionOption[];
externalReferences?: MarkdownExternalReferenceMap;
schemaBlocks?: readonly SchemaBlock[] | null;
imageUploadHandler?: (file: File) => Promise<string>;
onDropFile?: (file: File) => Promise<void>;
}
@@ -64,7 +67,8 @@ export function TaskChatDescriptionBubble({ brief }: TaskChatDescriptionBubblePr
const coordinator = useCoordinatorPresentation();
const [editing, setEditing] = useState(false);
const isHuman = brief.author === "human";
const hasDescription = brief.description.trim().length > 0;
const hasDescription =
brief.description.trim().length > 0 || Boolean(brief.schemaBlocks?.length);
if (editing) {
return (
@@ -155,6 +159,10 @@ export function TaskChatDescriptionBubble({ brief }: TaskChatDescriptionBubblePr
>
{brief.description}
</MarkdownBody>
<StandaloneSchemaBlockList
markdown={brief.description}
schemaBlocks={brief.schemaBlocks}
/>
</FoldCurtain>
</div>
{!isHuman ? (
@@ -11,6 +11,7 @@ import type { Agent } from "@paperclipai/shared";
import type { IssueChatComment } from "@/lib/issue-chat-messages";
import { resolveCommentAttribution } from "@/lib/comment-attribution";
import { resolveIssueChatHumanAuthor } from "@/lib/issue-chat-human-author";
import { resolveActorProfileAttribution } from "../CommentStructuredMeta";
import type { CompanyUserProfile } from "@/lib/company-members";
import type { TaskChatAuthorKind, TaskChatItem, TaskChatMessageItem } from "./task-chat-model";
@@ -84,9 +85,18 @@ export function commentsToTaskChatItems(
const humanAuthor = kind === "human" ? resolveIssueChatHumanAuthor({
authorUserId: comment.authorUserId,
authorName: comment.authorUserId ? ctx.userLabelMap?.get(comment.authorUserId) : null,
actorProfile: comment.actorProfile,
currentUserId: ctx.currentUserId,
userProfileMap: ctx.userProfileMap,
}) : undefined;
const actorProfileAttribution = kind === "human"
? resolveActorProfileAttribution({
actorProfile: comment.actorProfile,
authorUserId: comment.authorUserId,
userLabelMap: ctx.userLabelMap,
userProfileMap: ctx.userProfileMap,
})
: null;
if (kind === "agent") {
const agentId = effectiveAgentId(comment);
authorName = (agentId && ctx.agentMap?.get(agentId)?.name) || "Agent";
@@ -133,6 +143,9 @@ export function commentsToTaskChatItems(
authorAvatarUrl: humanAuthor.avatarUrl,
isCurrentUser: humanAuthor.isCurrentUser,
} : {}),
...(actorProfileAttribution ? { actorProfileAttribution } : {}),
...(comment.kvLabels && Object.keys(comment.kvLabels).length > 0 ? { kvLabels: comment.kvLabels } : {}),
...(comment.schemaBlocks && comment.schemaBlocks.length > 0 ? { schemaBlocks: comment.schemaBlocks } : {}),
agent: effectiveAgentId(comment) ? ctx.agentMap?.get(effectiveAgentId(comment)!) ?? { id: effectiveAgentId(comment)! } : undefined,
text: comment.body,
origin: comment.origin ?? "comment",
@@ -134,6 +134,9 @@ export interface TaskChatMessageItem {
authorUserId?: string | null;
authorAvatarUrl?: string | null;
isCurrentUser?: boolean;
actorProfileAttribution?: import("../CommentStructuredMeta").ResolvedActorProfileAttribution | null;
kvLabels?: Record<string, string> | null;
schemaBlocks?: readonly import("@paperclipai/shared").SchemaBlock[] | null;
text: string;
/** Runner-authored output channel. Legacy adapters leave this unset. */
channel?: "progress" | "final" | "unknown";
+11 -4
View File
@@ -8,16 +8,23 @@ export function paperclipHumanAvatarUrl(value: string | null | undefined): strin
export function resolveIssueChatHumanAuthor(args: {
authorName?: string | null;
authorUserId?: string | null;
actorProfile?: string | null;
currentUserId?: string | null;
userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
}) {
const { authorName, authorUserId, currentUserId, userProfileMap } = args;
const { authorName, authorUserId, actorProfile, currentUserId, userProfileMap } = args;
const trimmedActorProfile = actorProfile?.trim() || null;
const profile = authorUserId ? userProfileMap?.get(authorUserId) : null;
const isCurrentUser = Boolean(authorUserId && currentUserId && authorUserId === currentUserId);
const isCurrentUser =
!trimmedActorProfile &&
Boolean(authorUserId && currentUserId && authorUserId === currentUserId);
return {
isCurrentUser,
authorName: profile?.label?.trim() || authorName?.trim() ||
authorName:
trimmedActorProfile ||
profile?.label?.trim() ||
authorName?.trim() ||
(authorUserId === "local-board" ? "Board" : isCurrentUser ? "You" : "User"),
avatarUrl: profile?.image ?? null,
avatarUrl: trimmedActorProfile ? null : (profile?.image ?? null),
};
}
+5
View File
@@ -546,6 +546,8 @@ function authorNameForComment(
if (authorAgentId) {
return agentMap?.get(authorAgentId)?.name ?? (options?.isSystemNotice ? "Paperclip" : authorAgentId.slice(0, 8));
}
const actorProfile = comment.actorProfile?.trim();
if (actorProfile) return actorProfile;
const authorUserId = comment.authorUserId ?? null;
if (!authorUserId) return options?.isSystemNotice ? "Paperclip" : "You";
const userLabel = userLabelMap?.get(authorUserId)?.trim();
@@ -586,6 +588,9 @@ function createCommentMessage(args: {
authorType: effectiveCommentAuthorType(comment),
authorAgentId,
authorUserId: comment.authorUserId,
actorProfile: comment.actorProfile ?? null,
kvLabels: comment.kvLabels ?? null,
schemaBlocks: comment.schemaBlocks ?? null,
// Responsible user this agent comment rode the authority of (the open cross-task write design (attribution)).
onBehalfOfUserId: comment.onBehalfOfUserId ?? null,
companyId: companyId ?? comment.companyId,
+505
View File
@@ -0,0 +1,505 @@
import {
SCHEMA_REF_REGEX,
parseSchemaRef,
type ParsedSchemaRef,
type SchemaBlock,
} from "@paperclipai/shared";
export const EMPTY_SCHEMA_BLOCKS: readonly SchemaBlock[] = [];
const MAX_SCANNED_MARKDOWN_CHARS = 512 * 1024;
const MAX_SCHEMA_FENCE_BODY_CHARS = 64 * 1024;
const MAX_SCANNED_JSON_FENCES = 64;
const MAX_FENCE_META_CHARS = 256;
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
type CanonicalStackItem =
| { kind: "token"; text: string }
| { kind: "exit"; ref: object }
| { kind: "value"; value: unknown };
/**
* Iteratively serializes arbitrary JSON-like values with sorted object keys
* using an explicit heap stack so deeply nested payloads neither overflow the
* call stack nor collide under depth truncation.
*/
function serializeCanonicalJson(root: unknown): string {
const parts: string[] = [];
const activeAncestors = new Set<object>();
const stack: CanonicalStackItem[] = [{ kind: "value", value: root }];
while (stack.length > 0) {
const current = stack.pop()!;
if (current.kind === "token") {
parts.push(current.text);
continue;
}
if (current.kind === "exit") {
activeAncestors.delete(current.ref);
continue;
}
const value = current.value;
if (value === null || value === undefined) {
parts.push("null");
continue;
}
if (typeof value === "boolean" || typeof value === "number") {
parts.push(
Number.isFinite(value as number) || typeof value === "boolean"
? String(value)
: "null",
);
continue;
}
if (typeof value === "string") {
parts.push(JSON.stringify(value));
continue;
}
if (Array.isArray(value)) {
if (activeAncestors.has(value)) {
parts.push('"[Circular]"');
continue;
}
if (value.length === 0) {
parts.push("[]");
continue;
}
activeAncestors.add(value);
stack.push({ kind: "exit", ref: value });
stack.push({ kind: "token", text: "]" });
for (let idx = value.length - 1; idx >= 0; idx -= 1) {
stack.push({ kind: "value", value: value[idx] });
if (idx > 0) {
stack.push({ kind: "token", text: "," });
}
}
stack.push({ kind: "token", text: "[" });
continue;
}
if (isPlainRecord(value)) {
if (activeAncestors.has(value)) {
parts.push('"[Circular]"');
continue;
}
const keys = Object.keys(value)
.filter((key) => value[key] !== undefined)
.sort();
if (keys.length === 0) {
parts.push("{}");
continue;
}
activeAncestors.add(value);
stack.push({ kind: "exit", ref: value });
stack.push({ kind: "token", text: "}" });
for (let idx = keys.length - 1; idx >= 0; idx -= 1) {
const key = keys[idx]!;
stack.push({ kind: "value", value: value[key] });
stack.push({ kind: "token", text: `${JSON.stringify(key)}:` });
if (idx > 0) {
stack.push({ kind: "token", text: "," });
}
}
stack.push({ kind: "token", text: "{" });
continue;
}
parts.push(JSON.stringify(String(value)));
}
return parts.join("");
}
export function canonicalSchemaBlockKey(block: SchemaBlock): string {
return `${block.schema.toLowerCase()}@${block.version}:${serializeCanonicalJson(block.data)}`;
}
function isHorizontalSpace(code: number): boolean {
return code === 32 || code === 9;
}
export function parseSchemaFenceMeta(meta: string | null | undefined): ParsedSchemaRef | null {
if (!meta || meta.length > MAX_FENCE_META_CHARS) return null;
let idx = 0;
const len = meta.length;
while (idx < len) {
while (idx < len && isHorizontalSpace(meta.charCodeAt(idx))) {
idx += 1;
}
if (idx >= len) break;
let tokenEnd = idx;
while (tokenEnd < len && !isHorizontalSpace(meta.charCodeAt(tokenEnd))) {
tokenEnd += 1;
}
const token = meta.slice(idx, tokenEnd);
idx = tokenEnd;
if (token.length > 7 && token.slice(0, 7).toLowerCase() === "schema=") {
const candidate = token.slice(7).toLowerCase();
if (!SCHEMA_REF_REGEX.test(candidate)) return null;
try {
return parseSchemaRef(candidate);
} catch {
return null;
}
}
}
return null;
}
export interface ParsedFencedSchemaBlock {
block: SchemaBlock;
rawJson: string;
}
/**
* Parses a JSON code-fence payload into a `SchemaBlock` when valid.
*
* Supports:
* 1. Explicit fence metadata (` ```json schema=<name>@<version> `) with raw `data` object
* (or `{ schema, data }` envelope).
* 2. Envelope JSON (` ```json\n{ "schema": "<name>@<version>", "data": { ... } }\n``` `)
* emitted by `formatBlocksAsFencedJson`.
*
* Returns `null` when JSON is malformed, oversized, or not a schema object so callers
* fall back cleanly to standard code block rendering.
*/
export function parseJsonSchemaBlock(
rawCode: string,
explicitRef?: string | null,
): ParsedFencedSchemaBlock | null {
if (rawCode.length > MAX_SCHEMA_FENCE_BODY_CHARS) return null;
const trimmed = rawCode.trim();
if (!trimmed.startsWith("{")) return null;
let parsedRef: ParsedSchemaRef | null = null;
if (explicitRef) {
try {
parsedRef = parseSchemaRef(explicitRef.toLowerCase());
} catch {
return null;
}
} else if (!trimmed.includes('"schema"') || !trimmed.includes('"data"')) {
return null;
}
let parsedJson: unknown;
try {
parsedJson = JSON.parse(trimmed);
} catch {
return null;
}
if (!isPlainRecord(parsedJson)) return null;
if (parsedRef) {
const keys = Object.keys(parsedJson);
const isWrappedEnvelope =
keys.length === 2 &&
typeof parsedJson.schema === "string" &&
parsedJson.schema.trim().toLowerCase() === parsedRef.ref &&
isPlainRecord(parsedJson.data);
const data = isWrappedEnvelope ? (parsedJson.data as Record<string, unknown>) : parsedJson;
return {
block: {
schema: parsedRef.name,
version: parsedRef.version,
data,
},
rawJson: JSON.stringify(data, null, 2),
};
}
const keys = Object.keys(parsedJson);
if (
keys.length !== 2 ||
typeof parsedJson.schema !== "string" ||
!SCHEMA_REF_REGEX.test(parsedJson.schema.trim().toLowerCase()) ||
!isPlainRecord(parsedJson.data)
) {
return null;
}
try {
const envelopeRef = parseSchemaRef(parsedJson.schema.trim().toLowerCase());
return {
block: {
schema: envelopeRef.name,
version: envelopeRef.version,
data: parsedJson.data,
},
rawJson: JSON.stringify(parsedJson.data, null, 2),
};
} catch {
return null;
}
}
interface OpenMarkdownFence {
markerCode: number;
markerLen: number;
isJson: boolean;
meta: string | null;
bodyStart: number;
}
function matchFenceOpening(
markdown: string,
lineStart: number,
lineEnd: number,
bodyStart: number,
): OpenMarkdownFence | null {
let pos = lineStart;
while (pos < lineEnd && pos - lineStart < 3 && markdown.charCodeAt(pos) === 32) {
pos += 1;
}
if (pos >= lineEnd) return null;
const markerCode = markdown.charCodeAt(pos);
if (markerCode !== 96 && markerCode !== 126) return null;
let markerEnd = pos;
while (markerEnd < lineEnd && markdown.charCodeAt(markerEnd) === markerCode) {
markerEnd += 1;
}
const markerLen = markerEnd - pos;
if (markerLen < 3) return null;
// CommonMark: backtick fence info strings cannot contain backticks.
if (markerCode === 96) {
for (let idx = markerEnd; idx < lineEnd; idx += 1) {
if (markdown.charCodeAt(idx) === 96) return null;
}
}
let infoStart = markerEnd;
while (infoStart < lineEnd && isHorizontalSpace(markdown.charCodeAt(infoStart))) {
infoStart += 1;
}
let langEnd = infoStart;
while (langEnd < lineEnd && !isHorizontalSpace(markdown.charCodeAt(langEnd))) {
langEnd += 1;
}
const lang = markdown.slice(infoStart, langEnd).toLowerCase();
const isJson = lang === "json";
let meta: string | null = null;
if (isJson && langEnd < lineEnd) {
const rest = markdown.slice(langEnd, lineEnd).trim();
if (rest.length > 0 && rest.length <= MAX_FENCE_META_CHARS) {
meta = rest;
}
}
return {
markerCode,
markerLen,
isJson,
meta,
bodyStart,
};
}
function isMatchingFenceClose(
markdown: string,
lineStart: number,
lineEnd: number,
openFence: OpenMarkdownFence,
): boolean {
let pos = lineStart;
while (pos < lineEnd && pos - lineStart < 3 && markdown.charCodeAt(pos) === 32) {
pos += 1;
}
if (pos >= lineEnd || markdown.charCodeAt(pos) !== openFence.markerCode) {
return false;
}
let markerEnd = pos;
while (markerEnd < lineEnd && markdown.charCodeAt(markerEnd) === openFence.markerCode) {
markerEnd += 1;
}
if (markerEnd - pos < openFence.markerLen) {
return false;
}
for (let idx = markerEnd; idx < lineEnd; idx += 1) {
if (!isHorizontalSpace(markdown.charCodeAt(idx))) {
return false;
}
}
return true;
}
export interface ExtractedFencedSchemaBlocksResult {
blocks: SchemaBlock[];
truncated: boolean;
}
/**
* Single-pass O(N) CommonMark fence scanner with zero multi-line regexes or
* backreferences. Unterminated fences consume to EOF once without rescanning
* inner lines, ordinary non-schema JSON blocks do not consume the schema-parse
* budget, and truncated scans are flagged explicitly so callers do not confuse
* skipped content with a missing result block.
*/
export function extractFencedSchemaBlocksWithStatus(
markdown: string | null | undefined,
): ExtractedFencedSchemaBlocksResult {
if (!markdown) {
return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated: false };
}
let truncated = false;
let source = markdown;
if (markdown.length > MAX_SCANNED_MARKDOWN_CHARS) {
truncated = true;
const lastNewline = markdown.lastIndexOf("\n", MAX_SCANNED_MARKDOWN_CHARS - 1);
if (lastNewline === -1) {
return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated: true };
}
source = markdown.slice(0, lastNewline);
}
if (!source.includes("```") && !source.includes("~~~")) {
return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated };
}
const found: SchemaBlock[] = [];
let openFence: OpenMarkdownFence | null = null;
let parsedSchemaCandidates = 0;
let lineStart = 0;
const totalLen = source.length;
while (lineStart <= totalLen) {
const nlIdx = source.indexOf("\n", lineStart);
const rawLineEnd = nlIdx === -1 ? totalLen : nlIdx;
const lineEnd =
rawLineEnd > lineStart && source.charCodeAt(rawLineEnd - 1) === 13
? rawLineEnd - 1
: rawLineEnd;
const nextLineStart = nlIdx === -1 ? totalLen + 1 : nlIdx + 1;
if (openFence === null) {
openFence = matchFenceOpening(source, lineStart, lineEnd, nextLineStart);
} else if (isMatchingFenceClose(source, lineStart, lineEnd, openFence)) {
if (openFence.isJson) {
let bodyEnd = lineStart;
if (bodyEnd > openFence.bodyStart && source.charCodeAt(bodyEnd - 1) === 10) {
bodyEnd -= 1;
if (bodyEnd > openFence.bodyStart && source.charCodeAt(bodyEnd - 1) === 13) {
bodyEnd -= 1;
}
}
const bodyLen = bodyEnd - openFence.bodyStart;
const metaRef = parseSchemaFenceMeta(openFence.meta);
if (bodyLen > MAX_SCHEMA_FENCE_BODY_CHARS) {
if (metaRef) {
truncated = true;
}
} else if (bodyLen > 0) {
const rawBody = source.slice(openFence.bodyStart, bodyEnd);
const isCandidate =
Boolean(metaRef) ||
(rawBody.includes('"schema"') && rawBody.includes('"data"'));
if (isCandidate) {
if (parsedSchemaCandidates >= MAX_SCANNED_JSON_FENCES) {
truncated = true;
openFence = null;
break;
}
parsedSchemaCandidates += 1;
const parsed = parseJsonSchemaBlock(rawBody, metaRef?.ref ?? null);
if (parsed) {
found.push(parsed.block);
}
}
}
}
openFence = null;
}
lineStart = nextLineStart;
}
return { blocks: found, truncated };
}
export function extractFencedSchemaBlocks(markdown: string | null | undefined): SchemaBlock[] {
return extractFencedSchemaBlocksWithStatus(markdown).blocks;
}
export function getUnfencedSchemaBlocks(
markdown: string | null | undefined,
blocks: readonly SchemaBlock[] | null | undefined,
): readonly SchemaBlock[] {
if (!blocks || blocks.length === 0) return EMPTY_SCHEMA_BLOCKS;
if (!markdown || (!markdown.includes("```") && !markdown.includes("~~~"))) {
return blocks;
}
const fenced = extractFencedSchemaBlocks(markdown);
if (fenced.length === 0) return blocks;
const fencedKeys = new Set(fenced.map(canonicalSchemaBlockKey));
const remaining = blocks.filter((block) => !fencedKeys.has(canonicalSchemaBlockKey(block)));
return remaining.length > 0 ? remaining : EMPTY_SCHEMA_BLOCKS;
}
export type SchemaBlockMatchStatus = "matched" | "missing" | "unverified";
export function checkMatchingSchemaBlock(
schemaRef: string | null | undefined,
sources: {
schemaBlocks?: readonly SchemaBlock[] | null;
markdownBodies?: ReadonlyArray<string | null | undefined>;
commentSchemaBlocks?: ReadonlyArray<readonly SchemaBlock[] | null | undefined>;
},
): SchemaBlockMatchStatus {
if (!schemaRef) return "missing";
let target: ParsedSchemaRef;
try {
target = parseSchemaRef(schemaRef.trim().toLowerCase());
} catch {
return "missing";
}
const matches = (block: SchemaBlock) =>
block.schema.toLowerCase() === target.name && block.version === target.version;
if (sources.schemaBlocks?.some(matches)) return "matched";
if (sources.commentSchemaBlocks?.some((list) => list?.some(matches))) return "matched";
let anyTruncated = false;
if (sources.markdownBodies) {
for (const body of sources.markdownBodies) {
if (!body) continue;
const scanned = extractFencedSchemaBlocksWithStatus(body);
if (scanned.blocks.some(matches)) return "matched";
if (scanned.truncated) {
anyTruncated = true;
}
}
}
return anyTruncated ? "unverified" : "missing";
}
export function hasMatchingSchemaBlock(
schemaRef: string | null | undefined,
sources: {
schemaBlocks?: readonly SchemaBlock[] | null;
markdownBodies?: ReadonlyArray<string | null | undefined>;
commentSchemaBlocks?: ReadonlyArray<readonly SchemaBlock[] | null | undefined>;
},
): boolean {
return checkMatchingSchemaBlock(schemaRef, sources) === "matched";
}
export function safeHttpsUrl(raw: unknown): string | null {
if (typeof raw !== "string") return null;
const trimmed = raw.trim();
if (!trimmed) return null;
try {
const parsed = new URL(trimmed);
return parsed.protocol === "https:" ? parsed.toString() : null;
} catch {
return null;
}
}
+32 -24
View File
@@ -256,6 +256,7 @@ import {
} from "../lib/issue-output";
import { IssueSiblingNavigation } from "../components/IssueSiblingNavigation";
import type { MarkdownExternalReferenceMap } from "../components/MarkdownBody";
import { StandaloneSchemaBlockList } from "../components/SchemaBlockCard";
import { IssuesList } from "../components/IssuesList";
import { IssueReferenceActivitySummary } from "../components/IssueReferenceActivitySummary";
import { IssueFieldChangeReceipt } from "../components/IssueFieldChangeReceipt";
@@ -8309,30 +8310,36 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
/>
{taskChatShellEnabled ? null : (
<InlineEditor
value={issue.description ?? ""}
onSave={(description) => updateIssue.mutateAsync({ description })}
draftKey={`issue:${issue.id}:description`}
readCurrentValue={async () => (await issuesApi.getCore(issue.id, { cache: "no-store", fresh: true })).description ?? ""}
as="p"
className="text-sm leading-7 text-foreground"
placeholder="Add a description..."
multiline
foldable
mentions={mentionOptions}
externalReferences={
externalObjectsState.isEnabled
? externalObjectsState.markdownReferences
: undefined
}
imageUploadHandler={async (file) => {
const attachment = await uploadAttachment.mutateAsync(file);
return attachment.contentPath;
}}
onDropFile={async (file) => {
await uploadAttachment.mutateAsync(file);
}}
/>
<>
<InlineEditor
value={issue.description ?? ""}
onSave={(description) => updateIssue.mutateAsync({ description })}
draftKey={`issue:${issue.id}:description`}
readCurrentValue={async () => (await issuesApi.getCore(issue.id, { cache: "no-store", fresh: true })).description ?? ""}
as="p"
className="text-sm leading-7 text-foreground"
placeholder="Add a description..."
multiline
foldable
mentions={mentionOptions}
externalReferences={
externalObjectsState.isEnabled
? externalObjectsState.markdownReferences
: undefined
}
imageUploadHandler={async (file) => {
const attachment = await uploadAttachment.mutateAsync(file);
return attachment.contentPath;
}}
onDropFile={async (file) => {
await uploadAttachment.mutateAsync(file);
}}
/>
<StandaloneSchemaBlockList
markdown={issue.description}
schemaBlocks={issue.schemaBlocks}
/>
</>
)}
</div>
);
@@ -8796,6 +8803,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
onSave: (description) =>
updateIssue.mutateAsync({ description }),
mentions: mentionOptions,
schemaBlocks: issue.schemaBlocks,
externalReferences: externalObjectsState.isEnabled
? externalObjectsState.markdownReferences
: undefined,
@@ -0,0 +1,642 @@
import { useMemo, useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { useQueryClient } from "@tanstack/react-query";
import type { Issue, IssueComment } from "@paperclipai/shared";
import { CommentThread } from "@/components/CommentThread";
import { IssueProperties } from "@/components/IssueProperties";
import type { KvLabelMutationPayload } from "@/components/issue-properties";
import { MarkdownBody } from "@/components/MarkdownBody";
import { SchemaBlockCard } from "@/components/SchemaBlockCard";
import { Badge } from "@/components/ui/badge";
import { StatusIcon } from "@/components/StatusIcon";
import { queryKeys } from "@/lib/queryKeys";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
import {
storybookAgentMap,
storybookAgents,
storybookIssueLabels,
storybookIssues,
storybookProjects,
} from "../../fixtures/paperclipData";
const STORY_COMPANY_ID = "company-storybook";
const FIXED_LEASE_NOW_MS = new Date("2026-12-01T15:00:00.000Z").getTime();
const ACTIVE_LEASE_EXPIRES_AT = new Date(FIXED_LEASE_NOW_MS + 14 * 60_000).toISOString();
const EXPIRED_LEASE_AT = new Date(FIXED_LEASE_NOW_MS - 8 * 60_000).toISOString();
const baseTemplateIssue = storybookIssues[0]!;
const defaultProject = storybookProjects[0]!;
const workerAgent = storybookAgents[0]!;
function seedStaticQuery<T>(
queryClient: ReturnType<typeof useQueryClient>,
key: readonly unknown[],
value: T,
) {
queryClient.setQueryDefaults(key, {
queryFn: async () => value,
staleTime: Infinity,
});
queryClient.setQueryData(key, value);
}
function seedIssueSupportQueries(
queryClient: ReturnType<typeof useQueryClient>,
issue: Issue,
comments: IssueComment[] = [],
) {
seedStaticQuery(queryClient, queryKeys.issues.detail(issue.id), issue);
seedStaticQuery(queryClient, queryKeys.issues.documents(issue.id), []);
seedStaticQuery(queryClient, queryKeys.issues.document(issue.id, "plan"), null);
seedStaticQuery(queryClient, queryKeys.issues.acceptedPlanDecompositions(issue.id), []);
seedStaticQuery(queryClient, queryKeys.issues.attachments(issue.id), []);
seedStaticQuery(queryClient, queryKeys.issues.workProducts(issue.id), []);
seedStaticQuery(queryClient, queryKeys.issues.workProductPullRequestRefresh(issue.id), []);
seedStaticQuery(queryClient, queryKeys.issues.allRecoveryActions(issue.id), []);
seedStaticQuery(queryClient, queryKeys.issues.comments(issue.id), {
pages: [comments],
pageParams: [null],
});
seedStaticQuery(queryClient, queryKeys.issues.labels(STORY_COMPANY_ID), storybookIssueLabels);
seedStaticQuery(queryClient, queryKeys.agents.list(STORY_COMPANY_ID), storybookAgents);
seedStaticQuery(queryClient, queryKeys.projects.list(STORY_COMPANY_ID), storybookProjects);
seedStaticQuery(queryClient, queryKeys.access.companyUserDirectory(STORY_COMPANY_ID), {
users: [
{
principalId: "user-ada",
status: "active",
user: {
id: "user-ada",
email: "ada@paperclip.local",
name: "Ada",
image: null,
},
},
{
principalId: "user-julian",
status: "active",
user: {
id: "user-julian",
email: "julian@paperclip.local",
name: "julian",
image: null,
},
},
],
});
}
function applyStoryKvMutation(
current: Record<string, string>,
payload: KvLabelMutationPayload,
): Record<string, string> {
const next = { ...current };
for (const key of payload.delete ?? []) {
delete next[key];
}
for (const [key, value] of Object.entries(payload.set ?? {})) {
next[key] = value;
}
return next;
}
function makeStoryIssue(overrides: Partial<Issue>): Issue {
return {
...baseTemplateIssue,
id: "issue-structured-story",
companyId: STORY_COMPANY_ID,
identifier: "PAP-408",
issueNumber: 408,
projectId: defaultProject.id,
project: defaultProject,
assigneeAgentId: null,
assigneeUserId: null,
createdByAgentId: null,
createdByUserId: "user-ada",
createdByProfile: "lead",
status: "in_progress",
displayStatus: "in_progress",
priority: "high",
workMode: "standard",
reviewPolicy: null,
labels: [storybookIssueLabels[0]!],
labelIds: [storybookIssueLabels[0]!.id],
blockedBy: [],
blocks: [],
ancestors: [],
requestDepth: 0,
createdAt: new Date("2026-12-01T14:20:00.000Z"),
updatedAt: new Date("2026-12-01T14:56:00.000Z"),
...overrides,
};
}
function ChannelTaskPropertiesActiveLeaseScene() {
const queryClient = useQueryClient();
const [issue, setIssue] = useState<Issue>(() =>
makeStoryIssue({
id: "issue-channel-active-lease",
identifier: "PAP-412",
title: "Fix session cookie SameSite attribute on token refresh",
scope: "channel",
channelId: "channel-build-auth",
channelPath: "build/auth",
assigneeAgentId: workerAgent.id,
createdByUserId: "user-ada",
createdByProfile: "lead",
kvLabels: {
role: "worker",
env: "staging",
step: "fix",
},
resultSchemaRef: "test-report@1",
claimEpoch: 2,
claimAttemptCount: 1,
claimHolderProfile: "worker-1",
claimLeasedAt: new Date(FIXED_LEASE_NOW_MS - 60_000).toISOString(),
claimLeaseExpiresAt: ACTIVE_LEASE_EXPIRES_AT,
}),
);
seedIssueSupportQueries(queryClient, issue);
return (
<div className="min-h-screen bg-background p-6 text-foreground">
<div className="mx-auto flex max-w-4xl flex-col gap-6 md:flex-row md:items-start">
<div className="w-80 shrink-0 rounded-md border border-border bg-card p-4">
<IssueProperties
issue={issue}
onUpdate={(patch) => setIssue((prev) => ({ ...prev, ...(patch as Partial<Issue>) }))}
sidePanelContentOnly
contextUsage={null}
leaseNowMs={FIXED_LEASE_NOW_MS}
onUpdateKvLabels={(payload) => {
const nextLabels = applyStoryKvMutation(issue.kvLabels ?? {}, payload);
setIssue((prev) => ({ ...prev, kvLabels: nextLabels }));
return { kvLabels: nextLabels };
}}
/>
</div>
<div className="min-w-0 flex-1 space-y-3 rounded-md border border-border bg-muted/20 p-4">
<div className="flex items-center justify-between gap-2">
<div>
<div className="font-mono text-xs text-muted-foreground">{issue.identifier}</div>
<h2 className="text-base font-semibold text-foreground">{issue.title}</h2>
</div>
<Badge variant="outline" className="font-mono text-xs">
#build/auth
</Badge>
</div>
<p className="text-xs text-muted-foreground">
Click any <code className="font-mono">key=value</code> pill in the properties panel to edit its value, click <code className="font-mono">×</code> to remove, or click <code className="font-mono">+ Add</code> to append a new key-value via CAS mutation.
</p>
<div className="rounded-sm border border-border bg-background p-3">
<div className="mb-1.5 text-xs font-medium text-muted-foreground">
Live key-values state
</div>
<pre className="font-mono text-xs text-foreground">
{JSON.stringify(issue.kvLabels ?? {}, null, 2)}
</pre>
</div>
</div>
</div>
</div>
);
}
function ExpiredLeasePropertiesScene() {
const queryClient = useQueryClient();
const [expiredIssue, setExpiredIssue] = useState<Issue>(() =>
makeStoryIssue({
id: "issue-expired-lease",
identifier: "PAP-419",
title: "Audit stale OAuth refresh grants in worker pool",
status: "todo",
displayStatus: "todo",
scope: "agent",
channelId: null,
channelPath: null,
createdByUserId: "local-board",
createdByProfile: "triage-bot",
kvLabels: {
pool: "sec-audit",
retry_policy: "requeue",
},
resultSchemaRef: "finding@1",
claimEpoch: 3,
claimAttemptCount: 3,
claimHolderProfile: "scanner-2",
claimLeasedAt: new Date(FIXED_LEASE_NOW_MS - 23 * 60_000).toISOString(),
claimLeaseExpiresAt: EXPIRED_LEASE_AT,
}),
);
const [standardIssue, setStandardIssue] = useState<Issue>(() =>
makeStoryIssue({
id: "issue-standard-unset",
identifier: "PAP-420",
title: "Standard board task with unset channel, key-values, lease, and schema",
status: "todo",
displayStatus: "todo",
scope: "board",
channelId: null,
channelPath: null,
createdByUserId: "user-ada",
createdByProfile: null,
kvLabels: {},
resultSchemaRef: null,
claimEpoch: 0,
claimAttemptCount: 0,
claimHolderProfile: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
}),
);
seedIssueSupportQueries(queryClient, expiredIssue);
seedIssueSupportQueries(queryClient, standardIssue);
return (
<div className="min-h-screen bg-background p-6 text-foreground">
<div className="mx-auto grid max-w-5xl grid-cols-1 gap-6 md:grid-cols-2 md:items-start">
<div className="space-y-3">
<div className="rounded-md border border-border bg-muted/20 p-3">
<div className="font-mono text-xs text-muted-foreground">{expiredIssue.identifier}</div>
<h2 className="text-sm font-semibold text-foreground">{expiredIssue.title}</h2>
<p className="mt-1 text-xs text-muted-foreground">
Expired claim lease (<code className="font-mono">attempt 3</code>), read-only key-values, <code className="font-mono">finding@1</code> result schema, and profile attribution (<code className="font-mono">triage-bot (profile)</code>) — <code className="font-mono">Channel</code> is omitted because <code className="font-mono">channelPath</code> is unset.
</p>
</div>
<div className="w-80 rounded-md border border-border bg-card p-4">
<IssueProperties
issue={expiredIssue}
onUpdate={(patch) =>
setExpiredIssue((prev) => ({ ...prev, ...(patch as Partial<Issue>) }))
}
sidePanelContentOnly
contextUsage={null}
leaseNowMs={FIXED_LEASE_NOW_MS}
canEditKvLabels={false}
/>
</div>
</div>
<div className="space-y-3">
<div className="rounded-md border border-border bg-muted/20 p-3">
<div className="font-mono text-xs text-muted-foreground">{standardIssue.identifier}</div>
<h2 className="text-sm font-semibold text-foreground">{standardIssue.title}</h2>
<p className="mt-1 text-xs text-muted-foreground">
When <code className="font-mono">Channel</code>, <code className="font-mono">Key-values</code>, <code className="font-mono">Lease</code>, and <code className="font-mono">Result schema</code> are unset, none of those rows appear in the properties panel.
</p>
</div>
<div className="w-80 rounded-md border border-border bg-card p-4">
<IssueProperties
issue={standardIssue}
onUpdate={(patch) =>
setStandardIssue((prev) => ({ ...prev, ...(patch as Partial<Issue>) }))
}
sidePanelContentOnly
contextUsage={null}
leaseNowMs={FIXED_LEASE_NOW_MS}
/>
</div>
</div>
</div>
</div>
);
}
const SCHEMA_GALLERY_MARKDOWN = `### Security finding (\`finding@1\`)
\`\`\`json schema=finding@1
{
"severity": "high",
"category": "auth-cookie",
"title": "Refresh cookie omits SameSite=Lax on subdomain rotation",
"path": "server/src/routes/auth-refresh.ts",
"line": 142,
"summary": "Cross-site POST redirects can replay the pre-rotation refresh cookie during the 30-second grace window.",
"recommendation": "Set SameSite=Lax and HttpOnly=true on both primary and fallback refresh cookies."
}
\`\`\`
### Test execution summary (\`test-report@1\`)
\`\`\`json schema=test-report@1
{
"passed": false,
"total": 48,
"passedCount": 46,
"failed": 1,
"skipped": 1,
"durationMs": 2840,
"command": "pnpm --filter @paperclipai/server test auth-refresh",
"failures": [
{
"name": "rotates refresh token with SameSite=Lax on subdomain",
"message": "Expected Set-Cookie header to include SameSite=Lax"
}
]
}
\`\`\`
`;
const GIT_AND_PR_GALLERY_MARKDOWN = `### Commit receipt (\`git-commit@1\`)
\`\`\`json schema=git-commit@1
{
"sha": "9f3c2a184b7e6d051a22c98e41f0b3d7a6c5e812",
"branch": "fix/refresh-cookie-samesite",
"repo": "paperclipai/paperclip",
"message": "fix(auth): enforce SameSite=Lax on rotated refresh cookies",
"filesChanged": 3,
"insertions": 44,
"deletions": 9
}
\`\`\`
### Pull request receipt (\`pull-request@1\`)
\`\`\`json schema=pull-request@1
{
"number": 23341,
"state": "open",
"repo": "paperclipai/paperclip",
"title": "fix(auth): enforce SameSite=Lax on rotated refresh cookies",
"head": "fix/refresh-cookie-samesite",
"base": "master",
"url": "https://github.com/paperclipai/paperclip/pull/23341"
}
\`\`\`
`;
function BuiltInAndCustomSchemaBlocksScene() {
return (
<div className="min-h-screen bg-background p-6 text-foreground">
<div className="mx-auto max-w-6xl space-y-6">
<div>
<div className="font-mono text-xs uppercase tracking-wide text-muted-foreground">
Structured Schema Blocks
</div>
<h1 className="mt-1 text-xl font-semibold text-foreground">
Built-in and custom schema=&lt;name&gt;@&lt;version&gt; cards
</h1>
<p className="mt-1 text-sm text-muted-foreground">
Rendered directly through production <code className="font-mono text-xs">MarkdownBody</code> fences and <code className="font-mono text-xs">SchemaBlockCard</code> with interactive Structured / JSON inspection.
</p>
</div>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
<div className="rounded-md border border-border bg-card p-4">
<MarkdownBody>{SCHEMA_GALLERY_MARKDOWN}</MarkdownBody>
</div>
<div className="space-y-4 rounded-md border border-border bg-card p-4">
<MarkdownBody>{GIT_AND_PR_GALLERY_MARKDOWN}</MarkdownBody>
<div className="pt-1">
<MarkdownBody>{"### Custom company schema (`deploy-receipt@2`)"}</MarkdownBody>
<SchemaBlockCard
block={{
schema: "deploy-receipt",
version: 2,
data: {
environment: "staging-us-east-1",
releaseTag: "v2026.1201.4",
healthy: true,
canaryWeightPercent: 100,
verifiedEndpoints: [
"https://staging.paperclip.ing/api/health",
"https://staging.paperclip.ing/api/auth/get-session",
],
metrics: {
p95LatencyMs: 38,
errorRate: 0,
migratedTables: 2,
},
},
}}
/>
</div>
</div>
</div>
</div>
</div>
);
}
const END_TO_END_DESCRIPTION = `Investigate refresh-cookie rotation on \`#build/auth\` and attach a passing \`test-report@1\` block before closing the task.
- Verify \`SameSite=Lax\` and \`HttpOnly\` flags on token rotation
- Run the focused \`auth-refresh\` Vitest suite`;
function ChannelTaskThreadEndToEndScene() {
const queryClient = useQueryClient();
const userLabelMap = useMemo(
() =>
new Map<string, string>([
["user-ada", "Ada"],
["user-julian", "julian"],
]),
[],
);
const [comments, setComments] = useState<IssueComment[]>(() => [
{
id: "comment-channel-1",
companyId: STORY_COMPANY_ID,
issueId: "issue-channel-e2e",
authorType: "user",
authorAgentId: null,
authorUserId: "user-julian",
actorProfile: "claude",
kvLabels: {
phase: "triage",
severity: "high",
} as Record<string, string>,
body: `Isolated the cookie flag mismatch during subdomain token refresh:
\`\`\`json schema=finding@1
{
"severity": "high",
"title": "Fallback refresh cookie omits SameSite=Lax",
"path": "server/src/routes/auth-refresh.ts",
"line": 142,
"recommendation": "Apply SHARED_REFRESH_COOKIE_OPTIONS to both setCookie calls."
}
\`\`\``,
presentation: null,
metadata: null,
createdAt: new Date("2026-12-01T14:32:00.000Z"),
updatedAt: new Date("2026-12-01T14:32:00.000Z"),
},
{
id: "comment-channel-2",
companyId: STORY_COMPANY_ID,
issueId: "issue-channel-e2e",
authorType: "user",
authorAgentId: null,
authorUserId: "local-board",
actorProfile: "ci-bot",
kvLabels: {
status: "fixed",
suite: "auth",
} as Record<string, string>,
body: `Patched \`auth-refresh.ts\` and verified the full auth-refresh suite:
\`\`\`json schema=test-report@1
{
"passed": true,
"total": 48,
"failed": 0,
"skipped": 0,
"durationMs": 1920,
"command": "pnpm --filter @paperclipai/server test auth-refresh",
"summary": "All 48 assertions passed with SameSite=Lax enforced."
}
\`\`\``,
presentation: null,
metadata: null,
createdAt: new Date("2026-12-01T14:48:00.000Z"),
updatedAt: new Date("2026-12-01T14:48:00.000Z"),
},
]);
const [issue, setIssue] = useState<Issue>(() =>
makeStoryIssue({
id: "issue-channel-e2e",
identifier: "PAP-424",
title: "Harden refresh cookie flags across #build/auth worker pipeline",
description: END_TO_END_DESCRIPTION,
status: "in_review",
displayStatus: "in_review",
scope: "channel",
channelId: "channel-build-auth",
channelPath: "build/auth",
createdByUserId: "user-ada",
createdByProfile: "lead",
kvLabels: {
role: "scanner",
env: "staging",
status: "verified",
},
resultSchemaRef: "test-report@1",
claimEpoch: 1,
claimAttemptCount: 1,
claimHolderProfile: "scanner-1",
claimLeasedAt: new Date(FIXED_LEASE_NOW_MS - 3 * 60_000).toISOString(),
claimLeaseExpiresAt: ACTIVE_LEASE_EXPIRES_AT,
}),
);
seedIssueSupportQueries(queryClient, issue, comments);
return (
<div className="min-h-screen bg-background text-foreground">
<div className="mx-auto flex max-w-6xl flex-col lg:flex-row">
<main className="min-w-0 flex-1 space-y-5 p-6">
<header className="space-y-2 border-b border-border pb-4">
<div className="flex flex-wrap items-center gap-2">
<StatusIcon {...taskStatusIconProps(issue)} />
<span className="font-mono text-xs text-muted-foreground">{issue.identifier}</span>
<Badge variant="outline" className="font-mono text-xs font-normal">
#build/auth
</Badge>
<span className="text-xs text-muted-foreground">
Created by <span className="font-mono text-foreground">lead</span> via Ada
</span>
</div>
<h1 className="text-xl font-bold text-foreground">{issue.title}</h1>
</header>
<section className="rounded-md border border-border bg-card p-4">
<div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Description
</div>
<MarkdownBody className="text-sm">{issue.description ?? ""}</MarkdownBody>
</section>
<CommentThread
comments={comments}
agentMap={storybookAgentMap}
userLabelMap={userLabelMap}
currentUserId="user-ada"
companyId={STORY_COMPANY_ID}
projectId={defaultProject.id}
issueStatus={issue.status}
onAdd={async (body) => {
const now = new Date();
setComments((prev) => [
...prev,
{
id: `comment-channel-${prev.length + 1}`,
companyId: STORY_COMPANY_ID,
issueId: issue.id,
authorType: "user",
authorAgentId: null,
authorUserId: "user-ada",
body,
presentation: null,
metadata: null,
createdAt: now,
updatedAt: now,
},
]);
}}
/>
</main>
<aside className="w-full shrink-0 border-t border-border bg-card/40 p-5 lg:w-80 lg:border-l lg:border-t-0">
<IssueProperties
issue={issue}
onUpdate={(patch) => setIssue((prev) => ({ ...prev, ...(patch as Partial<Issue>) }))}
sidePanelContentOnly
contextUsage={null}
leaseNowMs={FIXED_LEASE_NOW_MS}
onUpdateKvLabels={(payload) => {
const nextLabels = applyStoryKvMutation(issue.kvLabels ?? {}, payload);
setIssue((prev) => ({ ...prev, kvLabels: nextLabels }));
return { kvLabels: nextLabels };
}}
/>
</aside>
</div>
</div>
);
}
const meta = {
id: "tasks-channels-leases-and-schemas",
title: "Tasks and conversations/Task creation and lifecycle/Channels, leases, and schemas",
parameters: {
layout: "fullscreen",
paperclip: {
capabilities: ["tasks/properties", "tasks/discussion"],
status: "current",
implementation: "production",
boundary: "fixtures",
notes: "Demonstrates channel provenance, key-values editing, claim lease indicators, result schema badges, profile attribution, and structured schema=<name>@<ver> block cards on existing task surfaces.",
},
},
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
export const ChannelTaskPropertiesActiveLease: Story = {
render: () => <ChannelTaskPropertiesActiveLeaseScene />,
};
export const ExpiredLeaseProperties: Story = {
render: () => <ExpiredLeasePropertiesScene />,
};
export const BuiltInAndCustomSchemaBlocks: Story = {
render: () => <BuiltInAndCustomSchemaBlocksScene />,
};
export const ChannelTaskThreadEndToEnd: Story = {
render: () => <ChannelTaskThreadEndToEndScene />,
};