Use only normal API keys for OpenRouter spend #8

Merged
raucao merged 1 commits from bugfix/openrouter_key into master 2026-11-16 18:30:58 +00:00
13 changed files with 272 additions and 958 deletions

No files matched your search

+19 -8
View File
@@ -20,6 +20,24 @@ export default class OpenRouterUsageComponent extends Component {
return this.format(this.openrouter.usage);
}
// Explains which number the widget shows. Kept in the title attribute so the
// visible "Today"/"This week" words do not alter the dashboard text.
get valueDescription() {
return `OpenRouter spend, ${this.granularityLabel} (UTC)`;
}
get granularityLabel() {
if (this.openrouter.granularity === 'this-week') {
return 'this week';
}
if (this.openrouter.granularity === 'this-month') {
return 'this month';
}
return 'today';
}
format(value) {
if (value == null) {
return '—';
@@ -46,6 +64,7 @@ export default class OpenRouterUsageComponent extends Component {
<button
type="button"
data-test-openrouter-usage
title={{this.valueDescription}}
{{on "click" this.openSettings}}
aria-label="Edit OpenRouter Spend settings"
class="cursor-pointer rounded-lg text-white text-shadow-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white/70"
@@ -78,14 +97,6 @@ export default class OpenRouterUsageComponent extends Component {
{{#if this.openrouter.error}}
<div class="text-xs text-red-300">{{this.openrouter.error}}</div>
{{/if}}
{{#if this.openrouter.truncated}}
<div class="text-xs text-amber-200">Partial data</div>
{{/if}}
{{#if this.openrouter.warnings.length}}
<div class="text-xs text-amber-200">Some filters could not be resolved</div>
{{/if}}
</button>
{{/if}}
</template>
@@ -1,18 +1,16 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import { modifier } from 'ember-modifier';
import SettingsSelect from './select.gjs';
import {
OPENROUTER_API_KEYS_URL,
OPENROUTER_DEFAULT_GRANULARITY,
OPENROUTER_DEFAULT_INTERVAL,
OPENROUTER_GRANULARITY_OPTIONS,
OPENROUTER_INTERVAL_OPTIONS,
OPENROUTER_MANAGEMENT_KEYS_URL,
openrouterKeyLabel,
} from '../../../config/openrouter';
import { isCancellation } from '../../../services/http';
@@ -21,12 +19,10 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
@service pageLifecycle;
@tracked apiKeyDraft = null;
@tracked keyIdsDraft = null;
@tracked intervalDraft = null;
@tracked granularityDraft = null;
@tracked error = null;
@tracked submitting = false;
@tracked keysLoaded = false;
get apiKeyDraftValue() {
return this.apiKeyDraft ?? '';
@@ -49,22 +45,13 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
}
// A blank draft falls back to the stored key so users can change only the
// key selection or interval without re-entering the password.
// interval or granularity without re-entering the password.
get apiKey() {
return (
this.apiKeyDraft ?? this.integration?.apiKey ?? this.openrouter.apiKey
);
}
get keyIds() {
return (
this.keyIdsDraft ??
this.integration?.keyIds ??
this.openrouter.keyIds ??
[]
);
}
get interval() {
return (
this.intervalDraft ??
@@ -83,22 +70,6 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
);
}
get allKeys() {
return this.keyIds.length === 0;
}
get keys() {
return this.openrouter.keys;
}
get keysLoading() {
return this.openrouter.keysLoading;
}
get keysError() {
return this.openrouter.keysError;
}
get intervalOptions() {
return OPENROUTER_INTERVAL_OPTIONS;
}
@@ -107,8 +78,8 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
return OPENROUTER_GRANULARITY_OPTIONS;
}
get managementKeysUrl() {
return OPENROUTER_MANAGEMENT_KEYS_URL;
get apiKeysUrl() {
return OPENROUTER_API_KEYS_URL;
}
resetOnClose = modifier((element) => {
@@ -120,11 +91,9 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
const handleClose = () => {
this.apiKeyDraft = null;
this.keyIdsDraft = null;
this.intervalDraft = null;
this.granularityDraft = null;
this.error = null;
this.keysLoaded = false;
};
dialog.addEventListener('close', handleClose);
@@ -139,74 +108,6 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
this.error = null;
}
@action
async loadKeys() {
this.error = null;
if (!this.apiKey) {
this.error = 'Please enter a management key';
return;
}
try {
await this.openrouter.fetchKeys(this.apiKey);
this.keysLoaded = true;
} catch (err) {
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
this.error = this.openrouter.classifyError(err);
}
}
formatUsage(value) {
if (value == null) {
return '—';
}
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 2,
}).format(value);
}
keyState(key) {
if (key.disabled) {
return 'Disabled';
}
if (key.expires_at && new Date(key.expires_at).getTime() <= Date.now()) {
return 'Expired';
}
return null;
}
@action
toggleAllKeys(event) {
this.keyIdsDraft = event.target.checked
? []
: this.keys.map((key) => key.hash);
}
@action
toggleKey(key) {
const hash = key.hash;
const current = this.keyIds;
const next = current.includes(hash)
? current.filter((id) => id !== hash)
: [...current, hash];
this.keyIdsDraft = next;
}
@action
isSelected(key) {
return this.keyIds.includes(key.hash);
}
@action
updateInterval(value) {
this.intervalDraft = Number(value);
@@ -223,7 +124,7 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
this.error = null;
if (!this.apiKey) {
this.error = 'Please enter a management key';
this.error = 'Please enter an API key';
return;
}
@@ -233,14 +134,12 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
if (this.isEdit) {
await this.openrouter.update(
this.apiKey,
this.keyIds,
this.interval,
this.granularity
);
} else {
await this.openrouter.enable(
this.apiKey,
this.keyIds,
this.interval,
this.granularity
);
@@ -265,10 +164,8 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
class="text-base font-semibold leading-6 text-gray-900"
>{{this.title}}</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
Show your OpenRouter spend on the dashboard. You need a management key
(not an inference key).
</p>
<p class="text-sm text-gray-500" data-test-openrouter-description>Show
your OpenRouter spend on the dashboard.</p>
</div>
<form {{on "submit" this.handleSubmit}} class="mt-5">
@@ -278,7 +175,7 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
for="openrouter-key"
class="block text-sm font-medium leading-6 text-gray-900"
>
Management key
API key
</label>
<div class="mt-2">
<input
@@ -295,76 +192,17 @@ export default class SettingsIntegrationsOpenRouterForm extends Component {
<p class="mt-2 text-sm text-gray-500">
Create one at
<a
href={{this.managementKeysUrl}}
href={{this.apiKeysUrl}}
target="_blank"
rel="noopener noreferrer"
class="font-medium text-indigo-600 hover:text-indigo-500"
>OpenRouter management keys</a>. It is read-only for analytics but
can manage keys.
>OpenRouter API keys</a>.
</p>
<p class="mt-1 text-xs text-gray-500">
Shows this key's usage for the selected window (UTC).
</p>
</div>
<div>
<button
type="button"
data-test-load-keys
{{on "click" this.loadKeys}}
disabled={{this.keysLoading}}
class="inline-flex items-center justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 disabled:opacity-50"
>
{{if this.keysLoading "Loading…" "Load keys"}}
</button>
{{#if this.keysError}}
<p class="mt-2 text-sm text-red-600">{{this.keysError}}</p>
{{/if}}
</div>
{{#if this.keysLoaded}}
{{#if this.keys.length}}
<div>
<label
class="flex items-center gap-2 text-sm font-medium text-gray-900"
>
<input
type="checkbox"
data-test-all-keys
checked={{this.allKeys}}
{{on "change" this.toggleAllKeys}}
/>
All keys
</label>
{{#unless this.allKeys}}
<div class="mt-2 space-y-2">
{{#each this.keys as |key|}}
<label
class="flex items-center gap-2 text-sm text-gray-700"
>
<input
type="checkbox"
data-test-key={{key.hash}}
checked={{this.isSelected key}}
{{on "change" (fn this.toggleKey key)}}
/>
<span>{{openrouterKeyLabel key}}</span>
<span class="text-xs text-gray-500">
{{this.formatUsage key.usage}}
</span>
{{#if (this.keyState key)}}
<span class="text-xs text-amber-600">
{{this.keyState key}}
</span>
{{/if}}
</label>
{{/each}}
</div>
{{/unless}}
</div>
{{else}}
<p class="text-sm text-gray-500">No keys found.</p>
{{/if}}
{{/if}}
<SettingsSelect
@id="openrouter-interval"
@name="interval"
+17 -68
View File
@@ -1,9 +1,6 @@
export const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1';
export const OPENROUTER_KEYS_URL = `${OPENROUTER_API_URL}/keys`;
export const OPENROUTER_ANALYTICS_URL = `${OPENROUTER_API_URL}/analytics/query`;
export const OPENROUTER_MANAGEMENT_KEYS_URL =
'https://openrouter.ai/settings/management-keys';
export const OPENROUTER_ACTIVITY_URL = 'https://openrouter.ai/activity';
export const OPENROUTER_KEY_URL = `${OPENROUTER_API_URL}/key`;
export const OPENROUTER_API_KEYS_URL = 'https://openrouter.ai/settings/keys';
export const OPENROUTER_DEFAULT_INTERVAL = 300000;
export const OPENROUTER_INTERVAL_OPTIONS = [
@@ -19,8 +16,6 @@ export const OPENROUTER_GRANULARITY_OPTIONS = [
{ value: 'this-month', label: 'This month' },
];
export const OPENROUTER_METRIC = 'total_usage';
// The OpenRouter glyph is a single path in a 1024x1024 viewBox. Scaling it to
// the 24x24 viewBox keeps the same shape in the dashboard's small icon.
export const OPENROUTER_ICON_PATH =
@@ -28,19 +23,19 @@ export const OPENROUTER_ICON_PATH =
export const OPENROUTER_ICON_TRANSFORM = 'scale(0.0234375)';
// Maps the dashboard granularity onto the UTC usage buckets returned by
// GET /api/v1/key. OpenRouter only reports UTC-windowed figures, so "today"
// rolls over at 00:00 UTC regardless of the browser's timezone.
const USAGE_FIELD_BY_GRANULARITY = {
today: 'usage_daily',
'this-week': 'usage_weekly',
'this-month': 'usage_monthly',
};
export function openrouterAuthorizationHeader(apiKey) {
return `Bearer ${apiKey}`;
}
export function openrouterKeyLabel(key) {
return key.name || key.label || 'Unnamed key';
}
// Local calendar date key, e.g. "2026-11-13".
export function openrouterLocalDateKey(now = new Date()) {
return now.toLocaleDateString('en-CA');
}
// Falls back to "today" for values the app no longer supports, so a stored
// value written during development cannot render an empty select.
export function openrouterNormalizeGranularity(granularity) {
@@ -51,58 +46,12 @@ export function openrouterNormalizeGranularity(granularity) {
: OPENROUTER_DEFAULT_GRANULARITY;
}
// Returns the query range as UTC ISO strings. The start is widened to the
// previous UTC hour boundary so analytics buckets are never clipped in
// non-whole-hour timezones. Local filtering happens in openrouterUsageTotal,
// which uses windowStart (the local date of the intended range start, before
// widening).
export function openrouterTimeRange(
now = new Date(),
// Reads the usage bucket for the chosen window from a GET /api/v1/key response.
export function openrouterUsageForGranularity(
keyData,
granularity = OPENROUTER_DEFAULT_GRANULARITY
) {
const start = new Date(now);
if (granularity === 'this-week') {
const day = start.getDay();
const diff = day === 0 ? 6 : day - 1;
start.setDate(start.getDate() - diff);
start.setHours(0, 0, 0, 0);
} else if (granularity === 'this-month') {
start.setDate(1);
start.setHours(0, 0, 0, 0);
} else {
// today (and any unsupported value)
start.setHours(0, 0, 0, 0);
}
const windowStart = openrouterLocalDateKey(start);
start.setUTCMinutes(0, 0, 0);
start.setUTCHours(start.getUTCHours() - 1);
return {
start: start.toISOString(),
end: now.toISOString(),
windowStart,
};
}
// Sums total_usage rows whose local date is on or after windowStart. This
// skips the widened pre-window rows (the widened start may include up to one
// hour of the previous local day).
export function openrouterUsageTotal(rows, windowStart) {
return rows.reduce((total, row) => {
const stamp = row.date__hour ?? row.created_at__hour ?? row.date;
if (!stamp) return total;
const localDate = openrouterLocalDateKey(new Date(stamp));
return localDate >= windowStart
? total + Number(row.total_usage ?? 0)
: total;
}, 0);
}
// Removes stored hashes that no longer appear in the current key list.
export function openrouterPruneKeyIds(keys, keyIds) {
const available = new Set(keys.map((key) => key.hash));
return keyIds.filter((id) => available.has(id));
const field =
USAGE_FIELD_BY_GRANULARITY[openrouterNormalizeGranularity(granularity)];
return Number(keyData?.[field] ?? 0);
}
+3 -4
View File
@@ -68,10 +68,9 @@ export default class HttpService extends Service {
try {
// Extension pages with host permissions are treated as same-origin, so
// the target origin's cookies would ride along. Cookie-first APIs (e.g.
// OpenRouter's Clerk-protected analytics endpoint) then try to read our
// Authorization key as a session JWT and reject it. We authenticate with
// headers, never cookies.
// the target origin's cookies would ride along. Cookie-first APIs can
// then try to read our Authorization key as a session JWT and reject it.
// We authenticate with headers, never cookies.
response = await fetch(target, {
credentials: 'omit',
...options,
-1
View File
@@ -211,7 +211,6 @@ const ADAPTERS = {
label: 'OpenRouter Spend',
status: 'active',
apiKey: this.openrouter.apiKey,
keyIds: this.openrouter.keyIds,
interval: this.openrouter.interval,
granularity: this.openrouter.granularity,
},
+32 -109
View File
@@ -2,16 +2,12 @@ import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { isCancellation } from './http';
import {
OPENROUTER_ANALYTICS_URL,
OPENROUTER_DEFAULT_GRANULARITY,
OPENROUTER_DEFAULT_INTERVAL,
OPENROUTER_KEYS_URL,
OPENROUTER_METRIC,
OPENROUTER_KEY_URL,
openrouterAuthorizationHeader,
openrouterNormalizeGranularity,
openrouterPruneKeyIds,
openrouterTimeRange,
openrouterUsageTotal,
openrouterUsageForGranularity,
} from '../config/openrouter';
export default class OpenRouterService extends Service {
@@ -23,18 +19,11 @@ export default class OpenRouterService extends Service {
@tracked enabled = false;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = OPENROUTER_DEFAULT_INTERVAL;
@tracked granularity = OPENROUTER_DEFAULT_GRANULARITY;
@tracked usage = null;
@tracked loading = false;
@tracked error = null;
@tracked keys = [];
@tracked keysLoading = false;
@tracked keysError = null;
@tracked truncated = false;
@tracked warnings = [];
@tracked cachedAt = null;
intervalId = null;
fetching = false;
@@ -62,7 +51,6 @@ export default class OpenRouterService extends Service {
if (integration?.status === 'active') {
this.enabled = true;
this.apiKey = integration.apiKey ?? null;
this.keyIds = integration.keyIds ?? [];
this.interval = integration.interval ?? OPENROUTER_DEFAULT_INTERVAL;
this.granularity = openrouterNormalizeGranularity(
integration.granularity
@@ -76,57 +64,45 @@ export default class OpenRouterService extends Service {
async enable(
apiKey,
keyIds = [],
interval = OPENROUTER_DEFAULT_INTERVAL,
granularity = OPENROUTER_DEFAULT_GRANULARITY
) {
await this.ready;
const keys = await this.fetchKeys(apiKey);
const pruned = openrouterPruneKeyIds(keys, keyIds);
this.apiKey = apiKey;
this.keyIds = pruned;
this.interval = interval;
this.granularity = granularity;
this.enabled = true;
await this.persist({ apiKey, keyIds: pruned, interval, granularity });
this.startPolling();
await this.save(apiKey, interval, granularity);
}
async update(
apiKey = this.apiKey,
keyIds = this.keyIds,
interval = this.interval,
granularity = this.granularity
) {
await this.ready;
await this.save(apiKey, interval, granularity);
}
const keys = await this.fetchKeys(apiKey);
const pruned = openrouterPruneKeyIds(keys, keyIds);
// Validates the key before persisting so a typo shows up in the settings
// dialog instead of surfacing later on the dashboard.
async save(apiKey, interval, granularity) {
await this.fetchKeyInfo(apiKey);
this.apiKey = apiKey;
this.keyIds = pruned;
this.interval = interval;
this.granularity = granularity;
this.enabled = true;
await this.persist({ apiKey, keyIds: pruned, interval, granularity });
await this.persist({ apiKey, interval, granularity });
this.startPolling();
}
async persist({ apiKey, keyIds, interval, granularity }) {
async persist({ apiKey, interval, granularity }) {
const existing = await this.storage.get('integrations', 'openrouter');
// Build the record fresh. Older versions also stored keyType/keyIds for the
// removed management-key flow, and spreading `existing` would keep them.
await this.storage.set('integrations', 'openrouter', {
...existing,
type: 'openrouter',
status: 'active',
apiKey,
keyIds,
interval,
granularity,
createdAt: existing?.createdAt ?? Date.now(),
@@ -139,45 +115,22 @@ export default class OpenRouterService extends Service {
this.stopPolling();
this.enabled = false;
this.apiKey = null;
this.keyIds = [];
this.interval = OPENROUTER_DEFAULT_INTERVAL;
this.granularity = OPENROUTER_DEFAULT_GRANULARITY;
this.usage = null;
this.error = null;
this.keys = [];
this.keysError = null;
this.truncated = false;
this.warnings = [];
this.cachedAt = null;
await this.storage.remove('integrations', 'openrouter');
}
// Lists the account's keys (including disabled ones) so the form can pick a
// subset and validate the management key before saving. Returns the keys so
// callers can validate a draft key without persisting it.
async fetchKeys(apiKey) {
this.keysLoading = true;
this.keysError = null;
// Reads this key's own usage from GET /api/v1/key. It is the only OpenRouter
// usage endpoint that works with a normal API key from the browser.
async fetchKeyInfo(apiKey) {
const response = await this.http.requestJson(OPENROUTER_KEY_URL, {
headers: { Authorization: openrouterAuthorizationHeader(apiKey) },
});
try {
const response = await this.http.requestJson(
`${OPENROUTER_KEYS_URL}?include_disabled=true&include_expired=true`,
{ headers: { Authorization: openrouterAuthorizationHeader(apiKey) } }
);
const keys = response?.data ?? [];
this.keys = keys;
return keys;
} catch (err) {
if (isCancellation(err) || this.pageLifecycle.leaving) {
throw err;
}
this.keysError = this.classifyError(err);
throw err;
} finally {
this.keysLoading = false;
}
return response?.data ?? {};
}
async fetchUsage() {
@@ -189,43 +142,8 @@ export default class OpenRouterService extends Service {
this.loading = true;
try {
const now = new Date();
const { start, end, windowStart } = openrouterTimeRange(
now,
this.granularity
);
const body = {
metrics: [OPENROUTER_METRIC],
dimensions: [],
granularity: 'hour',
time_range: { start, end },
limit: 1000,
};
if (this.keyIds.length) {
body.filters = [
{ field: 'api_key_id', operator: 'in', value: this.keyIds },
];
}
const response = await this.http.requestJson(OPENROUTER_ANALYTICS_URL, {
method: 'POST',
headers: {
Authorization: openrouterAuthorizationHeader(this.apiKey),
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const rows = response?.data?.data ?? [];
const metadata = response?.data?.metadata ?? {};
const warnings = response?.data?.warnings ?? [];
this.usage = openrouterUsageTotal(rows, windowStart);
this.truncated = Boolean(metadata.truncated);
this.warnings = warnings;
this.cachedAt = response?.data?.cachedAt ?? null;
const keyData = await this.fetchKeyInfo(this.apiKey);
this.usage = openrouterUsageForGranularity(keyData, this.granularity);
this.error = null;
} catch (err) {
// A navigation or bfcache freeze cancels the request; keep the last
@@ -247,17 +165,22 @@ export default class OpenRouterService extends Service {
return 'Unable to reach OpenRouter';
}
// Prefer the API's own message (e.g. "Only management keys can perform
// this operation") so auth and permission failures stay diagnosable,
// falling back to a status-based summary.
// Prefer the API's own message so auth and permission failures stay
// diagnosable, falling back to a status-based summary.
const apiMessage = err?.body?.error?.message;
// OpenRouter refuses management keys that look browser-originated. A stored
// management key hits this guard; point the user at a normal API key.
if (apiMessage && /cannot be used from a browser/i.test(apiMessage)) {
return 'OpenRouter does not allow management keys from the browser. Use a normal API key instead.';
}
if (err?.status === 401) {
return apiMessage ?? 'Invalid or expired management key';
return apiMessage ?? 'Invalid or expired API key';
}
if (err?.status === 403) {
return apiMessage ?? 'Management key required';
return apiMessage ?? 'Access denied by OpenRouter';
}
if (err?.status === 408) {
@@ -10,8 +10,6 @@ class FakeOpenRouterService {
@tracked granularity = 'today';
@tracked loading = false;
@tracked error = null;
@tracked truncated = false;
@tracked warnings = [];
}
class FakeModalService {
@@ -70,6 +68,26 @@ module('Integration | Component | openrouter-usage', function (hooks) {
assert.dom().doesNotContainText('Yesterday');
});
test('it describes the selected window', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
openrouter.usage = 1.5;
openrouter.granularity = 'this-week';
await render(<template><OpenRouterUsage /></template>);
assert
.dom('[data-test-openrouter-usage]')
.hasAttribute('title', 'OpenRouter spend, this week (UTC)');
assert
.dom('[data-test-openrouter-usage]')
.hasAttribute('aria-label', 'Edit OpenRouter Spend settings');
});
test('it renders the icon', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
@@ -118,40 +136,10 @@ module('Integration | Component | openrouter-usage', function (hooks) {
});
openrouter.enabled = true;
openrouter.error = 'Management key required';
openrouter.error = 'Invalid or expired API key';
await render(<template><OpenRouterUsage /></template>);
assert.dom().containsText('Management key required');
});
test('it shows a partial note when truncated', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
openrouter.usage = 1.5;
openrouter.truncated = true;
await render(<template><OpenRouterUsage /></template>);
assert.dom().containsText('Partial data');
});
test('it shows a warning when filters could not be resolved', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
openrouter.usage = 1.5;
openrouter.warnings = ['Unresolved api_key_id'];
await render(<template><OpenRouterUsage /></template>);
assert.dom().containsText('Some filters could not be resolved');
assert.dom().containsText('Invalid or expired API key');
});
});
@@ -38,7 +38,6 @@ class FakeBitcoinService {
class FakeOpenRouterService {
@tracked enabled = false;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = 300000;
@tracked granularity = 'today';
disabled = false;
@@ -23,7 +23,6 @@ class FakeBitcoinService {
class FakeOpenRouterService {
@tracked enabled = false;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = 300000;
@tracked granularity = 'today';
@@ -1,6 +1,6 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, triggerEvent, click } from '@ember/test-helpers';
import { render, fillIn, triggerEvent } from '@ember/test-helpers';
import { tracked } from '@glimmer/tracking';
import OpenRouterForm from 'dashtab/components/settings/integrations/openrouter-form';
@@ -12,27 +12,18 @@ function changeSelect(selector, value) {
}
class FakeOpenRouterService {
@tracked keys = [];
@tracked keysLoading = false;
@tracked keysError = null;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = 300000;
@tracked granularity = 'today';
calls = [];
async fetchKeys(apiKey) {
this.calls.push({ type: 'fetchKeys', apiKey });
return this.keys;
async enable(apiKey, interval, granularity) {
this.calls.push({ type: 'enable', apiKey, interval, granularity });
}
async enable(apiKey, keyIds, interval, granularity) {
this.calls.push({ type: 'enable', apiKey, keyIds, interval, granularity });
}
async update(apiKey, keyIds, interval, granularity) {
this.calls.push({ type: 'update', apiKey, keyIds, interval, granularity });
async update(apiKey, interval, granularity) {
this.calls.push({ type: 'update', apiKey, interval, granularity });
}
classifyError(err) {
@@ -45,7 +36,7 @@ module(
function (hooks) {
setupRenderingTest(hooks);
test('it renders the management key field', async function (assert) {
test('it renders the API key fields and a fixed description', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
@@ -55,10 +46,15 @@ module(
await render(<template><OpenRouterForm @close={{noop}} /></template>);
assert.dom().containsText('Add OpenRouter Spend');
assert
.dom('[data-test-openrouter-description]')
.hasText('Show your OpenRouter spend on the dashboard.');
assert.dom('#openrouter-key-type').doesNotExist();
assert.dom('#openrouter-key').exists();
assert.dom('#openrouter-interval').exists();
assert.dom('#openrouter-granularity').exists();
assert.dom().containsText('OpenRouter management keys');
assert.dom('[data-test-load-keys]').doesNotExist();
assert.dom().containsText('OpenRouter API keys');
});
test('offers the three supported granularity options', async function (assert) {
@@ -78,90 +74,6 @@ module(
assert.deepEqual(labels, ['Today', 'This week', 'This month']);
});
test('loads keys and shows them', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.keys = [{ hash: 'abc', name: 'Key A' }];
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await fillIn('#openrouter-key', 'sk-or-v1-test');
await click('[data-test-load-keys]');
await click('[data-test-all-keys]');
assert.dom().containsText('Key A');
assert.deepEqual(openrouter.calls, [
{ type: 'fetchKeys', apiKey: 'sk-or-v1-test' },
]);
});
test('shows disabled and expired keys and formats their usage', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.keys = [
{ hash: 'abc', name: 'Key A', usage: 1.5, disabled: true },
{
hash: 'def',
name: 'Key B',
usage: 2.25,
expires_at: '2020-01-01T00:00:00Z',
},
];
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await fillIn('#openrouter-key', 'sk-or-v1-test');
await click('[data-test-load-keys]');
await click('[data-test-all-keys]');
assert.dom().containsText('Key A');
assert.dom().containsText('$1.50');
assert.dom().containsText('Disabled');
assert.dom().containsText('Key B');
assert.dom().containsText('$2.25');
assert.dom().containsText('Expired');
});
test('shows no keys found when the account has no keys', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.keys = [];
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await fillIn('#openrouter-key', 'sk-or-v1-test');
await click('[data-test-load-keys]');
assert.dom().containsText('No keys found.');
});
test('shows an error when loading keys fails', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.fetchKeys = async () => {
throw new Error('Invalid key');
};
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await fillIn('#openrouter-key', 'bad');
await click('[data-test-load-keys]');
assert.dom().containsText('Invalid key');
});
test('submits the default settings in add mode', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
@@ -178,7 +90,6 @@ module(
{
type: 'enable',
apiKey: 'sk-or-v1-test',
keyIds: [],
interval: 300000,
granularity: 'today',
},
@@ -187,7 +98,6 @@ module(
test('edit mode prefills the stored settings and saves with update', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.keys = [{ hash: 'abc' }];
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
@@ -196,9 +106,8 @@ module(
mode: 'edit',
integration: {
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
granularity: 'this-week',
},
};
@@ -215,7 +124,7 @@ module(
assert.dom().containsText('Edit OpenRouter Spend');
assert.dom('#openrouter-interval').containsText('Every 10 minutes');
assert.dom('#openrouter-granularity').containsText('Today');
assert.dom('#openrouter-granularity').containsText('This week');
await triggerEvent('form', 'submit');
@@ -223,9 +132,8 @@ module(
{
type: 'update',
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
granularity: 'this-week',
},
]);
assert.true(closed);
@@ -233,7 +141,6 @@ module(
test('a blank key in edit mode keeps the stored key', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.keys = [{ hash: 'abc' }];
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
@@ -242,7 +149,6 @@ module(
mode: 'edit',
integration: {
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
},
@@ -262,7 +168,6 @@ module(
{
type: 'update',
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
},
@@ -280,47 +185,10 @@ module(
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a management key');
assert.dom().containsText('Please enter an API key');
assert.deepEqual(openrouter.calls, []);
});
test('toggles a key and the all-keys checkbox', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.keys = [
{ hash: 'abc', name: 'Key A' },
{ hash: 'def', name: 'Key B' },
];
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await fillIn('#openrouter-key', 'sk-or-v1-test');
await click('[data-test-load-keys]');
await click('[data-test-all-keys]');
assert.dom('[data-test-key="abc"]').isChecked();
assert.dom('[data-test-key="def"]').isChecked();
await click('[data-test-key="abc"]');
assert.dom('[data-test-key="abc"]').isNotChecked();
await triggerEvent('form', 'submit');
assert.deepEqual(openrouter.calls, [
{ type: 'fetchKeys', apiKey: 'sk-or-v1-test' },
{
type: 'enable',
apiKey: 'sk-or-v1-test',
keyIds: ['def'],
interval: 300000,
granularity: 'today',
},
]);
});
test('uses the selected interval and granularity', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
@@ -332,16 +200,15 @@ module(
await fillIn('#openrouter-key', 'sk-or-v1-test');
changeSelect('#openrouter-interval', '600000');
changeSelect('#openrouter-granularity', 'today');
changeSelect('#openrouter-granularity', 'this-month');
await triggerEvent('form', 'submit');
assert.deepEqual(openrouter.calls, [
{
type: 'enable',
apiKey: 'sk-or-v1-test',
keyIds: [],
interval: 600000,
granularity: 'today',
granularity: 'this-month',
},
]);
});
+18 -97
View File
@@ -1,57 +1,10 @@
import { module, test } from 'qunit';
import {
openrouterKeyLabel,
openrouterLocalDateKey,
openrouterNormalizeGranularity,
openrouterPruneKeyIds,
openrouterTimeRange,
openrouterUsageTotal,
openrouterUsageForGranularity,
} from 'dashtab/config/openrouter';
module('Unit | Config | openrouter', function () {
test('openrouterTimeRange returns the right window for each granularity', function (assert) {
const now = new Date('2026-11-13T12:00:00Z');
const today = openrouterTimeRange(now, 'today');
assert.strictEqual(today.windowStart, openrouterLocalDateKey(now));
assert.strictEqual(today.end, now.toISOString());
const thisWeek = openrouterTimeRange(now, 'this-week');
const weekStart = new Date(now);
const day = weekStart.getDay();
const diff = day === 0 ? 6 : day - 1;
weekStart.setDate(weekStart.getDate() - diff);
assert.strictEqual(thisWeek.windowStart, openrouterLocalDateKey(weekStart));
const thisMonth = openrouterTimeRange(now, 'this-month');
const monthStart = new Date(now);
monthStart.setDate(1);
assert.strictEqual(
thisMonth.windowStart,
openrouterLocalDateKey(monthStart)
);
});
test('openrouterTimeRange falls back to today for unknown values', function (assert) {
const now = new Date('2026-11-13T12:00:00Z');
const unknown = openrouterTimeRange(now, 'today-yesterday');
const today = openrouterTimeRange(now, 'today');
assert.strictEqual(unknown.windowStart, today.windowStart);
assert.strictEqual(unknown.start, today.start);
});
test('openrouterTimeRange widens the start to the previous UTC hour', function (assert) {
const now = new Date('2026-11-13T12:00:00Z');
const { start } = openrouterTimeRange(now, 'today');
const startDate = new Date(start);
assert.strictEqual(startDate.getUTCMinutes(), 0);
assert.strictEqual(startDate.getUTCSeconds(), 0);
assert.strictEqual(startDate.getUTCMilliseconds(), 0);
});
test('openrouterNormalizeGranularity falls back to today', function (assert) {
assert.strictEqual(openrouterNormalizeGranularity('today'), 'today');
assert.strictEqual(
@@ -69,57 +22,25 @@ module('Unit | Config | openrouter', function () {
assert.strictEqual(openrouterNormalizeGranularity(undefined), 'today');
});
test('openrouterUsageTotal excludes rows before the window', function (assert) {
const now = new Date('2026-11-13T12:00:00Z');
const windowStart = openrouterLocalDateKey(now);
test('openrouterUsageForGranularity reads the matching UTC bucket', function (assert) {
const keyData = {
usage: 9,
usage_daily: 1,
usage_weekly: 2,
usage_monthly: 3,
};
const rows = [
{
date__hour: new Date(
now.getFullYear(),
now.getMonth(),
13,
0,
0,
0
).toISOString(),
total_usage: 0.5,
},
{
date__hour: new Date(
now.getFullYear(),
now.getMonth(),
13,
1,
0,
0
).toISOString(),
total_usage: 0.25,
},
{
date__hour: new Date(
now.getFullYear(),
now.getMonth(),
12,
23,
0,
0
).toISOString(),
total_usage: 0.75,
},
];
assert.strictEqual(openrouterUsageTotal(rows, windowStart), 0.75);
assert.strictEqual(openrouterUsageForGranularity(keyData, 'today'), 1);
assert.strictEqual(openrouterUsageForGranularity(keyData, 'this-week'), 2);
assert.strictEqual(openrouterUsageForGranularity(keyData, 'this-month'), 3);
});
test('openrouterKeyLabel falls back to label or Unnamed key', function (assert) {
assert.strictEqual(openrouterKeyLabel({ name: 'A' }), 'A');
assert.strictEqual(openrouterKeyLabel({ label: 'B' }), 'B');
assert.strictEqual(openrouterKeyLabel({}), 'Unnamed key');
});
test('openrouterPruneKeyIds removes stale hashes', function (assert) {
const keys = [{ hash: 'a' }, { hash: 'b' }];
assert.deepEqual(openrouterPruneKeyIds(keys, ['a', 'c']), ['a']);
test('openrouterUsageForGranularity tolerates missing data', function (assert) {
assert.strictEqual(openrouterUsageForGranularity(null, 'today'), 0);
assert.strictEqual(openrouterUsageForGranularity({}, 'today'), 0);
assert.strictEqual(
openrouterUsageForGranularity({ usage_daily: 0.25 }, 'unknown'),
0.25
);
});
});
-3
View File
@@ -40,7 +40,6 @@ class FakeBitcoinService {
class FakeOpenRouterService {
@tracked enabled = false;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = 300000;
@tracked granularity = 'today';
disabled = false;
@@ -241,7 +240,6 @@ module('Unit | Service | integrations', function (hooks) {
const openrouter = new FakeOpenRouterService();
openrouter.enabled = true;
openrouter.apiKey = 'sk-or-v1-test';
openrouter.keyIds = ['abc'];
openrouter.interval = 600000;
openrouter.granularity = 'today';
@@ -255,7 +253,6 @@ module('Unit | Service | integrations', function (hooks) {
assert.true(openrouterEntry.hasSettings);
assert.strictEqual(openrouterEntry.instances.length, 1);
assert.strictEqual(openrouterEntry.instances[0].apiKey, 'sk-or-v1-test');
assert.deepEqual(openrouterEntry.instances[0].keyIds, ['abc']);
assert.strictEqual(openrouterEntry.instances[0].interval, 600000);
assert.strictEqual(openrouterEntry.instances[0].granularity, 'today');
+130 -306
View File
@@ -1,9 +1,6 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import {
OPENROUTER_ANALYTICS_URL,
OPENROUTER_KEYS_URL,
} from 'dashtab/config/openrouter';
import { OPENROUTER_KEY_URL } from 'dashtab/config/openrouter';
module('Unit | Service | openrouter', function (hooks) {
setupTest(hooks);
@@ -32,13 +29,15 @@ module('Unit | Service | openrouter', function (hooks) {
test('load enables a stored active integration', async function (assert) {
const storage = this.owner.lookup('service:storage');
// A record written by the old management-key flow must still load.
await storage.set('integrations', 'openrouter', {
type: 'openrouter',
status: 'active',
apiKey: 'sk-or-v1-test',
keyType: 'management',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
granularity: 'this-week',
});
const service = this.owner.lookup('service:openrouter');
@@ -47,9 +46,8 @@ module('Unit | Service | openrouter', function (hooks) {
assert.true(service.enabled);
assert.strictEqual(service.apiKey, 'sk-or-v1-test');
assert.deepEqual(service.keyIds, ['abc']);
assert.strictEqual(service.interval, 600000);
assert.strictEqual(service.granularity, 'today');
assert.strictEqual(service.granularity, 'this-week');
assert.ok(service.intervalId);
service.stopPolling();
@@ -71,34 +69,37 @@ module('Unit | Service | openrouter', function (hooks) {
test('enable validates the key and persists the integration', async function (assert) {
let requestedUrl;
globalThis.fetch = async (url) => {
let requestedHeaders;
globalThis.fetch = async (url, options) => {
requestedUrl = url;
requestedHeaders = options.headers;
return {
ok: true,
json: async () => ({ data: [{ hash: 'abc' }, { hash: 'def' }] }),
json: async () => ({ data: { usage_daily: 1.25 } }),
};
};
const service = this.owner.lookup('service:openrouter');
service.fetchUsage = async () => {};
await service.enable('sk-or-v1-test', ['abc', 'stale'], 600000, 'today');
await service.enable('sk-or-v1-test', 600000, 'this-month');
assert.strictEqual(
requestedUrl,
`${OPENROUTER_KEYS_URL}?include_disabled=true&include_expired=true`
);
assert.strictEqual(requestedUrl, OPENROUTER_KEY_URL);
assert.strictEqual(requestedHeaders.Authorization, 'Bearer sk-or-v1-test');
assert.true(service.enabled);
assert.strictEqual(service.apiKey, 'sk-or-v1-test');
assert.deepEqual(service.keyIds, ['abc']);
assert.strictEqual(service.interval, 600000);
assert.strictEqual(service.granularity, 'today');
assert.strictEqual(service.granularity, 'this-month');
const storage = this.owner.lookup('service:storage');
const integration = await storage.get('integrations', 'openrouter');
assert.strictEqual(integration.status, 'active');
assert.strictEqual(integration.type, 'openrouter');
assert.deepEqual(integration.keyIds, ['abc']);
assert.strictEqual(integration.apiKey, 'sk-or-v1-test');
assert.strictEqual(integration.interval, 600000);
assert.strictEqual(integration.granularity, 'this-month');
assert.false('keyType' in integration);
assert.false('keyIds' in integration);
service.stopPolling();
});
@@ -113,7 +114,7 @@ module('Unit | Service | openrouter', function (hooks) {
const service = this.owner.lookup('service:openrouter');
await service.ready;
await assert.rejects(service.enable('bad', [], 600000, 'today'), (err) => {
await assert.rejects(service.enable('bad', 600000, 'today'), (err) => {
assert.strictEqual(err.status, 401);
return true;
});
@@ -121,54 +122,18 @@ module('Unit | Service | openrouter', function (hooks) {
assert.false(service.enabled);
});
test('fetchUsage posts the query and aggregates the response', async function (assert) {
let requestedUrl;
let requestedOptions;
test('fetchUsage reads the usage bucket for the granularity', async function (assert) {
const requested = [];
globalThis.fetch = async (url, options) => {
requestedUrl = url;
requestedOptions = options;
requested.push({ url, options });
return {
ok: true,
json: async () => ({
data: {
data: [
{
date__hour: new Date(
new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate(),
0,
0,
0
).toISOString(),
total_usage: 0.5,
},
{
date__hour: new Date(
new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate(),
1,
0,
0
).toISOString(),
total_usage: 0.75,
},
{
date__hour: new Date(
new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate() - 1,
23,
0,
0
).toISOString(),
total_usage: 0.1,
},
],
metadata: { truncated: false, query_time_ms: 1, row_count: 3 },
warnings: [],
cachedAt: 123,
usage: 9,
usage_daily: 1,
usage_weekly: 2,
usage_monthly: 3,
},
}),
};
@@ -176,59 +141,39 @@ module('Unit | Service | openrouter', function (hooks) {
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.keyIds = ['abc'];
service.granularity = 'today';
service.enabled = true;
service.granularity = 'today';
await service.fetchUsage();
assert.strictEqual(service.usage, 1);
assert.strictEqual(requestedUrl, OPENROUTER_ANALYTICS_URL);
assert.strictEqual(requestedOptions.method, 'POST');
service.granularity = 'this-week';
await service.fetchUsage();
assert.strictEqual(service.usage, 2);
service.granularity = 'this-month';
await service.fetchUsage();
assert.strictEqual(service.usage, 3);
assert.strictEqual(requested.length, 3);
assert.strictEqual(requested[0].url, OPENROUTER_KEY_URL);
assert.strictEqual(
requestedOptions.headers.Authorization,
requested[0].options.headers.Authorization,
'Bearer sk-or-v1-test'
);
const body = JSON.parse(requestedOptions.body);
assert.deepEqual(body.metrics, ['total_usage']);
assert.deepEqual(body.dimensions, []);
assert.strictEqual(body.granularity, 'hour');
assert.deepEqual(body.filters, [
{ field: 'api_key_id', operator: 'in', value: ['abc'] },
]);
assert.strictEqual(service.usage, 1.25);
assert.false(service.truncated);
assert.strictEqual(service.cachedAt, 123);
assert.strictEqual(service.error, null);
});
test('fetchUsage omits filters when all keys are selected', async function (assert) {
let requestedOptions;
globalThis.fetch = async (url, options) => {
requestedOptions = options;
return {
ok: true,
json: async () => ({ data: { data: [], metadata: {} } }),
};
};
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.keyIds = [];
service.enabled = true;
await service.fetchUsage();
const body = JSON.parse(requestedOptions.body);
assert.notOk('filters' in body);
});
test('fetchUsage maps a 403 to a management key message', async function (assert) {
test('fetchUsage surfaces the browser management key error', async function (assert) {
globalThis.fetch = async () => ({
ok: false,
status: 403,
json: async () => ({ error: { code: 403 } }),
json: async () => ({
error: {
message:
'Management keys cannot be used from a browser. Call the management API from your server and keep the key out of client-side code.',
},
}),
});
const service = this.owner.lookup('service:openrouter');
@@ -237,7 +182,10 @@ module('Unit | Service | openrouter', function (hooks) {
await service.fetchUsage();
assert.strictEqual(service.error, 'Management key required');
assert.strictEqual(
service.error,
'OpenRouter does not allow management keys from the browser. Use a normal API key instead.'
);
});
test('fetchUsage surfaces the API error message on failure', async function (assert) {
@@ -264,166 +212,33 @@ module('Unit | Service | openrouter', function (hooks) {
);
});
test('fetchKeys returns the keys and reads the response data', async function (assert) {
globalThis.fetch = async () => ({
ok: true,
json: async () => ({ data: [{ hash: 'abc' }] }),
});
test('classifyError falls back to status-based messages', async function (assert) {
const service = this.owner.lookup('service:openrouter');
await service.ready;
const keys = await service.fetchKeys('sk-or-v1-test');
assert.deepEqual(keys, [{ hash: 'abc' }]);
assert.deepEqual(service.keys, [{ hash: 'abc' }]);
assert.strictEqual(service.keysError, null);
});
test('fetchKeys sets a 401 error', async function (assert) {
globalThis.fetch = async () => ({
ok: false,
status: 401,
json: async () => ({ error: { code: 401 } }),
});
const service = this.owner.lookup('service:openrouter');
await service.ready;
await assert.rejects(service.fetchKeys('bad'), (err) => {
assert.strictEqual(err.status, 401);
return true;
});
assert.strictEqual(service.keysError, 'Invalid or expired management key');
});
test('disable clears storage and resets state', async function (assert) {
const service = this.owner.lookup('service:openrouter');
service.fetchUsage = async () => {};
service.fetchKeys = async () => [{ hash: 'abc' }];
await service.enable('sk-or-v1-test', ['abc'], 600000, 'today');
service.usage = 1.5;
service.error = 'nope';
await service.disable();
const storage = this.owner.lookup('service:storage');
const integration = await storage.get('integrations', 'openrouter');
assert.strictEqual(integration, null);
assert.false(service.enabled);
assert.strictEqual(service.intervalId, null);
assert.strictEqual(service.apiKey, null);
assert.deepEqual(service.keyIds, []);
assert.strictEqual(service.interval, 300000);
assert.strictEqual(service.granularity, 'today');
assert.strictEqual(service.usage, null);
assert.strictEqual(service.error, null);
});
test('update validates the key and keeps the existing createdAt', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'openrouter', {
type: 'openrouter',
status: 'active',
apiKey: 'sk-or-v1-old',
keyIds: ['old'],
interval: 300000,
granularity: 'today',
createdAt: 12345,
});
globalThis.fetch = async () => ({
ok: true,
json: async () => ({ data: [{ hash: 'abc' }] }),
});
const service = this.owner.lookup('service:openrouter');
service.fetchUsage = async () => {};
await service.ready;
await service.update('sk-or-v1-new', ['abc', 'stale'], 600000, 'today');
const integration = await storage.get('integrations', 'openrouter');
assert.strictEqual(integration.apiKey, 'sk-or-v1-new');
assert.deepEqual(integration.keyIds, ['abc']);
assert.strictEqual(integration.interval, 600000);
assert.strictEqual(integration.granularity, 'today');
assert.strictEqual(integration.createdAt, 12345);
service.stopPolling();
});
test('fetchKeys maps a 403 to a management key error', async function (assert) {
globalThis.fetch = async () => ({
ok: false,
status: 403,
json: async () => ({ error: { code: 403 } }),
});
const service = this.owner.lookup('service:openrouter');
await service.ready;
await assert.rejects(service.fetchKeys('bad'), (err) => {
assert.strictEqual(err.status, 403);
return true;
});
assert.strictEqual(service.keysError, 'Management key required');
});
test('fetchKeys maps a 408 to a timeout error', async function (assert) {
globalThis.fetch = async () => ({
ok: false,
status: 408,
json: async () => ({ error: { code: 408 } }),
});
const service = this.owner.lookup('service:openrouter');
await service.ready;
await assert.rejects(service.fetchKeys('bad'), (err) => {
assert.strictEqual(err.status, 408);
return true;
});
assert.strictEqual(service.keysError, 'OpenRouter timed out');
});
test('fetchKeys maps a 429 to a rate limit error', async function (assert) {
globalThis.fetch = async () => ({
ok: false,
status: 429,
json: async () => ({ error: { code: 429 } }),
});
const service = this.owner.lookup('service:openrouter');
await service.ready;
await assert.rejects(service.fetchKeys('bad'), (err) => {
assert.strictEqual(err.status, 429);
return true;
});
assert.strictEqual(service.keysError, 'Rate limited by OpenRouter');
});
test('fetchKeys maps a network failure to a reachability error', async function (assert) {
globalThis.fetch = async () => {
throw new TypeError('offline');
};
const service = this.owner.lookup('service:openrouter');
await service.ready;
await assert.rejects(service.fetchKeys('bad'), (err) => {
assert.strictEqual(err.name, 'NetworkError');
return true;
});
assert.strictEqual(service.keysError, 'Unable to reach OpenRouter');
assert.strictEqual(
service.classifyError({ status: 401 }),
'Invalid or expired API key'
);
assert.strictEqual(
service.classifyError({ status: 403 }),
'Access denied by OpenRouter'
);
assert.strictEqual(
service.classifyError({ status: 408 }),
'OpenRouter timed out'
);
assert.strictEqual(
service.classifyError({ status: 429 }),
'Rate limited by OpenRouter'
);
assert.strictEqual(
service.classifyError({ status: 500 }),
'OpenRouter returned an error'
);
assert.strictEqual(
service.classifyError({ name: 'NetworkError' }),
'Unable to reach OpenRouter'
);
});
test('fetchUsage ignores cancellation and page leaving', async function (assert) {
@@ -453,7 +268,7 @@ module('Unit | Service | openrouter', function (hooks) {
let calls = 0;
globalThis.fetch = async () => {
calls += 1;
return { ok: true, json: async () => ({ data: { data: [] } }) };
return { ok: true, json: async () => ({ data: {} }) };
};
const service = this.owner.lookup('service:openrouter');
@@ -467,57 +282,66 @@ module('Unit | Service | openrouter', function (hooks) {
service.fetching = false;
});
test('fetchUsage uses the configured granularity', async function (assert) {
let requestedOptions;
globalThis.fetch = async (url, options) => {
requestedOptions = options;
return {
ok: true,
json: async () => ({ data: { data: [], metadata: {} } }),
};
};
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.enabled = true;
service.granularity = 'today';
await service.fetchUsage();
const todayStart = new Date(
JSON.parse(requestedOptions.body).time_range.start
);
service.granularity = 'this-month';
await service.fetchUsage();
const monthStart = new Date(
JSON.parse(requestedOptions.body).time_range.start
);
assert.ok(monthStart.getTime() < todayStart.getTime());
assert.ok(monthStart.getTime() <= Date.now());
});
test('fetchUsage stores warnings and truncated metadata', async function (assert) {
test('disable clears storage and resets state', async function (assert) {
globalThis.fetch = async () => ({
ok: true,
json: async () => ({
data: {
data: [],
metadata: { truncated: true, query_time_ms: 1, row_count: 0 },
warnings: ['Unresolved api_key_id'],
cachedAt: 456,
},
}),
json: async () => ({ data: { usage_daily: 1 } }),
});
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.enabled = true;
service.fetchUsage = async () => {};
await service.fetchUsage();
await service.enable('sk-or-v1-test', 600000, 'this-month');
service.usage = 1.5;
service.error = 'nope';
assert.true(service.truncated);
assert.deepEqual(service.warnings, ['Unresolved api_key_id']);
assert.strictEqual(service.cachedAt, 456);
await service.disable();
const storage = this.owner.lookup('service:storage');
const integration = await storage.get('integrations', 'openrouter');
assert.strictEqual(integration, null);
assert.false(service.enabled);
assert.strictEqual(service.intervalId, null);
assert.strictEqual(service.apiKey, null);
assert.strictEqual(service.interval, 300000);
assert.strictEqual(service.granularity, 'today');
assert.strictEqual(service.usage, null);
assert.strictEqual(service.error, null);
});
test('update validates the key, keeps createdAt, and drops old fields', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'openrouter', {
type: 'openrouter',
status: 'active',
apiKey: 'sk-or-v1-old',
keyType: 'management',
keyIds: ['old'],
interval: 300000,
granularity: 'today',
createdAt: 12345,
});
globalThis.fetch = async () => ({
ok: true,
json: async () => ({ data: { usage_weekly: 2 } }),
});
const service = this.owner.lookup('service:openrouter');
service.fetchUsage = async () => {};
await service.ready;
await service.update('sk-or-v1-new', 600000, 'this-week');
const integration = await storage.get('integrations', 'openrouter');
assert.strictEqual(integration.apiKey, 'sk-or-v1-new');
assert.strictEqual(integration.interval, 600000);
assert.strictEqual(integration.granularity, 'this-week');
assert.strictEqual(integration.createdAt, 12345);
assert.false('keyType' in integration);
assert.false('keyIds' in integration);
service.stopPolling();
});
});