mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task indicators tell an operator whether work is active, waiting, or
complete.
> - An agent can yield until a saved monitor checks CI or another
external result.
> - The task currently keeps the In Progress icon between those runs.
> - Changing the stored status would affect monitor admission and
recovery.
> - This pull request adds a read-only Monitoring display state with a
blue clock.
> - Operators can see and filter scheduled waits while execution keeps
its existing rules.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Task status indicators, task collection filters, board columns, and
search facets.
**Current behavior**
A task that waits for a scheduled monitor shows the same In Progress
icon as active work.
**Proposed behavior**
Show Monitoring with a static blue clock when an agent-owned task has a
saved ordinary monitor and no active run, execution lock, review
participant, or active recovery action. Return to the normal task
indicator when the check starts. Preserve review, blocked, terminal, and
quota-recovery states.
**Reason and benefit**
Operators can distinguish scheduled waits from current agent work
without reading the task history.
**Breaking changes**
None to stored task statuses or execution rules. Task reads gain
optional displayStatus. Collections and search gain a separate read
filter. Existing status filters keep their lifecycle meaning.
Related historical work: #4396 covered a monitoring label exemption.
This change uses the saved monitor and a read projection.
## What Changed
- Add one SQL projection for task detail, compact lists, summaries,
relations, search results, and display-status counts.
- Show the blue clock in shared task icons and chips, task detail and
breadcrumbs, properties, references, list rows, recent navigation, and
agent task cards.
- Add Monitoring to task filtering, grouping, sorting, board columns,
and search facets. Prevent a drag from creating this derived state.
- Keep stored lifecycle statuses, monitor scheduling, checkout,
recovery, permissions, and agent status filters unchanged.
- Add database and UI regression coverage, full-page Storybook examples,
and product and access-map documentation.
## Verification
- Passed `pnpm -r typecheck`.
- Passed `pnpm build`.
- Passed `pnpm check:token-gates` and the map/catalog structural checks.
- Ran the new database suite on a disposable PostgreSQL 17 database. It
covers read surfaces, filter pagination/counts, queued/running checks,
rescheduling, completion, retained monitors, review, and recovery holds.
- Ran existing search, list, board, sidebar, task status, and filter
tests. Corrected board queries use displayStatus and eight columns.
- The full local `pnpm test:run` stopped in a chat integration shard: 12
failures (four timeouts and eight FIFO publication assertions). That run
spanned a rebase. A focused rerun on the current source passed all 21
selected cases without assertion or timeout changes. The original cause
is not established; this does not claim the full local suite passed.
Final-head required CI passed (ci / verify and ci / e2e, run
41488267209).
- Passed 82 tests for task API summaries, recovery precedence, search,
and optimistic updates; 54 tests for status cards, database reads, and
board moves; and 27 tests for blocker relations and recent-task cache
updates. One intermediate database setup hit its 20-second hook timeout;
the serial rerun passed.
- Greptile is 5/5 on d003ea672d. All
review threads are resolved. The separate optional Paperclip Review
ended early and returned neutral; GitHub rejected a direct rerun request
with HTTP 404. It is not counted as a completed review.
- Review fixes cover escalated recovery, is:open, optimistic status
changes, blocker-summary projection, and recent-task dedupe.
- Reviewed 15 screenshots from production pages and components with
isolated Storybook API fixtures: task detail/properties/breadcrumb,
list, groups, status filter, board, search/results/filter counts,
reference pills, sibling navigation, agent cards, picker, dashboard,
inbox, profile, watched status-card tasks, light theme, and mobile. This
does not claim deployed staging verification.
## Risks
- Read projections must stay consistent across full, compact, summary,
and search responses. Tests cover those paths.
- Monitoring is not a writable lifecycle status. The board does not
accept drops into its Monitoring lane or onto a monitored card. This
prevents a drag from implying a scheduled check. Move work into In
Progress through that lane instead.
- The read projection adds run/recovery existence checks. Existing
heartbeat_runs_company_issue_created_idx and
issue_recovery_actions_company_source_status_idx indexes cover the
company/task lookup. It adds no worker, timer, recurring query,
migration, or provider call. No production load benchmark is claimed.
- Older clients can ignore displayStatus. Existing lifecycle status
filters keep their behavior.
## Model Used
OpenAI Codex, GPT-6, with reasoning, repository tools, code execution,
and browser tools. The exact backend model identifier and context-window
size are not exposed in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
463 lines
16 KiB
TypeScript
463 lines
16 KiB
TypeScript
import { issueDisplayStatusSql } from "../services/issue-display-status.js";
|
||
import { Router } from "express";
|
||
import { and, desc, eq, gte, inArray, isNull, or, sql, type SQLWrapper } from "drizzle-orm";
|
||
import type { Db } from "@paperclipai/db";
|
||
import {
|
||
activityLog,
|
||
agents,
|
||
authUsers,
|
||
companyMemberships,
|
||
costEvents,
|
||
issueComments,
|
||
issues,
|
||
} from "@paperclipai/db";
|
||
import type {
|
||
UserProfileDailyPoint,
|
||
UserProfileIdentity,
|
||
UserProfileResponse,
|
||
UserProfileWindowStats,
|
||
} from "@paperclipai/shared";
|
||
import { notFound } from "../errors.js";
|
||
import { visibleIssueCondition } from "../services/issue-visibility.js";
|
||
import { assertCompanyAccess } from "./authz.js";
|
||
|
||
type CompanyUserRow = {
|
||
id: string;
|
||
principalId: string;
|
||
status: string;
|
||
membershipRole: string | null;
|
||
createdAt: Date;
|
||
userId: string | null;
|
||
name: string | null;
|
||
email: string | null;
|
||
image: string | null;
|
||
};
|
||
|
||
const PROFILE_WINDOWS = [
|
||
{ key: "last7", label: "Last 7 days", days: 7 },
|
||
{ key: "last30", label: "Last 30 days", days: 30 },
|
||
{ key: "all", label: "All time", days: null },
|
||
] as const;
|
||
|
||
function slugifyUserPart(value: string | null | undefined) {
|
||
const normalized = value
|
||
?.trim()
|
||
.toLowerCase()
|
||
.replace(/['"]/g, "")
|
||
.replace(/[^a-z0-9]+/g, "-")
|
||
.replace(/^-+|-+$/g, "");
|
||
return normalized || null;
|
||
}
|
||
|
||
function userSlugCandidates(row: CompanyUserRow) {
|
||
const candidates = new Set<string>();
|
||
const add = (value: string | null | undefined) => {
|
||
const slug = slugifyUserPart(value);
|
||
if (slug) candidates.add(slug);
|
||
};
|
||
add(row.name);
|
||
add(row.email?.split("@")[0]);
|
||
add(row.email);
|
||
add(row.principalId);
|
||
return [...candidates];
|
||
}
|
||
|
||
function userSlugSql(value: SQLWrapper) {
|
||
// Match JavaScript's ASCII slug after Unicode lowercasing, independently of
|
||
// the database locale. Only İ and K lowercase to ASCII from outside ASCII;
|
||
// İ also leaves a combining dot, which becomes a separator. Replace whole
|
||
// multibyte strings before ASCII-only translate so SQL_ASCII databases do
|
||
// not translate individual UTF-8 bytes. translate also drops both quotes.
|
||
return sql<string>`btrim(regexp_replace(translate(replace(replace(${value}, 'İ', 'i-'), 'K', 'k'),
|
||
'ABCDEFGHIJKLMNOPQRSTUVWXYZ''"', 'abcdefghijklmnopqrstuvwxyz') collate "C",
|
||
'[^a-z0-9]+', '-', 'g'), '-')`;
|
||
}
|
||
|
||
async function resolveCompanyUser(db: Db, companyId: string, rawSlug: string): Promise<CompanyUserRow | null> {
|
||
const slug = slugifyUserPart(rawSlug);
|
||
if (!slug) return null;
|
||
|
||
const select = () => db.select({
|
||
id: companyMemberships.id,
|
||
principalId: companyMemberships.principalId,
|
||
status: companyMemberships.status,
|
||
membershipRole: companyMemberships.membershipRole,
|
||
createdAt: companyMemberships.createdAt,
|
||
userId: authUsers.id,
|
||
name: authUsers.name,
|
||
email: authUsers.email,
|
||
image: authUsers.image,
|
||
})
|
||
.from(companyMemberships)
|
||
.leftJoin(authUsers, eq(authUsers.id, companyMemberships.principalId));
|
||
const scope = and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.principalType, "user"));
|
||
const order = [desc(companyMemberships.updatedAt), desc(companyMemberships.id)];
|
||
|
||
// Known-user links use principal IDs. Prefer an indexed exact identity over
|
||
// a namesake's display slug, including older memberships beyond row 200.
|
||
const [exact] = await select()
|
||
.where(and(scope, inArray(companyMemberships.principalId, [...new Set([rawSlug, slug])])))
|
||
.orderBy(desc(sql`${companyMemberships.principalId} = ${rawSlug}`), ...order)
|
||
.limit(1);
|
||
if (exact) return exact;
|
||
|
||
// A normalized non-UUID ID cannot be reversed. Search all supported aliases
|
||
// in one bounded result instead of fetching/sorting successive member pages.
|
||
const [match] = await select()
|
||
.where(and(scope, or(
|
||
eq(userSlugSql(authUsers.name), slug),
|
||
eq(userSlugSql(sql`split_part(${authUsers.email}, '@', 1)`), slug),
|
||
eq(userSlugSql(authUsers.email), slug),
|
||
eq(userSlugSql(companyMemberships.principalId), slug),
|
||
)))
|
||
.orderBy(...order)
|
||
.limit(1);
|
||
return match ?? null;
|
||
}
|
||
|
||
function userIssueInvolvementSql(companyId: string, userId: string) {
|
||
return sql<boolean>`
|
||
(
|
||
${issues.createdByUserId} = ${userId}
|
||
OR ${issues.assigneeUserId} = ${userId}
|
||
OR EXISTS (
|
||
SELECT 1
|
||
FROM ${issueComments}
|
||
WHERE ${issueComments.companyId} = ${companyId}
|
||
AND ${issueComments.issueId} = ${issues.id}
|
||
AND ${issueComments.authorUserId} = ${userId}
|
||
)
|
||
)
|
||
`;
|
||
}
|
||
|
||
function windowStart(days: number | null) {
|
||
if (!days) return null;
|
||
return new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||
}
|
||
|
||
function startOfUtcDay(date: Date) {
|
||
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
||
}
|
||
|
||
function isoDay(date: Date) {
|
||
return startOfUtcDay(date).toISOString().slice(0, 10);
|
||
}
|
||
|
||
function dayKeyExpr(dateSql: ReturnType<typeof sql>) {
|
||
return sql<string>`to_char(date_trunc('day', ${dateSql}), 'YYYY-MM-DD')`;
|
||
}
|
||
|
||
function sumNumber(column: typeof costEvents.costCents | typeof costEvents.inputTokens | typeof costEvents.cachedInputTokens | typeof costEvents.outputTokens) {
|
||
return sql<number>`coalesce(sum(${column}), 0)::double precision`;
|
||
}
|
||
|
||
async function loadWindowStats(
|
||
db: Db,
|
||
companyId: string,
|
||
userId: string,
|
||
key: UserProfileWindowStats["key"],
|
||
label: string,
|
||
from: Date | null,
|
||
): Promise<UserProfileWindowStats> {
|
||
const involvement = userIssueInvolvementSql(companyId, userId);
|
||
const openStatuses = ["backlog", "todo", "in_progress", "in_review", "blocked"];
|
||
const fromIso = from?.toISOString();
|
||
|
||
const [issueStats] = await db
|
||
.select({
|
||
touchedIssues: sql<number>`count(distinct case when ${involvement} ${fromIso ? sql`and ${issues.updatedAt} >= ${fromIso}` : sql``} then ${issues.id} end)::int`,
|
||
createdIssues: sql<number>`count(distinct case when ${issues.createdByUserId} = ${userId} ${fromIso ? sql`and ${issues.createdAt} >= ${fromIso}` : sql``} then ${issues.id} end)::int`,
|
||
completedIssues: sql<number>`count(distinct case when ${involvement} and ${issues.status} = 'done' ${fromIso ? sql`and ${issues.completedAt} >= ${fromIso}` : sql``} then ${issues.id} end)::int`,
|
||
assignedOpenIssues: sql<number>`count(distinct case when ${issues.assigneeUserId} = ${userId} and ${issues.status} in (${sql.join(openStatuses.map((status) => sql`${status}`), sql`, `)}) then ${issues.id} end)::int`,
|
||
})
|
||
.from(issues)
|
||
.where(and(eq(issues.companyId, companyId), visibleIssueCondition()));
|
||
|
||
const commentConditions = [
|
||
eq(issueComments.companyId, companyId),
|
||
eq(issueComments.authorUserId, userId),
|
||
];
|
||
if (from) commentConditions.push(gte(issueComments.createdAt, from));
|
||
const [commentStats] = await db
|
||
.select({ count: sql<number>`count(*)::int` })
|
||
.from(issueComments)
|
||
.where(and(...commentConditions));
|
||
|
||
const activityConditions = [
|
||
eq(activityLog.companyId, companyId),
|
||
eq(activityLog.actorType, "user"),
|
||
eq(activityLog.actorId, userId),
|
||
];
|
||
if (from) activityConditions.push(gte(activityLog.createdAt, from));
|
||
const [activityStats] = await db
|
||
.select({ count: sql<number>`count(*)::int` })
|
||
.from(activityLog)
|
||
.where(and(...activityConditions));
|
||
|
||
const costConditions = [
|
||
eq(costEvents.companyId, companyId),
|
||
userIssueInvolvementSql(companyId, userId),
|
||
];
|
||
if (from) costConditions.push(gte(costEvents.occurredAt, from));
|
||
const [costStats] = await db
|
||
.select({
|
||
costCents: sumNumber(costEvents.costCents),
|
||
inputTokens: sumNumber(costEvents.inputTokens),
|
||
cachedInputTokens: sumNumber(costEvents.cachedInputTokens),
|
||
outputTokens: sumNumber(costEvents.outputTokens),
|
||
costEventCount: sql<number>`count(${costEvents.id})::int`,
|
||
})
|
||
.from(costEvents)
|
||
.innerJoin(issues, and(eq(issues.id, costEvents.issueId), eq(issues.companyId, costEvents.companyId)))
|
||
.where(and(...costConditions));
|
||
|
||
return {
|
||
key,
|
||
label,
|
||
touchedIssues: Number(issueStats?.touchedIssues ?? 0),
|
||
createdIssues: Number(issueStats?.createdIssues ?? 0),
|
||
completedIssues: Number(issueStats?.completedIssues ?? 0),
|
||
assignedOpenIssues: Number(issueStats?.assignedOpenIssues ?? 0),
|
||
commentCount: Number(commentStats?.count ?? 0),
|
||
activityCount: Number(activityStats?.count ?? 0),
|
||
costCents: Number(costStats?.costCents ?? 0),
|
||
inputTokens: Number(costStats?.inputTokens ?? 0),
|
||
cachedInputTokens: Number(costStats?.cachedInputTokens ?? 0),
|
||
outputTokens: Number(costStats?.outputTokens ?? 0),
|
||
costEventCount: Number(costStats?.costEventCount ?? 0),
|
||
};
|
||
}
|
||
|
||
async function loadDailyStats(db: Db, companyId: string, userId: string): Promise<UserProfileDailyPoint[]> {
|
||
const firstDay = startOfUtcDay(new Date(Date.now() - 13 * 24 * 60 * 60 * 1000));
|
||
const points = new Map<string, UserProfileDailyPoint>();
|
||
for (let index = 0; index < 14; index += 1) {
|
||
const date = new Date(firstDay.getTime() + index * 24 * 60 * 60 * 1000);
|
||
points.set(isoDay(date), {
|
||
date: isoDay(date),
|
||
activityCount: 0,
|
||
completedIssues: 0,
|
||
costCents: 0,
|
||
inputTokens: 0,
|
||
cachedInputTokens: 0,
|
||
outputTokens: 0,
|
||
});
|
||
}
|
||
|
||
const activityDay = dayKeyExpr(sql`${activityLog.createdAt}`);
|
||
const activityRows = await db
|
||
.select({
|
||
date: activityDay,
|
||
count: sql<number>`count(*)::int`,
|
||
})
|
||
.from(activityLog)
|
||
.where(
|
||
and(
|
||
eq(activityLog.companyId, companyId),
|
||
eq(activityLog.actorType, "user"),
|
||
eq(activityLog.actorId, userId),
|
||
gte(activityLog.createdAt, firstDay),
|
||
),
|
||
)
|
||
.groupBy(activityDay);
|
||
|
||
for (const row of activityRows) {
|
||
const point = points.get(row.date);
|
||
if (point) point.activityCount = Number(row.count);
|
||
}
|
||
|
||
const completedDay = dayKeyExpr(sql`${issues.completedAt}`);
|
||
const completedRows = await db
|
||
.select({
|
||
date: completedDay,
|
||
count: sql<number>`count(distinct ${issues.id})::int`,
|
||
})
|
||
.from(issues)
|
||
.where(
|
||
and(
|
||
eq(issues.companyId, companyId),
|
||
visibleIssueCondition(),
|
||
eq(issues.status, "done"),
|
||
gte(issues.completedAt, firstDay),
|
||
userIssueInvolvementSql(companyId, userId),
|
||
),
|
||
)
|
||
.groupBy(completedDay);
|
||
|
||
for (const row of completedRows) {
|
||
const point = points.get(row.date);
|
||
if (point) point.completedIssues = Number(row.count);
|
||
}
|
||
|
||
const costDay = dayKeyExpr(sql`${costEvents.occurredAt}`);
|
||
const costRows = await db
|
||
.select({
|
||
date: costDay,
|
||
costCents: sumNumber(costEvents.costCents),
|
||
inputTokens: sumNumber(costEvents.inputTokens),
|
||
cachedInputTokens: sumNumber(costEvents.cachedInputTokens),
|
||
outputTokens: sumNumber(costEvents.outputTokens),
|
||
})
|
||
.from(costEvents)
|
||
.innerJoin(issues, and(eq(issues.id, costEvents.issueId), eq(issues.companyId, costEvents.companyId)))
|
||
.where(
|
||
and(
|
||
eq(costEvents.companyId, companyId),
|
||
gte(costEvents.occurredAt, firstDay),
|
||
userIssueInvolvementSql(companyId, userId),
|
||
),
|
||
)
|
||
.groupBy(costDay);
|
||
|
||
for (const row of costRows) {
|
||
const point = points.get(row.date);
|
||
if (!point) continue;
|
||
point.costCents = Number(row.costCents);
|
||
point.inputTokens = Number(row.inputTokens);
|
||
point.cachedInputTokens = Number(row.cachedInputTokens);
|
||
point.outputTokens = Number(row.outputTokens);
|
||
}
|
||
|
||
return [...points.values()];
|
||
}
|
||
|
||
export function userProfileRoutes(db: Db) {
|
||
const router = Router();
|
||
|
||
router.get("/companies/:companyId/users/:userSlug/profile", async (req, res) => {
|
||
const companyId = req.params.companyId as string;
|
||
const userSlug = req.params.userSlug as string;
|
||
assertCompanyAccess(req, companyId);
|
||
|
||
const row = await resolveCompanyUser(db, companyId, userSlug);
|
||
if (!row) throw notFound("User not found");
|
||
const canonicalSlug = userSlugCandidates(row)[0] ?? row.principalId;
|
||
const userId = row.userId ?? row.principalId;
|
||
|
||
const [stats, daily, recentIssues, recentActivity, topAgents, topProviders] = await Promise.all([
|
||
Promise.all(
|
||
PROFILE_WINDOWS.map((entry) =>
|
||
loadWindowStats(db, companyId, userId, entry.key, entry.label, windowStart(entry.days)),
|
||
),
|
||
),
|
||
loadDailyStats(db, companyId, userId),
|
||
db
|
||
.select({
|
||
id: issues.id,
|
||
identifier: issues.identifier,
|
||
title: issues.title,
|
||
status: issues.status,
|
||
displayStatus: issueDisplayStatusSql(),
|
||
priority: issues.priority,
|
||
assigneeAgentId: issues.assigneeAgentId,
|
||
assigneeUserId: issues.assigneeUserId,
|
||
updatedAt: issues.updatedAt,
|
||
completedAt: issues.completedAt,
|
||
})
|
||
.from(issues)
|
||
.where(
|
||
and(
|
||
eq(issues.companyId, companyId),
|
||
visibleIssueCondition(),
|
||
userIssueInvolvementSql(companyId, userId),
|
||
),
|
||
)
|
||
.orderBy(desc(issues.updatedAt))
|
||
.limit(8),
|
||
db
|
||
.select({
|
||
id: activityLog.id,
|
||
action: activityLog.action,
|
||
entityType: activityLog.entityType,
|
||
entityId: activityLog.entityId,
|
||
details: activityLog.details,
|
||
createdAt: activityLog.createdAt,
|
||
})
|
||
.from(activityLog)
|
||
.where(
|
||
and(
|
||
eq(activityLog.companyId, companyId),
|
||
eq(activityLog.actorType, "user"),
|
||
eq(activityLog.actorId, userId),
|
||
),
|
||
)
|
||
.orderBy(desc(activityLog.createdAt))
|
||
.limit(12),
|
||
db
|
||
.select({
|
||
agentId: costEvents.agentId,
|
||
agentName: agents.name,
|
||
costCents: sumNumber(costEvents.costCents),
|
||
inputTokens: sumNumber(costEvents.inputTokens),
|
||
cachedInputTokens: sumNumber(costEvents.cachedInputTokens),
|
||
outputTokens: sumNumber(costEvents.outputTokens),
|
||
})
|
||
.from(costEvents)
|
||
.innerJoin(issues, and(eq(issues.id, costEvents.issueId), eq(issues.companyId, costEvents.companyId)))
|
||
.leftJoin(agents, eq(agents.id, costEvents.agentId))
|
||
.where(and(eq(costEvents.companyId, companyId), userIssueInvolvementSql(companyId, userId)))
|
||
.groupBy(costEvents.agentId, agents.name)
|
||
.orderBy(desc(sumNumber(costEvents.costCents)))
|
||
.limit(5),
|
||
db
|
||
.select({
|
||
provider: costEvents.provider,
|
||
biller: costEvents.biller,
|
||
model: costEvents.model,
|
||
costCents: sumNumber(costEvents.costCents),
|
||
inputTokens: sumNumber(costEvents.inputTokens),
|
||
cachedInputTokens: sumNumber(costEvents.cachedInputTokens),
|
||
outputTokens: sumNumber(costEvents.outputTokens),
|
||
})
|
||
.from(costEvents)
|
||
.innerJoin(issues, and(eq(issues.id, costEvents.issueId), eq(issues.companyId, costEvents.companyId)))
|
||
.where(and(eq(costEvents.companyId, companyId), userIssueInvolvementSql(companyId, userId)))
|
||
.groupBy(costEvents.provider, costEvents.biller, costEvents.model)
|
||
.orderBy(desc(sumNumber(costEvents.costCents)))
|
||
.limit(5),
|
||
]);
|
||
|
||
const user: UserProfileIdentity = {
|
||
id: userId,
|
||
slug: canonicalSlug,
|
||
name: row.name,
|
||
email: row.email,
|
||
image: row.image,
|
||
membershipRole: row.membershipRole,
|
||
membershipStatus: row.status,
|
||
joinedAt: row.createdAt,
|
||
};
|
||
|
||
const payload: UserProfileResponse = {
|
||
user,
|
||
stats,
|
||
daily,
|
||
recentIssues: recentIssues.map((issue) => ({
|
||
...issue,
|
||
status: issue.status as UserProfileResponse["recentIssues"][number]["status"],
|
||
priority: issue.priority as UserProfileResponse["recentIssues"][number]["priority"],
|
||
})),
|
||
recentActivity,
|
||
topAgents: topAgents.map((entry) => ({
|
||
...entry,
|
||
costCents: Number(entry.costCents),
|
||
inputTokens: Number(entry.inputTokens),
|
||
cachedInputTokens: Number(entry.cachedInputTokens),
|
||
outputTokens: Number(entry.outputTokens),
|
||
})),
|
||
topProviders: topProviders.map((entry) => ({
|
||
...entry,
|
||
costCents: Number(entry.costCents),
|
||
inputTokens: Number(entry.inputTokens),
|
||
cachedInputTokens: Number(entry.cachedInputTokens),
|
||
outputTokens: Number(entry.outputTokens),
|
||
})),
|
||
};
|
||
|
||
res.json(payload);
|
||
});
|
||
|
||
return router;
|
||
}
|