- ${labels.tokenDetails}
${labels.tokenDetailsNote}
${labels.cacheHit} ${percentage(total.cached, total.input)}${stats.omittedTurns ? (zh ? "已加载轮次 · " : "Loaded turns · ") : ""}${labels.modelRequests} ${number(modelRequests)}${costCoverage}${contextBadge}
+ ${labels.tokenDetails}
${labels.tokenDetailsNote}
${labels.cacheHit} ${percentage(total.cached, total.input)}${!cost && stats.omittedTurns ? (zh ? "已加载轮次 · " : "Loaded turns · ") : ""}${labels.modelRequests} ${number(modelRequests)}${costCoverage}${contextBadge}
${costModeControls()}
${tokenMetric("total", labels.totalTokens, total.total)}${tokenMetric("input", labels.inputTokens, total.input)}${tokenMetric("cached", labels.cachedInput, total.cached)}${tokenMetric("uncached", labels.uncachedInput, total.uncached)}${tokenMetric("output", labels.outputTokens, total.output)}${tokenMetric("reasoning", labels.reasoningTokens, total.reasoning)}${costMetric(cost)}
${tokenBreakdown(labels.inputBreakdown, total.input, [{ className: "token-new", label: labels.uncachedInput, value: total.uncached }, { className: "token-cached", label: labels.cachedInput, value: total.cached }])}${tokenBreakdown(labels.outputBreakdown, total.output, [{ className: "token-visible", label: labels.visibleOutput, value: total.visible }, { className: "token-reasoning", label: labels.reasoningTokens, value: total.reasoning }])}
diff --git a/plugins/codex-trajectory/scripts/codex_trajectory/projection.py b/plugins/codex-trajectory/scripts/codex_trajectory/projection.py
index 672412d..192ea18 100644
--- a/plugins/codex-trajectory/scripts/codex_trajectory/projection.py
+++ b/plugins/codex-trajectory/scripts/codex_trajectory/projection.py
@@ -17,7 +17,7 @@
from pathlib import Path
from typing import Any
-from . import __version__
+from . import __version__, subagents
from .command_summary import command_activity
from .json_support import strict_json_loads
from .page_index import PageIndex
@@ -905,6 +905,7 @@ def parse_session(
*,
_index: PageIndex | None = None,
_entries: Iterator[tuple[int, int, dict[str, Any]]] | None = None,
+ _usage: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Project one Codex rollout log into a turn-aware trajectory page."""
detail_level = normalize_detail_level(detail_level)
@@ -932,6 +933,7 @@ def detail_json_text(value: Any) -> str | None:
last_model_service_tier: str | None = None
latest_rate_limits: dict[str, dict[str, Any]] | None = None
previous_total_usage: dict[str, int | float] = {}
+ child_agents: set[str] = set()
context_window: int | None = None
current_turn = 0
current_step = 0
@@ -1685,6 +1687,10 @@ def source_entries() -> Iterator[tuple[int, int, dict[str, Any]]]:
_index.flush()
for event_number, line_number, entry in _entries if _entries is not None else source_entries():
+ if _usage is not None:
+ child_agents.update(subagents.referenced_agents(entry))
+ if len(child_agents) > subagents.MAX_TASK_AGENTS:
+ raise ValueError("Task subagent activity exceeds the supported discovery limit.")
entry_type = entry.get("type")
payload = entry.get("payload")
if not isinstance(payload, dict):
@@ -2490,6 +2496,16 @@ def source_entries() -> Iterator[tuple[int, int, dict[str, Any]]]:
"agentPath": safe_text(metadata.get("agent_path"), 200),
"git": git,
}
+ if _usage is not None:
+ _usage.update(
+ tokens=accounted_usage if accounted_usage is not None else latest_usage,
+ cost=session_cost,
+ children=tuple(sorted(child_agents)),
+ fast=bool(fast_cost_calls),
+ readWarnings=any(
+ warning["code"] != "codex_fast_cost_multiplier" for warning in warnings
+ ),
+ )
return {
"schemaVersion": TRAJECTORY_SCHEMA_VERSION,
"detailLevel": detail_level,
@@ -2536,6 +2552,17 @@ def cached_trajectory(
max_records: int = DEFAULT_MAX_RECORDS,
detail_level: DetailLevel = "summary",
before_record: int | None = None,
+) -> dict[str, Any]:
+ """Keep session pages cached while refreshing totals from all descendant agents."""
+ trajectory = _cached_session_trajectory(path, max_records, detail_level, before_record)
+ return subagents.aggregate_usage(path, trajectory)
+
+
+def _cached_session_trajectory(
+ path: Path,
+ max_records: int = DEFAULT_MAX_RECORDS,
+ detail_level: DetailLevel = "summary",
+ before_record: int | None = None,
) -> dict[str, Any]:
"""Return one immutable-signature projection from a small process cache."""
normalized_detail = normalize_detail_level(detail_level)
@@ -2554,13 +2581,17 @@ def cached_trajectory(
if index is None:
try:
index = PageIndex()
- summary = parse_session(path, limited, "summary", before_record, _index=index)
+ usage: dict[str, Any] = {}
+ summary = parse_session(
+ path, limited, "summary", before_record, _index=index, _usage=usage
+ )
index.finish(summary)
if not index.enabled or session_signature(path) != signature:
index.close()
index = None
else:
_PAGE_INDEXES[index_key] = index
+ subagents.remember_usage(path, signature, usage)
except (OSError, sqlite3.Error):
if index is not None:
index.close()
@@ -2625,7 +2656,12 @@ def cached_trajectory(
_, evicted_index = _PAGE_INDEXES.popitem(last=False)
evicted_index.close()
else:
- trajectory = parse_session(path, limited, normalized_detail, before_record)
+ usage = {}
+ trajectory = parse_session(
+ path, limited, normalized_detail, before_record, _usage=usage
+ )
+ if session_signature(path) == signature:
+ subagents.remember_usage(path, signature, usage)
size = len(json.dumps(trajectory, ensure_ascii=True).encode("ascii"))
if session_signature(path) == signature:
with _TRAJECTORY_CACHE_LOCK:
@@ -2805,14 +2841,9 @@ def trajectory_result(
def trajectory_revision(path: Path) -> str:
- """Return an opaque revision for every file in a rollout lineage."""
- digest = hashlib.sha256()
- for item in session_signature(path):
- for value in item:
- encoded = str(value).encode("utf-8", errors="replace")
- digest.update(len(encoded).to_bytes(8, "big"))
- digest.update(encoded)
- return digest.hexdigest()
+ """Refresh task totals when any descendant's log or membership changes."""
+ signature = subagents.task_usage(path).signature
+ return hashlib.sha256(json.dumps(signature, ensure_ascii=True).encode("ascii")).hexdigest()
def trajectory_update_result(arguments: dict[str, Any]) -> dict[str, Any]:
@@ -2841,20 +2872,20 @@ def trajectory_update_result(arguments: dict[str, Any]) -> dict[str, Any]:
):
raise ValueError("maxReadBytes requires an explicit sessionId.")
path = resolve_session(session_id, include_archived)
- current_revision = trajectory_revision(path)
- update: dict[str, Any] = {
- "schemaVersion": TRAJECTORY_SCHEMA_VERSION,
- "unchanged": revision == current_revision,
- "revision": current_revision,
- "quota": latest_account_quota(),
- }
- if revision != current_revision:
- try:
+ try:
+ current_revision = trajectory_revision(path)
+ update: dict[str, Any] = {
+ "schemaVersion": TRAJECTORY_SCHEMA_VERSION,
+ "unchanged": revision == current_revision,
+ "revision": current_revision,
+ "quota": latest_account_quota(),
+ }
+ if revision != current_revision:
update["trajectory"] = cached_trajectory(path, LIVE_MAX_RECORDS, "summary")
- except ReadLimitExceeded as error:
- error.session_id = _read_limit_task_id(path)
- error.session_id_verified = error.session_id is not None
- raise
+ except ReadLimitExceeded as error:
+ error.session_id = _read_limit_task_id(path)
+ error.session_id_verified = error.session_id is not None
+ raise
state = "unchanged" if update["unchanged"] else "updated"
return {
"structuredContent": update,
diff --git a/plugins/codex-trajectory/scripts/codex_trajectory/subagents.py b/plugins/codex-trajectory/scripts/codex_trajectory/subagents.py
new file mode 100644
index 0000000..284ed46
--- /dev/null
+++ b/plugins/codex-trajectory/scripts/codex_trajectory/subagents.py
@@ -0,0 +1,276 @@
+"""Read-only task usage across explicitly related local agent sessions."""
+
+from __future__ import annotations
+
+import json
+import threading
+from collections import OrderedDict, defaultdict, deque
+from contextlib import nullcontext
+from copy import deepcopy
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from . import sessions
+from .pricing import merge_cost_estimates
+
+MAX_CACHED_USAGE = 256
+MAX_USAGE_CACHE_BYTES = 8 * 1024 * 1024
+MAX_CACHED_LINKS = 10_000
+MAX_TASK_AGENTS = sessions.MAX_DISCOVERED_SESSION_FILES
+Signature = tuple[tuple[str, int, int, int], ...]
+_USAGE: OrderedDict[Any, tuple[Signature, dict[str, Any]]] = OrderedDict()
+_USAGE_SIZES: dict[Any, int] = {}
+_LINKS: OrderedDict[Any, tuple[tuple[int, ...], SessionLink]] = OrderedDict()
+_LOCK = threading.Lock()
+
+
+@dataclass(frozen=True)
+class SessionLink:
+ """Keep only identities, never raw session metadata, in discovery caches."""
+
+ session_id: str | None
+ parent_id: str | None
+
+
+@dataclass
+class TaskUsage:
+ members: list[dict[str, Any]]
+ signature: list[Any]
+ unavailable: int = 0
+ read_warnings: int = 0
+
+
+def _identifier(value: Any) -> str | None:
+ if (
+ isinstance(value, str)
+ and 0 < len(value) <= 240
+ and value == value.strip()
+ and not any(char in value for char in ("/", "\\", "\x00"))
+ ):
+ return value
+ return None
+
+
+def referenced_agents(entry: dict[str, Any]) -> set[str]:
+ """Use structured activity IDs, never tool output or arbitrary message text."""
+ payload = entry.get("payload")
+ if entry.get("type") != "event_msg" or not isinstance(payload, dict):
+ return set()
+ if payload.get("type") == "item_completed":
+ payload = payload.get("item")
+ if not isinstance(payload, dict) or payload.get("type") not in {
+ "sub_agent_activity",
+ "SubAgentActivity",
+ }:
+ return set()
+ identifier = _identifier(payload.get("agent_thread_id"))
+ return {identifier} if identifier is not None else set()
+
+
+def remember_usage(path: Path, signature: Signature, usage: dict[str, Any]) -> None:
+ """Reuse compact own-agent accounting independently of displayed history pages."""
+ key = (path, sessions.jsonl_byte_limit())
+ size = len(json.dumps(usage, ensure_ascii=True).encode("ascii"))
+ with _LOCK:
+ _USAGE[key] = (signature, deepcopy(usage))
+ _USAGE_SIZES[key] = size
+ _USAGE.move_to_end(key)
+ while _USAGE and (
+ len(_USAGE) > MAX_CACHED_USAGE or sum(_USAGE_SIZES.values()) > MAX_USAGE_CACHE_BYTES
+ ):
+ old_key, _ = _USAGE.popitem(last=False)
+ _USAGE_SIZES.pop(old_key, None)
+
+
+def _own_usage(path: Path, *, prime_index: bool = False) -> tuple[Signature, dict[str, Any]]:
+ from . import projection
+
+ signature = sessions.session_signature(path)
+ key = (path, sessions.jsonl_byte_limit())
+ with _LOCK:
+ cached = _USAGE.get(key)
+ if cached is not None and cached[0] == signature:
+ _USAGE.move_to_end(key)
+ return signature, deepcopy(cached[1])
+ # Prime the selected task's normal index so its first revision read does not
+ # cause an extra full scan. Children need only a bounded streaming summary.
+ if prime_index:
+ projection._cached_session_trajectory(path, projection.MIN_RECORDS)
+ with _LOCK:
+ cached = _USAGE.get(key)
+ if cached is not None and cached[0] == signature:
+ return signature, deepcopy(cached[1])
+ usage: dict[str, Any] = {}
+ projection.parse_session(path, projection.MIN_RECORDS, _usage=usage)
+ if sessions.session_signature(path) == signature:
+ remember_usage(path, signature, usage)
+ return signature, usage
+
+
+def _session_link(path: Path, *, related: bool = False) -> SessionLink:
+ stat = sessions._safe_file_stat(path)
+ signature = (stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_size, stat.st_ctime_ns)
+ # A larger selected-task budget never expands unrelated metadata probes.
+ with nullcontext() if related else sessions.session_read_limit():
+ key = (path, sessions.jsonl_byte_limit())
+ with _LOCK:
+ cached = _LINKS.get(key)
+ if cached is not None and cached[0] == signature:
+ _LINKS.move_to_end(key)
+ return cached[1]
+ metadata = sessions.first_session_metadata(path)
+ identifier = _identifier(metadata.get("id")) or _identifier(metadata.get("session_id"))
+ parent = _identifier(metadata.get("parent_thread_id"))
+ source = metadata.get("source")
+ if isinstance(source, dict):
+ subagent = source.get("subagent")
+ if isinstance(subagent, dict):
+ spawn = subagent.get("thread_spawn", subagent)
+ if isinstance(spawn, dict):
+ source_parent = _identifier(spawn.get("parent_thread_id"))
+ if parent is not None and source_parent not in (None, parent):
+ raise ValueError("Conflicting subagent parent identities.")
+ parent = parent or source_parent
+ result = SessionLink(identifier, parent)
+ with _LOCK:
+ _LINKS[key] = (signature, result)
+ _LINKS.move_to_end(key)
+ while len(_LINKS) > MAX_CACHED_LINKS:
+ _LINKS.popitem(last=False)
+ return result
+
+
+@sessions.session_scan()
+def task_usage(path: Path) -> TaskUsage:
+ """Follow metadata and activity links, counting each descendant task ID once."""
+ from . import projection
+
+ signature, own = _own_usage(path, prime_index=True)
+ identifier = projection.metadata_identity(sessions.first_session_metadata(path), path)
+ result = TaskUsage([own], [(identifier, signature)])
+ # Standalone parser callers may use synthetic files outside Codex's roots.
+ if not any(sessions.is_safe_session_file(path, root) for root in sessions.session_roots(True)):
+ return result
+ by_id: dict[str, tuple[Path, SessionLink]] = {}
+ by_parent: dict[str, set[str]] = defaultdict(set)
+ deferred: dict[str, Path] = {}
+ referenced = {identifier, *own["children"]}
+ for candidate in sessions.session_files(True):
+ try:
+ named_id = sessions.thread_id_from_path(candidate)
+ link = _session_link(candidate, related=candidate == path or named_id in referenced)
+ except sessions.ReadLimitExceeded:
+ if named_id is not None:
+ deferred.setdefault(named_id, candidate)
+ continue
+ except (OSError, RuntimeError, ValueError):
+ continue
+ if link.session_id is not None and link.session_id not in by_id:
+ # Discovery orders newest rollouts first; resumes and archive copies
+ # of the same logical agent must never be added a second time.
+ by_id[link.session_id] = (candidate, link)
+ if link.parent_id is not None:
+ by_parent[link.parent_id].add(link.session_id)
+ seen = {identifier}
+ pending = deque([(identifier, own)])
+ while pending:
+ parent, parent_usage = pending.popleft()
+ children = by_parent.get(parent, set()) | set(parent_usage["children"])
+ for child in sorted(children):
+ if child in seen:
+ continue
+ candidate_link = by_id.get(child)
+ if candidate_link is None and child in deferred:
+ candidate = deferred[child]
+ # A structured exact reference can authorize a larger metadata
+ # probe for this child, without expanding any other task's budget.
+ link = _session_link(candidate, related=True)
+ if link.session_id == child:
+ candidate_link = (candidate, link)
+ if candidate_link is not None and candidate_link[1].parent_id not in (None, parent):
+ # Root activity can mention a grandchild. Its immediate parent's
+ # metadata edge owns it; a notification cannot reparent a task.
+ continue
+ seen.add(child)
+ if len(seen) > MAX_TASK_AGENTS:
+ raise ValueError("Task subagents exceed the supported discovery limit.")
+ if candidate_link is None:
+ result.unavailable += 1
+ result.signature.append((child, "unavailable"))
+ pending.append((child, {"children": ()}))
+ continue
+ candidate = candidate_link[0]
+ try:
+ child_signature, usage = _own_usage(candidate)
+ except sessions.ReadLimitExceeded:
+ raise
+ except (OSError, RuntimeError, ValueError):
+ result.unavailable += 1
+ try:
+ stat = sessions._safe_file_stat(candidate)
+ result.signature.append(
+ (child, "unreadable", stat.st_mtime_ns, stat.st_size, stat.st_ctime_ns)
+ )
+ except OSError:
+ result.signature.append((child, "unavailable"))
+ pending.append((child, {"children": ()}))
+ continue
+ result.members.append(usage)
+ result.signature.append((child, child_signature))
+ result.read_warnings += bool(usage["readWarnings"])
+ pending.append((child, usage))
+ return result
+
+
+def _with_total(usage: dict[str, Any] | None) -> dict[str, Any] | None:
+ """A missing total in one agent must not disappear into another agent's total."""
+ if usage is None or "total_tokens" in usage:
+ return usage
+ if "input_tokens" not in usage and "output_tokens" not in usage:
+ return usage
+ total = usage.get("input_tokens", 0) + usage.get("output_tokens", 0)
+ if total > 2**53 - 1:
+ raise ValueError("Task token totals exceed the supported integer limit.")
+ return {**usage, "total_tokens": total}
+
+
+def aggregate_usage(path: Path, trajectory: dict[str, Any]) -> dict[str, Any]:
+ """Replace task totals only; each agent's records and turn totals stay its own."""
+ from . import projection
+
+ family = task_usage(path)
+ stats = trajectory["stats"]
+ stats["tokens"] = _with_total(stats["tokens"])
+ fast = False
+ for usage in family.members[1:]:
+ child_tokens = _with_total(usage["tokens"])
+ if child_tokens is not None:
+ for key, value in child_tokens.items():
+ if value + (stats["tokens"] or {}).get(key, 0) > projection.MAX_SAFE_INTEGER:
+ raise ValueError("Task token totals exceed the supported integer limit.")
+ stats["tokens"] = projection.merge_token_usage(stats["tokens"], child_tokens)
+ if usage["cost"] is not None:
+ stats["cost"] = merge_cost_estimates(stats["cost"], usage["cost"])
+ fast |= usage["fast"]
+ warnings = trajectory["warnings"]
+ notices: list[dict[str, Any]] = []
+ if family.unavailable or family.read_warnings:
+ projection.add_warning(
+ notices,
+ "subagent_usage_incomplete",
+ 1,
+ "Task totals include available subagent usage only: "
+ f"{family.unavailable} subagent log(s) unavailable and "
+ f"{family.read_warnings} subagent log(s) with read warnings.",
+ )
+ if fast and not any(warning["code"] == "codex_fast_cost_multiplier" for warning in warnings):
+ projection.add_warning(
+ notices,
+ "codex_fast_cost_multiplier",
+ 1,
+ "Logged subagent Fast x2.5 included-usage estimates are included in task costs; "
+ "this is not an API invoice or purchased-credit bill.",
+ )
+ trajectory["warnings"] = (notices + warnings)[: projection.MAX_WARNINGS]
+ return trajectory
diff --git a/plugins/codex-trajectory/skills/inspect-codex-trajectory/SKILL.md b/plugins/codex-trajectory/skills/inspect-codex-trajectory/SKILL.md
index 1c3acd5..b029a5d 100644
--- a/plugins/codex-trajectory/skills/inspect-codex-trajectory/SKILL.md
+++ b/plugins/codex-trajectory/skills/inspect-codex-trajectory/SKILL.md
@@ -17,4 +17,6 @@ Use the plugin's session MCP tools instead of opening raw files under the Codex
8. A `read-limit-exceeded` result means the selected log exceeds its byte budget, not that the task is missing. The viewer's error page shows the size and lets the user choose a larger limit. Keep the default 512 MiB unless the user explicitly chooses or requests a larger budget; pass the chosen byte count as `maxReadBytes` with an explicit `sessionId` on subsequent reads. Never enable full details merely because a larger read budget was approved. Other line, page, cache, lineage, and filesystem checks continue to apply.
9. For current-task timing or local versus model/token time, call `get_codex_project_timing` with the verified selected task ID. The tool keeps its original name for compatibility and now reads only that task, reusing its loaded source/index when available. Report durations and percentages from `timing`, and disclose untimed turns/tools when nonzero. Distinguish `missingTimingTools` and `invalidTimingTools` from `zeroDurationTools` and `submillisecondTools`: zero/below-precision calls do not block estimates, while missing/invalid calls reserve their possible execution windows as unattributed. A null duration in a public trajectory record alone does not reveal its timing quality. Explain that active time excludes gaps between turns and parallel tools count once. Model/token time includes estimated response/network/queueing waits and cannot isolate pure token generation. Do not infer time from token counts or reinterpret unattributed time as model time. For the visual view, open the task trajectory and use **Calculate task timing**.
-The tools never modify task logs. Session-list calls do update a private search index; its title contains up to 100 characters of the first prompt, so treat list results as potentially sensitive. Do not claim that list results contain no prompt text. They read local `sessions/` and, when requested, `archived_sessions/` beneath `CODEX_HOME` or `~/.codex`.
+10. Trajectory `stats.tokens` and `stats.cost` include the selected agent and all recursively related subagents, including archived descendants, counted once per task ID and priced using each agent's logged model/Fast tier. Turn details, events, and timing remain the selected agent's own activity; session-list overview counters remain per session. A `subagent_usage_incomplete` warning means the task total contains available logs only; disclose this limitation instead of reporting it as a complete total. Child-only changes refresh live task totals.
+
+The tools never modify task logs. Session-list calls do update a private search index; its title contains up to 100 characters of the first prompt, so treat list results as potentially sensitive. Do not claim that list results contain no prompt text. They read local `sessions/` and, when requested for a target or needed for related subagents, `archived_sessions/` beneath `CODEX_HOME` or `~/.codex`.
diff --git a/plugins/codex-trajectory/tests/test_page_index.py b/plugins/codex-trajectory/tests/test_page_index.py
index 7c9ff62..53d4759 100644
--- a/plugins/codex-trajectory/tests/test_page_index.py
+++ b/plugins/codex-trajectory/tests/test_page_index.py
@@ -40,7 +40,7 @@ def test_index_matches_canonical_projection(
) -> None:
path = codex_home / "sessions/2026/rollout-alpha.jsonl"
expected = projection.parse_session(path, 50, detail, before) # type: ignore[arg-type]
- actual = projection.cached_trajectory(path, 50, detail, before) # type: ignore[arg-type]
+ actual = projection._cached_session_trajectory(path, 50, detail, before) # type: ignore[arg-type]
assert comparable(actual) == comparable(expected)
@@ -187,7 +187,7 @@ def test_index_size_cap_falls_back_without_leaking_tempfiles(
monkeypatch.setattr(page_index, "MAX_INDEX_BYTES", 1)
path = codex_home / "sessions/2026/rollout-alpha.jsonl"
expected = projection.parse_session(path, 50)
- actual = projection.cached_trajectory(path, 50)
+ actual = projection._cached_session_trajectory(path, 50)
assert comparable(actual) == comparable(expected)
assert not projection._PAGE_INDEXES
@@ -445,7 +445,7 @@ def unavailable() -> Any:
path = codex_home / "sessions/2026/rollout-alpha.jsonl"
expected = projection.parse_session(path, 50)
monkeypatch.setattr(projection, "PageIndex", unavailable)
- assert comparable(projection.cached_trajectory(path, 50)) == comparable(expected)
+ assert comparable(projection._cached_session_trajectory(path, 50)) == comparable(expected)
@pytest.mark.parametrize("before", [None, 51, 40])
diff --git a/plugins/codex-trajectory/tests/test_subagents.py b/plugins/codex-trajectory/tests/test_subagents.py
new file mode 100644
index 0000000..4c3aa6b
--- /dev/null
+++ b/plugins/codex-trajectory/tests/test_subagents.py
@@ -0,0 +1,534 @@
+"""Task totals include descendants without mixing their records or inherited usage."""
+
+from __future__ import annotations
+
+import importlib
+import json
+import os
+from pathlib import Path
+from typing import Any
+
+import pytest
+from codex_trajectory import projection, sessions, subagents
+from codex_trajectory.tools import call_tool
+from conftest import write_rollout
+from jsonschema import Draft202012Validator, FormatChecker
+
+SCHEMA = json.loads(
+ (Path(__file__).parents[3] / "schemas/trajectory-v2.schema.json").read_text(encoding="utf-8")
+)
+VALIDATOR = Draft202012Validator(SCHEMA, format_checker=FormatChecker())
+
+
+def tokens(input_tokens: int = 200, output_tokens: int = 40) -> dict[str, int]:
+ return {
+ "input_tokens": input_tokens,
+ "cached_input_tokens": input_tokens * 2 // 5,
+ "output_tokens": output_tokens,
+ "reasoning_output_tokens": output_tokens // 2,
+ "total_tokens": input_tokens + output_tokens,
+ }
+
+
+def event(entry_type: str, payload: dict[str, Any]) -> dict[str, Any]:
+ return {"timestamp": "2026-10-01T00:00:01Z", "type": entry_type, "payload": payload}
+
+
+def activity(identifier: str, *, canonical: bool = False) -> dict[str, Any]:
+ payload = {
+ "type": "SubAgentActivity" if canonical else "sub_agent_activity",
+ "agent_thread_id": identifier,
+ "agent_path": "/root/worker",
+ "kind": "started",
+ }
+ if canonical:
+ return event("event_msg", {"type": "item_completed", "item": payload})
+ return event("event_msg", payload)
+
+
+def write_agent(
+ home: Path,
+ identifier: str,
+ *,
+ parent: str | None = None,
+ model: str = "gpt-5",
+ tier: str = "default",
+ usage: dict[str, int] | None = None,
+ archived: bool = False,
+ nested_parent: bool = False,
+ activities: list[dict[str, Any]] | None = None,
+) -> Path:
+ metadata: dict[str, Any] = {
+ "id": identifier,
+ "source": "cli",
+ "base_instructions": "private child instructions",
+ }
+ if parent is not None:
+ if nested_parent:
+ metadata["source"] = {
+ "subagent": {"thread_spawn": {"parent_thread_id": parent, "depth": 1}}
+ }
+ else:
+ metadata["parent_thread_id"] = parent
+ values = [
+ event("session_meta", metadata),
+ event("turn_context", {"model": model, "service_tier": tier}),
+ event("event_msg", {"type": "task_started", "turn_id": identifier}),
+ event("event_msg", {"type": "user_message", "message": f"Prompt for {identifier}"}),
+ *(activities or []),
+ event(
+ "response_item",
+ {
+ "type": "message",
+ "id": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": f"Output for {identifier}"}],
+ },
+ ),
+ event(
+ "event_msg",
+ {"type": "token_count", "info": {"total_token_usage": usage or tokens()}},
+ ),
+ event("event_msg", {"type": "task_complete", "turn_id": identifier, "duration_ms": 1000}),
+ ]
+ root = "archived_sessions" if archived else "sessions"
+ return write_rollout(home / root / f"rollout-{identifier}.jsonl", values)
+
+
+def read_task(identifier: str = "root", **arguments: Any) -> dict[str, Any]:
+ return call_tool("get_codex_trajectory", {"sessionId": identifier, **arguments})[
+ "structuredContent"
+ ]
+
+
+@pytest.mark.parametrize(
+ "tool", ["get_codex_trajectory", "show_codex_trajectory", "open_codex_trajectory"]
+)
+def test_task_totals_include_nested_archived_agents_with_their_own_prices(
+ codex_home: Path, tool: str
+) -> None:
+ write_agent(codex_home, "root", activities=[activity("grandchild")])
+ write_agent(
+ codex_home,
+ "child",
+ parent="root",
+ model="gpt-5-mini",
+ tier="fast",
+ usage=tokens(1000, 200),
+ nested_parent=True,
+ )
+ write_agent(codex_home, "grandchild", parent="child", model="gpt-5-nano", archived=True)
+ write_agent(codex_home, "unrelated", usage=tokens(900_000, 100_000))
+ arguments = {} if tool == "open_codex_trajectory" else {"sessionId": "root"}
+ result = call_tool(tool, arguments, metadata={"thread_id": "root"})["structuredContent"]
+
+ assert result["stats"]["tokens"] == tokens(1400, 280)
+ assert result["stats"]["cost"]["totalUsd"] == pytest.approx(0.0019824)
+ assert result["stats"]["cost"]["pricedModelCalls"] == 3
+ assert result["stats"]["cost"]["coverage"] == "complete"
+ assert result["turns"][0]["usage"] == tokens()
+ assert result["turns"][0]["cost"]["totalUsd"] == pytest.approx(0.00056)
+ assert result["stats"]["turns"] == 1
+ assert any(w["code"] == "codex_fast_cost_multiplier" for w in result["warnings"])
+ assert not any(w["code"] == "subagent_usage_incomplete" for w in result["warnings"])
+ serialized = json.dumps(result)
+ assert "Output for child" not in serialized
+ assert "Prompt for grandchild" not in serialized
+ assert "private child instructions" not in serialized
+ assert str(codex_home) not in serialized
+ VALIDATOR.validate(result)
+
+
+def test_selecting_a_child_includes_only_its_descendants(codex_home: Path) -> None:
+ write_agent(codex_home, "root")
+ write_agent(codex_home, "child", parent="root")
+ write_agent(codex_home, "grandchild", parent="child")
+ write_agent(codex_home, "sibling", parent="root", usage=tokens(1000, 200))
+
+ result = read_task("child")
+ assert result["stats"]["tokens"] == tokens(400, 80)
+ assert result["stats"]["cost"]["pricedModelCalls"] == 2
+
+
+@pytest.mark.parametrize("canonical", [False, True])
+def test_activity_links_resolve_older_agents_without_parent_metadata(
+ codex_home: Path, canonical: bool
+) -> None:
+ write_agent(codex_home, "root", activities=[activity("child", canonical=canonical)] * 2)
+ write_agent(codex_home, "child", activities=[activity("root")])
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens(400, 80)
+ assert result["stats"]["cost"]["pricedModelCalls"] == 2
+
+
+def test_duplicate_logical_agent_ids_and_parent_cycles_count_once(codex_home: Path) -> None:
+ write_agent(codex_home, "root", parent="grandchild")
+ child = write_agent(codex_home, "child", parent="root")
+ duplicate = write_rollout(codex_home / "archived_sessions/rollout-copy.jsonl", [])
+ duplicate.write_bytes(child.read_bytes())
+ write_agent(codex_home, "grandchild", parent="child")
+
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens(600, 120)
+ assert result["stats"]["cost"]["pricedModelCalls"] == 3
+
+
+def test_unknown_child_price_preserves_tokens_and_partial_pricing(codex_home: Path) -> None:
+ write_agent(codex_home, "root")
+ write_agent(codex_home, "child", parent="root", model="unpublished-test-model")
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens(400, 80)
+ assert result["stats"]["cost"]["totalUsd"] == pytest.approx(0.00056)
+ assert result["stats"]["cost"]["coverage"] == "partial"
+ assert result["stats"]["cost"]["pricedModelCalls"] == 1
+ assert result["stats"]["cost"]["unpricedModelCalls"] == 1
+
+
+@pytest.mark.parametrize("missing_in", ["root", "child"])
+def test_missing_agent_total_is_derived_before_combining(codex_home: Path, missing_in: str) -> None:
+ partial = {key: value for key, value in tokens().items() if key != "total_tokens"}
+ write_agent(codex_home, "root", usage=partial if missing_in == "root" else tokens())
+ write_agent(
+ codex_home, "child", parent="root", usage=partial if missing_in == "child" else tokens()
+ )
+ assert read_task()["stats"]["tokens"] == tokens(400, 80)
+
+
+def test_child_growth_updates_live_totals_without_rescanning_parent(
+ codex_home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ root = write_agent(codex_home, "root")
+ child = write_agent(codex_home, "child", parent="root")
+ first = projection.trajectory_update_result({"sessionId": "root"})["structuredContent"]
+ root_signature = sessions.session_signature(root)
+ original = projection.parse_session
+ scans: list[Path] = []
+
+ def track_scan(path: Path, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ scans.append(path)
+ return original(path, *args, **kwargs)
+
+ monkeypatch.setattr(projection, "parse_session", track_scan)
+ with child.open("a", encoding="utf-8") as handle:
+ handle.write(
+ json.dumps(
+ event(
+ "event_msg",
+ {"type": "token_count", "info": {"total_token_usage": tokens(400, 80)}},
+ )
+ )
+ + "\n"
+ )
+ second = projection.trajectory_update_result(
+ {"sessionId": "root", "revision": first["revision"]}
+ )["structuredContent"]
+ assert second["unchanged"] is False
+ assert second["revision"] != first["revision"]
+ assert second["trajectory"]["stats"]["tokens"] == tokens(600, 120)
+ assert second["trajectory"]["stats"]["cost"]["pricedModelCalls"] == 3
+ assert sessions.session_signature(root) == root_signature
+ assert scans == [child]
+ third = projection.trajectory_update_result(
+ {"sessionId": "root", "revision": second["revision"]}
+ )["structuredContent"]
+ assert third["unchanged"] is True
+ assert scans == [child]
+
+
+def test_new_or_removed_child_changes_revision_with_unchanged_parent(codex_home: Path) -> None:
+ write_agent(codex_home, "root", activities=[activity("child")])
+ first = projection.trajectory_update_result({"sessionId": "root"})["structuredContent"]
+ assert first["trajectory"]["warnings"][0]["code"] == "subagent_usage_incomplete"
+ child = write_agent(codex_home, "child", parent="root")
+ second = projection.trajectory_update_result(
+ {"sessionId": "root", "revision": first["revision"]}
+ )["structuredContent"]
+ assert second["unchanged"] is False
+ assert second["trajectory"]["stats"]["tokens"] == tokens(400, 80)
+ assert second["trajectory"]["warnings"] == []
+ child.unlink()
+ third = projection.trajectory_update_result(
+ {"sessionId": "root", "revision": second["revision"]}
+ )["structuredContent"]
+ assert third["unchanged"] is False
+ assert third["trajectory"]["stats"]["tokens"] == tokens()
+ assert third["trajectory"]["warnings"][0]["code"] == "subagent_usage_incomplete"
+
+
+def test_metadata_only_new_child_is_found_without_parent_activity(codex_home: Path) -> None:
+ write_agent(codex_home, "root")
+ first = projection.trajectory_update_result({"sessionId": "root"})["structuredContent"]
+ write_agent(codex_home, "child", parent="root")
+ second = projection.trajectory_update_result(
+ {"sessionId": "root", "revision": first["revision"]}
+ )["structuredContent"]
+ assert second["unchanged"] is False
+ assert second["trajectory"]["stats"]["tokens"] == tokens(400, 80)
+
+
+@pytest.mark.parametrize("detail", ["summary", "full"])
+@pytest.mark.parametrize("before", [None, 2, 1])
+def test_task_totals_are_independent_of_parent_page(
+ codex_home: Path, detail: str, before: int | None
+) -> None:
+ write_agent(codex_home, "root")
+ write_agent(codex_home, "child", parent="root")
+ arguments: dict[str, Any] = {"detailLevel": detail, "maxRecords": 50}
+ if before is not None:
+ arguments["beforeRecord"] = before
+ result = read_task(**arguments)
+ assert result["stats"]["tokens"] == tokens(400, 80)
+ assert result["stats"]["cost"]["totalUsd"] == pytest.approx(0.00112)
+ assert all("Output for child" not in str(record) for record in result["records"])
+ VALIDATOR.validate(result)
+
+
+def test_corrupt_child_reports_incomplete_totals_and_still_visits_grandchildren(
+ codex_home: Path,
+) -> None:
+ write_agent(codex_home, "root")
+ child = write_agent(codex_home, "child", parent="root")
+ values = [json.loads(line) for line in child.read_text(encoding="utf-8").splitlines()]
+ values[0]["payload"]["history_mode"] = "paginated"
+ write_rollout(child, values)
+ write_agent(codex_home, "grandchild", parent="child")
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens(400, 80)
+ assert result["warnings"][0]["code"] == "subagent_usage_incomplete"
+ assert "1 subagent log(s) unavailable" in result["warnings"][0]["message"]
+
+
+def test_child_read_warnings_cannot_silently_claim_complete_history(codex_home: Path) -> None:
+ write_agent(codex_home, "root")
+ child = write_agent(codex_home, "child", parent="root")
+ with child.open("a", encoding="utf-8") as handle:
+ handle.write("{malformed private-child-data}\n")
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens(400, 80)
+ assert result["warnings"][0]["code"] == "subagent_usage_incomplete"
+ assert "1 subagent log(s) with read warnings" in result["warnings"][0]["message"]
+ assert "private-child-data" not in json.dumps(result)
+
+
+def test_subagent_read_budget_is_not_bypassed_by_cached_larger_reads(
+ codex_home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ root = write_agent(codex_home, "root")
+ child = write_agent(codex_home, "child", parent="root")
+ with child.open("a", encoding="utf-8") as handle:
+ handle.write(json.dumps({"padding": "x" * 8000}) + "\n")
+ monkeypatch.setattr(sessions, "MAX_JSONL_TOTAL_BYTES", root.stat().st_size + 100)
+ permitted = read_task(maxReadBytes=child.stat().st_size + 100)
+ assert permitted["stats"]["tokens"] == tokens(400, 80)
+ with pytest.raises(sessions.ReadLimitExceeded) as raised:
+ projection.trajectory_result({"sessionId": "root"}, False)
+ assert raised.value.session_id == "root"
+ with pytest.raises(sessions.ReadLimitExceeded) as live_error:
+ projection.trajectory_update_result({"sessionId": "root"})
+ assert live_error.value.session_id == "root"
+ assert live_error.value.session_id_verified is True
+
+
+def test_linked_subagent_log_is_never_read(codex_home: Path) -> None:
+ write_agent(codex_home, "root", activities=[activity("child")])
+ outside = write_agent(codex_home.parent / "outside-home", "child", parent="root")
+ link = codex_home / "sessions/rollout-child.jsonl"
+ try:
+ link.symlink_to(outside)
+ except OSError:
+ pytest.skip("Symlinks unavailable")
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens()
+ assert result["warnings"][0]["code"] == "subagent_usage_incomplete"
+
+
+def test_subagent_token_total_overflow_is_explicit(codex_home: Path) -> None:
+ write_agent(codex_home, "root")
+ write_agent(
+ codex_home,
+ "child",
+ parent="root",
+ usage={"input_tokens": projection.MAX_SAFE_INTEGER, "output_tokens": 0},
+ )
+ with pytest.raises(ValueError, match="integer limit"):
+ projection.trajectory_result({"sessionId": "root"}, False)
+
+
+def test_paginated_subagent_resume_counts_own_usage_once(codex_home: Path) -> None:
+ write_agent(codex_home, "root")
+ identifier = "12121212-1212-4212-8212-121212121212"
+ physical = "34343434-3434-4434-8434-343434343434"
+ child = codex_home / "sessions" / f"rollout-2026-10-01T00-00-00-{identifier}.jsonl"
+ values = [
+ event(
+ "session_meta",
+ {
+ "id": identifier,
+ "history_mode": "paginated",
+ "subagent_history_start_ordinal": 4,
+ "parent_thread_id": "root",
+ },
+ ),
+ event(
+ "event_msg", {"type": "token_count", "info": {"total_token_usage": tokens(8000, 1600)}}
+ ),
+ event("event_msg", {"type": "turn_started", "turn_id": "inherited-parent"}),
+ event("event_msg", {"type": "turn_complete", "turn_id": "inherited-parent"}),
+ event("turn_context", {"model": "gpt-5"}),
+ event("event_msg", {"type": "turn_started", "turn_id": "own"}),
+ event("event_msg", {"type": "token_count", "info": {"total_token_usage": tokens()}}),
+ event("event_msg", {"type": "turn_complete", "turn_id": "own"}),
+ ]
+ for ordinal, value in enumerate(values):
+ value["ordinal"] = ordinal
+ write_rollout(child, values)
+ resumed = child.with_name(f"rollout-2026-10-01T00-00-00-{identifier}_{physical}.jsonl")
+ resumed_values = [
+ event(
+ "session_meta",
+ {
+ "id": identifier,
+ "history_mode": "paginated",
+ "parent_thread_id": "root",
+ "history_base": {
+ "thread_id": identifier,
+ "end_ordinal_exclusive": len(values),
+ "end_byte_offset": child.stat().st_size,
+ },
+ },
+ ),
+ event("event_msg", {"type": "turn_started", "turn_id": "resumed"}),
+ event("event_msg", {"type": "token_count", "info": {"total_token_usage": tokens(400, 80)}}),
+ event("event_msg", {"type": "turn_complete", "turn_id": "resumed"}),
+ ]
+ for ordinal, value in enumerate(resumed_values, len(values)):
+ value["ordinal"] = ordinal
+ write_rollout(resumed, resumed_values)
+ now = child.stat().st_mtime_ns + 1_000_000_000
+ os.utime(resumed, ns=(now, now))
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens(600, 120)
+ assert result["stats"]["cost"]["pricedModelCalls"] == 3
+ assert result["warnings"] == []
+
+
+def test_compressed_subagent_is_counted_once_with_plain_sibling(codex_home: Path) -> None:
+ write_agent(codex_home, "root")
+ child = write_agent(codex_home, "child", parent="root")
+ try:
+ zstd = importlib.import_module("compression.zstd")
+ except ImportError:
+ zstd = importlib.import_module("zstandard")
+ compressed_bytes = zstd.ZstdCompressor().compress(child.read_bytes())
+ else:
+ compressed_bytes = zstd.compress(child.read_bytes())
+ compressed = child.with_suffix(".jsonl.zst")
+ compressed.write_bytes(compressed_bytes)
+ assert read_task()["stats"]["tokens"] == tokens(400, 80)
+ child.unlink()
+ assert read_task()["stats"]["tokens"] == tokens(400, 80)
+
+
+def test_raised_budget_can_read_an_exact_referenced_compressed_child(
+ codex_home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ identifier = "56565656-5656-4656-8656-565656565656"
+ root = write_agent(codex_home, "root", activities=[activity(identifier)])
+ child = write_agent(codex_home, identifier, parent="root")
+ with child.open("a", encoding="utf-8") as handle:
+ handle.write(json.dumps({"padding": "x" * 8000}) + "\n")
+ try:
+ zstd = importlib.import_module("compression.zstd")
+ except ImportError:
+ zstd = importlib.import_module("zstandard")
+ compressed_bytes = zstd.ZstdCompressor().compress(child.read_bytes())
+ else:
+ compressed_bytes = zstd.compress(child.read_bytes())
+ required = child.stat().st_size
+ child.with_suffix(".jsonl.zst").write_bytes(compressed_bytes)
+ child.unlink()
+ monkeypatch.setattr(sessions, "MAX_JSONL_TOTAL_BYTES", root.stat().st_size + 100)
+ with pytest.raises(sessions.ReadLimitExceeded):
+ projection.trajectory_result({"sessionId": "root"}, False)
+ assert read_task(maxReadBytes=required + 100)["stats"]["tokens"] == tokens(400, 80)
+
+
+def test_task_without_own_usage_can_total_its_child(codex_home: Path) -> None:
+ write_rollout(
+ codex_home / "sessions/rollout-root.jsonl", [event("session_meta", {"id": "root"})]
+ )
+ write_agent(codex_home, "child", parent="root")
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens()
+ assert result["stats"]["cost"]["totalUsd"] == pytest.approx(0.00056)
+ assert result["turns"] == []
+
+
+def test_activity_does_not_override_a_different_explicit_parent(codex_home: Path) -> None:
+ write_agent(codex_home, "root", activities=[activity("unrelated")])
+ write_agent(codex_home, "unrelated", parent="other-root")
+ assert read_task()["stats"]["tokens"] == tokens()
+
+
+def test_arbitrary_tool_output_and_cwd_never_link_an_unrelated_agent(codex_home: Path) -> None:
+ root = write_agent(codex_home, "root")
+ child = write_agent(codex_home, "unrelated")
+ for path in (root, child):
+ values = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]
+ values[0]["payload"]["cwd"] = "/same/project"
+ if path == root:
+ values.append(
+ event(
+ "response_item",
+ {"type": "function_call_output", "output": activity("unrelated")["payload"]},
+ )
+ )
+ write_rollout(path, values)
+ assert read_task()["stats"]["tokens"] == tokens()
+
+
+def test_conflicting_parent_metadata_is_reported_as_unavailable(codex_home: Path) -> None:
+ write_agent(codex_home, "root", activities=[activity("child")])
+ child = write_agent(codex_home, "child", parent="root", nested_parent=True)
+ values = [json.loads(line) for line in child.read_text(encoding="utf-8").splitlines()]
+ values[0]["payload"]["parent_thread_id"] = "other-root"
+ write_rollout(child, values)
+ result = read_task()
+ assert result["stats"]["tokens"] == tokens()
+ assert result["warnings"][0]["code"] == "subagent_usage_incomplete"
+
+
+def test_usage_cache_has_a_byte_limit(codex_home: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(subagents, "MAX_USAGE_CACHE_BYTES", 1)
+ write_agent(codex_home, "root")
+ write_agent(codex_home, "child", parent="root")
+ assert read_task()["stats"]["tokens"] == tokens(400, 80)
+ assert not subagents._USAGE
+ assert not subagents._USAGE_SIZES
+
+
+@pytest.mark.parametrize("activities_only", [False, True])
+def test_agent_discovery_limit_is_explicit(
+ codex_home: Path, monkeypatch: pytest.MonkeyPatch, activities_only: bool
+) -> None:
+ monkeypatch.setattr(subagents, "MAX_TASK_AGENTS", 2)
+ activities = [activity(name) for name in ("one", "two", "three")] if activities_only else []
+ write_agent(codex_home, "root", activities=activities)
+ if not activities_only:
+ for identifier in ("one", "two", "three"):
+ write_agent(codex_home, identifier, parent="root")
+ with pytest.raises(ValueError, match="discovery limit"):
+ projection.trajectory_result({"sessionId": "root"}, False)
+
+
+def test_usage_and_metadata_caches_are_bounded(
+ codex_home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(subagents, "MAX_CACHED_USAGE", 2)
+ monkeypatch.setattr(subagents, "MAX_CACHED_LINKS", 2)
+ write_agent(codex_home, "root")
+ for identifier in ("first", "second", "third"):
+ write_agent(codex_home, identifier, parent="root")
+ assert read_task()["stats"]["tokens"] == tokens(800, 160)
+ assert len(subagents._USAGE) <= 2
+ assert len(subagents._LINKS) <= 2
diff --git a/plugins/codex-trajectory/tests/test_ui.py b/plugins/codex-trajectory/tests/test_ui.py
index bf6a4eb..0d814f5 100644
--- a/plugins/codex-trajectory/tests/test_ui.py
+++ b/plugins/codex-trajectory/tests/test_ui.py
@@ -1116,7 +1116,7 @@ def test_safe_summary_search_filter_keyboard_and_detail_inspector(
)
assert token_panel.locator(".token-metric[title]").count() == 0
assert frame.locator(".stat[title]").count() == 0
- assert "cache is part of input and reasoning is part of output" in token_panel.inner_text()
+ assert "Cache is part of input and reasoning is part of output" in token_panel.inner_text()
assert "Cache hit 75%" in token_panel.locator(".token-badges").inner_text()
assert "Pricing coverage Complete" in token_panel.locator(".token-badges").inner_text()
assert "not a Codex subscription bill" in token_panel.locator(".cost-note").inner_text()
@@ -2637,6 +2637,46 @@ def test_manual_fast_cost_mode_updates_all_surfaces_and_is_task_scoped(
page.set_viewport_size({"width": 1280, "height": 900})
+@pytest.mark.parametrize("language", ["en", "zh"])
+def test_task_totals_include_descendants_while_turns_show_current_agent(
+ page: Page, harness_url: str, language: str
+) -> None:
+ page.goto(f"{harness_url}/{language}-native")
+ frame = viewer(page)
+ frame.locator("#refresh").wait_for()
+ page.evaluate(
+ """() => {
+ const stats = trajectories['session-alpha'].stats;
+ for (const name of Object.keys(stats.tokens)) stats.tokens[name] *= 2;
+ for (const name of ['totalUsd', 'uncachedInputUsd', 'cachedInputUsd', 'outputUsd']) {
+ stats.cost[name] *= 2;
+ }
+ stats.cost.pricedModelCalls = 5;
+ }"""
+ )
+ frame.locator("#refresh").click()
+ expect(frame.locator('[data-token-metric="total"] .token-metric-value')).to_have_text("1,280")
+ expect(frame.locator('[data-token-metric="cost"] .token-metric-value')).to_have_text(
+ "≈$0.002976"
+ )
+ expect(frame.locator("#tokenDetails .section-note").first).to_contain_text(
+ "所有子代理" if language == "zh" else "all descendants"
+ )
+ expect(frame.locator("#tokenDetails .token-badges")).to_contain_text(
+ "模型请求 5" if language == "zh" else "Model requests 5"
+ )
+ frame.locator("details.token-turns summary").click()
+ expect(frame.locator(".token-turn-row")).to_have_count(2)
+ assert frame.locator('.token-turn-row [data-token-column="cost"]').all_inner_texts() == [
+ "≈$0.000832",
+ "≈$0.000656",
+ ]
+ frame.locator("#openPip").click()
+ expect(frame.locator("#liveDock")).to_have_attribute("data-total-cost", "≈$0.002976")
+ expect(frame.locator("#liveDock")).to_have_attribute("data-turn-cost", "≈$0.000656")
+ expect(frame.locator("#liveDock")).to_have_attribute("data-tokens", "1280,256,768,256,80")
+
+
def test_logged_fast_costs_override_manual_mode_without_double_multiplication(
page: Page, harness_url: str
) -> None: