Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/vscode-extension/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@
- **Historical comparison and project evolution no longer refuse a folder opened through a link.** When the analyzed folder was reached through a symbolic link, a junction, or a shortened Windows path (`C:\Users\JOHNDO~1\...`), Code-XR compared it with the repository path Git reports and wrongly concluded the folder was outside the repository, so the Git-based analyses were unavailable. Both paths are now resolved to their real location before they are compared.
- **The installed extension only ever runs the Python analysis scripts it ships with.** If its bundled copy of an analysis script was missing (a damaged or partially deleted install), Code-XR fell back to a developer location two folders above the extension, which in an installed copy is your home folder, and could have run a file found there. That fallback is now limited to development builds; an installed extension reports the missing script instead.
- **The analysis backend loads again on Python 3.8 and 3.9.** One type annotation in the line-metrics module used syntax that only exists from Python 3.10, so on 3.8 or 3.9 every analysis failed as soon as the backend loaded, although the extension asks only for Python 3.7 or newer. The annotation now uses the older spelling; results on newer Python versions are unchanged.
- **Local servers are reported on the port they actually listen on, and stopping them frees the port.** Several issues in how XR scenes are served are fixed:
- When the requested port was taken, an HTTPS server could pick a different port from the one shown in the Active Servers list and the opened URL. The launcher now reports the port the server really bound.
- "Force stop" removed a server from the list without closing it, so the port stayed busy until VS Code restarted. It now closes the listener and its open connections.
- When the requested port is busy, the next 100 ports are tried. Before, the search stopped at 8080, so a busy port of 8080 or higher made every launch fail.
- A port held on `localhost` only is no longer reported free (on macOS and Windows the browser could reach the other program instead of the scene).
- A server that started but could not be added to the list is shut down, and the launch is reported as failed instead of leaving an unreachable server running.
- "Stop all servers" counts only running servers in its prompt and shows one summary instead of one notification per server, saying how many did not shut down cleanly.
- **Charts stay on the analysis table.** Bar, cylinder and map charts could end with their axis hanging up to 2.6 m past the table edge, or squeezed into a thin sliver at one end of a long empty axis, while the scene reported the chart as fitted:
- BabiaXR resizes an axis with an animation that A-Frame 1.7.1 never applies, so an axis kept the length of its first build. Axis lines are now written directly, and a resized axis triggers a new fit.
- The table fit checked the chart's size but not its position: centring the bars could push the axis off one side. The axes are now kept on the table, and a chart that still sticks out is no longer reported as fitted.
Expand Down
16 changes: 15 additions & 1 deletion apps/vscode-extension/src/core/server/httpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,22 @@ export class HttpServer {
*/
public forceStop(): void {
this.disposeRuntimeFeatures();
this.server?.closeAllConnections();
const server = this.server;
this.server = null;
this.isRunning = false;
if (server) {
// close() stops accepting connections and releases the port; it
// was never called here, so a force-stopped server kept listening
// with no entry left in the tree to stop it from.
server.close(() => undefined);
server.closeAllConnections();
}
}

/** The port the listener is actually bound to, or null when not listening. */
public getListeningPort(): number | null {
const address = this.server?.address();
return address && typeof address === 'object' ? address.port : null;
}

/**
Expand Down
29 changes: 27 additions & 2 deletions apps/vscode-extension/src/core/server/httpsServerBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,22 @@ export abstract class HttpsServerBase<TConfig extends HttpsServerBaseConfig> {
*/
public forceStop(): void {
this.httpHandler.disposeRuntimeFeatures();
this.server?.closeAllConnections();
const server = this.server;
this.server = null;
this.isRunning = false;
if (server) {
// close() stops accepting connections and releases the port; it
// was never called here, so a force-stopped server kept listening
// with no entry left in the tree to stop it from.
server.close(() => undefined);
server.closeAllConnections();
}
}

/** The port the listener is actually bound to, or null when not listening. */
public getListeningPort(): number | null {
const address = this.server?.address();
return address && typeof address === 'object' ? address.port : null;
}

public getIsRunning(): boolean {
Expand Down Expand Up @@ -157,8 +171,19 @@ export abstract class HttpsServerBase<TConfig extends HttpsServerBaseConfig> {
}
}

/** Finds a free port from the configured one upwards and adopts it. */
/**
* Keeps the configured port when it is free, and only otherwise searches
* upwards and adopts the next free one. The launcher has already picked a
* free port; searching again unconditionally went through get-port, which
* locks every port it returns for 15-30 s and therefore skipped the very
* port the launcher had just chosen, so the server listened one port above
* the one shown in the tree, the toast and the LAN URL.
*/
protected async resolveListeningPort(): Promise<void> {
if (await PortManager.isPortAvailable(this.config.port, this.config.host)) {
logger.debug(() => `Port ${this.config.port} is available on host ${this.config.host}`);
return;
}
logger.debug(() => `Looking for available port starting from ${this.config.port} on host ${this.config.host}...`);
const availablePort = await PortManager.findAvailablePort(this.config.port, this.config.port + 100, this.config.host);

Expand Down
90 changes: 71 additions & 19 deletions apps/vscode-extension/src/core/server/multiServerLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,47 @@ export class MultiServerLauncher {
logger.debug('Multi-server launcher initialized');
}

/** Logs (and, when it differs, announces) the port a server bound; returns whether it changed. */
private reportBoundPort(requestedPort: number, boundPort: number): boolean {
if (boundPort === requestedPort) {
logger.debug(() => `Using requested port ${boundPort}`);
return false;
}
logger.debug(() => `Port ${requestedPort} already in use. Using port ${boundPort} instead.`);
notifyPortChanged(requestedPort, boundPort);
return true;
}

/** Opens a freshly launched server per the settings; a failure is logged, never thrown. */
private async openLaunchedServer(
settings: Parameters<typeof handleAutoOpening>[0],
serverUrl: string,
htmlFile: string | undefined,
activeServerId: string
): Promise<void> {
try {
await handleAutoOpening(settings, serverUrl, htmlFile, determineLaunchMode(settings), activeServerId);
} catch (error) {
logger.error('Failed to open the launched server:', error);
}
}

/** Stops a server that started but could not be registered, falling back to forceStop. */
private async discardUnregisteredServer(instance: { stop?: () => Promise<void>; forceStop?: () => void } | undefined): Promise<void> {
try {
if (typeof instance?.stop === 'function') {
await instance.stop();
}
} catch (stopError) {
logger.warn('Stopping the unregistered server failed; forcing it closed:', stopError);
try {
instance?.forceStop?.();
} catch (forceError) {
logger.warn('Forcing the unregistered server closed failed:', forceError);
}
}
}

/**
* Launch a new server instance with dynamic port allocation
* @param htmlFile Optional HTML file to serve
Expand Down Expand Up @@ -114,14 +155,6 @@ export class MultiServerLauncher {
// Find available port using dynamic allocation
const requestedPort = settings.defaultPort;
const finalPort = await this.findAvailablePortWithLogging(requestedPort);
const portChanged = finalPort !== requestedPort;

if (portChanged) {
logger.debug(() => `Port ${requestedPort} already in use. Using port ${finalPort} instead.`);
notifyPortChanged(requestedPort, finalPort);
} else {
logger.debug(() => `Using requested port ${finalPort}`);
}

// Launch the server - Use 0.0.0.0 to listen on all network interfaces for external access
const host = '0.0.0.0';
Expand All @@ -137,7 +170,12 @@ export class MultiServerLauncher {
);

if (result.success && result.serverUrl) {
logger.debug(() => `Successfully launched ${serverType} server on port ${finalPort}`);
// The port the server really listens on. Everything below
// (registry, session, toasts, LAN URL) uses it, never the port
// that was only requested.
const boundPort = result.port ?? finalPort;
const portChanged = this.reportBoundPort(requestedPort, boundPort);
logger.debug(() => `Successfully launched ${serverType} server on port ${boundPort}`);

// Generate unique server ID
const serverId = this.generateServerId();
Expand All @@ -147,7 +185,7 @@ export class MultiServerLauncher {
id: serverId,
server: result.serverInstance!,
serverType: serverType,
port: finalPort,
port: boundPort,
htmlFile: htmlFile,
activeServerId: ''
};
Expand All @@ -159,12 +197,12 @@ export class MultiServerLauncher {

logger.debug('DEBUG - About to register server with the following details:');
logger.debug('DEBUG - customName:', customName);
logger.debug('DEBUG - port:', finalPort);
logger.debug('DEBUG - port:', boundPort);
logger.debug('DEBUG - url:', result.serverUrl);

const registrar = getServerRegistrar();
const activeServer = registrar.registerServer({
port: finalPort,
port: boundPort,
url: result.serverUrl,
launchMode: launchMode,
certMode: certMode,
Expand Down Expand Up @@ -192,22 +230,31 @@ export class MultiServerLauncher {

logger.debug(() => `Successfully registered server ${serverId} (active ID: ${activeServer.id}) via registrar service`);
logger.debug(() => `Currently managing ${this.servers.size} server(s)`);

// Handle auto-opening based on configuration
await handleAutoOpening(settings, result.serverUrl, htmlFile, launchMode, serverInfo.activeServerId);

} catch (error) {
// A server nobody registered cannot be found, listed or
// stopped again: stop it now and report the launch as failed
// instead of leaving an unreachable listener on 0.0.0.0.
logger.error('Failed to register server in registry:', error);
// Don't fail the launch if registry registration fails
this.servers.delete(serverId);
await this.discardUnregisteredServer(result.serverInstance);
return {
success: false,
error: `Failed to register the server: ${error instanceof Error ? error.message : String(error)}`,
httpsOverridden: isHttpsOverridden
};
}

// Handle auto-opening based on configuration. A failure to open
// the page does not undo a server that is running and listed.
await this.openLaunchedServer(settings, result.serverUrl, htmlFile, serverInfo.activeServerId);

return {
success: true,
serverUrl: result.serverUrl,
serverType: serverType,
serverId: serverId,
activeServerId: serverInfo.activeServerId || undefined,
port: finalPort,
port: boundPort,
httpsOverridden: isHttpsOverridden,
portChanged: portChanged,
originalPort: requestedPort
Expand Down Expand Up @@ -253,7 +300,12 @@ export class MultiServerLauncher {
logger.debug(() => `Port ${requestedPort} already in use. Searching for next available port (${requestedPort + 1})...`);

try {
const availablePort = await PortManager.findAvailablePort(requestedPort + 1);
// The search window follows the requested port: the default end port
// (8080) made a busy 8080 (allowed by the settings) fail every launch.
const availablePort = await PortManager.findAvailablePort(
requestedPort + 1,
Math.min(65535, requestedPort + 100),
);
logger.debug(() => `Free port found at ${availablePort}. Launching server...`);
return availablePort;
} catch (error) {
Expand Down
41 changes: 38 additions & 3 deletions apps/vscode-extension/src/core/server/portManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@ export class PortManager {
/**
* Check if a specific port is available
* @param port - The port number to check
* @param host - The host to bind to (default: '0.0.0.0')
* @param host - The host to bind to. Without one, the port must be free on
* the wildcard address and on loopback (see isPortFreeEverywhere).
* @returns Promise<boolean> - True if port is available, false otherwise
*/
public static async isPortAvailable(port: number, host: string = '0.0.0.0'): Promise<boolean> {
public static async isPortAvailable(port: number, host?: string): Promise<boolean> {
if (host === undefined) {
return PortManager.isPortFreeEverywhere(port);
}
return new Promise((resolve) => {
const server = net.createServer();

Expand All @@ -41,6 +45,36 @@ export class PortManager {
});
}

/**
* True only when the port is free on the wildcard address AND on loopback
* (IPv4 and IPv6). Checking 0.0.0.0 alone is not enough on macOS and
* Windows: a wildcard bind can succeed while another process (a Vite or
* Next dev server, typically on 3000) owns 127.0.0.1 or ::1, and
* "localhost" then reaches that other app instead of Code-XR.
*/
public static async isPortFreeEverywhere(port: number): Promise<boolean> {
for (const host of ['0.0.0.0', '127.0.0.1', '::1']) {
const free = await PortManager.isPortAvailableOnHost(port, host);
if (!free) {
return false;
}
}
return true;
}

/** Like isPortAvailable, but a host this machine does not have (no IPv6) counts as free. */
private static isPortAvailableOnHost(port: number, host: string): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
server.once('error', (err: NodeJS.ErrnoException) => {
resolve(err.code === 'EADDRNOTAVAIL' || err.code === 'EAFNOSUPPORT');
});
server.listen({ port, host, exclusive: true }, () => {
server.close(() => resolve(true));
});
});
}

/**
* Find the first available port starting from a given port number
* @param startPort - The starting port number (default: 3000)
Expand Down Expand Up @@ -81,9 +115,10 @@ export class PortManager {

logger.debug(() => `Checking ${ports.length} ports sequentially from ${startPort} to ${startPort + maxRange - 1}`);

// No host: get-port then checks the wildcard and every local
// interface, loopback included (see isPortFreeEverywhere).
const availablePort = await getPort({
port: ports,
host: '0.0.0.0' // Use 0.0.0.0 to check availability on all interfaces
});

logger.debug(() => `Found available port: ${availablePort} (sequential search successful)`);
Expand Down
Loading
Loading