You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@texera.apache.org by "aglinxinyuan (via GitHub)" <gi...@apache.org> on 2026/05/09 07:07:28 UTC

[PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

aglinxinyuan opened a new pull request, #4997:
URL: https://github.com/apache/texera/pull/4997

   Closes #4996.
   
   ## Summary
   
   Brings the frontend's Monaco / VS Code language-client stack up to `monaco-languageclient` v10 (from v8.8.3) and the matching `@codingame/monaco-vscode-*` v25.1.2 ecosystem. v10 split the old single-wrapper API into three composable pieces, so the editor component is rewritten and the build/test pipeline picks up the codingame v25 quirks the new packages introduce. Adjacent dep cleanups land here too — several codingame side-deps and the R UDF editor become superfluous once v10 is in place.
   
   ## API shape: v8 → v10
   
   ```
   v8 (before)                                      v10 (after)
   ─────────────────                                ──────────────────────────────────
   new MonacoEditorLanguageClientWrapper(           const api  = new MonacoVscodeApiWrapper(...)
     // single config with editor + LSP + workers   const app  = new EditorApp(...)
     // all in one bag                              const lc   = new LanguageClientWrapper(...)
   ).start(htmlContainer)                           await api.start();         // global vscode-api init
                                                    await app.start(container);// mount editor
                                                    await lc.start();          // open WebSocket to LS
   ```
   
   `code-editor.component.ts` is rewritten against the new shape, plus a `whenReady()` handshake on the default language extensions and a post-mount `forceTokenization` loop to fix a TextMate first-paint race that otherwise renders every token as the default `mtk1` class.
   
   ## Diff at a glance (excluding `yarn.lock`)
   
   | Area | File(s) | Change |
   |---|---|---|
   | API rewrite | `code-editor.component.ts` | v10 wrapper triplet, `whenReady()` await, forceTokenization fix |
   | Worker bundling | `workers/{editor,extension-host,textmate}.worker.ts` | three one-line trampolines that re-export the codingame worker entries (see *Worker bundling* below) |
   | Webpack config | `custom-webpack.config.js` | patches `license-webpack-plugin` for codingame's empty `descriptionFileRoot`, adds `oneOf` CSS rule with `exportType: 'css-style-sheet'`, aliases codingame's css-loader/style-loader paths |
   | Test polyfills | `jsdom-svg-polyfill.ts` | inline `data:`-URL Node ESM loader hook that swallows transitive `.css`; stubs for Constructable Stylesheets, `CSS.escape`, `matchMedia`, `requestIdleCallback`, WebSocket |
   | Editor scaffolding | `code-debugger.component.ts`, `result-table-frame.component.spec.ts` | small follow-on edits to match new monaco types |
   | Dep cleanup | `package.json`, `LICENSE-binary`, `yarn.lock` | drop ~6 codingame side-deps + the `vscode` direct dep + resolution + retire R UDF; pin via the new v25 stack |
   
   Total non-`yarn.lock` diff: 12 files, **+527 / −169** lines.
   
   ## Worker bundling: why three trampolines
   
   ```
   code-editor.component.ts                                workers/editor.worker.ts (1 line)
     │                                                       │
     │  new Worker(new URL("./workers/editor.worker",         │  import "@codingame/monaco-vscode-editor-api/
     │              import.meta.url),                         │          esm/vs/editor/editor.worker.js";
     │             { type: "module" })                        │
     │                                                       │
     ↓                                                       ↓
     webpack 5: literal relative URL → emits worker chunk     codingame source becomes the
     esbuild  : same literal → resolves on-disk → bundles     bundled worker entry
                 the imported codingame module into specs
   ```
   
   Both extremes were tried. Inlining `new URL("@codingame/...", import.meta.url)` makes webpack happy but esbuild treats the spec as a literal relative URL and the spec pre-bundle fails. A `fileReplacements`-swapped factory file works but adds an `angular.json` delta. Trampolines satisfy both bundlers with zero `angular.json` change.
   
   ## What gets dropped
   
   | | Why |
   |---|---|
   | `@codingame/monaco-vscode-textmate-service-override` | now a transitive of the v25 wrapper; not needed at top level |
   | `@codingame/monaco-vscode-theme-defaults-default-extension` | same — pulled in transitively by the language extensions |
   | `@codingame/monaco-vscode-r-default-extension` | upstream stopped publishing; R UDF editor retired |
   | `vscode` (package alias + `resolutions`) | v10 no longer needs the alias for type-only `vscode.Uri` references |
   | `webpack-bundle-analyzer` + `analyze` script | dead — script never ran in CI |
   | `content-disposition` + `@types/content-disposition` | dead `require` in `download.service.ts`, never read |
   
   ## Verification
   
   - [x] `yarn install` resolves cleanly
   - [x] `yarn build` exits 0; worker chunks identical hashes/sizes (~1.3 MB textmate, ~518 KB ext-host, ~220 KB editor)
   - [x] `yarn test` stays at **63 / 269** spec parity
   - [ ] Smoke-test the Python UDF editor (language detection, syntax colour first paint, breakpoints, collaborative cursors)
   
   ## Test plan
   
   - [ ] Open a workflow with a Python UDF — confirm syntax highlighting renders correctly on first open
   - [ ] Set / clear / step through a breakpoint with the debugger panel
   - [ ] Verify the AI-assistant "Add Type Annotation" / "Add All Type Annotations" actions still work
   - [ ] Check that two browser tabs editing the same workflow show each other's coeditor cursors
   - [ ] Run a Java UDF and confirm the editor shows Java syntax (no LSP, just grammar)
   
   ## Notes for reviewers
   
   - This branch overlaps with #4980 (drop unused `content-disposition` dep). Once #4980 lands, rebasing this branch will auto-resolve those lines (the duplicate-removal commit becomes a no-op for them).
   - The umbrella issue (#4996) carries the high-level rationale; this PR is the implementation.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4412986908

   do we want to add tests before we upgrade? just want to make sure things are not broken.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4883941326

   Tracked down the broken syntax highlighting / `cmd+/` / theme CSS from my comment above. Root cause is in the webpack build path.
   
   ### Root cause
   
   `ng serve` and `yarn build` go through webpack (`@angular-builders/custom-webpack`), where Angular's base config sets `module.parser.javascript.url: false` and `worker: false` (no `webWorkerTsConfig` in angular.json). With both off, webpack leaves `new URL(..., import.meta.url)` untransformed and inlines `import.meta.url` as a **build-machine `file://` path**. From the actual dev-server compiled output:
   
   ```js
   fetch(new URL('../../../../../../../external/vscode-oniguruma/release/onig.wasm',
     "file:///Users/.../node_modules/@codingame/monaco-vscode-textmate-service-override/..."))
   
   new Worker(new URL("./workers/editor.worker",
     "file:///Users/.../src/app/workspace/component/code-editor-dialog/code-editor.component.ts"))
   ```
   
   In a real browser both fail: the onig.wasm fetch dies → the TextMate tokenizer never starts → no Python/Java highlighting; all three worker trampolines fail to spawn → language configuration and theming degrade (`cmd+/` dead, unreadable token colors).
   
   This PR removed the previous `parser: { javascript: { url: true } }` override in `custom-webpack.config.js` — it was there precisely for the wasm case (see [angular-cli#24617](https://github.com/angular/angular-cli/issues/24617)) — and `worker` parsing has never been enabled in the webpack builds.
   
   ### Why CI stayed green
   
   The vitest specs (including the browser-mode ones) run through esbuild (`@angular/build:unit-test`), which natively supports both `new URL(...)` assets and `new Worker(new URL(...))`. Only the webpack-based `ng serve` / `yarn build` are affected — so every test passes while the served app is broken. The "worker chunks identical hashes/sizes" note in the PR description is worth re-checking: with `parser.javascript.worker: false`, webpack cannot have emitted those chunks.
   
   ### Fix (verified against the dev-server output)
   
   Restore/extend the parser override in `frontend/custom-webpack.config.js`:
   
   ```js
   module: {
     rules: [ /* unchanged */ ],
     parser: {
       javascript: {
         url: true,    // onig.wasm is fetched via new URL(..., import.meta.url)
         worker: true, // bundle the ./workers/* trampolines as worker chunks
       },
     },
   },
   ```
   
   With this applied, the compiled output contains zero `file://` references; onig.wasm is emitted as a hashed asset (466 KB, served 200) and the three trampolines become real worker chunks (editor 384 KB, extension-host 4.4 MB, textmate 107 KB).
   
   One gotcha for anyone re-testing: webpack's persistent cache (`.angular/cache`) does **not** track `custom-webpack.config.js`, so clear it before restarting `ng serve` — otherwise the stale broken output keeps being served.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4484860640

   Not planned.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3231682288


##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();

Review Comment:
   False positive — `workflowVersionStreamSubject` is initialized at the class-field declaration:
   
   ```ts
   private workflowVersionStreamSubject: Subject<void> = new Subject<void>();
   ```
   
   The initializer runs during instance construction (before any user code can observe the field), so the subject is never `undefined` by the time `ngOnDestroy` runs. The previous `isDefined(...)` guard was dead code; removing it doesn't introduce a new failure mode. The field is also not optional (`Subject<void>`, not `Subject<void> \| undefined`), so the type system enforces this too.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();
   }
 
   /**
    * Specify the co-editor's cursor style. This step is missing from MonacoBinding.
+   *
+   * `coeditor.clientId` and `coeditor.color` come from yjs awareness state,
+   * which any peer can write to. Both are interpolated into a `<style>` tag
+   * passed through `bypassSecurityTrustHtml`, so anything that escapes the
+   * tag would land in the page as raw HTML. Validate both to a tight
+   * allow-list (digits-only id, hex / `rgb(a)` / `hsl(a)` colour) and bail
+   * out otherwise; nothing else should reach the sanitiser.
    * @param coeditor
    */
   public getCoeditorCursorStyles(coeditor: Coeditor) {
-    const textCSS =
+    if (!CodeEditorComponent.SAFE_CLIENT_ID.test(coeditor.clientId)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    if (!coeditor.color || !CodeEditorComponent.SAFE_CSS_COLOR.test(coeditor.color)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    const id = coeditor.clientId;
+    const color = coeditor.color;
+    const selectionBg = color.replace("0.8", "0.5");
+    return this.sanitizer.bypassSecurityTrustHtml(
       "<style>" +
-      `.yRemoteSelection-${coeditor.clientId} { background-color: ${coeditor.color?.replace("0.8", "0.5")}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId}::after { border-color: ${coeditor.color}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId} { border-color: ${coeditor.color}}` +
-      "</style>";
-    return this.sanitizer.bypassSecurityTrustHtml(textCSS);
+        `.yRemoteSelection-${id} { background-color: ${selectionBg}}` +
+        `.yRemoteSelectionHead-${id}::after { border-color: ${color}}` +
+        `.yRemoteSelectionHead-${id} { border-color: ${color}}` +
+        "</style>"
+    );
   }
 
-  private getFileSuffixByLanguage(language: string): string {
-    switch (language.toLowerCase()) {
-      case "python":
-        return ".py";
-      case "r":
-        return ".r";
-      case "javascript":
-        return ".js";
-      case "java":
-        return ".java";
-      default:
-        return ".py";
-    }
+  // Allow-lists for the two awareness-derived values that flow into a `<style>`
+  // tag in `getCoeditorCursorStyles`. yjs serialises clientIDs as the decimal
+  // form of a 32-bit integer, and the colours we generate elsewhere only use
+  // these notations — anything outside these patterns is rejected.
+  private static readonly SAFE_CLIENT_ID = /^\d{1,10}$/;
+  private static readonly SAFE_CSS_COLOR = /^(?:#[0-9a-fA-F]{3,8}|rgba?\([\d.,\s]+\)|hsla?\([\d.,%\s]+\))$/;
+
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      try {
+        const apiConfig: MonacoVscodeApiConfig = {
+          $type: "extended",
+          viewsConfig: { $type: "EditorService" },
+          userConfiguration: {
+            json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+          },
+          // Wire workers via thin trampolines in `./workers/`. Webpack 5 only
+          // treats `new Worker(new URL("./relative", import.meta.url))` as a
+          // worker entry point and bundles the dep tree into a chunk; bare
+          // package URLs `new URL("@codingame/...", import.meta.url)` become
+          // static assets whose relative imports 404 at runtime. Esbuild
+          // (used by @angular/build:unit-test) also requires a real on-disk
+          // file for the URL spec — trampolines satisfy both bundlers.
+          monacoWorkerFactory: () => {
+            const env = getEnhancedMonacoEnvironment();
+            env.getWorker = (_workerId: string, label: string): Worker => {
+              switch (label) {
+                case "editorWorkerService":
+                  return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+                case "extensionHostWorkerMain":
+                  return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+                case "TextMateWorker":
+                  return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+                default:
+                  throw new Error(`No worker configured for label: ${label}`);
+              }
+            };

Review Comment:
   False positive — `monacoWorkerFactory` is typed as `(logger?: ILogger) => void` in `monaco-languageclient/vscodeApiWrapper`:
   
   \`\`\`ts
   // node_modules/monaco-languageclient/lib/vscode/config.d.ts:40
   monacoWorkerFactory?: (logger?: ILogger) => void;
   \`\`\`
   
   The wrapper invokes it for side effects only. We pull the enhanced env via `getEnhancedMonacoEnvironment()`, which returns the **shared** `globalThis.MonacoEnvironment` object — mutating `env.getWorker = …` on it lands on the same object the rest of the codingame stack reads. No return value is expected or used. Verified the upstream TypeFox angular example does the same thing (via `configureDefaultWorkerFactory`, which also returns `void`).



##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -158,36 +199,34 @@ class InertWebSocket {
   onerror: AnyFn | null = null;
   onmessage: AnyFn | null = null;
   onclose: AnyFn | null = null;
-  send(): void {}
-  close(): void {}
-  addEventListener(): void {}
-  removeEventListener(): void {}
-  dispatchEvent(): boolean {
-    return false;
-  }
+  send = () => undefined;
+  close = () => undefined;
+  addEventListener = () => undefined;
+  removeEventListener = () => undefined;
+  dispatchEvent = () => false;
   constructor(_url?: string, _protocols?: string | string[]) {}
 }
-(globalThis as unknown as { WebSocket: typeof InertWebSocket }).WebSocket = InertWebSocket;
+G.WebSocket = InertWebSocket;
 
-/**
- * NgZorro's NzIconService dynamically fetches icon SVGs over HTTP from
- * `/assets/...` when the icon isn't pre-registered. jsdom's XHR
- * implementation rejects those requests with an `AggregateError`, and
- * downstream the icon lookup re-throws as `IconNotFoundError`. Vitest
- * catches both as unhandled errors, which CI treats as a hard failure
- * (locally Vitest only reports them as non-fatal warnings).
- *
- * Stubbing every spec with `NzIconModule.forChild([...])` for every
- * icon its template uses is impractical — there are dozens. Instead,
- * suppress the two specific error patterns at the process level: they
- * originate inside ngZorro's icon plumbing and don't affect the
- * assertions specs actually make.
- */
+// Process-level error suppression for benign ngZorro icon / codingame
+// extension fetches. NzIconService fetches icon SVGs from `/assets/...` when
+// the icon isn't pre-registered; jsdom's XHR rejects with `AggregateError`
+// and the lookup re-throws as `IconNotFoundError`. Vitest catches both as
+// unhandled errors and CI treats that as a hard failure. Stubbing every spec
+// with `NzIconModule.forChild([...])` is impractical — dozens of icons.
+// Suppress just these patterns at the process level.
 function isBenignIconError(err: unknown): boolean {
   const msg = err instanceof Error ? err.message : String(err);
+  const stack = err instanceof Error ? err.stack ?? "" : "";
   return (
     msg.includes("[@ant-design/icons-angular]") ||
-    (err instanceof Error && err.name === "AggregateError" && /xhr-utils/.test(err.stack ?? ""))
+    (err instanceof Error && err.name === "AggregateError" && /xhr-utils/.test(stack)) ||
+    // codingame v25 default extensions try to fetch their bundled themes /
+    // language configs over `extension-file://` URIs at activation time.
+    // jsdom can't resolve the scheme so the fetch rejects, but it's cosmetic
+    // — the spec body never depends on the theme/grammar being applied.
+    msg.includes("extension-file://") ||
+    /workbenchThemeService|monaco-vscode-theme|monaco-vscode-.*-default-extension/.test(stack)
   );
 }
 process.on("uncaughtException", err => {

Review Comment:
   Good catch — fixed in 67bcc5b863 (now in 29cbba5a1c after a rebase on top of main).
   
   Gated both `process.on("uncaughtException", …)` and `process.on("unhandledRejection", …)` behind the same `Symbol.for("texera.processErrorHandlersInstalled")` flag on `globalThis` we use for the CSS loader hook. Without this, vitest re-evaluating `setupFiles` once per spec was attaching fresh handlers each time — Node warns with `MaxListenersExceededWarning` after ~11 specs and the benign-error filter reruns on every captured rejection.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3212704192


##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -228,53 +224,121 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     }
   }
 
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    if (CodeEditorComponent.apiWrapperStarted) {
+      return;
+    }
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      const apiConfig: MonacoVscodeApiConfig = {
+        $type: "extended",
+        viewsConfig: { $type: "EditorService" },
+        userConfiguration: {
+          json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+        },
+        // Wire up the workers monaco-vscode-api spawns at runtime (editor,
+        // extension host, textmate). Each `new Worker(new URL(...))` literal
+        // points at a thin trampoline in `./workers/` that just re-imports the
+        // codingame-shipped worker entry. Two reasons for the indirection:
+        //   1. webpack 5 only treats `new Worker(new URL("./relative", import.meta.url))`
+        //      as a worker entry point (so it bundles the dep tree into a chunk);
+        //      `new URL("@codingame/...", import.meta.url)` would just emit a
+        //      static asset whose own relative imports 404 at runtime.
+        //   2. the test pipeline (esbuild via @angular/build:unit-test) resolves
+        //      `new URL(spec, import.meta.url)` literally relative to the source
+        //      file, so the spec needs to point at a real on-disk file. The
+        //      trampolines satisfy both bundlers.
+        monacoWorkerFactory: () => {
+          const env = getEnhancedMonacoEnvironment();
+          env.getWorker = (_workerId: string, label: string): Worker => {
+            switch (label) {
+              case "editorWorkerService":
+                return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+              case "extensionHostWorkerMain":
+                return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+              case "TextMateWorker":
+                return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+              default:
+                throw new Error(`No worker configured for label: ${label}`);
+            }
+          };
+        },
+      };
+      await new MonacoVscodeApiWrapper(apiConfig).start();
+
+      // Load AND fully activate the default language extensions. Each module
+      // exports a `whenReady()` that resolves after its TextMate grammar /
+      // configuration files are registered with the host — without waiting,
+      // the editor opens with every token rendered as the default `mtk1`
+      // class (no syntax colours). Dynamic `import(...)` is used so the
+      // Angular build pipeline doesn't tree-shake the side-effect imports.
+      const extensions = await Promise.all([
+        import("@codingame/monaco-vscode-python-default-extension"),
+        import("@codingame/monaco-vscode-java-default-extension"),
+      ]);
+      await Promise.all(extensions.map(ext => ext.whenReady?.()));
+
+      CodeEditorComponent.apiWrapperStarted = true;
+    })();
+    return CodeEditorComponent.apiWrapperStartPromise;
+  }

Review Comment:
   `ensureVscodeApiStarted()` caches the first `apiWrapperStartPromise`, but if wrapper startup or extension activation fails once, the cached promise stays rejected and future calls will never retry (and `apiWrapperStarted` will remain false). Consider wrapping the startup sequence in try/catch and clearing `apiWrapperStartPromise` (and/or setting a failure flag) on rejection so a later editor open can retry or surface a clearer error.



##########
frontend/custom-webpack.config.js:
##########
@@ -19,15 +19,85 @@
 
 const { LicenseWebpackPlugin } = require("license-webpack-plugin");
 
+// Workaround for license-webpack-plugin v4 crashing with `ENOENT: scandir ''` when a
+// bundled module has no resolvable on-disk directory. Some @codingame/monaco-vscode-*
+// sub-modules surface as virtual entries (descriptionFileRoot === '') after the v25
+// upgrade. Make listPaths/readFileAsUtf8/isDirectory tolerant of empty paths.
+{
+  const fs = require("fs");

Review Comment:
   `const fs = require("fs")` is declared but unused in this file. Removing it avoids confusion about whether filesystem calls are expected here.
   



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -228,53 +224,121 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     }
   }
 
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    if (CodeEditorComponent.apiWrapperStarted) {
+      return;
+    }
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      const apiConfig: MonacoVscodeApiConfig = {
+        $type: "extended",
+        viewsConfig: { $type: "EditorService" },
+        userConfiguration: {
+          json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+        },
+        // Wire up the workers monaco-vscode-api spawns at runtime (editor,
+        // extension host, textmate). Each `new Worker(new URL(...))` literal
+        // points at a thin trampoline in `./workers/` that just re-imports the
+        // codingame-shipped worker entry. Two reasons for the indirection:
+        //   1. webpack 5 only treats `new Worker(new URL("./relative", import.meta.url))`
+        //      as a worker entry point (so it bundles the dep tree into a chunk);
+        //      `new URL("@codingame/...", import.meta.url)` would just emit a
+        //      static asset whose own relative imports 404 at runtime.
+        //   2. the test pipeline (esbuild via @angular/build:unit-test) resolves
+        //      `new URL(spec, import.meta.url)` literally relative to the source
+        //      file, so the spec needs to point at a real on-disk file. The
+        //      trampolines satisfy both bundlers.
+        monacoWorkerFactory: () => {
+          const env = getEnhancedMonacoEnvironment();
+          env.getWorker = (_workerId: string, label: string): Worker => {
+            switch (label) {
+              case "editorWorkerService":
+                return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+              case "extensionHostWorkerMain":
+                return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+              case "TextMateWorker":
+                return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+              default:
+                throw new Error(`No worker configured for label: ${label}`);
+            }
+          };
+        },
+      };
+      await new MonacoVscodeApiWrapper(apiConfig).start();
+
+      // Load AND fully activate the default language extensions. Each module
+      // exports a `whenReady()` that resolves after its TextMate grammar /
+      // configuration files are registered with the host — without waiting,
+      // the editor opens with every token rendered as the default `mtk1`
+      // class (no syntax colours). Dynamic `import(...)` is used so the
+      // Angular build pipeline doesn't tree-shake the side-effect imports.
+      const extensions = await Promise.all([
+        import("@codingame/monaco-vscode-python-default-extension"),
+        import("@codingame/monaco-vscode-java-default-extension"),
+      ]);
+      await Promise.all(extensions.map(ext => ext.whenReady?.()));
+
+      CodeEditorComponent.apiWrapperStarted = true;
+    })();
+    return CodeEditorComponent.apiWrapperStartPromise;
+  }
+
   /**
    * Create a Monaco editor and connect it to MonacoBinding.
    * @private
    */
   private initializeMonacoEditor() {
     const fileSuffix = this.getFileSuffixByLanguage(this.language);
-    const userConfig: UserConfig = {
-      wrapperConfig: {
-        editorAppConfig: {
-          $type: "extended",
-          codeResources: {
-            main: {
-              text: this.code?.toString() ?? "",
-              uri: `in-memory-${this.currentOperatorId}.${fileSuffix}`,
-            },
-          },
-          userConfiguration: {
-            json: JSON.stringify({
-              "workbench.colorTheme": "Default Dark Modern",
-            }),
-          },
+    const editorAppConfig: EditorAppConfig = {
+      codeResources: {
+        modified: {
+          text: this.code?.toString() ?? "",
+          uri: `in-memory-${this.currentOperatorId}${fileSuffix}`,
         },
       },
     };
 
-    // optionally, configure python language client.
-    // it may fail if no valid connection is established, yet the failure would be ignored.
     const languageServerWebsocketUrl = getWebsocketUrl(
       "/python-language-server",
       this.config.env.pythonLanguageServerPort
     );
-    if (this.language === "python") {
-      userConfig.languageClientConfig = {
-        languageId: this.language,
-        options: {
-          $type: "WebSocketUrl",
-          url: languageServerWebsocketUrl,
-        },
-      };
-    }
 
-    // init monaco editor, optionally with attempt on language client.
-    from(this.editorWrapper.initAndStart(userConfig, this.editorElement.nativeElement))
+    const startEditor = async (): Promise<MonacoEditor | undefined> => {
+      await CodeEditorComponent.ensureVscodeApiStarted();
+      this.editorApp = new EditorApp(editorAppConfig);
+      await this.editorApp.start(this.editorElement.nativeElement);
+
+      // optionally, configure python language client.
+      // it may fail if no valid connection is established, yet the failure would be ignored.
+      if (this.language === "python") {
+        const lcConfig: LanguageClientConfig = {
+          languageId: this.language,
+          connection: {
+            options: {
+              $type: "WebSocketUrl",
+              url: languageServerWebsocketUrl,
+            },
+          },
+          clientOptions: {
+            documentSelector: [this.language],
+          },
+        };
+        this.languageClientWrapper = new LanguageClientWrapper(lcConfig);
+        await this.languageClientWrapper.start();
+      }
+      return this.editorApp.getEditor();
+    };
+
+    from(startEditor())
       .pipe(
         timeout(LANGUAGE_SERVER_CONNECTION_TIMEOUT_MS),
-        switchMap(() => of(this.editorWrapper.getEditor())),
-        catchError(() => of(this.editorWrapper.getEditor())),
+        // Language-server connection may time out (or fail) — fall back to the editor
+        // that was already mounted before `languageClientWrapper.start()` was awaited.
+        catchError(() => of(this.editorApp?.getEditor())),
         filter(isDefined),
         untilDestroyed(this)
       )

Review Comment:
   `LANGUAGE_SERVER_CONNECTION_TIMEOUT_MS` is now applied to the entire `startEditor()` promise, which includes `ensureVscodeApiStarted()` (MonacoVscodeApiWrapper.start + extension activation) and `EditorApp.start()`. On first load, that initialization can easily exceed 1s; if the timeout fires before `EditorApp.start()` completes, `catchError(() => of(this.editorApp?.getEditor()))` will likely emit `undefined` and the subscription never runs (so MonacoBinding, actions, debugger setup never attach). Consider moving the timeout to only wrap `languageClientWrapper.start()` (or otherwise ensure the editor start path is not subject to this timeout), and keep the editor initialization always awaited.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,38 +184,37 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();
   }
 
   /**
    * Specify the co-editor's cursor style. This step is missing from MonacoBinding.
    * @param coeditor
    */
   public getCoeditorCursorStyles(coeditor: Coeditor) {
-    const textCSS =
-      "<style>" +
-      `.yRemoteSelection-${coeditor.clientId} { background-color: ${coeditor.color?.replace("0.8", "0.5")}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId}::after { border-color: ${coeditor.color}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId} { border-color: ${coeditor.color}}` +
-      "</style>";
-    return this.sanitizer.bypassSecurityTrustHtml(textCSS);
+    const id = coeditor.clientId;
+    const color = coeditor.color;
+    const selectionBg = color?.replace("0.8", "0.5");
+    return this.sanitizer.bypassSecurityTrustHtml(
+      `<style>` +
+        `.yRemoteSelection-${id} { background-color: ${selectionBg}}` +
+        `.yRemoteSelectionHead-${id}::after { border-color: ${color}}` +
+        `.yRemoteSelectionHead-${id} { border-color: ${color}}` +
+        `</style>`
+    );

Review Comment:
   `getCoeditorCursorStyles` uses `bypassSecurityTrustHtml` to inject a `<style>` tag containing interpolated `coeditor.clientId` and `coeditor.color`. In collaborative mode, those values originate from shared awareness state and can be tampered with by a malicious client, enabling CSS/HTML injection (e.g., breaking out of the style tag). Prefer generating styles via DOM APIs (e.g., `CSSStyleSheet`/`adoptedStyleSheets` in the real app) or strictly validating/escaping `clientId` (CSS identifier) and `color` (allow only known-safe formats like `hsl(...)`/`#RRGGBB`).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4484846133

   > Also the test coverage is not enough.
   > 
   > > Patch coverage is 47.14286% with 37 lines in your changes missing coverage. Please review.
   > 
   > I especially want to make sure the following can still work. If we do not currently have test coverage, it will be ideal to add tests for them first before upgrade.
   > 
   > 1. language client features can still work
   > 2. our custom editor logics (e.g., frozen editor during execution, unfreeze when paused).
   > 3. debugger logics (with Monaco-breakpoint)
   
   I tried to improve the general test coverage for the editor in PR #5004. I also tested the editor features manually for this PR. If full test coverage is required for all 3 points you mentioned before upgrading, I don't plan to move forward with this PR, as I don't have enough bandwidth. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4883749106

   Not sure if it just happens to my local, but the editor is not functioning as expected
   - highlighting css is problematic, cannot see code clearly
   - `command + /` cannot comment/uncomment code.
   - python syntax highlighting is not working 
   
   See recording here:
   https://github.com/user-attachments/assets/c6381d64-a545-4d45-937e-afaa6f0cd08b
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4530569436

   Tese cases added in PR #5191


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3264001613


##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.spec.ts:
##########
@@ -31,10 +31,10 @@ import { OperatorSchema } from "../../types/operator-schema.interface";
 import { of } from "rxjs";
 
 // Operator types that the constructor's language-detection branch must map
-// to a specific language. `RUDFSource` / `RUDF` -> `r`; the three V2 Python
-// types -> `python`; everything else -> `java`. Local to this spec so we
-// don't perturb the shared mock-workflow-data fixtures.
-const R_OPERATOR_TYPES = ["RUDFSource", "RUDF"];
+// to a specific language. The three V2 Python types -> `python`; everything
+// else (including the legacy `RUDF*` types) -> `java`, since R UDF editor
+// support was retired in this branch. Local to this spec so we don't

Review Comment:
   Reverted in f6536d790d — R UDF editor support is back. Added an `R_OPERATOR_TYPES` set alongside the Python one and a new `else if` branch in the constructor that maps `RUDFSource` / `RUDF` to `language = "r"`, plus `.r` through the two file-suffix call sites. The R operator types are kept on the frontend even though Texera proper no longer bundles the backend — when the non-apache R UDF plugin is installed, the editor opens those operators in R mode.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.spec.ts:
##########
@@ -52,7 +52,6 @@ const synthesizeSchema = (operatorType: string): OperatorSchema => ({ ...baseSch
 const augmentedSchemas: OperatorSchema[] = [
   ...mockOperatorMetaData.operators,
   ...PYTHON_OPERATOR_TYPES.map(synthesizeSchema),
-  ...R_OPERATOR_TYPES.map(synthesizeSchema),

Review Comment:
   Same fix in f6536d790d — `R_OPERATOR_TYPES = ["RUDFSource", "RUDF"]` is now back in the spec setup and the synthetic-schema augmentation includes both R operator types so `addOperator` accepts them.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.spec.ts:
##########
@@ -117,19 +116,11 @@ describe("CodeEditorComponent", () => {
     expect(fixture.componentInstance.currentOperatorId).toBe(mockJavaUDFPredicate.operatorID);
   });
 
-  // Language detection — the constructor maps `RUDFSource` / `RUDF` to `r`,
-  // the three V2-era Python operator types to `python`, and anything else
-  // to `java`. The exact branch lives in the constructor; the public
-  // `language` field is what the rest of the editor (LSP wiring, file-
-  // suffix selection) keys off.
-
-  R_OPERATOR_TYPES.forEach((operatorType, index) => {
-    it(`picks language="r" for operatorType=${operatorType}`, () => {
-      const fixture = makeFixture(buildPredicate(`r-${index}`, operatorType));
-      expect(fixture.componentInstance.language).toBe("r");
-      expect(fixture.componentInstance.languageTitle).toBe("R UDF");
-    });
-  });

Review Comment:
   Same fix in f6536d790d — added an `R_OPERATOR_TYPES.forEach(...)` test block that pins `language === "r"` and `languageTitle === "R UDF"` for each R operator type, parallel to the Python loop.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -143,18 +145,8 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
   ) {
     this.currentOperatorId = this.workflowActionService.getJointGraphWrapper().getCurrentHighlightedOperatorIDs()[0];
     const operatorType = this.workflowActionService.getTexeraGraph().getOperator(this.currentOperatorId).operatorType;
-
-    if (operatorType === "RUDFSource" || operatorType === "RUDF") {
-      this.setLanguage("r");
-    } else if (
-      operatorType === "PythonUDFV2" ||
-      operatorType === "PythonUDFSourceV2" ||
-      operatorType === "DualInputPortsPythonUDFV2"
-    ) {
-      this.setLanguage("python");
-    } else {
-      this.setLanguage("java");
-    }
+    this.language = CodeEditorComponent.PYTHON_OPERATOR_TYPES.has(operatorType) ? "python" : "java";
+    this.languageTitle = `${this.language[0].toUpperCase()}${this.language.slice(1)} UDF`;

Review Comment:
   Fixed in f6536d790d — the constructor now does:
   
   ```ts
   if (CodeEditorComponent.PYTHON_OPERATOR_TYPES.has(operatorType)) {
     this.language = "python";
   } else if (CodeEditorComponent.R_OPERATOR_TYPES.has(operatorType)) {
     this.language = "r";
   } else {
     this.language = "java";
   }
   ```
   
   so `RUDFSource` / `RUDF` route to `r` like before. No `@codingame/monaco-vscode-r-default-extension` is loaded (upstream stopped publishing a v25-compatible build) — the editor opens in R mode without TextMate syntax colours but the model URI carries the `.r` suffix so any future language-client config keys off it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3524600922


##########
frontend/package.json:
##########
@@ -9,7 +9,6 @@
     "start": "concurrently --kill-others \"npx y-websocket\" \"ng serve\"",
     "build": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration=production --progress=false --source-map=false",
     "build:ci": "node --max-old-space-size=8192 ./node_modules/nx/dist/bin/nx.js build --configuration=production --progress=false --source-map=false",
-    "analyze": "ng build --configuration=production --stats-json && webpack-bundle-analyzer dist/stats.json",

Review Comment:
   Opened #6156 to remove the `analyze` script (and its `webpack-bundle-analyzer` dep) on its own, so this PR stays scoped to the monaco upgrade.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3212865677


##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -228,53 +224,121 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     }
   }
 
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    if (CodeEditorComponent.apiWrapperStarted) {
+      return;
+    }
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      const apiConfig: MonacoVscodeApiConfig = {
+        $type: "extended",
+        viewsConfig: { $type: "EditorService" },
+        userConfiguration: {
+          json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+        },
+        // Wire up the workers monaco-vscode-api spawns at runtime (editor,
+        // extension host, textmate). Each `new Worker(new URL(...))` literal
+        // points at a thin trampoline in `./workers/` that just re-imports the
+        // codingame-shipped worker entry. Two reasons for the indirection:
+        //   1. webpack 5 only treats `new Worker(new URL("./relative", import.meta.url))`
+        //      as a worker entry point (so it bundles the dep tree into a chunk);
+        //      `new URL("@codingame/...", import.meta.url)` would just emit a
+        //      static asset whose own relative imports 404 at runtime.
+        //   2. the test pipeline (esbuild via @angular/build:unit-test) resolves
+        //      `new URL(spec, import.meta.url)` literally relative to the source
+        //      file, so the spec needs to point at a real on-disk file. The
+        //      trampolines satisfy both bundlers.
+        monacoWorkerFactory: () => {
+          const env = getEnhancedMonacoEnvironment();
+          env.getWorker = (_workerId: string, label: string): Worker => {
+            switch (label) {
+              case "editorWorkerService":
+                return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+              case "extensionHostWorkerMain":
+                return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+              case "TextMateWorker":
+                return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+              default:
+                throw new Error(`No worker configured for label: ${label}`);
+            }
+          };
+        },
+      };
+      await new MonacoVscodeApiWrapper(apiConfig).start();
+
+      // Load AND fully activate the default language extensions. Each module
+      // exports a `whenReady()` that resolves after its TextMate grammar /
+      // configuration files are registered with the host — without waiting,
+      // the editor opens with every token rendered as the default `mtk1`
+      // class (no syntax colours). Dynamic `import(...)` is used so the
+      // Angular build pipeline doesn't tree-shake the side-effect imports.
+      const extensions = await Promise.all([
+        import("@codingame/monaco-vscode-python-default-extension"),
+        import("@codingame/monaco-vscode-java-default-extension"),
+      ]);
+      await Promise.all(extensions.map(ext => ext.whenReady?.()));
+
+      CodeEditorComponent.apiWrapperStarted = true;
+    })();
+    return CodeEditorComponent.apiWrapperStartPromise;
+  }
+
   /**
    * Create a Monaco editor and connect it to MonacoBinding.
    * @private
    */
   private initializeMonacoEditor() {
     const fileSuffix = this.getFileSuffixByLanguage(this.language);
-    const userConfig: UserConfig = {
-      wrapperConfig: {
-        editorAppConfig: {
-          $type: "extended",
-          codeResources: {
-            main: {
-              text: this.code?.toString() ?? "",
-              uri: `in-memory-${this.currentOperatorId}.${fileSuffix}`,
-            },
-          },
-          userConfiguration: {
-            json: JSON.stringify({
-              "workbench.colorTheme": "Default Dark Modern",
-            }),
-          },
+    const editorAppConfig: EditorAppConfig = {
+      codeResources: {
+        modified: {
+          text: this.code?.toString() ?? "",
+          uri: `in-memory-${this.currentOperatorId}${fileSuffix}`,
         },
       },
     };
 
-    // optionally, configure python language client.
-    // it may fail if no valid connection is established, yet the failure would be ignored.
     const languageServerWebsocketUrl = getWebsocketUrl(
       "/python-language-server",
       this.config.env.pythonLanguageServerPort
     );
-    if (this.language === "python") {
-      userConfig.languageClientConfig = {
-        languageId: this.language,
-        options: {
-          $type: "WebSocketUrl",
-          url: languageServerWebsocketUrl,
-        },
-      };
-    }
 
-    // init monaco editor, optionally with attempt on language client.
-    from(this.editorWrapper.initAndStart(userConfig, this.editorElement.nativeElement))
+    const startEditor = async (): Promise<MonacoEditor | undefined> => {
+      await CodeEditorComponent.ensureVscodeApiStarted();
+      this.editorApp = new EditorApp(editorAppConfig);
+      await this.editorApp.start(this.editorElement.nativeElement);
+
+      // optionally, configure python language client.
+      // it may fail if no valid connection is established, yet the failure would be ignored.
+      if (this.language === "python") {
+        const lcConfig: LanguageClientConfig = {
+          languageId: this.language,
+          connection: {
+            options: {
+              $type: "WebSocketUrl",
+              url: languageServerWebsocketUrl,
+            },
+          },
+          clientOptions: {
+            documentSelector: [this.language],
+          },
+        };
+        this.languageClientWrapper = new LanguageClientWrapper(lcConfig);
+        await this.languageClientWrapper.start();
+      }
+      return this.editorApp.getEditor();
+    };
+
+    from(startEditor())
       .pipe(
         timeout(LANGUAGE_SERVER_CONNECTION_TIMEOUT_MS),
-        switchMap(() => of(this.editorWrapper.getEditor())),
-        catchError(() => of(this.editorWrapper.getEditor())),
+        // Language-server connection may time out (or fail) — fall back to the editor
+        // that was already mounted before `languageClientWrapper.start()` was awaited.
+        catchError(() => of(this.editorApp?.getEditor())),
         filter(isDefined),
         untilDestroyed(this)
       )

Review Comment:
   Good catch — fixed in 51b4fe5546.
   
   Pulled the timeout out of the rxjs pipeline and into a tight `Promise.race` around `languageClientWrapper.start()` only. The editor mount path (`ensureVscodeApiStarted()` + `EditorApp.start()`) is now always awaited to completion, and the rxjs pipeline is just `from(startEditor()).pipe(filter(isDefined), untilDestroyed(this))`. The unused `timeout` / `catchError` / `of` rxjs imports went with it.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -228,53 +224,121 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     }
   }
 
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    if (CodeEditorComponent.apiWrapperStarted) {
+      return;
+    }
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      const apiConfig: MonacoVscodeApiConfig = {
+        $type: "extended",
+        viewsConfig: { $type: "EditorService" },
+        userConfiguration: {
+          json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+        },
+        // Wire up the workers monaco-vscode-api spawns at runtime (editor,
+        // extension host, textmate). Each `new Worker(new URL(...))` literal
+        // points at a thin trampoline in `./workers/` that just re-imports the
+        // codingame-shipped worker entry. Two reasons for the indirection:
+        //   1. webpack 5 only treats `new Worker(new URL("./relative", import.meta.url))`
+        //      as a worker entry point (so it bundles the dep tree into a chunk);
+        //      `new URL("@codingame/...", import.meta.url)` would just emit a
+        //      static asset whose own relative imports 404 at runtime.
+        //   2. the test pipeline (esbuild via @angular/build:unit-test) resolves
+        //      `new URL(spec, import.meta.url)` literally relative to the source
+        //      file, so the spec needs to point at a real on-disk file. The
+        //      trampolines satisfy both bundlers.
+        monacoWorkerFactory: () => {
+          const env = getEnhancedMonacoEnvironment();
+          env.getWorker = (_workerId: string, label: string): Worker => {
+            switch (label) {
+              case "editorWorkerService":
+                return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+              case "extensionHostWorkerMain":
+                return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+              case "TextMateWorker":
+                return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+              default:
+                throw new Error(`No worker configured for label: ${label}`);
+            }
+          };
+        },
+      };
+      await new MonacoVscodeApiWrapper(apiConfig).start();
+
+      // Load AND fully activate the default language extensions. Each module
+      // exports a `whenReady()` that resolves after its TextMate grammar /
+      // configuration files are registered with the host — without waiting,
+      // the editor opens with every token rendered as the default `mtk1`
+      // class (no syntax colours). Dynamic `import(...)` is used so the
+      // Angular build pipeline doesn't tree-shake the side-effect imports.
+      const extensions = await Promise.all([
+        import("@codingame/monaco-vscode-python-default-extension"),
+        import("@codingame/monaco-vscode-java-default-extension"),
+      ]);
+      await Promise.all(extensions.map(ext => ext.whenReady?.()));
+
+      CodeEditorComponent.apiWrapperStarted = true;
+    })();
+    return CodeEditorComponent.apiWrapperStartPromise;
+  }

Review Comment:
   Fixed in 51b4fe5546.
   
   Wrapped the IIFE body in a try/catch and reset `apiWrapperStartPromise = undefined` before re-throwing, so a later open re-runs the start sequence instead of inheriting the rejection. `apiWrapperStarted` only flips to `true` on the success path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3213013104


##########
frontend/src/app/workspace/component/code-editor-dialog/code-debugger.component.ts:
##########
@@ -20,9 +20,6 @@
 import { AfterViewInit, Component, Input, ViewChild } from "@angular/core";
 import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy";
 import { SafeStyle } from "@angular/platform-browser";
-import "@codingame/monaco-vscode-python-default-extension";
-import "@codingame/monaco-vscode-r-default-extension";
-import "@codingame/monaco-vscode-java-default-extension";
 import { isDefined } from "../../../common/util/predicate";
 import * as monaco from "monaco-editor";
 import { MonacoBreakpoint } from "monaco-breakpoints";

Review Comment:
   Already done — see e8e67b56c7. Both `import "@codingame/monaco-vscode-{python,java}-default-extension"` lines were dropped from `code-debugger.component.ts`, and the centralized `ensureVscodeApiStarted()` in `code-editor.component.ts` (where the editor stack is actually instantiated) is the only place loading them now. The static side-effect imports on the debugger were leftover duplicates and are gone.



##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -18,22 +18,49 @@
  */
 
 /**
- * jsdom doesn't implement the SVG geometry APIs (`SVGSVGElement#createSVGMatrix`,
- * `createSVGPoint`, `createSVGTransform`, `getScreenCTM`, `getCTM`,
- * `getBBox`). jointjs reaches into these during graph layout and crashes
- * the spec build with `TypeError: svgDocument.createSVGMatrix is not a
- * function` etc.
- *
- * The stubs below return identity-ish geometry: matrices/points behave like
- * the identity, bounding boxes report zero dimensions. That's enough for
- * jointjs construction code to not throw; specs that actually depend on
- * accurate geometry should run under Vitest browser mode rather than
- * jsdom (tracked in #4861), but the bulk of the texera specs only need
- * jointjs to instantiate cleanly.
+ * Test-environment polyfills + setup hooks for jsdom + the Angular
+ * `@angular/build:unit-test` builder. Pulled in via `setupFiles` in
+ * `angular.json`. Each block below targets a specific gap that surfaces
+ * when the codingame monaco-vscode-* v25 stack or jointjs runs under
+ * jsdom; comments next to each block say which one.
  */
 
+// ───────────────────────────────────────────────────────────────────────────
+// Node ESM loader hook so every transitive `.css` import resolves to an empty
+// module. The unit-test builder pre-bundles spec files with `externalPackages:
+// true`, so imports like `monaco-languageclient` reach Node's native ESM
+// loader instead of Vite's transform pipeline — without the hook, every spec
+// that transitively loads the codingame v25 stack crashes with
+// `Unknown file extension ".css"`. The hook source lives inline as a `data:`
+// URL so we don't carry a sidecar `.mjs`. Must run before any spec body
+// imports the affected packages; `module.register` needs Node 20.6+ (the
+// project pins Node ≥ 24).
+import { register as registerLoader } from "node:module";
+
+const cssLoaderHookSource = `
+export function resolve(specifier, context, nextResolve) {
+  if (specifier.endsWith(".css") || /\\.css(\\?|$)/.test(specifier)) {
+    return {
+      url: "data:text/javascript,export%20default%20%7B%7D%3B",
+      shortCircuit: true,
+      format: "module",
+    };
+  }
+  return nextResolve(specifier, context);
+}
+`;
+registerLoader(`data:text/javascript;charset=utf-8,${encodeURIComponent(cssLoaderHookSource)}`);
+
 type AnyFn = (...args: unknown[]) => unknown;
 
+// ───────────────────────────────────────────────────────────────────────────
+// SVG geometry APIs (`SVGSVGElement#createSVGMatrix`, `createSVGPoint`,
+// `createSVGTransform`, `getScreenCTM`, `getCTM`, `getBBox`). jsdom doesn't
+// implement these and jointjs reaches into them during graph layout, so the
+// spec build crashes with `TypeError: svgDocument.createSVGMatrix is not a
+// function`. Stubs below return identity-ish geometry — enough for jointjs
+// construction code not to throw. Specs needing accurate geometry should
+// run under Vitest browser mode rather than jsdom (tracked in #4861).
 function fakeMatrix() {

Review Comment:
   Good catch — fixed in 33eea83c83.
   
   Vitest re-evaluates `setupFiles` once per spec file, so the unconditional `module.register(...)` was chaining a fresh `.css` ESM hook for every spec. Guarded the registration behind a `Symbol.for("texera.cssLoaderHookRegistered")` flag on `globalThis` so the hook is installed exactly once per process; subsequent setup invocations short-circuit before calling `register`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4411971312

   ## [Codecov](https://app.codecov.io/gh/apache/texera/pull/4997?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `43.33333%` with `34 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 42.73%. Comparing base ([`75ff07e`](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`45fd824`](https://app.codecov.io/gh/apache/texera/commit/45fd824ce0aa3fd4e3a87593ba682f91537af3b3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/texera/pull/4997?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...ponent/code-editor-dialog/code-editor.component.ts](https://app.codecov.io/gh/apache/texera/pull/4997?src=pr&el=tree&filepath=frontend%2Fsrc%2Fapp%2Fworkspace%2Fcomponent%2Fcode-editor-dialog%2Fcode-editor.component.ts&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZnJvbnRlbmQvc3JjL2FwcC93b3Jrc3BhY2UvY29tcG9uZW50L2NvZGUtZWRpdG9yLWRpYWxvZy9jb2RlLWVkaXRvci5jb21wb25lbnQudHM=) | 43.33% | [32 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/texera/pull/4997?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff            @@
   ##               main    #4997   +/-   ##
   =========================================
     Coverage     42.72%   42.73%           
     Complexity     2186     2186           
   =========================================
     Files          1031     1031           
     Lines         38152    38179   +27     
     Branches       4004     4002    -2     
   =========================================
   + Hits          16302    16317   +15     
   - Misses        20831    20846   +15     
   + Partials       1019     1016    -3     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | | *Carryforward flag |
   |---|---|---|---|
   | [access-control-service](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.53% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [agent-service](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `33.72% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [amber](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `43.22% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [computing-unit-managing-service](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `0.00% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [config-service](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `0.00% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [file-service](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `32.18% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [frontend](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `33.12% <43.33%> (+0.04%)` | :arrow_up: | |
   | [python](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `88.90% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [workflow-compiling-service](https://app.codecov.io/gh/apache/texera/pull/4997/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `47.72% <ø> (ø)` | | Carriedforward from [75ff07e](https://app.codecov.io/gh/apache/texera/commit/75ff07e36adcc626a91a41f96b78893e2d5e63c3?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   *This pull request uses carry forward flags. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/texera/pull/4997?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan merged PR #4997:
URL: https://github.com/apache/texera/pull/4997


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3264003975


##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();

Review Comment:
   The field has a class-field initializer:
   
   ```ts
   private workflowVersionStreamSubject: Subject<void> = new Subject<void>();
   ```
   
   so it's always defined by the time `ngOnDestroy` runs — the initializer fires during instance construction, before any user code can observe the instance. The type is also non-optional (`Subject<void>`, not `Subject<void> | undefined`), so the type system enforces this too. The `isDefined(...)` guard was dead code; removing it has no behavior change.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();
   }
 
   /**
    * Specify the co-editor's cursor style. This step is missing from MonacoBinding.
+   *
+   * `coeditor.clientId` and `coeditor.color` come from yjs awareness state,
+   * which any peer can write to. Both are interpolated into a `<style>` tag
+   * passed through `bypassSecurityTrustHtml`, so anything that escapes the
+   * tag would land in the page as raw HTML. Validate both to a tight
+   * allow-list (digits-only id, hex / `rgb(a)` / `hsl(a)` colour) and bail
+   * out otherwise; nothing else should reach the sanitiser.
    * @param coeditor
    */
   public getCoeditorCursorStyles(coeditor: Coeditor) {
-    const textCSS =
+    if (!CodeEditorComponent.SAFE_CLIENT_ID.test(coeditor.clientId)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    if (!coeditor.color || !CodeEditorComponent.SAFE_CSS_COLOR.test(coeditor.color)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    const id = coeditor.clientId;
+    const color = coeditor.color;
+    const selectionBg = color.replace("0.8", "0.5");
+    return this.sanitizer.bypassSecurityTrustHtml(
       "<style>" +
-      `.yRemoteSelection-${coeditor.clientId} { background-color: ${coeditor.color?.replace("0.8", "0.5")}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId}::after { border-color: ${coeditor.color}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId} { border-color: ${coeditor.color}}` +
-      "</style>";
-    return this.sanitizer.bypassSecurityTrustHtml(textCSS);
+        `.yRemoteSelection-${id} { background-color: ${selectionBg}}` +
+        `.yRemoteSelectionHead-${id}::after { border-color: ${color}}` +
+        `.yRemoteSelectionHead-${id} { border-color: ${color}}` +
+        "</style>"
+    );
   }
 
-  private getFileSuffixByLanguage(language: string): string {
-    switch (language.toLowerCase()) {
-      case "python":
-        return ".py";
-      case "r":
-        return ".r";
-      case "javascript":
-        return ".js";
-      case "java":
-        return ".java";
-      default:
-        return ".py";
-    }
+  // Allow-lists for the two awareness-derived values that flow into a `<style>`
+  // tag in `getCoeditorCursorStyles`. yjs serialises clientIDs as the decimal
+  // form of a 32-bit integer, and the colours we generate elsewhere only use
+  // these notations — anything outside these patterns is rejected.
+  private static readonly SAFE_CLIENT_ID = /^\d{1,10}$/;
+  private static readonly SAFE_CSS_COLOR = /^(?:#[0-9a-fA-F]{3,8}|rgba?\([\d.,\s]+\)|hsla?\([\d.,%\s]+\))$/;
+
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      try {
+        const apiConfig: MonacoVscodeApiConfig = {
+          $type: "extended",
+          viewsConfig: { $type: "EditorService" },
+          userConfiguration: {
+            json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+          },
+          // Wire workers via thin trampolines in `./workers/`. Webpack 5 only
+          // treats `new Worker(new URL("./relative", import.meta.url))` as a
+          // worker entry point and bundles the dep tree into a chunk; bare
+          // package URLs `new URL("@codingame/...", import.meta.url)` become
+          // static assets whose relative imports 404 at runtime. Esbuild
+          // (used by @angular/build:unit-test) also requires a real on-disk
+          // file for the URL spec — trampolines satisfy both bundlers.
+          monacoWorkerFactory: () => {
+            const env = getEnhancedMonacoEnvironment();
+            env.getWorker = (_workerId: string, label: string): Worker => {
+              switch (label) {
+                case "editorWorkerService":
+                  return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+                case "extensionHostWorkerMain":
+                  return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+                case "TextMateWorker":
+                  return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+                default:
+                  throw new Error(`No worker configured for label: ${label}`);
+              }
+            };
+          },
+        };
+        await new MonacoVscodeApiWrapper(apiConfig).start();
+
+        // Load AND fully activate the default language extensions. Each
+        // module exports a `whenReady()` that resolves after its TextMate
+        // grammar / configuration files are registered with the host —
+        // without waiting, the editor opens with every token rendered as
+        // the default `mtk1` class (no syntax colours). Dynamic `import(...)`
+        // is used so the Angular build pipeline doesn't tree-shake the
+        // side-effect imports.
+        const extensions = await Promise.all([
+          import("@codingame/monaco-vscode-python-default-extension"),
+          import("@codingame/monaco-vscode-java-default-extension"),
+        ]);

Review Comment:
   They're the two codingame default-extension packages (`@codingame/monaco-vscode-python-default-extension` and `…-java-default-extension`). They register the TextMate grammar + language configuration the editor uses at runtime to syntax-highlight Python / Java code — the editor can technically open without them, but you'd lose colours and language detection.
   
   They're dynamic `import(...)` rather than top-level `import "..."` so the Angular build pipeline doesn't tree-shake the side-effect imports — and yes, they appear in `dist/3rdpartylicenses.json` and therefore must stay in `LICENSE-binary`. No way to avoid the LICENSE-binary entry while keeping syntax highlighting; both packages are MIT.



##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -17,128 +17,183 @@
  * under the License.
  */
 
-/**
- * jsdom doesn't implement the SVG geometry APIs (`SVGSVGElement#createSVGMatrix`,
- * `createSVGPoint`, `createSVGTransform`, `getScreenCTM`, `getCTM`,
- * `getBBox`). jointjs reaches into these during graph layout and crashes
- * the spec build with `TypeError: svgDocument.createSVGMatrix is not a
- * function` etc.
- *
- * The stubs below return identity-ish geometry: matrices/points behave like
- * the identity, bounding boxes report zero dimensions. That's enough for
- * jointjs construction code to not throw; specs that actually depend on
- * accurate geometry should run under Vitest browser mode rather than
- * jsdom (tracked in #4861), but the bulk of the texera specs only need
- * jointjs to instantiate cleanly.
- */
+// Test-environment polyfills + setup hooks for jsdom + the Angular
+// `@angular/build:unit-test` builder. Pulled in via `setupFiles` in
+// `angular.json`. Each block below patches one specific gap that surfaces
+// when the codingame monaco-vscode-* v25 stack or jointjs runs under jsdom.
+
+// Node ESM loader hook so every transitive `.css` import resolves to an empty
+// module. The unit-test builder pre-bundles spec files with `externalPackages:
+// true`, so imports like `monaco-languageclient` reach Node's native ESM
+// loader instead of Vite's transform pipeline — without the hook, every spec
+// that transitively loads the codingame v25 stack crashes with
+// `Unknown file extension ".css"`. Inline as a `data:` URL so we don't carry
+// a sidecar `.mjs`. Vitest re-evaluates this setup file once per spec file,
+// so we gate the registration with a `globalThis` flag — `module.register`
+// chains every call, and we don't want N hooks doing identical work for N
+// specs. Must run before any spec body imports the affected packages;
+// `module.register` needs Node 20.6+ (project pins Node ≥ 24).

Review Comment:
   Tightened in f6536d790d. 14 lines → 7 lines. Same content, less prose.



##########
frontend/src/jsdom-svg-polyfill.ts:
##########


Review Comment:
   Yes — most of the polyfill is monaco-languageclient-v10-driven. The codingame v25 stack the new client pulls in calls into a bunch of browser APIs jsdom doesn't ship: Constructable Stylesheets (`new CSSStyleSheet().replaceSync(...)`), `CSS.escape`, `matchMedia`, `requestIdleCallback`, and the `extension-file://` fetch in language-extension activation. Each was crashing spec discovery on the v10 branch until the stub landed.
   
   The only blocks that predate this PR are the SVG geometry stubs (jointjs needed those long before the monaco upgrade) and the ngZorro icon error suppressor. Added a top-of-file comment in f6536d790d that calls this out explicitly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3264007098


##########
frontend/LICENSE-binary:
##########
@@ -247,30 +248,40 @@ Angular / npm packages:
   - @ant-design/icons-angular@21.0.0
   - @auth0/angular-jwt@5.1.0
   - @babel/runtime@7.29.2
-  - @codingame/monaco-vscode-api@8.0.4
-  - @codingame/monaco-vscode-base-service-override@8.0.4
-  - @codingame/monaco-vscode-configuration-service-override@8.0.4
-  - @codingame/monaco-vscode-editor-api@8.0.4
-  - @codingame/monaco-vscode-environment-service-override@8.0.4
-  - @codingame/monaco-vscode-extensions-service-override@8.0.4
-  - @codingame/monaco-vscode-files-service-override@8.0.4
-  - @codingame/monaco-vscode-host-service-override@8.0.4
-  - @codingame/monaco-vscode-java-default-extension@8.0.4
-  - @codingame/monaco-vscode-languages-service-override@8.0.4
-  - @codingame/monaco-vscode-layout-service-override@8.0.4
-  - @codingame/monaco-vscode-model-service-override@8.0.4
-  - @codingame/monaco-vscode-monarch-service-override@8.0.4
-  - @codingame/monaco-vscode-python-default-extension@8.0.4
-  - @codingame/monaco-vscode-quickaccess-service-override@8.0.4
-  - @codingame/monaco-vscode-r-default-extension@8.0.4
-  - @codingame/monaco-vscode-textmate-service-override@8.0.4
-  - @codingame/monaco-vscode-theme-defaults-default-extension@8.0.4
-  - @codingame/monaco-vscode-theme-service-override@8.0.4
+  - @codingame/monaco-vscode-api@25.1.2
+  - @codingame/monaco-vscode-base-service-override@25.1.2
+  - @codingame/monaco-vscode-bulk-edit-service-override@25.1.2
+  - @codingame/monaco-vscode-configuration-service-override@25.1.2
+  - @codingame/monaco-vscode-editor-api@25.1.2
+  - @codingame/monaco-vscode-editor-service-override@25.1.2
+  - @codingame/monaco-vscode-environment-service-override@25.1.2
+  - @codingame/monaco-vscode-extension-api@25.1.2
+  - @codingame/monaco-vscode-extensions-service-override@25.1.2
+  - @codingame/monaco-vscode-files-service-override@25.1.2
+  - @codingame/monaco-vscode-host-service-override@25.1.2
+  - @codingame/monaco-vscode-java-default-extension@25.1.2
+  - @codingame/monaco-vscode-keybindings-service-override@25.1.2
+  - @codingame/monaco-vscode-languages-service-override@25.1.2
+  - @codingame/monaco-vscode-layout-service-override@25.1.2
+  - @codingame/monaco-vscode-log-service-override@25.1.2
+  - @codingame/monaco-vscode-model-service-override@25.1.2
+  - @codingame/monaco-vscode-monarch-service-override@25.1.2
+  - @codingame/monaco-vscode-python-default-extension@25.1.2
+  - @codingame/monaco-vscode-quickaccess-service-override@25.1.2
+  - @codingame/monaco-vscode-textmate-service-override@25.1.2
+  - @codingame/monaco-vscode-theme-defaults-default-extension@25.1.2
+  - @codingame/monaco-vscode-theme-service-override@25.1.2
+  - @codingame/monaco-vscode-view-banner-service-override@25.1.2
+  - @codingame/monaco-vscode-view-common-service-override@25.1.2
+  - @codingame/monaco-vscode-view-status-bar-service-override@25.1.2
+  - @codingame/monaco-vscode-view-title-bar-service-override@25.1.2
+  - @codingame/monaco-vscode-views-service-override@25.1.2
+  - @codingame/monaco-vscode-workbench-service-override@25.1.2

Review Comment:
   The block at LICENSE-binary:279 is the @codingame/monaco-vscode-* service-override family. These are transitive deps of `monaco-vscode-api@25` (which `monaco-languageclient@10` depends on); each one is a separately-published facade that the codingame stack lazy-loads at editor init (`@codingame/monaco-vscode-files-service-override`, `@codingame/monaco-vscode-textmate-service-override`, etc.).
   
   We can't drop any individual one — the codingame entrypoint pulls each via `import("@codingame/monaco-vscode-*-service-override")` for the corresponding VS Code service, and `license-webpack-plugin` records everything webpack actually emits into a chunk. If we tried trimming, the next `yarn build:ci` would re-add them and `check_binary_deps.py` would flag a NEW-entry mismatch.
   
   All are MIT-licensed (same author / publisher), so the LICENSE-binary attribution is the simple group-by-license form. The list is generated, not hand-maintained.



##########
frontend/LICENSE-binary:
##########
@@ -283,18 +294,16 @@ Angular / npm packages:
   - file-saver@2.0.5
   - graphlib@2.1.8
   - html2canvas@1.4.1
-  - java@1.0.0
   - jquery@3.6.4
   - json-schema-traverse@1.0.0
   - jszip@3.10.1
   - lib0@0.2.117
   - lodash@4.18.1
   - lodash-es@4.18.1
-  - marked@17.0.1
+  - marked@14.0.0

Review Comment:
   We're not downgrading the direct dep — `package.json` still declares `marked: 17.0.1`. What `LICENSE-binary` reflects is the version actually bundled in `dist/`, and that's `marked@14.0.0` — pulled in transitively by `ngx-markdown@21.2.0`, whose peer-pin still sits at the v14 line.
   
   `bin/licensing/check_binary_deps.py` aligns `LICENSE-binary` with `dist/3rdpartylicenses.json`, not with `package.json`. So this entry tracks what ships, not what we asked for. The day `ngx-markdown` bumps to `marked@17`, the listing will follow automatically.
   
   Confirmed via:
   
   ```
   $ node -e "console.log(require('./dist/3rdpartylicenses.json').filter(p=>p.name==='marked').map(p=>p.name+'@'+p.version))"
   [ 'marked@14.0.0' ]
   ```



##########
frontend/package.json:
##########
@@ -9,7 +9,6 @@
     "start": "concurrently --kill-others \"npx y-websocket\" \"ng serve\"",
     "build": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration=production --progress=false --source-map=false",
     "build:ci": "node --max-old-space-size=8192 ./node_modules/nx/dist/bin/nx.js build --configuration=production --progress=false --source-map=false",
-    "analyze": "ng build --configuration=production --stats-json && webpack-bundle-analyzer dist/stats.json",

Review Comment:
   The removed line was `"analyze": "ng build --configuration=production --stats-json && webpack-bundle-analyzer dist/stats.json"`. It pulled `webpack-bundle-analyzer@4.5.0` in as a devDep purely to render a treemap of `dist/stats.json` locally.
   
   It was never invoked from CI and the dep itself wasn't used anywhere else — confirmed by `grep -r 'webpack-bundle-analyzer'` returning only the `package.json` declaration and the `analyze` script. Dropping both shrinks the install graph (~6 transitive deps).
   
   Happy to put both back if anyone uses the script locally — let me know.



##########
frontend/vitest.config.ts:
##########
@@ -29,17 +29,6 @@ export default defineConfig({
     // which Angular's `fakeAsync` requires. Karma+Jasmine installed this
     // implicitly; the @angular/build:unit-test path doesn't.
     setupFiles: ["src/test-zone-setup.ts"],
-    // monaco-breakpoints' entry does `import './style.css'`. By default
-    // Vitest leaves third-party deps externalized, so Node's ESM loader
-    // tries to import the .css and crashes with
-    // `TypeError: Unknown file extension ".css"`. Inlining the package
-    // routes its imports through Vite/esbuild, which rewrites the CSS
-    // import to a no-op.
-    server: {
-      deps: {
-        inline: [/monaco-breakpoints/],
-      },

Review Comment:
   `monaco-breakpoints@0.2.0` is still in deps (top-level, line 53 of `package.json`) and `CodeDebuggerComponent` still drives it the same way it did pre-upgrade — `new MonacoBreakpoint(...)`, plus the line-marker decoration plumbing for left/right-click. The v10 upgrade didn't touch any of that surface; the package's editor API is unchanged.
   
   For test coverage there's `code-debugger.component.spec.ts` in the suite, which exercises construction + the workflow-status subscription path. You're right that we don't have a spec that actually clicks the gutter and asserts a breakpoint round-trips — that lives in the per-component scope (#4861 tracks pulling these out into Vitest browser mode where the editor can mount for real). For this PR my goal was "don't regress what's already covered"; happy to spin off a follow-up issue if you want the breakpoint UX pinned in tests.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4502047542

   Let's fill the tests separately before upgrading. Thanks for the effort!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4827259999

   <!-- texera-reviewer-suggestion -->
   ### Automated Reviewer Suggestions
   
   Based on the `git blame` history of the changed files, we recommend the following reviewers:
   
   - **Contributors with relevant context:** `@Yicong-Huang`, `@Ma77Ball`, `@PG1204`
     You can notify them by mentioning `@Yicong-Huang`, `@Ma77Ball`, `@PG1204` in a comment.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3212877946


##########
frontend/src/app/workspace/component/code-editor-dialog/code-debugger.component.ts:
##########
@@ -20,9 +20,6 @@
 import { AfterViewInit, Component, Input, ViewChild } from "@angular/core";
 import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy";
 import { SafeStyle } from "@angular/platform-browser";
-import "@codingame/monaco-vscode-python-default-extension";
-import "@codingame/monaco-vscode-r-default-extension";
-import "@codingame/monaco-vscode-java-default-extension";
 import { isDefined } from "../../../common/util/predicate";
 import * as monaco from "monaco-editor";
 import { MonacoBreakpoint } from "monaco-breakpoints";

Review Comment:
   `CodeDebuggerComponent` still has top-level side-effect imports of the codingame default extensions. Since this component is declared in `AppModule`, these imports will be evaluated on initial app load and can pull the heavy v25 language extensions into the main bundle even if the code editor is never opened (defeating the lazy `ensureVscodeApiStarted()` activation flow). Consider removing these imports and relying on the centralized `ensureVscodeApiStarted()` (or a shared initializer) to load/activate extensions only when the editor stack is actually used.



##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -18,22 +18,49 @@
  */
 
 /**
- * jsdom doesn't implement the SVG geometry APIs (`SVGSVGElement#createSVGMatrix`,
- * `createSVGPoint`, `createSVGTransform`, `getScreenCTM`, `getCTM`,
- * `getBBox`). jointjs reaches into these during graph layout and crashes
- * the spec build with `TypeError: svgDocument.createSVGMatrix is not a
- * function` etc.
- *
- * The stubs below return identity-ish geometry: matrices/points behave like
- * the identity, bounding boxes report zero dimensions. That's enough for
- * jointjs construction code to not throw; specs that actually depend on
- * accurate geometry should run under Vitest browser mode rather than
- * jsdom (tracked in #4861), but the bulk of the texera specs only need
- * jointjs to instantiate cleanly.
+ * Test-environment polyfills + setup hooks for jsdom + the Angular
+ * `@angular/build:unit-test` builder. Pulled in via `setupFiles` in
+ * `angular.json`. Each block below targets a specific gap that surfaces
+ * when the codingame monaco-vscode-* v25 stack or jointjs runs under
+ * jsdom; comments next to each block say which one.
  */
 
+// ───────────────────────────────────────────────────────────────────────────
+// Node ESM loader hook so every transitive `.css` import resolves to an empty
+// module. The unit-test builder pre-bundles spec files with `externalPackages:
+// true`, so imports like `monaco-languageclient` reach Node's native ESM
+// loader instead of Vite's transform pipeline — without the hook, every spec
+// that transitively loads the codingame v25 stack crashes with
+// `Unknown file extension ".css"`. The hook source lives inline as a `data:`
+// URL so we don't carry a sidecar `.mjs`. Must run before any spec body
+// imports the affected packages; `module.register` needs Node 20.6+ (the
+// project pins Node ≥ 24).
+import { register as registerLoader } from "node:module";
+
+const cssLoaderHookSource = `
+export function resolve(specifier, context, nextResolve) {
+  if (specifier.endsWith(".css") || /\\.css(\\?|$)/.test(specifier)) {
+    return {
+      url: "data:text/javascript,export%20default%20%7B%7D%3B",
+      shortCircuit: true,
+      format: "module",
+    };
+  }
+  return nextResolve(specifier, context);
+}
+`;
+registerLoader(`data:text/javascript;charset=utf-8,${encodeURIComponent(cssLoaderHookSource)}`);
+
 type AnyFn = (...args: unknown[]) => unknown;
 
+// ───────────────────────────────────────────────────────────────────────────
+// SVG geometry APIs (`SVGSVGElement#createSVGMatrix`, `createSVGPoint`,
+// `createSVGTransform`, `getScreenCTM`, `getCTM`, `getBBox`). jsdom doesn't
+// implement these and jointjs reaches into them during graph layout, so the
+// spec build crashes with `TypeError: svgDocument.createSVGMatrix is not a
+// function`. Stubs below return identity-ish geometry — enough for jointjs
+// construction code not to throw. Specs needing accurate geometry should
+// run under Vitest browser mode rather than jsdom (tracked in #4861).
 function fakeMatrix() {

Review Comment:
   `src/jsdom-svg-polyfill.ts` is configured as a test `setupFiles` entry (runs once per spec file). Calling `module.register(...)` unconditionally will register a new ESM loader hook for every test file, which can lead to a growing hook chain and slower/less predictable module resolution across the run. Consider guarding this with a `globalThis` flag (register once per process) or moving the loader registration into a truly once-per-process setup path.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4427190275

   > do we want to add tests before we upgrade? just want to make sure things are not broken.
   
   Added in PR #5004.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3231683951


##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -17,128 +17,169 @@
  * under the License.
  */
 
-/**
- * jsdom doesn't implement the SVG geometry APIs (`SVGSVGElement#createSVGMatrix`,
- * `createSVGPoint`, `createSVGTransform`, `getScreenCTM`, `getCTM`,
- * `getBBox`). jointjs reaches into these during graph layout and crashes
- * the spec build with `TypeError: svgDocument.createSVGMatrix is not a
- * function` etc.
- *
- * The stubs below return identity-ish geometry: matrices/points behave like
- * the identity, bounding boxes report zero dimensions. That's enough for
- * jointjs construction code to not throw; specs that actually depend on
- * accurate geometry should run under Vitest browser mode rather than
- * jsdom (tracked in #4861), but the bulk of the texera specs only need
- * jointjs to instantiate cleanly.
- */
+// Test-environment polyfills + setup hooks for jsdom + the Angular
+// `@angular/build:unit-test` builder. Pulled in via `setupFiles` in
+// `angular.json`. Each block below patches one specific gap that surfaces
+// when the codingame monaco-vscode-* v25 stack or jointjs runs under jsdom.
+
+// Node ESM loader hook so every transitive `.css` import resolves to an empty
+// module. The unit-test builder pre-bundles spec files with `externalPackages:
+// true`, so imports like `monaco-languageclient` reach Node's native ESM
+// loader instead of Vite's transform pipeline — without the hook, every spec
+// that transitively loads the codingame v25 stack crashes with
+// `Unknown file extension ".css"`. Inline as a `data:` URL so we don't carry
+// a sidecar `.mjs`. Vitest re-evaluates this setup file once per spec file,
+// so we gate the registration with a `globalThis` flag — `module.register`
+// chains every call, and we don't want N hooks doing identical work for N
+// specs. Must run before any spec body imports the affected packages;
+// `module.register` needs Node 20.6+ (project pins Node ≥ 24).
+import { register as registerLoader } from "node:module";
+
+const CSS_HOOK_FLAG = Symbol.for("texera.cssLoaderHookRegistered");
+const flagHolder = globalThis as Record<symbol, boolean | undefined>;
+if (!flagHolder[CSS_HOOK_FLAG]) {
+  const cssLoaderHookSource = `
+export function resolve(specifier, context, nextResolve) {
+  if (specifier.endsWith(".css") || /\\.css(\\?|$)/.test(specifier)) {
+    return { url: "data:text/javascript,export%20default%20%7B%7D%3B", shortCircuit: true, format: "module" };
+  }
+  return nextResolve(specifier, context);
+}
+`;

Review Comment:
   Good point — hardened in 67bcc5b863 (now 29cbba5a1c after rebase).
   
   Switched the CSS stub from `export default {}` to a `CSSStyleSheet`-shaped object mirroring our `InertCSSStyleSheet` polyfill:
   
   ```js
   const s = { cssRules: [] };
   s.replaceSync = () => {};
   s.replace = () => Promise.resolve();
   s.insertRule = () => 0;
   s.deleteRule = () => {};
   export default s;
   ```
   
   So if any transitive consumer in the codingame v25 `css-style-sheet` export form reads `.replaceSync` / `.cssRules` / `.replace` off the imported value, it now gets the methods that the polyfill exposes everywhere else in the test env.



##########
frontend/LICENSE-binary:
##########
@@ -290,11 +301,10 @@ Angular / npm packages:
   - lib0@0.2.117
   - lodash@4.18.1
   - lodash-es@4.18.1
-  - marked@17.0.1
+  - marked@14.0.0

Review Comment:
   False positive — `marked@17.0.1` is in `yarn.lock` because it's the direct dep declared in `package.json`, but the production bundle only includes `marked@14.0.0` (transitively, via `ngx-markdown@21.2.0`'s peer-pin). Confirmed by:
   
   \`\`\`
   $ node -e "console.log(require('./dist/3rdpartylicenses.json').filter(p=>p.name==='marked').map(p=>p.name+'@'+p.version))"
   [ 'marked@14.0.0' ]
   \`\`\`
   
   `LICENSE-binary` is intentionally aligned with what `license-webpack-plugin` records — i.e., what actually ships in `dist/`. `bin/licensing/check_binary_deps.py` flags drift between these two precisely so we don't list unbundled deps. So `marked@17.0.1` shouldn't be in `LICENSE-binary`; it isn't bundled at runtime.
   
   If we want both versions reflected (e.g., a future code path imports the new one), the right fix is to reach into the source for an explicit use site so webpack pulls it in — not to amend `LICENSE-binary` ahead of that.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan closed pull request #4997: chore(frontend): upgrade frontend to monaco-languageclient v10
URL: https://github.com/apache/texera/pull/4997


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3212866041


##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,38 +184,37 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();
   }
 
   /**
    * Specify the co-editor's cursor style. This step is missing from MonacoBinding.
    * @param coeditor
    */
   public getCoeditorCursorStyles(coeditor: Coeditor) {
-    const textCSS =
-      "<style>" +
-      `.yRemoteSelection-${coeditor.clientId} { background-color: ${coeditor.color?.replace("0.8", "0.5")}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId}::after { border-color: ${coeditor.color}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId} { border-color: ${coeditor.color}}` +
-      "</style>";
-    return this.sanitizer.bypassSecurityTrustHtml(textCSS);
+    const id = coeditor.clientId;
+    const color = coeditor.color;
+    const selectionBg = color?.replace("0.8", "0.5");
+    return this.sanitizer.bypassSecurityTrustHtml(
+      `<style>` +
+        `.yRemoteSelection-${id} { background-color: ${selectionBg}}` +
+        `.yRemoteSelectionHead-${id}::after { border-color: ${color}}` +
+        `.yRemoteSelectionHead-${id} { border-color: ${color}}` +
+        `</style>`
+    );

Review Comment:
   Real concern, hardened in 51b4fe5546.
   
   Both `coeditor.clientId` and `coeditor.color` come from yjs awareness state and are interpolated into a `<style>` tag passed through `bypassSecurityTrustHtml`, so anything that escapes the tag would land in the page as raw HTML.
   
   Added two tight allow-list regexes and bail out to an empty stylesheet if either fails:
   
   ```ts
   private static readonly SAFE_CLIENT_ID = /^\d{1,10}$/;
   private static readonly SAFE_CSS_COLOR = /^(?:#[0-9a-fA-F]{3,8}|rgba?\([\d.,\s]+\)|hsla?\([\d.,%\s]+\))$/;
   ```
   
   The id regex matches yjs's decimal-serialised 32-bit clientID; the colour regex covers the only forms our own code emits (hex / `rgb(a)` / `hsl(a)`). Anything outside those patterns short-circuits to `bypassSecurityTrustHtml("")`. Long-term, `CSSStyleSheet` / `adoptedStyleSheets` would be even better — happy to file that as a follow-up if you'd like.



##########
frontend/custom-webpack.config.js:
##########
@@ -19,15 +19,85 @@
 
 const { LicenseWebpackPlugin } = require("license-webpack-plugin");
 
+// Workaround for license-webpack-plugin v4 crashing with `ENOENT: scandir ''` when a
+// bundled module has no resolvable on-disk directory. Some @codingame/monaco-vscode-*
+// sub-modules surface as virtual entries (descriptionFileRoot === '') after the v25
+// upgrade. Make listPaths/readFileAsUtf8/isDirectory tolerant of empty paths.
+{
+  const fs = require("fs");

Review Comment:
   Already gone in de4d47b7b2. The whole license-webpack-plugin filesystem-monkey-patch block (the `const fs = require("fs")` + the `WebpackFileSystem` overrides) was deleted as dead code — `handleMissingLicenseText: () => null` already absorbs the ENOENT cases on its own. `custom-webpack.config.js` shrank from 154 to 84 lines in that commit.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4438828658

   I manually canceled test after 1+ hr. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4438866759

   > 9107fe5
   
   
   
   > I manually canceled test after 1+ hr.
   
   https://github.com/apache/texera/pull/4997/commits/9107fe563e999b58d09af9444d9ecddae9182fff passed CI. Might be an issue on main.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4884435275

   Thanks for the fix! I tested both the commit before the fix and the one after the fix, and both work on my end (Windows + Chrome). Since I can't reproduce the issue, I'll rely on your Safari test results and go ahead with the fix anyway, as it doesn't introduce any regressions from my side.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4484584077

   @Yicong-Huang, can you review this PR?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3263919915


##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.spec.ts:
##########
@@ -52,7 +52,6 @@ const synthesizeSchema = (operatorType: string): OperatorSchema => ({ ...baseSch
 const augmentedSchemas: OperatorSchema[] = [
   ...mockOperatorMetaData.operators,
   ...PYTHON_OPERATOR_TYPES.map(synthesizeSchema),
-  ...R_OPERATOR_TYPES.map(synthesizeSchema),

Review Comment:
   ditto



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.spec.ts:
##########
@@ -31,10 +31,10 @@ import { OperatorSchema } from "../../types/operator-schema.interface";
 import { of } from "rxjs";
 
 // Operator types that the constructor's language-detection branch must map
-// to a specific language. `RUDFSource` / `RUDF` -> `r`; the three V2 Python
-// types -> `python`; everything else -> `java`. Local to this spec so we
-// don't perturb the shared mock-workflow-data fixtures.
-const R_OPERATOR_TYPES = ["RUDFSource", "RUDF"];
+// to a specific language. The three V2 Python types -> `python`; everything
+// else (including the legacy `RUDF*` types) -> `java`, since R UDF editor
+// support was retired in this branch. Local to this spec so we don't

Review Comment:
   Let's not remove R UDF (or R language) support. R UDF can be installed via a non-apache plugin. And frontend editor should work for it. 



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();

Review Comment:
   why can we remove 
   ```
    if (isDefined(this.workflowVersionStreamSubject)) {
   ```
   ?
   



##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -17,128 +17,183 @@
  * under the License.
  */
 
-/**
- * jsdom doesn't implement the SVG geometry APIs (`SVGSVGElement#createSVGMatrix`,
- * `createSVGPoint`, `createSVGTransform`, `getScreenCTM`, `getCTM`,
- * `getBBox`). jointjs reaches into these during graph layout and crashes
- * the spec build with `TypeError: svgDocument.createSVGMatrix is not a
- * function` etc.
- *
- * The stubs below return identity-ish geometry: matrices/points behave like
- * the identity, bounding boxes report zero dimensions. That's enough for
- * jointjs construction code to not throw; specs that actually depend on
- * accurate geometry should run under Vitest browser mode rather than
- * jsdom (tracked in #4861), but the bulk of the texera specs only need
- * jointjs to instantiate cleanly.
- */
+// Test-environment polyfills + setup hooks for jsdom + the Angular
+// `@angular/build:unit-test` builder. Pulled in via `setupFiles` in
+// `angular.json`. Each block below patches one specific gap that surfaces
+// when the codingame monaco-vscode-* v25 stack or jointjs runs under jsdom.
+
+// Node ESM loader hook so every transitive `.css` import resolves to an empty
+// module. The unit-test builder pre-bundles spec files with `externalPackages:
+// true`, so imports like `monaco-languageclient` reach Node's native ESM
+// loader instead of Vite's transform pipeline — without the hook, every spec
+// that transitively loads the codingame v25 stack crashes with
+// `Unknown file extension ".css"`. Inline as a `data:` URL so we don't carry
+// a sidecar `.mjs`. Vitest re-evaluates this setup file once per spec file,
+// so we gate the registration with a `globalThis` flag — `module.register`
+// chains every call, and we don't want N hooks doing identical work for N
+// specs. Must run before any spec body imports the affected packages;
+// `module.register` needs Node 20.6+ (project pins Node ≥ 24).

Review Comment:
   please simplify this comment. 



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.spec.ts:
##########
@@ -117,19 +116,11 @@ describe("CodeEditorComponent", () => {
     expect(fixture.componentInstance.currentOperatorId).toBe(mockJavaUDFPredicate.operatorID);
   });
 
-  // Language detection — the constructor maps `RUDFSource` / `RUDF` to `r`,
-  // the three V2-era Python operator types to `python`, and anything else
-  // to `java`. The exact branch lives in the constructor; the public
-  // `language` field is what the rest of the editor (LSP wiring, file-
-  // suffix selection) keys off.
-
-  R_OPERATOR_TYPES.forEach((operatorType, index) => {
-    it(`picks language="r" for operatorType=${operatorType}`, () => {
-      const fixture = makeFixture(buildPredicate(`r-${index}`, operatorType));
-      expect(fixture.componentInstance.language).toBe("r");
-      expect(fixture.componentInstance.languageTitle).toBe("R UDF");
-    });
-  });

Review Comment:
   ditto



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -143,18 +145,8 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
   ) {
     this.currentOperatorId = this.workflowActionService.getJointGraphWrapper().getCurrentHighlightedOperatorIDs()[0];
     const operatorType = this.workflowActionService.getTexeraGraph().getOperator(this.currentOperatorId).operatorType;
-
-    if (operatorType === "RUDFSource" || operatorType === "RUDF") {
-      this.setLanguage("r");
-    } else if (
-      operatorType === "PythonUDFV2" ||
-      operatorType === "PythonUDFSourceV2" ||
-      operatorType === "DualInputPortsPythonUDFV2"
-    ) {
-      this.setLanguage("python");
-    } else {
-      this.setLanguage("java");
-    }
+    this.language = CodeEditorComponent.PYTHON_OPERATOR_TYPES.has(operatorType) ? "python" : "java";
+    this.languageTitle = `${this.language[0].toUpperCase()}${this.language.slice(1)} UDF`;

Review Comment:
   ditto



##########
frontend/src/jsdom-svg-polyfill.ts:
##########


Review Comment:
   Is this file related to upgrade Monaco-language client at all?



##########
frontend/LICENSE-binary:
##########
@@ -247,30 +248,40 @@ Angular / npm packages:
   - @ant-design/icons-angular@21.0.0
   - @auth0/angular-jwt@5.1.0
   - @babel/runtime@7.29.2
-  - @codingame/monaco-vscode-api@8.0.4
-  - @codingame/monaco-vscode-base-service-override@8.0.4
-  - @codingame/monaco-vscode-configuration-service-override@8.0.4
-  - @codingame/monaco-vscode-editor-api@8.0.4
-  - @codingame/monaco-vscode-environment-service-override@8.0.4
-  - @codingame/monaco-vscode-extensions-service-override@8.0.4
-  - @codingame/monaco-vscode-files-service-override@8.0.4
-  - @codingame/monaco-vscode-host-service-override@8.0.4
-  - @codingame/monaco-vscode-java-default-extension@8.0.4
-  - @codingame/monaco-vscode-languages-service-override@8.0.4
-  - @codingame/monaco-vscode-layout-service-override@8.0.4
-  - @codingame/monaco-vscode-model-service-override@8.0.4
-  - @codingame/monaco-vscode-monarch-service-override@8.0.4
-  - @codingame/monaco-vscode-python-default-extension@8.0.4
-  - @codingame/monaco-vscode-quickaccess-service-override@8.0.4
-  - @codingame/monaco-vscode-r-default-extension@8.0.4
-  - @codingame/monaco-vscode-textmate-service-override@8.0.4
-  - @codingame/monaco-vscode-theme-defaults-default-extension@8.0.4
-  - @codingame/monaco-vscode-theme-service-override@8.0.4
+  - @codingame/monaco-vscode-api@25.1.2
+  - @codingame/monaco-vscode-base-service-override@25.1.2
+  - @codingame/monaco-vscode-bulk-edit-service-override@25.1.2
+  - @codingame/monaco-vscode-configuration-service-override@25.1.2
+  - @codingame/monaco-vscode-editor-api@25.1.2
+  - @codingame/monaco-vscode-editor-service-override@25.1.2
+  - @codingame/monaco-vscode-environment-service-override@25.1.2
+  - @codingame/monaco-vscode-extension-api@25.1.2
+  - @codingame/monaco-vscode-extensions-service-override@25.1.2
+  - @codingame/monaco-vscode-files-service-override@25.1.2
+  - @codingame/monaco-vscode-host-service-override@25.1.2
+  - @codingame/monaco-vscode-java-default-extension@25.1.2
+  - @codingame/monaco-vscode-keybindings-service-override@25.1.2
+  - @codingame/monaco-vscode-languages-service-override@25.1.2
+  - @codingame/monaco-vscode-layout-service-override@25.1.2
+  - @codingame/monaco-vscode-log-service-override@25.1.2
+  - @codingame/monaco-vscode-model-service-override@25.1.2
+  - @codingame/monaco-vscode-monarch-service-override@25.1.2
+  - @codingame/monaco-vscode-python-default-extension@25.1.2
+  - @codingame/monaco-vscode-quickaccess-service-override@25.1.2
+  - @codingame/monaco-vscode-textmate-service-override@25.1.2
+  - @codingame/monaco-vscode-theme-defaults-default-extension@25.1.2
+  - @codingame/monaco-vscode-theme-service-override@25.1.2
+  - @codingame/monaco-vscode-view-banner-service-override@25.1.2
+  - @codingame/monaco-vscode-view-common-service-override@25.1.2
+  - @codingame/monaco-vscode-view-status-bar-service-override@25.1.2
+  - @codingame/monaco-vscode-view-title-bar-service-override@25.1.2
+  - @codingame/monaco-vscode-views-service-override@25.1.2
+  - @codingame/monaco-vscode-workbench-service-override@25.1.2

Review Comment:
   do we need all of those?



##########
frontend/LICENSE-binary:
##########
@@ -283,18 +294,16 @@ Angular / npm packages:
   - file-saver@2.0.5
   - graphlib@2.1.8
   - html2canvas@1.4.1
-  - java@1.0.0
   - jquery@3.6.4
   - json-schema-traverse@1.0.0
   - jszip@3.10.1
   - lib0@0.2.117
   - lodash@4.18.1
   - lodash-es@4.18.1
-  - marked@17.0.1
+  - marked@14.0.0

Review Comment:
   why are we downgrading this?



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();
   }
 
   /**
    * Specify the co-editor's cursor style. This step is missing from MonacoBinding.
+   *
+   * `coeditor.clientId` and `coeditor.color` come from yjs awareness state,
+   * which any peer can write to. Both are interpolated into a `<style>` tag
+   * passed through `bypassSecurityTrustHtml`, so anything that escapes the
+   * tag would land in the page as raw HTML. Validate both to a tight
+   * allow-list (digits-only id, hex / `rgb(a)` / `hsl(a)` colour) and bail
+   * out otherwise; nothing else should reach the sanitiser.
    * @param coeditor
    */
   public getCoeditorCursorStyles(coeditor: Coeditor) {
-    const textCSS =
+    if (!CodeEditorComponent.SAFE_CLIENT_ID.test(coeditor.clientId)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    if (!coeditor.color || !CodeEditorComponent.SAFE_CSS_COLOR.test(coeditor.color)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    const id = coeditor.clientId;
+    const color = coeditor.color;
+    const selectionBg = color.replace("0.8", "0.5");
+    return this.sanitizer.bypassSecurityTrustHtml(
       "<style>" +
-      `.yRemoteSelection-${coeditor.clientId} { background-color: ${coeditor.color?.replace("0.8", "0.5")}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId}::after { border-color: ${coeditor.color}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId} { border-color: ${coeditor.color}}` +
-      "</style>";
-    return this.sanitizer.bypassSecurityTrustHtml(textCSS);
+        `.yRemoteSelection-${id} { background-color: ${selectionBg}}` +
+        `.yRemoteSelectionHead-${id}::after { border-color: ${color}}` +
+        `.yRemoteSelectionHead-${id} { border-color: ${color}}` +
+        "</style>"
+    );
   }
 
-  private getFileSuffixByLanguage(language: string): string {
-    switch (language.toLowerCase()) {
-      case "python":
-        return ".py";
-      case "r":
-        return ".r";
-      case "javascript":
-        return ".js";
-      case "java":
-        return ".java";
-      default:
-        return ".py";
-    }
+  // Allow-lists for the two awareness-derived values that flow into a `<style>`
+  // tag in `getCoeditorCursorStyles`. yjs serialises clientIDs as the decimal
+  // form of a 32-bit integer, and the colours we generate elsewhere only use
+  // these notations — anything outside these patterns is rejected.
+  private static readonly SAFE_CLIENT_ID = /^\d{1,10}$/;
+  private static readonly SAFE_CSS_COLOR = /^(?:#[0-9a-fA-F]{3,8}|rgba?\([\d.,\s]+\)|hsla?\([\d.,%\s]+\))$/;
+
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      try {
+        const apiConfig: MonacoVscodeApiConfig = {
+          $type: "extended",
+          viewsConfig: { $type: "EditorService" },
+          userConfiguration: {
+            json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+          },
+          // Wire workers via thin trampolines in `./workers/`. Webpack 5 only
+          // treats `new Worker(new URL("./relative", import.meta.url))` as a
+          // worker entry point and bundles the dep tree into a chunk; bare
+          // package URLs `new URL("@codingame/...", import.meta.url)` become
+          // static assets whose relative imports 404 at runtime. Esbuild
+          // (used by @angular/build:unit-test) also requires a real on-disk
+          // file for the URL spec — trampolines satisfy both bundlers.
+          monacoWorkerFactory: () => {
+            const env = getEnhancedMonacoEnvironment();
+            env.getWorker = (_workerId: string, label: string): Worker => {
+              switch (label) {
+                case "editorWorkerService":
+                  return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+                case "extensionHostWorkerMain":
+                  return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+                case "TextMateWorker":
+                  return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+                default:
+                  throw new Error(`No worker configured for label: ${label}`);
+              }
+            };
+          },
+        };
+        await new MonacoVscodeApiWrapper(apiConfig).start();
+
+        // Load AND fully activate the default language extensions. Each
+        // module exports a `whenReady()` that resolves after its TextMate
+        // grammar / configuration files are registered with the host —
+        // without waiting, the editor opens with every token rendered as
+        // the default `mtk1` class (no syntax colours). Dynamic `import(...)`
+        // is used so the Angular build pipeline doesn't tree-shake the
+        // side-effect imports.
+        const extensions = await Promise.all([
+          import("@codingame/monaco-vscode-python-default-extension"),
+          import("@codingame/monaco-vscode-java-default-extension"),
+        ]);

Review Comment:
   will these appear in license-BINARY? these seems to be libraries loaded during runtime... can we avoid this?



##########
frontend/vitest.config.ts:
##########
@@ -29,17 +29,6 @@ export default defineConfig({
     // which Angular's `fakeAsync` requires. Karma+Jasmine installed this
     // implicitly; the @angular/build:unit-test path doesn't.
     setupFiles: ["src/test-zone-setup.ts"],
-    // monaco-breakpoints' entry does `import './style.css'`. By default
-    // Vitest leaves third-party deps externalized, so Node's ESM loader
-    // tries to import the .css and crashes with
-    // `TypeError: Unknown file extension ".css"`. Inlining the package
-    // routes its imports through Vite/esbuild, which rewrites the CSS
-    // import to a no-op.
-    server: {
-      deps: {
-        inline: [/monaco-breakpoints/],
-      },

Review Comment:
   does Monaco-breakpoint still work? we need it for debugger. We might not have enough tests against it.



##########
frontend/package.json:
##########
@@ -9,7 +9,6 @@
     "start": "concurrently --kill-others \"npx y-websocket\" \"ng serve\"",
     "build": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration=production --progress=false --source-map=false",
     "build:ci": "node --max-old-space-size=8192 ./node_modules/nx/dist/bin/nx.js build --configuration=production --progress=false --source-map=false",
-    "analyze": "ng build --configuration=production --stats-json && webpack-bundle-analyzer dist/stats.json",

Review Comment:
   why remove this?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on PR #4997:
URL: https://github.com/apache/texera/pull/4997#issuecomment-4484819585

   Also the test coverage is not enough. 
   
   > Patch coverage is 47.14286% with 37 lines in your changes missing coverage. Please review.
   
   I especially want to make sure the following can still work. If we do not currently have test coverage, it will be ideal to add tests for them first before upgrade.
   1. language client features can still work
   2. our custom editor logics (e.g., frozen editor during execution, unfreeze when paused).
   3. debugger logics (with Monaco-breakpoint) 
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "aglinxinyuan (via GitHub)" <gi...@apache.org>.
aglinxinyuan commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3524581979


##########
frontend/package.json:
##########
@@ -9,7 +9,6 @@
     "start": "concurrently --kill-others \"npx y-websocket\" \"ng serve\"",
     "build": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration=production --progress=false --source-map=false",
     "build:ci": "node --max-old-space-size=8192 ./node_modules/nx/dist/bin/nx.js build --configuration=production --progress=false --source-map=false",
-    "analyze": "ng build --configuration=production --stats-json && webpack-bundle-analyzer dist/stats.json",

Review Comment:
   Done — restored the `analyze` script along with its `webpack-bundle-analyzer` devDependency (and the matching `yarn.lock` entries), since the removal was unrelated to this PR.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Yicong-Huang (via GitHub)" <gi...@apache.org>.
Yicong-Huang commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3524565737


##########
frontend/package.json:
##########
@@ -9,7 +9,6 @@
     "start": "concurrently --kill-others \"npx y-websocket\" \"ng serve\"",
     "build": "node --max-old-space-size=8192 ./node_modules/@angular/cli/bin/ng build --configuration=production --progress=false --source-map=false",
     "build:ci": "node --max-old-space-size=8192 ./node_modules/nx/dist/bin/nx.js build --configuration=production --progress=false --source-map=false",
-    "analyze": "ng build --configuration=production --stats-json && webpack-bundle-analyzer dist/stats.json",

Review Comment:
   let's put it back, it is not related to this PR. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] chore(frontend): upgrade frontend to monaco-languageclient v10 [texera]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #4997:
URL: https://github.com/apache/texera/pull/4997#discussion_r3223609260


##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -158,36 +199,34 @@ class InertWebSocket {
   onerror: AnyFn | null = null;
   onmessage: AnyFn | null = null;
   onclose: AnyFn | null = null;
-  send(): void {}
-  close(): void {}
-  addEventListener(): void {}
-  removeEventListener(): void {}
-  dispatchEvent(): boolean {
-    return false;
-  }
+  send = () => undefined;
+  close = () => undefined;
+  addEventListener = () => undefined;
+  removeEventListener = () => undefined;
+  dispatchEvent = () => false;
   constructor(_url?: string, _protocols?: string | string[]) {}
 }
-(globalThis as unknown as { WebSocket: typeof InertWebSocket }).WebSocket = InertWebSocket;
+G.WebSocket = InertWebSocket;
 
-/**
- * NgZorro's NzIconService dynamically fetches icon SVGs over HTTP from
- * `/assets/...` when the icon isn't pre-registered. jsdom's XHR
- * implementation rejects those requests with an `AggregateError`, and
- * downstream the icon lookup re-throws as `IconNotFoundError`. Vitest
- * catches both as unhandled errors, which CI treats as a hard failure
- * (locally Vitest only reports them as non-fatal warnings).
- *
- * Stubbing every spec with `NzIconModule.forChild([...])` for every
- * icon its template uses is impractical — there are dozens. Instead,
- * suppress the two specific error patterns at the process level: they
- * originate inside ngZorro's icon plumbing and don't affect the
- * assertions specs actually make.
- */
+// Process-level error suppression for benign ngZorro icon / codingame
+// extension fetches. NzIconService fetches icon SVGs from `/assets/...` when
+// the icon isn't pre-registered; jsdom's XHR rejects with `AggregateError`
+// and the lookup re-throws as `IconNotFoundError`. Vitest catches both as
+// unhandled errors and CI treats that as a hard failure. Stubbing every spec
+// with `NzIconModule.forChild([...])` is impractical — dozens of icons.
+// Suppress just these patterns at the process level.
 function isBenignIconError(err: unknown): boolean {
   const msg = err instanceof Error ? err.message : String(err);
+  const stack = err instanceof Error ? err.stack ?? "" : "";
   return (
     msg.includes("[@ant-design/icons-angular]") ||
-    (err instanceof Error && err.name === "AggregateError" && /xhr-utils/.test(err.stack ?? ""))
+    (err instanceof Error && err.name === "AggregateError" && /xhr-utils/.test(stack)) ||
+    // codingame v25 default extensions try to fetch their bundled themes /
+    // language configs over `extension-file://` URIs at activation time.
+    // jsdom can't resolve the scheme so the fetch rejects, but it's cosmetic
+    // — the spec body never depends on the theme/grammar being applied.
+    msg.includes("extension-file://") ||
+    /workbenchThemeService|monaco-vscode-theme|monaco-vscode-.*-default-extension/.test(stack)
   );
 }
 process.on("uncaughtException", err => {

Review Comment:
   This setup file notes it can be re-evaluated once per spec file, but the `process.on(...)` handler registration is not gated like the CSS loader hook is. That can lead to duplicate listeners (memory leak warnings, repeated filtering/side effects). Gate the `process.on` registrations behind the same global flag pattern used for the loader hook so listeners are only attached once per process.



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();
   }
 
   /**
    * Specify the co-editor's cursor style. This step is missing from MonacoBinding.
+   *
+   * `coeditor.clientId` and `coeditor.color` come from yjs awareness state,
+   * which any peer can write to. Both are interpolated into a `<style>` tag
+   * passed through `bypassSecurityTrustHtml`, so anything that escapes the
+   * tag would land in the page as raw HTML. Validate both to a tight
+   * allow-list (digits-only id, hex / `rgb(a)` / `hsl(a)` colour) and bail
+   * out otherwise; nothing else should reach the sanitiser.
    * @param coeditor
    */
   public getCoeditorCursorStyles(coeditor: Coeditor) {
-    const textCSS =
+    if (!CodeEditorComponent.SAFE_CLIENT_ID.test(coeditor.clientId)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    if (!coeditor.color || !CodeEditorComponent.SAFE_CSS_COLOR.test(coeditor.color)) {
+      return this.sanitizer.bypassSecurityTrustHtml("");
+    }
+    const id = coeditor.clientId;
+    const color = coeditor.color;
+    const selectionBg = color.replace("0.8", "0.5");
+    return this.sanitizer.bypassSecurityTrustHtml(
       "<style>" +
-      `.yRemoteSelection-${coeditor.clientId} { background-color: ${coeditor.color?.replace("0.8", "0.5")}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId}::after { border-color: ${coeditor.color}}` +
-      `.yRemoteSelectionHead-${coeditor.clientId} { border-color: ${coeditor.color}}` +
-      "</style>";
-    return this.sanitizer.bypassSecurityTrustHtml(textCSS);
+        `.yRemoteSelection-${id} { background-color: ${selectionBg}}` +
+        `.yRemoteSelectionHead-${id}::after { border-color: ${color}}` +
+        `.yRemoteSelectionHead-${id} { border-color: ${color}}` +
+        "</style>"
+    );
   }
 
-  private getFileSuffixByLanguage(language: string): string {
-    switch (language.toLowerCase()) {
-      case "python":
-        return ".py";
-      case "r":
-        return ".r";
-      case "javascript":
-        return ".js";
-      case "java":
-        return ".java";
-      default:
-        return ".py";
-    }
+  // Allow-lists for the two awareness-derived values that flow into a `<style>`
+  // tag in `getCoeditorCursorStyles`. yjs serialises clientIDs as the decimal
+  // form of a 32-bit integer, and the colours we generate elsewhere only use
+  // these notations — anything outside these patterns is rejected.
+  private static readonly SAFE_CLIENT_ID = /^\d{1,10}$/;
+  private static readonly SAFE_CSS_COLOR = /^(?:#[0-9a-fA-F]{3,8}|rgba?\([\d.,\s]+\)|hsla?\([\d.,%\s]+\))$/;
+
+  /**
+   * Lazily start the global monaco-vscode-api wrapper. The vscode API services are
+   * a process-wide singleton in v10; calling start() twice would throw, so we share
+   * a single Promise across every CodeEditorComponent instance.
+   */
+  private static async ensureVscodeApiStarted(): Promise<void> {
+    CodeEditorComponent.apiWrapperStartPromise ??= (async () => {
+      try {
+        const apiConfig: MonacoVscodeApiConfig = {
+          $type: "extended",
+          viewsConfig: { $type: "EditorService" },
+          userConfiguration: {
+            json: JSON.stringify({ "workbench.colorTheme": "Default Dark Modern" }),
+          },
+          // Wire workers via thin trampolines in `./workers/`. Webpack 5 only
+          // treats `new Worker(new URL("./relative", import.meta.url))` as a
+          // worker entry point and bundles the dep tree into a chunk; bare
+          // package URLs `new URL("@codingame/...", import.meta.url)` become
+          // static assets whose relative imports 404 at runtime. Esbuild
+          // (used by @angular/build:unit-test) also requires a real on-disk
+          // file for the URL spec — trampolines satisfy both bundlers.
+          monacoWorkerFactory: () => {
+            const env = getEnhancedMonacoEnvironment();
+            env.getWorker = (_workerId: string, label: string): Worker => {
+              switch (label) {
+                case "editorWorkerService":
+                  return new Worker(new URL("./workers/editor.worker", import.meta.url), { type: "module" });
+                case "extensionHostWorkerMain":
+                  return new Worker(new URL("./workers/extension-host.worker", import.meta.url), { type: "module" });
+                case "TextMateWorker":
+                  return new Worker(new URL("./workers/textmate.worker", import.meta.url), { type: "module" });
+                default:
+                  throw new Error(`No worker configured for label: ${label}`);
+              }
+            };

Review Comment:
   The `monacoWorkerFactory` callback configures `env.getWorker` but does not return `env`. If the `MonacoVscodeApiWrapper` expects the factory to return the enhanced environment, the worker wiring will be ignored and worker creation will fail at runtime. Return `env` from the factory (or set the expected global/field per the wrapper’s API).
   



##########
frontend/src/app/workspace/component/code-editor-dialog/code-editor.component.ts:
##########
@@ -187,97 +179,174 @@ export class CodeEditorComponent implements AfterViewInit, SafeStyle, OnDestroy
     this.workflowActionService.getTexeraGraph().updateSharedModelAwareness("editingCode", false);
     localStorage.setItem(this.currentOperatorId, this.containerElement.nativeElement.style.cssText);
 
-    if (isDefined(this.monacoBinding)) {
-      this.monacoBinding.destroy();
-    }
-
-    this.editorWrapper.dispose(true);
+    this.monacoBinding?.destroy();
+    this.languageClientWrapper?.dispose().catch(() => {});
+    this.languageClientWrapper = undefined;
+    this.editorApp?.dispose().catch(() => {});
+    this.editorApp = undefined;
 
-    if (isDefined(this.workflowVersionStreamSubject)) {
-      this.workflowVersionStreamSubject.next();
-      this.workflowVersionStreamSubject.complete();
-    }
+    this.workflowVersionStreamSubject.next();
+    this.workflowVersionStreamSubject.complete();

Review Comment:
   This previously guarded `workflowVersionStreamSubject` before calling `.next()`/`.complete()`. With the guard removed, `ngOnDestroy` can throw if the subject is ever left uninitialized. Either restore the guard or make the subject non-optional by initializing it at declaration/construction time.
   



##########
frontend/LICENSE-binary:
##########
@@ -290,11 +301,10 @@ Angular / npm packages:
   - lib0@0.2.117
   - lodash@4.18.1
   - lodash-es@4.18.1
-  - marked@17.0.1
+  - marked@14.0.0

Review Comment:
   `yarn.lock` shows both `marked@14.0.0` (transitive) and `marked@17.0.1` (direct dependency in `package.json`) are present, but `LICENSE-binary` now lists only `marked@14.0.0`. Please include both versions (or regenerate the license listing from the lockfile) to keep the third-party attribution accurate.
   



##########
frontend/src/jsdom-svg-polyfill.ts:
##########
@@ -17,128 +17,169 @@
  * under the License.
  */
 
-/**
- * jsdom doesn't implement the SVG geometry APIs (`SVGSVGElement#createSVGMatrix`,
- * `createSVGPoint`, `createSVGTransform`, `getScreenCTM`, `getCTM`,
- * `getBBox`). jointjs reaches into these during graph layout and crashes
- * the spec build with `TypeError: svgDocument.createSVGMatrix is not a
- * function` etc.
- *
- * The stubs below return identity-ish geometry: matrices/points behave like
- * the identity, bounding boxes report zero dimensions. That's enough for
- * jointjs construction code to not throw; specs that actually depend on
- * accurate geometry should run under Vitest browser mode rather than
- * jsdom (tracked in #4861), but the bulk of the texera specs only need
- * jointjs to instantiate cleanly.
- */
+// Test-environment polyfills + setup hooks for jsdom + the Angular
+// `@angular/build:unit-test` builder. Pulled in via `setupFiles` in
+// `angular.json`. Each block below patches one specific gap that surfaces
+// when the codingame monaco-vscode-* v25 stack or jointjs runs under jsdom.
+
+// Node ESM loader hook so every transitive `.css` import resolves to an empty
+// module. The unit-test builder pre-bundles spec files with `externalPackages:
+// true`, so imports like `monaco-languageclient` reach Node's native ESM
+// loader instead of Vite's transform pipeline — without the hook, every spec
+// that transitively loads the codingame v25 stack crashes with
+// `Unknown file extension ".css"`. Inline as a `data:` URL so we don't carry
+// a sidecar `.mjs`. Vitest re-evaluates this setup file once per spec file,
+// so we gate the registration with a `globalThis` flag — `module.register`
+// chains every call, and we don't want N hooks doing identical work for N
+// specs. Must run before any spec body imports the affected packages;
+// `module.register` needs Node 20.6+ (project pins Node ≥ 24).
+import { register as registerLoader } from "node:module";
+
+const CSS_HOOK_FLAG = Symbol.for("texera.cssLoaderHookRegistered");
+const flagHolder = globalThis as Record<symbol, boolean | undefined>;
+if (!flagHolder[CSS_HOOK_FLAG]) {
+  const cssLoaderHookSource = `
+export function resolve(specifier, context, nextResolve) {
+  if (specifier.endsWith(".css") || /\\.css(\\?|$)/.test(specifier)) {
+    return { url: "data:text/javascript,export%20default%20%7B%7D%3B", shortCircuit: true, format: "module" };
+  }
+  return nextResolve(specifier, context);
+}
+`;

Review Comment:
   The CSS loader hook resolves every `.css` import to a module exporting `{}`. If any runtime code reads the default export (e.g., expecting a `CSSStyleSheet` from `css-style-sheet` exports) this can cause follow-on type/shape errors. Consider exporting a more compatible stub (e.g., a `CSSStyleSheet` instance when available) so transitive consumers don’t break if they start using the imported value.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@texera.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org