summaryrefslogtreecommitdiff
path: root/backend
diff options
context:
space:
mode:
authorAAGaming <aagaming@riseup.net>2026-11-21 22:23:03 -0500
committerGitHub <noreply@github.com>2026-11-21 22:23:03 -0500
commit24082fe63cdcdf41993f9e1430d1405152a2c930 (patch)
tree59454b25fc5cffcbce82e7947d8e3803952fc5ba /backend
parentffd103b9c1a4ce5bf305e7c0998eda6e05457dad (diff)
downloaddecky-loader-d020af9f7fd305e666db36650e41b40af1c0db8a.tar.gz
decky-loader-d020af9f7fd305e666db36650e41b40af1c0db8a.zip
feat: Support new Steam Betas (only) and Frame (#1019)v4.0.0-pre1
Diffstat (limited to 'backend')
-rw-r--r--backend/decky_loader/injector.py94
-rw-r--r--backend/decky_loader/instrumentation.py22
-rw-r--r--backend/decky_loader/main.py3
-rw-r--r--backend/decky_loader/updater.py2
-rw-r--r--backend/decky_loader/utilities.py10
-rw-r--r--backend/decky_loader/wsrouter.py5
-rw-r--r--backend/pyinstaller.spec3
7 files changed, 121 insertions, 18 deletions
diff --git a/backend/decky_loader/injector.py b/backend/decky_loader/injector.py
index ded58193..8aa3bf29 100644
--- a/backend/decky_loader/injector.py
+++ b/backend/decky_loader/injector.py
@@ -2,10 +2,11 @@
from asyncio import sleep
from logging import getLogger
-from typing import Any, Callable, List, TypedDict, Dict
+from typing import Any, AsyncGenerator, Callable, List, Set, TypedDict, Dict
from aiohttp import ClientSession, ClientTimeout
from aiohttp.client_exceptions import ClientConnectorError, ClientOSError
+from asyncio import Queue, create_task
from asyncio.exceptions import TimeoutError
import uuid
@@ -27,6 +28,8 @@ class Tab:
self.id: str = res["id"]
self.url: str = res["url"]
self.ws_url: str = res["webSocketDebuggerUrl"]
+ self.queues: Set[Queue[Any]] = set()
+ self.reader = None
self.websocket = None
self.client = None
@@ -41,13 +44,31 @@ class Tab:
if self.client:
await self.client.close()
- async def listen_for_message(self):
+ async def message_reader(self):
if self.websocket:
- async for message in self.websocket:
- data = message.json()
- yield data
- logger.warning(f"The Tab {self.title} socket has been disconnected while listening for messages.")
- await self.close_websocket()
+ try:
+ async for message in self.websocket:
+ data = message.json()
+ for q in self.queues:
+ q.put_nowait(data)
+ logger.warning(f"The Tab {self.title} socket has been disconnected while listening for messages.")
+ finally:
+ for q in self.queues:
+ q.put_nowait(None)
+ await self.close_websocket()
+
+ async def listen_for_message(self) -> AsyncGenerator[Any]:
+ if self.websocket:
+ if not self.reader or self.reader.done():
+ self.reader = create_task(self.message_reader())
+
+ q: Queue[Any] = Queue()
+ self.queues.add(q)
+ try:
+ while (data := await q.get()) is not None:
+ yield data
+ finally:
+ self.queues.discard(q)
async def _send_devtools_cmd(self, dc: Dict[str, Any], receive: bool = True):
if self.websocket:
@@ -168,7 +189,7 @@ class Tab:
# Page finishes loading when breakpoint hits
for _ in range(20):
- # this works around 1/5 of the time, so just send it 8 times.
+ # this works around 1/5 of the time, so just send it 20 times.
# the js accounts for being injected multiple times allowing only one instance to run at a time anyway
await self._send_devtools_cmd({
"method": "Runtime.evaluate",
@@ -297,7 +318,7 @@ class Tab:
return res["result"]["result"]["value"]
- async def inject_css(self, style: str, manage_socket: bool = True):
+ async def inject_css(self, style: str, manage_socket: bool = True) -> Any:
try:
css_id = str(uuid.uuid4())
@@ -329,7 +350,7 @@ class Tab:
"result": e
}
- async def remove_css(self, css_id: str, manage_socket: bool = True):
+ async def remove_css(self, css_id: str, manage_socket: bool = True) -> Any:
try:
result = await self.evaluate_js(
f"""
@@ -363,6 +384,57 @@ class Tab:
assert res is not None
return res["result"]["result"]["value"]
+ async def get_module_scope(self, object_key: int):
+ # Evaluate the value of the module function export to get its object id
+ eval = await self._send_devtools_cmd({
+ "method": "Runtime.evaluate",
+ "params": {
+ "expression": f"window._deckyModuleResolverInternals.scopedObjects.get({object_key})",
+ "userGesture": True,
+ "generatePreview": False,
+ "returnByValue": False,
+ "awaitPromise": False
+ }
+ })
+
+ if eval is not None and "result" in eval["result"]:
+ fnObjId = eval["result"]["result"]["objectId"]
+ # getProperties to get the internal [[Scopes]] property of V8 objectId
+ props = await self._send_devtools_cmd({
+ "method": "Runtime.getProperties",
+ "params": {
+ "objectId": fnObjId
+ }
+ })
+ if props is not None and "internalProperties" in props["result"]:
+ internalProps = props["result"]["internalProperties"]
+ modScopesObj = next(s for s in internalProps if s["name"] == "[[Scopes]]")
+ # getProperties to get the Module scope objectId
+ scopeListR = await self._send_devtools_cmd({
+ "method": "Runtime.getProperties",
+ "params": {
+ "objectId": modScopesObj["value"]["objectId"]
+ }
+ })
+ if scopeListR is not None and "result" in scopeListR["result"]:
+ scopeList = scopeListR["result"]["result"]
+ scope = next(s for s in scopeList if s["value"]["description"] == "Module")
+ scopeId = scope["value"]["objectId"]
+ # expose the module scope back to the JS side using its objectId
+ await self._send_devtools_cmd({
+ "method": "Runtime.callFunctionOn",
+ "params": {
+ "functionDeclaration": f"""function(_moduleKey, _moduleScope) {{
+ window._deckyModuleResolverInternals.scopes.set(_moduleKey, _moduleScope);
+ }}""",
+ "objectId": fnObjId,
+ "arguments": [
+ { "value": object_key },
+ { "objectId": scopeId }
+ ]
+ }
+ })
+
def __repr__(self):
return self.title
@@ -435,4 +507,4 @@ async def close_old_tabs():
if not t.title or (t.title not in SHARED_CTX_NAMES and any(url in t.url for url in CLOSEABLE_URLS) and not any(url in t.url for url in DO_NOT_CLOSE_URLS)):
logger.debug("Closing tab: " + getattr(t, "title", "Untitled"))
await t.close()
- await sleep(0.5)
+ # await sleep(0.5)
diff --git a/backend/decky_loader/instrumentation.py b/backend/decky_loader/instrumentation.py
new file mode 100644
index 00000000..3605a69c
--- /dev/null
+++ b/backend/decky_loader/instrumentation.py
@@ -0,0 +1,22 @@
+from logging import getLogger
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+ from .main import PluginManager
+from .injector import Tab
+
+logger = getLogger("Instrumentation")
+
+
+class Instrumentation:
+ def __init__(self, context: PluginManager):
+ self.ctx: PluginManager = context
+ self.tab: Tab | None = None
+
+ self.ctx.ws.add_route("instrumentation/resolve_scope", self.get_module_scope)
+
+ def set_tab(self, tab: Tab):
+ self.tab = tab
+
+ async def get_module_scope(self, object_key: int):
+ assert self.tab is not None
+ await self.tab.get_module_scope(object_key) \ No newline at end of file
diff --git a/backend/decky_loader/main.py b/backend/decky_loader/main.py
index 24115419..36d52337 100644
--- a/backend/decky_loader/main.py
+++ b/backend/decky_loader/main.py
@@ -36,6 +36,7 @@ from .updater import Updater
from .utilities import Utilities
from .enums import UserType
from .wsrouter import WSRouter
+from .instrumentation import Instrumentation
basicConfig(
@@ -76,6 +77,7 @@ class PluginManager:
self.plugin_browser = PluginBrowser(plugin_path, self.plugin_loader.plugins, self.plugin_loader, self.settings)
self.utilities = Utilities(self)
self.updater = Updater(self)
+ self.instrumentation = Instrumentation(self)
self.last_webhelper_exit: float = 0
self.webhelper_crash_count: int = 0
self.inject_fallback: bool = False
@@ -207,6 +209,7 @@ class PluginManager:
await tab.open_websocket()
self.js_ctx_tab = tab
await tab.enable()
+ self.instrumentation.set_tab(tab)
await self.inject_javascript(tab, True)
try:
async for msg in tab.listen_for_message():
diff --git a/backend/decky_loader/updater.py b/backend/decky_loader/updater.py
index d018b4fe..cefa6b11 100644
--- a/backend/decky_loader/updater.py
+++ b/backend/decky_loader/updater.py
@@ -44,6 +44,7 @@ class Updater:
self.isSupported: bool = ON_LINUX
self.repo = getenv('DECKY_REPO', 'SteamDeckHomebrew/decky-loader')
self.git_branch = getenv('DECKY_BRANCH', 'dirty')
+ self.git_pr = getenv('DECKY_PR', None)
try:
self.currentBranch = self.get_branch(self.context.settings)
@@ -98,6 +99,7 @@ class Updater:
"current": self.localVer,
"repo": self.repo,
"gitBranch": self.git_branch,
+ "gitPR": self.git_pr,
"remote": self.remoteVer,
"all": self.allRemoteVers,
"updatable": self.localVer != "unknown" and self.localVer != "dev",
diff --git a/backend/decky_loader/utilities.py b/backend/decky_loader/utilities.py
index 99a1b019..49376065 100644
--- a/backend/decky_loader/utilities.py
+++ b/backend/decky_loader/utilities.py
@@ -215,7 +215,7 @@ class Utilities:
self.logger.debug(f"Finished stream for {url}")
return res
- async def http_request_legacy(self, method: str, url: str, extra_opts: Any = {}, timeout: int | None = None):
+ async def http_request_legacy(self, method: str, url: str, extra_opts: Any = {}, timeout: int | None = None) -> Any:
async with ClientSession() as web:
res = await web.request(method, url, ssl=helpers.get_ssl_context(), timeout=timeout, **extra_opts) # type: ignore
text = await res.text()
@@ -228,7 +228,7 @@ class Utilities:
async def ping(self, **kwargs: Any):
return "pong"
- async def execute_in_tab(self, tab: str, run_async: bool, code: str):
+ async def execute_in_tab(self, tab: str, run_async: bool, code: str)-> Any:
try:
result = await inject_to_tab(tab, code, run_async)
assert result
@@ -321,7 +321,7 @@ class Utilities:
order_by: str = "name_desc",
filter_for: str | None = None,
page: int = 1,
- max: int = 1000):
+ max: int = 1000) -> Any:
if path == None:
path = get_home_path()
@@ -382,7 +382,7 @@ class Utilities:
folders.sort(key=lambda x: x['file'].name.casefold(), reverse = rev)
#Constructing the final file list, folders first
- all = [{
+ all: List[Any] = [{
"isdir": x['is_dir'],
"name": str(x['file'].name),
"realpath": str(x['file']),
@@ -442,7 +442,7 @@ class Utilities:
enumerable: true,
configurable: true,
get: function() {
- return (GamepadNavTree?.m_context?.m_controller || FocusNavController)?.m_ActiveContext?.ActiveWindow || window;
+ return (window?.GamepadNavTree?.m_context?.m_controller || window?.FocusNavController)?.m_ActiveContext?.ActiveWindow || window;
}
});
""" + await res.text() + "\n}"
diff --git a/backend/decky_loader/wsrouter.py b/backend/decky_loader/wsrouter.py
index b0610b31..66bcc0ff 100644
--- a/backend/decky_loader/wsrouter.py
+++ b/backend/decky_loader/wsrouter.py
@@ -68,7 +68,7 @@ class WSRouter:
async def _call_route(self, route: str, args: ..., call_id: int):
try:
res = await self.routes[route](*args)
- message = {"type": MessageType.REPLY.value, "id": call_id, "result": res}
+ message: Any = {"type": MessageType.REPLY.value, "id": call_id, "result": res}
except PluginStopped as err:
message = {"type": MessageType.DISCARD.value, "id": call_id}
except Exception as err:
@@ -143,7 +143,8 @@ class WSRouter:
self.logger.debug(f'Started PY call {data["route"]} ID {call_id}')
self.loop.create_task(self._call_route(data["route"], data["args"], call_id))
else:
- error = {"error":f'Route {data["route"]} does not exist.', "name": "RouteNotFoundError", "traceback": None}
+ # TODO type better
+ error: Dict[str, str | None] = {"error":f'Route {data["route"]} does not exist.', "name": "RouteNotFoundError", "traceback": None}
self.loop.create_task(self.write({"type": MessageType.ERROR.value, "id": call_id, "error": error}))
def handle_received_response_message(self, call_id: int):
diff --git a/backend/pyinstaller.spec b/backend/pyinstaller.spec
index 3ef888f5..ab27d1ea 100644
--- a/backend/pyinstaller.spec
+++ b/backend/pyinstaller.spec
@@ -7,6 +7,7 @@ noconsole_str = os.getenv('DECKY_NOCONSOLE', '0')
noconsole = bool(noconsole_str)
repo = os.getenv('DECKY_REPO', 'SteamDeckHomebrew/decky-loader')
branch = os.getenv('DECKY_BRANCH', 'main')
+pr = os.getenv('DECKY_PR', None)
with open('build_config.py', 'w') as f:
f.write(f"""
import os
@@ -15,6 +16,8 @@ os.environ['DECKY_PACKAGED_BUILD'] = '1'
# Build info
os.environ['DECKY_REPO'] = {repr(repo)}
os.environ['DECKY_BRANCH'] = {repr(branch)}
+if {repr(pr)} is not None:
+ os.environ['DECKY_PR'] = {repr(pr)}
# Windows-specific
os.environ['DECKY_NOCONSOLE'] = {repr(noconsole_str)}