mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 08:22:20 +02:00
## Thinking Path > - Paperclip orchestrates AI agents for autonomous companies, and heartbeat execution is the control-plane loop that keeps assigned work moving. > - Max-turn exhaustion is a recoverable local-adapter stop condition for Claude and Gemini agents when a run needs another heartbeat to continue safely. > - The previous behavior could leave max-turn continuation details hard to inspect, and duplicate/stale continuation wakes could keep running after issue state changed. > - The adapter layer also needed to avoid trusting arbitrary stdout/stderr text as scheduler control metadata. > - This pull request adds bounded max-turn continuation scheduling, visible retry state, structured stop metadata handling, and stale/duplicate continuation guards. > - The benefit is safer automatic continuation after max-turn stops, clearer operator visibility, and fewer duplicate or stale agent runs. ## What Changed - Replaces closed PR #4952, whose head repository was deleted. - Rebases the recovered max-turn continuation branch onto current `paperclipai/paperclip:master`. - Adds max-turn continuation scheduling and retry-state plumbing for heartbeat runs. - Adds stale/duplicate continuation suppression when issue status, ownership, or execution locks change. - Normalizes Claude/Gemini max-turn detection around structured stop metadata instead of unstructured stdout/stderr text. - Surfaces max-turn continuation settings and retry visibility in the board UI. - Adds focused server, adapter, and UI tests for max-turn stop metadata, retry scheduling, stale queued-run invalidation, adapter parsing/execution, run ledger display, and agent config patching. ## Verification - `pnpm install --no-frozen-lockfile` to refresh local dependencies after rebasing onto current `master`. - `pnpm run preflight:workspace-links && pnpm exec vitest run server/src/__tests__/claude-local-adapter.test.ts server/src/__tests__/claude-local-execute.test.ts server/src/__tests__/gemini-local-adapter.test.ts server/src/__tests__/gemini-local-execute.test.ts server/src/__tests__/heartbeat-retry-scheduling.test.ts server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts server/src/services/heartbeat-stop-metadata.test.ts ui/src/components/IssueRunLedger.test.tsx ui/src/lib/agent-config-patch.test.ts ui/src/lib/runRetryState.test.ts --testTimeout=20000` - `pnpm --filter @paperclipai/adapter-claude-local typecheck && pnpm --filter @paperclipai/adapter-gemini-local typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter @paperclipai/ui typecheck` - UI screenshot note: the UI changes are limited to config/ledger state rendering rather than layout changes; component/unit coverage above verifies the rendered behavior. ## Risks - Medium behavior risk: heartbeat retry gating now suppresses max-turn continuations when issue state or execution locks drift, so any callers that relied on stale continuations running will now see cancellation instead. - Low adapter risk: Claude/Gemini unstructured text no longer triggers max-turn scheduler metadata, so only structured stop signals and Gemini exit code 53 are trusted. - No database migrations. > 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 coding agent, GPT-5-class model, tool-enabled local repository editing and command execution. ## 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 (not applicable: state/default rendering only; covered by component/unit tests) - [x] I have updated relevant documentation to reflect my changes (not applicable: no user-facing command or docs contract changed) - [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>
207 lines
6.9 KiB
TypeScript
207 lines
6.9 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);
|
|
}
|
|
|
|
/** 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}`;
|
|
}
|