Add company artifacts page (#7621)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators need a way to inspect files and work products created by agents across a company without opening each issue one by one. > - The existing issue detail surfaces already show attachments and outputs, but there was no company-level artifacts index or search-result affordance for artifact-like records. > - The backend needed a company-scoped artifacts projection API that preserves issue/run attribution and safe links back to source records. > - The UI needed a first-class Artifacts page, sidebar entry, reusable artifact cards, and deep-link handling that keeps company prefixes intact. > - This pull request adds the company artifacts API and page, then wires artifacts into search and issue output surfaces. > - The benefit is a single place to browse, filter, and open generated work products and attachments while preserving company boundaries. ## Linked Issues or Issue Description Fixes #7622. Feature request fields: - Problem/motivation: company operators need a consolidated artifacts surface for attachments and work products produced by agents. - Proposed solution: add a company-scoped artifacts projection endpoint, a board Artifacts route, reusable cards, sidebar navigation, and artifact search integration. - Alternatives considered: keep artifact discovery only on individual issue pages; that forces operators to know the source issue before finding generated outputs. - Roadmap alignment: checked `ROADMAP.md`; this is a focused board UI/API improvement and does not duplicate a listed roadmap item. ## What Changed - Added shared artifact types and validators. - Added a company-scoped artifact projection service/API with tests for attachment/work-product attribution. - Added Artifacts board UI route, API client, sidebar link, cards, filters, and storybook coverage. - Added artifact result handling to company search and issue output/deep-link flows. - Rebased the branch onto the latest `public-gh/master` state and resolved the route-test conflict by preserving both upstream team-catalog coverage and artifact route coverage. - Fixed a local Sidebar test helper so it no longer depends on a runtime-undefined `React.act` export in this dependency install. ## Verification - `pnpm --filter @paperclipai/ui exec vitest run src/components/artifacts/ArtifactCard.test.tsx src/api/artifacts.test.ts src/lib/company-routes.test.ts` - `pnpm --filter @paperclipai/ui exec vitest run src/pages/Artifacts.test.tsx src/pages/Search.test.tsx src/components/Sidebar.test.tsx` - `pnpm exec vitest run server/src/__tests__/company-artifacts-service.test.ts server/src/__tests__/company-search-service.test.ts server/src/__tests__/company-search-rate-limit-routes.test.ts server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts` - Confirmed the PR diff does not include `pnpm-lock.yaml` or `.github/workflows/*`. - Duplicate search: no open PRs or issues found for `artifact page ArtifactCard` in `paperclipai/paperclip`. Screenshots are intentionally omitted per the internal task instruction not to add design screenshots or images to this PR unless they are specifically part of the work. I also attempted browser capture in this runner, but `agent-browser` failed to launch Chrome and Playwright Chromium is missing `libatk-1.0.so.0`. ## Risks - Low-to-medium risk: this adds a new API projection and UI surface, so attribution/link regressions could affect artifact navigation. - Company scoping is covered in the new service/API tests. - No database migrations are included. - No lockfile or workflow changes are included. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex, GPT-5 coding agent with tool use and local command execution. Exact hosted model identifier is not exposed in this runtime. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] If this change affects the UI, I have included before/after screenshots (intentionally omitted per task instruction; browser capture unavailable in this runner) - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
@@ -19,6 +19,9 @@ vi.mock("../services/index.js", () => ({
|
||||
previewImport: vi.fn(),
|
||||
importBundle: vi.fn(),
|
||||
}),
|
||||
companyArtifactsService: () => ({
|
||||
list: vi.fn(),
|
||||
}),
|
||||
accessService: () => ({
|
||||
canUser: vi.fn(),
|
||||
ensureMembership: vi.fn(),
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
import { Readable } from "node:stream";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
assets,
|
||||
companies,
|
||||
createDb,
|
||||
documents,
|
||||
heartbeatRuns,
|
||||
issueAttachments,
|
||||
issueComments,
|
||||
issueDocuments,
|
||||
issues,
|
||||
issueWorkProducts,
|
||||
projects,
|
||||
} from "@paperclipai/db";
|
||||
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { companyRoutes } from "../routes/companies.js";
|
||||
import { companyArtifactsService } from "../services/company-artifacts.js";
|
||||
import type { StorageService } from "../storage/types.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
if (!embeddedPostgresSupport.supported) {
|
||||
console.warn(
|
||||
`Skipping embedded Postgres company artifacts tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
||||
);
|
||||
}
|
||||
|
||||
function createStorageService(files: Record<string, Buffer> = {}): StorageService {
|
||||
return {
|
||||
provider: "local_disk",
|
||||
putFile: vi.fn(),
|
||||
getObject: vi.fn(async (_companyId, objectKey, options) => {
|
||||
const body = files[objectKey] ?? Buffer.alloc(0);
|
||||
const range = options?.range;
|
||||
const ranged = range ? body.subarray(range.start, range.end + 1) : body;
|
||||
return {
|
||||
stream: Readable.from(ranged),
|
||||
contentType: "text/plain",
|
||||
contentLength: ranged.length,
|
||||
};
|
||||
}),
|
||||
headObject: vi.fn(),
|
||||
deleteObject: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describeEmbeddedPostgres("companyArtifactsService", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-company-artifacts-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 20_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(issueWorkProducts);
|
||||
await db.delete(issueAttachments);
|
||||
await db.delete(assets);
|
||||
await db.delete(issueComments);
|
||||
await db.delete(issueDocuments);
|
||||
await db.delete(documents);
|
||||
await db.delete(heartbeatRuns);
|
||||
await db.delete(issues);
|
||||
await db.delete(projects);
|
||||
await db.delete(agents);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
async function seedArtifacts() {
|
||||
const companyId = "11111111-1111-4111-8111-111111111111";
|
||||
const otherCompanyId = "22222222-2222-4222-8222-222222222222";
|
||||
const agentId = "33333333-3333-4333-8333-333333333333";
|
||||
const otherAgentId = "44444444-4444-4444-8444-444444444444";
|
||||
const projectId = "55555555-5555-4555-8555-555555555555";
|
||||
const issueId = "66666666-6666-4666-8666-666666666666";
|
||||
const secondIssueId = "77777777-7777-4777-8777-777777777777";
|
||||
const otherIssueId = "88888888-8888-4888-8888-888888888888";
|
||||
const runId = "99999999-9999-4999-8999-999999999999";
|
||||
const otherRunId = "19191919-1919-4191-8191-191919191919";
|
||||
const directAttachmentId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
const workProductAttachmentId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||
|
||||
await db.insert(companies).values([
|
||||
{ id: companyId, name: "Paperclip", issuePrefix: "PAP", requireBoardApprovalForNewAgents: false },
|
||||
{ id: otherCompanyId, name: "OtherCo", issuePrefix: "OTH", requireBoardApprovalForNewAgents: false },
|
||||
]);
|
||||
await db.insert(agents).values([
|
||||
{ id: agentId, companyId, name: "Coder", role: "engineer" },
|
||||
{ id: otherAgentId, companyId: otherCompanyId, name: "Other", role: "engineer" },
|
||||
]);
|
||||
await db.insert(projects).values({ id: projectId, companyId, name: "Artifacts", status: "in_progress" });
|
||||
await db.insert(issues).values([
|
||||
{
|
||||
id: issueId,
|
||||
companyId,
|
||||
projectId,
|
||||
identifier: "PAP-1",
|
||||
title: "Make the reel",
|
||||
status: "done",
|
||||
priority: "medium",
|
||||
},
|
||||
{
|
||||
id: secondIssueId,
|
||||
companyId,
|
||||
identifier: "PAP-2",
|
||||
title: "Write the plan",
|
||||
status: "done",
|
||||
priority: "medium",
|
||||
},
|
||||
{
|
||||
id: otherIssueId,
|
||||
companyId: otherCompanyId,
|
||||
identifier: "OTH-1",
|
||||
title: "Other output",
|
||||
status: "done",
|
||||
priority: "medium",
|
||||
},
|
||||
]);
|
||||
await db.insert(heartbeatRuns).values([
|
||||
{
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId,
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
id: otherRunId,
|
||||
companyId: otherCompanyId,
|
||||
agentId: otherAgentId,
|
||||
status: "completed",
|
||||
},
|
||||
]);
|
||||
await db.insert(documents).values([
|
||||
{
|
||||
id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
|
||||
companyId,
|
||||
title: "Review Notes",
|
||||
latestBody: "# Review\n\nAgent-created review document with useful details.",
|
||||
createdByAgentId: agentId,
|
||||
updatedAt: new Date("2026-01-04T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
|
||||
companyId,
|
||||
title: "Continuation Summary",
|
||||
latestBody: "System handoff",
|
||||
createdByAgentId: agentId,
|
||||
updatedAt: new Date("2026-01-05T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee",
|
||||
companyId,
|
||||
title: "User Upload Notes",
|
||||
latestBody: "User-authored context",
|
||||
createdByUserId: "user-1",
|
||||
updatedAt: new Date("2026-01-06T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "ffffffff-ffff-4fff-8fff-ffffffffffff",
|
||||
companyId: otherCompanyId,
|
||||
title: "Other Company Plan",
|
||||
latestBody: "Must not cross tenants",
|
||||
createdByAgentId: otherAgentId,
|
||||
updatedAt: new Date("2026-01-07T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
await db.insert(issueDocuments).values([
|
||||
{
|
||||
companyId,
|
||||
issueId: secondIssueId,
|
||||
documentId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
|
||||
key: "review",
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
issueId,
|
||||
documentId: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
|
||||
key: ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
issueId,
|
||||
documentId: "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee",
|
||||
key: "user-notes",
|
||||
},
|
||||
{
|
||||
companyId: otherCompanyId,
|
||||
issueId: otherIssueId,
|
||||
documentId: "ffffffff-ffff-4fff-8fff-ffffffffffff",
|
||||
key: "plan",
|
||||
},
|
||||
]);
|
||||
await db.insert(issueComments).values({
|
||||
id: "12121212-1212-4121-8121-121212121212",
|
||||
companyId,
|
||||
issueId,
|
||||
authorType: "agent",
|
||||
authorAgentId: agentId,
|
||||
body: "comment with screenshot",
|
||||
});
|
||||
await db.insert(assets).values([
|
||||
{
|
||||
id: "13131313-1313-4131-8131-131313131313",
|
||||
companyId,
|
||||
provider: "local_disk",
|
||||
objectKey: "direct-video.mp4",
|
||||
contentType: "video/mp4",
|
||||
byteSize: 100,
|
||||
sha256: "sha256-direct-video",
|
||||
originalFilename: "direct-video.mp4",
|
||||
createdByAgentId: agentId,
|
||||
},
|
||||
{
|
||||
id: "14141414-1414-4141-8141-141414141414",
|
||||
companyId,
|
||||
provider: "local_disk",
|
||||
objectKey: "primary-cut.mp4",
|
||||
contentType: "video/mp4",
|
||||
byteSize: 200,
|
||||
sha256: "sha256-primary-cut",
|
||||
originalFilename: "primary-cut.mp4",
|
||||
createdByAgentId: agentId,
|
||||
},
|
||||
{
|
||||
id: "15151515-1515-4151-8151-151515151515",
|
||||
companyId,
|
||||
provider: "local_disk",
|
||||
objectKey: "operator-screenshot.png",
|
||||
contentType: "image/png",
|
||||
byteSize: 300,
|
||||
sha256: "sha256-user",
|
||||
originalFilename: "operator-screenshot.png",
|
||||
createdByUserId: "user-1",
|
||||
},
|
||||
{
|
||||
id: "16161616-1616-4161-8161-161616161616",
|
||||
companyId,
|
||||
provider: "local_disk",
|
||||
objectKey: "comment-screenshot.png",
|
||||
contentType: "image/png",
|
||||
byteSize: 400,
|
||||
sha256: "sha256-comment",
|
||||
originalFilename: "comment-screenshot.png",
|
||||
createdByAgentId: agentId,
|
||||
},
|
||||
{
|
||||
id: "17171717-1717-4171-8171-171717171717",
|
||||
companyId,
|
||||
provider: "local_disk",
|
||||
objectKey: "notes.txt",
|
||||
contentType: "text/plain",
|
||||
byteSize: 64,
|
||||
sha256: "sha256-notes",
|
||||
originalFilename: "notes.txt",
|
||||
createdByAgentId: agentId,
|
||||
},
|
||||
]);
|
||||
await db.insert(issueAttachments).values([
|
||||
{
|
||||
id: directAttachmentId,
|
||||
companyId,
|
||||
issueId,
|
||||
assetId: "13131313-1313-4131-8131-131313131313",
|
||||
updatedAt: new Date("2026-01-03T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: workProductAttachmentId,
|
||||
companyId,
|
||||
issueId,
|
||||
assetId: "14141414-1414-4141-8141-141414141414",
|
||||
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
issueId,
|
||||
assetId: "15151515-1515-4151-8151-151515151515",
|
||||
updatedAt: new Date("2026-01-08T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
issueId,
|
||||
assetId: "16161616-1616-4161-8161-161616161616",
|
||||
issueCommentId: "12121212-1212-4121-8121-121212121212",
|
||||
updatedAt: new Date("2026-01-09T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
issueId,
|
||||
assetId: "17171717-1717-4171-8171-171717171717",
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
await db.insert(issueWorkProducts).values({
|
||||
id: "18181818-1818-4181-8181-181818181818",
|
||||
companyId,
|
||||
projectId,
|
||||
issueId,
|
||||
type: "artifact",
|
||||
provider: "paperclip",
|
||||
title: "Primary Cut",
|
||||
status: "ready_for_review",
|
||||
summary: "Main render for review",
|
||||
isPrimary: true,
|
||||
metadata: {
|
||||
attachmentId: workProductAttachmentId,
|
||||
contentType: "video/mp4",
|
||||
byteSize: 200,
|
||||
contentPath: `/api/attachments/${workProductAttachmentId}/content`,
|
||||
openPath: `/api/attachments/${workProductAttachmentId}/content`,
|
||||
downloadPath: `/api/attachments/${workProductAttachmentId}/content?download=1`,
|
||||
originalFilename: "primary-cut.mp4",
|
||||
},
|
||||
createdByRunId: runId,
|
||||
updatedAt: new Date("2026-01-02T12:00:00.000Z"),
|
||||
});
|
||||
|
||||
return { companyId, projectId, issueId, otherRunId };
|
||||
}
|
||||
|
||||
it("projects agent-created documents, direct attachments, and work products while excluding noisy sources", async () => {
|
||||
const { companyId } = await seedArtifacts();
|
||||
const storage = createStorageService({ "notes.txt": Buffer.from("Text file preview from an agent output.") });
|
||||
const result = await companyArtifactsService(db, storage).list(companyId, { limit: 20 });
|
||||
|
||||
expect(result.nextCursor).toBeNull();
|
||||
expect(result.artifacts.map((artifact) => artifact.title)).toEqual([
|
||||
"Review Notes",
|
||||
"direct-video.mp4",
|
||||
"Primary Cut",
|
||||
"notes.txt",
|
||||
]);
|
||||
expect(result.artifacts.map((artifact) => artifact.source)).toEqual([
|
||||
"document",
|
||||
"attachment",
|
||||
"work_product",
|
||||
"attachment",
|
||||
]);
|
||||
expect(result.artifacts.find((artifact) => artifact.title === "notes.txt")?.previewText)
|
||||
.toBe("Text file preview from an agent output.");
|
||||
expect(result.artifacts.some((artifact) => artifact.title === "primary-cut.mp4")).toBe(false);
|
||||
expect(result.artifacts.some((artifact) => artifact.title === "Continuation Summary")).toBe(false);
|
||||
expect(result.artifacts.some((artifact) => artifact.title === "operator-screenshot.png")).toBe(false);
|
||||
expect(result.artifacts.some((artifact) => artifact.title === "comment-screenshot.png")).toBe(false);
|
||||
expect(result.artifacts.some((artifact) => artifact.issue.identifier === "OTH-1")).toBe(false);
|
||||
});
|
||||
|
||||
it("supports project, kind, search, and cursor filters", async () => {
|
||||
const { companyId, projectId } = await seedArtifacts();
|
||||
const storage = createStorageService({ "notes.txt": Buffer.from("Searchable notes preview") });
|
||||
|
||||
const projectVideos = await companyArtifactsService(db, storage).list(companyId, {
|
||||
projectId,
|
||||
kind: "video",
|
||||
limit: 10,
|
||||
});
|
||||
expect(projectVideos.artifacts.map((artifact) => artifact.title)).toEqual(["direct-video.mp4", "Primary Cut"]);
|
||||
|
||||
const search = await companyArtifactsService(db, storage).list(companyId, {
|
||||
q: "review document",
|
||||
limit: 10,
|
||||
});
|
||||
expect(search.artifacts.map((artifact) => artifact.title)).toEqual(["Review Notes"]);
|
||||
|
||||
const firstPage = await companyArtifactsService(db, storage).list(companyId, { limit: 2 });
|
||||
expect(firstPage.artifacts.map((artifact) => artifact.title)).toEqual(["Review Notes", "direct-video.mp4"]);
|
||||
expect(firstPage.nextCursor).toEqual(expect.any(String));
|
||||
|
||||
const secondPage = await companyArtifactsService(db, storage).list(companyId, {
|
||||
limit: 10,
|
||||
cursor: firstPage.nextCursor ?? undefined,
|
||||
});
|
||||
expect(secondPage.artifacts.map((artifact) => artifact.title)).toEqual(["Primary Cut", "notes.txt"]);
|
||||
|
||||
const pageAfterPrimaryWorkProduct = await companyArtifactsService(db, storage).list(companyId, { limit: 3 });
|
||||
expect(pageAfterPrimaryWorkProduct.artifacts.map((artifact) => artifact.title)).toEqual([
|
||||
"Review Notes",
|
||||
"direct-video.mp4",
|
||||
"Primary Cut",
|
||||
]);
|
||||
|
||||
const afterPrimaryCursor = await companyArtifactsService(db, storage).list(companyId, {
|
||||
limit: 10,
|
||||
cursor: pageAfterPrimaryWorkProduct.nextCursor ?? undefined,
|
||||
});
|
||||
expect(afterPrimaryCursor.artifacts.map((artifact) => artifact.title)).toEqual(["notes.txt"]);
|
||||
});
|
||||
|
||||
it("deduplicates work product attachments beyond the work product fetch window", async () => {
|
||||
const { companyId, projectId, issueId } = await seedArtifacts();
|
||||
const dedupedAttachmentId = "abababab-abab-4bab-8bab-abababababab";
|
||||
|
||||
await db.insert(assets).values({
|
||||
id: "acacacac-acac-4cac-8cac-acacacacacac",
|
||||
companyId,
|
||||
provider: "local_disk",
|
||||
objectKey: "late-render.mp4",
|
||||
contentType: "video/mp4",
|
||||
byteSize: 500,
|
||||
sha256: "sha256-late-render",
|
||||
originalFilename: "late-render.mp4",
|
||||
createdByAgentId: "33333333-3333-4333-8333-333333333333",
|
||||
});
|
||||
await db.insert(issueAttachments).values({
|
||||
id: dedupedAttachmentId,
|
||||
companyId,
|
||||
issueId,
|
||||
assetId: "acacacac-acac-4cac-8cac-acacacacacac",
|
||||
updatedAt: new Date("2026-01-20T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
const fillerWorkProducts = Array.from({ length: 21 }, (_, index) => ({
|
||||
id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`,
|
||||
companyId,
|
||||
projectId,
|
||||
issueId,
|
||||
type: "artifact" as const,
|
||||
provider: "paperclip",
|
||||
title: `Filler Video ${index + 1}`,
|
||||
status: "ready_for_review" as const,
|
||||
summary: "Filler artifact to push the attachment-backed work product past the fetch window",
|
||||
metadata: { contentType: "video/mp4" },
|
||||
createdByRunId: "99999999-9999-4999-8999-999999999999",
|
||||
updatedAt: new Date(`2026-01-10T00:${String(index).padStart(2, "0")}:00.000Z`),
|
||||
}));
|
||||
await db.insert(issueWorkProducts).values([
|
||||
...fillerWorkProducts,
|
||||
{
|
||||
id: "adadadad-adad-4dad-8dad-adadadadadad",
|
||||
companyId,
|
||||
projectId,
|
||||
issueId,
|
||||
type: "artifact",
|
||||
provider: "paperclip",
|
||||
title: "Late Render",
|
||||
status: "ready_for_review",
|
||||
summary: "Attachment-backed work product outside the limited fetch window",
|
||||
metadata: {
|
||||
attachmentId: dedupedAttachmentId,
|
||||
contentType: "video/mp4",
|
||||
byteSize: 500,
|
||||
contentPath: `/api/attachments/${dedupedAttachmentId}/content`,
|
||||
openPath: `/api/attachments/${dedupedAttachmentId}/content`,
|
||||
downloadPath: `/api/attachments/${dedupedAttachmentId}/content?download=1`,
|
||||
originalFilename: "late-render.mp4",
|
||||
},
|
||||
createdByRunId: "99999999-9999-4999-8999-999999999999",
|
||||
updatedAt: new Date("2026-01-01T12:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await companyArtifactsService(db, createStorageService()).list(companyId, {
|
||||
kind: "video",
|
||||
limit: 20,
|
||||
});
|
||||
|
||||
expect(result.artifacts.some((artifact) => artifact.title === "late-render.mp4")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not project a foreign agent from a malformed work product run reference", async () => {
|
||||
const { companyId, issueId, otherRunId } = await seedArtifacts();
|
||||
|
||||
await db.insert(issueWorkProducts).values({
|
||||
id: "1a1a1a1a-1a1a-4a1a-8a1a-1a1a1a1a1a1a",
|
||||
companyId,
|
||||
issueId,
|
||||
type: "artifact",
|
||||
provider: "paperclip",
|
||||
title: "Forged Run Artifact",
|
||||
status: "ready_for_review",
|
||||
summary: "Historically malformed run attribution",
|
||||
metadata: { contentType: "text/plain" },
|
||||
createdByRunId: otherRunId,
|
||||
updatedAt: new Date("2026-01-10T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
const result = await companyArtifactsService(db, createStorageService()).list(companyId, { limit: 20 });
|
||||
const forged = result.artifacts.find((artifact) => artifact.title === "Forged Run Artifact");
|
||||
|
||||
expect(forged).toBeTruthy();
|
||||
expect(forged?.createdByAgent).toBeNull();
|
||||
expect(result.artifacts.some((artifact) => artifact.createdByAgent?.name === "Other")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("company artifacts route authorization", () => {
|
||||
it("rejects agent access across company boundaries before reading artifacts", async () => {
|
||||
const app = express();
|
||||
app.use((_req, _res, next) => {
|
||||
(_req as any).actor = {
|
||||
type: "agent",
|
||||
agentId: "agent-1",
|
||||
companyId: "company-allowed",
|
||||
};
|
||||
next();
|
||||
});
|
||||
app.use("/api/companies", companyRoutes({} as any, createStorageService()));
|
||||
app.use(errorHandler);
|
||||
|
||||
const res = await request(app).get("/api/companies/company-denied/artifacts");
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toBe("Agent key cannot access another company");
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,10 @@ const mockCompanyPortabilityService = vi.hoisted(() => ({
|
||||
importBundle: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockCompanyArtifactsService = vi.hoisted(() => ({
|
||||
list: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockLogActivity = vi.hoisted(() => vi.fn());
|
||||
const mockFeedbackService = vi.hoisted(() => ({
|
||||
listIssueVotesForUser: vi.fn(),
|
||||
@@ -43,6 +47,7 @@ vi.mock("../services/index.js", () => ({
|
||||
accessService: () => mockAccessService,
|
||||
agentService: () => mockAgentService,
|
||||
budgetService: () => mockBudgetService,
|
||||
companyArtifactsService: () => mockCompanyArtifactsService,
|
||||
companyPortabilityService: () => mockCompanyPortabilityService,
|
||||
companyService: () => mockCompanyService,
|
||||
feedbackService: () => mockFeedbackService,
|
||||
|
||||
@@ -31,6 +31,10 @@ const mockCompanyPortabilityService = vi.hoisted(() => ({
|
||||
importBundle: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockCompanyArtifactsService = vi.hoisted(() => ({
|
||||
list: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockLogActivity = vi.hoisted(() => vi.fn());
|
||||
const mockFeedbackService = vi.hoisted(() => ({
|
||||
listIssueVotesForUser: vi.fn(),
|
||||
@@ -71,6 +75,7 @@ vi.mock("../services/index.js", () => ({
|
||||
accessService: () => mockAccessService,
|
||||
agentService: () => mockAgentService,
|
||||
budgetService: () => mockBudgetService,
|
||||
companyArtifactsService: () => mockCompanyArtifactsService,
|
||||
companyPortabilityService: () => mockCompanyPortabilityService,
|
||||
companyService: () => mockCompanyService,
|
||||
feedbackService: () => mockFeedbackService,
|
||||
@@ -82,6 +87,7 @@ function registerCompanyRouteMocks() {
|
||||
accessService: () => mockAccessService,
|
||||
agentService: () => mockAgentService,
|
||||
budgetService: () => mockBudgetService,
|
||||
companyArtifactsService: () => mockCompanyArtifactsService,
|
||||
companyPortabilityService: () => mockCompanyPortabilityService,
|
||||
companyService: () => mockCompanyService,
|
||||
feedbackService: () => mockFeedbackService,
|
||||
|
||||
@@ -13,7 +13,7 @@ function createSearchResponse(query: CompanySearchQuery): CompanySearchResponse
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
results: [],
|
||||
countsByType: { issue: 0, agent: 0, project: 0 },
|
||||
countsByType: { issue: 0, artifact: 0, agent: 0, project: 0 },
|
||||
hasMore: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -202,6 +202,59 @@ describeEmbeddedPostgres("companySearchService", () => {
|
||||
expect(result.results[0]?.snippet).toMatch(/parser/i);
|
||||
});
|
||||
|
||||
it("searches artifact projections through the artifacts scope", async () => {
|
||||
const companyId = await createCompany();
|
||||
const agentId = await createAgent(companyId, { name: "Artifact Writer" });
|
||||
const issueId = await createIssue(companyId, {
|
||||
identifier: "TST-88",
|
||||
title: "Produce artifact",
|
||||
});
|
||||
const documentId = randomUUID();
|
||||
await db.insert(documents).values({
|
||||
id: documentId,
|
||||
companyId,
|
||||
title: "Launch Artifact Brief",
|
||||
latestBody: "The searchable artifact body mentions a comet-tail preview.",
|
||||
format: "markdown",
|
||||
createdByAgentId: agentId,
|
||||
});
|
||||
await db.insert(issueDocuments).values({
|
||||
companyId,
|
||||
issueId,
|
||||
documentId,
|
||||
key: "brief",
|
||||
});
|
||||
|
||||
const result = await svc.search(companyId, companySearchQuerySchema.parse({ q: "comet-tail", scope: "artifacts" }));
|
||||
|
||||
expect(result.results).toHaveLength(1);
|
||||
expect(result.results[0]).toMatchObject({
|
||||
type: "artifact",
|
||||
title: "Launch Artifact Brief",
|
||||
href: expect.stringContaining("#document-brief"),
|
||||
artifact: expect.objectContaining({
|
||||
mediaKind: "document",
|
||||
issueIdentifier: "TST-88",
|
||||
}),
|
||||
});
|
||||
expect(result.results[0]?.snippet).toMatch(/comet tail/i);
|
||||
expect(result.countsByType).toEqual({ issue: 0, artifact: 1, agent: 0, project: 0 });
|
||||
});
|
||||
|
||||
it("does not pass high-offset search fetch windows through to artifact query validation", async () => {
|
||||
const companyId = await createCompany();
|
||||
|
||||
const result = await svc.search(companyId, companySearchQuerySchema.parse({
|
||||
q: "artifact",
|
||||
scope: "artifacts",
|
||||
limit: "50",
|
||||
offset: "75",
|
||||
}));
|
||||
|
||||
expect(result.results).toEqual([]);
|
||||
expect(result.countsByType.artifact).toBe(0);
|
||||
});
|
||||
|
||||
it("excludes hidden issues and other companies' data", async () => {
|
||||
const companyId = await createCompany("Visible Co");
|
||||
const otherCompanyId = await createCompany("Other Co");
|
||||
@@ -387,7 +440,7 @@ describeEmbeddedPostgres("companySearchService", () => {
|
||||
const result = await svc.search(companyId, companySearchQuerySchema.parse({ q: "needle", limit: "2", offset: "2" }));
|
||||
|
||||
expect(result.results.map((row) => row.id)).toEqual([agentIds[2], projectIds[0]]);
|
||||
expect(result.countsByType).toEqual({ issue: 0, agent: 3, project: 3 });
|
||||
expect(result.countsByType).toEqual({ issue: 0, artifact: 0, agent: 3, project: 3 });
|
||||
expect(result.hasMore).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -201,35 +201,43 @@ function makeAgent(id: string, overrides: Record<string, unknown> = {}) {
|
||||
|
||||
function createRunContextDb(
|
||||
contextSnapshot: Record<string, unknown> = {},
|
||||
runAgentId: string = ownerAgentId,
|
||||
runAgentOrRows: string | Record<string, unknown>[] = ownerAgentId,
|
||||
runId: string = ownerRunId,
|
||||
) {
|
||||
const runRows = Array.isArray(runAgentOrRows)
|
||||
? runAgentOrRows
|
||||
: [{
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId: runAgentOrRows,
|
||||
agentCompanyId: companyId,
|
||||
contextSnapshot,
|
||||
}];
|
||||
const firstRun = runRows[0] ?? {};
|
||||
const runAgentId = typeof firstRun.agentId === "string" ? firstRun.agentId : ownerAgentId;
|
||||
const runAgentCompanyId = typeof firstRun.agentCompanyId === "string" ? firstRun.agentCompanyId : companyId;
|
||||
const rowsForSelection = (selection: Record<string, unknown>) => {
|
||||
const keys = Object.keys(selection);
|
||||
if (keys.includes("entityId")) return [];
|
||||
if (keys.includes("contextSnapshot")) return runRows;
|
||||
if (keys.includes("agentCompanyId")) return runRows;
|
||||
return [{ id: runAgentId, companyId: runAgentCompanyId, permissions: {}, role: "engineer", reportsTo: null }];
|
||||
};
|
||||
const buildQuery = (selection: Record<string, unknown>) => {
|
||||
const whereResult = {
|
||||
orderBy: vi.fn(async () => []),
|
||||
then: async (resolve: (rows: unknown[]) => unknown) => resolve(rowsForSelection(selection)),
|
||||
};
|
||||
const query = {
|
||||
innerJoin: vi.fn(() => query),
|
||||
where: vi.fn(() => whereResult),
|
||||
};
|
||||
return query;
|
||||
};
|
||||
return {
|
||||
transaction: async (callback: (tx: Record<string, never>) => Promise<unknown>) => callback({}),
|
||||
select: vi.fn((selection: Record<string, unknown> = {}) => ({
|
||||
from: vi.fn(() => ({
|
||||
where: vi.fn(() => ({
|
||||
orderBy: vi.fn(async () => []),
|
||||
then: async (resolve: (rows: unknown[]) => unknown) => {
|
||||
const keys = Object.keys(selection);
|
||||
if (keys.includes("entityId")) {
|
||||
return resolve([]);
|
||||
}
|
||||
if (keys.includes("contextSnapshot")) {
|
||||
return resolve([{
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId: runAgentId,
|
||||
contextSnapshot,
|
||||
}]);
|
||||
}
|
||||
if (keys.includes("permissions")) {
|
||||
return resolve([{ id: runAgentId, companyId, permissions: {}, role: "engineer", reportsTo: null }]);
|
||||
}
|
||||
return resolve([{ id: runAgentId, companyId, permissions: {}, role: "engineer", reportsTo: null }]);
|
||||
},
|
||||
})),
|
||||
})),
|
||||
from: vi.fn(() => buildQuery(selection)),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -622,6 +630,73 @@ describe("agent issue mutation checkout ownership", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("stores the authenticated agent run id when creating work products", async () => {
|
||||
const app = await createApp(ownerActor());
|
||||
|
||||
await request(app).post(`/api/issues/${issueId}/work-products`).send({
|
||||
type: "artifact",
|
||||
provider: "test",
|
||||
title: "Artifact",
|
||||
}).expect(201);
|
||||
|
||||
expect(mockWorkProductService.createForIssue).toHaveBeenCalledWith(
|
||||
issueId,
|
||||
companyId,
|
||||
expect.objectContaining({ createdByRunId: ownerRunId }),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects agent-created work products with a forged run id", async () => {
|
||||
const app = await createApp(ownerActor());
|
||||
|
||||
const res = await request(app).post(`/api/issues/${issueId}/work-products`).send({
|
||||
type: "artifact",
|
||||
provider: "test",
|
||||
title: "Artifact",
|
||||
createdByRunId: "66666666-6666-4666-8666-666666666666",
|
||||
});
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(403);
|
||||
expect(res.body.error).toBe("createdByRunId must match the authenticated agent run");
|
||||
expect(mockWorkProductService.createForIssue).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects work product updates with a forged agent run id", async () => {
|
||||
const app = await createApp(ownerActor());
|
||||
|
||||
const res = await request(app).patch("/api/work-products/product-1").send({
|
||||
createdByRunId: "66666666-6666-4666-8666-666666666666",
|
||||
});
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(403);
|
||||
expect(res.body.error).toBe("createdByRunId must match the authenticated agent run");
|
||||
expect(mockWorkProductService.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects board-created work products with a foreign-company run id", async () => {
|
||||
const app = await createApp(
|
||||
boardActor(),
|
||||
createRunContextDb({}, [{
|
||||
id: "66666666-6666-4666-8666-666666666666",
|
||||
companyId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
agentId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||
agentCompanyId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
contextSnapshot: {},
|
||||
}]),
|
||||
);
|
||||
|
||||
const res = await request(app).post(`/api/issues/${issueId}/work-products`).send({
|
||||
type: "artifact",
|
||||
provider: "test",
|
||||
title: "Artifact",
|
||||
createdByRunId: "66666666-6666-4666-8666-666666666666",
|
||||
});
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(403);
|
||||
expect(res.body.error).toBe("createdByRunId is not valid for this company");
|
||||
expect(mockWorkProductService.createForIssue).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"work product create",
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { Db } from "@paperclipai/db";
|
||||
import { agents as agentsTable } from "@paperclipai/db";
|
||||
import {
|
||||
DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION,
|
||||
companyArtifactsQuerySchema,
|
||||
companyPortabilityExportSchema,
|
||||
companyPortabilityImportSchema,
|
||||
companyPortabilityPreviewSchema,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
accessService,
|
||||
agentService,
|
||||
budgetService,
|
||||
companyArtifactsService,
|
||||
companyPortabilityService,
|
||||
companyService,
|
||||
feedbackService,
|
||||
@@ -37,6 +39,7 @@ export function companyRoutes(db: Db, storage?: StorageService) {
|
||||
const portability = companyPortabilityService(db, storage);
|
||||
const access = accessService(db);
|
||||
const budgets = budgetService(db);
|
||||
const artifacts = companyArtifactsService(db, storage);
|
||||
const feedback = feedbackService(db);
|
||||
const importJobs = new Map<string, ImportJobRecord>();
|
||||
const importJobTerminalRetentionMs = 5 * 60 * 1000;
|
||||
@@ -125,6 +128,13 @@ export function companyRoutes(db: Db, storage?: StorageService) {
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/:companyId/artifacts", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const query = companyArtifactsQuerySchema.parse(req.query);
|
||||
res.json(await artifacts.list(companyId, query));
|
||||
});
|
||||
|
||||
router.get("/:companyId", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { and, desc, eq, inArray, notInArray } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
documents,
|
||||
executionWorkspaces,
|
||||
heartbeatRuns,
|
||||
@@ -1926,6 +1927,55 @@ export function issueRoutes(
|
||||
return false;
|
||||
}
|
||||
|
||||
async function loadWorkProductRunAttribution(runId: string) {
|
||||
return await db
|
||||
.select({
|
||||
id: heartbeatRuns.id,
|
||||
companyId: heartbeatRuns.companyId,
|
||||
agentId: heartbeatRuns.agentId,
|
||||
agentCompanyId: agents.companyId,
|
||||
})
|
||||
.from(heartbeatRuns)
|
||||
.innerJoin(agents, eq(heartbeatRuns.agentId, agents.id))
|
||||
.where(eq(heartbeatRuns.id, runId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
}
|
||||
|
||||
async function resolveWorkProductCreatedByRunId(
|
||||
req: Request,
|
||||
res: Response,
|
||||
companyId: string,
|
||||
input: { createdByRunId?: string | null },
|
||||
mode: "create" | "update",
|
||||
): Promise<string | null | undefined> {
|
||||
const hasCreatedByRunId = Object.prototype.hasOwnProperty.call(input, "createdByRunId");
|
||||
if (mode === "update" && !hasCreatedByRunId) return undefined;
|
||||
|
||||
const requestedRunId = input.createdByRunId ?? null;
|
||||
if (req.actor.type === "agent") {
|
||||
const actorRunId = req.actor.runId?.trim() || null;
|
||||
if (requestedRunId && requestedRunId !== actorRunId) {
|
||||
res.status(403).json({ error: "createdByRunId must match the authenticated agent run" });
|
||||
return undefined;
|
||||
}
|
||||
if (!actorRunId) return requestedRunId;
|
||||
const run = await loadWorkProductRunAttribution(actorRunId);
|
||||
if (!run || run.companyId !== companyId || run.agentCompanyId !== companyId || run.agentId !== req.actor.agentId) {
|
||||
res.status(403).json({ error: "createdByRunId is not valid for this work product actor" });
|
||||
return undefined;
|
||||
}
|
||||
return actorRunId;
|
||||
}
|
||||
|
||||
if (!requestedRunId) return null;
|
||||
const run = await loadWorkProductRunAttribution(requestedRunId);
|
||||
if (!run || run.companyId !== companyId || run.agentCompanyId !== companyId) {
|
||||
res.status(403).json({ error: "createdByRunId is not valid for this company" });
|
||||
return undefined;
|
||||
}
|
||||
return requestedRunId;
|
||||
}
|
||||
|
||||
function assertStructuredCommentFieldsAllowed(
|
||||
req: Request,
|
||||
res: Response,
|
||||
@@ -3669,6 +3719,9 @@ export function issueRoutes(
|
||||
projectId: req.body.projectId ?? issue.projectId ?? null,
|
||||
sourceTrust: await sourceTrustForActorWrite(issue, actor),
|
||||
};
|
||||
const createdByRunId = await resolveWorkProductCreatedByRunId(req, res, issue.companyId, req.body, "create");
|
||||
if (createdByRunId === undefined) return;
|
||||
createInput.createdByRunId = createdByRunId;
|
||||
if (requiresPaperclipAttachmentMetadata(createInput)) {
|
||||
createInput.metadata = await canonicalizePaperclipArtifactMetadata({
|
||||
issue,
|
||||
@@ -3862,6 +3915,9 @@ export function issueRoutes(
|
||||
if (!(await assertDeliverableMutationAllowedByRunContext(req, res, issue))) return;
|
||||
const actor = getActorInfo(req);
|
||||
const patch = { ...req.body };
|
||||
const createdByRunId = await resolveWorkProductCreatedByRunId(req, res, existing.companyId, req.body, "update");
|
||||
if (createdByRunId === undefined && Object.prototype.hasOwnProperty.call(req.body, "createdByRunId")) return;
|
||||
if (createdByRunId !== undefined) patch.createdByRunId = createdByRunId;
|
||||
if (requiresPaperclipAttachmentMetadata(patch, existing)) {
|
||||
if (patch.metadata !== undefined) {
|
||||
patch.metadata = await canonicalizePaperclipArtifactMetadata({
|
||||
|
||||
@@ -35,6 +35,8 @@ import {
|
||||
createCompanySchema,
|
||||
updateCompanySchema,
|
||||
updateCompanyBrandingSchema,
|
||||
companyArtifactsQuerySchema,
|
||||
companyArtifactsResponseSchema,
|
||||
// Routine
|
||||
createRoutineSchema,
|
||||
updateRoutineSchema,
|
||||
@@ -789,6 +791,28 @@ registry.registerPath({
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies/{companyId}/artifacts",
|
||||
tags: ["companies"],
|
||||
summary: "List company artifacts",
|
||||
request: {
|
||||
params: z.object({ companyId: z.string() }),
|
||||
query: companyArtifactsQuerySchema,
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Company artifact projection",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: companyArtifactsResponseSchema,
|
||||
},
|
||||
},
|
||||
},
|
||||
401: r.unauthorized,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "patch",
|
||||
path: "/api/companies/{companyId}",
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
import { buffer } from "node:stream/consumers";
|
||||
import { and, desc, eq, isNotNull, isNull, notInArray, or, sql, type SQL } from "drizzle-orm";
|
||||
import { alias } from "drizzle-orm/pg-core";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
assets,
|
||||
companies,
|
||||
documents,
|
||||
heartbeatRuns,
|
||||
issueAttachments,
|
||||
issueDocuments,
|
||||
issues,
|
||||
issueWorkProducts,
|
||||
projects,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
attachmentArtifactWorkProductMetadataSchema,
|
||||
COMPANY_ARTIFACTS_MAX_LIMIT,
|
||||
companyArtifactsQuerySchema,
|
||||
SYSTEM_ISSUE_DOCUMENT_KEYS,
|
||||
type CompanyArtifact,
|
||||
type CompanyArtifactMediaKind,
|
||||
type CompanyArtifactsQuery,
|
||||
type CompanyArtifactsResponse,
|
||||
} from "@paperclipai/shared";
|
||||
import { badRequest, notFound } from "../errors.js";
|
||||
import type { StorageService } from "../storage/types.js";
|
||||
|
||||
const TEXT_PREVIEW_BYTES = 4096;
|
||||
const PREVIEW_TEXT_MAX_LENGTH = 280;
|
||||
|
||||
type ArtifactCursor = {
|
||||
updatedAt: string;
|
||||
id: string;
|
||||
};
|
||||
|
||||
function encodeCursor(cursor: ArtifactCursor) {
|
||||
return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
function decodeCursor(cursor: string | undefined): ArtifactCursor | null {
|
||||
if (!cursor) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")) as Partial<ArtifactCursor>;
|
||||
if (typeof parsed.id !== "string" || typeof parsed.updatedAt !== "string") {
|
||||
throw new Error("Invalid cursor");
|
||||
}
|
||||
const date = new Date(parsed.updatedAt);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
throw new Error("Invalid cursor date");
|
||||
}
|
||||
return { id: parsed.id, updatedAt: date.toISOString() };
|
||||
} catch {
|
||||
throw badRequest("Invalid artifacts cursor");
|
||||
}
|
||||
}
|
||||
|
||||
function cursorCondition(updatedAt: SQL<Date>, artifactId: SQL<string>, cursor: ArtifactCursor | null) {
|
||||
if (!cursor) return undefined;
|
||||
return sql`(${updatedAt} < ${cursor.updatedAt}::timestamptz OR (${updatedAt} = ${cursor.updatedAt}::timestamptz AND ${artifactId} < ${cursor.id}))`;
|
||||
}
|
||||
|
||||
function escapeLikePattern(value: string) {
|
||||
return value.replace(/[\\%_]/g, (match) => `\\${match}`);
|
||||
}
|
||||
|
||||
function normalizePreviewText(input: string | null | undefined) {
|
||||
if (!input) return null;
|
||||
const stripped = input
|
||||
.replace(/```[\s\S]*?```/g, " ")
|
||||
.replace(/`([^`]+)`/g, "$1")
|
||||
.replace(/!\[[^\]]*]\([^)]*\)/g, " ")
|
||||
.replace(/\[([^\]]+)]\([^)]*\)/g, "$1")
|
||||
.replace(/[#>*_\-~|]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
if (!stripped) return null;
|
||||
return stripped.length > PREVIEW_TEXT_MAX_LENGTH
|
||||
? `${stripped.slice(0, PREVIEW_TEXT_MAX_LENGTH - 3).trimEnd()}...`
|
||||
: stripped;
|
||||
}
|
||||
|
||||
function classifyMediaKind(contentType: string | null | undefined, fallback: CompanyArtifactMediaKind = "file") {
|
||||
const normalized = (contentType ?? "").toLowerCase();
|
||||
if (!normalized) return fallback;
|
||||
if (normalized.startsWith("image/")) return "image";
|
||||
if (normalized.startsWith("video/")) return "video";
|
||||
if (
|
||||
normalized.startsWith("text/") ||
|
||||
normalized === "application/json" ||
|
||||
normalized.endsWith("+json") ||
|
||||
normalized === "application/xml" ||
|
||||
normalized.endsWith("+xml") ||
|
||||
normalized === "application/markdown"
|
||||
) {
|
||||
return "text";
|
||||
}
|
||||
return "file";
|
||||
}
|
||||
|
||||
function contentTypeKindCondition(contentTypeExpression: SQL<string>, kind: CompanyArtifactsQuery["kind"]) {
|
||||
if (!kind || kind === "all") return undefined;
|
||||
if (kind === "image") return sql`${contentTypeExpression} ILIKE 'image/%'`;
|
||||
if (kind === "video") return sql`${contentTypeExpression} ILIKE 'video/%'`;
|
||||
if (kind === "text") {
|
||||
return sql`(${contentTypeExpression} ILIKE 'text/%' OR ${contentTypeExpression} IN ('application/json', 'application/xml', 'application/markdown') OR ${contentTypeExpression} ILIKE '%+json' OR ${contentTypeExpression} ILIKE '%+xml')`;
|
||||
}
|
||||
if (kind === "file") {
|
||||
return sql`NOT (${contentTypeExpression} ILIKE 'image/%' OR ${contentTypeExpression} ILIKE 'video/%' OR ${contentTypeExpression} ILIKE 'text/%' OR ${contentTypeExpression} IN ('application/json', 'application/xml', 'application/markdown') OR ${contentTypeExpression} ILIKE '%+json' OR ${contentTypeExpression} ILIKE '%+xml')`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildIssueHref(companyPrefix: string, identifier: string, anchor: string) {
|
||||
return `/${encodeURIComponent(companyPrefix)}/issues/${encodeURIComponent(identifier)}#${anchor}`;
|
||||
}
|
||||
|
||||
function attachmentContentPath(attachmentId: string) {
|
||||
return `/api/attachments/${attachmentId}/content`;
|
||||
}
|
||||
|
||||
async function readTextAttachmentPreview(
|
||||
storage: StorageService | undefined,
|
||||
input: { companyId: string; objectKey: string; byteSize: number },
|
||||
) {
|
||||
if (!storage || input.byteSize <= 0) return null;
|
||||
try {
|
||||
const object = await storage.getObject(input.companyId, input.objectKey, {
|
||||
range: { start: 0, end: Math.min(input.byteSize, TEXT_PREVIEW_BYTES) - 1 },
|
||||
});
|
||||
const body = await buffer(object.stream);
|
||||
return normalizePreviewText(body.toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function companyArtifactsService(db: Db, storage?: StorageService) {
|
||||
return {
|
||||
list: async (companyId: string, rawQuery: Partial<CompanyArtifactsQuery> = {}): Promise<CompanyArtifactsResponse> => {
|
||||
const query = companyArtifactsQuerySchema.parse(rawQuery);
|
||||
const cursor = decodeCursor(query.cursor);
|
||||
const company = await db
|
||||
.select({ id: companies.id, issuePrefix: companies.issuePrefix })
|
||||
.from(companies)
|
||||
.where(eq(companies.id, companyId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!company) throw notFound("Company not found");
|
||||
|
||||
const fetchLimit = Math.min(query.limit + 1, COMPANY_ARTIFACTS_MAX_LIMIT + 1);
|
||||
const q = query.q ? `%${escapeLikePattern(query.q)}%` : null;
|
||||
const artifacts: CompanyArtifact[] = [];
|
||||
const workProductAttachmentIds = new Set<string>();
|
||||
|
||||
if (query.kind === "all" || query.kind === "document") {
|
||||
const createdAgent = alias(agents, "document_created_agent");
|
||||
const updatedAgent = alias(agents, "document_updated_agent");
|
||||
const documentArtifactId = sql<string>`concat('document:', ${documents.id})`;
|
||||
const documentConditions: SQL[] = [
|
||||
eq(documents.companyId, companyId),
|
||||
or(isNotNull(documents.createdByAgentId), isNotNull(documents.updatedByAgentId))!,
|
||||
notInArray(issueDocuments.key, [...SYSTEM_ISSUE_DOCUMENT_KEYS]),
|
||||
];
|
||||
const documentCursor = cursorCondition(sql<Date>`${documents.updatedAt}`, documentArtifactId, cursor);
|
||||
if (documentCursor) documentConditions.push(documentCursor);
|
||||
if (query.projectId) documentConditions.push(eq(issues.projectId, query.projectId));
|
||||
if (q) {
|
||||
documentConditions.push(sql`(
|
||||
coalesce(${documents.title}, '') ILIKE ${q} ESCAPE '\\'
|
||||
OR ${documents.latestBody} ILIKE ${q} ESCAPE '\\'
|
||||
OR coalesce(${issues.identifier}, '') ILIKE ${q} ESCAPE '\\'
|
||||
OR ${issues.title} ILIKE ${q} ESCAPE '\\'
|
||||
)`);
|
||||
}
|
||||
|
||||
const documentRows = await db
|
||||
.select({
|
||||
artifactId: documentArtifactId,
|
||||
documentId: documents.id,
|
||||
issueId: issues.id,
|
||||
issueIdentifier: issues.identifier,
|
||||
issueTitle: issues.title,
|
||||
projectId: projects.id,
|
||||
projectName: projects.name,
|
||||
key: issueDocuments.key,
|
||||
title: documents.title,
|
||||
latestBody: documents.latestBody,
|
||||
createdByAgentId: sql<string | null>`coalesce(${createdAgent.id}, ${updatedAgent.id})`,
|
||||
createdByAgentName: sql<string | null>`coalesce(${createdAgent.name}, ${updatedAgent.name})`,
|
||||
updatedAt: documents.updatedAt,
|
||||
})
|
||||
.from(issueDocuments)
|
||||
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
||||
.innerJoin(issues, eq(issueDocuments.issueId, issues.id))
|
||||
.leftJoin(projects, eq(issues.projectId, projects.id))
|
||||
.leftJoin(createdAgent, eq(documents.createdByAgentId, createdAgent.id))
|
||||
.leftJoin(updatedAgent, eq(documents.updatedByAgentId, updatedAgent.id))
|
||||
.where(and(...documentConditions))
|
||||
.orderBy(desc(documents.updatedAt), desc(documentArtifactId))
|
||||
.limit(fetchLimit);
|
||||
|
||||
for (const row of documentRows) {
|
||||
const identifier = row.issueIdentifier ?? row.issueId;
|
||||
artifacts.push({
|
||||
id: row.artifactId,
|
||||
source: "document",
|
||||
mediaKind: "document",
|
||||
title: row.title ?? row.key,
|
||||
previewText: normalizePreviewText(row.latestBody),
|
||||
contentType: "text/markdown",
|
||||
contentPath: null,
|
||||
openPath: null,
|
||||
downloadPath: null,
|
||||
issue: { id: row.issueId, identifier, title: row.issueTitle },
|
||||
project: row.projectId && row.projectName ? { id: row.projectId, name: row.projectName } : null,
|
||||
createdByAgent: row.createdByAgentId && row.createdByAgentName
|
||||
? { id: row.createdByAgentId, name: row.createdByAgentName }
|
||||
: null,
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
href: buildIssueHref(company.issuePrefix, identifier, `document-${row.key}`),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (query.kind !== "document") {
|
||||
const workProductAgent = alias(agents, "work_product_agent");
|
||||
const workProductArtifactId = sql<string>`concat('work_product:', ${issueWorkProducts.id})`;
|
||||
const workProductContentType = sql<string>`coalesce(${issueWorkProducts.metadata}->>'contentType', '')`;
|
||||
const workProductBaseConditions: SQL[] = [
|
||||
eq(issueWorkProducts.companyId, companyId),
|
||||
eq(issueWorkProducts.type, "artifact"),
|
||||
eq(issueWorkProducts.provider, "paperclip"),
|
||||
];
|
||||
const workProductConditions: SQL[] = [...workProductBaseConditions];
|
||||
const workProductCursor = cursorCondition(sql<Date>`${issueWorkProducts.updatedAt}`, workProductArtifactId, cursor);
|
||||
const workProductKind = contentTypeKindCondition(workProductContentType, query.kind);
|
||||
if (workProductCursor) workProductConditions.push(workProductCursor);
|
||||
if (workProductKind) {
|
||||
workProductBaseConditions.push(workProductKind);
|
||||
workProductConditions.push(workProductKind);
|
||||
}
|
||||
if (query.projectId) {
|
||||
const projectCondition = eq(issues.projectId, query.projectId);
|
||||
workProductBaseConditions.push(projectCondition);
|
||||
workProductConditions.push(projectCondition);
|
||||
}
|
||||
if (q) {
|
||||
const searchCondition = sql`(
|
||||
${issueWorkProducts.title} ILIKE ${q} ESCAPE '\\'
|
||||
OR coalesce(${issueWorkProducts.summary}, '') ILIKE ${q} ESCAPE '\\'
|
||||
OR coalesce(${issues.identifier}, '') ILIKE ${q} ESCAPE '\\'
|
||||
OR ${issues.title} ILIKE ${q} ESCAPE '\\'
|
||||
)`;
|
||||
workProductBaseConditions.push(searchCondition);
|
||||
workProductConditions.push(searchCondition);
|
||||
}
|
||||
|
||||
const workProductRows = await db
|
||||
.select({
|
||||
artifactId: workProductArtifactId,
|
||||
workProductId: issueWorkProducts.id,
|
||||
issueId: issues.id,
|
||||
issueIdentifier: issues.identifier,
|
||||
issueTitle: issues.title,
|
||||
projectId: projects.id,
|
||||
projectName: projects.name,
|
||||
title: issueWorkProducts.title,
|
||||
summary: issueWorkProducts.summary,
|
||||
metadata: issueWorkProducts.metadata,
|
||||
createdByAgentId: workProductAgent.id,
|
||||
createdByAgentName: workProductAgent.name,
|
||||
updatedAt: issueWorkProducts.updatedAt,
|
||||
})
|
||||
.from(issueWorkProducts)
|
||||
.innerJoin(issues, eq(issueWorkProducts.issueId, issues.id))
|
||||
.leftJoin(projects, eq(issues.projectId, projects.id))
|
||||
.leftJoin(
|
||||
heartbeatRuns,
|
||||
and(
|
||||
eq(issueWorkProducts.createdByRunId, heartbeatRuns.id),
|
||||
eq(heartbeatRuns.companyId, issueWorkProducts.companyId),
|
||||
),
|
||||
)
|
||||
.leftJoin(
|
||||
workProductAgent,
|
||||
and(
|
||||
eq(heartbeatRuns.agentId, workProductAgent.id),
|
||||
eq(workProductAgent.companyId, issueWorkProducts.companyId),
|
||||
),
|
||||
)
|
||||
.where(and(...workProductConditions))
|
||||
.orderBy(desc(issueWorkProducts.updatedAt), desc(workProductArtifactId))
|
||||
.limit(fetchLimit);
|
||||
|
||||
const workProductAttachmentRows = await db
|
||||
.select({
|
||||
attachmentId: sql<string | null>`${issueWorkProducts.metadata}->>'attachmentId'`,
|
||||
})
|
||||
.from(issueWorkProducts)
|
||||
.innerJoin(issues, eq(issueWorkProducts.issueId, issues.id))
|
||||
.where(and(...workProductBaseConditions, sql`${issueWorkProducts.metadata}->>'attachmentId' IS NOT NULL`));
|
||||
|
||||
for (const row of workProductAttachmentRows) {
|
||||
if (row.attachmentId) {
|
||||
workProductAttachmentIds.add(row.attachmentId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const row of workProductRows) {
|
||||
const metadata = attachmentArtifactWorkProductMetadataSchema.safeParse(row.metadata);
|
||||
const attachmentMetadata = metadata.success ? metadata.data : null;
|
||||
if (attachmentMetadata) {
|
||||
workProductAttachmentIds.add(attachmentMetadata.attachmentId);
|
||||
}
|
||||
const contentType = attachmentMetadata?.contentType ?? null;
|
||||
const identifier = row.issueIdentifier ?? row.issueId;
|
||||
artifacts.push({
|
||||
id: row.artifactId,
|
||||
source: "work_product",
|
||||
mediaKind: classifyMediaKind(contentType, attachmentMetadata ? "file" : "empty"),
|
||||
title: row.title,
|
||||
previewText: normalizePreviewText(row.summary),
|
||||
contentType,
|
||||
contentPath: attachmentMetadata?.contentPath ?? null,
|
||||
openPath: attachmentMetadata?.openPath ?? (typeof row.metadata?.openPath === "string" ? row.metadata.openPath : null),
|
||||
downloadPath: attachmentMetadata?.downloadPath ?? null,
|
||||
issue: { id: row.issueId, identifier, title: row.issueTitle },
|
||||
project: row.projectId && row.projectName ? { id: row.projectId, name: row.projectName } : null,
|
||||
createdByAgent: row.createdByAgentId && row.createdByAgentName
|
||||
? { id: row.createdByAgentId, name: row.createdByAgentName }
|
||||
: null,
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
href: buildIssueHref(company.issuePrefix, identifier, `work-product-${row.workProductId}`),
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentAgent = alias(agents, "attachment_agent");
|
||||
const attachmentArtifactId = sql<string>`concat('attachment:', ${issueAttachments.id})`;
|
||||
const attachmentConditions: SQL[] = [
|
||||
eq(issueAttachments.companyId, companyId),
|
||||
isNull(issueAttachments.issueCommentId),
|
||||
isNotNull(assets.createdByAgentId),
|
||||
];
|
||||
const attachmentCursor = cursorCondition(sql<Date>`${issueAttachments.updatedAt}`, attachmentArtifactId, cursor);
|
||||
const attachmentKind = contentTypeKindCondition(sql<string>`${assets.contentType}`, query.kind);
|
||||
if (attachmentCursor) attachmentConditions.push(attachmentCursor);
|
||||
if (attachmentKind) attachmentConditions.push(attachmentKind);
|
||||
if (query.projectId) attachmentConditions.push(eq(issues.projectId, query.projectId));
|
||||
if (q) {
|
||||
attachmentConditions.push(sql`(
|
||||
coalesce(${assets.originalFilename}, '') ILIKE ${q} ESCAPE '\\'
|
||||
OR coalesce(${issues.identifier}, '') ILIKE ${q} ESCAPE '\\'
|
||||
OR ${issues.title} ILIKE ${q} ESCAPE '\\'
|
||||
)`);
|
||||
}
|
||||
|
||||
const attachmentRows = await db
|
||||
.select({
|
||||
artifactId: attachmentArtifactId,
|
||||
attachmentId: issueAttachments.id,
|
||||
companyId: issueAttachments.companyId,
|
||||
issueId: issues.id,
|
||||
issueIdentifier: issues.identifier,
|
||||
issueTitle: issues.title,
|
||||
projectId: projects.id,
|
||||
projectName: projects.name,
|
||||
objectKey: assets.objectKey,
|
||||
contentType: assets.contentType,
|
||||
byteSize: assets.byteSize,
|
||||
originalFilename: assets.originalFilename,
|
||||
createdByAgentId: attachmentAgent.id,
|
||||
createdByAgentName: attachmentAgent.name,
|
||||
updatedAt: issueAttachments.updatedAt,
|
||||
})
|
||||
.from(issueAttachments)
|
||||
.innerJoin(assets, eq(issueAttachments.assetId, assets.id))
|
||||
.innerJoin(issues, eq(issueAttachments.issueId, issues.id))
|
||||
.leftJoin(projects, eq(issues.projectId, projects.id))
|
||||
.leftJoin(attachmentAgent, eq(assets.createdByAgentId, attachmentAgent.id))
|
||||
.where(and(...attachmentConditions))
|
||||
.orderBy(desc(issueAttachments.updatedAt), desc(attachmentArtifactId))
|
||||
.limit(fetchLimit);
|
||||
|
||||
const attachmentArtifacts = await Promise.all(attachmentRows.map(async (row): Promise<CompanyArtifact | null> => {
|
||||
if (workProductAttachmentIds.has(row.attachmentId)) return null;
|
||||
const mediaKind = classifyMediaKind(row.contentType);
|
||||
const contentPath = attachmentContentPath(row.attachmentId);
|
||||
const identifier = row.issueIdentifier ?? row.issueId;
|
||||
return {
|
||||
id: row.artifactId,
|
||||
source: "attachment",
|
||||
mediaKind,
|
||||
title: row.originalFilename ?? "Attachment",
|
||||
previewText: mediaKind === "text"
|
||||
? await readTextAttachmentPreview(storage, {
|
||||
companyId: row.companyId,
|
||||
objectKey: row.objectKey,
|
||||
byteSize: row.byteSize,
|
||||
})
|
||||
: null,
|
||||
contentType: row.contentType,
|
||||
contentPath,
|
||||
openPath: contentPath,
|
||||
downloadPath: `${contentPath}?download=1`,
|
||||
issue: { id: row.issueId, identifier, title: row.issueTitle },
|
||||
project: row.projectId && row.projectName ? { id: row.projectId, name: row.projectName } : null,
|
||||
createdByAgent: row.createdByAgentId && row.createdByAgentName
|
||||
? { id: row.createdByAgentId, name: row.createdByAgentName }
|
||||
: null,
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
href: buildIssueHref(company.issuePrefix, identifier, `attachment-${row.attachmentId}`),
|
||||
};
|
||||
}));
|
||||
|
||||
artifacts.push(...attachmentArtifacts.filter((artifact): artifact is CompanyArtifact => artifact !== null));
|
||||
}
|
||||
|
||||
const sorted = artifacts
|
||||
.sort((a, b) => {
|
||||
const dateDiff = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
|
||||
if (dateDiff !== 0) return dateDiff;
|
||||
return b.id.localeCompare(a.id);
|
||||
});
|
||||
const page = sorted.slice(0, query.limit);
|
||||
const nextCursor = sorted.length > query.limit
|
||||
? encodeCursor({ id: page[page.length - 1]?.id ?? "", updatedAt: page[page.length - 1]?.updatedAt ?? new Date(0).toISOString() })
|
||||
: null;
|
||||
|
||||
return { artifacts: page, nextCursor };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
COMPANY_SEARCH_MAX_LIMIT,
|
||||
COMPANY_SEARCH_MAX_OFFSET,
|
||||
COMPANY_SEARCH_MAX_TOKENS,
|
||||
COMPANY_ARTIFACTS_MAX_LIMIT,
|
||||
COMPANY_ARTIFACTS_MAX_QUERY_LENGTH,
|
||||
type CompanyArtifact,
|
||||
type CompanySearchArtifactSummary,
|
||||
type CompanySearchIssueSummary,
|
||||
type CompanySearchQuery,
|
||||
type CompanySearchResponse,
|
||||
@@ -14,6 +18,7 @@ import {
|
||||
type CompanySearchScope,
|
||||
type CompanySearchSnippet,
|
||||
} from "@paperclipai/shared";
|
||||
import { companyArtifactsService } from "./company-artifacts.js";
|
||||
|
||||
const MIN_TOKEN_LENGTH = 2;
|
||||
const MIN_FUZZY_QUERY_LENGTH = 4;
|
||||
@@ -188,7 +193,7 @@ function matchTerms(normalizedQuery: string, tokens: string[]) {
|
||||
}
|
||||
|
||||
function makeCounts(results: CompanySearchResult[]) {
|
||||
const counts: Record<CompanySearchResultType, number> = { issue: 0, agent: 0, project: 0 };
|
||||
const counts: Record<CompanySearchResultType, number> = { issue: 0, artifact: 0, agent: 0, project: 0 };
|
||||
for (const result of results) counts[result.type] += 1;
|
||||
return counts;
|
||||
}
|
||||
@@ -201,6 +206,10 @@ function scopeIncludesAgents(scope: CompanySearchScope) {
|
||||
return scope === "all" || scope === "agents";
|
||||
}
|
||||
|
||||
function scopeIncludesArtifacts(scope: CompanySearchScope) {
|
||||
return scope === "all" || scope === "artifacts";
|
||||
}
|
||||
|
||||
function scopeIncludesProjects(scope: CompanySearchScope) {
|
||||
return scope === "all" || scope === "projects";
|
||||
}
|
||||
@@ -286,6 +295,49 @@ function scoreSimpleRow(row: SimpleSearchRow, normalizedQuery: string, tokens: s
|
||||
return score;
|
||||
}
|
||||
|
||||
function artifactResult(artifact: CompanyArtifact, normalizedQuery: string, tokens: string[]): CompanySearchResult {
|
||||
const terms = matchTerms(normalizedQuery, tokens);
|
||||
const snippet = createSnippet(
|
||||
"artifact",
|
||||
"Artifact",
|
||||
artifact.previewText ?? artifact.title,
|
||||
terms,
|
||||
);
|
||||
const summary: CompanySearchArtifactSummary = {
|
||||
id: artifact.id,
|
||||
source: artifact.source,
|
||||
mediaKind: artifact.mediaKind,
|
||||
issueId: artifact.issue.id,
|
||||
issueIdentifier: artifact.issue.identifier,
|
||||
issueTitle: artifact.issue.title,
|
||||
projectId: artifact.project?.id ?? null,
|
||||
projectName: artifact.project?.name ?? null,
|
||||
updatedAt: artifact.updatedAt,
|
||||
};
|
||||
const score = scoreSimpleRow({
|
||||
id: artifact.id,
|
||||
title: artifact.title,
|
||||
description: [artifact.previewText, artifact.issue.identifier, artifact.issue.title, artifact.project?.name]
|
||||
.filter(Boolean)
|
||||
.join(" "),
|
||||
updatedAt: new Date(artifact.updatedAt),
|
||||
}, normalizedQuery, tokens);
|
||||
return {
|
||||
id: artifact.id,
|
||||
type: "artifact",
|
||||
score,
|
||||
title: artifact.title,
|
||||
href: artifact.href,
|
||||
matchedFields: ["artifact"],
|
||||
sourceLabel: snippet?.label ?? "Artifact",
|
||||
snippet: snippet?.text ?? artifact.previewText,
|
||||
snippets: snippet ? [snippet] : [],
|
||||
artifact: summary,
|
||||
updatedAt: artifact.updatedAt,
|
||||
previewImageUrl: artifact.mediaKind === "image" ? artifact.contentPath : null,
|
||||
};
|
||||
}
|
||||
|
||||
function simpleTextCondition(fields: SQL[], containsPattern: string, tokenArray: SQL) {
|
||||
const phraseConditions = fields.map((field) => sql<boolean>`lower(coalesce(${field}, '')) LIKE ${containsPattern} ESCAPE '\\'`);
|
||||
const tokenConditions = fields.map((field) => tokenMatchExpression(field, tokenArray));
|
||||
@@ -306,7 +358,7 @@ export function companySearchService(db: Db) {
|
||||
const scope = query.scope;
|
||||
const limit = query.limit;
|
||||
const offset = query.offset;
|
||||
const emptyCounts: Record<CompanySearchResultType, number> = { issue: 0, agent: 0, project: 0 };
|
||||
const emptyCounts: Record<CompanySearchResultType, number> = { issue: 0, artifact: 0, agent: 0, project: 0 };
|
||||
if (normalizedQuery.length === 0) {
|
||||
return {
|
||||
query: query.q,
|
||||
@@ -643,8 +695,16 @@ export function companySearchService(db: Db) {
|
||||
.limit(fetchLimit)
|
||||
: [];
|
||||
|
||||
const artifactRows = scopeIncludesArtifacts(scope)
|
||||
? await companyArtifactsService(db).list(companyId, {
|
||||
q: normalizedQuery.slice(0, COMPANY_ARTIFACTS_MAX_QUERY_LENGTH),
|
||||
limit: Math.min(fetchLimit, COMPANY_ARTIFACTS_MAX_LIMIT),
|
||||
}).then((result) => result.artifacts)
|
||||
: [];
|
||||
|
||||
const results: CompanySearchResult[] = [
|
||||
...(issueRows as IssueSearchRow[]).map((row) => issueResult(row, prefix, normalizedQuery, tokens)),
|
||||
...artifactRows.map((artifact) => artifactResult(artifact, normalizedQuery, tokens)),
|
||||
...(agentRows as SimpleSearchRow[]).map((row) => {
|
||||
const terms = matchTerms(normalizedQuery, tokens);
|
||||
const snippet = createSnippet("capabilities", "Agent", row.description ?? row.role ?? row.title, terms);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export { companyService } from "./companies.js";
|
||||
export { companyArtifactsService } from "./company-artifacts.js";
|
||||
export { companySearchService } from "./company-search.js";
|
||||
export { feedbackService } from "./feedback.js";
|
||||
export { companySkillService } from "./company-skills.js";
|
||||
|
||||
Reference in New Issue
Block a user