peppa/apps/web/components/Incidents.tsx
Асель 498013472f PEP-58: Bugsink — production errors become Peppa incidents and tasks
- infra: Bugsink 2.6.3 in docker (infra/bugsink, scripts/bugsink-up.sh), database
  bugsink in Peppa's Postgres, Traefik route bugsink.telecom.quest
- packages/bugsink: REST API client + custom-webhook payload parsing
- incidents (migration 0011): incident_settings, error_sources, incidents; ingest from
  webhook POST /api/hooks/bugsink/<secret> and a 2-minute poll in the watchdog
- incident policy per project: notify / backlog (default) / start / ask (Telegram
  buttons) / triage (claude -p with the owner's token, falls back to ask)
- daily task cap, environments, ignore pattern; manual "fixed" until PEP-57;
  REGRESSED returns the task to the backlog
- web «Ошибки» section, bot buttons, MCP tools for agents and the PM, help, RULES.md
- testkit: mock-bugsink, mock-triage, incidents.test.ts (one test per scenario,
  plus a live run against the real Bugsink with PEPPA_LIVE_BUGSINK=1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:31:32 +05:00

162 lines
7.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Project page section «Ошибки» (PEP-58): connect Bugsink, incident policy, incidents list.
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions";
import { ago } from "./ui";
const Hidden = ({ projectId, back }: { projectId: number; back: string }) => (
<>
<input type="hidden" name="projectId" value={projectId} />
<input type="hidden" name="back" value={back} />
</>
);
export function IncidentsSection(props: {
projectId: number;
projectKey: string;
back: string;
isOwner: boolean;
settings: IncidentSettings | null;
sources: ErrorSource[];
incidents: Incident[];
taskKeys: Map<number, string>;
webhookUrl: string | null;
}) {
const { projectId, back, settings: s } = props;
if (!s) {
return (
<section>
<h2>Ошибки</h2>
<p className="muted">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.</p>
{props.isOwner ? (
<form action={connectErrorTrackingAction}>
<Hidden projectId={projectId} back={back} />
<button className="primary">Подключить отслеживание ошибок</button>
</form>
) : (
<p className="empty">Не подключено — подключает владелец проекта.</p>
)}
</section>
);
}
const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
<section>
<h2>
Ошибки <span className="muted small">политика: {POLICY_RU[s.policy]}</span>
</h2>
{active.length === 0 ? <p className="empty">Открытых ошибок нет.</p> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
{rest.length > 0 && (
<details>
<summary>Исправленные и игнорируемые ({rest.length})</summary>
{rest.map((i) => (
<IncidentCard key={i.id} i={i} {...props} />
))}
</details>
)}
<details>
<summary>Настройки ошибок</summary>
<div className="stack">
{props.sources.map((src) => (
<div key={src.id}>
<b>DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</b>
<code className="mcp-url">{src.dsn}</code>
</div>
))}
<p className="muted">
В коде: <code>{"NEXT_PUBLIC_SENTRY_DSN"}</code> / <code>SENTRY_DSN</code> из окружения, <code>release</code> = SHA деплоя, <code>environment</code> = prod, <code>sendDefaultPii: false</code>.
</p>
{!s.webhookAuto && props.webhookUrl && (
<div>
<b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:
<code className="mcp-url">{props.webhookUrl}</code>
<span className="muted">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span>
</div>
)}
<form action={saveIncidentSettings} className="stack">
<Hidden projectId={projectId} back={back} />
<label>
Политика инцидентов{" "}
<select name="policy" defaultValue={s.policy} aria-label="Политика инцидентов">
{incidentPolicies.map((p) => (
<option key={p} value={p}>
{p} — {POLICY_RU[p]}
</option>
))}
</select>
</label>
<textarea
name="triagePrompt"
rows={3}
defaultValue={s.triagePrompt ?? ""}
aria-label="Как принимать решение (для триажёра)"
placeholder="Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»"
/>
<div className="row">
<input type="text" name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" />
<input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Задач в сутки" style={{ width: "6em" }} />
</div>
<input type="text" name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" />
<button>Сохранить</button>
</form>
</div>
</details>
</section>
);
}
function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string> }) {
const taskKey = i.taskId ? taskKeys.get(i.taskId) : null;
const decide = (action: string, label: string) => (
<form action={decideIncidentAction}>
<Hidden projectId={projectId} back={back} />
<input type="hidden" name="incidentId" value={i.id} />
<input type="hidden" name="action" value={action} />
<button className="small">{label}</button>
</form>
);
return (
<div className="card">
<div className="row">
<span className="badge">{INCIDENT_STATUS_RU[i.status]}</span>
<b className="grow">{i.title}</b>
<span className="muted small">{ago(i.lastSeen)}</span>
</div>
<div className="muted small">
{i.source} · {i.environment ?? "—"} · релиз {i.lastRelease ?? "—"} · событий {i.events}
{i.culprit && <> · 📍 {i.culprit}</>}
{i.url && (
<>
{" · "}
<a href={i.url}>Bugsink</a>
</>
)}
{taskKey && (
<>
{" · "}
<a href={`/t/${taskKey}`}>{taskKey}</a>
</>
)}
</div>
{i.decisionReason && <div className="muted small">{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}</div>}
<div className="row">
{!i.taskId && i.status !== "resolved" && (
<>
{decide("backlog", "📥 В бэклог")}
{decide("start", "▶️ В работу")}
{i.status !== "ignored" && decide("ignore", "🙈 Игнорировать")}
</>
)}
{i.status !== "resolved" && i.status !== "ignored" && (
<form action={resolveIncidentAction} className="row">
<Hidden projectId={projectId} back={back} />
<input type="hidden" name="incidentId" value={i.id} />
<button className="small">✅ Исправлено</button>
</form>
)}
</div>
</div>
);
}