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:
@@ -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