Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

Ask before context wraps in the desktop app

Slendywya88b92035785
diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsx
index 4f04120b..f86ef0ca 100644
--- a/apps/app/src/react-app/shell/app-root.tsx
+++ b/apps/app/src/react-app/shell/app-root.tsx
@@ -29,6 +29,7 @@ import { EnterpriseActivationGate } from "../domains/cloud/enterprise-activation
import { OmniRushWebAccessGate } from "../domains/cloud/omnirush-web-access-gate";
import { OrgOnboardingPage } from "../domains/cloud/org-onboarding-page";
import { NewProvidersListener } from "./new-providers-listener";
+import { BudgetWrapConsent } from "./budget-wrap-consent";
import { useDesktopFontZoomBehavior } from "./font-zoom";
import { LoadingOverlay } from "./loading-overlay";
import { useVisualViewportInset } from "../../hooks/use-visual-viewport-inset";
@@ -389,6 +390,7 @@ export function AppRoot() {
<OmniRushControlProvider>
<OmniRushRouteControlActions />
<OmniRushContextPublisher />
+ <BudgetWrapConsent />
<DenAuthControlActions />
<BrandThemeControlActions />
<EnterpriseActivationGate>
diff --git a/apps/app/src/react-app/shell/budget-wrap-consent.tsx b/apps/app/src/react-app/shell/budget-wrap-consent.tsx
new file mode 100644
index 00000000..634c7943
--- /dev/null
+++ b/apps/app/src/react-app/shell/budget-wrap-consent.tsx
@@ -0,0 +1,100 @@
+import { useMemo } from "react";
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { useControlAction, type OmniRushControlAction } from "./control/control-provider";
+
+type Choice = "pending" | "accept" | "decline" | "done";
+type Offer = { sessionID: string; offerID: string; scopes: string; choice: Choice; error?: string };
+type WrapStore = {
+ offers: Offer[];
+ offer: (sessionID: string, offerID: string, scopes: string) => Choice;
+ choose: (sessionID: string, offerID: string, choice: Choice, error?: string) => void;
+ clear: (sessionID: string, offerID: string) => void;
+};
+
+const useWrapStore = create<WrapStore>()(persist((set, get) => ({
+ offers: [],
+ offer: (sessionID, offerID, scopes) => {
+ const existing = get().offers.find((entry) => entry.sessionID === sessionID && entry.offerID === offerID);
+ if (existing) return existing.choice;
+ set((state) => ({ offers: [
+ { sessionID, offerID, scopes, choice: "pending" },
+ ...state.offers.filter((entry) => entry.sessionID !== sessionID),
+ ] }));
+ return "pending";
+ },
+ choose: (sessionID, offerID, choice, error) => set((state) => ({
+ offers: state.offers.map((entry) => entry.sessionID === sessionID && entry.offerID === offerID
+ ? { ...entry, choice, error } : entry),
+ })),
+ clear: (sessionID, offerID) => set((state) => ({
+ offers: state.offers.filter((entry) => entry.sessionID !== sessionID || entry.offerID !== offerID),
+ })),
+}), {
+ name: "omnirush:budget-wrap-consent:v1",
+ storage: createJSONStorage(() => localStorage),
+ partialize: (state) => ({ offers: state.offers }),
+}));
+
+function fields(args: unknown): { sessionID: string; offerID: string; scopes: string } | null {
+ if (!args || typeof args !== "object") return null;
+ if (!("sessionID" in args) || !("offerID" in args)
+ || typeof args.sessionID !== "string" || typeof args.offerID !== "string") return null;
+ const sessionID = args.sessionID.trim();
+ const offerID = args.offerID.trim();
+ if (!sessionID || !offerID) return null;
+ return { sessionID, offerID, scopes: "scopes" in args && typeof args.scopes === "string" ? args.scopes : "" };
+}
+
+/** The choice stays on screen, and in local storage, until the person answers. */
+export function BudgetWrapConsent() {
+ const offers = useWrapStore((state) => state.offers);
+ const pending = offers.find((entry) => entry.choice === "pending");
+
+ const updateAction = useMemo<OmniRushControlAction>(() => ({
+ id: "budget.wrap.update",
+ label: "Update pending quota wrap",
+ description: "Show or settle a local, user-approved context wrap offer.",
+ // The engine syncs a local offer through the query mailbox, so polling
+ // does not turn on Control Mode or trigger its visible action animation.
+ kind: "query",
+ sideEffect: "none",
+ requiresArgs: true,
+ execute: (args) => {
+ const parsed = fields(args);
+ if (!parsed || !args || typeof args !== "object") return { ok: false, error: "Invalid wrap offer" };
+ const operation = "operation" in args ? args.operation : undefined;
+ const store = useWrapStore.getState();
+ if (operation === "offer") return { choice: store.offer(parsed.sessionID, parsed.offerID, parsed.scopes) };
+ if (operation === "finish") store.choose(parsed.sessionID, parsed.offerID, "done");
+ else if (operation === "fail") store.choose(parsed.sessionID, parsed.offerID, "pending", "The wrap could not finish. Choose whether to retry.");
+ else if (operation === "clear") store.clear(parsed.sessionID, parsed.offerID);
+ else return { ok: false, error: "Unknown wrap operation" };
+ return { ok: true };
+ },
+ }), []);
+ useControlAction(updateAction);
+
+ return <Dialog open={Boolean(pending)} onOpenChange={() => undefined}>
+ <DialogContent showCloseButton={false} data-testid="budget-wrap-consent">
+ <DialogHeader>
+ <DialogTitle>Save a handoff for this session?</DialogTitle>
+ <DialogDescription>
+ Your {pending?.scopes.replace(",", " and ") || "token"} allowance is nearly used. A wrap saves a summary of this session so you can resume it later. You can keep working while tokens remain, whether you wrap or not.
+ </DialogDescription>
+ </DialogHeader>
+ {pending?.error ? <p className="text-sm text-destructive">{pending.error}</p> : null}
+ <DialogFooter>
+ <Button variant="outline" data-testid="budget-wrap-decline" onClick={() => {
+ if (pending) useWrapStore.getState().choose(pending.sessionID, pending.offerID, "decline");
+ }}>Keep working</Button>
+ <Button data-testid="budget-wrap-accept" onClick={() => {
+ if (pending) useWrapStore.getState().choose(pending.sessionID, pending.offerID, "accept");
+ }}>Wrap up</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>;
+}
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
index ff6bc362..87fc7765 100644
--- a/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
@@ -2,117 +2,123 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { OmniRushBudgetWrap } from "./omnirush-budget-wrap.js";
-/**
- * The engine sends model requests through the global fetch: the plugin wraps
- * it and reads the backend's wrap headers on the requests it marked in
- * `chat.headers`. The model responses here come from a stand-in global fetch.
- */
-const gatewayHeaders = new Map<string, Record<string, string>>();
const originalFetch = globalThis.fetch;
+const originalServer = process.env.OMNIRUSH_SERVER_URL;
+const originalToken = process.env.OMNIRUSH_SERVER_TOKEN;
+const gatewayHeaders = new Map<string, Record<string, string>>();
+
beforeAll(() => {
+ process.env.OMNIRUSH_SERVER_URL = "http://localhost:3579";
+ process.env.OMNIRUSH_SERVER_TOKEN = "local-token";
globalThis.fetch = Object.assign(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
return new Response("{}", { status: 200, headers: gatewayHeaders.get(headers.get("x-omnirush-session-id") ?? "") ?? {} });
}, originalFetch);
});
+
afterAll(() => {
globalThis.fetch = originalFetch;
+ if (originalServer === undefined) delete process.env.OMNIRUSH_SERVER_URL;
+ else process.env.OMNIRUSH_SERVER_URL = originalServer;
+ if (originalToken === undefined) delete process.env.OMNIRUSH_SERVER_TOKEN;
+ else process.env.OMNIRUSH_SERVER_TOKEN = originalToken;
});
type Hooks = Awaited<ReturnType<typeof OmniRushBudgetWrap>>;
-/** One model request of `sessionID` as the engine sends it: headers from chat.headers, then the global fetch. */
-async function modelRequest(hooks: Hooks, sessionID: string, answer: Record<string, string>): Promise<void> {
+async function modelRequest(hooks: Hooks, sessionID: string, answer: Record<string, string>, agent?: string): Promise<Record<string, string>> {
const headers: Record<string, string> = { "content-type": "application/json" };
- await hooks["chat.headers"]!({ sessionID, model: { providerID: "omnirush", id: "gpt-6-astra" } }, { headers });
+ await hooks["chat.headers"]!({ sessionID, agent, model: { providerID: "omnirush", id: "gpt-6-astra" } }, { headers });
gatewayHeaders.set(sessionID, answer);
await (await fetch("http://gateway.test/v1/responses", { method: "POST", headers, body: "{}" })).text();
+ return headers;
}
-describe("account budget wrap plugin", () => {
- test("waits for session idle, then compacts on the session's model without inserting a trace message", async () => {
- const calls: Array<{ url: string; init?: RequestInit }> = [];
- const hooks = await OmniRushBudgetWrap({
- directory: "/workspace/project",
- serverUrl: new URL("http://127.0.0.1:4096"),
- fetch: async (input, init) => {
- calls.push({ url: String(input), init });
- return new Response("true", { status: 200 });
- },
- });
-
- const modelHeaders: Record<string, string> = {};
- await hooks["chat.headers"]!({ sessionID: "ses_1", model: { providerID: "omnirush", id: "gpt-6-astra" } }, { headers: modelHeaders });
- expect(modelHeaders["x-omnirush-session-id"]).toBe("ses_1");
- const otherHeaders: Record<string, string> = {};
- await hooks["chat.headers"]!({ sessionID: "ses_1", model: { providerID: "openai", id: "gpt-x" } }, { headers: otherHeaders });
- expect(otherHeaders["x-omnirush-session-id"]).toBeUndefined();
-
- await modelRequest(hooks, "ses_1", { "x-omnirush-wrap-required": "1" });
- await hooks.event!({ event: { type: "session.updated", properties: { sessionID: "ses_1" } } });
- expect(calls).toHaveLength(0);
- await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } });
-
- expect(calls).toHaveLength(1);
- expect(calls[0]!.url).toBe("http://127.0.0.1:4096/session/ses_1/summarize");
- expect(calls[0]!.init?.method).toBe("POST");
- expect(JSON.parse(String(calls[0]!.init?.body))).toEqual({ providerID: "omnirush", modelID: "gpt-6-astra" });
- expect(new Headers(calls[0]!.init?.headers).get("x-opencode-directory")).toBe(encodeURIComponent("/workspace/project"));
-
- // Done: the next idle does nothing.
- await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } });
- expect(calls).toHaveLength(1);
- });
+function operation(init?: RequestInit): string {
+ const body: unknown = JSON.parse(String(init?.body));
+ if (!body || typeof body !== "object" || !("input" in body)) return "";
+ const input = body.input;
+ if (!input || typeof input !== "object" || !("args" in input)) return "";
+ const args = input.args;
+ return args && typeof args === "object" && "operation" in args ? String(args.operation) : "";
+}
- test("the backend wrap-up response clears the pending marker", async () => {
- const calls: string[] = [];
- const hooks = await OmniRushBudgetWrap({
+describe("account budget wrap plugin", () => {
+ test("compacts only after acceptance, with the selected model and private marker", async () => {
+ const controls: string[] = [];
+ let compactCalls = 0;
+ let hooks: Hooks;
+ hooks = await OmniRushBudgetWrap({
serverUrl: "http://127.0.0.1:4096",
- fetch: async (input) => {
- calls.push(String(input));
- return new Response("true", { status: 200 });
+ fetch: async (input, init) => {
+ const url = String(input);
+ if (url.includes("/experimental/ui-control/request")) {
+ const action = operation(init);
+ controls.push(action);
+ return Response.json({ ok: true, result: { choice: action === "offer" ? "accept" : "ok" } });
+ }
+ if (url.endsWith("/session/ses_accept/summarize")) {
+ compactCalls += 1;
+ expect(JSON.parse(String(init?.body))).toEqual({ providerID: "omnirush", modelID: "gpt-6-astra" });
+ const headers = await modelRequest(hooks, "ses_accept", { "x-omnirush-wrap-up": "1" }, "compaction");
+ expect(headers["x-omnirush-context-wrap"]).toBe("1");
+ await hooks.event!({ event: { type: "session.compacted", properties: { sessionID: "ses_accept" } } });
+ return new Response("true", { status: 200 });
+ }
+ throw new Error("unexpected URL: " + url);
},
});
-
- await modelRequest(hooks, "ses_2", { "x-omnirush-wrap-required": "1" });
- await modelRequest(hooks, "ses_2", { "x-omnirush-wrap-up": "1" });
- await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_2" } } });
- expect(calls).toHaveLength(0);
+ try {
+ const headers = await modelRequest(hooks, "ses_accept", {
+ "x-omnirush-wrap-required": "1",
+ "x-omnirush-wrap-offer-id": "allowance-1",
+ "x-omnirush-wrap-scopes": "day",
+ });
+ expect(headers["x-omnirush-context-wrap"]).toBeUndefined();
+ expect(compactCalls).toBe(0);
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_accept" } } });
+ await Bun.sleep(30);
+ expect(controls).toContain("offer");
+ expect(controls).toContain("finish");
+ expect(compactCalls).toBe(1);
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_accept" } } });
+ await Bun.sleep(10);
+ expect(compactCalls).toBe(1);
+ } finally { await hooks.dispose!(); }
});
- test("a request without the marker never starts a wrap", async () => {
- const calls: string[] = [];
+ test("declining leaves the session running and never compacts it", async () => {
+ let compactCalls = 0;
const hooks = await OmniRushBudgetWrap({
serverUrl: "http://127.0.0.1:4096",
fetch: async (input) => {
- calls.push(String(input));
+ if (String(input).includes("/experimental/ui-control/request")) return Response.json({ ok: true, result: { choice: "decline" } });
+ compactCalls += 1;
return new Response("true", { status: 200 });
},
});
- gatewayHeaders.set("", { "x-omnirush-wrap-required": "1" });
- await (await fetch("http://gateway.test/v1/responses", { method: "POST", body: "{}" })).text();
- await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_4" } } });
- expect(calls).toHaveLength(0);
+ try {
+ await modelRequest(hooks, "ses_decline", { "x-omnirush-wrap-required": "1", "x-omnirush-wrap-offer-id": "allowance-2" });
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_decline" } } });
+ await Bun.sleep(30);
+ expect(compactCalls).toBe(0);
+ } finally { await hooks.dispose!(); }
});
- test("a failed wrap retries on the next idle without showing the toast again", async () => {
- const toasts: string[] = [];
- let attempts = 0;
+ test("no connected window keeps the offer pending without compaction", async () => {
+ let controlCalls = 0;
const hooks = await OmniRushBudgetWrap({
serverUrl: "http://127.0.0.1:4096",
- client: { tui: { showToast: async ({ body }) => { toasts.push(body.title); } } },
- fetch: async () => {
- attempts += 1;
- return new Response(null, { status: attempts < 3 ? 500 : 200 });
- },
+ fetch: async () => { controlCalls += 1; return Response.json({ ok: false, error: "window away" }); },
});
- await modelRequest(hooks, "ses_3", { "x-omnirush-wrap-required": "1" });
- for (let idle = 0; idle < 3; idle += 1) {
- // Every answer of the retried turns still asks for the wrap.
- await modelRequest(hooks, "ses_3", { "x-omnirush-wrap-required": "1" });
- await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_3" } } });
- }
- expect(attempts).toBe(3);
- expect(toasts).toEqual(["Wrapping up", "Wrap up complete"]);
+ try {
+ await modelRequest(hooks, "ses_away", { "x-omnirush-wrap-required": "1", "x-omnirush-wrap-offer-id": "allowance-3" });
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_away" } } });
+ await Bun.sleep(30);
+ expect(controlCalls).toBeGreaterThan(0);
+ const headers: Record<string, string> = {};
+ await hooks["chat.headers"]!({ sessionID: "ses_away", model: { providerID: "omnirush", id: "gpt-6-astra" } }, { headers });
+ expect(headers["x-omnirush-context-wrap"]).toBeUndefined();
+ } finally { await hooks.dispose!(); }
});
});
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
index 703d8374..451a32de 100644
--- a/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
@@ -1,18 +1,21 @@
-/** Automatically finish an account-level quota wrap in the desktop GUI.
+/** Offer an account-level quota wrap in the desktop GUI.
*
* The backend decides when a grant needs wrapping and publishes a private
* response header on the model response. The engine sends model requests
* through the global fetch, which this plugin wraps to read that header on
* requests it marked (`chat.headers`). Once the engine reports the session
- * idle it asks the engine to compact the session on the model it last ran on.
+ * idle it asks the desktop window for an explicit, persistent choice. Only an
+ * accepted offer asks the engine to compact on the model it last ran on.
* The compaction record itself contains the generated handoff summary; no
* warning or synthetic prompt is written to the session trace.
*/
const REQUIRED_HEADER = "x-omnirush-wrap-required";
const WRAP_UP_HEADER = "x-omnirush-wrap-up";
+const OFFER_HEADER = "x-omnirush-wrap-offer-id";
const SESSION_HEADER = "x-omnirush-session-id";
type ModelRef = { providerID: string; modelID: string };
-const pending = new Map<string, { inFlight: boolean; announced?: boolean }>();
+type Offer = { id: string; scopes: string; watching: boolean; inFlight: boolean; approved: boolean; backendWrapped: boolean; compacted: boolean };
+const pending = new Map<string, Offer>();
/** The model each session last sent a request on (the compaction runs on it). */
const models = new Map<string, ModelRef>();
const MAX_TRACKED_SESSIONS = 256;
@@ -39,17 +42,8 @@ function remember<T>(map: Map<string, T>, key: string, value: T): void {
while (map.size > MAX_TRACKED_SESSIONS) map.delete(map.keys().next().value as string);
}
-/** Records what a model response says about the session's wrap. */
-function noteBudgetResponse(sessionID: string, headers: Headers): void {
- if (!sessionID) return;
- if (headers.get(WRAP_UP_HEADER) === "1") {
- pending.delete(sessionID);
- return;
- }
- if (headers.get(REQUIRED_HEADER) === "1" && !pending.has(sessionID)) remember(pending, sessionID, { inFlight: false });
-}
-
let installed = false;
+const listeners = new Set<(sessionID: string, headers: Headers) => void>();
/** Wraps the global fetch once: a marked model request's response headers are read, nothing else changes. */
function install(): void {
@@ -60,7 +54,7 @@ function install(): void {
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
const sessionID = headers.get(SESSION_HEADER)?.trim() ?? "";
const response = await base(input, init);
- if (sessionID) noteBudgetResponse(sessionID, response.headers);
+ if (sessionID) for (const listener of listeners) listener(sessionID, response.headers);
return response;
};
globalThis.fetch = Object.assign(patched, base);
@@ -84,6 +78,53 @@ export const OmniRushBudgetWrap = async (input: {
const baseUrl = String(input.serverUrl ?? "").replace(/\/+$/, "");
const authorization = basicAuthorization();
const fetcher = input.fetch ?? globalThis.fetch;
+ let disposed = false;
+ const server = (process.env.OMNIRUSH_SERVER_URL ?? "").trim().replace(/\/+$/, "");
+ const token = (process.env.OMNIRUSH_SERVER_TOKEN ?? process.env.OMNIRUSH_POLICY_TOKEN ?? "").trim();
+
+ async function control(id: string, args: Record<string, string>): Promise<string> {
+ if (!server || !token) return "unavailable";
+ try {
+ const response = await fetcher(server + "/experimental/ui-control/request", {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify({ kind: "query", input: { id, args } }),
+ });
+ if (!response.ok) return "unavailable";
+ const result: unknown = await response.json();
+ if (!record(result) || result.ok !== true || !record(result.result)) return "unavailable";
+ const choice = result.result.choice;
+ return typeof choice === "string" ? choice : "ok";
+ } catch {
+ return "unavailable";
+ }
+ }
+
+ const update = (sessionID: string, entry: Offer, operation: string) =>
+ control("budget.wrap.update", { sessionID, offerID: entry.id, scopes: entry.scopes, operation });
+
+ const noteBudgetResponse = (sessionID: string, headers: Headers) => {
+ const current = pending.get(sessionID);
+ if (headers.get(WRAP_UP_HEADER) === "1") {
+ if (current?.approved) current.backendWrapped = true;
+ return;
+ }
+ if (headers.get(REQUIRED_HEADER) !== "1") {
+ if (current && !current.inFlight) {
+ pending.delete(sessionID);
+ void update(sessionID, current, "clear");
+ }
+ return;
+ }
+ const id = headers.get(OFFER_HEADER) || `legacy:${headers.get("x-omnirush-wrap-scopes") ?? ""}`;
+ if (current?.id === id) return;
+ if (current) void update(sessionID, current, "clear");
+ remember(pending, sessionID, {
+ id, scopes: headers.get("x-omnirush-wrap-scopes") || "token", watching: false,
+ inFlight: false, approved: false, backendWrapped: false, compacted: false,
+ });
+ };
+ listeners.add(noteBudgetResponse);
async function notify(title: string, message: string, variant: "info" | "warning"): Promise<void> {
const body = { title, message, variant, duration: 12_000 };
@@ -98,8 +139,6 @@ export const OmniRushBudgetWrap = async (input: {
// The desktop shell has its own notification center. The server-scoped
// control request is consumed by the connected window and never becomes a
// session message or trace part.
- const server = (process.env.OMNIRUSH_SERVER_URL ?? "").trim().replace(/\/+$/, "");
- const token = (process.env.OMNIRUSH_SERVER_TOKEN ?? process.env.OMNIRUSH_POLICY_TOKEN ?? "").trim();
if (!server || !token) return;
await fetcher(server + "/experimental/ui-control/request", {
method: "POST",
@@ -116,12 +155,8 @@ export const OmniRushBudgetWrap = async (input: {
const model = models.get(sessionID);
if (!entry || entry.inFlight || !baseUrl || !model) return;
entry.inFlight = true;
- // Once per wrap: a failed summarize retries on the next idle without
- // showing the toast again.
- if (!entry.announced) {
- entry.announced = true;
- await notify("Wrapping up", "Your token allowance is nearly exhausted. Saving a handoff now.", "warning");
- }
+ entry.approved = true;
+ await notify("Wrapping up", "Saving this session's handoff now.", "info");
try {
const response = await fetcher(
baseUrl + "/session/" + encodeURIComponent(sessionID) + "/summarize",
@@ -136,33 +171,58 @@ export const OmniRushBudgetWrap = async (input: {
},
);
if (!response.ok) throw new Error("automatic budget wrap returned " + response.status);
+ if (!entry.compacted || !entry.backendWrapped) throw new Error("the wrap was not confirmed by the engine and gateway");
await notify(
"Wrap up complete",
- "This session was wrapped because your token allowance was nearly exhausted. Please continue after receiving more tokens.",
+ "Your handoff is saved. You can keep working while tokens remain.",
"info",
);
+ await update(sessionID, entry, "finish");
pending.delete(sessionID);
} catch {
- // Leave the pending marker so the next idle event can retry. This path
- // never inserts a prompt or diagnostic message into the user's trace.
+ // A failed wrap requires a fresh click. Never retry on the next idle.
+ entry.approved = false;
entry.inFlight = false;
+ await update(sessionID, entry, "fail");
+ await notify("Wrap up did not finish", "Choose Wrap up again to retry, or keep working.", "warning");
+ }
+ }
+
+ async function watch(sessionID: string): Promise<void> {
+ const entry = pending.get(sessionID);
+ if (!entry || entry.watching || entry.inFlight) return;
+ entry.watching = true;
+ while (!disposed && pending.get(sessionID) === entry && !entry.inFlight) {
+ const offered = await update(sessionID, entry, "offer");
+ if (offered === "decline" || offered === "done") { pending.delete(sessionID); break; }
+ if (offered === "accept") { await compact(sessionID); continue; }
+ await new Promise<void>((resolve) => setTimeout(resolve, 3_000));
}
+ entry.watching = false;
}
return {
- "chat.headers": async (input: { sessionID?: string; model?: { providerID?: string; id?: string; modelID?: string } }, output: { headers: Record<string, string> }) => {
+ "chat.headers": async (input: { sessionID?: string; agent?: string; model?: { providerID?: string; id?: string; modelID?: string } }, output: { headers: Record<string, string> }) => {
const sessionID = input?.sessionID?.trim() ?? "";
if (!sessionID || input.model?.providerID !== "omnirush") return;
output.headers[SESSION_HEADER] = sessionID;
+ if (input.agent === "compaction" && pending.get(sessionID)?.approved) output.headers["x-omnirush-context-wrap"] = "1";
const modelID = input.model.id ?? input.model.modelID;
if (modelID) remember(models, sessionID, { providerID: input.model.providerID, modelID });
},
event: async ({ event }: { event: unknown }) => {
- if (!record(event) || event.type !== "session.idle") return;
+ if (!record(event)) return;
const sessionID = sessionIDFromEvent(event);
- if (sessionID) await compact(sessionID);
+ if (!sessionID) return;
+ if (event.type === "session.compacted") {
+ const entry = pending.get(sessionID);
+ if (entry?.inFlight) entry.compacted = true;
+ }
+ if (event.type === "session.idle") void watch(sessionID);
},
dispose: async () => {
+ disposed = true;
+ listeners.delete(noteBudgetResponse);
pending.clear();
models.clear();
},
diff --git a/evals/specs/budget-wrap-consent.e2e.test.ts b/evals/specs/budget-wrap-consent.e2e.test.ts
new file mode 100644
index 00000000..b648f0f9
--- /dev/null
+++ b/evals/specs/budget-wrap-consent.e2e.test.ts
@@ -0,0 +1,61 @@
+import { expect } from "vitest";
+import { browserScript, spec } from "@omnirush/testkit";
+import { shimmerChat } from "../worlds/chat.ts";
+
+const test = spec.world(shimmerChat);
+
+test("a quota handoff waits for a choice, honors decline, and offers again after the allowance changes", async ({ user, probe, step, evidence }) => {
+ const offer = (offerID: string, operation = "offer") => probe.eval(
+ browserScript(async (inputOfferID: string, inputOperation: string) => {
+ const control = window.__omnirushControl;
+ const connection = {
+ port: localStorage.getItem("omnirush.server.port"),
+ token: localStorage.getItem("omnirush.server.token"),
+ };
+ if (!control || !connection.port || !connection.token) throw new Error("Desktop control server unavailable");
+ const response = await fetch(`http://127.0.0.1:${connection.port}/experimental/ui-control/request`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${connection.token}`, "content-type": "application/json" },
+ body: JSON.stringify({ kind: "query", input: {
+ id: "budget.wrap.update",
+ args: { sessionID: "ses_budget_journey", offerID: inputOfferID, scopes: "day,week", operation: inputOperation },
+ } }),
+ });
+ if (!response.ok) throw new Error(`Control mailbox returned ${response.status}`);
+ return response.json();
+ }, [offerID, operation]),
+ { awaitPromise: true },
+ );
+
+ await step("the offer stays visible until answered", async () => {
+ expect(await offer("allowance-one")).toMatchObject({ ok: true, result: { choice: "pending" } });
+ await user.see({ testId: "budget-wrap-consent" });
+ await user.see({ role: "button", label: "Wrap up" });
+ await user.see({ role: "button", label: "Keep working" });
+ expect(await offer("allowance-one")).toMatchObject({ ok: true, result: { choice: "pending" } });
+ await user.see({ testId: "budget-wrap-consent" });
+ });
+
+ await step("declining suppresses that allowance's offer", async () => {
+ await user.click({ role: "button", label: "Keep working" });
+ await user.notSee({ testId: "budget-wrap-consent" });
+ expect(await offer("allowance-one")).toMatchObject({ ok: true, result: { choice: "decline" } });
+ await user.notSee({ testId: "budget-wrap-consent" });
+ });
+
+ await step("a changed allowance asks again, and acceptance closes the offer", async () => {
+ expect(await offer("allowance-two")).toMatchObject({ ok: true, result: { choice: "pending" } });
+ await user.see({ testId: "budget-wrap-consent" });
+ await user.click({ role: "button", label: "Wrap up" });
+ await user.notSee({ testId: "budget-wrap-consent" });
+ expect(await offer("allowance-two")).toMatchObject({ ok: true, result: { choice: "accept" } });
+ expect(await offer("allowance-two", "finish")).toMatchObject({ ok: true });
+ expect(await offer("allowance-two")).toMatchObject({ ok: true, result: { choice: "done" } });
+ });
+
+ evidence.recordAssertionEvidence(
+ "An unanswered wrap stays visible; decline is remembered for one allowance; a changed allowance asks again",
+ "The desktop shell showed a persistent choice for the first offer. Decline dismissed it and subsequent sync returned decline. A second allowance reopened it; acceptance and completion dismissed it without a stop screen.",
+ true,
+ );
+});