Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

ci(packaging): the desktop installers are built and attached by CI

rubenluetke10-beep47ce2106dcb4
diff --git a/.github/workflows/desktop-installers.yml b/.github/workflows/desktop-installers.yml
new file mode 100644
index 0000000000..ef68a55229
--- /dev/null
+++ b/.github/workflows/desktop-installers.yml
@@ -0,0 +1,342 @@
+# Native desktop installers for Personal Jarvis.
+#
+# What this produces, and why those exact names: the website's download button
+# and the in-app updater both resolve
+# https://github.com/PersonalJarvis/PersonalJarvis/releases/latest/download/<name>,
+# so the asset names below are a contract, not a convention.
+#
+# PersonalJarvis-Setup-x64.exe Windows 10/11 x64, per-user Inno wizard
+# PersonalJarvis-macOS-arm64.dmg Apple Silicon
+# PersonalJarvis-macOS-x64.dmg Intel Mac
+# PersonalJarvis-Linux-x86_64.AppImage Linux x86_64
+# installers-SHA256SUMS.txt what the updater verifies against
+#
+# Each OS job runs the SAME script a maintainer runs locally
+# (packaging/<os>/build.*), so a green run here means the documented command
+# works - not that CI has its own private build path.
+#
+# Signing is optional and secret-gated. GitHub forbids secrets in a job-level
+# `if:`, so the credentials are exported as job-level `env` and the steps test
+# the environment variable instead. Without the secrets the build still
+# produces a working, unsigned installer and says so.
+#
+# Action SHAs are pinned to 40-char commits (CVE-2025-30066 hardening), matching
+# the rest of this repo's workflows.
+
+name: Desktop installers
+
+on:
+ push:
+ tags:
+ - "v*.*.*"
+ workflow_dispatch: {}
+
+permissions:
+ contents: read
+
+concurrency:
+ group: desktop-installers-${{ github.ref }}
+ # Never cancel a release build half-way: a partially uploaded set of assets is
+ # worse than a duplicate run.
+ cancel-in-progress: false
+
+env:
+ PYTHON_VERSION: "3.12"
+ NODE_VERSION: "22"
+
+jobs:
+ # ------------------------------------------------------------------ Windows
+ windows:
+ name: Windows installer (x64)
+ runs-on: windows-latest
+ timeout-minutes: 90
+ env:
+ # Exported here (not per step) so the `if:` guards below can read them.
+ # An empty value means "this fork has no signing secrets" - not an error.
+ AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
+ AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
+ AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
+ AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
+ AZURE_CODE_SIGNING_ACCOUNT: ${{ secrets.AZURE_CODE_SIGNING_ACCOUNT }}
+ AZURE_CERTIFICATE_PROFILE: ${{ secrets.AZURE_CERTIFICATE_PROFILE }}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: ${{ env.PYTHON_VERSION }}
+
+ - name: Set up Node
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+
+ - name: Install Personal Jarvis (desktop + dev)
+ shell: bash
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install -e ".[desktop,dev]"
+
+ - name: Install Inno Setup
+ shell: pwsh
+ run: |
+ # windows-latest ships Inno Setup 6 preinstalled, but that is not a
+ # guarantee - install it when the compiler is absent.
+ $candidates = @(
+ "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",
+ "$env:ProgramFiles\Inno Setup 6\ISCC.exe",
+ "$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe"
+ )
+ $found = $candidates | Where-Object { Test-Path $_ } | Select-Object -First 1
+ if ($found) {
+ Write-Host "Inno Setup already present: $found"
+ } else {
+ choco install innosetup --no-progress -y
+ }
+
+ - name: Build the installer
+ shell: pwsh
+ run: pwsh packaging/windows/build.ps1
+
+ # Signs the SETUP executable. Windows attaches Mark-of-the-Web to the
+ # downloaded installer, so this signature is the one SmartScreen weighs;
+ # files the installer then writes inherit no MOTW.
+ - name: Sign the installer (Azure Trusted Signing)
+ if: env.AZURE_CLIENT_ID != ''
+ # pin: azure/[email protected] - pinned by commit SHA.
+ uses: azure/trusted-signing-action@c7ab2a863ab5f9a846ddb8265964877ef296ee82
+ with:
+ azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+ azure-client-id: ${{ secrets.AZURE_CLIENT_ID }}
+ azure-client-secret: ${{ secrets.AZURE_CLIENT_SECRET }}
+ endpoint: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
+ trusted-signing-account-name: ${{ secrets.AZURE_CODE_SIGNING_ACCOUNT }}
+ certificate-profile-name: ${{ secrets.AZURE_CERTIFICATE_PROFILE }}
+ files-folder: ${{ github.workspace }}/dist/installers
+ files-folder-filter: exe
+ file-digest: SHA256
+ timestamp-rfc3161: http://timestamp.acs.microsoft.com
+ timestamp-digest: SHA256
+
+ - name: Report the signing state honestly
+ if: env.AZURE_CLIENT_ID == ''
+ shell: bash
+ run: |
+ echo "::notice::AZURE_* signing secrets are not configured - the installer is UNSIGNED."
+
+ - name: Upload the installer
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
+ with:
+ name: installer-windows-x64
+ path: dist/installers/PersonalJarvis-Setup-x64.exe
+ if-no-files-found: error
+ retention-days: 14
+
+ # -------------------------------------------------------------------- macOS
+ macos:
+ name: macOS installer (${{ matrix.arch }})
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 90
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - runner: macos-15
+ arch: arm64
+ - runner: macos-15-intel
+ arch: x64
+ steps:
+ - name: Checkout
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: ${{ env.PYTHON_VERSION }}
+
+ - name: Set up Node
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+
+ - name: Install Personal Jarvis (desktop + dev)
+ shell: bash
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install -e ".[desktop,dev]"
+
+ # The script decides what to do with these: with them it codesigns with
+ # the Developer ID identity and notarizes; without them it ad-hoc signs,
+ # skips notarization and prints a one-line notice.
+ - name: Build the DMG
+ shell: bash
+ env:
+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
+ APPLE_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_CERTIFICATE_P12_BASE64 }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ run: |
+ chmod +x packaging/macos/build.sh
+ ./packaging/macos/build.sh
+
+ - name: Upload the DMG
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
+ with:
+ name: installer-macos-${{ matrix.arch }}
+ path: dist/installers/PersonalJarvis-macOS-${{ matrix.arch }}.dmg
+ if-no-files-found: error
+ retention-days: 14
+
+ # -------------------------------------------------------------------- Linux
+ linux:
+ name: Linux installer (x86_64)
+ # 22.04, not latest: an AppImage inherits the glibc of the machine that
+ # built it, so building on the OLDEST supported runner is what makes it run
+ # on more than the newest distributions.
+ runs-on: ubuntu-22.04
+ timeout-minutes: 90
+ steps:
+ - name: Checkout
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: ${{ env.PYTHON_VERSION }}
+
+ - name: Set up Node
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+
+ - name: Install Personal Jarvis (desktop + dev)
+ shell: bash
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install -e ".[desktop,dev]"
+
+ - name: Build the AppImage
+ shell: bash
+ run: |
+ chmod +x packaging/linux/build.sh
+ ./packaging/linux/build.sh
+
+ - name: Upload the AppImage
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
+ with:
+ name: installer-linux-x86_64
+ path: |
+ dist/installers/PersonalJarvis-Linux-x86_64.AppImage
+ dist/installers/personal-jarvis_*_amd64.deb
+ if-no-files-found: error
+ retention-days: 14
+
+ # ------------------------------------------------------- Checksums + Release
+ release:
+ name: Checksums and GitHub Release
+ needs: [windows, macos, linux]
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ permissions:
+ # The ONLY job that may write to the repository, and only to attach the
+ # assets it just verified.
+ contents: write
+ steps:
+ - name: Checkout
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: ${{ env.PYTHON_VERSION }}
+
+ # A tag that disagrees with the shipped version would publish installers
+ # nobody can trace back to a commit - and the in-app updater compares the
+ # release version against jarvis.__version__, so a mismatch would offer an
+ # update that installs the same build forever.
+ - name: Verify the tag matches jarvis.__version__
+ if: github.ref_type == 'tag'
+ shell: bash
+ run: |
+ set -euo pipefail
+ tag_version="${GITHUB_REF_NAME#v}"
+ package_version="$(python -c 'import re,pathlib; print(re.search(r"__version__ = \"([^\"]+)\"", pathlib.Path("jarvis/__init__.py").read_text()).group(1))')"
+ echo "tag=${tag_version} package=${package_version}"
+ if [ "${tag_version}" != "${package_version}" ]; then
+ echo "::error::Tag ${GITHUB_REF_NAME} does not match jarvis.__version__ (${package_version})."
+ exit 1
+ fi
+
+ - name: Download every installer
+ uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
+ with:
+ pattern: installer-*
+ path: installers
+ merge-multiple: true
+
+ - name: Write installers-SHA256SUMS.txt
+ shell: bash
+ run: |
+ set -euo pipefail
+ cd installers
+ ls -la
+ # Every asset the download page and the updater promise must be here.
+ # A silently missing DMG would ship a release that only half works.
+ required=(
+ PersonalJarvis-Setup-x64.exe
+ PersonalJarvis-macOS-arm64.dmg
+ PersonalJarvis-macOS-x64.dmg
+ PersonalJarvis-Linux-x86_64.AppImage
+ )
+ for asset in "${required[@]}"; do
+ if [ ! -f "$asset" ]; then
+ echo "::error::required release asset $asset is missing"
+ exit 1
+ fi
+ done
+ # Flat names only: the updater looks each asset up by its file name.
+ rm -f installers-SHA256SUMS.txt
+ sha256sum "${required[@]}" > installers-SHA256SUMS.txt
+ for optional in personal-jarvis_*_amd64.deb; do
+ [ -e "$optional" ] || continue
+ sha256sum "$optional" >> installers-SHA256SUMS.txt
+ done
+ cat installers-SHA256SUMS.txt
+ sha256sum -c installers-SHA256SUMS.txt
+
+ - name: Upload the checksum manifest
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
+ with:
+ name: installers-checksums
+ path: installers/installers-SHA256SUMS.txt
+ if-no-files-found: error
+ retention-days: 14
+
+ - name: Attach the installers to the GitHub Release
+ if: github.ref_type == 'tag'
+ # pin: softprops/[email protected] - same pin as sign-installer.yml.
+ uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228
+ with:
+ tag_name: ${{ github.ref_name }}
+ name: ${{ github.ref_name }}
+ # The release may already exist (sign-installer.yml runs on the same
+ # tag); this adds assets to it instead of replacing it.
+ fail_on_unmatched_files: true
+ files: |
+ installers/PersonalJarvis-Setup-x64.exe
+ installers/PersonalJarvis-macOS-arm64.dmg
+ installers/PersonalJarvis-macOS-x64.dmg
+ installers/PersonalJarvis-Linux-x86_64.AppImage
+ installers/installers-SHA256SUMS.txt
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 4cf7592659..cf89477aa4 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -12790,45 +12790,3 @@ index-state endpoint ("63 % of 12.7 GB read") does not exist yet.
and every reader is a place to be wrong in its own way. The audit that found
these was one agent per area with the real databases in front of it, not a
walk through the code.
-
----
-
-## BUG-179: OpenRouter and Gemini spend nobody could see — twenty callers of the brain protocol never reached the ledger (HIGH, FIXED 2026-08-25)
-
-**Symptom (maintainer, 2026-08-25).** "I have spent money on OpenRouter, I
-know it 100 %, and on Gemini too — the report shows almost nothing." The
-provider table showed OpenRouter at $0.00 and Gemini at $0.19.
-
-**Root cause.** The Costs section learned about spend only from the surfaces
-that happened to record it: a voice turn's `BrainTurnCompleted`, a chat's
-`turn_finished`, a mission's draft, the CLI transcripts. Everything else that
-calls `Brain.complete()` — dictation polish (its own HTTP clients, not even a
-plugin), the wiki curator and session roll-ups, awareness digests, the
-mission critic and decomposer, computer-use planning, skill authoring, board
-profiles, recap/prompt composers — spent on the configured primary brain
-(`openrouter` → `google/gemini-3.5-flash` on this machine) and told no one.
-`rg "\.complete\("` outside plugins and tests: 24 files.
-
-**Fix.**
-
-* `jarvis/costs/ledger.py` — one append-only ledger (`data/llm_usage.db`),
- written by a daemon thread off the hot path (AP-9), read by the report.
- `usage_context("wiki")` tags who asked.
-* `jarvis/brain/usage_meter.py` — `MeteredBrain` wraps every provider at the
- one door they all come through, `BrainProviderRegistry.instantiate`. The
- usage block a plugin yields is written down with the caller; `__class__`
- forwards so `isinstance` checks keep their answer.
-* Surfaces that already keep a richer record tag their calls (`voice-turn`,
- `agent-chat`, `mission-worker`) and the reader skips those tags — the
- ledger row is the audit trail, not a second bill.
-* The dictation polish clients parse the usage their responses carry and
- record it as `dictation`.
-* New surface `background` / role `background`, shown inside "{name}"; the
- entry's label names the job.
-* The section gains a spend switch — all · billed to keys · on
- subscriptions — and "Where it went" says "the 12 most expensive of N ·
- share of the total" instead of reading like a sum.
-
-**Lesson.** A report that depends on every caller remembering to report is a
-report of the callers that remembered. Meter where the object is made, not
-where it is used.
diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.py
index cccf1e8d98..5fe0474134 100644
--- a/jarvis/agent_chat/runner_api.py
+++ b/jarvis/agent_chat/runner_api.py
@@ -523,11 +523,7 @@ async def _run_gated_tool(
async def _stream(brain: Any, req: BrainRequest, cancel: asyncio.Event):
"""Iterate the brain stream, ending early when ``cancel`` is set."""
- from jarvis.costs.ledger import usage_context
-
- # The chat store records this turn's usage itself (``turn_finished``).
- with usage_context("agent-chat"):
- agen = brain.complete(req)
+ agen = brain.complete(req)
try:
while True:
if cancel.is_set():
diff --git a/jarvis/awareness/verdichter.py b/jarvis/awareness/verdichter.py
index e661ec1485..643921fc3c 100644
--- a/jarvis/awareness/verdichter.py
+++ b/jarvis/awareness/verdichter.py
@@ -20,14 +20,6 @@ with an empty summary instead of crashing.
"""
from __future__ import annotations
-from jarvis.costs.ledger import usage_context
-
-
-def _tagged_complete(brain, request): # type: ignore[no-untyped-def]
- """The digest's model calls are ledgered as awareness work."""
- with usage_context("awareness"):
- return brain.complete(request)
-
import asyncio
import logging
import time
@@ -123,7 +115,7 @@ class Verdichter:
start_ns = time.time_ns()
try:
agg = await asyncio.wait_for(
- aggregate(_tagged_complete(self._brain, request)),
+ aggregate(self._brain.complete(request)),
timeout=self._config.timeout_s,
)
except TimeoutError:
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 0479a17f9e..96ca3da933 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -10480,16 +10480,7 @@ class BrainManager:
_TURN_HISTORY_OVERRIDE.reset(history_token)
_PUBLISH_RESPONSE_EVENT.reset(token)
- async def _generate(self, user_text: str, *args: Any, **kwargs: Any) -> str:
- """A voice turn. Its spend is published on ``BrainTurnCompleted`` with
- the realtime/tool/pipeline split, so the ledger row the metered
- provider writes underneath is tagged and not counted a second time."""
- from jarvis.costs.ledger import usage_context
-
- with usage_context("voice-turn"):
- return await self._generate_untagged(user_text, *args, **kwargs)
-
- async def _generate_untagged(
+ async def _generate(
self,
user_text: str,
*,
diff --git a/jarvis/brain/provider_registry.py b/jarvis/brain/provider_registry.py
index d918875119..d09ffbd38e 100644
--- a/jarvis/brain/provider_registry.py
+++ b/jarvis/brain/provider_registry.py
@@ -51,12 +51,7 @@ class BrainProviderRegistry:
f"Failed: {list(self._failed.keys())}"
)
cls = self._classes[name]
- from jarvis.brain.usage_meter import meter_brain
-
- # Every instance leaves here metered: whatever asks it for tokens —
- # a voice turn, the wiki curator, a dictation polish — is written to
- # the usage ledger without the caller having to know (BUG-178).
- return meter_brain(cls(**kwargs), name)
+ return cls(**kwargs)
def get_class(self, name: str) -> type:
self._load()
diff --git a/jarvis/brain/usage_meter.py b/jarvis/brain/usage_meter.py
deleted file mode 100644
index a003546b30..0000000000
--- a/jarvis/brain/usage_meter.py
+++ /dev/null
@@ -1,135 +0,0 @@
-"""Wrap a brain provider so every call it answers is written to the ledger.
-
-Applied once, at construction, by :class:`jarvis.brain.provider_registry.
-BrainProviderRegistry` — the one door every provider instance comes through
-(the manager, the resolver, the health check, the vision brain). Callers keep
-the object they always had: attributes forward, ``estimate_cost`` forwards,
-``isinstance`` against the plugin class is the one thing that changes, and
-nothing in the tree does that.
-
-The usage block a plugin yields follows the canonical contract
-(``input_tokens`` = uncached input, ``cache_hit_tokens`` = cache reads,
-``output_tokens``). ``complete`` is a plain ``def`` that returns an async
-generator, exactly like the plugins, so both calling conventions in the tree
-keep working; the caller tag is read when ``complete`` is CALLED, so a
-``usage_context`` around the call expression is enough even when the stream
-is consumed later.
-"""
-
-from __future__ import annotations
-
-import logging
-from collections.abc import AsyncIterator
-from typing import Any
-
-from jarvis.core.protocols import BrainDelta, BrainRequest
-from jarvis.costs.ledger import current_caller, record_usage
-
-log = logging.getLogger(__name__)
-
-_IN_KEYS = ("input_tokens", "prompt_tokens")
-_OUT_KEYS = ("output_tokens", "completion_tokens")
-_CACHED_KEYS = ("cache_hit_tokens", "cache_read_input_tokens", "cached_input_tokens")
-
-
-def _totals(usage: dict[str, Any]) -> tuple[int, int, int]:
- def first(keys: tuple[str, ...]) -> int:
- for key in keys:
- value = usage.get(key)
- if value is not None:
- try:
- return max(0, int(value))
- except (TypeError, ValueError):
- return 0
- return 0
-
- return first(_IN_KEYS), first(_OUT_KEYS), first(_CACHED_KEYS)
-
-
-class MeteredBrain:
- """A :class:`~jarvis.core.protocols.Brain` that reports what it spent."""
-
- __slots__ = ("_inner", "_provider_name")
-
- def __init__(self, inner: Any, provider_name: str) -> None:
- object.__setattr__(self, "_inner", inner)
- object.__setattr__(self, "_provider_name", provider_name)
-
- # -- forwarding ------------------------------------------------------
-
- def __getattr__(self, name: str) -> Any:
- return getattr(self._inner, name)
-
- def __setattr__(self, name: str, value: Any) -> None:
- setattr(self._inner, name, value)
-
- def __repr__(self) -> str: # pragma: no cover — logging nicety
- return f"MeteredBrain({self._inner!r})"
-
- @property
- def unwrapped(self) -> Any:
- return self._inner
-
- @property # type: ignore[misc]
- def __class__(self) -> type: # type: ignore[override]
- # ``isinstance(provider, SomePluginClass)`` keeps its answer: the
- # pipeline asks exactly that of its brain (a subscription voice brain
- # is handled differently), and a wrapper must not change it.
- return type(self._inner)
-
- def estimate_cost(self, req: BrainRequest) -> float:
- return float(self._inner.estimate_cost(req))
-
- # -- the metered call ---------------------------------------------------
-
- def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- caller = current_caller()
- return self._metered(self._inner.complete(req), caller, self._model_of(req))
-
- def _model_of(self, req: BrainRequest) -> str:
- """The model the call runs on: the request's override, else whatever
- the plugin calls its configured model."""
- for source, attr in ((req, "model"), (self._inner, "model"), (self._inner, "_model"),
- (self._inner, "model_name"), (self._inner, "_model_name")):
- value = getattr(source, attr, None)
- if isinstance(value, str) and value:
- return value
- return ""
-
- async def _metered(
- self, stream: AsyncIterator[BrainDelta], caller: str, model: str
- ) -> AsyncIterator[BrainDelta]:
- tokens_in = tokens_out = tokens_cached = 0
- seen = False
- try:
- async for delta in stream:
- usage = getattr(delta, "usage", None)
- if isinstance(usage, dict) and usage:
- # One call reports its usage once, on its last chunk; a
- # plugin that reports running totals is covered by taking
- # the LAST block rather than summing.
- tokens_in, tokens_out, tokens_cached = _totals(usage)
- seen = True
- yield delta
- finally:
- if seen:
- record_usage(
- provider=self._provider_name,
- model=model,
- tokens_in=tokens_in,
- tokens_out=tokens_out,
- tokens_cached=tokens_cached,
- caller=caller,
- )
-
-
-def meter_brain(provider: Any, provider_name: str) -> Any:
- """Wrap once; a provider that is already metered is handed back as is."""
- if type(provider) is MeteredBrain:
- return provider
- if not callable(getattr(provider, "complete", None)):
- return provider
- return MeteredBrain(provider, provider_name)
-
-
-__all__ = ["MeteredBrain", "meter_brain"]
diff --git a/jarvis/costs/aggregate.py b/jarvis/costs/aggregate.py
index b2e18b2513..44cbe68338 100644
--- a/jarvis/costs/aggregate.py
+++ b/jarvis/costs/aggregate.py
@@ -158,9 +158,6 @@ class CostReport:
series: list[dict[str, Any]]
top_refs: list[dict[str, Any]]
models: list[dict[str, Any]]
- #: How many conversations/missions/sessions the window holds in all — the
- #: top list is a slice of these, and must say so.
- refs_total: int = 0
def to_dict(self) -> dict[str, Any]:
return {
@@ -175,7 +172,6 @@ class CostReport:
"series": self.series,
"top_refs": self.top_refs,
"models": self.models,
- "refs_total": self.refs_total,
}
@@ -188,13 +184,8 @@ def filter_entries(
surfaces: set[str] | None = None,
refs: set[str] | None = None,
search: str = "",
- billing: str = "all",
) -> list[CostEntry]:
- """Narrow the line items. An empty filter set means "everything".
-
- ``billing``: ``all``, ``billed`` (an API key paid — everything but seat
- quotes) or ``subscription`` (seat quotes only).
- """
+ """Narrow the line items. An empty filter set means "everything"."""
needle = search.strip().casefold()
def keep(e: CostEntry) -> bool:
@@ -208,10 +199,6 @@ def filter_entries(
return False
if refs and e.ref_id not in refs:
return False
- if billing == "billed" and e.price_source == "subscription":
- return False
- if billing == "subscription" and e.price_source != "subscription":
- return False
if needle and needle not in f"{e.model} {e.provider} {e.label}".casefold():
return False
return True
@@ -320,7 +307,6 @@ def build_report(
}
for row in _ranked(refs, total_cost, total_tokens, top_n)
],
- refs_total=len(refs),
models=sorted(
(
{
diff --git a/jarvis/costs/cli_usage_index.py b/jarvis/costs/cli_usage_index.py
index 235e873929..b19ddc470a 100644
--- a/jarvis/costs/cli_usage_index.py
+++ b/jarvis/costs/cli_usage_index.py
@@ -967,7 +967,7 @@ def _agy_row(
def _grok_row(
record: Mapping[str, Any], offset: int, cand: _Candidate, cursor: _Cursor
-) -> _PricedRow | None:
+) -> _Row | None:
params = _payload(record, "params")
update = _payload(params, "update")
if update.get("sessionUpdate") != "turn_completed":
@@ -989,10 +989,6 @@ def _grok_row(
session_id = str(params.get("sessionId") or cursor.session_id)
prompt_id = str(update.get("prompt_id") or "")
dedup = f"{session_id}:{prompt_id}" if session_id and prompt_id else f"{cand.key}:{offset}"
- # xAI writes what it billed for the turn, in ticks of 1e-10 USD (verified
- # against its list price to the cent, 2026-08-25). Grok Build runs on the
- # user's own key, so this IS the bill, not an estimate.
- cost_usd = _int(usage.get("costUsdTicks")) / 1e10
return (
cand.agent,
dedup,
@@ -1005,7 +1001,6 @@ def _grok_row(
cached,
cursor.cwd,
cursor.label,
- cost_usd,
)
@@ -1070,7 +1065,7 @@ def _agy_context(path: Path) -> tuple[str, str, str]:
@dataclass(slots=True)
class _FileScan:
- rows: list[_Row | _PricedRow]
+ rows: list[_Row]
offset: int
cursor: _Cursor
bytes_read: int
@@ -1294,7 +1289,7 @@ def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:
with a space would stay at $0 forever.
"""
del start
- rows: list[_Row | _PricedRow] = []
+ rows: list[_Row] = []
session_id = cand.path.stem
cwd = ""
model = ""
@@ -1382,7 +1377,7 @@ def _scan_opencode(cand: _Candidate, start: int) -> _FileScan:
indexed (the "offset" column holds a timestamp for this agent), so a run
reads only what arrived since. A store that shrank (vacuum) re-reads from
zero and the message-id key keeps every turn counted once."""
- rows: list[_Row | _PricedRow] = []
+ rows: list[_PricedRow] = []
newest = start
failed = False
try:
@@ -1446,7 +1441,7 @@ def _scan_opencode(cand: _Candidate, start: int) -> _FileScan:
finally:
conn.close()
return _FileScan(
- rows=rows,
+ rows=list(rows), # type: ignore[arg-type]
offset=max(newest, cand.size),
cursor=_Cursor(),
bytes_read=cand.size,
@@ -1461,7 +1456,7 @@ def _scan(cand: _Candidate, start: int, cursor: _Cursor, deadline: float) -> _Fi
return _scan_opencode(cand, start)
if cand.agent == AGENT_AGY:
return _scan_antigravity(cand, start)
- rows: list[_Row | _PricedRow] = []
+ rows: list[_Row] = []
reader = _LineReader(None, start)
if cand.agent == AGENT_KIMI and not cursor.session_id:
cursor.session_id, cursor.cwd, cursor.label = _agy_context(cand.path)
@@ -1515,7 +1510,7 @@ def _wanted(agent: str, raw: bytes) -> bool:
def _row_for(
agent: str, record: Mapping[str, Any], offset: int, cand: _Candidate, cursor: _Cursor
-) -> _Row | _PricedRow | None:
+) -> _Row | None:
if agent == AGENT_CLAUDE:
return _claude_row(record, cand, cursor)
if agent == AGENT_CODEX:
diff --git a/jarvis/costs/ledger.py b/jarvis/costs/ledger.py
deleted file mode 100644
index 0b3b580df9..0000000000
--- a/jarvis/costs/ledger.py
+++ /dev/null
@@ -1,317 +0,0 @@
-"""The one place every model call's usage is written down.
-
-The Costs section used to learn about spend from the surfaces that happened
-to record it — a voice turn's ``BrainTurnCompleted``, a chat's
-``turn_finished``, a mission's draft. Twenty-odd callers of the brain
-protocol never told anyone: dictation polish, the wiki curator, awareness
-digests, the mission critic, computer-use planning, skill authoring, board
-profiles. Their OpenRouter and Gemini bills were real and invisible
-(maintainer, 2026-08-25: "I have spent money on OpenRouter, I know it").
-
-So the ledger sits UNDER the surfaces: every provider instance is wrapped at
-construction (:mod:`jarvis.brain.usage_meter`) and every usage block a
-plugin reports lands here, tagged with the *caller* that asked. Surfaces that
-already keep their own richer record (a voice turn knows realtime vs tool
-role; a chat turn knows its runner) tag their calls so the read model does
-not count them twice — see ``COVERED_ELSEWHERE`` in ``sources.py``.
-
-AP-9: nothing here touches the hot path. ``record_usage`` appends to an
-in-memory queue and returns; a daemon thread owns the SQLite file. A failure
-to write is logged once and never raised into a caller.
-"""
-
-from __future__ import annotations
-
-import contextlib
-import contextvars
-import logging
-import queue
-import sqlite3
-import threading
-import time
-from collections.abc import Iterator
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-
-log = logging.getLogger(__name__)
-
-DB_NAME = "llm_usage.db"
-
-#: Who is asking, for the call currently being made. Set by the surface that
-#: owns the call (``usage_context("dictation")``); empty means "some
-#: background job" and is reported as such.
-usage_caller: contextvars.ContextVar[str] = contextvars.ContextVar(
- "jarvis_usage_caller", default=""
-)
-
-
-def usage_context(caller: str) -> Iterator[None]:
- """Tag every model call made inside the block with *caller*."""
- token = usage_caller.set(caller)
- try:
- yield
- finally:
- usage_caller.reset(token)
-
-
-def current_caller() -> str:
- return usage_caller.get()
-
-
-_SCHEMA = """
-CREATE TABLE IF NOT EXISTS llm_usage (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- ts_ms INTEGER NOT NULL,
- provider TEXT NOT NULL DEFAULT '',
- model TEXT NOT NULL DEFAULT '',
- tokens_in INTEGER NOT NULL DEFAULT 0,
- tokens_out INTEGER NOT NULL DEFAULT 0,
- tokens_cached INTEGER NOT NULL DEFAULT 0,
- cost_usd REAL NOT NULL DEFAULT 0,
- caller TEXT NOT NULL DEFAULT '',
- label TEXT NOT NULL DEFAULT ''
-);
-CREATE INDEX IF NOT EXISTS idx_llm_usage_ts ON llm_usage (ts_ms);
-"""
-
-
-@dataclass(frozen=True, slots=True)
-class UsageRow:
- ts_ms: int
- provider: str
- model: str
- tokens_in: int
- tokens_out: int
- tokens_cached: int
- cost_usd: float
- caller: str
- label: str
-
-
-class _Writer:
- """One daemon thread, one connection, one queue. Drops nothing it can help."""
-
- def __init__(self) -> None:
- self._queue: queue.Queue[tuple[Any, ...] | None] = queue.Queue(maxsize=10_000)
- self._thread: threading.Thread | None = None
- self._lock = threading.Lock()
- self._path: Path | None = None
- self._warned = False
- self._queued = 0
- self._done = 0
- self._done_cv = threading.Condition()
-
- def path(self) -> Path:
- with self._lock:
- if self._path is None:
- from jarvis.core import config as cfg
-
- self._path = Path(cfg.DATA_DIR) / DB_NAME
- return self._path
-
- def set_path(self, path: Path | None) -> None:
- """Test hook — point the ledger somewhere else (or back to default).
-
- The writer thread holds a connection to the OLD file; it is stopped
- first so nothing queued afterwards lands in the wrong place.
- """
- self._stop_thread()
- with self._lock:
- self._path = Path(path) if path is not None else None
-
- def put(self, row: tuple[Any, ...]) -> None:
- try:
- self._queue.put_nowait(row)
- except queue.Full:
- if not self._warned:
- self._warned = True
- log.warning("usage ledger: queue full, dropping usage rows")
- return
- with self._done_cv:
- self._queued += 1
- self._ensure_thread()
-
- def _ensure_thread(self) -> None:
- with self._lock:
- if self._thread is not None and self._thread.is_alive():
- return
- self._thread = threading.Thread(
- target=self._run, name="jarvis-usage-ledger", daemon=True
- )
- self._thread.start()
-
- def _stop_thread(self) -> None:
- with self._lock:
- thread = self._thread
- if thread is None or not thread.is_alive():
- return
- self._queue.put(None)
- thread.join(timeout=5.0)
-
- def flush(self, timeout_s: float = 2.0) -> None:
- """Wait until everything queued so far is on disk (tests, shutdown)."""
- with self._done_cv:
- target = self._queued
- deadline = time.monotonic() + timeout_s
- while self._done < target:
- remaining = deadline - time.monotonic()
- if remaining <= 0:
- break
- self._done_cv.wait(remaining)
-
- def _mark_done(self) -> None:
- with self._done_cv:
- self._done += 1
- self._done_cv.notify_all()
-
- def _run(self) -> None:
- conn: sqlite3.Connection | None = None
- try:
- while True:
- try:
- item = self._queue.get(timeout=5.0)
- except queue.Empty:
- # Idle: release the file so a report can read it freely and
- # the thread can be re-armed by the next record.
- break
- if item is None:
- break
- try:
- if conn is None:
- conn = self._open()
- if conn is not None:
- conn.execute(
- "INSERT INTO llm_usage (ts_ms, provider, model, tokens_in,"
- " tokens_out, tokens_cached, cost_usd, caller, label)"
- " VALUES (?,?,?,?,?,?,?,?,?)",
- item,
- )
- conn.commit()
- except sqlite3.Error as exc:
- if not self._warned:
- self._warned = True
- log.warning("usage ledger: write failed (%s); further rows are lost", exc)
- finally:
- self._mark_done()
- finally:
- if conn is not None:
- conn.close()
-
- def _open(self) -> sqlite3.Connection | None:
- path = self.path()
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- conn = sqlite3.connect(path, timeout=5.0)
- conn.execute("PRAGMA journal_mode=WAL")
- conn.execute("PRAGMA synchronous=NORMAL")
- conn.executescript(_SCHEMA)
- conn.commit()
- return conn
- except (OSError, sqlite3.Error) as exc:
- if not self._warned:
- self._warned = True
- log.warning("usage ledger: %s not writable (%s)", path, exc)
- return None
-
-
-_writer = _Writer()
-
-
-def record_usage(
- *,
- provider: str,
- model: str,
- tokens_in: int,
- tokens_out: int,
- tokens_cached: int = 0,
- cost_usd: float = 0.0,
- caller: str | None = None,
- label: str = "",
- ts_ms: int | None = None,
-) -> None:
- """Write one model call down. Never raises, never blocks the caller.
-
- ``caller`` defaults to the current :func:`usage_context`; ``cost_usd`` is
- what the provider itself reported, when it did — the report re-prices
- anything left at 0.0 from the rate tables.
- """
- try:
- total = max(0, int(tokens_in)) + max(0, int(tokens_out)) + max(0, int(tokens_cached))
- if total <= 0 and float(cost_usd) <= 0:
- return
- _writer.put(
- (
- int(ts_ms if ts_ms is not None else time.time() * 1000),
- str(provider or ""),
- str(model or ""),
- max(0, int(tokens_in)),
- max(0, int(tokens_out)),
- max(0, int(tokens_cached)),
- float(cost_usd or 0.0),
- str(caller if caller is not None else current_caller()),
- str(label or "")[:120],
- )
- )
- except Exception: # noqa: BLE001 — accounting must never cost a call
- log.debug("usage ledger: record failed", exc_info=True)
-
-
-def flush(timeout_s: float = 2.0) -> None:
- _writer.flush(timeout_s)
-
-
-def set_ledger_path(path: Path | None) -> None:
- _writer.set_path(path)
-
-
-def ledger_path() -> Path:
- return _writer.path()
-
-
-def read_usage(path: Path, since_ms: int, until_ms: int) -> Iterator[UsageRow]:
- """Rows in the window, oldest first. A missing file yields nothing."""
- if not path.exists():
- return
- try:
- conn = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True, timeout=5.0)
- except sqlite3.Error as exc:
- log.warning("usage ledger: %s not readable (%s)", path, exc)
- return
- try:
- conn.row_factory = sqlite3.Row
- for row in conn.execute(
- "SELECT ts_ms, provider, model, tokens_in, tokens_out, tokens_cached, cost_usd,"
- " caller, label FROM llm_usage WHERE ts_ms BETWEEN ? AND ? ORDER BY ts_ms",
- (since_ms, until_ms),
- ):
- yield UsageRow(
- ts_ms=int(row["ts_ms"] or 0),
- provider=str(row["provider"] or ""),
- model=str(row["model"] or ""),
- tokens_in=int(row["tokens_in"] or 0),
- tokens_out=int(row["tokens_out"] or 0),
- tokens_cached=int(row["tokens_cached"] or 0),
- cost_usd=float(row["cost_usd"] or 0.0),
- caller=str(row["caller"] or ""),
- label=str(row["label"] or ""),
- )
- except sqlite3.Error as exc:
- log.warning("usage ledger: read failed (%s)", exc)
- finally:
- conn.close()
-
-
-__all__ = [
- "DB_NAME",
- "UsageRow",
- "current_caller",
- "flush",
- "ledger_path",
- "read_usage",
- "record_usage",
- "set_ledger_path",
- "usage_caller",
- "usage_context",
-]
diff --git a/jarvis/costs/model.py b/jarvis/costs/model.py
index b2426a66ea..057f5b9a15 100644
--- a/jarvis/costs/model.py
+++ b/jarvis/costs/model.py
@@ -41,10 +41,6 @@ SURFACE_MISSION = "mission"
SURFACE_JARVIS_VOICE = "jarvis-voice"
#: Coding agents driven by a vendor CLI, indexed from their session logs.
SURFACE_AGENTIC_IDE = "agentic-ide"
-#: Every model call no surface above claims: dictation polish, the wiki
-#: curator, awareness digests, the mission critic, computer-use planning,
-#: skill authoring … — read from the usage ledger (:mod:`jarvis.costs.ledger`).
-SURFACE_BACKGROUND = "background"
ROLE_REALTIME = "realtime"
"""Speech-to-speech model — audio tokens, billed per Live/Realtime API rates."""
@@ -59,11 +55,9 @@ ROLE_AGENT = "agent"
"""A coding-agent turn (Claude Code, Codex, …) run from the chat surface."""
ROLE_WORKER = "worker"
-"""An autonomous mission worker."""
ROLE_STT = "stt"
ROLE_TTS = "tts"
-ROLE_BACKGROUND = "background"
-"""A model call made by a background job; the entry's label names the job."""
+"""An autonomous mission worker."""
# Every role and surface the read model can emit, in the order a report
# should offer them. A value missing here is invisible in the facets, which
@@ -77,7 +71,6 @@ ROLES: tuple[str, ...] = (
ROLE_WORKER,
ROLE_STT,
ROLE_TTS,
- ROLE_BACKGROUND,
)
SURFACES: tuple[str, ...] = (
SURFACE_VOICE,
@@ -85,7 +78,6 @@ SURFACES: tuple[str, ...] = (
SURFACE_MISSION,
SURFACE_AGENTIC_IDE,
SURFACE_JARVIS_VOICE,
- SURFACE_BACKGROUND,
)
# Runners whose usage object follows the OpenAI convention: ``input_tokens``
@@ -138,8 +130,7 @@ SUBSCRIPTION_RUNNERS: frozenset[str] = frozenset(
"codex-cli",
"agy-cli",
"kimi-cli",
- # NOT grok-cli: Grok Build runs on the user's xAI key and records what
- # it billed per turn (costUsdTicks) — money that moved, not a seat.
+ "grok-cli",
}
)
diff --git a/jarvis/costs/sources.py b/jarvis/costs/sources.py
index 13fa5520a5..cb93231e3e 100644
--- a/jarvis/costs/sources.py
+++ b/jarvis/costs/sources.py
@@ -18,13 +18,10 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
-from .ledger import DB_NAME as LEDGER_DB_NAME
-from .ledger import read_usage
from .model import (
MISSION_SUBSCRIPTION_CLIS,
OPENAI_CONVENTION_RUNNERS,
ROLE_AGENT,
- ROLE_BACKGROUND,
ROLE_PIPELINE,
ROLE_REALTIME,
ROLE_STT,
@@ -34,7 +31,6 @@ from .model import (
SUBSCRIPTION_RUNNERS,
SURFACE_AGENT_CHAT,
SURFACE_AGENTIC_IDE,
- SURFACE_BACKGROUND,
SURFACE_JARVIS_VOICE,
SURFACE_MISSION,
SURFACE_VOICE,
@@ -67,11 +63,9 @@ class CostSources:
#: a test with its own fixtures, above all — does not silently get this
#: machine's.
cli_index_dir: Path | None = None
- #: The usage ledger every metered provider writes to.
- ledger_db: Path | None = None
def existing(self) -> list[Path]:
- candidates = [self.sessions_db, self.missions_db, self.agent_chat_db, self.ledger_db]
+ candidates = [self.sessions_db, self.missions_db, self.agent_chat_db]
if self.cli_index_dir is not None:
# The index is a source like the others: a refresh that adds
# thousands of CLI turns must invalidate a cached report.
@@ -109,7 +103,6 @@ def default_sources(data_dir: Path | None = None) -> CostSources:
missions_db=root / "missions.db",
agent_chat_db=root / "agent_chat.db",
cli_index_dir=root,
- ledger_db=root / LEDGER_DB_NAME,
)
@@ -694,44 +687,6 @@ def _cli_entries(
)
-# Callers whose spend a richer source already reports. Their ledger rows are
-# the audit trail, not a second bill: a voice turn is on BrainTurnCompleted
-# with its role split, a chat turn on turn_finished, a mission worker on its
-# draft.
-COVERED_ELSEWHERE: frozenset[str] = frozenset({"voice-turn", "agent-chat", "mission-worker"})
-
-
-def _ledger_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterator[CostEntry]:
- """Every model call no surface claims, as the ledger recorded it."""
- if path is None:
- return
- for row in read_usage(path, since_ms, until_ms):
- if row.caller in COVERED_ELSEWHERE:
- continue
- cost, source = price_entry(
- provider=row.provider,
- model=row.model,
- tokens_in=row.tokens_in,
- tokens_out=row.tokens_out,
- recorded_usd=row.cost_usd,
- tokens_cached=row.tokens_cached,
- )
- yield CostEntry(
- ts_ms=row.ts_ms,
- surface=SURFACE_BACKGROUND,
- role=ROLE_BACKGROUND,
- provider=row.provider or "unknown",
- model=row.model,
- tokens_in=row.tokens_in,
- tokens_out=row.tokens_out,
- tokens_cached=row.tokens_cached,
- cost_usd=cost,
- price_source=source,
- ref_id="",
- label=_clip(row.label or row.caller or "background"),
- )
-
-
def collect_entries(
sources: CostSources,
*,
@@ -748,6 +703,5 @@ def collect_entries(
entries.extend(
_cli_entries(sources.cli_index_dir, since_ms, until_ms, bucket_ms)
)
- entries.extend(_ledger_entries(sources.ledger_db, since_ms, until_ms))
entries.sort(key=lambda e: e.ts_ms)
return entries
diff --git a/jarvis/cu/brain_call.py b/jarvis/cu/brain_call.py
index eece6dd5be..61fa323192 100644
--- a/jarvis/cu/brain_call.py
+++ b/jarvis/cu/brain_call.py
@@ -26,7 +26,6 @@ from dataclasses import dataclass
from typing import Any
from jarvis.core.protocols import BrainMessage, BrainRequest, ImageBlock
-from jarvis.costs.ledger import usage_context
logger = logging.getLogger(__name__)
@@ -348,9 +347,7 @@ async def call_vision_brain(
# step died "unterminated JSON", thoughts=304 of 320).
reasoning_effort="none",
)
- with usage_context("computer-use"):
- _stream = brain.complete(req)
- return await agg(_stream)
+ return await agg(brain.complete(req))
start_tokens = _starting_tokens(
provider, model, max_tokens, early_stop_json=early_stop_json,
diff --git a/jarvis/dictation/polish_client.py b/jarvis/dictation/polish_client.py
index 8c64dfdb9b..e5aadc7ba7 100644
--- a/jarvis/dictation/polish_client.py
+++ b/jarvis/dictation/polish_client.py
@@ -815,7 +815,6 @@ class OpenAIChatPolishClient:
"reasoning_effort": "low",
}
data = await self._post(payload, timeout_s=timeout_s)
- _record_openai_usage(self._family.id, self._model, data.get("usage"))
choices = data.get("choices") or []
if not choices:
return None
@@ -979,53 +978,10 @@ class GeminiPolishClient:
raise PolishProviderError(
f"{self._family.label} polish request failed: {exc}"
) from exc
- _record_gemini_usage(
- self._family.id, self._model, getattr(response, "usage_metadata", None)
- )
text = str(getattr(response, "text", "") or "").strip()
return text or None
-def _record_openai_usage(provider: str, model: str, usage: Any) -> None:
- """OpenAI-shaped usage: ``prompt_tokens`` INCLUDES the cached share."""
- if not isinstance(usage, dict):
- return
- from jarvis.costs.ledger import record_usage
-
- details = usage.get("prompt_tokens_details")
- cached = int((details or {}).get("cached_tokens") or 0) if isinstance(details, dict) else 0
- prompt = int(usage.get("prompt_tokens") or 0)
- record_usage(
- provider=provider,
- model=model,
- tokens_in=max(0, prompt - cached),
- tokens_out=int(usage.get("completion_tokens") or 0),
- tokens_cached=cached,
- caller="dictation",
- )
-
-
-def _record_gemini_usage(provider: str, model: str, meta: Any) -> None:
- """google-genai ``usage_metadata``: prompt count includes cached content."""
- if meta is None:
- return
- from jarvis.costs.ledger import record_usage
-
- prompt = int(getattr(meta, "prompt_token_count", 0) or 0)
- cached = int(getattr(meta, "cached_content_token_count", 0) or 0)
- out = int(getattr(meta, "candidates_token_count", 0) or 0) + int(
- getattr(meta, "thoughts_token_count", 0) or 0
- )
- record_usage(
- provider=provider,
- model=model,
- tokens_in=max(0, prompt - cached),
- tokens_out=out,
- tokens_cached=cached,
- caller="dictation",
- )
-
-
def build_polish_client(family: PolishFamily, *, model: str) -> PolishClient | None:
"""Construct the adapter for *family*, or ``None`` when it is unusable.
diff --git a/jarvis/memory/wiki/provider_chain.py b/jarvis/memory/wiki/provider_chain.py
index 87a8256570..a0aa5404f3 100644
--- a/jarvis/memory/wiki/provider_chain.py
+++ b/jarvis/memory/wiki/provider_chain.py
@@ -30,7 +30,6 @@ from collections.abc import Callable, Mapping
from typing import Any
from jarvis.core.redact import safe_preview
-from jarvis.costs.ledger import usage_context
from jarvis.memory.wiki.telemetry import telemetry
log = logging.getLogger(__name__)
@@ -324,8 +323,7 @@ async def complete_with_fallback(
failure_summaries.append(f"{provider} unavailable")
continue
try:
- with usage_context("wiki"):
- stream = brain.complete(request)
+ stream = brain.complete(request)
except Exception as exc: # noqa: BLE001 — synchronous provider failure
detail = _exception_summary(exc)
log.warning(
diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.py
index e8c5f23160..b1e880c6c8 100644
--- a/jarvis/missions/critic/runner.py
+++ b/jarvis/missions/critic/runner.py
@@ -33,8 +33,6 @@ from typing import Any, Final
from pydantic import ValidationError
-from jarvis.costs.ledger import usage_context
-
from ..stream_evidence import (
capability_refusal_answer,
diff_has_action_evidence,
@@ -1931,9 +1929,7 @@ class CriticRunner:
parts: list[str] = []
async with asyncio.timeout(self._timeout):
with override_provider_secrets({provider: worker_key}):
- with usage_context("mission-critic"):
- _stream = brain.complete(req)
- async for delta in _stream:
+ async for delta in brain.complete(req):
chunk = getattr(delta, "content", None)
if chunk:
parts.append(chunk)
diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.py
index 87b653ca1d..252ca6dbe8 100644
--- a/jarvis/missions/workers/api_agent_worker.py
+++ b/jarvis/missions/workers/api_agent_worker.py
@@ -40,7 +40,6 @@ from pathlib import Path
from typing import Any, Literal
from jarvis.core.protocols import BrainMessage, BrainRequest
-from jarvis.costs.ledger import usage_context
from .api_agent_tools import WORKER_TOOL_SPECS, execute_worker_tool_async
from .capabilities import WorkerCapabilityInventory
@@ -433,9 +432,7 @@ class ApiAgentWorker:
# call. ContextVar isolation keeps concurrent Brain and
# Jarvis-Agent tasks from observing one another's keys.
with override_provider_secrets({self.provider: worker_key}):
- with usage_context("mission-worker"):
- _stream = brain.complete(req)
- async for delta in _stream:
+ async for delta in brain.complete(req):
if delta.content:
text_parts.append(delta.content)
if delta.tool_call:
diff --git a/jarvis/ui/web/artifact_view.py b/jarvis/ui/web/artifact_view.py
index fae7deabc5..cd2483fd2c 100644
--- a/jarvis/ui/web/artifact_view.py
+++ b/jarvis/ui/web/artifact_view.py
@@ -15,8 +15,6 @@ from __future__ import annotations
import html
import logging
-from jarvis.artifacts.design_guide import THEME_CSS
-
log = logging.getLogger(__name__)
_MARKDOWN_EXT = (".md", ".markdown")
@@ -48,61 +46,55 @@ ARTIFACT_PAGE_CSP = (
"base-uri 'none';"
)
-# The artifact design standard (jarvis/artifacts/design_guide.py): the app's
-# own tokens in both palettes, so a Markdown output opened in the browser
-# looks like the page it sits next to in the Artifacts section — and follows
-# the app's theme through the same `?theme=light|dark` query the artifact
-# stage appends, stamped on <html> by the SERVER (the page stays script-free
-# under VIEW_CSP; the guide's bootstrap script is for worker-written pages).
-# The tokens are the guide's verbatim; only the document rules below are this
-# page's own.
+# Brand theme (matte black + signal yellow), kept in lockstep with the desktop
+# app's dark tokens (frontend/src/index.css) and video/src/intro/theme.ts. The
+# app is dark-first and this page opens from inside it, so it commits to the
+# brand look instead of following the OS light/dark preference.
_PAGE_CSS = (
- THEME_CSS + "\n"
- "body{padding:40px 24px 64px}"
- "main{max-width:72ch;margin:0 auto}"
- "h1,h2,h3,h4{margin:1.6em 0 .5em}"
- "main>h1:first-of-type{margin-top:0}"
- "h4{font-size:14px;font-weight:600}"
- "p,ul,ol{margin:.7em 0;max-width:none}li{margin:.25em 0}"
- "pre{background:var(--bg-2);border:1px solid var(--line);padding:14px 16px;"
- "overflow:auto;border-radius:var(--radius-sm);font-size:13px;line-height:1.5}"
- "code{background:var(--bg-3);border:1px solid var(--line);padding:.1em .35em;"
- "border-radius:4px}"
- "pre code{background:none;border:none;padding:0;font-size:inherit}"
- "table{border-collapse:collapse;margin:1em 0;display:block;overflow-x:auto;"
- "font-size:14px}"
- "th,td{border:1px solid var(--line);padding:.45rem .7rem;text-align:left}"
- "th{background:var(--bg-2);font-weight:600}"
- "blockquote{border-left:2px solid var(--accent);margin:1em 0;"
- "padding:.1em 0 .1em 1rem;color:var(--ink-2)}"
- "img{max-width:100%;border-radius:var(--radius-sm)}"
- "hr{border:none;border-top:1px solid var(--line);margin:2em 0}"
- ".artifact-name{margin:0 0 24px;padding-bottom:12px;border-bottom:1px solid var(--line)}"
+ "*{box-sizing:border-box}"
+ "body{max-width:52rem;margin:0 auto;padding:2.5rem 1.5rem 4rem;"
+ "font:15px/1.65 -apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;"
+ "color:#FAFAFA;background:#0A0A0A}"
+ "h1,h2,h3,h4{line-height:1.3;margin:1.6em 0 .6em;font-weight:600}"
+ "h1:first-child,h2:first-child{margin-top:0}"
+ "h1{font-size:1.5rem;padding-bottom:.4em;border-bottom:1px solid rgba(255,255,255,0.10)}"
+ "h2{font-size:1.2rem}h3{font-size:1.05rem}"
+ "a{color:#FFD60A}a:hover{color:#E6BE00}"
+ "p,ul,ol{margin:.7em 0}li{margin:.25em 0}"
+ "pre{background:#141414;border:1px solid rgba(255,255,255,0.10);"
+ "padding:1rem;overflow:auto;border-radius:10px}"
+ "code{background:#181818;border:1px solid rgba(255,255,255,0.10);"
+ "padding:.1em .35em;border-radius:5px;font-size:.92em}"
+ "pre code{background:none;border:none;padding:0}"
+ "table{border-collapse:collapse;margin:1em 0;display:block;overflow-x:auto}"
+ "th,td{border:1px solid rgba(255,255,255,0.14);padding:.45rem .7rem}"
+ "th{background:#141414;text-align:left}"
+ "blockquote{border-left:3px solid #FFD60A;margin:1em 0;"
+ "padding:.1em 0 .1em 1rem;color:#9A9A9A}"
+ "img{max-width:100%;border-radius:8px}"
+ "hr{border:none;border-top:1px solid rgba(255,255,255,0.10);margin:2em 0}"
+ ".artifact-name{font-size:11px;letter-spacing:.14em;text-transform:uppercase;"
+ "color:#9A9A9A;margin:0 0 1.6rem;display:flex;align-items:center;gap:.6em}"
+ ".artifact-name::before{content:'';width:9px;height:9px;border-radius:50%;"
+ "background:#FFD60A;box-shadow:0 0 10px rgba(255,214,10,0.35)}"
)
-_THEMES = frozenset({"light", "dark"})
-
-
-def _shell(title: str, body_html: str, theme: str | None) -> str:
- stamp = f" data-theme='{theme}'" if theme in _THEMES else ""
+def _shell(title: str, body_html: str) -> str:
return (
- f"<!doctype html><html lang='en'{stamp}><head><meta charset='utf-8'>"
+ "<!doctype html><html lang='en'><head><meta charset='utf-8'>"
f'<meta http-equiv="Content-Security-Policy" content="{VIEW_CSP}">'
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
f"<title>{html.escape(title)}</title><style>{_PAGE_CSS}</style></head>"
- f"<body><main><p class='artifact-name eyebrow'>{html.escape(title)}</p>"
- f"{body_html}</main></body></html>"
+ f"<body><p class='artifact-name'>{html.escape(title)}</p>{body_html}</body></html>"
)
-def render_artifact_html(filename: str, text: str, *, theme: str | None = None) -> str:
+def render_artifact_html(filename: str, text: str) -> str:
"""Return a complete HTML document rendering *text*.
Markdown filenames are rendered to HTML via the `markdown` library; everything
- else (and the no-markdown-lib fallback) is shown escaped in <pre>. *theme*
- (``light`` / ``dark``, anything else ignored) pins the palette the way the
- app's Artifacts stage pins it; without it the page follows the OS. Never raises.
+ else (and the no-markdown-lib fallback) is shown escaped in <pre>. Never raises.
"""
if filename.lower().endswith(_MARKDOWN_EXT):
try:
@@ -112,10 +104,10 @@ def render_artifact_html(filename: str, text: str, *, theme: str | None = None)
text,
extensions=["extra", "sane_lists", "tables", "fenced_code"],
)
- return _shell(filename, body, theme)
+ return _shell(filename, body)
except Exception as exc: # noqa: BLE001 — a view must never 500
log.info("markdown render unavailable (%s) — serving raw <pre>", exc)
- return _shell(filename, f"<pre>{html.escape(text)}</pre>", theme)
+ return _shell(filename, f"<pre>{html.escape(text)}</pre>")
__all__ = ["ARTIFACT_PAGE_CSP", "VIEW_CSP", "render_artifact_html"]
diff --git a/jarvis/ui/web/costs_routes.py b/jarvis/ui/web/costs_routes.py
index 5047130eed..021388cdc3 100644
--- a/jarvis/ui/web/costs_routes.py
+++ b/jarvis/ui/web/costs_routes.py
@@ -138,7 +138,6 @@ class CostSummary(BaseModel):
series: list[Bucket]
top_refs: list[RefBucket]
models: list[ModelRow]
- refs_total: int = 0
facets: Facets
currency: Currency
sources_present: list[str]
@@ -403,7 +402,6 @@ async def get_summary(
role: Annotated[list[str] | None, Query()] = None,
surface: Annotated[list[str] | None, Query()] = None,
ref: Annotated[list[str] | None, Query()] = None,
- billing: Annotated[str, Query(pattern="^(all|billed|subscription)$")] = "all",
search: str = "",
top: Annotated[int, Query(ge=1, le=100)] = 12,
) -> CostSummary:
@@ -423,7 +421,6 @@ async def get_summary(
surfaces=_split(surface),
refs=_split(ref),
search=search,
- billing=billing,
)
report = build_report(selected, since_ms=start, until_ms=end, top_n=top)
payload = report.to_dict()
@@ -451,7 +448,6 @@ async def get_daily(
role: Annotated[list[str] | None, Query()] = None,
surface: Annotated[list[str] | None, Query()] = None,
ref: Annotated[list[str] | None, Query()] = None,
- billing: Annotated[str, Query(pattern="^(all|billed|subscription)$")] = "all",
search: str = "",
) -> DailyLedger:
"""The daily ledger: one entry per day, newest first.
@@ -474,7 +470,6 @@ async def get_daily(
surfaces=_split(surface),
refs=_split(ref),
search=search,
- billing=billing,
)
rows: list[DayRow] = []
for key, day_entries in group_by_day(entries):
@@ -518,7 +513,6 @@ async def get_entries(
role: Annotated[list[str] | None, Query()] = None,
surface: Annotated[list[str] | None, Query()] = None,
ref: Annotated[list[str] | None, Query()] = None,
- billing: Annotated[str, Query(pattern="^(all|billed|subscription)$")] = "all",
search: str = "",
sort: Annotated[str, Query(pattern="^(recent|cost|tokens)$")] = "recent",
limit: Annotated[int, Query(ge=1, le=500)] = 100,
@@ -535,7 +529,6 @@ async def get_entries(
surfaces=_split(surface),
refs=_split(ref),
search=search,
- billing=billing,
)
if sort == "cost":
entries = sorted(entries, key=lambda e: -e.cost_usd)
diff --git a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
index 63567b38c9..88ae356360 100644
--- a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
+++ b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
@@ -17,7 +17,6 @@ export const ROLE_COLORS: Record<CostRole, string> = {
worker: "hsl(18 88% 62%)", // orange — autonomous missions
stt: "hsl(340 75% 65%)", // rose — the ear
tts: "hsl(30 90% 60%)", // amber — the voice
- background: "hsl(210 12% 60%)", // slate — work nobody watched
};
export const ROLE_ORDER: CostRole[] = [
@@ -28,7 +27,6 @@ export const ROLE_ORDER: CostRole[] = [
"worker",
"stt",
"tts",
- "background",
];
/** Fallback for a bucket key that is not a role (provider, model, day). */
@@ -234,7 +232,6 @@ export const ALL_SURFACES: CostSurface[] = [
"mission",
"agentic-ide",
"jarvis-voice",
- "background",
];
/**
@@ -262,8 +259,8 @@ export const SURFACE_GROUPS: SurfaceGroup[] = [
// named after it (maintainer decision 2026-08-24).
{
id: "jarvis",
- surfaces: ["voice", "agent-chat", "mission", "background"],
- roles: ["realtime", "tool", "pipeline", "agent", "worker", "background"],
+ surfaces: ["voice", "agent-chat", "mission"],
+ roles: ["realtime", "tool", "pipeline", "agent", "worker"],
},
// The assistant's voice — the speech layer built around the brain: the
// ears (speech to text) and the mouth (text to speech). Bills by audio
diff --git a/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx
index e09ec14fee..681893c207 100644
--- a/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx
+++ b/jarvis/ui/web/frontend/src/components/outputs/ArtifactViewer.tsx
@@ -17,6 +17,8 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { useQuery } from "@tanstack/react-query";
+import ReactMarkdown, { type Components } from "react-markdown";
+import remarkGfm from "remark-gfm";
import {
Check,
ChevronDown,
@@ -63,11 +65,6 @@ import {
} from "@/hooks/useOutputs";
import { CodeBlock } from "@/components/docs/CodeBlock";
import { OpenWithDialog } from "@/components/OpenWithDialog";
-import { MarkdownProse, resolveSiblingPath } from "@/components/outputs/MarkdownProse";
-
-// Re-exported: the resolver moved to MarkdownProse when the output page
-// started sharing the renderer; callers and tests keep importing it here.
-export { resolveSiblingPath };
/** Above this many characters the source view skips Shiki — highlighting a
* megabyte of text would freeze the UI thread for seconds. */
@@ -88,12 +85,10 @@ export interface ArtifactViewerProps {
slug: string;
files: ArtifactSummary[];
nativeActions: boolean;
- /** The file to open on first — how "Open in Files" on the output page lands on it. */
- initialPath?: string | null;
}
-export function ArtifactViewer({ slug, files, nativeActions, initialPath }: ArtifactViewerProps) {
- const [selectedPath, setSelectedPath] = useState<string | null>(initialPath ?? null);
+export function ArtifactViewer({ slug, files, nativeActions }: ArtifactViewerProps) {
+ const [selectedPath, setSelectedPath] = useState<string | null>(null);
const [fullscreen, setFullscreen] = useState(false);
// The selection follows the list: first file by default, and a path that
@@ -645,8 +640,7 @@ function HtmlPage({ slug, path }: { slug: string; path: string }) {
);
}
-/** Highlighted source for code, plain `<pre>` for text or anything huge. */
-export function SourceView({ path, text }: { path: string; text: string }) {
+function SourceView({ path, text }: { path: string; text: string }) {
const language = artifactLanguage(path);
if (text.length > HIGHLIGHT_MAX_CHARS || language === "txt") {
return (
@@ -662,8 +656,7 @@ export function SourceView({ path, text }: { path: string; text: string }) {
);
}
-/** A CSV/TSV as a table, capped at `CSV_MAX_ROWS` rows. */
-export function CsvTable({ text, tab }: { text: string; tab: boolean }) {
+function CsvTable({ text, tab }: { text: string; tab: boolean }) {
const t = useT();
const rows = useMemo(() => parseCsv(text, tab ? "\t" : ","), [text, tab]);
if (rows.length === 0) {
@@ -711,11 +704,25 @@ export function CsvTable({ text, tab }: { text: string; tab: boolean }) {
// --- Markdown document -----------------------------------------------------
-/**
- * The reader's document: the shared renderer in a serif reading face with a
- * measure — a report reads as a report, while everything else in the app
- * stays in the UI sans.
- */
+/** Resolve `href` relative to the directory of `fromPath` inside the archive. */
+export function resolveSiblingPath(fromPath: string, href: string): string | null {
+ if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#") || href.startsWith("/")) {
+ return null;
+ }
+ const clean = href.split(/[?#]/)[0];
+ const base = fromPath.split("/").slice(0, -1);
+ for (const seg of clean.split("/")) {
+ if (seg === "" || seg === ".") continue;
+ if (seg === "..") {
+ if (base.length === 0) return null;
+ base.pop();
+ } else {
+ base.push(seg);
+ }
+ }
+ return base.join("/");
+}
+
function MarkdownDocument({
slug,
path,
@@ -729,18 +736,110 @@ function MarkdownDocument({
text: string;
onSelectSibling: (path: string) => void;
}) {
+ const known = useMemo(() => new Set(files.map((f) => f.path)), [files]);
+ const components = useMemo<Components>(
+ () => ({
+ // Fenced blocks render their own complete container; unwrapping the
+ // Markdown ``pre`` avoids invalid ``pre > div`` nesting around CodeBlock.
+ pre({ children }) {
+ return <>{children}</>;
+ },
+ code({ className, children, ...rest }) {
+ const match = /language-(\w+)/.exec(className || "");
+ if (!match) {
+ return (
+ <code className={className} {...rest}>
+ {children}
+ </code>
+ );
+ }
+ return (
+ <CodeBlock language={match[1]} code={String(children).replace(/\n$/, "")} />
+ );
+ },
+ a({ href, children, ...rest }) {
+ const sibling = href ? resolveSiblingPath(path, href) : null;
+ if (sibling && known.has(sibling)) {
+ return (
+ <a
+ href={`#${sibling}`}
+ onClick={(e) => {
+ e.preventDefault();
+ onSelectSibling(sibling);
+ }}
+ {...rest}
+ >
+ {children}
+ </a>
+ );
+ }
+ if (href && /^https?:\/\//i.test(href)) {
+ return (
+ <a
+ href={href}
+ rel="noopener noreferrer"
+ onClick={(e) => {
+ e.preventDefault();
+ void openExternalUrl(href);
+ }}
+ {...rest}
+ >
+ {children}
+ </a>
+ );
+ }
+ return (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ );
+ },
+ img({ src, alt, ...rest }) {
+ const sibling = typeof src === "string" ? resolveSiblingPath(path, src) : null;
+ const resolved =
+ sibling && known.has(sibling) ? artifactInlineUrl(slug, sibling) : src;
+ return <img src={resolved} alt={alt ?? ""} loading="lazy" {...rest} />;
+ },
+ table({ children }) {
+ return (
+ <div className="not-prose my-5 overflow-x-auto rounded-md border border-border">
+ <table className="w-full text-sm [&_td]:px-3 [&_td]:py-1.5 [&_th]:px-3 [&_th]:py-2 [&_th]:text-left [&_th]:font-semibold [&_thead]:bg-muted/40 [&_tr]:border-t [&_tr]:border-border/60 [&_thead_tr]:border-t-0">
+ {children}
+ </table>
+ </div>
+ );
+ },
+ blockquote({ children }) {
+ return (
+ <blockquote className="border-l-2 border-primary/50 pl-4 not-italic text-muted-foreground">
+ {children}
+ </blockquote>
+ );
+ },
+ }),
+ [known, onSelectSibling, path, slug],
+ );
+
return (
- <MarkdownProse
- slug={slug}
- path={path}
- files={files}
- text={text}
- onSelectSibling={onSelectSibling}
+ <article
+ data-testid="artifact-markdown"
className={cn(
- "mx-auto max-w-3xl px-8 py-8 lg:px-12",
- "font-serif text-[15.5px] leading-7 prose-headings:font-serif",
+ "prose prose-neutral dark:prose-invert mx-auto max-w-3xl px-8 py-8 [overflow-wrap:anywhere] lg:px-12",
+ // A document reads as a document: a serif text face, generous leading,
+ // headings that are clearly headings. Everything else in the app stays
+ // in the UI sans.
+ "font-serif text-[15.5px] leading-7",
+ "prose-headings:font-serif prose-headings:font-semibold prose-headings:tracking-tight prose-headings:text-pretty",
"prose-h1:text-3xl prose-h1:leading-tight prose-h2:mt-10 prose-h2:text-2xl prose-h3:text-xl",
+ "prose-p:text-pretty prose-li:my-1",
+ "prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
+ "prose-code:rounded prose-code:bg-muted/60 prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:text-[0.85em] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden",
+ "prose-hr:border-border prose-img:rounded-md",
)}
- />
+ >
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ {text}
+ </ReactMarkdown>
+ </article>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
deleted file mode 100644
index 676155c3a0..0000000000
--- a/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
+++ /dev/null
@@ -1,186 +0,0 @@
-/**
- * A Markdown deliverable rendered as a document — the one renderer both the
- * Files reader (`ArtifactViewer`) and the output page (`OutputPreview`) draw
- * with, so a report reads the same wherever it is opened.
- *
- * What it adds over plain `react-markdown`: fenced code goes through the
- * Shiki `CodeBlock`; a link to a sibling file in the same run selects that
- * file instead of navigating; an external link opens in the user's real
- * browser through the open-external bridge (the desktop WebView drops a bare
- * `target="_blank"`); an image next to the document is served from the run
- * archive. The typography is the caller's — the reader passes its own
- * classes, the output page the artifact standard's.
- */
-import { useMemo } from "react";
-import ReactMarkdown, { type Components } from "react-markdown";
-import remarkGfm from "remark-gfm";
-
-import { cn } from "@/lib/utils";
-import { openExternalUrl } from "@/lib/openExternal";
-import { artifactInlineUrl, type ArtifactSummary } from "@/hooks/useOutputs";
-import { CodeBlock } from "@/components/docs/CodeBlock";
-
-/**
- * Split a leading YAML front matter block (`---` … `---`) off a document.
- * A SKILL.md or a note with metadata would otherwise render the block as one
- * run-on paragraph ("schema_version: "1" name: … description: …"), which
- * reads as a broken page. The metadata is kept and drawn as a small YAML
- * block above the body — it is part of the file, just not prose.
- */
-export function splitFrontMatter(text: string): { meta: string | null; body: string } {
- const match = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
- if (!match) return { meta: null, body: text };
- const meta = match[1].trim();
- return { meta: meta.length > 0 ? meta : null, body: text.slice(match[0].length) };
-}
-
-/** Resolve `href` relative to the directory of `fromPath` inside the archive. */
-export function resolveSiblingPath(fromPath: string, href: string): string | null {
- if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#") || href.startsWith("/")) {
- return null;
- }
- const clean = href.split(/[?#]/)[0];
- const base = fromPath.split("/").slice(0, -1);
- for (const seg of clean.split("/")) {
- if (seg === "" || seg === ".") continue;
- if (seg === "..") {
- if (base.length === 0) return null;
- base.pop();
- } else {
- base.push(seg);
- }
- }
- return base.join("/");
-}
-
-/**
- * The typographic base every Markdown document shares: Tailwind's prose in
- * both themes, links in the accent, inline code on a quiet chip, tables and
- * images with the app's radius. Callers add the face and the measure.
- */
-export const PROSE_BASE =
- "prose prose-neutral dark:prose-invert [overflow-wrap:anywhere] " +
- "prose-headings:font-semibold prose-headings:tracking-tight prose-headings:text-pretty " +
- "prose-p:text-pretty prose-li:my-1 " +
- "prose-a:text-primary prose-a:no-underline hover:prose-a:underline " +
- "prose-code:rounded prose-code:bg-muted/60 prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:text-[0.85em] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden " +
- "prose-hr:border-border prose-img:rounded-md";
-
-export function MarkdownProse({
- slug,
- path,
- files,
- text,
- onSelectSibling,
- className,
- testId = "artifact-markdown",
-}: {
- slug: string;
- /** The document's own archive path — what relative links resolve against. */
- path: string;
- /** Every file of the run, so a relative link can be recognised as a sibling. */
- files: ArtifactSummary[];
- text: string;
- /** Called with a sibling's path when the reader clicks a link to it. */
- onSelectSibling?: (path: string) => void;
- className?: string;
- testId?: string;
-}) {
- const known = useMemo(() => new Set(files.map((f) => f.path)), [files]);
- const { meta, body } = useMemo(() => splitFrontMatter(text), [text]);
- const components = useMemo<Components>(
- () => ({
- // Fenced blocks render their own complete container; unwrapping the
- // Markdown ``pre`` avoids invalid ``pre > div`` nesting around CodeBlock.
- pre({ children }) {
- return <>{children}</>;
- },
- code({ className: codeClass, children, ...rest }) {
- const match = /language-(\w+)/.exec(codeClass || "");
- if (!match) {
- return (
- <code className={codeClass} {...rest}>
- {children}
- </code>
- );
- }
- return (
- <CodeBlock language={match[1]} code={String(children).replace(/\n$/, "")} />
- );
- },
- a({ href, children, ...rest }) {
- const sibling = href ? resolveSiblingPath(path, href) : null;
- if (sibling && known.has(sibling) && onSelectSibling) {
- return (
- <a
- href={`#${sibling}`}
- onClick={(e) => {
- e.preventDefault();
- onSelectSibling(sibling);
- }}
- {...rest}
- >
- {children}
- </a>
- );
- }
- if (href && /^https?:\/\//i.test(href)) {
- return (
- <a
- href={href}
- rel="noopener noreferrer"
- onClick={(e) => {
- e.preventDefault();
- void openExternalUrl(href);
- }}
- {...rest}
- >
- {children}
- </a>
- );
- }
- return (
- <a href={href} {...rest}>
- {children}
- </a>
- );
- },
- img({ src, alt, ...rest }) {
- const sibling = typeof src === "string" ? resolveSiblingPath(path, src) : null;
- const resolved =
- sibling && known.has(sibling) ? artifactInlineUrl(slug, sibling) : src;
- return <img src={resolved} alt={alt ?? ""} loading="lazy" {...rest} />;
- },
- table({ children }) {
- return (
- <div className="not-prose my-5 overflow-x-auto rounded-md border border-border">
- <table className="w-full text-sm [&_td]:px-3 [&_td]:py-1.5 [&_th]:px-3 [&_th]:py-2 [&_th]:text-left [&_th]:font-semibold [&_thead]:bg-muted/40 [&_tr]:border-t [&_tr]:border-border/60 [&_thead_tr]:border-t-0">
- {children}
- </table>
- </div>
- );
- },
- blockquote({ children }) {
- return (
- <blockquote className="border-l-2 border-primary/50 pl-4 not-italic text-muted-foreground">
- {children}
- </blockquote>
- );
- },
- }),
- [known, onSelectSibling, path, slug],
- );
-
- return (
- <article data-testid={testId} className={cn(PROSE_BASE, className)}>
- {meta !== null && (
- <div data-testid="markdown-front-matter">
- <CodeBlock language="yaml" code={meta} />
- </div>
- )}
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
- {body}
- </ReactMarkdown>
- </article>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.test.tsx b/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.test.tsx
deleted file mode 100644
index 4bfbba4551..0000000000
--- a/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.test.tsx
+++ /dev/null
@@ -1,206 +0,0 @@
-/**
- * The output page — a run without a page composed the way an artifact is
- * shown. Pins: the headline comes from the report's own title when there is
- * one, the request is the lead, the final answer is the answer (the run's
- * "Done." summary is not repeated), every file is drawn in place by kind,
- * and "Open in Files" hands the file's path back.
- */
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-
-import { OutputPreview, markdownTitle } from "@/components/visualization/OutputPreview";
-import type { ArtifactSummary, OutputSummary } from "@/hooks/useOutputs";
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-function installFetchMock(
- files: ArtifactSummary[],
- rawByPath: Record<string, string>,
- finalAnswer: string | null,
-) {
- const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- const raw = /\/files\/(.+)\/raw$/.exec(url);
- if (raw) {
- const path = decodeURIComponent(raw[1]);
- const text = rawByPath[path];
- if (text === undefined) return { ok: false, status: 404, json: async () => ({}) };
- return {
- ok: true,
- status: 200,
- json: async () => ({ path, size: text.length, text, truncated: false }),
- };
- }
- if (url.endsWith("/artifacts")) {
- return { ok: true, status: 200, json: async () => ({ files }) };
- }
- if (url.endsWith("/plan")) {
- return {
- ok: true,
- status: 200,
- json: async () => ({
- plan: finalAnswer ? { plan_id: "p", vision: "", status: "complete" } : null,
- steps: [],
- final_answer: finalAnswer,
- }),
- };
- }
- return { ok: false, status: 404, json: async () => ({}) };
- });
- vi.stubGlobal("fetch", fetchMock);
- return fetchMock;
-}
-
-function renderPreview(run: OutputSummary, onOpenFile = vi.fn()) {
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- render(
- <QueryClientProvider client={client}>
- <OutputPreview run={run} onOpenFile={onOpenFile} />
- </QueryClientProvider>,
- );
- return onOpenFile;
-}
-
-function file(path: string, over: Partial<ArtifactSummary> = {}): ArtifactSummary {
- return { path, size: 120, mtime: 1_750_000_000, is_text: true, preview: null, ...over };
-}
-
-const RUN: OutputSummary = {
- slug: "run-1",
- utterance:
- "Do a deep dive on Reddit.\n\nSupporting context from the recent conversation " +
- "(use only to resolve references; the underlying request remains authoritative):\n- x",
- status: "success",
- summary: "Done. File reddit.md is in the folder Jarvis-Outputs.",
- duration_s: 153.2,
- completed_at: 1_755_000_000,
-};
-
-describe("markdownTitle", () => {
- it("reads the first heading and ignores inline marks", () => {
- expect(markdownTitle("intro\n\n# Reddit **Open Source** AI\n\ntext")).toBe(
- "Reddit Open Source AI",
- );
- expect(markdownTitle("no heading here")).toBeNull();
- expect(markdownTitle("")).toBeNull();
- });
-});
-
-describe("OutputPreview", () => {
- it("composes the page: report title, clean request, final answer, files in place", async () => {
- installFetchMock(
- [
- file("tasks/t/artifacts/files/reddit.md"),
- file("tasks/t/artifacts/files/scripts/tool.py"),
- file("tasks/t/artifacts/files/data.csv"),
- ],
- {
- "tasks/t/artifacts/files/reddit.md": "# Reddit Open Source AI Landscape\n\nA **report**.",
- "tasks/t/artifacts/files/scripts/tool.py": "print('hi')\n",
- "tasks/t/artifacts/files/data.csv": "a,b\n1,2\n",
- },
- "Done — the report is in reddit.md.",
- );
- const onOpenFile = renderPreview(RUN);
-
- const page = await screen.findByTestId("output-preview");
- await waitFor(() =>
- expect(within(page).getByTestId("output-preview-title").textContent).toBe(
- "Reddit Open Source AI Landscape",
- ),
- );
- // The request, without the builder's supporting-context tail.
- expect(within(page).getByTestId("output-preview-request").textContent).toBe(
- "Do a deep dive on Reddit.",
- );
- // Eyebrow facts: kind, when, duration, status word.
- expect(within(page).getByTestId("output-preview-status").textContent).toContain("Succeeded");
- expect(page.textContent).toContain("2 min 33 s");
- // The answer is the worker's final reply; the "Done." summary is not repeated.
- const answer = await within(page).findByTestId("output-preview-answer");
- expect(answer.textContent).toContain("Done — the report is in reddit.md.");
- expect(answer.textContent).not.toContain("Done. File reddit.md");
- // Every file drawn in place, by kind.
- await waitFor(() =>
- expect(within(page).getAllByTestId("output-preview-file")).toHaveLength(3),
- );
- const sections = within(page).getAllByTestId("output-preview-file");
- expect(sections.map((s) => s.getAttribute("data-kind"))).toEqual(["markdown", "csv", "code"]);
- await within(sections[0]).findByTestId("output-preview-markdown");
- expect(within(sections[0]).getByText("report").tagName).toBe("STRONG");
- await waitFor(() => expect(within(sections[1]).getByText("b")).toBeDefined());
- await waitFor(() => expect(sections[2].textContent).toContain("print"));
- // "Open in Files" hands the archive path back.
- fireEvent.click(within(sections[2]).getByTitle("Open in Files"));
- expect(onOpenFile).toHaveBeenCalledWith("tasks/t/artifacts/files/scripts/tool.py");
- });
-
- it("draws a document's front matter as a metadata block, not as prose", async () => {
- installFetchMock(
- [file("tasks/t/artifacts/files/SKILL.md")],
- {
- "tasks/t/artifacts/files/SKILL.md":
- '---\nname: gmail-deep-clean\ndescription: "Cleans the inbox"\n---\n# Gmail Deep Clean\n\nBody.',
- },
- null,
- );
- renderPreview({ slug: "run-skill", utterance: "Write a skill", status: "success" });
- const page = await screen.findByTestId("output-preview");
- await waitFor(() =>
- expect(within(page).getByTestId("output-preview-title").textContent).toBe(
- "Gmail Deep Clean",
- ),
- );
- const doc = await within(page).findByTestId("output-preview-markdown");
- const meta = within(doc).getByTestId("markdown-front-matter");
- expect(meta.textContent).toContain("name: gmail-deep-clean");
- // The body no longer starts with the run-on metadata paragraph.
- expect(within(doc).getByRole("heading", { level: 1 }).textContent).toBe("Gmail Deep Clean");
- expect(within(doc).queryByText(/^name: gmail-deep-clean/)).toBeNull();
- });
-
- it("falls back to the request as headline and the summary as answer", async () => {
- installFetchMock([], {}, null);
- renderPreview({
- slug: "run-2",
- utterance: "What is the capital of Australia?",
- status: "success",
- summary: "Canberra — not Sydney.",
- });
- const page = await screen.findByTestId("output-preview");
- expect(within(page).getByTestId("output-preview-title").textContent).toBe(
- "What is the capital of Australia?",
- );
- // The headline IS the request: it is not repeated as a lead.
- expect(within(page).queryByTestId("output-preview-request")).toBeNull();
- const answer = await within(page).findByTestId("output-preview-answer");
- expect(answer.textContent).toContain("Canberra — not Sydney.");
- expect(within(page).queryByTestId("output-preview-files")).toBeNull();
- });
-
- it("leads with why a run ended early, and says when nothing is left behind", async () => {
- installFetchMock([], {}, null);
- renderPreview({
- slug: "run-3",
- utterance: "Build it",
- status: "cancelled",
- terminal_reason: "ui_cancel",
- });
- const page = await screen.findByTestId("output-preview");
- const outcome = await within(page).findByTestId("output-preview-outcome");
- expect(outcome.textContent).toContain("ui_cancel");
- expect(within(page).getByTestId("output-preview-status").textContent).toContain("Cancelled");
- expect(within(page).queryByTestId("output-preview-nothing")).toBeNull();
- });
-
- it("says so when a finished run left neither an answer nor a file", async () => {
- installFetchMock([], {}, null);
- renderPreview({ slug: "run-4", utterance: "Nothing", status: "success" });
- const page = await screen.findByTestId("output-preview");
- await within(page).findByTestId("output-preview-nothing");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.tsx b/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.tsx
deleted file mode 100644
index b3892c18c5..0000000000
--- a/jarvis/ui/web/frontend/src/components/visualization/OutputPreview.tsx
+++ /dev/null
@@ -1,428 +0,0 @@
-/**
- * The output page — a run that produced no page or picture, shown the way an
- * artifact is shown: one composed page on the stage, not a file list.
- *
- * Every run gets the same treatment (2026-08-25): the artifacts a worker
- * wrote as HTML fill the stage as pages; everything else — a research answer,
- * a memo, a set of scripts, a failed build — is composed HERE from what the
- * run left behind, in the same design standard the artifact brief hands the
- * worker (`jarvis/artifacts/design_guide.py`: the app's tokens, an eyebrow
- * that says something true, a headline, the body in reading order, a
- * hairline where a section ends; no hero, no gradient, no decoration).
- *
- * Reading order, top to bottom:
- * 1. eyebrow (kind · when · duration · status), the headline, the request;
- * 2. why the run ended, when it ended early (failure, cancellation, review);
- * 3. the answer — the worker's final reply, or the run's summary;
- * 4. the deliverables — every file rendered in place: a Markdown report as
- * a document, code highlighted, a table as a table, a picture as a
- * picture; anything the page cannot draw is one click from Files.
- *
- * Data: the run itself (`OutputSummary`), the reconstructed plan for the
- * final answer (`/plan`, same cache the run graph reads), the file listing
- * (`/artifacts`, same cache the rail's scan fills) and each text file's
- * bytes (`/raw`). Nothing is fetched twice.
- */
-import { useMemo, type ReactNode } from "react";
-import {
- AlertTriangle,
- ArrowUpRight,
- FileCode2,
- FileImage,
- FileQuestion,
- FileText,
- Globe,
- Loader2,
- Table2,
-} from "lucide-react";
-
-import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
-import { artifactKind, formatBytes, isTextKind, type ArtifactKind } from "@/lib/artifactKind";
-import { cleanRequest, requestHeadline } from "@/lib/runRequest";
-import {
- artifactInlineUrl,
- useArtifactFile,
- useArtifactsForOutput,
- usePlanForOutput,
- type ArtifactSummary,
- type OutputStatus,
- type OutputSummary,
-} from "@/hooks/useOutputs";
-import { CsvTable, SourceView, deliverableDisplayPath } from "@/components/outputs/ArtifactViewer";
-import { MarkdownProse, splitFrontMatter } from "@/components/outputs/MarkdownProse";
-import { deliverableFiles, runNeedsReview } from "@/components/visualization/RunPanels";
-
-/** Files drawn in place; the rest are listed and one click from Files. */
-const MAX_INLINE_FILES = 12;
-/** Above this a text file is not fetched for the page — Files still shows it. */
-const MAX_INLINE_BYTES = 400_000;
-
-/** The document's first `# Heading` — the title the worker gave its report. */
-export function markdownTitle(text: string | null | undefined): string | null {
- if (!text) return null;
- const match = /^\s*#\s+(.+?)\s*#*\s*$/m.exec(splitFrontMatter(text).body.slice(0, 4000));
- if (!match) return null;
- const title = match[1].replace(/[*_`]/g, "").trim();
- return title.length > 0 ? title : null;
-}
-
-/** Status as a word plus a dot — the one place colour carries meaning here. */
-const STATUS_DOT: Record<OutputStatus, string> = {
- success: "bg-emerald-400",
- error: "bg-destructive",
- running: "bg-primary animate-pulse",
- cancelled: "bg-amber-400",
- unknown: "bg-muted-foreground/50",
-};
-
-function formatWhen(seconds: number | undefined): string {
- if (!seconds) return "";
- return new Date(seconds * 1000).toLocaleString(undefined, {
- year: "numeric",
- month: "short",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- });
-}
-
-function formatDuration(seconds: number | undefined): string {
- if (typeof seconds !== "number") return "";
- if (seconds < 90) return `${seconds.toFixed(seconds < 10 ? 1 : 0)} s`;
- const minutes = Math.floor(seconds / 60);
- const rest = Math.round(seconds - minutes * 60);
- return `${minutes} min ${rest} s`;
-}
-
-/** The first file the page would draw as a document — its title names the run. */
-function primaryMarkdown(files: ArtifactSummary[]): ArtifactSummary | null {
- return files.find((f) => artifactKind(f.path, f.is_text) === "markdown") ?? null;
-}
-
-export function OutputPreview({
- run,
- onOpenFile,
-}: {
- run: OutputSummary;
- /** Switch the stage to Files with this file selected. */
- onOpenFile?: (path: string) => void;
-}) {
- const t = useT();
- const listing = useArtifactsForOutput(run.slug);
- const plan = usePlanForOutput(run.slug);
- const lead = useMemo(
- () => primaryMarkdown(deliverableFiles(listing.data?.files ?? [])),
- [listing.data],
- );
- // The report leads the page; scripts, data and assets follow in the
- // reader's order (primary files first, then nested assets).
- const files = useMemo(() => {
- const ordered = deliverableFiles(listing.data?.files ?? []);
- return lead ? [lead, ...ordered.filter((f) => f.path !== lead.path)] : ordered;
- }, [listing.data, lead]);
- const leadText = useArtifactFile(run.slug, lead && lead.size <= MAX_INLINE_BYTES ? lead.path : null);
-
- const request = cleanRequest(run.utterance);
- const title = markdownTitle(leadText.data?.text) ?? requestHeadline(request);
- // The request repeats the headline when the headline IS the request.
- const showRequest = request.length > 0 && request !== title;
-
- // The answer is the worker's final reply. The run's summary is what the
- // voice read back — the reply itself (often cut short) or the stock "Done.
- // File X is in the folder…" — so it stands in only when no reply survived.
- const answer = plan.data?.final_answer?.trim() || run.summary?.trim() || "";
-
- const status = run.status ?? "unknown";
- const needsReview = runNeedsReview(run);
- const endedEarly = !!run.terminal_reason || needsReview || (!!run.error && status === "error");
- const loading = listing.isLoading || plan.isLoading;
- const inline = files.slice(0, MAX_INLINE_FILES);
- const rest = files.slice(MAX_INLINE_FILES);
- const nothing = !loading && files.length === 0 && answer.length === 0 && !endedEarly;
-
- return (
- <div className="h-full overflow-auto" data-testid="output-preview">
- <article className="mx-auto flex max-w-[1080px] flex-col gap-10 px-8 py-10 lg:px-12">
- <header className="flex flex-col gap-3">
- <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
- <span>{t("visualization.output_kind")}</span>
- {run.started_at || run.completed_at ? (
- <>
- <span aria-hidden>·</span>
- <span className="normal-case tracking-normal">
- {formatWhen(run.completed_at ?? run.started_at)}
- </span>
- </>
- ) : null}
- {typeof run.duration_s === "number" && (
- <>
- <span aria-hidden>·</span>
- <span className="normal-case tracking-normal tabular-nums">
- {formatDuration(run.duration_s)}
- </span>
- </>
- )}
- <span aria-hidden>·</span>
- <span className="inline-flex items-center gap-1.5" data-testid="output-preview-status">
- <span className={cn("h-1.5 w-1.5 rounded-full", STATUS_DOT[status])} aria-hidden />
- {needsReview ? t("outputs_view.needs_review") : t(`visualization.status_word_${status}`)}
- </span>
- </p>
- <h1
- className="text-balance text-[clamp(26px,3.2vw,34px)] font-semibold leading-tight tracking-tight text-foreground"
- data-testid="output-preview-title"
- >
- {title || run.slug}
- </h1>
- {showRequest && (
- <p
- className="max-w-[68ch] text-[15px] leading-relaxed text-muted-foreground"
- data-testid="output-preview-request"
- >
- {request}
- </p>
- )}
- </header>
-
- {endedEarly && (
- <section
- data-testid="output-preview-outcome"
- className={cn(
- "flex gap-3 rounded-xl border p-4",
- needsReview || status === "cancelled"
- ? "border-amber-400/30 bg-amber-400/5"
- : "border-destructive/30 bg-destructive/5",
- )}
- >
- <AlertTriangle
- className={cn(
- "mt-0.5 h-4 w-4 shrink-0",
- needsReview || status === "cancelled" ? "text-amber-400" : "text-destructive",
- )}
- aria-hidden
- />
- <div className="flex min-w-0 flex-col gap-1">
- <p className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
- {needsReview
- ? t("outputs_view.needs_review")
- : status === "cancelled"
- ? t("outputs_view.cancellation_reason")
- : t("outputs_view.failure_reason")}
- </p>
- {needsReview && (
- <p className="text-sm leading-relaxed text-foreground/90">
- {t("outputs_view.needs_review_hint")}
- </p>
- )}
- {!needsReview && status === "error" && run.has_partial_output && (
- <p className="text-sm leading-relaxed text-foreground/90">
- {t("outputs_view.partial_output_hint")}
- </p>
- )}
- {run.terminal_reason && (
- <p className="font-mono text-[12px] text-muted-foreground">{run.terminal_reason}</p>
- )}
- {run.error && !run.terminal_reason && (
- <pre className="whitespace-pre-wrap font-mono text-[12px] text-destructive/90">
- {run.error}
- </pre>
- )}
- </div>
- </section>
- )}
-
- {loading && answer.length === 0 && files.length === 0 && (
- <p className="flex items-center gap-2 text-xs text-muted-foreground">
- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
- {t("outputs_view.loading_artifacts")}
- </p>
- )}
-
- {nothing && (
- <p className="text-sm text-muted-foreground" data-testid="output-preview-nothing">
- {t("visualization.preview_nothing")}
- </p>
- )}
-
- {answer.length > 0 && (
- <section className="flex flex-col gap-3" data-testid="output-preview-answer">
- <SectionEyebrow>{t("visualization.preview_answer")}</SectionEyebrow>
- <MarkdownProse
- slug={run.slug}
- path=""
- files={files}
- text={answer}
- onSelectSibling={onOpenFile}
- className="max-w-none text-[15px] leading-7 prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg"
- testId="output-preview-answer-body"
- />
- </section>
- )}
-
- {files.length > 0 && (
- <section className="flex flex-col gap-4" data-testid="output-preview-files">
- <SectionEyebrow>
- {t("visualization.preview_deliverables")}
- <span className="ml-2 font-normal normal-case tracking-normal text-muted-foreground/70">
- {files.length} {files.length === 1 ? t("outputs_view.file") : t("outputs_view.files")}
- </span>
- </SectionEyebrow>
- {inline.map((file) => (
- <FileSection
- key={file.path}
- slug={run.slug}
- file={file}
- files={files}
- onOpenFile={onOpenFile}
- />
- ))}
- {rest.length > 0 && (
- <p className="text-xs text-muted-foreground">
- {t("visualization.preview_more_files").replace("{0}", String(rest.length))}
- </p>
- )}
- </section>
- )}
- </article>
- </div>
- );
-}
-
-/** A section's label — small caps, a hairline above, the way the standard marks a section. */
-function SectionEyebrow({ children }: { children: ReactNode }) {
- return (
- <h2 className="border-t border-border pt-4 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
- {children}
- </h2>
- );
-}
-
-function KindIcon({ kind, className }: { kind: ArtifactKind; className?: string }) {
- const cls = cn("h-3.5 w-3.5 shrink-0", className);
- switch (kind) {
- case "markdown":
- case "text":
- case "pdf":
- return <FileText className={cls} aria-hidden />;
- case "html":
- return <Globe className={cls} aria-hidden />;
- case "image":
- return <FileImage className={cls} aria-hidden />;
- case "code":
- return <FileCode2 className={cls} aria-hidden />;
- case "csv":
- return <Table2 className={cls} aria-hidden />;
- default:
- return <FileQuestion className={cls} aria-hidden />;
- }
-}
-
-/**
- * One deliverable in place: a labelled block with the file's own rendering
- * inside. Text is fetched only for kinds the page draws from text; a page
- * (HTML) and a binary are named and left to Files, where the reader has the
- * sandbox and the openers for them.
- */
-function FileSection({
- slug,
- file,
- files,
- onOpenFile,
-}: {
- slug: string;
- file: ArtifactSummary;
- files: ArtifactSummary[];
- onOpenFile?: (path: string) => void;
-}) {
- const t = useT();
- const kind = artifactKind(file.path, file.is_text);
- const drawsFromText = isTextKind(kind) && kind !== "html";
- const tooLarge = file.size > MAX_INLINE_BYTES;
- const full = useArtifactFile(slug, drawsFromText && !tooLarge ? file.path : null);
- const display = deliverableDisplayPath(file.path);
-
- let body: ReactNode;
- if (kind === "image") {
- body = (
- <div className="flex justify-center p-4">
- <img
- src={artifactInlineUrl(slug, file.path)}
- alt={display}
- loading="lazy"
- className="max-h-[70vh] max-w-full rounded-md"
- />
- </div>
- );
- } else if (!drawsFromText || tooLarge) {
- body = (
- <p className="px-4 py-3 text-xs text-muted-foreground">
- {t(tooLarge ? "visualization.preview_too_large" : "visualization.preview_open_in_files_hint")}
- </p>
- );
- } else if (full.isLoading || (!full.data && !full.isError)) {
- body = (
- <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
- <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
- {t("outputs_view.loading_file")}
- </p>
- );
- } else if (full.isError || !full.data) {
- body = (
- <p className="px-4 py-3 text-xs text-destructive">
- {t("common.error")}: {String(full.error ?? "")}
- </p>
- );
- } else if (kind === "markdown") {
- body = (
- <MarkdownProse
- slug={slug}
- path={file.path}
- files={files}
- text={full.data.text}
- onSelectSibling={onOpenFile}
- className="max-w-none px-6 py-5 text-[15px] leading-7 prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg"
- testId="output-preview-markdown"
- />
- );
- } else if (kind === "csv") {
- body = <CsvTable text={full.data.text} tab={file.path.toLowerCase().endsWith(".tsv")} />;
- } else {
- body = <SourceView path={file.path} text={full.data.text} />;
- }
-
- return (
- <section
- className="overflow-hidden rounded-xl border border-border bg-card/40"
- data-testid="output-preview-file"
- data-kind={kind}
- >
- <header className="flex h-10 items-center gap-2 border-b border-border/60 bg-card/60 px-4">
- <KindIcon kind={kind} className="text-primary" />
- <span className="min-w-0 flex-1 truncate font-mono text-[12px] text-foreground" title={file.path}>
- {display}
- </span>
- <span className="shrink-0 font-mono text-[11px] text-muted-foreground">
- {formatBytes(file.size)}
- </span>
- {onOpenFile && (
- <button
- type="button"
- onClick={() => onOpenFile(file.path)}
- className="inline-flex shrink-0 items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-secondary/50 hover:text-foreground"
- title={t("visualization.preview_open_in_files")}
- >
- {t("visualization.preview_open_in_files")}
- <ArrowUpRight className="h-3 w-3" aria-hidden />
- </button>
- )}
- </header>
- {full.data?.truncated && (
- <p className="border-b border-border/60 px-4 py-1.5 text-[10px] text-muted-foreground">
- {t("outputs_view.file_truncated")}
- </p>
- )}
- {body}
- </section>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx b/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx
index 950e74ac79..e75ccac33a 100644
--- a/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx
+++ b/jarvis/ui/web/frontend/src/components/visualization/RunPanels.tsx
@@ -353,14 +353,7 @@ export function deliverableFiles(files: ArtifactSummary[]): ArtifactSummary[] {
* (summary, why it ended) sit above the files: for a run that produced no
* page — a research answer, a failed build — they ARE the result.
*/
-export function RunFiles({
- run,
- initialPath,
-}: {
- run: OutputSummary;
- /** The file the reader opens on — set when the user came from the output page. */
- initialPath?: string | null;
-}) {
+export function RunFiles({ run }: { run: OutputSummary }) {
const t = useT();
const q = useArtifactsForOutput(run.slug);
const caps = useOutputsCapabilities();
@@ -396,11 +389,10 @@ export function RunFiles({
<div className="text-xs text-muted-foreground">{t("outputs_view.no_files")}</div>
) : (
<ArtifactViewer
- key={`${run.slug}:${initialPath ?? ""}`}
+ key={run.slug}
slug={run.slug}
files={files}
nativeActions={nativeActions}
- initialPath={initialPath}
/>
)}
</section>
diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
index c3af82bcad..7c345fc1e8 100644
--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
@@ -21,9 +21,7 @@ export type CostRole =
// The speech layer bills by audio second and by character, not by token —
// its own two roles rather than a shape forced onto the token vocabulary.
| "stt"
- | "tts"
- // A model call made by a background job (wiki, awareness, dictation …).
- | "background";
+ | "tts";
/** Which part of the app it was spent in. */
export type CostSurface =
@@ -31,8 +29,7 @@ export type CostSurface =
| "agent-chat"
| "mission"
| "agentic-ide"
- | "jarvis-voice"
- | "background";
+ | "jarvis-voice";
/**
* How confident the price is.
@@ -125,8 +122,6 @@ export interface CostSummary {
series: CostBucket[];
top_refs: CostRefBucket[];
models: CostModelRow[];
- /** Every conversation/mission/session in the window; `top_refs` is a slice. */
- refs_total: number;
facets: CostFacets;
currency: CostCurrency;
sources_present: string[];
@@ -198,8 +193,6 @@ export interface CostPricing {
// Query state shared by the summary and the line items
// ---------------------------------------------------------------------------
-export type CostBilling = "all" | "billed" | "subscription";
-
export interface CostFilters {
/** Rolling window in days; `0` means everything ever recorded. */
days: number;
@@ -210,8 +203,6 @@ export interface CostFilters {
/** Session / mission ids — set by clicking a row in "Where it went". */
refs: string[];
search: string;
- /** "all" · "billed" (an API key paid) · "subscription" (seat quotes only). */
- billing: CostBilling;
/**
* An explicit window, in epoch ms. When set it wins over `days` — the
* daily report drills into ONE day and everything it shows (the hourly
@@ -229,7 +220,6 @@ export const EMPTY_FILTERS: CostFilters = {
roles: [],
surfaces: [],
refs: [],
- billing: "all",
search: "",
};
@@ -258,7 +248,6 @@ function toParams(f: CostFilters): URLSearchParams {
for (const r of f.roles) params.append("role", r);
for (const s of f.surfaces) params.append("surface", s);
for (const r of f.refs) params.append("ref", r);
- if (f.billing !== "all") params.set("billing", f.billing);
if (f.search.trim()) params.set("search", f.search.trim());
return params;
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 9f1656d147..e4c7bd941c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -759,6 +759,7 @@
},
"insight_loading": "Der Verlauf des Laufs wird gelesen…",
"insight_load_error": "Der Verlauf des Laufs konnte nicht geladen werden: {detail}",
+ "action_open_output": "Ergebnis öffnen",
"action_map": "Missionskarte",
"no_output_dir": "Ausgabeordner liegt nicht mehr auf der Platte",
"stat_cost_label": "Kosten",
@@ -817,6 +818,7 @@
"transcript_no_dir": "Das vollständige Worker-Transkript ist mit dem Ausgabeordner verschwunden — die Schritte oben decken weiterhin jedes Ereignis des Laufs ab.",
"transcript_truncated": "Das Transkript war länger als hier gezeigt.",
"transcript_dropped": "{n} weitere Schritte werden nicht gezeigt.",
+ "final_answer": "Abschließende Antwort",
"step_status": {
"pending": "Ausstehend",
"running": "Läuft",
@@ -842,6 +844,9 @@
"details_title": "Details",
"live_title": "Gerade jetzt",
"live_subtitle": "Tool-Aufrufe, die der Agent in diesem Moment ausführt.",
+ "timeline_title": "Schritt für Schritt",
+ "timeline_subtitle": "Was {agent} gesagt und getan hat, der Reihe nach.",
+ "output_title": "Was herausgekommen ist",
"actions_one": "1 Aktion ausgeführt",
"actions_many": "{n} Aktionen in {span} ausgeführt",
"transcript_fold": "Vollständiges Worker-Transkript · {n} Schritte",
@@ -884,39 +889,6 @@
"failed_worker_error": "Der Worker-Prozess ist abgestürzt. Es wurde nichts geliefert.",
"failed_after_review": "Der Worker hat einen Entwurf abgeliefert, aber der Prüfer hat ihn nicht abgenommen — dort endete der Lauf.",
"failed_generic": "Die Aufgabe des Workers ist nach {runtime} fehlgeschlagen. Es wurde nichts geliefert."
- },
- "action_open_artifacts": "In Artefakten öffnen",
- "register_verdict": "Was passiert ist",
- "register_report": "Bericht von {agent}",
- "register_timeline": "Zeitverlauf",
- "register_files": "Dateien",
- "timeline_meta": "{n} aufgezeichnete Ereignisse",
- "files_meta": "{n} Dateien · +{add} −{del} Zeilen",
- "fact_files": "Dateien",
- "confidence": "{pct} % Sicherheit",
- "report_expand": "Ganzen Bericht lesen",
- "report_collapse": "Bericht einklappen",
- "kind": {
- "start": "Start",
- "plan": "Plan",
- "worker": "Worker",
- "said": "Sagte",
- "ran": "Lief",
- "draft": "Entwurf",
- "review": "Prüfung",
- "fix": "Korrektur",
- "stop": "Stopp",
- "end": "Ende",
- "budget": "Budget",
- "thought": "Gedanke"
- },
- "change": {
- "added": "Neue Datei",
- "modified": "Geändert",
- "deleted": "Gelöscht",
- "renamed": "Umbenannt",
- "delivered": "Geliefert",
- "binary": "binär"
}
},
"tasks_view": {
@@ -5030,7 +5002,7 @@
},
"visualization": {
"title": "Artefakte",
- "subtitle": "Alles, was deine Durchläufe erzeugt haben, jedes als Seite — Artefakte in voller Größe, jeder andere Output genauso aufbereitet; Quelltext, Dateien und Durchlauf einen Tab entfernt",
+ "subtitle": "Alles, was deine Durchläufe erzeugt haben — Seiten und Bilder in voller Größe, jeder andere Durchlauf mit Dateien, Status und Steuerung; Quelltext und Durchlauf einen Tab entfernt",
"refresh": "Aktualisieren",
"rail": "Artefakte & Durchläufe",
"building": "Wird gebaut …",
@@ -5041,23 +5013,6 @@
"tab_code": "Code",
"tab_files": "Dateien",
"tab_run": "Durchlauf",
- "rail_filter": "Anzeigen",
- "filter_all": "Alle",
- "filter_artifacts": "Artefakte",
- "filter_outputs": "Outputs",
- "output_kind": "Output",
- "preview_answer": "Antwort",
- "preview_deliverables": "Dateien",
- "preview_nothing": "Dieser Durchlauf hat weder eine Antwort noch Dateien hinterlassen.",
- "preview_open_in_files": "Unter Dateien öffnen",
- "preview_open_in_files_hint": "Diese Datei wird nicht auf der Seite gezeichnet — öffne sie unter Dateien.",
- "preview_too_large": "Zu groß für die Seite — öffne sie unter Dateien.",
- "preview_more_files": "{0} weitere Dateien unter Dateien.",
- "status_word_success": "Erfolgreich",
- "status_word_error": "Fehlgeschlagen",
- "status_word_running": "Läuft",
- "status_word_cancelled": "Abgebrochen",
- "status_word_unknown": "Unbekannt",
"stage_tabs": "Ansicht dieses Artefakts",
"open_external_hint": "Öffnet dieses Artefakt im Browser — ganzes Fenster, teilbar, druckbar.",
"page_sandbox_note": "Läuft in einer Sandbox: die Skripte der Seite funktionieren, das Netzwerk ist aus.",
@@ -5430,9 +5385,6 @@
"col_share": "Anteil",
"col_cost": "Kosten",
"col_calls": "Aufrufe",
- "billing_label": "Welche Ausgaben zeigen",
- "top_refs_subtitle_counted": "Die {shown} teuersten von {total} Gesprächen, Chats und Missionen — {share} der Gesamtsumme. Zum Filtern anklicken.",
- "billing": {"all": "Alle", "billed": "Über Keys bezahlt", "subscription": "Über Abos"},
"speech_area_note": "Hören und Sprechen werden in Audiosekunden und Zeichen abgerechnet — nie in Tokens. Ein Sprache-zu-Sprache-Modell hat kein eigenes Ohr und keinen eigenen Mund; seine Turns stehen unter {name} → Realtime-Stimme. Eine Zeile mit 0,00 $ ist entweder eine lokale Engine (kostenlos) oder ein Anbieter ohne veröffentlichten Tarif — die Spalte „Tarif“ sagt, was zutrifft.",
"col_rate": "Tarif",
"stat_total_hint_seat_only": "API-Gegenwert — vollständig durch Abos gedeckt, nichts über einen Key abgerechnet",
@@ -5502,7 +5454,6 @@
"rate_default": "Standardkurs",
"footnote": "Gelesen aus {sources}. {estimated} der Summe wurden hier aus den Preistabellen berechnet, nicht vom Anbieter gemeldet. EUR umgerechnet mit {rate} ({rateSource}).",
"role": {
- "background": "Hintergrundjob",
"realtime": "Echtzeit-Stimme",
"tool": "Tool-Modell",
"pipeline": "Pipeline-Gehirn",
@@ -5512,7 +5463,6 @@
"tts": "Text zu Sprache"
},
"surface": {
- "background": "Im Hintergrund",
"voice": "Sprache",
"agent_chat": "Agenten-Chat",
"mission": "Mission",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index fbefd1d02f..9542c9fac1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -759,6 +759,7 @@
},
"insight_loading": "Reading the run's record…",
"insight_load_error": "The run's record could not be loaded: {detail}",
+ "action_open_output": "Open output",
"action_map": "Mission map",
"no_output_dir": "output directory no longer on disk",
"stat_cost_label": "Cost",
@@ -817,6 +818,7 @@
"transcript_no_dir": "The worker's full transcript went with the output folder — the steps above still cover every event of the run.",
"transcript_truncated": "The transcript was longer than what is shown.",
"transcript_dropped": "{n} more steps are not shown.",
+ "final_answer": "Final answer",
"step_status": {
"pending": "Pending",
"running": "Running",
@@ -842,6 +844,9 @@
"details_title": "Details",
"live_title": "Right now",
"live_subtitle": "Tool calls the agent is running at this moment.",
+ "timeline_title": "Step by step",
+ "timeline_subtitle": "What {agent} said and did, in order.",
+ "output_title": "What came out",
"actions_one": "Ran 1 action",
"actions_many": "Ran {n} actions in {span}",
"transcript_fold": "Full worker transcript · {n} steps",
@@ -884,39 +889,6 @@
"failed_worker_error": "The worker process crashed. Nothing was delivered.",
"failed_after_review": "The worker produced a draft, but the reviewer did not approve it and the run ended there.",
"failed_generic": "The worker's task failed after {runtime}. Nothing was delivered."
- },
- "action_open_artifacts": "Open in Artifacts",
- "register_verdict": "What happened",
- "register_report": "{agent}'s report",
- "register_timeline": "Timeline",
- "register_files": "Files",
- "timeline_meta": "{n} recorded events",
- "files_meta": "{n} files · +{add} −{del} lines",
- "fact_files": "Files",
- "confidence": "{pct}% confidence",
- "report_expand": "Read the full report",
- "report_collapse": "Collapse the report",
- "kind": {
- "start": "Start",
- "plan": "Plan",
- "worker": "Worker",
- "said": "Said",
- "ran": "Ran",
- "draft": "Draft",
- "review": "Review",
- "fix": "Fix",
- "stop": "Stop",
- "end": "End",
- "budget": "Budget",
- "thought": "Thought"
- },
- "change": {
- "added": "New file",
- "modified": "Changed",
- "deleted": "Deleted",
- "renamed": "Renamed",
- "delivered": "Delivered",
- "binary": "binary"
}
},
"tasks_view": {
@@ -5030,7 +5002,7 @@
},
"visualization": {
"title": "Artifacts",
- "subtitle": "Everything your runs produced, every one as a page — artifacts full-size, every other output composed the same way; source, files and the run one tab away",
+ "subtitle": "Everything your runs produced — pages and pictures full-size, every other run with its files, status and controls; source and run one tab away",
"refresh": "Refresh",
"rail": "Artifacts & runs",
"building": "Building…",
@@ -5041,23 +5013,6 @@
"tab_code": "Code",
"tab_files": "Files",
"tab_run": "Run",
- "rail_filter": "Show",
- "filter_all": "All",
- "filter_artifacts": "Artifacts",
- "filter_outputs": "Outputs",
- "output_kind": "Output",
- "preview_answer": "Answer",
- "preview_deliverables": "Files",
- "preview_nothing": "This run left no answer and no files behind.",
- "preview_open_in_files": "Open in Files",
- "preview_open_in_files_hint": "This file is not drawn on the page — open it under Files.",
- "preview_too_large": "Too large to draw on the page — open it under Files.",
- "preview_more_files": "{0} more files under Files.",
- "status_word_success": "Succeeded",
- "status_word_error": "Failed",
- "status_word_running": "Running",
- "status_word_cancelled": "Cancelled",
- "status_word_unknown": "Unknown",
"stage_tabs": "How to view this artifact",
"open_external_hint": "Open this artifact in your browser — full window, shareable, printable.",
"page_sandbox_note": "Runs in a sandbox: the page's own scripts work, the network is off.",
@@ -5430,9 +5385,6 @@
"col_share": "Share",
"col_cost": "Cost",
"col_calls": "Calls",
- "billing_label": "Which spend to show",
- "top_refs_subtitle_counted": "The {shown} most expensive of {total} conversations, chats and missions — {share} of the total. Click one to filter by it.",
- "billing": {"all": "All", "billed": "Billed to keys", "subscription": "On subscriptions"},
"speech_area_note": "Hearing and speaking are billed in audio seconds and characters — never tokens. A speech-to-speech model has no separate ear or mouth, so its turns sit under {name} → Realtime voice. A row at $0.00 is either a local engine (free) or a vendor that publishes no rate — the Rate column says which.",
"col_rate": "Rate",
"stat_total_hint_seat_only": "API-equivalent — fully covered by subscriptions, nothing billed to a key",
@@ -5502,7 +5454,6 @@
"rate_default": "default rate",
"footnote": "Read from {sources}. {estimated} of the total was priced here from the rate tables rather than reported by the provider. EUR converted at {rate} ({rateSource}).",
"role": {
- "background": "Background job",
"realtime": "Realtime voice",
"tool": "Tool model",
"pipeline": "Pipeline brain",
@@ -5512,7 +5463,6 @@
"tts": "Text to speech"
},
"surface": {
- "background": "Behind the scenes",
"voice": "Voice",
"agent_chat": "Agent chat",
"mission": "Mission",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index d5f856bf46..52b4fbe51b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -759,6 +759,7 @@
},
"insight_loading": "Leyendo el registro de la ejecución…",
"insight_load_error": "No se pudo cargar el registro de la ejecución: {detail}",
+ "action_open_output": "Abrir resultado",
"action_map": "Mapa de la misión",
"no_output_dir": "la carpeta de salida ya no está en el disco",
"stat_cost_label": "Coste",
@@ -817,6 +818,7 @@
"transcript_no_dir": "La transcripción completa del worker se fue con la carpeta de salida — los pasos de arriba siguen cubriendo cada evento de la ejecución.",
"transcript_truncated": "La transcripción era más larga de lo que se muestra.",
"transcript_dropped": "{n} pasos más no se muestran.",
+ "final_answer": "Respuesta final",
"step_status": {
"pending": "Pendiente",
"running": "En marcha",
@@ -842,6 +844,9 @@
"details_title": "Detalles",
"live_title": "Ahora mismo",
"live_subtitle": "Llamadas a herramientas que el agente ejecuta en este momento.",
+ "timeline_title": "Paso a paso",
+ "timeline_subtitle": "Lo que {agent} dijo e hizo, en orden.",
+ "output_title": "Lo que salió",
"actions_one": "Ejecutó 1 acción",
"actions_many": "Ejecutó {n} acciones en {span}",
"transcript_fold": "Transcripción completa del worker · {n} pasos",
@@ -884,39 +889,6 @@
"failed_worker_error": "El proceso del worker falló. No se entregó nada.",
"failed_after_review": "El worker produjo un borrador, pero el revisor no lo aprobó y la ejecución terminó ahí.",
"failed_generic": "La tarea del worker falló tras {runtime}. No se entregó nada."
- },
- "action_open_artifacts": "Abrir en Artefactos",
- "register_verdict": "Qué pasó",
- "register_report": "Informe de {agent}",
- "register_timeline": "Cronología",
- "register_files": "Archivos",
- "timeline_meta": "{n} eventos registrados",
- "files_meta": "{n} archivos · +{add} −{del} líneas",
- "fact_files": "Archivos",
- "confidence": "{pct} % de confianza",
- "report_expand": "Leer el informe completo",
- "report_collapse": "Plegar el informe",
- "kind": {
- "start": "Inicio",
- "plan": "Plan",
- "worker": "Worker",
- "said": "Dijo",
- "ran": "Ejecutó",
- "draft": "Borrador",
- "review": "Revisión",
- "fix": "Corrección",
- "stop": "Parada",
- "end": "Fin",
- "budget": "Presupuesto",
- "thought": "Pensó"
- },
- "change": {
- "added": "Archivo nuevo",
- "modified": "Modificado",
- "deleted": "Eliminado",
- "renamed": "Renombrado",
- "delivered": "Entregado",
- "binary": "binario"
}
},
"tasks_view": {
@@ -5030,7 +5002,7 @@
},
"visualization": {
"title": "Artefactos",
- "subtitle": "Todo lo que produjeron tus ejecuciones, cada una como página — artefactos a tamaño completo, cualquier otro resultado compuesto igual; código, archivos y ejecución a una pestaña",
+ "subtitle": "Todo lo que produjeron tus ejecuciones — páginas e imágenes a tamaño completo, cada otra ejecución con sus archivos, estado y controles; código y ejecución a una pestaña de distancia",
"refresh": "Actualizar",
"rail": "Artefactos y ejecuciones",
"building": "Creando…",
@@ -5041,23 +5013,6 @@
"tab_code": "Código",
"tab_files": "Archivos",
"tab_run": "Ejecución",
- "rail_filter": "Mostrar",
- "filter_all": "Todo",
- "filter_artifacts": "Artefactos",
- "filter_outputs": "Resultados",
- "output_kind": "Resultado",
- "preview_answer": "Respuesta",
- "preview_deliverables": "Archivos",
- "preview_nothing": "Esta ejecución no dejó ni respuesta ni archivos.",
- "preview_open_in_files": "Abrir en Archivos",
- "preview_open_in_files_hint": "Este archivo no se dibuja en la página — ábrelo en Archivos.",
- "preview_too_large": "Demasiado grande para la página — ábrelo en Archivos.",
- "preview_more_files": "{0} archivos más en Archivos.",
- "status_word_success": "Completada",
- "status_word_error": "Fallida",
- "status_word_running": "En curso",
- "status_word_cancelled": "Cancelada",
- "status_word_unknown": "Desconocido",
"stage_tabs": "Cómo ver este artefacto",
"open_external_hint": "Abre este artefacto en el navegador — ventana completa, se puede compartir e imprimir.",
"page_sandbox_note": "Se ejecuta en un entorno aislado: los scripts de la página funcionan, la red está desactivada.",
@@ -5430,9 +5385,6 @@
"col_share": "Parte",
"col_cost": "Coste",
"col_calls": "Llamadas",
- "billing_label": "Qué gasto mostrar",
- "top_refs_subtitle_counted": "Las {shown} más caras de {total} conversaciones, chats y misiones — {share} del total. Haz clic en una para filtrar.",
- "billing": {"all": "Todo", "billed": "Facturado a claves", "subscription": "Con suscripciones"},
"speech_area_note": "Escuchar y hablar se facturan en segundos de audio y caracteres — nunca en tokens. Un modelo voz a voz no tiene oído ni boca propios; sus turnos están en {name} → Voz en tiempo real. Una fila a $0,00 es un motor local (gratis) o un proveedor sin tarifa publicada — la columna «Tarifa» lo indica.",
"col_rate": "Tarifa",
"stat_total_hint_seat_only": "Equivalente API — cubierto por completo por suscripciones, nada facturado a una clave",
@@ -5502,7 +5454,6 @@
"rate_default": "tipo por defecto",
"footnote": "Leído de {sources}. {estimated} del total se calculó aquí con las tablas de tarifas, no lo informó el proveedor. EUR convertido a {rate} ({rateSource}).",
"role": {
- "background": "Tarea en segundo plano",
"realtime": "Voz en tiempo real",
"tool": "Modelo de herramientas",
"pipeline": "Cerebro de la cadena",
@@ -5512,7 +5463,6 @@
"tts": "Texto a voz"
},
"surface": {
- "background": "En segundo plano",
"voice": "Voz",
"agent_chat": "Chat de agentes",
"mission": "Misión",
diff --git a/jarvis/ui/web/frontend/src/lib/runRequest.test.ts b/jarvis/ui/web/frontend/src/lib/runRequest.test.ts
deleted file mode 100644
index 5cfbf8fbca..0000000000
--- a/jarvis/ui/web/frontend/src/lib/runRequest.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { cleanRequest, requestHeadline } from "@/lib/runRequest";
-
-describe("cleanRequest", () => {
- it("drops the builder's supporting-context tail and collapses whitespace", () => {
- const utterance =
- "No, just spawn them.\n\nSupporting context from the recent conversation " +
- "(use only to resolve references; the underlying request remains authoritative):\n" +
- "- Conversation context (recent turns, newest last): …";
- expect(cleanRequest(utterance)).toBe("No, just spawn them.");
- });
-
- it("returns a plain request whole", () => {
- expect(cleanRequest(" Write notes ")).toBe("Write notes");
- expect(cleanRequest(undefined)).toBe("");
- });
-});
-
-describe("requestHeadline", () => {
- it("keeps a short request as it is", () => {
- expect(requestHeadline("Write notes")).toBe("Write notes");
- });
-
- it("takes the first sentence when it is short enough", () => {
- expect(
- requestHeadline(
- "Please start five new cloud coding instances. They should all do the same thing and " +
- "then report back in great detail on what happened.",
- ),
- ).toBe("Please start five new cloud coding instances.");
- });
-
- it("cuts a long single sentence at a word boundary with an ellipsis", () => {
- const text =
- "a quick deep dive that analyses all my e-mails through the Gmail plugin and then " +
- "tells me which ones matter and which ones I can delete";
- const headline = requestHeadline(text, 60);
- expect(headline.endsWith("…")).toBe(true);
- expect(headline.length).toBeLessThanOrEqual(61);
- expect(headline).toBe("a quick deep dive that analyses all my e-mails through the…");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/lib/runRequest.ts b/jarvis/ui/web/frontend/src/lib/runRequest.ts
deleted file mode 100644
index 4878812c47..0000000000
--- a/jarvis/ui/web/frontend/src/lib/runRequest.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * The user's real ask out of a run's recorded request — what a rail row, a
- * stage title and an output page call the run.
- *
- * The run list (`/api/outputs`) already strips the standing quality
- * directive the mission builder prepends (`clean_request_body`). What it
- * leaves in place is the TAIL the builder appends on a no-interpretation
- * spawn: "Supporting context from the recent conversation (use only to
- * resolve references; …):" followed by the transcript hints. That tail is
- * plumbing for the worker, not part of the request, and it made half the
- * rail read "…Supporting context from the recent conversation (use only to
- * resolve references; the underlying request remains authoritative): - …"
- * (2026-08-25). Pure text; no I/O.
- */
-
-/** The builder's supporting-context tail — everything from its lead on. */
-const SUPPORTING_CONTEXT_RE =
- /\s*Supporting context from the recent conversation\b[\s\S]*$/i;
-
-/** The user's request without the worker-facing tail, whitespace collapsed. */
-export function cleanRequest(utterance: string | null | undefined): string {
- const text = (utterance ?? "").replace(SUPPORTING_CONTEXT_RE, "");
- return text.replace(/\s+/g, " ").trim();
-}
-
-/** Default headline length — one comfortable line at the stage's h1 size. */
-export const HEADLINE_MAX_CHARS = 96;
-
-/**
- * A headline out of a request: its first sentence when that is short enough,
- * otherwise the first `max` characters cut at a word boundary with an
- * ellipsis. A request that is already short comes back whole.
- */
-export function requestHeadline(text: string, max: number = HEADLINE_MAX_CHARS): string {
- const clean = cleanRequest(text);
- if (clean.length <= max) return clean;
- const sentence = /^(.{12,}?[.!?])\s/.exec(clean)?.[1];
- if (sentence && sentence.length <= max) return sentence;
- const cut = clean.slice(0, max);
- const space = cut.lastIndexOf(" ");
- return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:\-–—(]+$/, "")}…`;
-}
diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsx
index d1a5118141..bfa07cda40 100644
--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx
@@ -86,7 +86,6 @@ import {
useCostSummary,
type CostBucket,
type CostDayRow,
- type CostBilling,
type CostFilters,
type CostRole,
type CostSurface,
@@ -262,16 +261,6 @@ export function CostsView() {
--------------------------------------------------------------- */}
<div className="flex flex-wrap items-center gap-x-2 gap-y-2">
<AreaSwitch value={area?.id ?? null} onChange={pickArea} />
- <SegmentedFilter<CostBilling>
- label={t("costs_view.billing_label")}
- value={filters.billing}
- onChange={(billing) => setFilters((f) => ({ ...f, billing }))}
- options={[
- { id: "all", label: t("costs_view.billing.all") },
- { id: "billed", label: t("costs_view.billing.billed") },
- { id: "subscription", label: t("costs_view.billing.subscription") },
- ]}
- />
<RoleFilters
roles={(area ?? SURFACE_GROUPS[0]).roles}
available={data?.facets.roles ?? []}
@@ -517,17 +506,7 @@ export function CostsView() {
<div className="px-4 pt-4">
<PanelHeader
title={t("costs_view.top_refs_title")}
- subtitle={
- data && data.refs_total > 0
- ? fill(t("costs_view.top_refs_subtitle_counted"), {
- shown: String(data.top_refs.length),
- total: formatExact(data.refs_total),
- share: formatShare(
- data.top_refs.reduce((sum, r) => sum + r.cost_share, 0),
- ),
- })
- : t("costs_view.top_refs_subtitle")
- }
+ subtitle={t("costs_view.top_refs_subtitle")}
/>
</div>
<div className="mt-3">
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
index 5b6ec085fe..ada1cab296 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
@@ -5,10 +5,8 @@
*
* Contracts:
* - a run without a page or picture shows as a run row; its stage opens on
- * Preview as a composed output page (the answer, the reason it ended, its
- * files in place), with Files one tab away carrying the notes above the
- * reader; the empty state appears only when there are no runs at all,
- * - the rail narrows to artifacts or outputs and back, remembering the pick,
+ * Files, with the summary / reason it ended above the files; the empty
+ * state appears only when there are no runs at all,
* - Continue / Restart gating per status, the needs-review card, the live
* continuation chip that jumps to the child, hold-to-abort while running,
* - Files: clean paths with primary files first, no direct download, the
@@ -145,13 +143,8 @@ const REPORT = file("tasks/019edf/artifacts/files/report.md", {
preview: "# Report",
});
-/** The stage opens on Preview; the Files reader is one click away. */
-async function openFiles() {
- fireEvent.click(await screen.findByTestId("visualization-tab-files"));
-}
-
describe("VisualizationView — runs without an artifact", () => {
- it("lists a page-less run as a run row and opens it on Preview as a page, Files one tab away", async () => {
+ it("lists a page-less run as a run row and opens it on Files with its notes", async () => {
installFetchMock(
[
run({
@@ -173,70 +166,18 @@ describe("VisualizationView — runs without an artifact", () => {
expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0);
// No empty state: the run IS the content.
expect(screen.queryByTestId("visualization-empty")).toBeNull();
- // The stage opens on Preview — the same four tabs every run gets …
- const previewTab = await screen.findByTestId("visualization-tab-preview");
- expect(previewTab.getAttribute("aria-selected")).toBe("true");
- expect(screen.getByTestId("visualization-tab-files")).toBeDefined();
- expect(screen.getByTestId("visualization-tab-run")).toBeDefined();
- // … and the page composed from the run: headline, the answer, the file in place.
- const page = await screen.findByTestId("output-preview");
- expect(within(page).getByTestId("output-preview-title").textContent).toBe("Write notes");
- await within(page).findByTestId("output-preview-answer");
- expect(within(page).getAllByText("Three notes, saved.").length).toBeGreaterThan(0);
- await waitFor(() =>
- expect(within(page).getAllByTestId("output-preview-file")).toHaveLength(1),
- );
- // Files: the notes above the reader, the file itself in it.
- await openFiles();
+ // The stage opens on Files (there is no page to preview) …
+ const filesTab = await screen.findByTestId("visualization-tab-files");
+ expect(filesTab.getAttribute("aria-selected")).toBe("true");
+ expect(screen.queryByTestId("visualization-tab-preview")).toBeNull();
+ // … with the summary above the files, and the file itself in the reader.
await screen.findByTestId("run-notes");
+ expect(screen.getAllByText("Three notes, saved.").length).toBeGreaterThan(0);
await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("notes.md"));
// The run status sits in the toolbar, one badge.
expect(screen.getByTestId("run-status-badge").textContent).toContain("success");
});
- it("narrows the rail to artifacts or outputs and remembers the pick", async () => {
- window.localStorage.removeItem("jarvis.artifacts.rail-filter");
- installFetchMock(
- [
- run({ slug: "page-run", utterance: "Draw a dashboard", status: "success" }),
- run({ slug: "notes-run", utterance: "Write notes", status: "success" }),
- ],
- {
- "page-run": [
- file("tasks/t1/artifacts/files/dashboard.html", {
- preview: "<title>Sales</title>",
- }),
- ],
- "notes-run": [file("tasks/t2/artifacts/files/notes.md")],
- },
- );
-
- renderView();
-
- await screen.findAllByTestId("visualization-artifact-row");
- await screen.findAllByTestId("visualization-run-row");
- const filter = screen.getByTestId("visualization-filter");
- expect(within(filter).getByTestId("visualization-filter-all").textContent).toContain("2");
-
- fireEvent.click(within(filter).getByTestId("visualization-filter-artifacts"));
- await waitFor(() => expect(screen.queryAllByTestId("visualization-run-row")).toHaveLength(0));
- expect(screen.getAllByTestId("visualization-artifact-row")).toHaveLength(1);
- expect(window.localStorage.getItem("jarvis.artifacts.rail-filter")).toBe("artifacts");
-
- fireEvent.click(within(filter).getByTestId("visualization-filter-outputs"));
- await waitFor(() =>
- expect(screen.queryAllByTestId("visualization-artifact-row")).toHaveLength(0),
- );
- expect(screen.getAllByTestId("visualization-run-row")).toHaveLength(1);
- // The stage followed the filter: the output is on stage, not the page.
- await screen.findByTestId("output-preview");
-
- fireEvent.click(within(filter).getByTestId("visualization-filter-all"));
- await waitFor(() => expect(screen.getAllByTestId("visualization-run-row")).toHaveLength(1));
- expect(screen.getAllByTestId("visualization-artifact-row")).toHaveLength(1);
- window.localStorage.removeItem("jarvis.artifacts.rail-filter");
- });
-
it("says so only when there are no runs at all", async () => {
installFetchMock([], {});
renderView();
@@ -278,12 +219,6 @@ describe("VisualizationView — runs without an artifact", () => {
renderView();
- // The output page leads with why the run ended …
- const outcome = await screen.findByTestId("output-preview-outcome");
- expect(within(outcome).getAllByText("Needs review").length).toBeGreaterThan(0);
- expect(within(outcome).getByText("critic_loop_exhausted")).toBeDefined();
- // … and Files carries the same verdict above the reader.
- await openFiles();
await waitFor(() => expect(screen.getByTestId("output-needs-review")).toBeDefined());
expect(screen.getAllByText("Needs review").length).toBeGreaterThan(0);
expect(screen.getAllByText("critic_loop_exhausted").length).toBeGreaterThan(0);
@@ -306,10 +241,6 @@ describe("VisualizationView — runs without an artifact", () => {
renderView();
- const outcome = await screen.findByTestId("output-preview-outcome");
- expect(within(outcome).getByText("task_error")).toBeDefined();
- expect(within(outcome).queryByText("Needs review")).toBeNull();
- await openFiles();
await waitFor(() => expect(screen.getByTestId("output-terminal-reason")).toBeDefined());
expect(screen.queryByTestId("output-needs-review")).toBeNull();
expect(screen.getByTestId("run-status-badge").textContent).toContain("error");
@@ -404,7 +335,6 @@ describe("VisualizationView — the Files tab", () => {
);
renderView();
- await openFiles();
await waitFor(() => expect(screen.getAllByTestId("artifact-path")).toHaveLength(3));
expect(screen.getAllByTestId("artifact-path").map((node) => node.textContent)).toEqual([
@@ -420,9 +350,8 @@ describe("VisualizationView — the Files tab", () => {
});
renderView();
- await openFiles();
- await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));
+ await waitFor(() => expect(screen.getByText("report.md")).toBeDefined());
expect(screen.queryByText("tasks/019edf/artifacts/files/report.md")).toBeNull();
expect(screen.queryByTitle("Download")).toBeNull();
@@ -449,9 +378,8 @@ describe("VisualizationView — the Files tab", () => {
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
renderView();
- await openFiles();
- await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));
+ await waitFor(() => expect(screen.getByText("report.md")).toBeDefined());
fireEvent.click(screen.getByTitle("Change how this opens"));
fireEvent.click(await screen.findByText("Browser"));
@@ -485,9 +413,8 @@ describe("VisualizationView — the Files tab", () => {
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
renderView();
- await openFiles();
- await waitFor(() => expect(screen.getByTestId("artifact-path").textContent).toBe("report.md"));
+ await waitFor(() => expect(screen.getByText("report.md")).toBeDefined());
// The remembered preference is a query of its own; "Open" asks the chooser
// until it has resolved, so wait for it before clicking.
await waitFor(() =>
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
index 918589df0c..9b28959a00 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.tsx
@@ -18,32 +18,26 @@ import {
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { OutputPreview } from "@/components/visualization/OutputPreview";
import { RunGraphPanel } from "@/components/visualization/RunGraphPanel";
import {
RunActions,
RunFiles,
RunStatusBadge,
- deliverableFiles,
} from "@/components/visualization/RunPanels";
import { ViewHeader } from "@/views/ChatsView";
import { useT } from "@/i18n";
import { useThemeValue } from "@/hooks/useTheme";
import { cn } from "@/lib/utils";
-import { artifactKind, isTextKind } from "@/lib/artifactKind";
-import { cleanRequest, requestHeadline } from "@/lib/runRequest";
import { useEventStore } from "@/store/events";
import { openExternalUrl } from "@/lib/openExternal";
import { endMissionDrag, startMissionDrag } from "@/lib/missionDnd";
import {
artifactDownloadUrl,
- artifactOpenUrl,
revealArtifact,
useArtifactFile,
useArtifactsForOutput,
useOutputsCapabilities,
useOutputsList,
- type ArtifactSummary,
type OutputStatus,
type OutputSummary,
} from "@/hooks/useOutputs";
@@ -77,14 +71,6 @@ import {
* Restart, the GitHub link). One place for what Jarvis and its agents made,
* not two.
*
- * Since 2026-08-25 the artifact treatment IS the standard for every run:
- * the stage always offers Preview / Code / Files / Run, and a run without a
- * page gets its Preview composed from what it left behind (`OutputPreview`
- * — the answer and every file rendered in place, in the artifact design
- * standard) instead of a bare file list. The rail can be narrowed to
- * artifacts (pages and pictures a worker drew) or outputs (every other
- * run); "all" is the default.
- *
* It owns no data: runs come from `/api/outputs`, files from the artifact
* listing (`useVisualArtifacts`, `useArtifactsForOutput`), a page's source
* from `/raw`. A run that is still building its artifact shows as a
@@ -152,43 +138,7 @@ export function parseArtifactUtterance(
/** What a run is called when it has no page title of its own. */
function runTitle(run: OutputSummary): string {
- return (
- parseArtifactUtterance(run.utterance)?.title || requestHeadline(run.utterance ?? "") || run.slug
- );
-}
-
-/** The rail's narrowing: everything, the pages and pictures, or the rest. */
-export type RailFilter = "all" | "artifacts" | "outputs";
-
-const RAIL_FILTER_KEY = "jarvis.artifacts.rail-filter";
-
-function readRailFilter(): RailFilter {
- try {
- const stored = window.localStorage.getItem(RAIL_FILTER_KEY);
- if (stored === "artifacts" || stored === "outputs") return stored;
- } catch {
- // Storage can be unavailable (private window, blocked site data) — "all" then.
- }
- return "all";
-}
-
-function storeRailFilter(filter: RailFilter): void {
- try {
- window.localStorage.setItem(RAIL_FILTER_KEY, filter);
- } catch {
- // A remembered filter is a convenience, never a requirement.
- }
-}
-
-/** An artifact row is a page or picture (or one being built); the rest are outputs. */
-function isArtifactRow(row: RailRow): boolean {
- return row.kind === "visual" || row.kind === "build";
-}
-
-/** The rows the filter lets through. */
-export function filterRailRows(rows: RailRow[], filter: RailFilter): RailRow[] {
- if (filter === "all") return rows;
- return rows.filter((row) => (filter === "artifacts" ? isArtifactRow(row) : !isArtifactRow(row)));
+ return parseArtifactUtterance(run.utterance)?.title || run.utterance?.trim() || run.slug;
}
/** The rail row's timestamp — what tells two same-named artifacts apart. */
@@ -269,21 +219,7 @@ export function VisualizationView() {
[runs],
);
- const allRows = useMemo(() => buildRailRows(runs, visuals, building), [runs, visuals, building]);
- const [filter, setFilterState] = useState<RailFilter>(readRailFilter);
- const setFilter = useCallback((next: RailFilter) => {
- setFilterState(next);
- storeRailFilter(next);
- }, []);
- const rows = useMemo(() => filterRailRows(allRows, filter), [allRows, filter]);
- const counts = useMemo(
- () => ({
- all: allRows.length,
- artifacts: allRows.filter(isArtifactRow).length,
- outputs: allRows.filter((row) => !isArtifactRow(row)).length,
- }),
- [allRows],
- );
+ const rows = useMemo(() => buildRailRows(runs, visuals, building), [runs, visuals, building]);
/* A `?run=<slug>` in the URL pre-selects that run's newest artifact — what
* makes a detached window or a pasted link open on the page it talks about.
@@ -356,20 +292,6 @@ export function VisualizationView() {
gallery.refetch();
}, [outputs, gallery]);
- /* Narrowing the rail to a group the picked row is not in would leave the
- * stage on something the rail no longer lists; the pick is dropped and the
- * first visible row takes the stage. Nothing happens while the rail is
- * still filling (a pick may simply not have loaded yet). */
- useEffect(() => {
- if (selection === null || filter === "all" || allRows.length === 0) return;
- const visible = rows.some(
- (row) =>
- (row.kind === "visual" && row.visual.slug === selection.slug) ||
- (row.kind !== "visual" && row.run.slug === selection.slug),
- );
- if (!visible) setSelection(null);
- }, [filter, rows, allRows.length, selection]);
-
const loading = outputs.isLoading || gallery.isLoading;
const activeKey =
target.building && target.run
@@ -407,17 +329,14 @@ export function VisualizationView() {
<div className="flex min-h-0 flex-1">
{/* Rail — builds in progress first, then every artifact and run, newest first. */}
<aside className="flex w-72 shrink-0 flex-col border-r border-border">
- <div className="flex flex-col gap-2 border-b border-border px-3 py-2">
- <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
- {t("visualization.rail")}
- {rows.length > 0 && (
- <span className="ml-1.5 normal-case tracking-normal text-muted-foreground/70">
- · {rows.length}
- </span>
- )}
- </p>
- <RailFilterControl filter={filter} counts={counts} onChange={setFilter} />
- </div>
+ <p className="border-b border-border px-3 py-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ {t("visualization.rail")}
+ {rows.length > 0 && (
+ <span className="ml-1.5 normal-case tracking-normal text-muted-foreground/70">
+ · {rows.length}
+ </span>
+ )}
+ </p>
<ScrollArea className="min-h-0 flex-1">
<ul className="space-y-1 p-2" data-testid="visualization-artifacts">
{rows.map((row) => (
@@ -463,55 +382,6 @@ export function VisualizationView() {
/* ------------------------------------------------------------------------- */
-/**
- * All · Artifacts · Outputs — one segmented control, the count beside each
- * word so an empty group reads as "none" rather than "broken".
- */
-function RailFilterControl({
- filter,
- counts,
- onChange,
-}: {
- filter: RailFilter;
- counts: Record<RailFilter, number>;
- onChange: (next: RailFilter) => void;
-}) {
- const t = useT();
- const options: Array<{ id: RailFilter; label: string }> = [
- { id: "all", label: t("visualization.filter_all") },
- { id: "artifacts", label: t("visualization.filter_artifacts") },
- { id: "outputs", label: t("visualization.filter_outputs") },
- ];
- return (
- <div
- role="radiogroup"
- aria-label={t("visualization.rail_filter")}
- className="flex items-center rounded-md border border-border bg-secondary/40 p-0.5"
- data-testid="visualization-filter"
- >
- {options.map(({ id, label }) => (
- <button
- key={id}
- type="button"
- role="radio"
- aria-checked={filter === id}
- onClick={() => onChange(id)}
- data-testid={`visualization-filter-${id}`}
- className={cn(
- "inline-flex flex-1 items-center justify-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium transition-colors",
- filter === id
- ? "bg-background text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- {label}
- <span className="tabular-nums text-muted-foreground/70">{counts[id]}</span>
- </button>
- ))}
- </div>
- );
-}
-
function RailRowButton({
row,
active,
@@ -590,7 +460,7 @@ function RailRowButton({
<span className="block truncate">
{[
formatWhen(visual.mtime),
- parsed?.request || cleanRequest(visual.utterance) || visual.name,
+ parsed?.request || visual.utterance?.trim() || visual.name,
]
.filter(Boolean)
.join(" · ")}
@@ -641,10 +511,9 @@ function RailRowButton({
/* ------------------------------------------------------------------------- */
/**
- * The stage for one run: its artifact under Preview / Code when it drew one,
- * the composed output page under Preview and the primary file's source under
- * Code when it did not; every file under Files, the graph under Run. Keyed
- * by run in the caller, so a new run opens on Preview.
+ * The stage for one run: its artifact (when it has one) under Preview / Code,
+ * every file under Files, the graph under Run. Keyed by run in the caller, so
+ * a new run opens on its own default tab.
*
* A run outside the rail's scan window arrives without artifacts in hand; its
* listing is read here (same cache entry the rail's scan fills) and the newest
@@ -661,7 +530,7 @@ function Stage({
onJumpToRun: (slug: string) => void;
}) {
const slug = run?.slug ?? pickedVisual?.slug ?? null;
- const listing = useArtifactsForOutput(run !== null ? slug : null);
+ const listing = useArtifactsForOutput(run !== null && pickedVisual === null ? slug : null);
const visual: VisualArtifact | null = useMemo(() => {
if (pickedVisual) return pickedVisual;
if (run === null) return null;
@@ -669,78 +538,43 @@ function Stage({
found.sort((a, b) => b.mtime - a.mtime);
return found[0] ?? null;
}, [pickedVisual, run, listing.data]);
- // The output's primary file — what Code shows and the toolbar's file
- // actions act on when the run drew no page: the first text deliverable.
- const primary: ArtifactSummary | null = useMemo(() => {
- if (visual !== null) return null;
- return primaryTextFile(listing.data?.files ?? []);
- }, [visual, listing.data]);
- const [mode, setMode] = useState<StageMode>("preview");
- // "Open in Files" on the output page lands the reader on that file.
- const [filesPath, setFilesPath] = useState<string | null>(null);
+ const [mode, setMode] = useState<StageMode>(visual ? "preview" : "files");
const currentId = visual ? visualId(visual) : null;
// A new artifact opens on its page, whatever tab the previous one was on; a
// run that turns out to have one (its listing just arrived) moves to it too.
useEffect(() => {
- setMode("preview");
+ setMode(currentId ? "preview" : "files");
}, [currentId]);
- const openFile = useCallback((path: string) => {
- setFilesPath(path);
- setMode("files");
- }, []);
return (
<>
<ArtifactToolbar
run={run}
visual={visual}
- primary={primary}
mode={mode}
onMode={setMode}
onJumpToRun={onJumpToRun}
/>
<div className="min-h-0 flex-1" data-testid="visualization-stage">
{mode === "preview" && visual && <ArtifactStage visual={visual} />}
- {mode === "preview" && !visual && run && (
- <OutputPreview key={run.slug} run={run} onOpenFile={openFile} />
- )}
{mode === "code" && visual && <ArtifactSource slug={visual.slug} path={visual.path} />}
- {mode === "code" && !visual && run && primary && (
- <ArtifactSource slug={run.slug} path={primary.path} />
- )}
- {mode === "files" && run && <RunFiles run={run} initialPath={filesPath} />}
+ {mode === "files" && run && <RunFiles run={run} />}
{mode === "run" && run && <RunGraphPanel key={run.slug} run={run} />}
</div>
</>
);
}
-/** The `/view` page follows the app's theme like an artifact page does. */
-function withTheme(url: string | null, theme: string): string | null {
- if (url === null) return null;
- return url.includes("?") ? url : `${url}?theme=${theme}`;
-}
-
-/** The first deliverable whose bytes are text — the output's "source". */
-function primaryTextFile(files: ArtifactSummary[]): ArtifactSummary | null {
- return (
- deliverableFiles(files).find((f) => isTextKind(artifactKind(f.path, f.is_text))) ?? null
- );
-}
-
function ArtifactToolbar({
run,
visual,
- primary,
mode,
onMode,
onJumpToRun,
}: {
run: OutputSummary | null;
visual: VisualArtifact | null;
- /** The output's primary text file when the run drew no page. */
- primary: ArtifactSummary | null;
mode: StageMode;
onMode: (mode: StageMode) => void;
onJumpToRun: (slug: string) => void;
@@ -750,57 +584,40 @@ function ArtifactToolbar({
const capabilities = useOutputsCapabilities();
const parsed = parseArtifactUtterance(visual?.utterance ?? run?.utterance);
const slug = visual?.slug ?? run?.slug ?? "";
- // The file the toolbar's Download / Reveal / Open act on: the artifact, or
- // the output's primary file.
- const file: { slug: string; path: string } | null = visual
- ? { slug: visual.slug, path: visual.path }
- : run && primary
- ? { slug: run.slug, path: primary.path }
- : null;
const onReveal = useCallback(async () => {
- if (!file) return;
+ if (!visual) return;
try {
- await revealArtifact(file.slug, file.path);
+ await revealArtifact(visual.slug, visual.path);
} catch {
pushToast("error", t("visualization.reveal_failed"));
}
- }, [file, pushToast, t]);
+ }, [visual, pushToast, t]);
const theme = useThemeValue();
const externalUrl = visual
? visual.kind === "page"
? `${artifactPageUrl(visual.slug, visual.path)}?theme=${theme}`
: visual.url
- : file
- ? withTheme(artifactOpenUrl(file.slug, file.path), theme)
- : null;
+ : null;
const title = visual?.title ?? (run ? runTitle(run) : "");
const caption = [
visual ? formatWhen(visual.mtime) : run ? formatWhen(runWhen(run)) : "",
visual ? formatSize(visual.size) : "",
run && typeof run.duration_s === "number" ? `${run.duration_s.toFixed(1)} s` : "",
- parsed?.request ||
- (visual ? cleanRequest(visual.utterance) || visual.name : run ? cleanRequest(run.utterance) : ""),
+ parsed?.request || (visual ? visual.utterance?.trim() || visual.name : ""),
]
.filter(Boolean)
.join(" · ");
- // Every run gets the same four tabs; Code is absent only when there is no
- // source to show (a picture, a run that left no text file).
const tabs: Array<{ id: StageMode; label: string; Icon: typeof Eye; show: boolean }> = [
- {
- id: "preview",
- label: t("visualization.tab_preview"),
- Icon: Eye,
- show: visual !== null || run !== null,
- },
+ { id: "preview", label: t("visualization.tab_preview"), Icon: Eye, show: visual !== null },
{
id: "code",
label: t("visualization.tab_code"),
Icon: Code2,
- show: visual !== null ? visual.kind === "page" || visual.kind === "vector" : primary !== null,
+ show: visual !== null && (visual.kind === "page" || visual.kind === "vector"),
},
{ id: "files", label: t("visualization.tab_files"), Icon: Files, show: run !== null },
{ id: "run", label: t("visualization.tab_run"), Icon: Workflow, show: run !== null },
@@ -860,7 +677,7 @@ function ArtifactToolbar({
{t("visualization.open_map_page")}
</Button>
)}
- {externalUrl && (
+ {visual && externalUrl && (
<Button
variant="ghost"
size="sm"
@@ -872,10 +689,10 @@ function ArtifactToolbar({
{t("visualization.open_external")}
</Button>
)}
- {file && (
+ {visual && (
<Button variant="ghost" size="sm" asChild>
<a
- href={artifactDownloadUrl(file.slug, file.path)}
+ href={artifactDownloadUrl(visual.slug, visual.path)}
download
title={t("visualization.download")}
aria-label={t("visualization.download")}
@@ -886,7 +703,7 @@ function ArtifactToolbar({
)}
{/* Desktop only: a headless host has no file manager to open, so the
button is absent rather than dead. */}
- {file && capabilities.data?.native_file_actions && (
+ {visual && capabilities.data?.native_file_actions && (
<Button
variant="ghost"
size="sm"
diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.py
index 92db9c3dc9..743e11243b 100644
--- a/jarvis/ui/web/outputs_routes.py
+++ b/jarvis/ui/web/outputs_routes.py
@@ -366,7 +366,9 @@ async def _terminal_outcome_details(
"terminal_event": event_type,
"terminal_reason": None,
"terminal_summary": (
- preferred_summary or payload.get("summary_en") or payload.get("summary_de")
+ preferred_summary
+ or payload.get("summary_en")
+ or payload.get("summary_de")
),
}
if event_type in ("MissionFailed", "MissionCancelled"):
@@ -616,11 +618,9 @@ async def list_outputs(request: Request) -> OutputsResponse:
# card and graph node would show that boilerplate instead of the
# user's actual ask. `clean_request_body` exists precisely for
# UI previews — see its docstring in stream_evidence.py.
- summary["utterance"] = (
- summary["utterance"]
- or clean_request_body(str(mission_row.get("prompt") or ""))
- or None
- )
+ summary["utterance"] = summary["utterance"] or clean_request_body(
+ str(mission_row.get("prompt") or "")
+ ) or None
summary["summary"] = mission_row.get("terminal_summary")
summary["terminal_reason"] = mission_row.get("terminal_reason")
summary["terminal_event"] = mission_row.get("terminal_event")
@@ -645,9 +645,8 @@ async def list_outputs(request: Request) -> OutputsResponse:
)
artifact_count = artifact_counts.get(entry, 0)
summary["artifact_count"] = artifact_count
- summary["has_partial_output"] = artifact_count > 0 and summary["status"] in (
- "error",
- "cancelled",
+ summary["has_partial_output"] = (
+ artifact_count > 0 and summary["status"] in ("error", "cancelled")
)
terminal_reason = str(summary.get("terminal_reason") or "")
reason_key = terminal_reason.split(":", 1)[0]
@@ -1129,9 +1128,7 @@ async def view_output_artifact(slug: str, path: str, request: Request) -> HTMLRe
except OSError as exc:
raise HTTPException(status_code=500, detail=f"read failed: {exc}") from exc
return HTMLResponse(
- # `?theme=` is what the Artifacts stage appends so the page follows
- # the app's theme rather than the OS's; absent = OS preference.
- render_artifact_html(target.name, text, theme=request.query_params.get("theme")),
+ render_artifact_html(target.name, text),
headers={
"Content-Security-Policy": VIEW_CSP,
"X-Content-Type-Options": "nosniff",
diff --git a/packaging/README.md b/packaging/README.md
new file mode 100644
index 0000000000..b54fdd3136
--- /dev/null
+++ b/packaging/README.md
@@ -0,0 +1,33 @@
+# packaging/
+
+Everything that turns the Python application into something a visitor can
+download and double-click. One directory per operating system, each with a
+single build script that produces exactly one release asset.
+
+| OS | Script | Produces |
+| ------- | ----------------------------------------------------- | --------------------------------------- |
+| Windows | [`windows/build.ps1`](windows/build.ps1) | `PersonalJarvis-Setup-x64.exe` |
+| macOS | [`macos/build.sh`](macos/build.sh) | `PersonalJarvis-macOS-<arm64\|x64>.dmg` |
+| Linux | [`linux/build.sh`](linux/build.sh) | `PersonalJarvis-Linux-x86_64.AppImage` |
+
+Each script writes into `dist/installers/`, prints the artifact path, and exits
+non-zero on any failure. `.github/workflows/desktop-installers.yml` runs these
+same three scripts, then publishes them plus `installers-SHA256SUMS.txt` to the
+GitHub Release for the tag.
+
+Shared pieces that are not per-OS:
+
+- **`../jarvis.spec`** - the PyInstaller build every script starts from. One
+ `onedir` bundle with two executables: the windowed launcher
+ (`PersonalJarvis`) and the console CLI (`jarvis`).
+- **`pyinstaller_rthook_frozen.py`** - runtime hook that points a frozen
+ install's `jarvis.toml` and data directory at the per-user application
+ directory, so an upgrade cannot overwrite settings and an uninstall cannot
+ delete the user's memory.
+- **`pyinstaller_hooks/`** - overrides for third-party PyInstaller hooks that
+ are wrong for this project's dependency set.
+
+Per-OS notes live next to each script: [`windows/`](windows),
+[`macos/`](macos), [`linux/`](linux). The full maintainer walkthrough -
+building, signing, releasing, and how the in-app updater consumes the result -
+is [`docs/desktop-installers.md`](../docs/desktop-installers.md).
diff --git a/tests/unit/costs/test_usage_ledger.py b/tests/unit/costs/test_usage_ledger.py
deleted file mode 100644
index 9b2f0d5f2c..0000000000
--- a/tests/unit/costs/test_usage_ledger.py
+++ /dev/null
@@ -1,140 +0,0 @@
-"""The usage ledger and the metered brain: every model call is written down,
-tagged with who asked, and the report reads it back without double counting."""
-
-from __future__ import annotations
-
-import asyncio
-from collections.abc import AsyncIterator
-from pathlib import Path
-
-import pytest
-
-from jarvis.brain.usage_meter import MeteredBrain, meter_brain
-from jarvis.core.protocols import BrainDelta, BrainRequest
-from jarvis.costs import CostSources, collect_entries, ledger
-from jarvis.costs.aggregate import filter_entries
-from jarvis.costs.model import CostEntry
-
-
-class FakeBrain:
- name = "fake"
- model = "gpt-5.5"
-
- def __init__(self) -> None:
- self.calls = 0
-
- async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- self.calls += 1
- yield BrainDelta(content="hel")
- yield BrainDelta(content="lo")
- yield BrainDelta(
- finish_reason="stop",
- usage={"input_tokens": 120, "output_tokens": 7, "cache_hit_tokens": 900},
- )
-
- def estimate_cost(self, req: BrainRequest) -> float:
- return 0.5
-
-
-def ledger_path(tmp_path: Path):
- path = tmp_path / "llm_usage.db"
- ledger.set_ledger_path(path)
- try:
- yield path
- finally:
- ledger.flush()
- ledger.set_ledger_path(None)
-
-
-def _request() -> BrainRequest:
- return BrainRequest(messages=[])
-
-
-async def _drain(stream: AsyncIterator[BrainDelta]) -> str:
- parts = [d.content or "" async for d in stream]
- return "".join(parts)
-
-
-def test_a_metered_brain_writes_the_call_with_its_caller(ledger_path: Path) -> None:
- brain = meter_brain(FakeBrain(), "openrouter")
- assert isinstance(brain, MeteredBrain)
-
- async def run() -> str:
- with ledger.usage_context("wiki"):
- stream = brain.complete(_request())
- return await _drain(stream)
-
- assert asyncio.run(run()) == "hello"
- ledger.flush()
- rows = list(ledger.read_usage(ledger_path, 0, 2**62))
- assert len(rows) == 1
- row = rows[0]
- assert (row.provider, row.model, row.caller) == ("openrouter", "gpt-5.5", "wiki")
- assert (row.tokens_in, row.tokens_out, row.tokens_cached) == (120, 7, 900)
-
-
-def test_the_caller_is_read_when_complete_is_called_not_when_consumed(
- ledger_path: Path,
-) -> None:
- brain = meter_brain(FakeBrain(), "gemini")
-
- async def run() -> None:
- with ledger.usage_context("dictation"):
- stream = brain.complete(_request())
- await _drain(stream)
-
- asyncio.run(run())
- ledger.flush()
- assert [r.caller for r in ledger.read_usage(ledger_path, 0, 2**62)] == ["dictation"]
-
-
-def test_wrapping_twice_is_wrapping_once() -> None:
- inner = FakeBrain()
- once = meter_brain(inner, "x")
- assert meter_brain(once, "x") is once
- assert once.unwrapped is inner
- assert once.name == "fake" and once.estimate_cost(_request()) == 0.5
-
-
-def test_the_report_counts_background_calls_and_skips_covered_ones(ledger_path: Path) -> None:
- for caller in ("wiki", "voice-turn", "agent-chat", "mission-worker", ""):
- ledger.record_usage(
- provider="openrouter",
- model="google/gemini-3.5-flash",
- tokens_in=1_000,
- tokens_out=100,
- caller=caller,
- ts_ms=1_700_000_000_000,
- )
- ledger.flush()
-
- rows = collect_entries(CostSources(ledger_db=ledger_path))
- assert len(rows) == 2
- assert {e.surface for e in rows} == {"background"}
- assert {e.role for e in rows} == {"background"}
- assert {e.label for e in rows} == {"wiki", "background"}
- assert all(e.cost_usd > 0 for e in rows)
-
-
-def test_a_zero_usage_call_is_not_written(ledger_path: Path) -> None:
- ledger.record_usage(provider="x", model="y", tokens_in=0, tokens_out=0)
- ledger.flush()
- assert list(ledger.read_usage(ledger_path, 0, 2**62)) == []
-
-
-def _entry(source: str) -> CostEntry:
- return CostEntry(
- ts_ms=1, surface="voice", role="tool", provider="p", model="m",
- tokens_in=1, tokens_out=1, tokens_cached=0, cost_usd=1.0,
- price_source=source, ref_id="", label="", # type: ignore[arg-type]
- )
-
-
-def test_billing_filter_splits_seat_quotes_from_key_spend() -> None:
- rows = [_entry("recorded"), _entry("subscription"), _entry("derived")]
- assert len(filter_entries(rows, billing="all")) == 3
- billed = [e.price_source for e in filter_entries(rows, billing="billed")]
- assert billed == ["recorded", "derived"]
- seats = [e.price_source for e in filter_entries(rows, billing="subscription")]
- assert seats == ["subscription"]
diff --git a/tests/unit/ui/web/test_artifact_view.py b/tests/unit/ui/web/test_artifact_view.py
index 01c44103c1..133844cfbe 100644
--- a/tests/unit/ui/web/test_artifact_view.py
+++ b/tests/unit/ui/web/test_artifact_view.py
@@ -1,5 +1,4 @@
"""Unit tests for server-side artifact HTML rendering (markdown + escape + CSP)."""
-
from __future__ import annotations
import builtins
@@ -44,19 +43,3 @@ def test_markdown_missing_lib_falls_back_to_pre(monkeypatch):
def test_csp_blocks_scripts():
assert "default-src 'none'" in VIEW_CSP
assert "script-src" not in VIEW_CSP
-
-
-def test_page_wears_the_artifact_tokens_and_no_script():
- out = render_artifact_html("report.md", "# Title")
- # The design guide's token block, both palettes, is the page's stylesheet.
- assert "--accent:#FFD60A" in out
- assert ':root[data-theme="light"]' in out
- assert "<script" not in out
-
-
-def test_theme_query_is_stamped_on_html_and_junk_is_ignored():
- assert "<html lang='en' data-theme='light'>" in render_artifact_html("r.md", "x", theme="light")
- assert "<html lang='en' data-theme='dark'>" in render_artifact_html("r.txt", "x", theme="dark")
- # (the stylesheet mentions data-theme selectors; the attribute is what matters)
- assert "data-theme='" not in render_artifact_html("r.md", "x", theme="<b>x</b>")
- assert "data-theme='" not in render_artifact_html("r.md", "x")