import { CopyBtn } from '../components/CopyBtn'; import { tr } from '../lib/i18n'; import { appBaseUrl } from '../lib/connect-urls'; import { deviceLabel, instanceLabel } from '../lib/runtime-models'; import { nativeRouting, useNative } from '../lib/native'; /** Connection facts first. Instructions and request details open only on demand. */ import { CloudflareDialog } from '../components/CloudflareDialog'; import { useEffect, useRef, useState } from 'react'; import { Btn, Dialog, Empty, Icon, IconBtn, Seg, Select, ErrorNotice } from '../components/ui'; import { Screen, SectionHead } from '../components/layout'; import { clockTime, duration, tokens } from '../lib/format'; import { cancelRequest, setLocalSharing, setServingAccess, useStore } from '../lib/store'; export function ServingScreen() { const serving = useStore(s => s.serving); const storedRuntime = useStore(s => s.runtime), hardware = useStore(s => s.hardware); const native = useNative(); const runtime = nativeRouting(native, hardware) ?? storedRuntime; const [modelFilter, setModelFilter] = useState('all'), [guideModel, setGuideModel] = useState(''); const [selectedId, setSelectedId] = useState(null); const [guide, setGuide] = useState(false); const [protocol, setProtocol] = useState<'openai' | 'responses' | 'anthropic'>('openai'); const [filter, setFilter] = useState<'all' | 'active' | 'done' | 'error'>('all'); const [query, setQuery] = useState(''); const [sort, setSort] = useState<'at' | 'durationMs'>('at'); const [cloudflareOpen, setCloudflareOpen] = useState(false); const [returnToTunnel, setReturnToTunnel] = useState(false); const [keyOpen, setKeyOpen] = useState(false); const [keyVisible, setKeyVisible] = useState(false); const [sharingOpen, setSharingOpen] = useState(false); const [generated, setGenerated] = useState(false); const [removeKeyOpen, setRemoveKeyOpen] = useState(false); const [keyDraft, setKeyDraft] = useState(''); const [pending, setPending] = useState(false); const [error, setError] = useState(''); function generateKey() { setKeyVisible(false); const bytes = crypto.getRandomValues(new Uint8Array(32)); setKeyDraft('sk-strata-' + Array.from(bytes, v => v.toString(16).padStart(2, '0')).join('')); setGenerated(true); } function closeKey() { setKeyVisible(false); setKeyOpen(false); setKeyDraft(''); if (returnToTunnel) { setReturnToTunnel(false); setCloudflareOpen(true); } } const selected = serving?.requests.find(r => r.id === selectedId); const requestedCancel = useRef(null); const cancelResult = useRef(null); useEffect(() => { if (selected?.id === requestedCancel.current && selected?.cancellable === false && cancelResult.current) { cancelResult.current.focus(); requestedCancel.current = null; } }, [selected?.id, selected?.cancellable]); if (!serving) return

{tr("Waiting for API status\u2026")}

; const multipleModels = (runtime?.instances.length ?? 0) > 1; const filterId = multipleModels && runtime?.instances.some(i => i.id === modelFilter) ? modelFilter : 'all'; const loaded = runtime?.instances.find(i => i.apiModelId === guideModel) ?? runtime?.instances.find(i => i.id === runtime.defaultId); const scopeRequests = filterId === 'all' ? serving.requests : serving.requests.filter(r => r.instanceId === filterId); const scopeStats = filterId === 'all' ? serving.stats : { running: scopeRequests.filter(r => r.state === 'generating').length, waiting: scopeRequests.filter(r => r.state === 'queued').length, completed: scopeRequests.filter(r => r.state === 'done').length }; const modelOptions = (runtime?.instances ?? []).map(i => ({ value: i.apiModelId, label: `${instanceLabel(i)} · ${deviceLabel(i.gpuIds, hardware)}` })); const requests = serving.requests.filter(r => (filterId === 'all' || r.instanceId === filterId) && (filter === 'all' || (filter === 'active' ? ['generating', 'queued'].includes(r.state) : r.state === filter)) && `${r.client} ${r.id} ${r.endpoint} ${r.model}`.toLowerCase().includes(query.toLowerCase())).sort((a, b) => sort === 'durationMs' ? b.durationMs - a.durationMs : b.at.localeCompare(a.at)); async function operation(action: () => Promise) { setPending(true); setError(''); try { await action(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setPending(false); } } // While sharing is on there are two addresses: the app's own, and the one other devices use on its own port (#4798). const twoAddresses = !!serving.sharing?.active && !!serving.sharing.url && !!serving.localUrl && serving.localUrl !== serving.sharing.url; const code = `curl ${serving.baseUrl}${protocol === 'responses' ? '/responses' : protocol === 'openai' ? serving.endpoints.openai : serving.endpoints.anthropic} \\\n -H 'Content-Type: application/json'${serving.access.apiKeySet ? " \\\n -H 'Authorization: Bearer YOUR_API_KEY'" : ''} \\\n -d '${JSON.stringify({ model: loaded?.apiModelId ?? 'YOUR_MODEL_ID', ...(protocol === 'responses' ? { input: 'Hello', store: false } : { ...(protocol === 'anthropic' ? { max_tokens: 256 } : {}), messages: [{ role: 'user', content: 'Hello' }] }) }, null, 2)}'`; return setCloudflareOpen(true)}>{tr("Cloudflare tunnel")} setGuide(true)}/>}>
{tr(twoAddresses ? "API base URL on this computer" : "API base URL")}
{twoAddresses ? serving.localUrl : serving.baseUrl}
{tr(twoAddresses ?
{tr("Address for other devices")}
{serving.sharing!.url}

{tr("Other devices use this address. It has its own port, separate from the one Strata's window uses, because only the model's API is shared on the network, not the app.")}

: null)}{tr(!multipleModels ?
{tr("Model ID")}
{loaded?.apiModelId ?? 'No model loaded'}
: null)}
{tr("Status")}
{tr(serving.running ? 'API listening' : 'API stopped')} · {tr(multipleModels ? `${runtime?.instances.length} models loaded` : loaded ? 'Model ready' : 'Model not ready')}
{tr("Local network")}
{tr(serving.sharing?.active ? "Shared on local network" : "Off")} { setError(''); setSharingOpen(true); }}>{tr(serving.sharing?.active ? "Manage / stop" : "Share")}
{tr(serving.tunnel?.status === "connected" && serving.tunnel.url ?
{tr("Cloudflare tunnel")}
{serving.tunnel.url} setCloudflareOpen(true)}/>
: serving.tunnel?.status === "starting" ?
{tr("Cloudflare tunnel")}
{tr("Connecting\u2026")}
: null)}
{tr("API key")}
{tr(serving.access.apiKeySet ? {tr("Required \u00B7 ")}{tr(serving.access.apiKeyHint)} : null)}
{ setError(''); generateKey(); setKeyOpen(true); }}>{tr(serving.access.apiKeySet ? 'Change key' : 'Set key')}{tr(serving.access.apiKeySet ? { setError(''); setRemoveKeyOpen(true); }}>{tr("Remove key")} : null)}
{tr(serving.access.otherDevices ? {tr("Keep a key while the API is available to other devices.")} : null)}
{tr(multipleModels ?

{tr("Available models")}

{tr("One API URL \u00B7 route by model ID")}
{tr(runtime?.instances.length ?
{tr(runtime.instances.map(i =>
{tr(i.family)}{tr(i.name)} · {tr(i.memory.context / 1024)}{tr("K \u00B7 ")}{tr(deviceLabel(i.gpuIds, hardware))}
{i.apiModelId}
))}
:

{tr("Load a model in Models to make it available here.")}

)}

{tr("Set ")}model{tr(" in each request. Each model has its own queue.")}{tr(runtime?.mode === 'simulated' ? ' Design preview · responses are illustrative.' : '')}

: null)}

{tr(scopeStats.running)}{tr(" active \u00B7 ")}{tr(scopeStats.waiting)}{tr(" queued \u00B7 ")}{tr(scopeStats.completed)}{tr(" completed")}

{tr(multipleModels ? setQuery(e.target.value)}/>
{tr(requests.length ?
{tr(multipleModels ? : null)}{tr(requests.map(r => {tr(multipleModels ? : null)}))}
{tr("Client / endpoint")}{tr("Model")}{tr("Status")}{tr("Tokens in / out")}
{tr(r.client)}
{tr(r.endpoint)}
{r.model}{tr({tr(r.cancelRequested ? r.cancellable ? 'Cancelling…' : 'Cancelled' : r.state.charAt(0).toUpperCase() + r.state.slice(1))})}{tr(tokens(r.tokensIn))} / {tr(tokens(r.tokensOut))}
{tr(r.usageSource === 'demo' ? 'Simulated' : r.usageSource === 'reported' ? 'Reported by model' : 'Usage unavailable')}
{tr(r.durationMs ? duration(r.durationMs) : '—')}
: { setQuery(''); setFilter('all'); setModelFilter('all'); }}>{tr("Clear filters")} : setGuide(true)}>{tr("Connect an app")})}/>)}
{tr(error ? : null)}
setGuide(false)} headerActions={
} sheet>
{tr(multipleModels ?
{tr("Generate another")} { setKeyDraft(''); setGenerated(false); setKeyVisible(false); }}>{tr("Use my own key")}

{tr("Copy this key into your client. It takes effect when you choose Use this key.")}{tr(serving.access.apiKeySet ? ' Your old key will stop working.' : '')}

{tr(error ? : null)}
!pending && setRemoveKeyOpen(false)} actions={<> setRemoveKeyOpen(false)}>{tr("Keep key")} void operation(async () => { await setServingAccess({ apiKey: null }); setRemoveKeyOpen(false); })}>{tr(pending ? 'Removing…' : 'Remove key')}}>

{tr("Apps on this computer will be able to send requests without a key. Existing clients can keep their current key field.")}

{tr(serving.access.otherDevices ?

{tr(" Without an API key, anyone who can reach this address can use your model.")}

: null)}{tr(error ? : null)}
setCloudflareOpen(false)} onCreateKey={() => { setReturnToTunnel(true); setCloudflareOpen(false); generateKey(); setKeyOpen(true); }}/>
; }