Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_object_ai.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_object_ai.py · 28.9 KB · 787 lines
1"""Tests for AI chat: provider adapters, the tool loop, and the endpoint."""
2
3import json
4
5import pytest
6
7import object_ai
8import object_mcp
9import object_record_changes
10import object_records
11import object_server
12
13from test_object_server import (
14 create_identity_session,
15 enable_admin_token,
16 request,
17 save_permission_policy,
18 write_records,
19)
20
21
22def anthropic_text_response(text):
23 return (
24 200,
25 json.dumps(
26 {
27 "content": [{"type": "text", "text": text}],
28 "usage": {"input_tokens": 10, "output_tokens": 5},
29 }
30 ).encode(),
31 )
32
33
34def anthropic_text_response_with_usage(text, *, input_tokens, output_tokens):
35 return (
36 200,
37 json.dumps(
38 {
39 "content": [{"type": "text", "text": text}],
40 "usage": {"input_tokens": input_tokens, "output_tokens": output_tokens},
41 }
42 ).encode(),
43 )
44
45
46def openai_text_response_with_usage(text, *, prompt_tokens, completion_tokens):
47 return (
48 200,
49 json.dumps(
50 {
51 "choices": [{"message": {"role": "assistant", "content": text}}],
52 "usage": {
53 "prompt_tokens": prompt_tokens,
54 "completion_tokens": completion_tokens,
55 },
56 }
57 ).encode(),
58 )
59
60
61def anthropic_tool_response(name, arguments):
62 return (
63 200,
64 json.dumps(
65 {
66 "content": [
67 {"type": "tool_use", "id": "call-1", "name": name, "input": arguments}
68 ],
69 "usage": {"input_tokens": 20, "output_tokens": 8},
70 }
71 ).encode(),
72 )
73
74
75def test_split_model_and_tool_conversion():
76 assert object_ai.split_model("anthropic:claude-haiku-4-5") == ("anthropic", "claude-haiku-4-5")
77 with pytest.raises(object_ai.InvalidChatRequestError):
78 object_ai.split_model("claude-haiku-4-5")
79 with pytest.raises(object_ai.InvalidChatRequestError):
80 object_ai.split_model("mystery:model")
81
82 tools = object_ai.mcp_tools_as_provider_tools(
83 ["global_search"], object_mcp.TOOLS, service="anthropic"
84 )
85 assert tools[0]["name"] == "global_search"
86 assert "input_schema" in tools[0]
87
88 openai_tools = object_ai.mcp_tools_as_provider_tools(
89 ["global_search"], object_mcp.TOOLS, service="openai"
90 )
91 assert openai_tools[0]["function"]["name"] == "global_search"
92
93 with pytest.raises(object_ai.InvalidChatRequestError, match="Unknown tools"):
94 object_ai.mcp_tools_as_provider_tools(["launch_missiles"], object_mcp.TOOLS, service="anthropic")
95
96
97def test_run_chat_loops_through_tool_calls():
98 responses = [
99 anthropic_tool_response("global_search", {"query": "flywheel"}),
100 anthropic_text_response("Found one note about the flywheel."),
101 ]
102 requests_seen = []
103
104 def send_http(url, headers, body):
105 requests_seen.append(json.loads(body))
106 return responses.pop(0)
107
108 dispatched = []
109
110 def dispatch_tool(name, arguments):
111 dispatched.append((name, arguments))
112 return {"http_status": 200, "response": {"results": {"notes": [{"id": "n1"}]}}}
113
114 result = object_ai.run_chat(
115 send_http=send_http,
116 dispatch_tool=dispatch_tool,
117 service="anthropic",
118 model="claude-haiku-4-5",
119 key="sk-test",
120 message="find flywheel notes",
121 tools=object_ai.mcp_tools_as_provider_tools(
122 ["global_search"], object_mcp.TOOLS, service="anthropic"
123 ),
124 )
125
126 assert result["reply"] == "Found one note about the flywheel."
127 assert result["rounds"] == 2
128 assert dispatched == [("global_search", {"query": "flywheel"})]
129 assert result["tool_calls"] == [
130 {"name": "global_search", "arguments": {"query": "flywheel"}, "http_status": 200}
131 ]
132 assert result["usage"] == {
133 "input_tokens": 30, "output_tokens": 13,
134 "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0,
135 "largest_prompt_tokens": 20,
136 }
137 # The second provider round carries the tool result back.
138 followup = requests_seen[1]["messages"]
139 assert followup[-1]["content"][0]["type"] == "tool_result"
140
141
142def test_read_page_tool_calls_echo_real_links_other_tools_do_not():
143 """The bug this fixes: only the model's own restated prose survives
144 into a later turn's history, never a tool's actual result -- so a
145 read_page call's real hrefs were lost the moment the model finished
146 replying, and a later "go to that story" had nothing but the model's
147 memory of its own summary to resolve against. tool_calls now echoes
148 read_page's real (capped) link list back to the caller; every other
149 tool's entry is unchanged, since most results are either already
150 small or not the kind of thing a later turn needs to resolve a vague
151 reference against.
152 """
153 responses = [
154 anthropic_tool_response("read_page", {"url": "https://techmeme.com"}),
155 anthropic_text_response("TechMeme is showing top tech news."),
156 ]
157
158 def send_http(url, headers, body):
159 return responses.pop(0)
160
161 def dispatch_tool(name, arguments):
162 return {
163 "http_status": 200,
164 "response": {
165 "title": "Techmeme",
166 "text": "...",
167 "final_url": "https://techmeme.com",
168 "links": [{"n": i, "label": f"Story {i}", "href": f"https://example.com/{i}"}
169 for i in range(1, 50)],
170 },
171 }
172
173 result = object_ai.run_chat(
174 send_http=send_http, dispatch_tool=dispatch_tool,
175 service="anthropic", model="claude-haiku-4-5", key="sk-test",
176 message="read techmeme",
177 tools=object_ai.mcp_tools_as_provider_tools(["read_page"], object_mcp.TOOLS, service="anthropic"),
178 )
179
180 [call] = result["tool_calls"]
181 assert call["name"] == "read_page"
182 assert call["result"]["final_url"] == "https://techmeme.com"
183 assert call["result"]["title"] == "Techmeme"
184 # Capped, not the full 49 -- a link-heavy page must not balloon every
185 # later turn's context once a caller starts re-injecting this.
186 assert len(call["result"]["links"]) == object_ai.READER_LINKS_ECHO_CAP
187 assert call["result"]["links"][0] == {"n": 1, "label": "Story 1", "href": "https://example.com/1"}
188
189
190def test_non_read_page_tool_calls_never_get_a_result_echo():
191 responses = [
192 anthropic_tool_response("global_search", {"query": "flywheel"}),
193 anthropic_text_response("Found one note."),
194 ]
195
196 def send_http(url, headers, body):
197 return responses.pop(0)
198
199 def dispatch_tool(name, arguments):
200 return {"http_status": 200, "response": {"results": {"notes": [{"id": "n1"}]}}}
201
202 result = object_ai.run_chat(
203 send_http=send_http, dispatch_tool=dispatch_tool,
204 service="anthropic", model="claude-haiku-4-5", key="sk-test",
205 message="find flywheel notes",
206 tools=object_ai.mcp_tools_as_provider_tools(["global_search"], object_mcp.TOOLS, service="anthropic"),
207 )
208 assert result["tool_calls"] == [
209 {"name": "global_search", "arguments": {"query": "flywheel"}, "http_status": 200}
210 ]
211
212
213def test_tool_result_summary_ignores_read_page_calls_with_no_links():
214 assert object_ai._tool_result_summary("read_page", {"title": "x", "links": []}) is None
215 assert object_ai._tool_result_summary("read_page", {"title": "x"}) is None
216 assert object_ai._tool_result_summary("read_page", "not a dict") is None
217 assert object_ai._tool_result_summary("global_search", {"links": [{"n": 1}]}) is None
218
219
220def test_run_chat_resumes_from_history():
221 requests_seen = []
222
223 def send_http(url, headers, body):
224 requests_seen.append(json.loads(body))
225 return anthropic_text_response("Continuing where we left off.")
226
227 result = object_ai.run_chat(
228 send_http=send_http,
229 dispatch_tool=lambda name, arguments: {},
230 service="anthropic",
231 model="claude-haiku-4-5",
232 key="sk-test",
233 message="and then?",
234 history=[
235 {"role": "user", "content": "tell me about the flywheel"},
236 {"role": "assistant", "content": "It spins."},
237 ],
238 )
239 assert result["reply"] == "Continuing where we left off."
240 messages = requests_seen[0]["messages"]
241 assert [m["role"] for m in messages] == ["user", "assistant", "user"]
242 assert messages[-1]["content"] == "and then?"
243
244 with pytest.raises(object_ai.InvalidChatRequestError, match="history"):
245 object_ai.normalize_history([{"role": "system", "content": "x"}])
246
247
248def test_run_chat_stops_at_round_limit():
249 def send_http(url, headers, body):
250 return anthropic_tool_response("global_search", {"query": "again"})
251
252 result = object_ai.run_chat(
253 send_http=send_http,
254 dispatch_tool=lambda name, arguments: {"http_status": 200, "response": {}},
255 service="anthropic",
256 model="claude-haiku-4-5",
257 key="sk-test",
258 message="loop forever",
259 tools=object_ai.mcp_tools_as_provider_tools(
260 ["global_search"], object_mcp.TOOLS, service="anthropic"
261 ),
262 max_rounds=2,
263 )
264 assert result["truncated"] is True
265 assert len(result["tool_calls"]) == 2
266
267
268def test_run_chat_raises_on_provider_error():
269 def send_http(url, headers, body):
270 return 401, json.dumps({"error": {"message": "invalid x-api-key"}}).encode()
271
272 with pytest.raises(object_ai.AIProviderError, match="invalid x-api-key"):
273 object_ai.run_chat(
274 send_http=send_http,
275 dispatch_tool=lambda name, arguments: {},
276 service="anthropic",
277 model="claude-haiku-4-5",
278 key="sk-bad",
279 message="hi",
280 )
281
282
283def test_ai_chat_endpoint_runs_tools_with_caller_permissions(tmp_path, monkeypatch):
284 data_dir = tmp_path / "data"
285 write_records(data_dir, "notes", "id\tcontent\nn1\tflywheel plan\n")
286 write_records(
287 data_dir,
288 "ai_usage",
289 "id\towner_id\tprovider\tmodel\ttokens_in\ttokens_out\tcost_cents\tcreated_at\n",
290 )
291 schema_file = data_dir / "schemas" / "notes.json"
292 schema_file.parent.mkdir(parents=True, exist_ok=True)
293 schema_file.write_text(
294 json.dumps(
295 {"fields": [{"name": "id"}, {"name": "content"}], "search": {"fields": ["content"]}}
296 )
297 )
298 save_permission_policy(
299 data_dir,
300 {
301 "access_mode": "role_based",
302 "rules": [
303 {
304 "effect": "allow",
305 "principal": "registered",
306 "actions": ["read"],
307 "collection": "notes",
308 "reason": "signed-in users read notes",
309 }
310 ],
311 },
312 )
313 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
314 monkeypatch.setenv(object_server.AI_CHAT_ENABLED_ENV, "true")
315 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
316 enable_admin_token(monkeypatch)
317 token, _ = create_identity_session({"user_id": "dan"})
318 bearer = [("authorization", f"Bearer {token}")]
319
320 responses = [
321 anthropic_tool_response("global_search", {"query": "flywheel"}),
322 anthropic_text_response("One note matches."),
323 ]
324 monkeypatch.setattr(
325 object_server.object_ai,
326 "run_chat",
327 object_ai.run_chat,
328 )
329
330 def fake_urlopen(request_obj, timeout=None):
331 raise AssertionError("network must go through the injected transport")
332
333 # Intercept at the handler's transport: patch urllib inside object_server.
334 class FakeResponse:
335 def __init__(self, status, body):
336 self.status = status
337 self._body = body
338
339 def read(self):
340 return self._body
341
342 def __enter__(self):
343 return self
344
345 def __exit__(self, *args):
346 return False
347
348 def fake_transport(request_obj, timeout=None):
349 status, body = responses.pop(0)
350 return FakeResponse(status, body)
351
352 monkeypatch.setattr(object_server.urllib.request, "urlopen", fake_transport)
353
354 # No key stored yet: helpful 400.
355 status, _, no_key = request(
356 "/api/ai/chat",
357 method="POST",
358 body=json.dumps({"message": "find flywheel notes", "tools": ["global_search"]}).encode(),
359 headers=bearer + [("content-type", "application/json")],
360 )
361 assert status == 400 and "service-keys" in no_key["error"]
362
363 request(
364 "/identity/users/dan/service-keys",
365 method="PUT",
366 body=json.dumps({"service": "anthropic", "key": "sk-test-1"}).encode(),
367 headers=bearer + [("content-type", "application/json")],
368 )
369
370 status, _, chat = request(
371 "/api/ai/chat",
372 method="POST",
373 body=json.dumps({"message": "find flywheel notes", "tools": ["global_search"]}).encode(),
374 headers=bearer + [("content-type", "application/json")],
375 )
376
377 assert status == 200, chat
378 assert chat["reply"] == "One note matches."
379 assert chat["tool_calls"][0]["name"] == "global_search"
380 assert chat["tool_calls"][0]["http_status"] == 200
381 assert chat["usage"]["output_tokens"] == 13
382
383
384def test_select_price_row_picks_most_recent_effective_date():
385 rows = [
386 {
387 "provider": "anthropic",
388 "model": "claude-haiku-4-5",
389 "input_per_million_cents": "80",
390 "output_per_million_cents": "400",
391 "effective_date": "2025-01-01",
392 },
393 {
394 "provider": "anthropic",
395 "model": "claude-haiku-4-5",
396 "input_per_million_cents": "100",
397 "output_per_million_cents": "500",
398 "effective_date": "2026-01-01",
399 },
400 {
401 "provider": "openai",
402 "model": "gpt-5-mini",
403 "input_per_million_cents": "25",
404 "output_per_million_cents": "200",
405 "effective_date": "2026-01-01",
406 },
407 ]
408 row = object_ai.select_price_row(rows, provider="anthropic", model="claude-haiku-4-5")
409 assert row["effective_date"] == "2026-01-01"
410 assert row["input_per_million_cents"] == "100"
411
412 assert object_ai.select_price_row(rows, provider="anthropic", model="claude-opus-4-8") is None
413 assert object_ai.select_price_row([], provider="anthropic", model="claude-haiku-4-5") is None
414
415
416def test_compute_cost_cents_exact_integer_math():
417 price_row = {"input_per_million_cents": "100", "output_per_million_cents": "500"}
418 # 2.5M input tokens @ 100c/M = 250c; 1.5M output tokens @ 500c/M = 750c.
419 assert object_ai.compute_cost_cents(2_500_000, 1_500_000, price_row) == 1000
420 # Floors rather than rounds: 999,999 tokens @ 100c/M is 99.9999c, not 100c.
421 assert object_ai.compute_cost_cents(999_999, 0, price_row) == 99
422 assert object_ai.compute_cost_cents(0, 0, price_row) == 0
423 # No price row -> cost is None, never zero (zero would look like a real free turn).
424 assert object_ai.compute_cost_cents(1000, 1000, None) is None
425
426
427def test_compute_cost_cents_sums_before_flooring():
428 # A cheap-model price row (gpt-5-mini's real rate): flooring each side
429 # separately before summing would give 0 + 0 = 0c for this call even
430 # though the true combined cost is ~1.06c -- real money silently
431 # recorded as free. Summing first and flooring once catches it.
432 price_row = {"input_per_million_cents": 25, "output_per_million_cents": 200}
433 assert object_ai.compute_cost_cents(36_428, 734, price_row) == 1
434 # A call whose combined cost genuinely is sub-cent still floors to 0 --
435 # that's correct integer-cent accounting, not the bug.
436 assert object_ai.compute_cost_cents(644, 1024, price_row) == 0
437
438
439def test_openai_request_sets_reasoning_effort_none_for_gpt_5_6_family_with_tools():
440 # OpenAI's own error, hit live: "Function tools with reasoning_effort
441 # are not supported for gpt-5.6-luna in /v1/chat/completions ... set
442 # reasoning_effort to 'none'." Scoped to the 5.6 family specifically --
443 # gpt-5/gpt-5-mini already work with tools under their own default and
444 # must NOT get this override.
445 captured_bodies = []
446
447 def send_http(url, headers, body):
448 captured_bodies.append(json.loads(body))
449 return openai_text_response_with_usage("ok", prompt_tokens=5, completion_tokens=2)
450
451 tools = [{"type": "function", "function": {"name": "noop", "parameters": {}}}]
452
453 object_ai.run_chat(
454 send_http=send_http, dispatch_tool=lambda name, arguments: {},
455 service="openai", model="gpt-5.6-luna", key="sk-test",
456 message="hello", tools=tools,
457 )
458 assert captured_bodies[-1]["reasoning_effort"] == "none"
459
460 captured_bodies.clear()
461 object_ai.run_chat(
462 send_http=send_http, dispatch_tool=lambda name, arguments: {},
463 service="openai", model="gpt-5-mini", key="sk-test",
464 message="hello", tools=tools,
465 )
466 assert "reasoning_effort" not in captured_bodies[-1]
467
468 captured_bodies.clear()
469 object_ai.run_chat(
470 send_http=send_http, dispatch_tool=lambda name, arguments: {},
471 service="openai", model="gpt-5.6-luna", key="sk-test",
472 message="hello", tools=None,
473 )
474 assert "reasoning_effort" not in captured_bodies[-1]
475
476
477def test_run_chat_openai_usage_shape_feeds_cost_math():
478 def send_http(url, headers, body):
479 return openai_text_response_with_usage(
480 "hi", prompt_tokens=1_000_000, completion_tokens=500_000
481 )
482
483 result = object_ai.run_chat(
484 send_http=send_http,
485 dispatch_tool=lambda name, arguments: {},
486 service="openai",
487 model="gpt-5-mini",
488 key="sk-test",
489 message="hello",
490 )
491 assert result["usage"] == {
492 "input_tokens": 1_000_000, "output_tokens": 500_000,
493 "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0,
494 "largest_prompt_tokens": 1_000_000,
495 }
496
497 price_row = {"input_per_million_cents": 25, "output_per_million_cents": 200}
498 # 1M input @ 25c/M = 25c; 0.5M output @ 200c/M = 100c.
499 assert (
500 object_ai.compute_cost_cents(
501 result["usage"]["input_tokens"], result["usage"]["output_tokens"], price_row
502 )
503 == 125
504 )
505
506
507def test_ai_chat_endpoint_records_cost_and_writes_usage(tmp_path, monkeypatch):
508 data_dir = tmp_path / "data"
509 write_records(
510 data_dir,
511 "ai_prices",
512 "id\tprovider\tmodel\tinput_per_million_cents\toutput_per_million_cents\teffective_date\n"
513 "p-old\tanthropic\tclaude-haiku-4-5\t80\t400\t2025-01-01\n"
514 "p-new\tanthropic\tclaude-haiku-4-5\t100\t500\t2026-01-01\n",
515 )
516 schema_file = data_dir / "schemas" / "ai_usage.json"
517 schema_file.parent.mkdir(parents=True, exist_ok=True)
518 schema_file.write_text(
519 json.dumps(
520 {
521 "fields": [
522 {"name": "id"},
523 {"name": "owner_id", "type": "text"},
524 {"name": "provider", "type": "text", "required": True},
525 {"name": "model", "type": "text", "required": True},
526 {"name": "tokens_in", "type": "int", "required": True},
527 {"name": "tokens_out", "type": "int", "required": True},
528 {"name": "cost_cents", "type": "int"},
529 {"name": "created_at", "type": "datetime", "read_only": True},
530 ]
531 }
532 )
533 )
534
535 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
536 monkeypatch.setenv(object_server.AI_CHAT_ENABLED_ENV, "true")
537 enable_admin_token(monkeypatch)
538 token, _ = create_identity_session({"user_id": "dan"})
539 bearer = [("authorization", f"Bearer {token}")]
540
541 request(
542 "/identity/users/dan/service-keys",
543 method="PUT",
544 body=json.dumps({"service": "anthropic", "key": "sk-test-1"}).encode(),
545 headers=bearer + [("content-type", "application/json")],
546 )
547
548 response = anthropic_text_response_with_usage(
549 "hi there", input_tokens=2_500_000, output_tokens=1_500_000
550 )
551
552 def fake_transport(request_obj, timeout=None):
553 status, body = response
554
555 class FakeResponse:
556 def __init__(self):
557 self.status = status
558
559 def read(self):
560 return body
561
562 def __enter__(self):
563 return self
564
565 def __exit__(self, *args):
566 return False
567
568 return FakeResponse()
569
570 monkeypatch.setattr(object_server.urllib.request, "urlopen", fake_transport)
571
572 status, _, chat = request(
573 "/api/ai/chat",
574 method="POST",
575 body=json.dumps(
576 {"message": "hi", "model": "anthropic:claude-haiku-4-5", "tools": []}
577 ).encode(),
578 headers=bearer + [("content-type", "application/json")],
579 )
580
581 assert status == 200, chat
582 assert chat["usage"]["input_tokens"] == 2_500_000
583 assert chat["usage"]["output_tokens"] == 1_500_000
584 # Must pick the 2026-01-01 row (100/500), not the older 2025-01-01 row (80/400):
585 # 2.5M * 100c/M + 1.5M * 500c/M = 250c + 750c = 1000c.
586 assert chat["usage"]["cost_cents"] == 1000
587
588 usage_rows = object_records.read_collection_records("ai_usage", base_dir=data_dir)
589 assert len(usage_rows) == 1
590 row = usage_rows[0]
591 assert row["owner_id"] == "dan"
592 assert row["provider"] == "anthropic"
593 assert row["model"] == "claude-haiku-4-5"
594 assert row["tokens_in"] == "2500000"
595 assert row["tokens_out"] == "1500000"
596 assert row["cost_cents"] == "1000"
597 assert row["created_at"] # server-stamped, never blank
598
599 # Server-side write, attributed to the calling user -- not the client.
600 changes = object_record_changes.list_record_changes("ai_usage", base_dir=data_dir)
601 assert changes["changes"][0]["actor"] == "dan"
602 assert changes["changes"][0]["action"] == "create"
603
604
605def test_ai_chat_endpoint_records_tokens_with_null_cost_when_price_missing(tmp_path, monkeypatch):
606 data_dir = tmp_path / "data"
607 # ai_prices has no row at all -- the collection is known but empty.
608 write_records(
609 data_dir,
610 "ai_prices",
611 "id\tprovider\tmodel\tinput_per_million_cents\toutput_per_million_cents\teffective_date\n",
612 )
613 schema_file = data_dir / "schemas" / "ai_usage.json"
614 schema_file.parent.mkdir(parents=True, exist_ok=True)
615 schema_file.write_text(
616 json.dumps(
617 {
618 "fields": [
619 {"name": "id"},
620 {"name": "owner_id", "type": "text"},
621 {"name": "provider", "type": "text", "required": True},
622 {"name": "model", "type": "text", "required": True},
623 {"name": "tokens_in", "type": "int", "required": True},
624 {"name": "tokens_out", "type": "int", "required": True},
625 {"name": "cost_cents", "type": "int"},
626 {"name": "created_at", "type": "datetime", "read_only": True},
627 ]
628 }
629 )
630 )
631
632 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
633 monkeypatch.setenv(object_server.AI_CHAT_ENABLED_ENV, "true")
634 enable_admin_token(monkeypatch)
635 token, _ = create_identity_session({"user_id": "dan"})
636 bearer = [("authorization", f"Bearer {token}")]
637
638 request(
639 "/identity/users/dan/service-keys",
640 method="PUT",
641 body=json.dumps({"service": "anthropic", "key": "sk-test-1"}).encode(),
642 headers=bearer + [("content-type", "application/json")],
643 )
644
645 response = anthropic_text_response_with_usage(
646 "hi there", input_tokens=42, output_tokens=7
647 )
648
649 def fake_transport(request_obj, timeout=None):
650 status, body = response
651
652 class FakeResponse:
653 def __init__(self):
654 self.status = status
655
656 def read(self):
657 return body
658
659 def __enter__(self):
660 return self
661
662 def __exit__(self, *args):
663 return False
664
665 return FakeResponse()
666
667 monkeypatch.setattr(object_server.urllib.request, "urlopen", fake_transport)
668
669 status, _, chat = request(
670 "/api/ai/chat",
671 method="POST",
672 body=json.dumps(
673 {"message": "hi", "model": "anthropic:claude-mystery-model", "tools": []}
674 ).encode(),
675 headers=bearer + [("content-type", "application/json")],
676 )
677
678 # Missing price row never fails the chat -- the reply still comes back.
679 assert status == 200, chat
680 assert chat["reply"] == "hi there"
681 assert chat["usage"]["cost_cents"] is None
682
683 usage_rows = object_records.read_collection_records("ai_usage", base_dir=data_dir)
684 assert len(usage_rows) == 1
685 row = usage_rows[0]
686 # Tokens are still recorded even though there is nothing to price them with.
687 assert row["tokens_in"] == "42"
688 assert row["tokens_out"] == "7"
689 assert row.get("cost_cents", "") == ""
690
691
692def test_ai_chat_endpoint_requires_flag_and_session(tmp_path, monkeypatch):
693 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
694 enable_admin_token(monkeypatch)
695
696 status, _, disabled = request(
697 "/api/ai/chat", method="POST", body=json.dumps({"message": "hi"}).encode()
698 )
699 assert status == 403 and "disabled" in disabled["error"]
700
701 monkeypatch.setenv(object_server.AI_CHAT_ENABLED_ENV, "true")
702 status, _, anonymous = request(
703 "/api/ai/chat", method="POST", body=json.dumps({"message": "hi"}).encode()
704 )
705 assert status == 401
706
707
708def test_ai_chat_endpoint_records_the_actual_reply_text(tmp_path, monkeypatch):
709 """The bug a session review caught, live: every server-recorded turn
710 had output == "" regardless of what the model said, because the
711 write read result.get("text") and run_chat's key is "reply". The
712 HTTP response spreads **result directly, so the client always saw
713 the correct reply -- this was invisible everywhere except the
714 history the server-side write exists specifically to make
715 inspectable, and it went unnoticed for as long as it did because
716 every source-presence test checked that "shell_commands" and
717 "created_at" appeared in the file, never the recorded VALUE. This
718 reads the row back and checks the text, not the source.
719 """
720 data_dir = tmp_path / "data"
721 schema_file = data_dir / "schemas" / "shell_commands.json"
722 schema_file.parent.mkdir(parents=True, exist_ok=True)
723 schema_file.write_text(json.dumps({"fields": [
724 {"name": "id"}, {"name": "input", "type": "text"},
725 {"name": "output", "type": "text"}, {"name": "kind", "type": "text"},
726 {"name": "owner_id", "type": "text"}, {"name": "session_id", "type": "text"},
727 {"name": "source", "type": "text"}, {"name": "model", "type": "text"},
728 {"name": "duration_ms", "type": "int"}, {"name": "tool_calls", "type": "text"},
729 {"name": "created_at", "type": "datetime"}, # NOT read_only, matching the real schema
730 ]}))
731 (data_dir / "schemas" / "ai_usage.json").write_text(json.dumps({"fields": [
732 {"name": "id"}, {"name": "owner_id", "type": "text"},
733 {"name": "provider", "type": "text", "required": True},
734 {"name": "model", "type": "text", "required": True},
735 {"name": "tokens_in", "type": "int", "required": True},
736 {"name": "tokens_out", "type": "int", "required": True},
737 {"name": "cost_cents", "type": "int"},
738 {"name": "created_at", "type": "datetime", "read_only": True},
739 ]}))
740
741 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
742 monkeypatch.setenv(object_server.AI_CHAT_ENABLED_ENV, "true")
743 enable_admin_token(monkeypatch)
744 token, _ = create_identity_session({"user_id": "dan"})
745 bearer = [("authorization", f"Bearer {token}")]
746
747 request(
748 "/identity/users/dan/service-keys", method="PUT",
749 body=json.dumps({"service": "anthropic", "key": "sk-test-1"}).encode(),
750 headers=bearer + [("content-type", "application/json")],
751 )
752
753 status, body = anthropic_text_response("Here are your 8 notes on screen, sorted newest first.")
754
755 def fake_transport(request_obj, timeout=None):
756 class FakeResponse:
757 def __init__(self):
758 self.status = status
759 def read(self):
760 return body
761 def __enter__(self):
762 return self
763 def __exit__(self, *args):
764 return False
765 return FakeResponse()
766
767 monkeypatch.setattr(object_server.urllib.request, "urlopen", fake_transport)
768
769 resp_status, _, chat = request(
770 "/api/ai/chat", method="POST",
771 body=json.dumps({"message": "show me my notes",
772 "model": "anthropic:claude-haiku-4-5", "tools": [],
773 "session_id": "s-test-1", "source": "talk"}).encode(),
774 headers=bearer + [("content-type", "application/json")],
775 )
776 assert resp_status == 200, chat
777 assert chat["reply"] == "Here are your 8 notes on screen, sorted newest first."
778
779 rows = object_records.read_collection_records("shell_commands", base_dir=data_dir)
780 assert len(rows) == 1, rows
781 row = rows[0]
782 assert row["input"] == "show me my notes"
783 # THE assertion the bug would have failed.
784 assert row["output"] == "Here are your 8 notes on screen, sorted newest first."
785 assert row["session_id"] == "s-test-1"
786 assert row["source"] == "talk"
787 assert row["created_at"]