paperclip/ui/src/lib/utils.ts
Dotta 424e81d087
Improve operator workflow QoL (#5291)
## Thinking Path

> - Paperclip is a control plane operators use repeatedly to supervise
agent companies.
> - Common operator workflows depend on fast scanning of inboxes, issue
sidebars, workspaces, cost totals, and runtime services.
> - Several small UI and service gaps made those workflows slower or
less clear.
> - This pull request groups the operator-facing QoL changes that can
stand alone from recovery and adapter work.
> - The benefit is a denser, clearer board experience for issue triage
and workspace operation.

## What Changed

- Added inbox assignee/project grouping and issue list token/runtime
totals.
- Improved issue properties with removable blocker chips and workspace
task links.
- Improved execution workspace layout, runtime controls, issues tab
default, and stopped-port reuse behavior.
- Added mobile markdown/routine dialog fixes, page title company names,
sidebar polish, and dashboard run task label cleanup.

## Verification

- `pnpm install --frozen-lockfile`
- `pnpm exec vitest run ui/src/lib/inbox.test.ts
ui/src/components/IssueProperties.test.tsx
ui/src/components/WorkspaceRuntimeControls.test.tsx
server/src/__tests__/workspace-runtime.test.ts
server/src/__tests__/costs-service.test.ts`

## Risks

- Medium UI risk because this touches several operator surfaces. The
branch is intentionally grouped around workflow/QoL files and keeps the
file count below the Greptile limit.

## Model Used

- OpenAI GPT-5 Codex via Paperclip `codex_local` adapter, with
shell/git/GitHub CLI tool use.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-05-06 06:30:44 -05:00

224 lines
7.7 KiB
TypeScript

import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { deriveAgentUrlKey, deriveProjectUrlKey, normalizeProjectUrlKey, hasNonAsciiContent } from "@paperclipai/shared";
import type { BillingType, FinanceDirection, FinanceEventKind } from "@paperclipai/shared";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function asObject(value: unknown): Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
? value as Record<string, unknown>
: {};
}
export function asBoolean(value: unknown, fallback: boolean) {
return typeof value === "boolean" ? value : fallback;
}
export function asFiniteNumber(value: unknown, fallback: number) {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
export function formatCents(cents: number): string {
return `$${(cents / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
export function formatNumber(n: number): string {
return n.toLocaleString("en-US");
}
export function formatDate(date: Date | string): string {
return new Date(date).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
});
}
export function formatDateTime(date: Date | string): string {
return new Date(date).toLocaleString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
});
}
export function formatShortDate(date: Date | string): string {
return new Date(date).toLocaleString("en-US", {
month: "short",
day: "numeric",
});
}
export function relativeTime(date: Date | string): string {
const now = Date.now();
const then = new Date(date).getTime();
const diffSec = Math.round((now - then) / 1000);
if (diffSec < 60) return "just now";
const diffMin = Math.round(diffSec / 60);
if (diffMin < 60) return `${diffMin}m ago`;
const diffHr = Math.round(diffMin / 60);
if (diffHr < 24) return `${diffHr}h ago`;
const diffDay = Math.round(diffHr / 24);
if (diffDay < 30) return `${diffDay}d ago`;
return formatDate(date);
}
export function formatTokens(n: number): string {
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(1)}B`;
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
return String(n);
}
/** Humanize a millisecond duration into a compact `1h 2m`, `45m 12s`, `12s` string. */
export function formatDurationMs(ms: number): string {
if (!Number.isFinite(ms) || ms <= 0) return "0s";
const totalSeconds = Math.round(ms / 1000);
if (totalSeconds < 60) return `${totalSeconds}s`;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
if (minutes < 60) return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
if (hours < 24) {
return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
}
const days = Math.floor(hours / 24);
const remainingHours = hours % 24;
return remainingHours > 0 ? `${days}d ${remainingHours}h` : `${days}d`;
}
/** Map a raw provider slug to a display-friendly name. */
export function providerDisplayName(provider: string): string {
const map: Record<string, string> = {
anthropic: "Anthropic",
aws_bedrock: "AWS Bedrock",
openai: "OpenAI",
openrouter: "OpenRouter",
chatgpt: "ChatGPT",
google: "Google",
cursor: "Cursor",
jetbrains: "JetBrains AI",
};
return map[provider.toLowerCase()] ?? provider;
}
export function billingTypeDisplayName(billingType: BillingType): string {
const map: Record<BillingType, string> = {
metered_api: "Metered API",
subscription_included: "Subscription",
subscription_overage: "Subscription overage",
credits: "Credits",
fixed: "Fixed",
unknown: "Unknown",
};
return map[billingType];
}
export function quotaSourceDisplayName(source: string): string {
const map: Record<string, string> = {
"anthropic-oauth": "Anthropic OAuth",
"claude-cli": "Claude CLI",
"bedrock": "AWS Bedrock",
"codex-rpc": "Codex app server",
"codex-wham": "ChatGPT WHAM",
};
return map[source] ?? source;
}
function coerceBillingType(value: unknown): BillingType | null {
if (
value === "metered_api" ||
value === "subscription_included" ||
value === "subscription_overage" ||
value === "credits" ||
value === "fixed" ||
value === "unknown"
) {
return value;
}
return null;
}
function readRunCostUsd(payload: Record<string, unknown> | null): number {
if (!payload) return 0;
for (const key of ["costUsd", "cost_usd", "total_cost_usd"] as const) {
const value = payload[key];
if (typeof value === "number" && Number.isFinite(value)) return value;
}
return 0;
}
export function visibleRunCostUsd(
usage: Record<string, unknown> | null,
result: Record<string, unknown> | null = null,
): number {
const billingType = coerceBillingType(usage?.billingType) ?? coerceBillingType(result?.billingType);
if (billingType === "subscription_included") return 0;
return readRunCostUsd(usage) || readRunCostUsd(result);
}
export function financeEventKindDisplayName(eventKind: FinanceEventKind): string {
const map: Record<FinanceEventKind, string> = {
inference_charge: "Inference charge",
platform_fee: "Platform fee",
credit_purchase: "Credit purchase",
credit_refund: "Credit refund",
credit_expiry: "Credit expiry",
byok_fee: "BYOK fee",
gateway_overhead: "Gateway overhead",
log_storage_charge: "Log storage",
logpush_charge: "Logpush",
provisioned_capacity_charge: "Provisioned capacity",
training_charge: "Training",
custom_model_import_charge: "Custom model import",
custom_model_storage_charge: "Custom model storage",
manual_adjustment: "Manual adjustment",
};
return map[eventKind];
}
export function financeDirectionDisplayName(direction: FinanceDirection): string {
return direction === "credit" ? "Credit" : "Debit";
}
/** Build an issue URL using the human-readable identifier when available. */
export function issueUrl(issue: { id: string; identifier?: string | null }): string {
return `/issues/${issue.identifier ?? issue.id}`;
}
/** Build an agent route URL using the short URL key when available. */
export function agentRouteRef(agent: { id: string; urlKey?: string | null; name?: string | null }): string {
return agent.urlKey ?? deriveAgentUrlKey(agent.name, agent.id);
}
/** Build an agent URL using the short URL key when available. */
export function agentUrl(agent: { id: string; urlKey?: string | null; name?: string | null }): string {
return `/agents/${agentRouteRef(agent)}`;
}
/** Build a project route reference, falling back to UUID when the derived key is ambiguous. */
export function projectRouteRef(project: { id: string; urlKey?: string | null; name?: string | null }): string {
const key = project.urlKey ?? deriveProjectUrlKey(project.name, project.id);
// Guard for rolling deploys or legacy data where the server returned a bare slug without UUID suffix.
if (key === normalizeProjectUrlKey(project.name) && hasNonAsciiContent(project.name)) return project.id;
return key;
}
/** Build a project URL using the short URL key when available. */
export function projectUrl(project: { id: string; urlKey?: string | null; name?: string | null }): string {
return `/projects/${projectRouteRef(project)}`;
}
/** Build a project workspace URL scoped under its project. */
export function projectWorkspaceUrl(
project: { id: string; urlKey?: string | null; name?: string | null },
workspaceId: string,
): string {
return `${projectUrl(project)}/workspaces/${workspaceId}`;
}