Skip to content

Open source CapCut alternative.

TypeScript

feat(site): hosted calls report the balance they leave behind

David Le65c620cac1d5
diff --git a/site/src/app/api/inference/responses/route.ts b/site/src/app/api/inference/responses/route.ts
index 60748e42..e95623d7 100644
--- a/site/src/app/api/inference/responses/route.ts
+++ b/site/src/app/api/inference/responses/route.ts
@@ -1,5 +1,7 @@
import { NextResponse } from "next/server";
+import { creditMicrosToString } from "@/lib/credits/amounts";
+
import {
creditErrorResponse,
creditUsageHeaders,
@@ -107,8 +109,12 @@ export const POST = withDonkeyAuth(async (request) => {
// Bill from the terminal usage before the terminal event goes
// out: the invocation lives only as long as the stream, so the
// usage row must land before the client can stop reading.
+ // The balance after the charge rides the terminal frame — the
+ // headers went out before the charge existed — so the page's
+ // credits readout moves the moment the reply lands.
+ let creditsRemaining: string | undefined;
if (!bypassCredits) {
- await recordInferenceUsage({
+ const recorded = await recordInferenceUsage({
clientId: client.clientId,
conversationId: request.donkey.conversationId,
model: streamed.model,
@@ -119,8 +125,9 @@ export const POST = withDonkeyAuth(async (request) => {
usage: event.usage,
userId: request.donkey.userId,
});
+ creditsRemaining = creditMicrosToString(recorded.remainingBalanceMicros);
}
- send({ type: "response.completed", response: event.body });
+ send({ type: "response.completed", response: event.body, creditsRemaining });
}
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
} catch (error) {
diff --git a/site/src/cut/lib/hosted.ts b/site/src/cut/lib/hosted.ts
index b470e9fc..f44a0bf3 100644
--- a/site/src/cut/lib/hosted.ts
+++ b/site/src/cut/lib/hosted.ts
@@ -39,9 +39,31 @@ function setOut(out: boolean) {
}
}
+/** The balance as the hosted routes last reported it, in dollars, as a
+ * subscription. A charged call answers with the balance it left behind — in a
+ * header, or in the terminal frame of a stream — so the top bar's credits
+ * readout follows every call without a request of its own. `settled` counts
+ * calls that answered with no balance, for which the readout asks the balance
+ * route once the charge has had a moment to land. */
+export const useHostedBalance = create<{ balance: string | null; settled: number }>(() => ({
+ balance: null,
+ settled: 0,
+}));
+
+export function reportBalance(balance: string | undefined) {
+ if (balance === undefined) {
+ useHostedBalance.setState((s) => ({ settled: s.settled + 1 }));
+ return;
+ }
+ useHostedBalance.setState({ balance });
+}
+
async function noteBalance(res: Response) {
if (res.ok) {
setOut(false);
+ // A stream reports from its terminal frame; the header is on the rest.
+ if (res.headers.get("Content-Type")?.startsWith("text/event-stream")) return;
+ reportBalance(res.headers.get("X-Donkey-Credits-Remaining") ?? undefined);
return;
}
if (res.status !== 402) return;
diff --git a/site/src/cut/lib/pi/donkeyStream.ts b/site/src/cut/lib/pi/donkeyStream.ts
index 7f30b4e4..e6a60af6 100644
--- a/site/src/cut/lib/pi/donkeyStream.ts
+++ b/site/src/cut/lib/pi/donkeyStream.ts
@@ -10,6 +10,7 @@ import {
type ToolCall,
type Usage,
} from "@earendil-works/pi-ai";
+import { reportBalance } from "../hosted";
// The transport adapter: pi Context in, Donkey's hosted Responses route out.
// Every model call the agent makes flows through here — pi's own providers are
@@ -164,7 +165,13 @@ async function readStream(
else if (line.startsWith("data: ")) data += line.slice(6);
}
if (!data || data === "[DONE]") continue;
- let event: { type?: string; delta?: string; response?: ResponseBody; message?: string };
+ let event: {
+ type?: string;
+ delta?: string;
+ response?: ResponseBody;
+ message?: string;
+ creditsRemaining?: string;
+ };
try {
event = JSON.parse(data) as typeof event;
} catch {
@@ -175,6 +182,7 @@ async function readStream(
onDelta(event.delta);
} else if (event.type === "response.completed" && event.response) {
completed = event.response;
+ reportBalance(event.creditsRemaining);
}
}
}