diff --git a/docs/api/issues.md b/docs/api/issues.md index 370e5eed203..be23f2bcd13 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -62,6 +62,8 @@ endpoint for its instruction and related content. Company and private-task acces checks apply before results are returned. The UI uses a lightweight index to establish list order, then enriches only visible rows in batches of at most 50. +Full list responses (when `view` is omitted) also include `channelPath` (`string | null`), resolved from `channelId` when the issue belongs to a channel that the caller's scopes and channel membership allow reading (`null` when `channelId` is unset or inaccessible to the caller). Lightweight `index`, `rows`, and `compact` projections omit `channelPath`. Serialized issue responses never include `claimTokenHash`. + ## Navigation summaries `GET /api/companies/{companyId}/issues/summaries?ids={comma-separated UUIDs}` @@ -88,6 +90,8 @@ The response also includes: - `planDocument`: the full text of the issue document with key `plan`, when present - `documentSummaries`: metadata for all linked issue documents - `legacyPlanDocument`: a read-only fallback when the description still contains an old `` block +- `channelPath`: normalized channel path (`string | null`) on full detail, `view=core`, and `view=chat-bootstrap` responses when `channelId` is present and readable under the caller's headless scopes and channel access (`null` otherwise) +- headless coordination fields stored on the issue (`channelId`, `createdByProfile`, `kvLabels`, `schemaBlocks`, `resultSchemaRef`, `claimEpoch`, `claimHolderAgentId`, `claimHolderUserId`, `claimHolderProfile`, `claimLeasedAt`, `claimLeaseExpiresAt`, `claimAttemptCount`); `claimTokenHash` is internal lease verification material and is omitted from all serialized issue responses ## Create Issue @@ -129,7 +133,7 @@ When updating `executionPolicy`, you can also send `expectedExecutionPolicy` wit ### Update Response -Without a `Prefer` header, a successful update returns the full, updated issue row with two additive fields: +Without a `Prefer` header, a successful update returns the full, updated issue row (including resolved `channelPath` and omitting `claimTokenHash`) with two additive fields: - `changes`: a receipt containing only values that actually changed in the committed write - `comment`: the comment created by the optional `comment` input, or `null` diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 84699de7b12..1a01870cfda 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -48,6 +48,7 @@ import type { Goal } from "./goal.js"; import type { Project, ProjectWorkspace } from "./project.js"; import type { ExecutionWorkspace, IssueExecutionWorkspaceSettings } from "./workspace-runtime.js"; import type { IssueWorkProduct } from "./work-product.js"; +import type { SchemaBlock } from "../headless/schemas.js"; import type { LowTrustReviewPresetPolicy, SourceTrustMetadata, @@ -941,6 +942,9 @@ export interface Issue { id: string; companyId: string; projectId: string | null; + channelId?: string | null; + /** Resolved from channels when channelId is present and accessible to the caller. */ + channelPath?: string | null; projectWorkspaceId: string | null; goalId: string | null; parentId: string | null; @@ -970,7 +974,18 @@ export interface Issue { executionLockedAt: Date | null; createdByAgentId: string | null; createdByUserId: string | null; + createdByProfile?: string | null; responsibleUserId: string | null; + kvLabels?: Record; + schemaBlocks?: SchemaBlock[]; + resultSchemaRef?: string | null; + claimEpoch?: number; + claimHolderAgentId?: string | null; + claimHolderUserId?: string | null; + claimHolderProfile?: string | null; + claimLeasedAt?: Date | string | null; + claimLeaseExpiresAt?: Date | string | null; + claimAttemptCount?: number; issueNumber: number | null; identifier: string | null; originKind?: IssueOriginKind; @@ -1159,6 +1174,9 @@ export interface IssueComment { deletedByAgentId?: string | null; deletedByUserId?: string | null; deletedByRunId?: string | null; + actorProfile?: string | null; + kvLabels?: Record; + schemaBlocks?: SchemaBlock[]; sourceTrust?: SourceTrustMetadata | null; followUpRequested?: boolean; /** diff --git a/server/src/__tests__/fixtures/issue-detail-response.json b/server/src/__tests__/fixtures/issue-detail-response.json index cbf15dee791..2ff1c7d14b7 100644 --- a/server/src/__tests__/fixtures/issue-detail-response.json +++ b/server/src/__tests__/fixtures/issue-detail-response.json @@ -39,7 +39,6 @@ "schemaBlocks": [], "resultSchemaRef": null, "claimEpoch": 0, - "claimTokenHash": null, "claimHolderAgentId": null, "claimHolderUserId": null, "claimHolderProfile": null, @@ -290,5 +289,6 @@ } ], "externalChannelBinding": null, + "channelPath": null, "createdFrom": null } diff --git a/server/src/__tests__/headless-channels-schemas-batch.test.ts b/server/src/__tests__/headless-channels-schemas-batch.test.ts index 595136c60d7..bfadbf3c975 100644 --- a/server/src/__tests__/headless-channels-schemas-batch.test.ts +++ b/server/src/__tests__/headless-channels-schemas-batch.test.ts @@ -1149,4 +1149,182 @@ describeEmbeddedPostgres("headless channels, schemas, CAS labels, and batch DAG" }) .expect(400); }); + + it("9. exposes headless issue and comment fields on canonical /api/issues routes, gates channelPath on canAccessChannel, and never serializes claimTokenHash", async () => { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "authenticated", + resolveSession: async (req) => { + const uid = req.header("x-test-user-id"); + if (!uid) return null; + return { + session: { id: `sess-${uid}`, userId: uid }, + user: { id: uid, name: uid, email: `${uid}@example.test` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + app.use("/api", issueRoutes(db, { deploymentMode: "authenticated" } as any)); + app.use(errorHandler); + + const createdTask = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .set("x-paperclip-actor-profile", "lead") + .send({ + channel: "build/auth", + kind: "task", + text: "Verify SameSite=Lax refresh cookies", + labels: { role: "worker", env: "staging" }, + resultSchema: "test-report@1", + }) + .expect(201); + + const leaseExpiresAt = new Date("2099-01-01T00:15:00.000Z"); + await db + .update(issues) + .set({ + status: "in_progress", + claimEpoch: 2, + claimAttemptCount: 1, + claimTokenHash: "sha256:super-secret-claim-token-hash", + claimHolderProfile: "worker-1", + claimLeasedAt: new Date("2099-01-01T00:00:00.000Z"), + claimLeaseExpiresAt: leaseExpiresAt, + }) + .where(eq(issues.id, createdTask.body.id)); + + await request(app) + .post(`/api/issues/${createdTask.body.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .set("x-paperclip-actor-profile", "ci-bot") + .send({ + body: "All auth cookie checks passed.", + kvLabels: { status: "fixed" }, + blocks: [ + { + schema: "test-report", + version: 1, + data: { passed: true, total: 12, failed: 0 }, + }, + ], + }) + .expect(201); + + const detailRes = await request(app) + .get(`/api/issues/${createdTask.body.id}`) + .set("x-test-user-id", ownerUserId) + .set("sec-fetch-mode", "cors") + .expect(200); + + expect("claimTokenHash" in detailRes.body).toBe(false); + expect(JSON.stringify(detailRes.body)).not.toContain("super-secret-claim-token-hash"); + expect(detailRes.body.channelPath).toBe("build/auth"); + expect(detailRes.body.createdByProfile).toBe("lead"); + expect(detailRes.body.kvLabels).toEqual({ role: "worker", env: "staging" }); + expect(detailRes.body.resultSchemaRef).toBe("test-report@1"); + expect(detailRes.body.claimEpoch).toBe(2); + expect(detailRes.body.claimHolderProfile).toBe("worker-1"); + expect(detailRes.body.claimAttemptCount).toBe(1); + + // Direct canonical issueRoutes also gates channelPath on canAccessChannel and actor scopes + const canonicalOnlyApp = express(); + canonicalOnlyApp.use(express.json()); + canonicalOnlyApp.use( + actorMiddleware(db, { + deploymentMode: "authenticated", + resolveSession: async (req) => { + const uid = req.header("x-test-user-id"); + if (!uid) return null; + return { + session: { id: `sess-${uid}`, userId: uid }, + user: { id: uid, name: uid, email: `${uid}@example.test` }, + }; + }, + }), + ); + canonicalOnlyApp.use("/api", issueRoutes(db, { deploymentMode: "authenticated" } as any)); + canonicalOnlyApp.use(errorHandler); + + const scopedDetailRes = await request(canonicalOnlyApp) + .get(`/api/issues/${createdTask.body.id}`) + .set("x-test-user-id", peerUserId) + .set("x-paperclip-actor-scopes", JSON.stringify({ channels: ["ops/*"] })) + .expect(200); + expect(scopedDetailRes.body.channelPath).toBeNull(); + expect("claimTokenHash" in scopedDetailRes.body).toBe(false); + + // Private channel attached to an open issue resolves channelPath: null for non-member peer + const privChannelRes = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "sec/internal", visibility: "private" }) + .expect(201); + const [crossLinkedIssue] = await db + .insert(issues) + .values({ + companyId, + channelId: privChannelRes.body.id, + visibility: "open", + scope: "board", + title: "Board task referencing restricted channel", + status: "todo", + claimTokenHash: "sha256:another-secret-hash", + createdByUserId: ownerUserId, + }) + .returning(); + + // Non-member peer cannot read private-channel issue (404), while channel owner resolves channelPath cleanly + await request(canonicalOnlyApp) + .get(`/api/issues/${crossLinkedIssue!.id}`) + .set("x-test-user-id", peerUserId) + .expect(404); + + const ownerCrossRead = await request(app) + .get(`/api/issues/${crossLinkedIssue!.id}`) + .set("x-test-user-id", ownerUserId) + .set("sec-fetch-mode", "cors") + .expect(200); + expect(ownerCrossRead.body.channelPath).toBe("sec/internal"); + expect("claimTokenHash" in ownerCrossRead.body).toBe(false); + + // PATCH /api/issues/:id and GET /api/companies/:companyId/issues never serialize claimTokenHash + const patchRes = await request(app) + .patch(`/api/issues/${crossLinkedIssue!.id}`) + .set("x-test-user-id", ownerUserId) + .send({ priority: "high" }) + .expect(200); + expect("claimTokenHash" in patchRes.body).toBe(false); + expect(patchRes.body.channelPath).toBe("sec/internal"); + + const fullListRes = await request(app) + .get(`/api/companies/${companyId}/issues`) + .set("x-test-user-id", peerUserId) + .expect(200); + for (const row of fullListRes.body) { + expect("claimTokenHash" in row).toBe(false); + } + + // GET /api/issues/:id/comments returns actorProfile, kvLabels, and schemaBlocks + const commentsRes = await request(app) + .get(`/api/issues/${createdTask.body.id}/comments?order=asc`) + .set("x-test-user-id", ownerUserId) + .expect(200); + expect(commentsRes.body).toHaveLength(1); + expect(commentsRes.body[0].actorProfile).toBe("ci-bot"); + expect(commentsRes.body[0].kvLabels).toEqual({ status: "fixed" }); + expect(commentsRes.body[0].schemaBlocks).toEqual([ + { + schema: "test-report", + version: 1, + data: { passed: true, total: 12, failed: 0 }, + }, + ]); + }); }); diff --git a/server/src/__tests__/issue-activity-events-routes.test.ts b/server/src/__tests__/issue-activity-events-routes.test.ts index 87d9b34b854..da38a21aa57 100644 --- a/server/src/__tests__/issue-activity-events-routes.test.ts +++ b/server/src/__tests__/issue-activity-events-routes.test.ts @@ -436,6 +436,7 @@ describe("issue activity event routes", () => { "to": "high", }, }, + "channelPath": null, "comment": null, "companyId": "company-1", "createdByUserId": "local-board", diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 88c1262f205..27a29f6fb4e 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -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>( + row: T, + ): Omit { + if (!("claimTokenHash" in row)) { + return row as Omit; + } + const { claimTokenHash: _claimTokenHash, ...safe } = row as T & { + claimTokenHash?: unknown; + }; + return safe; + } + + async function resolveVisibleChannelPathsForIssues( + req: Request, + companyId: string, + rows: ReadonlyArray<{ channelId?: string | null }>, + ): Promise> { + 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>; + 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(); + 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 { + 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[0] & { id: string }>( + async function readIssueCore< + T extends Parameters[0] & { + id: string; + companyId: string; + channelId?: string | null; + }, + >( + req: Request, issue: T, time: (phase: "documents" | "work_products", read: () => Promise) => Promise = (_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>>) { 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. */ diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 92a6912ea27..fce18873a81 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -3434,13 +3434,15 @@ async function withIssueLabels( ]); return rows.map((row) => { const issueLabels = labelsByIssueId.get(row.id) ?? []; + const { claimTokenHash: _claimTokenHash, ...safeRow } = row as IssueRow & { + claimTokenHash?: unknown; + }; return { - ...row, - ...("claimTokenHash" in row ? { claimTokenHash: null } : {}), + ...safeRow, labels: issueLabels, labelIds: issueLabels.map((label) => label.id), watchdog: watchdogByIssueId.get(row.id) ?? null, - }; + } as unknown as IssueWithLabels; }); } @@ -7255,9 +7257,11 @@ export function issueService(db: Db) { return title.trim().replace(/\s+/g, " ").toLowerCase(); } + const { claimTokenHash: _claimTokenHashColumn, ...publicIssueColumns } = getTableColumns(issues); + async function getIssueByUuid(id: string) { const row = await retryIdempotentDatabaseOperation(() => db - .select({ ...getTableColumns(issues), claimTokenHash: sql`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) + .select({ ...publicIssueColumns, claimTokenHash: sql`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) .from(issues) .where(eq(issues.id, id)) .then((rows) => rows[0] ?? null)); @@ -7268,7 +7272,7 @@ export function issueService(db: Db) { async function getIssueByIdentifier(identifier: string) { const row = await retryIdempotentDatabaseOperation(() => db - .select({ ...getTableColumns(issues), claimTokenHash: sql`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) + .select({ ...publicIssueColumns, claimTokenHash: sql`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() }) .from(issues) .where(eq(issues.identifier, identifier.toUpperCase())) .then((rows) => rows[0] ?? null)); @@ -7440,6 +7444,8 @@ export function issueService(db: Db) { body: "", presentation: null, metadata: null, + ...("kvLabels" in comment ? { kvLabels: {} } : {}), + ...("schemaBlocks" in comment ? { schemaBlocks: [] } : {}), deletedAt, deletedByType: comment.deletedByType ?? null, deletedByAgentId: comment.deletedByAgentId ?? null, @@ -13133,7 +13139,10 @@ export function issueService(db: Db) { .returning() .then((rows) => rows[0] ?? null); }); - if (adopted) return adopted; + if (adopted) { + const [enriched] = await withIssueLabels(db, [adopted]); + return enriched; + } } if ( @@ -13774,6 +13783,8 @@ export function issueService(db: Db) { body: DELETED_ISSUE_COMMENT_BODY, presentation: null, metadata: null, + kvLabels: {}, + schemaBlocks: [], deletedAt: now, deletedByType: actor.actorType, deletedByAgentId: diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 7c0dc5a22fe..ca9e06e485d 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -462,7 +462,7 @@ "packages/shared/src/types/index.ts": "f8eedd126cf46462eed07976d2f9480ad9194428", "packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "84699de7b12622743914b66ce6d6d2c91220a64a", + "packages/shared/src/types/issue.ts": "1a01870cfda97510486c20425fabe7ac553460ac", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "99567f30af5165880d67519c1d9e71855600d4f9", diff --git a/ui/src/api/issues.test.ts b/ui/src/api/issues.test.ts index 26a2ddcd212..3bbb67e85df 100644 --- a/ui/src/api/issues.test.ts +++ b/ui/src/api/issues.test.ts @@ -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" }, + }); + }); +}); diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.ts index 89e8d1cf3e5..d83283ba9b0 100644 --- a/ui/src/api/issues.ts +++ b/ui/src/api/issues.ts @@ -828,6 +828,31 @@ export const issuesApi = { api.post(`/issues/${id}/access-grants/${grantId}/revoke`, {}), setVisibility: (id: string, visibility: IssueVisibility) => api.patch(`/issues/${id}`, { visibility }), + updateKvLabels: ( + id: string, + payload: { + set?: Record; + delete?: string[]; + unset?: string[]; + ifMatch?: Record; + if?: Record; + }, + ) => { + const body: { + set?: Record; + unset?: string[]; + if?: Record; + } = {}; + 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; cursor: string }>( + `/issues/${encodeURIComponent(id)}/kv-labels`, + body, + ); + }, listApprovals: (id: string) => api.get(`/issues/${id}/approvals`), linkApproval: (id: string, approvalId: string) => api.post(`/issues/${id}/approvals`, { approvalId }), diff --git a/ui/src/components/CommentStructuredMeta.tsx b/ui/src/components/CommentStructuredMeta.tsx new file mode 100644 index 00000000000..96969b82420 --- /dev/null +++ b/ui/src/components/CommentStructuredMeta.tsx @@ -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 ` comment attribution so profile-attributed comments + * render ` via ` (delegated human session) or + * `` + `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 | null; + userProfileMap?: ReadonlyMap | 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 ( + + {showAvatar ? ( + + + {initialsForProfile(attribution.profile)} + + + ) : null} + + {attribution.profile} + + {attribution.viaUserLabel ? ( + + via {attribution.viaUserLabel} + + ) : ( + + + )} + + ); +}); + +export const CommentKvLabelsBar = memo(function CommentKvLabelsBar({ + kvLabels, + className, +}: { + kvLabels?: Record | 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 ( +
+ {entries.map(([key, value]) => ( + + {key} + = + {value} + + ))} +
+ ); +}); diff --git a/ui/src/components/CommentThread.tsx b/ui/src/components/CommentThread.tsx index fe028369093..6df0298aa5c 100644 --- a/ui/src/components/CommentThread.tsx +++ b/ui/src/components/CommentThread.tsx @@ -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; issueStatus?: string; agentMap?: Map; + userLabelMap?: ReadonlyMap | null; currentUserId?: string | null; imageUploadHandler?: (file: File) => Promise; /** 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; + userLabelMap?: ReadonlyMap | 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 (
+ ) : profileAttribution ? ( + ) : ( - + )} {isQueued ? ( @@ -398,7 +421,11 @@ function CommentCard({ {isDeleted ? (
Comment deleted
) : ( - {comment.body} + <> + {comment.body} + + + )} {companyId && !isPending && !isDeleted ? (
@@ -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; + userLabelMap?: ReadonlyMap | 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({ ; @@ -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) + : 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 = ( {avatarUrl ? ( @@ -2145,9 +2169,13 @@ function IssueChatUserMessage({ isCurrentUser ? "justify-end" : "justify-start", )} > - - {resolvedAuthorName} - + {profileAttribution ? ( + + ) : ( + + {resolvedAuthorName} + + )} {followUpRequested ? ( + +
)}
@@ -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) + : 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({ ) : (
+ + {notices.length > 0 ? (
{notices.map((notice, index) => ( diff --git a/ui/src/components/MarkdownBody.tsx b/ui/src/components/MarkdownBody.tsx index b43b248d833..1957a027f23 100644 --- a/ui/src/components/MarkdownBody.tsx +++ b/ui/src/components/MarkdownBody.tsx @@ -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>(() => { - const plugins: NonNullable = [remarkGfm, remarkDropHtmlComments]; + const plugins: NonNullable = [ + remarkGfm, + remarkDropHtmlComments, + remarkSchemaCodeBlocks, + ]; if (enableWikiLinks) { plugins.push(createRemarkWikiLinks({ wikiLinkRoot, resolveWikiLinkHref })); } @@ -886,6 +947,10 @@ function MarkdownBodyImpl({ if (mermaidSource && mediaMode === "render") { return ; } + const schemaBlock = mediaMode === "render" ? extractSchemaBlockSource(preChildren) : null; + if (schemaBlock) { + return ; + } return {preChildren}; }, code: ({ node: _node, style: codeStyle, children: codeChildren, ...codeProps }) => ( diff --git a/ui/src/components/SchemaBlockCard.test.tsx b/ui/src/components/SchemaBlockCard.test.tsx new file mode 100644 index 00000000000..f0bb78f1430 --- /dev/null +++ b/ui/src/components/SchemaBlockCard.test.tsx @@ -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 }) => ( + {children} + ), + useCaseHref: () => () => "#", +})); + +let container: HTMLDivElement | null = null; +let root: Root | null = null; + +async function act(callback: () => void | Promise) { + if (typeof reactAct === "function") { + await reactAct(callback); + return; + } + let result: void | Promise = 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( + + + {node} + + , + ); + }); + 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({markdown}); + 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( + <> + {markdown} + + , + ); + + // 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( +
+ {fencedMd} + +
, + ); + 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 = { leaf: "alpha" }; + let deepNestedB: Record = { 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( +
+ + + +
, + ); + + 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", + ); + }); +}); diff --git a/ui/src/components/SchemaBlockCard.tsx b/ui/src/components/SchemaBlockCard.tsx new file mode 100644 index 00000000000..147885650b3 --- /dev/null +++ b/ui/src/components/SchemaBlockCard.tsx @@ -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 | 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 }) { + 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 ( +
+
+ + + {category ? ( + + {category} + + ) : null} + {cve ? ( + + {cve} + + ) : null} + {location ? ( + + + ) : null} +
+ +
{title}
+ + {summary ?

{summary}

: null} + {details ?

{details}

: null} + + {recommendation ? ( +
+ Recommendation: + {recommendation} +
+ ) : null} +
+ ); +} + +function TestReportCardBody({ data }: { data: Record }) { + 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 ( +
+
+
+ + {isPassed ? ( + + {command ? ( + + {command} + + ) : null} +
+ {duration ? ( + + + ) : null} +
+ + {passedCount !== null || failedCount !== null || skippedCount !== null || computedTotal !== null ? ( +
+
+
Passed
+
+ {passedCount ?? 0} +
+
+
+
Failed
+
0 ? "text-destructive" : "text-foreground", + )} + > + {failedCount ?? 0} +
+
+
+
Skipped
+
+ {skippedCount ?? 0} +
+
+
+
Total
+
+ {computedTotal ?? 0} +
+
+
+ ) : null} + + {summary ?

{summary}

: null} + + {failures.length > 0 ? ( +
+
+ Failing tests ({failures.length}) +
+
    + {failures.map((failure, idx) => ( +
  • +
    {failure.name}
    + {failure.message ? ( +
    {failure.message}
    + ) : null} +
  • + ))} +
+
+ ) : null} +
+ ); +} + +function GitCommitCardBody({ data }: { data: Record }) { + 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 ( +
+
+ + + {branch ? ( + + + ) : null} + {repo ? ( + {repo} + ) : null} +
+ + {subject ?
{subject}
: null} + {bodyText ? ( +
{bodyText}
+ ) : null} + + {filesChanged !== null || insertions !== null || deletions !== null ? ( +
+ {filesChanged !== null ? ( + + {filesChanged} {filesChanged === 1 ? "file" : "files"} changed + + ) : null} + {insertions !== null ? ( + +{insertions} + ) : null} + {deletions !== null ? ( + -{deletions} + ) : null} +
+ ) : null} +
+ ); +} + +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 }) { + 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 ( +
+
+
+ + + {repo ? {repo} : null} + {head ? ( + + + ) : null} +
+ {safeUrl ? ( + + Open PR + + ) : null} +
+ + {title ?
{title}
: null} + + {safeUrl ? ( + + {safeUrl} + + ) : rawUrl ? ( + {rawUrl} + ) : null} +
+ ); +} + +function CustomValueView({ value, depth = 0 }: { value: unknown; depth?: number }) { + if (value === null || value === undefined) { + return null; + } + if (typeof value === "boolean") { + return ( + + {value ? "true" : "false"} + + ); + } + if (typeof value === "number") { + return {String(value)}; + } + if (typeof value === "string") { + const safeUrl = safeHttpsUrl(value); + if (safeUrl) { + return ( + + {safeUrl} + + ); + } + 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 ( + + {value} + + ); + } + + if (depth >= 3) { + let serialized = "[Complex value]"; + try { + serialized = JSON.stringify(value); + } catch { + // Fall back to static label on non-serializable values. + } + return ( + + {serialized} + + ); + } + + if (Array.isArray(value)) { + if (value.length === 0) { + return []; + } + const allPrimitives = value.every( + (item) => + item === null || + typeof item === "string" || + typeof item === "number" || + typeof item === "boolean", + ); + if (allPrimitives) { + return ( +
+ {value.map((item, idx) => ( + + {String(item)} + + ))} +
+ ); + } + return ( +
+ {value.map((item, idx) => ( +
+ +
+ ))} +
+ ); + } + + if (isPlainRecord(value)) { + const entries = Object.entries(value).filter(([, entry]) => entry !== undefined); + if (entries.length === 0) { + return {"{}"}; + } + return ( +
0 && "rounded-sm border border-border/60 bg-muted/20 px-2.5 py-1", + )} + > + {entries.map(([key, entryValue]) => ( +
+
+ {key} +
+
+ +
+
+ ))} +
+ ); + } + + return {String(value)}; +} + +function renderSchemaBody(block: SchemaBlock) { + const ref = `${block.schema.toLowerCase()}@${block.version}`; + switch (ref) { + case "finding@1": + return ; + case "test-report@1": + return ; + case "git-commit@1": + return ; + case "pull-request@1": + return ; + default: + return ( +
+ +
+ ); + } +} + +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>(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 ( +
+
+
+
+ +
+
+ + +
+ {viewMode === "json" ? ( + + ) : null} +
+
+ + {viewMode === "json" ? ( +
+          {formattedJson}
+        
+ ) : ( + renderSchemaBody(block) + )} +
+ ); +}); + +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 ( +
+ {unfenced.map((block, idx) => ( + + ))} +
+ ); +}); diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsx index 86b1a97e246..a69b232820e 100644 --- a/ui/src/components/issue-properties/IssueProperties.tsx +++ b/ui/src/components/issue-properties/IssueProperties.tsx @@ -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 } | void> + | { kvLabels?: Record } + | 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} + + + + @@ -2658,6 +2685,13 @@ export function IssueProperties({ + agentName(id)} + resolveUserName={(id) => actualUserLabel(id)} + nowMs={leaseNowMs} + /> + {/* Read-only: agents set the policy, the board does not. */} {reviewPolicyBadge ? ( @@ -2956,7 +2990,13 @@ export function IssueProperties({ ) : null} - {originatingActor ? ( + {issue.createdByProfile?.trim() && !issue.createdByAgentId ? ( + + ) : originatingActor ? ( {originatingActor.kind === "agent" ? ( void | Promise) { + if (typeof reactAct === "function") { + await reactAct(callback); + return; + } + let result: void | Promise = 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({node}); + }); + 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( + <> + + + + + + , + ); + expect(dom.innerHTML).toBe(""); + }); +}); + +describe("IssueChannelRow", () => { + it("renders nothing when channelPath is absent (regardless of scope)", async () => { + const { container: dom } = await renderWithQuery( + , + ); + expect(dom.textContent).toBe(""); + }); + + it("renders only the single #channelPath badge without a redundant scope badge", async () => { + const { container: dom } = await renderWithQuery( + , + ); + 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( + { + 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( + 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( + , + ); + 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( + , + 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( + , + ); + 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( + , + ); + 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( + , + ); + 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( + , + ); + 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( + , + ); + 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( + <> + + + + , + 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( + <> + + + , + ); + + 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"); + }); +}); diff --git a/ui/src/components/issue-properties/structured-task-rows.tsx b/ui/src/components/issue-properties/structured-task-rows.tsx new file mode 100644 index 00000000000..73ac4b53c5f --- /dev/null +++ b/ui/src/components/issue-properties/structured-task-rows.tsx @@ -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; + delete?: string[]; + ifMatch?: Record; +} + +function scStyle(cssVar: string): CSSProperties { + return { "--sc": `var(${cssVar})` } as CSSProperties; +} + +function isCommentRecord( + value: unknown, +): value is Pick { + return ( + typeof value === "object" && + value !== null && + typeof (value as { body?: unknown }).body === "string" + ); +} + +export function unwrapCachedIssueComments( + data: unknown, +): Array> { + 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> = []; + 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> { + const refs = [issueId]; + const trimmedIdentifier = identifier?.trim(); + if (trimmedIdentifier && trimmedIdentifier !== issueId) { + refs.push(trimmedIdentifier); + } + + const seenIds = new Set(); + const collected: Array> = []; + + 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; +}) { + const channelPath = issue.channelPath?.trim().replace(/^#/, "") || null; + if (!channelPath) { + return null; + } + + return ( + + + + + ); +} + +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; + canEdit?: boolean; + onUpdateKvLabels?: ( + payload: KvLabelMutationPayload, + ) => + | Promise<{ kvLabels?: Record } | void> + | { kvLabels?: Record } + | void; +}) { + const queryClient = useQueryClient(); + const [labelsState, setLabelsState] = useState>( + () => issue.kvLabels ?? {}, + ); + const [adding, setAdding] = useState(false); + const [newKey, setNewKey] = useState(""); + const [newValue, setNewValue] = useState(""); + const [editingKey, setEditingKey] = useState(null); + const [editingValue, setEditingValue] = useState(""); + const [saving, setSaving] = useState(false); + const [errorMessage, setErrorMessage] = useState(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, + ): Promise => { + 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( + 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 ( + +
+ {entries.length > 0 ? ( +
+ {entries.map(([key, value]) => { + const editable = canEdit && !isReservedKvLabelKey(key); + const isEditingThis = editingKey === key; + + if (isEditingThis) { + return ( +
+ {key}= + 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}`} + /> + + +
+ ); + } + + return ( + + {editable ? ( + + ) : ( + <> + {key} + = + {value} + + )} + {editable ? ( + + ) : null} + + ); + })} + {canEdit && !adding ? ( + + ) : null} +
+ ) : null} + + {canEdit && adding ? ( +
+
+ 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}`} + /> + = + 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}`} + /> +
+
+ + +
+
+ ) : null} + + {errorMessage ? ( +

+ {errorMessage} +

+ ) : null} +
+
+ ); +} + +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(() => 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 ( + + + + + ); + } + + if (isTerminal) { + if (!holder) return null; + const terminalSummary = [ + `Released (${holder})`, + ...(epoch > 0 ? [`epoch ${epoch}`] : []), + ].join(" · "); + return ( + + + {terminalSummary} + + + ); + } + + const displayAttempt = Math.max(1, attemptCount || epoch || 1); + const expiredSummary = [ + "Expired", + ...(holder ? [holder] : []), + `attempt ${displayAttempt}`, + ].join(" · "); + + return ( + + + + + ); +} + +export function IssueResultSchemaRow({ + issue, + commentBodies, + commentSchemaBlocks, +}: { + issue: Pick< + Issue, + "id" | "status" | "resultSchemaRef" | "description" | "schemaBlocks" + > & { + identifier?: string | null; + }; + commentBodies?: ReadonlyArray; + commentSchemaBlocks?: ReadonlyArray; +}) { + 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 ( + +
+ + + {matchState === "matched" ? ( + + + ) : matchState === "unverified" ? ( + Scan limit reached + ) : issue.status === "done" ? ( + + + ) : ( + Awaiting result + )} +
+
+ ); +} + +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 ( + + + + {profile} + + {humanLabel ? ( + + via {humanLabel} + + ) : ( + + + )} + + + ); +} diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsx index 97b6ea1a0e8..668b8560487 100644 --- a/ui/src/components/task-chat/TaskChatBubble.tsx +++ b/ui/src/components/task-chat/TaskChatBubble.tsx @@ -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 && From {item.chatMessage.sourceTaskIdentifier} } - {isHuman && !item.isCurrentUser && item.authorName ? ( + {isHuman && !item.isCurrentUser && item.actorProfileAttribution ? ( + + + + ) : isHuman && !item.isCurrentUser && item.authorName ? ( @@ -326,6 +332,13 @@ function TaskChatBubbleContent({ > {bodyText} + + +
+ ) : item.schemaBlocks?.length || (item.kvLabels && Object.keys(item.kvLabels).length > 0) ? ( +
+ +
) : null} {!artifactsV1 && imageRefs.length > 0 ? ( diff --git a/ui/src/components/task-chat/TaskChatDescriptionBubble.tsx b/ui/src/components/task-chat/TaskChatDescriptionBubble.tsx index ae14917eb0e..570522549d2 100644 --- a/ui/src/components/task-chat/TaskChatDescriptionBubble.tsx +++ b/ui/src/components/task-chat/TaskChatDescriptionBubble.tsx @@ -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; mentions?: MentionOption[]; externalReferences?: MarkdownExternalReferenceMap; + schemaBlocks?: readonly SchemaBlock[] | null; imageUploadHandler?: (file: File) => Promise; onDropFile?: (file: File) => Promise; } @@ -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} +
{!isHuman ? ( diff --git a/ui/src/components/task-chat/task-chat-adapter.ts b/ui/src/components/task-chat/task-chat-adapter.ts index a1fbb70ffee..9f5b6bddaed 100644 --- a/ui/src/components/task-chat/task-chat-adapter.ts +++ b/ui/src/components/task-chat/task-chat-adapter.ts @@ -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", diff --git a/ui/src/components/task-chat/task-chat-model.ts b/ui/src/components/task-chat/task-chat-model.ts index f5b1b9c790d..6e587e21a8b 100644 --- a/ui/src/components/task-chat/task-chat-model.ts +++ b/ui/src/components/task-chat/task-chat-model.ts @@ -134,6 +134,9 @@ export interface TaskChatMessageItem { authorUserId?: string | null; authorAvatarUrl?: string | null; isCurrentUser?: boolean; + actorProfileAttribution?: import("../CommentStructuredMeta").ResolvedActorProfileAttribution | null; + kvLabels?: Record | null; + schemaBlocks?: readonly import("@paperclipai/shared").SchemaBlock[] | null; text: string; /** Runner-authored output channel. Legacy adapters leave this unset. */ channel?: "progress" | "final" | "unknown"; diff --git a/ui/src/lib/issue-chat-human-author.ts b/ui/src/lib/issue-chat-human-author.ts index 6077844bb20..f6feba374e4 100644 --- a/ui/src/lib/issue-chat-human-author.ts +++ b/ui/src/lib/issue-chat-human-author.ts @@ -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 | 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), }; } diff --git a/ui/src/lib/issue-chat-messages.ts b/ui/src/lib/issue-chat-messages.ts index 3c354df4601..823edf23806 100644 --- a/ui/src/lib/issue-chat-messages.ts +++ b/ui/src/lib/issue-chat-messages.ts @@ -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, diff --git a/ui/src/lib/schema-block-utils.ts b/ui/src/lib/schema-block-utils.ts new file mode 100644 index 00000000000..475ff78539c --- /dev/null +++ b/ui/src/lib/schema-block-utils.ts @@ -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 { + 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(); + 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=@ `) with raw `data` object + * (or `{ schema, data }` envelope). + * 2. Envelope JSON (` ```json\n{ "schema": "@", "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) : 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; + commentSchemaBlocks?: ReadonlyArray; + }, +): 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; + commentSchemaBlocks?: ReadonlyArray; + }, +): 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; + } +} diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index d69d33d922f..04df27f03ad 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -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 : ( - 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); - }} - /> + <> + 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); + }} + /> + + )} ); @@ -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, diff --git a/ui/storybook/stories/tasks/channels-leases-and-schemas.stories.tsx b/ui/storybook/stories/tasks/channels-leases-and-schemas.stories.tsx new file mode 100644 index 00000000000..03bd85e488e --- /dev/null +++ b/ui/storybook/stories/tasks/channels-leases-and-schemas.stories.tsx @@ -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( + queryClient: ReturnType, + key: readonly unknown[], + value: T, +) { + queryClient.setQueryDefaults(key, { + queryFn: async () => value, + staleTime: Infinity, + }); + queryClient.setQueryData(key, value); +} + +function seedIssueSupportQueries( + queryClient: ReturnType, + 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, + payload: KvLabelMutationPayload, +): Record { + 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 { + 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(() => + 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 ( +
+
+
+ setIssue((prev) => ({ ...prev, ...(patch as Partial) }))} + sidePanelContentOnly + contextUsage={null} + leaseNowMs={FIXED_LEASE_NOW_MS} + onUpdateKvLabels={(payload) => { + const nextLabels = applyStoryKvMutation(issue.kvLabels ?? {}, payload); + setIssue((prev) => ({ ...prev, kvLabels: nextLabels })); + return { kvLabels: nextLabels }; + }} + /> +
+ +
+
+
+
{issue.identifier}
+

{issue.title}

+
+ + #build/auth + +
+

+ Click any key=value pill in the properties panel to edit its value, click × to remove, or click + Add to append a new key-value via CAS mutation. +

+
+
+ Live key-values state +
+
+              {JSON.stringify(issue.kvLabels ?? {}, null, 2)}
+            
+
+
+
+
+ ); +} + +function ExpiredLeasePropertiesScene() { + const queryClient = useQueryClient(); + const [expiredIssue, setExpiredIssue] = useState(() => + 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(() => + 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 ( +
+
+
+
+
{expiredIssue.identifier}
+

{expiredIssue.title}

+

+ Expired claim lease (attempt 3), read-only key-values, finding@1 result schema, and profile attribution (triage-bot (profile)) — Channel is omitted because channelPath is unset. +

+
+
+ + setExpiredIssue((prev) => ({ ...prev, ...(patch as Partial) })) + } + sidePanelContentOnly + contextUsage={null} + leaseNowMs={FIXED_LEASE_NOW_MS} + canEditKvLabels={false} + /> +
+
+ +
+
+
{standardIssue.identifier}
+

{standardIssue.title}

+

+ When Channel, Key-values, Lease, and Result schema are unset, none of those rows appear in the properties panel. +

+
+
+ + setStandardIssue((prev) => ({ ...prev, ...(patch as Partial) })) + } + sidePanelContentOnly + contextUsage={null} + leaseNowMs={FIXED_LEASE_NOW_MS} + /> +
+
+
+
+ ); +} + +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 ( +
+
+
+
+ Structured Schema Blocks +
+

+ Built-in and custom schema=<name>@<version> cards +

+

+ Rendered directly through production MarkdownBody fences and SchemaBlockCard with interactive Structured / JSON inspection. +

+
+ +
+
+ {SCHEMA_GALLERY_MARKDOWN} +
+ +
+ {GIT_AND_PR_GALLERY_MARKDOWN} +
+ {"### Custom company schema (`deploy-receipt@2`)"} + +
+
+
+
+
+ ); +} + +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([ + ["user-ada", "Ada"], + ["user-julian", "julian"], + ]), + [], + ); + + const [comments, setComments] = useState(() => [ + { + 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, + 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, + 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(() => + 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 ( +
+
+
+
+
+ + {issue.identifier} + + #build/auth + + + Created by lead via Ada + +
+

{issue.title}

+
+ +
+
+ Description +
+ {issue.description ?? ""} +
+ + { + 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, + }, + ]); + }} + /> +
+ + +
+
+ ); +} + +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=@ block cards on existing task surfaces.", + }, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const ChannelTaskPropertiesActiveLease: Story = { + render: () => , +}; + +export const ExpiredLeaseProperties: Story = { + render: () => , +}; + +export const BuiltInAndCustomSchemaBlocks: Story = { + render: () => , +}; + +export const ChannelTaskThreadEndToEnd: Story = { + render: () => , +};