Skip to content
Merged
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
23 changes: 21 additions & 2 deletions .github/workflows/mobile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Test App Store Connect processing status
run: python3 -m unittest discover -s desktop/ox-mobile/tests -p test_testflight_processing.py
- name: Test the App Store Connect helpers
run: python3 -m unittest discover -s desktop/ox-mobile/tests -p 'test_testflight_*.py'
- name: Install Rust for iPhone
run: rustup toolchain install 1.100.0 --profile minimal --target aarch64-apple-ios
- name: Select the TestFlight package
Expand Down Expand Up @@ -397,3 +397,22 @@ jobs:
PROCESSING|NOT_VISIBLE|UNAVAILABLE) echo "::notice::The hourly job will recheck build $number." ;;
*) echo "::error::Unexpected processing state"; exit 1 ;;
esac
# Testers see this under What to Test. A failure here leaves the text
# empty and warns; it never holds back the build.
- name: Set What to Test
continue-on-error: true
timeout-minutes: 12
env:
APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER_ID: ${{ secrets.APPLE_API_ISSUER_ID }}
run: |
set -euo pipefail
umask 077
key="$(mktemp)"
trap 'rm -f "$key"' EXIT
printf '%s\n' "$APPLE_API_KEY_P8" > "$key"
unset APPLE_API_KEY_P8
python3 desktop/ox-mobile/set-testflight-notes.py "$(cat "$RUNNER_TEMP/build-number.txt")" \
"$key" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER_ID" desktop/ox-mobile/testflight-notes.txt \
"$(git log -1 --format=%s)" | tee -a "$GITHUB_STEP_SUMMARY"
27 changes: 25 additions & 2 deletions desktop/ox-mobile/check-testflight-processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def raw_signature(der):
return result


def token(key, key_id, issuer, route, query):
def token(key, key_id, issuer, route, query, method="GET"):
now = int(time.time())
header = {"alg": "ES256", "kid": key_id, "typ": "JWT"}
payload = {
Expand All @@ -81,7 +81,7 @@ def token(key, key_id, issuer, route, query):
"aud": "appstoreconnect-v1",
# App Store Connect matches filters and field selectors in the scope.
# Pagination parameters such as limit are ignored.
"scope": [f"GET {route}?{urllib.parse.urlencode(query, safe='[],')}"],
"scope": [f"{method} {route}" + (f"?{urllib.parse.urlencode(query, safe='[],')}" if query else "")],
}
unsigned = b".".join(
base64url(json.dumps(part, separators=(",", ":")).encode())
Expand Down Expand Up @@ -122,6 +122,29 @@ def get(route, query, bearer):
connection.close()


def send(method, route, body, bearer):
"""POST or PATCH one JSON:API document; return the reply's `data`."""
connection = http.client.HTTPSConnection(API_HOST, timeout=8)
try:
connection.request(
method, route, body=json.dumps(body).encode(),
headers={
"Authorization": f"Bearer {bearer}",
"Accept": "application/json",
"Content-Type": "application/json",
},
)
response = connection.getresponse()
if response.status not in (200, 201):
raise LookupResponseError(response.status)
reply = response.read(MAX_REPLY + 1)
if len(reply) > MAX_REPLY:
raise ValueError("App Store Connect reply is too large")
return json.loads(reply)["data"]
finally:
connection.close()


def build_number(ipa):
with ZipFile(ipa) as archive:
info = archive.getinfo("Payload/OXGPUIProbe.app/Info.plist")
Expand Down
134 changes: 134 additions & 0 deletions desktop/ox-mobile/set-testflight-notes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Set the TestFlight "What to Test" text of an uploaded OX Mobile build.

Usage: set-testflight-notes.py NUMBER KEY KEY_ID ISSUER NOTES_FILE [THIS_BUILD]

NOTES_FILE holds the standing text testers see on every build. THIS_BUILD,
when given, is added as a last paragraph, for example the merged change's
title. The build may still be processing; App Store Connect accepts the text
as soon as it lists the build.
"""

import importlib.util
from pathlib import Path
import signal
import sys
import time

SPEC = importlib.util.spec_from_file_location(
"processing", Path(__file__).resolve().parent / "check-testflight-processing.py"
)
processing = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(processing)

LOCALE = "en-US"
LOCALIZATION_ROUTE = "/v1/betaBuildLocalizations"
LOCALIZATION_FIELDS = {"fields[betaBuildLocalizations]": "locale,whatsNew"}
# App Store Connect's limit for whatsNew.
MAX_TEXT = 4000
LISTED_WITHIN = 600
POLL = 20


def notes(path, this_build=""):
text = Path(path).read_text(encoding="utf-8").strip()
this_build = " ".join(this_build.split())
if this_build:
text += f"\n\nThis build: {this_build}"
if not text:
raise ValueError("The TestFlight notes are empty")
if len(text) > MAX_TEXT:
text = text[: MAX_TEXT - 1].rstrip() + "…"
return text


def listed_build(number, key, key_id, issuer):
"""Wait until App Store Connect lists the build; return its ID."""
with processing.verification("signing the read-only API token"):
bearer = processing.token(key, key_id, issuer, processing.APP_ROUTE, processing.APP_QUERY)
with processing.verification("looking up the OX Mobile app"):
application = processing.app_id(bearer)
query = processing.build_query(application, number)
deadline = time.monotonic() + LISTED_WITHIN
while True:
# A token lives five minutes and the wait can be longer: sign one per poll.
with processing.verification("signing the read-only build API token"):
bearer = processing.token(key, key_id, issuer, processing.BUILD_ROUTE, query)
with processing.verification("looking up the uploaded build"):
state, build = processing.build_processing(number, query, bearer)
if build is not None:
if not processing.RESOURCE_ID.fullmatch(build):
raise ValueError("Unexpected App Store Connect build ID")
return build
if time.monotonic() + POLL >= deadline:
raise TimeoutError("The build was not listed in time")
time.sleep(POLL)


def set_notes(build, text, key, key_id, issuer):
route = f"{processing.BUILD_ROUTE}/{build}/betaBuildLocalizations"
with processing.verification("signing the localization read token"):
bearer = processing.token(key, key_id, issuer, route, LOCALIZATION_FIELDS)
with processing.verification("reading the build's What to Test text"):
rows = processing.get(route, LOCALIZATION_FIELDS, bearer)
existing = next((row for row in rows if row["attributes"].get("locale") == LOCALE), None)
if existing is not None:
localization = existing["id"]
if not processing.RESOURCE_ID.fullmatch(localization):
raise processing.VerificationError("validating the localization ID")
if existing["attributes"].get("whatsNew") == text:
return "unchanged"
target = f"{LOCALIZATION_ROUTE}/{localization}"
with processing.verification("signing the localization update token"):
bearer = processing.token(key, key_id, issuer, target, None, method="PATCH")
with processing.verification("updating the What to Test text"):
processing.send("PATCH", target, {"data": {
"type": "betaBuildLocalizations",
"id": localization,
"attributes": {"whatsNew": text},
}}, bearer)
return "updated"
with processing.verification("signing the localization create token"):
bearer = processing.token(key, key_id, issuer, LOCALIZATION_ROUTE, None, method="POST")
with processing.verification("creating the What to Test text"):
processing.send("POST", LOCALIZATION_ROUTE, {"data": {
"type": "betaBuildLocalizations",
"attributes": {"locale": LOCALE, "whatsNew": text},
"relationships": {"build": {"data": {"type": "builds", "id": build}}},
}}, bearer)
return "created"


def timed_out(*_):
raise TimeoutError("Setting the TestFlight notes timed out")


def main():
args = sys.argv[1:]
if len(args) not in (5, 6):
print(__doc__.strip().splitlines()[2])
return 1
number, key, key_id, issuer, path = args[:5]
if not processing.BUILD_NUMBER.fullmatch(number):
print("Unexpected OX Mobile build number.")
return 1
text = notes(path, args[5] if len(args) == 6 else "")
signal.signal(signal.SIGALRM, timed_out)
signal.alarm(LISTED_WITHIN + 60)
try:
build = listed_build(number, key, key_id, issuer)
outcome = set_notes(build, text, key, key_id, issuer)
except processing.VerificationError as error:
print(f"The What to Test text of build {number} could not be set while {error}.")
return 1
except TimeoutError:
print(f"App Store Connect did not list build {number} in time to set What to Test.")
return 1
finally:
signal.alarm(0)
print(f"What to Test for OX Mobile build {number}: {outcome}.")
return 0


if __name__ == "__main__":
sys.exit(main())
7 changes: 7 additions & 0 deletions desktop/ox-mobile/testflight-notes.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Welcome to OX Mobile: remote control for the coding agents running on your computers.

To start, pair a host: choose Pair a device in OX Desktop (Settings, Remote access), or run `ox host pair` on a server, then scan the QR code in OX Mobile or enter the invitation under Add host.

Please try: open a session and follow a turn, send a message, answer an approval or a question, start a new session, and switch between hosts. Light and dark mode and large text sizes are worth a look too.

Something wrong or confusing? Take a screenshot and send it as beta feedback from TestFlight.
110 changes: 110 additions & 0 deletions desktop/ox-mobile/tests/test_testflight_notes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import base64
import importlib.util
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch


SPEC = importlib.util.spec_from_file_location(
"notes", Path(__file__).resolve().parents[1] / "set-testflight-notes.py"
)
notes = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(notes)
processing = notes.processing
STANDING = Path(__file__).resolve().parents[1] / "testflight-notes.txt"


def fake_token(key, key_id, issuer, route, query, method="GET"):
return json.dumps([method, route, query])


class TestFlightNotesTests(unittest.TestCase):
def test_standing_text_fits_and_names_this_build(self):
text = notes.notes(STANDING, "Keep OX Mobile alive when a\nhost closes (#341)")
self.assertTrue(text.startswith("Welcome to OX Mobile"))
self.assertTrue(text.endswith("\n\nThis build: Keep OX Mobile alive when a host closes (#341)"))
self.assertLessEqual(len(text), notes.MAX_TEXT)
self.assertEqual(notes.notes(STANDING), STANDING.read_text().strip())

def test_overlong_text_is_cut_to_the_limit(self):
with tempfile.NamedTemporaryFile("w", suffix=".txt") as file:
file.write("x" * 5000)
file.flush()
text = notes.notes(file.name)
self.assertEqual(len(text), notes.MAX_TEXT)
self.assertTrue(text.endswith("…"))

def test_creates_the_localization_when_none_exists(self):
with (
patch.object(processing, "token", side_effect=fake_token),
patch.object(processing, "get", return_value=[]) as get,
patch.object(processing, "send", return_value={}) as send,
):
self.assertEqual(notes.set_notes("fixture-build", "Hello", "k", "i", "s"), "created")
get.assert_called_once_with(
"/v1/builds/fixture-build/betaBuildLocalizations", notes.LOCALIZATION_FIELDS,
json.dumps(["GET", "/v1/builds/fixture-build/betaBuildLocalizations", notes.LOCALIZATION_FIELDS]),
)
method, route, body, bearer = send.call_args.args
self.assertEqual((method, route), ("POST", "/v1/betaBuildLocalizations"))
self.assertEqual(json.loads(bearer), ["POST", "/v1/betaBuildLocalizations", None])
self.assertEqual(body["data"]["attributes"], {"locale": "en-US", "whatsNew": "Hello"})
self.assertEqual(body["data"]["relationships"]["build"]["data"], {"type": "builds", "id": "fixture-build"})

def test_updates_an_existing_localization_and_skips_a_matching_one(self):
row = {"id": "fixture-loc", "attributes": {"locale": "en-US", "whatsNew": None}}
with (
patch.object(processing, "token", side_effect=fake_token),
patch.object(processing, "get", return_value=[row]),
patch.object(processing, "send", return_value={}) as send,
):
self.assertEqual(notes.set_notes("fixture-build", "Hello", "k", "i", "s"), "updated")
method, route, body, bearer = send.call_args.args
self.assertEqual((method, route), ("PATCH", "/v1/betaBuildLocalizations/fixture-loc"))
self.assertEqual(json.loads(bearer)[0], "PATCH")
self.assertEqual(body["data"], {
"type": "betaBuildLocalizations", "id": "fixture-loc", "attributes": {"whatsNew": "Hello"},
})
row["attributes"]["whatsNew"] = "Hello"
send.reset_mock()
self.assertEqual(notes.set_notes("fixture-build", "Hello", "k", "i", "s"), "unchanged")
send.assert_not_called()

def test_waits_for_the_build_to_be_listed(self):
states = iter([("NOT_VISIBLE", None), ("PROCESSING", "fixture-build")])
with (
patch.object(processing, "token", side_effect=fake_token) as token,
patch.object(processing, "app_id", return_value="fixture-app"),
patch.object(processing, "build_processing", side_effect=lambda *_: next(states)),
patch.object(notes.time, "sleep") as sleep,
):
self.assertEqual(notes.listed_build("200.2", "k", "i", "s"), "fixture-build")
sleep.assert_called_once_with(notes.POLL)
# One app token, then a fresh build token for each of the two polls.
self.assertEqual([c.args[3] for c in token.call_args_list], ["/v1/apps", "/v1/builds", "/v1/builds"])

def test_failures_are_reported_without_detail(self):
with (
patch.object(notes.sys, "argv", ["set", "200.2", "k", "i", "s", str(STANDING)]),
patch.object(notes, "listed_build", side_effect=processing.VerificationError("looking up the uploaded build")),
patch("builtins.print") as printed,
):
self.assertEqual(notes.main(), 1)
printed.assert_called_once_with(
"The What to Test text of build 200.2 could not be set while looking up the uploaded build."
)

def test_write_token_scope_has_no_query(self):
with tempfile.TemporaryDirectory() as folder:
key = Path(folder) / "key.p8"
subprocess.run(["openssl", "ecparam", "-name", "prime256v1", "-genkey", "-noout", "-out", key],
check=True, capture_output=True)
payload = processing.token(key, "i", "s", "/v1/betaBuildLocalizations", None, method="POST").split(".")[1]
claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
self.assertEqual(claims["scope"], ["POST /v1/betaBuildLocalizations"])

if __name__ == "__main__":
unittest.main()
Loading