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

+130 -17
View File
@@ -89,6 +89,7 @@ import {
chatConversations,
chatEndpoints,
chatPublications,
channels,
companyMemberships,
documents,
executionWorkspaces,
@@ -246,6 +247,10 @@ import {
workProductService,
} from "../services/index.js";
import { parseScopeFilter } from "../services/issue-visibility.js";
import {
findInaccessibleChannelIds,
resolveHeadlessActor,
} from "../services/headless-common.js";
import {
runnerGoalService,
RunnerGoalActionError,
@@ -8507,16 +8512,108 @@ export function issueRoutes(
res.json(summaries);
});
function stripIssueClaimTokenHash<T extends Record<string, unknown>>(
row: T,
): Omit<T, "claimTokenHash"> {
if (!("claimTokenHash" in row)) {
return row as Omit<T, "claimTokenHash">;
}
const { claimTokenHash: _claimTokenHash, ...safe } = row as T & {
claimTokenHash?: unknown;
};
return safe;
}
async function resolveVisibleChannelPathsForIssues(
req: Request,
companyId: string,
rows: ReadonlyArray<{ channelId?: string | null }>,
): Promise<Map<string, string>> {
const channelIds = [
...new Set(
rows
.map((row) => row.channelId)
.filter((id): id is string => typeof id === "string" && id.length > 0),
),
];
if (channelIds.length === 0) {
return new Map();
}
const channelRows = await db
.select({
id: channels.id,
companyId: channels.companyId,
path: channels.path,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(
and(eq(channels.companyId, companyId), inArray(channels.id, channelIds)),
);
if (channelRows.length === 0) {
return new Map();
}
let headlessActor: Awaited<ReturnType<typeof resolveHeadlessActor>>;
try {
headlessActor = await resolveHeadlessActor(db, req, companyId, {
requiredAction: "read",
});
} catch {
return new Map();
}
const inaccessibleIds = new Set(
await findInaccessibleChannelIds(db, companyId, headlessActor, channelRows),
);
const visible = new Map<string, string>();
for (const channel of channelRows) {
if (!inaccessibleIds.has(channel.id)) {
visible.set(channel.id, channel.path);
}
}
return visible;
}
async function resolveVisibleChannelPathForIssue(
req: Request,
issue: { companyId: string; channelId?: string | null },
): Promise<string | null> {
if (!issue.channelId) return null;
const paths = await resolveVisibleChannelPathsForIssues(
req,
issue.companyId,
[issue],
);
return paths.get(issue.channelId) ?? null;
}
/** `GET /issues/:id?view=core`, shared with the chat bootstrap. */
async function readIssueCore<T extends Parameters<typeof documentsSvc.getIssueDocumentPayload>[0] & { id: string }>(
async function readIssueCore<
T extends Parameters<typeof documentsSvc.getIssueDocumentPayload>[0] & {
id: string;
companyId: string;
channelId?: string | null;
},
>(
req: Request,
issue: T,
time: <R>(phase: "documents" | "work_products", read: () => Promise<R>) => Promise<R> = (_phase, read) => read(),
) {
const [documentPayload, workProducts] = await Promise.all([
const [documentPayload, workProducts, channelPath] = await Promise.all([
time("documents", () => documentsSvc.getIssueDocumentPayload(issue)),
time("work_products", () => workProductsSvc.listForIssue(issue.id)),
resolveVisibleChannelPathForIssue(req, issue),
]);
return { ...issue, ...documentPayload, workProducts };
return {
...stripIssueClaimTokenHash(issue),
...documentPayload,
workProducts,
channelPath,
};
}
/**
@@ -8578,7 +8675,7 @@ export function issueRoutes(
async function readChatBootstrapPayload(req: Request, issue: NonNullable<Awaited<ReturnType<typeof svc.getById>>>) {
const viewerUserId = req.actor.type === "board" ? getActorInfo(req).actorId : null;
const [issueCore, recentCommentsAndFacts, recentActivity, recentRuns, interactions, attachments, liveRuns, activeRun] = await Promise.all([
readIssueCore(issue),
readIssueCore(req, issue),
readRecentComments(issue).then(async (recentComments) => ({
recentComments,
// `/activity?view=comment-inputs` for the saved recent comments, as the chat requests them.
@@ -8689,9 +8786,10 @@ export function issueRoutes(
pagination,
};
}
const [handoffStates, recoveryActionByIssue] = await Promise.all([
const [handoffStates, recoveryActionByIssue, channelPaths] = await Promise.all([
listSuccessfulRunHandoffStates(db, companyId, issueIds),
recoveryActionsSvc.listActiveForIssues(companyId, issueIds),
resolveVisibleChannelPathsForIssues(req, companyId, result),
]);
const actor = getActorInfo(req);
await Promise.all(
@@ -8712,7 +8810,8 @@ export function issueRoutes(
return {
kind: "full",
body: result.map((issue) => ({
...issue,
...stripIssueClaimTokenHash(issue),
channelPath: issue.channelId ? (channelPaths.get(issue.channelId) ?? null) : null,
successfulRunHandoff: handoffStates.get(issue.id) ?? null,
activeRecoveryAction: recoveryActionByIssue.get(issue.id) ?? null,
interruption: interruptions.get(issue.id) ?? null,
@@ -9865,7 +9964,7 @@ export function issueRoutes(
// projection before first paint, independently of slow recovery, workspace
// and related-task enrichment. This never refreshes external providers.
if (req.query.view === "core") {
const core = await readIssueCore(issue, timing.time);
const core = await readIssueCore(req, issue, timing.time);
await recordAgentChildTaskRead(db, req, issue);
res.setHeader("Server-Timing", timing.header());
res.json(core);
@@ -9888,7 +9987,7 @@ export function issueRoutes(
scheduledRetry,
activeRecoveryAction,
inboxArchiveFields,
externalChannelBinding,
{ externalChannelBinding, channelPath },
currentExecutionWorkspace,
workProducts,
createdFrom,
@@ -9909,7 +10008,13 @@ export function issueRoutes(
timing.time("retry", () => svc.getCurrentScheduledRetry(issue.id, { companyId: issue.companyId })),
timing.time("recovery", () => recoveryActionsSvc.getActiveForIssue(issue.companyId, issue.id)),
inboxArchiveFieldsPromise,
timing.time("channel", () => getExternalChannelBindingSummary(db, issue.companyId, issue.id)),
timing.time("channel", async () => {
const [binding, resolvedPath] = await Promise.all([
getExternalChannelBindingSummary(db, issue.companyId, issue.id),
resolveVisibleChannelPathForIssue(req, issue),
]);
return { externalChannelBinding: binding, channelPath: resolvedPath };
}),
timing.time("workspace", () => issue.executionWorkspaceId
? executionWorkspacesSvc.getStoredById(issue.companyId, issue.executionWorkspaceId, { includeRuntimeServices: true })
: Promise.resolve(null)),
@@ -9951,7 +10056,7 @@ export function issueRoutes(
await recordAgentChildTaskRead(db, req, issue);
res.setHeader("Server-Timing", timing.header());
res.json({
...issue,
...stripIssueClaimTokenHash(issue),
...inboxArchiveFields,
goalId: goal?.id ?? issue.goalId,
ancestors,
@@ -9975,6 +10080,7 @@ export function issueRoutes(
currentExecutionWorkspace: compactIssueExecutionWorkspace(currentExecutionWorkspace),
workProducts,
externalChannelBinding,
channelPath,
createdFrom,
});
});
@@ -13567,7 +13673,7 @@ export function issueRoutes(
const referenceSummary = await issueReferencesSvc.listIssueReferenceSummary(issue.id);
const visibleReferenceSummary = await redactIssueReferenceEdges(req, companyId, referenceSummary);
res.status(200).json({
...issue,
...stripIssueClaimTokenHash(issue),
deduplicated: true,
deduplicationReason,
relatedWork: visibleReferenceSummary,
@@ -13765,7 +13871,7 @@ export function issueRoutes(
const visibleReferenceSummary = await redactIssueReferenceEdges(req, companyId, referenceSummary);
res.status(201).json({
...issue,
...stripIssueClaimTokenHash(issue),
relatedWork: visibleReferenceSummary,
referencedIssueIdentifiers: visibleReferenceSummary.outbound.map((item) => item.issue.identifier ?? item.issue.id),
});
@@ -17319,7 +17425,14 @@ export function issueRoutes(
});
return;
}
res.json({ ...issueResponse, changes, comment, ...(parentAdjusted ? { parentAdjusted } : {}) });
const updatedChannelPath = await resolveVisibleChannelPathForIssue(req, issue);
res.json({
...stripIssueClaimTokenHash(issueResponse),
channelPath: updatedChannelPath,
changes,
comment,
...(parentAdjusted ? { parentAdjusted } : {}),
});
},
);
@@ -17383,7 +17496,7 @@ export function issueRoutes(
});
await queueTaskWatchdogEvaluation(existing, actor.runId);
res.json(issue);
res.json(stripIssueClaimTokenHash(issue));
});
router.post(
@@ -17537,7 +17650,7 @@ export function issueRoutes(
);
}
res.json(updated);
res.json(updated ? stripIssueClaimTokenHash(updated) : updated);
},
);
@@ -17578,7 +17691,7 @@ export function issueRoutes(
details: { status: released.status, _previous: { status: existing.status } },
});
res.json(released);
res.json(stripIssueClaimTokenHash(released));
});
router.post("/issues/:id/admin/force-release", async (req, res) => {
@@ -17623,7 +17736,7 @@ export function issueRoutes(
},
});
res.json(result);
res.json({ ...result, issue: stripIssueClaimTokenHash(result.issue) });
});
/** `GET /issues/:id/recent-comments`, shared with the chat bootstrap. */