This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 94aceba1fe924feb18cf318d63b6545aac300938
Author: Ryan Zhang <[email protected]>
AuthorDate: Mon Nov 9 21:09:12 2026 +0000

    feat(notebook-migration): add r prompts and build rudf operators for r 
sources (#8911)
    
    ### What changes were proposed in this PR?
    
    This is the second of the PRs adding R support to the migration tool
    (#8009), building on the prompt sets from #8910. It adds the R side of
    the conversion. Nothing is user visible yet: the import modal options
    arrive in #8912 and #8963, and the new flag defaults to off.
    
    **Flag.** `gui.workflow-workspace.r-notebook-migration-enabled`, default
    false, overridable with
    `GUI_WORKFLOW_WORKSPACE_R_NOTEBOOK_MIGRATION_ENABLED` and exposed to the
    frontend as `rNotebookMigrationEnabled`. R UDFs only run where the
    computing unit has the texera-rudf plugin installed
    (https://github.com/apache/texera/discussions/4155), and no Texera image
    ships it, so R stays off unless a deployment opts in. It sits under the
    existing migration flag rather than replacing it.
    
    **R prompts.** A new `migration-prompts-r.ts` holds an R version of each
    prompt, notebook and script, with the same JSON reply contract so
    parsing does not change. The design follows a spike against texera-rudf
    that ran chained R UDFs in a real workflow:
    
    * Every UDF uses the Table API: one `function(table, port)` that takes
    and returns a data.frame. `RUDF` needs `useTupleAPI` set explicitly, and
    teaching one API keeps generated code and the flag consistent.
    * Python passes objects between UDFs pickled in `binary` columns. R has
    no pickle, so a UDF whose output another UDF reads returns one row of
    `I(list(serialize(x, NULL)))` columns, and the reader calls
    `unserialize(table$x[[1]])`. The spike passed data.frames and fitted
    `lm` models this way between real workers.
    * A UDF no other UDF reads returns character columns. Texera's schema
    check rejects a number in a column `buildWorkflow` declares as `string`,
    and does not cast it.
    * Plots are converted with `ggplotly()` into a page that loads Plotly
    from a CDN, returned as `html-content`. `htmlwidgets::saveWidget` is
    ruled out because it needs pandoc.
    * Each UDF reads from at most one other UDF. Results a later step needs
    are carried along one chain instead of merged from branches, which
    avoids R UDFs having to union tables.
    
    The worked examples are the diabetes pipeline in R. Their line numbers,
    mapping ranges and JSON escaping were generated rather than typed, and
    all six example UDFs were run through texera-rudf on `diabetes.csv`,
    chained the way `buildWorkflow` wires them. Unlike the Python examples,
    they are valid JSON.
    
    **Wiring.** `MigrationLanguage` widens to `"python" | "r"`. The R prompt
    set builds `RUDF` operators with `useTupleAPI: false` through a new
    `properties` overlay (empty for Python, so Python operators are
    unchanged) and derives notebooks with the `ir` kernelspec. A
    `promptsFor` guard refuses an R conversion while the R flag is off,
    before any model call. `NotebookMigrationService` passes the language
    through.
    
    ### Any related issues, documentation, discussions?
    
    Part of #8009
    Parent-issue #4301
    
    The plan is in https://github.com/apache/texera/discussions/8866. The
    import modal options follow in #8912 (R notebooks) and #8963 (R files),
    which are stacked on this PR.
    
    ### How was this PR tested?
    
    * `migration-llm.spec.ts`, six new tests: the exact R prelude and
    prompts for notebooks and scripts, the full `RUDF` property set with
    binary and string outputs, the `ir` kernelspec on a derived notebook,
    the R flag blocking R without a model call, and Python still converting
    with the R flag off. The Python prompt tests from #8910 pass unchanged.
    * `migration-prompts-r.spec.ts`, new, ten tests guarding the worked
    examples: both example blocks parse as JSON, edges only reference
    defined UDFs, every UDF is a numbered Table API function, only UDFs
    another UDF reads call `serialize`, no UDF has two inputs, and the
    mapping cells and line ranges point at real, non blank lines.
    * `notebook-migration.service.spec.ts`, two new tests that the language
    reaches both conversions.
    * `GuiConfigSpec` checks the flag defaults to false.
    
    Coverage of `migration-llm.ts` and `notebook-migration.service.ts` stays
    at 100% of lines. The full frontend suite passes.
    
    End to end with a live model, through the modal from #8912 and #8963: an
    R script and an R notebook each converted to a workflow of Table API
    `RUDF` operators. Run on the source dataset, the script's workflow
    reported the same model accuracies as running the original script in
    `Rscript`, and its plot rendered through an HTML Visualizer.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
    
    ---------
    
    Co-authored-by: Meng Wang <[email protected]>
---
 common/config/src/main/resources/gui.conf          |   4 +
 .../apache/texera/common/config/GuiConfig.scala    |   2 +
 .../texera/common/config/GuiConfigSpec.scala       |   3 +
 .../texera/service/resource/ConfigResource.scala   |   3 +-
 .../app/common/service/gui-config.service.mock.ts  |   1 +
 frontend/src/app/common/type/gui-config.ts         |   1 +
 .../notebook-migration/migration-llm.spec.ts       | 113 ++++-
 .../service/notebook-migration/migration-llm.ts    |  76 +++-
 .../notebook-migration/migration-prompts-r.spec.ts |  98 +++++
 .../notebook-migration/migration-prompts-r.ts      | 464 +++++++++++++++++++++
 .../notebook-migration.service.spec.ts             |  56 ++-
 .../notebook-migration.service.ts                  |  32 +-
 12 files changed, 821 insertions(+), 32 deletions(-)

diff --git a/common/config/src/main/resources/gui.conf 
b/common/config/src/main/resources/gui.conf
index d770b4ffd2..3a60b2dde1 100644
--- a/common/config/src/main/resources/gui.conf
+++ b/common/config/src/main/resources/gui.conf
@@ -136,6 +136,10 @@ gui {
     # how long a single AI python-notebook migration LLM request may run 
before it is aborted
     python-notebook-migration-timeout-minutes = 10
     python-notebook-migration-timeout-minutes = 
${?GUI_WORKFLOW_WORKSPACE_PYTHON_NOTEBOOK_MIGRATION_TIMEOUT_MINUTES}
+
+    # whether the migration tool also accepts R; needs the texera-rudf plugin 
on computing units
+    r-notebook-migration-enabled = false
+    r-notebook-migration-enabled = 
${?GUI_WORKFLOW_WORKSPACE_R_NOTEBOOK_MIGRATION_ENABLED}
   }
 
   # whether to show the "Powered by Texera" attribution link in the sidebar
diff --git 
a/common/config/src/main/scala/org/apache/texera/common/config/GuiConfig.scala 
b/common/config/src/main/scala/org/apache/texera/common/config/GuiConfig.scala
index 6283a8c225..84cf904342 100644
--- 
a/common/config/src/main/scala/org/apache/texera/common/config/GuiConfig.scala
+++ 
b/common/config/src/main/scala/org/apache/texera/common/config/GuiConfig.scala
@@ -85,4 +85,6 @@ object GuiConfig {
     conf.getBoolean("gui.workflow-workspace.python-notebook-migration-enabled")
   val guiWorkflowWorkspacePythonNotebookMigrationTimeoutMinutes: Int =
     
conf.getInt("gui.workflow-workspace.python-notebook-migration-timeout-minutes")
+  val guiWorkflowWorkspaceRNotebookMigrationEnabled: Boolean =
+    conf.getBoolean("gui.workflow-workspace.r-notebook-migration-enabled")
 }
diff --git 
a/common/config/src/test/scala/org/apache/texera/common/config/GuiConfigSpec.scala
 
b/common/config/src/test/scala/org/apache/texera/common/config/GuiConfigSpec.scala
index cfc978de3a..f1e63fb5e8 100644
--- 
a/common/config/src/test/scala/org/apache/texera/common/config/GuiConfigSpec.scala
+++ 
b/common/config/src/test/scala/org/apache/texera/common/config/GuiConfigSpec.scala
@@ -82,6 +82,9 @@ class GuiConfigSpec extends AnyFlatSpec with Matchers {
     ifUnset("GUI_WORKFLOW_WORKSPACE_PYTHON_NOTEBOOK_MIGRATION_ENABLED")(
       GuiConfig.guiWorkflowWorkspacePythonNotebookMigrationEnabled shouldBe 
false
     )
+    ifUnset("GUI_WORKFLOW_WORKSPACE_R_NOTEBOOK_MIGRATION_ENABLED")(
+      GuiConfig.guiWorkflowWorkspaceRNotebookMigrationEnabled shouldBe false
+    )
   }
 
   "GuiConfig string settings" should "resolve to their gui.conf defaults when 
env overrides are unset" in {
diff --git 
a/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala
 
b/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala
index e3dff08575..ab8eaa9030 100644
--- 
a/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala
+++ 
b/config-service/src/main/scala/org/apache/texera/service/resource/ConfigResource.scala
@@ -104,7 +104,8 @@ class ConfigResource {
       "aiFixModel" -> GuiConfig.guiWorkflowWorkspaceAiFixModel,
       "limitColumns" -> GuiConfig.guiWorkflowWorkspaceLimitColumns,
       "pythonNotebookMigrationEnabled" -> 
GuiConfig.guiWorkflowWorkspacePythonNotebookMigrationEnabled,
-      "pythonNotebookMigrationTimeoutMinutes" -> 
GuiConfig.guiWorkflowWorkspacePythonNotebookMigrationTimeoutMinutes
+      "pythonNotebookMigrationTimeoutMinutes" -> 
GuiConfig.guiWorkflowWorkspacePythonNotebookMigrationTimeoutMinutes,
+      "rNotebookMigrationEnabled" -> 
GuiConfig.guiWorkflowWorkspaceRNotebookMigrationEnabled
     )
 
   // Engine configs.
diff --git a/frontend/src/app/common/service/gui-config.service.mock.ts 
b/frontend/src/app/common/service/gui-config.service.mock.ts
index e108856bed..ccc746d95f 100644
--- a/frontend/src/app/common/service/gui-config.service.mock.ts
+++ b/frontend/src/app/common/service/gui-config.service.mock.ts
@@ -60,6 +60,7 @@ export class MockGuiConfigService {
     attributionEnabled: false,
     pythonNotebookMigrationEnabled: false,
     pythonNotebookMigrationTimeoutMinutes: 10,
+    rNotebookMigrationEnabled: false,
     deploymentVersionCheckEnabled: false,
   };
 
diff --git a/frontend/src/app/common/type/gui-config.ts 
b/frontend/src/app/common/type/gui-config.ts
index c84c104416..451ce25f1c 100644
--- a/frontend/src/app/common/type/gui-config.ts
+++ b/frontend/src/app/common/type/gui-config.ts
@@ -50,6 +50,7 @@ export interface GuiConfig {
   attributionEnabled: boolean;
   pythonNotebookMigrationEnabled: boolean;
   pythonNotebookMigrationTimeoutMinutes: number;
+  rNotebookMigrationEnabled: boolean;
   deploymentVersionCheckEnabled: boolean;
 }
 
diff --git 
a/frontend/src/app/workspace/service/notebook-migration/migration-llm.spec.ts 
b/frontend/src/app/workspace/service/notebook-migration/migration-llm.spec.ts
index 4503417a1c..b4a75851f4 100644
--- 
a/frontend/src/app/workspace/service/notebook-migration/migration-llm.spec.ts
+++ 
b/frontend/src/app/workspace/service/notebook-migration/migration-llm.spec.ts
@@ -41,6 +41,18 @@ import {
   SCRIPT_WORKFLOW_PROMPT,
   SCRIPT_MAPPING_PROMPT,
 } from "./migration-prompts";
+import {
+  R_TEXERA_OVERVIEW,
+  R_UDF_DOCUMENTATION,
+  R_DATA_PASSING_DOCUMENTATION,
+  R_VISUALIZER_DOCUMENTATION,
+  R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION,
+  R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT,
+  R_WORKFLOW_PROMPT,
+  R_MAPPING_PROMPT,
+  R_SCRIPT_WORKFLOW_PROMPT,
+  R_SCRIPT_MAPPING_PROMPT,
+} from "./migration-prompts-r";
 import { GuiConfigService } from "../../../common/service/gui-config.service";
 import { WorkflowUtilService } from 
"../workflow-graph/util/workflow-util.service";
 import { AuthService } from "../../../common/service/user/auth.service";
@@ -56,10 +68,11 @@ describe("NotebookMigrationLLM", () => {
 
   // Build a fresh, initialized session with stubbed dependencies. The stubbed
   // getNewOperatorPredicate hands out deterministic ids (PythonUDFV2-0, -1, 
...).
-  function makeLLM(): NotebookMigrationLLM {
+  function makeLLM(rNotebookMigrationEnabled = true): NotebookMigrationLLM {
     const stubConfig = {
       env: {
         pythonNotebookMigrationEnabled: true,
+        rNotebookMigrationEnabled,
         pythonNotebookMigrationTimeoutMinutes: 10,
         defaultDataTransferBatchSize: 400,
         defaultExecutionMode: "PIPELINED",
@@ -400,6 +413,104 @@ describe("NotebookMigrationLLM", () => {
     });
   });
 
+  describe("R prompts", () => {
+    const workflowResponse = JSON.stringify({
+      code: { UDF1: "# UDF1", UDF2: "# UDF2" },
+      edges: [["UDF1", "UDF2"]],
+      outputs: { UDF1: ["data"], UDF2: ["result"] },
+    });
+    const documentation = [
+      R_TEXERA_OVERVIEW,
+      R_UDF_DOCUMENTATION,
+      R_DATA_PASSING_DOCUMENTATION,
+      R_VISUALIZER_DOCUMENTATION,
+      R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION,
+    ];
+
+    function contentsFor(role: string): string[] {
+      return (callModelSpy.mock.calls[0][0] as { role: string; content: string 
}[])
+        .filter(message => message.role === role)
+        .map(message => message.content);
+    }
+
+    it("sends the R notebook prelude and prompts", async () => {
+      mockResponses(workflowResponse, JSON.stringify({ UDF1: ["CELL1"] }));
+
+      await makeLLM().convertNotebookToWorkflow({ cells: [codeCell("CELL1", "x 
<- 1")] }, "r");
+
+      expect(contentsFor("system")).toEqual(documentation);
+      const [workflowPrompt, mappingPrompt] = contentsFor("user");
+      expect(workflowPrompt.startsWith(`${R_WORKFLOW_PROMPT}\n`)).toBe(true);
+      expect(mappingPrompt).toBe(R_MAPPING_PROMPT);
+    });
+
+    it("sends the R script prelude and prompts", async () => {
+      mockResponses(workflowResponse, JSON.stringify({ UDF1: [[1, 1]] }));
+
+      await makeLLM().convertScriptToWorkflow("x <- 1", "r");
+
+      expect(contentsFor("system")).toEqual(
+        documentation.map(doc =>
+          doc === R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION ? 
R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT : doc
+        )
+      );
+      const [workflowPrompt, mappingPrompt] = contentsFor("user");
+      
expect(workflowPrompt.startsWith(`${R_SCRIPT_WORKFLOW_PROMPT}\n`)).toBe(true);
+      expect(mappingPrompt).toBe(R_SCRIPT_MAPPING_PROMPT);
+    });
+
+    it("builds Table API RUDF operators", async () => {
+      mockResponses(workflowResponse, JSON.stringify({ UDF1: ["CELL1"] }));
+
+      const result = await makeLLM().convertNotebookToWorkflow({ cells: 
[codeCell("CELL1", "x <- 1")] }, "r");
+      const { workflowJSON } = JSON.parse(result);
+
+      expect(stubUtil.getNewOperatorPredicate).toHaveBeenCalledWith("RUDF", 
"UDF1");
+      expect(workflowJSON.operators.map((op: any) => 
op.operatorType)).toEqual(["RUDF", "RUDF"]);
+      expect(workflowJSON.operators[0].operatorProperties).toEqual({
+        workers: 1,
+        defaultEnv: true,
+        envName: "",
+        useTupleAPI: false,
+        code: "# UDF1",
+        retainInputColumns: false,
+        outputColumns: [{ attributeName: "data", attributeType: "binary" }],
+      });
+      
expect(workflowJSON.operators[1].operatorProperties.outputColumns).toEqual([
+        { attributeName: "result", attributeType: "string" },
+      ]);
+    });
+
+    it("derives an R notebook from a script", async () => {
+      mockResponses(workflowResponse, JSON.stringify({ UDF1: [[1, 1]] }));
+
+      const { notebook } = await makeLLM().convertScriptToWorkflow("x <- 1", 
"r");
+
+      expect(notebook.metadata).toEqual({
+        kernelspec: { display_name: "R", language: "R", name: "ir" },
+        language_info: { name: "R" },
+      });
+    });
+
+    it("refuses R conversions while the R flag is off", async () => {
+      const llm = makeLLM(false);
+
+      await expect(llm.convertNotebookToWorkflow({ cells: [codeCell("CELL1", 
"x <- 1")] }, "r")).rejects.toThrow(
+        "R notebook migration is disabled"
+      );
+      await expect(llm.convertScriptToWorkflow("x <- 1", 
"r")).rejects.toThrow("R notebook migration is disabled");
+      expect(callModelSpy).not.toHaveBeenCalled();
+    });
+
+    it("still converts Python while the R flag is off", async () => {
+      mockResponses(workflowResponse, JSON.stringify({ UDF1: [[1, 1]] }));
+
+      const { workflowJSON } = await 
makeLLM(false).convertScriptToWorkflow("print(1)");
+
+      expect(workflowJSON.operators[0].operatorType).toBe("PythonUDFV2");
+    });
+  });
+
   describe("parseJsonResponse", () => {
     // parseJsonResponse is private; cast to access it directly for focused 
coverage.
     const parse = (raw: string) => (makeLLM() as any).parseJsonResponse(raw, 
"workflow");
diff --git 
a/frontend/src/app/workspace/service/notebook-migration/migration-llm.ts 
b/frontend/src/app/workspace/service/notebook-migration/migration-llm.ts
index f20a4c5700..a8040a737d 100644
--- a/frontend/src/app/workspace/service/notebook-migration/migration-llm.ts
+++ b/frontend/src/app/workspace/service/notebook-migration/migration-llm.ts
@@ -46,6 +46,18 @@ import {
   FOLDER_MAPPING_PROMPT,
   FOLDER_CODE_PROMPT,
 } from "./migration-prompts";
+import {
+  R_TEXERA_OVERVIEW,
+  R_UDF_DOCUMENTATION,
+  R_DATA_PASSING_DOCUMENTATION,
+  R_VISUALIZER_DOCUMENTATION,
+  R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION,
+  R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT,
+  R_WORKFLOW_PROMPT,
+  R_MAPPING_PROMPT,
+  R_SCRIPT_WORKFLOW_PROMPT,
+  R_SCRIPT_MAPPING_PROMPT,
+} from "./migration-prompts-r";
 import { DerivedCell, ScriptSegmentation, segmentScript, splitScriptLines } 
from "./script-segmentation";
 import { FolderDocument, resolveEntryPoint, scopeSegmentationToSpan } from 
"./folder-assembly";
 
@@ -142,7 +154,25 @@ const PYTHON_FOLDER_DOCUMENTATION: string[] = 
PYTHON_SCRIPT_DOCUMENTATION.map(do
   doc === EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT ? 
EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER : doc
 );
 
-export type MigrationLanguage = "python";
+const R_NOTEBOOK_DOCUMENTATION: string[] = [
+  R_TEXERA_OVERVIEW,
+  R_UDF_DOCUMENTATION,
+  R_DATA_PASSING_DOCUMENTATION,
+  R_VISUALIZER_DOCUMENTATION,
+  R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION,
+];
+
+const R_SCRIPT_DOCUMENTATION: string[] = R_NOTEBOOK_DOCUMENTATION.map(doc =>
+  doc === R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION ? 
R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT : doc
+);
+
+export type MigrationLanguage = "python" | "r";
+
+interface UdfOperator {
+  type: string;
+  // Overlaid on the schema defaults before the generated code and outputs.
+  properties: Record<string, unknown>;
+}
 
 interface MigrationPromptSet {
   notebookDocumentation: string[];
@@ -151,7 +181,7 @@ interface MigrationPromptSet {
   scriptDocumentation: string[];
   scriptWorkflowPrompt: string;
   scriptMappingPrompt: string;
-  operatorType: string;
+  operator: UdfOperator;
   notebookMetadata: Notebook["metadata"];
 }
 
@@ -163,12 +193,26 @@ const PROMPT_SETS: Record<MigrationLanguage, 
MigrationPromptSet> = {
     scriptDocumentation: PYTHON_SCRIPT_DOCUMENTATION,
     scriptWorkflowPrompt: SCRIPT_WORKFLOW_PROMPT,
     scriptMappingPrompt: SCRIPT_MAPPING_PROMPT,
-    operatorType: "PythonUDFV2",
+    operator: { type: "PythonUDFV2", properties: {} },
     notebookMetadata: {
       kernelspec: { display_name: "Python 3", language: "python", name: 
"python3" },
       language_info: { name: "python" },
     },
   },
+  r: {
+    notebookDocumentation: R_NOTEBOOK_DOCUMENTATION,
+    notebookWorkflowPrompt: R_WORKFLOW_PROMPT,
+    notebookMappingPrompt: R_MAPPING_PROMPT,
+    scriptDocumentation: R_SCRIPT_DOCUMENTATION,
+    scriptWorkflowPrompt: R_SCRIPT_WORKFLOW_PROMPT,
+    scriptMappingPrompt: R_SCRIPT_MAPPING_PROMPT,
+    // The prompts only teach the Table API.
+    operator: { type: "RUDF", properties: { useTupleAPI: false } },
+    notebookMetadata: {
+      kernelspec: { display_name: "R", language: "R", name: "ir" },
+      language_info: { name: "R" },
+    },
+  },
 };
 
 /**
@@ -235,6 +279,13 @@ export class NotebookMigrationLLM {
     return this.config.env.pythonNotebookMigrationEnabled;
   }
 
+  private promptsFor(language: MigrationLanguage): MigrationPromptSet {
+    if (language === "r" && !this.config.env.rNotebookMigrationEnabled) {
+      throw new Error("R notebook migration is disabled");
+    }
+    return PROMPT_SETS[language];
+  }
+
   private assertEnabled(): void {
     if (!this.enabled) {
       throw new Error("Notebook migration feature is disabled");
@@ -393,7 +444,7 @@ export class NotebookMigrationLLM {
       throw new Error("LLM session not initialized");
     }
 
-    const prompts = PROMPT_SETS[language];
+    const prompts = this.promptsFor(language);
     // Reset to the documentation prelude so a prior conversion's 
prompts/responses
     // don't leak into this one. The two sendPrompt calls below still share 
history.
     this.seedDocumentation(prompts.notebookDocumentation);
@@ -421,7 +472,7 @@ export class NotebookMigrationLLM {
 
     // Remove ```json blocks and parse
     const udfLLMResponse = this.parseJsonResponse(workflow, "workflow");
-    const { workflowJSON, udfIdToOperatorId } = 
this.buildWorkflow(udfLLMResponse, prompts.operatorType);
+    const { workflowJSON, udfIdToOperatorId } = 
this.buildWorkflow(udfLLMResponse, prompts.operator);
 
     // The notebook path keys its mapping on the cell uuids embedded in the 
prompt.
     const parsedMapping: Record<string, string[]> = 
this.parseJsonResponse(mapping, "mapping");
@@ -447,12 +498,12 @@ export class NotebookMigrationLLM {
       throw new Error("LLM session not initialized");
     }
 
-    const prompts = PROMPT_SETS[language];
+    const prompts = this.promptsFor(language);
     const { workflowJSON, udfIdToOperatorId, reportedRanges } = await 
this.requestConversion(
       prompts.scriptDocumentation,
       prompts.scriptWorkflowPrompt,
       prompts.scriptMappingPrompt,
-      prompts.operatorType,
+      prompts.operator,
       source
     );
 
@@ -486,7 +537,7 @@ export class NotebookMigrationLLM {
       PYTHON_FOLDER_DOCUMENTATION,
       FOLDER_WORKFLOW_PROMPT,
       FOLDER_MAPPING_PROMPT,
-      prompts.operatorType,
+      prompts.operator,
       document.source,
       // The layout is prompt text, never part of the numbered document: 
numbering it would shift
       // every line the model reports, and the segmenter would emit it as a 
cell of directory
@@ -518,7 +569,7 @@ export class NotebookMigrationLLM {
     documentation: string[],
     workflowPrompt: string,
     mappingPrompt: string,
-    operatorType: string,
+    udfOperator: UdfOperator,
     source: string,
     preamble?: string
   ): Promise<{
@@ -534,7 +585,7 @@ export class NotebookMigrationLLM {
     const mapping = await this.sendPrompt(mappingPrompt);
 
     const workflowResponse = this.parseJsonResponse(workflow, "workflow");
-    const { workflowJSON, udfIdToOperatorId } = 
this.buildWorkflow(workflowResponse, operatorType);
+    const { workflowJSON, udfIdToOperatorId } = 
this.buildWorkflow(workflowResponse, udfOperator);
 
     return {
       workflowJSON,
@@ -568,7 +619,7 @@ export class NotebookMigrationLLM {
    */
   private buildWorkflow(
     udfLLMResponse: any,
-    operatorType: string
+    udfOperator: UdfOperator
   ): {
     workflowJSON: WorkflowJSON;
     udfIdToOperatorId: Record<string, string>;
@@ -603,11 +654,12 @@ export class NotebookMigrationLLM {
 
       // Build the operator from the live schema so the operatorVersion, 
ports, and property
       // defaults track the backend definition, then overlay the generated 
code/outputs.
-      const base = 
this.workflowUtilService.getNewOperatorPredicate(operatorType, udfId);
+      const base = 
this.workflowUtilService.getNewOperatorPredicate(udfOperator.type, udfId);
       const operator: OperatorPredicate = {
         ...base,
         operatorProperties: {
           ...base.operatorProperties,
+          ...udfOperator.properties,
           code: udfCode,
           retainInputColumns: false,
           outputColumns: udfOutputColumns,
diff --git 
a/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.spec.ts
 
b/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.spec.ts
new file mode 100644
index 0000000000..f7b9341fd5
--- /dev/null
+++ 
b/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.spec.ts
@@ -0,0 +1,98 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import {
+  R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION,
+  R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT,
+  R_MAPPING_PROMPT,
+  R_SCRIPT_MAPPING_PROMPT,
+} from "./migration-prompts-r";
+
+interface Conversion {
+  code: Record<string, string>;
+  edges: [string, string][];
+  outputs: Record<string, string[]>;
+}
+
+function fencedBlock(prompt: string, language: string): string {
+  const match = prompt.match(new RegExp("```" + language + 
"\\n([\\s\\S]*?)\\n```"));
+  expect(match).not.toBeNull();
+  return match![1];
+}
+
+function mappingIn(prompt: string): Record<string, unknown> {
+  return JSON.parse(prompt.slice(prompt.indexOf("{"), prompt.lastIndexOf("}") 
+ 1));
+}
+
+describe("R migration prompts", () => {
+  [
+    ["notebook", R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION],
+    ["script", R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT],
+  ].forEach(([input, example]) => {
+    describe(`${input} worked example`, () => {
+      const conversion: Conversion = JSON.parse(fencedBlock(example, "json"));
+      const udfIds = Object.keys(conversion.code);
+      const edgeSources = new Set(conversion.edges.map(([source]) => source));
+
+      it("only references UDFs it defines", () => {
+        conversion.edges.flat().forEach(udfId => 
expect(udfIds).toContain(udfId));
+        
expect(Object.keys(conversion.outputs).sort()).toEqual([...udfIds].sort());
+      });
+
+      it("writes every UDF as a numbered Table API function", () => {
+        udfIds.forEach(udfId => {
+          const code = conversion.code[udfId];
+          expect(code.startsWith(`# ${udfId}\n`)).toBe(true);
+          expect(code).toContain("function(table, port)");
+          expect(code).not.toContain("coro");
+        });
+      });
+
+      it("serializes only the outputs another UDF reads", () => {
+        udfIds.forEach(udfId => {
+          
expect(/(?<!un)serialize\(/.test(conversion.code[udfId])).toBe(edgeSources.has(udfId));
+        });
+      });
+
+      it("gives each UDF at most one upstream UDF", () => {
+        const targets = conversion.edges.map(([, target]) => target);
+        expect(new Set(targets).size).toBe(targets.length);
+      });
+    });
+  });
+
+  it("maps the notebook example's UDFs to cells it contains", () => {
+    const notebook = fencedBlock(R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION, "r");
+    Object.values(mappingIn(R_MAPPING_PROMPT) as Record<string, string[]>)
+      .flat()
+      .forEach(cell => expect(notebook).toContain(`# START ${cell}\n`));
+  });
+
+  it("maps the script example's UDFs to non-blank lines it contains", () => {
+    const lines = fencedBlock(R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT, 
"r").split("\n");
+    Object.values(mappingIn(R_SCRIPT_MAPPING_PROMPT) as Record<string, 
[number, number][]>)
+      .flat()
+      .forEach(([first, last]) => {
+        expect(first).toBeLessThanOrEqual(last);
+        expect(last).toBeLessThanOrEqual(lines.length);
+        expect(lines[first - 1]).toMatch(new RegExp(`^ *${first}\\| +\\S`));
+        expect(lines[last - 1]).toMatch(new RegExp(`^ *${last}\\| +\\S`));
+      });
+  });
+});
diff --git 
a/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.ts 
b/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.ts
new file mode 100644
index 0000000000..0f77f97e4c
--- /dev/null
+++ 
b/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.ts
@@ -0,0 +1,464 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Prompts for converting R sources into RUDF operators (Table API only).
+
+export const R_TEXERA_OVERVIEW = `
+You are a robust compiler that takes R code and translates it into R 
user-defined functions (UDFs) for our workflow environment Texera.
+
+Texera is a data analytics tool that uses workflows to do machine learning and 
data analytics computation. Users drag and drop operators and connect their 
inputs and outputs in a graphical workflow editor, and the code we create runs 
inside those operators.
+
+Texera runs R UDFs with its Table API. The code of a Table API UDF ends with a 
function of two arguments, and that function is the value the code evaluates to:
+
+function(table, port) {
+  return(table)
+}
+
+table is an R data.frame holding every row that arrived on the input port, and 
port is the index of that port, starting at 0. The function returns a 
data.frame with at least one row. When there is nothing to report, return one 
row that says so. Each returned row becomes an output row and each column an 
output column.
+Code before the function, such as library() calls, runs once when the operator 
starts.
+`;
+
+export const R_UDF_DOCUMENTATION = `
+Rules for writing Texera R UDF code:
+1. Always use the Table API template above. Never use coro::generator or the 
Tuple API.
+2. Load packages with library() before the function. Never call 
install.packages().
+3. Read columns with table$column or table[['column']]. Check missing values 
with is.na() before comparing them.
+4. Do not read or write files, and do not call setwd(). Data arrives only 
through the table argument.
+5. Output that the original code prints or displays is returned as columns 
instead.
+6. Keep each UDF focused on one step of the original code.
+`;
+
+export const R_DATA_PASSING_DOCUMENTATION = `
+Texera R UDFs pass data to each other in data.frame columns, so R objects 
travel in serialized form.
+
+A UDF whose output another UDF reads returns a data.frame with exactly one 
row. Every column holds one R object, serialized:
+
+data.frame(
+  data = I(list(serialize(data, NULL))),
+  model = I(list(serialize(model, NULL)))
+)
+
+Any R object can be passed this way: data.frames, vectors, lists, and fitted 
models. The receiving UDF restores each object with unserialize():
+
+data <- unserialize(table$data[[1]])
+model <- unserialize(table$model[[1]])
+
+A UDF that no other UDF reads is shown to the user, so every column it returns 
must be character. Convert other values with as.character(), sprintf(), or 
paste(capture.output(print(x)), collapse = '\\n').
+`;
+
+export const R_VISUALIZER_DOCUMENTATION = `
+To show a plot, a UDF returns a single column named html-content holding a 
complete HTML page.
+1. Build the plot with plotly. Convert an existing ggplot2 plot with 
ggplotly(p) so the original plot code is kept.
+2. Turn the plot into a page that loads Plotly from a CDN. Do not use 
htmlwidgets::saveWidget, it needs pandoc, which is not available.
+3. If the input has no rows, return an html-content page explaining that the 
plot is not available.
+
+json <- plotly_json(ggplotly(p), jsonedit = FALSE)
+html <- paste0(
+  '<html><head><script 
src="https://cdn.plot.ly/plotly-2.35.2.min.js";></script></head>',
+  '<body><div id="plot" style="width:100%;height:100%"></div><script>',
+  'var fig = ', json, '; Plotly.newPlot("plot", fig.data, fig.layout);',
+  '</script></body></html>'
+)
+data.frame('html-content' = html, check.names = FALSE)
+`;
+
+export const R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION = `
+Here is an example of breaking up R code into multiple Texera R UDFs. Format 
your response structure exactly like the given example. The "code" key contains 
a dictionary of the UDF IDs with their respective code. The "edges" key 
contains a list of pairs that contains the connections between UDFs. The 
"outputs" key contains a dictionary of the UDF IDs with a list of the output 
column names of the data.frame that the UDF returns. The UDFs can branch, so it 
does not have to be a linear chai [...]
+
+Original Code:
+\`\`\`r
+# START CELL1
+library(ggplot2)
+library(rpart)
+# END CELL1
+
+# START CELL2
+# Load the dataset
+data <- read.csv('diabetes.csv')
+# END CELL2
+
+# START CELL3
+# Remove duplicate rows
+data <- unique(data)
+
+# Remove rows with missing values
+data <- na.omit(data)
+# END CELL3
+
+# START CELL4
+# Print the minimum, maximum, and mean for all fields
+print(sapply(data, min))
+print(sapply(data, max))
+print(colMeans(data))
+# END CELL4
+
+# START CELL5
+# Boxplot of glucose by outcome
+ggplot(data, aes(x = factor(Outcome), y = Glucose)) +
+  geom_boxplot() +
+  labs(x = 'Outcome', y = 'Glucose', title = 'Glucose by Outcome')
+# END CELL5
+
+# START CELL6
+# Split data into training and testing sets (80% train, 20% test)
+set.seed(42)
+train_idx <- sample(seq_len(nrow(data)), size = floor(0.8 * nrow(data)))
+train <- data[train_idx, ]
+test <- data[-train_idx, ]
+# END CELL6
+
+# START CELL7
+# Scale features using the training set center and spread
+features <- setdiff(names(data), 'Outcome')
+centers <- sapply(train[features], mean)
+spreads <- sapply(train[features], sd)
+train[features] <- scale(train[features], center = centers, scale = spreads)
+test[features] <- scale(test[features], center = centers, scale = spreads)
+# END CELL7
+
+# START CELL8
+# Train logistic regression model
+glm_model <- glm(Outcome ~ ., data = train, family = binomial)
+glm_pred <- ifelse(predict(glm_model, test, type = 'response') > 0.5, 1, 0)
+glm_accuracy <- mean(glm_pred == test$Outcome)
+print(sprintf('Logistic Regression Accuracy: %.2f%%', 100 * glm_accuracy))
+# END CELL8
+
+# START CELL9
+# Train decision tree model
+tree_model <- rpart(factor(Outcome) ~ ., data = train, method = 'class')
+tree_pred <- predict(tree_model, test, type = 'class')
+tree_accuracy <- mean(as.character(tree_pred) == as.character(test$Outcome))
+print(sprintf('Decision Tree Accuracy: %.2f%%', 100 * tree_accuracy))
+# END CELL9
+\`\`\`
+
+Texera UDF conversion:
+\`\`\`json
+{
+    "code": {
+        "UDF1": "# UDF1\\nfunction(table, port) {\\n  # Remove duplicate 
rows\\n  data <- unique(table)\\n\\n  # Remove rows with missing values\\n  
data <- na.omit(data)\\n\\n  # One row of serialized objects for the downstream 
UDFs\\n  data.frame(data = I(list(serialize(data, NULL))))\\n}",
+        "UDF2": "# UDF2\\nfunction(table, port) {\\n  data <- 
unserialize(table$data[[1]])\\n\\n  # Calculate the minimum, maximum, and mean 
for all fields\\n  min_values <- sapply(data, min)\\n  max_values <- 
sapply(data, max)\\n  mean_values <- colMeans(data)\\n\\n  # No UDF reads this 
one, so its columns are character\\n  data.frame(\\n    min_values = 
paste(capture.output(print(min_values)), collapse = '\\\\n'),\\n    max_values 
= paste(capture.output(print(max_values)), collapse = ' [...]
+        "UDF3": "# 
UDF3\\nlibrary(ggplot2)\\nlibrary(plotly)\\n\\nfunction(table, port) {\\n  data 
<- unserialize(table$data[[1]])\\n\\n  if (nrow(data) == 0) {\\n    html <- 
'<h1>Boxplot is not available.</h1><p>Reason is: input table is empty.</p>'\\n  
  return(data.frame('html-content' = html, check.names = FALSE))\\n  }\\n\\n  # 
Boxplot of glucose by outcome\\n  p <- ggplot(data, aes(x = factor(Outcome), y 
= Glucose)) +\\n    geom_boxplot() +\\n    labs(x = 'Outcome', y = 'Glucose',  
[...]
+        "UDF4": "# UDF4\\nfunction(table, port) {\\n  data <- 
unserialize(table$data[[1]])\\n\\n  # Split data into training and testing sets 
(80% train, 20% test)\\n  set.seed(42)\\n  train_idx <- 
sample(seq_len(nrow(data)), size = floor(0.8 * nrow(data)))\\n  train <- 
data[train_idx, ]\\n  test <- data[-train_idx, ]\\n\\n  # Scale features using 
the training set center and spread\\n  features <- setdiff(names(data), 
'Outcome')\\n  centers <- sapply(train[features], mean)\\n  spreads <- [...]
+        "UDF5": "# UDF5\\nfunction(table, port) {\\n  train <- 
unserialize(table$train[[1]])\\n  test <- unserialize(table$test[[1]])\\n\\n  # 
Train logistic regression model\\n  glm_model <- glm(Outcome ~ ., data = train, 
family = binomial)\\n  glm_pred <- ifelse(predict(glm_model, test, type = 
'response') > 0.5, 1, 0)\\n  glm_accuracy <- mean(glm_pred == 
test$Outcome)\\n\\n  # No UDF reads this one, so its columns are character\\n  
data.frame(glm_accuracy = sprintf('Logistic Regression [...]
+        "UDF6": "# UDF6\\nlibrary(rpart)\\n\\nfunction(table, port) {\\n  
train <- unserialize(table$train[[1]])\\n  test <- 
unserialize(table$test[[1]])\\n\\n  # Train decision tree model\\n  tree_model 
<- rpart(factor(Outcome) ~ ., data = train, method = 'class')\\n  tree_pred <- 
predict(tree_model, test, type = 'class')\\n  tree_accuracy <- 
mean(as.character(tree_pred) == as.character(test$Outcome))\\n\\n  # No UDF 
reads this one, so its columns are character\\n  data.frame(tree_accur [...]
+    },
+    "edges": [
+        [
+            "UDF1",
+            "UDF2"
+        ],
+        [
+            "UDF1",
+            "UDF3"
+        ],
+        [
+            "UDF1",
+            "UDF4"
+        ],
+        [
+            "UDF4",
+            "UDF5"
+        ],
+        [
+            "UDF4",
+            "UDF6"
+        ]
+    ],
+    "outputs": {
+        "UDF1": [
+            "data"
+        ],
+        "UDF2": [
+            "min_values",
+            "max_values",
+            "mean_values"
+        ],
+        "UDF3": [
+            "html-content"
+        ],
+        "UDF4": [
+            "train",
+            "test"
+        ],
+        "UDF5": [
+            "glm_accuracy"
+        ],
+        "UDF6": [
+            "tree_accuracy"
+        ]
+    }
+}
+\`\`\`
+`;
+
+export const R_WORKFLOW_PROMPT = `You are an expert in R coding and workflow 
systems.
+Many users of Texera system are non-technical, but the notebooks they provide 
are written by technical people.
+They want to convert their notebooks to Texera workflows.
+Your goal is to help convert these notebooks into a Texera workflow that 
non-technical users can use directly.
+So do not remove or modify any user-defined functions, preserve their names 
and structure as they are.
+Ensure that all essential logic remains intact.
+Create multiple Texera R UDF codes using the provided R code.
+Number each UDF, starting at 1 and incrementing, by starting with a comment 
that states that UDF number.
+
+Every UDF uses the Table API: its code ends with one function(table, port) 
that takes a data.frame and returns a data.frame.
+Do not use the Tuple API or coro generators.
+Load every package a UDF uses with library() before its function. Do not call 
install.packages().
+
+Do not load data from a file in the first UDF; the workflow's source operator 
supplies the initial data,
+so assume it is already given to you as the table argument. Replacing 
file-loading code with this input
+is the one exception to preserving all original code (see below).
+Separate operators as if they will run in different R sessions: a UDF sees 
only the table it receives.
+
+Each UDF has exactly one output, so follow the data passing rules:
+a UDF whose output another UDF reads returns one row where every column is a 
serialized R object,
+and a UDF that no other UDF reads returns character columns.
+Ensure all information is passed on (including training and testing data) if 
subsequent UDFs need it.
+Each UDF has one input. When a step needs results from several earlier UDFs, 
carry those results forward
+through a single chain instead of connecting several UDFs into one.
+Values the original code prints become columns of the returned data.frame.
+Plots follow the visualization rules and return an html-content column.
+
+It is VERY important that all of the original code in the Jupyter notebook is 
represented in the generated workflow.
+Make sure that nothing in the original is removed and that the semantic 
meaning of what the original code was doing is retained.
+The only exception is data-loading code (e.g. read.csv); it is represented by 
the workflow's input/source operator rather than copied into a UDF.
+If there are user-defined R functions, include the entire function definition 
in every UDF that calls it.
+
+Return only the JSON formatted response, do not give any explanation.
+Do not wrap the JSON in markdown code fences. Output raw JSON only.
+Make sure the response is a valid JSON structure, including closing all braces 
and not including commas after the last element.
+Follow this JSON format (don't reuse the values, this is just the format). 
'code', 'edges', and 'outputs' are all their own keys, do not nest any of these 
in another one and make sure to close their braces:
+{
+"code": {
+"UDF1": "code for UDF1 goes here",
+"UDF2": "code for UDF2 goes here"
+},
+"edges": [
+["UDF1", "UDF2"]
+],
+"outputs": {
+"UDF1": ["data"],
+"UDF2": ["html-content"]
+}
+}
+Make sure only the keys in the code section appear in the edges and outputs 
sections. Do not include any extraneous fields.
+Do not include any extraneous UDFs in the code field that include empty 
strings.
+Give ALL of the code, do not omit anything or use placeholders for code. Make 
sure ALL code in the original is translated over.
+The value of each UDF must be a valid JSON string: escape newlines, quotes, 
and backslashes correctly so that the decoded string is runnable R. Prefer 
single quotes for R strings so fewer characters need escaping.
+Convert following the instructions and examples given. Here is the code:
+`;
+
+export const R_MAPPING_PROMPT = `
+Here is an example of a mapping generated between the given example R code and 
the Texera UDFs using their CELL and UDF IDs. Cell IDs are designated by the 
UUID following '# START'. The format should be kept the same.
+{
+"UDF1": ["CELL3"],
+"UDF2": ["CELL4"],
+"UDF3": ["CELL5"],
+"UDF4": ["CELL6", "CELL7"],
+"UDF5": ["CELL8"],
+"UDF6": ["CELL9"]
+}
+Now create a mapping for the UDFs and the original code. Link the code blocks 
marked by 'START <cell-uuid>' and 'END <cell-uuid>' with the UDF UUIDs. The 
code between them should be equivalent. Multiple cells can be mapped to the 
same UDF when that UDF implements the logic of those cells. There could be any 
number of cells and UDFs, so only create the correct number in the mapping. 
Only give the mapping.
+`;
+
+export const R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT = `
+Here is an example of breaking up R code into multiple Texera R UDFs. Format 
your response structure exactly like the given example. The "code" key contains 
a dictionary of the UDF IDs with their respective code. The "edges" key 
contains a list of pairs that contains the connections between UDFs. The 
"outputs" key contains a dictionary of the UDF IDs with a list of the output 
column names of the data.frame that the UDF returns. The UDFs can branch, so it 
does not have to be a linear chai [...]
+
+The original code is shown with each line prefixed by its line number and a 
'|'. Those prefixes are annotations so that line ranges can be referred to 
later. They are not part of the code and must never appear in the code you 
generate.
+
+Original Code:
+\`\`\`r
+ 1| library(ggplot2)
+ 2| library(rpart)
+ 3| 
+ 4| # Load the dataset
+ 5| data <- read.csv('diabetes.csv')
+ 6| 
+ 7| # Remove duplicate rows
+ 8| data <- unique(data)
+ 9| 
+10| # Remove rows with missing values
+11| data <- na.omit(data)
+12| 
+13| # Print the minimum, maximum, and mean for all fields
+14| print(sapply(data, min))
+15| print(sapply(data, max))
+16| print(colMeans(data))
+17| 
+18| # Boxplot of glucose by outcome
+19| ggplot(data, aes(x = factor(Outcome), y = Glucose)) +
+20|   geom_boxplot() +
+21|   labs(x = 'Outcome', y = 'Glucose', title = 'Glucose by Outcome')
+22| 
+23| # Split data into training and testing sets (80% train, 20% test)
+24| set.seed(42)
+25| train_idx <- sample(seq_len(nrow(data)), size = floor(0.8 * nrow(data)))
+26| train <- data[train_idx, ]
+27| test <- data[-train_idx, ]
+28| 
+29| # Scale features using the training set center and spread
+30| features <- setdiff(names(data), 'Outcome')
+31| centers <- sapply(train[features], mean)
+32| spreads <- sapply(train[features], sd)
+33| train[features] <- scale(train[features], center = centers, scale = 
spreads)
+34| test[features] <- scale(test[features], center = centers, scale = spreads)
+35| 
+36| # Train logistic regression model
+37| glm_model <- glm(Outcome ~ ., data = train, family = binomial)
+38| glm_pred <- ifelse(predict(glm_model, test, type = 'response') > 0.5, 1, 0)
+39| glm_accuracy <- mean(glm_pred == test$Outcome)
+40| print(sprintf('Logistic Regression Accuracy: %.2f%%', 100 * glm_accuracy))
+41| 
+42| # Train decision tree model
+43| tree_model <- rpart(factor(Outcome) ~ ., data = train, method = 'class')
+44| tree_pred <- predict(tree_model, test, type = 'class')
+45| tree_accuracy <- mean(as.character(tree_pred) == 
as.character(test$Outcome))
+46| print(sprintf('Decision Tree Accuracy: %.2f%%', 100 * tree_accuracy))
+\`\`\`
+
+Texera UDF conversion:
+\`\`\`json
+{
+    "code": {
+        "UDF1": "# UDF1\\nfunction(table, port) {\\n  # Remove duplicate 
rows\\n  data <- unique(table)\\n\\n  # Remove rows with missing values\\n  
data <- na.omit(data)\\n\\n  # One row of serialized objects for the downstream 
UDFs\\n  data.frame(data = I(list(serialize(data, NULL))))\\n}",
+        "UDF2": "# UDF2\\nfunction(table, port) {\\n  data <- 
unserialize(table$data[[1]])\\n\\n  # Calculate the minimum, maximum, and mean 
for all fields\\n  min_values <- sapply(data, min)\\n  max_values <- 
sapply(data, max)\\n  mean_values <- colMeans(data)\\n\\n  # No UDF reads this 
one, so its columns are character\\n  data.frame(\\n    min_values = 
paste(capture.output(print(min_values)), collapse = '\\\\n'),\\n    max_values 
= paste(capture.output(print(max_values)), collapse = ' [...]
+        "UDF3": "# 
UDF3\\nlibrary(ggplot2)\\nlibrary(plotly)\\n\\nfunction(table, port) {\\n  data 
<- unserialize(table$data[[1]])\\n\\n  if (nrow(data) == 0) {\\n    html <- 
'<h1>Boxplot is not available.</h1><p>Reason is: input table is empty.</p>'\\n  
  return(data.frame('html-content' = html, check.names = FALSE))\\n  }\\n\\n  # 
Boxplot of glucose by outcome\\n  p <- ggplot(data, aes(x = factor(Outcome), y 
= Glucose)) +\\n    geom_boxplot() +\\n    labs(x = 'Outcome', y = 'Glucose',  
[...]
+        "UDF4": "# UDF4\\nfunction(table, port) {\\n  data <- 
unserialize(table$data[[1]])\\n\\n  # Split data into training and testing sets 
(80% train, 20% test)\\n  set.seed(42)\\n  train_idx <- 
sample(seq_len(nrow(data)), size = floor(0.8 * nrow(data)))\\n  train <- 
data[train_idx, ]\\n  test <- data[-train_idx, ]\\n\\n  # Scale features using 
the training set center and spread\\n  features <- setdiff(names(data), 
'Outcome')\\n  centers <- sapply(train[features], mean)\\n  spreads <- [...]
+        "UDF5": "# UDF5\\nfunction(table, port) {\\n  train <- 
unserialize(table$train[[1]])\\n  test <- unserialize(table$test[[1]])\\n\\n  # 
Train logistic regression model\\n  glm_model <- glm(Outcome ~ ., data = train, 
family = binomial)\\n  glm_pred <- ifelse(predict(glm_model, test, type = 
'response') > 0.5, 1, 0)\\n  glm_accuracy <- mean(glm_pred == 
test$Outcome)\\n\\n  # No UDF reads this one, so its columns are character\\n  
data.frame(glm_accuracy = sprintf('Logistic Regression [...]
+        "UDF6": "# UDF6\\nlibrary(rpart)\\n\\nfunction(table, port) {\\n  
train <- unserialize(table$train[[1]])\\n  test <- 
unserialize(table$test[[1]])\\n\\n  # Train decision tree model\\n  tree_model 
<- rpart(factor(Outcome) ~ ., data = train, method = 'class')\\n  tree_pred <- 
predict(tree_model, test, type = 'class')\\n  tree_accuracy <- 
mean(as.character(tree_pred) == as.character(test$Outcome))\\n\\n  # No UDF 
reads this one, so its columns are character\\n  data.frame(tree_accur [...]
+    },
+    "edges": [
+        [
+            "UDF1",
+            "UDF2"
+        ],
+        [
+            "UDF1",
+            "UDF3"
+        ],
+        [
+            "UDF1",
+            "UDF4"
+        ],
+        [
+            "UDF4",
+            "UDF5"
+        ],
+        [
+            "UDF4",
+            "UDF6"
+        ]
+    ],
+    "outputs": {
+        "UDF1": [
+            "data"
+        ],
+        "UDF2": [
+            "min_values",
+            "max_values",
+            "mean_values"
+        ],
+        "UDF3": [
+            "html-content"
+        ],
+        "UDF4": [
+            "train",
+            "test"
+        ],
+        "UDF5": [
+            "glm_accuracy"
+        ],
+        "UDF6": [
+            "tree_accuracy"
+        ]
+    }
+}
+\`\`\``;
+
+export const R_SCRIPT_WORKFLOW_PROMPT = `You are an expert in R coding and 
workflow systems.
+Many users of Texera system are non-technical, but the R scripts they provide 
are written by technical people.
+They want to convert their R scripts to Texera workflows.
+Your goal is to help convert these R scripts into a Texera workflow that 
non-technical users can use directly.
+So do not remove or modify any user-defined functions, preserve their names 
and structure as they are.
+Ensure that all essential logic remains intact.
+Create multiple Texera R UDF codes using the provided R code.
+Number each UDF, starting at 1 and incrementing, by starting with a comment 
that states that UDF number.
+
+Every UDF uses the Table API: its code ends with one function(table, port) 
that takes a data.frame and returns a data.frame.
+Do not use the Tuple API or coro generators.
+Load every package a UDF uses with library() before its function. Do not call 
install.packages().
+
+Do not load data from a file in the first UDF; the workflow's source operator 
supplies the initial data,
+so assume it is already given to you as the table argument. Replacing 
file-loading code with this input
+is the one exception to preserving all original code (see below).
+Separate operators as if they will run in different R sessions: a UDF sees 
only the table it receives.
+
+Each UDF has exactly one output, so follow the data passing rules:
+a UDF whose output another UDF reads returns one row where every column is a 
serialized R object,
+and a UDF that no other UDF reads returns character columns.
+Ensure all information is passed on (including training and testing data) if 
subsequent UDFs need it.
+Each UDF has one input. When a step needs results from several earlier UDFs, 
carry those results forward
+through a single chain instead of connecting several UDFs into one.
+Values the original code prints become columns of the returned data.frame.
+Plots follow the visualization rules and return an html-content column.
+
+It is VERY important that all of the original code in the R script is 
represented in the generated workflow.
+Make sure that nothing in the original is removed and that the semantic 
meaning of what the original code was doing is retained.
+The only exception is data-loading code (e.g. read.csv); it is represented by 
the workflow's input/source operator rather than copied into a UDF.
+If there are user-defined R functions, include the entire function definition 
in every UDF that calls it.
+
+Return only the JSON formatted response, do not give any explanation.
+Do not wrap the JSON in markdown code fences. Output raw JSON only.
+Make sure the response is a valid JSON structure, including closing all braces 
and not including commas after the last element.
+Follow this JSON format (don't reuse the values, this is just the format). 
'code', 'edges', and 'outputs' are all their own keys, do not nest any of these 
in another one and make sure to close their braces:
+{
+"code": {
+"UDF1": "code for UDF1 goes here",
+"UDF2": "code for UDF2 goes here"
+},
+"edges": [
+["UDF1", "UDF2"]
+],
+"outputs": {
+"UDF1": ["data"],
+"UDF2": ["html-content"]
+}
+}
+Make sure only the keys in the code section appear in the edges and outputs 
sections. Do not include any extraneous fields.
+Do not include any extraneous UDFs in the code field that include empty 
strings.
+Give ALL of the code, do not omit anything or use placeholders for code. Make 
sure ALL code in the original is translated over.
+The value of each UDF must be a valid JSON string: escape newlines, quotes, 
and backslashes correctly so that the decoded string is runnable R. Prefer 
single quotes for R strings so fewer characters need escaping.
+Each line of the script below is prefixed with its line number followed by '| 
'. Those prefixes are annotations
+so that line ranges can be referred to later; never reproduce them in any 
generated UDF code.
+Convert following the instructions and examples given. Here is the code:
+`;
+
+export const R_SCRIPT_MAPPING_PROMPT = `
+Here is an example of a mapping generated between the given example R code and 
the Texera UDFs, using line ranges of the original script and the UDF IDs. A 
range is a pair [firstLine, lastLine]; both bounds are 1-indexed and inclusive, 
and they refer to the line numbers shown in the prefix of the original code. A 
UDF may list several ranges when its logic came from separate parts of the 
script. The format should be kept the same.
+{
+"UDF1": [[7, 11]],
+"UDF2": [[13, 16]],
+"UDF3": [[18, 21]],
+"UDF4": [[23, 34]],
+"UDF5": [[36, 40]],
+"UDF6": [[42, 46]]
+}
+Now create a mapping for the UDFs and the original code you were given. For 
each UDF, report the line ranges of the original script whose logic that UDF 
implements. The code in those lines should be equivalent to what the UDF does. 
Lines that no UDF implements, such as library() calls or the data loading that 
the workflow's source operator replaces, can be left out entirely. Give the 
first line before the last within each range, and do not shift the numbers: 
they must match the prefixes  [...]
+`;
diff --git 
a/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.spec.ts
 
b/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.spec.ts
index 9b8be051ee..a5de565f63 100644
--- 
a/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.spec.ts
+++ 
b/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.spec.ts
@@ -32,18 +32,18 @@ describe("NotebookMigrationService", () => {
   let service: NotebookMigrationService;
   let httpMock: HttpTestingController;
   let mockNotificationService: { success: ReturnType<typeof vi.fn>; error: 
ReturnType<typeof vi.fn> };
-  // Mutable so individual describe blocks can flip the flag mid-spec by
-  // reassigning `mockGuiConfigService.env.pythonNotebookMigrationEnabled`.
-  // The service stores a reference to this object, so mutations are observed
-  // on the next read of `this.enabled`.
-  let mockGuiConfigService: { env: { pythonNotebookMigrationEnabled: boolean } 
};
+  // Mutable so individual describe blocks can flip the flags mid-spec by
+  // reassigning `mockGuiConfigService.env.pythonNotebookMigrationEnabled` or
+  // `rNotebookMigrationEnabled`. The service stores a reference to this 
object,
+  // so mutations are observed on the next read.
+  let mockGuiConfigService: { env: { pythonNotebookMigrationEnabled: boolean; 
rNotebookMigrationEnabled: boolean } };
 
   beforeEach(() => {
     mockNotificationService = {
       success: vi.fn(),
       error: vi.fn(),
     };
-    mockGuiConfigService = { env: { pythonNotebookMigrationEnabled: true } };
+    mockGuiConfigService = { env: { pythonNotebookMigrationEnabled: true, 
rNotebookMigrationEnabled: true } };
 
     TestBed.configureTestingModule({
       imports: [HttpClientTestingModule],
@@ -352,10 +352,21 @@ describe("NotebookMigrationService", () => {
       const result = await service.sendToAIGenerateWorkflow({ cells: [] } as 
any, "gpt-4");
 
       expect(result).toEqual({ workflowContent: { ops: 1 }, mappingContent: { 
m: 2 } });
+      expect(fakeLLM.convertNotebookToWorkflow).toHaveBeenCalledWith({ cells: 
[] }, "python");
       expect(fakeLLM.initialize).toHaveBeenCalledWith("gpt-4");
       expect(fakeLLM.close).toHaveBeenCalled();
     });
 
+    it("passes the source language to the conversion", async () => {
+      fakeLLM.convertNotebookToWorkflow.mockResolvedValue(
+        JSON.stringify({ workflowJSON: { ops: 1 }, workflowNotebookMapping: { 
m: 2 } })
+      );
+
+      await service.sendToAIGenerateWorkflow({ cells: [] } as any, "gpt-4", 
"r");
+
+      expect(fakeLLM.convertNotebookToWorkflow).toHaveBeenCalledWith({ cells: 
[] }, "r");
+    });
+
     it("rejects when the connection cannot be verified, and still closes the 
client", async () => {
       fakeLLM.verifyConnection.mockResolvedValue(false);
 
@@ -408,11 +419,19 @@ describe("NotebookMigrationService", () => {
         mappingContent: { m: 2 },
         notebook: conversion.notebook,
       });
-      expect(fakeLLM.convertScriptToWorkflow).toHaveBeenCalledWith("x = 1");
+      expect(fakeLLM.convertScriptToWorkflow).toHaveBeenCalledWith("x = 1", 
"python");
       expect(fakeLLM.initialize).toHaveBeenCalledWith("gpt-4");
       expect(fakeLLM.close).toHaveBeenCalled();
     });
 
+    it("passes the source language to the conversion", async () => {
+      fakeLLM.convertScriptToWorkflow.mockResolvedValue(conversion);
+
+      await service.sendScriptToAIGenerateWorkflow("x <- 1", "gpt-4", "r");
+
+      expect(fakeLLM.convertScriptToWorkflow).toHaveBeenCalledWith("x <- 1", 
"r");
+    });
+
     it("rejects when the connection cannot be verified, and still closes the 
client", async () => {
       fakeLLM.verifyConnection.mockResolvedValue(false);
 
@@ -429,6 +448,29 @@ describe("NotebookMigrationService", () => {
     });
   });
 
+  describe("when the R flag is disabled", () => {
+    let createMigrationLLM: ReturnType<typeof vi.spyOn>;
+
+    beforeEach(() => {
+      mockGuiConfigService.env.rNotebookMigrationEnabled = false;
+      createMigrationLLM = vi.spyOn(service as any, "createMigrationLLM");
+    });
+
+    it("rejects an R notebook before creating or pinging a client", async () 
=> {
+      await expect(service.sendToAIGenerateWorkflow({ cells: [] } as any, 
"gpt-4", "r")).rejects.toThrow(
+        "R notebook migration is disabled"
+      );
+      expect(createMigrationLLM).not.toHaveBeenCalled();
+    });
+
+    it("rejects an R script before creating or pinging a client", async () => {
+      await expect(service.sendScriptToAIGenerateWorkflow("x <- 1", "gpt-4", 
"r")).rejects.toThrow(
+        "R notebook migration is disabled"
+      );
+      expect(createMigrationLLM).not.toHaveBeenCalled();
+    });
+  });
+
   // Feature flag gate (defence in depth). With the flag off, every public
   // method must short-circuit — no HTTP traffic, no fetch, no LLM lifecycle,
   // no notifications.
diff --git 
a/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.ts
 
b/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.ts
index cef23e70b5..f710761f22 100644
--- 
a/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.ts
+++ 
b/frontend/src/app/workspace/service/notebook-migration/notebook-migration.service.ts
@@ -19,7 +19,7 @@
 
 import { Injectable } from "@angular/core";
 import { AppSettings } from "../../../common/app-setting";
-import { Notebook, NotebookMigrationLLM, SourceConversion } from 
"./migration-llm";
+import { MigrationLanguage, Notebook, NotebookMigrationLLM, SourceConversion } 
from "./migration-llm";
 import {
   buildFolderDocument,
   checkFolderByteSize,
@@ -123,11 +123,12 @@ export class NotebookMigrationService {
 
   public async sendToAIGenerateWorkflow(
     notebookContent: Notebook,
-    modelType: string
+    modelType: string,
+    language: MigrationLanguage = "python"
   ): Promise<{ workflowContent: WorkflowContent; mappingContent: 
MappingContent }> {
-    return this.withMigrationLLM(modelType, async migrationLLM => {
+    return this.withMigrationLLM(modelType, language, async migrationLLM => {
       try {
-        const result = await 
migrationLLM.convertNotebookToWorkflow(notebookContent);
+        const result = await 
migrationLLM.convertNotebookToWorkflow(notebookContent, language);
         const parsedResult = JSON.parse(result);
         const workflowContent = parsedResult.workflowJSON;
         const mappingContent = parsedResult.workflowNotebookMapping;
@@ -140,7 +141,7 @@ export class NotebookMigrationService {
   }
 
   /**
-   * Convert a Python script into a workflow.
+   * Convert a script into a workflow.
    *
    * Returns a notebook alongside the workflow and mapping, which the notebook 
path does not:
    * a script has no cells, so the LLM reports which line ranges became which 
operator and the
@@ -149,10 +150,11 @@ export class NotebookMigrationService {
    */
   public async sendScriptToAIGenerateWorkflow(
     scriptSource: string,
-    modelType: string
+    modelType: string,
+    language: MigrationLanguage = "python"
   ): Promise<GeneratedWorkflowContent> {
-    return this.generateFromSource(modelType, "script", migrationLLM =>
-      migrationLLM.convertScriptToWorkflow(scriptSource)
+    return this.generateFromSource(modelType, "script", language, migrationLLM 
=>
+      migrationLLM.convertScriptToWorkflow(scriptSource, language)
     );
   }
 
@@ -167,7 +169,9 @@ export class NotebookMigrationService {
     folder: FolderDocument,
     modelType: string
   ): Promise<GeneratedWorkflowContent> {
-    return this.generateFromSource(modelType, "folder", migrationLLM => 
migrationLLM.convertFolderToWorkflow(folder));
+    return this.generateFromSource(modelType, "folder", "python", migrationLLM 
=>
+      migrationLLM.convertFolderToWorkflow(folder)
+    );
   }
 
   /**
@@ -177,9 +181,10 @@ export class NotebookMigrationService {
   private async generateFromSource(
     modelType: string,
     input: "script" | "folder",
+    language: MigrationLanguage,
     convert: (migrationLLM: NotebookMigrationLLM) => Promise<SourceConversion>
   ): Promise<GeneratedWorkflowContent> {
-    return this.withMigrationLLM(modelType, async migrationLLM => {
+    return this.withMigrationLLM(modelType, language, async migrationLLM => {
       try {
         const conversion = await convert(migrationLLM);
         return {
@@ -188,7 +193,7 @@ export class NotebookMigrationService {
           notebook: conversion.notebook,
         };
       } catch (error) {
-        console.error(`Error converting Python ${input}:`, error);
+        console.error(`Error converting ${input}:`, error);
         throw error;
       }
     });
@@ -201,9 +206,14 @@ export class NotebookMigrationService {
    */
   private async withMigrationLLM<T>(
     modelType: string,
+    language: MigrationLanguage,
     convert: (migrationLLM: NotebookMigrationLLM) => Promise<T>
   ): Promise<T> {
     if (!this.enabled) throw new Error("Notebook migration feature is 
disabled");
+    // Checked before verifyConnection so a disabled language never reaches 
the model.
+    if (language === "r" && !this.config.env.rNotebookMigrationEnabled) {
+      throw new Error("R notebook migration is disabled");
+    }
     const migrationLLM = this.createMigrationLLM();
     // initialize() defaults to the user's Texera JWT via 
AuthService.getAccessToken().
     try {

Reply via email to