Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(tasks): show persisted execution events in Studio (#4864)

chenyua57d7f941a9d
diff --git a/docs/en/api/17-tasks.md b/docs/en/api/17-tasks.md
index 2021e7d18..abfc22f74 100644
--- a/docs/en/api/17-tasks.md
+++ b/docs/en/api/17-tasks.md
@@ -32,6 +32,7 @@ Task records are persisted in AGFS and can be queried after server restart, subj
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| task_id | str | Yes | - | Task ID returned by a background API |
+| include_events | bool | No | false | Include persisted execution events in the HTTP response |
#### 3. Usage Examples
@@ -115,6 +116,44 @@ ov task status uuid-xxx
`stage` is nullable. Git repository resource import tasks may report `queued`, `fetching`, `parsing`, `finalizing`, or `processing_queue`; other task types may leave it as `null`. Live queue counters are intentionally not part of task status; use observer queue APIs for live counts, or read `result.queue_status` after completion.
+**Recorded execution events (HTTP)**
+
+Request `GET /api/v1/tasks/{task_id}?include_events=true` to also receive `result.execution_events`. The default detail response and task lists omit this field. Events use the same authorization and retention policy as the task record.
+
+```json
+{
+ "items": [
+ {
+ "seq": 1,
+ "recorded_at": "2026-09-09T01:00:00.123456+00:00",
+ "kind": "created",
+ "status": "pending",
+ "stage": null,
+ "operation": null,
+ "error": null
+ }
+ ],
+ "dropped_count": 0,
+ "started_mid_task": false
+}
+```
+
+| Kind | Recorded fact |
+|------|---------------|
+| `created` | TaskTracker created the task record |
+| `status_changed` | TaskTracker accepted a new status, including cancellation and terminal states |
+| `stage_changed` | An execution path reported a different stage while the task was active |
+| `error_recorded` | TaskTracker accepted the task's first sanitized error |
+| `waiting_for_descendants` | The wait path observed unfinished owned queue work, excluding its own work ID |
+
+`recorded_at` is the UTC time TaskTracker recorded the event, not browser polling time or necessarily when an underlying exception occurred. Events and task state are written together before publication. `seq` orders events within this task even when timestamps coincide. `stage` is the last reported task stage; parallel work can report errors from other stages. `operation`, when present, identifies the reporting work item. Errors use the existing sanitization and length limit; this history is not the complete component log or Python traceback.
+
+History retains at most 64 events and 32 KiB of serialized event data. Older entries are removed first, `dropped_count` counts removed entries, and retained sequence numbers are not reset. Events expire with the task. Legacy tasks return `execution_events: null`; if an active legacy task later emits an event, `started_mid_task` is true. No earlier events are reconstructed. An older server can omit the field even when requested. Studio explains these cases and retains task metadata, results and errors.
+
+To instrument another execution point, register its kind in `openviking/service/task_events.py`, add Studio translations, and call `await tracker.record_event(task_id, kind, account_id=..., user_id=..., operation=...)`. This internal API records a fact without changing status or stage; it accepts bounded operation identifiers, not arbitrary log payloads. Existing lifecycle methods automatically record their accepted transitions.
+
+Persisted task files now contain `execution_events`. Rolling back requires a version that preserves unknown task fields (commit `a5166386` or later); older readers may reject these files. Rolling back also stops event reporting, so history for tasks active during a downgrade may be incomplete.
+
**Response Example (completed)**
```json
diff --git a/docs/zh/api/17-tasks.md b/docs/zh/api/17-tasks.md
index ea7bb9b9b..e4edbc19b 100644
--- a/docs/zh/api/17-tasks.md
+++ b/docs/zh/api/17-tasks.md
@@ -32,6 +32,7 @@
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| task_id | str | 是 | - | 后台 API 返回的任务 ID |
+| include_events | bool | 否 | false | 在 HTTP 响应中包含持久化的执行事件 |
#### 3. 使用示例
@@ -115,6 +116,44 @@ ov task status uuid-xxx
`stage` 可以为 `null`。Git 仓库资源导入任务可能报告 `queued`、`fetching`、`parsing`、`finalizing`、`processing_queue`;其他任务类型可能将其留空。实时队列计数不会出现在任务状态中;需要实时数量时使用 observer queue,任务完成后可读取 `result.queue_status`。
+**执行事件记录(HTTP)**
+
+请求 `GET /api/v1/tasks/{task_id}?include_events=true`,即可获得额外的 `result.execution_events` 字段。默认详情响应和任务列表不包含此字段。事件沿用任务记录的权限和保留策略。
+
+```json
+{
+ "items": [
+ {
+ "seq": 1,
+ "recorded_at": "2026-09-09T01:00:00.123456+00:00",
+ "kind": "created",
+ "status": "pending",
+ "stage": null,
+ "operation": null,
+ "error": null
+ }
+ ],
+ "dropped_count": 0,
+ "started_mid_task": false
+}
+```
+
+| 事件类型 | 记录的事实 |
+|----------|------------|
+| `created` | TaskTracker 创建了任务记录 |
+| `status_changed` | TaskTracker 接受了新的任务状态,包括取消过程和终态 |
+| `stage_changed` | 执行路径在任务活跃期间上报了不同的阶段 |
+| `error_recorded` | TaskTracker 接受了任务的首个脱敏错误 |
+| `waiting_for_descendants` | 等待路径发现任务仍有未结束的队列工作,已排除自身 work ID |
+
+`recorded_at` 是 TaskTracker 记录事件的 UTC 时间,不是浏览器轮询时间,也不一定是底层异常发生的时间。事件与任务状态在同一次写入成功后才对外发布。`seq` 确定任务内的事件顺序,即使多个事件时间相同也不会混淆。`stage` 表示任务最后上报的阶段;并行工作可能在其他阶段产生错误。`operation` 存在时标识上报事件的工作项。错误沿用现有脱敏和长度限制;这里不包含完整组件日志或 Python 堆栈。
+
+每个任务最多保留 64 条事件,序列化事件数据不超过 32 KiB。超限时优先删除较早事件,`dropped_count` 记录删除数量,保留事件的序号不重置。事件随任务过期清理。旧任务返回 `execution_events: null`;若旧的活跃任务后来产生事件,则 `started_mid_task` 为 true,不会重建此前的历史。旧版本服务即使收到参数也可能不返回该字段。Studio 会说明这些情况,并保留任务元数据、结果和错误展示。
+
+扩展执行事件时,在 `openviking/service/task_events.py` 注册事件类型、补充 Studio 翻译,然后在实际执行点调用 `await tracker.record_event(task_id, kind, account_id=..., user_id=..., operation=...)`。这个内部接口不修改任务状态或阶段,只接受有长度限制的操作标识,不接受任意日志内容。现有生命周期方法会自动记录它们接受的状态变化。
+
+持久化任务文件新增 `execution_events` 字段。回滚目标需要具备未知任务字段的保留能力(提交 `a5166386` 或之后的版本);更早的读取实现可能拒绝这些文件。回滚期间也会停止上报事件,因此跨降级执行的任务历史可能不完整。
+
**响应示例(完成)**
```json
diff --git a/openviking/server/routers/tasks.py b/openviking/server/routers/tasks.py
index 6c0f13ea8..cbcfb078a 100644
--- a/openviking/server/routers/tasks.py
+++ b/openviking/server/routers/tasks.py
@@ -28,6 +28,7 @@ router = APIRouter(prefix="/api/v1", tags=["tasks"])
@router.get("/tasks/{task_id}")
async def get_task(
task_id: str,
+ include_events: bool = Query(False, description="Include recorded execution events"),
_ctx: RequestContext = Depends(get_request_context),
):
"""Get the status of a single background task."""
@@ -52,7 +53,7 @@ async def get_task(
code="NOT_FOUND",
details={"resource": task_id, "type": "task"},
)
- return Response(status="ok", result=task.to_dict())
+ return Response(status="ok", result=task.to_dict(include_events=include_events))
@router.post("/tasks/{task_id}/cancel")
diff --git a/openviking/service/task_events.py b/openviking/service/task_events.py
new file mode 100644
index 000000000..775ae9e72
--- /dev/null
+++ b/openviking/service/task_events.py
@@ -0,0 +1,61 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Bounded, task-owned execution history stored with each task snapshot."""
+
+import json
+from datetime import datetime, timezone
+from typing import Optional, TypedDict
+
+MAX_TASK_EVENTS = 64
+MAX_TASK_EVENT_BYTES = 32 * 1024
+PROCESS_EVENT_KINDS = frozenset({"waiting_for_descendants"})
+
+
+class TaskEvent(TypedDict):
+ seq: int
+ recorded_at: str
+ kind: str
+ status: str
+ stage: Optional[str]
+ operation: Optional[str]
+ error: Optional[str]
+
+
+class TaskEventHistory(TypedDict):
+ items: list[TaskEvent]
+ dropped_count: int
+ started_mid_task: bool
+
+
+def append_task_event(
+ history: Optional[TaskEventHistory],
+ *,
+ kind: str,
+ status: str,
+ stage: Optional[str],
+ error: Optional[str] = None,
+ operation: Optional[str] = None,
+ recorded_at: Optional[str] = None,
+) -> TaskEventHistory:
+ """Append to an unpublished snapshot; callers supply only public, sanitized fields."""
+ if history is None:
+ history = {"items": [], "dropped_count": 0, "started_mid_task": kind != "created"}
+ items = history["items"]
+ items.append(
+ {
+ "seq": items[-1]["seq"] + 1 if items else 1,
+ "recorded_at": recorded_at or datetime.now(timezone.utc).isoformat(),
+ "kind": kind,
+ "status": status,
+ "stage": stage[:128] if stage is not None else None,
+ "operation": operation,
+ "error": error,
+ }
+ )
+ while (
+ len(items) > MAX_TASK_EVENTS
+ or len(json.dumps(history).encode("utf-8")) > MAX_TASK_EVENT_BYTES
+ ):
+ items.pop(0)
+ history["dropped_count"] += 1
+ return history
diff --git a/openviking/service/task_store.py b/openviking/service/task_store.py
index 9110b07dd..cd9e4ff2c 100644
--- a/openviking/service/task_store.py
+++ b/openviking/service/task_store.py
@@ -187,6 +187,7 @@ def _task_to_payload(task: Any) -> Dict[str, Any]:
"stage": task.stage,
"result": deepcopy(task.result),
"error": task.error,
+ "execution_events": deepcopy(task.execution_events),
"auth": deepcopy(task.auth),
}
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.py
index 38172f948..8722daa99 100644
--- a/openviking/service/task_tracker.py
+++ b/openviking/service/task_tracker.py
@@ -25,6 +25,11 @@ from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import uuid4
+from openviking.service.task_events import (
+ PROCESS_EVENT_KINDS,
+ TaskEventHistory,
+ append_task_event,
+)
from openviking.service.task_store import TaskStore
from openviking.service.task_tracker_concurrency import (
KeyedAsyncLockPool,
@@ -82,13 +87,15 @@ class TaskRecord:
result: Optional[Dict[str, Any]] = None
error: Optional[str] = None
auth: Dict[str, Any] = field(default_factory=dict, repr=False)
+ execution_events: Optional[TaskEventHistory] = None
_extra_fields: Dict[str, Any] = field(
default_factory=dict, init=False, repr=False, compare=False
)
- def to_dict(self) -> Dict[str, Any]:
+ def to_dict(self, *, include_events: bool = False) -> Dict[str, Any]:
"""Serialize for JSON response."""
return {
+ **({"execution_events": deepcopy(self.execution_events)} if include_events else {}),
"task_id": self.task_id,
"task_type": self.task_type,
"status": self.status.value,
@@ -499,7 +506,7 @@ class TaskTracker:
if stage is not None:
updated.stage = stage
updated.updated_at = self._next_updated_at(task)
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
async def update_stage(
self,
@@ -531,7 +538,7 @@ class TaskTracker:
if meta:
updated.meta.update(deepcopy(meta))
updated.updated_at = self._next_updated_at(task)
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
async def update_task_auth(
self,
@@ -565,7 +572,7 @@ class TaskTracker:
updated = deepcopy(task)
updated.auth.update(deepcopy(values))
updated.updated_at = self._next_updated_at(task)
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
async def record_feishu_response(
self,
@@ -585,7 +592,7 @@ class TaskTracker:
updated = deepcopy(task)
updated.meta.setdefault("feishu_responses", {})[entry] = response_id
updated.updated_at = self._next_updated_at(task)
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
await self._dispatcher.run(record)
@@ -662,7 +669,7 @@ class TaskTracker:
updated = deepcopy(task)
updated.status = TaskStatus.CANCELLING
updated.updated_at = self._next_updated_at(task)
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
await self._finalize_task_on_owner(task_id, account_id, user_id)
async def _record_outcome(
@@ -720,7 +727,7 @@ class TaskTracker:
updated.updated_at = self._next_updated_at(task)
updated.auth = {}
try:
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
except _CommittedMutationCancelled as exc:
cancellation = exc
outcome_persisted = True
@@ -777,7 +784,7 @@ class TaskTracker:
updated.status = TaskStatus.CANCELLING
updated.updated_at = self._next_updated_at(task)
try:
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
except _CommittedMutationCancelled as exc:
cancellation = exc
cancellation_persisted = True
@@ -846,7 +853,7 @@ class TaskTracker:
updated.stage = updated.status.value
updated.updated_at = self._next_updated_at(task)
updated.auth = {}
- await self._persist_and_publish("update", updated)
+ await self._persist_and_publish("update", updated, previous=task)
self._work_index.clear_failure(task_id)
logger.info("[TaskTracker] Task %s %s", task_id, updated.status.value)
@@ -944,9 +951,57 @@ class TaskTracker:
async def wait_for_descendants(self, task_id: str, current_work_id: str) -> None:
"""Wait on the same durable work index used by completion and cancellation."""
+ if self._work_index.has_work(task_id, exclude_work_id=current_work_id):
+ task = self._cached_task(task_id)
+ if task and task.account_id and task.user_id:
+ await self.record_event(
+ task_id,
+ "waiting_for_descendants",
+ operation=current_work_id,
+ account_id=task.account_id,
+ user_id=task.user_id,
+ )
while self._work_index.has_work(task_id, exclude_work_id=current_work_id):
await asyncio.sleep(0.05)
+ async def record_event(
+ self,
+ task_id: str,
+ kind: str,
+ *,
+ account_id: str,
+ user_id: str,
+ operation: Optional[str] = None,
+ ) -> None:
+ """Record a registered process event without changing task status or stage.
+
+ Add process event kinds here and their Studio translations when instrumenting
+ new execution points. Callers report facts, not inferred lifecycle transitions.
+ """
+ self._validate_owner(account_id, user_id)
+ if kind not in PROCESS_EVENT_KINDS:
+ raise ValueError(f"Unknown task process event: {kind}")
+ if operation is not None and not re.fullmatch(r"[\w.:-]{1,128}", operation):
+ raise ValueError("operation must be a bounded operation identifier")
+
+ async def record() -> None:
+ async with self._task_locks.acquire(task_id):
+ task = await self._load_for_update(task_id, account_id, user_id)
+ if task is None or task.status not in _ACTIVE_STATUSES:
+ return
+ updated = deepcopy(task)
+ updated.execution_events = append_task_event(
+ updated.execution_events,
+ kind=kind,
+ status=task.status.value,
+ stage=_sanitize_error(task.stage) if task.stage else None,
+ operation=operation,
+ )
+ updated.updated_at = self._next_updated_at(task)
+ await self._persist_and_publish("update", updated, previous=task)
+
+ await self._dispatcher.run(record)
+
def has_work(self, task_id: str) -> bool:
"""Return whether a task still owns durable or active queue work."""
return self._work_index.has_work(task_id)
@@ -1129,7 +1184,36 @@ class TaskTracker:
)
]
- async def _persist_and_publish(self, operation: str, task: TaskRecord) -> None:
+ async def _persist_and_publish(
+ self, operation: str, task: TaskRecord, *, previous: Optional[TaskRecord] = None
+ ) -> None:
+ # All mutation callers supply the snapshot read under this task's lock.
+ # Build history before the same physical write as the state transition.
+ if operation == "update" and previous is None:
+ raise ValueError("Task updates require the previous snapshot")
+ kinds = []
+ if previous is None:
+ kinds.append("created")
+ else:
+ if task.error is not None and previous.error is None:
+ kinds.append("error_recorded")
+ if task.status != previous.status:
+ kinds.append("status_changed")
+ if task.stage != previous.stage and task.status not in _TERMINAL_STATUSES:
+ kinds.append("stage_changed")
+ stage = previous.stage if previous and task.status in _TERMINAL_STATUSES else task.stage
+ recorded_at = datetime.now(timezone.utc).isoformat()
+ for kind in kinds:
+ task.execution_events = append_task_event(
+ task.execution_events,
+ kind=kind,
+ status=task.status.value,
+ stage=_sanitize_error(stage) if stage else None,
+ error=_sanitize_error(task.error)
+ if kind == "error_recorded" and task.error is not None
+ else None,
+ recorded_at=recorded_at,
+ )
committed = False
async def write_and_publish() -> None:
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index 842979f9d..abeeccc75 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -415,7 +415,11 @@ async def test_task_endpoints_require_auth():
app = _build_task_http_test_app(identity=None)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- for url in ("/api/v1/tasks", "/api/v1/tasks/nonexistent-id"):
+ for url in (
+ "/api/v1/tasks",
+ "/api/v1/tasks/nonexistent-id",
+ "/api/v1/tasks/nonexistent-id?include_events=true",
+ ):
resp = await client.get(url)
assert resp.status_code == 401
set_task_tracker(None)
@@ -455,16 +459,24 @@ async def test_task_endpoints_are_user_scoped():
alice_get = await alice_client.get(f"/api/v1/tasks/{alice_task.task_id}")
assert alice_get.status_code == 200
assert alice_get.json()["result"]["resource_id"] == "alice-session"
+ assert "execution_events" not in alice_get.json()["result"]
+ with_events = await alice_client.get(
+ f"/api/v1/tasks/{alice_task.task_id}?include_events=true"
+ )
+ assert with_events.json()["result"]["execution_events"]["items"][0]["kind"] == "created"
alice_list = await alice_client.get("/api/v1/tasks")
assert alice_list.status_code == 200
assert {task["task_id"] for task in alice_list.json()["result"]} == {alice_task.task_id}
+ assert all("execution_events" not in task for task in alice_list.json()["result"])
async with httpx.AsyncClient(
transport=bob_transport, base_url="http://testserver"
) as bob_client:
bob_get_other = await bob_client.get(f"/api/v1/tasks/{alice_task.task_id}")
assert bob_get_other.status_code == 404
+ bob_events = await bob_client.get(f"/api/v1/tasks/{alice_task.task_id}?include_events=true")
+ assert bob_events.status_code == 404
bob_list = await bob_client.get("/api/v1/tasks")
assert bob_list.status_code == 200
@@ -1810,9 +1822,7 @@ async def test_watcher_reloads_on_signature_change(auth_service):
from openviking.server.auth.plugins import ApiKeyAuthPlugin
manager = _FakeManager(signatures=[("sig-a",), ("sig-b",)])
- task = asyncio.create_task(
- ApiKeyAuthPlugin._watch_key_store(manager, interval=0.01)
- )
+ task = asyncio.create_task(ApiKeyAuthPlugin._watch_key_store(manager, interval=0.01))
try:
await asyncio.sleep(0.1)
finally:
@@ -1828,9 +1838,7 @@ async def test_watcher_skips_reload_when_unchanged(auth_service):
from openviking.server.auth.plugins import ApiKeyAuthPlugin
manager = _FakeManager(signatures=[("sig-stable",)])
- task = asyncio.create_task(
- ApiKeyAuthPlugin._watch_key_store(manager, interval=0.01)
- )
+ task = asyncio.create_task(ApiKeyAuthPlugin._watch_key_store(manager, interval=0.01))
try:
await asyncio.sleep(0.08)
finally:
diff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.py
index 4685527bd..f41926c95 100644
--- a/tests/test_task_tracker.py
+++ b/tests/test_task_tracker.py
@@ -3,6 +3,7 @@
"""Unit tests for TaskTracker."""
+import asyncio
import json
import time
from copy import deepcopy
@@ -827,3 +828,132 @@ async def test_feishu_response_checkpoint_survives_reload(tracker):
restored = TaskTracker(store=tracker._store)
record = await restored.get(task.task_id, **_owner_kwargs())
assert record.meta["feishu_responses"] == {"nested/doc": "response-1"}
+
+
+async def test_execution_events_survive_restart_and_preserve_reported_facts():
+ store = PersistentTaskStore(_FakeAgfs())
+ tracker = TaskTracker(store=store)
+ owner = _owner_kwargs()
+ task = await tracker.create("add_resource", **owner)
+ await tracker.start(task.task_id, stage="parsing", **owner)
+ await tracker.start(task.task_id, stage="parsing", **owner)
+ await tracker.record_event(task.task_id, "waiting_for_descendants", operation="work-1", **owner)
+ await tracker.fail(task.task_id, "provider rejected sk-testsecret123", **owner)
+ before = (await tracker.get(task.task_id, **owner)).to_dict(include_events=True)
+ restored = (await TaskTracker(store=store).get(task.task_id, **owner)).to_dict(
+ include_events=True
+ )
+ assert restored == before
+ events = restored["execution_events"]["items"]
+ assert [event["kind"] for event in events] == [
+ "created",
+ "status_changed",
+ "stage_changed",
+ "waiting_for_descendants",
+ "error_recorded",
+ "status_changed",
+ ]
+ assert [event["seq"] for event in events] == list(range(1, 7))
+ assert events[-1]["status"] == "failed"
+ assert events[-1]["stage"] == "parsing"
+ assert "[REDACTED]" in events[-2]["error"]
+ assert "testsecret123" not in json.dumps(restored)
+ assert "execution_events" not in (await tracker.get(task.task_id, **owner)).to_dict()
+
+
[email protected]("outcome", ["complete", "fail"])
+async def test_terminal_event_waits_for_owned_work(tracker, outcome):
+ from openviking.service.task_work_index import QueueTaskMetadata, TaskWorkIndex
+
+ owner = _owner_kwargs()
+ task = await tracker.create("add_resource", **owner)
+ await tracker.start(task.task_id, **owner)
+ work_index = TaskWorkIndex()
+ tracker.attach_work_index(work_index)
+ child = QueueTaskMetadata(task.task_id, "child-work", "acme", "alice")
+ work_index.register("Semantic", child)
+ await getattr(tracker, outcome)(
+ task.task_id, {"done": True} if outcome == "complete" else "error", **owner
+ )
+ snapshot = await tracker.get(task.task_id, **owner)
+ assert snapshot.status == TaskStatus.RUNNING
+ waiting = asyncio.create_task(tracker.wait_for_descendants(task.task_id, "parent-work"))
+
+ # Observe the public history while work remains, not a helper call sequence.
+ async def observed_wait():
+ while True:
+ record = await tracker.get(task.task_id, **owner)
+ if record.execution_events["items"][-1]["kind"] == "waiting_for_descendants":
+ return
+ await asyncio.sleep(0)
+
+ try:
+ await asyncio.wait_for(observed_wait(), timeout=2)
+ finally:
+ await work_index.prepare_ack("Semantic", child)
+ await waiting
+ snapshot = await tracker.get(task.task_id, **owner)
+ last = snapshot.execution_events["items"][-1]
+ assert last["kind"] == "status_changed"
+ assert last["status"] == ("completed" if outcome == "complete" else "failed")
+ await tracker.wait_for_descendants(task.task_id, "parent-work")
+ assert (await tracker.get(task.task_id, **owner)).execution_events == snapshot.execution_events
+
+
+async def test_legacy_tasks_do_not_get_invented_history():
+ agfs = _FakeAgfs()
+ store = PersistentTaskStore(agfs)
+ task = await TaskTracker(store=store).create("session_commit", **_owner_kwargs())
+ path = f"/local/acme/_system/tasks/alice/{task.task_id}.json"
+ payload = json.loads(agfs.files[path])
+ payload.pop("execution_events")
+ agfs.files[path] = json.dumps(payload).encode()
+ reader = TaskTracker(store=store)
+ assert (await reader.get(task.task_id, **_owner_kwargs())).execution_events is None
+ await reader.start(task.task_id, **_owner_kwargs())
+ history = (await reader.get(task.task_id, **_owner_kwargs())).execution_events
+ assert history["started_mid_task"] is True
+ assert [event["kind"] for event in history["items"]] == ["status_changed"]
+
+
[email protected]("stage_prefix", ["stage", "阶段" * 64])
+async def test_event_history_is_bounded_and_reports_truncation(tracker, stage_prefix):
+ from openviking.service.task_events import MAX_TASK_EVENT_BYTES, MAX_TASK_EVENTS
+
+ task = await tracker.create("add_resource", **_owner_kwargs())
+ for index in range(80):
+ await tracker.update_stage(task.task_id, f"{index}:{stage_prefix}", **_owner_kwargs())
+ await tracker.complete(task.task_id, {"done": True}, **_owner_kwargs())
+ history = (await tracker.get(task.task_id, **_owner_kwargs())).execution_events
+ assert len(history["items"]) <= MAX_TASK_EVENTS
+ assert len(json.dumps(history).encode()) <= MAX_TASK_EVENT_BYTES
+ assert history["dropped_count"] + len(history["items"]) == 82
+ assert history["items"][0]["seq"] == history["dropped_count"] + 1
+ assert history["items"][-1]["status"] == "completed"
+
+
+async def test_process_events_respect_owner_and_terminal_boundaries(tracker):
+ task = await tracker.create("add_resource", **_owner_kwargs())
+ await tracker.record_event(
+ task.task_id, "waiting_for_descendants", account_id="acme", user_id="bob"
+ )
+ assert (
+ await tracker.get(task.task_id, **_owner_kwargs())
+ ).execution_events == task.execution_events
+ with pytest.raises(ValueError, match="Unknown task process event"):
+ await tracker.record_event(task.task_id, "completed", **_owner_kwargs())
+ with pytest.raises(ValueError, match="operation"):
+ await tracker.record_event(
+ task.task_id, "waiting_for_descendants", operation="Bearer secret", **_owner_kwargs()
+ )
+ await tracker.cancel(task.task_id, **_owner_kwargs())
+ cancelled = await tracker.get(task.task_id, **_owner_kwargs())
+ assert [event["status"] for event in cancelled.execution_events["items"]] == [
+ "pending",
+ "cancelling",
+ "cancelled",
+ ]
+ await tracker.record_event(task.task_id, "waiting_for_descendants", **_owner_kwargs())
+ assert (
+ await tracker.get(task.task_id, **_owner_kwargs())
+ ).execution_events == cancelled.execution_events
diff --git a/tests/test_task_tracker_concurrency.py b/tests/test_task_tracker_concurrency.py
index fb19e50b4..5e2f784dd 100644
--- a/tests/test_task_tracker_concurrency.py
+++ b/tests/test_task_tracker_concurrency.py
@@ -36,6 +36,7 @@ class _ControllableTaskStore:
"stage": task.stage,
"result": deepcopy(task.result),
"error": task.error,
+ "execution_events": deepcopy(task.execution_events),
}
async def create(self, task: Any) -> None:
@@ -562,6 +563,8 @@ async def test_task_tracker_failed_update_does_not_contaminate_cached_snapshot()
snapshot = await tracker.get(task.task_id)
assert snapshot is not None
assert snapshot.status == TaskStatus.PENDING
+ assert snapshot.execution_events == task.execution_events
+ assert store.payloads[task.task_id]["execution_events"] == task.execution_events
@pytest.mark.asyncio
@@ -588,6 +591,12 @@ async def test_cancelled_thread_write_settles_before_later_same_task_mutation():
assert snapshot is not None
assert snapshot.status == TaskStatus.COMPLETED
assert store.payloads[task.task_id]["status"] == TaskStatus.COMPLETED.value
+ assert store.payloads[task.task_id]["execution_events"] == snapshot.execution_events
+ assert [event["status"] for event in snapshot.execution_events["items"]] == [
+ "pending",
+ "running",
+ "completed",
+ ]
assert tracker._task_locks.entry_count == 0
assert tracker._store_io.inflight == 0
diff --git a/web-studio/src/gen/ov-client/types.gen.ts b/web-studio/src/gen/ov-client/types.gen.ts
index 9ba2f11d3..700596ebe 100644
--- a/web-studio/src/gen/ov-client/types.gen.ts
+++ b/web-studio/src/gen/ov-client/types.gen.ts
@@ -4115,7 +4115,14 @@ export type GetTaskByTaskIdData = {
*/
task_id: string;
};
- query?: never;
+ query?: {
+ /**
+ * Include Events
+ *
+ * Include recorded execution events
+ */
+ include_events?: boolean;
+ };
url: '/api/v1/tasks/{task_id}';
};
diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.ts
index 06b85d49e..cc0cc2b47 100644
--- a/web-studio/src/i18n/locales/en/workspace.ts
+++ b/web-studio/src/i18n/locales/en/workspace.ts
@@ -405,6 +405,27 @@ const workspace = {
noResultCancelledDescription:
'This task was cancelled before it returned a result.',
},
+ events: {
+ title: 'Task execution log',
+ description:
+ 'Reported task events. Times show when the backend recorded each event.',
+ created: 'Task registered',
+ statusChanged: 'Task status changed to {{status}}',
+ stageChanged: 'Reported stage changed to {{stage}}',
+ errorRecorded: 'Backend recorded an error',
+ waitingForDescendants:
+ 'Unfinished work remains; waiting for owned work to settle',
+ stageContext: 'Last reported stage: {{stage}}',
+ operation: 'Operation: {{operation}}',
+ partial: 'Only events recorded after tracking began are available.',
+ truncated: '{{count}} earlier events were truncated.',
+ unsupported: 'The server did not provide task events.',
+ empty: 'No execution events were recorded for this task.',
+ copy: 'Copy events',
+ copied: 'Events copied',
+ copyFailed: 'Could not copy events',
+ context: 'Current task context',
+ },
filters: {
label: 'Filter',
type: 'Task type',
diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.ts
index f5b5fb97f..5bcf6b7af 100644
--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts
+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts
@@ -390,6 +390,25 @@ const workspace = {
noResultFailedDescription: '该任务未返回结果,请查看上方失败原因。',
noResultCancelledDescription: '该任务已取消,未返回执行结果。',
},
+ events: {
+ title: '任务执行日志',
+ description: '显示已上报的任务事件,时间为后端记录各事件的时间。',
+ created: '任务已登记',
+ statusChanged: '任务状态变更为{{status}}',
+ stageChanged: '上报阶段变更为 {{stage}}',
+ errorRecorded: '后端记录到错误',
+ waitingForDescendants: '仍有所属工作未完成,等待其结束',
+ stageContext: '最近上报的阶段:{{stage}}',
+ operation: '操作:{{operation}}',
+ partial: '仅包含开始记录后的事件,较早过程未记录。',
+ truncated: '较早的 {{count}} 条事件已截断。',
+ unsupported: '服务端未提供任务事件。',
+ empty: '该任务没有已记录的执行事件。',
+ copy: '复制事件',
+ copied: '事件已复制',
+ copyFailed: '复制事件失败',
+ context: '当前任务上下文',
+ },
filters: {
label: '筛选',
type: '任务类型',
diff --git a/web-studio/src/routes/tasks/-components/task-detail-sheet.test.tsx b/web-studio/src/routes/tasks/-components/task-detail-sheet.test.tsx
new file mode 100644
index 000000000..8c3614264
--- /dev/null
+++ b/web-studio/src/routes/tasks/-components/task-detail-sheet.test.tsx
@@ -0,0 +1,187 @@
+// @vitest-environment jsdom
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react'
+import { createInstance } from 'i18next'
+import { I18nextProvider } from 'react-i18next'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import en from '#/i18n/locales/en/workspace'
+import zh from '#/i18n/locales/zh-CN/workspace'
+import { TaskDetailSheet } from './task-detail-sheet'
+import type { TaskRecord } from '../-lib/task-record'
+
+const api = vi.hoisted(() => ({ getTask: vi.fn(), copy: vi.fn() }))
+vi.mock('#/lib/ov-client', () => ({
+ getTaskByTaskId: api.getTask,
+ getOvResult: async (result: Promise<unknown>) => await result,
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+
+const task: TaskRecord = {
+ task_id: 'task-1',
+ task_type: 'session_commit',
+ resource_id: 'session-1',
+ status: 'completed',
+ created_at_iso: '2026-09-09T01:00:00Z',
+ updated_at_iso: '2026-09-09T01:01:00Z',
+ result: { memories: 2 },
+ execution_events: {
+ started_mid_task: true,
+ dropped_count: 2,
+ items: [
+ {
+ seq: 3,
+ recorded_at: '2026-09-09T01:00:59.123Z',
+ kind: 'status_changed',
+ status: 'completed',
+ stage: 'memory_extraction',
+ operation: null,
+ error: null,
+ },
+ ],
+ },
+}
+const clients: QueryClient[] = []
+
+async function showDetail(
+ language = 'en',
+ identity = 'acme/alice',
+ existingClient?: QueryClient,
+) {
+ const i18n = createInstance()
+ await i18n.init({
+ lng: language,
+ fallbackLng: 'en',
+ resources: {
+ en: { tasksPage: en.tasksPage },
+ zh: { tasksPage: zh.tasksPage },
+ },
+ })
+ const client =
+ existingClient ??
+ new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ clients.push(client)
+ const view = render(
+ <I18nextProvider i18n={i18n}>
+ <QueryClientProvider client={client}>
+ <TaskDetailSheet
+ open
+ taskId="task-1"
+ identityScopeKey={identity}
+ onOpenChange={vi.fn()}
+ />
+ </QueryClientProvider>
+ </I18nextProvider>,
+ )
+ return { client, ...view }
+}
+
+beforeEach(() => {
+ api.getTask.mockReset().mockResolvedValue(structuredClone(task))
+ api.copy.mockReset().mockResolvedValue(undefined)
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: api.copy },
+ })
+})
+afterEach(() => {
+ cleanup()
+ clients.splice(0).forEach((client) => client.clear())
+ localStorage.clear()
+})
+
+describe('recorded task execution events', () => {
+ it.each(['en', 'zh'])(
+ 'shows and copies backend events in %s without synthetic lines',
+ async (language) => {
+ localStorage.setItem(
+ 'ov_studio_task_history',
+ JSON.stringify([{ ...task, resource_id: 'stale-private-session' }]),
+ )
+ await showDetail(language)
+ const title = language === 'en' ? 'Task execution log' : '任务执行日志'
+ const events = await screen.findByRole('region', { name: title })
+ expect(api.getTask).toHaveBeenCalledWith({
+ path: { task_id: 'task-1' },
+ query: { include_events: true },
+ })
+ expect(within(events).getAllByRole('listitem')).toHaveLength(1)
+ expect(events.querySelector('time')?.dateTime).toBe(
+ '2026-09-09T01:00:59.123Z',
+ )
+ expect(screen.queryByText('stale-private-session')).toBeNull()
+ expect(events.textContent).not.toContain('WorkerThread')
+ fireEvent.click(
+ within(events).getByRole('button', {
+ name: language === 'en' ? 'Copy events' : '复制事件',
+ }),
+ )
+ await waitFor(() => expect(api.copy).toHaveBeenCalledOnce())
+ const copied = api.copy.mock.calls[0][0]
+ expect(copied).toContain('task-1')
+ expect(copied).toContain('session-1')
+ expect(copied).toContain('2026-09-09T01:00:59.123Z')
+ expect(copied).not.toContain('2026-09-09T01:00:00Z')
+ expect(copied).toContain(
+ language === 'en' ? '2 earlier events' : '2 条事件',
+ )
+ expect(copied).toContain(language === 'en' ? 'tracking began' : '仅包含')
+ },
+ )
+
+ it.each([
+ [undefined, 'The server did not provide task events.'],
+ [null, 'No execution events were recorded for this task.'],
+ ])(
+ 'explains unavailable history while preserving task details',
+ async (history, message) => {
+ api.getTask.mockResolvedValue({ ...task, execution_events: history })
+ await showDetail()
+ expect(await screen.findByText(message)).toBeDefined()
+ expect(screen.getByText('session-1')).toBeDefined()
+ expect(
+ screen
+ .getByRole('button', { name: 'Copy events' })
+ .hasAttribute('disabled'),
+ ).toBe(true)
+ },
+ )
+
+ it('retains the last recorded events and reports a refresh error', async () => {
+ const { client } = await showDetail()
+ await screen.findByRole('region', { name: 'Task execution log' })
+ api.getTask.mockRejectedValue(new Error('UNAUTHENTICATED: expired key'))
+ await act(async () => {
+ await client.refetchQueries({ queryKey: ['task-detail'] })
+ })
+ expect(await screen.findByRole('alert')).toBeDefined()
+ expect(screen.getByRole('alert').textContent).toContain('UNAUTHENTICATED')
+ expect(
+ screen.getByRole('region', { name: 'Task execution log' }),
+ ).toBeDefined()
+ })
+
+ it('keeps unfamiliar event types visible and never imports another identity cache', async () => {
+ const changed = structuredClone(task)
+ changed.execution_events!.items[0].kind = 'future_process_event'
+ api.getTask.mockResolvedValue(changed)
+ const first = await showDetail()
+ expect(await screen.findByText('future_process_event')).toBeDefined()
+ first.unmount()
+ api.getTask.mockRejectedValue(new Error('NOT_FOUND: task not visible'))
+ await showDetail('en', 'acme/bob', first.client)
+ expect(await screen.findByText('NOT_FOUND: task not visible')).toBeDefined()
+ expect(screen.queryByText('future_process_event')).toBeNull()
+ })
+})
diff --git a/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
index 53e9e0a5d..93f730f7d 100644
--- a/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
+++ b/web-studio/src/routes/tasks/-components/task-detail-sheet.tsx
@@ -6,7 +6,6 @@ import {
CircleDashedIcon,
CircleXIcon,
ClipboardListIcon,
- CopyIcon,
FileJson2Icon,
FolderSearch2Icon,
Layers3Icon,
@@ -15,7 +14,6 @@ import {
TimerResetIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
-import { toast } from 'sonner'
import { Button } from '#/components/ui/button'
import {
@@ -26,7 +24,6 @@ import {
SheetTitle,
} from '#/components/ui/sheet'
import { getOvResult, getTaskByTaskId } from '#/lib/ov-client'
-import { cn } from '#/lib/utils'
import { formatTaskDuration, getTaskDate } from '#/routes/tasks/-lib/task-time'
import {
@@ -36,6 +33,7 @@ import {
} from '../-lib/task-record'
import type { TaskRecord } from '../-lib/task-record'
import { getTaskPipelineSteps } from '../-lib/task-pipeline'
+import { TaskExecutionEvents } from './task-execution-events'
type TaskDetailSheetProps = {
identityScopeKey: string
@@ -45,34 +43,15 @@ type TaskDetailSheetProps = {
}
async function fetchTask(taskId: string): Promise<TaskRecord> {
- if (typeof window !== 'undefined') {
- try {
- const raw = localStorage.getItem('ov_studio_task_history')
- if (raw) {
- const history = JSON.parse(raw)
- if (Array.isArray(history)) {
- const match = history.find((t: Record<string, any>) => t.task_id === taskId)
- if (match) return match as TaskRecord
- }
- }
- } catch {
- // Ignore storage errors
- }
- }
-
- try {
- const result = await getOvResult<unknown>(
- getTaskByTaskId({
- path: { task_id: taskId },
- }),
- )
- const task = normalizeTaskRecord(result)
- if (task) return task
- } catch (err) {
- console.warn('[fetchTask] Backend fetch failed for taskId:', taskId, err)
- }
-
- throw new Error('Task not found or expired')
+ const result = await getOvResult<unknown>(
+ getTaskByTaskId({
+ path: { task_id: taskId },
+ query: { include_events: true },
+ }),
+ )
+ const task = normalizeTaskRecord(result)
+ if (task) return task
+ throw new Error('Invalid task response')
}
export function TaskDetailSheet({
@@ -120,7 +99,7 @@ export function TaskDetailSheet({
<LoaderCircleIcon className="size-4 animate-spin" />
{t('detail.loading')}
</div>
- ) : detailQuery.isError ? (
+ ) : detailQuery.isError && !task ? (
<div className="flex min-h-48 flex-col items-center justify-center gap-3 text-center">
<CircleXIcon className="size-8 text-destructive/70" />
<div className="grid gap-1">
@@ -141,65 +120,115 @@ export function TaskDetailSheet({
{t('detail.retry')}
</Button>
</div>
- ) : task ? (() => {
- const status = normalizeTaskStatus(task.status)
- return (
- <div className="grid gap-6">
- <div className="grid grid-cols-2 gap-2">
- <DetailField
- icon={<ActivityIcon />}
- label={t('detail.fields.status')}
- value={t(`status.${status}`)}
- />
- <DetailField
- icon={<Layers3Icon />}
- label={t('detail.fields.type')}
- value={t(`types.${task.task_type}`) || task.task_type || '-'}
- />
- <DetailField
- className="col-span-2"
- icon={<TimerResetIcon />}
- label={t('detail.fields.stage')}
- value={(() => {
- const raw = task.stage
- if (!raw) return '-'
- // If stage is just echoing the task status, it's redundant - hide it
- if (['completed', 'failed', 'pending', 'running', 'unknown'].includes(raw)) return '-'
- return raw
- })()}
- />
- <DetailField
- className="col-span-2"
- icon={<FolderSearch2Icon />}
- label={t('detail.fields.resource')}
- value={task.resource_id || '-'}
- mono
- />
- <DetailField
- icon={<CalendarClockIcon />}
- label={t('detail.fields.createdAt')}
- value={formatTaskTime(task, i18n.resolvedLanguage, 'created')}
- />
- <DetailField
- icon={<RefreshCwIcon />}
- label={t('detail.fields.updatedAt')}
- value={formatTaskTime(task, i18n.resolvedLanguage, 'updated')}
- />
- <DetailField
- className="col-span-2"
- icon={<TimerResetIcon />}
- label={i18n.language.startsWith('zh') ? '执行耗时 / 已用时长' : 'Duration'}
- value={formatTaskDuration(task, i18n.language.startsWith('zh'))}
- mono
- />
- </div>
+ ) : task ? (
+ (() => {
+ const status = normalizeTaskStatus(task.status)
+ return (
+ <div className="grid gap-6">
+ {detailQuery.isError && (
+ <div
+ role="alert"
+ className="grid gap-2 text-sm text-destructive"
+ >
+ <p>
+ {t('detail.loadFailed')}: {String(detailQuery.error)}
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void detailQuery.refetch()}
+ >
+ {t('detail.retry')}
+ </Button>
+ </div>
+ )}
+ <div className="grid grid-cols-2 gap-2">
+ <DetailField
+ icon={<ActivityIcon />}
+ label={t('detail.fields.status')}
+ value={t(`status.${status}`)}
+ />
+ <DetailField
+ icon={<Layers3Icon />}
+ label={t('detail.fields.type')}
+ value={
+ t(`types.${task.task_type}`) || task.task_type || '-'
+ }
+ />
+ <DetailField
+ className="col-span-2"
+ icon={<TimerResetIcon />}
+ label={t('detail.fields.stage')}
+ value={(() => {
+ const raw = task.stage
+ if (!raw) return '-'
+ // If stage is just echoing the task status, it's redundant - hide it
+ if (
+ [
+ 'completed',
+ 'failed',
+ 'pending',
+ 'running',
+ 'unknown',
+ ].includes(raw)
+ )
+ return '-'
+ return raw
+ })()}
+ />
+ <DetailField
+ className="col-span-2"
+ icon={<FolderSearch2Icon />}
+ label={t('detail.fields.resource')}
+ value={task.resource_id || '-'}
+ mono
+ />
+ <DetailField
+ icon={<CalendarClockIcon />}
+ label={t('detail.fields.createdAt')}
+ value={formatTaskTime(
+ task,
+ i18n.resolvedLanguage,
+ 'created',
+ )}
+ />
+ <DetailField
+ icon={<RefreshCwIcon />}
+ label={t('detail.fields.updatedAt')}
+ value={formatTaskTime(
+ task,
+ i18n.resolvedLanguage,
+ 'updated',
+ )}
+ />
+ <DetailField
+ className="col-span-2"
+ icon={<TimerResetIcon />}
+ label={
+ i18n.language.startsWith('zh')
+ ? '执行耗时 / 已用时长'
+ : 'Duration'
+ }
+ value={formatTaskDuration(
+ task,
+ i18n.language.startsWith('zh'),
+ )}
+ mono
+ />
+ </div>
{/* Worker Sub-Queue Pipeline Diagram (Type-Aware) */}
{(() => {
const steps = getTaskPipelineSteps(task, i18n.language)
return (
- <DetailSection title={i18n.language.startsWith('zh') ? '工序进度' : 'Pipeline Steps'}>
+ <DetailSection
+ title={
+ i18n.language.startsWith('zh')
+ ? '工序进度'
+ : 'Pipeline Steps'
+ }
+ >
<div className="rounded-xl border bg-muted/20 p-3 text-xs">
<div className="grid gap-1.5">
{steps.map((st, i) => {
@@ -207,14 +236,35 @@ export function TaskDetailSheet({
const isRun = st.state === 'running'
const isFail = st.state === 'failed'
return (
- <div key={i} className="flex items-center justify-between rounded-lg border bg-background/60 px-3 py-2">
- <span className="font-medium text-foreground">{i + 1}. {st.name}</span>
+ <div
+ key={i}
+ className="flex items-center justify-between rounded-lg border bg-background/60 px-3 py-2"
+ >
+ <span className="font-medium text-foreground">
+ {i + 1}. {st.name}
+ </span>
<span className="flex items-center gap-2 text-[11px]">
{st.count !== undefined && (
- <span className="font-mono text-muted-foreground">{st.count} 项</span>
+ <span className="font-mono text-muted-foreground">
+ {st.count} 项
+ </span>
)}
- <span className={isDone ? 'text-foreground' : isFail ? 'text-destructive' : 'text-muted-foreground'}>
- {isDone ? '已完成' : isRun ? '进行中' : isFail ? '失败' : '等待中'}
+ <span
+ className={
+ isDone
+ ? 'text-foreground'
+ : isFail
+ ? 'text-destructive'
+ : 'text-muted-foreground'
+ }
+ >
+ {isDone
+ ? '已完成'
+ : isRun
+ ? '进行中'
+ : isFail
+ ? '失败'
+ : '等待中'}
</span>
</span>
</div>
@@ -226,99 +276,65 @@ export function TaskDetailSheet({
)
})()}
- {/* Execution Log Section */}
- <DetailSection title={i18n.language.startsWith('zh') ? '📜 任务执行日志' : 'Execution Trace Log'}>
- <div className="relative rounded-xl border border-border/60 bg-muted/30 p-3 font-mono text-[11px] leading-relaxed">
- <div className="flex items-center justify-between border-b border-border/40 pb-2 mb-2 text-[10px] text-muted-foreground font-mono">
- <span>LOG TRACE STREAM (ID: {task.task_id})</span>
- <Button
- variant="ghost"
- size="xs"
- className="h-5 px-1.5 text-[10px] text-muted-foreground hover:text-foreground hover:bg-muted/60 cursor-pointer"
- onClick={() => {
- const logLines = generateStepLogs(task, i18n.language)
- navigator.clipboard.writeText(logLines.join('\n'))
- toast.success(i18n.language.startsWith('zh') ? '日志已成功复制到剪贴板' : 'Logs copied to clipboard')
- }}
- >
- <CopyIcon className="size-3 mr-1" />
- {i18n.language.startsWith('zh') ? '复制日志' : 'Copy Logs'}
- </Button>
- </div>
- <div className="space-y-1 overflow-x-auto max-h-48">
- {generateStepLogs(task, i18n.language).map((line, idx) => {
- const isErr = line.includes('[ERROR]') || line.includes('[FATAL]')
- const isSucc = line.includes('[SUCCESS]')
- const isWarn = line.includes('[WARN]')
- return (
- <div key={idx} className={cn(
- 'whitespace-pre-wrap',
- isErr ? 'text-rose-600 dark:text-rose-400 font-medium' : isSucc ? 'text-cyan-600 dark:text-cyan-400 font-medium' : isWarn ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground'
- )}>
- {line}
- </div>
- )
- })}
- </div>
- </div>
- </DetailSection>
-
- {task.error ? (
- <DetailSection title={t('detail.error')}>
- <p className="whitespace-pre-wrap rounded-xl border border-destructive/25 bg-destructive/5 p-4 font-mono text-xs leading-5 text-destructive">
- {task.error}
- </p>
- </DetailSection>
- ) : null}
+ <TaskExecutionEvents task={task} />
- {status === 'completed' ? (
- hasTaskResult(task.result) ? (
- <DetailSection title={t('detail.result')}>
- <pre className="min-h-[200px] max-h-[400px] overflow-auto rounded-xl border bg-muted/30 p-4 font-mono text-xs leading-5">
- {formatTaskResult(task.result)}
- </pre>
+ {task.error ? (
+ <DetailSection title={t('detail.error')}>
+ <p className="whitespace-pre-wrap rounded-xl border border-destructive/25 bg-destructive/5 p-4 font-mono text-xs leading-5 text-destructive">
+ {task.error}
+ </p>
</DetailSection>
- ) : (
- <div className="flex items-start gap-3 rounded-xl border border-dashed bg-muted/10 p-4">
- <FileJson2Icon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ ) : null}
+
+ {status === 'completed' ? (
+ hasTaskResult(task.result) ? (
+ <DetailSection title={t('detail.result')}>
+ <pre className="min-h-[200px] max-h-[400px] overflow-auto rounded-xl border bg-muted/30 p-4 font-mono text-xs leading-5">
+ {formatTaskResult(task.result)}
+ </pre>
+ </DetailSection>
+ ) : (
+ <div className="flex items-start gap-3 rounded-xl border border-dashed bg-muted/10 p-4">
+ <FileJson2Icon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <div className="grid gap-0.5">
+ <p className="text-sm font-medium">
+ {t('detail.noResultCompleted')}
+ </p>
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t('detail.noResultCompletedDescription')}
+ </p>
+ </div>
+ </div>
+ )
+ ) : status === 'running' ? (
+ <div className="flex items-start gap-3 rounded-xl border border-sky-500/30 bg-sky-500/5 p-4">
+ <LoaderCircleIcon className="mt-0.5 size-4 shrink-0 animate-spin text-sky-500" />
<div className="grid gap-0.5">
- <p className="text-sm font-medium">
- {t('detail.noResultCompleted')}
+ <p className="text-sm font-medium text-sky-600 dark:text-sky-400">
+ {t('detail.noResultRunning')}
</p>
<p className="text-xs leading-5 text-muted-foreground">
- {t('detail.noResultCompletedDescription')}
+ {t('detail.noResultRunningDescription')}
</p>
</div>
</div>
- )
- ) : status === 'running' ? (
- <div className="flex items-start gap-3 rounded-xl border border-sky-500/30 bg-sky-500/5 p-4">
- <LoaderCircleIcon className="mt-0.5 size-4 shrink-0 animate-spin text-sky-500" />
- <div className="grid gap-0.5">
- <p className="text-sm font-medium text-sky-600 dark:text-sky-400">
- {t('detail.noResultRunning')}
- </p>
- <p className="text-xs leading-5 text-muted-foreground">
- {t('detail.noResultRunningDescription')}
- </p>
- </div>
- </div>
- ) : status === 'pending' ? (
- <div className="flex items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4">
- <CircleDashedIcon className="mt-0.5 size-4 shrink-0 text-amber-500" />
- <div className="grid gap-0.5">
- <p className="text-sm font-medium text-amber-600 dark:text-amber-400">
- {t('detail.noResultPending')}
- </p>
- <p className="text-xs leading-5 text-muted-foreground">
- {t('detail.noResultPendingDescription')}
- </p>
+ ) : status === 'pending' ? (
+ <div className="flex items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4">
+ <CircleDashedIcon className="mt-0.5 size-4 shrink-0 text-amber-500" />
+ <div className="grid gap-0.5">
+ <p className="text-sm font-medium text-amber-600 dark:text-amber-400">
+ {t('detail.noResultPending')}
+ </p>
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t('detail.noResultPendingDescription')}
+ </p>
+ </div>
</div>
- </div>
- ) : null}
- </div>
- )
- })() : null}
+ ) : null}
+ </div>
+ )
+ })()
+ ) : null}
</div>
</SheetContent>
</Sheet>
@@ -403,40 +419,3 @@ function formatTaskResult(result: unknown): string {
return String(result)
}
}
-
-function generateStepLogs(task: TaskRecord, lang?: string): string[] {
- const logs: string[] = []
- const createdAtStr = formatTaskTime(task, lang, 'created')
- const status = normalizeTaskStatus(task.status)
-
- logs.push(`[${createdAtStr}] [INFO] [TaskPool] 任务已登记入队: ID=${task.task_id} Type=${task.task_type || 'generic'}`)
- if (task.resource_id) {
- logs.push(`[${createdAtStr}] [INFO] [ResourcePipeline] 关联物理资源路径: ${task.resource_id}`)
- }
-
- if (status === 'pending') {
- logs.push(`[${createdAtStr}] [DEBUG] [WorkerThread] 任务就绪,正等待队列空闲分配 worker...`)
- } else if (status === 'running') {
- logs.push(`[${createdAtStr}] [INFO] [WorkerThread-01] 已由可用 Worker 抢占分发,初始化解构环境`)
- logs.push(`[${createdAtStr}] [INFO] [EmbeddingService] 物理向量索引计算落盘中...`)
- } else if (status === 'completed') {
- logs.push(`[${createdAtStr}] [INFO] [WorkerThread-01] 物理工序 100% 结算完毕,校验物理一致性契约通过`)
- if (task.result && typeof task.result === 'object') {
- const resObj = task.result as Record<string, any>
- if (resObj.reindexed_items) {
- logs.push(`[${createdAtStr}] [SUCCESS] [ReindexWorker] 重置构建向量索引项: ${resObj.reindexed_items} 项`)
- }
- if (resObj.processed) {
- logs.push(`[${createdAtStr}] [SUCCESS] [DataProcessor] 文本分片处理完成: ${resObj.processed} 块`)
- }
- }
- logs.push(`[${createdAtStr}] [SUCCESS] 任务状态自愈闭环无缝更新为 [completed]`)
- } else if (status === 'failed') {
- logs.push(`[${createdAtStr}] [ERROR] [WorkerThread-01] 工序处理触发异常中断`)
- if (task.error) {
- logs.push(`[${createdAtStr}] [FATAL] Error Traceback: ${task.error}`)
- }
- logs.push(`[${createdAtStr}] [WARN] 可随时点击 [重新入队/自愈] 触发自愈流水线二次重试`)
- }
- return logs
-}
diff --git a/web-studio/src/routes/tasks/-components/task-execution-events.tsx b/web-studio/src/routes/tasks/-components/task-execution-events.tsx
new file mode 100644
index 000000000..539c2e2d6
--- /dev/null
+++ b/web-studio/src/routes/tasks/-components/task-execution-events.tsx
@@ -0,0 +1,108 @@
+import { CopyIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+
+import { Button } from '#/components/ui/button'
+import { cn } from '#/lib/utils'
+import { describeTaskEvent, formatTaskEvent } from '../-lib/task-events'
+import type { TaskRecord } from '../-lib/task-record'
+
+export function TaskExecutionEvents({ task }: { task: TaskRecord }) {
+ const { t, i18n } = useTranslation('tasksPage')
+ const history = task.execution_events
+ const notices = [
+ history?.started_mid_task ? t('events.partial') : '',
+ history?.dropped_count
+ ? t('events.truncated', { count: history.dropped_count })
+ : '',
+ ].filter(Boolean)
+
+ async function copyEvents() {
+ const context = {
+ task_id: task.task_id,
+ task_type: task.task_type,
+ resource_id: task.resource_id,
+ }
+ try {
+ await navigator.clipboard.writeText(
+ [
+ `${t('events.context')}: ${JSON.stringify(context)}`,
+ ...notices,
+ ...(history?.items.map((event) => formatTaskEvent(event, t)) ?? []),
+ ].join('\n'),
+ )
+ toast.success(t('events.copied'))
+ } catch {
+ toast.error(t('events.copyFailed'))
+ }
+ }
+
+ return (
+ <section className="grid gap-3" aria-label={t('events.title')}>
+ <div className="flex items-center justify-between gap-3">
+ <h3 className="text-sm font-medium">{t('events.title')}</h3>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={!history?.items.length}
+ onClick={() => void copyEvents()}
+ >
+ <CopyIcon />
+ {t('events.copy')}
+ </Button>
+ </div>
+ <p className="text-xs text-muted-foreground">{t('events.description')}</p>
+ {notices.map((notice) => (
+ <p key={notice} className="text-xs text-muted-foreground">
+ {notice}
+ </p>
+ ))}
+ {!history?.items.length ? (
+ <p className="text-sm text-muted-foreground">
+ {history === undefined ? t('events.unsupported') : t('events.empty')}
+ </p>
+ ) : (
+ <ol className="max-h-64 space-y-3 overflow-auto rounded-md border bg-muted/30 p-3 font-mono text-xs">
+ {history.items.map((event) => (
+ <li
+ key={event.seq}
+ className={cn(
+ 'grid gap-1',
+ (event.error !== null || event.status === 'failed') &&
+ 'text-destructive',
+ )}
+ >
+ <div className="text-muted-foreground">
+ <span>#{event.seq} </span>
+ <time dateTime={event.recorded_at} title={event.recorded_at}>
+ {new Date(event.recorded_at).toLocaleString(
+ i18n.resolvedLanguage,
+ {
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ fractionalSecondDigits: 3,
+ },
+ )}
+ </time>
+ </div>
+ <p>{describeTaskEvent(event, t)}</p>
+ {event.stage && (
+ <p>{t('events.stageContext', { stage: event.stage })}</p>
+ )}
+ {event.operation && (
+ <p>{t('events.operation', { operation: event.operation })}</p>
+ )}
+ {event.error !== null && (
+ <p className="whitespace-pre-wrap break-words">{event.error}</p>
+ )}
+ </li>
+ ))}
+ </ol>
+ )}
+ </section>
+ )
+}
diff --git a/web-studio/src/routes/tasks/-lib/task-events.ts b/web-studio/src/routes/tasks/-lib/task-events.ts
new file mode 100644
index 000000000..6a28fe330
--- /dev/null
+++ b/web-studio/src/routes/tasks/-lib/task-events.ts
@@ -0,0 +1,48 @@
+import type { TFunction } from 'i18next'
+
+export type TaskEvent = {
+ seq: number
+ recorded_at: string
+ kind: string
+ status: string
+ stage: string | null
+ operation: string | null
+ error: string | null
+}
+
+export type TaskEventHistory = {
+ items: TaskEvent[]
+ dropped_count: number
+ started_mid_task: boolean
+}
+
+export function describeTaskEvent(event: TaskEvent, t: TFunction<'tasksPage'>) {
+ switch (event.kind) {
+ case 'created':
+ return t('events.created')
+ case 'status_changed':
+ return t('events.statusChanged', {
+ status: t(`status.${event.status}`, { defaultValue: event.status }),
+ })
+ case 'stage_changed':
+ return t('events.stageChanged', { stage: event.stage ?? '-' })
+ case 'error_recorded':
+ return t('events.errorRecorded')
+ case 'waiting_for_descendants':
+ return t('events.waitingForDescendants')
+ default:
+ return event.kind
+ }
+}
+
+export function formatTaskEvent(event: TaskEvent, t: TFunction<'tasksPage'>) {
+ return [
+ `#${event.seq} [${event.recorded_at}]`,
+ describeTaskEvent(event, t),
+ event.stage ? `stage=${event.stage}` : '',
+ event.operation ? `operation=${event.operation}` : '',
+ event.error ?? '',
+ ]
+ .filter(Boolean)
+ .join(' ')
+}
diff --git a/web-studio/src/routes/tasks/-lib/task-record.ts b/web-studio/src/routes/tasks/-lib/task-record.ts
index e8d56fd8b..5b98146ef 100644
--- a/web-studio/src/routes/tasks/-lib/task-record.ts
+++ b/web-studio/src/routes/tasks/-lib/task-record.ts
@@ -1,4 +1,5 @@
import type { TaskTimestamp } from './task-time'
+import type { TaskEventHistory } from './task-events'
export type TaskStatus =
| 'cancelled'
@@ -11,6 +12,7 @@ export type TaskStatus =
export type TaskRecord = TaskTimestamp & {
error?: string | null
+ execution_events?: TaskEventHistory | null
resource_id?: string | null
result?: unknown
stage?: string | null