From 2cf2f11a000c3ac871b6e0e5d7b81128e2dc471b Mon Sep 17 00:00:00 2001 From: Bruno Fargnoli Date: Fri, 26 Jun 2026 10:40:16 +0200 Subject: [PATCH] Server can be configured on another machine and/or port --- .env | 1 + .gitignore | 7 ------ server.js | 34 +++++++++++++++++---------- src/components/AssetSelectorModal.jsx | 3 ++- src/components/Footer.jsx | 3 ++- src/components/SetupWizardModal.jsx | 3 +-- src/config.js | 19 +++++++++++++++ src/context/ProjectContext.jsx | 2 +- src/context/SettingsContext.jsx | 2 +- src/pages/KanbanPage.jsx | 7 +++--- src/pages/MeshEditorPage.jsx | 13 +++++----- src/utils/graphHelpers.js | 3 ++- src/utils/kanbanHelpers.js | 3 ++- src/utils/meshExport.js | 3 +-- src/utils/meshTexturing.js | 3 ++- storage.js | 16 ++++++------- 16 files changed, 74 insertions(+), 48 deletions(-) create mode 100644 .env create mode 100644 src/config.js diff --git a/.env b/.env new file mode 100644 index 0000000..1b4fc3e --- /dev/null +++ b/.env @@ -0,0 +1 @@ +VITE_SERVER_ORIGIN=http://localhost:3001 diff --git a/.gitignore b/.gitignore index 3127d6e..78d5bd2 100644 --- a/.gitignore +++ b/.gitignore @@ -15,13 +15,6 @@ data/ .DS_Store Thumbs.db -# Environment variables -.env -.env.local -.env.development.local -.env.test.local -.env.production.local - # Vite / IDE .vscode/ .idea/ diff --git a/server.js b/server.js index fd9602c..fd56406 100644 --- a/server.js +++ b/server.js @@ -96,7 +96,15 @@ import { } from './wikiStorage.js'; const app = express(); -const PORT = 3001; +const PORT = Number(process.env.PORT) || 3001; + +// Build the externally-reachable base URL ("http://host:port") from the +// incoming request so generated asset/media URLs point back at whatever host +// and port the client actually used to reach us — works on another machine or +// another port without baking "localhost" into responses. +function getRequestBaseUrl(req) { + return `${req.protocol}://${req.get('host')}`; +} const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp']); const MESH_EXTENSIONS = new Set(['.glb', '.gltf', '.obj', '.fbx', '.stl', '.ply']); const comfyProgressSubscribers = new Map(); @@ -538,7 +546,7 @@ app.post('/api/wiki/media', requireWikiAuthor, wikiMediaUpload.single('file'), a const isVideo = ['.mp4', '.webm', '.ogg', '.mov', '.m4v'].includes(extension); res.status(201).json({ - url: `http://localhost:${PORT}/wiki-media/${encodeURIComponent(uniqueName)}`, + url: `${getRequestBaseUrl(req)}/wiki-media/${encodeURIComponent(uniqueName)}`, kind: isVideo ? 'video' : 'image', name: req.file.originalname }); @@ -3159,7 +3167,7 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req : await createProjectAsset(generatedAssetPayload); generatedAssets.push({ ...persistedAsset, - url: `http://localhost:${PORT}/assets/${encodeURI(toAssetUrlPath(storedFilePath))}`, + url: `${getRequestBaseUrl(req)}/assets/${encodeURI(toAssetUrlPath(storedFilePath))}`, outputKey: workflowFile.outputKey, outputNodeId: workflowFile.nodeId, expectedType: workflowFile.expectedType, @@ -4313,9 +4321,9 @@ app.delete('/api/graph/connections', async (req, res) => { app.get('/api/assets/library', async (req, res) => { try { const [images, meshes, brushes] = await Promise.all([ - listLibraryAssetsByType('image', PORT), - listLibraryAssetsByType('mesh', PORT), - listLibraryAssetsByType('brush', PORT) + listLibraryAssetsByType('image', getRequestBaseUrl(req)), + listLibraryAssetsByType('mesh', getRequestBaseUrl(req)), + listLibraryAssetsByType('brush', getRequestBaseUrl(req)) ]); res.json({ images, meshes, brushes }); } catch (err) { @@ -4549,20 +4557,20 @@ app.post('/api/assets/library/brush-edits', libraryImportUpload.any(), async (re // Paint documents — sidecar layer data for painted meshes // ------------------------------------------------------------------------- -function buildPaintDocumentResponse(doc, assetId) { +function buildPaintDocumentResponse(doc, assetId, baseUrl) { if (!doc) return null; - const baseUrl = doc.baseFilePath - ? `http://localhost:${PORT}/assets/${encodeURI(doc.baseFilePath.replace(/^data\/assets\//, ''))}` + const baseTextureUrl = doc.baseFilePath + ? `${baseUrl}/assets/${encodeURI(doc.baseFilePath.replace(/^data\/assets\//, ''))}` : null; return { assetId, textureWidth: doc.textureWidth, textureHeight: doc.textureHeight, - base: doc.baseFilePath ? { filePath: doc.baseFilePath, url: baseUrl } : null, + base: doc.baseFilePath ? { filePath: doc.baseFilePath, url: baseTextureUrl } : null, layers: (doc.layers || []).map(layer => ({ ...layer, url: layer.filePath - ? `http://localhost:${PORT}/assets/${encodeURI(layer.filePath.replace(/^data\/assets\//, ''))}` + ? `${baseUrl}/assets/${encodeURI(layer.filePath.replace(/^data\/assets\//, ''))}` : null })), updatedAt: doc.updatedAt @@ -4581,7 +4589,7 @@ app.get('/api/assets/:assetId/paint-document', async (req, res) => { return res.status(404).json({ error: 'Paint document not found' }); } - res.json(buildPaintDocumentResponse(doc, assetId)); + res.json(buildPaintDocumentResponse(doc, assetId, getRequestBaseUrl(req))); } catch (err) { console.error('Failed to load paint document:', err); res.status(500).json({ error: err.message || 'Failed to load paint document' }); @@ -4695,7 +4703,7 @@ app.put('/api/assets/:assetId/paint-document', paintDocumentUpload.any(), async layers: persistedLayers }); - res.status(200).json(buildPaintDocumentResponse(saved, assetId)); + res.status(200).json(buildPaintDocumentResponse(saved, assetId, getRequestBaseUrl(req))); } catch (err) { console.error('Failed to save paint document:', err); res.status(500).json({ error: err.message || 'Failed to save paint document' }); diff --git a/src/components/AssetSelectorModal.jsx b/src/components/AssetSelectorModal.jsx index e1ae143..803c322 100644 --- a/src/components/AssetSelectorModal.jsx +++ b/src/components/AssetSelectorModal.jsx @@ -1,6 +1,7 @@ // components/AssetSelectorModal.jsx import { useEffect, useMemo, useState } from 'react'; import { useProjects } from '../context/ProjectContext'; +import { assetUrl } from '../config'; import './AssetSelectorModal.css'; // we'll create a separate CSS or reuse AssetsPage.css function formatDimensions(width, height) { @@ -10,7 +11,7 @@ function formatDimensions(width, height) { function getAssetPreviewUrl(filename) { if (!filename) return null; - return `http://localhost:3001/assets/${encodeURI(filename)}`; + return assetUrl(filename); } const ASSETS_PER_PAGE = 20; diff --git a/src/components/Footer.jsx b/src/components/Footer.jsx index 1d9ff50..1cdb463 100644 --- a/src/components/Footer.jsx +++ b/src/components/Footer.jsx @@ -1,4 +1,5 @@ import { useState, useEffect } from 'react' +import { API_BASE } from '../config' import './Footer.css' export default function Footer({ variant = 'default', onChangeLogClick }) { @@ -7,7 +8,7 @@ export default function Footer({ variant = 'default', onChangeLogClick }) { useEffect(() => { const fetchStats = async () => { try { - const response = await fetch('http://localhost:3001/api/system/stats'); + const response = await fetch(`${API_BASE}/system/stats`); if (!response.ok) return; // stats not ready yet — keep showing previous value const data = await response.json(); setStats(data); diff --git a/src/components/SetupWizardModal.jsx b/src/components/SetupWizardModal.jsx index 137b7df..338bc91 100644 --- a/src/components/SetupWizardModal.jsx +++ b/src/components/SetupWizardModal.jsx @@ -1,8 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useSettings } from '../context/SettingsContext.shared' import './SetupWizardModal.css' - -const API_BASE = 'http://localhost:3001/api' +import { API_BASE } from '../config' const STEPS = [ { id: 'comfy-path', label: 'ComfyUI' }, diff --git a/src/config.js b/src/config.js new file mode 100644 index 0000000..c7f73c2 --- /dev/null +++ b/src/config.js @@ -0,0 +1,19 @@ +// Central place to resolve where the backend (server.js) lives. +// +// Set VITE_SERVER_ORIGIN in a .env file to point the frontend at a backend on +// another computer or port, e.g. +// VITE_SERVER_ORIGIN=http://192.168.1.50:3001 +// Leave it as an empty string ("") to use the same origin the app was served +// from — useful once Express serves the built UI itself (single origin). +// When unset, it defaults to the local dev backend. +const rawOrigin = import.meta.env.VITE_SERVER_ORIGIN + +export const SERVER_ORIGIN = (rawOrigin === undefined ? 'http://localhost:3001' : rawOrigin) + .replace(/\/$/, '') + +export const API_BASE = `${SERVER_ORIGIN}/api` + +// Build a URL to a static asset served from the backend's /assets mount. +export function assetUrl(pathOrFilename) { + return `${SERVER_ORIGIN}/assets/${encodeURI(pathOrFilename)}` +} diff --git a/src/context/ProjectContext.jsx b/src/context/ProjectContext.jsx index ef728f0..6a576b5 100644 --- a/src/context/ProjectContext.jsx +++ b/src/context/ProjectContext.jsx @@ -1,8 +1,8 @@ /* eslint-disable react-refresh/only-export-components */ import { createContext, useContext, useState, useEffect, useCallback } from 'react' +import { API_BASE } from '../config' const ProjectContext = createContext(null) -const API_BASE = 'http://localhost:3001/api' export function ProjectProvider({ children }) { const [projects, setProjects] = useState([]) diff --git a/src/context/SettingsContext.jsx b/src/context/SettingsContext.jsx index bc74120..ee54077 100644 --- a/src/context/SettingsContext.jsx +++ b/src/context/SettingsContext.jsx @@ -1,7 +1,7 @@ import { useState, useEffect, useCallback } from 'react' import { SettingsContext } from './SettingsContext.shared' +import { API_BASE } from '../config' -const API_BASE = 'http://localhost:3001/api' const DEFAULT_CUSTOM_API_TYPE = 'image-generation' function normalizeCustomApiType(type) { diff --git a/src/pages/KanbanPage.jsx b/src/pages/KanbanPage.jsx index 1e98e47..091a056 100644 --- a/src/pages/KanbanPage.jsx +++ b/src/pages/KanbanPage.jsx @@ -12,6 +12,7 @@ import SettingsModal from '../components/SettingsModal' import { createMeshThumbnailFile } from '../utils/meshThumbnail' import './KanbanPage.css' import AssetSelectorModal from '../components/AssetSelectorModal'; +import { assetUrl } from '../config' import KanbanImageCard from '../components/kanban/KanbanImageCard' import MeshGenApiOptions from '../components/kanban/MeshGenApiOptions' import ComfyTextButton from '../components/comfy/ComfyTextButton' @@ -283,8 +284,8 @@ export default function KanbanPage() { return asset } - const assetUrl = `http://localhost:3001/assets/${encodeURI(asset.filename)}` - const response = await fetch(assetUrl) + const meshAssetUrl = assetUrl(asset.filename) + const response = await fetch(meshAssetUrl) if (!response.ok) { throw new Error(`Failed to download generated mesh ${asset.name || asset.filename}`) @@ -1598,7 +1599,7 @@ export default function KanbanPage() { return null } - return `http://localhost:3001/assets/${encodeURI(filename)}` + return assetUrl(filename) } const formatAssetDimensions = (width, height) => { diff --git a/src/pages/MeshEditorPage.jsx b/src/pages/MeshEditorPage.jsx index f305ae4..1dae881 100644 --- a/src/pages/MeshEditorPage.jsx +++ b/src/pages/MeshEditorPage.jsx @@ -9,6 +9,7 @@ import SettingsModal from '../components/SettingsModal' import { useProjects } from '../context/ProjectContext' import { useNotifications } from '../context/NotificationContext' import { createMeshThumbnailFile } from '../utils/meshThumbnail' +import { assetUrl } from '../config' import { bridgeSelectedHoleSegments, bridgeAndFillSelectedHole, @@ -658,7 +659,7 @@ export default function MeshEditorPage() { if (paintBrushSource === 'asset' && paintBrushAsset) { sourceUrl = paintBrushAsset.url || (paintBrushAsset.filename - ? `http://localhost:3001/assets/${encodeURI(paintBrushAsset.filename)}` + ? assetUrl(paintBrushAsset.filename) : null); } else if (paintBrushSource === 'computer' && paintBrushFile) { objectUrl = URL.createObjectURL(paintBrushFile); @@ -1433,7 +1434,7 @@ export default function MeshEditorPage() { if (sculptStampSource === 'asset' && sculptStampAsset) { sourceUrl = sculptStampAsset.url || (sculptStampAsset.filename - ? `http://localhost:3001/assets/${encodeURI(sculptStampAsset.filename)}` + ? assetUrl(sculptStampAsset.filename) : null); } else if (sculptStampSource === 'computer' && sculptStampFile) { objectUrl = URL.createObjectURL(sculptStampFile); @@ -3892,8 +3893,8 @@ export default function MeshEditorPage() { }) try { - const assetUrl = savedAsset?.filename ? `http://localhost:3001/assets/${encodeURI(savedAsset.filename)}` : '' - const response = assetUrl ? await fetch(assetUrl) : null + const savedAssetUrl = savedAsset?.filename ? assetUrl(savedAsset.filename) : '' + const response = savedAssetUrl ? await fetch(savedAssetUrl) : null if (response?.ok) { const blob = await response.blob() const meshFile = new File([blob], savedAsset.filename?.split('/').pop() || `${savedAsset.name || 'mesh'}.glb`, { @@ -3968,7 +3969,7 @@ export default function MeshEditorPage() { if (saveMode === 'version' && savedAsset?.id) { const nextSearchParams = new URLSearchParams(searchParams) const savedFilename = savedAsset.filename || (savedAsset.filePath ? savedAsset.filePath.replace(/^data\/assets\//, '') : '') - const savedUrl = savedFilename ? `http://localhost:3001/assets/${encodeURI(savedFilename)}` : modelUrl + const savedUrl = savedFilename ? assetUrl(savedFilename) : modelUrl nextSearchParams.set('assetId', String(savedAsset.id)) nextSearchParams.set('filePath', savedAsset.filePath || '') @@ -5141,7 +5142,7 @@ export default function MeshEditorPage() { let file = null; if (config.type === 'asset') { // Build asset URL - const url = config.filePath ? `http://localhost:3001/assets/${encodeURI(config.filePath.replace(/^data\/assets\//, ''))}` : null; + const url = config.filePath ? assetUrl(config.filePath.replace(/^data\/assets\//, '')) : null; if (!url) throw new Error(`Asset ${config.assetName} has no file path`); const response = await fetch(url); if (!response.ok) throw new Error(`Failed to load asset ${config.assetName}`); diff --git a/src/utils/graphHelpers.js b/src/utils/graphHelpers.js index 66af921..8824cfa 100644 --- a/src/utils/graphHelpers.js +++ b/src/utils/graphHelpers.js @@ -1,5 +1,6 @@ // Pure helpers and config constants for the node-graph editor (GraphPage). // Extracted from GraphPage.jsx — no React, no component state. +import { assetUrl } from '../config' export const DEFAULT_OUTPUT_ID = 'output-0' export const DEFAULT_INPUT_ID = 'input-0' @@ -324,7 +325,7 @@ export function getAssetPreviewUrl(filename) { return null } - return `http://localhost:3001/assets/${encodeURI(filename)}` + return assetUrl(filename) } export function appendCacheBust(url, cacheKey) { diff --git a/src/utils/kanbanHelpers.js b/src/utils/kanbanHelpers.js index 61b8e4f..e8369a3 100644 --- a/src/utils/kanbanHelpers.js +++ b/src/utils/kanbanHelpers.js @@ -1,5 +1,6 @@ // Pure helpers and config constants for the Kanban board page (KanbanPage). // Extracted from KanbanPage.jsx — no React, no component state. +import { assetUrl } from '../config' export const IMAGE_API_LIST = [ { id: 'nanobana', name: 'Nanobana' }, @@ -156,7 +157,7 @@ export function buildMeshEditorPath(asset, projectId, returnTo) { const query = new URLSearchParams({ assetId: String(asset?.id || ''), filePath: asset?.filePath || asset?.filename || '', - url: asset?.filename ? `http://localhost:3001/assets/${encodeURI(asset.filename)}` : '', + url: asset?.filename ? assetUrl(asset.filename) : '', name: asset?.name || 'Mesh', projectId: projectId ? String(projectId) : '', returnTo: returnTo || '' diff --git a/src/utils/meshExport.js b/src/utils/meshExport.js index be196ed..e6c79ef 100644 --- a/src/utils/meshExport.js +++ b/src/utils/meshExport.js @@ -8,8 +8,7 @@ import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js' import { OBJExporter } from 'three/examples/jsm/exporters/OBJExporter.js' import { PLYExporter } from 'three/examples/jsm/exporters/PLYExporter.js' import { STLExporter } from 'three/examples/jsm/exporters/STLExporter.js' - -const API_BASE = 'http://localhost:3001/api' +import { API_BASE } from '../config' // Formats we can reliably serialize with three.js. FBX has no official // exporter, so it is intentionally excluded. diff --git a/src/utils/meshTexturing.js b/src/utils/meshTexturing.js index fad17a6..b105108 100644 --- a/src/utils/meshTexturing.js +++ b/src/utils/meshTexturing.js @@ -1,4 +1,5 @@ import * as THREE from 'three' +import { assetUrl } from '../config' import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js' import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js' import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js' @@ -1484,7 +1485,7 @@ export function buildAssetUrl(asset) { .replace(/^data\/assets\//, '') .replace(/^assets\//, '') - return `http://localhost:3001/assets/${encodeURI(normalizedPath)}` + return assetUrl(normalizedPath) } export function createTexturePaintWorkflowDraft(workflow) { diff --git a/storage.js b/storage.js index 222b7da..a39c063 100644 --- a/storage.js +++ b/storage.js @@ -516,18 +516,18 @@ async function migrateLegacyAssetEditsToAssets(db) { } } -function groupChildAssetsByParentFilePath(rows = [], port = null) { +function groupChildAssetsByParentFilePath(rows = [], baseUrl = null) { return rows.reduce((accumulator, row) => { if (!accumulator[row.parentFilePath]) { accumulator[row.parentFilePath] = []; } const childAsset = mapChildAssetRow(row); - const childWithUrl = port + const childWithUrl = baseUrl ? { ...childAsset, - url: `http://localhost:${port}/assets/${encodeURI(childAsset.filename)}`, - thumbnailUrl: childAsset.thumbnail ? `http://localhost:${port}/assets/${encodeURI(childAsset.thumbnail)}` : null + url: `${baseUrl}/assets/${encodeURI(childAsset.filename)}`, + thumbnailUrl: childAsset.thumbnail ? `${baseUrl}/assets/${encodeURI(childAsset.thumbnail)}` : null } : childAsset; @@ -3145,7 +3145,7 @@ export async function getWikiPage(id) { return row ? mapWikiPageRow(row) : null; } -export async function listLibraryAssetsByType(type, port) { +export async function listLibraryAssetsByType(type, baseUrl) { const db = await getDb(); const assetDirectory = getAssetDirectory(type); await fs.mkdir(assetDirectory, { recursive: true }); @@ -3225,7 +3225,7 @@ export async function listLibraryAssetsByType(type, port) { const childAssetRows = await listChildAssetsByParentFilePaths(db, candidateStoredPaths, normalizeAssetTypeName(type)); - const childrenBySourceFilePath = groupChildAssetsByParentFilePath(childAssetRows, port); + const childrenBySourceFilePath = groupChildAssetsByParentFilePath(childAssetRows, baseUrl); const dbAssets = rows.reduce((accumulator, row) => { const filename = toAssetUrlPath(row.filePath); @@ -3261,11 +3261,11 @@ export async function listLibraryAssetsByType(type, port) { projectIds: projectIdsByFilePath[row.filePath] || [], type, extension: path.extname(filename).replace('.', '').toUpperCase() || type.toUpperCase(), - url: `http://localhost:${port}/assets/${encodeURI(filename)}`, + url: `${baseUrl}/assets/${encodeURI(filename)}`, width: canonicalAsset?.width ?? row.width ?? 0, height: canonicalAsset?.height ?? row.height ?? 0, thumbnailPath, - thumbnailUrl: thumbnailFilename ? `http://localhost:${port}/assets/${encodeURI(thumbnailFilename)}` : null, + thumbnailUrl: thumbnailFilename ? `${baseUrl}/assets/${encodeURI(thumbnailFilename)}` : null, children: assetChildren, childCount: assetChildren.length, edits: assetChildren,