Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions apps/desktop/src/main/__tests__/pricing-settings-boundary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';

const PAGE = new URL('../../../src/renderer/settings/usage-settings-page.tsx', import.meta.url);
const OVERLAYS = new URL('../../../src/renderer/app-shell-overlays.tsx', import.meta.url);
const MODAL = new URL('../../../src/renderer/settings/settings-modal.tsx', import.meta.url);
const SURFACE = new URL('../../../src/renderer/settings/settings-surface.tsx', import.meta.url);

test('Pricing renderer stays behind the Host-backed port and away from the legacy bridge', async () => {
const [source, overlays, modal, surface] = await Promise.all([
readFile(PAGE, 'utf8'),
readFile(OVERLAYS, 'utf8'),
readFile(MODAL, 'utf8'),
readFile(SURFACE, 'utf8'),
]);

assert.match(source, /DesktopPricingSettingsPort/);
assert.match(source, /EffectivePricingEntry/);
assert.match(source, /saved_refresh_failed/);
assert.match(source, /onReloadPricing/);
assert.match(source, /isReady/);
assert.doesNotMatch(source, /window\.maka\.settings\.pricing/);
assert.doesNotMatch(source, /usage:pricing:(?:list|put|reset|changed)/);

assert.match(overlays, /pricingPort=\{desktopPricingSettingsPort\}/);
assert.match(modal, /pricingPort: DesktopPricingSettingsPort/);
assert.match(modal, /pricingPort=\{props\.pricingPort\}/);
assert.match(surface, /pricingPort: DesktopPricingSettingsPort/);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import assert from "node:assert/strict";
import { describe, test } from "node:test";
import { registerRuntimeHostPricingIpc } from "../runtime-host-pricing-ipc-main.js";

type Handler = (event: unknown, ...args: any[]) => unknown;

describe("Runtime Host Pricing IPC", () => {
test("forwards Host snapshots and normalizes mutation inputs", async () => {
const handlers = new Map<string, Handler>();
const snapshot = {
hostEpoch: "epoch",
connectionId: "connection",
revision: 3,
entries: [],
};
let received: unknown;
const outcome = {
kind: "reconciliation_unavailable",
reason: "outcome_unknown",
} as const;
const client = {
async loadPricingSnapshot() {
return snapshot;
},
async applyPricingMutation(input: unknown) {
received = input;
return outcome;
},
};
register(handlers, client);

assert.deepEqual(
await handlers.get("settings:pricing:load")?.({}),
snapshot,
);
assert.deepEqual(
await handlers.get("settings:pricing:mutate")?.(
{},
{
base: snapshot,
mutation: { kind: "delete", modelKey: "provider:model" },
},
),
outcome,
);
assert.deepEqual(received, {
base: snapshot,
mutation: { kind: "delete", modelKey: "provider:model" },
});
});

test("rejects a mutation whose base snapshot is malformed", async () => {
const handlers = new Map<string, Handler>();
register(handlers, {
async loadPricingSnapshot() {
return { hostEpoch: "epoch", connectionId: "connection", revision: 0, entries: [] };
},
async applyPricingMutation() {
throw new Error("must not reach Host client");
},
});
const mutate = handlers.get("settings:pricing:mutate")!;

await assert.rejects(
async () => mutate({}, {
base: {
hostEpoch: "",
connectionId: "connection",
revision: 0,
entries: [],
},
mutation: { kind: "delete", modelKey: "provider:model" },
}),
/Invalid pricing host epoch/,
);
});
});

function register(handlers: Map<string, Handler>, client: object): void {
registerRuntimeHostPricingIpc({
ipcMain: {
handle: (channel, handler) => {
handlers.set(channel, handler as Handler);
},
},
client: client as never,
});
}
2 changes: 2 additions & 0 deletions apps/desktop/src/main/runtime-host-boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ import { registerRuntimeHostMemoryIpc } from "./runtime-host-memory-ipc-main.js"
import { registerRuntimeHostOAuthIpc } from "./runtime-host-oauth-ipc-main.js";
import { RuntimeHostOAuthPresentation } from "./runtime-host-oauth-presentation.js";
import { registerRuntimeHostPermissionsIpc } from "./runtime-host-permissions-ipc-main.js";
import { registerRuntimeHostPricingIpc } from "./runtime-host-pricing-ipc-main.js";
import { registerRuntimeHostSearchIpc } from "./runtime-host-search-ipc-main.js";
import { createRuntimeHostProjectSessionCatalog } from "./runtime-host-project-session-catalog.js";
import { toDesktopHostSessionSummary } from "./runtime-host-session-catalog-ipc-main.js";
Expand Down Expand Up @@ -584,6 +585,7 @@ function registerHostClientIpc(
},
} satisfies Parameters<typeof registerRuntimeHostSettingsIpc>[0];
registerRuntimeHostSettingsIpc(settingsIpcDeps);
registerRuntimeHostPricingIpc({ ipcMain: scopedIpc, client });
registerRuntimeHostConfigIpc({
ipcMain: scopedIpc,
client,
Expand Down
123 changes: 123 additions & 0 deletions apps/desktop/src/main/runtime-host-pricing-ipc-main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import type { ipcMain as electronIpcMain } from "electron";
import { comparePricingModelKeys } from "@maka/core/usage-stats/pricing";
import {
decodePricingMutateInput,
decodePricingQueryResult,
PRICING_PAGE_MAX_ITEMS,
type EffectivePricingEntry,
} from "@maka/runtime-host/protocol";
import type {
DesktopPricingMutationInput,
DesktopPricingSnapshot,
} from "../shared/runtime-host-pricing.js";
import type { DesktopRuntimeHostClient } from "./runtime-host-client.js";

interface RuntimeHostPricingIpcDeps {
readonly ipcMain: Pick<typeof electronIpcMain, "handle">;
readonly client: Pick<
DesktopRuntimeHostClient,
"loadPricingSnapshot" | "applyPricingMutation"
>;
}

export function registerRuntimeHostPricingIpc(
deps: RuntimeHostPricingIpcDeps,
): void {
deps.ipcMain.handle("settings:pricing:load", () =>
deps.client.loadPricingSnapshot(),
);
deps.ipcMain.handle(
"settings:pricing:mutate",
(_event, input: unknown) =>
deps.client.applyPricingMutation(
decodeDesktopPricingMutationInput(input),
),
);
}

export function decodeDesktopPricingMutationInput(
value: unknown,
): DesktopPricingMutationInput {
const input = requireRecord(value, "pricing mutation input");
const base = decodeDesktopPricingSnapshot(input.base);
const mutation = decodePricingMutateInput({
expectedRevision: base.revision,
mutation: input.mutation,
});
return { base, mutation: mutation.mutation };
}

function decodeDesktopPricingSnapshot(value: unknown): DesktopPricingSnapshot {
const snapshot = requireRecord(value, "pricing snapshot");
const hostEpoch = requireNonEmptyString(snapshot.hostEpoch, "pricing host epoch");
const connectionId = requireNonEmptyString(
snapshot.connectionId,
"pricing connection id",
);
const revision = requireCount(snapshot.revision, "pricing revision");
if (!Array.isArray(snapshot.entries)) {
throw new TypeError("Invalid pricing snapshot entries");
}

const entries: EffectivePricingEntry[] = [];
for (
let offset = 0;
offset < snapshot.entries.length || offset === 0;
offset += PRICING_PAGE_MAX_ITEMS
) {
const pageEntries = snapshot.entries.slice(
offset,
offset + PRICING_PAGE_MAX_ITEMS,
);
const page = decodePricingQueryResult({
kind: "page",
revision,
offset,
entries: pageEntries,
nextOffset:
offset + pageEntries.length < snapshot.entries.length
? offset + pageEntries.length
: null,
});
if (page.kind !== "page") {
throw new TypeError("Invalid pricing snapshot page");
}
entries.push(...page.entries);
if (page.nextOffset === null) break;
}

for (let index = 1; index < entries.length; index += 1) {
if (
comparePricingModelKeys(
entries[index - 1]!.pricing.modelKey,
entries[index]!.pricing.modelKey,
) >= 0
) {
throw new TypeError("Pricing snapshot entries are not canonically ordered");
}
}

return { hostEpoch, connectionId, revision, entries };
}

function requireRecord(value: unknown, label: string): Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new TypeError(`Invalid ${label}`);
}
return value as Record<string, unknown>;
}

function requireNonEmptyString(value: unknown, label: string): string {
if (typeof value !== "string" || value.length === 0) {
throw new TypeError(`Invalid ${label}`);
}
return value;
}

function requireCount(value: unknown, label: string): number {
const count = typeof value === "number" ? value : Number.NaN;
if (!Number.isSafeInteger(count) || count < 0) {
throw new TypeError(`Invalid ${label}`);
}
return count;
}
9 changes: 9 additions & 0 deletions apps/desktop/src/preload/bridge-contract.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ import type {
} from './diagnostics-contract.js';
import type { Result } from '@maka/core/result';
import type { CreateSessionRequestInput } from '@maka/core';
import type {
DesktopPricingMutationInput,
DesktopPricingMutationOutcome,
DesktopPricingSnapshot,
} from '../shared/runtime-host-pricing.js';
import type {
McpConfigFile,
McpServerConfig,
Expand Down Expand Up @@ -484,6 +489,10 @@ export interface MakaBridge {
testNetworkProxy(input?: TestProxyInput): Promise<SettingsTestResult>;
testBotChannel(provider: BotProvider): Promise<SettingsTestResult>;
usageStats(range?: UsageRange): Promise<UsageStats>;
pricing: {
loadSnapshot(): Promise<DesktopPricingSnapshot>;
applyMutation(input: DesktopPricingMutationInput): Promise<DesktopPricingMutationOutcome>;
};
bots: {
listStatuses(): Promise<Record<BotProvider, BotStatus>>;
restart(provider: BotProvider): Promise<BotStatus>;
Expand Down
13 changes: 13 additions & 0 deletions apps/desktop/src/preload/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ import type { ConfigCategory } from '@maka/storage';
import type { TestProxyInput } from '@maka/core/settings/network-settings';
import type { Result } from '@maka/core/result';
import type { CreateSessionRequestInput } from '@maka/core';
import type {
DesktopPricingMutationInput,
DesktopPricingMutationOutcome,
DesktopPricingSnapshot,
} from '../shared/runtime-host-pricing.js';
import type {
McpConfigFile,
McpServerConfig,
Expand Down Expand Up @@ -965,6 +970,14 @@ const makaBridge = {
usageStats(range?: UsageRange): Promise<UsageStats> {
return ipcRenderer.invoke('settings:usageStats', range);
},
pricing: {
loadSnapshot(): Promise<DesktopPricingSnapshot> {
return ipcRenderer.invoke('settings:pricing:load');
},
applyMutation(input: DesktopPricingMutationInput): Promise<DesktopPricingMutationOutcome> {
return ipcRenderer.invoke('settings:pricing:mutate', input);
},
},
bots: {
listStatuses(): Promise<Record<BotProvider, BotStatus>> {
return ipcRenderer.invoke('settings:bots:listStatuses');
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/renderer/app-shell-overlays.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { CommandPalette } from './command-palette';
import { useAppShellCommands, type AppShellCommandListOptions } from './app-shell-command-actions';
import type { UiLocaleUpdateGate } from './settings/ui-locale-update-gate';
import { getShellRemainingCopy } from './locales/shell-remaining-copy.js';
import { desktopPricingSettingsPort } from './settings/runtime-host-pricing-port';
import { ExternalSessionImportDialog } from './external-session-import-dialog.js';

// Settings is a large surface (providers, OAuth, network, bots, daily-review,
Expand Down Expand Up @@ -134,6 +135,7 @@ export function AppShellOverlays(props: {
onOpenDailyReview={props.onOpenDailyReview}
onOpenKeyboardHelp={props.onOpenKeyboardHelp}
onOpenSession={props.onOpenSettingsSession}
pricingPort={desktopPricingSettingsPort}
/>
</Suspense>
)}
Expand Down
Loading
Loading