Add OpenRouter spend stats and unify ticker settings #4

Merged
raucao merged 4 commits from feature/openrouter-stats into master 2026-11-13 11:54:09 +00:00
26 changed files with 2493 additions and 179 deletions

No files matched your search

+20
View File
@@ -3,6 +3,10 @@ import { action } from '@ember/object';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import { formFor } from '../config/integration-forms';
import {
BITCOIN_ICON_PATH,
BITCOIN_ICON_TRANSFORM,
} from '../config/integrations';
export default class BitcoinTickerComponent extends Component {
@service bitcoin;
@@ -49,6 +53,22 @@ export default class BitcoinTickerComponent extends Component {
class="cursor-pointer rounded-lg text-center text-white text-shadow-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white/70"
>
<div class="flex items-center justify-center gap-1.5">
<span
data-test-bitcoin-icon
class="flex size-4 flex-none items-center justify-center rounded-full bg-[#F7931A]"
aria-hidden="true"
>
<svg
viewBox="0 0 24 24"
fill="currentColor"
class="size-2.5 text-white"
>
<path
d={{BITCOIN_ICON_PATH}}
transform={{BITCOIN_ICON_TRANSFORM}}
/>
</svg>
</span>
<span class="text-lg font-semibold">{{this.formattedPrice}}</span>
{{#if this.hasChange}}
<svg
+92
View File
@@ -0,0 +1,92 @@
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import { formFor } from '../config/integration-forms';
import {
OPENROUTER_ICON_PATH,
OPENROUTER_ICON_TRANSFORM,
} from '../config/openrouter';
export default class OpenRouterUsageComponent extends Component {
@service openrouter;
@service modal;
get hasData() {
return this.openrouter.usage !== null;
}
get formattedUsage() {
return this.format(this.openrouter.usage);
}
format(value) {
if (value == null) {
return '—';
}
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 2,
}).format(value);
}
@action
openSettings() {
this.modal.open({
component: formFor('openrouter'),
props: { mode: 'edit' },
size: 'md',
});
}
<template>
{{#if this.openrouter.enabled}}
<button
type="button"
data-test-openrouter-usage
{{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"
>
<div class="flex items-center gap-1.5">
<span
class="flex size-4 flex-none items-center justify-center rounded-full bg-indigo-600"
aria-hidden="true"
>
<svg
viewBox="0 0 24 24"
fill="currentColor"
class="size-2.5 text-white"
>
<path
d={{OPENROUTER_ICON_PATH}}
transform={{OPENROUTER_ICON_TRANSFORM}}
/>
</svg>
</span>
<span class="text-lg font-semibold">{{this.formattedUsage}}</span>
</div>
{{#if this.openrouter.loading}}
{{#unless this.hasData}}
<div class="text-xs text-white/70">Loading…</div>
{{/unless}}
{{/if}}
{{#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,29 +1,32 @@
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import { formFor } from '../../../../config/integration-forms';
import { MARKET_TICKER_TYPES } from '../../../../config/market-ticker';
import { TICKER_STATS_TYPES } from '../../../../config/tickers-stats';
import AddList from '../../integrations/add-list.gjs';
import IntegrationGrid from './integration-grid.gjs';
// The dashboard market tickers (currently just Bitcoin), managed like the
// calendar sources. New asset integrations are added to MARKET_TICKER_TYPES.
export default class SettingsMarketTickerSection extends Component {
// The dashboard tickers and usage stats, managed together. Market tickers and
// usage stats share the same add/edit/remove flow, so they live in one section
// instead of separate ones. New types are added to TICKER_STATS_TYPES.
export default class SettingsTickersStatsSection extends Component {
@service integrations;
@service modal;
get rows() {
return this.integrations.rows.filter((row) =>
MARKET_TICKER_TYPES.includes(row.type)
TICKER_STATS_TYPES.includes(row.type)
);
}
// Market ticker integrations that are available and not connected yet.
// Ticker/stat integrations that are available and not connected yet. Both
// current types are single-instance, so this is empty once everything is
// connected and the Add button is hidden.
get addable() {
return this.integrations.all.filter(
(integration) =>
MARKET_TICKER_TYPES.includes(integration.id) &&
TICKER_STATS_TYPES.includes(integration.id) &&
integration.available &&
!(
integration.supportsMultiple === false && integration.instances.length
@@ -52,20 +55,18 @@ export default class SettingsMarketTickerSection extends Component {
}
@action
add(integration) {
const component = formFor(integration.id);
if (!component) {
return;
}
this.modal.open({ component, props: { mode: 'add' }, size: 'md' });
add() {
this.modal.open({
component: AddList,
props: { types: TICKER_STATS_TYPES },
size: 'md',
});
}
<template>
<div class="min-h-0 flex-1 overflow-y-auto px-6 py-6">
<p class="max-w-prose text-sm text-gray-500">
Track asset prices on your dashboard.
Track asset prices and usage stats on your dashboard.
</p>
<div class="mt-4">
@@ -73,23 +74,20 @@ export default class SettingsMarketTickerSection extends Component {
@rows={{this.rows}}
@onEdit={{this.edit}}
@onRemove={{this.remove}}
@emptyLabel="No market tickers enabled yet."
@emptyLabel="No tickers or stats enabled yet."
/>
</div>
{{#if this.addable.length}}
<div class="mt-6 flex flex-wrap gap-2">
{{#each this.addable as |integration|}}
<button
type="button"
data-test-add={{integration.id}}
{{on "click" (fn this.add integration)}}
class="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"
>
Add
{{integration.label}}
</button>
{{/each}}
<button
type="button"
data-test-add
{{on "click" this.add}}
class="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"
>
Add integration
</button>
</div>
{{/if}}
</div>
@@ -40,6 +40,15 @@ export default class SettingsIntegrationsAvatar extends Component {
return safeColor(this.siteIcon?.themeColor);
}
// Bundled icons are assumed to be full-bleed square canvases, but some (e.g.
// OpenRouter's glyph) have no padding of their own, so they must be inset
// instead of being cropped to the edges.
get iconUrlClass() {
return this.integration?.iconInset
? 'size-7 rounded-md object-contain'
: 'size-full object-cover';
}
get iconUrlThemeColor() {
return safeColor(this.integration?.themeColor);
}
@@ -67,7 +76,7 @@ export default class SettingsIntegrationsAvatar extends Component {
src={{@integration.iconUrl}}
alt=""
aria-hidden="true"
class="size-full object-cover"
class={{this.iconUrlClass}}
/>
</span>
{{else}}
@@ -0,0 +1,410 @@
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_DEFAULT_GRANULARITY,
OPENROUTER_DEFAULT_INTERVAL,
OPENROUTER_GRANULARITY_OPTIONS,
OPENROUTER_INTERVAL_OPTIONS,
OPENROUTER_MANAGEMENT_KEYS_URL,
openrouterKeyLabel,
} from '../../../config/openrouter';
import { isCancellation } from '../../../services/http';
export default class SettingsIntegrationsOpenRouterForm extends Component {
@service openrouter;
@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 ?? '';
}
get integration() {
return this.args.props?.integration;
}
get isEdit() {
return this.args.props?.mode === 'edit';
}
get title() {
return this.isEdit ? 'Edit OpenRouter Spend' : 'Add OpenRouter Spend';
}
get submitLabel() {
return this.isEdit ? 'Save' : 'Enable';
}
// A blank draft falls back to the stored key so users can change only the
// key selection or interval 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 ??
this.integration?.interval ??
this.openrouter.interval ??
OPENROUTER_DEFAULT_INTERVAL
);
}
get granularity() {
return (
this.granularityDraft ??
this.integration?.granularity ??
this.openrouter.granularity ??
OPENROUTER_DEFAULT_GRANULARITY
);
}
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;
}
get granularityOptions() {
return OPENROUTER_GRANULARITY_OPTIONS;
}
get managementKeysUrl() {
return OPENROUTER_MANAGEMENT_KEYS_URL;
}
resetOnClose = modifier((element) => {
const dialog = element.closest('dialog');
if (!dialog) {
return;
}
const handleClose = () => {
this.apiKeyDraft = null;
this.keyIdsDraft = null;
this.intervalDraft = null;
this.granularityDraft = null;
this.error = null;
this.keysLoaded = false;
};
dialog.addEventListener('close', handleClose);
return () => dialog.removeEventListener('close', handleClose);
});
@action
updateApiKey(event) {
const value = event.target.value;
this.apiKeyDraft = value || null;
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);
}
@action
updateGranularity(value) {
this.granularityDraft = value;
}
@action
async handleSubmit(event) {
event.preventDefault();
this.error = null;
if (!this.apiKey) {
this.error = 'Please enter a management key';
return;
}
this.submitting = true;
try {
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
);
}
this.args.close?.();
} catch (err) {
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
this.error = this.openrouter.classifyError(err);
} finally {
this.submitting = false;
}
}
<template>
<div class="p-6" {{this.resetOnClose}}>
<h3
id={{if @titleId @titleId "modal-title"}}
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>
</div>
<form {{on "submit" this.handleSubmit}} class="mt-5">
<div class="space-y-5">
<div>
<label
for="openrouter-key"
class="block text-sm font-medium leading-6 text-gray-900"
>
Management key
</label>
<div class="mt-2">
<input
type="password"
id="openrouter-key"
name="apiKey"
autocomplete="off"
value={{this.apiKeyDraftValue}}
{{on "input" this.updateApiKey}}
placeholder={{if this.isEdit "Leave blank to keep current" ""}}
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
Create one at
<a
href={{this.managementKeysUrl}}
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.
</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"
@label="Update interval"
@options={{this.intervalOptions}}
@value={{this.interval}}
@onChange={{this.updateInterval}}
/>
<SettingsSelect
@id="openrouter-granularity"
@name="granularity"
@label="Show"
@options={{this.granularityOptions}}
@value={{this.granularity}}
@onChange={{this.updateGranularity}}
/>
{{#if this.error}}
<p class="text-sm text-red-600">{{this.error}}</p>
{{/if}}
</div>
<div class="mt-5 sm:mt-6 flex gap-3">
<button
type="submit"
disabled={{this.submitting}}
class="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:opacity-50"
>
{{this.submitLabel}}
</button>
<button
type="button"
{{on "click" @close}}
class="inline-flex w-full 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"
>
Cancel
</button>
</div>
</form>
</div>
</template>
}
+2
View File
@@ -6,6 +6,7 @@ import GiteaForm from '../components/settings/integrations/gitea-form.gjs';
import HomeAssistantForm from '../components/settings/integrations/home-assistant-form.gjs';
import CalendarCaldavForm from '../components/settings/integrations/calendar-caldav-form.gjs';
import CalendarIcsForm from '../components/settings/integrations/calendar-ics-form.gjs';
import OpenRouterForm from '../components/settings/integrations/openrouter-form.gjs';
const FORMS = {
discourse: DiscourseForm,
@@ -16,6 +17,7 @@ const FORMS = {
homeassistant: HomeAssistantForm,
'calendar-caldav': CalendarCaldavForm,
'calendar-ics': CalendarIcsForm,
openrouter: OpenRouterForm,
};
export function formFor(type) {
+16 -2
View File
@@ -11,11 +11,11 @@ const CALENDAR_ICON_PATH =
// B-only glyph from the official Simple Icons bitcoin path. The full mark is
// a circle with the B cut out; extracting the B subpath and anchoring its
// relative move absolutely keeps the glyph centred in the 24x24 viewBox.
const BITCOIN_ICON_PATH =
export const BITCOIN_ICON_PATH =
'M17.288 10.291c.24-1.59-.974-2.45-2.64-3.03l.54-2.153-1.315-.33-.525 2.107c-.345-.087-.705-.167-1.064-.25l.526-2.127-1.32-.33-.54 2.165c-.285-.067-.565-.132-.84-.2l-1.815-.45-.35 1.407s.975.225.955.236c.535.136.63.486.615.766l-1.477 5.92c-.075.166-.24.406-.614.314.015.02-.96-.24-.96-.24l-.66 1.51 1.71.426.93.242-.54 2.19 1.32.327.54-2.17c.36.1.705.19 1.05.273l-.51 2.154 1.32.33.545-2.19c2.24.427 3.93.257 4.64-1.774.57-1.637-.03-2.58-1.217-3.196.854-.193 1.5-.76 1.68-1.93h.01zm-3.01 4.22c-.404 1.64-3.157.75-4.05.53l.72-2.9c.896.23 3.757.67 3.33 2.37zm.41-4.24c-.37 1.49-2.662.735-3.405.55l.654-2.64c.744.18 3.137.524 2.75 2.084v.006z';
// Scale the B glyph around its visual centre so it fills more of the avatar.
const BITCOIN_ICON_TRANSFORM =
export const BITCOIN_ICON_TRANSFORM =
'translate(11.575 11.775) scale(1.5) translate(-11.575 -11.775)';
export const FEEDBIN_ICON_URL = '/img/icons/feedbin.png';
@@ -124,6 +124,20 @@ export const INTEGRATIONS = [
hasSettings: true,
reconnectable: false,
},
{
id: 'openrouter',
label: 'OpenRouter Spend',
description: 'Daily, weekly, or monthly',
colorClass: 'bg-indigo-600',
iconUrl: '/img/icons/openrouter.svg',
// The glyph fills its square viewBox, so it needs to be inset rather than
// treated as a maskable full-bleed icon.
iconInset: true,
available: true,
supportsMultiple: false,
hasSettings: true,
reconnectable: false,
},
];
export function integrationFor(type) {
+108
View File
@@ -0,0 +1,108 @@
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_DEFAULT_INTERVAL = 300000;
export const OPENROUTER_INTERVAL_OPTIONS = [
{ value: 300000, label: 'Every 5 minutes' },
{ value: 600000, label: 'Every 10 minutes' },
{ value: 1800000, label: 'Every 30 minutes' },
];
export const OPENROUTER_DEFAULT_GRANULARITY = 'today';
export const OPENROUTER_GRANULARITY_OPTIONS = [
{ value: 'today', label: 'Today' },
{ value: 'this-week', label: 'This week' },
{ 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 =
'm 795.89139,147.2 c 119.883,0 217.05701,97.9963 217.05701,218.88 0,120.884 -97.17401,218.88 -217.05701,218.88 l 215.30701,217.109 c 27.35,27.578 7.98,74.731 -30.69601,74.731 h -618.734 c -199.8,0 -361.76999913,-163.327 -361.76999913,-364.8 0,-201.473 161.96999913,-364.8 361.76999913,-364.8 z m -434.123,145.92 c -119.88,0 -217.062,97.996 -217.062,218.88 0,120.884 97.182,218.88 217.062,218.88 119.879,0 217.061,-97.996 217.061,-218.88 0,-120.884 -97.182,-218.88 -217.061,-218.88 z';
export const OPENROUTER_ICON_TRANSFORM = 'scale(0.0234375)';
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) {
return OPENROUTER_GRANULARITY_OPTIONS.some(
(option) => option.value === granularity
)
? 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(),
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));
}
+2 -2
View File
@@ -1,8 +1,8 @@
import Events from '../components/settings/global-settings/sections/events.gjs';
import MarketTicker from '../components/settings/global-settings/sections/market-ticker.gjs';
import Photos from '../components/settings/global-settings/sections/photos.gjs';
import ProtocolGateway from '../components/settings/global-settings/sections/protocol-gateway.gjs';
import SiteLinks from '../components/settings/global-settings/sections/site-links.gjs';
import TickersStats from '../components/settings/global-settings/sections/tickers-stats.gjs';
// Maps a settings section id to its content component. Sections without an
// entry fall back to the generic placeholder, so this grows one section at a
@@ -11,7 +11,7 @@ const CONTENT = {
photos: Photos,
'site-links': SiteLinks,
events: Events,
'market-ticker': MarketTicker,
'tickers-stats': TickersStats,
'protocol-gateway': ProtocolGateway,
};
+3 -3
View File
@@ -43,9 +43,9 @@ export const SETTINGS_GROUPS = [
],
},
{
id: 'market-ticker',
label: 'Market Ticker',
description: 'Track asset prices on your dashboard.',
id: 'tickers-stats',
label: 'Tickers & Stats',
description: 'Track asset prices and usage stats on your dashboard.',
// Lucide chart-no-axes-combined.
icon: [
'M12 16v5',
+7
View File
@@ -0,0 +1,7 @@
import { MARKET_TICKER_TYPES } from './market-ticker';
import { USAGE_TYPES } from './usage';
// The integration types managed by the unified Tickers & Stats settings
// section. Market tickers and usage stats share the same add/edit/remove flow,
// so they are grouped here instead of in separate settings sections.
export const TICKER_STATS_TYPES = [...MARKET_TICKER_TYPES, ...USAGE_TYPES];
+4
View File
@@ -0,0 +1,4 @@
// The integration types that render as usage stats. New usage integrations
// get added here as their integrations are built, the same way market ticker
// types are grouped in `config/market-ticker.js`.
export const USAGE_TYPES = ['openrouter'];
+25
View File
@@ -172,6 +172,29 @@ const ADAPTERS = {
return this.bitcoin.disable();
},
},
openrouter: {
instances() {
if (!this.openrouter.enabled) {
return [];
}
return [
{
id: 'openrouter',
type: 'openrouter',
label: 'OpenRouter Spend',
status: 'active',
apiKey: this.openrouter.apiKey,
keyIds: this.openrouter.keyIds,
interval: this.openrouter.interval,
granularity: this.openrouter.granularity,
},
];
},
remove() {
return this.openrouter.disable();
},
},
'calendar-caldav': {
instances() {
return this.calendar.instancesFor('calendar-caldav').map((instance) => ({
@@ -213,6 +236,7 @@ const ADAPTERS = {
export default class IntegrationsService extends Service {
@service sites;
@service bitcoin;
@service openrouter;
@service calendar;
@service notifications;
@@ -247,6 +271,7 @@ export default class IntegrationsService extends Service {
iconTransform: integration.iconTransform,
iconFill: integration.iconFill,
iconUrl: integration.iconUrl,
iconInset: integration.iconInset,
hasSettings: integration.hasSettings,
reconnectable: integration.reconnectable,
}))
+289
View File
@@ -0,0 +1,289 @@
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,
openrouterAuthorizationHeader,
openrouterNormalizeGranularity,
openrouterPruneKeyIds,
openrouterTimeRange,
openrouterUsageTotal,
} from '../config/openrouter';
export default class OpenRouterService extends Service {
@service storage;
@service http;
@service pageLifecycle;
removeRestoreHandler = null;
@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;
ready = null;
constructor() {
super(...arguments);
this.ready = this.load();
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
this.handleRestore()
);
}
// A bfcache restore may have cancelled the last usage fetch, leaving a stale
// error behind. Fetch again immediately instead of waiting for the interval.
handleRestore() {
if (this.enabled) {
this.fetchUsage();
}
}
async load() {
try {
const integration = await this.storage.get('integrations', 'openrouter');
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
);
this.startPolling();
}
} catch (err) {
console.error('Error loading OpenRouter integration:', err);
}
}
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();
}
async update(
apiKey = this.apiKey,
keyIds = this.keyIds,
interval = this.interval,
granularity = this.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();
}
async persist({ apiKey, keyIds, interval, granularity }) {
const existing = await this.storage.get('integrations', 'openrouter');
await this.storage.set('integrations', 'openrouter', {
...existing,
type: 'openrouter',
status: 'active',
apiKey,
keyIds,
interval,
granularity,
createdAt: existing?.createdAt ?? Date.now(),
});
}
async disable() {
await this.ready;
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;
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;
}
}
async fetchUsage() {
if (this.fetching) {
return;
}
this.fetching = true;
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;
this.error = null;
} catch (err) {
// A navigation or bfcache freeze cancels the request; keep the last
// known values and do not report a failure.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error('Error fetching OpenRouter usage:', err);
this.error = this.classifyError(err);
} finally {
this.fetching = false;
this.loading = false;
}
}
classifyError(err) {
if (err?.name === 'NetworkError') {
return 'Unable to reach OpenRouter';
}
if (err?.status === 401) {
return 'Invalid or expired management key';
}
if (err?.status === 403) {
return 'Management key required';
}
if (err?.status === 408) {
return 'OpenRouter timed out';
}
if (err?.status === 429) {
return 'Rate limited by OpenRouter';
}
return 'OpenRouter returned an error';
}
startPolling() {
this.stopPolling();
this.fetchUsage();
this.intervalId = setInterval(() => {
this.fetchUsage();
}, this.interval);
}
stopPolling() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
willDestroy() {
this.removeRestoreHandler?.();
this.stopPolling();
super.willDestroy();
}
}
+5 -1
View File
@@ -1,6 +1,7 @@
import { pageTitle } from 'ember-page-title';
import DefaultClock from '../components/default-clock.gjs';
import BitcoinTicker from '../components/bitcoin-ticker.gjs';
import OpenRouterUsage from '../components/openrouter-usage.gjs';
import SiteLinks from '../components/site-links.gjs';
import SettingsButton from '../components/settings-button.gjs';
import UpcomingEvents from '../components/upcoming-events.gjs';
@@ -28,8 +29,11 @@ import WallpaperCredit from '../components/wallpaper-credit.gjs';
<SiteLinks />
</div>
<div class="col-start-2 row-start-1 flex items-start justify-center pt-12">
<div
class="col-start-2 row-start-1 flex items-start justify-center gap-6 pt-12"
>
<BitcoinTicker />
<OpenRouterUsage />
</div>
<div class="col-start-2 row-start-2 flex items-center justify-center">
+39
View File
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="1024"
height="1024"
viewBox="0 0 1024 1024"
fill="none"
version="1.1"
id="svg1"
sodipodi:docname="openrouter.svg"
inkscape:version="1.4.4 (dcaf3e7d9e, 2026-05-05)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs1" />
<sodipodi:namedview
id="namedview1"
pagecolor="#ffffff"
bordercolor="#111111"
borderopacity="1"
inkscape:showpageshadow="0"
inkscape:pageopacity="0"
inkscape:pagecheckerboard="1"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="0.4966649"
inkscape:cx="342.2831"
inkscape:cy="598.99542"
inkscape:window-width="2560"
inkscape:window-height="1365"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="svg1" />
<path
d="m 795.89139,147.2 c 119.883,0 217.05701,97.9963 217.05701,218.88 0,120.884 -97.17401,218.88 -217.05701,218.88 l 215.30701,217.109 c 27.35,27.578 7.98,74.731 -30.69601,74.731 h -618.734 c -199.8,0 -361.76999913,-163.327 -361.76999913,-364.8 0,-201.473 161.96999913,-364.8 361.76999913,-364.8 z m -434.123,145.92 c -119.88,0 -217.062,97.996 -217.062,218.88 0,120.884 97.182,218.88 217.062,218.88 119.879,0 217.061,-97.996 217.061,-218.88 0,-120.884 -97.182,-218.88 -217.061,-218.88 z"
fill="#7624f4"
id="path1" />
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -67,6 +67,17 @@ module('Integration | Component | bitcoin-ticker', function (hooks) {
assert.dom().doesNotContainText('%');
});
test('it renders the bitcoin icon circle', async function (assert) {
const bitcoin = new FakeBitcoinService();
this.owner.register('service:bitcoin', bitcoin, { instantiate: false });
bitcoin.enabled = true;
await render(<template><BitcoinTicker /></template>);
assert.dom('[data-test-bitcoin-icon]').exists();
});
test('it shows an error message when the fetch fails', async function (assert) {
const bitcoin = new FakeBitcoinService();
this.owner.register('service:bitcoin', bitcoin, { instantiate: false });
@@ -0,0 +1,157 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, click } from '@ember/test-helpers';
import { tracked } from '@glimmer/tracking';
import OpenRouterUsage from 'dashtab/components/openrouter-usage';
class FakeOpenRouterService {
@tracked enabled = false;
@tracked usage = null;
@tracked granularity = 'today';
@tracked loading = false;
@tracked error = null;
@tracked truncated = false;
@tracked warnings = [];
}
class FakeModalService {
opened = null;
open(descriptor) {
this.opened = descriptor;
}
}
module('Integration | Component | openrouter-usage', function (hooks) {
setupRenderingTest(hooks);
test('it renders nothing when disabled', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
await render(<template><OpenRouterUsage /></template>);
assert.dom('[data-test-openrouter-usage]').doesNotExist();
});
test('it opens the OpenRouter settings when enabled', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const modal = new FakeModalService();
this.owner.register('service:modal', modal, { instantiate: false });
openrouter.enabled = true;
await render(<template><OpenRouterUsage /></template>);
await click('[data-test-openrouter-usage]');
assert.ok(modal.opened.component);
assert.strictEqual(modal.opened.props.mode, 'edit');
assert.strictEqual(modal.opened.size, 'md');
});
test('it shows a single usage number', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
openrouter.usage = 1.5;
await render(<template><OpenRouterUsage /></template>);
assert.dom().containsText('$1.50');
assert.dom().doesNotContainText('Today');
assert.dom().doesNotContainText('Yesterday');
});
test('it renders the icon', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
openrouter.usage = 1.5;
await render(<template><OpenRouterUsage /></template>);
assert.dom('[data-test-openrouter-usage] svg').exists();
});
test('it shows a placeholder when no value is available', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
await render(<template><OpenRouterUsage /></template>);
assert.dom().containsText('—');
});
test('it shows a loading state while loading and no data', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
openrouter.loading = true;
await render(<template><OpenRouterUsage /></template>);
assert.dom().containsText('Loading…');
});
test('it shows an error message', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
openrouter.enabled = true;
openrouter.error = 'Management key required';
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');
});
});
@@ -1,138 +0,0 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, click } from '@ember/test-helpers';
import { tracked } from '@glimmer/tracking';
import MarketTicker from 'dashtab/components/settings/global-settings/sections/market-ticker';
class FakeSitesService {
@tracked all = [];
integrationFor() {
return undefined;
}
async removeSource() {}
}
class FakeNotificationsService {
stateFor() {
return { error: null, errorType: null };
}
}
class FakeBitcoinService {
@tracked enabled = false;
@tracked interval = 30000;
@tracked provider = 'coingecko';
disabled = false;
async disable() {
this.disabled = true;
this.enabled = false;
}
}
class FakeCalendarService {
instancesFor() {
return [];
}
}
class FakeModalService {
opened = null;
open(descriptor) {
this.opened = descriptor;
}
replace(descriptor) {
this.opened = descriptor;
}
}
function register(owner, overrides = {}) {
const sites = overrides.sites ?? new FakeSitesService();
const notifications =
overrides.notifications ?? new FakeNotificationsService();
const bitcoin = overrides.bitcoin ?? new FakeBitcoinService();
const calendar = overrides.calendar ?? new FakeCalendarService();
const modal = overrides.modal ?? new FakeModalService();
owner.register('service:sites', sites, { instantiate: false });
owner.register('service:notifications', notifications, {
instantiate: false,
});
owner.register('service:bitcoin', bitcoin, { instantiate: false });
owner.register('service:calendar', calendar, { instantiate: false });
owner.register('service:modal', modal, { instantiate: false });
return { sites, notifications, bitcoin, calendar, modal };
}
module(
'Integration | Component | settings/global-settings/sections/market-ticker',
function (hooks) {
setupRenderingTest(hooks);
test('offers to add Bitcoin when it is not enabled', async function (assert) {
register(this.owner);
await render(<template><MarketTicker /></template>);
assert.dom('[data-test-add="bitcoin"]').exists();
assert
.dom('[data-test-add="bitcoin"]')
.hasText('Add Bitcoin Price Ticker');
assert.dom('[data-instance="bitcoin"]').doesNotExist();
});
test('shows the enabled ticker in the grid instead of the add button', async function (assert) {
const bitcoin = new FakeBitcoinService();
bitcoin.enabled = true;
register(this.owner, { bitcoin });
await render(<template><MarketTicker /></template>);
assert.dom('[data-instance="bitcoin"]').exists();
assert.dom('[data-instance="bitcoin"] [data-test-settings]').exists();
assert.dom('[data-instance="bitcoin"] [data-test-remove]').exists();
assert.dom('[data-test-add="bitcoin"]').doesNotExist();
});
test('editing the ticker opens its form', async function (assert) {
const bitcoin = new FakeBitcoinService();
bitcoin.enabled = true;
const { modal } = register(this.owner, { bitcoin });
await render(<template><MarketTicker /></template>);
await click('[data-instance="bitcoin"] [data-test-settings]');
assert.ok(modal.opened.component);
assert.strictEqual(modal.opened.props.mode, 'edit');
});
test('adding Bitcoin opens its form in add mode', async function (assert) {
const { modal } = register(this.owner);
await render(<template><MarketTicker /></template>);
await click('[data-test-add="bitcoin"]');
assert.ok(modal.opened.component);
assert.strictEqual(modal.opened.props.mode, 'add');
});
test('removing the ticker disables it', async function (assert) {
const bitcoin = new FakeBitcoinService();
bitcoin.enabled = true;
register(this.owner, { bitcoin });
await render(<template><MarketTicker /></template>);
await click('[data-instance="bitcoin"] [data-test-remove]');
assert.true(bitcoin.disabled);
});
}
);
@@ -0,0 +1,197 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, click } from '@ember/test-helpers';
import { tracked } from '@glimmer/tracking';
import TickersStats from 'dashtab/components/settings/global-settings/sections/tickers-stats';
import AddList from 'dashtab/components/settings/integrations/add-list';
import BitcoinForm from 'dashtab/components/settings/integrations/bitcoin-form';
import OpenRouterForm from 'dashtab/components/settings/integrations/openrouter-form';
class FakeSitesService {
@tracked all = [];
integrationFor() {
return undefined;
}
async removeSource() {}
}
class FakeNotificationsService {
stateFor() {
return { error: null, errorType: null };
}
}
class FakeBitcoinService {
@tracked enabled = false;
@tracked interval = 30000;
@tracked provider = 'coingecko';
disabled = false;
async disable() {
this.disabled = true;
this.enabled = false;
}
}
class FakeOpenRouterService {
@tracked enabled = false;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = 300000;
@tracked granularity = 'today';
disabled = false;
async disable() {
this.disabled = true;
this.enabled = false;
}
}
class FakeCalendarService {
instancesFor() {
return [];
}
}
class FakeModalService {
opened = null;
open(descriptor) {
this.opened = descriptor;
}
replace(descriptor) {
this.opened = descriptor;
}
}
function register(owner, overrides = {}) {
const sites = overrides.sites ?? new FakeSitesService();
const notifications =
overrides.notifications ?? new FakeNotificationsService();
const bitcoin = overrides.bitcoin ?? new FakeBitcoinService();
const openrouter = overrides.openrouter ?? new FakeOpenRouterService();
const calendar = overrides.calendar ?? new FakeCalendarService();
const modal = overrides.modal ?? new FakeModalService();
owner.register('service:sites', sites, { instantiate: false });
owner.register('service:notifications', notifications, {
instantiate: false,
});
owner.register('service:bitcoin', bitcoin, { instantiate: false });
owner.register('service:openrouter', openrouter, { instantiate: false });
owner.register('service:calendar', calendar, { instantiate: false });
owner.register('service:modal', modal, { instantiate: false });
return { sites, notifications, bitcoin, openrouter, calendar, modal };
}
module(
'Integration | Component | settings/global-settings/sections/tickers-stats',
function (hooks) {
setupRenderingTest(hooks);
test('offers a single Add integration button when nothing is enabled', async function (assert) {
register(this.owner);
await render(<template><TickersStats /></template>);
assert.dom('[data-test-add]').exists();
assert.dom('[data-test-add]').hasText('Add integration');
assert.dom('[data-test-add="bitcoin"]').doesNotExist();
assert.dom('[data-test-add="openrouter"]').doesNotExist();
assert.dom('[data-instance="bitcoin"]').doesNotExist();
assert.dom('[data-instance="openrouter"]').doesNotExist();
});
test('adding opens the integration list filtered to tickers and stats', async function (assert) {
const { modal } = register(this.owner);
await render(<template><TickersStats /></template>);
await click('[data-test-add]');
assert.strictEqual(modal.opened.component, AddList);
assert.deepEqual(modal.opened.props.types, ['bitcoin', 'openrouter']);
});
test('hides the Add integration button when both integrations are connected', async function (assert) {
const bitcoin = new FakeBitcoinService();
bitcoin.enabled = true;
const openrouter = new FakeOpenRouterService();
openrouter.enabled = true;
register(this.owner, { bitcoin, openrouter });
await render(<template><TickersStats /></template>);
assert.dom('[data-test-add]').doesNotExist();
assert.dom('[data-instance="bitcoin"]').exists();
assert.dom('[data-instance="openrouter"]').exists();
});
test('shows active tickers and stats with settings and remove buttons', async function (assert) {
const bitcoin = new FakeBitcoinService();
bitcoin.enabled = true;
const openrouter = new FakeOpenRouterService();
openrouter.enabled = true;
register(this.owner, { bitcoin, openrouter });
await render(<template><TickersStats /></template>);
assert.dom('[data-instance="bitcoin"]').exists();
assert.dom('[data-instance="bitcoin"] [data-test-settings]').exists();
assert.dom('[data-instance="bitcoin"] [data-test-remove]').exists();
assert.dom('[data-instance="openrouter"]').exists();
assert.dom('[data-instance="openrouter"] [data-test-settings]').exists();
assert.dom('[data-instance="openrouter"] [data-test-remove]').exists();
});
test('editing a ticker opens its form', async function (assert) {
const bitcoin = new FakeBitcoinService();
bitcoin.enabled = true;
const { modal } = register(this.owner, { bitcoin });
await render(<template><TickersStats /></template>);
await click('[data-instance="bitcoin"] [data-test-settings]');
assert.strictEqual(modal.opened.component, BitcoinForm);
assert.strictEqual(modal.opened.props.mode, 'edit');
assert.strictEqual(modal.opened.props.integration.type, 'bitcoin');
});
test('editing a stat opens its form', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.enabled = true;
const { modal } = register(this.owner, { openrouter });
await render(<template><TickersStats /></template>);
await click('[data-instance="openrouter"] [data-test-settings]');
assert.strictEqual(modal.opened.component, OpenRouterForm);
assert.strictEqual(modal.opened.props.mode, 'edit');
assert.strictEqual(modal.opened.props.integration.type, 'openrouter');
});
test('removing a ticker or stat disables it', async function (assert) {
const bitcoin = new FakeBitcoinService();
bitcoin.enabled = true;
const openrouter = new FakeOpenRouterService();
openrouter.enabled = true;
register(this.owner, { bitcoin, openrouter });
await render(<template><TickersStats /></template>);
await click('[data-instance="bitcoin"] [data-test-remove]');
assert.true(bitcoin.disabled);
await click('[data-instance="openrouter"] [data-test-remove]');
assert.true(openrouter.disabled);
});
}
);
@@ -1,6 +1,6 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, click } from '@ember/test-helpers';
import { render, triggerEvent } from '@ember/test-helpers';
import { tracked } from '@glimmer/tracking';
import List from 'dashtab/components/settings/integrations/add-list';
@@ -20,6 +20,26 @@ class FakeBitcoinService {
@tracked provider = 'coingecko';
}
class FakeOpenRouterService {
@tracked enabled = false;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = 300000;
@tracked granularity = 'today';
async disable() {}
}
// The real calendar service loads asynchronously in its constructor and
// re-renders the list when it resolves. That can tear down a button between the
// click's element lookup and its event dispatch, which made the click test
// flake. A stub keeps the list stable for the whole test.
class FakeCalendarService {
instancesFor() {
return [];
}
}
class FakeModalService {
replaced = null;
@@ -46,6 +66,16 @@ function register(owner, overrides = {}) {
overrides.bitcoin ?? new FakeBitcoinService(),
{ instantiate: false }
);
owner.register(
'service:openrouter',
overrides.openrouter ?? new FakeOpenRouterService(),
{ instantiate: false }
);
owner.register(
'service:calendar',
overrides.calendar ?? new FakeCalendarService(),
{ instantiate: false }
);
const modal = overrides.modal ?? new FakeModalService();
owner.register('service:modal', modal, { instantiate: false });
@@ -141,7 +171,9 @@ module(
await render(<template><List /></template>);
await click('[data-add="discourse"]');
const btn = this.element.querySelector('[data-add="discourse"]');
await triggerEvent(btn, 'click');
assert.ok(modal.replaced.component);
assert.strictEqual(modal.replaced.props.mode, 'add');
@@ -50,6 +50,20 @@ module(
assert.dom('svg').doesNotExist();
});
test('it renders an inset bundled icon when the icon is not maskable', async function (assert) {
this.integration = {
iconUrl: '/img/icons/openrouter.svg',
iconInset: true,
};
await render(
<template><Avatar @integration={{this.integration}} /></template>
);
assert.dom('img').hasAttribute('src', '/img/icons/openrouter.svg');
assert.dom('img').hasClass('object-contain');
});
test('it paints the backdrop behind a transparent bundled icon', async function (assert) {
this.integration = {
iconUrl: '/img/icons/github-inverted.png',
@@ -0,0 +1,349 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, triggerEvent, click } from '@ember/test-helpers';
import { tracked } from '@glimmer/tracking';
import OpenRouterForm from 'dashtab/components/settings/integrations/openrouter-form';
function changeSelect(selector, value) {
const select = document.querySelector(selector);
const event = new Event('change', { bubbles: true });
Object.defineProperty(event, 'target', { value: { value } });
select.dispatchEvent(event);
}
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, 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 });
}
classifyError(err) {
return err?.message ?? 'OpenRouter returned an error';
}
}
module(
'Integration | Component | settings/integrations/openrouter-form',
function (hooks) {
setupRenderingTest(hooks);
test('it renders the management key field', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
assert.dom().containsText('Add OpenRouter Spend');
assert.dom('#openrouter-key').exists();
assert.dom('#openrouter-interval').exists();
assert.dom('#openrouter-granularity').exists();
assert.dom().containsText('OpenRouter management keys');
});
test('offers the three supported granularity options', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
const select = document.querySelector('#openrouter-granularity');
const labels = [...select.querySelectorAll('el-option')].map((option) =>
option.textContent.trim()
);
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, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await fillIn('#openrouter-key', 'sk-or-v1-test');
await triggerEvent('form', 'submit');
assert.deepEqual(openrouter.calls, [
{
type: 'enable',
apiKey: 'sk-or-v1-test',
keyIds: [],
interval: 300000,
granularity: 'today',
},
]);
});
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,
});
this.props = {
mode: 'edit',
integration: {
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
},
};
let closed = false;
const closeDialog = () => {
closed = true;
};
await render(
<template>
<OpenRouterForm @props={{this.props}} @close={{closeDialog}} />
</template>
);
assert.dom().containsText('Edit OpenRouter Spend');
assert.dom('#openrouter-interval').containsText('Every 10 minutes');
assert.dom('#openrouter-granularity').containsText('Today');
await triggerEvent('form', 'submit');
assert.deepEqual(openrouter.calls, [
{
type: 'update',
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
},
]);
assert.true(closed);
});
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,
});
this.props = {
mode: 'edit',
integration: {
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
},
};
const noop = () => {};
await render(
<template>
<OpenRouterForm @props={{this.props}} @close={{noop}} />
</template>
);
await triggerEvent('form', 'submit');
assert.deepEqual(openrouter.calls, [
{
type: 'update',
apiKey: 'sk-or-v1-stored',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
},
]);
});
test('shows an error when the key is missing', async function (assert) {
const openrouter = new FakeOpenRouterService();
this.owner.register('service:openrouter', openrouter, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a management 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, {
instantiate: false,
});
const noop = () => {};
await render(<template><OpenRouterForm @close={{noop}} /></template>);
await fillIn('#openrouter-key', 'sk-or-v1-test');
changeSelect('#openrouter-interval', '600000');
changeSelect('#openrouter-granularity', 'today');
await triggerEvent('form', 'submit');
assert.deepEqual(openrouter.calls, [
{
type: 'enable',
apiKey: 'sk-or-v1-test',
keyIds: [],
interval: 600000,
granularity: 'today',
},
]);
});
}
);
+125
View File
@@ -0,0 +1,125 @@
import { module, test } from 'qunit';
import {
openrouterKeyLabel,
openrouterLocalDateKey,
openrouterNormalizeGranularity,
openrouterPruneKeyIds,
openrouterTimeRange,
openrouterUsageTotal,
} 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(
openrouterNormalizeGranularity('this-week'),
'this-week'
);
assert.strictEqual(
openrouterNormalizeGranularity('this-month'),
'this-month'
);
assert.strictEqual(
openrouterNormalizeGranularity('today-yesterday'),
'today'
);
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);
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);
});
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']);
});
});
+48 -1
View File
@@ -37,6 +37,20 @@ class FakeBitcoinService {
}
}
class FakeOpenRouterService {
@tracked enabled = false;
@tracked apiKey = null;
@tracked keyIds = [];
@tracked interval = 300000;
@tracked granularity = 'today';
disabled = false;
async disable() {
this.disabled = true;
this.enabled = false;
}
}
class FakeCalendarService {
instancesByType = { 'calendar-caldav': [], 'calendar-ics': [] };
removed = [];
@@ -55,6 +69,7 @@ function register(owner, overrides = {}) {
const notifications =
overrides.notifications ?? new FakeNotificationsService();
const bitcoin = overrides.bitcoin ?? new FakeBitcoinService();
const openrouter = overrides.openrouter ?? new FakeOpenRouterService();
const calendar = overrides.calendar ?? new FakeCalendarService();
owner.register('service:sites', sites, { instantiate: false });
@@ -62,9 +77,10 @@ function register(owner, overrides = {}) {
instantiate: false,
});
owner.register('service:bitcoin', bitcoin, { instantiate: false });
owner.register('service:openrouter', openrouter, { instantiate: false });
owner.register('service:calendar', calendar, { instantiate: false });
return { sites, notifications, bitcoin, calendar };
return { sites, notifications, bitcoin, openrouter, calendar };
}
module('Unit | Service | integrations', function (hooks) {
@@ -214,6 +230,37 @@ module('Unit | Service | integrations', function (hooks) {
assert.true(bitcoin.disabled);
});
test('openrouter adapter exposes the configured integration', async function (assert) {
const openrouter = new FakeOpenRouterService();
openrouter.enabled = true;
openrouter.apiKey = 'sk-or-v1-test';
openrouter.keyIds = ['abc'];
openrouter.interval = 600000;
openrouter.granularity = 'today';
register(this.owner, { openrouter });
const service = this.owner.lookup('service:integrations');
const openrouterEntry = service.all.find(
(entry) => entry.id === 'openrouter'
);
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');
const row = service.rows.find((entry) => entry.type === 'openrouter');
assert.strictEqual(row.label, 'OpenRouter Spend');
assert.strictEqual(row.byline, 'Daily, weekly, or monthly');
assert.true(row.iconInset);
await service.remove({ type: 'openrouter', id: 'openrouter' });
assert.true(openrouter.disabled);
});
test('feedbin adapter exposes the connected account without reconnect', async function (assert) {
const sites = new FakeSitesService();
sites.all = [
+499
View File
@@ -0,0 +1,499 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import {
OPENROUTER_ANALYTICS_URL,
OPENROUTER_KEYS_URL,
} from 'dashtab/config/openrouter';
module('Unit | Service | openrouter', function (hooks) {
setupTest(hooks);
let originalFetch;
let originalConsoleError;
hooks.beforeEach(async function () {
originalFetch = globalThis.fetch;
originalConsoleError = console.error;
console.error = () => {};
const storage = this.owner.lookup('service:storage');
await storage.remove('integrations', 'openrouter');
});
hooks.afterEach(function () {
globalThis.fetch = originalFetch;
console.error = originalConsoleError;
});
test('it exists', function (assert) {
const service = this.owner.lookup('service:openrouter');
assert.ok(service);
});
test('load enables a stored active integration', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'openrouter', {
type: 'openrouter',
status: 'active',
apiKey: 'sk-or-v1-test',
keyIds: ['abc'],
interval: 600000,
granularity: 'today',
});
const service = this.owner.lookup('service:openrouter');
service.fetchUsage = async () => {};
await service.ready;
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.ok(service.intervalId);
service.stopPolling();
});
test('load stays disabled for a pending integration', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'openrouter', {
type: 'openrouter',
status: 'pending',
});
const service = this.owner.lookup('service:openrouter');
await service.ready;
assert.false(service.enabled);
assert.strictEqual(service.intervalId, null);
});
test('enable validates the key and persists the integration', async function (assert) {
let requestedUrl;
globalThis.fetch = async (url) => {
requestedUrl = url;
return {
ok: true,
json: async () => ({ data: [{ hash: 'abc' }, { hash: 'def' }] }),
};
};
const service = this.owner.lookup('service:openrouter');
service.fetchUsage = async () => {};
await service.enable('sk-or-v1-test', ['abc', 'stale'], 600000, 'today');
assert.strictEqual(
requestedUrl,
`${OPENROUTER_KEYS_URL}?include_disabled=true&include_expired=true`
);
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');
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']);
service.stopPolling();
});
test('enable throws when the key is invalid', 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.enable('bad', [], 600000, 'today'), (err) => {
assert.strictEqual(err.status, 401);
return true;
});
assert.false(service.enabled);
});
test('fetchUsage posts the query and aggregates the response', async function (assert) {
let requestedUrl;
let requestedOptions;
globalThis.fetch = async (url, options) => {
requestedUrl = url;
requestedOptions = 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,
},
}),
};
};
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.keyIds = ['abc'];
service.granularity = 'today';
service.enabled = true;
await service.fetchUsage();
assert.strictEqual(requestedUrl, OPENROUTER_ANALYTICS_URL);
assert.strictEqual(requestedOptions.method, 'POST');
assert.strictEqual(
requestedOptions.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) {
globalThis.fetch = async () => ({
ok: false,
status: 403,
json: async () => ({ error: { code: 403 } }),
});
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.enabled = true;
await service.fetchUsage();
assert.strictEqual(service.error, 'Management key required');
});
test('fetchKeys returns the keys and reads the response data', async function (assert) {
globalThis.fetch = async () => ({
ok: true,
json: async () => ({ data: [{ hash: 'abc' }] }),
});
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');
});
test('fetchUsage ignores cancellation and page leaving', async function (assert) {
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.enabled = true;
globalThis.fetch = async () => {
throw new DOMException('Aborted', 'AbortError');
};
await service.fetchUsage();
assert.strictEqual(service.error, null);
service.pageLifecycle.leaving = true;
globalThis.fetch = async () => {
throw new Error('boom');
};
await service.fetchUsage();
assert.strictEqual(service.error, null);
service.pageLifecycle.leaving = false;
});
test('fetchUsage skips overlapping requests', async function (assert) {
let calls = 0;
globalThis.fetch = async () => {
calls += 1;
return { ok: true, json: async () => ({ data: { data: [] } }) };
};
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.enabled = true;
service.fetching = true;
await service.fetchUsage();
assert.strictEqual(calls, 0);
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) {
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,
},
}),
});
const service = this.owner.lookup('service:openrouter');
service.apiKey = 'sk-or-v1-test';
service.enabled = true;
await service.fetchUsage();
assert.true(service.truncated);
assert.deepEqual(service.warnings, ['Unresolved api_key_id']);
assert.strictEqual(service.cachedAt, 456);
});
});