mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
Merge origin/master and renumber additive Speko migrations
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
bf1ead3772
65 files changed
+5336
-56682
No files matched your search
@@ -43,6 +43,24 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("tenant-session recovery", () => {
|
||||
it("loads anonymous Dot consent despite concurrent protected background probes", async () => {
|
||||
const reload = vi.fn();
|
||||
const requestId = `pcmcp_request_${"a".repeat(43)}`;
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => `/dot-connect/${requestId}`);
|
||||
vi.spyOn(tenantSessionRecovery, "recoverIfNeeded").mockImplementation(recovery.recoverIfNeeded);
|
||||
fetchMock.mockImplementation((url: string) => Promise.resolve(
|
||||
url.includes("/dot-mcp/requests/")
|
||||
? jsonResponse({ id: requestId, agentConnection: true })
|
||||
: errorResponse({ error: "tenant_session_required" }),
|
||||
));
|
||||
|
||||
const background = api.get("/health");
|
||||
const consent = api.get(`/dot-mcp/requests/${requestId}`);
|
||||
await expect(background).rejects.toMatchObject({ status: 401 });
|
||||
await expect(consent).resolves.toEqual({ id: requestId, agentConnection: true });
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps concurrent failures pending and schedules one top-level reload", async () => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { SubscriptionCostReport, UpdateSubscriptionPrice } from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
|
||||
export const subscriptionsApi = {
|
||||
report(companyId: string, from?: string, to?: string) {
|
||||
const query = new URLSearchParams();
|
||||
if (from) query.set("from", from);
|
||||
if (to) query.set("to", to);
|
||||
if (!from && !to) query.set("period", "all");
|
||||
return api.get<SubscriptionCostReport>(`/companies/${companyId}/costs/subscriptions?${query}`);
|
||||
},
|
||||
refresh: (companyId: string) => api.post<{ status: string }>(`/companies/${companyId}/costs/subscriptions/refresh`, {}),
|
||||
update: (companyId: string, id: string, input: UpdateSubscriptionPrice) =>
|
||||
api.patch(`/companies/${companyId}/costs/subscriptions/${id}`, input),
|
||||
link: (companyId: string, id: string, targetId: string, expectedRevision: number, targetRevision: number) =>
|
||||
api.post(`/companies/${companyId}/costs/subscriptions/${id}/link`, { targetId, expectedRevision, targetRevision }),
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { CostByAgent } from "@paperclipai/shared";
|
||||
import { formatCents } from "../lib/utils";
|
||||
import { CostEstimateLabel } from "./CostEstimateLabel";
|
||||
|
||||
export function CostAmount({
|
||||
costCents,
|
||||
eventCount,
|
||||
estimatedEventCount,
|
||||
unpricedEventCount,
|
||||
suffix,
|
||||
}: Pick<CostByAgent, "costCents"> & Partial<Pick<CostByAgent, "eventCount" | "estimatedEventCount">> & {
|
||||
unpricedEventCount?: number;
|
||||
suffix?: ReactNode;
|
||||
}) {
|
||||
const entirelyUnpriced = costCents === 0 && (eventCount ?? 0) > 0 && unpricedEventCount === eventCount;
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1 text-right">
|
||||
<div className="whitespace-nowrap font-mono font-medium tabular-nums">
|
||||
{entirelyUnpriced ? "—" : formatCents(costCents)}
|
||||
{suffix}
|
||||
</div>
|
||||
<CostEstimateLabel eventCount={eventCount} estimatedEventCount={estimatedEventCount} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { CostByUserReport } from "@paperclipai/shared";
|
||||
import { CostEstimateLabel } from "./CostEstimateLabel";
|
||||
import { CostAmount } from "./CostAmount";
|
||||
import { Identity } from "./Identity";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
|
||||
import { formatCents, formatTokens } from "../lib/utils";
|
||||
import { formatTokens } from "../lib/utils";
|
||||
|
||||
export function CostByUserTable({ report }: { report: CostByUserReport }) {
|
||||
return (
|
||||
@@ -38,8 +38,7 @@ export function CostByUserTable({ report }: { report: CostByUserReport }) {
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums">{formatTokens(row.outputTokens)}</td>
|
||||
<td className="py-3 pl-4 text-right tabular-nums">
|
||||
<div>{row.costCents === 0 && row.eventCount > 0 && row.unpricedEventCount === row.eventCount ? "—" : formatCents(row.costCents)}</div>
|
||||
<CostEstimateLabel eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} unpricedEventCount={row.unpricedEventCount} />
|
||||
{row.unpricedEventCount > 0 && <div className="whitespace-nowrap text-xs text-muted-foreground">{row.unpricedEventCount} unpriced {row.unpricedEventCount === 1 ? "charge" : "charges"}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -221,7 +221,7 @@ it.each([{ enableOpenAiDot: false, enablePublicMcp: true }, { enableOpenAiDot: t
|
||||
});
|
||||
|
||||
it("copies one scoped Dot prompt, resumes on Back, and trusts only server readiness", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: null as any };
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
@@ -265,7 +265,7 @@ it("copies one scoped Dot prompt, resumes on Back, and trusts only server readin
|
||||
|
||||
it("waits for company approval before issuing a Dot capability", async () => {
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "pending-dot", status: "pending_approval" }, approvalId: "approval-id", binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "pending_approval", binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "pending_approval", agentLifecycleState: "pending_approval", canConfigureConnection: false, binding: null });
|
||||
await act(async () => cache.setQueryData(queryKeys.instance.experimentalSettings, { enableOpenAiDot: true, enablePublicMcp: true }));
|
||||
await click("Invite an external agent");
|
||||
await act(async () => [...document.querySelectorAll("button")].find(b => b.textContent?.startsWith("Dot"))!.click());
|
||||
@@ -298,7 +298,7 @@ const pendingDotBinding = (id: string, expiresAt: string) => ({
|
||||
});
|
||||
|
||||
it.each(["expired", "unavailable"])("automatically replaces an %s saved Dot prompt on opening", async condition => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: pendingDotBinding("saved-binding", new Date(Date.now() + (condition === "expired" ? -60000 : 900000)).toISOString()) };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: connection.binding });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
@@ -318,7 +318,7 @@ it.each(["expired", "unavailable"])("automatically replaces an %s saved Dot prom
|
||||
});
|
||||
|
||||
it("renews a Dot prompt that expires while setup stays open", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: null as any };
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
let generation = 0;
|
||||
@@ -342,10 +342,10 @@ it("renews a Dot prompt that expires while setup stays open", async () => {
|
||||
it("checks fresh connection state before renewing a cached pending Dot invitation", async () => {
|
||||
const staleBinding = pendingDotBinding("saved-binding", new Date(Date.now() - 60000).toISOString());
|
||||
cache.setQueryData(["dot-binding", "company-1", "dot-agent"], {
|
||||
enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: staleBinding,
|
||||
enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: staleBinding,
|
||||
});
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: staleBinding });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: { ...staleBinding, status: "ready", connected: true, subscriptionVerified: true } });
|
||||
await openDotSetup();
|
||||
expect(dotApi.connection).toHaveBeenCalled();
|
||||
@@ -354,7 +354,7 @@ it("checks fresh connection state before renewing a cached pending Dot invitatio
|
||||
});
|
||||
|
||||
it("offers a retry after automatic renewal fails without rotating on every poll", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: pendingDotBinding("saved-binding", new Date(Date.now() - 60000).toISOString()) };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: connection.binding });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
@@ -378,7 +378,7 @@ it("offers a retry after automatic renewal fails without rotating on every poll"
|
||||
|
||||
|
||||
it("does not let an older window renew another window's fresh Dot prompt", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: null as any };
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
@@ -396,7 +396,7 @@ it("does not let an older window renew another window's fresh Dot prompt", async
|
||||
});
|
||||
|
||||
it("retries the event test after Dot connects during a failed prompt renewal", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: pendingDotBinding("saved-binding", new Date(Date.now() - 60000).toISOString()) as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: connection.binding });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
@@ -411,3 +411,71 @@ it("retries the event test after Dot connects during a failed prompt renewal", a
|
||||
expect(dotApi.retry).toHaveBeenCalledExactlyOnceWith("company-1", "dot-agent", "saved-binding");
|
||||
expect(dotApi.pair).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
|
||||
it.each(["preparing", "verifying"])("prepares the Dot prompt while the hire is %s", async agentLifecycleState => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "paused",
|
||||
agentLifecycleState, canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
connection.binding = pendingDotBinding("binding", new Date(Date.now() + 900000).toISOString());
|
||||
return { bindingId: "binding", pairingCode: "setup-hire-code", expiresAt: connection.binding.pairingExpiresAt };
|
||||
});
|
||||
await openDotSetup();
|
||||
expect(dotApi.pair).toHaveBeenCalledTimes(1);
|
||||
expect(document.body.textContent).not.toContain("Resume this agent");
|
||||
await click("Copy setup prompt");
|
||||
expect(invites.copy.mock.calls[0][0]).toContain("setup-hire-code");
|
||||
});
|
||||
|
||||
it("does not prepare a Dot capability for a real paused agent", async () => {
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner",
|
||||
agentStatus: "paused", agentLifecycleState: "paused", canConfigureConnection: false, binding: null });
|
||||
await openDotSetup();
|
||||
expect(dotApi.pair).not.toHaveBeenCalled();
|
||||
expect(document.body.textContent).toContain("Resume this agent before connecting Dot.");
|
||||
});
|
||||
|
||||
it("keeps watching after the event check until hire verification completes", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "paused",
|
||||
agentLifecycleState: "verifying", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
connection.binding = pendingDotBinding("binding", new Date(Date.now() + 900000).toISOString());
|
||||
return { bindingId: "binding", pairingCode: "setup-hire-code", expiresAt: connection.binding.pairingExpiresAt };
|
||||
});
|
||||
await openDotSetup();
|
||||
connection.binding = { ...connection.binding, status: "ready", connected: true, subscriptionVerified: true, hasPendingChallenge: false };
|
||||
await act(async () => cache.invalidateQueries({ queryKey: ["dot-binding", "company-1", "dot-agent"] }));
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
|
||||
expect(document.body.textContent).not.toContain("Your Dot is connected");
|
||||
expect(document.body.textContent).toContain("Test event confirmed: complete");
|
||||
expect(document.body.textContent).toContain("Your Dot confirmed the test event. Paperclip is finishing agent setup.");
|
||||
const finishing = Array.from(document.querySelectorAll("button")).find(button => button.textContent?.includes("Finishing setup…"));
|
||||
expect(finishing?.disabled).toBe(true);
|
||||
connection.agentLifecycleState = "ready";
|
||||
connection.agentStatus = "idle";
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 2750)); });
|
||||
expect(document.body.textContent).toContain("Your Dot is connected");
|
||||
await click("Done");
|
||||
expect(state.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps completed checks but shows a pause blocker for a paired paused Dot", async () => {
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner",
|
||||
agentStatus: "paused", agentLifecycleState: "paused", canConfigureConnection: false,
|
||||
binding: { ...pendingDotBinding("binding", new Date(Date.now() + 900000).toISOString()),
|
||||
status: "ready", connected: true, subscriptionVerified: true, hasPendingChallenge: false } });
|
||||
await openDotSetup();
|
||||
expect(document.body.textContent).toContain("Test event confirmed: complete");
|
||||
expect(document.body.textContent).toContain("Resume this agent before connecting Dot.");
|
||||
expect(document.body.textContent).not.toContain("Finishing setup…");
|
||||
expect(document.body.textContent).not.toContain("Paperclip is finishing agent setup.");
|
||||
const blocked = Array.from(document.querySelectorAll("button")).find(button => button.textContent?.includes("Agent unavailable"));
|
||||
expect(blocked?.disabled).toBe(true);
|
||||
expect(dotApi.pair).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SubscriptionCostReport } from "@paperclipai/shared";
|
||||
import { SubscriptionCostCard } from "./SubscriptionCostCard";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ update: vi.fn(), link: vi.fn() }));
|
||||
vi.mock("../api/subscriptions", () => ({ subscriptionsApi: mocks }));
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const emptyUsage = () => ({ inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 });
|
||||
function fixture(): SubscriptionCostReport {
|
||||
const price = { revision: 0, plan: "Claude Max 5x", amountCents: "10000", monthlyCents: "10000", currency: "USD", cadence: "month" as const, status: "active" as const, source: "catalog" as const, sourceUrl: "https://claude.com/pricing", effectiveAt: "2026-10-08T00:00:00Z" };
|
||||
return { canRefresh: true, asOf: "2026-10-08T00:00:00Z", activeCount: 1, unknownPriceCount: 0, unidentifiedAccountCount: 0,
|
||||
monthlyTotals: [{ currency: "USD", amountCents: "10000", estimatedCount: 1 }],
|
||||
api: emptyUsage(), subscription: { ...emptyUsage(), inputTokens: 100, cachedInputTokens: 50, outputTokens: 10 }, unknown: emptyUsage(), unattributedSubscription: emptyUsage(),
|
||||
accounts: [{ id: "account-1", provider: "anthropic", name: "Alice’s Claude", ownerUserId: "alice", ownerName: "Alice", shared: false, identityVerified: true,
|
||||
detectedPlan: "max_5x", observedAt: "2026-10-08T00:00:00Z", lastCheckedAt: "2026-10-08T00:00:00Z", refreshStatus: "ok", canEdit: true,
|
||||
price, usage: emptyUsage(), agents: [{ id: "leela", name: "Leela" }] }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("subscription costs", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
let client: QueryClient;
|
||||
const changed = vi.fn();
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
mocks.update.mockResolvedValue({}); mocks.link.mockResolvedValue({}); changed.mockClear();
|
||||
});
|
||||
afterEach(() => { act(() => root.unmount()); container.remove(); client.clear(); vi.clearAllMocks(); });
|
||||
async function render(report?: SubscriptionCostReport, error?: unknown) {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><SubscriptionCostCard companyId="company" report={report} error={error} onChanged={changed} /></QueryClientProvider>));
|
||||
}
|
||||
async function click(label: string) {
|
||||
await act(async () => [...document.querySelectorAll("button")].find(button => button.textContent === label)!.click());
|
||||
}
|
||||
it("labels the monthly estimate and counts cached input exactly once", async () => {
|
||||
await render(fixture());
|
||||
expect(container.textContent).toContain("$100.00/month");
|
||||
expect(container.textContent).toContain("Estimated");
|
||||
expect(container.textContent).toContain("150 in · 10 out");
|
||||
expect(container.textContent).toContain("50 input cached");
|
||||
await click("View details");
|
||||
expect(document.body.textContent).toContain("Used by Leela");
|
||||
expect(document.body.textContent).toContain("before tax");
|
||||
});
|
||||
it("retains loaded totals during reload failure and never calls an unknown price zero", async () => {
|
||||
const report = fixture();
|
||||
report.monthlyTotals = []; report.unknownPriceCount = 1; report.accounts[0].price.amountCents = null; report.accounts[0].price.monthlyCents = null;
|
||||
await render(report, new Error("private raw error"));
|
||||
expect(container.textContent).toContain("1 price unknown");
|
||||
expect(container.textContent).not.toContain("$0.00");
|
||||
expect(container.textContent).not.toContain("private raw error");
|
||||
await render(fixture(), new Error("private raw error"));
|
||||
expect(container.textContent).toContain("$100.00/month");
|
||||
expect(container.textContent).toContain("last loaded");
|
||||
});
|
||||
it("does not describe legacy subscription usage with no identified account as free", async () => {
|
||||
const report = fixture(); report.accounts = []; report.activeCount = 0; report.monthlyTotals = [];
|
||||
report.unattributedSubscription = { ...report.subscription, eventCount: 1 };
|
||||
await render(report);
|
||||
expect(container.textContent).toContain("No visible subscriptions");
|
||||
expect(container.textContent).not.toContain("$0.00");
|
||||
await click("View details");
|
||||
expect(document.body.textContent).toContain("Some subscription usage has no recorded account");
|
||||
});
|
||||
it("keeps identity uncertainty visible even when a user has supplied the price", async () => {
|
||||
const report = fixture(); report.unidentifiedAccountCount = 1;
|
||||
report.accounts[0].identityVerified = false; report.accounts[0].price.source = "user";
|
||||
report.monthlyTotals[0].estimatedCount = 0;
|
||||
await render(report);
|
||||
expect(container.textContent).toContain("$100.00/month");
|
||||
expect(container.textContent).toContain("1 unconfirmed account identity");
|
||||
});
|
||||
it("saves an annual price with the expected revision and selected currency", async () => {
|
||||
await render(fixture()); await click("View details"); await click("Edit price");
|
||||
await act(async () => {
|
||||
const amount = document.querySelector<HTMLInputElement>("#subscription-price")!;
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(amount, "1200");
|
||||
amount.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
const cadence = document.querySelector<HTMLSelectElement>("#subscription-cadence")!;
|
||||
cadence.value = "year"; cadence.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
const currency = document.querySelector<HTMLSelectElement>("#subscription-currency")!;
|
||||
currency.value = "EUR"; currency.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await act(async () => document.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));
|
||||
await vi.waitFor(() => expect(mocks.update).toHaveBeenCalledWith("company", "account-1", expect.objectContaining({ amountCents: "120000.0000000", currency: "EUR", cadence: "year", expectedRevision: 0 })));
|
||||
expect(changed).toHaveBeenCalled();
|
||||
});
|
||||
it("hides editing when the viewer does not own the account", async () => {
|
||||
const report = fixture(); report.accounts[0].canEdit = false;
|
||||
await render(report); await click("View details");
|
||||
expect([...document.querySelectorAll("button")].some(button => button.textContent === "Edit price")).toBe(false);
|
||||
});
|
||||
it.each(["ended", "excluded"])("can change tracking to %s without rounding a saved fractional price", async (status) => {
|
||||
const report = fixture(); report.accounts[0].price.amountCents = "1575.5000000";
|
||||
await render(report); await click("View details"); await click("Edit price");
|
||||
const amount = document.querySelector<HTMLInputElement>("#subscription-price")!;
|
||||
expect(amount.value).toBe("15.755");
|
||||
expect(amount.checkValidity()).toBe(true);
|
||||
await act(async () => {
|
||||
const tracking = document.querySelector<HTMLSelectElement>("#subscription-status")!;
|
||||
tracking.value = status; tracking.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await click("Save price");
|
||||
await vi.waitFor(() => expect(mocks.update).toHaveBeenCalledWith("company", "account-1", expect.objectContaining({
|
||||
amountCents: "1575.5000000", status,
|
||||
})));
|
||||
});
|
||||
it("distinguishes personal seats with multiple owners from company-shared subscriptions", async () => {
|
||||
const report = fixture();
|
||||
report.accounts[0] = { ...report.accounts[0], ownerUserId: null, ownerName: null, shared: false, canEdit: false };
|
||||
await render(report); await click("View details");
|
||||
expect(document.body.textContent).toContain("Personal accounts");
|
||||
expect(document.body.textContent).not.toContain("Shared ·");
|
||||
report.accounts[0].shared = true;
|
||||
await render(report);
|
||||
expect(document.body.textContent).toContain("Shared ·");
|
||||
expect(document.body.textContent).not.toContain("Personal accounts");
|
||||
});
|
||||
it("links only an explicitly chosen duplicate and keeps the target price", async () => {
|
||||
const report = fixture();
|
||||
report.accounts.push({ ...report.accounts[0], id: "account-2", name: "Other connection", price: { ...report.accounts[0].price, revision: 3 } });
|
||||
await render(report); await click("View details"); await click("Edit price");
|
||||
expect(document.body.textContent).toContain("keeps the selected account’s price");
|
||||
await act(async () => { const select = document.querySelector<HTMLSelectElement>("#subscription-link")!; select.value = "account-2"; select.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
await click("Link accounts");
|
||||
await vi.waitFor(() => expect(mocks.link).toHaveBeenCalledWith("company", "account-1", "account-2", 0, 3));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { SUBSCRIPTION_CURRENCIES, centsToUsd, usdToCents, type SubscriptionAccountReport, type SubscriptionCostReport, type SubscriptionUsage } from "@paperclipai/shared";
|
||||
import { subscriptionsApi } from "../api/subscriptions";
|
||||
import { formatCents, formatDateTime, formatTokens, providerDisplayName } from "../lib/utils";
|
||||
import { Button } from "./ui/button";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Card } from "./ui/card";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
|
||||
import { Input } from "./ui/input";
|
||||
import { Label } from "./ui/label";
|
||||
|
||||
export function subscriptionMoney(cents: string, currency: string) {
|
||||
return currency === "USD" ? formatCents(Number(cents))
|
||||
: new Intl.NumberFormat(undefined, { style: "currency", currency, currencyDisplay: "code" }).format(Number(cents) / 100);
|
||||
}
|
||||
|
||||
export function SubscriptionTokenUsage({ usage }: { usage: SubscriptionUsage }) {
|
||||
return <span className="font-mono text-xs text-muted-foreground">
|
||||
{formatTokens(usage.inputTokens + usage.cachedInputTokens)} in · {formatTokens(usage.outputTokens)} out
|
||||
{usage.cachedInputTokens > 0 && <span className="block">{formatTokens(usage.cachedInputTokens)} input cached</span>}
|
||||
</span>;
|
||||
}
|
||||
|
||||
function SubscriptionEditor({ account, accounts, companyId, onDone }: {
|
||||
account: SubscriptionAccountReport; accounts: SubscriptionAccountReport[]; companyId: string; onDone: () => void;
|
||||
}) {
|
||||
const [plan, setPlan] = useState(account.price.plan);
|
||||
const [amount, setAmount] = useState(account.price.amountCents == null ? "" : centsToUsd(account.price.amountCents).replace(/\.?0+$/, ""));
|
||||
const [currency, setCurrency] = useState(account.price.currency);
|
||||
const [cadence, setCadence] = useState(account.price.cadence);
|
||||
const [status, setStatus] = useState(account.price.status);
|
||||
const [targetId, setTargetId] = useState("");
|
||||
const save = useMutation({ mutationFn: () => subscriptionsApi.update(companyId, account.id, {
|
||||
expectedRevision: account.price.revision, plan, amountCents: amount.trim() ? usdToCents(amount.trim()) : null,
|
||||
currency: currency as typeof SUBSCRIPTION_CURRENCIES[number], cadence, status,
|
||||
}), onSuccess: onDone });
|
||||
const link = useMutation({ mutationFn: () => subscriptionsApi.link(companyId, account.id, targetId, account.price.revision,
|
||||
accounts.find(row => row.id === targetId)!.price.revision), onSuccess: onDone });
|
||||
const targets = accounts.filter(row => row.id !== account.id && row.provider === account.provider && row.canEdit);
|
||||
const busy = save.isPending || link.isPending;
|
||||
const selectClass = "h-9 rounded-md border border-input bg-background px-3 text-sm";
|
||||
return <div className="space-y-5">
|
||||
<form className="space-y-4" onSubmit={event => { event.preventDefault(); save.mutate(); }}>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-plan">Plan</Label><Input id="subscription-plan" value={plan} onChange={event => setPlan(event.target.value)} required maxLength={100} /></div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2"><Label htmlFor="subscription-price">Price per billing period</Label><Input id="subscription-price" type="number" min="0" step="any" value={amount} placeholder="Unknown" onChange={event => setAmount(event.target.value)} /></div>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-currency">Currency</Label><select id="subscription-currency" className={selectClass} value={currency} onChange={event => setCurrency(event.target.value)}>{SUBSCRIPTION_CURRENCIES.map(code => <option key={code}>{code}</option>)}</select></div>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-cadence">Billed</Label><select id="subscription-cadence" className={selectClass} value={cadence} onChange={event => setCadence(event.target.value as typeof cadence)}><option value="month">Monthly</option><option value="year">Annually</option></select></div>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-status">Tracking</Label><select id="subscription-status" className={selectClass} value={status} onChange={event => setStatus(event.target.value as typeof status)}><option value="active">Active</option><option value="ended">Subscription ended</option><option value="excluded">Exclude from this organization</option></select></div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">Enter the full amount for one account or seat. Annual prices are divided by 12. Changes apply from now. Ending tracking here does not cancel your provider subscription.</p>
|
||||
{save.error && <p role="alert" className="text-sm text-destructive">Could not save this price. Check the amount, or reopen the account if another person updated it.</p>}
|
||||
<div className="flex items-center justify-between"><Button type="button" variant="ghost" disabled={busy} onClick={onDone}>Cancel</Button><Button type="submit" disabled={busy}>{save.isPending ? "Saving…" : "Save price"}</Button></div>
|
||||
</form>
|
||||
{targets.length > 0 && <div className="space-y-2 border-t border-border pt-4">
|
||||
<Label htmlFor="subscription-link">Same subscription as another account?</Label>
|
||||
<select id="subscription-link" className={selectClass} value={targetId} onChange={event => setTargetId(event.target.value)}><option value="">Choose an account</option>{targets.map(row => <option key={row.id} value={row.id}>{row.name} · {row.price.plan}</option>)}</select>
|
||||
<p className="text-xs text-muted-foreground">Linking counts these accounts once, combines their Paperclip usage, and keeps the selected account’s price. Only link the same subscription or paid seat.</p>
|
||||
{link.error && <p role="alert" className="text-sm text-destructive">Could not link these accounts. Reopen their details and try again.</p>}
|
||||
<Button type="button" variant="outline" disabled={!targetId || busy} onClick={() => link.mutate()}>Link accounts</Button>
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function SubscriptionCostCard({ companyId, report, error, onChanged }: {
|
||||
companyId: string; report?: SubscriptionCostReport; error?: unknown; onChanged: () => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<SubscriptionAccountReport | null>(null);
|
||||
const closeEditor = () => { setEditing(null); onChanged(); };
|
||||
const known = report?.monthlyTotals.length;
|
||||
const estimatedCount = report?.monthlyTotals.reduce((sum, total) => sum + total.estimatedCount, 0) ?? 0;
|
||||
return <>
|
||||
<Card className="block p-4">
|
||||
<div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Subscriptions</div>
|
||||
<div className="mt-2 font-mono text-2xl font-semibold tabular-nums">
|
||||
{known ? report!.monthlyTotals.map(total => <div key={total.currency}>{subscriptionMoney(total.amountCents, total.currency)}<span className="text-sm font-normal">/month</span></div>) : report && report.activeCount === 0 && report.accounts.length > 0 ? "$0.00/month" : "—"}
|
||||
</div>
|
||||
<div className="mt-1 space-y-1 text-xs text-muted-foreground">
|
||||
{report ? <>
|
||||
{estimatedCount > 0 && <div><Badge variant="outline" className="font-normal text-muted-foreground">{estimatedCount < report.activeCount - report.unknownPriceCount ? "Partially estimated" : "Estimated"}</Badge></div>}
|
||||
{report.unknownPriceCount > 0 && !!known && <div>Known monthly subtotal</div>}
|
||||
<div>{report.accounts.length === 0 ? "No visible subscriptions" : <>{report.activeCount} active {report.activeCount === 1 ? "subscription" : "subscriptions"}{report.unknownPriceCount > 0 && ` · ${report.unknownPriceCount} ${report.unknownPriceCount === 1 ? "price" : "prices"} unknown`}</>}</div>
|
||||
{report.accounts.length > 0 && <div>Monthly fees for accounts visible to you</div>}
|
||||
{report.unidentifiedAccountCount > 0 && <div>{report.unidentifiedAccountCount} unconfirmed {report.unidentifiedAccountCount === 1 ? "account identity" : "account identities"}</div>}
|
||||
<SubscriptionTokenUsage usage={report.subscription} />
|
||||
</> : error ? <div>Subscription data is unavailable.</div> : <div>Loading subscriptions…</div>}
|
||||
{report && error ? <div>Showing last loaded subscription data.</div> : null}
|
||||
</div>
|
||||
<Button variant="link" size="sm" className="h-auto p-0" onClick={() => setOpen(true)} disabled={!report}>View details</Button>
|
||||
</Card>
|
||||
<Dialog open={open} onOpenChange={value => { setOpen(value); if (!value) setEditing(null); }}>
|
||||
<DialogContent className="max-h-(--sz-80vh) overflow-y-auto sm:max-w-3xl">
|
||||
<DialogHeader><DialogTitle>{editing ? "Subscription price" : "Subscriptions"}</DialogTitle><DialogDescription>Current monthly costs for accounts visible to you. Token totals cover company work in the selected period.</DialogDescription></DialogHeader>
|
||||
{editing ? <SubscriptionEditor key={editing.id} companyId={companyId} account={editing} accounts={report?.accounts ?? []} onDone={closeEditor} /> : <div className="space-y-4">
|
||||
{report?.accounts.length === 0 && <p className="text-sm text-muted-foreground">No subscriptions are visible to you yet. Connect an AI account or run an agent with a connected subscription.</p>}
|
||||
{report?.accounts.map(account => <div key={account.id} className="space-y-2 border-b border-border pb-4 last:border-0">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div><div className="font-medium">{account.name}</div><div className="text-xs text-muted-foreground">{account.shared ? "Shared" : account.ownerName ?? (account.ownerUserId ? "Account owner" : "Personal accounts")} · {providerDisplayName(account.provider)} · {account.price.plan}</div></div>
|
||||
<div className="text-right"><div className="font-mono">{account.price.status !== "active" ? account.price.status === "ended" ? "Ended" : "Excluded" : account.price.monthlyCents == null ? "Price unknown" : `${subscriptionMoney(account.price.monthlyCents, account.price.currency)}/month`}</div><div className="text-xs text-muted-foreground">{account.price.source === "catalog" ? "Estimated · before tax" : account.price.source === "user" ? "User supplied" : ""}{account.price.cadence === "year" ? " · annual payment ÷ 12" : ""}</div></div>
|
||||
</div>
|
||||
<SubscriptionTokenUsage usage={account.usage} />
|
||||
{Number(account.usage.costCents) > 0 && <div className="text-xs text-muted-foreground">{formatCents(Number(account.usage.costCents))} recorded usage charges in selected period, separate from the subscription fee.</div>}
|
||||
{account.agents.length > 0 && <div className="text-xs text-muted-foreground">Used by {account.agents.map(agent => agent.name).join(", ")}</div>}
|
||||
{!account.identityVerified && <p className="text-xs text-muted-foreground">Account identity is unconfirmed. Link duplicates if these connections use the same subscription.</p>}
|
||||
{account.observedAt && <div className="text-xs text-muted-foreground">Plan checked {formatDateTime(account.observedAt)}{account.refreshStatus === "unavailable" ? " · latest check unavailable" : ""}</div>}
|
||||
{account.refreshStatus === "unavailable" && !account.observedAt && <p className="text-xs text-muted-foreground">The provider did not make plan details available. You can enter the price yourself.</p>}
|
||||
{account.canEdit && <div><Button variant="outline" size="sm" onClick={() => setEditing(account)}>Edit price</Button></div>}
|
||||
</div>)}
|
||||
{!!report?.unattributedSubscription.eventCount && <p className="text-xs text-muted-foreground">Some subscription usage has no recorded account. It is included in the subscription token total.</p>}
|
||||
<p className="text-xs text-muted-foreground">Monthly fees cover the whole account, including use outside Paperclip. They are separate from recorded charges and agent budgets. Currencies are totaled separately.</p>
|
||||
</div>}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>;
|
||||
}
|
||||
@@ -8,8 +8,8 @@ import { cn } from "@/lib/utils";
|
||||
|
||||
export type ExternalAgentPreset = "dot" | "hermes" | "other";
|
||||
export type DotConnectionState = {
|
||||
phase: "waiting" | "connected" | "subscribed" | "testing" | "ready";
|
||||
problem?: "event_timeout" | "prompt_unavailable" | "offline";
|
||||
phase: "waiting" | "connected" | "subscribed" | "testing" | "finishing" | "ready";
|
||||
problem?: "event_timeout" | "prompt_unavailable" | "offline" | "agent_unavailable";
|
||||
};
|
||||
|
||||
const presets = [
|
||||
@@ -43,10 +43,12 @@ const checks = [
|
||||
|
||||
/** Controlled by server evidence in the invite controller, never by copying a prompt. */
|
||||
export function DotConnectionChecks({ state }: { state: DotConnectionState }) {
|
||||
const completed = { waiting: 0, connected: 1, subscribed: 2, testing: 2, ready: 3 }[state.phase];
|
||||
const message = state.problem === "offline" ? "Connection updates paused. Reconnect to check the latest status."
|
||||
const completed = { waiting: 0, connected: 1, subscribed: 2, testing: 2, finishing: 3, ready: 3 }[state.phase];
|
||||
const message = state.problem === "agent_unavailable" ? "Connection checks passed, but this agent cannot receive tasks. Resolve the agent’s setup blocker in Paperclip."
|
||||
: state.problem === "offline" ? "Connection updates paused. Reconnect to check the latest status."
|
||||
: state.problem === "prompt_unavailable" ? "This setup prompt was replaced in another window. Create a fresh prompt to continue."
|
||||
: state.problem === "event_timeout" ? "Your Dot connected, but hasn’t confirmed the test event. Ask it to check Paperclip, then retry."
|
||||
: state.phase === "finishing" ? "Your Dot confirmed the test event. Paperclip is finishing agent setup."
|
||||
: state.phase === "ready" ? "Your Dot is ready for tasks. Messages can travel both ways."
|
||||
: state.phase === "waiting" ? "Watching for your Dot. Updates will appear here automatically."
|
||||
: state.phase === "connected" ? "Your Dot connected. Waiting for it to enable task updates."
|
||||
@@ -99,8 +101,10 @@ export function ExternalAgentInviteContent({
|
||||
const dot = preset === "dot";
|
||||
const ready = dot && connection.phase === "ready" && !connection.problem;
|
||||
const connecting = dot && connection.phase !== "waiting";
|
||||
const progressLabel = connection.problem === "offline" ? "Updates paused"
|
||||
const progressLabel = connection.problem === "agent_unavailable" ? "Agent unavailable"
|
||||
: connection.problem === "offline" ? "Updates paused"
|
||||
: connection.problem === "event_timeout" ? "Needs attention"
|
||||
: connection.phase === "finishing" ? "Finishing setup…"
|
||||
: connection.phase === "connected" ? "Connecting…" : "Confirming connection…";
|
||||
return <>
|
||||
<div className="min-h-0 space-y-6 overflow-y-auto px-6 pb-6 pt-8 sm:px-8">
|
||||
@@ -113,6 +117,8 @@ export function ExternalAgentInviteContent({
|
||||
<DialogDescription className="text-sm leading-relaxed">
|
||||
{!provider ? `Bring an agent you already use into ${companyName}.`
|
||||
: ready ? `Your Dot can now receive assignments and work with ${companyName}.`
|
||||
: connection.problem === "agent_unavailable" ? "Your Dot is connected. This agent must be available in Paperclip before it can receive assignments."
|
||||
: connection.phase === "finishing" ? "Your Dot has connected and confirmed task updates. Paperclip is preparing it for assignments."
|
||||
: connecting ? "Your Dot has connected. We’re checking that task updates can travel both ways."
|
||||
: dot ? "Copy the setup prompt and send it to your Dot in ChatGPT. Your Dot will connect itself; we’ll watch for it here."
|
||||
: `Copy the invitation prompt and send it to your ${preset === "hermes" ? "Hermes " : ""}agent. Approve its join request in Paperclip when it’s ready.`}
|
||||
|
||||
@@ -36,7 +36,8 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
enabled: preset === "dot" && !!invitation,
|
||||
retry: false,
|
||||
staleTime: 0,
|
||||
refetchInterval: query => query.state.error ? false : query.state.data?.binding?.status === "ready" && query.state.data.binding.subscriptionVerified ? false : 2500,
|
||||
refetchInterval: query => query.state.error ? false : query.state.data?.agentLifecycleState === "ready" && query.state.data.canConfigureConnection
|
||||
&& query.state.data.binding?.status === "ready" && query.state.data.binding.subscriptionVerified ? false : 2500,
|
||||
});
|
||||
const generate = useMutation({
|
||||
mutationFn: async (kind: ExternalAgentPreset) => {
|
||||
@@ -71,7 +72,7 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
onSuccess: () => { void cache.invalidateQueries({ queryKey: key }); } });
|
||||
const binding = state.data?.binding;
|
||||
const canPreparePairing = preset === "dot" && state.data?.enabled && !!state.data.resourceUrl
|
||||
&& !["pending_approval", "paused", "terminated"].includes(state.data.agentStatus)
|
||||
&& state.data.canConfigureConnection
|
||||
&& (!binding || binding.status === "pairing");
|
||||
const preparePairing = canPreparePairing && !pairing && !state.error && !pair.isError
|
||||
&& !attemptedAutomaticPairing.current
|
||||
@@ -93,15 +94,20 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
}, Math.max(0, Date.parse(pairing.expiresAt) - Date.now()));
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [pairing]);
|
||||
const checksReady = binding?.status === "ready" && binding.subscriptionVerified;
|
||||
const agentReady = state.data?.agentLifecycleState === "ready" && state.data.canConfigureConnection;
|
||||
const finishingSetup = ["preparing", "verifying"].includes(state.data?.agentLifecycleState ?? "")
|
||||
&& state.data?.canConfigureConnection;
|
||||
const connection: DotConnectionState = {
|
||||
phase: binding?.status === "ready" && binding.subscriptionVerified && !["paused", "terminated", "pending_approval"].includes(state.data?.agentStatus ?? "") ? "ready"
|
||||
phase: checksReady ? agentReady ? "ready" : finishingSetup ? "finishing" : "ready"
|
||||
: binding?.hasPendingChallenge ? "testing" : binding?.subscriptionVerified ? "subscribed" : binding?.connected ? "connected" : "waiting",
|
||||
problem: state.error ? "offline"
|
||||
: checksReady && !agentReady && !finishingSetup ? "agent_unavailable"
|
||||
: binding?.status === "pairing" && !preparePairing && !pair.isPending && !state.isFetching && !pair.isError && pairing?.bindingId !== binding.id ? "prompt_unavailable"
|
||||
: binding?.challengeExpiresAt && !binding.hasPendingChallenge && binding.status !== "ready" ? "event_timeout" : undefined,
|
||||
};
|
||||
const pendingApproval = (state.data?.agentStatus ?? invitation?.agent.status) === "pending_approval";
|
||||
const unavailable = state.data && ["paused", "terminated"].includes(state.data.agentStatus);
|
||||
const unavailable = state.data && !state.data.canConfigureConnection && !pendingApproval;
|
||||
const prompt = preset === "dot" ? pairing && pairing.bindingId === binding?.id && state.data?.resourceUrl && invitation
|
||||
? buildDotSetupPrompt({ companyId, agentId: invitation.agent.id, resourceUrl: state.data.resourceUrl, ...pairing }) : "" : genericPrompt;
|
||||
const error = (generate.variables === preset ? generate.error : null) ?? (preset === "dot" ? (binding?.connected ? null : pair.error) ?? test.error : null);
|
||||
@@ -118,7 +124,7 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
<AnimatedDialogContent className="sm:max-w-(--sz-560px)">
|
||||
<ExternalAgentInviteContent preset={preset} prompt={prompt} companyName={selectedCompany?.name ?? "your organization"}
|
||||
connection={connection} dotDisabledReason={dotDisabledReason} busy={busy}
|
||||
error={error?.message ?? (unavailable ? "Resume this agent before connecting Dot." : undefined)}
|
||||
error={error?.message ?? (unavailable ? state.data?.agentLifecycleState === "terminated" ? "This agent was terminated. Invite another agent to connect Dot." : "Resume this agent before connecting Dot." : undefined)}
|
||||
approvalHref={pendingApproval && invitation?.approvalId ? `/approvals/${invitation.approvalId}` : undefined}
|
||||
onSelect={kind => { setPreset(kind); if (kind === "dot" ? !invitation : !genericPrompt) generate.mutate(kind); }}
|
||||
onBack={() => setPreset(null)} onClose={preset ? onClose : onBack} onCopied={() => { if (preset === "dot") void state.refetch(); }}
|
||||
|
||||
@@ -7,6 +7,11 @@ import {
|
||||
} from "./company-routes";
|
||||
|
||||
describe("company routes", () => {
|
||||
it("keeps public Dot consent outside company-prefixed routes", () => {
|
||||
const path = `/dot-connect/pcmcp_request_${"a".repeat(43)}`;
|
||||
expect(extractCompanyPrefixFromPath(path)).toBeNull();
|
||||
expect(applyCompanyPrefix(path, "DOT")).toBe(path);
|
||||
});
|
||||
it("treats the task-list alias as an unprefixed board route", () => {
|
||||
expect(isBoardPathWithoutPrefix("/tasks")).toBe(true);
|
||||
expect(extractCompanyPrefixFromPath("/tasks")).toBeNull();
|
||||
|
||||
@@ -33,7 +33,7 @@ const BOARD_ROUTE_ROOTS = new Set([
|
||||
"timeline",
|
||||
]);
|
||||
|
||||
const GLOBAL_ROUTE_ROOTS = new Set(["auth", "invite", "board-claim", "cli-auth", "mcp-connect", "assistant-connections", "docs", "instance"]);
|
||||
const GLOBAL_ROUTE_ROOTS = new Set(["auth", "invite", "board-claim", "cli-auth", "mcp-connect", "dot-connect", "assistant-connections", "docs", "instance"]);
|
||||
|
||||
export function normalizeCompanyPrefix(prefix: string): string {
|
||||
return prefix.trim().toUpperCase();
|
||||
|
||||
@@ -43,6 +43,36 @@ describe("isArchivedStackRecoveryError", () => {
|
||||
});
|
||||
|
||||
describe("tenant-session recovery coordinator", () => {
|
||||
it.each(["tenant_session_required", "tenant_session_invalid"])(
|
||||
"leaves public Dot consent mounted after an expected %s background failure",
|
||||
(error) => {
|
||||
const reload = vi.fn();
|
||||
const pathname = `/dot-connect/pcmcp_request_${"a".repeat(43)}`;
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => pathname);
|
||||
|
||||
expect(recovery.recoverIfNeeded(401, { error })).toBeNull();
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["/DOT/agents/dot", "/dot-connect/not-a-request", `/dot-connect/pcmcp_request_${"a".repeat(43)}/extra`])(
|
||||
"still recovers tenant sessions outside the public consent route: %s",
|
||||
(pathname) => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => pathname);
|
||||
|
||||
expect(recovery.recoverIfNeeded(401, { error: "tenant_session_required" })).not.toBeNull();
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("still leaves archived stacks from the public Dot consent route", () => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => `/dot-connect/pcmcp_request_${"a".repeat(43)}`);
|
||||
|
||||
expect(recovery.recoverIfNeeded(423, { statusPage: { code: "archived" } })).not.toBeNull();
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("reloads once and shares one never-settling promise across concurrent failures", async () => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload);
|
||||
|
||||
@@ -40,12 +40,22 @@ export interface TenantSessionRecoveryCoordinator {
|
||||
|
||||
export function createTenantSessionRecoveryCoordinator(
|
||||
reloadTopLevelPage: () => void,
|
||||
getDocumentPathname: () => string = () => "",
|
||||
): TenantSessionRecoveryCoordinator {
|
||||
let recoveryPromise: Promise<never> | null = null;
|
||||
|
||||
return {
|
||||
recoverIfNeeded(status, body) {
|
||||
if (!isTenantDocumentRecoveryError(status, body)) return null;
|
||||
// Dot consent is intentionally public. Global settings/session probes can
|
||||
// receive an expected 401 here; reloading would repeat that probe forever
|
||||
// and prevent the public connection request from finishing. Leave those
|
||||
// failures to their consumers while preserving recovery on board routes
|
||||
// and for archived stacks.
|
||||
if (
|
||||
isTenantSessionRecoveryError(status, body)
|
||||
&& /^\/dot-connect\/pcmcp_request_[A-Za-z0-9_-]{43}$/.test(getDocumentPathname())
|
||||
) return null;
|
||||
if (recoveryPromise) return recoveryPromise;
|
||||
|
||||
// Keep every affected consumer pending while the browser leaves this
|
||||
@@ -70,4 +80,4 @@ export const tenantSessionRecovery = createTenantSessionRecoveryCoordinator(() =
|
||||
// stack is redirected to the portfolio.
|
||||
const topLevelWindow = window.top ?? window;
|
||||
topLevelWindow.location.reload();
|
||||
});
|
||||
}, () => typeof window === "undefined" ? "" : window.location.pathname);
|
||||
@@ -28,6 +28,8 @@ const costsApiMocks = vi.hoisted(() => ({
|
||||
windowSpend: vi.fn(),
|
||||
quotaWindows: vi.fn(),
|
||||
}));
|
||||
const subscriptionsMocks = vi.hoisted(() => ({ report: vi.fn(), refresh: vi.fn(), update: vi.fn(), link: vi.fn() }));
|
||||
vi.mock("../api/subscriptions", () => ({ subscriptionsApi: subscriptionsMocks }));
|
||||
|
||||
vi.mock("../api/budgets", () => ({
|
||||
budgetsApi: {
|
||||
@@ -63,6 +65,8 @@ describe("Shared Costs surfaces", () => {
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
|
||||
beforeEach(() => {
|
||||
const usage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
|
||||
subscriptionsMocks.report.mockResolvedValue({ canRefresh: false, asOf: "2026-10-08T00:00:00Z", accounts: [], monthlyTotals: [], activeCount: 0, unknownPriceCount: 0, unidentifiedAccountCount: 0, api: usage, subscription: usage, unknown: usage, unattributedSubscription: usage });
|
||||
decisionHistoryMock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
container = document.createElement("div");
|
||||
@@ -92,6 +96,24 @@ describe("Shared Costs surfaces", () => {
|
||||
expect(container.textContent).toContain("1 unpriced charge");
|
||||
});
|
||||
|
||||
it.each(surfaces)("labels other and unknown billing accurately on the %s surface", async (_name, props) => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 600, budgetCents: 0, pricingComplete: true });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const report = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, unknown: { ...report.unknown,
|
||||
inputTokens: 100, cachedInputTokens: 40, outputTokens: 10, costCents: "600", eventCount: 3,
|
||||
} });
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>));
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain(
|
||||
"150 tokens have other or unknown billing types, with $6.00 in recorded charges. They remain in the inference ledger.",
|
||||
)));
|
||||
expect(container.textContent).not.toContain("tokens have an unknown billing type");
|
||||
});
|
||||
|
||||
it("renders a focused Budgets section without duplicate Costs chrome or spend queries", async () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
@@ -212,6 +234,56 @@ describe("Shared Costs surfaces", () => {
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("retries failed account discovery without discarding the last subscription report", async () => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 0, budgetCents: 0, pricingComplete: true });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const report = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, canRefresh: true, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }] });
|
||||
subscriptionsMocks.refresh.mockRejectedValueOnce(new Error("private connection error")).mockResolvedValue({});
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs /></QueryClientProvider></MemoryRouter>));
|
||||
const retry = () => [...container.querySelectorAll("button")].find(button => button.textContent === "Retry account check");
|
||||
await act(async () => { await vi.waitFor(() => expect(retry()).toBeDefined()); });
|
||||
expect(container.textContent).toContain("$20.00/month");
|
||||
expect(container.textContent).not.toContain("private connection error");
|
||||
await act(async () => retry()!.click());
|
||||
await act(async () => { await vi.waitFor(() => expect(retry()).toBeUndefined()); });
|
||||
expect(subscriptionsMocks.refresh).toHaveBeenCalledTimes(2);
|
||||
expect(subscriptionsMocks.refresh).toHaveBeenLastCalledWith("company-1");
|
||||
expect(container.textContent).toContain("$20.00/month");
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("keeps monthly subscription fees through date changes and failed background reloads", async () => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 200, budgetCents: 0, pricingComplete: true });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const report = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }], api: { ...report.api, costCents: "200" } });
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs /></QueryClientProvider></MemoryRouter>));
|
||||
const card = (label: string) => [...container.querySelectorAll("div")].find(node => node.textContent === label)?.closest('[data-slot="card"]');
|
||||
await act(async () => { await vi.waitFor(() => expect(card("Subscriptions")?.textContent).toContain("$20.00/month")); });
|
||||
expect(card("API spend")?.textContent).toContain("$2.00");
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }], api: { ...report.api, costCents: "300" } });
|
||||
await act(async () => [...container.querySelectorAll("button")].find(button => button.textContent === "All Time")!.click());
|
||||
await act(async () => { await vi.waitFor(() => expect(card("API spend")?.textContent).toContain("$3.00")); });
|
||||
expect(card("Subscriptions")?.textContent).toContain("$20.00/month");
|
||||
expect(subscriptionsMocks.report).toHaveBeenLastCalledWith("company-1", undefined, undefined);
|
||||
subscriptionsMocks.report.mockRejectedValue(new Error("private provider failure"));
|
||||
await act(async () => { await queryClient.invalidateQueries({ queryKey: ["cost-subscriptions"] }); });
|
||||
await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("Showing the last loaded API and subscription usage")); });
|
||||
expect(card("API spend")?.textContent).toContain("$3.00");
|
||||
expect(card("Subscriptions")?.textContent).toContain("$20.00/month");
|
||||
expect(container.textContent).not.toContain("private provider failure");
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("compares monthly budgets only with month-to-date spend", async () => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
@@ -224,6 +296,8 @@ describe("Shared Costs surfaces", () => {
|
||||
await act(async () => { await vi.waitFor(() => expect(budgetCard()?.textContent).toContain("20%")); });
|
||||
expect(budgetCard()?.textContent).toContain("$2.00 of $10.00 this month");
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 12000, budgetCents: 1000, utilizationPercent: 1200, pricingComplete: true });
|
||||
const subscriptionReport = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...subscriptionReport, api: { ...subscriptionReport.api, costCents: "12000" } });
|
||||
await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === "All Time")!.click());
|
||||
await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("$120.00")); });
|
||||
expect(budgetCard()?.textContent).toContain("$10.00");
|
||||
@@ -281,7 +355,7 @@ describe("Shared Costs surfaces", () => {
|
||||
expect(notice.querySelector(".text-destructive")).toBeNull();
|
||||
expect(notice.classList.contains("text-destructive")).toBe(false);
|
||||
expect(notice.textContent).toContain("1 run is awaiting cost data.");
|
||||
expect(notice.previousElementSibling?.textContent).toContain("Inference spend");
|
||||
expect(notice.previousElementSibling?.textContent).toContain("API spend");
|
||||
expect(container.textContent).toContain("Finance headline totals are USD only");
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 12.4, budgetCents: 0, pricingComplete: false, unpricedEventCount: 10, pendingRunCount: 0 });
|
||||
await act(async () => { await queryClient.invalidateQueries(); });
|
||||
@@ -296,12 +370,17 @@ describe("Shared Costs surfaces", () => {
|
||||
await vi.waitFor(() => expect(container.contains(notice)).toBe(false));
|
||||
});
|
||||
|
||||
it.each(surfaces)("labels each agent and expanded model independently on the %s page", async (_name, props) => {
|
||||
it.each(surfaces)("labels each agent, project, and expanded model independently on the %s page", async (_name, props) => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 600, budgetCents: 0, pricingComplete: true, estimatedEventCount: 3 });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const base = { costCents: 200, inputTokens: 10, cachedInputTokens: 5, outputTokens: 2, apiRunCount: 2, subscriptionRunCount: 0, eventCount: 2 };
|
||||
costsApiMocks.byProject.mockResolvedValue([
|
||||
{ ...base, projectId: "estimated-project", projectName: "Estimated project", estimatedEventCount: 2 },
|
||||
{ ...base, projectId: "mixed-project", projectName: "Mixed project", estimatedEventCount: 1 },
|
||||
{ ...base, projectId: "reported-project", projectName: "Reported project", estimatedEventCount: 0 },
|
||||
]);
|
||||
costsApiMocks.byAgent.mockResolvedValue([
|
||||
{ ...base, agentId: "codie", agentName: "Codie", estimatedEventCount: 2 },
|
||||
{ ...base, agentId: "mixed", agentName: "Mixed", estimatedEventCount: 1 },
|
||||
@@ -326,6 +405,11 @@ describe("Shared Costs surfaces", () => {
|
||||
expect(card("Mixed").textContent).toContain("Partially estimated");
|
||||
expect(card("Reported").textContent).not.toMatch(/Estimated|Partially estimated/);
|
||||
expect(card("Legacy").textContent).not.toMatch(/Estimated|Partially estimated/);
|
||||
const projectBadge = (name: string) => [...container.querySelectorAll("span")]
|
||||
.find(element => element.textContent === name)!.parentElement!.querySelector('[data-slot="badge"]');
|
||||
expect(projectBadge("Estimated project")?.textContent).toBe("Estimated");
|
||||
expect(projectBadge("Mixed project")?.textContent).toBe("Partially estimated");
|
||||
expect(projectBadge("Reported project")).toBeNull();
|
||||
await act(async () => card("Mixed").querySelector<HTMLElement>(".cursor-pointer")!.click());
|
||||
const breakdown = card("Mixed").querySelector(".border-l")!;
|
||||
expect(breakdown.textContent).toContain("gpt-6-astra");
|
||||
|
||||
+54
-30
@@ -1,6 +1,9 @@
|
||||
import { DecisionHistory } from "../components/decision-models/DecisionHistory";
|
||||
import { SubscriptionCostCard, SubscriptionTokenUsage } from "../components/SubscriptionCostCard";
|
||||
import { subscriptionsApi } from "../api/subscriptions";
|
||||
import { useSearchParams } from "@/lib/router";
|
||||
import { CostEstimateLabel } from "../components/CostEstimateLabel";
|
||||
import { CostAmount } from "../components/CostAmount";
|
||||
import { CostByUserTable } from "../components/CostByUserTable";
|
||||
import { AgentIdentity } from "@/components/AgentIdentity";
|
||||
import { useEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from "react";
|
||||
@@ -228,6 +231,23 @@ export function Costs({
|
||||
const reportQueryFrom = ["custom", "mtd", "ytd"].includes(preset) ? from || undefined : undefined;
|
||||
const reportQueryTo = preset === "custom" ? to || undefined : preset;
|
||||
|
||||
const subscriptionKey = ["cost-subscriptions", companyId, reportQueryFrom, reportQueryTo];
|
||||
const { data: subscriptions, error: subscriptionError } = useQuery({
|
||||
queryKey: subscriptionKey,
|
||||
queryFn: () => subscriptionsApi.report(companyId, from || undefined, to || undefined),
|
||||
enabled: !!selectedCompanyId && customReady && showSummaryChrome,
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
const invalidateSubscriptions = () => { void queryClient.invalidateQueries({ queryKey: ["cost-subscriptions", companyId] }); };
|
||||
const discoveryCompany = useRef<string | null>(null);
|
||||
const discoverSubscriptions = useMutation({ mutationFn: (id: string) => subscriptionsApi.refresh(id),
|
||||
onSuccess: (_data, id) => { void queryClient.invalidateQueries({ queryKey: ["cost-subscriptions", id] }); } });
|
||||
useEffect(() => {
|
||||
if (!selectedCompanyId || !showSummaryChrome || !subscriptions?.canRefresh || discoveryCompany.current === selectedCompanyId) return;
|
||||
discoveryCompany.current = selectedCompanyId;
|
||||
discoverSubscriptions.mutate(selectedCompanyId);
|
||||
}, [selectedCompanyId, showSummaryChrome, subscriptions?.canRefresh, discoverSubscriptions.mutate]);
|
||||
|
||||
const { data: budgetData, isLoading: budgetLoading, error: budgetError } = useQuery({
|
||||
queryKey: queryKeys.budgets.overview(companyId),
|
||||
queryFn: () => budgetsApi.overview(companyId),
|
||||
@@ -558,12 +578,6 @@ export function Costs({
|
||||
];
|
||||
}, [byBiller]);
|
||||
|
||||
const inferenceTokenTotal =
|
||||
(spendData?.byAgent ?? []).reduce(
|
||||
(sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens,
|
||||
0,
|
||||
);
|
||||
|
||||
const topFinanceEvents = (financeData?.events ?? []) as FinanceEvent[];
|
||||
const budgetPolicies = budgetData?.policies ?? [];
|
||||
const activeBudgetIncidents = budgetData?.activeIncidents ?? [];
|
||||
@@ -631,13 +645,17 @@ export function Costs({
|
||||
Finance headline totals are USD only. Other currencies are listed separately; no exchange-rate conversion is applied.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-3 lg:grid-cols-4">
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
|
||||
<MetricTile
|
||||
label="Inference spend"
|
||||
value={spendData ? formatCents(spendData.summary.spendCents) : "—"}
|
||||
subtitle={`${formatTokens(inferenceTokenTotal)} tokens across request-scoped events`}
|
||||
label="API spend"
|
||||
value={subscriptions ? subscriptions.api.unpricedEventCount === subscriptions.api.eventCount && subscriptions.api.eventCount > 0 ? "—" : formatCents(Number(subscriptions.api.costCents)) : "—"}
|
||||
subtitle={subscriptions ? <div className="space-y-1">
|
||||
<CostEstimateLabel eventCount={subscriptions.api.eventCount} estimatedEventCount={subscriptions.api.estimatedEventCount} />
|
||||
<div><SubscriptionTokenUsage usage={subscriptions.api} /></div>
|
||||
</div> : subscriptionError ? "API usage is unavailable" : "API usage is loading"}
|
||||
icon={DollarSign}
|
||||
/>
|
||||
<SubscriptionCostCard key={companyId} companyId={companyId} report={subscriptions} error={subscriptionError} onChanged={invalidateSubscriptions} />
|
||||
<MetricTile
|
||||
label="Budget"
|
||||
value={activeBudgetIncidents.length > 0 ? String(activeBudgetIncidents.length) : (
|
||||
@@ -672,6 +690,14 @@ export function Costs({
|
||||
icon={ArrowUpRight}
|
||||
/>
|
||||
</div>
|
||||
{subscriptions && Number(subscriptions.subscription.costCents) > 0 && <p className="text-sm text-muted-foreground">Subscription accounts also have {formatCents(Number(subscriptions.subscription.costCents))} in recorded usage charges for this period, separate from monthly fees.</p>}
|
||||
{subscriptions && subscriptions.unknown.eventCount > 0 && <p className="text-sm text-muted-foreground">{formatTokens(subscriptions.unknown.inputTokens + subscriptions.unknown.cachedInputTokens + subscriptions.unknown.outputTokens)} tokens have other or unknown billing types{Number(subscriptions.unknown.costCents) > 0 ? `, with ${formatCents(Number(subscriptions.unknown.costCents))} in recorded charges` : ""}. They remain in the inference ledger.</p>}
|
||||
{subscriptionError && subscriptions && <p role="status" className="text-sm text-muted-foreground">Showing the last loaded API and subscription usage. Updates will resume automatically.</p>}
|
||||
{discoverSubscriptions.error && <div role="status" className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
||||
<p>Connected accounts could not be checked. Existing subscription estimates are still shown.</p>
|
||||
{subscriptions?.canRefresh && <Button variant="outline" size="sm" disabled={discoverSubscriptions.isPending}
|
||||
onClick={() => discoverSubscriptions.mutate(companyId)}>Retry account check</Button>}
|
||||
</div>}
|
||||
{spendData?.summary.pricingComplete === false && (
|
||||
<div role="status" className="space-y-1 text-sm text-muted-foreground">
|
||||
{spendData.summary.unpricedEventCount > 0 && (
|
||||
@@ -704,14 +730,16 @@ export function Costs({
|
||||
{incidentMutation.error && <p role="alert" className="text-sm text-destructive">Could not update the budget. Check any pending runs or unpriced usage shown on this page, then try again.</p>}
|
||||
<Tabs value={mainTab} onValueChange={(value) => { setMainTab(value as typeof mainTab); setSearchParams(current => { const next = new URLSearchParams(current); next.set("tab", value); return next; }, { replace: true }); }}>
|
||||
{!lockTab ? (
|
||||
<TabsList variant="line" className="justify-start">
|
||||
<TabsTrigger value="overview">Overview</TabsTrigger>
|
||||
{!hideBudgetsTab ? <TabsTrigger value="budgets">Budgets</TabsTrigger> : null}
|
||||
<TabsTrigger value="providers">Providers</TabsTrigger>
|
||||
<TabsTrigger value="billers">Billers</TabsTrigger>
|
||||
<TabsTrigger value="finance">Finance</TabsTrigger>
|
||||
<TabsTrigger value="decisions">Decisions</TabsTrigger>
|
||||
</TabsList>
|
||||
<div className="max-w-full overflow-x-auto pb-2">
|
||||
<TabsList variant="line" className="justify-start">
|
||||
<TabsTrigger value="overview">Overview</TabsTrigger>
|
||||
{!hideBudgetsTab ? <TabsTrigger value="budgets">Budgets</TabsTrigger> : null}
|
||||
<TabsTrigger value="providers">Providers</TabsTrigger>
|
||||
<TabsTrigger value="billers">Billers</TabsTrigger>
|
||||
<TabsTrigger value="finance">Finance</TabsTrigger>
|
||||
<TabsTrigger value="decisions">Decisions</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<TabsContent value="decisions" className="mt-4">{showCustomPrompt ? <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p> : <DecisionHistory companyId={companyId} from={from} to={to} />}</TabsContent>
|
||||
@@ -756,10 +784,7 @@ export function Costs({
|
||||
{row.agentStatus === "terminated" ? <StatusBadge status="terminated" /> : null}
|
||||
</div>
|
||||
<div className="text-right text-sm tabular-nums">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 font-medium">
|
||||
<span>{formatCents(row.costCents)}</span>
|
||||
<CostEstimateLabel eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
</div>
|
||||
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
<div className="text-xs text-muted-foreground">
|
||||
in {formatTokens(row.inputTokens + row.cachedInputTokens)} ({formatTokens(row.cachedInputTokens)} cached) · out {formatTokens(row.outputTokens)}
|
||||
</div>
|
||||
@@ -796,13 +821,12 @@ export function Costs({
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right tabular-nums">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 font-medium">
|
||||
<span>
|
||||
{formatCents(modelRow.costCents)}
|
||||
<span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>
|
||||
</span>
|
||||
<CostEstimateLabel eventCount={modelRow.eventCount} estimatedEventCount={modelRow.estimatedEventCount} />
|
||||
</div>
|
||||
<CostAmount
|
||||
costCents={modelRow.costCents}
|
||||
eventCount={modelRow.eventCount}
|
||||
estimatedEventCount={modelRow.estimatedEventCount}
|
||||
suffix={<span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>}
|
||||
/>
|
||||
<div className="text-muted-foreground">
|
||||
{formatTokens(modelRow.inputTokens + modelRow.cachedInputTokens + modelRow.outputTokens)} tok
|
||||
</div>
|
||||
@@ -841,7 +865,7 @@ export function Costs({
|
||||
className="flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm"
|
||||
>
|
||||
<span className="truncate">{row.projectName ?? row.projectId ?? "Unattributed"}</span>
|
||||
<span className="font-medium tabular-nums">{formatCents(row.costCents)}</span>
|
||||
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user