mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
Merge branch 'codex/speko-voice-runtime' into codex/speko-voice-ui
* codex/speko-voice-runtime: feat(costs): report monthly subscriptions beside API spend (#15634) Fix Dot Cloud invitation and anonymous consent setup (#15722) refactor(heartbeat): extract scheduling and monitor recovery (#15717)
This commit is contained in:
commit
7f044b4d8a
65 files changed
+5336
-56682
No files matched your search
@@ -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(); }}
|
||||
|
||||
Reference in new issue
Block a user