"""No-network contracts for running WeCom and Matrix in one gateway with shared output hooks.""" import asyncio import contextlib from dataclasses import dataclass import hashlib import importlib.util import io import json import os from pathlib import Path import sys import tempfile import time import unittest from unittest.mock import patch ROOT = Path(__file__).resolve().parents[2] RUNTIME = ROOT / 'cloud/onboarding/runtime' REFERENCE = 'https://work.weixin.qq.com/api/doc/90000/90136/91770' FAKE_DELIVERABLE = 'https://s3.fmode.cn/deliverables/agent/invented-report.pdf' def load(name, path, package=False): spec = importlib.util.spec_from_file_location( name, path, submodule_search_locations=[str(path.parent)] if package else None) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module class InjectPluginContracts(unittest.TestCase): def setUp(self): self.m = load('dual_contract_inject', RUNTIME / 'plugins/plugin-deliverable-inject/__init__.py', True) self.m._load_state = lambda sid: {} self.m._current_turn_id = lambda sid: 'turn-1' self.addCleanup(lambda: [sys.modules.pop(n, None) for n in list(sys.modules) if n.startswith('dual_contract_inject')]) env = patch.dict(os.environ, {'PLUGIN_DELIVERABLE_INJECT_DISABLE': '0', 'PLUGIN_FMODE_STRIP_MEDIA_DISABLE': '0'}) env.start() self.addCleanup(env.stop) def run_hook(self, text, platform): out = self.m._on_transform_llm_output(text, 'session-a', 'turn-1', platform=platform) return text if out is None else out def test_reference_url_kept_without_deliverables_on_both_platforms(self): for platform in ('matrix', 'wecom'): with self.subTest(platform=platform): self.assertIn(REFERENCE, self.run_hook('参考官方文档:' + REFERENCE, platform)) def test_fabricated_deliverable_url_still_removed(self): for platform in ('matrix', 'wecom'): with self.subTest(platform=platform): self.assertNotIn(FAKE_DELIVERABLE, self.run_hook('下载:' + FAKE_DELIVERABLE, platform)) def test_wecom_media_references_survive_shared_layer(self): for line in ('MEDIA:/opt/data/work/output.pdf', 'MEDIA:https://example.com/picture.png'): with self.subTest(line=line): self.assertIn(line, self.run_hook('交付文件\n' + line, 'wecom')) def test_matrix_local_media_anchor_kept(self): self.assertIn('MEDIA:/opt/data/work/output.pdf', self.run_hook('交付文件\nMEDIA:/opt/data/work/output.pdf', 'matrix')) def test_platform_enum_value_is_understood(self): class Platform: value = 'wecom' out = self.m._on_transform_llm_output('图\nMEDIA:https://example.com/a.png', 'session-a', 'turn-1', platform=Platform()) self.assertIn('MEDIA:https://example.com/a.png', out or '图\nMEDIA:https://example.com/a.png') class ShellHookContracts(unittest.TestCase): def setUp(self): self.m = load('dual_contract_hook', RUNTIME / 'scripts/fmode-deliverable-hook.py') self.m.log = lambda text: None def test_reference_url_kept_and_fabricated_deliverable_removed(self): cleaned = self.m._scrub_fake_urls('参考:%s\n下载:%s' % (REFERENCE, FAKE_DELIVERABLE), set()) self.assertIn(REFERENCE, cleaned) self.assertNotIn(FAKE_DELIVERABLE, cleaned) def test_existing_local_media_line_is_kept_intact(self): real = '/opt/data/work/output.pdf' with patch.object(self.m.os.path, 'isfile', side_effect=lambda p: p == real): cleaned = self.m._scrub_local_paths('交付文件\nMEDIA:%s\n本地路径:%s' % (real, real)) self.assertIn('MEDIA:' + real, cleaned) self.assertNotIn('本地路径', cleaned) def test_placeholder_media_line_still_removed(self): with patch.object(self.m.os.path, 'isfile', return_value=False): cleaned = self.m._scrub_local_paths('交付\nMEDIA:(本地工作目录)\nMEDIA:/opt/data/missing.pdf') self.assertNotIn('MEDIA:', cleaned) def test_same_turn_same_name_different_content_both_uploaded(self): with tempfile.TemporaryDirectory() as tmp: a, b, c = Path(tmp, 'a/report.pdf'), Path(tmp, 'b/report.pdf'), Path(tmp, 'c/report.pdf') for p, data, mtime in ((a, b'AAAA', 100), (b, b'BBBB', 200), (c, b'BBBB', 300)): p.parent.mkdir() p.write_bytes(data) os.utime(p, (mtime, mtime)) state = {'queued': [{'path': str(p), 'turn_id': 'turn-1', 'ts': time.time()} for p in (a, b, c)], 'pushed': []} uploaded = [] self.m.load_round = lambda sid: {'turn_id': 'turn-1'} self.m.load_state = lambda sid: state self.m.save_state = lambda sid, st: None self.m._denied = lambda path: None self.m.LEDGER = Path(tmp, 'ledger.jsonl') def upload(todo, title, summary): uploaded.extend(q['path'] for q in todo) return [{'path': q['path'], 'ok': True, 'url': 'https://s3.fmode.cn/deliverables/%d.pdf' % i} for i, q in enumerate(todo)] self.m.upload_and_register = upload with contextlib.redirect_stdout(io.StringIO()): self.m.handle_transform_llm_output({'session_id': 'session-a', 'response_text': '完成'}) self.assertEqual(sorted(uploaded), sorted([str(a), str(c)])) @dataclass class Source: platform: str chat_id: str thread_id: str chat_type: str = 'dm' @dataclass class Event: source: Source text: str media_urls: list media_types: list class MediaMergeContracts(unittest.TestCase): def setUp(self): self.m = load('dual_contract_merge', RUNTIME / 'plugins/plugin-media-text-merge/__init__.py') self.m._log = lambda message: None self.m._arm_timer = lambda key, gateway: None self.m._PENDING.clear() self.addCleanup(self.m._PENDING.clear) def dispatch(self, platform, thread, text, media=()): return self.m._on_pre_gateway_dispatch( Event(Source(platform, 'same-chat', thread), text, list(media), ['image/png'] * len(media))) def test_text_in_other_thread_is_not_merged_into_image(self): with patch.dict(os.environ, {'MEDIA_TEXT_MERGE_SECONDS': '2.5'}): self.assertEqual(self.dispatch('matrix', 'thread-a', 'A', ['https://s3.fmode.cn/a.png'])['action'], 'skip') self.assertIsNone(self.dispatch('matrix', 'thread-b', 'B')) self.assertEqual(len(self.m._PENDING), 1) merged = self.m._merged_event(next(iter(self.m._PENDING.values()))) self.assertNotIn('B', merged.text) def test_same_chat_id_on_other_platform_is_not_merged(self): with patch.dict(os.environ, {'MEDIA_TEXT_MERGE_SECONDS': '2.5'}): self.dispatch('matrix', 'thread-a', 'A', ['https://s3.fmode.cn/a.png']) self.assertIsNone(self.dispatch('wecom', 'thread-a', 'B')) def test_same_thread_text_still_merged(self): with patch.dict(os.environ, {'MEDIA_TEXT_MERGE_SECONDS': '2.5'}): self.dispatch('matrix', 'thread-a', '', ['https://s3.fmode.cn/a.png']) self.assertEqual(self.dispatch('matrix', 'thread-a', '说明')['action'], 'skip') merged = self.m._merged_event(next(iter(self.m._PENDING.values()))) self.assertEqual(merged.text, '说明') def test_flush_releases_the_buffer_it_was_armed_for(self): released = [] class Gateway: def handle_message(self, event): released.append(event.source.thread_id) with patch.dict(os.environ, {'MEDIA_TEXT_MERGE_SECONDS': '2.5'}): self.dispatch('matrix', 'thread-a', 'A', ['https://s3.fmode.cn/a.png']) self.dispatch('matrix', 'thread-b', 'B', ['https://s3.fmode.cn/b.png']) for key in list(self.m._PENDING): asyncio.run(self.m._flush(key, Gateway())) self.assertEqual(sorted(released), ['thread-a', 'thread-b']) class OutboundContracts(unittest.TestCase): def setUp(self): self.m = load('dual_contract_outbound', RUNTIME / 'plugins/plugin-matrix-outbound-s3/__init__.py') self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.dir = Path(self.temp.name) self.m._STATE_DIR = str(self.dir) self.m._INDEX_CACHE = {'sig': None, 'map': {}} def write(self, session, name, data, url, ts, with_digest=True): path = self.dir / session / name path.parent.mkdir(exist_ok=True) path.write_bytes(data) record = {'path': str(path), 'url': url, 'ts': ts, 'turn_id': 'turn-' + session, 'did': 'batch-1'} if with_digest: record['sha256'] = hashlib.sha256(data).hexdigest() (self.dir / (session + '.json')).write_text(json.dumps({'pushed': [record]})) return path def test_same_name_same_size_resolves_by_content(self): now = time.time() self.write('a', 'report.pdf', b'AAAA', 'https://s3.fmode.cn/deliverables/a.pdf', now - 2) self.write('b', 'report.pdf', b'BBBB', 'https://s3.fmode.cn/deliverables/b.pdf', now - 1) digest = hashlib.sha256(b'AAAA').hexdigest() self.assertEqual(self.m._preuploaded_lookup('report.pdf', 4, digest=digest, wait=False), 'https://s3.fmode.cn/deliverables/a.pdf') def test_legacy_record_without_digest_verified_from_disk(self): now = time.time() self.write('a', 'report.pdf', b'AAAA', 'https://s3.fmode.cn/deliverables/a.pdf', now - 2, with_digest=False) self.write('b', 'report.pdf', b'BBBB', 'https://s3.fmode.cn/deliverables/b.pdf', now - 1, with_digest=False) self.assertEqual(self.m._preuploaded_lookup('report.pdf', 4, digest=hashlib.sha256(b'AAAA').hexdigest(), wait=False), 'https://s3.fmode.cn/deliverables/a.pdf') def test_unknown_content_gets_no_url(self): self.write('b', 'report.pdf', b'BBBB', 'https://s3.fmode.cn/deliverables/b.pdf', time.time()) self.assertEqual(self.m._preuploaded_lookup('report.pdf', 4, digest=hashlib.sha256(b'CCCC').hexdigest(), wait=False), '') def test_file_event_matches_app_card_contract(self): content = self.m._file_card_content('report.pdf', 'https://s3.fmode.cn/deliverables/a.pdf', 'application/pdf', 4, None) self.assertEqual(content['msgtype'], 'm.text') self.assertEqual(content['body'], 'report.pdf\nhttps://s3.fmode.cn/deliverables/a.pdf') self.assertEqual(content['com.fmode.file_card'], { 'name': 'report.pdf', 'url': 'https://s3.fmode.cn/deliverables/a.pdf', 'size': 4, 'mimetype': 'application/pdf', 'isImage': False}) self.assertEqual(content['com.fmode.cloud_url'], 'https://s3.fmode.cn/deliverables/a.pdf') self.assertNotIn('url', content) image = self.m._file_card_content('a.png', 'https://s3.fmode.cn/a.png', 'image/png', 9, '说明') self.assertTrue(image['com.fmode.file_card']['isImage']) self.assertEqual(image['body'], '说明\nhttps://s3.fmode.cn/a.png') def test_upload_and_send_keeps_thread_relation(self): sent = [] class SendResult: def __init__(self, success=True, error=None): self.success, self.error = success, error class MatrixAdapter: def _media_too_large(self, n): return SendResult(False, 'too-large') def _apply_relation_metadata(self, content, reply_to=None, metadata=None): content['m.relates_to'] = {'rel_type': 'm.thread', 'event_id': metadata['thread_id']} async def _send_content_event(self, room_id, content): sent.append(content) return SendResult() MatrixAdapter.__module__ = 'dual_contract_outbound_fixture' sys.modules['dual_contract_outbound_fixture'] = type(sys)('fixture') sys.modules['dual_contract_outbound_fixture'].SendResult = SendResult self.addCleanup(sys.modules.pop, 'dual_contract_outbound_fixture', None) self.m._candidate_classes = lambda: iter([('subclasses', MatrixAdapter)]) self.m._PATCHED_CLASSES.clear() self.assertEqual(self.m._install_patch(), 1) self.write('a', 'report.pdf', b'AAAA', 'https://s3.fmode.cn/deliverables/a.pdf', time.time()) result = asyncio.run(MatrixAdapter()._upload_and_send( '!room', b'AAAA', 'report.pdf', 'application/pdf', 'm.file', metadata={'thread_id': '$root'})) self.assertTrue(result.success) self.assertEqual(sent[0]['msgtype'], 'm.text') self.assertEqual(sent[0]['m.relates_to'], {'rel_type': 'm.thread', 'event_id': '$root'}) if __name__ == '__main__': unittest.main()