Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: auto wrap desktop sessions at account quota

Slendywy9815354a55eb
diff --git a/apps/app/src/react-app/shell/notification-center.tsx b/apps/app/src/react-app/shell/notification-center.tsx
index ca3749d0..32aaf7a9 100644
--- a/apps/app/src/react-app/shell/notification-center.tsx
+++ b/apps/app/src/react-app/shell/notification-center.tsx
@@ -25,6 +25,7 @@ import { useControlAction, type OmniRushControlAction } from "./control/control-
import { openNotificationCenterEvent } from "./notifications";
import { useReloadCoordinator } from "./reload-coordinator";
import { useShellConfig } from "./shell-config";
+import { toast } from "@/components/ui/sonner";
const SEVERITY_ICONS: Record<NotificationSeverity, LucideIcon> = {
info: Info,
@@ -87,6 +88,25 @@ export function NotificationBell({ variant = "icon" }: { variant?: "icon" | "sid
}), [notifications]);
useControlAction(notificationsListAction);
+ const notificationToastAction = useMemo<OmniRushControlAction>(() => ({
+ id: "notifications.show",
+ label: "Show notification",
+ description: "Show a short status notification in the desktop shell.",
+ kind: "command",
+ sideEffect: "none",
+ requiresArgs: true,
+ execute: (args) => {
+ const value = args && typeof args === "object" ? args as Record<string, unknown> : {};
+ const title = typeof value.title === "string" ? value.title : "OmniRush";
+ const body = typeof value.body === "string" ? value.body : "";
+ const severity = value.severity === "warning" || value.severity === "error" || value.severity === "success" ? value.severity : "info";
+ const show = severity === "warning" ? toast.warning : severity === "error" ? toast.error : severity === "success" ? toast.success : toast.info;
+ show(title, body ? { description: body } : undefined);
+ return { shown: true };
+ },
+ }), []);
+ useControlAction(notificationToastAction);
+
const unreadCount = useMemo(
() => notifications.filter((notification) => notification.readAt === null).length,
[notifications],
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
new file mode 100644
index 00000000..ab8167c2
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, describe, expect, test } from "bun:test";
+
+import { OmniRushBudgetWrap } from "./omnirush-budget-wrap.js";
+
+const previousAdapter = process.env.OMNIRUSH_ENGINE_ADAPTER_URL;
+const previousAuthorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION;
+
+afterEach(() => {
+ if (previousAdapter === undefined) delete process.env.OMNIRUSH_ENGINE_ADAPTER_URL;
+ else process.env.OMNIRUSH_ENGINE_ADAPTER_URL = previousAdapter;
+ if (previousAuthorization === undefined) delete process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION;
+ else process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION = previousAuthorization;
+});
+
+describe("account budget wrap plugin", () => {
+ test("waits for session idle, then compacts without inserting a trace message", async () => {
+ process.env.OMNIRUSH_ENGINE_ADAPTER_URL = "http://adapter.test";
+ process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION = "Bearer adapter";
+ const calls: Array<{ url: string; init?: RequestInit }> = [];
+ const hooks = await OmniRushBudgetWrap({
+ directory: "/workspace/project",
+ fetch: async (input, init) => {
+ calls.push({ url: String(input), init });
+ return new Response(null, { status: 204 });
+ },
+ });
+
+ const modelHeaders: Record<string, string> = {};
+ await hooks["chat.headers"]!({ sessionID: "ses_1", model: { providerID: "omnirush" } }, { headers: modelHeaders });
+ expect(modelHeaders["x-omnirush-session-id"]).toBe("ses_1");
+
+ await hooks["omnirush.http.response"]!({
+ request: new Request("http://gateway.test/v1/responses", {
+ headers: { "x-omnirush-session-id": "ses_1" },
+ }),
+ response: new Response(null, {
+ status: 200,
+ headers: { "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://adapter.test/session/ses_1/summarize");
+ expect(calls[0]!.init?.method).toBe("POST");
+ expect(calls[0]!.init?.body).toBe("{}");
+ expect(new Headers(calls[0]!.init?.headers).get("authorization")).toBe("Bearer adapter");
+ expect(new Headers(calls[0]!.init?.headers).get("x-opencode-directory")).toBe(encodeURIComponent("/workspace/project"));
+ });
+
+ test("the backend wrap-up response clears the pending marker", async () => {
+ process.env.OMNIRUSH_ENGINE_ADAPTER_URL = "http://adapter.test";
+ const calls: string[] = [];
+ const hooks = await OmniRushBudgetWrap({
+ fetch: async (input) => {
+ calls.push(String(input));
+ return new Response(null, { status: 204 });
+ },
+ });
+
+ const request = new Request("http://gateway.test/v1/responses", {
+ headers: { "x-omnirush-session-id": "ses_2" },
+ });
+ await hooks["omnirush.http.response"]!({
+ request,
+ response: new Response(null, { status: 200, headers: { "x-omnirush-wrap-required": "1" } }),
+ });
+ await hooks["omnirush.http.response"]!({
+ request,
+ response: new Response(null, { status: 200, headers: { "x-omnirush-wrap-up": "1" } }),
+ });
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_2" } } });
+ expect(calls).toHaveLength(0);
+ });
+});
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
new file mode 100644
index 00000000..e57cb7c3
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
@@ -0,0 +1,123 @@
+/** Automatically finish an account-level quota wrap in the desktop GUI.
+ *
+ * The backend decides when a grant needs wrapping and publishes a private
+ * response header. This plugin waits until the engine reports the session
+ * idle, then asks the local engine to compact. 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 pending = new Map<string, { inFlight: boolean }>();
+type BudgetFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
+type BudgetClient = {
+ tui?: { showToast?: (input: { query?: { directory?: string }; body: { title: string; message: string; variant: string; duration: number } }) => Promise<unknown> };
+};
+
+type RecordValue = Record<string, unknown>;
+
+function record(value: unknown): value is RecordValue {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function sessionIDFromEvent(event: unknown): string {
+ if (!record(event) || !record(event.properties)) return "";
+ const properties = event.properties;
+ return typeof properties.sessionID === "string" ? properties.sessionID : "";
+}
+
+export const OmniRushBudgetWrap = async (input: {
+ directory?: string;
+ fetch?: BudgetFetch;
+ client?: BudgetClient;
+}) => {
+ const baseUrl = (process.env.OMNIRUSH_ENGINE_ADAPTER_URL?.trim() ?? "").replace(/\/+$/, "");
+ const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim() ?? "";
+ const fetcher = input.fetch ?? globalThis.fetch;
+
+ async function notify(title: string, message: string, variant: "info" | "warning"): Promise<void> {
+ const body = { title, message, variant, duration: 12_000 };
+ try {
+ await input.client?.tui?.showToast?.({
+ ...(input.directory ? { query: { directory: input.directory } } : {}),
+ body,
+ });
+ } catch {
+ // The headless adapter may not implement the native TUI endpoint.
+ }
+ // 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",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify({
+ kind: "command",
+ input: { id: "notifications.show", args: { title, body: message, severity: variant } },
+ }),
+ }).catch(() => undefined);
+ }
+
+ async function compact(sessionID: string): Promise<void> {
+ const entry = pending.get(sessionID);
+ if (!entry || entry.inFlight || !baseUrl) return;
+ entry.inFlight = true;
+ await notify("Wrapping up", "Your token allowance is nearly exhausted. Saving a handoff now.", "warning");
+ try {
+ const response = await fetcher(
+ baseUrl + "/session/" + encodeURIComponent(sessionID) + "/summarize",
+ {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ ...(authorization ? { authorization } : {}),
+ ...(input.directory ? { "x-opencode-directory": encodeURIComponent(input.directory) } : {}),
+ },
+ body: "{}",
+ },
+ );
+ if (!response.ok) throw new Error("automatic budget wrap returned " + response.status);
+ await notify(
+ "Wrap up complete",
+ "This session was wrapped because your token allowance was nearly exhausted. Please continue after receiving more tokens.",
+ "info",
+ );
+ 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.
+ entry.inFlight = false;
+ }
+ }
+
+ return {
+ "chat.headers": async (input: { sessionID?: string; model?: { providerID?: string } }, output: { headers: Record<string, string> }) => {
+ const sessionID = input?.sessionID?.trim() ?? "";
+ if (sessionID && input.model?.providerID === "omnirush") output.headers["x-omnirush-session-id"] = sessionID;
+ },
+ "omnirush.http.response": async (event: { request?: Request; response?: Response }) => {
+ const request = event?.request;
+ const response = event?.response;
+ const sessionID = request?.headers.get("x-omnirush-session-id")?.trim() ?? "";
+ if (!sessionID || !response) return;
+ if (response.headers.get(WRAP_UP_HEADER) === "1") {
+ pending.delete(sessionID);
+ return;
+ }
+ if (response.headers.get(REQUIRED_HEADER) === "1") {
+ pending.set(sessionID, { inFlight: false });
+ }
+ },
+ event: async ({ event }: { event: unknown }) => {
+ if (!record(event) || event.type !== "session.idle") return;
+ const sessionID = sessionIDFromEvent(event);
+ if (sessionID) await compact(sessionID);
+ },
+ dispose: async () => {
+ pending.clear();
+ },
+ };
+};
diff --git a/apps/server/src/opencode-plugins/omnirush-engine2.ts b/apps/server/src/opencode-plugins/omnirush-engine2.ts
index f8c039a2..a813b858 100644
--- a/apps/server/src/opencode-plugins/omnirush-engine2.ts
+++ b/apps/server/src/opencode-plugins/omnirush-engine2.ts
@@ -37,6 +37,7 @@ import * as ManagedPolicy from "./managed-policy.js";
import * as ChromeDevtools from "./omnirush-chrome-devtools.js";
import * as CapabilitiesKnowledge from "./omnirush-capabilities-knowledge.js";
import * as ExtensionsPreview from "./omnirush-extensions-preview.js";
+import * as BudgetWrap from "./omnirush-budget-wrap.js";
import * as OfficeAttachments from "./omnirush-office-attachments.js";
import * as Spreadsheets from "./omnirush-spreadsheets.js";
import * as PdfAttachments from "./omnirush-pdf-attachments.js";
@@ -57,6 +58,7 @@ export const OMNIRUSH_V1_PLUGIN_MODULES: ReadonlyArray<Record<string, unknown>>
ChromeDevtools,
CapabilitiesKnowledge,
ExtensionsPreview,
+ BudgetWrap,
OfficeAttachments,
Spreadsheets,
PdfAttachments,