"""A paired iMessage turn can text back once, even when Photon replays it, and the chat shows the assistant typing only while a text's turn runs.""" import base64 import json from pathlib import Path import selectors import shutil import subprocess import sys import threading import unittest from _imagegen_support import png from harness import Albedo, Provider, error, exclusive, python, text, wait_until FIXTURE = Path(__file__).parent.resolve() / "fixtures" / "photon" RECIPIENT = "+15550101111" ASSIGNED_NUMBER = "+15550101122" @exclusive class PhotonTests(unittest.TestCase): def respond(self, request): last = request["input"][-1] if last.get("type") != "function_call_output": # The first answer threads under its text; the second does not. for guid, thread in (("first-text", True), ("offline-text", False)): if f"iMessage [{guid}]" in json.dumps(last): return python( "from pathlib import Path\n" + ( "assert await photon.react('first-text', '🎉') == 'reaction-guid'\n" if guid == "first-text" else "" ) + "try:\n" " await photon.react('first-text', '👍')\n" "except PhotonError:\n" " pass\n" "else:\n" " raise AssertionError('duplicate Tapback was accepted')\n" + f"receipt = await photon.reply({guid!r}, 'answer to {guid}', thread={thread})\n" "assert receipt == 'sent-guid', receipt\n" f"assert await photon.reply({guid!r}, 'answer to {guid}') == receipt\n" f"Path({guid!r}).write_text(receipt)\nawait end_turn()" ) return text("done") def calls(self): log = self.app.root / "calls" return ( [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] ) def publish(self, *events): self.events.extend(events) path = self.app.root / "events" temporary = path.with_suffix(".new") temporary.write_text(json.dumps(self.events)) temporary.replace(path) def start_provider_fixture(self, app): helper = shutil.which("albedo-photon") assert helper is not None, "the development shell must provide albedo-photon" server = subprocess.Popen( ["node", FIXTURE / "server.cjs", Path(helper).resolve(), app.root], stdout=subprocess.PIPE, text=True, ) output = server.stdout assert output is not None self.addCleanup(output.close) self.addCleanup(server.wait) self.addCleanup(server.terminate) # The fixture prints both endpoints once both listen, in about 0.1 s. # A wait on the pipe sees a line written before the deadline even # when this thread runs again only after it, and ends at once if the # fixture dies; the deadline only bounds a hang, and CI once stalled # three fixtures past 10 s together. with selectors.DefaultSelector() as pipe: pipe.register(output, selectors.EVENT_READ) if not pipe.select(30): raise AssertionError("fixture did not bind in 30 s") line = output.readline() if not line: raise AssertionError(f"fixture exited with {server.wait()} before binding") bound = json.loads(line) app.env.update( SSL_CERT_FILE=str(FIXTURE / "localhost.pem"), NIX_SSL_CERT_FILE=str(FIXTURE / "localhost.pem"), ) return bound["address"], bound["cloud"] def test_text_and_resume(self): provider = Provider(self.respond) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as self.app: session = self.app.session() self.events = [] self.publish({"guid": "old", "text": "before pairing"}) address, _ = self.start_provider_fixture(self.app) token_file = self.app.root / "photon-token" token_file.write_text("local-fixture-token\n") token_file.chmod(0o600) def pair(app): app.write_extensions({"enabled": {"photon": True}}) app.env.update( ALBEDO_PHOTON_ADDRESS=address, ALBEDO_PHOTON_TOKEN_FILE=str(token_file), ALBEDO_PHOTON_RECIPIENT=RECIPIENT, ALBEDO_PHOTON_SESSION_ID=session, ) self.app.restart(prepare=pair) wait_until( lambda: any(c.get("after") == 1 for c in self.calls()), 30, "no initial Photon checkpoint", ) self.publish( {"guid": "echo", "text": "outgoing", "outgoing": True}, {"guid": "first-text", "text": "hello"}, ) self.wait_reply("first-text") self.app.restart( prepare=lambda _: self.publish( {"guid": "offline-text", "text": "hello again"} ) ) self.wait_reply("offline-text") sends = [c for c in self.calls() if c["kind"] == "send"] self.assertEqual( [c["text"] for c in sends], ["answer to first-text", "answer to offline-text"], ) self.assertEqual({c["chatGuid"] for c in sends}, {f"any;-;{RECIPIENT}"}) self.assertEqual( [c.get("replyTo") for c in sends], [{"messageGuid": "first-text"}, None], ) reactions = [c for c in self.calls() if c["kind"] == "react"] self.assertEqual( len(reactions), 1, "Tapback duplicated or missing across restart" ) self.assertEqual( reactions[0]["target"], {"chatGuid": f"any;-;{RECIPIENT}", "messageGuid": "first-text"}, ) self.assertEqual(reactions[0]["reaction"], {"kind": 6, "emoji": "🎉"}) self.assertTrue(reactions[0]["isSet"]) prompts = json.dumps(provider.requests) self.assertNotIn("iMessage [old]", prompts) self.assertNotIn("iMessage [echo]", prompts) def test_spectrum_setup_and_automatic_replies(self): local_turn_started = threading.Event() release_local_turn = threading.Event() release_answer = threading.Event() release_crash = threading.Event() release_disconnect = threading.Event() earlier_started = threading.Event() release_earlier = threading.Event() explicit_mark = [] def prepare(app): self.app = app self.events = [] self.publish({"guid": "previous", "text": "before managed pairing"}) address, cloud = self.start_provider_fixture(app) app.env.update( PHOTON_DASHBOARD_HOST=cloud, PHOTON_SPECTRUM_HOST=cloud, SPECTRUM_IMESSAGE_ADDRESS=address, PHOTON_PROJECT_ID="fixture-project", PHOTON_PROJECT_SECRET="fixture-secret", ) def respond(request): last = request["input"][-1] if last.get("type") == "function_call_output": # Typing stops once the explicit reply is sent, while the # turn that sent it still runs. if explicit_mark: self.wait_typing(explicit_mark[0], [True, False]) return text("final after explicit reply") prompt = json.dumps(last) if "send an explicit response" in prompt: return python( "assert await photon.react('explicit', '👍') == 'reaction-guid'\n" "try:\n" " await photon.react('first', '🎉')\n" "except PhotonError:\n" " pass\n" "else:\n" " raise AssertionError('Tapback cooldown was bypassed')\n" "assert await photon.reply('explicit', '*explicit* ~~old~~ response ``a ` *literal*``')" " == 'sent-guid'" ) if "hold this local turn" in prompt: local_turn_started.set() if not release_local_turn.wait(25): raise TimeoutError("local turn was never released") return text("local turn finished") if "first managed text" in prompt: if not release_answer.wait(20): raise TimeoutError( "read receipt or typing missing while the model was answering" ) return text("👋 **first** normal response") if "answer before a quiet turn" in prompt: earlier_started.set() if not release_earlier.wait(20): raise TimeoutError("the quiet text was never accepted") return text("earlier answer") if "fail this turn" in prompt: return error(400, "provider refused") if "hold until the crash" in prompt: release_crash.wait(30) return text("answer after the crash") if "hold until disconnect" in prompt: release_disconnect.wait(30) return text("answer after disconnect") if "new text during restart" in prompt: return text("second normal response") return text("answer to local prompt") provider = Provider(respond) self.addCleanup(provider.close) with Albedo(provider, protocol="responses", prepare=prepare): session = self.app.session() other = self.app.session() setup = self.app.cli( "photon", "setup", "--phone", RECIPIENT, "--session", session ) self.assertIn(ASSIGNED_NUMBER, setup) self.assertNotIn("fixture-secret", setup) pairing_file = self.app.home / "photon.json" self.assertEqual(pairing_file.stat().st_mode & 0o777, 0o600) with self.app.api("/extensions/photon/status") as response: self.assertEqual( json.load(response), {"session": session, "ready": True} ) # A new helper tells Photon the current typing state. self.wait_typing(0, [False]) self.assertFalse(any(c["kind"] == "read" for c in self.calls())) mark = len(self.calls()) self.app.prompt(session, "hold this local turn").close() self.assertTrue(local_turn_started.wait(10)) try: self.publish({"guid": "first", "text": "first managed text"}) wait_until( lambda: sum(c.get("after") == 2 for c in self.calls()) >= 2, 15, "Photon did not checkpoint the queued text", ) self.assertFalse(any(c["kind"] == "read" for c in self.calls())) # A local turn shows no typing, even with a text waiting. self.assertEqual(self.typing_since(mark), []) finally: release_local_turn.set() try: wait_until( lambda: ( any(c["kind"] == "read" for c in self.calls()) and self.typing_since(mark) == [True] ), 15, "missing read receipt or typing", ) finally: release_answer.set() self.wait_send("👋 first normal response") self.app.idle(session) self.wait_typing(mark, [True, False]) kinds = [ c["kind"] for c in self.calls()[mark:] if c["kind"] in ("typing", "send") ] self.assertEqual(kinds, ["typing", "send", "typing"]) self.assertEqual(self.photon_captions(session), ["first managed text"]) credentials_file = self.app.root / "project.env" credentials_file.write_text( "PHOTON_PROJECT_ID=fixture-project\n" 'PHOTON_PROJECT_SECRET="fixture-secret"\n' ) credentials_file.chmod(0o600) self.app.env["PHOTON_PROJECT_SECRET"] = "wrong-fixture-secret" imported = self.app.cli( "photon", "setup", "--phone", RECIPIENT, "--session", session, "--env-file", str(credentials_file), ) del self.app.env["PHOTON_PROJECT_ID"] del self.app.env["PHOTON_PROJECT_SECRET"] self.assertIn(ASSIGNED_NUMBER, imported) self.assertNotIn("fixture-secret", imported) mark = len(self.calls()) for session_id in (session, other): # A local turn can even resemble a Photon inbox event. self.app.prompt(session_id, "iMessage [first] manual request").close() self.app.idle(session_id) self.assertEqual(self.typing_since(mark), []) explicit_mark.append(len(self.calls())) self.publish( {"guid": "echo", "text": "managed outgoing echo", "outgoing": True}, { "guid": "stranger", "text": "stranger text", "sender": ASSIGNED_NUMBER, }, {"guid": "group", "text": "group text", "chatGuid": "any;+;group"}, {"guid": "explicit", "text": "send an explicit response"}, ) self.wait_send("explicit old response ``a ` *literal*``") self.app.idle(session) self.assertEqual(self.typing_since(explicit_mark[0]), [True, False]) # A turn that fails sends nothing and stops typing. mark = len(self.calls()) self.publish({"guid": "failing", "text": "fail this turn"}) self.wait_typing(mark, [True, False]) self.app.idle(session) # The earlier text's answer still waits when the next text's turn # starts at once and ends with nothing to send. Typing stays on # until the earlier answer is sent. mark = len(self.calls()) self.publish({"guid": "earlier", "text": "answer before a quiet turn"}) self.assertTrue(earlier_started.wait(10)) try: self.publish({"guid": "quiet", "text": "fail this turn"}) accepted = len(self.events) wait_until( lambda: any(c.get("after") == accepted for c in self.calls()), 15, "Photon did not checkpoint the quiet text", ) finally: release_earlier.set() self.wait_send("earlier answer") self.app.idle(session) self.wait_typing(mark, [True, False]) kinds = [ c["kind"] for c in self.calls()[mark:] if c["kind"] in ("typing", "send") ] self.assertEqual(kinds, ["typing", "send", "typing"]) # The daemon dies while the chat shows typing. The helper that # replaces its helper clears what it left. mark = len(self.calls()) self.publish({"guid": "crashed", "text": "hold until the crash"}) self.wait_typing(mark, [True]) mark = len(self.calls()) self.app.restart(crash=True, prepare=lambda _: release_crash.set()) self.wait_typing(mark, [False]) self.app.idle(session) mark = len(self.calls()) self.app.restart( prepare=lambda _: self.publish( {"guid": "first", "text": "replayed copy of the first text"}, {"guid": "offline", "text": "new text during restart"}, ) ) self.wait_send("second normal response") self.app.idle(session) wait_until( lambda: ( self.typing_since(mark)[-1:] == [False] and True in self.typing_since(mark) ), 30, "typing did not follow the turn after the restart", ) sends = [c for c in self.calls() if c["kind"] == "send"] self.assertEqual( [c["text"] for c in sends], [ "👋 first normal response", "explicit old response ``a ` *literal*``", "earlier answer", "second normal response", ], ) self.assertEqual({c["chatGuid"] for c in sends}, {f"any;-;{RECIPIENT}"}) reactions = [c for c in self.calls() if c["kind"] == "react"] self.assertEqual(len(reactions), 1) self.assertEqual(reactions[0]["target"]["messageGuid"], "explicit") self.assertEqual(reactions[0]["reaction"], {"kind": 1}) self.assertTrue(all(not c.get("replyTo") for c in sends)) self.assertEqual( [ [{"start": 0, **part} for part in c.get("formatting", [])] for c in sends ], [ [{"type": "bold", "start": 3, "length": 5}], [ {"type": "italic", "start": 0, "length": 8}, {"type": "strikethrough", "start": 9, "length": 3}, ], [], [], ], ) self.assertEqual( sum( c.get("route") == "POST /projects/fixture-project/users/" for c in self.calls() ), 1, ) prompts = json.dumps(provider.requests) for ignored in ( "before managed pairing", "managed outgoing echo", "stranger text", "group text", "replayed copy of the first text", ): self.assertNotIn(ignored, prompts) status = self.app.cli("photon", "status") self.assertIn(ASSIGNED_NUMBER, status) self.assertNotIn("fixture-secret", status) # Removing the pairing while typing is on disconnects the helper, # which flushes typing off before closing its Photon client. mark = len(self.calls()) self.publish({"guid": "disconnect", "text": "hold until disconnect"}) self.wait_typing(mark, [True]) mark = len(self.calls()) try: pairing_file.unlink() self.wait_typing(mark, [False]) finally: release_disconnect.set() self.app.idle(session) def test_heic_photo_reaches_session(self): photo = (FIXTURE / "rotated.heic").read_bytes() attachment = { "guid": "fixture-photo", "mimeType": "image/heic", "totalBytes": len(photo), "transferState": 5, } def respond(request): last = request["input"][-1] if last.get("type") == "function_call_output": return text("done") parts = last["content"] if isinstance(parts, str): return text("missing photo") images = [p["image_url"] for p in parts if p["type"] == "input_image"] if len(images) != 1 or not images[0].startswith("data:image/jpeg;base64,"): return text("missing JPEG") if not any("Where is the cat?" in part.get("text", "") for part in parts): return text("missing caption") if sys.platform == "linux" and "resend" not in json.dumps(parts): return text("missing HEIC recovery note") return python( "import base64\n" f"assert await files.image() == base64.b64decode({images[0].split(',')[1]!r})\n" "from pathlib import Path\n" "Path('jpeg-retrieved').touch()" ) def prepare(app): self.app = app self.events = [] self.publish() (app.root / "photo").write_bytes(photo) address, cloud = self.start_provider_fixture(app) app.env.update( PHOTON_DASHBOARD_HOST=cloud, PHOTON_SPECTRUM_HOST=cloud, SPECTRUM_IMESSAGE_ADDRESS=address, PHOTON_PROJECT_ID="fixture-project", PHOTON_PROJECT_SECRET="fixture-secret", ) provider = Provider(respond) self.addCleanup(provider.close) with Albedo(provider, protocol="responses", prepare=prepare): session = self.app.session() self.app.cli("photon", "setup", "--phone", RECIPIENT, "--session", session) self.app.restart( prepare=lambda _: self.publish( { "guid": "wrong-sender", "sender": ASSIGNED_NUMBER, "attachments": [attachment], }, { "guid": "heic", "placeholderOnly": True, "text": "Where is the cat?\ufffc", "attachments": [dict(attachment, guid="truncated"), attachment], }, ) ) wait_until( lambda: (self.app.workspace / "jpeg-retrieved").exists(), 30, "could not retrieve the converted Photon upload", ) self.assertIn("Where is the cat?", "\n".join(self.photon_captions(session))) self.assertEqual( [c["guid"] for c in self.calls() if c["kind"] == "download"], ["truncated", "fixture-photo"], ) def test_pending_photo_waits_for_the_transfer(self): photo = png(200, 200, noise=True) attachment = { "guid": "fixture-photo", "mimeType": "image/png", "totalBytes": len(photo), "transferState": 0, } data_url = "data:image/png;base64," + base64.b64encode(photo).decode() def respond(request): parts = request["input"][-1]["content"] images = [ part["image_url"] for part in parts if part["type"] == "input_image" ] return text("photo only" if images == [data_url] else "missing image") def prepare(app): self.app = app self.events = [] (app.root / "transfer").write_text(json.dumps("pending")) self.publish() (app.root / "photo").write_bytes(photo) address, cloud = self.start_provider_fixture(app) app.env.update( PHOTON_DASHBOARD_HOST=cloud, PHOTON_SPECTRUM_HOST=cloud, SPECTRUM_IMESSAGE_ADDRESS=address, PHOTON_PROJECT_ID="fixture-project", PHOTON_PROJECT_SECRET="fixture-secret", ) provider = Provider(respond) self.addCleanup(provider.close) with Albedo(provider, protocol="responses", prepare=prepare): session = self.app.session() self.app.cli("photon", "setup", "--phone", RECIPIENT, "--session", session) self.publish({"guid": "pending-photo", "attachments": [attachment]}) wait_until( lambda: any(c["kind"] == "info" for c in self.calls()), 15, "the helper did not wait for the photo transfer", ) self.assertFalse( any(c["kind"] == "download" for c in self.calls()), "the helper downloaded a photo whose transfer was still pending", ) (self.app.root / "transfer").write_text(json.dumps("finished")) self.wait_send("photo only") self.assertEqual(self.photon_captions(session), [""]) self.assertEqual( [c["guid"] for c in self.calls() if c["kind"] == "download"], ["fixture-photo"], ) def photon_captions(self, session): with self.app.api(f"/sessions/{session}/history") as response: items = json.load(response)["items"] return [ part["text"] for item in items if item["kind"] == "user" and (item["mail"] or {}).get("sender_label") == "photon" for part in item["content"] if part.get("kind") == "text" ] def wait_send(self, text): wait_until( lambda: any( c["kind"] == "send" and c["text"] == text for c in self.calls() ), 30, f"no iMessage with text {text!r}", ) def typing_since(self, mark): """The typing states Photon was told after the first `mark` calls.""" return [c["on"] for c in self.calls()[mark:] if c["kind"] == "typing"] def wait_typing(self, mark, expected): wait_until( lambda: self.typing_since(mark) == expected, 30, f"typing after call {mark} was not {expected}", ) def wait_reply(self, guid): wait_until( lambda: (self.app.workspace / guid).exists(), 45, f"no iMessage reply for {guid}", )