Fix Model Price

This commit is contained in:
decolua
2026-04-04 14:40:49 +07:00
parent 2b1faeb2c6
commit 341a1c6490
6 changed files with 412 additions and 973 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "9router-app",
"version": "0.3.73",
"version": "0.3.74",
"description": "9Router web dashboard",
"private": true,
"scripts": {

View File

@@ -1080,93 +1080,65 @@ export async function getCloudUrl() {
/**
* Get pricing configuration
* Returns merged user pricing with defaults
* Returns merged: PROVIDER_PRICING defaults + user overrides
*/
export async function getPricing() {
const db = await getDb();
const userPricing = db.data.pricing || {};
// Import default pricing
const { getDefaultPricing } = await import("@/shared/constants/pricing.js");
const defaultPricing = getDefaultPricing();
const { PROVIDER_PRICING } = await import("@/shared/constants/pricing.js");
// Merge user pricing with defaults
// User pricing overrides defaults for specific provider/model combinations
const mergedPricing = {};
// Deep merge PROVIDER_PRICING + user overrides
const merged = {};
for (const [provider, models] of Object.entries(defaultPricing)) {
mergedPricing[provider] = { ...models };
// Apply user overrides if they exist
for (const [provider, models] of Object.entries(PROVIDER_PRICING)) {
merged[provider] = { ...models };
if (userPricing[provider]) {
for (const [model, pricing] of Object.entries(userPricing[provider])) {
if (mergedPricing[provider][model]) {
mergedPricing[provider][model] = { ...mergedPricing[provider][model], ...pricing };
} else {
mergedPricing[provider][model] = pricing;
}
merged[provider][model] = merged[provider][model]
? { ...merged[provider][model], ...pricing }
: pricing;
}
}
}
// Add any user-only pricing entries
// User-only providers not in PROVIDER_PRICING
for (const [provider, models] of Object.entries(userPricing)) {
if (!mergedPricing[provider]) {
mergedPricing[provider] = { ...models };
if (!merged[provider]) {
merged[provider] = { ...models };
} else {
for (const [model, pricing] of Object.entries(models)) {
if (!mergedPricing[provider][model]) {
mergedPricing[provider][model] = pricing;
}
if (!merged[provider][model]) merged[provider][model] = pricing;
}
}
}
return mergedPricing;
return merged;
}
/**
* Get pricing for a specific provider and model
* Get pricing for a specific provider and model.
* Delegates to getPricingForModel in pricing.js which handles the full fallback chain:
* 1. PROVIDER_PRICING[provider][model] — provider-specific override
* 2. MODEL_PRICING[model] — canonical model price
* 3. PATTERN_PRICING — glob pattern match
*
* Also checks user DB overrides first.
*/
export async function getPricingForModel(provider, model) {
const pricing = await getPricing();
if (!model) return null;
// Try direct lookup
if (pricing[provider]?.[model]) {
return pricing[provider][model];
const db = await getDb();
const userPricing = db.data.pricing || {};
// User override takes top priority
if (provider && userPricing[provider]?.[model]) {
return userPricing[provider][model];
}
// Try mapping provider ID to alias
// We need to duplicate the mapping here or import it
// Since we can't easily import from open-sse, we'll implement the mapping locally
const PROVIDER_ID_TO_ALIAS = {
claude: "cc",
codex: "cx",
"gemini-cli": "gc",
qwen: "qw",
iflow: "if",
antigravity: "ag",
github: "gh",
kiro: "kr",
openai: "openai",
anthropic: "anthropic",
gemini: "gemini",
openrouter: "openrouter",
glm: "glm",
kimi: "kimi",
minimax: "minimax",
};
const alias = PROVIDER_ID_TO_ALIAS[provider];
if (alias && pricing[alias]) {
return pricing[alias][model] || null;
}
// Fallback: strip vendor prefix (e.g. "deepseek/deepseek-chat" → "deepseek-chat")
// then lookup in MODEL_PRICING (provider-agnostic explicit map)
const { MODEL_PRICING } = await import("@/shared/constants/pricing.js");
const baseModel = model.includes("/") ? model.split("/").pop() : model;
return MODEL_PRICING[baseModel] || MODEL_PRICING[model] || null;
// Delegate to constants fallback chain
const { getPricingForModel: resolve } = await import("@/shared/constants/pricing.js");
return resolve(provider, model);
}
/**

View File

@@ -92,6 +92,12 @@ if (!global._statsEmitter) {
}
export const statsEmitter = global._statsEmitter;
// Safety timers — force-clear pending counts after 1 min if END was never called
if (!global._pendingTimers) global._pendingTimers = {};
const pendingTimers = global._pendingTimers;
const PENDING_TIMEOUT_MS = 60 * 1000; // 1 minute
/**
* Track a pending request
* @param {string} model
@@ -102,6 +108,7 @@ export const statsEmitter = global._statsEmitter;
*/
export function trackPendingRequest(model, provider, connectionId, started, error = false) {
const modelKey = provider ? `${model} (${provider})` : model;
const timerKey = `${connectionId}|${modelKey}`;
// Track by model
if (!pendingRequests.byModel[modelKey]) pendingRequests.byModel[modelKey] = 0;
@@ -109,10 +116,28 @@ export function trackPendingRequest(model, provider, connectionId, started, erro
// Track by account
if (connectionId) {
const accountKey = connectionId;
if (!pendingRequests.byAccount[accountKey]) pendingRequests.byAccount[accountKey] = {};
if (!pendingRequests.byAccount[accountKey][modelKey]) pendingRequests.byAccount[accountKey][modelKey] = 0;
pendingRequests.byAccount[accountKey][modelKey] = Math.max(0, pendingRequests.byAccount[accountKey][modelKey] + (started ? 1 : -1));
if (!pendingRequests.byAccount[connectionId]) pendingRequests.byAccount[connectionId] = {};
if (!pendingRequests.byAccount[connectionId][modelKey]) pendingRequests.byAccount[connectionId][modelKey] = 0;
pendingRequests.byAccount[connectionId][modelKey] = Math.max(0, pendingRequests.byAccount[connectionId][modelKey] + (started ? 1 : -1));
}
if (started) {
// Safety timeout: force-clear if END is never called (client disconnect, crash, etc.)
clearTimeout(pendingTimers[timerKey]);
pendingTimers[timerKey] = setTimeout(() => {
delete pendingTimers[timerKey];
if (pendingRequests.byModel[modelKey] > 0) {
pendingRequests.byModel[modelKey] = 0;
}
if (connectionId && pendingRequests.byAccount[connectionId]?.[modelKey] > 0) {
pendingRequests.byAccount[connectionId][modelKey] = 0;
}
statsEmitter.emit("pending");
}, PENDING_TIMEOUT_MS);
} else {
// END called normally — cancel the safety timer
clearTimeout(pendingTimers[timerKey]);
delete pendingTimers[timerKey];
}
// Track error provider (auto-clears after 10s)

View File

@@ -1,104 +1,23 @@
"use client";
import { useState, useEffect, useRef } from "react";
import NineRemoteModal from "./NineRemoteModal";
// step 0-4 từ 9remote SSE: 0=Stopped,1=Preparing,2=Connecting,3=Tunneling,4=Ready
const STEP = { STOPPED: 0, PREPARING: 1, CONNECTING: 2, TUNNELING: 3, READY: 4 };
// Retry interval khi 9remote chưa chạy (30s để không spam)
const RETRY_MS = 30000;
const stepStyle = (step, installed) => {
if (!installed) return { color: "text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5", glow: null };
switch (step) {
case STEP.READY: return { color: "text-emerald-500 hover:bg-emerald-500/10", glow: "drop-shadow(0 0 6px rgb(16 185 129 / 0.7))" };
case STEP.STOPPED: return { color: "text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5", glow: null };
default: return { color: "text-amber-400 hover:bg-amber-400/10", glow: null };
}
};
import { useState } from "react";
import NineRemotePromoModal from "./NineRemotePromoModal";
export default function NineRemoteButton() {
const [isOpen, setIsOpen] = useState(false);
const [installed, setInstalled] = useState(false);
const [step, setStep] = useState(STEP.STOPPED);
const esRef = useRef(null);
const retryRef = useRef(null);
const scheduleRetry = () => {
clearTimeout(retryRef.current);
retryRef.current = setTimeout(connect, RETRY_MS);
};
const connect = () => {
esRef.current?.close();
clearTimeout(retryRef.current);
const es = new EventSource("http://localhost:2208/api/ui/events");
es.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === "state") {
setInstalled(true);
setStep(data.step ?? STEP.STOPPED);
}
} catch {}
};
es.onerror = () => {
es.close();
setStep(STEP.STOPPED);
// 9remote not running — retry after delay
scheduleRetry();
};
esRef.current = es;
};
useEffect(() => {
// Check installed once on mount (no polling, just 1 call)
fetch("/api/9remote/status")
.then((r) => r.json())
.then((d) => setInstalled(d.installed))
.catch(() => {});
connect();
return () => {
esRef.current?.close();
clearTimeout(retryRef.current);
};
}, []);
// When modal closes, reconnect SSE immediately (user may have just started 9remote)
const handleClose = () => {
setIsOpen(false);
setTimeout(connect, 800);
};
const { color, glow } = stepStyle(step, installed);
const isPulsing = installed && step >= STEP.PREPARING && step <= STEP.TUNNELING;
return (
<>
<button
onClick={() => setIsOpen(true)}
className={`relative flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg transition-all ${color}`}
style={glow ? { filter: glow } : {}}
className="relative flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg transition-all text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5"
title="9Remote"
>
<span className={`material-symbols-outlined text-[18px]${isPulsing ? " animate-pulse" : ""}`}>
computer
</span>
<span className="material-symbols-outlined text-[18px]">computer</span>
<span className="text-xs font-medium">Remote</span>
</button>
<NineRemoteModal
isOpen={isOpen}
onClose={handleClose}
onInstalled={() => setInstalled(true)}
/>
<NineRemotePromoModal isOpen={isOpen} onClose={() => setIsOpen(false)} />
</>
);
}

View File

@@ -0,0 +1,103 @@
"use client";
import { useEffect } from "react";
import { createPortal } from "react-dom";
const FEATURES = [
{ icon: "terminal", label: "Terminal", desc: "Full shell access" },
{ icon: "cast", label: "Desktop", desc: "Screen sharing" },
{ icon: "folder_open", label: "Files", desc: "Browse & edit files" },
];
const BULLETS = [
{ icon: "qr_code_scanner", text: "Scan QR to connect instantly" },
{ icon: "wifi_off", text: "No port forwarding needed" },
{ icon: "devices", text: "Works on any device" },
];
const NINE_REMOTE_URL = "https://9remote.cc";
export default function NineRemotePromoModal({ isOpen, onClose }) {
useEffect(() => {
if (!isOpen) return;
document.body.style.overflow = "hidden";
const onEsc = (e) => { if (e.key === "Escape") onClose(); };
document.addEventListener("keydown", onEsc);
return () => { document.body.style.overflow = ""; document.removeEventListener("keydown", onEsc); };
}, [isOpen, onClose]);
if (!isOpen) return null;
return createPortal(
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
<div className="relative w-full max-w-sm rounded-xl overflow-hidden shadow-2xl animate-in fade-in zoom-in-95 duration-200 flex flex-col bg-surface border border-black/10 dark:border-white/10">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-black/5 dark:border-white/5">
<div className="flex items-center gap-3">
<div className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ background: "#FF570A" }}>
<span className="material-symbols-outlined text-white text-base">terminal</span>
</div>
<span className="text-xs font-bold uppercase tracking-wider" style={{ fontFamily: "monospace", color: "#FF570A" }}>9Remote</span>
</div>
<button
onClick={onClose}
className="w-7 h-7 flex items-center justify-center rounded-lg bg-black/5 dark:bg-white/5 border border-black/5 dark:border-white/10 text-text-muted hover:text-text-main transition-colors"
>
<span className="material-symbols-outlined text-base">close</span>
</button>
</div>
{/* Body */}
<div className="px-7 py-7 pb-9 flex flex-col gap-6">
{/* Hero */}
<div className="flex flex-col items-center gap-2 text-center mt-2">
<div
className="w-14 h-14 rounded-2xl flex items-center justify-center mb-1"
style={{ background: "#FF570A", boxShadow: "rgba(255,87,10,0.35) 0px 8px 32px" }}
>
<span className="material-symbols-outlined text-white" style={{ fontSize: 30 }}>terminal</span>
</div>
<h1 className="text-lg font-bold text-text-main tracking-tight">9Remote</h1>
<p className="text-xs text-text-muted leading-5 max-w-[220px]">
Access your terminal, desktop &amp; files from anywhere
</p>
</div>
{/* Feature cards */}
<div className="flex gap-2 w-full">
{FEATURES.map(({ icon, label, desc }) => (
<div key={label} className="flex-1 flex flex-col items-center gap-1.5 py-4 px-1 rounded-xl border border-black/10 dark:border-white/10 bg-bg-alt">
<span className="material-symbols-outlined" style={{ fontSize: 22, color: "#ff6e33" }}>{icon}</span>
<p className="text-xs font-semibold text-text-main">{label}</p>
<p className="text-[10px] text-text-muted text-center leading-4">{desc}</p>
</div>
))}
</div>
{/* Bullets */}
<div className="flex flex-col gap-3 w-full">
{BULLETS.map(({ icon, text }) => (
<div key={icon} className="flex items-center gap-2.5">
<span className="material-symbols-outlined flex-shrink-0" style={{ fontSize: 16, color: "#ff6e33" }}>{icon}</span>
<span className="text-xs text-text-muted">{text}</span>
</div>
))}
</div>
{/* CTA */}
<button
onClick={() => window.open(NINE_REMOTE_URL, "_blank")}
className="w-full py-3.5 flex items-center justify-center gap-2 text-sm font-semibold text-white rounded-xl hover:opacity-90 active:scale-[0.98] transition-all"
style={{ background: "#FF570A", boxShadow: "0 4px 16px rgba(255,87,10,0.35)" }}
>
<span className="material-symbols-outlined text-base">open_in_new</span>
Get 9Remote
</button>
</div>
</div>
</div>,
document.body
);
}

File diff suppressed because it is too large Load Diff