Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(lenses): build lens data and serve it at /api/lens-data

Claude587c56d37d24
diff --git a/CLAUDE.md b/CLAUDE.md
index 5537bd94..25f52cf6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -15,7 +15,7 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.
- `plugins`: TypeScript sources for the managed runtime plugins/extensions (`opencode-beacon`, `cline-beacon`, `pi-beacon`, `omp-beacon`, `openclaw-beacon`, `prime-beacon`, `omo-beacon`), each mirrored into an embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`.
- `agent-skills`: publishable Agent Skills plugin for the traces-to-memory workflow (`beacon-memory-recall`, `beacon-memory-distill`, `beacon-memory-promote`) with manifests for Claude Code, Agent Plugins (Codex, Copilot, VS Code, Kiro, Devin), Cursor, Kimi Code, and Gemini CLI. At the repo root, `.claude-plugin/marketplace.json` is read by most harnesses, `.cursor-plugin/marketplace.json` by Cursor, and `package.json` (`pi.skills` only) makes the repo a Pi/Prime Agent package; keep that root `package.json` free of dependencies and scripts. `cli/beacon/cmd/agent_skills_test.go` checks every `beacon` command and flag the skills name against the real command tree, so rename a command and update the skills together.
- `rules` and `spec/threat-rules`: the open rule corpus and the Threat Rules format it conforms to.
-- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard host, built-in lenses and `beacon lenses` CLI are not built yet.
+- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`); the lens frame host, built-in lenses and `beacon lenses` CLI are not built yet.
- `beacon-sandbox`: harness that runs a real Claude Code session in a disposable sandbox and checks what Beacon captured. See `beacon-sandbox/AGENTS.md`.
- `packaging`: macOS, Linux, and Windows packaging and deployment assets.
- `docs`: the published documentation site (docs.asymptotelabs.ai).
diff --git a/cli/beacon/internal/endpoint/dashboard/detections.go b/cli/beacon/internal/endpoint/dashboard/detections.go
index 668aedff..70528324 100644
--- a/cli/beacon/internal/endpoint/dashboard/detections.go
+++ b/cli/beacon/internal/endpoint/dashboard/detections.go
@@ -93,20 +93,9 @@ func RunScan(userMode bool, logPath, rulesDir, session, minSeverity string) (Fin
}
}
- loaded, skipped, err := detect.LoadActiveSkipping(userMode, strings.TrimSpace(rulesDir))
+ compiled, skipped, err := compileActiveRules(userMode, rulesDir)
if err != nil {
- return FindingsResponse{}, fmt.Errorf("load rules: %w", err)
- }
- if len(loaded) == 0 {
- return FindingsResponse{}, &detect.NoRulesError{Skipped: skipped}
- }
- compiled := make([]*threatrules.CompiledRule, 0, len(loaded))
- for _, lr := range loaded {
- c, err := threatrules.Compile(lr.Rule)
- if err != nil {
- return FindingsResponse{}, fmt.Errorf("compile rule %q: %w", lr.Rule.ID, err)
- }
- compiled = append(compiled, c)
+ return FindingsResponse{}, err
}
sessionFilter := strings.TrimSpace(session)
@@ -139,5 +128,26 @@ func RunScan(userMode bool, logPath, rulesDir, session, minSeverity string) (Fin
if findings == nil {
findings = []threatrules.Finding{}
}
- return FindingsResponse{Findings: findings, Scanned: len(events), Count: len(findings), Skipped: detect.SkippedStrings(skipped)}, nil
+ return FindingsResponse{Findings: findings, Scanned: len(events), Count: len(findings), Skipped: skipped}, nil
+}
+
+// compileActiveRules loads and compiles the rules `beacon scan` would run. It returns a
+// *detect.NoRulesError when none are active, so callers can tell "no rules" from a broken rule.
+func compileActiveRules(userMode bool, rulesDir string) ([]*threatrules.CompiledRule, []string, error) {
+ loaded, skipped, err := detect.LoadActiveSkipping(userMode, strings.TrimSpace(rulesDir))
+ if err != nil {
+ return nil, nil, fmt.Errorf("load rules: %w", err)
+ }
+ if len(loaded) == 0 {
+ return nil, nil, &detect.NoRulesError{Skipped: skipped}
+ }
+ compiled := make([]*threatrules.CompiledRule, 0, len(loaded))
+ for _, lr := range loaded {
+ c, err := threatrules.Compile(lr.Rule)
+ if err != nil {
+ return nil, nil, fmt.Errorf("compile rule %q: %w", lr.Rule.ID, err)
+ }
+ compiled = append(compiled, c)
+ }
+ return compiled, detect.SkippedStrings(skipped), nil
}
diff --git a/cli/beacon/internal/endpoint/dashboard/history_test.go b/cli/beacon/internal/endpoint/dashboard/history_test.go
index 164017ed..6de3adbf 100644
--- a/cli/beacon/internal/endpoint/dashboard/history_test.go
+++ b/cli/beacon/internal/endpoint/dashboard/history_test.go
@@ -140,6 +140,9 @@ func traceAnswers(t *testing.T, path string, showIDs []string) map[string]string
"typed": {Limit: 100, EventTypes: []string{"user_message", "command"}},
"around": {AroundEvent: 3, Before: 1, After: 1},
"agent": {Limit: 100, EventTypes: []string{"agent_text"}},
+ // Lens data reads a whole trace in one call.
+ "no-limit": {EventQuery: EventQuery{NoLimit: true}},
+ "no-limit-offset": {EventQuery: EventQuery{NoLimit: true}, Offset: 2},
} {
show, ok, err := ShowTrace(path, id, query)
if err != nil {
diff --git a/cli/beacon/internal/endpoint/dashboard/lens_data.go b/cli/beacon/internal/endpoint/dashboard/lens_data.go
new file mode 100644
index 00000000..2096550e
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/lens_data.go
@@ -0,0 +1,153 @@
+package dashboard
+
+import (
+ "encoding/json"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/threatrules"
+)
+
+type LensDataV1 = asymptoteobserve.LensDataV1
+
+// lensDataEventBudget bounds the encoded size of the events a lens receives. The data crosses into
+// the frame in one structured-clone message and a lens builds its view from all of it at once, so
+// a trace past this size is cut to a prefix and marked truncated rather than handed over whole.
+const lensDataEventBudget = 12 << 20
+
+// LensDataOptions selects the rules the findings are computed with, the same way `beacon scan`
+// does. The zero value scans with the user's active rules.
+type LensDataOptions struct {
+ UserMode bool
+ RulesDir string
+}
+
+// BuildLensData assembles what window.beacon.getTrace() resolves with for one trace: the trace
+// bundle the trace view reads, the threat-rule findings over the trace's own events, and whether
+// its runtime reports token usage at all. ok is false when no trace has that ID.
+//
+// The bundle comes from ShowTrace, so it answers from the opted-in history exactly when the trace
+// view does. Findings and token coverage are computed from the trace's events in the live JSONL,
+// because the rules engine evaluates whole endpoint events and the history keeps only projected
+// ones; a trace whose lines were rotated away keeps its bundle and loses only those two.
+func BuildLensData(logPath, traceID string, opts LensDataOptions) (LensDataV1, bool, error) {
+ show, ok, err := ShowTrace(logPath, traceID, TraceQuery{EventQuery: EventQuery{NoLimit: true}})
+ if err != nil || !ok {
+ return LensDataV1{}, ok, err
+ }
+ data := LensDataV1{
+ APIVersion: asymptoteobserve.LensAPIVersion,
+ Trace: TraceBundleFromShow(show, version.Version),
+ }
+ data.Truncated = fitLensEvents(&data.Trace, lensDataEventBudget)
+
+ var raw []schema.Event
+ err = StreamEvents(logPath, func(event schema.Event) error {
+ if traceProjectionID(event) == traceID {
+ raw = append(raw, event)
+ }
+ return nil
+ })
+ if err != nil {
+ return LensDataV1{}, false, err
+ }
+ // Findings and coverage are each optional in the contract. A rule pack that fails to load
+ // leaves Findings nil -- "not scanned" -- instead of failing the whole lens, since every other
+ // part of the data is still right.
+ if findings, err := lensFindings(raw, opts); err == nil {
+ data.Findings = findings
+ }
+ data.TokenCoverage = lensTokenCoverage(raw, show.Trace.Harness.Name)
+ return data, true, nil
+}
+
+// fitLensEvents keeps the longest prefix of the bundle's events that encodes within budget, and
+// reports whether it dropped any. Spans that only cover dropped events are kept: they are small,
+// and a lens resolves span event IDs leniently because truncation already allows a miss.
+func fitLensEvents(bundle *asymptoteobserve.TraceBundleV1, budget int) bool {
+ used := 0
+ for i, event := range bundle.Events {
+ encoded, err := json.Marshal(event)
+ if err != nil {
+ continue
+ }
+ used += len(encoded) + 1
+ if used > budget {
+ bundle.Events = bundle.Events[:i]
+ if bundle.Range != nil {
+ bundle.Range.ReturnedEvents = i
+ bundle.Range.Limit = i
+ }
+ return true
+ }
+ }
+ return false
+}
+
+// lensFindings runs the active rules over the trace's events. Any error, including no active rules
+// (*detect.NoRulesError), leaves the caller's Findings nil: "not scanned".
+func lensFindings(raw []schema.Event, opts LensDataOptions) (*asymptoteobserve.LensFindingsV1, error) {
+ compiled, skipped, err := compileActiveRules(opts.UserMode, opts.RulesDir)
+ if err != nil {
+ return nil, err
+ }
+ events := append([]asymptoteobserve.Event(nil), raw...)
+ // Same reason as RunScan: the log is in append order, not the order things happened, and
+ // ordered correlation rules miss without this.
+ threatrules.SortEvents(events)
+ found, err := threatrules.ScanEvents(compiled, events)
+ if err != nil {
+ return nil, err
+ }
+ threatrules.SortFindings(found)
+
+ taxonomy := make(map[string]map[string]string, len(compiled))
+ for _, rule := range compiled {
+ taxonomy[rule.Rule().ID] = rule.Rule().Taxonomy
+ }
+ items := make([]asymptoteobserve.LensFindingV1, 0, len(found))
+ for _, f := range found {
+ ids := make([]string, 0, len(f.Events))
+ for _, event := range f.Events {
+ // Trace events take their ID from the endpoint event ID, so evidence resolves against
+ // trace.events[].id without copying the event.
+ if id := strings.TrimSpace(event.Event.ID); id != "" {
+ ids = append(ids, id)
+ }
+ }
+ items = append(items, asymptoteobserve.LensFindingV1{
+ RuleID: f.RuleID,
+ Title: f.Title,
+ Severity: f.Severity,
+ Posture: string(f.Posture),
+ Reason: f.Reason,
+ Taxonomy: taxonomy[f.RuleID],
+ EventIDs: ids,
+ })
+ }
+ return &asymptoteobserve.LensFindingsV1{RulesEvaluated: len(compiled), Items: items, Skipped: skipped}, nil
+}
+
+// lensTokenCoverage is the trace's own line from the token coverage join, computed over just its
+// events. The question a lens asks is about this run -- did it report usage, and should it have --
+// so the installed-runtime half of the join, which answers "was the runtime used", is left out.
+func lensTokenCoverage(raw []schema.Event, harness string) *asymptoteobserve.LensTokenCoverageV1 {
+ want := asymptoteobserve.NormalizeHarnessName(strings.TrimSpace(harness))
+ if want == "" || len(raw) == 0 {
+ return nil
+ }
+ for _, line := range tokens.Coverage(raw, nil).Runtimes {
+ if line.Harness == want {
+ return &asymptoteobserve.LensTokenCoverageV1{
+ Harness: line.Harness,
+ Status: line.Status,
+ Expectation: line.Expectation,
+ Reason: line.Reason,
+ }
+ }
+ }
+ return nil
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/lens_data_test.go b/cli/beacon/internal/endpoint/dashboard/lens_data_test.go
new file mode 100644
index 00000000..83fcf70e
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/lens_data_test.go
@@ -0,0 +1,223 @@
+package dashboard
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// lensFixture writes a log holding two Claude Code sessions that each run a command the baseline
+// recursive-root-delete rule matches, so a test can check that one trace's lens data carries only
+// its own finding.
+func lensFixture(t *testing.T) string {
+ t.Helper()
+ testenv.SetHome(t, t.TempDir()) // empty rule store -> embedded baseline
+ withoutHistory(t)
+ var events []schema.Event
+ for _, session := range []string{"s1", "s2"} {
+ prompt := testSchemaEvent("2026-06-11T10:00:00Z", "claude_code", "prompt.submitted", "prompt", "repo-a")
+ prompt.Event.ID = "evt-prompt-" + session
+ prompt.Session = &schema.SessionInfo{ID: session}
+ prompt.Prompt = &schema.PromptInfo{Text: "clean up " + session}
+ command := testSchemaEvent("2026-06-11T10:01:00Z", "claude_code", "command.executed", "command", "repo-a")
+ command.Event.ID = "evt-rm-" + session
+ command.Session = prompt.Session
+ command.Command = &schema.CommandInfo{Command: "rm -rf /"}
+ events = append(events, prompt, command)
+ }
+ return newTestLog(t, marshalEvents(t, events...))
+}
+
+func TestBuildLensDataBundlesTheTraceItsFindingsAndCoverage(t *testing.T) {
+ path := lensFixture(t)
+
+ data, ok, err := BuildLensData(path, "session:claude_code:s1", LensDataOptions{UserMode: true})
+ if err != nil || !ok {
+ t.Fatalf("BuildLensData = ok %v, err %v", ok, err)
+ }
+ if data.APIVersion != asymptoteobserve.LensAPIVersion || data.Trace.SchemaVersion != asymptoteobserve.TraceSchemaVersion {
+ t.Fatalf("versions = %q / %q", data.APIVersion, data.Trace.SchemaVersion)
+ }
+ if data.Trace.ID != "session:claude_code:s1" || len(data.Trace.Events) != 2 || data.Truncated {
+ t.Fatalf("trace = %s with %d events, truncated %v", data.Trace.ID, len(data.Trace.Events), data.Truncated)
+ }
+
+ if data.Findings == nil || data.Findings.RulesEvaluated == 0 {
+ t.Fatalf("findings = %#v, want a scan over the baseline rules", data.Findings)
+ }
+ var rmFindings []asymptoteobserve.LensFindingV1
+ for _, f := range data.Findings.Items {
+ if f.RuleID == "recursive-root-delete" {
+ rmFindings = append(rmFindings, f)
+ }
+ }
+ if len(rmFindings) != 1 {
+ t.Fatalf("recursive-root-delete findings = %#v, want exactly s1's", rmFindings)
+ }
+ if got := rmFindings[0].EventIDs; len(got) != 1 || got[0] != "evt-rm-s1" {
+ t.Fatalf("evidence = %v, want [evt-rm-s1]", got)
+ }
+ resolved := false
+ for _, event := range data.Trace.Events {
+ if event.ID == rmFindings[0].EventIDs[0] {
+ resolved = true
+ }
+ }
+ if !resolved {
+ t.Fatal("finding evidence does not resolve against trace.events[].id")
+ }
+
+ // Claude Code is a runtime Beacon reads usage from, and this trace reported none.
+ want := asymptoteobserve.LensTokenCoverageV1{Harness: "claude_code", Status: "silent", Expectation: "reported", Reason: "OTLP token and cost telemetry"}
+ if data.TokenCoverage == nil || *data.TokenCoverage != want {
+ t.Fatalf("token coverage = %#v, want %#v", data.TokenCoverage, want)
+ }
+}
+
+func TestBuildLensDataWithoutRulesLeavesFindingsUnscanned(t *testing.T) {
+ path := lensFixture(t)
+ // An empty rules directory is the "no rules to run" case.
+ data, ok, err := BuildLensData(path, "session:claude_code:s1", LensDataOptions{UserMode: true, RulesDir: t.TempDir()})
+ if err != nil || !ok {
+ t.Fatalf("BuildLensData = ok %v, err %v", ok, err)
+ }
+ if data.Findings != nil {
+ t.Fatalf("findings = %#v, want nil (not scanned)", data.Findings)
+ }
+ if len(data.Trace.Events) != 2 || data.TokenCoverage == nil {
+ t.Fatal("the rest of the lens data should survive a rule-load failure")
+ }
+}
+
+func TestBuildLensDataUnknownTrace(t *testing.T) {
+ path := lensFixture(t)
+ if _, ok, err := BuildLensData(path, "session:claude_code:nope", LensDataOptions{UserMode: true}); ok || err != nil {
+ t.Fatalf("BuildLensData = ok %v, err %v, want not found", ok, err)
+ }
+}
+
+// TestBuildLensDataReadsPastTheTraceViewPageLimit checks that a lens gets the whole trace, not the
+// first page the trace view would show.
+func TestBuildLensDataReadsPastTheTraceViewPageLimit(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ withoutHistory(t)
+ total := maxEventLimit + 25
+ events := make([]schema.Event, 0, total)
+ for i := 0; i < total; i++ {
+ event := testSchemaEvent("2026-06-11T10:00:00Z", "cursor", "command.executed", "command", "repo-a")
+ event.Event.ID = fmt.Sprintf("evt-%05d", i)
+ event.Session = &schema.SessionInfo{ID: "long"}
+ event.Command = &schema.CommandInfo{Command: "true"}
+ events = append(events, event)
+ }
+ path := newTestLog(t, marshalEvents(t, events...))
+
+ data, ok, err := BuildLensData(path, "session:cursor:long", LensDataOptions{UserMode: true})
+ if err != nil || !ok {
+ t.Fatalf("BuildLensData = ok %v, err %v", ok, err)
+ }
+ if len(data.Trace.Events) != total || data.Truncated {
+ t.Fatalf("events = %d (truncated %v), want all %d", len(data.Trace.Events), data.Truncated, total)
+ }
+ if data.Trace.Range == nil || data.Trace.Range.TotalEvents != total || data.Trace.Range.ReturnedEvents != total {
+ t.Fatalf("range = %#v", data.Trace.Range)
+ }
+}
+
+func TestFitLensEventsKeepsTheLongestPrefixWithinBudget(t *testing.T) {
+ bundle := asymptoteobserve.TraceBundleV1{Range: &asymptoteobserve.TraceRangeV1{TotalEvents: 4, ReturnedEvents: 4, Offset: 1, Limit: 4}}
+ for i := 1; i <= 4; i++ {
+ bundle.Events = append(bundle.Events, asymptoteobserve.TraceEventV1{ID: fmt.Sprintf("e%d", i), Number: i, Summary: strings.Repeat("x", 100)})
+ }
+ one, _ := json.Marshal(bundle.Events[0])
+ perEvent := len(one) + 1
+
+ whole := bundle
+ whole.Events = append([]asymptoteobserve.TraceEventV1(nil), bundle.Events...)
+ if fitLensEvents(&whole, perEvent*4) || len(whole.Events) != 4 {
+ t.Fatalf("a bundle that fits was cut to %d events", len(whole.Events))
+ }
+
+ cut := bundle
+ cut.Range = &asymptoteobserve.TraceRangeV1{TotalEvents: 4, ReturnedEvents: 4, Offset: 1, Limit: 4}
+ if !fitLensEvents(&cut, perEvent*2+perEvent/2) {
+ t.Fatal("fitLensEvents did not report truncation")
+ }
+ if len(cut.Events) != 2 || cut.Events[1].ID != "e2" {
+ t.Fatalf("kept %d events, want the first 2", len(cut.Events))
+ }
+ if cut.Range.TotalEvents != 4 || cut.Range.ReturnedEvents != 2 {
+ t.Fatalf("range = %#v, want total 4, returned 2", cut.Range)
+ }
+}
+
+func TestLensDataEndpoint(t *testing.T) {
+ path := lensFixture(t)
+ handler, err := Handler(Options{UserMode: true, LogPath: path})
+ if err != nil {
+ t.Fatal(err)
+ }
+ get := func(url string) *httptest.ResponseRecorder {
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, url, nil))
+ return rec
+ }
+
+ rec := get("/api/lens-data?trace=" + "session:claude_code:s1")
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
+ }
+ // The served JSON is the contract: it must decode strictly into LensDataV1.
+ decoder := json.NewDecoder(bytes.NewReader(rec.Body.Bytes()))
+ decoder.DisallowUnknownFields()
+ var data asymptoteobserve.LensDataV1
+ if err := decoder.Decode(&data); err != nil {
+ t.Fatalf("response is not LensDataV1: %v", err)
+ }
+ if data.Trace.ID != "session:claude_code:s1" {
+ t.Fatalf("trace = %q", data.Trace.ID)
+ }
+
+ if rec := get("/api/lens-data"); rec.Code != http.StatusBadRequest {
+ t.Fatalf("missing trace status = %d, want 400", rec.Code)
+ }
+ if rec := get("/api/lens-data?trace=session:claude_code:nope"); rec.Code != http.StatusNotFound {
+ t.Fatalf("unknown trace status = %d, want 404", rec.Code)
+ }
+ rec = httptest.NewRecorder()
+ handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/lens-data?trace=session:claude_code:s1", nil))
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Fatalf("POST status = %d, want 405", rec.Code)
+ }
+}
+
+func TestLensDataEvidenceResolvesAgainstTheHistoryBundle(t *testing.T) {
+ // With the history opted in, the bundle comes from the store; findings still come from the
+ // live log. Both must agree on event IDs so evidence resolves.
+ path := lensFixture(t)
+ withHistory(t)
+ optIn(t, path)
+ data, ok, err := BuildLensData(path, "session:claude_code:s1", LensDataOptions{UserMode: true})
+ if err != nil || !ok {
+ t.Fatalf("BuildLensData = ok %v, err %v", ok, err)
+ }
+ ids := map[string]bool{}
+ for _, event := range data.Trace.Events {
+ ids[event.ID] = true
+ }
+ for _, f := range data.Findings.Items {
+ for _, id := range f.EventIDs {
+ if !ids[id] {
+ t.Fatalf("finding %s cites %s, missing from the history-served bundle %v", f.RuleID, id, ids)
+ }
+ }
+ }
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.go
index a2e8711a..7642b091 100644
--- a/cli/beacon/internal/endpoint/dashboard/server.go
+++ b/cli/beacon/internal/endpoint/dashboard/server.go
@@ -232,6 +232,30 @@ func Handler(opts Options) (http.Handler, error) {
}
writeJSON(w, trace)
})
+ // Lens data is what one lens frame receives from window.beacon.getTrace(). The session page
+ // fetches it and hands it to the frame over a MessageChannel; the frame itself never calls
+ // this route, because its sandbox and CSP give it no network.
+ mux.HandleFunc("/api/lens-data", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ methodNotAllowed(w)
+ return
+ }
+ id := r.URL.Query().Get("trace")
+ if strings.TrimSpace(id) == "" {
+ writeError(w, http.StatusBadRequest, fmt.Errorf("trace id is required"))
+ return
+ }
+ data, ok, err := BuildLensData(opts.LogPath, id, LensDataOptions{UserMode: rulesUserMode})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, err)
+ return
+ }
+ if !ok {
+ writeError(w, http.StatusNotFound, fmt.Errorf("trace not found"))
+ return
+ }
+ writeJSON(w, data)
+ })
mux.HandleFunc("/api/memory", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
methodNotAllowed(w)
diff --git a/cli/beacon/internal/endpoint/dashboard/traces.go b/cli/beacon/internal/endpoint/dashboard/traces.go
index 1ac0ac5c..dbeee2de 100644
--- a/cli/beacon/internal/endpoint/dashboard/traces.go
+++ b/cli/beacon/internal/endpoint/dashboard/traces.go
@@ -952,6 +952,10 @@ func traceRange(query TraceQuery, total int) (int, int) {
if offset <= 0 {
offset = 1
}
+ if query.NoLimit {
+ // Lens data needs the whole trace in one read; the size budget is applied by its caller.
+ limit = total
+ }
if query.AroundEvent > 0 {
before, after := query.Before, query.After
if before <= 0 {