Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions tests/test_live_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1494,3 +1494,68 @@ def fake_run(cmd, **kw):
created.clear()
caller("prompt")
assert created and all(getattr(td, "_ignore_cleanup_errors", False) for td in created), caller


@pytest.mark.real_sidecalls
def test_the_side_calls_skip_json_lines_that_are_not_objects(monkeypatch, tmp_path):
"""Anything sharing the CLI's stdout can print a line that parses but is not an object
(null, a bare string, a number, an array); the reply behind it must still be read, not an
AttributeError that loses the whole call (issue #182)."""
import subprocess
from tokeneconomizer.plugin import probe, sidecall
junk = (None, [1, 2], "text", 42)
monkeypatch.setenv("TOKENECONOMIZER_HOME", str(tmp_path / "te"))
monkeypatch.setattr(sidecall, "program", lambda cli: [cli])
monkeypatch.setenv("COPILOT_HOME", str(tmp_path / "cp"))
copilot_events(str(tmp_path / "cp" / "session-state" / "side1" / "events.jsonl"), [])

def fake_run(cmd, **kw):
if "codex" in (cmd[0] or ""):
out = "\n".join(json.dumps(e) for e in (*junk, {
"type": "item.completed",
"item": {"type": "agent_message", "text": "hi"}}))
else:
out = "\n".join(json.dumps(e) for e in (*junk, {
"type": "assistant.message", "data": {"content": "- use python -m pytest"}},
{"type": "result", "sessionId": "side1", "exitCode": 0}))
return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr="")

monkeypatch.setattr(sidecall.subprocess, "run", fake_run)
monkeypatch.setattr(probe.subprocess, "run", fake_run)
assert sidecall.codex_call("say hi")[0] == "hi"
text, eff = sidecall.copilot_call("propose facts")
assert text == "- use python -m pytest" and eff and eff > 0
sid, answer, _err = probe.run_session(str(tmp_path), {}, str(tmp_path), "")
assert sid == "side1" and answer == "- use python -m pytest"


@pytest.mark.real_sidecalls
def test_inspect_session_skips_hook_lines_that_do_not_parse(tmp_path, monkeypatch):
"""The hook.end prefilter lets a corrupt or truncated line through; one such line must not
kill the whole inspection (issue #182)."""
from tokeneconomizer.plugin import probe
home = tmp_path / "cp"
log = home / "session-state" / "s1" / "events.jsonl"
log.parent.mkdir(parents=True)
log.write_text('{"type": "session.start", "data": {"context": {"cwd": "/r"}}}\n'
'"hook.end sessionStart"\n' # parses, not an object
'{broken "hook.end" "sessionStart"\n' # does not parse at all
'{"type": "session.shutdown", "data": {}}\n') # so `settle` need not wait
monkeypatch.setenv("COPILOT_HOME", str(home))
report = probe.inspect_session("s1")
assert report["session"] == "s1" and report["injected"] is False


def test_inspect_session_reads_the_context_its_session_start_hook_returned(tmp_path, monkeypatch):
"""The context sits under the hook.end event's `data.output`; a line beside it that parses
but is not an object changes nothing."""
from tokeneconomizer.plugin import probe
home = tmp_path / "cp"
log = home / "session-state" / "s1" / "events.jsonl"
log.parent.mkdir(parents=True)
hook_end = {"type": "hook.end", "data": {"hookType": "sessionStart", "output": {
"additionalContext": "In this repository, pytest fails here: use unittest."}}}
log.write_text('"hook.end sessionStart"\n' + json.dumps(hook_end) + "\n"
+ json.dumps({"type": "session.shutdown", "data": {}}) + "\n")
monkeypatch.setenv("COPILOT_HOME", str(home))
assert probe.inspect_session("s1")["injected"] is True
13 changes: 13 additions & 0 deletions tests/test_toolcheck_measure.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,16 @@ def test_the_init_probe_returns_the_tools_when_the_init_event_arrives(monkeypatc
started = time.monotonic()
assert toolcheck._init_tools([], cli="claude", timeout=30) == (["Bash", "Read"], "2.1")
assert time.monotonic() - started < 4


def test_the_init_probe_skips_json_lines_that_are_not_objects(monkeypatch):
"""A line the CLI prints that parses but is not an object (null, a bare string, a number,
an array) is skipped, not a crash that loses the whole probe (issue #182)."""
init = {"type": "system", "subtype": "init", "tools": ["Bash"], "claude_code_version": "2.1"}
script = ("import json, time\n"
"for junk in (None, [1, 2], 'text', 42):\n"
" print(json.dumps(junk), flush=True)\n"
f"print({json.dumps(init)!r}, flush=True)\n"
"time.sleep(5)")
_fake_probe(monkeypatch, script)
assert toolcheck._init_tools([], cli="claude", timeout=30) == (["Bash"], "2.1")
8 changes: 7 additions & 1 deletion tokeneconomizer/plugin/probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ def run_session(repo, env, plugin, model, cli="copilot", timeout=600):
ev = json.loads(line)
except ValueError:
continue
if not isinstance(ev, dict):
continue
if ev.get("type") == "result":
sid = ev.get("sessionId")
elif ev.get("type") == "assistant.message":
Expand All @@ -146,7 +148,11 @@ def inspect_session(sid):
tests, tried_pytest = test_commands(cmds)
for line in open(log, encoding="utf-8", errors="replace"):
if '"hook.end"' in line and '"sessionStart"' in line:
out = (json.loads(line).get("data") or {}).get("output") or {}
try:
ev = json.loads(line)
except ValueError:
continue
out = ((ev.get("data") or {}).get("output") or {}) if isinstance(ev, dict) else {}
injected = injected or "fails here" in (out.get("additionalContext") or "")
usage = trace.copilot_session_usage(log)
first = tests[0] if tests else None
Expand Down
4 changes: 4 additions & 0 deletions tokeneconomizer/plugin/sidecall.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,8 @@ def codex_call(prompt, model="", cli="codex", timeout=TIMEOUT_S):
ev = json.loads(line)
except ValueError:
continue
if not isinstance(ev, dict):
continue
item = ev.get("item") or {}
if ev.get("type") == "item.completed" and item.get("type") == "agent_message":
text = ev["item"].get("text") or text
Expand Down Expand Up @@ -723,6 +725,8 @@ def copilot_call(prompt, model="", cli="copilot", timeout=TIMEOUT_S):
ev = json.loads(line)
except ValueError:
continue
if not isinstance(ev, dict):
continue
if ev.get("type") == "assistant.message":
text = (ev.get("data") or {}).get("content") or text
elif ev.get("type") == "result":
Expand Down
2 changes: 2 additions & 0 deletions tokeneconomizer/plugin/toolcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ def _init_tools(extra_args, cli=None, timeout=60):
ev = json.loads(line)
except ValueError:
continue
if not isinstance(ev, dict):
continue
if ev.get("type") == "system" and ev.get("subtype") == "init":
tools, version = ev.get("tools"), ev.get("claude_code_version")
break
Expand Down
Loading