diff --git a/backend/tests/test_atomic_admission_authority.py b/backend/tests/test_atomic_admission_authority.py index af0a792d1d..98d7716cfd 100644 --- a/backend/tests/test_atomic_admission_authority.py +++ b/backend/tests/test_atomic_admission_authority.py @@ -220,16 +220,32 @@ async def test_successful_renewal_invalidates_the_earlier_deadline_guard(): @pytest.mark.anyio -async def test_expiry_fences_even_while_atomic_ack_holds_the_manager_lock(): - from deerflow.runtime.runs.store.memory import MemoryRunStore +async def test_expiry_fences_even_while_atomic_ack_holds_the_manager_lock(monkeypatch): + from deerflow.runtime.runs import manager as manager_module + from deerflow.runtime.runs.store import memory as memory_store + from deerflow.utils import time as time_utils - store = MemoryRunStore() + wall_start = datetime.now(UTC) + elapsed = timedelta() + loop = asyncio.get_running_loop() + real_loop_time = loop.time + + class LeaseClock(datetime): + @classmethod + def now(cls, tz=None): + instant = wall_start + elapsed + return instant.astimezone(tz) if tz is not None else instant.replace(tzinfo=None) + + monkeypatch.setattr(manager_module, "datetime", LeaseClock) + monkeypatch.setattr(memory_store, "datetime", LeaseClock) + monkeypatch.setattr(time_utils, "datetime", LeaseClock) + monkeypatch.setattr(loop, "time", lambda: real_loop_time() + elapsed.total_seconds()) + + store = memory_store.MemoryRunStore() manager = manager_for(store) old = await manager.create_or_reject("thread") + expiry = datetime.fromisoformat(old.lease_expires_at) original_atomic, original_renew = store.create_thread_operation_atomic, store.renew_lease - expiry = (datetime.now(UTC) + timedelta(milliseconds=100)).isoformat() - old.lease_expires_at = expiry - store._runs[old.run_id]["lease_expires_at"] = expiry renewing, allow_renew, committed, release_ack = (asyncio.Event() for _ in range(4)) async def held_renew(*args, **kwargs): @@ -248,14 +264,26 @@ async def test_expiry_fences_even_while_atomic_ack_holds_the_manager_lock(): admission = None try: await asyncio.wait_for(renewing.wait(), 1) + # The replacement starts with a later lease than the run it interrupts. + elapsed = timedelta(seconds=2) admission = asyncio.create_task(manager.create_or_reject("thread", multitask_strategy="rollback")) await asyncio.wait_for(committed.wait(), 1) - allow_renew.set() - done, _ = await asyncio.wait({renewal}, timeout=0.3) - assert renewal in done, "expiry fencing waited behind the atomic Store await under the manager lock" - assert old.ownership_lost + assert not old.ownership_lost + + # Keep the manager lock busy and the committed admission ACK paused. + await asyncio.wait_for(manager._lock.acquire(), 1) + try: + elapsed = expiry - wall_start + timedelta(seconds=1) + allow_renew.set() + done, _ = await asyncio.wait({renewal}, timeout=1) + assert renewal in done, "expiry fencing waited behind the manager lock" + await renewal + assert old.ownership_lost + finally: + manager._lock.release() release_ack.set() - await asyncio.wait_for(admission, 1) + replacement = await asyncio.wait_for(admission, 1) + assert datetime.fromisoformat(replacement.lease_expires_at) > LeaseClock.now(UTC) assert old.ownership_lost assert not manager._has_terminal_ack(old) assert not manager._terminal_attempts @@ -264,6 +292,8 @@ async def test_expiry_fences_even_while_atomic_ack_holds_the_manager_lock(): release_ack.set() await asyncio.gather(renewal, *([admission] if admission else []), return_exceptions=True) await manager.stop_heartbeat(timeout=0.1) + for handle in manager._lease_deadlines.values(): + handle.cancel() @pytest.mark.anyio diff --git a/backend/tests/test_run_postmortem_extension.py b/backend/tests/test_run_postmortem_extension.py index f9922fda2b..246091934b 100644 --- a/backend/tests/test_run_postmortem_extension.py +++ b/backend/tests/test_run_postmortem_extension.py @@ -9,6 +9,7 @@ import pytest from deerflow_extension_api import CompletedRunEvent, CompletedRunEventPage, CompletedRunSnapshot, EvidenceLimits, ExtensionRuntimeDeps from deerflow_extension_api.run_evidence import RunPage +from deerflow.extensions.browser_assets import load_browser_assets from deerflow.extensions.loader import ExtensionSpec, load_extensions pytestmark = pytest.mark.bundled_extension @@ -50,6 +51,13 @@ def test_install_registers_one_service_and_its_router(monkeypatch): ((_, service),) = loaded.services assert service.ready is False # the host starts services; install only registers assert [getattr(router, "prefix", "") for _, router in loaded.routers] == [PREFIX] + ((_, plugin),) = loaded.plugins + assert plugin.namespace == "community.run-postmortem" + assert [action.name for action in plugin.backend] == ["latest", "report", "markdown"] + assets = load_browser_assets(plugin.frontend) + assert assets.entry == "static/postmortem.mjs" + assert assets.module == "run-postmortem.v1" + assert "static/postmortem.mjs" in assets.files @pytest.mark.asyncio @@ -73,6 +81,7 @@ def test_disabled_configuration_registers_nothing(monkeypatch): assert not diagnostics assert loaded.services == () assert loaded.routers == () + assert loaded.plugins == () def test_a_mistyped_off_switch_fails_the_load(monkeypatch): @@ -81,3 +90,4 @@ def test_a_mistyped_off_switch_fails_the_load(monkeypatch): assert diagnostics assert loaded.services == () assert loaded.routers == () + assert loaded.plugins == () diff --git a/examples/deerflow-extension-run-postmortem/README.md b/examples/deerflow-extension-run-postmortem/README.md index 1c148ba354..749b3b3e9b 100644 --- a/examples/deerflow-extension-run-postmortem/README.md +++ b/examples/deerflow-extension-run-postmortem/README.md @@ -7,7 +7,8 @@ happened, and what should I check next?* It uses extension API 0.2.11 with no host code changes. The host owns evidence storage, sealing, retention and authorization; this package owns only the -interpretation of one sealed run. +interpretation of one sealed run, exposed both as HTTP routes and as a +workspace page. ## What it produces @@ -40,6 +41,23 @@ read-bound signals: `evidence_bounded` (the caller's `max_events` cut the read), The Markdown route renders the same data as a document that can be attached to an incident ticket. Query `max_events` (1–2000, default 200) bounds the work. + +### Workspace page + +The same plugin adds a **Run postmortem** page (sidebar entry, localized en/zh) +with the same data. When the host supplies the current thread id to the surface, +the page prefills it; hosts that mount pages without thread context leave the +field empty, so it stays editable. The page can load the latest run the caller +owns on that thread **when the changed-run feed can be read to its end**; a +bounded scan that stops early says so and asks for a run ID instead of +presenting an older run as latest. It renders the verdict, anomalies, activity +and a timeline that reveals further events on demand, and downloads the +Markdown report. It reaches the host only +through three declared actions — `latest`, `report`, `markdown` — so the page +holds no credentials and no network code of its own. A run the caller does not +own answers `{"not_found": true}` rather than an error, and the action route's +principal binding is the same one the HTTP routes use. + ## Install and configure From the DeerFlow checkout root: diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/__init__.py b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/__init__.py index 3c372b2b7b..f1a41bed02 100644 --- a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/__init__.py +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/__init__.py @@ -8,18 +8,20 @@ reports a diagnostic; nothing else changes. from __future__ import annotations from collections.abc import Mapping +from pathlib import Path from typing import Any -from deerflow_extension_api import ExtensionInstall, ExtensionRegistry, extension +from deerflow_extension_api import ExtensionInstall, ExtensionRegistry, PluginContribution, extension +from deerflow_extension_api.plugins import BrowserAssets -from deerflow_extension_run_postmortem.service import PostmortemService, build_router +from deerflow_extension_run_postmortem.service import PostmortemService, build_actions, build_router __all__ = ["install"] @extension(api="0.2.11", name="run-postmortem") def install(registry: ExtensionRegistry, config: Mapping[str, Any]) -> None: - """Register the report service and its HTTP surface.""" + """Register the report service, its HTTP surface and the workspace page.""" # ``is False`` alone would silently keep the plugin on for ``enabled: 0`` or # ``enabled: "false"``; a mistyped off switch must fail the deployment. enabled = config.get("enabled", True) @@ -31,6 +33,15 @@ def install(registry: ExtensionRegistry, config: Mapping[str, Any]) -> None: service = PostmortemService() registry.service(service) registry.routers((build_router(service),)) + contribution = PluginContribution( + namespace="community.run-postmortem", + title="运行复盘 / Run postmortem", + description="把一次已封存运行的事件证据整理成结论、异常清单与时间线,并可下载 Markdown 报告。", + enabled=enabled, + frontend=BrowserAssets("run-postmortem.v1", Path(__file__).resolve().parent), + backend=build_actions(service), + ) + registry.plugin(contribution) _entry_point: ExtensionInstall = install diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/deerflow-extension.json b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/deerflow-extension.json index 38178787db..a24dc2205d 100644 --- a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/deerflow-extension.json +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/deerflow-extension.json @@ -1,15 +1,19 @@ { "schema_version": 1, - "id": "catalog/runPostmortem", + "id": "community.run-postmortem", "locales": { "zh-CN": { "title": "运行复盘", - "description": "把一次已封存运行的事件证据整理成时间线、异常清单与可分享的 Markdown 报告,用来回答“这次为什么失败/卡住”。", + "description": "在会话页把一次已封存运行的事件证据整理成结论、异常清单与时间线,并可下载 Markdown 报告。", "usage": [ { "title": "安装并授权", "description": "通过 make extension-install 安装示例,在 config.yaml 的 plugins 中授予 host_access.evidence 后重启 Gateway。" }, + { + "title": "在工作区打开运行复盘页", + "description": "侧边栏进入“运行复盘”,填入会话与运行 ID(或点“最新一次运行”),生成报告后可下载 Markdown。" + }, { "title": "查看单次运行报告", "description": "调用 /api/extension-run-postmortem/runs/{thread_id}/{run_id} 获取结构化复盘,或在末尾追加 /markdown 下载可分享报告。" @@ -26,12 +30,16 @@ }, "en-US": { "title": "Run postmortem", - "description": "Turns one sealed run's event evidence into a timeline, an anomaly list and a shareable Markdown report that answers \"why did this run fail or stall\".", + "description": "Explain one sealed run from its own evidence on a workspace page: verdict, anomalies and a timeline, with a downloadable Markdown report.", "usage": [ { "title": "Install and grant access", "description": "Install the example with make extension-install, grant host_access.evidence in config.yaml plugins, then restart Gateway." }, + { + "title": "Open the workspace page", + "description": "Open Run postmortem from the sidebar, enter a thread and run ID (or load the latest run), then generate and download the Markdown report." + }, { "title": "Open a run report", "description": "Call /api/extension-run-postmortem/runs/{thread_id}/{run_id} for the structured report, or append /markdown for a shareable document." diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/service.py b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/service.py index b0621dbd64..d5c9229939 100644 --- a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/service.py +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/service.py @@ -7,7 +7,7 @@ the interpretation of one sealed run, exposed as JSON and Markdown. from __future__ import annotations -from collections.abc import Awaitable +from collections.abc import Awaitable, Mapping from typing import Any from deerflow_extension_api import ( @@ -21,6 +21,7 @@ from deerflow_extension_api import ( resolve_principal, resolve_run_evidence_reader, ) +from deerflow_extension_api.plugins import ActionContext, BackendAction from fastapi import APIRouter, HTTPException, Query, Request from fastapi.responses import PlainTextResponse @@ -77,6 +78,42 @@ class PostmortemService: snapshot = await evidence.get_snapshot(thread_id=thread_id, run_id=run_id, limits=limits) return build_postmortem(snapshot, await self._read_events(evidence, snapshot, limits), max_events=max_events) + async def latest_run(self, *, thread_id: str, user_id: str, candidate_limit: int = 20, page_limit: int = 3) -> dict[str, Any]: + """Latest run this caller owns on the thread, from the changed-run feed. + + The feed is ordered by change sequence across *every* thread in the + evidence grant, not by run recency, so a bounded scan cannot prove a run + is the newest. Only a scan that reached the end of the feed may answer a + run; an incomplete scan answers ``complete: false`` so the caller can ask + for a run ID instead of being shown an older run as "latest". + + ``list_changed_runs`` is allowlist-scoped for the plugin, not for the + caller, so each candidate's snapshot is checked against the caller before + anything is returned. + """ + evidence = self._require_evidence() + matched: list[Any] = [] + scanned = 0 + cursor: str | None = None + seen: set[str] = set() + complete = False + for _ in range(page_limit): + page = await evidence.list_changed_runs(cursor=cursor, limit=200) + scanned += len(page.items) + matched.extend(item for item in page.items if item.thread_id == thread_id) + if not page.has_more or page.next_cursor is None or page.next_cursor in seen: + complete = True + break + seen.add(page.next_cursor) + cursor = page.next_cursor + if not complete: + return {"run": None, "complete": False, "scanned": scanned} + for item in reversed(matched[-candidate_limit:]): + snapshot = await evidence.get_snapshot(thread_id=item.thread_id, run_id=item.run_id, limits=EvidenceLimits(max_events=1)) + if snapshot.owner_id == user_id: + return {"run": {"run_id": item.run_id, "status": item.status, "updated_at": item.updated_at}, "complete": True, "scanned": scanned} + return {"run": None, "complete": True, "scanned": scanned} + async def _read_events(self, evidence: CompletedRunEvidenceReader, snapshot: CompletedRunSnapshot, limits: EvidenceLimits) -> list[CompletedRunEvent]: """Follow the event cursor until the snapshot ends or the cap is met.""" events: list[CompletedRunEvent] = [] @@ -166,3 +203,56 @@ def build_router(service: PostmortemService): __all__ = ["DEFAULT_MAX_EVENTS", "MAX_EVENTS", "PostmortemError", "PostmortemService", "build_router"] + +_MAX_FIELD = 256 + + +def _text_field(payload: Mapping[str, Any], field: str) -> str: + value = payload.get(field) + if not isinstance(value, str) or not value.strip() or len(value) > _MAX_FIELD: + raise ValueError(f"{field} must be a non-empty string of at most {_MAX_FIELD} characters") + return value.strip() + + +def _max_events_field(payload: Mapping[str, Any], field: str = "max_events") -> int: + value = payload.get(field, DEFAULT_MAX_EVENTS) + if type(value) is not int or not 1 <= value <= MAX_EVENTS: + raise ValueError(f"{field} must be an integer between 1 and {MAX_EVENTS}") + return value + + +async def _owned_report(service: PostmortemService, principal: ExtensionPrincipal, payload: Mapping[str, Any]) -> Postmortem | None: + postmortem = await service.postmortem( + thread_id=_text_field(payload, "thread_id"), + run_id=_text_field(payload, "run_id"), + max_events=_max_events_field(payload), + ) + return postmortem if postmortem.owner_id == principal.user_id else None + + +def build_actions(service: PostmortemService) -> tuple[BackendAction, ...]: + """Browser-facing actions serving the same report as the HTTP routes. + + A run the caller does not own answers ``{"not_found": true}`` instead of an + error: the action route turns a ``ValueError`` into a generic 422, which + would read as a bad request rather than a missing run. + """ + + async def latest(payload: Mapping[str, Any], context: ActionContext) -> dict[str, Any]: + thread_id = _text_field(payload, "thread_id") + return await service.latest_run(thread_id=thread_id, user_id=context.principal.user_id) + + async def report(payload: Mapping[str, Any], context: ActionContext) -> dict[str, Any]: + postmortem = await _owned_report(service, context.principal, payload) + return {"not_found": True} if postmortem is None else to_dict(postmortem) + + async def markdown(payload: Mapping[str, Any], context: ActionContext) -> dict[str, Any]: + postmortem = await _owned_report(service, context.principal, payload) + if postmortem is None: + return {"not_found": True} + return {"markdown": render_markdown(postmortem), "filename": f"postmortem-{postmortem.run_id}.md"} + + return (BackendAction("latest", latest), BackendAction("report", report), BackendAction("markdown", markdown)) + + +__all__ = ["DEFAULT_MAX_EVENTS", "MAX_EVENTS", "PostmortemError", "PostmortemService", "build_actions", "build_router"] diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/static/postmortem.mjs b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/static/postmortem.mjs new file mode 100644 index 0000000000..04245ae375 --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/static/postmortem.mjs @@ -0,0 +1,497 @@ +/** + * Run postmortem page. + * + * Renders one sealed run's evidence report and downloads its Markdown form. + * All data crosses the host's authenticated action bridge (`context.callBackend`); + * this module holds no credentials and no network code of its own. + */ + +const WORDS = { + en: { + title: "Run postmortem", + intro: + "Explain one finished run from its sealed evidence. Reports are owner-scoped.", + thread: "Thread ID", + run: "Run ID", + maxEvents: "Max events", + latest: "Latest run", + generate: "Generate report", + loading: "Reading evidence…", + missing: "Enter a thread and run ID, or load the latest run.", + notFound: "No run of yours was found for that thread and run ID.", + noRun: "This thread has no runs you own.", + latestFound: "Latest run", + scanIncomplete: (scanned) => + `Scanned ${scanned} run records without reaching the end; the newest run could not be confirmed. Enter the run ID manually.`, + showing: (shown, total) => `Showing ${shown} of ${total} events`, + showMore: (count) => `Show ${count} more events`, + verdict: "Verdict", + anomalies: "Anomalies", + none: "None detected in the retained evidence.", + activity: "Activity", + timeline: "Timeline", + caveats: "Evidence caveats", + download: "Download Markdown", + downloaded: "Report downloaded.", + failed: "Could not build the report. Check the IDs and try again.", + truncated: "(truncated)", + messages: "Messages", + toolFailures: "Tool failures", + subagents: "Subagents", + delivery: "Delivery", + events: "Events", + status: "Status", + stopReason: "Stop reason", + seal: "Evidence", + agent: "Agent", + origin: "Origin", + seq: "#", + event: "Event", + summary: "Summary", + }, + zh: { + title: "运行复盘", + intro: "用一次已封存运行的事件证据解释它发生了什么。报告仅限运行所有者查看。", + thread: "会话 ID", + run: "运行 ID", + maxEvents: "最多事件数", + latest: "最新一次运行", + generate: "生成报告", + loading: "正在读取证据…", + missing: "请填写会话与运行 ID,或先获取最新一次运行。", + notFound: "没有找到属于你的这次运行。", + noRun: "该会话下没有属于你的运行。", + latestFound: "最新运行", + scanIncomplete: (scanned) => + `只扫描了 ${scanned} 条运行记录,未到末尾,无法确认最新一次;请手动填写运行 ID。`, + showing: (shown, total) => `已显示 ${shown} / ${total} 条事件`, + showMore: (count) => `再显示 ${count} 条`, + verdict: "结论", + anomalies: "异常", + none: "在保留的证据中未发现异常。", + activity: "活动", + timeline: "时间线", + caveats: "证据覆盖说明", + download: "下载 Markdown", + downloaded: "报告已下载。", + failed: "无法生成报告,请检查 ID 后重试。", + truncated: "(已截断)", + messages: "消息", + toolFailures: "工具失败", + subagents: "子代理", + delivery: "交付", + events: "事件数", + status: "状态", + stopReason: "停止原因", + seal: "证据", + agent: "智能体", + origin: "来源", + seq: "序号", + event: "事件", + summary: "摘要", + }, +}; + +function el(tag, props = {}, children = []) { + const node = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null) continue; + if (key === "class") node.className = value; + else if (key === "text") node.textContent = String(value); + else node.setAttribute(key, String(value)); + } + for (const child of children) { + if (child) node.append(child); + } + return node; +} + +function styleSheet() { + return ` +.pm-page { display: flex; flex-direction: column; gap: 16px; padding: 4px 0; max-width: 1080px; } +.pm-page h2 { margin: 0; font-size: 20px; } +.pm-page p { margin: 0; } +.pm-intro { opacity: .72; } +.pm-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; align-items: end; } +.pm-field { display: flex; flex-direction: column; gap: 4px; font-size: 13px; } +.pm-field input { padding: 7px 9px; border: 1px solid color-mix(in srgb, currentColor 24%, transparent); border-radius: 7px; background: transparent; color: inherit; } +.pm-actions { display: flex; gap: 8px; flex-wrap: wrap; } +.pm-page button { padding: 7px 12px; border-radius: 7px; border: 1px solid color-mix(in srgb, currentColor 28%, transparent); background: transparent; color: inherit; cursor: pointer; } +.pm-page button.pm-primary { background: color-mix(in srgb, currentColor 12%, transparent); font-weight: 600; } +.pm-page button:disabled { opacity: .5; cursor: default; } +.pm-status { opacity: .78; } +.pm-error { color: #b42318; } +.pm-report { display: flex; flex-direction: column; gap: 14px; } +.pm-verdict { font-size: 16px; font-weight: 600; } +.pm-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 8px; } +.pm-card { border: 1px solid color-mix(in srgb, currentColor 16%, transparent); border-radius: 9px; padding: 9px 11px; } +.pm-card dt { font-size: 12px; opacity: .7; } +.pm-card dd { margin: 3px 0 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } +.pm-page h3 { margin: 6px 0 0; font-size: 15px; } +.pm-list { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; } +.pm-code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; opacity: .85; } +.pm-timeline { overflow: auto; max-height: 460px; border: 1px solid color-mix(in srgb, currentColor 16%, transparent); border-radius: 9px; } +.pm-timeline table { border-collapse: collapse; width: 100%; font-size: 13px; } +.pm-timeline th, .pm-timeline td { text-align: left; padding: 6px 9px; border-bottom: 1px solid color-mix(in srgb, currentColor 12%, transparent); vertical-align: top; } +.pm-timeline th { position: sticky; top: 0; background: color-mix(in srgb, currentColor 6%, Canvas); } +.pm-timeline td.pm-seq { font-variant-numeric: tabular-nums; opacity: .7; white-space: nowrap; } +.pm-timeline td.pm-type { white-space: nowrap; } +`; +} + +export function mount(root, context) { + const zh = String(context.locale || "en").startsWith("zh"); + const t = zh ? WORDS.zh : WORDS.en; + let disposed = false; + let pending = null; + let timelineEntries = []; + let renderedRows = 0; + let timelineBody = null; + let timelineFooter = null; + let showMoreButton = null; + const TIMELINE_CHUNK = 400; + + const alive = () => !disposed && !context.signal.aborted; + + const style = el("style"); + style.textContent = styleSheet(); + const page = el("section", { class: "pm-page", "aria-label": t.title }); + + const threadInput = el("input", { + type: "text", + maxlength: "256", + placeholder: "00000000-0000-0000-0000-000000000000", + "aria-label": t.thread, + }); + const runInput = el("input", { + type: "text", + maxlength: "256", + placeholder: "run id", + "aria-label": t.run, + }); + const maxInput = el("input", { + type: "number", + min: "1", + max: "2000", + step: "1", + value: "200", + "aria-label": t.maxEvents, + }); + // Hosts that mount a page without thread context omit threadId; the field + // stays empty and editable so the operator can type it. + if (context.threadId) threadInput.value = context.threadId; + + const latestButton = el("button", { + type: "button", + text: t.latest, + "aria-label": t.latest, + }); + const generateButton = el("button", { + type: "submit", + class: "pm-primary", + text: t.generate, + }); + const statusLine = el("p", { class: "pm-status", role: "status" }); + const errorLine = el("p", { class: "pm-error", role: "alert" }); + + const report = el("div", { class: "pm-report", hidden: "hidden" }); + const verdict = el("p", { class: "pm-verdict" }); + const overview = el("div", { class: "pm-grid" }); + const anomalies = el("ul", { class: "pm-list" }); + const activity = el("ul", { class: "pm-list" }); + const timeline = el("div", { class: "pm-timeline" }); + const caveats = el("ul", { class: "pm-list" }); + const downloadButton = el("button", { + type: "button", + text: t.download, + disabled: "disabled", + }); + + const form = el("form", { class: "pm-form" }, [ + el("label", { class: "pm-field" }, [el("span", { text: t.thread }), threadInput]), + el("label", { class: "pm-field" }, [el("span", { text: t.run }), runInput]), + el("label", { class: "pm-field" }, [el("span", { text: t.maxEvents }), maxInput]), + el("div", { class: "pm-actions" }, [latestButton, generateButton]), + ]); + + page.append( + el("h2", { text: t.title }), + el("p", { class: "pm-intro", text: t.intro }), + form, + statusLine, + errorLine, + report, + ); + report.append( + verdict, + overview, + el("h3", { text: t.anomalies }), + anomalies, + el("h3", { text: t.activity }), + activity, + el("h3", { text: t.timeline }), + timeline, + el("h3", { text: t.caveats }), + caveats, + el("div", { class: "pm-actions" }, [downloadButton]), + ); + root.replaceChildren(style, page); + + const setStatus = (text) => { + statusLine.textContent = text || ""; + }; + const setError = (text) => { + errorLine.textContent = text || ""; + }; + const setBusy = (busy) => { + latestButton.disabled = busy; + generateButton.disabled = busy; + downloadButton.disabled = busy || !pending; + }; + const payloadFor = () => { + const parsed = Number.parseInt(maxInput.value, 10); + const max = Number.isFinite(parsed) ? Math.min(2000, Math.max(1, parsed)) : 200; + return { + thread_id: threadInput.value.trim(), + run_id: runInput.value.trim(), + max_events: max, + }; + }; + + const card = (term, value) => + el("dl", { class: "pm-card" }, [el("dt", { text: term }), el("dd", { text: value })]); + + const renderTimelineChunk = () => { + if (!timelineBody) return; + const next = timelineEntries.slice(renderedRows, renderedRows + TIMELINE_CHUNK); + for (const entry of next) { + timelineBody.append( + el("tr", {}, [ + el("td", { class: "pm-seq", text: String(entry.seq ?? "") }), + el("td", { class: "pm-type" }, [ + el("span", { class: "pm-code", text: entry.event_type || "" }), + ]), + el("td", { + text: `${entry.summary || ""}${entry.truncated ? ` ${t.truncated}` : ""}`, + }), + ]), + ); + } + renderedRows += next.length; + const remaining = timelineEntries.length - renderedRows; + timelineFooter.textContent = t.showing(renderedRows, timelineEntries.length); + showMoreButton.hidden = remaining <= 0; + if (remaining > 0) { + showMoreButton.textContent = t.showMore(Math.min(TIMELINE_CHUNK, remaining)); + } + }; + + const renderReport = (data) => { + report.hidden = false; + verdict.textContent = data.verdict || ""; + overview.replaceChildren( + card(t.status, data.status || "-"), + card(t.stopReason, data.stop_reason || "-"), + card(t.seal, `${data.seal_state || "-"} (${data.events_read}/${data.events_total})`), + card(t.agent, data.agent_id || "-"), + card(t.origin, data.origin || "-"), + card( + t.messages, + `${data.message_counts?.user ?? 0} / ${data.message_counts?.assistant ?? 0} / ${data.message_counts?.tool_results ?? 0}`, + ), + card(t.toolFailures, String(data.tool_failures ?? 0)), + card( + t.subagents, + `${data.subagents?.started ?? 0} / ${data.subagents?.ended ?? 0}`, + ), + ); + const delivery = data.delivery || {}; + if (delivery.satisfied !== null && delivery.satisfied !== undefined) { + overview.append( + card( + t.delivery, + `${delivery.satisfied} (${delivery.presented ?? 0}/${delivery.produced ?? 0})`, + ), + ); + } + anomalies.replaceChildren(); + const items = Array.isArray(data.anomalies) ? data.anomalies : []; + if (items.length === 0) { + anomalies.append(el("li", { text: t.none })); + } else { + for (const anomaly of items) { + anomalies.append( + el("li", {}, [ + el("span", { class: "pm-code", text: anomaly.code || "anomaly" }), + el("span", { text: ` — ${anomaly.detail || ""}` }), + ]), + ); + } + } + activity.replaceChildren( + el("li", { + text: `${t.events}: ${data.events_read ?? 0}/${data.events_total ?? 0}`, + }), + ); + timelineEntries = Array.isArray(data.timeline) ? data.timeline : []; + renderedRows = 0; + timelineBody = el("tbody"); + timelineFooter = el("p", { class: "pm-status" }); + showMoreButton = el("button", { + type: "button", + text: t.showMore(TIMELINE_CHUNK), + }); + showMoreButton.addEventListener("click", () => renderTimelineChunk()); + timeline.replaceChildren( + el("table", {}, [ + el("tr", {}, [ + el("th", { text: t.seq }), + el("th", { text: t.event }), + el("th", { text: t.summary }), + ]), + timelineBody, + ]), + el("div", { class: "pm-actions" }, [showMoreButton, timelineFooter]), + ); + renderTimelineChunk(); + caveats.replaceChildren( + ...(Array.isArray(data.caveats) ? data.caveats : []).map((item) => + el("li", { text: item }), + ), + ); + }; + + const clearReport = () => { + report.hidden = true; + pending = null; + timelineEntries = []; + renderedRows = 0; + setBusy(false); + }; + + const generate = async () => { + const payload = payloadFor(); + if (!payload.thread_id || !payload.run_id) { + setStatus(t.missing); + setError(""); + return; + } + setError(""); + setStatus(t.loading); + setBusy(true); + try { + const data = await context.callBackend("report", payload); + if (!alive()) return; + if (!data || data.not_found) { + clearReport(); + setStatus(t.notFound); + return; + } + pending = payload; + renderReport(data); + setStatus(""); + setBusy(false); + } catch { + if (!alive()) return; + clearReport(); + setError(t.failed); + setStatus(""); + } + }; + + const loadLatest = async () => { + const threadId = threadInput.value.trim(); + if (!threadId) { + setStatus(t.missing); + return; + } + setError(""); + setStatus(t.loading); + setBusy(true); + try { + const data = await context.callBackend("latest", { thread_id: threadId }); + if (!alive()) return; + if (!data || data.complete === false) { + runInput.value = ""; + setStatus(t.scanIncomplete(data && data.scanned ? data.scanned : 0)); + return; + } + const run = data.run; + if (!run) { + setStatus(t.noRun); + return; + } + runInput.value = run.run_id || ""; + setStatus(`${t.latestFound}: ${run.run_id} (${run.status})`); + } catch { + if (!alive()) return; + setError(t.failed); + } finally { + if (alive()) setBusy(false); + } + }; + + const download = async () => { + if (!pending) return; + setError(""); + setBusy(true); + try { + const data = await context.callBackend("markdown", pending); + if (!alive()) return; + if (!data || data.not_found) { + setError(t.notFound); + return; + } + const blob = new Blob([data.markdown || ""], { type: "text/markdown" }); + const url = URL.createObjectURL(blob); + const anchor = el("a", { + href: url, + download: data.filename || "postmortem.md", + }); + document.body.append(anchor); + anchor.click(); + anchor.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + setStatus(t.downloaded); + } catch { + if (alive()) setError(t.failed); + } finally { + if (alive()) setBusy(false); + } + }; + + const onSubmit = (event) => { + event.preventDefault(); + void generate(); + }; + form.addEventListener("submit", onSubmit); + latestButton.addEventListener("click", () => void loadLatest()); + downloadButton.addEventListener("click", () => void download()); + + return { + dispose() { + disposed = true; + form.removeEventListener("submit", onSubmit); + root.replaceChildren(); + }, + }; +} + +export default { + apiVersion: 1, + module: "run-postmortem.v1", + icon: "file-text", + surfaces: [ + { + id: "postmortem", + slot: "page", + title: "Run postmortem", + navigation: { + label: "Run postmortem", + labelZh: "运行复盘", + icon: "file-text", + }, + mount, + }, + ], +}; diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/ui_manifest.json b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/ui_manifest.json new file mode 100644 index 0000000000..6f616adbe4 --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/ui_manifest.json @@ -0,0 +1,5 @@ +{ + "schema_version": 1, + "entry": "static/postmortem.mjs", + "files": ["static/postmortem.mjs"] +} diff --git a/examples/deerflow-extension-run-postmortem/tests/test_actions.py b/examples/deerflow-extension-run-postmortem/tests/test_actions.py new file mode 100644 index 0000000000..dd7c98429e --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/tests/test_actions.py @@ -0,0 +1,160 @@ +"""Browser actions: shared derivation, owner binding and result sentinels.""" + +from __future__ import annotations + +import json + +import pytest +from deerflow_extension_api import CompletedRunEvent, CompletedRunEventPage, CompletedRunSnapshot, EvidenceLimits, ExtensionPrincipal, ExtensionRuntimeDeps +from deerflow_extension_api.plugins import ActionContext +from deerflow_extension_api.run_evidence import RunPage, RunStatusView + +from deerflow_extension_run_postmortem.service import PostmortemService, build_actions + + +def snapshot(*, run_id: str = "r1", owner: str = "alice", status: str = "success") -> CompletedRunSnapshot: + return CompletedRunSnapshot(snapshot_ref=f"snap-{run_id}", thread_id="t1", run_id=run_id, owner_id=owner, agent_id="lead_agent", origin="interactive", status=status, seal_state="sealed", event_count=1) + + +class FakeEvidence: + def __init__(self, *, runs: tuple[RunStatusView, ...] = (), snapshots: dict[str, CompletedRunSnapshot] | None = None, run_pages: dict[str | None, RunPage] | None = None) -> None: + self.runs = runs + self.run_pages = run_pages + self.run_calls: list[str | None] = [] + self.snapshots = snapshots or {"r1": snapshot()} + + async def list_changed_runs(self, *, cursor: str | None = None, limit: int = 200) -> RunPage: + self.run_calls.append(cursor) + if self.run_pages is not None: + return self.run_pages.get(cursor, RunPage(items=(), next_cursor=None, has_more=False)) + return RunPage(items=self.runs, next_cursor=None, has_more=False) + + async def get_snapshot(self, *, thread_id: str, run_id: str, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunSnapshot: + return self.snapshots[run_id] + + async def read_events(self, *, snapshot_ref: str, cursor: str | None = None, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunEventPage: + if cursor is not None: + return CompletedRunEventPage() + return CompletedRunEventPage(items=(CompletedRunEvent(event_id="e1", seq=1, event_type="run.start", category="trace", content_json=json.dumps({"status": "running"}), content_bytes=0, content_sha256=""),)) + + +async def service_with(evidence: FakeEvidence) -> tuple[PostmortemService, tuple]: + service = PostmortemService() + await service.start(ExtensionRuntimeDeps(completed_run_evidence=evidence)) + return service, build_actions(service) + + +def actions_by_name(actions: tuple) -> dict: + return {action.name: action.handler for action in actions} + + +def user(name: str) -> ActionContext: + return ActionContext(ExtensionPrincipal(name), {}) + + +async def test_report_action_serves_the_same_derivation_as_the_route(): + _, actions = await service_with(FakeEvidence()) + + report = await actions_by_name(actions)["report"]({"thread_id": "t1", "run_id": "r1", "max_events": 50}, user("alice")) + + assert report["run_id"] == "r1" + assert report["verdict"] == "Run completed successfully." + assert [item["event_type"] for item in report["timeline"]] == ["run.start"] + + +async def test_markdown_action_returns_a_downloadable_document(): + _, actions = await service_with(FakeEvidence()) + + document = await actions_by_name(actions)["markdown"]({"thread_id": "t1", "run_id": "r1"}, user("alice")) + + assert document["filename"] == "postmortem-r1.md" + assert document["markdown"].startswith("# Run postmortem — `r1`") + + +@pytest.mark.parametrize("action_name", ["report", "markdown"]) +async def test_another_owners_run_answers_not_found(action_name: str): + _, actions = await service_with(FakeEvidence(snapshots={"r1": snapshot(owner="bob")})) + + result = await actions_by_name(actions)[action_name]({"thread_id": "t1", "run_id": "r1"}, user("alice")) + + assert result == {"not_found": True} + + +async def test_latest_run_skips_runs_the_caller_does_not_own(): + evidence = FakeEvidence( + runs=( + RunStatusView(thread_id="t1", run_id="old", status="success"), + RunStatusView(thread_id="t1", run_id="theirs", status="success"), + RunStatusView(thread_id="t1", run_id="new", status="error"), + RunStatusView(thread_id="other", run_id="elsewhere", status="success"), + ), + snapshots={"old": snapshot(run_id="old"), "theirs": snapshot(run_id="theirs", owner="bob"), "new": snapshot(run_id="new", status="error")}, + ) + _, actions = await service_with(evidence) + + result = await actions_by_name(actions)["latest"]({"thread_id": "t1"}, user("alice")) + + assert result == {"run": {"run_id": "new", "status": "error", "updated_at": ""}, "complete": True, "scanned": 4} + + +async def test_latest_run_answers_none_when_the_thread_has_no_owned_run(): + evidence = FakeEvidence( + runs=(RunStatusView(thread_id="t1", run_id="theirs", status="success"),), + snapshots={"theirs": snapshot(run_id="theirs", owner="bob")}, + ) + _, actions = await service_with(evidence) + + assert await actions_by_name(actions)["latest"]({"thread_id": "t1"}, user("alice")) == {"run": None, "complete": True, "scanned": 1} + + +@pytest.mark.parametrize( + "payload", + [ + {}, + {"thread_id": "", "run_id": "r1"}, + {"thread_id": "t1", "run_id": "r1", "max_events": 0}, + {"thread_id": "t1", "run_id": "r1", "max_events": "many"}, + {"thread_id": "t1" * 200, "run_id": "r1"}, + ], + ids=["missing", "blank-thread", "zero-events", "non-numeric-events", "oversized-thread"], +) +async def test_invalid_action_payloads_are_refused(payload: dict): + _, actions = await service_with(FakeEvidence()) + + with pytest.raises(ValueError): + await actions_by_name(actions)["report"](payload, user("alice")) + + +async def test_latest_run_follows_the_feed_to_its_end(): + evidence = FakeEvidence( + run_pages={ + None: RunPage(items=(RunStatusView(thread_id="t1", run_id="old", status="success"),), next_cursor="c2", has_more=True), + "c2": RunPage(items=(RunStatusView(thread_id="t1", run_id="new", status="error"),), next_cursor=None, has_more=False), + }, + snapshots={"old": snapshot(run_id="old"), "new": snapshot(run_id="new", status="error")}, + ) + _, actions = await service_with(evidence) + + result = await actions_by_name(actions)["latest"]({"thread_id": "t1"}, user("alice")) + + assert result == {"run": {"run_id": "new", "status": "error", "updated_at": ""}, "complete": True, "scanned": 2} + assert evidence.run_calls == [None, "c2"] + + +async def test_an_unscanned_feed_never_reports_an_older_run_as_latest(): + # The feed is ordered across every thread in the grant, so a run beyond the + # scan bound may be newer than anything this thread showed. + evidence = FakeEvidence( + run_pages={ + None: RunPage(items=(RunStatusView(thread_id="t1", run_id="old", status="success"),), next_cursor="c2", has_more=True), + "c2": RunPage(items=(RunStatusView(thread_id="t2", run_id="other", status="success"),), next_cursor="c3", has_more=True), + "c3": RunPage(items=(RunStatusView(thread_id="t2", run_id="other-2", status="success"),), next_cursor="c4", has_more=True), + }, + snapshots={"old": snapshot(run_id="old")}, + ) + _, actions = await service_with(evidence) + + result = await actions_by_name(actions)["latest"]({"thread_id": "t1"}, user("alice")) + + assert result == {"run": None, "complete": False, "scanned": 3} + assert evidence.run_calls == [None, "c2", "c3"] diff --git a/frontend/src/core/extensions/bundled-documentation.json b/frontend/src/core/extensions/bundled-documentation.json index 82f6ca9ed5..7c08d80a89 100644 --- a/frontend/src/core/extensions/bundled-documentation.json +++ b/frontend/src/core/extensions/bundled-documentation.json @@ -585,16 +585,20 @@ }, "deerflow-extension-run-postmortem": { "schema_version": 1, - "id": "catalog/runPostmortem", + "id": "community.run-postmortem", "locales": { "zh-CN": { "title": "运行复盘", - "description": "把一次已封存运行的事件证据整理成时间线、异常清单与可分享的 Markdown 报告,用来回答“这次为什么失败/卡住”。", + "description": "在会话页把一次已封存运行的事件证据整理成结论、异常清单与时间线,并可下载 Markdown 报告。", "usage": [ { "title": "安装并授权", "description": "通过 make extension-install 安装示例,在 config.yaml 的 plugins 中授予 host_access.evidence 后重启 Gateway。" }, + { + "title": "在工作区打开运行复盘页", + "description": "侧边栏进入“运行复盘”,填入会话与运行 ID(或点“最新一次运行”),生成报告后可下载 Markdown。" + }, { "title": "查看单次运行报告", "description": "调用 /api/extension-run-postmortem/runs/{thread_id}/{run_id} 获取结构化复盘,或在末尾追加 /markdown 下载可分享报告。" @@ -611,12 +615,16 @@ }, "en-US": { "title": "Run postmortem", - "description": "Turns one sealed run's event evidence into a timeline, an anomaly list and a shareable Markdown report that answers \"why did this run fail or stall\".", + "description": "Explain one sealed run from its own evidence on a workspace page: verdict, anomalies and a timeline, with a downloadable Markdown report.", "usage": [ { "title": "Install and grant access", "description": "Install the example with make extension-install, grant host_access.evidence in config.yaml plugins, then restart Gateway." }, + { + "title": "Open the workspace page", + "description": "Open Run postmortem from the sidebar, enter a thread and run ID (or load the latest run), then generate and download the Markdown report." + }, { "title": "Open a run report", "description": "Call /api/extension-run-postmortem/runs/{thread_id}/{run_id} for the structured report, or append /markdown for a shareable document." diff --git a/frontend/src/core/extensions/catalog.ts b/frontend/src/core/extensions/catalog.ts index 4fe2e183cd..97fcf907ae 100644 --- a/frontend/src/core/extensions/catalog.ts +++ b/frontend/src/core/extensions/catalog.ts @@ -86,7 +86,7 @@ export const extensionCatalog = [ { key: "runPostmortem", package: "deerflow-extension-run-postmortem", - namespace: null, + namespace: "community.run-postmortem", }, { key: "lightrag", package: "deerflow-extension-lightrag", namespace: null }, { key: "weknora", package: "deerflow-extension-weknora", namespace: null },