Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
test(agent): claude-code compatible otel e2e against a real collector
thinhlpg8ab3563ad133
diff --git a/scripts/otel-e2e.sh b/scripts/otel-e2e.shnew file mode 100755index 000000000..378158ac3--- /dev/null+++ b/scripts/otel-e2e.sh@@ -0,0 +1,71 @@+#!/usr/bin/env bash+# End-to-end OTel check: a real `jan` binary, a real OpenTelemetry Collector+# (Docker), and a fake OpenAI-compatible model, so it needs no provider key.+#+# scripts/otel-e2e.sh [path/to/jan]+#+# JAN_E2E_REAL_MODEL=1 use your own ~/.jan config and default model instead+# LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY / LANGFUSE_BASE_URL+# also forward traces to Langfuse (keys never logged)+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+jan="${1:-$here/../src-tauri/target/debug/jan}"+[ -x "$jan" ] || { echo "no jan binary at $jan (build src-tauri/jan-cli first)"; exit 2; }+command -v docker >/dev/null || { echo "docker required"; exit 2; }++work="$(mktemp -d)"+name="jan-otel-e2e-$$"+port_otlp="${JAN_E2E_OTLP_PORT:-14318}"+port_model="${JAN_E2E_MODEL_PORT:-18765}"+cleanup() {+ docker rm -f "$name" >/dev/null 2>&1 || true+ [ -n "${model_pid:-}" ] && kill "$model_pid" 2>/dev/null || true+ rm -rf "$work"+}+trap cleanup EXIT+mkdir -p "$work/out" "$work/proj" "$work/home/.jan"+chmod 777 "$work/out"++config="$here/otel-e2e/collector.yaml"+docker_env=()+if [ -n "${LANGFUSE_PUBLIC_KEY:-}" ] && [ -n "${LANGFUSE_SECRET_KEY:-}" ]; then+ config="$here/otel-e2e/collector.langfuse.yaml"+ printf 'LANGFUSE_OTLP_ENDPOINT=%s/api/public/otel\nLANGFUSE_AUTH=%s\n' \+ "${LANGFUSE_BASE_URL:-https://cloud.langfuse.com}" \+ "$(printf '%s:%s' "$LANGFUSE_PUBLIC_KEY" "$LANGFUSE_SECRET_KEY" | base64 | tr -d '\n')" \+ > "$work/lf.env"+ docker_env=(--env-file "$work/lf.env")+ echo "forwarding traces to Langfuse"+fi+docker run -d --name "$name" -p "127.0.0.1:$port_otlp:4318" \+ -v "$config:/etc/otelcol-contrib/config.yaml:ro" -v "$work/out:/out" \+ ${docker_env[@]+"${docker_env[@]}"} \+ otel/opentelemetry-collector-contrib:0.161.0 >/dev/null+for _ in $(seq 50); do curl -s -o /dev/null "http://127.0.0.1:$port_otlp" && break; sleep 0.2; done++export JAN_AGENT_ENABLE_TELEMETRY=1 OTEL_TRACES_EXPORTER=otlp+export OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$port_otlp"+export OTEL_EXPORTER_OTLP_PROTOCOL="${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}"+export OTEL_RESOURCE_ATTRIBUTES="deployment.environment=otel-e2e"++args=(cli agent run --output-format stream-json)+if [ "${JAN_E2E_REAL_MODEL:-0}" = 1 ]; then+ prompt="Run the shell command: echo otel-e2e. Then reply done."+ (cd "$work/proj" && "$jan" "${args[@]}" "$prompt" >"$work/run.jsonl" 2>"$work/run.err") || true+else+ python3 "$here/otel-e2e/fake_model.py" "$port_model" & model_pid=$!+ cat > "$work/home/.jan/config.toml" <<TOML+default_model = "fake-model"+[providers.fake]+base_url = "http://127.0.0.1:$port_model/v1"+models = ["fake-model"]+TOML+ sleep 0.5+ (cd "$work/proj" && HOME="$work/home" "$jan" "${args[@]}" "run echo" \+ >"$work/run.jsonl" 2>"$work/run.err") || true+fi+sleep 3 # collector batch timeout + file flush+if [ ! -s "$work/out/otel.jsonl" ]; then+ echo "collector received nothing"; tail -20 "$work/run.err"; exit 1+fi+python3 "$here/otel-e2e/check.py" "$work/out/otel.jsonl" || { tail -20 "$work/run.err"; exit 1; }diff --git a/scripts/otel-e2e/check.py b/scripts/otel-e2e/check.pynew file mode 100644index 000000000..aeb502718--- /dev/null+++ b/scripts/otel-e2e/check.py@@ -0,0 +1,57 @@+"""Validate the collector's JSON lines against the Claude Code-compatible+names jan emits. Exit 1 listing every gap."""+import json, sys++want_metrics = {"jan_agent.session.count", "jan_agent.prompt.count", "jan_agent.turn.count",+ "jan_agent.api_request.count", "jan_agent.token.usage", "jan_agent.tool.count",+ "jan_agent.active_time.total"}+want_events = {"jan_agent.user_prompt": ["session.id", "prompt.id", "prompt_length"],+ "jan_agent.api_request": ["session.id", "prompt.id", "model", "input_tokens", "output_tokens"],+ "jan_agent.tool_decision": ["tool_name", "decision", "source"],+ "jan_agent.tool_result": ["tool_name", "success", "duration_ms"]}+want_spans = {"jan_agent.interaction": ["session.id", "prompt.id", "user_prompt_length", "interaction.sequence"],+ "jan_agent.llm_request": ["gen_ai.request.model", "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"],+ "jan_agent.tool": ["tool_name", "tool_use_id", "success"]}++metrics, events, spans = set(), {}, []+for line in open(sys.argv[1]):+ doc = json.loads(line)+ for rm in doc.get("resourceMetrics", []):+ for sm in rm["scopeMetrics"]:+ metrics |= {m["name"] for m in sm["metrics"]}+ for rl in doc.get("resourceLogs", []):+ for sl in rl["scopeLogs"]:+ for r in sl["logRecords"]:+ events.setdefault(r.get("eventName"), []).append({a["key"] for a in r.get("attributes", [])})+ for rs in doc.get("resourceSpans", []):+ for ss in rs["scopeSpans"]:+ spans += ss["spans"]++gaps = [f"metric {m}" for m in sorted(want_metrics - metrics)]+for name, keys in want_events.items():+ got = events.get(name)+ if not got:+ gaps.append(f"event {name}")+ else:+ gaps += [f"event {name}.{k}" for k in keys if not any(k in g for g in got)]+by_name = {}+for s in spans:+ by_name.setdefault(s["name"], []).append(s)+for name, keys in want_spans.items():+ got = by_name.get(name)+ if not got:+ gaps.append(f"span {name}")+ continue+ for k in keys:+ if not any(k in {a["key"] for a in s["attributes"]} for s in got):+ gaps.append(f"span {name}.{k}")+roots = by_name.get("jan_agent.interaction", [])+for s in spans:+ if s["name"] != "jan_agent.interaction" and not any(+ s["traceId"] == r["traceId"] and s.get("parentSpanId") == r["spanId"] for r in roots):+ gaps.append(f"span {s['name']} {s['spanId']} is not under an interaction")+print(f"metrics={len(metrics)} events={sum(map(len, events.values()))} spans={len(spans)}")+if gaps:+ print("GAPS:\n " + "\n ".join(gaps))+ sys.exit(1)+print("OK: Claude Code-compatible metrics, events and span tree present")diff --git a/scripts/otel-e2e/collector.langfuse.yaml b/scripts/otel-e2e/collector.langfuse.yamlnew file mode 100644index 000000000..17f6f49b9--- /dev/null+++ b/scripts/otel-e2e/collector.langfuse.yaml@@ -0,0 +1,20 @@+receivers:+ otlp:+ protocols:+ http:+ endpoint: 0.0.0.0:4318+exporters:+ file:+ path: /out/otel.jsonl+ otlphttp/langfuse:+ endpoint: ${env:LANGFUSE_OTLP_ENDPOINT}+ headers:+ Authorization: "Basic ${env:LANGFUSE_AUTH}"+processors:+ batch:+ timeout: 1s+service:+ pipelines:+ metrics: { receivers: [otlp], processors: [batch], exporters: [file] }+ logs: { receivers: [otlp], processors: [batch], exporters: [file] }+ traces: { receivers: [otlp], processors: [batch], exporters: [file, otlphttp/langfuse] }diff --git a/scripts/otel-e2e/collector.yaml b/scripts/otel-e2e/collector.yamlnew file mode 100644index 000000000..53bc0d8d9--- /dev/null+++ b/scripts/otel-e2e/collector.yaml@@ -0,0 +1,19 @@+# Collector for scripts/otel-e2e.sh: OTLP/HTTP in, JSON lines out. Forwards+# traces to Langfuse too when LANGFUSE_OTLP_ENDPOINT/LANGFUSE_AUTH are set+# (see otel-e2e/collector.langfuse.yaml).+receivers:+ otlp:+ protocols:+ http:+ endpoint: 0.0.0.0:4318+exporters:+ file:+ path: /out/otel.jsonl+processors:+ batch:+ timeout: 1s+service:+ pipelines:+ metrics: { receivers: [otlp], processors: [batch], exporters: [file] }+ logs: { receivers: [otlp], processors: [batch], exporters: [file] }+ traces: { receivers: [otlp], processors: [batch], exporters: [file] }diff --git a/scripts/otel-e2e/fake_model.py b/scripts/otel-e2e/fake_model.pynew file mode 100644index 000000000..b053a72f6--- /dev/null+++ b/scripts/otel-e2e/fake_model.py@@ -0,0 +1,47 @@+"""An OpenAI-compatible /v1/chat/completions stub: the first request answers+with one bash tool call, every later one with plain text. Streams SSE."""+import json, sys+from http.server import BaseHTTPRequestHandler, HTTPServer++calls = 0++def chunk(delta, finish=None, usage=None):+ body = {"id": "x", "object": "chat.completion.chunk", "created": 1, "model": "fake-model",+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}+ if usage:+ body["usage"] = usage+ return f"data: {json.dumps(body)}\n\n"++class H(BaseHTTPRequestHandler):+ def log_message(self, *a):+ pass++ def do_GET(self):+ body = json.dumps({"object": "list", "data": [{"id": "fake-model", "object": "model"}]}).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self):+ global calls+ self.rfile.read(int(self.headers.get("Content-Length", 0)))+ calls += 1+ usage = {"prompt_tokens": 120, "completion_tokens": 8, "total_tokens": 128,+ "prompt_tokens_details": {"cached_tokens": 64}}+ if calls == 1:+ call = {"index": 0, "id": "call_1", "type": "function",+ "function": {"name": "bash", "arguments": json.dumps({"command": "echo otel-e2e"})}}+ out = chunk({"role": "assistant", "tool_calls": [call]}) + chunk({}, "tool_calls", usage)+ else:+ out = chunk({"role": "assistant", "content": "done"}) + chunk({}, "stop", usage)+ out += "data: [DONE]\n\n"+ data = out.encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()