PEP-224: переводы, тест статуса функций

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-20 21:01:27 +05:00
parent 80d66d2b83
commit 971c7f67d8
7 changed files with 240 additions and 13 deletions

View File

@ -34,7 +34,7 @@ export async function FeatureGate({ view, label, title, children, className }: {
)}
<p className="m-0 text-xs text-muted-foreground">
{t.text(view.text)}
{since ? ` · ${t("с {time}", { time: since })}` : ""}
{since ? " · " + t("с {time}", { time: since }) : ""}
</p>
</div>
);

View File

@ -1,16 +1,16 @@
## 1. Ядро
- [ ] 1.1 `observe.db` v2: `monitors.features`, `features`, `feature_log`; eGov-мониторингам `egov_login`; `features` в create/update мониторинга
- [ ] 1.2 `core/feature-status.ts`: список функций, `computeFeatures`, `featureStatus(es)` с кэшем, `setFeatureThreshold`, `featureTick`, тексты
- [ ] 1.3 Встроенные мониторинги MCP (`seedFeatureMonitors`), `featureTick` в сервисе мониторингов
- [ ] 1.4 `startEgovFlow` отказывает при недоступности
- [x] 1.1 `observe.db` v2: `monitors.features`, `features`, `feature_log`; eGov-мониторингам `egov_login`; `features` в create/update мониторинга
- [x] 1.2 `core/feature-status.ts`: список функций, `computeFeatures`, `featureStatus(es)` с кэшем, `setFeatureThreshold`, `featureTick`, тексты
- [x] 1.3 Встроенные мониторинги MCP (`seedFeatureMonitors`), `featureTick` в сервисе мониторингов
- [x] 1.4 `startEgovFlow` отказывает при недоступности
## 2. Веб и MCP
- [ ] 2.1 Живая область `features` (без входа)
- [ ] 2.2 `FeatureGate`; вход, «Настройки → eGov», подключение ИИ-клиентов, `/mcp-guide`, помощь
- [ ] 2.3 `/mcp` — понятная ошибка при недоступности
- [ ] 2.4 `/observability`: «Функции», «Что отключать при сбое»; MCP `features`
- [ ] 2.5 Переводы en/kk, словарь
- [x] 2.1 Живая область `features` (без входа)
- [x] 2.2 `FeatureGate`; вход, «Настройки → eGov», подключение ИИ-клиентов, `/mcp-guide`, помощь
- [x] 2.3 `/mcp` — понятная ошибка при недоступности
- [x] 2.4 `/observability`: «Функции», «Что отключать при сбое»; MCP `features`
- [x] 2.5 Переводы en/kk, словарь
## 3. Проверка
- [ ] 3.1 Тест `feature-status.test.ts`
- [x] 3.1 Тест `feature-status.test.ts`
- [ ] 3.2 Проверки (lint, typecheck, тесты), браузер

View File

@ -0,0 +1,37 @@
import type { Dict } from "../index.ts";
// PEP-224: platform features follow their monitors.
export const features: Dict = {
"Временно недоступно — технические неполадки. Попробуйте позже": "Temporarily unavailable — technical problems. Please try again later",
"Вход через eGov": "Sign-in with eGov",
"Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже": "Temporarily unavailable — technical problems on the eGov side. Please try again later",
"Подключение к Claude и ChatGPT": "Connecting to Claude and ChatGPT",
"MCP временно недоступен — технические неполадки. Попробуйте позже": "MCP is temporarily unavailable — technical problems. Please try again later",
"Вход через Google": "Sign-in with Google",
"Временно недоступно — технические неполадки на стороне Google. Попробуйте позже": "Temporarily unavailable — technical problems on the Google side. Please try again later",
"Telegram-бот": "Telegram bot",
"Голосовой ввод": "Voice input",
"Отслеживание ошибок": "Error tracking",
"Может работать с задержками": "May work with delays",
"Неизвестная функция: {name}. Есть: {list}": "Unknown feature: {name}. Known: {list}",
"⛔ «{feature}» отключено для пользователей: не работает {why}": "⛔ «{feature}» is switched off for users: down — {why}",
"✅ «{feature}» снова включено для пользователей": "✅ «{feature}» is switched on for users again",
"MCP временно недоступен": "MCP is temporarily unavailable",
"Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.": "There is no other way to sign in right now. Open this page later — the button will come back by itself as soon as eGov is available again.",
"с {time}": "since {time}",
"Что отключать при сбое": "What to switch off when it fails",
"Что отключать при сбое:": "Switches off when it fails:",
"ничего": "nothing",
"доступна": "available",
"с задержками": "with delays",
"отключена": "switched off",
"снова включена": "switched on again",
"Функции": "Features",
"Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.":
"A feature turns grey for users when a linked monitor is down longer than the threshold and switches back on by itself after recovery. Link them with «What to switch off when it fails» on a monitor or the features field of MCP update_monitor.",
"отключать через, мин": "switch off after, min",
"Мониторинги:": "Monitors:",
"Не связана ни с одним мониторингом — всегда доступна.": "Not linked to any monitor — always available.",
"Журнал включений и выключений ({n})": "Switch-off log ({n})",
"Функции ещё не отключались.": "No feature has been switched off yet.",
};

View File

@ -28,5 +28,6 @@ import { analyst } from "./analyst.ts";
import { chatsUx } from "./chats-ux.ts";
import { accountMerge } from "./account-merge.ts";
import { acceptScreen } from "./accept-screen.ts";
import { features } from "./features.ts";
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen };
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...features };

View File

@ -0,0 +1,37 @@
import type { Dict } from "../index.ts";
// PEP-224: платформа функциялары мониторингтерге қарай қосылады және өшеді.
export const features: Dict = {
"Временно недоступно — технические неполадки. Попробуйте позже": "Уақытша қолжетімсіз — техникалық ақаулар. Кейінірек қайталап көріңіз",
"Вход через eGov": "eGov арқылы кіру",
"Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже": "Уақытша қолжетімсіз — eGov жағында техникалық ақаулар. Кейінірек қайталап көріңіз",
"Подключение к Claude и ChatGPT": "Claude және ChatGPT-ке қосылу",
"MCP временно недоступен — технические неполадки. Попробуйте позже": "MCP уақытша қолжетімсіз — техникалық ақаулар. Кейінірек қайталап көріңіз",
"Вход через Google": "Google арқылы кіру",
"Временно недоступно — технические неполадки на стороне Google. Попробуйте позже": "Уақытша қолжетімсіз — Google жағында техникалық ақаулар. Кейінірек қайталап көріңіз",
"Telegram-бот": "Telegram-бот",
"Голосовой ввод": "Дауыспен енгізу",
"Отслеживание ошибок": "Қателерді бақылау",
"Может работать с задержками": "Кідірістермен жұмыс істеуі мүмкін",
"Неизвестная функция: {name}. Есть: {list}": "Белгісіз функция: {name}. Бар функциялар: {list}",
"⛔ «{feature}» отключено для пользователей: не работает {why}": "⛔ «{feature}» пайдаланушылар үшін өшірілді: жұмыс істемейді — {why}",
"✅ «{feature}» снова включено для пользователей": "✅ «{feature}» пайдаланушылар үшін қайта қосылды",
"MCP временно недоступен": "MCP уақытша қолжетімсіз",
"Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.": "Қазір кірудің басқа жолы жоқ. Бұл бетті кейінірек ашыңыз — eGov қайта қолжетімді болғанда, батырма өзі іске қосылады.",
"с {time}": "{time} бастап",
"Что отключать при сбое": "Ақау кезінде не өшіріледі",
"Что отключать при сбое:": "Ақау кезінде өшіріледі:",
"ничего": "ештеңе",
"доступна": "қолжетімді",
"с задержками": "кідірістермен",
"отключена": "өшірілген",
"снова включена": "қайта қосылды",
"Функции": "Функциялар",
"Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.":
"Байланысты мониторинг шектен ұзақ жұмыс істемесе, функция пайдаланушыларда сұр болады және қалпына келгенде өзі қосылады. Байланыс — мониторингтегі «Ақау кезінде не өшіріледі» немесе MCP update_monitor ішіндегі features өрісі.",
"отключать через, мин": "өшіру уақыты, мин",
"Мониторинги:": "Мониторингтер:",
"Не связана ни с одним мониторингом — всегда доступна.": "Ешбір мониторингпен байланыспаған — әрқашан қолжетімді.",
"Журнал включений и выключений ({n})": "Қосу және өшіру журналы ({n})",
"Функции ещё не отключались.": "Функциялар әлі өшірілмеген.",
};

View File

@ -28,5 +28,6 @@ import { analyst } from "./analyst.ts";
import { chatsUx } from "./chats-ux.ts";
import { accountMerge } from "./account-merge.ts";
import { acceptScreen } from "./accept-screen.ts";
import { features } from "./features.ts";
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen };
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...features };

View File

@ -0,0 +1,151 @@
// PEP-224, spec feature-status: a platform feature follows its monitors — unavailable after its
// monitor is down longer than the threshold, back after recovery; startEgovFlow refuses without a
// request to the relay; one message per change; trouble with observe.db = available.
import assert from "node:assert/strict";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { after, before, describe, test } from "node:test";
import { events, telegramOutbox, users } from "@peppa/db";
import { and, eq, like } from "drizzle-orm";
import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, project, runner, teardown } from "./helpers.ts";
import { MockKazedsRelay } from "../src/mock-kazeds-relay.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const relay = new MockKazedsRelay({ iin: "900101300126", name: "ТЕСТОВА АСЕЛЬ" });
const CHAT = 880_224;
before(async () => {
process.env.KAZEDS_RELAY_BASE = await relay.start();
const u = await core.upsertUserFromGitea(db, { id: CHAT, login: "mock-feature-admin" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: CHAT, telegramUserId: CHAT }).where(eq(users.id, u.id));
await core.setPlatformAdmins(db, ["mock-feature-admin"]);
});
after(async () => {
await relay.stop();
core.closeObserveDb();
await teardown();
});
const min = (n: number) => new Date(Date.now() + n * 60_000);
const bad = { ok: false, degraded: false, reason: "ответ 503", detail: {} };
const good = { ok: true, degraded: false, reason: "", detail: {} };
const sent = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "mon:feature:%"))).map((r) => stripAsIs(String(r.params.text)));
const check = (id: number, r: typeof bad, at: Date) => core.recordCheck(core.getMonitor(id)!, r, { now: at });
describe("Feature status", () => {
test("Scenario: built-in eGov monitors switch off «Вход через eGov»; MCP monitors are made only for a public address", () => {
const made = core.seedMonitors();
assert.deepEqual(made.find((m) => m.name === "eGov relay")!.features, ["egov_login"]);
assert.deepEqual(made.find((m) => m.name === "eGov relay — DNS")!.features, ["egov_login"]);
assert.deepEqual(core.seedFeatureMonitors("http://localhost:3100"), [], "localhost — no MCP monitors");
const mcp = core.seedFeatureMonitors("https://peppa.example");
assert.deepEqual(mcp.map((m) => [m.name, m.features]), [["MCP-сервер /mcp", ["mcp"]], ["MCP — вход OAuth", ["mcp"]]]);
assert.deepEqual((mcp[0]!.target as { expectStatus: number[] }).expectStatus, [401]);
assert.deepEqual(core.seedFeatureMonitors("https://peppa.example"), [], "once");
for (const m of core.listMonitors()) core.deleteMonitor(m.id);
});
test("Scenario: an unknown feature is refused; features can be changed (MCP update_monitor)", () => {
assert.throws(() => core.createMonitor({ name: "x", kind: "dns", target: { host: "a.example" }, features: ["nope"] }, "system"), /Неизвестная функция/);
const m = core.createMonitor({ name: "Bugsink", kind: "dns", target: { host: "bugsink.example" } }, "system");
assert.deepEqual(m.features, []);
assert.deepEqual(core.updateMonitor(m.id, { features: ["bugsink"] }).features, ["bugsink"]);
assert.deepEqual(core.updateMonitor(m.id, { name: "Bugsink 2" }).features, ["bugsink"], "left out — unchanged");
core.deleteMonitor(m.id);
});
test("Scenario: eGov relay down 6 min — unavailable, startEgovFlow refuses without a request; back after 2 good checks", async () => {
const relayMon = core.createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.example/" }, features: ["egov_login"] }, "system", min(-10));
check(relayMon.id, good, min(-10));
assert.deepEqual(await core.featureTick(db), ["egov_login", "mcp", "google_login", "bot", "voice", "bugsink"], "the first computation only remembers");
assert.deepEqual(await sent(), []);
for (const at of [-8, -7, -6]) check(relayMon.id, bad, min(at));
assert.equal(core.getMonitor(relayMon.id)!.state, "down");
assert.equal(core.featureStatus("egov_login", { now: min(-3) }).state, "available", "down 3 min — shorter than 5");
const s = core.featureStatus("egov_login", { now: new Date() });
assert.equal(s.state, "unavailable");
assert.equal(s.since, core.getMonitor(relayMon.id)!.stateSince);
core.resetFeatureCache();
const before = relay.sessions.size;
await assert.rejects(core.startEgovFlow(db, "login"), (e: Error) => e instanceof core.PeppaError && /Временно недоступно — технические неполадки на стороне eGov/.test(e.message));
assert.equal(relay.sessions.size, before, "no request to the relay");
assert.equal(core.featureGateView("egov_login").state, "unavailable");
// Announced once: journal, message, event of the platform project.
const platform = await project({ turns: [[{ say: "ok" }]] });
process.env.PEPPA_PLATFORM_KEY = platform.key;
const platformId = (await core.getProject(db, platform.key)).id;
assert.deepEqual(await core.featureTick(db), ["egov_login"]);
assert.deepEqual(await core.featureTick(db), [], "no repeat");
let msgs = await sent();
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /⛔ «Вход через eGov» отключено для пользователей: не работает eGov relay — ответ 503, 6 мин/);
assert.equal(core.featureLog()[0]!.state, "unavailable");
assert.equal((await db.select().from(events).where(and(eq(events.projectId, platformId), eq(events.type, "feature_disabled")))).length, 1);
assert.notEqual(core.featureFingerprint(), "", "live pages see the change");
check(relayMon.id, good, new Date());
assert.equal(core.featureStatus("egov_login", { fresh: true }).state, "unavailable", "one good check is not enough (recover_threshold 2)");
check(relayMon.id, good, new Date());
assert.equal(core.featureStatus("egov_login", { fresh: true }).state, "available");
await core.featureTick(db);
msgs = await sent();
assert.equal(msgs.length, 2);
assert.match(msgs[1]!, /✅ «Вход через eGov» снова включено для пользователей/);
assert.equal((await db.select().from(events).where(and(eq(events.projectId, platformId), eq(events.type, "feature_enabled")))).length, 1);
assert.deepEqual(core.featureLog().map((e) => e.state), ["available", "unavailable"]);
core.resetFeatureCache();
const flow = await core.startEgovFlow(db, "login");
assert.ok(flow.qrContent, "eGov works again");
core.deleteMonitor(relayMon.id);
});
test("Scenario: unstable — only a note; a paused monitor and a custom threshold", async () => {
const m = core.createMonitor({ name: "mock mcp", kind: "http", target: { url: "https://mcp.example/" }, features: ["mcp"] }, "system", min(-30));
for (const at of [-20, -19, -18]) check(m.id, { ok: true, degraded: true, reason: "медленно", detail: {} }, min(at));
const v = core.featureGateView("mcp", { now: new Date() });
assert.equal(v.state, "degraded");
assert.match(v.text, /Может работать с задержками/);
for (const at of [-2, -1.5, -1]) check(m.id, bad, min(at));
assert.equal(core.featureStatus("mcp", { now: new Date() }).state, "available", "down 1 min");
core.setFeatureThreshold("mcp", 0);
assert.equal(core.featureStatus("mcp", { now: new Date() }).state, "unavailable", "threshold 0 — at once");
assert.equal(core.featureStatus("mcp", { now: new Date() }).disableAfterMin, 0);
core.setMonitorPaused(m.id, true);
assert.equal(core.featureStatus("mcp", { now: new Date() }).state, "available", "a paused monitor switches nothing off");
assert.throws(() => core.setFeatureThreshold("nope", 5), /Неизвестная функция/);
core.setFeatureThreshold("mcp", 5);
core.deleteMonitor(m.id);
});
test("Scenario: observe.db can not be opened — every feature is available", async () => {
const m = core.createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.example/" }, features: ["egov_login"] }, "system", min(-30));
for (const at of [-20, -19, -18]) check(m.id, bad, min(at));
assert.equal(core.featureStatus("egov_login", { now: new Date() }).state, "unavailable");
const real = process.env.PEPPA_OBSERVE_DB;
const file = join(tmpdir(), `mock-not-a-dir-${process.pid}`);
writeFileSync(file, "x");
process.env.PEPPA_OBSERVE_DB = join(file, "observe.db");
try {
assert.equal(core.featureStatus("egov_login", { now: new Date() }).state, "available");
assert.equal(core.featureFingerprint(), "");
core.resetFeatureCache();
assert.doesNotThrow(() => core.assertFeatureAvailable("egov_login"));
} finally {
if (real === undefined) delete process.env.PEPPA_OBSERVE_DB;
else process.env.PEPPA_OBSERVE_DB = real;
}
core.deleteMonitor(m.id);
});
test("Scenario: the live scope «features» is open without a sign-in, others are not", async () => {
assert.deepEqual(runner.parseScopes("features"), ["features"]);
await runner.checkScopeAccess(db, null, "features");
await assert.rejects(runner.checkScopeAccess(db, null, "home"), (e: Error) => e instanceof runner.LiveError && e.status === 401);
});
});