okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-app: GitHub app and Terminal items for 0.2.73cabb9e3f

main
15.3 KiB289 linesraw
1"""Raster MCP delivery: cache bounds, authenticated downloads and vision forwarding; no GPU."""
2import base64
3import json
4import tempfile
5import unittest
6import urllib.error
7import urllib.request
8from pathlib import Path
9from unittest.mock import patch
10from serve.mcp import cache_images, hub_from_config
11from serve.frontend import ChatTemplate, images_of
12from serve.server import ByteTokenizer, Service, serve
13from serve.test_mcp import ScriptedEngine, call_script
14from serve import test_mcp as fixtures
15PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jB0kAAAAASUVORK5CYII=')
16
17def image(data=PNG, mime='image/png'):
18    return {'type': 'image', 'mimeType': mime, 'data': base64.b64encode(data).decode()}
19
20class Configuration(unittest.TestCase):
21    def test_documented_switch_reaches_hub_and_tool_result(self):
22        hub = hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}},
23                               'mcp': {'image_results': True}})
24        self.assertTrue(hub.settings['image_results'])
25        server = hub.servers['fake']
26        server.status = 'ready'
27        server.tools = [{'name': 'image', 'inputSchema': {}}]
28        with tempfile.TemporaryDirectory() as tmp:
29            hub.media_dir = Path(tmp)
30            with patch.object(server, 'call', return_value={'content': [image()]}):
31                result = hub.call('fake__image', {})
32            self.assertEqual(len(result['images']), 1)
33            self.assertEqual(result['model_content'][1]['type'], 'image')
34
35    def test_disabled_and_omitted_switch_stay_off(self):
36        for settings in ({}, {'image_results': False}):
37            with self.subTest(settings=settings):
38                hub = hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}}, 'mcp': settings})
39                self.assertFalse(hub.settings['image_results'])
40
41    def test_switch_rejects_non_booleans(self):
42        for value in ('true', 'false', 0, 1, None, [], {}):
43            with self.subTest(value=value), self.assertRaisesRegex(SystemExit, 'expected a boolean'):
44                hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}},
45                                 'mcp': {'image_results': value}})
46
47class Cache(unittest.TestCase):
48
49    def test_image_text_obeys_result_cap(self):
50        from serve.mcp import McpHub
51        hub = McpHub({'fake': {'command': 'unused'}}, {'max_result_chars': 1000, 'image_results': True})
52        server = hub.servers['fake']
53        server.status = 'ready'
54        server.tools = [{'name': 'image', 'inputSchema': {}}]
55        with tempfile.TemporaryDirectory() as tmp:
56            hub.media_dir = Path(tmp)
57            with patch.object(server, 'call', return_value={'content': [{'type': 'text', 'text': 'x' * 100000}, image()]}):
58                result = hub.call('fake__image', {})
59            self.assertTrue(result['truncated'])
60            self.assertLessEqual(len(result['model_content'][0]['text']), len(result['text']))
61            self.assertNotIn('x' * 1001, result['model_content'][0]['text'])
62            self.assertEqual(len(result['images']), 1)
63
64    def test_disabled_is_identical_to_text_only_result(self):
65        from serve.mcp import McpHub, result_text
66        hub = McpHub({'fake': {'command': 'unused'}})
67        server = hub.servers['fake']
68        server.status = 'ready'
69        server.tools = [{'name': 'image', 'inputSchema': {}}]
70        result = {'content': [{'type': 'text', 'text': 'hello'}, image()]}
71        with tempfile.TemporaryDirectory() as tmp:
72            hub.media_dir = Path(tmp) / 'unused'
73            with patch.object(server, 'call', return_value=result), patch('serve.mcp.cache_images') as cache:
74                output = hub.call('fake__image', {})
75            cache.assert_not_called()
76            self.assertEqual(output['text'], result_text(result))
77            self.assertNotIn('images', output)
78            self.assertNotIn('model_content', output)
79            self.assertFalse(hub.media_dir.exists())
80
81    def test_cache_failure_keeps_text_result(self):
82        from serve.mcp import McpHub
83        hub = McpHub({'fake': {'command': 'unused'}}, {'image_results': True})
84        server = hub.servers['fake']
85        server.status = 'ready'
86        server.tools = [{'name': 'image', 'inputSchema': {}}]
87        hub.media_dir = Path('unused')
88        with patch.object(server, 'call', return_value={'content': [{'type': 'text', 'text': 'hello'}, image()]}), patch('serve.mcp.cache_images', side_effect=OSError('disk full')):
89            output = hub.call('fake__image', {})
90        self.assertTrue(output['ok'])
91        self.assertIn('hello', output['text'])
92        self.assertNotIn('model_content', output)
93
94    def test_null_and_non_object_content(self):
95        with tempfile.TemporaryDirectory() as tmp:
96            self.assertEqual(cache_images({'content': None}, tmp), [])
97            self.assertEqual(cache_images({'content': [None, False, 'bad', image()]}, tmp), cache_images({'content': [image()]}, tmp))
98
99    def test_cache_deduplicates_and_preserves_bytes(self):
100        with tempfile.TemporaryDirectory() as tmp:
101            a = cache_images({'content': [image()]}, tmp)
102            b = cache_images({'content': [image()]}, tmp)
103            self.assertEqual(a, b)
104            self.assertEqual(len(list(Path(tmp).iterdir())), 1)
105            self.assertEqual((Path(tmp) / a[0]['url'].split('/')[-1]).read_bytes(), PNG)
106
107    def test_rejects_invalid_and_active_content(self):
108        with tempfile.TemporaryDirectory() as tmp:
109            blocks = [image(b'not a PNG'), image(b'<svg/>', 'image/svg+xml'), {'type': 'image', 'mimeType': 'image/png', 'data': '***'}]
110            self.assertEqual(cache_images({'content': blocks}, tmp), [])
111
112    def test_caps_images_per_result(self):
113        with tempfile.TemporaryDirectory() as tmp:
114            self.assertEqual(len(cache_images({'content': [image()] * 8}, tmp)), 4)
115
116    def test_authenticated_download_and_traversal(self):
117        with tempfile.TemporaryDirectory() as tmp:
118            media = cache_images({'content': [image()]}, tmp)[0]
119            tok = ByteTokenizer()
120            svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja'))
121
122            class Hub:
123                media_dir = tmp
124            svc.mcp = Hub()
125            svc.api_key = 'test-key'
126            httpd = serve(svc, port=0)
127            base = f'http://127.0.0.1:{httpd.server_address[1]}/'
128            try:
129                with self.assertRaises(urllib.error.HTTPError) as error:
130                    urllib.request.urlopen(base + media['url'])
131                self.assertEqual(error.exception.code, 401)
132                req = urllib.request.Request(base + media['url'], headers={'Authorization': 'Bearer test-key'})
133                with urllib.request.urlopen(req) as response:
134                    self.assertEqual(response.read(), PNG)
135                    self.assertEqual(response.headers['Content-Type'], 'image/png')
136                req = urllib.request.Request(base + 'tool-media/../../secret.png', headers={'Authorization': 'Bearer test-key'})
137                with self.assertRaises(urllib.error.HTTPError) as error:
138                    urllib.request.urlopen(req)
139                self.assertEqual(error.exception.code, 404)
140            finally:
141                httpd.shutdown()
142                httpd.server_close()
143
144class HistoryReferences(unittest.TestCase):
145
146    def test_reference_resolves_only_to_cache(self):
147        with tempfile.TemporaryDirectory() as tmp:
148            im = cache_images({'content': [image()]}, tmp)[0]
149            name = im['url'].split('/')[-1]
150            tok = ByteTokenizer()
151            svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja'))
152
153            class Hub:
154                media_dir = tmp
155            svc.mcp = Hub()
156            message = [{'role': 'tool', 'content': [{'type': 'image', 'source': 'strata-tool-media:' + name}]}]
157            with patch.object(svc, '_note_unreadable_tool_images', return_value={}):
158                with self.assertRaisesRegex(ValueError, 'without the vision encoder'):
159                    svc.prepare(message, [], {}, 16)
160            self.assertEqual(images_of(message), [str(Path(tmp) / name)])
161
162    def test_mixed_missing_and_valid_pictures_keeps_valid_vision(self):
163        with tempfile.TemporaryDirectory() as tmp:
164            media = cache_images({'content': [image()]}, tmp)[0]
165            source = str(Path(tmp) / media['url'].split('/')[-1])
166            rows = Path(tmp) / 'img.sve'
167            rows.write_bytes(b'rows')
168            class Vision:
169                dir = Path(tmp)
170
171                def encode(self, value):
172                    if value != source:
173                        raise AssertionError('Only the valid cached image may reach the encoder')
174                    return rows, 3
175            tok = ByteTokenizer()
176            svc = Service(ScriptedEngine(tok, ['OK']), tok,
177                          ChatTemplate(Path(__file__).parent / 'chat_template.jinja'), vision=Vision())
178            class Hub:
179                media_dir = tmp
180            svc.mcp = Hub()
181            messages = [{'role': 'tool', 'content': [
182                {'type': 'text', 'text': 'Retain this text.'},
183                {'type': 'image', 'source': 'strata-tool-media:' + '0' * 64 + '.png'},
184                {'type': 'image', 'source': 'strata-tool-media:' + media['url'].split('/')[-1]}]}]
185            try:
186                ids, _, _ = svc.prepare(messages, [], {}, 16)
187                prompt = tok.decode(ids)
188                self.assertIn('Retain this text.', prompt)
189                self.assertIn('[image omitted:', prompt)
190                self.assertEqual(images_of(messages), [source])
191                self.assertEqual(ids.count(tok.encode('<|image_pad|>', parse_special=True)[0]), 3)
192            finally:
193                if svc.embeddings.path:
194                    svc.embeddings.path.unlink(missing_ok=True)
195
196    def test_bad_reference_cannot_read_other_files(self):
197        tok = ByteTokenizer()
198        svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja'))
199        with self.assertRaisesRegex(ValueError, 'invalid tool image reference'):
200            svc.prepare([{'role': 'tool', 'content': [{'type': 'image', 'source': 'strata-tool-media:../../secret.png'}]}], [], {}, 16)
201
202class ImageLoop(unittest.TestCase):
203    setUp = fixtures.ToolLoop.setUp
204    tearDown = fixtures.ToolLoop.tearDown
205    start = fixtures.ToolLoop.start
206    post = fixtures.ToolLoop.post
207    chunks = staticmethod(fixtures.ToolLoop.chunks)
208
209    def check_stale_history(self, state):
210        self.start('</think>\n\nText reply survives.')
211        with tempfile.TemporaryDirectory() as tmp:
212            self.hub.media_dir = Path(tmp) if state == 'missing' else None
213            if state == 'no_hub':
214                self.svc.mcp = None
215            history = [
216                {'role': 'user', 'content': 'Create a picture'},
217                {'role': 'assistant', 'content': '', 'tool_calls': [
218                    {'id': 'old', 'type': 'function', 'function': {'name': 'fake__echo', 'arguments': '{}'}}]},
219                {'role': 'tool', 'tool_call_id': 'old', 'content': [
220                    {'type': 'text', 'text': 'Keep this original tool text.'},
221                    {'type': 'image_url', 'image_url': {'url': 'strata-tool-media:' + '0' * 64 + '.png'}}]},
222                {'role': 'user', 'content': 'Continue with text only'}]
223            # API clients resend the original unmodified history on every later turn.
224            for turn in range(2):
225                for stream in (False, True):
226                    with self.subTest(state=state, turn=turn, stream=stream):
227                        code, text = self.post({'messages': history}, stream=stream)
228                        self.assertEqual(code, 200, text)
229                        if stream:
230                            answer = ''.join(c['choices'][0]['delta'].get('content', '') for c in self.chunks(text))
231                        else:
232                            answer = json.loads(text)['choices'][0]['message']['content']
233                        self.assertIn('Text reply survives.', answer)
234                        prompt = self.engine.prompt_text(turn * 2 + int(stream))
235                        self.assertIn('Keep this original tool text.', prompt)
236                        self.assertIn('[image omitted:', prompt)
237                        self.assertNotIn('strata-tool-media:', prompt)
238
239    def test_missing_cache_history_continues_across_turns(self):
240        self.check_stale_history('missing')
241
242    def test_disabled_cache_history_continues_across_turns(self):
243        self.check_stale_history('disabled')
244
245    def test_removed_mcp_history_continues_across_turns(self):
246        self.check_stale_history('no_hub')
247
248    def test_malformed_history_still_rejected_over_http(self):
249        self.start('</think>\n\nShould not run.')
250        self.svc.mcp = None
251        for name in ('../../secret.png', 'a' * 64 + '.svg', 'A' * 64 + '.png', 'short.png'):
252            with self.subTest(name=name):
253                code, text = self.post({'messages': [{'role': 'tool', 'content': [
254                    {'type': 'image_url', 'image_url': {'url': 'strata-tool-media:' + name}}]}]}, stream=False)
255                self.assertEqual(code, 400)
256                self.assertIn('invalid tool image reference', text)
257        self.assertEqual(self.engine.prompts, [])
258
259    def test_default_stream_has_no_image_fields(self):
260        self.start(call_script('fake__echo', text='hello'), '</think>\n\nDone.')
261        code, text = self.post({'strata_mcp': True})
262        self.assertEqual(code, 200)
263        event = [c['strata_mcp'] for c in self.chunks(text) if c.get('strata_mcp', {}).get('event') == 'result'][0]
264        self.assertEqual(set(event), {'event', 'id', 'ok', 'text', 'chars', 'truncated', 'ms'})
265
266    def test_image_result_streams_and_reaches_vision_prepare(self):
267        with tempfile.TemporaryDirectory() as tmp:
268            self.hub.settings['image_results'] = True
269            self.hub.media_dir = Path(tmp)
270            im = cache_images({'content': [image()]}, tmp)
271            source = str(Path(tmp) / im[0]['url'].split('/')[-1])
272            self.start(call_script('fake__echo', text='picture'), '</think>\n\nImage received.')
273            self.svc.vision = object()
274            native = self.svc.prepare
275            seen = []
276
277            def prepare(messages, *args, **kwargs):
278                seen.extend(images_of(messages))
279                clean = [{**m, 'content': 'image delivered'} if isinstance(m.get('content'), list) else m for m in messages]
280                return native(clean, *args, **kwargs)
281            result = {'ok': True, 'text': 'image delivered', 'chars': 15, 'truncated': False, 'ms': 1, 'images': im, 'model_content': [{'type': 'text', 'text': 'image delivered'}, {'type': 'image', 'source': source}]}
282            with patch.object(self.hub, 'call', return_value=result), patch.object(self.svc, 'prepare', side_effect=prepare):
283                code, text = self.post({'strata_mcp': True})
284            self.assertEqual(code, 200)
285            self.assertIn(source, seen)
286            events = [c['strata_mcp'] for c in self.chunks(text) if 'strata_mcp' in c]
287            self.assertEqual(events[-1]['images'], im)
288            answer = ''.join((c['choices'][0]['delta'].get('content', '') for c in self.chunks(text)))
289            self.assertIn('Image received.', answer)