Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: support portless desktop managed processes and app→sprite reverse lookup (#2991)

[._.]/ Adam Eivy29619675b498
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d119c67e9b..3aa7345728 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -156,3 +156,4 @@
- **Variable walk-cycle frame count + adjustable walking speed, reprocessable from the clip already on disk** — walk cycles were hardcoded to 8 frames at 12fps, a 0.67s cycle that reads as a run rather than a walk. Two knobs are now user-controlled in the Walk Cycles panel: **frame count** (6–16, default 12 — more frames = smoother) and **playback speed** (4–24 fps, default 10 — lower = slower/more deliberate), with a live "N.NNs / cycle" readout. The deterministic packer resamples the detected gait window *down* to the chosen count (it never upsamples — the count is bounded by the source frames in one cycle) and stamps the chosen fps as playback metadata, so a slower, smoother walk needs **no regeneration**: a per-candidate "Reprocess" rebuilds the loop from the clip already on disk at the current count/speed with no grok call. The runtime atlas grid follows the set's actual frame count (idle + N walk phases), read from the approved run manifests and required identical across all eight directions, with `walkFrameCount`/`walkFps` stamped into the geometry manifest for the external game to read; the historical 8-frame packing keeps its named 2-beat gait-phase labels for byte-identical back-compat. A new per-direction **Reopen** re-opens just one approved direction (finer-grained than the whole-set Unlock) so a single too-fast walk can be redone without disturbing the other seven. The Clip length picker now offers only grok's real 6s/10s options — shorter values were a silent no-op (grok clamps to ~6s), and clip length only affects how much source footage the packer has to choose from, not the cycle's look.
- **Render the sprite turnaround sheet as a large square instead of a wasteful strip** — the locked "identity root" turnaround preview in the Reference workflow used a fixed 192×128 landscape box, but the sheet is a square PNG (four figures in a 1:1 canvas); `object-contain` letterboxed it into a ~128px center strip and wasted the sides. It now renders as a large responsive square (`w-full max-w-sm aspect-square`, stacking the "frozen · identity root" caption below it on mobile), so the four-view sheet is shown as big as its column allows. The candidate thumbnails and locked directional-anchor previews (also square PNGs previously fit into short `h-24` boxes) switch to `aspect-square` too, so every reference image in the panel fills its cell instead of floating in a center band.
- **[claude-default-opus-5] Default Claude CLI/TUI and Bedrock providers now use `claude-opus-5`.** The seeded `claude-code`, `claude-code-tui`, `claude-code-bedrock`, and `claude-code-tui-bedrock` providers ship the new opus tier as their default/heavy model (`claude-opus-5`; Bedrock: `global.anthropic.claude-opus-5[1m]`), and `claude-opus-5` leads the Anthropic API model-refresh list. The Bedrock `[1m]` long-context variant is carried forward and mapped like-for-like — a box pinned to `…opus-4-8[1m]` lands on `…opus-5[1m]`, one pinned to the plain id lands on the plain id — so the bump never silently changes which context tier a Bedrock request asks for. `data.reference/providers.json`, the aiToolkit sample defaults, and the PortOS scaffolder are updated together, and migration `206-claude-default-opus-5.js` rewrites existing installs' `data/providers.json` on the next `update.sh` — conservatively, matching migration 058/153: only an exact match on the prior seeded model list is rewritten (a curated list is left alone), a tier pointer still parked on a now-absent opus-4-8 id is repaired on its own, and still-current haiku/sonnet pins are preserved. `claude-opus-5` is added to the usage cost table at Opus-tier rates ($5/$25 per MTok), and the `/opus/i` family rule now reports it as the tier's rate anchor.
+- **[issue-2991] Support portless desktop managed processes and an app→sprite reverse lookup** — a managed app can now describe a GUI/desktop process (`type: 'desktop'`, e.g. a Godot game binary) with no HTTP port, and the port-dependent surfaces degrade gracefully instead of faking a port. Start now launches a desktop app from its own `startCommands` with PM2 `autorestart` OFF (a window closing is a normal exit, not a crash to loop on — `startWithCommand` gained an `{ autorestart }` option), skips the web-server ecosystem path, and refuses to spawn a second instance when the process is already online. Status reports from the supervisor alone (a clean quit renders as *stopped*, never "unreachable"), and the null-tolerant reserved-port collection already excludes absent ports. The "Open UI" launcher stays hidden for a portless app (`getLaunchUrls` returns all-null) rather than linking to `undefined`. New `GET /api/apps/:id/sprite-bindings` reverse-lookup lists the sprite records whose `publishBinding.appId` targets an app, surfaced on the app Overview tab as "Published Sprite Assets" with their destination paths — making "PortOS is the creative source for this app" legible from the app side. Publishing itself still resolves purely from `repoPath`, with no dependency on registered processes.
diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsx
index 51ea263ed9..6cd505dcc9 100644
--- a/client/src/components/apps/tabs/OverviewTab.jsx
+++ b/client/src/components/apps/tabs/OverviewTab.jsx
@@ -1,5 +1,6 @@
import { useState, useEffect, useMemo } from 'react';
-import { FolderOpen, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Ticket, Download, Tag, AlertTriangle, Rocket, Camera, Image } from 'lucide-react';
+import { Link } from 'react-router-dom';
+import { FolderOpen, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Ticket, Download, Tag, AlertTriangle, Rocket, Camera, Image, Sparkles } from 'lucide-react';
import toast from '../../ui/Toast';
import { NON_PM2_TYPES } from '../constants';
import BrailleSpinner from '../../BrailleSpinner';
@@ -24,6 +25,8 @@ export default function OverviewTab({ app, onRefresh }) {
const [loadingTickets, setLoadingTickets] = useState(false);
const [installingScripts, setInstallingScripts] = useState(false);
const [detectingIcon, setDetectingIcon] = useState(false);
+ // Reverse lookup (#2991): sprite records that publish assets into this app.
+ const [spriteBindings, setSpriteBindings] = useState([]);
const onComplete = useMemo(() => () => onRefresh(), [onRefresh]);
const { steps, isOperating, operationType, error, completed, startUpdate, startStandardize } = useAppOperation({ onComplete });
@@ -40,6 +43,16 @@ export default function OverviewTab({ app, onRefresh }) {
}
}, [app?.jira?.enabled, app?.jira?.instanceId, app?.jira?.projectKey]);
+ // Load the sprite records bound to this app (empty for an app with none).
+ useEffect(() => {
+ if (!app?.id) return;
+ let cancelled = false;
+ api.getAppSpriteBindings(app.id)
+ .then((res) => { if (!cancelled) setSpriteBindings(res?.bindings || []); })
+ .catch(() => { if (!cancelled) setSpriteBindings([]); });
+ return () => { cancelled = true; };
+ }, [app?.id]);
+
const handleUpdate = () => startUpdate(app.id);
const handleRefreshConfig = async () => {
@@ -227,6 +240,32 @@ export default function OverviewTab({ app, onRefresh }) {
</div>
)}
+ {/* Sprite assets PortOS publishes into this app (reverse lookup, #2991).
+ Shown only when at least one sprite record is bound — makes "PortOS is
+ the creative source for this app" visible from the app side. */}
+ {spriteBindings.length > 0 && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Published Sprite Assets</div>
+ <div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">
+ {spriteBindings.map((b) => (
+ <div key={b.recordId} className="flex flex-wrap items-center gap-2 px-3 py-2">
+ <Sparkles size={14} className="text-port-accent shrink-0" />
+ <Link
+ to={`/sprites/${b.recordId}`}
+ className="text-sm text-port-accent hover:underline font-medium"
+ >
+ {b.name}
+ </Link>
+ {b.kind && <span className="text-xs text-gray-500">{b.kind}</span>}
+ {b.atlasDestPath && (
+ <code className="text-xs text-cyan-300 font-mono break-all">→ {b.atlasDestPath}</code>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
{/* JIRA Integration */}
{app.jira?.enabled && (
<div>
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index f446192fcd..1737b37270 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -4,6 +4,10 @@ import { request, API_BASE } from './apiCore.js';
// Apps
export const getApps = (options) => request('/apps', options);
export const getApp = (id) => request(`/apps/${id}`);
+// Reverse lookup (#2991): sprite records whose publishBinding.appId targets this
+// app. Read-only; the caller owns a .catch fallback, so default to silent.
+export const getAppSpriteBindings = (id, options) =>
+ request(`/apps/${id}/sprite-bindings`, { silent: true, ...options });
// Resolves what the app's `workTracker` field ('auto' or explicit) actually
// points to: { configured, resolved, host, forge, source }. Read-only — the
// caller (EditAppDrawer) owns its own .catch fallback, so default to silent.
diff --git a/client/src/services/appUrls.test.js b/client/src/services/appUrls.test.js
new file mode 100644
index 0000000000..1d74422d52
--- /dev/null
+++ b/client/src/services/appUrls.test.js
@@ -0,0 +1,29 @@
+import { describe, it, expect } from 'vitest';
+import { getLaunchUrls, getPrimaryLaunchUrl } from './appUrls';
+
+// The "Open UI" affordance in AppDetailView renders a button per non-null launch
+// URL and hides entirely when there are none. A portless desktop app (a game
+// window, #2991) must therefore surface NO launch URL — never a link to
+// `undefined` — while a port-bearing app still does.
+describe('getLaunchUrls — portless vs port-bearing (#2991)', () => {
+ it('returns all-null for a portless desktop app', () => {
+ const urls = getLaunchUrls({ id: 'the-game', type: 'desktop', uiPort: null, apiPort: null, devUiPort: null, tlsPort: null });
+ expect(urls).toEqual({ https: null, http: null, dev: null });
+ // The single-click launcher likewise has nothing to open.
+ expect(getPrimaryLaunchUrl({ id: 'the-game', type: 'desktop' })).toBeNull();
+ });
+
+ it('returns an http launch URL when the app has a uiPort', () => {
+ const urls = getLaunchUrls({ id: 'web-app', type: 'express', uiPort: 3000 });
+ expect(urls.http).toBe(`http://${window.location.hostname}:3000`);
+ expect(getPrimaryLaunchUrl({ id: 'web-app', type: 'express', uiPort: 3000 }))
+ .toBe(`http://${window.location.hostname}:3000`);
+ });
+
+ it('prefers https when a tlsPort is present', () => {
+ const urls = getLaunchUrls({ id: 'web-app', type: 'express', uiPort: 3000, tlsPort: 8443 });
+ expect(urls.https).toBe(`https://${window.location.hostname}:8443`);
+ expect(getPrimaryLaunchUrl({ id: 'web-app', type: 'express', uiPort: 3000, tlsPort: 8443 }))
+ .toBe(`https://${window.location.hostname}:8443`);
+ });
+});
diff --git a/server/routes/apps/index.js b/server/routes/apps/index.js
index 414fd0f005..0b6f7a8ba0 100644
--- a/server/routes/apps/index.js
+++ b/server/routes/apps/index.js
@@ -33,6 +33,7 @@ import taskTypeRoutes from './taskTypes.js';
import launchRoutes from './launch.js';
import documentRoutes from './documents.js';
import agentRoutes from './agents.js';
+import spriteBindingRoutes from './spriteBindings.js';
const router = Router();
@@ -45,5 +46,6 @@ router.use(taskTypeRoutes);
router.use(launchRoutes);
router.use(documentRoutes);
router.use(agentRoutes);
+router.use(spriteBindingRoutes);
export default router;
diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.js
index 045cf6da6d..b15ddafbdb 100644
--- a/server/routes/apps/lifecycle.js
+++ b/server/routes/apps/lifecycle.js
@@ -22,7 +22,7 @@ import * as appUpdater from '../../services/appUpdater.js';
import * as appBuilder from '../../services/appBuilder.js';
import { logAction } from '../../services/history.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { parseEcosystemFromPath, usesPm2 } from '../../services/streamingDetect.js';
+import { parseEcosystemFromPath, usesPm2, isDesktopType } from '../../services/streamingDetect.js';
import { detectAppIcon, isUsableSvg } from '../../services/appIconDetect.js';
import { loadApp, pathExists, deriveUiPort } from './shared.js';
@@ -41,11 +41,18 @@ router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {
const processNames = app.pm2ProcessNames || [app.name.toLowerCase().replace(/\s+/g, '-')];
- // Check if ecosystem config exists - prefer using it for proper env var handling
+ // Desktop/GUI apps (a game window) are driven from their own startCommands with
+ // autorestart OFF — never wrapped in a web-server ecosystem config. A window
+ // closing is a normal exit, and relaunching it would loop forever.
+ const desktop = isDesktopType(app.type);
+
+ // Check if ecosystem config exists - prefer using it for proper env var handling.
+ // A desktop app is command-launched even if the repo also ships an ecosystem
+ // config for its (unrelated) web processes.
const ecosystemChecks = await Promise.all(
['ecosystem.config.cjs', 'ecosystem.config.js'].map(f => pathExists(`${app.repoPath}/${f}`))
);
- const hasEcosystem = ecosystemChecks.some(Boolean);
+ const hasEcosystem = !desktop && ecosystemChecks.some(Boolean);
let results = {};
@@ -64,7 +71,16 @@ router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {
for (let i = 0; i < processNames.length; i++) {
const name = processNames[i];
const command = commands[i] || commands[0];
- const result = await pm2Service.startWithCommand(name, app.repoPath, command)
+ // Single instance: a desktop/GUI process that is already online must not be
+ // relaunched into a second window — reflect the live process state instead.
+ if (desktop) {
+ const current = await pm2Service.getAppStatus(name, app.pm2Home).catch(() => null);
+ if (current?.status === 'online') {
+ results[name] = { success: true, alreadyRunning: true };
+ continue;
+ }
+ }
+ const result = await pm2Service.startWithCommand(name, app.repoPath, command, desktop ? { autorestart: false } : {})
.catch(err => ({ success: false, error: err.message }));
results[name] = result;
}
diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.js
index 2883cd6f99..48d7283f30 100644
--- a/server/routes/apps/lifecycle.test.js
+++ b/server/routes/apps/lifecycle.test.js
@@ -28,7 +28,8 @@ vi.mock('../../services/history.js', () => ({
vi.mock('../../services/streamingDetect.js', () => ({
parseEcosystemFromPath: vi.fn(),
usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),
- NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift'])
+ NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift']),
+ isDesktopType: vi.fn((type) => type === 'desktop')
}));
vi.mock('../../services/appUpdater.js', () => ({
@@ -82,6 +83,52 @@ describe('Apps Lifecycle Routes', () => {
expect(response.status).toBe(404);
});
+
+ it('launches a desktop app from its startCommands with autorestart OFF (#2991)', async () => {
+ const mockApp = {
+ id: 'game-001',
+ name: 'The Game',
+ type: 'desktop',
+ repoPath: '/tmp', // real dir; no ecosystem config there, and desktop skips it anyway
+ pm2ProcessNames: ['the-game'],
+ startCommands: ['./scripts/game run']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.getAppStatus.mockResolvedValue({ status: 'stopped' }); // not running yet
+ pm2Service.startWithCommand.mockResolvedValue({ success: true });
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app).post('/api/apps/game-001/start');
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ // Command-based launch, never the ecosystem web-server path.
+ expect(pm2Service.startFromEcosystem).not.toHaveBeenCalled();
+ expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
+ 'the-game', '/tmp', './scripts/game run', { autorestart: false }
+ );
+ });
+
+ it('does not spawn a second instance when the desktop app is already online (#2991)', async () => {
+ const mockApp = {
+ id: 'game-001',
+ name: 'The Game',
+ type: 'desktop',
+ repoPath: '/tmp',
+ pm2ProcessNames: ['the-game'],
+ startCommands: ['./scripts/game run']
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.getAppStatus.mockResolvedValue({ status: 'online' }); // already running
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app).post('/api/apps/game-001/start');
+
+ expect(response.status).toBe(200);
+ expect(response.body.results['the-game']).toEqual({ success: true, alreadyRunning: true });
+ // Single instance: no second launch.
+ expect(pm2Service.startWithCommand).not.toHaveBeenCalled();
+ });
});
describe('POST /api/apps/:id/stop', () => {
diff --git a/server/routes/apps/spriteBindings.js b/server/routes/apps/spriteBindings.js
new file mode 100644
index 0000000000..fd44568992
--- /dev/null
+++ b/server/routes/apps/spriteBindings.js
@@ -0,0 +1,26 @@
+/**
+ * App → sprite reverse lookup (issue #2991).
+ *
+ * GET /:id/sprite-bindings → { bindings: [{ recordId, name, kind,
+ * atlasDestPath, codeBindingPath }] }
+ *
+ * Lists the sprite records whose `publishBinding.appId` targets this app — the
+ * app-side view of "PortOS publishes assets into this repo." Empty for an app
+ * nothing is bound to. Display-only: it never gates a publish (publishing
+ * resolves purely from the app's repoPath).
+ */
+
+import { Router } from 'express';
+import { asyncHandler } from '../../lib/errorHandler.js';
+import { loadApp } from './shared.js';
+import { listPublishBindingsForApp } from '../../services/sprites/publish.js';
+
+const router = Router();
+
+// GET /api/apps/:id/sprite-bindings - sprite records publishing into this app
+router.get('/:id/sprite-bindings', loadApp, asyncHandler(async (req, res) => {
+ const bindings = await listPublishBindingsForApp(req.params.id);
+ res.json({ bindings });
+}));
+
+export default router;
diff --git a/server/services/apps.test.js b/server/services/apps.test.js
index 56a0681964..638d0852af 100644
--- a/server/services/apps.test.js
+++ b/server/services/apps.test.js
@@ -34,7 +34,7 @@ vi.mock('./pm2.js', () => ({
import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';
import { listProcessesStrict } from './pm2.js';
import { resetExecutionHistory } from './taskSchedule.js';
-import { getAppStatuses, getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID, updateAppTaskTypeOverride } from './apps.js';
+import { createApp, getAppStatuses, getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID, updateAppTaskTypeOverride } from './apps.js';
describe('pr-watcher cooldown reset', () => {
beforeEach(() => {
@@ -169,6 +169,107 @@ describe('getReservedPorts', () => {
});
});
+describe('portless / desktop apps (#2991)', () => {
+ beforeEach(() => {
+ invalidateCache();
+ vi.clearAllMocks();
+ });
+
+ it('never lets a portless desktop app contribute a port to the reserved set', async () => {
+ // A desktop/GUI app (a game binary) has no HTTP port at all: all top-level
+ // port fields are null and its supervised process carries no ports map.
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: { name: 'PortOS', uiPort: 5555, apiPort: 5555, devUiPort: 5554 },
+ 'the-game': {
+ name: 'The Game',
+ type: 'desktop',
+ uiPort: null,
+ apiPort: null,
+ devUiPort: null,
+ tlsPort: null,
+ pm2ProcessNames: ['the-game'],
+ processes: [{ name: 'the-game' }], // no `port` / `ports` — portless
+ },
+ },
+ });
+
+ const reserved = await getReservedPorts();
+ // Only PortOS baseline ports — the desktop app added nothing.
+ expect(reserved).toContain(5555);
+ expect(reserved).toContain(5554);
+ expect(reserved).not.toContain(null);
+ expect(reserved.every(p => Number.isInteger(p) && p >= 1 && p <= 65535)).toBe(true);
+ expect(reserved).toEqual([5554, 5555]);
+ });
+
+ it('createApp stores a desktop app with null ports (no port ever synthesized)', async () => {
+ readJSONFile.mockResolvedValue({ apps: { [PORTOS_APP_ID]: { name: 'PortOS' } } });
+
+ const created = await createApp({
+ name: 'The Game',
+ repoPath: '/tmp/the-game',
+ type: 'desktop',
+ startCommands: ['./scripts/game run'],
+ });
+
+ expect(created.type).toBe('desktop');
+ expect(created.uiPort).toBeNull();
+ expect(created.apiPort).toBeNull();
+ expect(created.devUiPort).toBeNull();
+ expect(created.startCommands).toEqual(['./scripts/game run']);
+
+ // The persisted record carries no numeric port anywhere.
+ const persisted = atomicWrite.mock.calls.at(-1)?.[1];
+ const stored = persisted.apps[created.id];
+ expect(stored.uiPort).toBeNull();
+ expect(stored.apiPort).toBeNull();
+ expect(stored.devUiPort).toBeNull();
+ });
+
+ it('reports a portless desktop app from supervisor state alone (no HTTP probe)', async () => {
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },
+ 'the-game': {
+ name: 'The Game',
+ type: 'desktop',
+ uiPort: null,
+ pm2ProcessNames: ['the-game'],
+ },
+ },
+ });
+ // A clean quit exits 0 → PM2 reports the process 'stopped', not 'errored'.
+ listProcessesStrict.mockResolvedValue([
+ { name: 'portos-server', status: 'online' },
+ { name: 'the-game', status: 'stopped' },
+ ]);
+
+ const statuses = await getAppStatuses();
+ const game = statuses.find(s => s.name === 'The Game');
+ expect(game).toBeDefined();
+ expect(game.managed).toBe(true); // supervised, not 'n/a'
+ expect(game.overallStatus).toBe('stopped'); // reflects supervisor, never "unreachable"
+ });
+
+ it('renders a running desktop app as online purely from the supervisor', async () => {
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },
+ 'the-game': { name: 'The Game', type: 'desktop', uiPort: null, pm2ProcessNames: ['the-game'] },
+ },
+ });
+ listProcessesStrict.mockResolvedValue([
+ { name: 'portos-server', status: 'online' },
+ { name: 'the-game', status: 'online' },
+ ]);
+
+ const statuses = await getAppStatuses();
+ const game = statuses.find(s => s.name === 'The Game');
+ expect(game.overallStatus).toBe('online');
+ });
+});
+
describe('getAppStatusSummary', () => {
beforeEach(() => {
invalidateCache();
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 39e2fb2444..987d7c8dff 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -476,8 +476,16 @@ export async function getLogs(name, lines = 100, pm2Home = null) {
* @param {string} name PM2 process name
* @param {string} cwd Working directory
* @param {string} command Command to run (e.g., "npm run dev")
+ * @param {object} [options]
+ * @param {boolean} [options.autorestart=true] When false, PM2 will NOT relaunch
+ * the process after it exits. Portless/desktop apps (a game window) pass false:
+ * the user closing the window is a normal exit, not a crash to loop on. The
+ * restart-tuning fields (max_restarts/min_uptime/restart_delay) are omitted in
+ * that mode since they only apply when autorestart is on.
+ * @param {number} [options.maxRestarts=10] Restart cap when autorestart is on.
*/
-export async function startWithCommand(name, cwd, command) {
+export async function startWithCommand(name, cwd, command, options = {}) {
+ const { autorestart = true, maxRestarts = 10 } = options;
// Parse with quote-awareness so `node --opt "arg with spaces"` survives;
// a bare split(' ') would shred quoted segments. PM2 accepts `args` as an
// array, which avoids re-joining and re-splitting on the way through.
@@ -491,10 +499,10 @@ export async function startWithCommand(name, cwd, command) {
args,
cwd,
watch: false,
- autorestart: true,
- max_restarts: 10,
- min_uptime: '10s',
- restart_delay: 5000,
+ autorestart,
+ // Restart tuning only matters when autorestart is on; a desktop process
+ // exiting cleanly should stay stopped, not be nursed back up.
+ ...(autorestart ? { max_restarts: maxRestarts, min_uptime: '10s', restart_delay: 5000 } : {}),
max_memory_restart: '500M',
windowsHide: IS_WIN
};
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index 6fc4fa7667..c3b3eb8b91 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -41,7 +41,7 @@ import { getAppById } from '../apps.js';
import { isDeploying } from '../appDeployer.js';
import { spriteDir, RUNTIME_POINTER_REL, RUNTIME_PUBLICATIONS_REL } from './paths.js';
import { requireCharacter } from './reference.js';
-import { updateRecord } from './records.js';
+import { listRecords, updateRecord } from './records.js';
import { withWalkWriteTail } from './walk.js';
import { compileAtlasInTail } from './atlas.js';
import { sha256Buffer } from './walkPostprocess.js';
@@ -167,6 +167,29 @@ export async function setPublishBinding(recordId, binding) {
return updateRecord(recordId, { publishBinding: validated });
}
+/**
+ * Reverse lookup (#2991): the sprite records whose `publishBinding.appId`
+ * targets the given app, with their repo-relative destination paths. This is
+ * the app-side view of the publish relationship — it makes "PortOS is the
+ * creative source for this app" legible from the app's own detail page, rather
+ * than a hidden per-record setting. Returns `[]` for an app nothing publishes
+ * into (and for a falsy appId). Publishing itself still resolves purely from
+ * the app's `repoPath`; this is display-only and never gates a publish.
+ */
+export async function listPublishBindingsForApp(appId) {
+ if (!appId) return [];
+ const records = await listRecords();
+ return records
+ .filter((r) => r?.publishBinding?.appId === appId)
+ .map((r) => ({
+ recordId: r.id,
+ name: r.name || r.id,
+ kind: r.kind || null,
+ atlasDestPath: r.publishBinding.atlasDestPath || null,
+ codeBindingPath: r.publishBinding.codeBinding?.path || null,
+ }));
+}
+
const countOccurrences = (text, needle) => (needle ? text.split(needle).length - 1 : 0);
/**
diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.js
index e3cbef6741..152c170050 100644
--- a/server/services/sprites/publish.test.js
+++ b/server/services/sprites/publish.test.js
@@ -46,7 +46,7 @@ vi.mock('./atlas.js', () => ({
}));
const records = await import('./records.js');
-const { setPublishBinding, publishAtlas, validatePublishBinding } = await import('./publish.js');
+const { setPublishBinding, publishAtlas, validatePublishBinding, listPublishBindingsForApp } = await import('./publish.js');
const { walkPhaseLabels } = await import('./walkBounds.js');
let seq = 0;
@@ -194,6 +194,37 @@ describe('validatePublishBinding / setPublishBinding', () => {
});
});
+describe('listPublishBindingsForApp (reverse lookup, #2991)', () => {
+ it('lists exactly the records bound to the app, with destination paths', async () => {
+ const a = await characterWithAtlas();
+ const b = await characterWithAtlas();
+ const other = await characterWithAtlas();
+ await setPublishBinding(a.id, { appId: 'game-app', atlasDestPath: 'assets/sprites/a.png' });
+ await setPublishBinding(b.id, {
+ appId: 'game-app',
+ atlasDestPath: 'assets/sprites/b.png',
+ codeBinding: { path: 'src/B.cs', resourcePath: 'res://assets/sprites/b.png' },
+ });
+ // Bound to a DIFFERENT app — must not appear in game-app's lookup.
+ await setPublishBinding(other.id, { appId: 'other-app', atlasDestPath: 'assets/sprites/o.png' });
+
+ const bound = await listPublishBindingsForApp('game-app');
+ expect(bound.map(x => x.recordId).sort()).toEqual([a.id, b.id].sort());
+ const byId = Object.fromEntries(bound.map(x => [x.recordId, x]));
+ expect(byId[a.id].atlasDestPath).toBe('assets/sprites/a.png');
+ expect(byId[a.id].codeBindingPath).toBeNull();
+ expect(byId[b.id].atlasDestPath).toBe('assets/sprites/b.png');
+ expect(byId[b.id].codeBindingPath).toBe('src/B.cs');
+ });
+
+ it('is empty for an app nothing publishes into (and for a falsy id)', async () => {
+ const c = await characterWithAtlas();
+ await setPublishBinding(c.id, { appId: 'game-app', atlasDestPath: 'assets/sprites/c.png' });
+ expect(await listPublishBindingsForApp('other-app')).toEqual([]);
+ expect(await listPublishBindingsForApp(undefined)).toEqual([]);
+ });
+});
+
describe('publishAtlas', () => {
it('refuses without a binding', async () => {
const { id } = await characterWithAtlas();
@@ -222,6 +253,19 @@ describe('publishAtlas', () => {
expect(history).toHaveLength(1);
});
+ it('resolves purely from repoPath — no dependency on registered processes/ports (#2991)', async () => {
+ // The mocked app carries only { id, name, repoPath } — no processes, no
+ // ports, portless. Publishing must still succeed: it targets the repo tree,
+ // never a running/registered process.
+ expect(APPS['game-app'].processes).toBeUndefined();
+ expect(APPS['game-app'].uiPort).toBeUndefined();
+ const { id, atlasBytes } = await characterWithAtlas();
+ await setPublishBinding(id, BINDING);
+ const result = await publishAtlas(id);
+ expect(result.published).toBe(true);
+ expect((await readFile(join(APP_REPO, BINDING.atlasDestPath))).toString()).toBe(atlasBytes);
+ });
+
it('is idempotent when the destination already holds the current bytes', async () => {
const { id } = await characterWithAtlas();
await setPublishBinding(id, BINDING);
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index d073fd6f25..425a4559a8 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -9,6 +9,19 @@ import { detectAppIcon } from './appIconDetect.js';
/** App types that do not use PM2 for process management */
export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'swift']);
+/**
+ * App types that run a GUI/desktop process with no HTTP port (e.g. a Godot
+ * game binary). These are still supervised through PM2, but launched from the
+ * app's own `startCommands` — never an ecosystem web-server config — and with
+ * autorestart OFF: the user closing the window is a NORMAL exit (code 0), not a
+ * crash to relaunch. Port-dependent surfaces (Open UI, HTTP probes) branch on
+ * "has a port" rather than assuming one.
+ */
+export const DESKTOP_TYPES = new Set(['desktop']);
+
+/** Check if an app type is a portless GUI/desktop process. */
+export const isDesktopType = (type) => DESKTOP_TYPES.has(type);
+
/**
* Ecosystem config filenames in the order they're resolved. The READER
* (parseEcosystemFromPath) and the WRITER (writeEcosystemPorts) must agree on