mirror of
https://github.com/Finesssee/ProxyPilot.git
synced 2026-11-18 18:04:20 +00:00
chore: finalize upstream CLIProxyAPI v6.9.5 sync
This commit is contained in:
+1
-1
@@ -1 +1 @@
|
||||
v6.9.1
|
||||
v6.9.5
|
||||
|
||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"project": "ProxyPilot",
|
||||
"version": "0.3.0",
|
||||
"upstream": "CLIProxyAPI v6.9.1",
|
||||
"upstream": "CLIProxyAPI v6.9.5",
|
||||
"features": [
|
||||
{
|
||||
"id": 1,
|
||||
|
||||
+14
-2
@@ -1,7 +1,9 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Activity, BarChart3, Database, GitBranch, Key, ScrollText, Terminal } from 'lucide-react'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { Toaster } from 'sonner'
|
||||
import { ProxyProvider, useProxyContext } from '@/hooks/useProxyContext'
|
||||
import { ProxyProvider } from '@/hooks/ProxyProvider'
|
||||
import { useProxyContext } from '@/hooks/useProxyContext'
|
||||
import {
|
||||
EngineControl,
|
||||
ProviderLogins,
|
||||
@@ -21,10 +23,20 @@ import {
|
||||
import { Header } from '@/components/layout/Header'
|
||||
import { StatusBar } from '@/components/layout/StatusBar'
|
||||
import { UpdateBanner } from '@/components/layout/UpdateBanner'
|
||||
import { IconRail, navigationItems } from '@/components/ui/icon-rail'
|
||||
import { IconRail } from '@/components/ui/icon-rail'
|
||||
|
||||
type ViewId = 'command' | 'providers' | 'routing' | 'memory' | 'logs' | 'requests' | 'analytics'
|
||||
|
||||
const navigationItems = [
|
||||
{ id: 'command', icon: Terminal, label: 'Command', color: 'var(--accent-primary)', shortcut: 'Ctrl+1' },
|
||||
{ id: 'providers', icon: Key, label: 'Providers', color: 'var(--accent-glow)', shortcut: 'Ctrl+2' },
|
||||
{ id: 'routing', icon: GitBranch, label: 'Routing', color: 'var(--status-processing)', shortcut: 'Ctrl+3' },
|
||||
{ id: 'memory', icon: Database, label: 'Memory', color: 'var(--accent-secondary)', shortcut: 'Ctrl+4' },
|
||||
{ id: 'logs', icon: ScrollText, label: 'Logs', color: 'var(--text-secondary)', shortcut: 'Ctrl+5' },
|
||||
{ id: 'requests', icon: Activity, label: 'Monitor', color: 'var(--accent-glow)', shortcut: 'Ctrl+6' },
|
||||
{ id: 'analytics', icon: BarChart3, label: 'Analytics', color: 'var(--accent-primary)', shortcut: 'Ctrl+7' },
|
||||
]
|
||||
|
||||
function DashboardContent() {
|
||||
const { status, isDesktop, mgmtKey } = useProxyContext()
|
||||
const [activeView, setActiveView] = useState<ViewId>('command')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { useProxyContext } from '@/hooks/useProxyContext'
|
||||
import { Loader2, Users, Zap, Activity, RefreshCw, Clock } from 'lucide-react'
|
||||
@@ -203,7 +203,7 @@ export function AccountUsage() {
|
||||
|
||||
const isRunning = status?.running ?? false
|
||||
|
||||
const fetchData = async () => {
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!isRunning) {
|
||||
setAccounts([])
|
||||
setLoading(false)
|
||||
@@ -220,13 +220,20 @@ export function AccountUsage() {
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [isRunning, mgmtFetch])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
const interval = setInterval(fetchData, 30000)
|
||||
return () => clearInterval(interval)
|
||||
}, [isRunning])
|
||||
const timer = setTimeout(() => {
|
||||
void fetchData()
|
||||
}, 0)
|
||||
const interval = setInterval(() => {
|
||||
void fetchData()
|
||||
}, 30000)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [fetchData])
|
||||
|
||||
// Calculate max tokens for relative bar sizing
|
||||
const maxTotalTokens = Math.max(
|
||||
|
||||
@@ -16,6 +16,10 @@ interface Agent {
|
||||
config_path?: string
|
||||
}
|
||||
|
||||
interface AgentsResponse {
|
||||
agents?: Agent[]
|
||||
}
|
||||
|
||||
export function AgentSetup() {
|
||||
const { mgmtFetch, showToast, status, isMgmtLoading, pp_detect_agents, pp_configure_agent, pp_unconfigure_agent, isDesktop } = useProxyContext()
|
||||
const [agents, setAgents] = useState<Agent[]>([])
|
||||
@@ -31,9 +35,9 @@ export function AgentSetup() {
|
||||
try {
|
||||
let data: Agent[] = []
|
||||
if (isDesktop && pp_detect_agents) {
|
||||
data = await pp_detect_agents()
|
||||
data = await pp_detect_agents() as Agent[]
|
||||
} else {
|
||||
const res = await mgmtFetch('/v0/management/agents')
|
||||
const res = await mgmtFetch('/v0/management/agents') as AgentsResponse
|
||||
data = res.agents || []
|
||||
}
|
||||
setAgents(data)
|
||||
@@ -47,11 +51,18 @@ export function AgentSetup() {
|
||||
|
||||
useEffect(() => {
|
||||
if (isRunning) {
|
||||
fetchAgents()
|
||||
const timer = setTimeout(() => {
|
||||
void fetchAgents()
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
} else {
|
||||
setAgents([])
|
||||
const timer = setTimeout(() => {
|
||||
setAgents([])
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isRunning, fetchAgents])
|
||||
return undefined
|
||||
}, [fetchAgents, isRunning])
|
||||
|
||||
const copyToClipboard = (text: string, label: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useProxyContext, EngineOfflineError } from '@/hooks/useProxyContext'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -10,7 +10,7 @@ export function ConfigEditor() {
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const isRunning = status?.running ?? false
|
||||
|
||||
const fetchConfig = async () => {
|
||||
const fetchConfig = useCallback(async () => {
|
||||
try {
|
||||
const data = await mgmtFetch('/v0/management/config.yaml')
|
||||
setConfigYaml(typeof data === 'string' ? data : JSON.stringify(data, null, 2))
|
||||
@@ -19,7 +19,7 @@ export function ConfigEditor() {
|
||||
showToast(e instanceof Error ? e.message : String(e), 'error')
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [mgmtFetch, showToast])
|
||||
|
||||
const saveConfig = async () => {
|
||||
setIsSaving(true)
|
||||
@@ -39,9 +39,13 @@ export function ConfigEditor() {
|
||||
|
||||
useEffect(() => {
|
||||
if (isRunning) {
|
||||
fetchConfig()
|
||||
const timer = setTimeout(() => {
|
||||
void fetchConfig()
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isRunning])
|
||||
return undefined
|
||||
}, [fetchConfig, isRunning])
|
||||
|
||||
return (
|
||||
<Card className="backdrop-blur-sm bg-card/60 border-border/50 shadow-xl overflow-hidden">
|
||||
|
||||
@@ -49,7 +49,10 @@ export function EngineControl() {
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
startTimeRef.current = null;
|
||||
setUptime(0);
|
||||
const timer = setTimeout(() => {
|
||||
setUptime(0);
|
||||
}, 0);
|
||||
return () => clearTimeout(timer);
|
||||
}, [isRunning]);
|
||||
|
||||
const handleCopyUrl = async () => {
|
||||
|
||||
@@ -8,10 +8,15 @@ interface Integration {
|
||||
id: string
|
||||
name?: string
|
||||
detected: boolean
|
||||
installed?: boolean
|
||||
binary_path?: string
|
||||
config_path?: string
|
||||
}
|
||||
|
||||
interface IntegrationsResponse {
|
||||
integrations?: Integration[]
|
||||
}
|
||||
|
||||
export function Integrations() {
|
||||
const { mgmtKey, mgmtFetch, showToast, status, isMgmtLoading } = useProxyContext()
|
||||
const [integrations, setIntegrations] = useState<Integration[]>([])
|
||||
@@ -25,11 +30,11 @@ export function Integrations() {
|
||||
setLoading(true)
|
||||
setScanKey(prev => prev + 1)
|
||||
try {
|
||||
const data = await mgmtFetch('/v0/management/integrations/status')
|
||||
const data = await mgmtFetch('/v0/management/integrations/status') as IntegrationsResponse
|
||||
// Map 'installed' from API to 'detected' for UI
|
||||
const mapped = (data.integrations || []).map((i: any) => ({
|
||||
...i,
|
||||
detected: i.installed ?? i.detected ?? false,
|
||||
const mapped = (data.integrations || []).map((integration) => ({
|
||||
...integration,
|
||||
detected: integration.installed ?? integration.detected ?? false,
|
||||
}))
|
||||
setIntegrations(mapped)
|
||||
} catch (e) {
|
||||
@@ -56,10 +61,17 @@ export function Integrations() {
|
||||
|
||||
useEffect(() => {
|
||||
if (mgmtKey && isRunning) {
|
||||
fetchIntegrations()
|
||||
const timer = setTimeout(() => {
|
||||
void fetchIntegrations()
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
} else if (!isRunning) {
|
||||
setIntegrations([])
|
||||
const timer = setTimeout(() => {
|
||||
setIntegrations([])
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
return undefined
|
||||
}, [mgmtKey, isRunning, fetchIntegrations])
|
||||
|
||||
const truncatePath = (path: string, maxLen: number = 35) => {
|
||||
|
||||
@@ -51,6 +51,18 @@ interface ParsedEvent {
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface MemoryEventRecord {
|
||||
ts?: string;
|
||||
kind?: string;
|
||||
role?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
interface MemoryAnchorRecord {
|
||||
ts?: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
const downloadBlob = (blob: Blob, filename: string) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
@@ -240,11 +252,11 @@ export function MemoryManager() {
|
||||
setMemoryEvents([])
|
||||
return
|
||||
}
|
||||
const parsed: ParsedEvent[] = events.map((e: any) => ({
|
||||
ts: e.ts || '',
|
||||
kind: e.kind || '',
|
||||
role: e.role || '',
|
||||
text: (e.text || '').toString(),
|
||||
const parsed: ParsedEvent[] = events.map((event: MemoryEventRecord) => ({
|
||||
ts: event.ts || '',
|
||||
kind: event.kind || '',
|
||||
role: event.role || '',
|
||||
text: (event.text || '').toString(),
|
||||
}))
|
||||
setMemoryEvents(parsed)
|
||||
} catch (e) {
|
||||
@@ -267,9 +279,9 @@ export function MemoryManager() {
|
||||
setMemoryAnchors([])
|
||||
return
|
||||
}
|
||||
const parsed: ParsedAnchor[] = anchors.map((a: any) => ({
|
||||
ts: a.ts || '',
|
||||
summary: (a.summary || '').toString(),
|
||||
const parsed: ParsedAnchor[] = anchors.map((anchor: MemoryAnchorRecord) => ({
|
||||
ts: anchor.ts || '',
|
||||
summary: (anchor.summary || '').toString(),
|
||||
}))
|
||||
setMemoryAnchors(parsed)
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useProxyContext, EngineOfflineError } from '@/hooks/useProxyContext'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -10,6 +10,13 @@ interface ModelMapping {
|
||||
provider: string
|
||||
}
|
||||
|
||||
interface ModelMappingsResponse {
|
||||
mappings?: ModelMapping[]
|
||||
model?: string
|
||||
to?: string
|
||||
provider?: string
|
||||
}
|
||||
|
||||
const PROVIDERS = ['anthropic', 'google', 'openai', 'azure', 'bedrock', 'vertex', 'other'] as const
|
||||
|
||||
function getProviderColor(provider: string): string {
|
||||
@@ -45,16 +52,16 @@ export function ModelMappings() {
|
||||
|
||||
const isRunning = status?.running ?? false
|
||||
|
||||
const fetchModelMappings = async () => {
|
||||
const fetchModelMappings = useCallback(async () => {
|
||||
try {
|
||||
const data = await mgmtFetch('/v0/management/model-mappings')
|
||||
const data = await mgmtFetch('/v0/management/model-mappings') as ModelMappingsResponse
|
||||
setModelMappings(data.mappings || [])
|
||||
} catch (e) {
|
||||
if (!(e instanceof EngineOfflineError)) {
|
||||
console.error('Failed to fetch model mappings:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [mgmtFetch])
|
||||
|
||||
const addModelMapping = async () => {
|
||||
if (!newMapping.from.trim() || !newMapping.to.trim()) {
|
||||
@@ -116,24 +123,33 @@ export function ModelMappings() {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await mgmtFetch(`/v0/management/model-mappings/test?model=${encodeURIComponent(mappingTestInput.trim())}`)
|
||||
const data = await mgmtFetch(
|
||||
`/v0/management/model-mappings/test?model=${encodeURIComponent(mappingTestInput.trim())}`,
|
||||
) as ModelMappingsResponse
|
||||
setMappingTestResult({
|
||||
model: data.model || data.to || mappingTestInput,
|
||||
provider: data.provider,
|
||||
matched: data.model !== mappingTestInput || !!data.provider
|
||||
})
|
||||
} catch (e) {
|
||||
} catch {
|
||||
setMappingTestResult({ matched: false })
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (mgmtKey && isRunning) {
|
||||
fetchModelMappings()
|
||||
const timer = setTimeout(() => {
|
||||
void fetchModelMappings()
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
} else if (!isRunning) {
|
||||
setModelMappings([])
|
||||
const timer = setTimeout(() => {
|
||||
setModelMappings([])
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [mgmtKey, isRunning])
|
||||
return undefined
|
||||
}, [fetchModelMappings, isRunning, mgmtKey])
|
||||
|
||||
if (!mgmtKey) {
|
||||
return null
|
||||
|
||||
@@ -214,6 +214,14 @@ interface AuthFileInfo {
|
||||
usage?: UsageStats
|
||||
}
|
||||
|
||||
interface ManagementConfig {
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
interface AuthFilesResponse {
|
||||
files?: AuthFileInfo[]
|
||||
}
|
||||
|
||||
function formatTokens(n?: number): string {
|
||||
if (!n || n === 0) return '—'
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
|
||||
@@ -239,7 +247,7 @@ export function ProviderLogins() {
|
||||
const [privateOAuth, setPrivateOAuth] = useState(false)
|
||||
const [showConfig, setShowConfig] = useState(false)
|
||||
const [authFileList, setAuthFileList] = useState<AuthFileInfo[]>([])
|
||||
const [mgmtConfig, setMgmtConfig] = useState<any>(null)
|
||||
const [mgmtConfig, setMgmtConfig] = useState<ManagementConfig | null>(null)
|
||||
|
||||
const isRunning = status?.running ?? false
|
||||
|
||||
@@ -275,9 +283,9 @@ export function ProviderLogins() {
|
||||
if (!mgmtKey || !isRunning) return
|
||||
;(async () => {
|
||||
try {
|
||||
const cfg = await mgmtFetch('/v0/management/config')
|
||||
const cfg = await mgmtFetch('/v0/management/config') as ManagementConfig
|
||||
setMgmtConfig(cfg)
|
||||
const res = await mgmtFetch('/v0/management/auth-files')
|
||||
const res = await mgmtFetch('/v0/management/auth-files') as AuthFilesResponse
|
||||
setAuthFileList(res.files || [])
|
||||
} catch (e) {
|
||||
if (!(e instanceof EngineOfflineError)) {
|
||||
@@ -285,7 +293,7 @@ export function ProviderLogins() {
|
||||
}
|
||||
}
|
||||
})()
|
||||
}, [mgmtKey, isRunning])
|
||||
}, [isRunning, mgmtFetch, mgmtKey])
|
||||
|
||||
const handlePrivateOAuthChange = async (checked: boolean) => {
|
||||
try {
|
||||
|
||||
@@ -48,6 +48,21 @@ interface HistoryStats {
|
||||
direct_api_cost: number
|
||||
savings: number
|
||||
savings_percent: number
|
||||
by_model?: Record<string, number>
|
||||
by_provider?: Record<string, number>
|
||||
}
|
||||
|
||||
interface LiveRequestsResponse {
|
||||
requests?: RequestLogEntry[]
|
||||
}
|
||||
|
||||
interface RequestHistoryResponse {
|
||||
entries?: RequestLogEntry[]
|
||||
total?: number
|
||||
}
|
||||
|
||||
interface RequestHistoryStatsResponse {
|
||||
stats?: HistoryStats | null
|
||||
}
|
||||
|
||||
type ViewMode = 'live' | 'history'
|
||||
@@ -83,9 +98,9 @@ export function RequestMonitor() {
|
||||
try {
|
||||
let data: RequestLogEntry[] = []
|
||||
if (window.pp_get_requests) {
|
||||
data = await window.pp_get_requests()
|
||||
data = await window.pp_get_requests() as RequestLogEntry[]
|
||||
} else {
|
||||
const res = await mgmtFetch('/v0/management/requests')
|
||||
const res = await mgmtFetch('/v0/management/requests') as LiveRequestsResponse
|
||||
data = res.requests || []
|
||||
}
|
||||
setRequests([...data].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()))
|
||||
@@ -123,12 +138,12 @@ export function RequestMonitor() {
|
||||
params.set('errors_only', 'true')
|
||||
}
|
||||
|
||||
const res = await mgmtFetch(`/v0/management/request-history?${params.toString()}`)
|
||||
const res = await mgmtFetch(`/v0/management/request-history?${params.toString()}`) as RequestHistoryResponse
|
||||
setRequests(res.entries || [])
|
||||
setTotalCount(res.total || 0)
|
||||
|
||||
// Also fetch stats
|
||||
const statsRes = await mgmtFetch('/v0/management/request-history/stats')
|
||||
const statsRes = await mgmtFetch('/v0/management/request-history/stats') as RequestHistoryStatsResponse
|
||||
setHistoryStats(statsRes.stats || null)
|
||||
|
||||
// Extract unique models and providers from stats
|
||||
@@ -212,12 +227,15 @@ export function RequestMonitor() {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (viewMode === 'live') {
|
||||
fetchLiveRequests()
|
||||
} else {
|
||||
fetchHistory()
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
if (viewMode === 'live') {
|
||||
void fetchLiveRequests()
|
||||
} else {
|
||||
void fetchHistory()
|
||||
}
|
||||
}, 0)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
if (liveIntervalRef.current) {
|
||||
clearInterval(liveIntervalRef.current)
|
||||
}
|
||||
@@ -226,7 +244,10 @@ export function RequestMonitor() {
|
||||
|
||||
// Reset page when filters change
|
||||
useEffect(() => {
|
||||
setPage(1)
|
||||
const timer = setTimeout(() => {
|
||||
setPage(1)
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}, [filterModel, filterProvider, filterStatus, filterStartDate, filterEndDate])
|
||||
|
||||
const getStatusColor = (code: number) => {
|
||||
|
||||
@@ -31,6 +31,14 @@ interface SemanticItem {
|
||||
text?: string
|
||||
}
|
||||
|
||||
interface SemanticNamespacesResponse {
|
||||
namespaces?: SemanticNamespace[]
|
||||
}
|
||||
|
||||
interface SemanticItemsResponse {
|
||||
items?: SemanticItem[]
|
||||
}
|
||||
|
||||
export function SemanticMemory() {
|
||||
const { mgmtKey, mgmtFetch, showToast, status, isMgmtLoading } = useProxyContext()
|
||||
|
||||
@@ -55,7 +63,7 @@ export function SemanticMemory() {
|
||||
|
||||
const loadSemanticNamespaces = useCallback(async () => {
|
||||
try {
|
||||
const res = await mgmtFetch('/v0/management/semantic/namespaces')
|
||||
const res = await mgmtFetch('/v0/management/semantic/namespaces') as SemanticNamespacesResponse
|
||||
const namespaces = res.namespaces || []
|
||||
setSemanticNamespaces(namespaces)
|
||||
if (!semanticNamespace && namespaces.length > 0) {
|
||||
@@ -76,7 +84,7 @@ export function SemanticMemory() {
|
||||
try {
|
||||
const res = await mgmtFetch(
|
||||
`/v0/management/semantic/items?namespace=${encodeURIComponent(semanticNamespace)}&limit=${encodeURIComponent(semanticLimit)}`
|
||||
)
|
||||
) as SemanticItemsResponse
|
||||
const items: SemanticItem[] = res.items || []
|
||||
if (!Array.isArray(items) || items.length === 0) {
|
||||
setSemanticItems('No items.')
|
||||
@@ -100,14 +108,21 @@ export function SemanticMemory() {
|
||||
// Load initial data when mgmtKey is available
|
||||
useEffect(() => {
|
||||
if (mgmtKey && isRunning) {
|
||||
loadSemanticHealth()
|
||||
loadSemanticNamespaces()
|
||||
const timer = setTimeout(() => {
|
||||
void loadSemanticHealth()
|
||||
void loadSemanticNamespaces()
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
} else if (!isRunning) {
|
||||
setSemanticHealth(null)
|
||||
setSemanticNamespaces([])
|
||||
setSemanticItems('')
|
||||
const timer = setTimeout(() => {
|
||||
setSemanticHealth(null)
|
||||
setSemanticNamespaces([])
|
||||
setSemanticItems('')
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [mgmtKey, isRunning, loadSemanticHealth, loadSemanticNamespaces])
|
||||
return undefined
|
||||
}, [isRunning, loadSemanticHealth, loadSemanticNamespaces, mgmtKey])
|
||||
|
||||
if (!mgmtKey) {
|
||||
return null
|
||||
|
||||
@@ -75,9 +75,13 @@ export function ThinkingBudgetSettings() {
|
||||
|
||||
useEffect(() => {
|
||||
if (isRunning) {
|
||||
fetchData()
|
||||
const timer = setTimeout(() => {
|
||||
void fetchData()
|
||||
}, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [isRunning, fetchData])
|
||||
return undefined
|
||||
}, [fetchData, isRunning])
|
||||
|
||||
const handleModeChange = (mode: string) => {
|
||||
setSelectedMode(mode)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { useProxyContext } from '@/hooks/useProxyContext'
|
||||
import { Loader2, BarChart3, Activity, Zap, DollarSign, PieChart, TrendingDown, Sparkles } from 'lucide-react'
|
||||
@@ -30,19 +30,39 @@ interface UsageData {
|
||||
daily: DailyUsage[]
|
||||
}
|
||||
|
||||
interface UsageSource extends Partial<UsageData> {
|
||||
totalRequests?: number
|
||||
successCount?: number
|
||||
failureCount?: number
|
||||
totalInputTokens?: number
|
||||
totalOutputTokens?: number
|
||||
estimatedCostSaved?: number
|
||||
actualCost?: number
|
||||
directApiCost?: number
|
||||
savingsPercent?: number
|
||||
byModel?: Record<string, number>
|
||||
byProvider?: Record<string, number>
|
||||
costByModel?: Record<string, number>
|
||||
costByProvider?: Record<string, number>
|
||||
}
|
||||
|
||||
interface UsageResponse extends UsageSource {
|
||||
usage?: UsageSource
|
||||
}
|
||||
|
||||
export function UsageStats() {
|
||||
const { mgmtFetch } = useProxyContext()
|
||||
const [data, setData] = useState<UsageData | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const fetchData = async () => {
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
let result: any
|
||||
let result: UsageResponse | null = null
|
||||
if (window.pp_get_usage) {
|
||||
result = await window.pp_get_usage()
|
||||
result = await window.pp_get_usage() as UsageResponse
|
||||
} else if (mgmtFetch) {
|
||||
result = await mgmtFetch('/v0/management/usage')
|
||||
result = await mgmtFetch('/v0/management/usage') as UsageResponse
|
||||
} else {
|
||||
throw new Error('No method available to fetch usage data')
|
||||
}
|
||||
@@ -76,13 +96,20 @@ export function UsageStats() {
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [mgmtFetch])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
const interval = setInterval(fetchData, 30000) // Refresh every 30s
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
const timer = setTimeout(() => {
|
||||
void fetchData()
|
||||
}, 0)
|
||||
const interval = setInterval(() => {
|
||||
void fetchData()
|
||||
}, 30000)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [fetchData])
|
||||
|
||||
if (loading && !data) {
|
||||
return (
|
||||
@@ -115,7 +142,7 @@ export function UsageStats() {
|
||||
|
||||
const maxDailyRequests = Math.max(...data.daily.map((d) => d.requests), 1)
|
||||
const providerEntries = Object.entries(data.by_provider).sort((a, b) => b[1] - a[1])
|
||||
const totalProviderRequests = providerEntries.reduce((acc, [_, count]) => acc + count, 0)
|
||||
const totalProviderRequests = providerEntries.reduce((acc, [, count]) => acc + count, 0)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
|
||||
@@ -98,4 +98,4 @@ function BadgeWithDot({
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, BadgeWithDot, badgeVariants };
|
||||
export { Badge, BadgeWithDot };
|
||||
|
||||
@@ -131,4 +131,4 @@ function Button({
|
||||
);
|
||||
}
|
||||
|
||||
export { Button, buttonVariants };
|
||||
export { Button };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Terminal, Key, GitBranch, Database, ScrollText, Activity, BarChart3, type LucideIcon } from 'lucide-react'
|
||||
import { type LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface IconRailItem {
|
||||
@@ -15,16 +15,6 @@ interface IconRailProps {
|
||||
onSelect: (id: string) => void
|
||||
}
|
||||
|
||||
export const navigationItems: IconRailItem[] = [
|
||||
{ id: 'command', icon: Terminal, label: 'Command', color: 'var(--accent-primary)', shortcut: 'Ctrl+1' },
|
||||
{ id: 'providers', icon: Key, label: 'Providers', color: 'var(--accent-glow)', shortcut: 'Ctrl+2' },
|
||||
{ id: 'routing', icon: GitBranch, label: 'Routing', color: 'var(--status-processing)', shortcut: 'Ctrl+3' },
|
||||
{ id: 'memory', icon: Database, label: 'Memory', color: 'var(--accent-secondary)', shortcut: 'Ctrl+4' },
|
||||
{ id: 'logs', icon: ScrollText, label: 'Logs', color: 'var(--text-secondary)', shortcut: 'Ctrl+5' },
|
||||
{ id: 'requests', icon: Activity, label: 'Monitor', color: 'var(--accent-glow)', shortcut: 'Ctrl+6' },
|
||||
{ id: 'analytics', icon: BarChart3, label: 'Analytics', color: 'var(--accent-primary)', shortcut: 'Ctrl+7' },
|
||||
]
|
||||
|
||||
export function IconRail({ items, activeId, onSelect }: IconRailProps) {
|
||||
return (
|
||||
<nav
|
||||
|
||||
@@ -179,4 +179,4 @@ const StatusBadge = React.forwardRef<
|
||||
})
|
||||
StatusBadge.displayName = "StatusBadge"
|
||||
|
||||
export { StatusIndicator, StatusBadge, statusColors, type StatusIndicatorProps, type StatusBadgeProps }
|
||||
export { StatusIndicator, StatusBadge, type StatusIndicatorProps, type StatusBadgeProps }
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { EngineOfflineError, ProxyContext, type ProxyStatus } from './useProxyContext'
|
||||
|
||||
const SERVICE_PREFLIGHT_CACHE_MS = 5000
|
||||
|
||||
export function ProxyProvider({ children }: { children: ReactNode }) {
|
||||
const [status, setStatus] = useState<ProxyStatus | null>(null)
|
||||
const statusRef = useRef<ProxyStatus | null>(null)
|
||||
const servicePreflightCacheRef = useRef<{ at: number; status: ProxyStatus } | null>(null)
|
||||
const [mgmtKey, setMgmtKey] = useState<string | null>(null)
|
||||
const [authFiles, setAuthFiles] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState<string | null>(null)
|
||||
const [isMgmtLoading, setIsMgmtLoading] = useState(false)
|
||||
const [retryDelay, setRetryDelay] = useState(1200)
|
||||
const [wasRunning, setWasRunning] = useState(false)
|
||||
const [userStopped, setUserStopped] = useState(false)
|
||||
const isDesktop = typeof window.pp_status === 'function'
|
||||
|
||||
const showToast = useCallback((message: string, type: 'success' | 'error' = 'success') => {
|
||||
if (type === 'success') {
|
||||
toast.success(message)
|
||||
return
|
||||
}
|
||||
toast.error(message)
|
||||
}, [])
|
||||
|
||||
const fetchServicePreflight = useCallback(async (force = false) => {
|
||||
const cached = servicePreflightCacheRef.current
|
||||
if (!force && cached && cached.status.running && Date.now() - cached.at < SERVICE_PREFLIGHT_CACHE_MS) {
|
||||
return cached.status
|
||||
}
|
||||
|
||||
let nextStatus: ProxyStatus
|
||||
if (window.pp_status) {
|
||||
nextStatus = await window.pp_status()
|
||||
} else {
|
||||
try {
|
||||
const res = await fetch('/healthz')
|
||||
if (!res.ok) {
|
||||
nextStatus = {
|
||||
running: false,
|
||||
port: 0,
|
||||
base_url: location.origin,
|
||||
last_error: res.statusText,
|
||||
}
|
||||
} else {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
nextStatus = {
|
||||
running: true,
|
||||
port: typeof body.port === 'number' ? body.port : 0,
|
||||
base_url: location.origin,
|
||||
last_error: '',
|
||||
}
|
||||
}
|
||||
} catch (fetchErr) {
|
||||
nextStatus = {
|
||||
running: false,
|
||||
port: 0,
|
||||
base_url: location.origin,
|
||||
last_error: String(fetchErr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
servicePreflightCacheRef.current = nextStatus.running ? { at: Date.now(), status: nextStatus } : null
|
||||
return nextStatus
|
||||
}, [])
|
||||
|
||||
const refreshStatus = useCallback(async (force = false) => {
|
||||
try {
|
||||
const nextStatus = await fetchServicePreflight(force)
|
||||
setStatus(nextStatus)
|
||||
statusRef.current = nextStatus
|
||||
const isRunning = nextStatus.running
|
||||
|
||||
if (isRunning) {
|
||||
setWasRunning(true)
|
||||
setUserStopped(false)
|
||||
setRetryDelay(1200)
|
||||
if (mgmtKey) {
|
||||
try {
|
||||
const headers = { 'X-Management-Key': mgmtKey }
|
||||
const res = await fetch('/v0/management/auth-files', { headers })
|
||||
if (res.ok) {
|
||||
const files = await res.json()
|
||||
if (Array.isArray(files)) {
|
||||
setAuthFiles(files.filter((file): file is string => typeof file === 'string'))
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Auth files error:', error)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (wasRunning && !userStopped && isDesktop && window.pp_start) {
|
||||
console.log('Unexpected stop detected, attempting auto-reconnect...')
|
||||
window.pp_start().catch(error => console.error('Auto-reconnect failed:', error))
|
||||
}
|
||||
setAuthFiles([])
|
||||
setRetryDelay(prev => Math.min(prev * 1.5, 10000))
|
||||
} catch (error) {
|
||||
console.error('Status error:', error)
|
||||
setRetryDelay(prev => Math.min(prev * 1.5, 10000))
|
||||
}
|
||||
}, [fetchServicePreflight, isDesktop, mgmtKey, userStopped, wasRunning])
|
||||
|
||||
const mgmtFetch = useCallback(async (path: string, opts: RequestInit = {}) => {
|
||||
const currentStatus = statusRef.current
|
||||
if (!currentStatus?.running) {
|
||||
throw new EngineOfflineError()
|
||||
}
|
||||
if (!mgmtKey) {
|
||||
throw new Error('Missing management key')
|
||||
}
|
||||
|
||||
setIsMgmtLoading(true)
|
||||
try {
|
||||
const headers = Object.assign({}, opts.headers || {}, { 'X-Management-Key': mgmtKey })
|
||||
const res = await fetch(path, { ...opts, headers })
|
||||
const contentType = (res.headers.get('content-type') || '').toLowerCase()
|
||||
const body = contentType.includes('application/json') ? await res.json() : await res.text()
|
||||
if (!res.ok) {
|
||||
const latestStatus = statusRef.current
|
||||
if (res.status === 404 && (!latestStatus || !latestStatus.running)) {
|
||||
throw new EngineOfflineError()
|
||||
}
|
||||
const message =
|
||||
typeof body === 'string'
|
||||
? body
|
||||
: typeof body?.error === 'string'
|
||||
? body.error
|
||||
: JSON.stringify(body)
|
||||
throw new Error(`${res.status} ${res.statusText}: ${message}`)
|
||||
}
|
||||
return body
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError) {
|
||||
throw new EngineOfflineError()
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
setIsMgmtLoading(false)
|
||||
}
|
||||
}, [mgmtKey])
|
||||
|
||||
const handleAction = useCallback(async (
|
||||
action: (() => Promise<void>) | undefined,
|
||||
actionId: string,
|
||||
successMsg: string,
|
||||
) => {
|
||||
if (!action) {
|
||||
return
|
||||
}
|
||||
if (actionId === 'stop') {
|
||||
setUserStopped(true)
|
||||
}
|
||||
if (actionId === 'start' || actionId === 'restart') {
|
||||
setUserStopped(false)
|
||||
}
|
||||
setLoading(actionId)
|
||||
try {
|
||||
await action()
|
||||
showToast(successMsg, 'success')
|
||||
await refreshStatus(true)
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : String(error), 'error')
|
||||
} finally {
|
||||
setLoading(null)
|
||||
}
|
||||
}, [refreshStatus, showToast])
|
||||
|
||||
useEffect(() => {
|
||||
refreshStatus()
|
||||
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined
|
||||
const scheduleRefresh = () => {
|
||||
timeoutId = setTimeout(async () => {
|
||||
await refreshStatus()
|
||||
scheduleRefresh()
|
||||
}, retryDelay)
|
||||
}
|
||||
scheduleRefresh()
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
if (window.pp_get_management_key) {
|
||||
const key = await window.pp_get_management_key()
|
||||
setMgmtKey(key)
|
||||
return
|
||||
}
|
||||
if (!isDesktop) {
|
||||
const meta = document.querySelector('meta[name="pp-mgmt-key"]')
|
||||
setMgmtKey(meta ? meta.getAttribute('content') : null)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Management key error:', error)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
}
|
||||
}, [isDesktop, refreshStatus, retryDelay])
|
||||
|
||||
return (
|
||||
<ProxyContext.Provider
|
||||
value={{
|
||||
status,
|
||||
isDesktop,
|
||||
mgmtKey,
|
||||
authFiles,
|
||||
loading,
|
||||
isMgmtLoading,
|
||||
setLoading,
|
||||
refreshStatus,
|
||||
showToast,
|
||||
mgmtFetch,
|
||||
handleAction,
|
||||
pp_get_usage: window.pp_get_usage,
|
||||
pp_detect_agents: window.pp_detect_agents,
|
||||
pp_configure_agent: window.pp_configure_agent,
|
||||
pp_unconfigure_agent: window.pp_unconfigure_agent,
|
||||
pp_check_updates: window.pp_check_updates,
|
||||
pp_download_update: window.pp_download_update,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ProxyContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createContext, useContext, useEffect, useState, useCallback, useRef } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { createContext, useContext } from 'react'
|
||||
|
||||
type JsonPayload = Awaited<ReturnType<Response['json']>>
|
||||
|
||||
// Type declarations for desktop app bindings
|
||||
declare global {
|
||||
@@ -18,12 +18,12 @@ declare global {
|
||||
pp_oauth?: (provider: string) => Promise<void>;
|
||||
pp_copy_diagnostics?: () => Promise<void>;
|
||||
pp_get_management_key?: () => Promise<string>;
|
||||
pp_get_requests?: () => Promise<any>;
|
||||
pp_get_usage?: () => Promise<any>;
|
||||
pp_detect_agents?: () => Promise<any[]>;
|
||||
pp_get_requests?: () => Promise<JsonPayload>;
|
||||
pp_get_usage?: () => Promise<JsonPayload>;
|
||||
pp_detect_agents?: () => Promise<Array<JsonPayload>>;
|
||||
pp_configure_agent?: (agentId: string) => Promise<void>;
|
||||
pp_unconfigure_agent?: (agentId: string) => Promise<void>;
|
||||
pp_check_updates?: () => Promise<any>;
|
||||
pp_check_updates?: () => Promise<JsonPayload>;
|
||||
pp_download_update?: (url: string) => Promise<void>;
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ export class EngineOfflineError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
interface ProxyContextType {
|
||||
export interface ProxyContextType {
|
||||
status: ProxyStatus | null;
|
||||
isDesktop: boolean;
|
||||
mgmtKey: string | null;
|
||||
@@ -53,235 +53,20 @@ interface ProxyContextType {
|
||||
setLoading: (id: string | null) => void;
|
||||
refreshStatus: () => Promise<void>;
|
||||
showToast: (message: string, type?: 'success' | 'error') => void;
|
||||
mgmtFetch: (path: string, opts?: RequestInit) => Promise<any>;
|
||||
mgmtFetch: (path: string, opts?: RequestInit) => Promise<JsonPayload | string>;
|
||||
handleAction: (action: (() => Promise<void>) | undefined, actionId: string, successMsg: string) => Promise<void>;
|
||||
pp_get_usage?: () => Promise<any>;
|
||||
pp_detect_agents?: () => Promise<any[]>;
|
||||
pp_get_usage?: () => Promise<JsonPayload>;
|
||||
pp_detect_agents?: () => Promise<Array<JsonPayload>>;
|
||||
pp_configure_agent?: (agentId: string) => Promise<void>;
|
||||
pp_unconfigure_agent?: (agentId: string) => Promise<void>;
|
||||
pp_check_updates?: () => Promise<any>;
|
||||
pp_check_updates?: () => Promise<JsonPayload>;
|
||||
pp_download_update?: (url: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const ProxyContext = createContext<ProxyContextType | null>(null)
|
||||
export const ProxyContext = createContext<ProxyContextType | null>(null)
|
||||
|
||||
export function useProxyContext() {
|
||||
const ctx = useContext(ProxyContext)
|
||||
if (!ctx) throw new Error('useProxyContext must be used within ProxyProvider')
|
||||
return ctx
|
||||
}
|
||||
|
||||
export function ProxyProvider({ children }: { children: ReactNode }) {
|
||||
const [status, setStatus] = useState<ProxyStatus | null>(null)
|
||||
const statusRef = useRef<ProxyStatus | null>(null)
|
||||
const servicePreflightCacheRef = useRef<{ at: number; status: ProxyStatus } | null>(null)
|
||||
const [mgmtKey, setMgmtKey] = useState<string | null>(null)
|
||||
const [authFiles, setAuthFiles] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState<string | null>(null)
|
||||
const [isMgmtLoading, setIsMgmtLoading] = useState(false)
|
||||
const [retryDelay, setRetryDelay] = useState(1200)
|
||||
const [wasRunning, setWasRunning] = useState(false)
|
||||
const [userStopped, setUserStopped] = useState(false)
|
||||
const SERVICE_PREFLIGHT_CACHE_MS = 5000
|
||||
|
||||
const isDesktop = typeof window.pp_status === 'function'
|
||||
|
||||
const showToast = useCallback((message: string, type: 'success' | 'error' = 'success') => {
|
||||
if (type === 'success') {
|
||||
toast.success(message)
|
||||
} else {
|
||||
toast.error(message)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fetchServicePreflight = useCallback(async (force = false) => {
|
||||
const cached = servicePreflightCacheRef.current
|
||||
if (!force && cached && cached.status.running && Date.now() - cached.at < SERVICE_PREFLIGHT_CACHE_MS) {
|
||||
return cached.status
|
||||
}
|
||||
|
||||
let nextStatus: ProxyStatus
|
||||
if (window.pp_status) {
|
||||
nextStatus = await window.pp_status()
|
||||
} else {
|
||||
try {
|
||||
const res = await fetch('/healthz')
|
||||
if (!res.ok) {
|
||||
nextStatus = {
|
||||
running: false,
|
||||
port: 0,
|
||||
base_url: location.origin,
|
||||
last_error: res.statusText,
|
||||
}
|
||||
} else {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
nextStatus = {
|
||||
running: true,
|
||||
port: body.port || 0,
|
||||
base_url: location.origin,
|
||||
last_error: '',
|
||||
}
|
||||
}
|
||||
} catch (fetchErr) {
|
||||
nextStatus = {
|
||||
running: false,
|
||||
port: 0,
|
||||
base_url: location.origin,
|
||||
last_error: String(fetchErr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
servicePreflightCacheRef.current = nextStatus.running
|
||||
? { at: Date.now(), status: nextStatus }
|
||||
: null
|
||||
|
||||
return nextStatus
|
||||
}, [SERVICE_PREFLIGHT_CACHE_MS])
|
||||
|
||||
const refreshStatus = useCallback(async (force = false) => {
|
||||
try {
|
||||
const s = await fetchServicePreflight(force)
|
||||
setStatus(s)
|
||||
statusRef.current = s
|
||||
const isRunning = s.running
|
||||
|
||||
if (isRunning) {
|
||||
setWasRunning(true)
|
||||
setUserStopped(false)
|
||||
setRetryDelay(1200) // Reset delay on success
|
||||
if (mgmtKey) {
|
||||
try {
|
||||
const headers = { 'X-Management-Key': mgmtKey }
|
||||
const res = await fetch('/v0/management/auth-files', { headers })
|
||||
if (res.ok) {
|
||||
const files = await res.json()
|
||||
if (Array.isArray(files)) {
|
||||
setAuthFiles(files)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Auth files error:', e)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (wasRunning && !userStopped && isDesktop && window.pp_start) {
|
||||
console.log('Unexpected stop detected, attempting auto-reconnect...')
|
||||
window.pp_start().catch(e => console.error('Auto-reconnect failed:', e))
|
||||
}
|
||||
setAuthFiles([])
|
||||
setRetryDelay(prev => Math.min(prev * 1.5, 10000)) // Increase delay on failure
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Status error:', e)
|
||||
setRetryDelay(prev => Math.min(prev * 1.5, 10000))
|
||||
}
|
||||
}, [fetchServicePreflight, mgmtKey, wasRunning, userStopped, isDesktop])
|
||||
|
||||
const mgmtFetch = useCallback(async (path: string, opts: RequestInit = {}) => {
|
||||
const currentStatus = statusRef.current
|
||||
if (!currentStatus?.running) {
|
||||
throw new EngineOfflineError()
|
||||
}
|
||||
if (!mgmtKey) throw new Error('Missing management key')
|
||||
|
||||
setIsMgmtLoading(true)
|
||||
try {
|
||||
const headers = Object.assign({}, opts.headers || {}, { 'X-Management-Key': mgmtKey })
|
||||
const res = await fetch(path, { ...opts, headers })
|
||||
const ct = (res.headers.get('content-type') || '').toLowerCase()
|
||||
const body = ct.includes('application/json') ? await res.json() : await res.text()
|
||||
if (!res.ok) {
|
||||
const latestStatus = statusRef.current
|
||||
if (res.status === 404 && (!latestStatus || !latestStatus.running)) {
|
||||
throw new EngineOfflineError()
|
||||
}
|
||||
const msg = typeof body === 'string' ? body : body?.error ? body.error : JSON.stringify(body)
|
||||
throw new Error(`${res.status} ${res.statusText}: ${msg}`)
|
||||
}
|
||||
return body
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError) {
|
||||
// Network error
|
||||
throw new EngineOfflineError()
|
||||
}
|
||||
throw e
|
||||
} finally {
|
||||
setIsMgmtLoading(false)
|
||||
}
|
||||
}, [mgmtKey])
|
||||
|
||||
const handleAction = useCallback(async (
|
||||
action: (() => Promise<void>) | undefined,
|
||||
actionId: string,
|
||||
successMsg: string
|
||||
) => {
|
||||
if (!action) return
|
||||
if (actionId === 'stop') setUserStopped(true)
|
||||
if (actionId === 'start' || actionId === 'restart') setUserStopped(false)
|
||||
setLoading(actionId)
|
||||
try {
|
||||
await action()
|
||||
showToast(successMsg, 'success')
|
||||
await refreshStatus(true)
|
||||
} catch (e) {
|
||||
showToast(e instanceof Error ? e.message : String(e), 'error')
|
||||
} finally {
|
||||
setLoading(null)
|
||||
}
|
||||
}, [showToast, refreshStatus])
|
||||
|
||||
// Initialize on mount
|
||||
useEffect(() => {
|
||||
refreshStatus()
|
||||
|
||||
let timeoutId: any
|
||||
const scheduleRefresh = () => {
|
||||
timeoutId = setTimeout(async () => {
|
||||
await refreshStatus()
|
||||
scheduleRefresh()
|
||||
}, retryDelay)
|
||||
}
|
||||
scheduleRefresh()
|
||||
|
||||
; (async () => {
|
||||
try {
|
||||
if (window.pp_get_management_key) {
|
||||
const key = await window.pp_get_management_key()
|
||||
setMgmtKey(key)
|
||||
} else if (!isDesktop) {
|
||||
const meta = document.querySelector('meta[name="pp-mgmt-key"]')
|
||||
setMgmtKey(meta ? meta.getAttribute('content') : null)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Management key error:', e)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => clearTimeout(timeoutId)
|
||||
}, [refreshStatus, isDesktop, retryDelay])
|
||||
|
||||
return (
|
||||
<ProxyContext.Provider value={{
|
||||
status,
|
||||
isDesktop,
|
||||
mgmtKey,
|
||||
authFiles,
|
||||
loading,
|
||||
isMgmtLoading,
|
||||
setLoading,
|
||||
refreshStatus,
|
||||
showToast,
|
||||
mgmtFetch,
|
||||
handleAction,
|
||||
pp_get_usage: window.pp_get_usage,
|
||||
pp_detect_agents: window.pp_detect_agents,
|
||||
pp_configure_agent: window.pp_configure_agent,
|
||||
pp_unconfigure_agent: window.pp_unconfigure_agent,
|
||||
pp_check_updates: window.pp_check_updates,
|
||||
pp_download_update: window.pp_download_update,
|
||||
}}>
|
||||
{children}
|
||||
</ProxyContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user