2Btainment commited on
Commit
7f84efa
·
1 Parent(s): 2804efa

feat(linux_appimage): real x86_64 AppImage via pinned Neutralinojs + appimagetool (Hosted Wrapper)

Browse files
Dockerfile CHANGED
@@ -19,7 +19,8 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
19
  GRADLE_USER_HOME=/opt/gradle-cache \
20
  SPACEFORGE_ANDROID_SDK=1 \
21
  SPACEFORGE_BUILD_TIMEOUT=900 \
22
- SPACEFORGE_MAX_DOWNLOAD=104857600
 
23
 
24
  # Node (from official image) + JDK 17 + unzip/curl for SDK
25
  COPY --from=node:20-bookworm-slim /usr/local/bin/node /usr/local/bin/node
@@ -28,10 +29,15 @@ RUN ln -sf /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
28
  && ln -sf /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
29
 
30
  RUN apt-get update && apt-get install -y --no-install-recommends \
31
- ca-certificates curl wget unzip git \
32
  openjdk-17-jdk-headless \
33
  && rm -rf /var/lib/apt/lists/*
34
 
 
 
 
 
 
35
  # Minimal Android SDK (cmdline-tools + platform 34 + build-tools)
36
  ARG CMDLINE_TOOLS_URL=https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
37
  RUN mkdir -p ${ANDROID_HOME}/cmdline-tools ${ANDROID_HOME}/licenses ${GRADLE_USER_HOME} \
 
19
  GRADLE_USER_HOME=/opt/gradle-cache \
20
  SPACEFORGE_ANDROID_SDK=1 \
21
  SPACEFORGE_BUILD_TIMEOUT=900 \
22
+ SPACEFORGE_MAX_DOWNLOAD=104857600 \
23
+ SPACEFORGE_TOOLS=/opt/spaceforge-tools
24
 
25
  # Node (from official image) + JDK 17 + unzip/curl for SDK
26
  COPY --from=node:20-bookworm-slim /usr/local/bin/node /usr/local/bin/node
 
29
  && ln -sf /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
30
 
31
  RUN apt-get update && apt-get install -y --no-install-recommends \
32
+ ca-certificates curl wget unzip git file \
33
  openjdk-17-jdk-headless \
34
  && rm -rf /var/lib/apt/lists/*
35
 
36
+ # Linux desktop targets (AppImage / Arch PKGBUILD): pinned + sha256-verified prebuilt
37
+ # Neutralinojs linux_x64 runtime, appimagetool (pre-extracted, no FUSE) and type2 runtime.
38
+ COPY scripts/fetch_desktop_tools.sh /tmp/fetch_desktop_tools.sh
39
+ RUN sh /tmp/fetch_desktop_tools.sh /opt/spaceforge-tools && rm -f /tmp/fetch_desktop_tools.sh
40
+
41
  # Minimal Android SDK (cmdline-tools + platform 34 + build-tools)
42
  ARG CMDLINE_TOOLS_URL=https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
43
  RUN mkdir -p ${ANDROID_HOME}/cmdline-tools ${ANDROID_HOME}/licenses ${GRADLE_USER_HOME} \
backend/app/converters/desktop/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Desktop (Linux) Hosted Wrapper converters built on the prebuilt Neutralinojs runtime."""
backend/app/converters/desktop/arch_pkgbuild.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Arch Linux PKGBUILD converter (CachyOS/Manjaro/EndeavourOS) — Hosted Wrapper.
2
+
3
+ Emits ``<pkgname>-pkgbuild.tar.gz`` with a PKGBUILD whose sources are all bundled local files
4
+ (prebuilt Neutralinojs binary, generated config, launcher, .desktop, icon, license), with real
5
+ sha256sums. ``makepkg -si`` installs to /opt/<pkgname>, /usr/bin/<pkgname>, desktop entry + icon.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import io
11
+ import tarfile
12
+ import time
13
+ from pathlib import Path
14
+
15
+ from backend.app.converters.base import Artifact, BuildContext, Converter, ConverterResult
16
+ from backend.app.converters.desktop import common as dc
17
+
18
+
19
+ def _sha256(data: bytes) -> str:
20
+ return hashlib.sha256(data).hexdigest()
21
+
22
+
23
+ def _sh_single(s: str) -> str:
24
+ """Single-quote a string for bash."""
25
+ return "'" + s.replace("'", "'\"'\"'") + "'"
26
+
27
+
28
+ def build_pkg_files(info: dict) -> tuple[str, dict[str, tuple[bytes, int]]]:
29
+ """Return (pkgname, {relative filename: (bytes, mode)})."""
30
+ binary = dc.neutralino_binary()
31
+ if not binary:
32
+ raise RuntimeError("Neutralinojs binary not available")
33
+ pkg = dc.pkg_name(info)
34
+ embed = info.get("embed_url") or ""
35
+ title = dc.safe_title(info)
36
+ files: dict[str, tuple[bytes, int]] = {}
37
+ files[dc.NEUTRALINO_BIN_NAME] = (binary.read_bytes(), 0o755)
38
+ import json
39
+
40
+ files["neutralino.config.json"] = (
41
+ (json.dumps(dc.neutralino_config(info), indent=2, ensure_ascii=False) + "\n").encode(), 0o644
42
+ )
43
+ files[f"{pkg}.sh"] = (dc.launcher_script(f"/opt/{pkg}", pkg).encode(), 0o755)
44
+ files[f"{pkg}.desktop"] = (
45
+ dc.desktop_entry(info, exec_name=pkg, icon_name=pkg, wm_class=pkg).encode(), 0o644
46
+ )
47
+ files[f"{pkg}.png"] = (dc.icon_png(info.get("repo_id") or pkg), 0o644)
48
+ files["LICENSE-neutralinojs"] = (dc.neutralino_license().encode(), 0o644)
49
+
50
+ sources = list(files.keys())
51
+ sums = [_sha256(files[s][0]) for s in sources]
52
+ pkgver = time.strftime("%Y.%m.%d", time.gmtime())
53
+ desc = f"{title} — Hugging Face Space desktop wrapper (SpaceForge Hosted Wrapper)"
54
+ desc = desc.replace("\n", " ")[:200]
55
+ src_lines = "\n".join(f" {_sh_single(s)}" for s in sources)
56
+ sum_lines = "\n".join(f" {_sh_single(s)}" for s in sums)
57
+ pkgbuild = f"""# Maintainer: SpaceForge (generated) <https://huggingface.co/spaces/2Btainment/spaceforge>
58
+ # Hosted Wrapper for https://huggingface.co/spaces/{info.get('repo_id')}
59
+ # Window loads {embed} via prebuilt Neutralinojs {dc.NEUTRALINO_VERSION} + system WebKitGTK 4.1.
60
+ pkgname={pkg}
61
+ pkgver={pkgver}
62
+ pkgrel=1
63
+ pkgdesc={_sh_single(desc)}
64
+ arch=('x86_64')
65
+ url={_sh_single(info.get('space_url') or embed)}
66
+ license=('MIT')
67
+ depends=('webkit2gtk-4.1' 'gtk3' 'glibc' 'gcc-libs')
68
+ options=('!strip' '!debug')
69
+ source=(
70
+ {src_lines}
71
+ )
72
+ sha256sums=(
73
+ {sum_lines}
74
+ )
75
+
76
+ package() {{
77
+ cd "$srcdir"
78
+ install -Dm755 {dc.NEUTRALINO_BIN_NAME} "$pkgdir/opt/$pkgname/{dc.NEUTRALINO_BIN_NAME}"
79
+ install -Dm644 neutralino.config.json "$pkgdir/opt/$pkgname/neutralino.config.json"
80
+ install -Dm644 "$pkgname.png" "$pkgdir/opt/$pkgname/icon.png"
81
+ install -Dm755 "$pkgname.sh" "$pkgdir/opt/$pkgname/$pkgname"
82
+ install -d "$pkgdir/usr/bin"
83
+ ln -s "/opt/$pkgname/$pkgname" "$pkgdir/usr/bin/$pkgname"
84
+ install -Dm644 "$pkgname.desktop" "$pkgdir/usr/share/applications/$pkgname.desktop"
85
+ install -Dm644 "$pkgname.png" "$pkgdir/usr/share/icons/hicolor/256x256/apps/$pkgname.png"
86
+ install -Dm644 LICENSE-neutralinojs "$pkgdir/usr/share/licenses/$pkgname/LICENSE-neutralinojs"
87
+ }}
88
+ """
89
+ files["PKGBUILD"] = (pkgbuild.encode(), 0o644)
90
+ readme = (
91
+ f"tar xf {pkg}-pkgbuild.tar.gz\n"
92
+ f"cd {pkg}\n"
93
+ "makepkg -si\n"
94
+ "\n"
95
+ f"# {title} — Arch Linux package (SpaceForge Hosted Wrapper)\n"
96
+ f"# Installs /opt/{pkg}, /usr/bin/{pkg}, a desktop entry and icon. Uninstall: sudo pacman -R {pkg}\n"
97
+ f"# The window loads {embed} (needs network + the Space running). Deps: webkit2gtk-4.1, gtk3.\n"
98
+ )
99
+ files["README.md"] = (readme.encode(), 0o644)
100
+ return pkg, files
101
+
102
+
103
+ class ArchPkgbuildConverter(Converter):
104
+ id = "arch_pkgbuild"
105
+ label = "Arch Linux (PKGBUILD)"
106
+ mode = "hosted_wrapper"
107
+ stub = False
108
+
109
+ @property
110
+ def available(self) -> bool: # type: ignore[override]
111
+ return dc.neutralino_binary() is not None
112
+
113
+ async def convert(self, ctx: BuildContext) -> ConverterResult:
114
+ info = ctx.space_info
115
+ if not dc.neutralino_binary():
116
+ msg = "Arch PKGBUILD: Neutralinojs binary not installed in this SpaceForge image."
117
+ ctx.info(msg)
118
+ return ConverterResult(ok=False, error=msg)
119
+ pkg, files = build_pkg_files(info)
120
+ name = dc.file_slug(info.get("name") or "app")
121
+ out = ctx.work_dir / f"{name}-pkgbuild.tar.gz"
122
+ now = int(time.time())
123
+ with tarfile.open(out, "w:gz") as tf:
124
+ d = tarfile.TarInfo(pkg)
125
+ d.type = tarfile.DIRTYPE
126
+ d.mode = 0o755
127
+ d.mtime = now
128
+ tf.addfile(d)
129
+ for rel, (data, mode) in files.items():
130
+ ti = tarfile.TarInfo(f"{pkg}/{rel}")
131
+ ti.size = len(data)
132
+ ti.mode = mode
133
+ ti.mtime = now
134
+ tf.addfile(ti, io.BytesIO(data))
135
+ ctx.info(
136
+ f"OK: Arch PKGBUILD tarball {out.name} ({out.stat().st_size} bytes) pkgname={pkg} "
137
+ f"(Neutralinojs {dc.NEUTRALINO_VERSION}; depends webkit2gtk-4.1 gtk3)"
138
+ )
139
+ return ConverterResult(
140
+ ok=True,
141
+ artifact=Artifact(
142
+ target_id=self.id,
143
+ path=out,
144
+ filename=out.name,
145
+ mode=self.mode,
146
+ media_type="application/gzip",
147
+ notes=(
148
+ f"Arch/CachyOS package source: tar xf {out.name}; cd {pkg}; makepkg -si. "
149
+ f"Installs /opt/{pkg} + /usr/bin/{pkg} + desktop entry. Hosted Wrapper: loads "
150
+ f"{info.get('embed_url')} (needs network + Space running). depends: webkit2gtk-4.1, gtk3."
151
+ ),
152
+ binary_included=True,
153
+ ),
154
+ )
backend/app/converters/desktop/common.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers for Neutralinojs-based Linux desktop wrappers (AppImage + Arch PKGBUILD).
2
+
3
+ Per-build work is packaging only: the prebuilt, pinned ``neutralino-linux_x64`` binary
4
+ (fetched + sha256-verified at Docker build time) is combined with a generated
5
+ ``neutralino.config.json`` whose ``url`` is the live Space (``embed_url``).
6
+ The resulting app is a **Hosted Wrapper**: it needs the Space online + network.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import struct
15
+ import zlib
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from backend.app.converters.mobile.android import _app_id, _pkg_segment
20
+
21
+ TOOLS_ROOT = Path(os.environ.get("SPACEFORGE_TOOLS", "/opt/spaceforge-tools"))
22
+ NEUTRALINO_VERSION = os.environ.get("SPACEFORGE_NEUTRALINO_VERSION", "6.10.0")
23
+ NEUTRALINO_BIN_NAME = "neutralino-linux_x64"
24
+
25
+ _MIT_FALLBACK = """MIT License
26
+
27
+ Copyright (c) 2021-2025 Neutralinojs and contributors
28
+
29
+ Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ of this software and associated documentation files (the "Software"), to deal
31
+ in the Software without restriction, including without limitation the rights
32
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ copies of the Software, and to permit persons to whom the Software is
34
+ furnished to do so, subject to the following conditions:
35
+
36
+ The above copyright notice and this permission notice shall be included in all
37
+ copies or substantial portions of the Software.
38
+
39
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
45
+ SOFTWARE.
46
+ """
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Tool discovery
51
+ # ---------------------------------------------------------------------------
52
+
53
+ def neutralino_binary() -> Path | None:
54
+ raw = os.environ.get("SPACEFORGE_NEUTRALINO_BIN", "").strip()
55
+ p = Path(raw) if raw else TOOLS_ROOT / "neutralino" / NEUTRALINO_BIN_NAME
56
+ return p if p.is_file() and os.access(p, os.R_OK) else None
57
+
58
+
59
+ def neutralino_license() -> str:
60
+ for p in (
61
+ Path(os.environ.get("SPACEFORGE_NEUTRALINO_LICENSE", "") or "/nonexistent"),
62
+ TOOLS_ROOT / "neutralino" / "LICENSE",
63
+ ):
64
+ if p.is_file():
65
+ try:
66
+ return p.read_text(encoding="utf-8", errors="replace")
67
+ except OSError:
68
+ pass
69
+ return _MIT_FALLBACK
70
+
71
+
72
+ def appimagetool_cmd() -> list[str] | None:
73
+ """Return the argv prefix for appimagetool (extracted AppRun preferred; no FUSE needed)."""
74
+ raw = os.environ.get("SPACEFORGE_APPIMAGETOOL", "").strip()
75
+ cands = [Path(raw)] if raw else [
76
+ TOOLS_ROOT / "appimagetool" / "AppRun",
77
+ TOOLS_ROOT / "appimagetool-x86_64.AppImage",
78
+ ]
79
+ for p in cands:
80
+ if p.is_file() and os.access(p, os.X_OK):
81
+ if p.suffix == ".AppImage":
82
+ return [str(p), "--appimage-extract-and-run"]
83
+ return [str(p)]
84
+ return None
85
+
86
+
87
+ def appimage_runtime() -> Path | None:
88
+ raw = os.environ.get("SPACEFORGE_APPIMAGE_RUNTIME", "").strip()
89
+ p = Path(raw) if raw else TOOLS_ROOT / "runtime-x86_64"
90
+ return p if p.is_file() else None
91
+
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # Naming (consistent with the Android fix: owner + full space name, sanitized)
95
+ # ---------------------------------------------------------------------------
96
+
97
+ def file_slug(s: str) -> str:
98
+ out = "".join(c if c.isalnum() or c in "-_" else "-" for c in (s or ""))[:48].strip("-")
99
+ return out or "spaceforge-app"
100
+
101
+
102
+ def owner_of(info: dict[str, Any]) -> str:
103
+ return info.get("owner") or (info.get("repo_id") or "").split("/")[0]
104
+
105
+
106
+ def app_id(info: dict[str, Any]) -> str:
107
+ """com.spaceforge.<owner>.<space> — same scheme as the Android applicationId."""
108
+ return _app_id(info.get("name") or "", owner_of(info))
109
+
110
+
111
+ def pkg_name(info: dict[str, Any]) -> str:
112
+ """Arch/desktop-safe package name: spaceforge-<owner>-<space> (lowercase, [a-z0-9-])."""
113
+ parts = []
114
+ for raw in (owner_of(info), info.get("name") or ""):
115
+ seg = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-")
116
+ if seg:
117
+ parts.append(seg)
118
+ name = "-".join(["spaceforge", *parts]) if parts else "spaceforge-app"
119
+ return re.sub(r"-+", "-", name)[:100].strip("-")
120
+
121
+
122
+ def safe_title(info: dict[str, Any]) -> str:
123
+ t = str(info.get("title") or info.get("repo_id") or "SpaceForge App")
124
+ t = re.sub(r"[\r\n\t]+", " ", t).strip()
125
+ return t[:80] or "SpaceForge App"
126
+
127
+
128
+ def desktop_escape(s: str) -> str:
129
+ """Escape a value for a .desktop file string (no newlines / control chars)."""
130
+ s = re.sub(r"[\x00-\x1f]+", " ", s)
131
+ return s.replace("\\", "\\\\")
132
+
133
+
134
+ # ---------------------------------------------------------------------------
135
+ # Generated files
136
+ # ---------------------------------------------------------------------------
137
+
138
+ def neutralino_config(info: dict[str, Any], *, icon: str = "/icon.png") -> dict[str, Any]:
139
+ embed = info.get("embed_url") or ""
140
+ return {
141
+ "applicationId": app_id(info),
142
+ "version": "1.0.0",
143
+ "defaultMode": "window",
144
+ # Remote URL as main window — Neutralino loads it directly in WebKitGTK.
145
+ "url": embed,
146
+ "documentRoot": "/",
147
+ "enableServer": False,
148
+ "enableNativeAPI": False,
149
+ "enableExtensions": False,
150
+ "tokenSecurity": "one-time",
151
+ "nativeBlockList": ["*"],
152
+ # The install dir (AppImage squashfs / /opt) is read-only -> keep state in ~/.local/share
153
+ "dataLocation": "system",
154
+ "storageLocation": "system",
155
+ "logging": {"enabled": True, "writeToLogFile": False},
156
+ "globalVariables": {
157
+ "SPACEFORGE_SPACE": info.get("repo_id"),
158
+ "SPACEFORGE_MODE": "hosted_wrapper",
159
+ },
160
+ "modes": {
161
+ "window": {
162
+ "title": safe_title(info),
163
+ "width": 1200,
164
+ "height": 820,
165
+ "minWidth": 480,
166
+ "minHeight": 360,
167
+ "center": True,
168
+ "resizable": True,
169
+ "icon": icon,
170
+ "exitProcessOnClose": True,
171
+ "useSavedState": True,
172
+ "enableInspector": False,
173
+ "newWindowPolicy": "browser",
174
+ "extendUserAgentWith": "SpaceForge/1.0",
175
+ }
176
+ },
177
+ }
178
+
179
+
180
+ def launcher_script(app_dir_expr: str, prgname: str) -> str:
181
+ """Bash launcher; ``app_dir_expr`` is a shell expression that resolves the app dir."""
182
+ return f"""#!/bin/bash
183
+ # SpaceForge launcher (Hosted Wrapper) — Neutralinojs {NEUTRALINO_VERSION} + WebKitGTK
184
+ APP_DIR={app_dir_expr}
185
+ LDC="$(command -v ldconfig 2>/dev/null || echo /sbin/ldconfig)"
186
+ if [ -x "$LDC" ] && ! "$LDC" -p 2>/dev/null | grep -qE 'libwebkit2gtk-4\\.(1|0)\\.so'; then
187
+ echo "[spaceforge] warning: libwebkit2gtk-4.1 (or 4.0) not found — install webkit2gtk-4.1 / libwebkit2gtk-4.1-0" >&2
188
+ fi
189
+ # WebKitGTK on some GPUs/VMs renders blank without this; user env wins.
190
+ export WEBKIT_DISABLE_DMABUF_RENDERER="${{WEBKIT_DISABLE_DMABUF_RENDERER:-1}}"
191
+ exec -a "{prgname}" "$APP_DIR/{NEUTRALINO_BIN_NAME}" --path="$APP_DIR" --load-dir-res "$@"
192
+ """
193
+
194
+
195
+ def desktop_entry(info: dict[str, Any], *, exec_name: str, icon_name: str, wm_class: str) -> str:
196
+ title = desktop_escape(safe_title(info))
197
+ comment = desktop_escape(
198
+ (info.get("short_description") or f"Hugging Face Space {info.get('repo_id')}")[:140]
199
+ )
200
+ return (
201
+ "[Desktop Entry]\n"
202
+ "Type=Application\n"
203
+ f"Name={title}\n"
204
+ f"Comment={comment} (SpaceForge Hosted Wrapper)\n"
205
+ f"Exec={exec_name} %U\n"
206
+ f"Icon={icon_name}\n"
207
+ "Terminal=false\n"
208
+ "Categories=Network;Utility;\n"
209
+ f"StartupWMClass={wm_class}\n"
210
+ "Keywords=huggingface;space;ai;spaceforge;\n"
211
+ )
212
+
213
+
214
+ def readme_runtime_deps() -> str:
215
+ return (
216
+ "## Runtime requirements\n\n"
217
+ "- x86_64 Linux with a graphical session (X11 or Wayland)\n"
218
+ "- **WebKitGTK 4.1** (preferred) or 4.0 and GTK 3:\n"
219
+ " - Arch / CachyOS / Manjaro: `sudo pacman -S webkit2gtk-4.1 gtk3`\n"
220
+ " - Debian / Ubuntu: `sudo apt install libwebkit2gtk-4.1-0 libgtk-3-0`\n"
221
+ " - Fedora: `sudo dnf install webkit2gtk4.1 gtk3`\n"
222
+ "- Network access: this is a **Hosted Wrapper** — the window loads the live Hugging Face Space.\n"
223
+ " If the Space is sleeping/paused/private, you'll see the Hugging Face page instead of the app.\n"
224
+ "- If the window stays blank on some GPUs/VMs, the launcher already sets "
225
+ "`WEBKIT_DISABLE_DMABUF_RENDERER=1`; also try `WEBKIT_DISABLE_COMPOSITING_MODE=1`.\n"
226
+ )
227
+
228
+
229
+ # ---------------------------------------------------------------------------
230
+ # Icon: pure-python PNG (no Pillow in the image). Default "Einswarm" style:
231
+ # rounded square with a per-Space gradient + hub mark. Deterministic per repo id.
232
+ # ---------------------------------------------------------------------------
233
+
234
+ def _png(width: int, height: int, rgba_rows: list[bytes]) -> bytes:
235
+ raw = b"".join(b"\x00" + row for row in rgba_rows)
236
+
237
+ def chunk(tag: bytes, data: bytes) -> bytes:
238
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
239
+
240
+ ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
241
+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")
242
+
243
+
244
+ def _hsv(h: float, s: float, v: float) -> tuple[int, int, int]:
245
+ import colorsys
246
+
247
+ r, g, b = colorsys.hsv_to_rgb(h % 1.0, s, v)
248
+ return int(r * 255), int(g * 255), int(b * 255)
249
+
250
+
251
+ def icon_png(seed: str, size: int = 256) -> bytes:
252
+ h = int(hashlib.sha256(seed.encode("utf-8")).hexdigest()[:8], 16) / 0xFFFFFFFF
253
+ c1 = _hsv(h, 0.70, 0.95)
254
+ c2 = _hsv(h + 0.18, 0.80, 0.55)
255
+ radius = size * 0.22
256
+ cx = cy = (size - 1) / 2
257
+ rows: list[bytes] = []
258
+ for y in range(size):
259
+ row = bytearray()
260
+ for x in range(size):
261
+ # rounded-square mask
262
+ dx = max(abs(x - cx) - (cx - radius), 0)
263
+ dy = max(abs(y - cy) - (cy - radius), 0)
264
+ if dx * dx + dy * dy > radius * radius:
265
+ row += b"\x00\x00\x00\x00"
266
+ continue
267
+ t = (x + y) / (2 * (size - 1))
268
+ r = int(c1[0] + (c2[0] - c1[0]) * t)
269
+ g = int(c1[1] + (c2[1] - c1[1]) * t)
270
+ b = int(c1[2] + (c2[2] - c1[2]) * t)
271
+ d = ((x - cx) ** 2 + (y - cy) ** 2) ** 0.5
272
+ # hub mark: white ring + center dot + 6 satellite dots ("swarm")
273
+ white = (size * 0.27 < d < size * 0.33) or d < size * 0.11
274
+ if not white:
275
+ import math
276
+
277
+ for k in range(6):
278
+ a = k * math.pi / 3 + math.pi / 6
279
+ sx = cx + math.cos(a) * size * 0.30
280
+ sy = cy + math.sin(a) * size * 0.30
281
+ if (x - sx) ** 2 + (y - sy) ** 2 < (size * 0.055) ** 2:
282
+ white = True
283
+ break
284
+ if white:
285
+ r, g, b = 255, 255, 255
286
+ row += bytes((r, g, b, 255))
287
+ rows.append(bytes(row))
288
+ return _png(size, size, rows)
289
+
290
+
291
+ def write_json(path: Path, data: Any) -> None:
292
+ path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
backend/app/converters/desktop/linux_appimage.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Linux AppImage converter — real x86_64 AppImage (Hosted Wrapper).
2
+
3
+ Packaging only: pinned prebuilt Neutralinojs ``neutralino-linux_x64`` + generated config that
4
+ loads the live Space URL, assembled into an AppDir and packed with pinned ``appimagetool``
5
+ (extracted at Docker build time, so no FUSE is needed) using a pinned type2 runtime.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ from pathlib import Path
14
+
15
+ from backend.app.converters.base import Artifact, BuildContext, Converter, ConverterResult
16
+ from backend.app.converters.desktop import common as dc
17
+
18
+
19
+ def appimage_tools_ready() -> bool:
20
+ # appimagetool shells out to `file`; mksquashfs ships inside the extracted appimagetool.
21
+ return bool(dc.neutralino_binary() and dc.appimagetool_cmd() and shutil.which("file"))
22
+
23
+
24
+ def check_appimage(path: Path) -> None:
25
+ """Cheap structural check: ELF executable carrying the AppImage type-2 magic (AI\\x02 at 8)."""
26
+ with path.open("rb") as fh:
27
+ head = fh.read(16)
28
+ if head[:4] != b"\x7fELF" or head[8:11] != b"AI\x02":
29
+ raise RuntimeError("packed file is not an ELF type-2 AppImage")
30
+
31
+
32
+ def build_appdir(info: dict, appdir: Path) -> dict:
33
+ """Assemble an AppDir. Returns metadata (pkg, app_id, embed)."""
34
+ pkg = dc.pkg_name(info)
35
+ aid = dc.app_id(info)
36
+ embed = info.get("embed_url") or ""
37
+ binary = dc.neutralino_binary()
38
+ if not binary:
39
+ raise RuntimeError("Neutralinojs binary not available")
40
+
41
+ lib = appdir / "usr" / "lib" / pkg
42
+ for d in (
43
+ lib,
44
+ appdir / "usr" / "bin",
45
+ appdir / "usr" / "share" / "applications",
46
+ appdir / "usr" / "share" / "icons" / "hicolor" / "256x256" / "apps",
47
+ appdir / "usr" / "share" / "doc" / pkg,
48
+ appdir / "usr" / "share" / "licenses" / pkg,
49
+ ):
50
+ d.mkdir(parents=True, exist_ok=True)
51
+
52
+ shutil.copy2(binary, lib / dc.NEUTRALINO_BIN_NAME)
53
+ (lib / dc.NEUTRALINO_BIN_NAME).chmod(0o755)
54
+ dc.write_json(lib / "neutralino.config.json", dc.neutralino_config(info))
55
+ icon = dc.icon_png(info.get("repo_id") or pkg)
56
+ (lib / "icon.png").write_bytes(icon)
57
+ (appdir / f"{pkg}.png").write_bytes(icon)
58
+ (appdir / "usr" / "share" / "icons" / "hicolor" / "256x256" / "apps" / f"{pkg}.png").write_bytes(icon)
59
+ os.symlink(f"{pkg}.png", appdir / ".DirIcon")
60
+
61
+ # Launcher inside usr/bin (also usable after --appimage-extract) + AppRun at root.
62
+ launcher = appdir / "usr" / "bin" / pkg
63
+ launcher.write_text(
64
+ dc.launcher_script('"$(dirname "$(readlink -f "$0")")/../lib/' + pkg + '"', pkg),
65
+ encoding="utf-8",
66
+ )
67
+ launcher.chmod(0o755)
68
+ apprun = appdir / "AppRun"
69
+ apprun.write_text(
70
+ dc.launcher_script('"${APPDIR:-$(dirname "$(readlink -f "$0")")}/usr/lib/' + pkg + '"', pkg),
71
+ encoding="utf-8",
72
+ )
73
+ apprun.chmod(0o755)
74
+
75
+ desktop = dc.desktop_entry(info, exec_name=pkg, icon_name=pkg, wm_class=pkg)
76
+ (appdir / f"{pkg}.desktop").write_text(desktop, encoding="utf-8")
77
+ (appdir / "usr" / "share" / "applications" / f"{pkg}.desktop").write_text(desktop, encoding="utf-8")
78
+
79
+ (appdir / "usr" / "share" / "licenses" / pkg / "LICENSE-neutralinojs").write_text(
80
+ dc.neutralino_license(), encoding="utf-8"
81
+ )
82
+ readme = (
83
+ f"# {dc.safe_title(info)} — Linux AppImage (SpaceForge)\n\n"
84
+ f"Hosted Wrapper for the Hugging Face Space `{info.get('repo_id')}`.\n"
85
+ f"The window loads **{embed}** in WebKitGTK via Neutralinojs {dc.NEUTRALINO_VERSION}.\n"
86
+ "Nothing of the model runs locally; inference stays on Hugging Face.\n\n"
87
+ "## Run\n\n"
88
+ "```bash\n"
89
+ f"chmod +x {dc.file_slug(info.get('name') or pkg)}-x86_64.AppImage\n"
90
+ f"./{dc.file_slug(info.get('name') or pkg)}-x86_64.AppImage\n"
91
+ "# no FUSE? -> ./<file>.AppImage --appimage-extract-and-run\n"
92
+ "```\n\n"
93
+ + dc.readme_runtime_deps()
94
+ + f"\nApp id: `{aid}` · package: `{pkg}` · built by SpaceForge (2Btainment).\n"
95
+ "Neutralinojs is MIT licensed (see usr/share/licenses).\n"
96
+ )
97
+ (appdir / "usr" / "share" / "doc" / pkg / "README.md").write_text(readme, encoding="utf-8")
98
+ (appdir / "README.md").write_text(readme, encoding="utf-8")
99
+ dc.write_json(
100
+ appdir / "usr" / "share" / "doc" / pkg / "spaceforge.json",
101
+ {
102
+ "product": "SpaceForge",
103
+ "target": "linux_appimage",
104
+ "mode": "hosted_wrapper",
105
+ "runtime": f"neutralinojs {dc.NEUTRALINO_VERSION} (webkit2gtk)",
106
+ "app_id": aid,
107
+ "package": pkg,
108
+ "space": info.get("repo_id"),
109
+ "embed_url": embed,
110
+ "space_url": info.get("space_url"),
111
+ "binary_included": True,
112
+ },
113
+ )
114
+ return {"pkg": pkg, "app_id": aid, "embed": embed}
115
+
116
+
117
+ def pack_appimage(appdir: Path, out: Path, log) -> None:
118
+ cmd = dc.appimagetool_cmd()
119
+ if not cmd:
120
+ raise RuntimeError("appimagetool not available")
121
+ argv = [*cmd, "--no-appstream"]
122
+ rt = dc.appimage_runtime()
123
+ if rt:
124
+ argv += ["--runtime-file", str(rt)]
125
+ argv += [str(appdir), str(out)]
126
+ env = os.environ.copy()
127
+ env["ARCH"] = "x86_64"
128
+ env["APPIMAGE_EXTRACT_AND_RUN"] = "1"
129
+ env.pop("SOURCE_DATE_EPOCH", None)
130
+ log("$ " + " ".join(Path(a).name if i == 0 else a for i, a in enumerate(argv)))
131
+ proc = subprocess.run(argv, env=env, capture_output=True, text=True, timeout=240)
132
+ tail = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip().splitlines()[-12:]
133
+ for line in tail:
134
+ if line.strip():
135
+ log(" " + line[:300])
136
+ if proc.returncode != 0 or not out.is_file():
137
+ raise RuntimeError(f"appimagetool failed (exit {proc.returncode})")
138
+ out.chmod(0o755)
139
+ check_appimage(out)
140
+
141
+
142
+ class LinuxAppImageConverter(Converter):
143
+ id = "linux_appimage"
144
+ label = "Linux AppImage"
145
+ mode = "hosted_wrapper"
146
+ stub = False
147
+
148
+ @property
149
+ def available(self) -> bool: # type: ignore[override]
150
+ return appimage_tools_ready()
151
+
152
+ async def convert(self, ctx: BuildContext) -> ConverterResult:
153
+ info = ctx.space_info
154
+ if not appimage_tools_ready():
155
+ msg = "Linux AppImage: Neutralinojs/appimagetool/`file` not installed in this SpaceForge image."
156
+ ctx.info(msg)
157
+ return ConverterResult(ok=False, error=msg)
158
+ name = dc.file_slug(info.get("name") or "app")
159
+ appdir = ctx.work_dir / "appimage" / f"{name}.AppDir"
160
+ if appdir.exists():
161
+ shutil.rmtree(appdir)
162
+ appdir.mkdir(parents=True)
163
+ ctx.info(
164
+ f"Linux AppImage for {info.get('repo_id')}: Neutralinojs {dc.NEUTRALINO_VERSION} "
165
+ f"prebuilt runtime → window loads {info.get('embed_url')} (Hosted Wrapper)"
166
+ )
167
+ meta = build_appdir(info, appdir)
168
+ out = ctx.work_dir / f"{name}-x86_64.AppImage"
169
+ await asyncio.to_thread(pack_appimage, appdir, out, ctx.info)
170
+ size = out.stat().st_size
171
+ ctx.info(f"OK: AppImage ready {out.name} ({size} bytes) package={meta['pkg']}")
172
+ return ConverterResult(
173
+ ok=True,
174
+ artifact=Artifact(
175
+ target_id=self.id,
176
+ path=out,
177
+ filename=out.name,
178
+ mode=self.mode,
179
+ media_type="application/vnd.appimage",
180
+ notes=(
181
+ f"Real x86_64 AppImage (Neutralinojs {dc.NEUTRALINO_VERSION} + system WebKitGTK). "
182
+ f"Hosted Wrapper: window loads {meta['embed']} — needs network and the Space running. "
183
+ "Runtime deps: libwebkit2gtk-4.1 (or 4.0) + GTK3. "
184
+ "No FUSE? run with --appimage-extract-and-run."
185
+ ),
186
+ binary_included=True,
187
+ ),
188
+ )
backend/app/converters/registry.py CHANGED
@@ -10,10 +10,9 @@ from backend.app.converters.firefox_ext import FirefoxExtConverter
10
  from backend.app.converters.chromium_ext import ChromiumExtConverter
11
  from backend.app.converters.tauri import TauriConverter
12
  from backend.app.converters.mobile.android import AndroidConverter
13
- from backend.app.converters.stubs import (
14
- LinuxAppImageStub,
15
- WindowsPortableStub,
16
- )
17
 
18
 
19
  def get_registry() -> Dict[str, Converter]:
@@ -24,7 +23,8 @@ def get_registry() -> Dict[str, Converter]:
24
  ChromiumExtConverter(),
25
  TauriConverter(),
26
  AndroidConverter(),
27
- LinuxAppImageStub(),
 
28
  WindowsPortableStub(),
29
  ]
30
  return {c.id: c for c in converters}
 
10
  from backend.app.converters.chromium_ext import ChromiumExtConverter
11
  from backend.app.converters.tauri import TauriConverter
12
  from backend.app.converters.mobile.android import AndroidConverter
13
+ from backend.app.converters.desktop.linux_appimage import LinuxAppImageConverter
14
+ from backend.app.converters.desktop.arch_pkgbuild import ArchPkgbuildConverter
15
+ from backend.app.converters.stubs import WindowsPortableStub
 
16
 
17
 
18
  def get_registry() -> Dict[str, Converter]:
 
23
  ChromiumExtConverter(),
24
  TauriConverter(),
25
  AndroidConverter(),
26
+ LinuxAppImageConverter(),
27
+ ArchPkgbuildConverter(),
28
  WindowsPortableStub(),
29
  ]
30
  return {c.id: c for c in converters}
backend/app/converters/stubs.py CHANGED
@@ -19,11 +19,6 @@ class _Stub(Converter):
19
  return ConverterResult(ok=False, error=msg, project_only=True)
20
 
21
 
22
- class LinuxAppImageStub(_Stub):
23
- id = "linux_appimage"
24
- label = "Linux AppImage"
25
-
26
-
27
  class WindowsPortableStub(_Stub):
28
  id = "windows_portable"
29
  label = "Windows Portable"
 
19
  return ConverterResult(ok=False, error=msg, project_only=True)
20
 
21
 
 
 
 
 
 
22
  class WindowsPortableStub(_Stub):
23
  id = "windows_portable"
24
  label = "Windows Portable"
backend/app/providers/huggingface.py CHANGED
@@ -150,7 +150,12 @@ async def fetch_space_info(owner: str, name: str, token: Optional[str] = None) -
150
  def classify_compatibility(info: dict[str, Any]) -> dict[str, Any]:
151
  from backend.app.converters.mobile.android_sdk import android_sdk_ready
152
 
 
 
 
153
  _apk_env = android_sdk_ready()
 
 
154
  sdk = info.get("sdk", "unknown")
155
  notes: list[str] = []
156
  warnings: list[str] = []
@@ -246,11 +251,42 @@ def classify_compatibility(info: dict[str, Any]) -> dict[str, Any]:
246
  {
247
  "id": "linux_appimage",
248
  "label": "Linux AppImage",
249
- "mode": "local",
250
- "available": False,
251
- "stub": True,
252
- "artifact": "project-only",
253
- "reason": "Binary AppImage build not available in HF Space CPU environment. Use Tauri project locally.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  },
255
  {
256
  "id": "windows_portable",
 
150
  def classify_compatibility(info: dict[str, Any]) -> dict[str, Any]:
151
  from backend.app.converters.mobile.android_sdk import android_sdk_ready
152
 
153
+ from backend.app.converters.desktop.common import neutralino_binary
154
+ from backend.app.converters.desktop.linux_appimage import appimage_tools_ready
155
+
156
  _apk_env = android_sdk_ready()
157
+ _appimage_ok = appimage_tools_ready()
158
+ _pkgbuild_ok = neutralino_binary() is not None
159
  sdk = info.get("sdk", "unknown")
160
  notes: list[str] = []
161
  warnings: list[str] = []
 
251
  {
252
  "id": "linux_appimage",
253
  "label": "Linux AppImage",
254
+ "mode": "hosted_wrapper",
255
+ "available": _appimage_ok,
256
+ "stub": False,
257
+ "artifact": "appimage",
258
+ "reason": (
259
+ "✓ Real x86_64 AppImage (prebuilt Neutralinojs + system WebKitGTK 4.1) · "
260
+ "⚠ Hosted Wrapper: window loads the live Space (needs network + Space running)"
261
+ if _appimage_ok
262
+ else "AppImage tooling not installed in this SpaceForge image."
263
+ ),
264
+ },
265
+ {
266
+ "id": "arch_pkgbuild",
267
+ "label": "Arch Linux (PKGBUILD)",
268
+ "mode": "hosted_wrapper",
269
+ "available": _pkgbuild_ok,
270
+ "stub": False,
271
+ "artifact": "tar.gz",
272
+ "reason": (
273
+ "✓ PKGBUILD tarball for Arch/CachyOS: tar xf · cd · makepkg -si "
274
+ "(installs /opt + /usr/bin + desktop entry) · ⚠ Hosted Wrapper (needs network)"
275
+ if _pkgbuild_ok
276
+ else "Neutralinojs runtime not installed in this SpaceForge image."
277
+ ),
278
+ },
279
+ {
280
+ "id": "mcp",
281
+ "label": "MCP Server / Config",
282
+ "mode": "hosted_wrapper",
283
+ "available": True,
284
+ "stub": False,
285
+ "artifact": "zip",
286
+ "reason": (
287
+ "✓ MCP configs (Cursor / Claude Desktop) if the Space exposes Gradio MCP, "
288
+ "otherwise a Python FastMCP stdio server wrapping the Space API · ⚠ calls the live Space"
289
+ ),
290
  },
291
  {
292
  "id": "windows_portable",
backend/app/services/builds.py CHANGED
@@ -151,6 +151,7 @@ class BuildManager:
151
  if result.ok and result.artifact:
152
  art = result.artifact
153
  is_apk = art.path.suffix.lower() == ".apk"
 
154
  job.artifacts[tid] = {
155
  "filename": art.filename,
156
  "mode": art.mode,
@@ -158,9 +159,14 @@ class BuildManager:
158
  "notes": art.notes,
159
  "size": art.path.stat().st_size if art.path.exists() else 0,
160
  "path_name": art.path.name,
161
- "binary_included": is_apk,
162
  "apk_included": is_apk,
163
- "artifact_kind": "apk" if is_apk else ("project-zip" if art.filename.endswith(".zip") else "file"),
 
 
 
 
 
164
  "project_only": bool(result.project_only),
165
  }
166
  job.logs.append(
 
151
  if result.ok and result.artifact:
152
  art = result.artifact
153
  is_apk = art.path.suffix.lower() == ".apk"
154
+ has_binary = is_apk or bool(art.binary_included)
155
  job.artifacts[tid] = {
156
  "filename": art.filename,
157
  "mode": art.mode,
 
159
  "notes": art.notes,
160
  "size": art.path.stat().st_size if art.path.exists() else 0,
161
  "path_name": art.path.name,
162
+ "binary_included": has_binary,
163
  "apk_included": is_apk,
164
+ "artifact_kind": (
165
+ "apk" if is_apk
166
+ else "appimage" if art.filename.endswith(".AppImage")
167
+ else "project-zip" if art.filename.endswith(".zip")
168
+ else "file"
169
+ ),
170
  "project_only": bool(result.project_only),
171
  }
172
  job.logs.append(
backend/tests/test_converters.py CHANGED
@@ -8,7 +8,7 @@ from backend.app.converters.base import BuildContext
8
  from backend.app.converters.firefox_ext import FirefoxExtConverter
9
  from backend.app.converters.html_widget import HtmlWidgetConverter
10
  from backend.app.converters.pwa import PwaConverter
11
- from backend.app.converters.stubs import LinuxAppImageStub
12
  from backend.app.converters.tauri import TauriConverter
13
 
14
 
@@ -75,8 +75,8 @@ async def test_tauri_project_only(tmp_path: Path):
75
 
76
 
77
  @pytest.mark.asyncio
78
- async def test_stub_appimage(tmp_path: Path):
79
- r = await LinuxAppImageStub().convert(_ctx(tmp_path))
80
  assert not r.ok
81
  assert r.project_only
82
  assert "not available" in (r.error or "").lower() or "HF" in (r.error or "")
 
8
  from backend.app.converters.firefox_ext import FirefoxExtConverter
9
  from backend.app.converters.html_widget import HtmlWidgetConverter
10
  from backend.app.converters.pwa import PwaConverter
11
+ from backend.app.converters.stubs import WindowsPortableStub
12
  from backend.app.converters.tauri import TauriConverter
13
 
14
 
 
75
 
76
 
77
  @pytest.mark.asyncio
78
+ async def test_stub_windows_portable(tmp_path: Path):
79
+ r = await WindowsPortableStub().convert(_ctx(tmp_path))
80
  assert not r.ok
81
  assert r.project_only
82
  assert "not available" in (r.error or "").lower() or "HF" in (r.error or "")
backend/tests/test_desktop.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Linux desktop targets: AppImage + Arch PKGBUILD (Neutralinojs Hosted Wrapper)."""
2
+ import io
3
+ import json
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import tarfile
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from backend.app.converters.base import BuildContext
13
+ from backend.app.converters.desktop import common as dc
14
+
15
+ SAMPLE = {
16
+ "repo_id": "gradio/hello_world",
17
+ "owner": "gradio",
18
+ "name": "hello_world",
19
+ "title": "Hello World",
20
+ "short_description": "demo",
21
+ "sdk": "gradio",
22
+ "embed_url": "https://gradio-hello-world.hf.space",
23
+ "space_url": "https://huggingface.co/spaces/gradio/hello_world",
24
+ }
25
+
26
+
27
+ def _tools_dir() -> Path | None:
28
+ for c in (os.environ.get("SPACEFORGE_TOOLS"), "/opt/spaceforge-tools", "/workspace/sf-tools"):
29
+ if c and (Path(c) / "neutralino" / dc.NEUTRALINO_BIN_NAME).is_file():
30
+ return Path(c)
31
+ return None
32
+
33
+
34
+ @pytest.fixture
35
+ def fake_neutralino(tmp_path, monkeypatch):
36
+ b = tmp_path / "fake-neutralino"
37
+ b.write_bytes(b"\x7fELF fake neutralino binary for tests")
38
+ b.chmod(0o755)
39
+ monkeypatch.setenv("SPACEFORGE_NEUTRALINO_BIN", str(b))
40
+ return b
41
+
42
+
43
+ def test_pkg_name_sanitized():
44
+ assert dc.pkg_name(SAMPLE) == "spaceforge-gradio-hello-world"
45
+ assert dc.pkg_name({"owner": "2Btainment", "name": "Repo.Space__X"}) == "spaceforge-2btainment-repo-space-x"
46
+ assert dc.pkg_name({"repo_id": "", "name": ""}) == "spaceforge-app"
47
+
48
+
49
+ def test_neutralino_config_points_to_space():
50
+ cfg = dc.neutralino_config(SAMPLE)
51
+ assert cfg["url"] == "https://gradio-hello-world.hf.space"
52
+ assert cfg["enableNativeAPI"] is False and cfg["nativeBlockList"] == ["*"]
53
+ assert cfg["applicationId"].startswith("com.spaceforge.")
54
+
55
+
56
+ def test_icon_is_png():
57
+ png = dc.icon_png("x/y", size=32)
58
+ assert png[:8] == b"\x89PNG\r\n\x1a\n"
59
+
60
+
61
+ def test_desktop_entry_no_injection():
62
+ info = dict(SAMPLE, title="Evil\nExec=rm -rf /")
63
+ entry = dc.desktop_entry(info, exec_name="p", icon_name="p", wm_class="p")
64
+ assert [l for l in entry.splitlines() if l.startswith("Exec=")] == ["Exec=p %U"]
65
+
66
+
67
+ def test_appdir_layout(tmp_path, fake_neutralino):
68
+ from backend.app.converters.desktop.linux_appimage import build_appdir
69
+
70
+ appdir = tmp_path / "x.AppDir"
71
+ appdir.mkdir()
72
+ meta = build_appdir(SAMPLE, appdir)
73
+ pkg = meta["pkg"]
74
+ assert (appdir / "AppRun").stat().st_mode & 0o111
75
+ assert (appdir / f"{pkg}.desktop").is_file()
76
+ assert (appdir / f"{pkg}.png").is_file() and (appdir / ".DirIcon").is_symlink()
77
+ cfg = json.loads((appdir / "usr" / "lib" / pkg / "neutralino.config.json").read_text())
78
+ assert cfg["url"] == SAMPLE["embed_url"]
79
+ readme = (appdir / "README.md").read_text()
80
+ assert "webkit2gtk-4.1" in readme and "gtk3" in readme
81
+ r = subprocess.run(["bash", "-n", str(appdir / "AppRun")], capture_output=True)
82
+ assert r.returncode == 0, r.stderr
83
+
84
+
85
+ @pytest.mark.asyncio
86
+ async def test_pkgbuild_tarball(tmp_path, fake_neutralino):
87
+ from backend.app.converters.desktop.arch_pkgbuild import ArchPkgbuildConverter
88
+
89
+ r = await ArchPkgbuildConverter().convert(BuildContext("t", tmp_path, SAMPLE))
90
+ assert r.ok and r.artifact and r.artifact.filename == "hello_world-pkgbuild.tar.gz"
91
+ pkg = "spaceforge-gradio-hello-world"
92
+ with tarfile.open(r.artifact.path) as tf:
93
+ names = tf.getnames()
94
+ assert f"{pkg}/PKGBUILD" in names and f"{pkg}/README.md" in names
95
+ pb = tf.extractfile(f"{pkg}/PKGBUILD").read().decode()
96
+ readme = tf.extractfile(f"{pkg}/README.md").read().decode()
97
+ tf.extractall(tmp_path / "x", filter="data")
98
+ assert f"pkgname={pkg}" in pb
99
+ assert "depends=('webkit2gtk-4.1' 'gtk3'" in pb
100
+ assert "/opt/$pkgname" in pb and "/usr/bin/$pkgname" in pb and "hicolor" in pb
101
+ assert readme.startswith(f"tar xf {pkg}-pkgbuild.tar.gz") or "makepkg -si" in readme
102
+ r2 = subprocess.run(["bash", "-n", str(tmp_path / "x" / pkg / "PKGBUILD")], capture_output=True)
103
+ assert r2.returncode == 0, r2.stderr
104
+ # sha256sums match the bundled sources
105
+ import hashlib
106
+ import re
107
+
108
+ srcs = re.findall(r"^ '([^']+)'$", pb.split("sha256sums=(")[0].split("source=(")[1], re.M)
109
+ sums = re.findall(r"^ '([0-9a-f]{64})'$", pb.split("sha256sums=(")[1], re.M)
110
+ assert len(srcs) == len(sums) > 0
111
+ for s, h in zip(srcs, sums):
112
+ assert hashlib.sha256((tmp_path / "x" / pkg / s).read_bytes()).hexdigest() == h
113
+
114
+
115
+ @pytest.mark.asyncio
116
+ async def test_real_appimage_pack(tmp_path, monkeypatch):
117
+ tools = _tools_dir()
118
+ if not tools or not shutil.which("file"):
119
+ pytest.skip("pinned desktop tools not installed (scripts/fetch_desktop_tools.sh)")
120
+ monkeypatch.setenv("SPACEFORGE_TOOLS", str(tools))
121
+ monkeypatch.delenv("SPACEFORGE_NEUTRALINO_BIN", raising=False)
122
+ import importlib
123
+
124
+ importlib.reload(dc)
125
+ from backend.app.converters.desktop import linux_appimage as la
126
+
127
+ importlib.reload(la)
128
+ r = await la.LinuxAppImageConverter().convert(BuildContext("t", tmp_path, SAMPLE))
129
+ assert r.ok and r.artifact and r.artifact.filename == "hello_world-x86_64.AppImage"
130
+ head = r.artifact.path.read_bytes()[:16]
131
+ assert head[:4] == b"\x7fELF" and head[8:11] == b"AI\x02"
132
+ ex = tmp_path / "ex"
133
+ ex.mkdir()
134
+ p = subprocess.run([str(r.artifact.path), "--appimage-extract"], cwd=ex, capture_output=True, timeout=120)
135
+ assert p.returncode == 0, p.stderr
136
+ root = ex / "squashfs-root"
137
+ assert (root / "AppRun").is_file()
138
+ assert (root / "spaceforge-gradio-hello-world.desktop").is_file()
139
+ cfg = json.loads((root / "usr/lib/spaceforge-gradio-hello-world/neutralino.config.json").read_text())
140
+ assert cfg["url"] == "https://gradio-hello-world.hf.space"
backend/tests/test_provider.py CHANGED
@@ -40,7 +40,7 @@ def test_classify_gpu_and_unknown():
40
  assert any("GPU" in w for w in c["warnings"])
41
  assert c["targets"][0]["id"] == "html_widget"
42
  stubs = [t for t in c["targets"] if t.get("stub")]
43
- assert len(stubs) >= 2 # linux_appimage, windows_portable (android is real converter)
44
  assert all(not t["available"] for t in stubs)
45
  android = next(t for t in c["targets"] if t["id"] == "android")
46
  assert android["available"] is True
@@ -94,3 +94,14 @@ def test_android_compat_no_gpu():
94
  assert android["mode"] == "hosted_wrapper"
95
  assert android["compat"]["gpu_local"] == "warn"
96
  assert "Hosted Wrapper" in android["reason"] or "project" in android["reason"].lower() or "APK" in android["reason"]
 
 
 
 
 
 
 
 
 
 
 
 
40
  assert any("GPU" in w for w in c["warnings"])
41
  assert c["targets"][0]["id"] == "html_widget"
42
  stubs = [t for t in c["targets"] if t.get("stub")]
43
+ assert [t["id"] for t in stubs] == ["windows_portable"] # AppImage/PKGBUILD/MCP are real now
44
  assert all(not t["available"] for t in stubs)
45
  android = next(t for t in c["targets"] if t["id"] == "android")
46
  assert android["available"] is True
 
94
  assert android["mode"] == "hosted_wrapper"
95
  assert android["compat"]["gpu_local"] == "warn"
96
  assert "Hosted Wrapper" in android["reason"] or "project" in android["reason"].lower() or "APK" in android["reason"]
97
+
98
+
99
+ def test_new_targets_listed():
100
+ c = classify_compatibility({"sdk": "gradio", "needs_gpu": False, "private": False})
101
+ ids = [t["id"] for t in c["targets"]]
102
+ for tid in ("linux_appimage", "arch_pkgbuild", "mcp"):
103
+ assert tid in ids
104
+ t = next(x for x in c["targets"] if x["id"] == tid)
105
+ assert t["stub"] is False and t["mode"] == "hosted_wrapper"
106
+ # new targets are listed above the remaining disabled stub
107
+ assert ids.index("mcp") < ids.index("windows_portable")
scripts/fetch_desktop_tools.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # Fetch pinned, sha256-verified prebuilt tools for the Linux desktop targets
3
+ # (linux_appimage, arch_pkgbuild). Usage: fetch_desktop_tools.sh [DEST=/opt/spaceforge-tools]
4
+ set -eu
5
+ DEST="${1:-/opt/spaceforge-tools}"
6
+ NEU_VER="6.10.0"
7
+ NEU_SHA="e633f480737f229f582d8ec6165a52d789340950aef062560702122389f08329"
8
+ AIT_VER="1.9.1"
9
+ AIT_SHA="ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0"
10
+ RT_VER="20251108"
11
+ RT_SHA="2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d"
12
+ LIC_SHA="b860f62b9354b256468430e862053c84c40f6de491c02529bf1cf5c40f688ea7"
13
+
14
+ TMP="$(mktemp -d)"
15
+ trap 'rm -rf "$TMP"' EXIT
16
+ mkdir -p "$DEST/neutralino"
17
+ get() { # url out sha
18
+ curl -fsSL --retry 3 -o "$2" "$1"
19
+ echo "$3 $2" | sha256sum -c -
20
+ }
21
+ get "https://github.com/neutralinojs/neutralinojs/releases/download/v${NEU_VER}/neutralinojs-v${NEU_VER}.zip" "$TMP/neu.zip" "$NEU_SHA"
22
+ get "https://raw.githubusercontent.com/neutralinojs/neutralinojs/v${NEU_VER}/LICENSE" "$TMP/LICENSE" "$LIC_SHA"
23
+ get "https://github.com/AppImage/appimagetool/releases/download/${AIT_VER}/appimagetool-x86_64.AppImage" "$TMP/appimagetool.AppImage" "$AIT_SHA"
24
+ get "https://github.com/AppImage/type2-runtime/releases/download/${RT_VER}/runtime-x86_64" "$TMP/runtime-x86_64" "$RT_SHA"
25
+
26
+ unzip -o -q -j "$TMP/neu.zip" neutralino-linux_x64 -d "$DEST/neutralino"
27
+ chmod 755 "$DEST/neutralino/neutralino-linux_x64"
28
+ cp "$TMP/LICENSE" "$DEST/neutralino/LICENSE"
29
+ echo "$NEU_VER" > "$DEST/neutralino/VERSION"
30
+ cp "$TMP/runtime-x86_64" "$DEST/runtime-x86_64"
31
+
32
+ # Extract appimagetool once so no FUSE is needed at build time (it is itself an AppImage).
33
+ chmod +x "$TMP/appimagetool.AppImage"
34
+ rm -rf "$DEST/appimagetool"
35
+ ( cd "$TMP" && ./appimagetool.AppImage --appimage-extract >/dev/null )
36
+ mv "$TMP/squashfs-root" "$DEST/appimagetool"
37
+ "$DEST/appimagetool/AppRun" --version 2>&1 | head -n 2 || true
38
+ echo "desktop tools ready in $DEST (neutralino $NEU_VER, appimagetool $AIT_VER, runtime $RT_VER)"