Open source CapCut alternative.
TypeScript
feat(site): judge CLI turns when credits allow [rebuild]
David Le7a7d6f9d963c
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex e3756a63..0bb30e61 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -1,6 +1,6 @@"use client";-import { useQueryClient } from "@tanstack/react-query";+import { useQueryClient, type QueryClient } from "@tanstack/react-query";import { notesKey } from "@/cut/lib/queries";import { ChatStatusBadge, type ChatStatus } from "./ChatStatusBadge";@@ -108,7 +108,10 @@ import { holdEditorChat } from "@/cut/lib/editorWork";import { recoverSceneCall } from "@/cut/lib/chatRecovery";import { replayChatStream } from "@/cut/lib/chatReplay";import { INTERRUPTED_ERROR, isResumeMessage, RESUME_LIMIT, resumePrompt, scrubLostTurn, unfinishedAsk, type ResumeMetadata, type TurnSettled } from "@/cut/lib/chatResume";-import { claimEngineTool, cancelEngineChat, foldIntoEngineChat } from "@/cut/lib/engineChat";+import { answerEngineGate, claimEngineTool, cancelEngineChat, foldIntoEngineChat } from "@/cut/lib/engineChat";+import { EngineGate, engineInstant, handledSince, judgeEngineTurn } from "@/cut/lib/pi/engineTurn";+import type { EngineRoute } from "@/cut/server/ai/turnCatalog";+import { fetchCreditBalance } from "@/queries/credits";import { projectBackend } from "@/cut/lib/residency";import { beginBrowserChat, browserChatRunning, cancelBrowserChat, watchBrowserChatTurns } from "@/cut/lib/browserChatTurns";import { putCloudThread } from "@/cut/lib/chatCloud";@@ -900,6 +903,17 @@ function ChipsReveal({ open, children }: { open: boolean; children: ReactNode })}/** Running sessions stay mounted for the lifetime of their editor. */+/** Whether this account's turns are judged: signed in, with credits. An+ * account with none chats on its own CLI model, which decides alone. */+async function accountJudges(queryClient: QueryClient): Promise<boolean> {+ if (useGenerate.getState().signedIn !== true || useOutOfCredits.getState().out) return false;+ try {+ return Number((await fetchCreditBalance(queryClient)).balanceMicros) > 0;+ } catch {+ return false;+ }+}+function ChatSession({projectId,threadId,@@ -1037,6 +1051,11 @@ function ChatSession({}, [readOnly, visible]);const sessionKeyRef = useRef<string | null>(null);const toolAbort = useRef(new AbortController());+ const queryClient = useQueryClient();+ // The judged route the next engine send carries, and the quality gate of+ // the engine turn in flight. Both stay empty for an unjudged turn.+ const engineRouteRef = useRef<EngineRoute | undefined>(undefined);+ const engineGateRef = useRef<EngineGate | null>(null);// Resume from the saved thread when this id exists in history.const [initialThread] = useState<ChatThread | undefined>(() =>typeof window === "undefined"@@ -1108,9 +1127,8 @@ function ChatSession({// localBackend (read after the origin resolves), which carries the// account scope the engine requires on every data route.prepareSendMessagesRequest: async ({ messages }) => {- // A CLI turn runs on the person's own model and calls nothing- // hosted on the way, so a free account keeps chatting on a local- // project; the model reads skills through read_skill.+ // The route was judged in sendMessages; an unjudged turn (an account+ // with no credits) carries none and the model reads skills itself.await engineReady();return {api: localBackend.url("/api/cut/ai/chat"),@@ -1121,6 +1139,8 @@ function ChatSession({model: currentModel(),context: productionDeps(projectId).buildContext(),providerSession: sessionFor(currentModel()),+ route: engineRouteRef.current,+ handled: handledSince(messages),},};},@@ -1152,6 +1172,22 @@ function ChatSession({}setClientTools(false);toolAbort.current = new AbortController();+ // An account with credits has the turn judged before the send: one+ // known action runs here with no model round, and the rest go out+ // routed, with the gate answering when the CLI signs off.+ const decision = (await accountJudges(queryClient))+ ? await judgeEngineTurn(options.messages, productionDeps(projectId), options.abortSignal)+ : null;+ if (decision?.instant) {+ const handled = await engineInstant(decision.instant, productionDeps(projectId, options.abortSignal));+ if (handled) {+ setClientTools(true);+ return handled;+ }+ }+ engineRouteRef.current = decision?.route;+ const ask = options.messages.findLast((m) => m.role === "user" && !isResumeMessage(m));+ engineGateRef.current = decision?.route.gate ? new EngineGate(ask?.parts.map((p) => (p.type === "text" ? p.text : "")).join("").trim() ?? "") : null;return engine().sendMessages(options);},reconnectToStream: async (options) => {@@ -1169,7 +1205,7 @@ function ChatSession({return replay;},};- }, [threadId, projectId, currentModel, sessionFor, setClientTools, prepareReplay, attachReplay, registerBrowserTurn]);+ }, [threadId, projectId, currentModel, sessionFor, setClientTools, prepareReplay, attachReplay, registerBrowserTurn, queryClient]);const { messages, setMessages, sendMessage, stop, status, error, clearError, resumeStream } = useChat({id: threadId,@@ -1231,6 +1267,18 @@ function ChatSession({providerSessions.current[provider(modelRef.current)] =d.providerSession;}+ // The engine's turn is signing off: judge its record and answer with+ // the next pass's steer, or none to let it close.+ if (part.type === "data-gate") {+ const { gateId, reply } = part.data as { gateId: string; reply: string };+ const gate = engineGateRef.current;+ const sessionKey = sessionKeyRef.current;+ const signal = toolAbort.current.signal;+ void (async () => {+ const steer = gate ? await gate.steer(reply, productionDeps(projectId), signal).catch(() => null) : null;+ await answerEngineGate(sessionKey, gateId, steer).catch(() => {});+ })();+ }},onToolCall: ({ toolCall }) => {// Gemini turns already executed the tool in the transport loop; their@@ -1257,12 +1305,13 @@ function ChatSession({signal.throwIfAborted();beginChatTurn(threadId);const output = await runAiTool(toolCall.toolName, (toolCall.input ?? {}) as Record<string, unknown>);+ engineGateRef.current?.record(toolCall.toolName, output, undefined);await post({ output });}, signal);} catch (err) {- await post({- errorText: err instanceof Error ? err.message : String(err),- });+ const errorText = err instanceof Error ? err.message : String(err);+ engineGateRef.current?.record(toolCall.toolName, undefined, errorText);+ await post({ errorText });}})();},@@ -1530,6 +1579,9 @@ function ChatSession({const triage = async (rows: QueuedMessage[]) => {const ask = runningAskRef.current;if (!ask) return;+ // Placing rows is a judgment; with no credits to judge with they wait in+ // the tray for the turn to end.+ if (!(await accountJudges(queryClient))) return;triagingRef.current += 1;triagedAtRef.current = Date.now();try {diff --git a/site/src/cut/lib/engineChat.ts b/site/src/cut/lib/engineChat.tsindex 0437eae1..08f6d863 100644--- a/site/src/cut/lib/engineChat.ts+++ b/site/src/cut/lib/engineChat.ts@@ -30,3 +30,13 @@ export async function foldIntoEngineChat(if (!response.ok) return false;return (await response.json() as { folded: boolean }).folded;}++/** Answer the engine's quality gate for a signing-off turn: the steer for its+ * next pass, or null to let it close. A gate the engine no longer holds is+ * dropped. */+export async function answerEngineGate(sessionKey: string | null, gateId: string, steer: string | null): Promise<void> {+ await localBackend.fetch("/api/cut/ai/gate", {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ sessionKey, gateId, steer }),+ });+}diff --git a/site/src/cut/lib/pi/engineTurn.test.ts b/site/src/cut/lib/pi/engineTurn.test.tsnew file mode 100644index 00000000..1dc65da2--- /dev/null+++ b/site/src/cut/lib/pi/engineTurn.test.ts@@ -0,0 +1,194 @@+import { describe, expect, test } from "bun:test";+import type { UIMessage } from "ai";+import { SETTINGS } from "@/lib/config/registry";+import { TOOL_AREA_NAMES } from "@/cut/server/ai/catalog";+import type { CutAgentDeps } from "./cutAgent";+import { EngineGate, engineInstant, handledSince, judgeEngineTurn } from "./engineTurn";++// A Claude or Codex turn judged from the page: the route it carries to the+// engine, the instant path that skips the engine, the asks the provider's+// session hears of later, and the quality gate the engine asks at sign-off.++const WATCH_RESULT = {+ images: [],+ sceneChanges: [1, 2, 3],+ coveredTo: 20,+ truncated: true,+ unwatchedSeconds: 51.6,+ recorded: [],+ unnoted: [{ from: 20, to: 71.6 }],+ source: { assetId: "a1", name: "reference.mp4", duration: 71.6 },+};++function routeAnswers(areas: string[]) {+ const out: Record<string, unknown> = {+ intent: {+ type: "choice",+ choice: "complex",+ probabilities: { chat: 0.02, simple: 0.08, complex: 0.9 },+ confidence: 0.9,+ },+ skill: { type: "choice", choice: "none", probabilities: { none: 0.9 }, confidence: 0.9 },+ needs_reference: { type: "noul", noul: 0.1 },+ unresolved_target: { type: "noul", noul: 0.02 },+ };+ for (const area of TOOL_AREA_NAMES) out[`area::${area}`] = { type: "noul", noul: areas.includes(area) ? 0.9 : 0.01 };+ return out;+}++function qualityAnswers(finished: number) {+ return {+ finished: { type: "noul", noul: finished },+ wantsChange: { type: "noul", noul: 0.9 },+ asksBack: { type: "noul", noul: 0.1 },+ seen: { type: "noul", noul: finished },+ honest: { type: "noul", noul: 0.9 },+ hears: { type: "noul", noul: 0.1 },+ captionsSpeak: { type: "noul", noul: 0.1 },+ next: { type: "choice", choice: "watch", probabilities: { watch: 0.8 }, confidence: 0.8 },+ closeness: { type: "choice", choice: "exact", probabilities: { exact: 0.8 }, confidence: 0.8 },+ };+}++function deps(opts: { finished?: number; delayMs?: number; settings?: Partial<CutAgentDeps["judgeSettings"]> } = {}) {+ const asks: string[][] = [];+ const d: CutAgentDeps = {+ post: async () => new Response(null, { status: 500 }),+ judge: async (payload) => {+ const questions = Object.keys((payload as { questions?: Record<string, unknown> }).questions ?? {});+ asks.push(questions);+ if (opts.delayMs) await new Promise((r) => setTimeout(r, opts.delayMs));+ const answers = questions.includes("finished") ? qualityAnswers(opts.finished ?? 0.9) : routeAnswers(["timeline"]);+ return new Response(JSON.stringify({ model: "jev-latest", answers, usage: {} }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ },+ judgeSettings: { ...SETTINGS.cutJudge.default, instantAction: false, judgeWaitMs: 500, ...opts.settings },+ execTool: async () => ({ ok: true }),+ models: { simple: "chatSimple", complex: "chat" },+ buildContext: () => ({ project: { aspect: "9:16" }, videoTrack: [], media: [] }),+ resolveRefs: async () => [],+ };+ return { deps: d, asks };+}++const user = (id: string, text: string) => ({ id, role: "user", parts: [{ type: "text", text }] }) as UIMessage;++describe("judgeEngineTurn", () => {+ test("a judged turn carries its areas, its skill pick and the gate", async () => {+ const { deps: d } = deps();+ const decision = await judgeEngineTurn([user("u1", "tighten every cut")], d);+ expect(decision?.route.intent).toBe("complex");+ expect(decision?.route.areas).toEqual(["timeline"]);+ expect(decision?.route.skill).toBeNull();+ expect(decision?.route.gate).toBe(true);+ expect(decision?.instant).toBeNull();+ });++ test("skill suggestion off leaves the skill out of the route", async () => {+ const { deps: d } = deps({ settings: { skillSuggestion: false } });+ const decision = await judgeEngineTurn([user("u1", "tighten every cut")], d);+ expect(decision ? "skill" in decision.route : true).toBe(false);+ });++ test("a judgment slower than the wait sends the turn unrouted", async () => {+ const { deps: d } = deps({ delayMs: 200, settings: { judgeWaitMs: 20 } });+ expect(await judgeEngineTurn([user("u1", "tighten every cut")], d)).toBeNull();+ });+});++describe("engineInstant", () => {+ test("the action runs in the editor and streams as a handled single-tool turn", async () => {+ const { deps: d } = deps();+ const ran: string[] = [];+ d.execTool = async (name) => {+ ran.push(name);+ return { id: "c1", muted: true };+ };+ const stream = await engineInstant({ id: "mute", tool: "set_clip_muted", args: { clipId: "c1", muted: true }, say: "Muted it." }, d);+ const chunks: Record<string, unknown>[] = [];+ const reader = stream!.getReader();+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ chunks.push(value as Record<string, unknown>);+ }+ expect(ran).toEqual(["set_clip_muted"]);+ expect(chunks.map((c) => c.type)).toEqual([+ "start",+ "tool-input-available",+ "tool-output-available",+ "text-start",+ "text-delta",+ "text-end",+ "finish",+ ]);+ expect(chunks[0].messageMetadata).toEqual({+ handled: { tool: "set_clip_muted", args: { clipId: "c1", muted: true }, say: "Muted it." },+ });+ });++ test("a tool that throws leaves the turn to the engine", async () => {+ const { deps: d } = deps();+ d.execTool = async () => {+ throw new Error("no such clip");+ };+ expect(await engineInstant({ id: "mute", tool: "set_clip_muted", args: {}, say: "Muted it." }, d)).toBeNull();+ });+});++describe("handledSince", () => {+ test("the handled run before the newest message reaches the provider, oldest first", () => {+ const messages = [+ user("u1", "cut the intro"),+ { id: "a1", role: "assistant", parts: [{ type: "text", text: "Cut." }] } as UIMessage,+ user("u2", "mute it"),+ { id: "a2", role: "assistant", metadata: { handled: { tool: "set_clip_muted", args: { muted: true }, say: "Muted." } }, parts: [] } as UIMessage,+ user("u3", "make it 16:9"),+ { id: "a3", role: "assistant", metadata: { handled: { tool: "set_aspect", args: { aspect: "16:9" }, say: "Now 16:9." } }, parts: [] } as UIMessage,+ user("u4", "now add a title"),+ ];+ expect(handledSince(messages)).toEqual([+ { ask: "mute it", tool: "set_clip_muted", args: { muted: true }, say: "Muted." },+ { ask: "make it 16:9", tool: "set_aspect", args: { aspect: "16:9" }, say: "Now 16:9." },+ ]);+ });++ test("a provider turn last leaves nothing to report", () => {+ const messages = [+ user("u1", "cut the intro"),+ { id: "a1", role: "assistant", parts: [{ type: "text", text: "Cut." }] } as UIMessage,+ user("u2", "now add a title"),+ ];+ expect(handledSince(messages)).toEqual([]);+ });+});++describe("EngineGate", () => {+ test("a turn that half-watched its source is sent back once, then closes when nothing moved", async () => {+ const { deps: d, asks } = deps({ finished: 0.1 });+ const gate = new EngineGate("what happens in this video?");+ gate.record("watch_video", WATCH_RESULT, undefined);+ const steer = await gate.steer("It opens on a yellow title.", d);+ expect(steer).toContain("from=20");+ expect(await gate.steer("It opens on a yellow title.", d)).toBeNull();+ expect(asks.filter((q) => q.includes("finished")).length).toBe(1);+ });++ test("a turn that changed the project without looking is not held", async () => {+ const { deps: d, asks } = deps({ finished: 0.01 });+ const gate = new EngineGate("mute the first clip");+ gate.record("set_clip_muted", { id: "c1", muted: true }, undefined);+ expect(await gate.steer("Muted it.", d)).toBeNull();+ expect(asks.length).toBe(0);+ });++ test("the gate off lets the turn close", async () => {+ const { deps: d, asks } = deps({ finished: 0.1, settings: { qualityGate: false } });+ const gate = new EngineGate("what happens in this video?");+ gate.record("watch_video", WATCH_RESULT, undefined);+ expect(await gate.steer("It opens on a yellow title.", d)).toBeNull();+ expect(asks.length).toBe(0);+ });+});diff --git a/site/src/cut/lib/pi/engineTurn.ts b/site/src/cut/lib/pi/engineTurn.tsnew file mode 100644index 00000000..38f6b8dc--- /dev/null+++ b/site/src/cut/lib/pi/engineTurn.ts@@ -0,0 +1,145 @@+import type { UIMessage, UIMessageChunk } from "ai";+import type { EngineRoute, HandledAsk } from "@/cut/server/ai/turnCatalog";+import { cutJudge } from "../chatRuntime";+import type { ResolvedAction } from "../instantAction";+import { recordLook, type WatchedSource } from "../turnQuality";+import { gateVerdict, judgeTurnAndAction, playInstant, workMark, type CutAgentDeps } from "./cutAgent";+import { isMutatingTool, recordCall, type LedgerRecord } from "./mutationLedger";+import { toToolResult } from "./tools";++// A Claude or Codex turn judged the way a Gemini turn is. The page asks the+// judge before the send: a turn settled to one known action runs in the+// editor with no model round, and any other turn goes to the engine with its+// route — the declared tool areas and the skill to attach. While the CLI+// works, the page records what its tool calls ran and watched, and answers+// the engine's quality gate when the turn signs off. Only an account with+// credits is judged; the rest send unrouted and the model decides.++const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));++/** What the judgment settled for an engine turn. */+export interface EngineDecision {+ route: EngineRoute;+ instant: ResolvedAction | null;+}++/** The turn's route and instant action. Null when the judgment did not land+ * within the wait the hosted loop gives it: the turn then goes out unrouted. */+export async function judgeEngineTurn(+ messages: UIMessage[],+ deps: CutAgentDeps,+ signal?: AbortSignal+): Promise<EngineDecision | null> {+ const settings = deps.judgeSettings ?? cutJudge();+ const decision = judgeTurnAndAction(messages, deps.buildContext(), deps, signal);+ const landed = await Promise.race([decision, sleep(settings.judgeWaitMs).then(() => null)]);+ if (!landed) {+ return null;+ }++ const { route } = landed.verdict;+ return {+ route: {+ intent: route.intent,+ areas: route.areas,+ ...(settings.skillSuggestion && { skill: route.skill }),+ gate: settings.qualityGate,+ },+ instant: landed.instant,+ };+}++/** The settled action as a finished turn: the editor runs it and the stream+ * carries the chunks a single-tool turn emits. The message is marked handled+ * so the provider's session hears of it on the next send. Null when the tool+ * threw, and the turn goes to the engine instead. */+export async function engineInstant(+ action: ResolvedAction,+ deps: CutAgentDeps+): Promise<ReadableStream<UIMessageChunk> | null> {+ const chunks: Record<string, unknown>[] = [];+ const played = await playInstant(action, deps, (chunk) => chunks.push(chunk));+ if (!played) {+ return null;+ }++ const handled: Omit<HandledAsk, "ask"> = { tool: action.tool, args: action.args, say: action.say };+ return new ReadableStream<UIMessageChunk>({+ start(controller) {+ const all = [{ type: "start", messageMetadata: { handled } }, ...chunks, { type: "finish" }];+ for (const chunk of all) controller.enqueue(chunk as unknown as UIMessageChunk);+ controller.close();+ },+ });+}++/** The handled asks since the provider's last turn, oldest first: the run of+ * handled assistant messages that ends just before the newest message. */+export function handledSince(messages: UIMessage[]): HandledAsk[] {+ const out: HandledAsk[] = [];+ for (let i = messages.length - 2; i >= 0; i--) {+ const message = messages[i];+ if (message.role !== "assistant") {+ continue;+ }+ const handled = (message.metadata as { handled?: Omit<HandledAsk, "ask"> } | undefined)?.handled;+ if (!handled) {+ break;+ }+ const before = messages[i - 1];+ const ask = before?.role === "user" ? before.parts.map((p) => (p.type === "text" ? p.text : "")).join("").trim() : "";+ out.unshift({ ask, ...handled });+ }+ return out;+}++/**+ * The quality gate for one engine turn. The page executes every tool call+ * the CLI makes, so it keeps the turn's record here; when the engine asks at+ * sign-off, the record and the reply are judged the way the hosted loop+ * judges them, under the same rounds cap and the same stand-downs.+ */+export class EngineGate {+ private records: LedgerRecord[] = [];+ private looks = new Map<string, WatchedSource>();+ private rounds = 0;+ private mark = "";++ constructor(private readonly ask: string) {}++ /** One tool call the page ran for the turn. */+ record(name: string, output: unknown, errorText: string | undefined): void {+ const response = errorText === undefined ? toToolResult(name, output).details?.response : undefined;+ recordCall(this.records, name, response, errorText);+ if (errorText === undefined) {+ recordLook(this.looks, name, response);+ }+ }++ /** The steer for the turn's next pass, or null to let it close. */+ async steer(reply: string, deps: CutAgentDeps, signal?: AbortSignal): Promise<string | null> {+ const settings = deps.judgeSettings ?? cutJudge();+ if (!settings.qualityGate || this.rounds >= settings.qualityRounds) {+ return null;+ }++ // The hosted loop's stand-downs: a turn that changed the project without+ // looking at a source has nothing measurable, and one sent back that+ // returns with the same record has stopped moving.+ if (this.looks.size === 0 && this.records.some((r) => !r.error && isMutatingTool(r.name))) {+ return null;+ }+ const mark = workMark(this.records, this.looks);+ if (mark === this.mark) {+ return null;+ }++ const verdict = await gateVerdict(reply, this.ask, this.records, this.looks, deps, settings, signal);+ if (!verdict) {+ return null;+ }+ this.mark = mark;+ this.rounds++;+ return verdict.steer;+ }+}diff --git a/site/src/cut/server/ai/bridge.ts b/site/src/cut/server/ai/bridge.tsindex ac23e927..cc681002 100644--- a/site/src/cut/server/ai/bridge.ts+++ b/site/src/cut/server/ai/bridge.ts@@ -22,6 +22,8 @@ interface Waiter {interface Session {writer: UIChunkWriter;waiters: Map<string, Waiter>;+ /** Quality-gate asks the page has not answered yet, by gate id. */+ gates: Map<string, (steer: string | null) => void>;attached: boolean;}@@ -36,7 +38,7 @@ const g2 = globalThis as unknown as { __veditorAiProjects?: Map<string, string>const sessionProjects = (g2.__veditorAiProjects ??= new Map<string, string>());export function registerSession(key: string, writer: UIChunkWriter, projectId?: string) {- sessions.set(key, { writer, waiters: new Map(), attached: true });+ sessions.set(key, { writer, waiters: new Map(), gates: new Map(), attached: true });if (projectId) sessionProjects.set(key, projectId);}@@ -57,6 +59,7 @@ export function detachSession(key: string): void {else waiter.resolve({ errorText: "The editor disconnected before recording this result. Check the project state before repeating the operation." });}session.waiters.clear();+ settleGates(session);}export function unregisterSession(key: string) {@@ -66,6 +69,7 @@ export function unregisterSession(key: string) {clearTimeout(w.timer);w.resolve({ errorText: "The chat request ended before the tool finished." });}+ settleGates(s);}sessions.delete(key);// The chat route unregisters after the provider run settles, so no more@@ -176,3 +180,43 @@ export function resolveBrowserTool(waiter.resolve(result);return true;}++// The page judges the gate with the hosted judge; a page that does not+// answer in this long lets the turn close.+const GATE_TIMEOUT_MS = 20_000;++/** A gate no page will answer lets its turn close. */+function settleGates(session: Session) {+ for (const settle of session.gates.values()) settle(null);+ session.gates.clear();+}++/**+ * Ask the attached page whether a signing-off turn holds up. The page reads+ * the turn's record against the ask through the hosted judge and answers+ * with the steer for the next pass, or null to let the turn close. A session+ * with no attached page closes at once.+ */+export function askPageGate(sessionKey: string, reply: string): Promise<string | null> {+ const session = sessions.get(sessionKey);+ if (!session?.attached) return Promise.resolve(null);+ const gateId = crypto.randomUUID().slice(0, 12);+ session.writer.write({ type: "data-gate", data: { gateId, reply }, transient: true });+ return new Promise((resolve) => {+ const timer = setTimeout(() => settle(null), GATE_TIMEOUT_MS);+ const settle = (steer: string | null) => {+ clearTimeout(timer);+ session.gates.delete(gateId);+ resolve(steer);+ };+ session.gates.set(gateId, settle);+ });+}++/** Called by /api/cut/ai/gate with the page's verdict. */+export function resolvePageGate(sessionKey: string, gateId: string, steer: string | null): boolean {+ const settle = sessions.get(sessionKey)?.gates.get(gateId);+ if (!settle) return false;+ settle(steer);+ return true;+}diff --git a/site/src/cut/server/ai/mcp-proxy-core.mjs b/site/src/cut/server/ai/mcp-proxy-core.mjsindex e6f4a134..d29d0e87 100644--- a/site/src/cut/server/ai/mcp-proxy-core.mjs+++ b/site/src/cut/server/ai/mcp-proxy-core.mjs@@ -68,7 +68,7 @@ export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {if (method === "initialize") {reply({protocolVersion: params?.protocolVersion ?? "2024-11-05",- capabilities: { tools: {} },+ capabilities: { tools: { listChanged: true } },serverInfo: { name: "cut", version: "1.0.0" },});} else if (method === "notifications/initialized" || method === "notifications/cancelled") {@@ -78,7 +78,13 @@ export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {} else if (method === "tools/list") {// Idempotent: retry so a momentary hiccup can't leave the model with an// empty tool set (which reads to it as "editing tools aren't reachable").- const res = await fetchEngine(`${BASE}/api/cut/ai/proxy?type=catalog`, undefined, "tools/list", true);+ // The listing is this session's turn catalog, which request_tools widens.+ const res = await fetchEngine(+ `${BASE}/api/cut/ai/proxy?type=catalog&session=${encodeURIComponent(SESSION)}`,+ undefined,+ "tools/list",+ true+ );const { tools } = await res.json();reply({ tools });} else if (method === "tools/call") {@@ -100,6 +106,8 @@ export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {);const body = await res.json();reply(body); // { content: [...], isError? } — already MCP-shaped+ // A widened catalog: a client that refreshes on notice lists it now.+ if (params?.name === "request_tools") send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });} else if (id !== undefined) {send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown method ${method}` } });}diff --git a/site/src/cut/server/ai/turnCatalog.test.ts b/site/src/cut/server/ai/turnCatalog.test.tsnew file mode 100644index 00000000..849bedf9--- /dev/null+++ b/site/src/cut/server/ai/turnCatalog.test.ts@@ -0,0 +1,60 @@+import { describe, expect, test } from "bun:test";+import { AI_TOOLS, areaTools, CORE_TOOLS, REQUEST_TOOLS_DEF, TOOL_AREA_NAMES } from "./catalog";+import { declaresTool, declareTurn, dropTurn, takeWidened, turnTools, widenTurn } from "./turnCatalog";++const names = (key: string) => turnTools(key).map((t) => t.name);++describe("turnCatalog", () => {+ test("an unrouted turn lists the whole catalog", () => {+ declareTurn("unrouted", undefined, "live");+ expect(names("unrouted")).toEqual(AI_TOOLS.map((t) => t.name));+ expect(turnTools(null)).toBe(AI_TOOLS);+ dropTurn("unrouted");+ });++ test("a routed turn lists the core, its areas and the escape hatch", () => {+ declareTurn("routed", { intent: "simple", areas: ["timeline"], gate: true }, "live");+ const listed = new Set(names("routed"));+ for (const t of [...CORE_TOOLS, ...areaTools(["timeline"])]) expect(listed.has(t.name)).toBe(true);+ expect(listed.has(REQUEST_TOOLS_DEF.name)).toBe(true);+ expect(listed.has(areaTools(["color"])[0].name)).toBe(false);+ expect(declaresTool("routed", areaTools(["color"])[0].name)).toBe(false);+ dropTurn("routed");+ });++ test("a turn routed to every area lists the whole catalog with no escape hatch", () => {+ declareTurn("every", { intent: "complex", areas: [...TOOL_AREA_NAMES], gate: true }, "live");+ expect(names("every")).toEqual(AI_TOOLS.map((t) => t.name));+ dropTurn("every");+ });++ test("a chat turn keeps only the skill readers", () => {+ declareTurn("chat", { intent: "chat", areas: [...TOOL_AREA_NAMES], gate: true }, "live");+ expect(names("chat").sort()).toEqual(["list_skills", "read_skill"]);+ expect(declaresTool("chat", "set_project_name")).toBe(false);+ dropTurn("chat");+ });++ test("request_tools widens the listing, live for Claude", () => {+ declareTurn("widen-live", { intent: "simple", areas: ["timeline"], gate: true }, "live");+ const colorTool = areaTools(["color"])[0].name;+ const result = widenTurn("widen-live", ["color", "timeline", "nonsense"]);+ expect(result.added).toEqual(["color"]);+ expect(result.tools).toContain(colorTool);+ expect(result.note).toBe("Available from your next step.");+ expect(declaresTool("widen-live", colorTool)).toBe(true);+ expect(takeWidened("widen-live")).toBe(false);+ dropTurn("widen-live");+ });++ test("a Codex turn resumes once per widening to list the new tools", () => {+ declareTurn("widen-run", { intent: "simple", areas: ["timeline"], gate: true }, "next-run");+ expect(takeWidened("widen-run")).toBe(false);+ expect(widenTurn("widen-run", ["color"]).note).toContain("next run");+ expect(takeWidened("widen-run")).toBe(true);+ expect(takeWidened("widen-run")).toBe(false);+ expect(widenTurn("widen-run", ["color"]).added).toEqual([]);+ expect(takeWidened("widen-run")).toBe(false);+ dropTurn("widen-run");+ });+});diff --git a/site/src/cut/server/ai/turnCatalog.ts b/site/src/cut/server/ai/turnCatalog.tsnew file mode 100644index 00000000..9346156d--- /dev/null+++ b/site/src/cut/server/ai/turnCatalog.ts@@ -0,0 +1,106 @@+import type { AiToolDef } from "@/cut/lib/aiToolDef";+import { AI_TOOLS, areaTools, CORE_TOOLS, REQUEST_TOOLS_DEF, TOOL_AREA_NAMES } from "./catalog";++// The tools one engine chat turn declares. The page judges a Claude or Codex+// turn the way it judges a Gemini one and sends the route with the request;+// the MCP proxy lists this turn's catalog, a call outside it is refused, and+// `request_tools` widens it. A turn sent without a route (no credits to judge+// with, or an older page) declares the whole catalog and the model decides.++/** The judged route an engine turn carries. Mirrors the page's TurnRoute. */+export interface EngineRoute {+ intent: "chat" | "simple" | "complex";+ areas: string[];+ /** The skill to attach: a name, null for none, absent when skill+ * suggestion is off. */+ skill?: string | null;+ /** The page answers the quality gate when the turn signs off. */+ gate: boolean;+}++/** An ask the page settled to one known action and ran with no model round,+ * reported to the provider's session on its next turn. */+export interface HandledAsk {+ ask: string;+ tool: string;+ args: unknown;+ say: string;+}++/** How the provider picks up a widened catalog. Claude refreshes its listing+ * on the proxy's list_changed notice; Codex reads it once per run, so the+ * turn resumes in a fresh run to see the new tools. */+export type CatalogRefresh = "live" | "next-run";++interface TurnTools {+ /** The declared areas; null declares the whole catalog. */+ areas: Set<string> | null;+ /** A chat verdict: no editor tool at all. */+ chat: boolean;+ refresh: CatalogRefresh;+ /** Areas added since the last run started. */+ widened: boolean;+}++// A chat turn keeps only the skill readers: they run in the engine, change+// nothing, and keep the editor server bound for a session that resumes with+// tool calls in its history.+const CHAT_TOOLS = new Set(["list_skills", "read_skill"]);++// Survives dev-server module reloads.+const g = globalThis as unknown as { __cutTurnTools?: Map<string, TurnTools> };+const turns = (g.__cutTurnTools ??= new Map<string, TurnTools>());++/** Record the catalog a chat session's turn declares. */+export function declareTurn(sessionKey: string, route: EngineRoute | undefined, refresh: CatalogRefresh): void {+ const areas = route && route.intent !== "chat" ? new Set(route.areas.filter((a) => TOOL_AREA_NAMES.includes(a))) : null;+ turns.set(sessionKey, { areas, chat: route?.intent === "chat", refresh, widened: false });+}++export function dropTurn(sessionKey: string): void {+ turns.delete(sessionKey);+}++/** The MCP listing for a session: the whole catalog for an unrouted turn,+ * the core plus its areas (and the escape hatch) for a routed one. */+export function turnTools(sessionKey: string | null): AiToolDef[] {+ const turn = sessionKey ? turns.get(sessionKey) : undefined;+ if (!turn) return AI_TOOLS;+ if (turn.chat) return AI_TOOLS.filter((t) => CHAT_TOOLS.has(t.name));+ if (!turn.areas || turn.areas.size === TOOL_AREA_NAMES.length) return AI_TOOLS;+ const names = new Set([...CORE_TOOLS, ...areaTools(turn.areas)].map((t) => t.name));+ return [...AI_TOOLS.filter((t) => names.has(t.name)), REQUEST_TOOLS_DEF];+}++/** Whether the session's turn declares the tool. */+export function declaresTool(sessionKey: string, name: string): boolean {+ return turnTools(sessionKey).some((t) => t.name === name);+}++/** Add the asked areas to the session's turn. Returns the result the model+ * reads: what was added, the tool names, and when they arrive. */+export function widenTurn(sessionKey: string, asked: unknown): { added: string[]; tools: string[]; note: string } {+ const turn = turns.get(sessionKey);+ const wanted = Array.isArray(asked) ? asked : [];+ const added = !turn?.areas+ ? []+ : wanted.filter((a): a is string => typeof a === "string" && TOOL_AREA_NAMES.includes(a) && !turn.areas!.has(a));+ for (const a of added) turn!.areas!.add(a);+ if (added.length > 0) turn!.widened = true;+ const note =+ added.length === 0+ ? "Nothing to add: those areas are already declared."+ : turn!.refresh === "live"+ ? "Available from your next step."+ : "Declared from the next run: end this step with one short line and the turn resumes with them.";+ return { added, tools: areaTools(added).map((t) => t.name), note };+}++/** True once per widening, for a provider that reads its catalog per run:+ * the turn resumes so the new tools are listed. */+export function takeWidened(sessionKey: string): boolean {+ const turn = turns.get(sessionKey);+ if (!turn?.widened || turn.refresh !== "next-run") return false;+ turn.widened = false;+ return true;+}diff --git a/site/src/cut/server/ai/turnStreams.test.ts b/site/src/cut/server/ai/turnStreams.test.tsindex d95868b8..6f049de5 100644--- a/site/src/cut/server/ai/turnStreams.test.ts+++ b/site/src/cut/server/ai/turnStreams.test.ts@@ -4,7 +4,7 @@ import os from "node:os";import path from "node:path";import type { UIMessageChunk } from "ai";import { cancelTurnStream, followTurnStream, startTurnStream } from "./turnStreams";-import { callBrowserTool, claimBrowserTool, detachSession, registerSession, resolveBrowserTool, unregisterSession } from "./bridge";+import { askPageGate, callBrowserTool, claimBrowserTool, detachSession, registerSession, resolveBrowserTool, resolvePageGate, unregisterSession } from "./bridge";import { createProject, readProject } from "../projects";const root = await mkdtemp(path.join(os.tmpdir(), "donkey-chat-test-"));@@ -60,6 +60,23 @@ test("only one tab can claim a tool, and detached calls are not replayed", asyncunregisterSession("session");});+test("the page answers the quality gate, and a detached page lets the turn close", async () => {+ const chunks: Record<string, unknown>[] = [];+ registerSession("gate", { write: (chunk) => chunks.push(chunk) });+ const held = askPageGate("gate", "It opens on a title.");+ const ask = chunks[0] as { type: string; data: { gateId: string; reply: string }; transient: boolean };+ expect(ask.type).toBe("data-gate");+ expect(ask.transient).toBe(true);+ expect(ask.data.reply).toBe("It opens on a title.");+ expect(resolvePageGate("gate", ask.data.gateId, "Watch the rest.")).toBe(true);+ expect(await held).toBe("Watch the rest.");+ const pending = askPageGate("gate", "Done.");+ detachSession("gate");+ expect(await pending).toBeNull();+ expect(await askPageGate("gate", "Done.")).toBeNull();+ unregisterSession("gate");+});+test("detached tools edit their original documents and journal their results", async () => {const first = await createProject("First chat test");const second = await createProject("Second chat test");diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.tsindex d9b26b95..17469825 100644--- a/site/src/cut/server/http/ai.ts+++ b/site/src/cut/server/http/ai.ts@@ -14,14 +14,17 @@ import {attachSession,detachSession,claimBrowserTool,+ askPageGate,registerSession,+ resolvePageGate,resolveBrowserTool,unregisterSession,type UIChunkWriter,} from "../ai/bridge";import { rewriteCaptions, translateCaptions } from "../ai/captions";import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";-import { AI_SKILL_INDEX, AI_TOOLS, attachedAssetsBlock, readSkill, systemPrompt } from "../ai/catalog";+import { AI_SKILL_INDEX, AI_TOOLS, attachedAssetsBlock, readSkill, skillRelevanceBlock, systemPrompt } from "../ai/catalog";+import { declaresTool, declareTurn, dropTurn, takeWidened, turnTools, widenTurn, type EngineRoute, type HandledAsk } from "../ai/turnCatalog";import { STEP_BUDGET, stopText, turnClose, type TurnEnd } from "../../lib/turnBudget";import { codexCommand } from "../tool-path";import { errorMessage } from "../util";@@ -33,6 +36,35 @@ interface ChatBody {context?: unknown;/** Provider-native session/thread id from the previous turn, if any. */providerSession?: string;+ /** The page's judged route; absent when the turn was not judged. */+ route?: EngineRoute;+ /** Asks the editor carried out on its own since the provider's last turn. */+ handled?: HandledAsk[];+}++const routeSchema = z.object({+ intent: z.enum(["chat", "simple", "complex"]),+ areas: z.array(z.string().max(100)).max(100),+ skill: z.string().max(200).nullable().optional(),+ gate: z.boolean(),+});++const handledSchema = z.array(z.object({+ ask: z.string().max(100_000),+ tool: z.string().max(200),+ args: z.unknown(),+ say: z.string().max(10_000),+})).max(50);++// The steer a Codex turn resumes on once request_tools widened its catalog.+const WIDENED_STEER = "The tool areas you requested are declared now. Carry on with the request.";++/** The asks the provider's session never saw, as prompt text. The editor ran+ * them straight from the judgment, so a resumed session learns of them here. */+function handledBlock(handled: HandledAsk[]): string {+ if (handled.length === 0) return "";+ const lines = handled.map((h) => `- "${h.ask}" → ${h.tool} ${JSON.stringify(h.args)}: ${h.say}`);+ return `<handled_by_editor>\nThe editor carried out these asks itself since your last turn:\n${lines.join("\n")}\n</handled_by_editor>\n\n`;}// Cut lives under site/src/cut; the proxy is spawned by filesystem path (not@@ -84,6 +116,8 @@ async function runClaude(signal.throwIfAborted();let textCount = 0;let session = body.providerSession;+ // The newest assistant message's text: the line the quality gate reads.+ let reply = "";const say = (text: string) => {const id = `t${++textCount}`;emit({ type: "text-start", id });@@ -198,10 +232,13 @@ async function runClaude(content_block?: { type: string };delta?: { type: string; text?: string };};- if (ev.type === "content_block_start" && ev.content_block?.type === "text") {+ if (ev.type === "message_start") {+ reply = "";+ } else if (ev.type === "content_block_start" && ev.content_block?.type === "text") {textId = `t${++textCount}`;emit({ type: "text-start", id: textId });} else if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && textId) {+ reply += ev.delta.text ?? "";emit({ type: "text-delta", id: textId, delta: ev.delta.text ?? "" });} else if (ev.type === "content_block_stop" && textId) {emit({ type: "text-end", id: textId });@@ -237,14 +274,23 @@ async function runClaude(// A run that spent the budget resumes from its own session, so the next// one carries the whole tool history and the build finishes on its own.+ // A judged turn that signs off asks the page's quality gate first, and a+ // hold resumes the session on the gate's steer.let ask = prompt;- for (let extensions = 0; ; extensions++) {+ let extensions = 0;+ for (;;) {const end = await pass(ask);if (signal.aborted) return;+ const steer = end === "done" && body.route?.gate ? await askPageGate(sessionKey, reply) : null;+ if (steer && !signal.aborted) {+ ask = steer;+ continue;+ }const close = turnClose({ end, spoke: textCount > 0, extensions });if (!close) return;if ("signoff" in close) return say(close.signoff);ask = close.steer;+ extensions++;}}@@ -264,16 +310,27 @@ async function runCodex(let session = body.providerSession;let ask = prompt;for (;;) {- session = (await codexRun(emit, ask, body.model, session, base, sessionKey, signal)) ?? session;+ const run = await codexRun(emit, ask, body.model, session, base, sessionKey, signal);+ session = run.thread ?? session;if (signal.aborted || !session) return;const folds = inbox.take();- if (!folds.length) return;- for (const fold of folds) fold.resolve(true);- ask = folds.map((fold) => fold.text).join("\n\n");+ if (folds.length) {+ for (const fold of folds) fold.resolve(true);+ ask = folds.map((fold) => fold.text).join("\n\n");+ continue;+ }+ // Codex lists its tools once per run, so a widened catalog takes a run.+ if (takeWidened(sessionKey)) {+ ask = WIDENED_STEER;+ continue;+ }+ const steer = body.route?.gate ? await askPageGate(sessionKey, run.reply) : null;+ if (!steer || signal.aborted) return;+ ask = steer;}}-/** One `codex exec` run; returns the session it ran in. */+/** One `codex exec` run; returns the session it ran in and its last line. */async function codexRun(emit: UIChunkWriter["write"],prompt: string,@@ -282,11 +339,12 @@ async function codexRun(base: string,sessionKey: string,signal: AbortSignal-): Promise<string | undefined> {+): Promise<{ thread: string | undefined; reply: string }> {signal.throwIfAborted();const codex = await codexCommand();const mcp = mcpCommand(base, sessionKey);let thread = session;+ let reply = "";const args = ["exec"];if (session) args.push("resume", session);args.push("--json", "--skip-git-repo-check", "-m", model);@@ -356,6 +414,7 @@ async function codexRun(thread = ev.thread_id;emit({ type: "data-session", data: { providerSession: ev.thread_id }, transient: true });} else if (ev.type === "item.completed" && ev.item?.type === "agent_message" && ev.item.text) {+ reply = ev.item.text;say(ev.item.text);} else if (ev.type === "error" || ev.type === "turn.failed") {emit({ type: "error", errorText: stopText(ev.error?.message ?? ev.message) });@@ -396,7 +455,7 @@ async function codexRun(resolve();});});- return thread;+ return { thread, reply };}/**@@ -530,14 +589,21 @@ export const aiApi = {messages: z.array(z.object({ id: z.string(), role: z.enum(["user", "assistant", "system"]), parts: z.array(z.object({ type: z.string() })) })),runtime: SETTINGS.chatRuntime.schema,context: z.object({ project: z.object({ id: z.string().min(1).max(200) }) }),+ route: routeSchema.optional(),+ handled: handledSchema.optional(),}).safeParse(body);if (!identity.success) return Response.json({ error: "A project and chat are required." }, { status: 400 });const projectId = identity.data.context.project.id;+ const { route, handled = [] } = identity.data;const base = new URL(req.url).origin;const sessionKey = crypto.randomUUID();const userText = lastUserText(body.messages);const attachments = lastUserAttachments(body.messages);- const prompt = `${userText}${attachedAssetsBlock(attachments)}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;+ // A judged work turn carries the judge's skill pick, the same block the+ // hosted loop attaches.+ const skill = route && route.intent !== "chat" && route.skill !== undefined ? `\n\n${skillRelevanceBlock(route.skill)}` : "";+ const prompt = `${handledBlock(handled)}${userText}${attachedAssetsBlock(attachments)}${skill}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;+ declareTurn(sessionKey, route, body.model.startsWith("claude") ? "live" : "next-run");return startTurnStream(projectId, body.threadId, (signal) => createUIMessageStream({execute: async ({ writer }) => {@@ -566,6 +632,7 @@ export const aiApi = {} finally {folds.close();unregisterSession(sessionKey);+ dropTurn(sessionKey);emit({ type: "finish" });}},@@ -638,12 +705,13 @@ export const aiApi = {});},- /** MCP-shaped tool catalog for the stdio proxy. */+ /** MCP-shaped tool catalog for the stdio proxy: the session's turn+ * catalog. */async proxyCatalog(req: Request) {- const type = new URL(req.url).searchParams.get("type");- if (type !== "catalog") return Response.json({ error: "Bad request." }, { status: 400 });+ const params = new URL(req.url).searchParams;+ if (params.get("type") !== "catalog") return Response.json({ error: "Bad request." }, { status: 400 });return Response.json({- tools: AI_TOOLS.map((t) => ({+ tools: turnTools(params.get("session")).map((t) => ({name: t.name,description: t.description,inputSchema: t.inputSchema,@@ -658,10 +726,15 @@ export const aiApi = {name?: string;args?: Record<string, unknown>;};+ const key = String(sessionKey ?? "");+ if (name === "request_tools") return Response.json(mcpText(widenTurn(key, args?.areas)));const def = AI_TOOLS.find((t) => t.name === name);if (!name || !def) {return Response.json({ ...mcpText(`Unknown tool: ${name}`), isError: true });}+ if (!declaresTool(key, name)) {+ return Response.json({ ...mcpText(`${name} is not declared this turn. Call request_tools with its area first.`), isError: true });+ }if (def.server) {if (name === "list_skills") return Response.json(mcpText({ skills: AI_SKILL_INDEX }));@@ -676,7 +749,7 @@ export const aiApi = {}}- const result = await callBrowserTool(String(sessionKey ?? ""), name, args ?? {});+ const result = await callBrowserTool(key, name, args ?? {});if (result.errorText !== undefined) {return Response.json({ ...mcpText(result.errorText), isError: true });}@@ -709,6 +782,17 @@ export const aiApi = {return Response.json(mcpText(result.output ?? { ok: true }));},+ /** The page's quality-gate verdict for a signing-off turn. */+ async gate(req: Request) {+ const body = z.object({+ sessionKey: z.string().min(1).max(200),+ gateId: z.string().min(1).max(200),+ steer: z.string().max(20_000).nullable(),+ }).safeParse(await req.json().catch(() => null));+ if (!body.success) return Response.json({ error: "A chat session and gate are required." }, { status: 400 });+ return Response.json({ ok: resolvePageGate(body.data.sessionKey, body.data.gateId, body.data.steer) });+ },+/** The browser posts tool outputs here after executing them on the store. */async toolResult(req: Request) {const { sessionKey, toolCallId, output, errorText } = (await req.json()) as {diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 63b03aae..732a7a88 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -129,6 +129,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "GET", path: "/api/cut/ai/proxy", handler: (req) => aiApi.proxyCatalog(req) },{ method: "POST", path: "/api/cut/ai/proxy", handler: (req) => aiApi.proxyCall(req) },{ method: "POST", path: "/api/cut/ai/tool-result", handler: (req) => aiApi.toolResult(req) },+ { method: "POST", path: "/api/cut/ai/gate", handler: (req) => aiApi.gate(req) },];export type RouteMatch =diff --git a/site/src/queries/credits.ts b/site/src/queries/credits.tsindex cca90ac9..15e33449 100644--- a/site/src/queries/credits.ts+++ b/site/src/queries/credits.ts@@ -1,6 +1,6 @@"use client";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";import { apiFetch } from "@/queries/apiClient";@@ -39,13 +39,24 @@ export type Account = {superUser: boolean;};+const readCreditBalance = () => apiFetch<CreditBalance>("/api/credits/balance");++// How long a read balance stands in for the account's before it is read again.+const BALANCE_FRESH_MS = 60_000;+export function useCreditBalance() {return useQuery({- queryFn: () => apiFetch<CreditBalance>("/api/credits/balance"),+ queryFn: readCreditBalance,queryKey: creditBalanceQueryKey,});}+/** The balance through the shared cache: a fresh read is reused, a stale one+ * is read again. */+export function fetchCreditBalance(queryClient: QueryClient): Promise<CreditBalance> {+ return queryClient.fetchQuery({ queryKey: creditBalanceQueryKey, queryFn: readCreditBalance, staleTime: BALANCE_FRESH_MS });+}+export type SubscribeBonus = {// Where the offer reached the person: the app opened the bonus on its own,// a promotion came by email.