v1.8: live gateway requests feed (/api/requests ring-buffer + dashboard Requests tab auto-refresh 4s) + reasoning_effort selector (opus high verified)

This commit is contained in:
aaronjaworski710
2026-10-15 17:05:37 +03:00
parent 9ed87864ff
commit c5337c15c1
4 changed files with 114 additions and 6 deletions
+15
View File
@@ -277,3 +277,18 @@ Gateway вешается в `~/AppData/Local/hermes/config.yaml` -> `custom_prov
### Фикс _secret
`*_env`-ссылка в конфиге больше не глушит прямое значение: env пуст -> берётся поле из config.json. (Раньше catchall молча отваливался, если env не задан.)
## v1.8 — Live-лента запросов + reasoning в дашборде
### Gateway: GET /api/requests
Все запросы через шлюз (chat/models/check) пишутся в ring-buffer (2000) и отдаются через `/api/requests?limit=N&kind=chat` (header X-Logicc-Admin: 1). Поля: ts, kind, model, account (маскирован), status, httpStatus, ms, ttftMs, attempts, stream, usage, error.
### Дашборд: вкладка Requests
Live-таблица (авто-обновление 4с, фильтр по kind): время, модель, аккаунт, OK/ERR, ms, TTFT, токены in/out, попытки, ошибка.
### Reasoning effort
Chat completion test: dropdown Reasoning (off/low/medium/high) -> body.reasoning_effort -> gateway форвардит как reasoningEffort в Logicc API. Проверено: claude-5.5-opus high = DASH-OK 12.2s.
### Прокси в дашборде
POST /api/gateway/requests {limit, kind} — дашборд сам добавляет admin-заголовок.
+19 -3
View File
@@ -385,9 +385,11 @@ def gw_restart():
return {"ok": code == 200, "gw_code": code}
def chat_test(model):
def chat_test(model, effort=None):
payload = {"model": model, "max_tokens": 30,
"messages": [{"role": "user", "content": "Say DASH-OK"}]}
if effort:
payload["reasoning_effort"] = effort
t0 = time.time()
code, body = jpost(GW + "/v1/chat/completions", payload, timeout=180)
dt = round(time.time() - t0, 1)
@@ -396,7 +398,19 @@ def chat_test(model):
txt = json.loads(body)["choices"][0]["message"]["content"][:100]
except Exception:
txt = body[:150]
return {"ok": code == 200, "code": code, "sec": dt, "reply": txt}
return {"ok": code == 200, "code": code, "sec": dt, "reply": txt, "effort": effort or "-"}
def gw_requests(limit=60, kind=None):
url = GW + "/api/requests?limit=%d" % limit
if kind:
url += "&kind=" + kind
try:
r = urllib.request.urlopen(urllib.request.Request(url, headers={"X-Logicc-Admin": "1"}), timeout=15)
d = json.loads(r.read().decode())
return {"ok": True, "requests": d.get("requests", [])}
except Exception as e:
return {"ok": False, "err": str(e)[:120]}
OPENCODE_MODELS = ["gpt-6-luna", "gpt-6.1-sol", "gemini-3.8-flash", "gemini-2.5-pro",
@@ -518,7 +532,9 @@ class H(BaseHTTPRequestHandler):
elif p == "/api/opencode/install":
self._send(opencode_install())
elif p == "/api/chat/test":
self._send(chat_test(body.get("model", "gpt-6-luna")))
self._send(chat_test(body.get("model", "gpt-6-luna"), body.get("reasoning_effort")))
elif p == "/api/gateway/requests":
self._send(gw_requests(int(body.get("limit", 60)), body.get("kind")))
elif p == "/api/mail/imap_add":
self._send(mail_imap_add(body))
else:
+68 -3
View File
@@ -177,6 +177,7 @@
<button id="tab-wave" data-t="wave" role="tab" aria-selected="false" aria-controls="t-wave" tabindex="-1">Wave</button>
<button id="tab-gw" data-t="gw" role="tab" aria-selected="false" aria-controls="t-gw" tabindex="-1">Gateway</button>
<button id="tab-log" data-t="log" role="tab" aria-selected="false" aria-controls="t-log" tabindex="-1">Activity log</button>
<button id="tab-req" data-t="req" role="tab" aria-selected="false" aria-controls="t-req" tabindex="-1">Requests</button>
</nav>
<section id="t-ov" role="tabpanel" aria-labelledby="tab-ov" class="space-y-5">
@@ -304,7 +305,7 @@
<article class="card">
<div class="card-header"><h3 class="card-title">Chat completion test</h3><p class="card-description">Send a prompt through the gateway to verify a model response.</p></div>
<div class="card-content">
<div class="grid items-end gap-4 md:grid-cols-[240px_1fr_auto]">
<div class="grid items-end gap-4 md:grid-cols-[220px_140px_1fr_auto]">
<div>
<label for="chat-model" class="mb-2 block text-xs font-medium">Model</label>
<div class="relative">
@@ -312,6 +313,12 @@
<svg class="pointer-events-none absolute right-3 top-3.5 text-zinc-500" width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="m4 6 4 4 4-4"/></svg>
</div>
</div>
<div>
<label for="chat-effort" class="mb-2 block text-xs font-medium">Reasoning</label>
<div class="relative">
<select id="chat-effort" class="input mono text-xs"><option value="">off</option><option value="low">low</option><option value="medium">medium</option><option value="high">high</option></select>
</div>
</div>
<div><label for="chat-prompt" class="mb-2 block text-xs font-medium">Prompt</label><input id="chat-prompt" class="input" value="Say hello in one short sentence." placeholder="Enter a test prompt…" autocomplete="off"></div>
<button id="b-chat" class="btn btn-default min-h-10">Test model <span aria-hidden="true">→</span></button>
</div>
@@ -333,6 +340,28 @@
</article>
</section>
<section id="t-req" class="hide" role="tabpanel" aria-labelledby="tab-req">
<article class="card">
<div class="card-header flex flex-wrap items-start justify-between gap-4 pb-5">
<div><h3 class="card-title">Gateway requests</h3><p class="card-description">Live-лента всех запросов через шлюз: модель, аккаунт, статус, время, токены. Авто-обновление 4с.</p></div>
<div class="flex items-center gap-3">
<select id="req-kind" class="input mono text-xs w-28"><option value="">all</option><option value="chat">chat</option><option value="models">models</option><option value="check">check</option></select>
<button id="b-req-refresh" class="btn btn-outline">Refresh</button>
</div>
</div>
<div class="separator"></div>
<div class="overflow-x-auto">
<table class="w-full text-xs">
<thead><tr class="border-b border-border text-left text-[10px] uppercase tracking-wider text-zinc-500">
<th class="px-4 py-2">Time</th><th class="px-4 py-2">Kind</th><th class="px-4 py-2">Model</th><th class="px-4 py-2">Account</th><th class="px-4 py-2">Status</th><th class="px-4 py-2 text-right">ms</th><th class="px-4 py-2 text-right">TTFT</th><th class="px-4 py-2 text-right">Tok in/out</th><th class="px-4 py-2 text-right">Try</th><th class="px-4 py-2">Error</th>
</tr></thead>
<tbody id="req-body"><tr><td colspan="10" class="px-4 py-6 text-center text-zinc-500">Loading…</td></tr></tbody>
</table>
</div>
<div class="flex items-center justify-between border-t border-border px-6 py-3 text-[10px] text-zinc-500"><span class="mono" id="req-count">0 requests</span><span id="req-ago">—</span></div>
</article>
</section>
<footer class="mt-9 flex flex-wrap items-center justify-between gap-3 border-t border-border pt-5 text-[10px] text-zinc-600">
<div class="flex items-center gap-3"><span class="font-medium tracking-wider text-zinc-500">LOGICC FARM</span><span class="mono">127.0.0.1:8560</span></div>
<div class="flex items-center gap-4"><span>Auto-refresh every 5s</span><a href="https://github.com/aaronjaworski710/logicc-farm" target="_blank" rel="noopener noreferrer" class="text-zinc-500 transition-colors hover:text-zinc-200">GitHub <span aria-hidden="true">↗</span></a></div>
@@ -676,10 +705,10 @@
}
const started = performance.now();
$('chat-out').setAttribute('aria-busy', 'true');
act('/api/chat/test', { model, prompt }, 'chat-msg', result => {
act('/api/chat/test', { model, prompt, reasoning_effort: $('chat-effort').value || null }, 'chat-msg', result => {
const elapsed = result.sec ?? ((performance.now() - started) / 1000).toFixed(2);
$('chat-msg').textContent = (result.ok ? 'OK' : 'FAIL') + ' · ' + elapsed + 's';
$('chat-out').textContent = (result.ok ? 'OK ' : 'FAIL ') + (result.code ?? '—') + ' · ' + elapsed + 's\n\n' + (result.reply || '');
$('chat-out').textContent = (result.ok ? 'OK ' : 'FAIL ') + (result.code ?? '—') + ' · ' + elapsed + 's · reasoning=' + (result.effort || '-') + '\n\n' + (result.reply || '');
}, 'b-chat', 'Chat test').finally(() => {
$('chat-out').setAttribute('aria-busy', 'false');
});
@@ -690,6 +719,42 @@
$('b-chat').click();
}
};
async function refreshReq() {
try {
const r = await fetch('/api/gateway/requests', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ limit: 80, kind: $('req-kind').value || null }) });
const d = await r.json();
const tb = $('req-body');
if (!d.ok) { tb.innerHTML = '<tr><td colspan="10" class="px-4 py-6 text-center text-red-400">' + (d.err || 'gateway unavailable') + '</td></tr>'; return; }
const rs = d.requests || [];
$('req-count').textContent = rs.length + ' requests';
if (!rs.length) { tb.innerHTML = '<tr><td colspan="10" class="px-4 py-6 text-center text-zinc-500">Запросов ещё не было</td></tr>'; return; }
tb.innerHTML = rs.map(x => {
const tm = new Date(x.ts).toLocaleTimeString('ru-RU');
const ok = x.status === 'success';
const u = x.usage || {};
const err = String(x.error || '').replace(/"/g, '&quot;').replace(/</g, '&lt;');
return '<tr class="border-b border-border/50 hover:bg-zinc-900/40">' +
'<td class="px-4 py-1.5 mono whitespace-nowrap">' + tm + '</td>' +
'<td class="px-4 py-1.5"><span class="badge badge-outline mono">' + x.kind + '</span></td>' +
'<td class="px-4 py-1.5 mono">' + (x.model || '—') + '</td>' +
'<td class="px-4 py-1.5 mono text-zinc-400">' + (x.account || '—') + '</td>' +
'<td class="px-4 py-1.5">' + (ok ? '<span class="text-emerald-400">OK' + (x.stream ? ' stream' : '') + '</span>' : '<span class="text-red-400">ERR ' + (x.httpStatus || '') + '</span>') + '</td>' +
'<td class="px-4 py-1.5 text-right mono">' + (x.ms ?? '—') + '</td>' +
'<td class="px-4 py-1.5 text-right mono text-zinc-400">' + (x.ttftMs ?? '—') + '</td>' +
'<td class="px-4 py-1.5 text-right mono">' + (u.prompt_tokens ?? 0) + '/' + (u.completion_tokens ?? 0) + '</td>' +
'<td class="px-4 py-1.5 text-right mono">' + (x.attempts ?? 1) + '</td>' +
'<td class="px-4 py-1.5 text-zinc-500 max-w-[200px] truncate" title="' + err + '">' + err + '</td></tr>';
}).join('');
$('req-ago').textContent = 'updated ' + new Date().toLocaleTimeString('ru-RU');
} catch (e) {
$('req-body').innerHTML = '<tr><td colspan="10" class="px-4 py-6 text-center text-red-400">' + e.message + '</td></tr>';
}
}
$('b-req-refresh').onclick = () => refreshReq();
$('req-kind').onchange = () => refreshReq();
setInterval(() => { if (!$('t-req').classList.contains('hide')) refreshReq(); }, 4000);
refreshReq();
$('b-bank-refresh').onclick = () => refreshBank(true);
$('b-log-refresh').onclick = () => refreshLog(true);
+12
View File
@@ -333,6 +333,18 @@ export function createAdapter({ env = process.env, dataFile = env.LOGICC_DATA_FI
const models = await track(req, res, 'models', (account, _trace, signal) => modelsFor(account, signal));
return json(res, 200, { models, updatedAt: pool.data.modelsUpdatedAt });
}
if (url.pathname === '/api/requests' && req.method === 'GET') {
const limit = Math.min(Math.max(Number(url.searchParams.get('limit') || 60) || 60, 1), 500);
const kind = url.searchParams.get('kind');
const list = kind ? pool.data.requests.filter(r => r.kind === kind) : pool.data.requests;
return json(res, 200, { requests: list.slice(0, limit).map(r => ({
id: r.id, ts: r.startedAt, kind: r.kind, model: r.model, status: r.status,
httpStatus: r.httpStatus || null, ms: r.durationMs ?? null, ttftMs: r.ttftMs ?? null,
attempts: r.attempts || 1, stream: Boolean(r.stream),
account: r.accountName ? String(r.accountName).replace(/^(.{3})[^@]*(@.*)$/, '$1***$2') : null,
usage: r.usage || null, error: r.error || null,
})) });
}
throw new HttpError(404, '管理接口不存在');
}
if (url.pathname === '/__set_token' && req.method === 'POST') {