From b4508462b3cb15197f68ef5f45f8af9ece0cccb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:32:16 +0000 Subject: [PATCH 01/29] IDE: one desktop seam for every Electron import of the main process (#480, #482) Every Node-side module now imports Electron through src/main/host/desktop.ts, which only re-exports it: the Electron build is unchanged. The Tauri build will swap that one module for the sidecar's implementation. nodeRuntime.ts holds the ELECTRON_RUN_AS_NODE variable that children run on the IDE's own executable need (extension host, TypeScript server, MCP, local agent, ACP agents), so the sidecar, a real Node, can drop it. --- .../src/main/agentSessions/agentCatalog.ts | 5 ++- .../main/agentSessions/agentSessionsIpc.ts | 2 +- .../agentSessions/agentSessionsRuntime.ts | 2 +- .../src/main/agentSessions/codexrMcpSpec.ts | 3 +- apps/ide/src/main/agents/agentsIpc.ts | 2 +- apps/ide/src/main/agents/agentsRuntime.ts | 2 +- apps/ide/src/main/agents/electronCipher.ts | 2 +- apps/ide/src/main/analysis/analysisService.ts | 2 +- apps/ide/src/main/analysis/sceneView.ts | 2 +- apps/ide/src/main/appIcon.ts | 2 +- apps/ide/src/main/appProtocol.ts | 2 +- apps/ide/src/main/codexr/analysesService.ts | 2 +- apps/ide/src/main/codexr/codexrIpc.ts | 2 +- apps/ide/src/main/codexr/serversService.ts | 2 +- apps/ide/src/main/codexr/settingsService.ts | 2 +- apps/ide/src/main/core/coreRuntime.ts | 2 +- apps/ide/src/main/core/electronHost.ts | 2 +- apps/ide/src/main/debug/debugHost.ts | 2 +- apps/ide/src/main/displayLanguage.ts | 2 +- .../main/extensions/extensionHostManager.ts | 5 ++- .../src/main/extensions/extensionsService.ts | 2 +- apps/ide/src/main/extensions/webviewServer.ts | 2 +- apps/ide/src/main/git/gitIpc.ts | 2 +- apps/ide/src/main/hardening.ts | 2 +- apps/ide/src/main/host/desktop.ts | 42 +++++++++++++++++++ apps/ide/src/main/index.ts | 2 +- apps/ide/src/main/ipc.ts | 2 +- apps/ide/src/main/lsp/lspHost.ts | 2 +- apps/ide/src/main/lsp/lspIpc.ts | 2 +- apps/ide/src/main/lsp/lspServers.ts | 3 +- apps/ide/src/main/menu.ts | 2 +- apps/ide/src/main/menuTemplate.ts | 2 +- apps/ide/src/main/nodeRuntime.ts | 21 ++++++++++ .../ide/src/main/outputPanel/outputService.ts | 2 +- .../main/problems/functionMetricsService.ts | 2 +- apps/ide/src/main/settings/theme.ts | 2 +- apps/ide/src/main/smoke.ts | 2 +- apps/ide/src/main/smokeProgramInput.ts | 2 +- apps/ide/src/main/tasks/taskHost.ts | 2 +- apps/ide/src/main/terminal/terminalHost.ts | 2 +- apps/ide/src/main/trust/workspaceTrust.ts | 2 +- apps/ide/src/main/unsavedGuard.ts | 2 +- apps/ide/src/main/updates/updateCheck.ts | 2 +- apps/ide/src/main/window.ts | 2 +- apps/ide/src/main/workspace/searchService.ts | 2 +- .../src/main/workspace/workspaceWindows.ts | 2 +- 46 files changed, 113 insertions(+), 46 deletions(-) create mode 100644 apps/ide/src/main/host/desktop.ts create mode 100644 apps/ide/src/main/nodeRuntime.ts diff --git a/apps/ide/src/main/agentSessions/agentCatalog.ts b/apps/ide/src/main/agentSessions/agentCatalog.ts index 0fd51324e..64814a3e7 100644 --- a/apps/ide/src/main/agentSessions/agentCatalog.ts +++ b/apps/ide/src/main/agentSessions/agentCatalog.ts @@ -5,6 +5,7 @@ import { AGENT_PRESET_IDS, type AcpAgentDefinition, type AgentAvailability, type import { isLocalServerId, LOCAL_SERVER_PRESETS, normalizeLocalBaseUrl } from '@codexr/local-models/servers.ts'; import type { AgentLaunch } from './acpConnection.ts'; import { API_KEY_ENV, type AuthMethodSpec } from './acpMapping.ts'; +import { nodeModeEnv } from '../nodeRuntime.ts'; /** * AF1/AF2: the agents a chat can use. Three presets the IDE knows how to @@ -453,7 +454,7 @@ export class AgentCatalog { const viaNode = (script: string, via: string): Resolution => ({ found: true, via, - launch: { command: execPath, args: [script, ...definition.args], env: agentEnv({ ELECTRON_RUN_AS_NODE: '1' }) }, + launch: { command: execPath, args: [script, ...definition.args], env: agentEnv({ ...nodeModeEnv() }) }, }); if (definition.local) { @@ -470,7 +471,7 @@ export class AgentCatalog { args: [script], // The key travels in the environment only, never on the command line. env: agentEnvironment(env, null, { - ELECTRON_RUN_AS_NODE: '1', + ...nodeModeEnv(), CODEXR_LOCAL_AGENT_NAME: definition.name, CODEXR_LOCAL_BASE_URL: definition.local.baseUrl, CODEXR_LOCAL_MODEL: definition.local.model, diff --git a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts index b86874e58..f4207c9e4 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts @@ -1,4 +1,4 @@ -import type { IpcMainInvokeEvent } from 'electron'; +import type { IpcMainInvokeEvent } from '../host/desktop.ts'; import { AGENT_SESSION_CHANNELS } from '../../shared/agentSession.ts'; import type { AgentSessionsRuntime } from './agentSessionsRuntime.ts'; diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index e8518003f..2e6cfc301 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, dialog, net, webContents, type WebContents } from 'electron'; +import { app, BrowserWindow, dialog, net, webContents, type WebContents } from '../host/desktop.ts'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/apps/ide/src/main/agentSessions/codexrMcpSpec.ts b/apps/ide/src/main/agentSessions/codexrMcpSpec.ts index b96409e2c..b5fcc2115 100644 --- a/apps/ide/src/main/agentSessions/codexrMcpSpec.ts +++ b/apps/ide/src/main/agentSessions/codexrMcpSpec.ts @@ -1,4 +1,5 @@ import path from 'node:path'; +import { nodeModeEnv } from '../nodeRuntime.ts'; /** * The stdio MCP server spec that hands Code-XR's analysis to an external @@ -49,6 +50,6 @@ export function codexrMcpServerSpec(options: CodexrMcpSpecOptions): CodexrMcpSer name: CODEXR_MCP_SERVER_NAME, command: options.execPath, args: [codexrMcpEntry(options.appPath), '--root', options.root, '--analysis', options.analysisDir ?? ''], - env: [{ name: 'ELECTRON_RUN_AS_NODE', value: '1' }], + env: Object.entries(nodeModeEnv()).map(([name, value]) => ({ name, value })), }; } diff --git a/apps/ide/src/main/agents/agentsIpc.ts b/apps/ide/src/main/agents/agentsIpc.ts index 0673e089f..63a484917 100644 --- a/apps/ide/src/main/agents/agentsIpc.ts +++ b/apps/ide/src/main/agents/agentsIpc.ts @@ -1,4 +1,4 @@ -import type { IpcMainInvokeEvent, WebContents } from 'electron'; +import type { IpcMainInvokeEvent, WebContents } from '../host/desktop.ts'; import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent } from '../../shared/agents.ts'; import { currentWorkspaceInfo, workspaceOrNull } from '../workspace/workspaceWindows.ts'; import type { AgentServices } from './agentsRuntime.ts'; diff --git a/apps/ide/src/main/agents/agentsRuntime.ts b/apps/ide/src/main/agents/agentsRuntime.ts index 0a63e56a2..01f03f0ff 100644 --- a/apps/ide/src/main/agents/agentsRuntime.ts +++ b/apps/ide/src/main/agents/agentsRuntime.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, dialog } from 'electron'; +import { app, BrowserWindow, dialog } from '../host/desktop.ts'; import os from 'node:os'; import path from 'node:path'; import { JsonKeyValueStore } from '../core/jsonStore.ts'; diff --git a/apps/ide/src/main/agents/electronCipher.ts b/apps/ide/src/main/agents/electronCipher.ts index 1e1b5a9f8..97d9f0475 100644 --- a/apps/ide/src/main/agents/electronCipher.ts +++ b/apps/ide/src/main/agents/electronCipher.ts @@ -1,4 +1,4 @@ -import { safeStorage } from 'electron'; +import { safeStorage } from '../host/desktop.ts'; import type { SecretCipher } from './keyVault.ts'; /** diff --git a/apps/ide/src/main/analysis/analysisService.ts b/apps/ide/src/main/analysis/analysisService.ts index 6acd62f9e..9927159e1 100644 --- a/apps/ide/src/main/analysis/analysisService.ts +++ b/apps/ide/src/main/analysis/analysisService.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, clipboard, webContents, type WebContents } from 'electron'; +import { BrowserWindow, clipboard, webContents, type WebContents } from '../host/desktop.ts'; import { createHash } from 'node:crypto'; import path from 'node:path'; import { AnalysisOrchestrator } from '@codexr/core/analysis/analysisOrchestrator'; diff --git a/apps/ide/src/main/analysis/sceneView.ts b/apps/ide/src/main/analysis/sceneView.ts index 34a9e4cd1..519d2d8ff 100644 --- a/apps/ide/src/main/analysis/sceneView.ts +++ b/apps/ide/src/main/analysis/sceneView.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, WebContentsView, desktopCapturer, dialog, net, session, type Session, type WebContents } from 'electron'; +import { BrowserWindow, WebContentsView, desktopCapturer, dialog, net, session, type Session, type WebContents } from '../host/desktop.ts'; import fs from 'node:fs/promises'; import path from 'node:path'; import type { SceneBounds } from '../../shared/api.ts'; diff --git a/apps/ide/src/main/appIcon.ts b/apps/ide/src/main/appIcon.ts index b9d0e7a55..19e3fa5f3 100644 --- a/apps/ide/src/main/appIcon.ts +++ b/apps/ide/src/main/appIcon.ts @@ -1,4 +1,4 @@ -import { app } from 'electron'; +import { app } from './host/desktop.ts'; import path from 'node:path'; /** diff --git a/apps/ide/src/main/appProtocol.ts b/apps/ide/src/main/appProtocol.ts index 1c432abf8..2895272ca 100644 --- a/apps/ide/src/main/appProtocol.ts +++ b/apps/ide/src/main/appProtocol.ts @@ -1,4 +1,4 @@ -import { net, protocol } from 'electron'; +import { net, protocol } from './host/desktop.ts'; import { pathToFileURL } from 'node:url'; import { APP_HOST, APP_SCHEME, buildContentSecurityPolicy } from './security.ts'; import { resolveRendererAsset } from './assetPath.ts'; diff --git a/apps/ide/src/main/codexr/analysesService.ts b/apps/ide/src/main/codexr/analysesService.ts index ae2d83a51..e495da0bb 100644 --- a/apps/ide/src/main/codexr/analysesService.ts +++ b/apps/ide/src/main/codexr/analysesService.ts @@ -1,4 +1,4 @@ -import { BrowserWindow } from 'electron'; +import { BrowserWindow } from '../host/desktop.ts'; import { listActiveAnalyses } from '@codexr/core/analysis/session/activeAnalyses'; import { UnifiedSessionRegistry } from '@codexr/core/analysis/session/sessionRegistry'; import type { HostDisposable } from '@codexr/core/host/codeXRHost'; diff --git a/apps/ide/src/main/codexr/codexrIpc.ts b/apps/ide/src/main/codexr/codexrIpc.ts index 0ed6ca609..7d9c8e2de 100644 --- a/apps/ide/src/main/codexr/codexrIpc.ts +++ b/apps/ide/src/main/codexr/codexrIpc.ts @@ -1,4 +1,4 @@ -import { shell, type IpcMainInvokeEvent } from 'electron'; +import { shell, type IpcMainInvokeEvent } from '../host/desktop.ts'; import { CODEXR_IPC_CHANNELS, parseAnalysisAction, parseParticipantRef, parseSceneMode, parseServerAction, parseSettingsPatch } from '../../shared/codexr.ts'; import type { AnalysisService } from '../analysis/analysisService.ts'; import type { AnalysesService } from './analysesService.ts'; diff --git a/apps/ide/src/main/codexr/serversService.ts b/apps/ide/src/main/codexr/serversService.ts index 1370fe200..2c0f9a1e8 100644 --- a/apps/ide/src/main/codexr/serversService.ts +++ b/apps/ide/src/main/codexr/serversService.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, clipboard } from 'electron'; +import { BrowserWindow, clipboard } from '../host/desktop.ts'; import { UnifiedSessionRegistry } from '@codexr/core/analysis/session/sessionRegistry'; import { COLLABORATION_AVATARS } from '@codexr/core/collaboration/collaborationProfile'; import type { HostDisposable } from '@codexr/core/host/codeXRHost'; diff --git a/apps/ide/src/main/codexr/settingsService.ts b/apps/ide/src/main/codexr/settingsService.ts index 3ff3158d0..1f0cd2076 100644 --- a/apps/ide/src/main/codexr/settingsService.ts +++ b/apps/ide/src/main/codexr/settingsService.ts @@ -1,4 +1,4 @@ -import { BrowserWindow } from 'electron'; +import { BrowserWindow } from '../host/desktop.ts'; import { DEFAULT_COLLABORATION_PROFILE } from '@codexr/core/collaboration/collaborationProfile'; import { CollaborationProfileManager } from '@codexr/core/collaboration/collaborationProfileManager'; import { ServerSettingsManager } from '@codexr/core/server/serverSettingsManager'; diff --git a/apps/ide/src/main/core/coreRuntime.ts b/apps/ide/src/main/core/coreRuntime.ts index 937c1abe7..b82f3fa37 100644 --- a/apps/ide/src/main/core/coreRuntime.ts +++ b/apps/ide/src/main/core/coreRuntime.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow } from 'electron'; +import { app, BrowserWindow } from '../host/desktop.ts'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/apps/ide/src/main/core/electronHost.ts b/apps/ide/src/main/core/electronHost.ts index e262e9c13..3458204d3 100644 --- a/apps/ide/src/main/core/electronHost.ts +++ b/apps/ide/src/main/core/electronHost.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, clipboard, dialog, shell } from 'electron'; +import { BrowserWindow, clipboard, dialog, shell } from '../host/desktop.ts'; import path from 'node:path'; import type { CodeXRHost, diff --git a/apps/ide/src/main/debug/debugHost.ts b/apps/ide/src/main/debug/debugHost.ts index 989b99087..b66d713b0 100644 --- a/apps/ide/src/main/debug/debugHost.ts +++ b/apps/ide/src/main/debug/debugHost.ts @@ -1,4 +1,4 @@ -import type { IpcMainInvokeEvent, WebContents } from 'electron'; +import type { IpcMainInvokeEvent, WebContents } from '../host/desktop.ts'; import { spawn } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; diff --git a/apps/ide/src/main/displayLanguage.ts b/apps/ide/src/main/displayLanguage.ts index f51e49b5d..e8a5c9afa 100644 --- a/apps/ide/src/main/displayLanguage.ts +++ b/apps/ide/src/main/displayLanguage.ts @@ -1,4 +1,4 @@ -import { app } from 'electron'; +import { app } from './host/desktop.ts'; import { LOCALE_QUERY_PARAMETER, resolveLocale, setLocale, type Locale } from '../shared/i18n/i18n.ts'; import { log } from './log.ts'; diff --git a/apps/ide/src/main/extensions/extensionHostManager.ts b/apps/ide/src/main/extensions/extensionHostManager.ts index 8f0872519..867ba7853 100644 --- a/apps/ide/src/main/extensions/extensionHostManager.ts +++ b/apps/ide/src/main/extensions/extensionHostManager.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, clipboard, dialog, shell, type IpcMainInvokeEvent, type WebContents } from 'electron'; +import { app, BrowserWindow, clipboard, dialog, shell, type IpcMainInvokeEvent, type WebContents } from '../host/desktop.ts'; import { fork, type ChildProcess } from 'node:child_process'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -26,6 +26,7 @@ import { inlineTreeIcons } from './viewIcons.ts'; import { ExtensionSettingsStore } from './extensionSettings.ts'; import type { ActivationSource, ExtensionsService } from './extensionsService.ts'; import type { LoadedExtension } from './extensionStore.ts'; +import { nodeModeEnv } from '../nodeRuntime.ts'; type Handle = (channel: string, handler: (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown) => void; @@ -143,7 +144,7 @@ export class ExtensionHostManager implements ActivationSource { const child = fork(this.hostScript, [], { execPath: process.execPath, cwd: folder ?? app.getPath('home'), - env: serverEnvironment(process.env, { ELECTRON_RUN_AS_NODE: '1', CODEXR_EXTENSION_HOST: '1' }), + env: serverEnvironment(process.env, { ...nodeModeEnv(), CODEXR_EXTENSION_HOST: '1' }), stdio: ['ignore', 'pipe', 'pipe', 'ipc'], serialization: 'advanced', ...(this.isDevelopment ? { execArgv: ['--enable-source-maps'] } : {}), diff --git a/apps/ide/src/main/extensions/extensionsService.ts b/apps/ide/src/main/extensions/extensionsService.ts index e58190087..c413b68a5 100644 --- a/apps/ide/src/main/extensions/extensionsService.ts +++ b/apps/ide/src/main/extensions/extensionsService.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, dialog, net, type IpcMainInvokeEvent, type WebContents } from 'electron'; +import { BrowserWindow, dialog, net, type IpcMainInvokeEvent, type WebContents } from '../host/desktop.ts'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/apps/ide/src/main/extensions/webviewServer.ts b/apps/ide/src/main/extensions/webviewServer.ts index 9be4da04d..6bd4520e7 100644 --- a/apps/ide/src/main/extensions/webviewServer.ts +++ b/apps/ide/src/main/extensions/webviewServer.ts @@ -1,4 +1,4 @@ -import { net, protocol } from 'electron'; +import { net, protocol } from '../host/desktop.ts'; import crypto from 'node:crypto'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; diff --git a/apps/ide/src/main/git/gitIpc.ts b/apps/ide/src/main/git/gitIpc.ts index fe4dd69bb..e6167e76b 100644 --- a/apps/ide/src/main/git/gitIpc.ts +++ b/apps/ide/src/main/git/gitIpc.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, dialog, shell, type IpcMainInvokeEvent, type MessageBoxOptions, type WebContents } from 'electron'; +import { BrowserWindow, dialog, shell, type IpcMainInvokeEvent, type MessageBoxOptions, type WebContents } from '../host/desktop.ts'; import fs from 'node:fs'; import path from 'node:path'; import { emptyGitStatus, GIT_IPC_CHANNELS, GIT_IPC_EVENTS, isGitRemoteOperation, type GitCommitResult, type GitDeleteBranchResult, type GitRemoteResult, type GitStatus } from '../../shared/git.ts'; diff --git a/apps/ide/src/main/hardening.ts b/apps/ide/src/main/hardening.ts index 704ddaa41..b5a099577 100644 --- a/apps/ide/src/main/hardening.ts +++ b/apps/ide/src/main/hardening.ts @@ -1,4 +1,4 @@ -import { app, session, type WebContents, type WebFrameMain } from 'electron'; +import { app, session, type WebContents, type WebFrameMain } from './host/desktop.ts'; import { buildContentSecurityPolicy, isAllowedNavigation } from './security.ts'; import { log } from './log.ts'; diff --git a/apps/ide/src/main/host/desktop.ts b/apps/ide/src/main/host/desktop.ts new file mode 100644 index 000000000..19949f3c4 --- /dev/null +++ b/apps/ide/src/main/host/desktop.ts @@ -0,0 +1,42 @@ +/** + * The desktop seam (#480/#482, epic #477: the move from Electron to Tauri 2). + * + * Every Node-side module of the IDE that needs the desktop (windows, dialogs, + * clipboard, the OS shell, secrets, the theme...) imports it from here, never + * from `electron` directly. This file is the Electron implementation: it only + * re-exports Electron, so the Electron build behaves exactly as before. + * + * The Tauri build (the Node sidecar, scripts/viteConfigs.mjs) swaps this + * module for `src/sidecar/tauriHost.ts`, which implements the same subset by + * asking the Rust core over JSON-RPC. Add a name here only together with its + * counterpart there. + */ +export { + app, + BrowserWindow, + clipboard, + desktopCapturer, + dialog, + ipcMain, + Menu, + nativeImage, + nativeTheme, + net, + protocol, + safeStorage, + session, + shell, + webContents, + WebContentsView, +} from 'electron'; +export type { + IpcMainInvokeEvent, + MenuItemConstructorOptions, + MessageBoxOptions, + Session, + WebContents, + WebFrameMain, +} from 'electron'; + +/** Which shell this build runs in (the sidecar's implementation says `tauri`). */ +export const DESKTOP_SHELL: 'electron' | 'tauri' = 'electron'; diff --git a/apps/ide/src/main/index.ts b/apps/ide/src/main/index.ts index 28b8c223d..38ab32d4b 100644 --- a/apps/ide/src/main/index.ts +++ b/apps/ide/src/main/index.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, nativeTheme } from 'electron'; +import { app, BrowserWindow, nativeTheme } from './host/desktop.ts'; import fs from 'node:fs'; import path from 'node:path'; import { applyProcessHardening } from './hardening.ts'; diff --git a/apps/ide/src/main/ipc.ts b/apps/ide/src/main/ipc.ts index 3be035aa6..60416fbbc 100644 --- a/apps/ide/src/main/ipc.ts +++ b/apps/ide/src/main/ipc.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, clipboard, ipcMain, shell, type IpcMainInvokeEvent, type WebContents } from 'electron'; +import { app, BrowserWindow, clipboard, ipcMain, shell, type IpcMainInvokeEvent, type WebContents } from './host/desktop.ts'; import type { CoreServices } from './core/coreRuntime.ts'; import { isAnalysisKind } from '../shared/analysisKinds.ts'; import { BENCH_FLAG, BENCH_RESULT_PREFIX } from './bench.ts'; diff --git a/apps/ide/src/main/lsp/lspHost.ts b/apps/ide/src/main/lsp/lspHost.ts index dd3030d8f..ac8499f7f 100644 --- a/apps/ide/src/main/lsp/lspHost.ts +++ b/apps/ide/src/main/lsp/lspHost.ts @@ -1,4 +1,4 @@ -import type { WebContents } from 'electron'; +import type { WebContents } from '../host/desktop.ts'; import fs from 'node:fs'; import { createRequire } from 'node:module'; import path from 'node:path'; diff --git a/apps/ide/src/main/lsp/lspIpc.ts b/apps/ide/src/main/lsp/lspIpc.ts index 9d53e7765..64d23e49d 100644 --- a/apps/ide/src/main/lsp/lspIpc.ts +++ b/apps/ide/src/main/lsp/lspIpc.ts @@ -1,4 +1,4 @@ -import type { IpcMainInvokeEvent } from 'electron'; +import type { IpcMainInvokeEvent } from '../host/desktop.ts'; import { LSP_IPC_CHANNELS } from '../../shared/lsp.ts'; import type { LspHost } from './lspHost.ts'; diff --git a/apps/ide/src/main/lsp/lspServers.ts b/apps/ide/src/main/lsp/lspServers.ts index 6220cbf01..c7ee1a2de 100644 --- a/apps/ide/src/main/lsp/lspServers.ts +++ b/apps/ide/src/main/lsp/lspServers.ts @@ -1,4 +1,5 @@ import path from 'node:path'; +import { nodeModeEnv } from '../nodeRuntime.ts'; /** * Which program serves each language (#21). The renderer never names one: @@ -40,7 +41,7 @@ export function typescriptServerCommand(paths: { readonly execPath: string; read name: 'typescript-language-server', command: paths.execPath, args: [paths.cliPath, '--stdio', '--log-level', '2'], - env: serverEnvironment(env, { ELECTRON_RUN_AS_NODE: '1' }), + env: serverEnvironment(env, { ...nodeModeEnv() }), initializationOptions: { hostInfo: 'code-xr-ide', tsserver: { path: paths.tsserverPath }, diff --git a/apps/ide/src/main/menu.ts b/apps/ide/src/main/menu.ts index 4e36bd8ff..34f882df1 100644 --- a/apps/ide/src/main/menu.ts +++ b/apps/ide/src/main/menu.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, dialog, Menu, nativeImage, type MenuItemConstructorOptions } from 'electron'; +import { app, BrowserWindow, dialog, Menu, nativeImage, type MenuItemConstructorOptions } from './host/desktop.ts'; import { appIconPath } from './appIcon.ts'; import { IDE_COMMANDS, IPC_EVENTS, type IdeCommand } from '../shared/api.ts'; import { electronAccelerator, isChord, isValidKeybinding, menuAccelerator } from '../shared/keybindings.ts'; diff --git a/apps/ide/src/main/menuTemplate.ts b/apps/ide/src/main/menuTemplate.ts index 6ac62a4e9..e3b54e950 100644 --- a/apps/ide/src/main/menuTemplate.ts +++ b/apps/ide/src/main/menuTemplate.ts @@ -1,4 +1,4 @@ -import type { MenuItemConstructorOptions } from 'electron'; +import type { MenuItemConstructorOptions } from './host/desktop.ts'; import type { IdeCommand } from '../shared/api.ts'; import type { MenuToggles } from '../shared/settings.ts'; import { getLocale, t, type MessageKey } from '../shared/i18n/i18n.ts'; diff --git a/apps/ide/src/main/nodeRuntime.ts b/apps/ide/src/main/nodeRuntime.ts new file mode 100644 index 000000000..33a44b5d5 --- /dev/null +++ b/apps/ide/src/main/nodeRuntime.ts @@ -0,0 +1,21 @@ +/** + * How a child process runs the IDE's own executable as Node.js (#482). + * + * On Electron, `process.execPath` is the Electron binary, which behaves as + * Node only with `ELECTRON_RUN_AS_NODE=1`. In the Tauri build the same code + * runs in the Node sidecar, where `process.execPath` is a real Node and the + * variable is not needed: the sidecar calls `useRealNodeRuntime()` before it + * starts anything. Electron is the default so the Electron build (and the + * unit tests) see exactly what they saw before. + */ +let runAsNodeEnv: Readonly> = Object.freeze({ ELECTRON_RUN_AS_NODE: '1' }); + +/** The variables a child started as `process.execPath x'; + assert.equal( + rewriteSceneLibraryUrls(page), + `x`, + ); + // A-Frame's run-time font root, and BabiaXR's literal default font. + assert.equal(rewriteSceneLibraryUrls('a="https://cdn.aframe.io/"'), `a="${LOCAL_SCENE_LIBRARIES_ROUTE}"`); + assert.equal(rewriteSceneLibraryUrls('"https://cdn.aframe.io/fonts/Roboto-msdf.json"'), `"${LOCAL_SCENE_LIBRARIES_ROUTE}fonts/Roboto-msdf.json"`); + }); + + it('serves only the files of the table under the route', async () => { + assert.equal(localLibraryFileOf(`${LOCAL_SCENE_LIBRARIES_ROUTE}aframe-1.7.1.min.js`), 'aframe-1.7.1.min.js'); + assert.equal(localLibraryFileOf(`${LOCAL_SCENE_LIBRARIES_ROUTE}fonts/Roboto-msdf.png`), 'fonts/Roboto-msdf.png'); + assert.equal(localLibraryFileOf(`${LOCAL_SCENE_LIBRARIES_ROUTE}README.md`), null); + assert.equal(localLibraryFileOf(`${LOCAL_SCENE_LIBRARIES_ROUTE}../package.json`), null); + assert.equal(localLibraryFileOf('/aframe-1.7.1.min.js'), null); + + assert.equal(localSceneLibrariesEnabled(), false); + assert.equal(await readLocalLibrary('aframe-1.7.1.min.js'), null); + setLocalSceneLibraries(vendor); + try { + const aframe = (await readLocalLibrary('aframe-1.7.1.min.js'))?.toString('utf8') ?? ''; + assert.ok(aframe.length > 100_000); + assert.ok(!aframe.includes('"https://cdn.aframe.io/"'), 'A-Frame\'s font root still points at the CDN'); + assert.ok(aframe.includes(`"${LOCAL_SCENE_LIBRARIES_ROUTE}"`)); + const png = await readLocalLibrary('fonts/Roboto-msdf.png'); + assert.deepEqual(png?.subarray(0, 4), Buffer.from([0x89, 0x50, 0x4e, 0x47])); + assert.equal(await readLocalLibrary('README.md'), null); + } finally { + setLocalSceneLibraries(null); + } + }); }); diff --git a/apps/vscode-extension/src/core/server/http/localSceneLibraries.ts b/apps/vscode-extension/src/core/server/http/localSceneLibraries.ts new file mode 100644 index 000000000..86abfaa81 --- /dev/null +++ b/apps/vscode-extension/src/core/server/http/localSceneLibraries.ts @@ -0,0 +1,127 @@ +import * as fs from 'fs'; +import * as path from 'path'; + +/** + * The scene's third-party libraries served by the analysis server itself, + * from the copies in the repository, instead of their CDNs (Code-XR IDE, + * #16 and #483). + * + * Generated scenes load A-Frame, BabiaXR and friends from CDNs (pinned + * versions). The VS Code extension keeps doing so: nothing here is active + * until a host calls `setLocalSceneLibraries`. The Code-XR IDE does, at + * start-up: the project rule is no network access without consent, and a + * scene beside the code must not depend on a CDN being up. Its Electron build + * used to answer the CDN URLs by intercepting `https` in the scene view's + * session; the system webviews of its Tauri build cannot intercept `https`, + * so the server rewrites the pinned URLs of the pages it sends to this + * machine into `LOCAL_SCENE_LIBRARIES_ROUTE`, and serves that route from + * `test/vendor/scene-libraries/` (the same copies, and licences, the offline + * browser harnesses use). + * + * Pages sent through the Cloudflare tunnel (a guest, a standalone headset) + * are not rewritten: they keep loading the CDNs, as they always have. + */ + +/** Where the vendored files are served, on the scene's own origin. */ +export const LOCAL_SCENE_LIBRARIES_ROUTE = '/__codexr/scene-libraries/'; + +/** [URL pattern, vendored file]: the versions the templates pin (kept in step with test/helpers/harnessBrowser.cjs). */ +export const SCENE_LIBRARIES: ReadonlyArray = [ + [/^https:\/\/aframe\.io\/releases\/1\.7\.1\/aframe(?:\.min)?\.js(?:\?|$)/, 'aframe-1.7.1.min.js'], + [/^https:\/\/unpkg\.com\/aframe-babia-components@1\.5\.0\//, 'aframe-babia-components-1.5.0.min.js'], + [/^https:\/\/cdn\.jsdelivr\.net\/gh\/(?:c-frame|donmccurdy)\/aframe-extras@v?7\.5\.4\//, 'aframe-extras-7.5.4.min.js'], + [/^https:\/\/unpkg\.com\/aframe-environment-component@1\.5\.0\//, 'aframe-environment-component-1.5.0.min.js'], + [/^https:\/\/unpkg\.com\/aframe-geometry-merger-component@2\.0\.1\//, 'aframe-geometry-merger-component-2.0.1.min.js'], + [/^https:\/\/cdnjs\.cloudflare\.com\/ajax\/libs\/html2canvas\/1\.4\.1\/html2canvas(?:\.min)?\.js(?:\?|$)/, 'html2canvas-1.4.1.min.js'], + // A-Frame's default text font (its `text` component fetches it at run time). + [/^https:\/\/cdn\.aframe\.io\/fonts\/Roboto-msdf\.json(?:\?|$)/, 'fonts/Roboto-msdf.json'], + [/^https:\/\/cdn\.aframe\.io\/fonts\/Roboto-msdf\.png(?:\?|$)/, 'fonts/Roboto-msdf.png'], +]; + +/** + * A-Frame builds its font URLs from this root at run time + * (`window.AFRAME_CDN_ROOT || "https://cdn.aframe.io/"`); the vendored + * folder mirrors its `fonts/` folder, so the root maps to the route. + */ +const AFRAME_CDN_ROOT = 'https://cdn.aframe.io/'; + +const CONTENT_TYPES: Readonly> = { + '.js': 'application/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.png': 'image/png', +}; + +/** The content type a vendored file is served with. */ +export function contentTypeOf(file: string): string { + const dot = file.lastIndexOf('.'); + return CONTENT_TYPES[dot >= 0 ? file.slice(dot) : ''] ?? 'application/octet-stream'; +} + +/** The vendored file name for a CDN URL, or null when the URL is not one of the pinned libraries. */ +export function vendoredLibraryFor(url: string): string | null { + return SCENE_LIBRARIES.find(([pattern]) => pattern.test(url))?.[1] ?? null; +} + +/** + * `text` with every pinned CDN URL (and A-Frame's CDN root) pointing at the + * local route instead. Any other address is left as it is. + */ +export function rewriteSceneLibraryUrls(text: string): string { + return text.replace(/https:\/\/[^\s"'`()<>]+/g, (url) => { + if (url === AFRAME_CDN_ROOT) { + return LOCAL_SCENE_LIBRARIES_ROUTE; + } + const file = vendoredLibraryFor(url); + return file ? `${LOCAL_SCENE_LIBRARIES_ROUTE}${file}` : url; + }); +} + +const SERVED_FILES: ReadonlySet = new Set(SCENE_LIBRARIES.map(([, file]) => file)); + +/** + * The vendored file a request path of the route names, or null: only the + * files of the table are served, whatever else the folder holds. + */ +export function localLibraryFileOf(pathname: string): string | null { + if (!pathname.startsWith(LOCAL_SCENE_LIBRARIES_ROUTE)) { + return null; + } + const file = pathname.slice(LOCAL_SCENE_LIBRARIES_ROUTE.length); + return SERVED_FILES.has(file) ? file : null; +} + +let librariesDir: string | null = null; +const cache = new Map(); + +/** A host serves the vendored libraries from `dir` (null turns it off, the default). */ +export function setLocalSceneLibraries(dir: string | null): void { + librariesDir = dir; + cache.clear(); +} + +/** Whether a host turned local libraries on. */ +export function localSceneLibrariesEnabled(): boolean { + return librariesDir !== null; +} + +/** + * The body of a vendored file, scripts with their own CDN URLs rewritten + * (A-Frame's font root, BabiaXR's default font), or null when it cannot be read. + */ +export async function readLocalLibrary(file: string): Promise { + if (!librariesDir || !SERVED_FILES.has(file)) { + return null; + } + const cached = cache.get(file); + if (cached) { + return cached; + } + try { + const raw = await fs.promises.readFile(path.join(librariesDir, ...file.split('/'))); + const body = file.endsWith('.js') ? Buffer.from(rewriteSceneLibraryUrls(raw.toString('utf8')), 'utf8') : raw; + cache.set(file, body); + return body; + } catch { + return null; + } +} diff --git a/apps/vscode-extension/src/core/server/http/staticAssets.ts b/apps/vscode-extension/src/core/server/http/staticAssets.ts index 421aa18da..ffddb05d0 100644 --- a/apps/vscode-extension/src/core/server/http/staticAssets.ts +++ b/apps/vscode-extension/src/core/server/http/staticAssets.ts @@ -25,7 +25,7 @@ export class StaticAssetServer { * Serve the main CodeXR page * @param res - HTTP response */ - public async serveMainPage(res: http.ServerResponse): Promise { + public async serveMainPage(res: http.ServerResponse, rewriteHtml?: (html: string) => string): Promise { let mainPagePath: string; if (this.options.mainFile) { @@ -47,7 +47,7 @@ export class StaticAssetServer { // Check if file exists and serve it if (fs.existsSync(mainPagePath)) { logger.debug(() => `Successfully found main file, serving: ${mainPagePath}`); - await this.serveFile(res, mainPagePath, 'text/html'); + await this.serveFile(res, mainPagePath, 'text/html', rewriteHtml); } else { logger.error(`Main file not found: ${mainPagePath}`); logger.error(`Current working directory: ${process.cwd()}`); @@ -72,11 +72,13 @@ export class StaticAssetServer { * @param _req - HTTP request (unused) * @param res - HTTP response * @param url - Request URL + * @param rewriteHtml - Optional rewrite of an HTML page's text (local scene libraries) */ public async serveStaticFile( _req: http.IncomingMessage, res: http.ServerResponse, - url: string + url: string, + rewriteHtml?: (html: string) => string ): Promise { // Parse URL to extract pathname without query string (WHATWG parser: // the legacy url.parse() emits DEP0169 in the extension host). @@ -99,7 +101,7 @@ export class StaticAssetServer { if (fs.existsSync(normalizedPath) && fs.statSync(normalizedPath).isFile()) { logger.debug(() => `SERVER_DEBUG: Serving file: ${normalizedPath}`); - await this.serveFile(res, normalizedPath); + await this.serveFile(res, normalizedPath, undefined, rewriteHtml); } else { logger.debug(() => `SERVER_DEBUG: File not found: ${normalizedPath}`); sendErrorResponse(res, 404, 'File not found'); @@ -111,15 +113,20 @@ export class StaticAssetServer { * @param res - HTTP response * @param filePath - Path to the file * @param contentType - Content type (optional, will be detected) + * @param rewriteHtml - Optional rewrite of the text of an HTML file */ public async serveFile( res: http.ServerResponse, filePath: string, - contentType?: string + contentType?: string, + rewriteHtml?: (html: string) => string ): Promise { try { - const content = await fs.promises.readFile(filePath); + const raw = await fs.promises.readFile(filePath); const detectedContentType = contentType || this.getContentType(filePath); + const content = rewriteHtml && detectedContentType.startsWith('text/html') + ? Buffer.from(rewriteHtml(raw.toString('utf8')), 'utf8') + : raw; const headers: Record = { 'Content-Type': detectedContentType }; if (/\.(:html|js|mjs|json|map)$/i.test(filePath)) { headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'; diff --git a/apps/vscode-extension/src/core/server/httpServer.ts b/apps/vscode-extension/src/core/server/httpServer.ts index 9a74f65ab..399712f83 100644 --- a/apps/vscode-extension/src/core/server/httpServer.ts +++ b/apps/vscode-extension/src/core/server/httpServer.ts @@ -13,6 +13,7 @@ import { REVEAL_IN_SCENE_MESSAGE, scenePathOf } from './analysis/sceneReveal'; import { hostMessageContext, sceneModeOptions, switchSceneMode, type SceneModeResult, type SceneModes } from './analysis/sceneModeControl'; import { addCorsHeaders, sendErrorResponse, sendJsonResponse } from './http/httpRespond'; import { StaticAssetServer } from './http/staticAssets'; +import { contentTypeOf, localLibraryFileOf, localSceneLibrariesEnabled, readLocalLibrary, rewriteSceneLibraryUrls } from './http/localSceneLibraries'; import { RemoteAccessPolicy } from './remote/remoteAccessPolicy'; import { RemotePairingApi } from './remote/remotePairingApi'; import { CollaborationSessionApi } from './collaboration/collaborationSessionApi'; @@ -493,9 +494,18 @@ export class HttpServer { res: http.ServerResponse, url: string ): Promise { + // A host that serves the scene libraries itself (the Code-XR IDE): + // pages sent to this machine load them from here, not from the CDNs. + const localLibraries = localSceneLibrariesEnabled() && !this.policy.isRemoteRequest(req); + const rewriteHtml = localLibraries ? rewriteSceneLibraryUrls : undefined; + if (localLibraries && url.startsWith('/__codexr/')) { + await this.serveLocalLibrary(res, url); + return; + } + // Root path - serve main page if (url === '/' || url === '/index.html') { - await this.staticAssets.serveMainPage(res); + await this.staticAssets.serveMainPage(res, rewriteHtml); return; } @@ -521,7 +531,19 @@ export class HttpServer { } // Static files - await this.staticAssets.serveStaticFile(req, res, url); + await this.staticAssets.serveStaticFile(req, res, url, rewriteHtml); + } + + /** A vendored scene library (localSceneLibraries.ts); anything else under the route is not found. */ + private async serveLocalLibrary(res: http.ServerResponse, url: string): Promise { + const file = localLibraryFileOf(new URL(url, 'http://codexr.local').pathname); + const body = file ? await readLocalLibrary(file) : null; + if (!file || !body) { + sendErrorResponse(res, 404, 'File not found'); + return; + } + res.writeHead(200, { 'Content-Type': contentTypeOf(file), 'Cache-Control': 'public, max-age=86400' }); + res.end(body); } /** diff --git a/apps/vscode-extension/test/servers/localSceneLibraries.test.cjs b/apps/vscode-extension/test/servers/localSceneLibraries.test.cjs new file mode 100644 index 000000000..bc5957924 --- /dev/null +++ b/apps/vscode-extension/test/servers/localSceneLibraries.test.cjs @@ -0,0 +1,84 @@ +'use strict'; + +/** + * The scene libraries a host may serve itself (core/server/http/ + * localSceneLibraries.ts, Code-XR IDE #483). Off by default: the extension's + * pages keep loading the CDNs byte for byte and the route does not exist. + * Once a host turns it on, pages sent to this machine point at the route, + * which serves the vendored copies; pages sent through the tunnel do not. + */ + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const net = require('node:net'); +const os = require('node:os'); +const path = require('node:path'); + +const { createFakeVscode, withFakeVscode } = require('../helpers/fakeVscode.cjs'); + +const projectRoot = path.resolve(__dirname, '..', '..'); +const VENDOR = path.join(projectRoot, 'test', 'vendor', 'scene-libraries'); +const ROUTE = '/__codexr/scene-libraries/'; +const PAGE = 'x'; + +function getFreePort() { + return new Promise((resolve, reject) => { + const probe = net.createServer(); + probe.once('error', reject); + probe.listen(0, '127.0.0.1', () => { + const { port } = probe.address(); + probe.close(() => resolve(port)); + }); + }); +} + +function get(port, pathname, headers = {}) { + return new Promise((resolve, reject) => { + http.get({ host: '127.0.0.1', port, path: pathname, headers }, (response) => { + const chunks = []; + response.on('data', (chunk) => chunks.push(chunk)); + response.on('end', () => resolve({ status: response.statusCode, type: response.headers['content-type'], body: Buffer.concat(chunks) })); + }).on('error', reject); + }); +} + +test('local scene libraries: off by default, then served and rewritten for this machine only', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-local-libraries-')); + fs.writeFileSync(path.join(root, 'scene.html'), PAGE); + const port = await getFreePort(); + try { + await withFakeVscode(createFakeVscode(), async ({ requireOut }) => { + const libraries = requireOut('core/server/http/localSceneLibraries.js'); + const { HttpServer } = requireOut('core/server/httpServer.js'); + const server = new HttpServer({ port, host: '127.0.0.1', staticRoot: root }); + await server.start(); + try { + assert.equal(libraries.localSceneLibrariesEnabled(), false); + assert.equal((await get(port, '/scene.html')).body.toString('utf8'), PAGE); + assert.equal((await get(port, `${ROUTE}aframe-1.7.1.min.js`)).status, 404); + + libraries.setLocalSceneLibraries(VENDOR); + const local = (await get(port, '/scene.html')).body.toString('utf8'); + assert.equal(local, `x`); + const aframe = await get(port, `${ROUTE}aframe-1.7.1.min.js`); + assert.equal(aframe.status, 200); + assert.equal(aframe.type, 'application/javascript; charset=utf-8'); + assert.ok(aframe.body.length > 100000); + assert.equal((await get(port, `${ROUTE}README.md`)).status, 404); + assert.equal((await get(port, `${ROUTE}..%2Fscene.html`)).status, 404); + + // Through the Cloudflare tunnel nothing changes: a guest without the + // room's cookie is not served at all, and the route is never there for it. + assert.equal((await get(port, '/scene.html', { 'cf-connecting-ip': '198.51.100.7' })).status, 404); + assert.equal((await get(port, `${ROUTE}aframe-1.7.1.min.js`, { 'cf-connecting-ip': '198.51.100.7' })).status, 404); + } finally { + libraries.setLocalSceneLibraries(null); + await server.stop(); + } + }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); From f02911569593f2b2b0145273dcd8b588787c65a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:30:33 +0000 Subject: [PATCH 19/29] IDE (Tauri): the scene view beside the code in a second webview, with its bridge (#483) Window::add_child (unstable multiwebview) behind the seam's WebContentsView: made on first load, placed in order (scene.setBounds on the reader thread), incognito, kept on its own server's origin. src/sceneBridge (an init script) gives the page CodeXRHostBridge.openInEditor over one command, codexr_scene, allowed to scene-* webviews on loopback pages only and checked again in the core and in ipc.ts. executeJavaScript on a scene answers through the bridge. Windows are looked up with get_window: with two webviews Tauri no longer sees a webview window. --- apps/ide/eslint.config.mjs | 8 + apps/ide/scripts/tauri.mjs | 7 +- apps/ide/scripts/viteConfigs.mjs | 21 +- apps/ide/src-tauri/Cargo.toml | 3 +- apps/ide/src-tauri/build.rs | 7 +- apps/ide/src-tauri/capabilities/scene.json | 11 + apps/ide/src-tauri/src/host.rs | 60 ++++- apps/ide/src-tauri/src/main.rs | 28 ++- apps/ide/src-tauri/src/scene.rs | 243 +++++++++++++++++++++ apps/ide/src-tauri/src/sidecar.rs | 12 +- apps/ide/src/sceneBridge/index.ts | 134 ++++++++++++ apps/ide/src/shared/sceneBridge.ts | 58 +++++ apps/ide/src/sidecar/index.ts | 3 +- apps/ide/src/sidecar/tauriHost.ts | 204 +++++++++++++++-- apps/ide/test/tauriSceneView.test.ts | 126 +++++++++++ apps/ide/tsconfig.web.json | 2 +- 16 files changed, 885 insertions(+), 42 deletions(-) create mode 100644 apps/ide/src-tauri/capabilities/scene.json create mode 100644 apps/ide/src-tauri/src/scene.rs create mode 100644 apps/ide/src/sceneBridge/index.ts create mode 100644 apps/ide/test/tauriSceneView.test.ts diff --git a/apps/ide/eslint.config.mjs b/apps/ide/eslint.config.mjs index a1fc9504f..470affa48 100644 --- a/apps/ide/eslint.config.mjs +++ b/apps/ide/eslint.config.mjs @@ -67,6 +67,14 @@ export default [ 'no-restricted-imports': ['error', { patterns: [{ group: ['electron', 'electron/*', 'node:*', '../main/*', '../sidecar/*', '@codexr/core/*', '@codexr/logging/*'], message: 'The bridge runs in the page: it may only use src/shared and src/preload/codexrApi.ts.' }] }], }, }, + { + // #483: the scene view's bridge in the Tauri build runs in an analysis page: src/shared only. + files: ['src/sceneBridge/**/*.ts'], + languageOptions: { globals: globals.browser }, + rules: { + 'no-restricted-imports': ['error', { patterns: [{ group: ['electron', 'electron/*', 'node:*', '../main/*', '../sidecar/*', '../preload/*', '../renderer/*', '@codexr/core/*', '@codexr/logging/*'], message: 'The scene bridge runs in an analysis page: it may only use src/shared.' }] }], + }, + }, { files: ['src/main/**/*.ts', 'src/sidecar/**/*.ts', 'test/**/*.ts'], languageOptions: { globals: globals.node }, diff --git a/apps/ide/scripts/tauri.mjs b/apps/ide/scripts/tauri.mjs index 681e8aa20..7b6da546f 100644 --- a/apps/ide/scripts/tauri.mjs +++ b/apps/ide/scripts/tauri.mjs @@ -1,7 +1,7 @@ // The Tauri build of the IDE (#480-#482, epic #477), beside the Electron one. // // node scripts/tauri.mjs build web build (scripts/build.mjs) + the Node sidecar + the -// bridge into out/, then `cargo build --release` in src-tauri +// bridges into out/, then `cargo build --release` in src-tauri // node scripts/tauri.mjs start [-- args] build, then run the Tauri app (args go to the app, e.g. --folder=) // node scripts/tauri.mjs run [-- args] run the last build // @@ -14,7 +14,7 @@ import path from 'node:path'; import zlib from 'node:zlib'; import { fileURLToPath } from 'node:url'; import { build } from 'vite'; -import { IDE_ROOT, bridgeConfig, nodeTargetConfig } from './viteConfigs.mjs'; +import { IDE_ROOT, bridgeConfig, nodeTargetConfig, sceneBridgeConfig } from './viteConfigs.mjs'; export const TAURI_DIR = path.join(IDE_ROOT, 'src-tauri'); export const TAURI_BINARY = path.join(TAURI_DIR, 'target', 'release', process.platform === 'win32' ? 'codexr-ide.exe' : 'codexr-ide'); @@ -101,13 +101,14 @@ export async function buildTauri() { } await build(nodeTargetConfig('sidecar')); await build(bridgeConfig()); + await build(sceneBridgeConfig()); writeIcons(); const locked = fs.existsSync(path.join(TAURI_DIR, 'Cargo.lock')) ? ['--locked'] : []; const cargo = spawnSync(cargoCommand(), ['build', '--release', ...locked], { cwd: TAURI_DIR, stdio: 'inherit' }); if (cargo.status !== 0) { throw new Error(`cargo build failed (${cargo.status})`); } - console.log(`[code-xr-ide] Tauri build: ${path.relative(process.cwd(), TAURI_BINARY)} (sidecar in out/sidecar, bridge in out/bridge)`); + console.log(`[code-xr-ide] Tauri build: ${path.relative(process.cwd(), TAURI_BINARY)} (sidecar in out/sidecar, bridges in out/bridge and out/sceneBridge)`); } export function runTauri(args) { diff --git a/apps/ide/scripts/viteConfigs.mjs b/apps/ide/scripts/viteConfigs.mjs index 285895f0d..98c38f7eb 100644 --- a/apps/ide/scripts/viteConfigs.mjs +++ b/apps/ide/scripts/viteConfigs.mjs @@ -9,10 +9,11 @@ // out/extensionHost/index.cjs extension host (#259: a Node child process on Electron's own Node) // out/localAgent/index.cjs the local-model ACP agent (#312: a child process per chat, ELECTRON_RUN_AS_NODE) // -// The Tauri build (#480-#482, scripts/tauri.mjs) adds two more: +// The Tauri build (#480-#483, scripts/tauri.mjs) adds three more: // out/sidecar/index.cjs the Node sidecar: the main process's services on plain Node, // with src/main/host/desktop.ts swapped for src/sidecar/tauriHost.ts // out/bridge/index.js window.codexr for the Tauri webview (an IIFE the Rust core injects) +// out/sceneBridge/index.js CodeXRHostBridge for the Tauri scene view (an IIFE the Rust core injects) import { builtinModules } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -116,6 +117,24 @@ export function bridgeConfig(opts = {}) { }; } +/** + * #483: the scene view's bridge in the Tauri build, one IIFE with no exports, + * injected by the Rust core into the scene webview before the analysis page's + * scripts. The three engines run it: ES2022. + * @param {{ dev?: boolean }} [opts] + */ +export function sceneBridgeConfig(opts = {}) { + const config = bridgeConfig(opts); + return { + ...config, + build: { + ...config.build, + outDir: path.join(OUT_DIR, 'sceneBridge'), + lib: { entry: path.join(IDE_ROOT, 'src', 'sceneBridge', 'index.ts'), formats: ['iife'], name: 'codexrSceneBridge', fileName: () => 'index.js' }, + }, + }; +} + /** @param {{ dev?: boolean }} [opts] */ export function rendererConfig(opts = {}) { return { diff --git a/apps/ide/src-tauri/Cargo.toml b/apps/ide/src-tauri/Cargo.toml index ae9b79917..d41a62108 100644 --- a/apps/ide/src-tauri/Cargo.toml +++ b/apps/ide/src-tauri/Cargo.toml @@ -18,7 +18,8 @@ path = "src/main.rs" tauri-build = { version = "2.8", features = [] } [dependencies] -tauri = { version = "2.13", features = ["image-png"] } +# "unstable" turns on multiwebview (Window::add_child): the scene view beside the code (#483). +tauri = { version = "2.13", features = ["image-png", "unstable"] } tauri-plugin-dialog = "2" tauri-plugin-clipboard-manager = "2" tauri-plugin-opener = "2" diff --git a/apps/ide/src-tauri/build.rs b/apps/ide/src-tauri/build.rs index 277dd2c62..0162b289d 100644 --- a/apps/ide/src-tauri/build.rs +++ b/apps/ide/src-tauri/build.rs @@ -1,9 +1,10 @@ fn main() { - // The two commands of the IDE are declared, so only a capability can allow - // them: capabilities/app.json grants them to the main window's local pages. + // The commands of the IDE are declared, so only a capability can allow them: + // capabilities/app.json grants codexr_ipc, codexr_events and codexr_log to the main window's local pages, + // capabilities/scene.json the scene bridge's to the scene views' loopback pages. tauri_build::try_build( tauri_build::Attributes::new() - .app_manifest(tauri_build::AppManifest::new().commands(&["codexr_ipc", "codexr_events", "codexr_log"])), + .app_manifest(tauri_build::AppManifest::new().commands(&["codexr_ipc", "codexr_events", "codexr_log", "codexr_scene"])), ) .expect("failed to run tauri-build"); } diff --git a/apps/ide/src-tauri/capabilities/scene.json b/apps/ide/src-tauri/capabilities/scene.json new file mode 100644 index 000000000..21786729d --- /dev/null +++ b/apps/ide/src-tauri/capabilities/scene.json @@ -0,0 +1,11 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "scene", + "description": "The scene views (webviews scene-*), on pages of the local Code-XR analysis server, may send the scene bridge's one message and nothing else.", + "webviews": ["scene-*"], + "local": false, + "remote": { + "urls": ["http://127.0.0.1:*/*", "http://localhost:*/*", "https://127.0.0.1:*/*", "https://localhost:*/*"] + }, + "permissions": ["allow-codexr-scene"] +} diff --git a/apps/ide/src-tauri/src/host.rs b/apps/ide/src-tauri/src/host.rs index 65f5a6fd3..719fbafed 100644 --- a/apps/ide/src-tauri/src/host.rs +++ b/apps/ide/src-tauri/src/host.rs @@ -13,18 +13,23 @@ use base64::Engine; use serde_json::{json, Value}; use tauri::image::Image; use tauri::webview::{NewWindowResponse, PageLoadEvent}; -use tauri::{AppHandle, LogicalSize, Manager, Theme, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder}; +use tauri::{AppHandle, LogicalSize, Manager, Theme, Url, WebviewUrl, Window, WebviewWindowBuilder}; use tauri_plugin_clipboard_manager::ClipboardExt; use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult}; use tauri_plugin_opener::OpenerExt; use crate::assets; +use crate::scene::{self, Scenes}; use crate::sidecar::Sidecar; -/// What the shell knows beside the sidecar: where the build is, the bridge script, the CSP. +/// What the shell knows beside the sidecar: where the build is, the bridge scripts, the CSP, the scenes. pub struct Shell { out: PathBuf, bridge: String, + /// The scene view's initialization script (src/sceneBridge), empty when it was not built. + scene_bridge: String, + /// The scene views open now (scene.rs). + pub scenes: Scenes, /// The IDE's policy, handed over by the sidecar as it starts; None until then. csp: Mutex>, csp_ready: Condvar, @@ -41,8 +46,21 @@ const SHOW_ANYWAY_AFTER: Duration = Duration::from_secs(10); const CSP_WAIT: Duration = Duration::from_secs(60); impl Shell { - pub fn new(out: PathBuf, bridge: String) -> Self { - Self { out, bridge, csp: Mutex::new(None), csp_ready: Condvar::new(), main_url: Mutex::new(None), closing: Mutex::new(HashSet::new()) } + pub fn new(out: PathBuf, bridge: String, scene_bridge: String) -> Self { + Self { + out, + bridge, + scene_bridge, + scenes: Scenes::default(), + csp: Mutex::new(None), + csp_ready: Condvar::new(), + main_url: Mutex::new(None), + closing: Mutex::new(HashSet::new()), + } + } + + pub fn scene_bridge(&self) -> String { + self.scene_bridge.clone() } pub fn renderer_dir(&self) -> PathBuf { @@ -85,9 +103,11 @@ fn required<'a>(params: &'a Value, key: &str) -> Result<&'a str, String> { str_param(params, key).ok_or_else(|| format!("missing {key}")) } -fn window_of(app: &AppHandle, params: &Value) -> Result { +/// A window by label. Not `get_webview_window`: a window with the scene view beside +/// its page holds two webviews, and Tauri no longer sees it as a webview window (#483). +fn window_of(app: &AppHandle, params: &Value) -> Result { let label = required(params, "window")?; - app.get_webview_window(label).ok_or_else(|| format!("no window {label}")) + app.get_window(label).ok_or_else(|| format!("no window {label}")) } /// The Code-XR logo, the file the extension uses as its icon (as Electron's window.ts does). @@ -105,6 +125,13 @@ pub fn show_fatal(app: &AppHandle, message: &str) { .blocking_show(); } +/// The host requests answered on the reader thread, in the order they came: the +/// scene view's place (a hide after a show must not overtake it). Each only posts +/// to the event loop, so it never blocks the reader. +pub fn runs_in_order(method: &str) -> bool { + method == "host.scene.setBounds" +} + pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) -> Result { let shell = app.state::>().inner().clone(); match op { @@ -119,7 +146,8 @@ pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) if !assets::is_app_url(&url) { return Err(format!("Refused to load {url}: not the app.")); } - window_of(app, params)?.navigate(url).map_err(|error| error.to_string())?; + let label = required(params, "window")?; + app.get_webview(label).ok_or_else(|| format!("no webview {label}"))?.navigate(url).map_err(|error| error.to_string())?; Ok(Value::Null) } "window.focus" => { @@ -128,6 +156,17 @@ pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) window.set_focus().map_err(|error| error.to_string())?; Ok(Value::Null) } + "webview.focus" => { + // Electron's webContents.focus(): the window, then the keyboard into this webview + // (out of the scene view beside it, when the scene had it). + let label = required(params, "window")?; + let webview = app.get_webview(label).ok_or_else(|| format!("no webview {label}"))?; + let window = webview.window(); + let _ = window.unminimize(); + window.set_focus().map_err(|error| error.to_string())?; + webview.set_focus().map_err(|error| error.to_string())?; + Ok(Value::Null) + } "window.show" => { window_of(app, params)?.show().map_err(|error| error.to_string())?; Ok(Value::Null) @@ -178,7 +217,7 @@ pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) _ => None, }; app.set_theme(theme); - let dark = app.get_webview_window("main").and_then(|window| window.theme().ok()).map(|theme| theme == Theme::Dark); + let dark = app.get_window("main").and_then(|window| window.theme().ok()).map(|theme| theme == Theme::Dark); Ok(dark.map(Value::Bool).unwrap_or(Value::Null)) } "secrets.masterKey" => master_key(), @@ -188,6 +227,7 @@ pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) app.exit(code); Ok(Value::Null) } + op if op.starts_with("scene.") => scene::handle(app, &shell, sidecar, op, params), "app.info" => Ok(json!({ "version": app.package_info().version.to_string(), "tauri": tauri::VERSION, @@ -308,8 +348,8 @@ fn build_window(app: &AppHandle, shell: &Arc, sidecar: &Arc, spe Ok(()) } -fn parent_dialog(app: &AppHandle, params: &Value) -> Option> { - str_param(params, "window").and_then(|label| app.get_webview_window(label)) +fn parent_dialog(app: &AppHandle, params: &Value) -> Option> { + str_param(params, "window").and_then(|label| app.get_window(label)) } fn with_filters(mut dialog: tauri_plugin_dialog::FileDialogBuilder, params: &Value) -> tauri_plugin_dialog::FileDialogBuilder { diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index 3e9294a06..e1e5f66b9 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -14,6 +14,7 @@ mod assets; mod host; mod locale; +mod scene; mod sidecar; use std::path::PathBuf; @@ -76,6 +77,21 @@ fn codexr_events(webview: tauri::Webview, sidecar: State<'_, Arc>, chan Ok(()) } +/// The scene view's one message to the IDE (src/sceneBridge): only from a scene +/// view (`scene-*`, capabilities/scene.json) showing its own local server's page. +/// The sidecar checks what it asks for (ipc.ts: a path inside the open folder). +#[tauri::command] +fn codexr_scene(webview: tauri::Webview, shell: State<'_, Arc>, sidecar: State<'_, Arc>, message: Value) -> Result<(), String> { + let url = webview.url().map_err(|error| error.to_string())?; + let allowed = shell.scenes.origin_of(webview.label()).is_some_and(|origin| scene::is_scene_page(&url, &origin)); + if !allowed { + eprintln!("[codexr-ide] Refused a scene message from {} ({url})", webview.label()); + return Err("Refused.".into()); + } + sidecar.notify("scene.message", json!({ "webview": webview.label(), "url": url.as_str(), "message": message })); + Ok(()) +} + /// Set by `software_rendering_defaults` (and so taken out of the sidecar's environment). const DMABUF_SWITCH: &str = "WEBKIT_DISABLE_DMABUF_RENDERER"; @@ -121,16 +137,22 @@ fn main() { std::process::exit(1); } }; + // The scene view's bridge (#483); without it the scene still opens, it only cannot open files in the editor. + let scene_bridge = std::fs::read_to_string(out.join("sceneBridge").join("index.js")).unwrap_or_else(|error| { + eprintln!("[codexr-ide] The scene bridge is missing ({}): {error}", out.join("sceneBridge").display()); + String::new() + }); // A benchmark run may start while an IDE is open, as on Electron. let single_instance = !args.iter().any(|arg| arg == "--codexr-bench"); let sidecar = Arc::new(Sidecar::new()); - let shell = Arc::new(host::Shell::new(out.clone(), bridge)); + let shell = Arc::new(host::Shell::new(out.clone(), bridge, scene_bridge)); let mut builder = tauri::Builder::default(); if single_instance { let sidecar = sidecar.clone(); builder = builder.plugin(tauri_plugin_single_instance::init(move |app, argv, _cwd| { - if let Some(window) = app.get_webview_window("main") { + // A window, not a webview window: with the scene view it holds two webviews (#483). + if let Some(window) = app.get_window("main") { let _ = window.unminimize(); let _ = window.set_focus(); } @@ -151,7 +173,7 @@ fn main() { std::thread::spawn(move || responder.respond(assets::serve(&shell, &request))); } }) - .invoke_handler(tauri::generate_handler![codexr_ipc, codexr_events, codexr_log]) + .invoke_handler(tauri::generate_handler![codexr_ipc, codexr_events, codexr_log, codexr_scene]) .on_window_event({ let sidecar = sidecar.clone(); let shell = shell.clone(); diff --git a/apps/ide/src-tauri/src/scene.rs b/apps/ide/src-tauri/src/scene.rs new file mode 100644 index 000000000..9fd4fc7a0 --- /dev/null +++ b/apps/ide/src-tauri/src/scene.rs @@ -0,0 +1,243 @@ +//! The analysis scene beside the code (#483, R5 of epic #477): the Tauri side +//! of Electron's `WebContentsView` scene view (src/main/analysis/sceneView.ts). +//! +//! The scene is a second webview of the window (`Window::add_child`, Tauri's +//! `unstable` multiwebview), laid over the slot the renderer reserves and +//! moved, resized, hidden and shown as the sidecar asks. Like Electron's, it +//! is a separate page, never an iframe of the app: it is served by the local +//! Code-XR analysis server (`http://127.0.0.1:/`), so it never reaches +//! `window.codexr`, and it runs in its own ephemeral (incognito) data store. +//! +//! Its only bridge to the IDE is the initialization script built from +//! src/sceneBridge (out/sceneBridge/index.js), which calls one command, +//! `codexr_scene`, allowed by capabilities/scene.json to webviews labelled +//! `scene-*` on loopback pages only. The core checks the label and the +//! page's origin again and forwards the message to the sidecar, where the +//! same checks as on Electron decide (ipc.ts: the path must be inside the +//! open folder). +//! +//! Navigation stays on the scene's own server and new windows are refused, +//! as on Electron (hardening.ts `allowSceneOrigin`). + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use serde_json::{json, Value}; +use tauri::webview::{NewWindowResponse, PageLoadEvent}; +use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, Url, WebviewBuilder, WebviewUrl}; + +use crate::host::Shell; +use crate::sidecar::Sidecar; + +/// Every scene webview's label starts so (capabilities/scene.json grants `scene-*`). +pub const SCENE_LABEL_PREFIX: &str = "scene-"; +/// The largest side the renderer may ask for, as sceneUrl.ts `sanitizeBounds` caps it. +const MAX_SIDE: f64 = 16384.0; + +/// The scenes the sidecar opened: webview label to the origin it may show. +#[derive(Default)] +pub struct Scenes { + origins: Mutex>, +} + +impl Scenes { + fn insert(&self, label: &str, origin: String) { + self.origins.lock().unwrap().insert(label.to_string(), origin); + } + + fn remove(&self, label: &str) { + self.origins.lock().unwrap().remove(label); + } + + /// The origin the scene webview `label` was opened on, if it is a scene. + pub fn origin_of(&self, label: &str) -> Option { + self.origins.lock().unwrap().get(label).cloned() + } +} + +/// The origin of a page served by Code-XR's own local server, or None for +/// anything else: http(s) on a loopback host with an explicit port and no +/// credentials. The same rule as `localSceneOrigin` in sceneUrl.ts. +pub fn local_scene_origin(url: &Url) -> Option { + if !matches!(url.scheme(), "http" | "https") || !url.username().is_empty() || url.password().is_some() { + return None; + } + let host = url.host_str()?; + if !matches!(host, "127.0.0.1" | "localhost" | "[::1]") { + return None; + } + let port = url.port()?; + Some(format!("{}://{}:{}", url.scheme(), host, port)) +} + +/// Whether `url` is a page of the scene opened on `origin`. +pub fn is_scene_page(url: &Url, origin: &str) -> bool { + local_scene_origin(url).as_deref() == Some(origin) +} + +/// Whole, positive logical pixels for a webview's place, or None (hide it). +pub fn scene_rect(bounds: &Value) -> Option<(f64, f64, f64, f64)> { + let number = |key: &str| bounds.get(key).and_then(Value::as_f64).filter(|n| n.is_finite()); + let (x, y, width, height) = (number("x")?, number("y")?, number("width")?, number("height")?); + let clamp = |n: f64| n.round().clamp(0.0, MAX_SIDE); + let (width, height) = (clamp(width), clamp(height)); + if width < 1.0 || height < 1.0 { + return None; + } + Some((clamp(x), clamp(y), width, height)) +} + +fn label_param(params: &Value) -> Result { + let label = params.get("webview").and_then(Value::as_str).ok_or("missing webview")?; + if !label.starts_with(SCENE_LABEL_PREFIX) { + return Err(format!("{label} is not a scene view.")); + } + Ok(label.to_string()) +} + +fn scene_webview(app: &AppHandle, params: &Value) -> Result { + let label = label_param(params)?; + app.get_webview(&label).ok_or_else(|| format!("no scene view {label}")) +} + +fn place(webview: &tauri::Webview, bounds: Option<&Value>) -> Result<(), String> { + match bounds.and_then(scene_rect) { + Some((x, y, width, height)) => { + webview.set_position(LogicalPosition::new(x, y)).map_err(|error| error.to_string())?; + webview.set_size(LogicalSize::new(width, height)).map_err(|error| error.to_string())?; + webview.show().map_err(|error| error.to_string()) + } + None => webview.hide().map_err(|error| error.to_string()), + } +} + +/// The `scene.*` host operations (src/sidecar/tauriHost.ts `WebContentsView`). +/// They run on a host thread of their own (sidecar.rs), never on the main +/// thread: `add_child` waits for it, and on Windows a webview created from +/// the main thread's own call deadlocks (R1 spike). +pub fn handle(app: &AppHandle, shell: &Arc, sidecar: &Arc, op: &str, params: &Value) -> Result { + match op { + "scene.create" => create(app, shell, sidecar, params), + "scene.navigate" => { + let webview = scene_webview(app, params)?; + let url: Url = params.get("url").and_then(Value::as_str).ok_or("missing url")?.parse().map_err(|error| format!("bad url: {error}"))?; + let origin = shell.scenes.origin_of(webview.label()).ok_or("not a scene")?; + if !is_scene_page(&url, &origin) { + return Err(format!("Refused to show {url}: not this scene's server.")); + } + webview.navigate(url).map_err(|error| error.to_string())?; + Ok(Value::Null) + } + "scene.setBounds" => { + place(&scene_webview(app, params)?, params.get("bounds"))?; + Ok(Value::Null) + } + "scene.eval" => { + let script = params.get("script").and_then(Value::as_str).ok_or("missing script")?; + scene_webview(app, params)?.eval(script).map_err(|error| error.to_string())?; + Ok(Value::Null) + } + "scene.close" => { + let label = label_param(params)?; + shell.scenes.remove(&label); + if let Some(webview) = app.get_webview(&label) { + webview.close().map_err(|error| error.to_string())?; + } + sidecar.notify("window.event", json!({ "window": label, "event": "destroyed" })); + Ok(Value::Null) + } + _ => Err(format!("Unknown host operation {op}.")), + } +} + +fn create(app: &AppHandle, shell: &Arc, sidecar: &Arc, params: &Value) -> Result { + let label = label_param(params)?; + let window_label = params.get("window").and_then(Value::as_str).ok_or("missing window")?; + let window = app.get_window(window_label).ok_or_else(|| format!("no window {window_label}"))?; + let url: Url = params.get("url").and_then(Value::as_str).ok_or("missing url")?.parse().map_err(|error| format!("bad url: {error}"))?; + let origin = local_scene_origin(&url).ok_or_else(|| format!("Refused to show {url}: not a local Code-XR server."))?; + if app.get_webview(&label).is_some() { + return Err(format!("{label} already exists.")); + } + shell.scenes.insert(&label, origin.clone()); + + let navigation_origin = origin.clone(); + let loads = sidecar.clone(); + let load_label = label.clone(); + let load_origin = origin.clone(); + let builder = WebviewBuilder::new(&label, WebviewUrl::External(url)) + // Electron's in-memory `codexr-scene` partition: nothing the scene stores outlives it. + .incognito(true) + // CodeXRHostBridge, before the page's own scripts (src/sceneBridge). + .initialization_script(shell.scene_bridge()) + .on_navigation(move |url| { + let allowed = is_scene_page(url, &navigation_origin) || url.scheme() == "about"; + if !allowed { + eprintln!("[codexr-ide] Scene view: blocked navigation to {url}"); + } + allowed + }) + .on_new_window(|url, _features| { + eprintln!("[codexr-ide] Scene view: blocked a new window for {url}"); + NewWindowResponse::Deny + }) + .on_page_load(move |_webview, payload| { + if payload.event() == PageLoadEvent::Finished && is_scene_page(payload.url(), &load_origin) { + loads.notify("window.event", json!({ "window": load_label, "event": "loaded", "url": payload.url().as_str() })); + } + }); + let rect = params.get("bounds").and_then(scene_rect); + let (x, y, width, height) = rect.unwrap_or((0.0, 0.0, 1.0, 1.0)); + let webview = window + .add_child(builder, LogicalPosition::new(x, y), LogicalSize::new(width, height)) + .map_err(|error| { + shell.scenes.remove(&label); + error.to_string() + })?; + let visible = params.get("visible").and_then(Value::as_bool).unwrap_or(true); + if rect.is_none() || !visible { + let _ = webview.hide(); + } + eprintln!("[codexr-ide] Scene view {label} opened on {origin}"); + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn url(text: &str) -> Url { + text.parse().unwrap() + } + + #[test] + fn only_a_local_server_with_a_port_is_a_scene() { + assert_eq!(local_scene_origin(&url("http://127.0.0.1:3000/index.html?x=1")).as_deref(), Some("http://127.0.0.1:3000")); + assert_eq!(local_scene_origin(&url("https://localhost:3443/")).as_deref(), Some("https://localhost:3443")); + assert_eq!(local_scene_origin(&url("http://[::1]:8080/")).as_deref(), Some("http://[::1]:8080")); + assert_eq!(local_scene_origin(&url("http://127.0.0.1/")), None); + assert_eq!(local_scene_origin(&url("http://example.org:3000/")), None); + assert_eq!(local_scene_origin(&url("http://localhost.evil.test:3000/")), None); + assert_eq!(local_scene_origin(&url("http://user:pw@127.0.0.1:3000/")), None); + assert_eq!(local_scene_origin(&url("file:///etc/passwd")), None); + assert_eq!(local_scene_origin(&url("codexr://app/index.html")), None); + } + + #[test] + fn a_scene_stays_on_its_own_server() { + let origin = "http://127.0.0.1:3000"; + assert!(is_scene_page(&url("http://127.0.0.1:3000/other.html"), origin)); + assert!(!is_scene_page(&url("http://127.0.0.1:3001/"), origin)); + assert!(!is_scene_page(&url("https://127.0.0.1:3000/"), origin)); + assert!(!is_scene_page(&url("http://localhost:3000/"), origin)); + } + + #[test] + fn bounds_are_whole_positive_pixels_or_hidden() { + assert_eq!(scene_rect(&json!({ "x": 10.4, "y": 20.6, "width": 300.2, "height": 200.5 })), Some((10.0, 21.0, 300.0, 201.0))); + assert_eq!(scene_rect(&json!({ "x": -5, "y": 0, "width": 99999, "height": 10 })), Some((0.0, 0.0, MAX_SIDE, 10.0))); + assert_eq!(scene_rect(&json!({ "x": 0, "y": 0, "width": 0, "height": 10 })), None); + assert_eq!(scene_rect(&json!({ "x": 0, "y": 0, "width": "wide", "height": 10 })), None); + assert_eq!(scene_rect(&Value::Null), None); + } +} diff --git a/apps/ide/src-tauri/src/sidecar.rs b/apps/ide/src-tauri/src/sidecar.rs index 5e172406f..a512d590e 100644 --- a/apps/ide/src-tauri/src/sidecar.rs +++ b/apps/ide/src-tauri/src/sidecar.rs @@ -274,8 +274,7 @@ impl Sidecar { let op = op.to_string(); let this = self.clone(); let app = app.clone(); - // Host operations may block (dialogs): each runs on its own thread. - std::thread::spawn(move || { + let run = move || { let result = host::handle(&app, &this, &op, ¶ms); match id { Some(id) => this.respond(id, result), @@ -285,7 +284,14 @@ impl Sidecar { } } } - }); + }; + if host::runs_in_order(method) { + // Never blocks (it only posts to the event loop), and must keep its order. + run(); + } else { + // Host operations may block (dialogs, creating a webview): each runs on its own thread. + std::thread::spawn(run); + } return; } let Some(id) = message.get("id").and_then(Value::as_u64) else { diff --git a/apps/ide/src/sceneBridge/index.ts b/apps/ide/src/sceneBridge/index.ts new file mode 100644 index 000000000..91fafb9b5 --- /dev/null +++ b/apps/ide/src/sceneBridge/index.ts @@ -0,0 +1,134 @@ +/** + * The scene view's bridge in the Tauri build (#483): what Electron's scene + * preload (src/scenePreload) gives an analysis page, plus what the IDE needs + * to reach into the scene now that a webview's `eval` returns nothing and + * cannot count as the person's gesture. + * + * The Rust core injects this script, built as one IIFE into out/sceneBridge/, + * as an initialization script of the scene webview only: it runs before the + * page's own scripts. It talks to the IDE through one command, `codexr_scene + * { message }`, which capabilities/scene.json allows to scene views on + * loopback pages only, and which the core and the sidecar check again. + * + * - `CodeXRHostBridge.openInEditor(target)`: as on Electron, a file of the + * analysed project in the editor (checked here, in the core, and in ipc.ts). + * - `__codexrSceneReply(id, ok, value)`: the answer of a script the IDE ran + * (`sceneEvalScript` in shared/sceneBridge.ts). + * - `__codexrScene.offerEnterXr()`: Enter XR in the header. An immersive + * session needs a gesture inside the scene's own page, which the IDE cannot + * simulate here, so the scene shows its own Enter XR button for the person + * to press, where the webview exposes WebXR and a headset is there. + */ +import { SCENE_BRIDGE_INTERNALS, SCENE_EVAL_REPLY, toSceneEditorTarget, type SceneBridgeMessage } from '../shared/sceneBridge.ts'; + +interface TauriInternals { + invoke(command: string, args?: Record): Promise; +} + +interface XrSystem { + isSessionSupported(mode: string): Promise; +} + +interface AScene extends HTMLElement { + enterVR?(): unknown; +} + +/** What `offerEnterXr` did: the button is shown, the webview or headset cannot, or the page is no 3D scene. */ +type XrOffer = 'offered' | 'unsupported' | 'no-scene'; + +const OVERLAY_ID = 'codexr-ide-enter-xr'; + +/** Something JSON can carry back (the answer of an IDE script). */ +function jsonSafe(value: unknown): unknown { + if (value === undefined) { + return null; + } + try { + return JSON.parse(JSON.stringify(value)) as unknown; + } catch { + return String(value); + } +} + +function overlayButton(scene: AScene): HTMLElement { + const box = document.createElement('div'); + box.id = OVERLAY_ID; + box.setAttribute('role', 'dialog'); + box.setAttribute('aria-label', 'Enter XR'); + box.style.cssText = [ + 'position:fixed', 'left:50%', 'bottom:24px', 'transform:translateX(-50%)', 'z-index:2147483647', + 'display:flex', 'gap:8px', 'align-items:center', 'padding:10px 12px', 'border-radius:8px', + 'background:rgba(20,24,31,0.92)', 'color:#fff', 'font:14px system-ui,sans-serif', 'box-shadow:0 4px 16px rgba(0,0,0,0.4)', + ].join(';'); + const text = document.createElement('span'); + text.textContent = 'Put on the headset, then press'; + const enter = document.createElement('button'); + enter.type = 'button'; + enter.textContent = 'Enter XR'; + enter.style.cssText = 'font:600 14px system-ui,sans-serif;padding:8px 14px;border:0;border-radius:6px;background:#2f6feb;color:#fff;cursor:pointer'; + const dismiss = document.createElement('button'); + dismiss.type = 'button'; + dismiss.textContent = 'Cancel'; + dismiss.style.cssText = 'font:14px system-ui,sans-serif;padding:8px 10px;border:1px solid #556;border-radius:6px;background:transparent;color:#fff;cursor:pointer'; + // A real click inside the scene: the user activation WebXR's requestSession needs. + enter.addEventListener('click', () => { + box.remove(); + Promise.resolve(scene.enterVR?.()).catch((error: unknown) => { + console.error('[codexr] Entering XR failed.', error); + }); + }); + dismiss.addEventListener('click', () => box.remove()); + box.append(text, enter, dismiss); + return box; +} + +async function offerEnterXr(): Promise { + const scene = document.querySelector('a-scene'); + if (!scene || typeof scene.enterVR !== 'function') { + return 'no-scene'; + } + const xr = (navigator as Navigator & { xr?: XrSystem }).xr; + if (!xr || !await xr.isSessionSupported('immersive-vr').catch(() => false)) { + return 'unsupported'; + } + document.getElementById(OVERLAY_ID)?.remove(); + document.body.append(overlayButton(scene)); + return 'offered'; +} + +function define(name: string, value: unknown): void { + Object.defineProperty(window, name, { value, writable: false, configurable: false, enumerable: false }); +} + +function install(): void { + const internals = (window as unknown as { __TAURI_INTERNALS__?: TauriInternals }).__TAURI_INTERNALS__; + if (!internals) { + console.error('[codexr] Tauri internals are missing: CodeXRHostBridge is not available.'); + return; + } + // Taken once, before any page script runs. + const tauriInvoke = internals.invoke.bind(internals); + const send = (message: SceneBridgeMessage): void => { + tauriInvoke('codexr_scene', { message }).catch((error: unknown) => console.error('[codexr] The IDE refused a scene message.', error)); + }; + + define('CodeXRHostBridge', Object.freeze({ + openInEditor(target: unknown): void { + const checked = toSceneEditorTarget(target); + if (checked) { + send({ type: 'open-in-editor', target: checked }); + } + }, + })); + define(SCENE_EVAL_REPLY, (id: unknown, ok: unknown, value: unknown): void => { + if (typeof id === 'string' && typeof ok === 'boolean') { + send({ type: 'eval-result', id, ok, value: jsonSafe(value) }); + } + }); + define(SCENE_BRIDGE_INTERNALS, Object.freeze({ offerEnterXr })); +} + +// Injected into every page of the scene view, in the top frame only. +if (window.top === window) { + install(); +} diff --git a/apps/ide/src/shared/sceneBridge.ts b/apps/ide/src/shared/sceneBridge.ts index bdb888737..1971b92d7 100644 --- a/apps/ide/src/shared/sceneBridge.ts +++ b/apps/ide/src/shared/sceneBridge.ts @@ -27,3 +27,61 @@ export function toSceneEditorTarget(value: unknown): SceneEditorTarget | null { const lineNumber = typeof line === 'number' && Number.isInteger(line) && line > 0 && line < 10_000_000 ? line : undefined; return lineNumber === undefined ? { path } : { path, line: lineNumber }; } + +/** + * #483: the Tauri build's scene bridge (src/sceneBridge, an initialization + * script of the scene webview) sends its messages through one command, + * `codexr_scene { message }`, which the Rust core accepts from a scene view + * on its own local server only and forwards to the sidecar: + * + * - `open-in-editor`: what Electron's scene preload sends on + * `SCENE_OPEN_IN_EDITOR_CHANNEL`; + * - `eval-result`: the answer of a script the IDE ran in the scene + * (`sceneEvalScript`), since a Tauri webview's `eval` returns nothing. + */ +export type SceneBridgeMessage = + | { readonly type: 'open-in-editor'; readonly target: SceneEditorTarget } + | { readonly type: 'eval-result'; readonly id: string; readonly ok: boolean; readonly value: unknown }; + +/** The function the scene bridge defines for `sceneEvalScript`'s answers. */ +export const SCENE_EVAL_REPLY = '__codexrSceneReply'; +/** The scene bridge's own calls the IDE runs in the scene (`offerEnterXr`). */ +export const SCENE_BRIDGE_INTERNALS = '__codexrScene'; + +const EVAL_ID = /^[0-9a-f-]{16,64}$/; + +/** The message if `value` is a well-formed one, else null. */ +export function toSceneBridgeMessage(value: unknown): SceneBridgeMessage | null { + if (typeof value !== 'object' || value === null) { + return null; + } + const record = value as Record; + if (record['type'] === 'open-in-editor') { + const target = toSceneEditorTarget(record['target']); + return target ? { type: 'open-in-editor', target } : null; + } + if (record['type'] === 'eval-result' && typeof record['id'] === 'string' && EVAL_ID.test(record['id']) && typeof record['ok'] === 'boolean') { + return { type: 'eval-result', id: record['id'], ok: record['ok'], value: record['value'] ?? null }; + } + return null; +} + +/** + * The script that runs the expression `code` in the scene and answers its + * value (awaited when it is a promise) through the scene bridge, under `id`. + * `code` is the IDE's own, never the page's. + */ +export function sceneEvalScript(id: string, code: string): string { + if (!EVAL_ID.test(id)) { + throw new Error(`Not an evaluation id: ${id}`); + } + return [ + '(() => {', + `const reply = window.${SCENE_EVAL_REPLY};`, + 'if (typeof reply !== "function") { return; }', + 'let result;', + `try { result = Promise.resolve((${code})); } catch (error) { result = Promise.reject(error); }`, + `result.then((value) => reply(${JSON.stringify(id)}, true, value), (error) => reply(${JSON.stringify(id)}, false, String(error && error.message || error)));`, + '})()', + ].join('\n'); +} diff --git a/apps/ide/src/sidecar/index.ts b/apps/ide/src/sidecar/index.ts index 74e096138..cf6f137fb 100644 --- a/apps/ide/src/sidecar/index.ts +++ b/apps/ide/src/sidecar/index.ts @@ -3,7 +3,7 @@ import { writeProtocolLine } from './stdio.ts'; import path from 'node:path'; import { LineSplitter, RpcPeer } from './rpc.ts'; import fs from 'node:fs'; -import { app, attachCore, handleInvoke, handleWindowEvent, initTauriHost, openIpc, TauriBrowserWindow } from './tauriHost.ts'; +import { app, attachCore, handleInvoke, handleSceneMessage, handleWindowEvent, initTauriHost, openIpc, TauriBrowserWindow } from './tauriHost.ts'; import { useRealNodeRuntime } from '../main/nodeRuntime.ts'; import { afterFirstWindow, startServices, stopServices, type BootOptions } from '../main/boot.ts'; import { APP_ORIGIN, buildContentSecurityPolicy, trustedOrigins } from '../main/security.ts'; @@ -56,6 +56,7 @@ function connect(): RpcPeer { const peer = new RpcPeer({ write: writeProtocolLine }, (message) => log.warn(`[sidecar] ${message}`)); peer.onRequest('ipc.invoke', handleInvoke); peer.onNotification('window.event', handleWindowEvent); + peer.onNotification('scene.message', handleSceneMessage); peer.onNotification('app.secondInstance', () => { TauriBrowserWindow.getAllWindows()[0]?.focus(); }); diff --git a/apps/ide/src/sidecar/tauriHost.ts b/apps/ide/src/sidecar/tauriHost.ts index d55bcacd4..024b2522e 100644 --- a/apps/ide/src/sidecar/tauriHost.ts +++ b/apps/ide/src/sidecar/tauriHost.ts @@ -10,10 +10,14 @@ * one; the window key of the main-process code (`webContents.id`) keeps * working. * + * The scene view (#483) is a second webview of the window in the core + * (`WebContentsView` below, src-tauri/src/scene.rs), with its own bridge + * (src/sceneBridge) in place of Electron's scene preload. + * * What Tauri cannot do yet degrades with one logged "not yet on Tauri (Rn)" - * line and never throws at import or start-up: the scene view (R5), - * extension webviews (R6), menus and the About box (R9), the screen picker - * and dialogs with more than three buttons (R9). + * line and never throws at import or start-up: extension webviews (R6), + * menus and the About box (R9), the screen picker, webview permission + * handlers and dialogs with more than three buttons (R9). * * Importing this module has no side effect: the entry (index.ts) connects * it to the core with `attachCore`. @@ -25,6 +29,7 @@ import os from 'node:os'; import path from 'node:path'; import type { RpcPeer } from './rpc.ts'; import { decodeValue, encodeValue, type Base64 } from '../shared/jsonCodec.ts'; +import { SCENE_OPEN_IN_EDITOR_CHANNEL, sceneEvalScript, toSceneBridgeMessage } from '../shared/sceneBridge.ts'; export const DESKTOP_SHELL: 'electron' | 'tauri' = 'tauri'; @@ -199,7 +204,7 @@ export class TauriWebContents extends EventEmitter { readonly label: string; private url = ''; private destroyed = false; - private loadWaiters: Array<() => void> = []; + protected loadWaiters: Array<() => void> = []; /** Electron's main frame; the scene bridge compares it with the sender frame. */ readonly mainFrame: { url: string }; @@ -232,8 +237,9 @@ export class TauriWebContents extends EventEmitter { return this.loadWaiters.length > 0; } + /** The window, then the keyboard into this webview (out of a scene view beside it). */ focus(): void { - hostNotify('window.focus', { window: this.label }); + hostNotify('webview.focus', { window: this.label }); } /** Navigates the webview and resolves when the page finished loading. */ @@ -324,10 +330,11 @@ export class TauriBrowserWindow extends EventEmitter { readonly label: string; readonly webContents: TauriWebContents; private destroyed = false; - /** Electron's contentView: child views are the scene view, not yet on Tauri (R5). */ + /** Electron's contentView: its child views are scene views (#483), webviews of this window in the core. */ readonly contentView = { - addChildView: (): void => notYetOnTauri('Child views of a window (the scene view)', 'R5'), - removeChildView: (): void => {}, + addChildView: (view: WebContentsView): void => view.attachTo(this.label), + // The view's webview goes with webContents.close() (sceneView.ts closes it right after). + removeChildView: (_view: WebContentsView): void => {}, }; constructor(label: string) { @@ -514,6 +521,9 @@ export function openIpc(): void { openIpcGate(); } +type OneWayListener = (event: { readonly sender: TauriWebContents; readonly senderFrame: { readonly url: string } }, ...args: unknown[]) => void; +const oneWayListeners = new Map(); + export const ipcMain = { handle(channel: string, handler: InvokeHandler): void { if (invokeHandlers.has(channel)) { @@ -524,9 +534,9 @@ export const ipcMain = { removeHandler(channel: string): void { invokeHandlers.delete(channel); }, - on(channel: string, _listener: (...args: unknown[]) => void): void { - // Only the scene view's preload sends one-way messages (#16): it comes with the scene view (R5). - notYetOnTauri(`One-way IPC ${channel} (the scene bridge)`, 'R5'); + /** One-way messages: only the scene view's bridge sends one (#16, #483: `scene.message`). */ + on(channel: string, listener: OneWayListener): void { + oneWayListeners.set(channel, [...(oneWayListeners.get(channel) ?? []), listener]); }, }; @@ -783,11 +793,12 @@ export async function initTauriHost(): Promise { class StubSession { readonly protocol = { - handle: (): void => notYetOnTauri('A webview session protocol handler (scene libraries)', 'R5'), + // The scene's libraries come from its own local server on Tauri (#483, core localSceneLibraries.ts). + handle: (): void => {}, unhandle: (): void => {}, }; readonly webRequest = { - onBeforeRequest: (): void => notYetOnTauri('Request filtering of a webview session', 'R5'), + onBeforeRequest: (): void => notYetOnTauri('Request filtering of a webview session (the scene view\'s other requests)', 'R9'), onHeadersReceived: (): void => {}, }; setPermissionRequestHandler(): void { @@ -809,10 +820,171 @@ export const protocol = { handle: (scheme: string): void => notYetOnTauri(`The ${scheme}: protocol (extension webviews)`, 'R6'), }; +// -- The scene view (#483) --------------------------------------------------------------------- + +/** How long a script run in the scene may take to answer. */ +const SCENE_EVAL_TIMEOUT_MS = 10_000; + +interface PendingEval { + readonly label: string; + readonly resolve: (value: unknown) => void; + readonly reject: (error: Error) => void; + readonly timer: NodeJS.Timeout; +} + +const pendingEvals = new Map(); +let nextSceneId = 1; + +interface SceneRect { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +/** A scene view's webview seen as Electron's WebContents: created in the core on its first load. */ +class TauriSceneContents extends TauriWebContents { + private created = false; + private readonly view: WebContentsView; + + constructor(label: string, view: WebContentsView) { + super(label); + this.view = view; + contentsByLabel.set(label, this); + } + + /** Whether the core has the webview yet. */ + isCreated(): boolean { + return this.created; + } + + override loadURL(url: string): Promise { + const window = this.view.parentLabel(); + if (!window) { + return Promise.reject(new Error('The scene view is in no window.')); + } + const loaded = new Promise((resolve) => this.loadWaiters.push(resolve)); + if (this.created) { + return hostRequest('scene.navigate', { webview: this.label, url }).then(() => loaded); + } + return hostRequest('scene.create', { window, webview: this.label, url, ...this.view.placement() }).then(() => { + this.created = true; + // Bounds the renderer sent while the webview was being made. + this.view.place(); + return loaded; + }); + } + + /** + * Runs the expression `code` in the scene and answers its value. A Tauri + * webview's eval answers nothing and cannot count as the person's gesture + * (`userGesture`, ignored): the scene bridge answers instead (sceneBridge.ts). + */ + override executeJavaScript(code: string, _userGesture?: boolean): Promise { + const id = crypto.randomUUID(); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pendingEvals.delete(id); + reject(new Error('The scene did not answer.')); + }, SCENE_EVAL_TIMEOUT_MS); + timer.unref(); + pendingEvals.set(id, { label: this.label, resolve, reject, timer }); + hostRequest('scene.eval', { webview: this.label, script: sceneEvalScript(id, code) }).catch((error: unknown) => { + clearTimeout(timer); + pendingEvals.delete(id); + reject(error instanceof Error ? error : new Error(String(error))); + }); + }); + } + + override close(): void { + if (this.created) { + hostNotify('scene.close', { webview: this.label }); + } else { + this.markDestroyed(); + } + } +} + +/** + * Electron's WebContentsView, as the scene view uses it (src/main/analysis/ + * sceneView.ts): a second webview of its window in the core (src-tauri/src/ + * scene.rs), placed over the renderer's slot, hidden and shown. It is made + * on its first `loadURL`, with the bounds and visibility set before. + */ export class WebContentsView { - constructor() { - notYetOnTauri('The scene view beside the code', 'R5'); - throw new Error('The scene view is not yet on Tauri (R5): use "Open in browser" for this scene.'); + readonly webContents: TauriSceneContents; + private parent: string | null = null; + private bounds: SceneRect | null = null; + private visible = true; + + constructor(_options?: unknown) { + this.webContents = new TauriSceneContents(`scene-${nextSceneId++}`, this); + } + + setBounds(bounds: SceneRect): void { + this.bounds = { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }; + this.place(); + } + + setVisible(visible: boolean): void { + this.visible = visible; + this.place(); + } + + /** @internal Electron's addChildView. */ + attachTo(window: string): void { + this.parent = window; + } + + /** @internal */ + parentLabel(): string | null { + return this.parent; + } + + /** @internal Where the webview goes: its bounds, or null while hidden. */ + placement(): { bounds: SceneRect | null; visible: boolean } { + return { bounds: this.visible ? this.bounds : null, visible: this.visible && this.bounds !== null }; + } + + /** @internal Tells the core where the webview is (in order: the core applies these as they come). */ + place(): void { + if (this.webContents.isCreated() && !this.webContents.isDestroyed()) { + hostNotify('scene.setBounds', { webview: this.webContents.label, bounds: this.placement().bounds }); + } + } +} + +/** + * A message of a scene view's bridge (`scene.message`, src-tauri `codexr_scene`): + * the core checked it comes from a scene view on its own server; what it asks + * for is checked again here and by the listeners, as on Electron. + */ +export function handleSceneMessage(params: unknown): void { + const { webview: label, url, message } = (params ?? {}) as { webview?: unknown; url?: unknown; message?: unknown }; + const contents = typeof label === 'string' ? contentsByLabel.get(label) : undefined; + const checked = toSceneBridgeMessage(message); + if (!(contents instanceof TauriSceneContents) || !checked || typeof url !== 'string') { + return; + } + if (checked.type === 'eval-result') { + const pending = pendingEvals.get(checked.id); + if (!pending || pending.label !== contents.label) { + return; + } + pendingEvals.delete(checked.id); + clearTimeout(pending.timer); + if (checked.ok) { + pending.resolve(checked.value); + } else { + pending.reject(new Error(String(checked.value))); + } + return; + } + // Electron's sender frame is the scene's main frame: the bridge runs in the top frame only. + const event = { sender: contents, senderFrame: contents.mainFrame }; + for (const listener of oneWayListeners.get(SCENE_OPEN_IN_EDITOR_CHANNEL) ?? []) { + listener(event, checked.target); } } diff --git a/apps/ide/test/tauriSceneView.test.ts b/apps/ide/test/tauriSceneView.test.ts new file mode 100644 index 000000000..06535d333 --- /dev/null +++ b/apps/ide/test/tauriSceneView.test.ts @@ -0,0 +1,126 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import vm from 'node:vm'; +import { RpcPeer } from '../src/sidecar/rpc.ts'; +import * as tauriHost from '../src/sidecar/tauriHost.ts'; +import { SCENE_EVAL_REPLY, SCENE_OPEN_IN_EDITOR_CHANNEL, sceneEvalScript, toSceneBridgeMessage } from '../src/shared/sceneBridge.ts'; + +interface Sent { + readonly id?: number; + readonly method: string; + readonly params: Record; +} + +/** The sidecar's host, connected to a fake core that answers every request with null. */ +function fakeCore(): { sent: Sent[]; peer: RpcPeer } { + const sent: Sent[] = []; + const peer = new RpcPeer({ + write: (line) => { + const message = JSON.parse(line) as Sent; + sent.push(message); + if (message.id !== undefined) { + queueMicrotask(() => peer.receive(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }))); + } + }, + }); + tauriHost.attachCore(peer); + return { sent, peer }; +} + +const tick = (): Promise => new Promise((resolve) => setImmediate(resolve)); + +describe('Tauri scene view (#483)', () => { + it('parses only well-formed bridge messages', () => { + assert.deepEqual(toSceneBridgeMessage({ type: 'open-in-editor', target: { path: 'src/a.ts', line: 3 } }), { type: 'open-in-editor', target: { path: 'src/a.ts', line: 3 } }); + const id = '0123456789abcdef0123'; + assert.deepEqual(toSceneBridgeMessage({ type: 'eval-result', id, ok: true, value: false }), { type: 'eval-result', id, ok: true, value: false }); + assert.deepEqual(toSceneBridgeMessage({ type: 'eval-result', id, ok: false }), { type: 'eval-result', id, ok: false, value: null }); + for (const value of [null, 'x', {}, { type: 'open-in-editor', target: { path: '' } }, { type: 'eval-result', id: 'short', ok: true }, { type: 'eval-result', id, ok: 'yes' }, { type: 'run', code: '1' }]) { + assert.equal(toSceneBridgeMessage(value), null, JSON.stringify(value)); + } + }); + + it('runs an expression in the scene and answers its awaited value through the bridge', async () => { + const replies: unknown[][] = []; + const page = { [SCENE_EVAL_REPLY]: (...args: unknown[]) => replies.push(args), navigator: {} }; + const context = vm.createContext({ window: page, navigator: page.navigator, Promise }); + const id = '11111111-2222-3333-4444-555555555555'; + vm.runInContext(sceneEvalScript(id, 'navigator.xr ? navigator.xr.isSessionSupported("immersive-vr") : false'), context); + vm.runInContext(sceneEvalScript(id.replace('1', '9'), 'Promise.resolve(41).then((n) => n + 1)'), context); + vm.runInContext(sceneEvalScript(id.replace('1', '8'), 'missing.thing'), context); + await tick(); + assert.deepEqual(replies.sort((a, b) => String(a[0]).localeCompare(String(b[0]))), [ + [id, true, false], + [id.replace('1', '8'), false, 'missing is not defined'], + [id.replace('1', '9'), true, 42], + ]); + assert.throws(() => sceneEvalScript('"); evil("', '1'), /Not an evaluation id/); + }); + + it('drives a second webview of the window: made on first load, placed in order, closed', async () => { + const { sent } = fakeCore(); + const win = tauriHost.TauriBrowserWindow.adopt('main'); + const view = new tauriHost.WebContentsView({}); + const label = view.webContents.label; + assert.match(label, /^scene-\d+$/); + view.setVisible(false); + win.contentView.addChildView(view); + view.setBounds({ x: 10, y: 20, width: 300, height: 200 }); + view.setVisible(true); + assert.equal(sent.length, 0, 'nothing reaches the core before the webview exists'); + + const loading = view.webContents.loadURL('http://127.0.0.1:3000/'); + await tick(); + const create = sent.find((message) => message.method === 'host.scene.create'); + assert.deepEqual(create?.params, { window: 'main', webview: label, url: 'http://127.0.0.1:3000/', bounds: { x: 10, y: 20, width: 300, height: 200 }, visible: true }); + tauriHost.handleWindowEvent({ window: label, event: 'loaded', url: 'http://127.0.0.1:3000/' }); + await loading; + assert.equal(view.webContents.getURL(), 'http://127.0.0.1:3000/'); + + sent.length = 0; + view.setVisible(false); + view.setBounds({ x: 0, y: 0, width: 50, height: 60 }); + view.setVisible(true); + assert.deepEqual(sent.map((message) => [message.method, message.params['bounds']]), [ + ['host.scene.setBounds', null], + ['host.scene.setBounds', null], + ['host.scene.setBounds', { x: 0, y: 0, width: 50, height: 60 }], + ]); + + view.webContents.focus(); + assert.deepEqual(sent.at(-1), { jsonrpc: '2.0', method: 'host.webview.focus', params: { window: label } }); + view.webContents.close(); + assert.deepEqual(sent.at(-1), { jsonrpc: '2.0', method: 'host.scene.close', params: { webview: label } }); + }); + + it('hands the bridge\'s open-in-editor to ipcMain.on from the scene\'s main frame, and answers evaluations', async () => { + const { sent } = fakeCore(); + const win = tauriHost.TauriBrowserWindow.adopt('main'); + const view = new tauriHost.WebContentsView({}); + win.contentView.addChildView(view); + const loading = view.webContents.loadURL('http://127.0.0.1:3000/'); + await tick(); + tauriHost.handleWindowEvent({ window: view.webContents.label, event: 'loaded', url: 'http://127.0.0.1:3000/' }); + await loading; + + const heard: Array<{ sender: unknown; sameFrame: boolean; target: unknown }> = []; + tauriHost.ipcMain.on(SCENE_OPEN_IN_EDITOR_CHANNEL, (event, target) => { + heard.push({ sender: event.sender, sameFrame: event.senderFrame === event.sender.mainFrame, target }); + }); + const url = 'http://127.0.0.1:3000/'; + tauriHost.handleSceneMessage({ webview: view.webContents.label, url, message: { type: 'open-in-editor', target: { path: 'src/a.ts', line: 2 } } }); + tauriHost.handleSceneMessage({ webview: view.webContents.label, url, message: { type: 'open-in-editor', target: { path: '' } } }); + tauriHost.handleSceneMessage({ webview: 'main', url, message: { type: 'open-in-editor', target: { path: 'src/b.ts' } } }); + assert.deepEqual(heard, [{ sender: view.webContents, sameFrame: true, target: { path: 'src/a.ts', line: 2 } }]); + + const answer = view.webContents.executeJavaScript('1 + 1', true); + await tick(); + const evaluation = sent.find((message) => message.method === 'host.scene.eval'); + const id = /reply\("([0-9a-f-]+)"/.exec(String(evaluation?.params['script']))?.[1] ?? ''; + assert.ok(id); + // Another view cannot answer for this one. + tauriHost.handleSceneMessage({ webview: 'scene-999', url, message: { type: 'eval-result', id, ok: true, value: 'forged' } }); + tauriHost.handleSceneMessage({ webview: view.webContents.label, url, message: { type: 'eval-result', id, ok: true, value: 2 } }); + assert.equal(await answer, 2); + }); +}); diff --git a/apps/ide/tsconfig.web.json b/apps/ide/tsconfig.web.json index b1af9497d..f465a1270 100644 --- a/apps/ide/tsconfig.web.json +++ b/apps/ide/tsconfig.web.json @@ -11,5 +11,5 @@ "@codexr/core/analysis/languages/*": ["./.core-types/core/analysis/languages/*"] } }, - "include": ["src/renderer/**/*.ts", "src/shared/**/*.ts", "src/bridge/**/*.ts"] + "include": ["src/renderer/**/*.ts", "src/shared/**/*.ts", "src/bridge/**/*.ts", "src/sceneBridge/**/*.ts"] } From 8b4cfaf3316ef47a8d69107eb1c66c39d35353a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:30:33 +0000 Subject: [PATCH 20/29] IDE: honest Enter XR on Tauri; no dead button (#483) Where the webview has WebXR (WebView2), Enter XR asks the scene to show its own Enter XR button: the click inside the scene is the gesture WebXR needs. Where it has none (WKWebView, WebKitGTK), SceneInfo.xrUnavailable hides the button and the note points at Open in browser and On a headset. Electron is unchanged. Also fixes the LivePanel check, which never matched the -livepanel kinds. --- apps/ide/src/main/analysis/analysisService.ts | 11 ++++---- apps/ide/src/main/analysis/sceneView.ts | 26 +++++++++++++++++-- apps/ide/src/main/analysis/sceneXrPolicy.ts | 18 ++++++++++++- apps/ide/src/renderer/codexr/sceneSection.ts | 10 +++---- apps/ide/src/renderer/sceneHeaderModel.ts | 23 ++++++++++++++-- apps/ide/src/renderer/sceneXrControls.ts | 9 ++++--- apps/ide/src/shared/api.ts | 12 +++++++-- apps/ide/test/sceneXr.test.ts | 26 ++++++++++++++++++- 8 files changed, 113 insertions(+), 22 deletions(-) diff --git a/apps/ide/src/main/analysis/analysisService.ts b/apps/ide/src/main/analysis/analysisService.ts index 9927159e1..c27bee0d4 100644 --- a/apps/ide/src/main/analysis/analysisService.ts +++ b/apps/ide/src/main/analysis/analysisService.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, clipboard, webContents, type WebContents } from '../host/desktop.ts'; +import { BrowserWindow, clipboard, DESKTOP_SHELL, webContents, type WebContents } from '../host/desktop.ts'; import { createHash } from 'node:crypto'; import path from 'node:path'; import { AnalysisOrchestrator } from '@codexr/core/analysis/analysisOrchestrator'; @@ -30,7 +30,7 @@ import { readMetrics, type FileMetrics } from '../agents/tools/analysisQueries.t import { computeMetricDelta, type MetricDeltaReport } from './metricDelta.ts'; import { followRefreshes, waitUntilSettled, type RefreshPort, type SceneUpdatedEvent, type SettleResult } from './sceneRefresh.ts'; import { closeScene, enterSceneXr, sceneSupportsImmersiveXr, showScene } from './sceneView.ts'; -import { unsupportedXrMessage } from './sceneXrPolicy.ts'; +import { ENTER_XR_IN_SCENE_MESSAGE, inIdeXrUnavailable, unsupportedXrMessage } from './sceneXrPolicy.ts'; import { sceneTargetToWorkspacePath } from './sceneEditorTarget.ts'; import type { SceneEditorTarget } from '../../shared/sceneBridge.ts'; import { localSceneOrigin, sceneTitle, targetName } from './sceneUrl.ts'; @@ -589,11 +589,11 @@ export class AnalysisService { return { ok: false, reason: 'failed', message: 'A LivePanel is a 2D page: analyse in XR to enter a scene.' }; } if (!await sceneSupportsImmersiveXr(win)) { - return { ok: false, reason: 'unsupported', message: unsupportedXrMessage(process.platform) }; + return { ok: false, reason: 'unsupported', message: unsupportedXrMessage(process.platform, DESKTOP_SHELL) }; } try { - await enterSceneXr(win); - return { ok: true }; + const entered = await enterSceneXr(win); + return entered === 'in-scene' ? { ok: true, message: ENTER_XR_IN_SCENE_MESSAGE } : { ok: true }; } catch (error) { log.error('Entering XR failed', error); return { ok: false, reason: 'failed', message: error instanceof Error ? error.message : String(error) }; @@ -759,6 +759,7 @@ export class AnalysisService { targetPath: this.ownerTarget, files, share, + xrUnavailable: inIdeXrUnavailable(DESKTOP_SHELL, process.platform) ?? undefined, }; win.webContents.send(IPC_EVENTS.analysisSceneOpened, scene); // #173: the Problems panel measures the functions of the folder the scene shows. diff --git a/apps/ide/src/main/analysis/sceneView.ts b/apps/ide/src/main/analysis/sceneView.ts index 519d2d8ff..13a0b09ff 100644 --- a/apps/ide/src/main/analysis/sceneView.ts +++ b/apps/ide/src/main/analysis/sceneView.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, WebContentsView, desktopCapturer, dialog, net, session, type Session, type WebContents } from '../host/desktop.ts'; +import { BrowserWindow, DESKTOP_SHELL, WebContentsView, desktopCapturer, dialog, net, session, type Session, type WebContents } from '../host/desktop.ts'; import fs from 'node:fs/promises'; import path from 'node:path'; import type { SceneBounds } from '../../shared/api.ts'; @@ -8,6 +8,7 @@ import { localSceneOrigin } from './sceneUrl.ts'; import { allowXrPermission, XR_ARM_MS, type XrArm } from './sceneXrPolicy.ts'; import { allowScreenShareRequest, shareAudioFor, shareChoices } from './sceneScreenShare.ts'; import { contentTypeOf, isLoopbackUrl, vendoredLibraryFor } from './sceneLibraries.ts'; +import { SCENE_BRIDGE_INTERNALS } from '../../shared/sceneBridge.ts'; /** * The analysis scene beside the code (#16): a `WebContentsView` laid over the @@ -20,6 +21,12 @@ import { contentTypeOf, isLoopbackUrl, vendoredLibraryFor } from './sceneLibrari * Its only preload (src/scenePreload) exposes one call, `CodeXRHostBridge. * openInEditor`, which the main process checks against the open folder. It * may navigate only within the local server it was opened on. + * + * #483: on Tauri the same code drives a second webview of the window in the + * Rust core (src/sidecar/tauriHost.ts `WebContentsView`, src-tauri/src/ + * scene.rs); its bridge is src/sceneBridge, its libraries come from the local + * server (localSceneLibraries in the core), and the session's handlers below + * are not there yet (R9: permissions, request filtering, the screen picker). */ const SCENE_PARTITION = 'codexr-scene'; @@ -213,8 +220,12 @@ export async function sceneSupportsImmersiveXr(win: BrowserWindow): Promise { +export async function enterSceneXr(win: BrowserWindow): Promise<'entered' | 'in-scene'> { const view = views.get(win.id); const origin = view ? localSceneOrigin(view.webContents.getURL()) : null; if (!view || !origin) { @@ -222,6 +233,16 @@ export async function enterSceneXr(win: BrowserWindow): Promise { } xrArms.set(win.id, { origin, until: Date.now() + XR_ARM_MS }); setTimeout(() => xrArms.delete(win.id), XR_ARM_MS).unref(); + if (DESKTOP_SHELL === 'tauri') { + const offer: unknown = await view.webContents.executeJavaScript(`window.${SCENE_BRIDGE_INTERNALS}.offerEnterXr()`); + if (offer === 'no-scene') { + throw new Error('This scene has no XR mode (a LivePanel is a 2D page).'); + } + if (offer !== 'offered') { + throw new Error('No XR headset is available to the scene any more.'); + } + return 'in-scene'; + } const entered: unknown = await view.webContents.executeJavaScript( '(() => { const scene = document.querySelector("a-scene"); if (!scene || !scene.enterVR) { return false; } return Promise.resolve(scene.enterVR()).then(() => true); })()', true, @@ -229,6 +250,7 @@ export async function enterSceneXr(win: BrowserWindow): Promise { if (entered !== true) { throw new Error('This scene has no XR mode (a LivePanel is a 2D page).'); } + return 'entered'; } /** The URL the window's scene shows, for the smoke run and tests. */ diff --git a/apps/ide/src/main/analysis/sceneXrPolicy.ts b/apps/ide/src/main/analysis/sceneXrPolicy.ts index 2ffdc3530..833b34ffa 100644 --- a/apps/ide/src/main/analysis/sceneXrPolicy.ts +++ b/apps/ide/src/main/analysis/sceneXrPolicy.ts @@ -34,7 +34,11 @@ export function allowXrPermission(arm: XrArm | null, permission: string, request } /** Why the IDE cannot start an immersive session, for the header and the docs' support matrix. */ -export function unsupportedXrMessage(platform: NodeJS.Platform): string { +export function unsupportedXrMessage(platform: NodeJS.Platform, shell: 'electron' | 'tauri' = 'electron'): string { + if (shell === 'tauri' && platform !== 'win32') { + // #483: WKWebView and WebKitGTK have no WebXR at all (R1 spike: navigator.xr absent). + return 'This system webview has no WebXR, so the IDE cannot enter the scene in XR itself: open it in a WebXR browser with Open in browser, or on a standalone headset with On a headset.'; + } const common = 'No XR headset is available to the IDE.'; switch (platform) { case 'win32': @@ -45,3 +49,15 @@ export function unsupportedXrMessage(platform: NodeJS.Platform): string { return `${common} Chromium has no headset support on Linux: open the scene on a standalone headset instead.`; } } + +/** + * #483: why this IDE can never enter a scene in XR, or null where it can try + * (Electron everywhere, as before; Tauri on Windows, whose WebView2 exposes + * WebXR). The header then shows no dead Enter XR button. + */ +export function inIdeXrUnavailable(shell: 'electron' | 'tauri', platform: NodeJS.Platform): string | null { + return shell === 'tauri' && platform !== 'win32' ? unsupportedXrMessage(platform, shell) : null; +} + +/** #483: what the header says once a Tauri scene shows its own Enter XR button. */ +export const ENTER_XR_IN_SCENE_MESSAGE = 'Put on the headset and press Enter XR in the scene: the immersive session starts from a click inside it.'; diff --git a/apps/ide/src/renderer/codexr/sceneSection.ts b/apps/ide/src/renderer/codexr/sceneSection.ts index dfd7d6d05..a712de1e6 100644 --- a/apps/ide/src/renderer/codexr/sceneSection.ts +++ b/apps/ide/src/renderer/codexr/sceneSection.ts @@ -2,7 +2,7 @@ import { t } from '../../shared/i18n/i18n.ts'; import type { CodeXRApi, SceneInfo } from '../../shared/api.ts'; import type { CodeXrViewApi, SceneModes } from '../../shared/codexr.ts'; import { el } from '../dom.ts'; -import { analysedFilesLabel, analysisKindLabel, displayAddress, INITIAL_SHARE_VIEW, ipcErrorMessage, reduceShare, shareControls, type ShareAction, type ShareView } from '../sceneHeaderModel.ts'; +import { analysedFilesLabel, analysisKindLabel, displayAddress, enterXrNote, enterXrState, INITIAL_SHARE_VIEW, ipcErrorMessage, reduceShare, shareControls, type ShareAction, type ShareView } from '../sceneHeaderModel.ts'; import { qrSvg } from '../sceneXrControls.ts'; import type { CodeXrSection } from './codexrView.ts'; import { modeLabel, modePicker, withActive } from './sceneModel.ts'; @@ -174,8 +174,8 @@ export function createSceneSection( files.hidden = files.textContent === ''; local.textContent = displayAddress(scene.url); local.title = scene.url; - // A LivePanel is a 2D page: nothing to enter. - enter.hidden = scene.kind.startsWith('livepanel'); + // A LivePanel is a 2D page: nothing to enter (#483: nor where the IDE has no WebXR). + enter.hidden = !enterXrState(scene).visible; } mode.addEventListener('change', () => { @@ -202,7 +202,7 @@ export function createSceneSection( enter.addEventListener('click', () => { say(''); enter.disabled = true; - api.analysis.enterXr().then((result) => say(result.ok ? '' : result.message), (reason: unknown) => say(ipcErrorMessage(reason))) + api.analysis.enterXr().then((result) => say(enterXrNote(result)), (reason: unknown) => say(ipcErrorMessage(reason))) .finally(() => { enter.disabled = false; }); @@ -265,7 +265,7 @@ export function createSceneSection( const changed = scene?.url !== next.url; scene = next; if (changed) { - say(''); + say(enterXrState(next).note); modes = null; drawModes(); headsetOpen = false; diff --git a/apps/ide/src/renderer/sceneHeaderModel.ts b/apps/ide/src/renderer/sceneHeaderModel.ts index 01b3c6454..bfaea9f9b 100644 --- a/apps/ide/src/renderer/sceneHeaderModel.ts +++ b/apps/ide/src/renderer/sceneHeaderModel.ts @@ -1,5 +1,5 @@ -import { sceneKindLabel, type AnalysisKind } from '../shared/analysisKinds.ts'; -import type { SceneShareState, SceneShareStatus } from '../shared/api.ts'; +import { ANALYSIS_KIND_INFO, sceneKindLabel, type AnalysisKind } from '../shared/analysisKinds.ts'; +import type { EnterXrResult, SceneInfo, SceneShareState, SceneShareStatus } from '../shared/api.ts'; /** * Pure state of the scene's header (#155): what ran, where it is served, and @@ -105,3 +105,22 @@ export function analysedFilesLabel(count: number | undefined): string { } return `${Math.round(count).toLocaleString('en')} ${count === 1 ? 'file' : 'files'}`; } + +/** + * #19, #483: whether a scene's Enter XR button shows, and the note it starts + * with. A LivePanel is a 2D page: nothing to enter. Where the IDE can never + * enter XR (a system webview without WebXR) the button goes and the note says + * which paths are left, so no button is dead. + */ +export function enterXrState(scene: Pick): { readonly visible: boolean; readonly note: string } { + // Kinds are `-livepanel...`: the mode says it (the old `startsWith('livepanel')` never matched). + if (ANALYSIS_KIND_INFO[scene.kind].mode === 'LivePanel') { + return { visible: false, note: '' }; + } + return scene.xrUnavailable ? { visible: false, note: scene.xrUnavailable } : { visible: true, note: '' }; +} + +/** What the note says after Enter XR answered. */ +export function enterXrNote(result: EnterXrResult): string { + return result.ok ? result.message ?? '' : result.message; +} diff --git a/apps/ide/src/renderer/sceneXrControls.ts b/apps/ide/src/renderer/sceneXrControls.ts index 3d8f9eaaa..b0c17c067 100644 --- a/apps/ide/src/renderer/sceneXrControls.ts +++ b/apps/ide/src/renderer/sceneXrControls.ts @@ -1,6 +1,6 @@ import type { CodeXRApi, SceneInfo } from '../shared/api.ts'; import { el } from './dom.ts'; -import { ipcErrorMessage } from './sceneHeaderModel.ts'; +import { enterXrNote, enterXrState, ipcErrorMessage } from './sceneHeaderModel.ts'; import { qrDrawing } from '@codexr/core/xr/headsetQr'; /** @@ -97,7 +97,7 @@ export function createSceneXrControls(api: CodeXRApi['analysis'], callbacks: { o say(''); enter.disabled = true; api.enterXr().then((result) => { - say(result.ok ? '' : result.message); + say(enterXrNote(result)); }, (reason: unknown) => say(ipcErrorMessage(reason))).finally(() => { enter.disabled = false; }); @@ -120,9 +120,10 @@ export function createSceneXrControls(api: CodeXRApi['analysis'], callbacks: { o const sceneChanged = scene?.url !== next.url; scene = next; // A LivePanel is a 2D page: nothing to enter, but it opens in a browser or on a headset all the same. - enter.hidden = next.kind.startsWith('livepanel'); + const xr = enterXrState(next); + enter.hidden = !xr.visible; if (sceneChanged) { - say(''); + say(xr.note); drawHeadset(); } }, diff --git a/apps/ide/src/shared/api.ts b/apps/ide/src/shared/api.ts index d6823a983..758807416 100644 --- a/apps/ide/src/shared/api.ts +++ b/apps/ide/src/shared/api.ts @@ -289,14 +289,22 @@ export interface SceneInfo { /** #203: how many files the analysis took (its own records), when known. */ readonly files?: number | undefined; readonly share: SceneShareState; + /** + * #483: why this IDE cannot enter a scene in XR at all (a system webview + * without WebXR), when it cannot: the header then offers only Open in + * browser and On a headset, with this note. Absent where it can try. + */ + readonly xrUnavailable?: string | undefined; } /** * #19: entering the scene in XR from the IDE. `unsupported` means no headset - * reached Electron's Chromium here; `message` says what to do instead. + * reached the IDE's web engine here; `message` says what to do instead. + * #483: an `ok` result may carry what the person still has to do (on Tauri, + * press the Enter XR button the scene shows). */ export type EnterXrResult = - | { readonly ok: true } + | { readonly ok: true; readonly message?: string | undefined } | { readonly ok: false; readonly reason: 'unsupported' | 'failed'; readonly message: string }; /** A change of the sharing state of the calling window's scene (#155). `url` names the scene it belongs to. */ diff --git a/apps/ide/test/sceneXr.test.ts b/apps/ide/test/sceneXr.test.ts index f7bc86be1..556569d04 100644 --- a/apps/ide/test/sceneXr.test.ts +++ b/apps/ide/test/sceneXr.test.ts @@ -1,6 +1,7 @@ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; -import { allowXrPermission, isXrPermission, unsupportedXrMessage, XR_ARM_MS } from '../src/main/analysis/sceneXrPolicy.ts'; +import { allowXrPermission, inIdeXrUnavailable, isXrPermission, unsupportedXrMessage, XR_ARM_MS } from '../src/main/analysis/sceneXrPolicy.ts'; +import { enterXrNote, enterXrState } from '../src/renderer/sceneHeaderModel.ts'; import { qrDrawing } from '@codexr/core/xr/headsetQr'; const ORIGIN = 'http://localhost:3000'; @@ -44,3 +45,26 @@ describe('qrDrawing (#19)', () => { assert.ok(drawing.path.includes(`M4 ${modules + 3}h1v1h-1z`), 'bottom-left finder corner'); }); }); + +describe('Enter XR without dead buttons (#483)', () => { + it('says which paths are left where a Tauri system webview has no WebXR', () => { + assert.equal(inIdeXrUnavailable('electron', 'linux'), null); + assert.equal(inIdeXrUnavailable('electron', 'darwin'), null); + assert.equal(inIdeXrUnavailable('tauri', 'win32'), null, 'WebView2 exposes WebXR: the button stays'); + assert.match(inIdeXrUnavailable('tauri', 'linux') ?? '', /Open in browser.*On a headset/); + assert.match(inIdeXrUnavailable('tauri', 'darwin') ?? '', /no WebXR/); + assert.equal(unsupportedXrMessage('win32', 'tauri'), unsupportedXrMessage('win32')); + assert.equal(unsupportedXrMessage('linux'), unsupportedXrMessage('linux', 'electron')); + }); + + it('hides the button, with the note, where it could never work', () => { + assert.deepEqual(enterXrState({ kind: 'project-xr' }), { visible: true, note: '' }); + assert.deepEqual(enterXrState({ kind: 'file-xr', xrUnavailable: undefined }), { visible: true, note: '' }); + assert.deepEqual(enterXrState({ kind: 'directory-livepanel' }), { visible: false, note: '' }, 'a LivePanel is a 2D page'); + assert.deepEqual(enterXrState({ kind: 'project-livepanel-deep', xrUnavailable: 'none here' }), { visible: false, note: '' }); + assert.deepEqual(enterXrState({ kind: 'directory-xr-deep', xrUnavailable: 'none here' }), { visible: false, note: 'none here' }); + assert.equal(enterXrNote({ ok: true }), ''); + assert.equal(enterXrNote({ ok: true, message: 'press it in the scene' }), 'press it in the scene'); + assert.equal(enterXrNote({ ok: false, reason: 'unsupported', message: 'no headset' }), 'no headset'); + }); +}); From 76992deac071584a3b5b28cc36655403687797be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:30:33 +0000 Subject: [PATCH 21/29] docs(ide): R5 scene view on Tauri: what works, deviations, what is left (#483) --- docs/ide/tauri-migration.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/ide/tauri-migration.md b/docs/ide/tauri-migration.md index 1fd77ffc3..fa992177c 100644 --- a/docs/ide/tauri-migration.md +++ b/docs/ide/tauri-migration.md @@ -165,7 +165,7 @@ Deviations from the design given for these stories: 7. Build-time icons are generated placeholders (no binary committed); the window shows the real logo, loaded at run time. Installer icons come with R12. 8. Menus are not built yet (logged); they were listed under R2 and move to the R9 native pieces with the About box. -Degraded on Tauri, each with one logged "not yet on Tauri (Rn)" line, never a crash: the scene view beside the code (R5: the analysis runs, the in-IDE view refuses with "use Open in browser"), the scene bridge and `executeJavaScript` (Enter XR, R5), extension webviews and the `codexr-webview:` scheme (R6), the application menu, About box, screen picker, permission handlers and dialogs with more than three buttons (R9: they answer their Cancel button), the smoke run (R11; `--codexr-smoke` starts a normal session), the Vite dev server (R2 follow-up), installers and a bundled Node (R12). The status bar still says "Electron" (cosmetic). +Degraded on Tauri, each with one logged "not yet on Tauri (Rn)" line, never a crash (the scene view, its bridge and Enter XR came with R5, section 9): extension webviews and the `codexr-webview:` scheme (R6), the application menu, About box, screen picker, permission handlers and dialogs with more than three buttons (R9: they answer their Cancel button), the smoke run (R11; `--codexr-smoke` starts a normal session), the Vite dev server (R2 follow-up), installers and a bundled Node (R12). The status bar still says "Electron" (cosmetic). Verified by running here (Linux x64 container, Xvfb, WebKitGTK 2.52, software GL): the window opens on `--folder=`, the explorer lists the folder, Monaco opens `package.json` with Git blame, the terminal runs bash and shows its prompt, settings load, Git status shows (branch, ahead/behind, the changed-file badge, in a trusted folder), and killing the sidecar shows an error dialog. Not verified: dialogs, clipboard, opener and trash (code paths compiled, not clicked), the extension host with real extensions, Windows and macOS. @@ -190,3 +190,23 @@ What changed, each measured alone (Tauri usable time / idle CPU / PSS, Electron Tried without a measured win (not kept): `WEBKIT_DISABLE_COMPOSITING_MODE=1` (alone 1.5 % / 490 MB; on top of the DMA-BUF switch no change), `WEBKIT_SKIA_ENABLE_CPU_RENDERING=1` (no idle gain), `NO_AT_BRIDGE=1` and `GTK_A11Y=none` (no start-up gain), the WebKit cache model `DocumentViewer` through `with_webview` (PSS 472 to 474 MB). The Rust process (84 MB PSS, 151 MB RSS) is 35 MB of heap plus shared GTK, WebKit and Mesa libraries (libLLVM alone 16 MB, loaded by the UI process's GL context); the binary is 6 MB and already built with `lto`, `strip`, `opt-level = "s"`, `codegen-units = 1`, so build flags have nothing left to take. Read with care: this is software-rendered WebKitGTK in a container. Of the Tauri tree now, the web process is 256 MB PSS (Electron's renderer: 163 MB), the sidecar 109 MB, the Rust process 84 MB. The renderer itself is still about twice as slow on JavaScriptCore as on V8 here: from Monaco's chunks being requested to the next ones about 570 ms pass with the scheme handler answering each file in under 5 ms (2.7 MB in 5 ms) and IPC round trips of 0 to 35 ms (48 calls to the usable point), so that time is parse and evaluation of about 4 MB of JavaScript. CI on macOS (before these changes) showed 2.1 s before the page's time origin and 2.8 s between the explorer and Monaco; the next CI run tells how much of it the window-at-launch change takes. + +## 9. Scene view (R5 #483) + +State on 4 Dec 2026: on the Tauri build the analysis scene opens beside the code as on Electron. Verified by running here (Linux x64 container, Xvfb, WebKitGTK 2.52, software GL, a two-file project, screenshots in the project files `ide-tauri/screenshots/r5-*.png`): the folder's automatic XR analysis opens the scene in the right slot; it follows a window resize and zen mode, hides while the welcome dialog is over it and comes back after; the close button removes it and a new analysis (File, XR) opens a second one on another port; a drill-down card's *Open in editor* opens `app.py` in Monaco through the scene bridge; saving a file updates the scene live; scene text renders with the vendored font. + +``` +src/main/analysis/sceneView.ts (unchanged flow) src-tauri/src/scene.rs + new WebContentsView / addChildView / loadURL ----> host.scene.create: Window::add_child (unstable multiwebview), + setBounds / setVisible ----> host.scene.setBounds (applied in order on the reader thread) + webContents.close / focus / executeJavaScript ----> host.scene.close / webview.focus / scene.eval + ipcMain.on(SCENE_OPEN_IN_EDITOR_CHANNEL) <---- scene.message <- codexr_scene <- out/sceneBridge (init script) +``` + +- **The seam.** `src/sidecar/tauriHost.ts` implements `WebContentsView` (made in the core on its first `loadURL`, with the bounds and visibility set before), `contentView.addChildView`, and `ipcMain.on` for the scene bridge, so `sceneView.ts`, `analysisService.ts` and `ipc.ts` run unchanged. The scene webview is labelled `scene-`, incognito (Electron's in-memory partition), may navigate only on its own server's origin, and new windows are refused. +- **Bridge.** `src/sceneBridge` (an IIFE in `out/sceneBridge/index.js`, injected into the scene webview only) defines the frozen `CodeXRHostBridge.openInEditor`, as Electron's scene preload does, and talks through one command, `codexr_scene`. `capabilities/scene.json` grants it to webviews `scene-*` on loopback pages (`http(s)://127.0.0.1:*`, `localhost:*`) only; the core checks the label and the origin it opened the view on again, and the sidecar hands the message to the same `ipc.ts` listener (path inside the open folder, sender frame = main frame). +- **Offline libraries.** A system webview cannot intercept `https`, so the shared core serves them: `@codexr/core/server/http/localSceneLibraries` (off by default, the VS Code plugin is unchanged; the IDE turns it on in `coreRuntime.ts` on both shells). Pages sent to this machine get the pinned CDN URLs rewritten to `/__codexr/scene-libraries/`, served from `apps/vscode-extension/test/vendor/scene-libraries` (only the table's files); A-Frame's font root and BabiaXR's default font URL are rewritten inside the served scripts. Pages sent through the Cloudflare tunnel are not rewritten (guests and headsets keep the CDNs). The Electron scene session keeps its interception as a second line. +- **Enter XR.** A Tauri webview's `eval` returns nothing and cannot carry the person's gesture. `executeJavaScript` on a scene view runs the expression through the bridge (`sceneEvalScript`, answers matched by a random id and the view's label). Where `navigator.xr` exists (WebView2) and a headset is reported, Enter XR asks the scene to show its own Enter XR button, and the click inside the scene starts the session; the header says so. Where it does not (WKWebView, WebKitGTK: R1 spike), `SceneInfo.xrUnavailable` hides the header's Enter XR and the note points at *Open in browser* and *On a headset*: no dead button. The same change fixes the LivePanel check, which compared `startsWith('livepanel')` against kinds named `-livepanel` and never hid the button. +- **Windows by label.** A window with the scene beside its page holds two webviews, and Tauri then no longer returns it from `get_webview_window`: the host looks windows up with `get_window` and webviews with `get_webview` (the first run showed "no window main" on focus). + +Deviations: the XR permission is not armed or checked on Tauri (no webview permission handlers before R9; the in-scene click is the gesture, and WebView2 applies its own prompt); the scene's other requests are not filtered (Electron's `onBeforeRequest`; R9, or a CSP from the core in IDE mode); the screen picker stays degraded (R9, logged). Not verified by running: Enter XR on WebView2 with a headset, the eval path in a real webview (unit-tested in a VM context only, since Linux hides the button), Windows and macOS (CI), the Agent Flow view (scene-side, not exercised here). Left: R9 permission handlers and request filtering for the scene view, a headset test on Windows. From 8b459238f47746d400548319f282d4c1f10f6242 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:32:09 +0000 Subject: [PATCH 22/29] IDE: the Node debugger drops the inspector's 'Debugger ending on' line from the program output --- apps/ide/src/main/debug/nodeAdapter.ts | 2 +- apps/ide/test/debug.test.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/ide/src/main/debug/nodeAdapter.ts b/apps/ide/src/main/debug/nodeAdapter.ts index dd5026902..6da2891bc 100644 --- a/apps/ide/src/main/debug/nodeAdapter.ts +++ b/apps/ide/src/main/debug/nodeAdapter.ts @@ -50,7 +50,7 @@ interface CallFrame { const THREAD_ID = 1; const LISTENING = /Debugger listening on (ws:\/\/[^\s]+)/; /** What Node prints about the inspector, which is not the program's output. */ -const INSPECTOR_NOISE = /^(Debugger listening on |For help, see: https:\/\/nodejs\.org\/|Debugger attached\.|Waiting for the debugger to disconnect\.\.\.)/; +const INSPECTOR_NOISE = /^(Debugger listening on |For help, see: https:\/\/nodejs\.org\/|Debugger attached\.|Debugger ending on |Waiting for the debugger to disconnect\.\.\.)/; const CONNECT_TIMEOUT_MS = 15_000; const MAX_PROPERTIES = 1000; const MAX_VALUE_LENGTH = 1000; diff --git a/apps/ide/test/debug.test.ts b/apps/ide/test/debug.test.ts index c3d5de926..5ccab143a 100644 --- a/apps/ide/test/debug.test.ts +++ b/apps/ide/test/debug.test.ts @@ -182,6 +182,8 @@ describe('Node.js adapter helpers (#180)', () => { assert.equal(inspectorAddress(stderr), 'ws://127.0.0.1:40123/0f5e-11'); assert.equal(inspectorAddress('nothing'), null); assert.equal(withoutInspectorNoise(`${stderr}Debugger attached.\nreal error\nWaiting for the debugger to disconnect...\n`), 'real error\n'); + // Node's last line on Windows, when the program ends before the client detaches. + assert.equal(withoutInspectorNoise('result 6\nDebugger ending on ws://127.0.0.1:60327/17957d18\r\n'), 'result 6\n'); }); it('matches a file by path or file URL, in any case on Windows', () => { From d1104ef18b7a4c52ef8a813d46dd644eae0d4848 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:36:04 +0000 Subject: [PATCH 23/29] ci(ide): bench traces the first Tauri run's stderr with timings, to find the slow start on Linux and Windows (#480) --- .github/workflows/ide-bench.yml | 4 ++-- apps/ide/scripts/bench.mjs | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ide-bench.yml b/.github/workflows/ide-bench.yml index 028ba72b5..3949afbee 100644 --- a/.github/workflows/ide-bench.yml +++ b/.github/workflows/ide-bench.yml @@ -152,7 +152,7 @@ jobs: - name: Bench (Linux, virtual display) if: runner.os == 'Linux' shell: bash - run: CODEXR_NODE="$(node -p process.execPath)" xvfb-run -a -s "-screen 0 1920x1080x24" node apps/ide/scripts/bench.mjs --label=tauri --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- apps/ide/src-tauri/target/release/codexr-ide + run: CODEXR_IPC_TRACE=1 CODEXR_NODE="$(node -p process.execPath)" xvfb-run -a -s "-screen 0 1920x1080x24" node apps/ide/scripts/bench.mjs --label=tauri --trace-first --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- apps/ide/src-tauri/target/release/codexr-ide - name: Bench if: runner.os != 'Linux' @@ -160,7 +160,7 @@ jobs: run: | exe=apps/ide/src-tauri/target/release/codexr-ide if [ "$RUNNER_OS" = "Windows" ]; then exe="$exe.exe"; fi - CODEXR_IPC_TRACE="${{ runner.os == 'Windows' && '1' || '' }}" CODEXR_NODE="$(node -p process.execPath)" node apps/ide/scripts/bench.mjs --label=tauri --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- "$exe" + CODEXR_IPC_TRACE=1 CODEXR_NODE="$(node -p process.execPath)" node apps/ide/scripts/bench.mjs --label=tauri --trace-first --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- "$exe" - name: Summary if: always() diff --git a/apps/ide/scripts/bench.mjs b/apps/ide/scripts/bench.mjs index 4baed351d..0e3cc7947 100644 --- a/apps/ide/scripts/bench.mjs +++ b/apps/ide/scripts/bench.mjs @@ -2,7 +2,7 @@ // so the same numbers can be taken for any desktop shell (Electron today, the next one after). // // Usage: -// node scripts/bench.mjs [--runs=5] [--idle-seconds=20] [--folder=] [--out=] [--label=] -- [args...] +// node scripts/bench.mjs [--runs=5] [--idle-seconds=20] [--folder=] [--out=] [--label=] [--trace-first] -- [args...] // With no command it launches the built Electron IDE (npm run build first). // // One run: spawn the app with --codexr-bench --folder=; the renderer's driver @@ -36,6 +36,8 @@ const runs = Number(options.runs ?? 5); const idleSeconds = Number(options['idle-seconds'] ?? 20); const folder = path.resolve(options.folder ?? path.join(IDE_ROOT, '..', '..')); const label = options.label ?? 'electron'; +// --trace-first: the first run's stderr, each line with its time since launch (where a slow start goes). +const traceFirst = options['trace-first'] !== undefined; let command = separator === -1 ? [] : argv.slice(separator + 1); // A relative path to the app (a CI build) is resolved here: Windows cannot spawn one with forward slashes. if (command.length > 0 && /[\\/]/.test(command[0]) && fs.existsSync(command[0])) { @@ -156,6 +158,12 @@ async function oneRun(index) { child.stderr.on('data', (chunk) => { const lines = (stderrPartial + chunk).split(/\r?\n/); stderrPartial = lines.pop() ?? ''; + if (traceFirst && index === 0) { + const at = Math.round(performance.now() - started); + for (const line of lines) { + if (line.trim() !== '') console.error(`[bench] +${at} ms ${line}`); + } + } stderrTail.push(...lines); stderrTail.splice(0, Math.max(0, stderrTail.length - STDERR_TAIL_LINES)); }); From 6d5648d56700de1d1a6d5ee619a0d7aaa23cb885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:40:50 +0000 Subject: [PATCH 24/29] ci(ide): bench trace satisfies the curly rule (#480) --- apps/ide/scripts/bench.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/ide/scripts/bench.mjs b/apps/ide/scripts/bench.mjs index 0e3cc7947..f71415add 100644 --- a/apps/ide/scripts/bench.mjs +++ b/apps/ide/scripts/bench.mjs @@ -161,7 +161,9 @@ async function oneRun(index) { if (traceFirst && index === 0) { const at = Math.round(performance.now() - started); for (const line of lines) { - if (line.trim() !== '') console.error(`[bench] +${at} ms ${line}`); + if (line.trim() !== '') { + console.error(`[bench] +${at} ms ${line}`); + } } } stderrTail.push(...lines); From c559d28dc0ec038cf11f2eaaa3f80ae55a117034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:52:58 +0000 Subject: [PATCH 25/29] ci(ide): Tauri start-up diagnostics: event delivery on the core log, bench step failures, a Linux strace pass (#480) --- .github/workflows/ide-bench.yml | 12 ++++++++++++ apps/ide/src-tauri/src/sidecar.rs | 7 ++++++- apps/ide/src/bridge/index.ts | 4 ++++ apps/ide/src/renderer/bench/benchDriver.ts | 3 +++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ide-bench.yml b/.github/workflows/ide-bench.yml index 3949afbee..c63e16377 100644 --- a/.github/workflows/ide-bench.yml +++ b/.github/workflows/ide-bench.yml @@ -149,6 +149,18 @@ jobs: - name: Build (web, sidecar, bridge, Rust core) run: npm run tauri:build --workspace=code-xr-ide + # Temporary (#480): where the Linux start-up waits ~25 s on the runner. + - name: Start-up trace (Linux, temporary) + if: runner.os == 'Linux' + continue-on-error: true + shell: bash + run: | + sudo apt-get install -y strace >/dev/null + echo "DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR"; ls -la /run/user/$(id -u) || true + CODEXR_NODE="$(node -p process.execPath)" G_MESSAGES_DEBUG=all timeout 120 xvfb-run -a -s "-screen 0 1920x1080x24" strace -f -tt -s 200 -e trace=connect,execve,poll,ppoll -o /tmp/st.txt node apps/ide/scripts/bench.mjs --label=trace --runs=1 --idle-seconds=1 --trace-first --out=/tmp/trace.json -- apps/ide/src-tauri/target/release/codexr-ide 2>&1 | grep -v "ipc codexr" | head -150 || true + grep -E "connect\(|execve\(" /tmp/st.txt | grep -vE "ENOENT.*execve|/proc/" | head -120 || true + awk '{print $2}' /tmp/st.txt | head -1; grep -E "resumed>.*= 0 \(Timeout\)" /tmp/st.txt | head -20 || true + - name: Bench (Linux, virtual display) if: runner.os == 'Linux' shell: bash diff --git a/apps/ide/src-tauri/src/sidecar.rs b/apps/ide/src-tauri/src/sidecar.rs index a512d590e..f262c814b 100644 --- a/apps/ide/src-tauri/src/sidecar.rs +++ b/apps/ide/src-tauri/src/sidecar.rs @@ -41,6 +41,9 @@ impl Events { pub fn register(&self, label: &str, channel: Channel) { let queued = self.queued.lock().unwrap().remove(label).unwrap_or_default(); + if std::env::var_os("CODEXR_IPC_TRACE").is_some() { + eprintln!("[codexr-ide] events: {label} registered channel {}, {} queued", channel.id(), queued.len()); + } for message in queued { let _ = channel.send(message); } @@ -54,7 +57,9 @@ impl Events { fn deliver(&self, label: &str, message: Value) { if let Some(channel) = self.channels.lock().unwrap().get(label) { - let _ = channel.send(message); + if let Err(error) = channel.send(message) { + eprintln!("[codexr-ide] An event for {label} was not delivered: {error}"); + } return; } let mut queued = self.queued.lock().unwrap(); diff --git a/apps/ide/src/bridge/index.ts b/apps/ide/src/bridge/index.ts index 01cfd2a11..d353bfca2 100644 --- a/apps/ide/src/bridge/index.ts +++ b/apps/ide/src/bridge/index.ts @@ -67,6 +67,10 @@ function install(): void { if (typeof message !== 'object' || message === null || typeof message.index !== 'number') { return; } + if (message.index === 0) { + // Proof on the core's log that events reach this page (a page without them looks frozen). + void tauriInvoke('codexr_log', { level: 'warn', message: 'events: the first one arrived' }).catch(() => undefined); + } early.set(message.index, message); let current = early.get(nextIndex); while (current) { diff --git a/apps/ide/src/renderer/bench/benchDriver.ts b/apps/ide/src/renderer/bench/benchDriver.ts index fda0760b1..94a041d51 100644 --- a/apps/ide/src/renderer/bench/benchDriver.ts +++ b/apps/ide/src/renderer/bench/benchDriver.ts @@ -31,6 +31,9 @@ async function runBench(hooks: BenchHooks): Promise { return performance.now(); } failures.push(`${name} not ready after ${STEP_TIMEOUT_MS / 1000}s`); + // On the shell's log at once: a run that never reports still says where it stopped. + const explorer = document.querySelector('[data-testid="explorer-tree"]'); + console.error(`[codexr bench] ${name} not ready after ${STEP_TIMEOUT_MS / 1000}s; explorer: ${explorer ? (explorer.textContent ?? '').slice(0, 300) : 'absent'}`); return -1; }; const explorerRow = (): HTMLElement | null => document.querySelector(`[data-testid="explorer-tree"] [data-path="${BENCH_FILE}"]`); From 62efaf54de7ecd48581abb019f204ae60fc006ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:55:44 +0000 Subject: [PATCH 26/29] IDE (Tauri): start-up timing trace under CODEXR_IPC_TRACE (core setup, window build, policy, assets) (#480) --- apps/ide/src-tauri/src/assets.rs | 1 + apps/ide/src-tauri/src/host.rs | 3 +++ apps/ide/src-tauri/src/main.rs | 15 +++++++++++++++ 3 files changed, 19 insertions(+) diff --git a/apps/ide/src-tauri/src/assets.rs b/apps/ide/src-tauri/src/assets.rs index b27cb6317..6c45d0511 100644 --- a/apps/ide/src-tauri/src/assets.rs +++ b/apps/ide/src-tauri/src/assets.rs @@ -111,6 +111,7 @@ pub fn serve(shell: &Shell, request: &Request>) -> Response> { eprintln!("[codexr-ide] Refused a request for {uri}: not the app."); return plain(StatusCode::NOT_FOUND, "Not found"); } + crate::trace(format_args!("serve {}", uri.path())); let Some(file) = resolve_asset(&shell.renderer_dir(), uri.path()) else { eprintln!("[codexr-ide] Not found: {uri}"); return plain(StatusCode::NOT_FOUND, "Not found"); diff --git a/apps/ide/src-tauri/src/host.rs b/apps/ide/src-tauri/src/host.rs index 719fbafed..2808361a6 100644 --- a/apps/ide/src-tauri/src/host.rs +++ b/apps/ide/src-tauri/src/host.rs @@ -76,6 +76,7 @@ impl Shell { } pub fn set_csp(&self, csp: &str) { + crate::trace("policy received"); *self.csp.lock().unwrap() = Some(csp.to_string()); self.csp_ready.notify_all(); } @@ -333,7 +334,9 @@ fn build_window(app: &AppHandle, shell: &Arc, sidecar: &Arc, spe if let Some(icon) = window_icon(shell) { builder = builder.icon(icon).map_err(|error| error.to_string())?; } + crate::trace(format_args!("building window {}", spec.label)); let window = builder.build().map_err(|error| error.to_string())?; + crate::trace(format_args!("built window {}", spec.label)); let _ = window.set_min_size(Some(LogicalSize::new(spec.min_width, spec.min_height))); if show { // Never left invisible: a page that has not loaded by now is shown as it is. diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index e1e5f66b9..f73df0433 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -26,6 +26,17 @@ use tauri::{Manager, RunEvent, State, WindowEvent}; use crate::sidecar::Sidecar; +/// When the process started, for `trace`. +static STARTED: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// A start-up timing line on stderr, only with `CODEXR_IPC_TRACE` (CI diagnostics). +pub fn trace(message: impl std::fmt::Display) { + if std::env::var_os("CODEXR_IPC_TRACE").is_some() { + let elapsed = STARTED.get().map(|started| started.elapsed().as_millis()).unwrap_or(0); + eprintln!("[codexr-ide] +{elapsed} ms {message}"); + } +} + /// Where the IDE's build output is: `CODEXR_IDE_OUT`, or apps/ide/out next to this crate (unpackaged; R12 packages it). fn out_dir() -> PathBuf { std::env::var_os("CODEXR_IDE_OUT") @@ -127,6 +138,7 @@ fn software_rendering_defaults() -> bool { } fn main() { + let _ = STARTED.set(std::time::Instant::now()); let set_dmabuf_switch = software_rendering_defaults(); let args: Vec = std::env::args().skip(1).collect(); let out = out_dir(); @@ -147,6 +159,7 @@ fn main() { let sidecar = Arc::new(Sidecar::new()); let shell = Arc::new(host::Shell::new(out.clone(), bridge, scene_bridge)); + trace("main"); let mut builder = tauri::Builder::default(); if single_instance { let sidecar = sidecar.clone(); @@ -203,6 +216,7 @@ fn main() { let shell = shell.clone(); let out = out.clone(); move |app| { + trace("setup"); // The sidecar boots while the window's web processes start and the page // loads: its policy and its IPC answers are awaited, never failed (host.rs, // src/sidecar/index.ts). @@ -219,6 +233,7 @@ fn main() { }) .build(tauri::generate_context!()) .expect("error while building the Code-XR IDE"); + trace("built"); app.run(move |app, event| match event { RunEvent::ExitRequested { api, code, .. } => { From b96285263a37478c9767a25c6ebcd0f90732eb03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:06:22 +0000 Subject: [PATCH 27/29] IDE (Tauri): trace IPC answers and the page when a bench step stalls (#480) --- apps/ide/src-tauri/src/main.rs | 13 ++++++++----- apps/ide/src/renderer/bench/benchDriver.ts | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index f73df0433..15dca67f0 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -54,12 +54,15 @@ async fn codexr_ipc(webview: tauri::Webview, sidecar: State<'_, Arc>, c eprintln!("[codexr-ide] Refused IPC {channel} from {url}"); return Err("Refused.".into()); } - if std::env::var_os("CODEXR_IPC_TRACE").is_some() { - eprintln!("[codexr-ide] ipc {channel}"); - } - sidecar + trace(format_args!("ipc {channel}")); + let result = sidecar .request("ipc.invoke", json!({ "window": webview.label(), "url": url.as_str(), "channel": channel, "args": args })) - .await + .await; + match &result { + Ok(value) => trace(format_args!("ipc {channel} answered ({} bytes)", value.to_string().len())), + Err(error) => trace(format_args!("ipc {channel} failed: {error}")), + } + result } /// The page's uncaught errors and console errors (forwarded by the bridge), on the diff --git a/apps/ide/src/renderer/bench/benchDriver.ts b/apps/ide/src/renderer/bench/benchDriver.ts index 94a041d51..c9146da27 100644 --- a/apps/ide/src/renderer/bench/benchDriver.ts +++ b/apps/ide/src/renderer/bench/benchDriver.ts @@ -33,7 +33,7 @@ async function runBench(hooks: BenchHooks): Promise { failures.push(`${name} not ready after ${STEP_TIMEOUT_MS / 1000}s`); // On the shell's log at once: a run that never reports still says where it stopped. const explorer = document.querySelector('[data-testid="explorer-tree"]'); - console.error(`[codexr bench] ${name} not ready after ${STEP_TIMEOUT_MS / 1000}s; explorer: ${explorer ? (explorer.textContent ?? '').slice(0, 300) : 'absent'}`); + console.error(`[codexr bench] ${name} not ready after ${STEP_TIMEOUT_MS / 1000}s; explorer: ${explorer ? `${explorer.childElementCount} children, rows ${[...explorer.querySelectorAll('[data-path]')].map((row) => row.dataset['path']).slice(0, 15).join(', ')}` : 'absent'}; page: ${(document.body.innerText ?? '').replace(/\s+/g, ' ').slice(0, 600)}`); return -1; }; const explorerRow = (): HTMLElement | null => document.querySelector(`[data-testid="explorer-tree"] [data-path="${BENCH_FILE}"]`); From 2ecd7ef509429942c5c8378c8b991ff34c2fd319 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:18:12 +0000 Subject: [PATCH 28/29] IDE (Tauri): one Tauri host in the sidecar on Windows, so IPC handlers are found; Linux start-up variants on CI (#480) The seam resolver returned a backslashed path on Windows, while the sidecar's own ./tauriHost.ts import got Vite's forward-slashed id: two module copies, the handlers registered in one and looked up in the other. The build now fails if the bundle holds more than one copy. --- .github/workflows/ide-bench.yml | 19 ++++++++++++------- apps/ide/scripts/tauri.mjs | 13 +++++++++++++ apps/ide/scripts/viteConfigs.mjs | 6 +++++- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ide-bench.yml b/.github/workflows/ide-bench.yml index c63e16377..e575e4400 100644 --- a/.github/workflows/ide-bench.yml +++ b/.github/workflows/ide-bench.yml @@ -149,17 +149,22 @@ jobs: - name: Build (web, sidecar, bridge, Rust core) run: npm run tauri:build --workspace=code-xr-ide - # Temporary (#480): where the Linux start-up waits ~25 s on the runner. - - name: Start-up trace (Linux, temporary) + # Temporary (#480): the Linux start-up waits ~25 s, then 2 x 5 s, on D-Bus (strace: + # right after GTK's AT-SPI bridge connects to the session bus). Which setting removes it. + - name: Start-up variants (Linux, temporary) if: runner.os == 'Linux' continue-on-error: true shell: bash run: | - sudo apt-get install -y strace >/dev/null - echo "DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR"; ls -la /run/user/$(id -u) || true - CODEXR_NODE="$(node -p process.execPath)" G_MESSAGES_DEBUG=all timeout 120 xvfb-run -a -s "-screen 0 1920x1080x24" strace -f -tt -s 200 -e trace=connect,execve,poll,ppoll -o /tmp/st.txt node apps/ide/scripts/bench.mjs --label=trace --runs=1 --idle-seconds=1 --trace-first --out=/tmp/trace.json -- apps/ide/src-tauri/target/release/codexr-ide 2>&1 | grep -v "ipc codexr" | head -150 || true - grep -E "connect\(|execve\(" /tmp/st.txt | grep -vE "ENOENT.*execve|/proc/" | head -120 || true - awk '{print $2}' /tmp/st.txt | head -1; grep -E "resumed>.*= 0 \(Timeout\)" /tmp/st.txt | head -20 || true + export CODEXR_IPC_TRACE=1 CODEXR_NODE="$(node -p process.execPath)" + run() { echo "=== $1"; shift; timeout 150 "$@" node apps/ide/scripts/bench.mjs --label=variant --runs=1 --idle-seconds=1 --trace-first --out=/tmp/variant.json -- apps/ide/src-tauri/target/release/codexr-ide 2>&1 | grep -E "\+[0-9]+ ms (main|built|setup|building|policy|serve /index)|bench\] run" || true; } + run "as is" xvfb-run -a -s "-screen 0 1920x1080x24" + run "NO_AT_BRIDGE=1" env NO_AT_BRIDGE=1 xvfb-run -a -s "-screen 0 1920x1080x24" + run "NO_AT_BRIDGE=1 + WEBKIT_DISABLE_ACCESSIBILITY" env NO_AT_BRIDGE=1 WEBKIT_DISABLE_ACCESSIBILITY=1 xvfb-run -a -s "-screen 0 1920x1080x24" + run "private session bus" xvfb-run -a -s "-screen 0 1920x1080x24" dbus-run-session -- + sudo apt-get install -y at-spi2-core >/dev/null 2>&1 || true + run "private session bus + at-spi2-core" xvfb-run -a -s "-screen 0 1920x1080x24" dbus-run-session -- + echo "=== user units"; systemctl --user list-unit-files 2>/dev/null | grep -iE "spi|portal" || true; ls /usr/share/dbus-1/services/ || true - name: Bench (Linux, virtual display) if: runner.os == 'Linux' diff --git a/apps/ide/scripts/tauri.mjs b/apps/ide/scripts/tauri.mjs index 7b6da546f..b11f05f19 100644 --- a/apps/ide/scripts/tauri.mjs +++ b/apps/ide/scripts/tauri.mjs @@ -93,6 +93,18 @@ function writeIcons() { // -- Build and run --------------------------------------------------------------- +/** + * The sidecar must hold one copy of the Tauri host: two (the seam and a direct + * import resolving to different ids) split its IPC handler map and its core + * connection, and every window.codexr call fails. It happened on Windows. + */ +function assertOneTauriHost(bundle) { + const copies = fs.readFileSync(bundle, 'utf8').split('No handler registered for').length - 1; + if (copies !== 1) { + throw new Error(`The sidecar bundle holds ${copies} copies of src/sidecar/tauriHost.ts, not one: check the desktop seam alias in scripts/viteConfigs.mjs.`); + } +} + export async function buildTauri() { // The web build is the Electron one (renderer, extension host, MCP, local agent...). const web = spawnSync(process.execPath, [path.join(IDE_ROOT, 'scripts', 'build.mjs')], { stdio: 'inherit' }); @@ -100,6 +112,7 @@ export async function buildTauri() { throw new Error(`scripts/build.mjs failed (${web.status})`); } await build(nodeTargetConfig('sidecar')); + assertOneTauriHost(path.join(IDE_ROOT, 'out', 'sidecar', 'index.cjs')); await build(bridgeConfig()); await build(sceneBridgeConfig()); writeIcons(); diff --git a/apps/ide/scripts/viteConfigs.mjs b/apps/ide/scripts/viteConfigs.mjs index 98c38f7eb..9851fbb07 100644 --- a/apps/ide/scripts/viteConfigs.mjs +++ b/apps/ide/scripts/viteConfigs.mjs @@ -17,6 +17,7 @@ import { builtinModules } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { normalizePath } from 'vite'; export const IDE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); export const OUT_DIR = path.join(IDE_ROOT, 'out'); @@ -42,7 +43,10 @@ const MAIN_NATIVE_EXTERNALS = ['node-pty']; /** #482: the seam the sidecar build swaps (see src/main/host/desktop.ts). */ const DESKTOP_SEAM = path.join(IDE_ROOT, 'src', 'main', 'host', 'desktop.ts'); -const TAURI_HOST = path.join(IDE_ROOT, 'src', 'sidecar', 'tauriHost.ts'); +// Vite's own spelling of the id (forward slashes): with Windows backslashes the seam and +// the sidecar's `./tauriHost.ts` were two modules, so ipc.ts registered its handlers in a +// second copy whose map nobody read ("No handler registered", Windows only). +const TAURI_HOST = normalizePath(path.join(IDE_ROOT, 'src', 'sidecar', 'tauriHost.ts')); /** * The sidecar's resolver: the desktop seam resolves to the Tauri host, and a From 9ccbb061898f527b4760017cb634fd12d7dd4d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Montes=20Linares?= <128893712+aMonteSl@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:36:10 +0000 Subject: [PATCH 29/29] ci(ide): Linux bench in a session bus of its own for both shells; temporary start-up probes removed (#480) --- .github/workflows/ide-bench.yml | 26 ++++++-------------------- apps/ide/src/bridge/index.ts | 4 ---- 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/.github/workflows/ide-bench.yml b/.github/workflows/ide-bench.yml index e575e4400..66dc48d56 100644 --- a/.github/workflows/ide-bench.yml +++ b/.github/workflows/ide-bench.yml @@ -77,9 +77,12 @@ jobs: run: node apps/ide/scripts/benchSizes.mjs --label=electron --out=apps/ide/bench-sizes-electron-${{ runner.os }}.json # Same build, run from the workspace (the packaged app adds nothing the bench measures). + # Both shells run in a session bus of their own, as on a desktop: the runner's systemd + # user bus activates portals that cannot reach the virtual display, and GTK (Tauri) + # waits 25 s + 2 x 5 s on them at start-up (measured, #480); Electron is unaffected. - name: Bench (Linux, virtual display) if: runner.os == 'Linux' - run: xvfb-run -a -s "-screen 0 1920x1080x24" node apps/ide/scripts/bench.mjs --runs=6 --idle-seconds=20 --out=apps/ide/bench-electron-${{ runner.os }}.json + run: xvfb-run -a -s "-screen 0 1920x1080x24" dbus-run-session -- node apps/ide/scripts/bench.mjs --runs=6 --idle-seconds=20 --out=apps/ide/bench-electron-${{ runner.os }}.json - name: Bench if: runner.os != 'Linux' @@ -149,27 +152,10 @@ jobs: - name: Build (web, sidecar, bridge, Rust core) run: npm run tauri:build --workspace=code-xr-ide - # Temporary (#480): the Linux start-up waits ~25 s, then 2 x 5 s, on D-Bus (strace: - # right after GTK's AT-SPI bridge connects to the session bus). Which setting removes it. - - name: Start-up variants (Linux, temporary) - if: runner.os == 'Linux' - continue-on-error: true - shell: bash - run: | - export CODEXR_IPC_TRACE=1 CODEXR_NODE="$(node -p process.execPath)" - run() { echo "=== $1"; shift; timeout 150 "$@" node apps/ide/scripts/bench.mjs --label=variant --runs=1 --idle-seconds=1 --trace-first --out=/tmp/variant.json -- apps/ide/src-tauri/target/release/codexr-ide 2>&1 | grep -E "\+[0-9]+ ms (main|built|setup|building|policy|serve /index)|bench\] run" || true; } - run "as is" xvfb-run -a -s "-screen 0 1920x1080x24" - run "NO_AT_BRIDGE=1" env NO_AT_BRIDGE=1 xvfb-run -a -s "-screen 0 1920x1080x24" - run "NO_AT_BRIDGE=1 + WEBKIT_DISABLE_ACCESSIBILITY" env NO_AT_BRIDGE=1 WEBKIT_DISABLE_ACCESSIBILITY=1 xvfb-run -a -s "-screen 0 1920x1080x24" - run "private session bus" xvfb-run -a -s "-screen 0 1920x1080x24" dbus-run-session -- - sudo apt-get install -y at-spi2-core >/dev/null 2>&1 || true - run "private session bus + at-spi2-core" xvfb-run -a -s "-screen 0 1920x1080x24" dbus-run-session -- - echo "=== user units"; systemctl --user list-unit-files 2>/dev/null | grep -iE "spi|portal" || true; ls /usr/share/dbus-1/services/ || true - - name: Bench (Linux, virtual display) if: runner.os == 'Linux' shell: bash - run: CODEXR_IPC_TRACE=1 CODEXR_NODE="$(node -p process.execPath)" xvfb-run -a -s "-screen 0 1920x1080x24" node apps/ide/scripts/bench.mjs --label=tauri --trace-first --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- apps/ide/src-tauri/target/release/codexr-ide + run: CODEXR_NODE="$(node -p process.execPath)" xvfb-run -a -s "-screen 0 1920x1080x24" dbus-run-session -- node apps/ide/scripts/bench.mjs --label=tauri --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- apps/ide/src-tauri/target/release/codexr-ide - name: Bench if: runner.os != 'Linux' @@ -177,7 +163,7 @@ jobs: run: | exe=apps/ide/src-tauri/target/release/codexr-ide if [ "$RUNNER_OS" = "Windows" ]; then exe="$exe.exe"; fi - CODEXR_IPC_TRACE=1 CODEXR_NODE="$(node -p process.execPath)" node apps/ide/scripts/bench.mjs --label=tauri --trace-first --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- "$exe" + CODEXR_NODE="$(node -p process.execPath)" node apps/ide/scripts/bench.mjs --label=tauri --runs=6 --idle-seconds=20 --out=apps/ide/bench-tauri-${{ runner.os }}.json -- "$exe" - name: Summary if: always() diff --git a/apps/ide/src/bridge/index.ts b/apps/ide/src/bridge/index.ts index d353bfca2..01cfd2a11 100644 --- a/apps/ide/src/bridge/index.ts +++ b/apps/ide/src/bridge/index.ts @@ -67,10 +67,6 @@ function install(): void { if (typeof message !== 'object' || message === null || typeof message.index !== 'number') { return; } - if (message.index === 0) { - // Proof on the core's log that events reach this page (a page without them looks frozen). - void tauriInvoke('codexr_log', { level: 'warn', message: 'events: the first one arrived' }).catch(() => undefined); - } early.set(message.index, message); let current = early.get(nextIndex); while (current) {