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
6 changes: 4 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ jobs:
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.13"
- name: Install worker dependency
run: python -m pip install 'pymobiledevice3==9.31.0'
- name: Install compatible worker dependencies
run: python -m pip install 'pymobiledevice3==9.31.0' 'pmd-pytcp>=0.0.4,<0.1.0'
- name: Check installed dependencies
run: python -m pip check
- name: Run worker tests
env:
PYTHONDONTWRITEBYTECODE: "1"
Expand Down
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

All notable changes to GeoShift are documented here.

## Unreleased

### Fixed

- Fresh backend installs no longer resolve `pmd-pytcp` 0.1.0 or newer, whose
async API breaks pymobiledevice3 9.31.0's userspace tunnel and floods the log
with `asyncio.queues.QueueFull` ([#4](https://github.com/Lemelson/GeoShift/issues/4)).
Installation, test, and CI commands now pin `pmd-pytcp>=0.0.4,<0.1.0`.

### Added

- The worker detects an incompatible `pmd-pytcp` before opening a tunnel, logs
the repair command once a minute instead of looping on `QueueFull`, and the
app shows a dedicated status message.

## 1.5.2 — 2026-07-21

### Added
Expand Down
11 changes: 9 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,21 @@ Use GitHub Security Advisories, not a public issue, for security or privacy bugs

```bash
brew install uv
uv tool install --python 3.13 'pymobiledevice3==9.31.0'
uv tool install --python 3.13 --with 'pmd-pytcp>=0.0.4,<0.1.0' \
'pymobiledevice3==9.31.0'
swift test
PYTHONDONTWRITEBYTECODE=1 uv run --with 'pymobiledevice3==9.31.0' \
PYTHONDONTWRITEBYTECODE=1 uv run --python 3.13 \
--with 'pymobiledevice3==9.31.0' --with 'pmd-pytcp>=0.0.4,<0.1.0' \
python -m unittest discover -s Tests/Python -v
```

See [Installation](docs/INSTALLATION.md) for the complete setup.

The transitive `pmd-pytcp` bound is required by pymobiledevice3 9.31.0's
synchronous tunnel API. Keep installation, test commands, and CI aligned when
changing either dependency. The Python suite checks the real installed API;
it does not replace physical-iPhone tests of Start, Restore GPS, and reconnect.

## Pull requests

- Keep changes focused and explain the user-visible behavior.
Expand Down
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ GeoShift does not attempt to conceal simulation or bypass third-party rules.
| Swift | 6.2 or newer |
| Python | 3.11–3.13; 3.13 recommended |
| pymobiledevice3 | 9.31.0 |
| pmd-pytcp | >=0.0.4, <0.1.0 (synchronous API) |
| Physical iPhone | iOS 17+ with Developer Mode |
| Cable-free pairing | iOS 27 RemotePairing; currently beta-tested |
| iOS Simulator | Not targeted; use Xcode's built-in controls |
Expand All @@ -84,9 +85,14 @@ Install the backend in an isolated `uv` environment:

```bash
brew install uv
uv tool install --python 3.13 'pymobiledevice3==9.31.0'
uv tool install --python 3.13 --with 'pmd-pytcp>=0.0.4,<0.1.0' \
'pymobiledevice3==9.31.0'
```

Keep the `pmd-pytcp` bound: pymobiledevice3 9.31.0 uses its synchronous API,
which changed in 0.1.0. For an existing installation, use the
[backend repair command](docs/TROUBLESHOOTING.md#queuefull-or-unawaited-coroutine-errors).

Clone, build, and install GeoShift:

```bash
Expand Down Expand Up @@ -143,14 +149,19 @@ and apply it again; choose **Restore GPS** before restarting whenever possible.

```bash
swift test
PYTHONDONTWRITEBYTECODE=1 uv run --with 'pymobiledevice3==9.31.0' \
PYTHONDONTWRITEBYTECODE=1 uv run --python 3.13 \
--with 'pymobiledevice3==9.31.0' --with 'pmd-pytcp>=0.0.4,<0.1.0' \
python -m unittest discover -s Tests/Python -v
./Scripts/package_app.sh release
```

The package script builds the localized resource bundle, creates `GeoShift.app`,
and applies an ad-hoc signature.

Python tests check the installed backend versions and the real synchronous
PyTCP API without opening a tunnel. Connecting, changing location, and verifying
Restore GPS in Maps still require a physical iPhone.

## Documentation

- [Installation](docs/INSTALLATION.md)
Expand Down
11 changes: 8 additions & 3 deletions Sources/GeoShift/KeeperController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,15 @@ final class KeeperController {
configuration: configuration,
workerStatus: workerStatus
)
detail = statusDetail(
state: state,
configuration: configuration
detail = StatusParser.hasIncompatibleBackend(
configuration: configuration,
workerStatus: workerStatus
)
? localization.text("status.incompatibleBackend")
: statusDetail(
state: state,
configuration: configuration
)
}

private func recoverOnLaunch() async {
Expand Down
1 change: 1 addition & 0 deletions Sources/GeoShift/Resources/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
"status.gpsEvery" = "GPS refresh every";
"status.connecting" = "The background service is connecting";
"status.notConfirmed" = "Real GPS is not confirmed; choose Restore GPS";
"status.incompatibleBackend" = "The pymobiledevice3 backend has an incompatible pmd-pytcp. Repair it with the command in Diagnostics, then choose Restart.";

"error.commandFailed" = "The command failed.";
"error.previousOperation" = "The previous operation failed. Try again or open Diagnostics for connection details.";
Expand Down
60 changes: 60 additions & 0 deletions Sources/GeoShift/Resources/keeper.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
import asyncio
import errno
import fcntl
import inspect
import json
import logging
import math
import os
import signal
import time
from contextlib import suppress
from importlib import metadata
from logging.handlers import RotatingFileHandler
from pathlib import Path

Expand Down Expand Up @@ -42,6 +44,10 @@
STOP_GRACE_SECONDS = 12
APP_HEARTBEAT_TIMEOUT_SECONDS = 5 * 60
APP_HEARTBEAT_FUTURE_TOLERANCE_SECONDS = 60
BACKEND_REPAIR_COMMAND = (
"uv tool install --force --python 3.13 --with 'pmd-pytcp>=0.0.4,<0.1.0' "
"'pymobiledevice3==9.31.0'"
)


class ConfigurationError(ValueError):
Expand All @@ -52,6 +58,10 @@ class AmbiguousDeviceError(RuntimeError):
pass


class IncompatibleBackendError(RuntimeError):
pass


class AppCleanupLease:
def __init__(self, descriptor: int):
self.descriptor = descriptor
Expand Down Expand Up @@ -229,6 +239,7 @@ def write_status(
message: str | None = None,
path: Path | None = None,
required: bool = False,
problem: str | None = None,
) -> None:
path = path or STATUS_PATH
payload = {
Expand All @@ -239,6 +250,8 @@ def write_status(
"message": message,
"updatedAt": time.time(),
}
if problem:
payload["problem"] = problem
path.parent.mkdir(parents=True, exist_ok=True)
temporary_path = path.with_name(f".{path.name}.{os.getpid()}.tmp")
try:
Expand Down Expand Up @@ -308,7 +321,36 @@ async def resolve_target_device(saved_udid: str | None) -> tuple[str, bool]:
return available_udids[0], False


def backend_incompatibility(
pymobiledevice3_version: str | None = None,
pytcp_start=None,
) -> str | None:
# pymobiledevice3 9.x calls the synchronous PyTCP API. pmd-pytcp 0.1.0+
# made it async, so the tunnel never opens and asyncio floods QueueFull.
try:
pymobiledevice3_version = pymobiledevice3_version or metadata.version("pymobiledevice3")
if pytcp_start is None:
from pmd_pytcp import stack

pytcp_start = stack.start
except (ImportError, metadata.PackageNotFoundError):
return None
if not pymobiledevice3_version.startswith("9.") or not inspect.iscoroutinefunction(pytcp_start):
return None
try:
pytcp_version = metadata.version("pmd-pytcp")
except metadata.PackageNotFoundError:
pytcp_version = "unknown"
return (
f"pmd-pytcp {pytcp_version} is incompatible with pymobiledevice3 "
f"{pymobiledevice3_version}; repair the backend with: {BACKEND_REPAIR_COMMAND}"
)


async def open_target_tunnel(target_udid: str, uses_remote_pairing: bool):
problem = backend_incompatibility()
if problem:
raise IncompatibleBackendError(problem)
tunnel = UserspaceRsdTunnel(serial=target_udid, autopair=not uses_remote_pairing)
if not uses_remote_pairing:
return tunnel, await asyncio.wait_for(tunnel.aopen(), timeout=CONNECT_TIMEOUT_SECONDS)
Expand Down Expand Up @@ -456,6 +498,7 @@ async def run_worker(stop_event: asyncio.Event) -> None:
target_udid = previous_status.get("deviceUDID") if simulation_may_be_active else None
last_logged_request_id = ""
waiting_log_time = 0.0
backend_log_time = 0.0
expired_heartbeat_request = ""
cleanup_lease = None

Expand Down Expand Up @@ -643,6 +686,23 @@ async def run_worker(stop_event: asyncio.Event) -> None:
target_udid,
message,
)
except IncompatibleBackendError as error:
now = time.monotonic()
if now - backend_log_time >= 60:
logger.error("%s", error)
backend_log_time = now
should_simulate, cleanup_lease = simulation_request_decision(
config,
cleanup_lease,
)
write_status(
"failed" if should_simulate else "clearPending",
config["requestID"],
simulation_may_be_active,
target_udid,
str(error),
problem="incompatibleBackend",
)
except AmbiguousDeviceError as error:
logger.error("%s", error)
write_status(
Expand Down
1 change: 1 addition & 0 deletions Sources/GeoShift/Resources/ru.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
"status.active" = "Симуляция активна";
"status.gpsEvery" = "GPS каждые";
"status.connecting" = "Фоновый сервис подключается";
"status.incompatibleBackend" = "В бэкенде pymobiledevice3 несовместимая версия pmd-pytcp. Почините его командой из диагностики и нажмите «Перезапустить».";
"status.notConfirmed" = "Реальный GPS не подтверждён; нажмите «Вернуть GPS»";

"error.commandFailed" = "Команда завершилась с ошибкой.";
Expand Down
14 changes: 14 additions & 0 deletions Sources/GeoShift/StatusParser.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import Foundation

enum StatusParser {
static let incompatibleBackendProblem = "incompatibleBackend"

static func hasIncompatibleBackend(
configuration: KeeperConfiguration?,
workerStatus: WorkerStatus?
) -> Bool {
guard let configuration, let workerStatus else {
return false
}
return workerStatus.requestID == configuration.requestID
&& workerStatus.problem == incompatibleBackendProblem
&& [.failed, .clearPending].contains(workerStatus.phase)
}

static func state(
launchctlOutput: String,
configuration: KeeperConfiguration?,
Expand Down
1 change: 1 addition & 0 deletions Sources/GeoShift/WorkerStatus.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ struct WorkerStatus: Codable, Equatable, Sendable {
let simulationMayBeActive: Bool
let message: String?
let updatedAt: Double
var problem: String? = nil
}
2 changes: 2 additions & 0 deletions Tests/GeoShiftTests/LocalizationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ struct LocalizationTests {
#expect(localization.text("header.subtitle") == "Control iPhone GPS simulation from your Mac")
#expect(localization.text("settings.language") == "App language")
#expect(AppLanguage.english.selectionLabel == "🇬🇧 English")
#expect(localization.text("status.incompatibleBackend").contains("pmd-pytcp"))

localization.language = .russian
#expect(localization.text("header.subtitle").contains("симуляцией GPS"))
#expect(localization.text("settings.language") == "Язык приложения")
#expect(AppLanguage.russian.selectionLabel == "🇷🇺 Русский")
#expect(localization.text("status.incompatibleBackend").contains("«Перезапустить»"))
#expect(KeeperError.commandFailed("The command timed out after 5 seconds.")
.description(using: localization) == "Команда завершилась с ошибкой.")
}
Expand Down
41 changes: 41 additions & 0 deletions Tests/GeoShiftTests/StatusParserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,47 @@ struct StatusParserTests {
)
}

@Test("An incompatible backend reported for the current request is surfaced")
func incompatibleBackendIsSurfaced() throws {
var failed = status(.failed, mayBeActive: false)
failed.problem = StatusParser.incompatibleBackendProblem
var pending = status(.clearPending, mayBeActive: true)
pending.problem = StatusParser.incompatibleBackendProblem
var recovered = status(.active, mayBeActive: true)
recovered.problem = StatusParser.incompatibleBackendProblem

#expect(StatusParser.hasIncompatibleBackend(configuration: enabled, workerStatus: failed))
#expect(StatusParser.hasIncompatibleBackend(
configuration: configuration(enabled: false),
workerStatus: pending
))
#expect(!StatusParser.hasIncompatibleBackend(configuration: enabled, workerStatus: recovered))
#expect(!StatusParser.hasIncompatibleBackend(
configuration: enabled,
workerStatus: status(.failed, mayBeActive: false)
))

let otherRequest = WorkerStatus(
phase: .failed,
requestID: "old-request",
deviceUDID: "phone",
simulationMayBeActive: false,
message: nil,
updatedAt: 0,
problem: StatusParser.incompatibleBackendProblem
)
#expect(!StatusParser.hasIncompatibleBackend(configuration: enabled, workerStatus: otherRequest))
}

@Test("Worker status decodes with and without a problem code")
func problemCodeIsOptional() throws {
let legacy = Data(#"{"phase":"failed","requestID":"request","deviceUDID":null,"simulationMayBeActive":false,"message":null,"updatedAt":1}"#.utf8)
let current = Data(#"{"phase":"failed","requestID":"request","deviceUDID":null,"simulationMayBeActive":false,"message":"x","updatedAt":1,"problem":"incompatibleBackend"}"#.utf8)

#expect(try JSONDecoder().decode(WorkerStatus.self, from: legacy).problem == nil)
#expect(try JSONDecoder().decode(WorkerStatus.self, from: current).problem == "incompatibleBackend")
}

private func status(_ phase: WorkerStatus.Phase, mayBeActive: Bool) -> WorkerStatus {
WorkerStatus(
phase: phase,
Expand Down
44 changes: 44 additions & 0 deletions Tests/Python/test_dependencies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Guard the real userspace-tunnel dependency contract without an iPhone."""

import inspect
import unittest
from importlib.metadata import version

from packaging.specifiers import SpecifierSet
from pmd_pytcp import stack
from pmd_pytcp.socket.tcp__socket import TcpSocket
from pmd_pytcp.socket.udp__socket import UdpSocket


class DependencyCompatibilityTests(unittest.TestCase):
def test_installed_backend_versions_are_compatible(self):
for package, supported in (
("pymobiledevice3", "==9.31.0"),
("pmd-pytcp", ">=0.0.4,<0.1.0"),
):
with self.subTest(package=package):
installed = version(package)
self.assertIn(
installed,
SpecifierSet(supported),
f"{package} {installed} is incompatible; install {package}{supported}",
)

def test_userspace_tunnel_dependencies_have_synchronous_api(self):
# pymobiledevice3 9.31.0 calls these functions directly or in a thread.
# Async replacements return unawaited coroutines and can flood its queue.
for owner, methods in (
(stack, ("start", "stop")),
(TcpSocket, ("connect", "send", "recv", "close")),
(UdpSocket, ("recv", "sendto", "close")),
):
for name in methods:
with self.subTest(owner=owner.__name__, method=name):
self.assertFalse(
inspect.iscoroutinefunction(getattr(owner, name)),
f"{owner.__name__}.{name} must be synchronous for pymobiledevice3 9.31.0",
)


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