diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt index 93922c8050..1b57562273 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt @@ -76,6 +76,9 @@ class AgentBridgeProvider : ContentProvider() { "stop" -> stop(context) "resume" -> resume(context) "launch" -> launch(context, request) + "library" -> AgentStores.library(context, request) + "xodus" -> AgentStores.xodus(context, request) + "cloud" -> AgentStores.cloud(context, request) "focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000) "quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId")) .put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000)) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentStores.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentStores.kt new file mode 100644 index 0000000000..82ce426c88 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentStores.kt @@ -0,0 +1,91 @@ +package com.droiddeck.launcher.agent + +import android.content.Context +import com.droiddeck.launcher.frontend.LibraryCache +import com.droiddeck.launcher.stores.CloudSaves +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.xbox.Xodus +import java.io.ByteArrayOutputStream +import java.io.InputStream +import java.util.concurrent.TimeUnit +import org.json.JSONArray +import org.json.JSONObject + +internal object AgentStores { + private const val OUTPUT_CAP = 160 * 1024 + + fun library(context: Context, request: JSONObject): JSONObject { + val query = request.optString("query").trim() + val source = request.optString("source").trim() + val games = JSONArray() + LibraryCache.load(context) + .filter { (query.isEmpty() || it.name.contains(query, ignoreCase = true)) && (source.isEmpty() || it.source.equals(source, ignoreCase = true)) } + .forEach { + games.put(JSONObject().put("id", it.gameIdString).put("name", it.name).put("source", it.source) + .put("storeId", it.storeId ?: JSONObject.NULL).put("folder", it.gameFiles?.path ?: JSONObject.NULL)) + } + return JSONObject().put("ok", true).put("command", "library").put("games", games) + } + + fun xodus(context: Context, request: JSONObject): JSONObject { + AgentAccess.requireCommands(context) + val list = request.optJSONArray("args") + val args = if (list == null) emptyList() else List(list.length()) { list.optString(it) } + if (args.isEmpty() || args.any { it.isEmpty() }) throw AgentException("INVALID_REQUEST", "xodus needs its arguments") + val timeoutMs = (request.optDouble("timeout", 120.0) * 1000).toLong().coerceIn(1_000L, 900_000L) + return Xodus.start(context.applicationContext, args).use { child -> + val out = Tail(child.process.inputStream) + val err = Tail(child.process.errorStream) + val finished = child.process.waitFor(timeoutMs, TimeUnit.MILLISECONDS) + if (!finished) child.close() + JSONObject().put("ok", true).put("command", "xodus").put("timedOut", !finished) + .put("exit", if (finished) child.process.exitValue() else JSONObject.NULL) + .put("stdout", out.text()).put("stderr", err.text()) + } + } + + fun cloud(context: Context, request: JSONObject): JSONObject { + AgentAccess.requireCommands(context) + val store = Store.byId(request.optString("store"))?.takeIf(CloudSaves::supports) + ?: throw AgentException("INVALID_REQUEST", "store must be one with cloud saves") + val id = request.optString("id").ifEmpty { throw AgentException("INVALID_REQUEST", "cloud needs a game id") } + val force = request.optBoolean("force") + val result = when (val direction = request.optString("direction")) { + "down" -> CloudSaves.download(context.applicationContext, store, id, force) + "up" -> CloudSaves.upload(context.applicationContext, store, id, force) + else -> throw AgentException("INVALID_REQUEST", "direction '$direction' is not down or up") + } + return JSONObject().put("ok", true).put("command", "cloud").put("result", result.result).put("files", result.files) + .put("bytes", result.bytes).put("reason", result.reason).put("conflicts", result.conflicts).put("detail", result.detail) + } + + private class Tail(stream: InputStream) { + private val kept = ByteArrayOutputStream() + private var dropped = false + private val reader = Thread({ + val buffer = ByteArray(8192) + stream.use { input -> + while (true) { + val n = runCatching { input.read(buffer) }.getOrDefault(-1) + if (n < 0) break + synchronized(kept) { + kept.write(buffer, 0, n) + if (kept.size() > OUTPUT_CAP * 2) { + val bytes = kept.toByteArray() + kept.reset() + kept.write(bytes, bytes.size - OUTPUT_CAP, OUTPUT_CAP) + dropped = true + } + } + } + } + }, "agent-xodus-output").apply { isDaemon = true; start() } + + fun text(): String { + reader.join(2_000) + val bytes = synchronized(kept) { kept.toByteArray() } + val tail = if (bytes.size > OUTPUT_CAP) bytes.copyOfRange(bytes.size - OUTPUT_CAP, bytes.size) else bytes + return (if (dropped || bytes.size > OUTPUT_CAP) "...\n" else "") + String(tail, Charsets.UTF_8) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt index 6f9f364539..b437f3ae4e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt @@ -708,10 +708,10 @@ internal object EnhancedSessionLogShare { } val logs = LinuxRuntime.logDir(context) for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) { - val scan = directFiles(root, remaining(maxFiles, out.size)) + val scan = directFiles(root, STORE_LOG_SCAN) truncated = truncated || scan.truncated partial = partial || scan.partial - scan.files.asSequence().filter { recent(it) } + scan.files.filter { recent(it) }.sortedByDescending { it.lastModified() }.take(remaining(maxFiles, out.size)) .forEach { add(it, root, "$name/${it.name}", name) } } if (legacy) { @@ -965,6 +965,7 @@ internal object EnhancedSessionLogShare { "events.jsonl", "memory.csv", "capture.json", "crash.log", ) private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000 + private const val STORE_LOG_SCAN = 512 private const val COPY_BUFFER_BYTES = 64 * 1024 private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024 private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024 diff --git a/docs/agent-control.md b/docs/agent-control.md index ed9fbcf1e3..13bf1c232d 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -122,9 +122,12 @@ tools/droiddeckctl stop tools/droiddeckctl resume tools/droiddeckctl launch 489830 --wait +tools/droiddeckctl library --source xbox +tools/droiddeckctl launch --game "dead space" --wait tools/droiddeckctl wait focused 489830 tools/droiddeckctl wait game tools/droiddeckctl quit 489830 +tools/droiddeckctl quit tools/droiddeckctl focus tools/droiddeckctl input key ENTER @@ -145,6 +148,10 @@ tools/droiddeckctl ui click --match "Play" tools/droiddeckctl ui set-text some-field --text abc tools/droiddeckctl guest -- xprop -root GAMESCOPE_FOCUSED_APP +tools/droiddeckctl native -- ls /usr/local/lib/droiddeck-xbox +tools/droiddeckctl xodus --timeout 60 -- resolve-package 9N51S9QZMSB6 --json --market US +tools/droiddeckctl cloud down ubisoft 92c79ab6-a69a-411d-ba2b-625ab104235d +tools/droiddeckctl cloud up ea DR:105641400 --force tools/droiddeckctl cdp targets tools/droiddeckctl cdp eval 'SteamClient.Apps.GetMyRunningApps?.()' tools/droiddeckctl env set DXVK_HUD=fps @@ -209,9 +216,24 @@ every 10 s until the battery is under that temperature, so runs being compared s `input` needs a session that has drawn its first frame. Pad input goes through the session screen's virtual pad, the same one the on-screen controls drive, so games that ignore touch still respond. -`launch`, `quit` and `cdp` need a Steam session; `focus` and `wait focused` need gamescope (every +`launch` with an app id and `cdp` need a Steam session; `focus` and `wait focused` need gamescope (every mode except the desktop). +Store and added games (Xbox, EA, Ubisoft, GOG, Epic, Battle.net, Rockstar, a folder added by hand) are +launched by their library id, the same `droiddeck://game/` link a home screen shortcut opens, so +they go through the front end's own launch path and start a session when none is running. `library` +lists the ids with each game's name, source, store id and folder (`--query` and `--source` narrow it), +and `launch --game` takes an id or a unique part of a name; an ambiguous name exits with +`GAME_AMBIGUOUS` and lists the matches. With `--wait` it returns once a game other than the Steam +client has focus. `quit` without an id quits the focused game, so store games close the same way. + +`xodus` runs the Xbox backend with the app's own credentials and runtime, as the Xbox store does, +and returns its exit code with the last 160 KiB of stdout and stderr (`--timeout` stops it). +`cloud down|up ` syncs one game's cloud saves now, without launching it, with the +`result`, `files`, `bytes`, `reason`, `conflicts` and `detail` the game page shows; `--force` takes +that side over conflicts. The store id is the one in the game's install record (`library` shows +it). Both need Setup > Developer > Debugging tools. + `input pen` does not go through the app. It registers a virtual pen with `adb shell uinput -`, so Android's own input reader makes the stylus events, as for a built-in pen, and it works on whatever is on screen, without a session or Setup > Developer > Debugging tools. Positions are fractions of @@ -402,6 +424,7 @@ Automator show them: | Tag | Where | |---|---| | `rail-steam`, `rail-games` (the Library), `rail-desktop`, `rail-store`, `rail-components`, `rail-android-apps`, `rail-setup`, `rail-updates` | the front end's rail | +| `dual-rail-` (`dual-rail-games`, `dual-rail-downloads`, ...) | the rail on the second screen of a dual-screen device | | `play-steam` | Play on the Steam page, and on the Library when it has no games | | `library-source-` | the Library's source filter chips (`all`, `steam`, `gog`, ...) | | `game-tab-` | the open tab of a game page | diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 15675a1797..50ff42423d 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -153,6 +153,31 @@ def checked(response: dict, default_code: str) -> dict: return response +def find_game(adb: str, serial: str, wanted: str) -> dict: + games = checked(provider_call(adb, serial, "library", request={}), "LIBRARY_FAILED").get("games") or [] + exact = [g for g in games if g.get("id") == wanted] + if exact: + return exact[0] + named = [g for g in games if wanted.casefold() in str(g.get("name", "")).casefold()] + if len(named) == 1: + return named[0] + if not named: + raise ControlError(f"No library game matches {wanted!r}; list them with library", "GAME_NOT_FOUND") + names = ", ".join(f"{g.get('name')} ({g.get('id')})" for g in named[:10]) + raise ControlError(f"{wanted!r} matches {len(named)} games: {names}", "GAME_AMBIGUOUS") + + +def open_game_link(adb: str, serial: str, game_id: str) -> None: + if not game_id.isdigit(): + raise ControlError(f"Library id {game_id!r} is not a number", "INVALID_GAME_ID") + result = run_adb(adb, serial, "shell", "am", "start", "-W", "-a", "android.intent.action.VIEW", + "-d", f"droiddeck://game/{game_id}", "-n", f"{PACKAGE}/com.droiddeck.launcher.FrontEndActivity", + timeout=60) + output = (result.stdout + result.stderr).decode(errors="replace") + if result.returncode != 0 or "error" in output.lower(): + raise ControlError(output.strip() or "The game link did not open", "ACTIVITY_START_FAILED") + + def start_agent_activity(adb: str, serial: str, request: dict) -> None: encoded = encode_request(request) result = run_adb( @@ -949,6 +974,17 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict: return add_serial(checked(provider_call(adb, serial, "resume"), "RESUME_FAILED"), serial) if command == "launch": + if (args.app_id is None) == (args.game is None): + raise ControlError("launch takes a Steam app id or --game, not both", "INVALID_ARGUMENTS") + if args.game is not None: + game = find_game(adb, serial, args.game) + open_game_link(adb, serial, game["id"]) + response = {"ok": True, "command": "launch", "game": game} + if args.wait: + state = wait_until(adb, serial, f"{game['name']} to have focus", + lambda s: focused(s, None), args.timeout, 0.5) + response["focus"] = state["session"].get("focus") + return add_serial(response, serial) response = checked(provider_call(adb, serial, "launch", request={"appId": str(args.app_id)}), "LAUNCH_FAILED") if args.wait: state = wait_until(adb, serial, f"app {args.app_id} to have focus", @@ -957,10 +993,33 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict: return add_serial(response, serial) if command == "quit": - response = provider_call(adb, serial, "quit", request={"appId": args.app_id, "timeout": args.timeout}, + app_id = args.app_id + if app_id is None: + current = (get_state(adb, serial)["session"].get("focus") or {}).get("focusedApp") + if current in (None, 0, STEAM_CLIENT_APP): + raise ControlError("No game has focus; name the app id to quit", "NO_FOCUSED_GAME") + app_id = current + response = provider_call(adb, serial, "quit", request={"appId": app_id, "timeout": args.timeout}, timeout=args.timeout + 40) return add_serial(checked(response, "QUIT_FAILED"), serial) + if command == "library": + request = {"query": args.query or "", "source": args.source or ""} + return add_serial(checked(provider_call(adb, serial, "library", request=request), "LIBRARY_FAILED"), serial) + + if command == "xodus": + argv = args.argv[1:] if args.argv[:1] == ["--"] else args.argv + if not argv: + raise ControlError("xodus needs its arguments after --", "INVALID_ARGUMENTS") + response = provider_call(adb, serial, "xodus", request={"args": argv, "timeout": args.timeout}, + timeout=args.timeout + 30) + return add_serial(checked(response, "XODUS_FAILED"), serial) + + if command == "cloud": + request = {"direction": args.direction, "store": args.store, "id": args.game_id, "force": args.force} + response = provider_call(adb, serial, "cloud", request=request, timeout=args.timeout) + return add_serial(checked(response, "CLOUD_FAILED"), serial) + if command == "focus": return add_serial(checked(provider_call(adb, serial, "focus", timeout=40), "FOCUS_FAILED"), serial) @@ -1224,15 +1283,31 @@ def build_parser() -> argparse.ArgumentParser: stop.add_argument("--artifact-timeout", type=float, default=300) commands.add_parser("resume", help="resume a suspended session") - launch = commands.add_parser("launch", help="launch a Steam game in the running Steam session") - launch.add_argument("app_id", type=int) + launch = commands.add_parser("launch", help="launch a Steam game in the running Steam session, or any library game with --game") + launch.add_argument("app_id", type=int, nargs="?") + launch.add_argument("--game", help="a library game id or a unique part of its name (store and added games too)") launch.add_argument("--wait", action="store_true", help="wait until the game has focus") launch.add_argument("--timeout", type=float, default=180) - quit_ = commands.add_parser("quit", help="quit a running game (through the client, then signals)") - quit_.add_argument("app_id", type=int) + quit_ = commands.add_parser("quit", help="quit a running game (through the client, then signals); the focused one by default") + quit_.add_argument("app_id", type=int, nargs="?") quit_.add_argument("--timeout", type=float, default=15) + library = commands.add_parser("library", help="the library games the front end lists, with the ids launch --game takes") + library.add_argument("--query", help="only games whose name contains this") + library.add_argument("--source", help="only games from this source, e.g. steam, xbox, ea, ubisoft, gog, epic") + + xodus = commands.add_parser("xodus", help="run the Xbox backend with the app's credentials (debugging tools)") + xodus.add_argument("--timeout", type=float, default=120) + xodus.add_argument("argv", nargs=argparse.REMAINDER) + + cloud = commands.add_parser("cloud", help="sync a store game's cloud saves now (debugging tools)") + cloud.add_argument("direction", choices=["down", "up"]) + cloud.add_argument("store", help="gog, epic, ea or ubisoft") + cloud.add_argument("game_id", help="the store's id for the game, as its install record names it") + cloud.add_argument("--force", action="store_true", help="take this side even over conflicts") + cloud.add_argument("--timeout", type=float, default=300) + commands.add_parser("focus", help="gamescope's focus and every Xwayland server's windows, fresh") guest = commands.add_parser("guest", help="run a command inside the session (debugging tools)") diff --git a/tools/tests/test_droiddeckctl.py b/tools/tests/test_droiddeckctl.py index 9dd7dff676..59f187a7f5 100644 --- a/tools/tests/test_droiddeckctl.py +++ b/tools/tests/test_droiddeckctl.py @@ -274,6 +274,60 @@ class DroiddeckctlTest(FakeAdbTest): self.assertEqual(0, code) self.assertEqual(489830, out["focus"]["focusedApp"]) + LIBRARY = {"ok": True, "command": "library", "games": [ + {"id": "9227380185612091392", "name": "TimeSplitters Future Perfect", "source": "xbox", "storeId": "9N51S9QZMSB6", "folder": "/g/ts"}, + {"id": "12302733539203571712", "name": "Dead Space (2008)", "source": "ea", "storeId": "DR:105641400", "folder": "/g/ds"}, + {"id": "12302733539203571999", "name": "Dead Space 2", "source": "ea", "storeId": "DR:1", "folder": "/g/ds2"}, + ]} + + def test_launch_by_name_opens_the_game_link_and_waits_for_a_game(self): + self.configure({"library": self.LIBRARY, "state": [state(focused=769, focusable=[769]), state(focused=7, focusable=[7, 769])]}) + code, out = self.run_ctl("launch", "--game", "timesplitters", "--wait", "--timeout", "5") + self.assertEqual(0, code) + self.assertEqual("TimeSplitters Future Perfect", out["game"]["name"]) + self.assertEqual(7, out["focus"]["focusedApp"]) + started = [e["args"] for e in self.calls() if e["args"][:3] == ["shell", "am", "start"]] + self.assertIn("droiddeck://game/9227380185612091392", started[0]) + self.assertIn("com.droiddeck.launcher/com.droiddeck.launcher.FrontEndActivity", started[0]) + self.assertFalse(self.calls("launch")) + + def test_launch_by_name_refuses_an_ambiguous_or_missing_game(self): + self.configure({"library": self.LIBRARY}) + code, out = self.run_ctl("launch", "--game", "dead space") + self.assertNotEqual(0, code) + self.assertEqual("GAME_AMBIGUOUS", out["error"]["code"]) + self.assertIn("Dead Space 2 (12302733539203571999)", out["error"]["message"]) + code, out = self.run_ctl("launch", "--game", "12302733539203571712") + self.assertEqual(0, code) + self.assertEqual("ea", out["game"]["source"]) + code, out = self.run_ctl("launch", "--game", "halo") + self.assertEqual("GAME_NOT_FOUND", out["error"]["code"]) + code, out = self.run_ctl("launch") + self.assertEqual("INVALID_ARGUMENTS", out["error"]["code"]) + self.assertFalse([e for e in self.calls() if e["args"][:3] == ["shell", "am", "start"] and "droiddeck://game/12302733539203571999" in e["args"]]) + + def test_quit_without_an_app_quits_the_focused_game(self): + self.configure({"state": state(focused=4040, focusable=[4040, 769]), "quit": {"ok": True, "command": "quit"}}) + code, _ = self.run_ctl("quit") + self.assertEqual(0, code) + self.assertEqual(4040, self.calls("quit")[0]["request"]["appId"]) + self.configure({"state": state(focused=769, focusable=[769])}) + code, out = self.run_ctl("quit") + self.assertEqual("NO_FOCUSED_GAME", out["error"]["code"]) + self.assertEqual(1, len(self.calls("quit"))) + + def test_library_xodus_and_cloud_pass_their_requests(self): + self.configure({"library": self.LIBRARY, "xodus": {"ok": True, "command": "xodus", "exit": 0, "stdout": "{}", "stderr": ""}, + "cloud": {"ok": True, "command": "cloud", "result": "ok", "files": 2, "reason": "downloaded"}}) + self.assertEqual(0, self.run_ctl("library", "--source", "ea", "--query", "dead")[0]) + self.assertEqual({"query": "dead", "source": "ea"}, self.calls("library")[0]["request"]) + self.assertEqual(0, self.run_ctl("xodus", "--timeout", "30", "--", "license", "abc", "--market", "US")[0]) + self.assertEqual({"args": ["license", "abc", "--market", "US"], "timeout": 30.0}, self.calls("xodus")[0]["request"]) + code, out = self.run_ctl("cloud", "down", "ubisoft", "92c79ab6", "--force") + self.assertEqual(0, code) + self.assertEqual("downloaded", out["reason"]) + self.assertEqual({"direction": "down", "store": "ubisoft", "id": "92c79ab6", "force": True}, self.calls("cloud")[0]["request"]) + def test_start_reuse_keeps_a_running_session(self): running = state(focused=769) running["session"]["mode"] = "steam"