This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9427-f1a6bed13aaefd5ae23565ea4e99f87faed59c67 in repository https://gitbox.apache.org/repos/asf/texera.git
commit 1d7c00616a5494792e26bb3e9b353dac6b85d62c Author: Ryan Zhang <[email protected]> AuthorDate: Thu Nov 19 00:37:59 2026 +0000 feat(notebook-migration): add r folders to the import modal (#9427) ### What changes were proposed in this PR? This PR lets users convert a local folder of R files, the last input type for R support (#8009). It reuses the Python folder pipeline from #8767: the folder is assembled into one banner separated document, the model names an entry point, and the notebook shows that file with each operator mapped to its call site. **Folder assembly.** `folder-assembly.ts` now takes the language. A small per language table gives the file extension, the directories to skip and the name used in messages. R reads `.R` and `.r` and skips `renv` and `packrat`, which hold installed packages full of `.R` files. Python's extension, exclusions and messages are unchanged. Files in other languages are named in the folder layout and never read, as for Python, so a folder of `.py` files on the R tab gets "No R files were found in the selected folder." **R folder prompts.** `MigrationPromptSet` gains folder fields, so `convertFolderToWorkflow` takes the language like the notebook and script conversions and goes through the same R flag guard. `migration-prompts-r.ts` adds R versions of the three folder prompts, which differ from the Python ones where R differs: * `source()` is how R files load each other, and it reads a file, which a UDF cannot do. The prompt asks the model to copy every definition a UDF uses into that UDF and to never call `source()`. * R has no `if __name__ == "__main__"`, so the entry point is described as the file whose top level code sources the others and calls their functions. The worked example is a three file project: `data_prep.R` and `models.R` define functions, and `main.R` sources them and calls them in order. Unlike the Python folder example, each example UDF carries the definition of the function it calls, which is what the prompt asks for. The example was generated from a real project that runs under `Rscript`, and all six example UDFs were run through texera-rudf on `diabetes.csv`, chained the way `buildWorkflow` wires them. **Escaped slashes.** In one live run the model wrote `<\/script>` inside an R string. R rejects `\/` as an unrecognized escape, so the plot UDF failed to parse. The R visualization rules now say to write closing tags as shown, and a guard test keeps every R worked example free of `\/`. The rule is part of the shared R documentation, so it covers R notebooks and files too. **Import modal.** An "R Folder" tab after R File, laid out like the Python Folder tab with its own diagram and a directory picker. It is one more `IMPORT_TABS` entry, so the existing folder handling (directory picker, drop rejection, whole list selection) applies to it unchanged. As with the other R options, it is shown but disabled with the tooltip "R is not enabled on this deployment." when `rNotebookMigrationEnabled` is off. Its description is shorter than the Python Folder one so the tab fits the modal without scrolling. The dashboard passes the language to `parseFolder` and the folder conversion. **Assets.** A new R folder diagram, at the same size and border as the others. `frontend/LICENSE-binary` adds it to the Material Symbols entry. **Demo video (wait time cut out)** https://github.com/user-attachments/assets/f7be5cfb-fb49-46eb-a440-b4711ddad40f **R Folder disabled on a deployment without R** <img width="727" height="156" alt="image" src="https://github.com/user-attachments/assets/383e127e-9a4b-40b4-9992-1b8f2a4995ad" /> ### Any related issues, documentation, discussions? Closes #9386 Closes #8009 Parent-issue #4301 The plan is in https://github.com/apache/texera/discussions/8866. With this PR, R supports the same three inputs as Python: notebooks (#8912), files (#8963) and folders. Language mismatches between the upload and the selected tab are tracked in #8929. ### How was this PR tested? * `folder-assembly.spec.ts`: R paths (`.R` and `.r` accepted; `.py`, `.Rmd` and `.Rproj` rejected; `renv`, `packrat` and `.Rproj.user` skipped), each language's exclusions applying only to that language, the exact Python messages and the R messages, and the layout's overflow line naming R. * `notebook-migration.service.spec.ts`: `parseFolder` for R keeps the R files, names a `.py` in the layout and drops `renv`, with the R messages for no files and all blank files. The language reaches the folder conversion, and an R folder is refused before any client is created while the R flag is off. * `migration-llm.spec.ts`: the exact R folder prelude, layout and prompts, RUDF operators and the `ir` kernel from a folder, and the R flag blocking a folder without a model call. * `migration-prompts-r.spec.ts`: the folder example passes the same guards as the notebook and script examples, plus four of its own: its entry point is a file in the folder, no UDF calls `source()` and each copies the definitions it calls, the layout names a file the document leaves out, and every mapping range falls on non blank lines of the entry point. * `notebook-import-modal.component.spec.ts`: four new tests for the R Folder tab: disabled with its tooltip while the flag is off, not selectable by a click, a directory picker with the R language while the flag is on, and submit passing the whole folder with `"r"`. The tab counts now expect five. * `user-workflow.component.spec.ts`: an R folder is read and converted as R, and the Python folder test now checks `"python"`. The full frontend suite passes, and every new line and branch is covered. Checked by hand against a local stack. With the R flag on, all five tabs fit on one line, every tab fits the modal without scrolling, and the R Folder tab stages a picked folder as one R selection. Two live conversions of the example project each produced a six operator RUDF workflow with the expected edges and output types, and a notebook of only `main.R` with each operator mapped to its call site. After the slash fix, the generated UDFs ran through texera-rudf with the same accuracies as `Rscript`. These runs used the worked example's own project, so they check the pipeline more than how well the model generalizes. With the flag off, the R Folder tab is disabled, ignores clicks and shows its tooltip on one line. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (Claude Opus 5.5) --- frontend/LICENSE-binary | 1 + .../user-workflow/user-workflow.component.spec.ts | 14 +- .../user/user-workflow/user-workflow.component.ts | 12 +- .../notebook-import-modal.component.html | 53 +++++ .../notebook-import-modal.component.spec.ts | 52 ++++- .../notebook-import-modal.component.ts | 5 +- .../notebook-migration/folder-assembly.spec.ts | 95 ++++++-- .../service/notebook-migration/folder-assembly.ts | 70 ++++-- .../notebook-migration/migration-llm.spec.ts | 34 +++ .../service/notebook-migration/migration-llm.ts | 29 ++- .../notebook-migration/migration-prompts-r.spec.ts | 58 +++++ .../notebook-migration/migration-prompts-r.ts | 245 +++++++++++++++++++++ .../notebook-migration.service.spec.ts | 47 +++- .../notebook-migration.service.ts | 31 +-- .../notebook_migration_tool/r_folder_diagram.png | Bin 0 -> 77019 bytes 15 files changed, 672 insertions(+), 74 deletions(-) diff --git a/frontend/LICENSE-binary b/frontend/LICENSE-binary index c51b588daa..66bc0d1b79 100644 --- a/frontend/LICENSE-binary +++ b/frontend/LICENSE-binary @@ -231,6 +231,7 @@ Third-party assets: frontend/src/assets/notebook_migration_tool/python_folder_diagram.png frontend/src/assets/notebook_migration_tool/r_notebook_diagram.png frontend/src/assets/notebook_migration_tool/r_file_diagram.png + frontend/src/assets/notebook_migration_tool/r_folder_diagram.png https://github.com/google/material-design-icons - Google Material Symbols icons (area_chart, autorenew, batch_prediction, forest, join_inner, merge, table_chart, tune) frontend/src/assets/operator_images/FigureFactoryTable.png diff --git a/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.spec.ts b/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.spec.ts index 3f487612bb..4a305fb906 100644 --- a/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.spec.ts +++ b/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.spec.ts @@ -660,7 +660,8 @@ describe("SavedWorkflowSectionComponent", () => { // The Files themselves are what carry webkitRelativePath, so those are what get passed on. expect(parseSpy.mock.calls[0][0]).toEqual(selection); - expect(convertSpy).toHaveBeenCalledWith(assembled, "gpt-4"); + expect(parseSpy.mock.calls[0][1]).toBe("python"); + expect(convertSpy).toHaveBeenCalledWith(assembled, "gpt-4", "python"); // Named after the selected folder, with no extension to strip. expect(persist.createWorkflow.mock.calls[0][1]).toBe("proj_GENERATED_BY_LLM"); expect(storeSpy).toHaveBeenCalledWith(77, expect.anything(), derivedNotebook); @@ -668,6 +669,17 @@ describe("SavedWorkflowSectionComponent", () => { expect(proceed).toBe(true); }); + it("reads and converts an R folder as R", async () => { + const { parseSpy, convertSpy } = mockFolderGenerationSuccess(); + vi.spyOn(TestBed.inject(Router), "navigate").mockResolvedValue(true); + + const proceed = await getRequestImport()(selection, "gpt-4", "r"); + + expect(parseSpy.mock.calls[0][1]).toBe("r"); + expect(convertSpy).toHaveBeenCalledWith(assembled, "gpt-4", "r"); + expect(proceed).toBe(true); + }); + it("never reaches the single-file paths for a folder", async () => { mockFolderGenerationSuccess(); vi.spyOn(TestBed.inject(Router), "navigate").mockResolvedValue(true); diff --git a/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.ts b/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.ts index 7374932c4b..2294632480 100644 --- a/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.ts +++ b/frontend/src/app/dashboard/component/user/user-workflow/user-workflow.component.ts @@ -333,7 +333,7 @@ export class UserWorkflowComponent implements AfterViewInit, OnDestroy { language: MigrationLanguage ): Promise<boolean> { if (Array.isArray(selection)) { - const generated = await this.generateFromFolder(selection, model); + const generated = await this.generateFromFolder(selection, model, language); // Null means the step already told the user what went wrong. if (!generated) { return false; @@ -419,10 +419,14 @@ export class UserWorkflowComponent implements AfterViewInit, OnDestroy { } /** Read and convert a picked directory. The notebook comes back derived, as it does for a .py. */ - private async generateFromFolder(files: NzUploadFile[], model: string): Promise<GeneratedWorkflowContent | null> { + private async generateFromFolder( + files: NzUploadFile[], + model: string, + language: MigrationLanguage + ): Promise<GeneratedWorkflowContent | null> { let folder: FolderDocument; try { - folder = await this.notebookMigrationService.parseFolder(files.map(pickedFileObject)); + folder = await this.notebookMigrationService.parseFolder(files.map(pickedFileObject), language); } catch (error) { // parseFolder names what was wrong with the selection, so its message is shown as-is. this.notificationService.error(error instanceof Error ? error.message : "Failed to read the selected folder."); @@ -431,7 +435,7 @@ export class UserWorkflowComponent implements AfterViewInit, OnDestroy { } try { - return await this.notebookMigrationService.sendFolderToAIGenerateWorkflow(folder, model); + return await this.notebookMigrationService.sendFolderToAIGenerateWorkflow(folder, model, language); } catch (error) { this.reportGenerationFailure(error, "folder"); return null; diff --git a/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.html b/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.html index 2304d7d2aa..a457d220c8 100644 --- a/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.html +++ b/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.html @@ -277,6 +277,59 @@ "></ng-container> </ng-template> </nz-tab> + + <nz-tab + [nzTitle]="rFolderTitle" + [nzDisabled]="!rMigrationEnabled"> + <ng-template #rFolderTitle> + <span + nz-tooltip + [nzTooltipTitle]="rMigrationEnabled ? null : rDisabledTooltip" + [nzTooltipOverlayStyle]="{ 'max-width': 'none' }"> + R Folder + </span> + </ng-template> + <ng-template nz-tab> + <div class="import-modal-diagram"> + <img + ngSrc="assets/notebook_migration_tool/r_folder_diagram.png" + alt="R Folder to Workflow" + width="1350" + height="344" /> + </div> + + <nz-form-item> + <p class="import-modal-text"> + This tool converts a folder of R files into a single Texera workflow of R UDFs using LLM capabilities. The + folder's R files are joined into one document, each behind a heading naming the file it came from, so the + LLM can follow logic that crosses files. The conversion time depends on the folder's size and can take 1-5 + minutes. Once generation finishes, you are taken to the new workflow, which opens with: + </p> + <ol class="import-modal-list"> + <li> + The generated workflow ready to use (Note: you will still need to upload the dataset and connect it to + the workflow). + </li> + <li> + A floating Jupyter window containing the file that runs your project, divided into cells, for reference. + </li> + </ol> + <p class="import-modal-text"> + Generation runs here after you submit. Please keep this window open while you wait. + </p> + </nz-form-item> + + <ng-container + *ngTemplateOutlet=" + uploadRow; + context: { + label: 'Upload R Folder', + action: 'Upload R folder', + directory: true, + } + "></ng-container> + </ng-template> + </nz-tab> </nz-tabs> <nz-form-item> diff --git a/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.spec.ts b/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.spec.ts index 76702d33f6..5c0b24549a 100644 --- a/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.spec.ts +++ b/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.spec.ts @@ -406,7 +406,7 @@ describe("NotebookImportModalComponent", () => { it("selects the Python tab from a click on its header, not just a direct call", async () => { await createWith(of([{ name: "gpt-4" }])); const headers = (fixture.nativeElement as HTMLElement).querySelectorAll(".ant-tabs-tab"); - expect(headers.length).toBe(4); + expect(headers.length).toBe(5); (headers[1] as HTMLElement).click(); // nz-tabs emits nzSelectedIndexChange from a microtask inside ngAfterContentChecked, @@ -720,7 +720,7 @@ describe("NotebookImportModalComponent", () => { it("is shown but disabled with an explanation while the R flag is off", async () => { await createWith(of([{ name: "gpt-4" }])); - expect(root().querySelectorAll(".ant-tabs-tab").length).toBe(4); + expect(root().querySelectorAll(".ant-tabs-tab").length).toBe(5); expect(rFileTab().classList).toContain("ant-tabs-tab-disabled"); expect(tooltipOn("R File")).toBe(R_DISABLED_TOOLTIP); }); @@ -758,4 +758,52 @@ describe("NotebookImportModalComponent", () => { expect(requestImport).toHaveBeenCalledWith(file, "gpt-4", "r"); }); }); + + describe("R Folder tab", () => { + const root = () => fixture.nativeElement as HTMLElement; + const pane = () => root().querySelector(".ant-tabs-tabpane-active") as HTMLElement; + const rFolderTab = () => root().querySelectorAll(".ant-tabs-tab")[4] as HTMLElement; + + it("is shown but disabled with an explanation while the R flag is off", async () => { + await createWith(of([{ name: "gpt-4" }])); + + expect(rFolderTab().classList).toContain("ant-tabs-tab-disabled"); + expect(tooltipOn("R Folder")).toBe(R_DISABLED_TOOLTIP); + }); + + it("cannot be selected while the R flag is off", async () => { + await createWith(of([{ name: "gpt-4" }])); + + (rFolderTab().querySelector(".ant-tabs-tab-btn") as HTMLElement).click(); + fixture.detectChanges(); + await fixture.whenStable(); + + expect(component.selectedTabIndex).toBe(0); + }); + + it("picks a directory with the R language while the R flag is on", async () => { + await createWith(of([{ name: "gpt-4" }]), true); + component.onTabChange(4); + fixture.detectChanges(); + + expect(rFolderTab().classList).not.toContain("ant-tabs-tab-disabled"); + expect(tooltipOn("R Folder")).toBeNull(); + expect(pane().querySelector("img[alt='R Folder to Workflow']")).not.toBeNull(); + expect(pane().querySelector("input[type='file']")?.hasAttribute("webkitdirectory")).toBe(true); + expect(component.isFolderTab).toBe(true); + expect(component.language).toBe("r"); + }); + + it("submits the whole R folder with the R language", async () => { + await createWith(of([{ name: "gpt-4" }]), true); + component.onTabChange(4); + const files = [{ name: "main.R", webkitRelativePath: "proj/main.R" }] as unknown as NzUploadFile[]; + component.beforeUpload(files[0], files); + component.importForm.patchValue({ model: "gpt-4" }); + + await component.onSubmit(); + + expect(requestImport).toHaveBeenCalledWith(files, "gpt-4", "r"); + }); + }); }); diff --git a/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.ts b/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.ts index 25c0d13f18..7e85299383 100644 --- a/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.ts +++ b/frontend/src/app/workspace/component/notebook-import-modal/notebook-import-modal.component.ts @@ -62,6 +62,7 @@ const IMPORT_TABS: readonly ImportTab[] = [ { kind: "file", language: "python" }, { kind: "folder", language: "python" }, { kind: "file", language: "r" }, + { kind: "folder", language: "r" }, ]; // How long after the last rejected file a drop is treated as over: long enough that a slow @@ -77,8 +78,8 @@ function describeFolderSelection(files: readonly NzUploadFile[]): string { /** * The "AI Generate Workflow from Source Code" modal body: a tab per accepted input kind - * (Jupyter notebook in Python or R, Python script, Python folder, R script), each with its own diagram, description and - * upload control, over a shared model dropdown and footer. + * (Jupyter notebook in Python or R, Python script, Python folder, R script, R folder), each with its own + * diagram, description and upload control, over a shared model dropdown and footer. * * On Submit it hands the selection and model to requestImport and shows a loading state until * it resolves; the opener dispatches on a folder's list shape, or on a single file's extension. diff --git a/frontend/src/app/workspace/service/notebook-migration/folder-assembly.spec.ts b/frontend/src/app/workspace/service/notebook-migration/folder-assembly.spec.ts index 8d4eff2075..b286e385c7 100644 --- a/frontend/src/app/workspace/service/notebook-migration/folder-assembly.spec.ts +++ b/frontend/src/app/workspace/service/notebook-migration/folder-assembly.spec.ts @@ -26,7 +26,7 @@ import { fileBanner, folderRootName, isExcludedPath, - isMigratablePythonPath, + isMigratableSourcePath, MAX_FOLDER_BYTES, MAX_FOLDER_CHARACTERS, MAX_FOLDER_FILES, @@ -39,44 +39,64 @@ import { } from "./folder-assembly"; import { segmentScript } from "./script-segmentation"; -describe("isMigratablePythonPath", () => { +describe("isMigratableSourcePath", () => { it("accepts Python source at any depth, whatever the extension's case", () => { - expect(isMigratablePythonPath("train.py")).toBe(true); - expect(isMigratablePythonPath("pkg/models/train.py")).toBe(true); - expect(isMigratablePythonPath("pkg/Train.PY")).toBe(true); + expect(isMigratableSourcePath("train.py")).toBe(true); + expect(isMigratableSourcePath("pkg/models/train.py")).toBe(true); + expect(isMigratableSourcePath("pkg/Train.PY")).toBe(true); }); it("rejects anything that is not a .py file", () => { - expect(isMigratablePythonPath("notes.ipynb")).toBe(false); - expect(isMigratablePythonPath("requirements.txt")).toBe(false); - expect(isMigratablePythonPath("pkg/py")).toBe(false); - expect(isMigratablePythonPath("")).toBe(false); + expect(isMigratableSourcePath("notes.ipynb")).toBe(false); + expect(isMigratableSourcePath("requirements.txt")).toBe(false); + expect(isMigratableSourcePath("pkg/py")).toBe(false); + expect(isMigratableSourcePath("")).toBe(false); }); it("rejects hidden files and anything under a hidden directory", () => { - expect(isMigratablePythonPath(".hidden.py")).toBe(false); - expect(isMigratablePythonPath(".venv/lib/thing.py")).toBe(false); - expect(isMigratablePythonPath("pkg/.tox/run.py")).toBe(false); + expect(isMigratableSourcePath(".hidden.py")).toBe(false); + expect(isMigratableSourcePath(".venv/lib/thing.py")).toBe(false); + expect(isMigratableSourcePath("pkg/.tox/run.py")).toBe(false); }); it("rejects caches and vendored dependencies wherever they sit in the tree", () => { - expect(isMigratablePythonPath("__pycache__/train.py")).toBe(false); - expect(isMigratablePythonPath("pkg/__pycache__/train.py")).toBe(false); - expect(isMigratablePythonPath("venv/lib/site-packages/numpy/core.py")).toBe(false); - expect(isMigratablePythonPath("a/node_modules/b/x.py")).toBe(false); - expect(isMigratablePythonPath("build/lib/train.py")).toBe(false); - expect(isMigratablePythonPath("dist/train.py")).toBe(false); + expect(isMigratableSourcePath("__pycache__/train.py")).toBe(false); + expect(isMigratableSourcePath("pkg/__pycache__/train.py")).toBe(false); + expect(isMigratableSourcePath("venv/lib/site-packages/numpy/core.py")).toBe(false); + expect(isMigratableSourcePath("a/node_modules/b/x.py")).toBe(false); + expect(isMigratableSourcePath("build/lib/train.py")).toBe(false); + expect(isMigratableSourcePath("dist/train.py")).toBe(false); }); it("keeps a build or dist package that is not at the root", () => { // Only conventional build output at the root. Deeper in a tree these are ordinary package // names, and silently dropping real code is the failure the mapping exists to catch. - expect(isMigratablePythonPath("src/build/features.py")).toBe(true); - expect(isMigratablePythonPath("pkg/dist/writer.py")).toBe(true); + expect(isMigratableSourcePath("src/build/features.py")).toBe(true); + expect(isMigratableSourcePath("pkg/dist/writer.py")).toBe(true); }); it("keeps test files, which are logic the user may want represented", () => { - expect(isMigratablePythonPath("tests/test_train.py")).toBe(true); + expect(isMigratableSourcePath("tests/test_train.py")).toBe(true); + }); + + it("accepts R source for R, whatever the extension's case", () => { + expect(isMigratableSourcePath("main.R", "r")).toBe(true); + expect(isMigratableSourcePath("R/helpers.r", "r")).toBe(true); + expect(isMigratableSourcePath("tests/testthat/test-model.R", "r")).toBe(true); + }); + + it("rejects other languages and R documents for R", () => { + expect(isMigratableSourcePath("train.py", "r")).toBe(false); + expect(isMigratableSourcePath("report.Rmd", "r")).toBe(false); + expect(isMigratableSourcePath("project.Rproj", "r")).toBe(false); + expect(isMigratableSourcePath("main.R")).toBe(false); + }); + + it("rejects installed R packages and hidden R state for R", () => { + expect(isMigratableSourcePath("renv/activate.R", "r")).toBe(false); + expect(isMigratableSourcePath("renv/library/R-4.4/dplyr/R/dplyr.R", "r")).toBe(false); + expect(isMigratableSourcePath("packrat/lib/x/R/a.R", "r")).toBe(false); + expect(isMigratableSourcePath(".Rproj.user/shared/a.R", "r")).toBe(false); }); }); @@ -264,6 +284,22 @@ describe("folder cap checks", () => { ); }); + it("names Python in every message by default", () => { + expect(checkFolderFileCount(0)).toBe("No Python files were found in the selected folder."); + expect(checkFolderFileCount(MAX_FOLDER_FILES + 1)).toContain(" Python files, more than "); + expect(checkFolderByteSize(MAX_FOLDER_BYTES + 1)).toContain("Its Python files hold more than "); + expect(checkFolderDocument(documentOf(0, 0))).toBe("The Python files in the selected folder are all empty."); + expect(checkFolderDocument(documentOf(MAX_FOLDER_CHARACTERS + 1))).toContain("folder's Python code totals "); + }); + + it("names R in every message for R", () => { + expect(checkFolderFileCount(0, "r")).toBe("No R files were found in the selected folder."); + expect(checkFolderFileCount(MAX_FOLDER_FILES + 1, "r")).toContain(" R files, more than "); + expect(checkFolderByteSize(MAX_FOLDER_BYTES + 1, "r")).toContain("Its R files hold more than "); + expect(checkFolderDocument(documentOf(0, 0), "r")).toBe("The R files in the selected folder are all empty."); + expect(checkFolderDocument(documentOf(MAX_FOLDER_CHARACTERS + 1), "r")).toContain("folder's R code totals "); + }); + it("quotes one limit in one unit, so the byte guard does not read as a second cap", () => { const message = checkFolderByteSize(MAX_FOLDER_BYTES + 1); @@ -321,6 +357,13 @@ describe("isExcludedPath", () => { expect(isExcludedPath("data/churn.csv")).toBe(false); expect(isExcludedPath("")).toBe(true); }); + + it("excludes each language's own dependency directories and not the other's", () => { + expect(isExcludedPath("renv/library/a.R", "r")).toBe(true); + expect(isExcludedPath("packrat/lib/a.R", "r")).toBe(true); + expect(isExcludedPath("renv/settings.py")).toBe(false); + expect(isExcludedPath("pkg/__pycache__/notes.txt", "r")).toBe(false); + }); }); describe("renderFolderTree", () => { @@ -404,6 +447,16 @@ describe("buildFolderDocument layout", () => { expect(document.tree.split("\n").filter(line => line.endsWith(".csv"))).toHaveLength(MAX_LISTED_OTHER_FILES); }); + it("names the language of the files it left out", () => { + const others = Array.from({ length: MAX_LISTED_OTHER_FILES + 1 }, (_unused, index) => `data/file${index}.csv`); + const document = buildFolderDocument([{ path: "main.R", source: "main()" }], { + otherPaths: others, + language: "r", + }); + + expect(document.tree).toContain("... and 1 more non-R files"); + }); + it("defaults the root label when none is given", () => { expect(buildFolderDocument(files).tree.split("\n")[0]).toBe("project/"); }); diff --git a/frontend/src/app/workspace/service/notebook-migration/folder-assembly.ts b/frontend/src/app/workspace/service/notebook-migration/folder-assembly.ts index 27041c00e2..69f43fe710 100644 --- a/frontend/src/app/workspace/service/notebook-migration/folder-assembly.ts +++ b/frontend/src/app/workspace/service/notebook-migration/folder-assembly.ts @@ -17,10 +17,11 @@ * under the License. */ +import type { MigrationLanguage } from "./migration-llm"; import { ScriptSegmentation, splitScriptLines } from "./script-segmentation"; /** - * Assembles a folder of Python sources into the one numbered document the migration LLM sees. + * Assembles a folder of source files into the one numbered document the migration LLM sees. * * Converted as a single input, so the model reports line ranges as it does for a script and * nothing downstream learns folders exist; a banner line before each file carries provenance. @@ -28,15 +29,31 @@ import { ScriptSegmentation, splitScriptLines } from "./script-segmentation"; * agree on what a line is. */ -// Never project code, matched per segment so a cache or vendored dependency is caught at any -// depth. Hidden segments are covered separately by the leading-dot rule. -const EXCLUDED_SEGMENTS = new Set(["__pycache__", "venv", "site-packages", "node_modules"]); +interface FolderLanguage { + // How messages name the language's files. + name: string; + // Lowercase, since file names are lowercased before matching. + extension: string; + // Never project code, matched per segment so a cache or vendored dependency is caught at any + // depth. Hidden segments are covered separately by the leading-dot rule. + excludedSegments: ReadonlySet<string>; +} + +const FOLDER_LANGUAGES: Record<MigrationLanguage, FolderLanguage> = { + python: { + name: "Python", + extension: ".py", + excludedSegments: new Set(["__pycache__", "venv", "site-packages", "node_modules"]), + }, + // renv and packrat hold installed packages, which are full of .R files. + r: { name: "R", extension: ".r", excludedSegments: new Set(["renv", "packrat", "node_modules"]) }, +}; // Build output at the root, but ordinary package names deeper in a tree (src/build/ can be real // code). Dropping real code silently is worse than letting a build tree hit the caps. const EXCLUDED_ROOT_DIRECTORIES = new Set(["build", "dist"]); -// Non-Python files are named in the layout, never read. Capped because a folder can hold +// Files that are not source are named in the layout, never read. Capped because a folder can hold // thousands of data files and the layout is orientation, not an inventory. export const MAX_LISTED_OTHER_FILES = 20; @@ -88,7 +105,7 @@ export interface FolderDocument { /** * An indented listing of the folder, sent ahead of the document as prompt text. Never part of * `source`: numbering it would shift every line the model reports, and the segmenter would emit - * it as a cell of directory listing. Also the only place non-Python files are named. + * it as a cell of directory listing. Also the only place files that are not source are named. */ tree: string; } @@ -96,8 +113,9 @@ export interface FolderDocument { export interface FolderDocumentOptions { // The selected folder's own name, used as the layout's root label. rootName?: string; - // Paths in the selection that hold no Python source. Listed in the layout, never read. + // Paths in the selection that hold no source. Listed in the layout, never read. otherPaths?: readonly string[]; + language?: MigrationLanguage; } /** Either shape an upload control hands a picked file over in: the File itself, or a wrapper. */ @@ -156,7 +174,7 @@ function pathSegments(path: string): string[] { /** True for a cache, a vendored dependency or anything hidden. Left out of the layout as well as * the document: noise, not structure. */ -export function isExcludedPath(path: string): boolean { +export function isExcludedPath(path: string, language: MigrationLanguage = "python"): boolean { const segments = pathSegments(path); if (segments.length === 0) { return true; @@ -164,15 +182,17 @@ export function isExcludedPath(path: string): boolean { if (segments.length > 1 && EXCLUDED_ROOT_DIRECTORIES.has(segments[0])) { return true; } - return segments.some(segment => segment.startsWith(".") || EXCLUDED_SEGMENTS.has(segment)); + const { excludedSegments } = FOLDER_LANGUAGES[language]; + return segments.some(segment => segment.startsWith(".") || excludedSegments.has(segment)); } -/** True for a path holding project Python source. Tests are kept: dropping real logic silently is - * the failure the mapping exists to prevent. */ -export function isMigratablePythonPath(path: string): boolean { +/** True for a path holding project source in the language. Tests are kept: dropping real logic + * silently is the failure the mapping exists to prevent. */ +export function isMigratableSourcePath(path: string, language: MigrationLanguage = "python"): boolean { const segments = pathSegments(path); if (segments.length === 0) return false; - return segments[segments.length - 1].toLowerCase().endsWith(".py") && !isExcludedPath(path); + const { extension } = FOLDER_LANGUAGES[language]; + return segments[segments.length - 1].toLowerCase().endsWith(extension) && !isExcludedPath(path, language); } /** Renders the folder as an indented listing. Files come before subdirectories, which ordering by @@ -236,7 +256,7 @@ export function compareFolderPaths(a: string, b: string): number { * what was actually included. */ export function buildFolderDocument(files: readonly FolderFile[], options: FolderDocumentOptions = {}): FolderDocument { - const { rootName = "project", otherPaths = [] } = options; + const { rootName = "project", otherPaths = [], language = "python" } = options; const ordered = [...files].sort((a, b) => compareFolderPaths(a.path, b.path)); const documentLines: string[] = []; const spans: FolderFileSpan[] = []; @@ -258,7 +278,7 @@ export function buildFolderDocument(files: readonly FolderFile[], options: Folde source: documentLines.join("\n"), forcedBoundaries: spans.map(span => span.startLine), files: spans, - tree: hidden > 0 ? `${tree}\n ... and ${hidden} more non-Python files` : tree, + tree: hidden > 0 ? `${tree}\n ... and ${hidden} more non-${FOLDER_LANGUAGES[language].name} files` : tree, }; } @@ -267,33 +287,35 @@ export function buildFolderDocument(files: readonly FolderFile[], options: Folde * and byte size before anything is read, character count only once the document is assembled. * Refusing up front beats truncating, which would produce a silently incomplete workflow. */ -export function checkFolderFileCount(fileCount: number): string | null { +export function checkFolderFileCount(fileCount: number, language: MigrationLanguage = "python"): string | null { + const { name } = FOLDER_LANGUAGES[language]; if (fileCount === 0) { - return "No Python files were found in the selected folder."; + return `No ${name} files were found in the selected folder.`; } if (fileCount > MAX_FOLDER_FILES) { - return `The selected folder has ${fileCount.toLocaleString()} Python files, more than the ${MAX_FOLDER_FILES.toLocaleString()} this tool converts at once. Select a smaller folder.`; + return `The selected folder has ${fileCount.toLocaleString()} ${name} files, more than the ${MAX_FOLDER_FILES.toLocaleString()} this tool converts at once. Select a smaller folder.`; } return null; } -export function checkFolderByteSize(totalBytes: number): string | null { +export function checkFolderByteSize(totalBytes: number, language: MigrationLanguage = "python"): string | null { if (totalBytes > MAX_FOLDER_BYTES) { // Quotes the character cap and no byte figure: the byte bound guards that same limit, and // naming both would read as two limits in two units. - return `The selected folder is too large to convert. Its Python files hold more than the ${MAX_FOLDER_CHARACTERS.toLocaleString()} characters this tool converts at once. Select a smaller folder.`; + return `The selected folder is too large to convert. Its ${FOLDER_LANGUAGES[language].name} files hold more than the ${MAX_FOLDER_CHARACTERS.toLocaleString()} characters this tool converts at once. Select a smaller folder.`; } return null; } -export function checkFolderDocument(document: FolderDocument): string | null { +export function checkFolderDocument(document: FolderDocument, language: MigrationLanguage = "python"): string | null { + const { name } = FOLDER_LANGUAGES[language]; if (document.files.length === 0) { - // Distinct from finding no Python at all: these were found, and every one held no code. - return "The Python files in the selected folder are all empty."; + // Distinct from finding no source at all: these were found, and every one held no code. + return `The ${name} files in the selected folder are all empty.`; } if (document.source.length > MAX_FOLDER_CHARACTERS) { // Counts the assembled document, so it includes the banner line added per file. - return `The selected folder's Python code totals ${document.source.length.toLocaleString()} characters, more than the ${MAX_FOLDER_CHARACTERS.toLocaleString()} this tool converts at once. Select a smaller folder.`; + return `The selected folder's ${name} code totals ${document.source.length.toLocaleString()} characters, more than the ${MAX_FOLDER_CHARACTERS.toLocaleString()} this tool converts at once. Select a smaller folder.`; } return null; } 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 b4a75851f4..cb7b64fbc3 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 @@ -52,6 +52,9 @@ import { R_MAPPING_PROMPT, R_SCRIPT_WORKFLOW_PROMPT, R_SCRIPT_MAPPING_PROMPT, + R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER, + R_FOLDER_WORKFLOW_PROMPT, + R_FOLDER_MAPPING_PROMPT, } from "./migration-prompts-r"; import { GuiConfigService } from "../../../common/service/gui-config.service"; import { WorkflowUtilService } from "../workflow-graph/util/workflow-util.service"; @@ -459,6 +462,34 @@ describe("NotebookMigrationLLM", () => { expect(mappingPrompt).toBe(R_SCRIPT_MAPPING_PROMPT); }); + it("sends the R folder prelude and prompts", async () => { + mockResponses(workflowResponse, JSON.stringify({ UDF1: [[2, 2]] })); + const folder = buildFolderDocument([{ path: "main.R", source: "x <- 1" }], { rootName: "proj", language: "r" }); + + await makeLLM().convertFolderToWorkflow(folder, "r"); + + expect(contentsFor("system")).toEqual( + documentation.map(doc => + doc === R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION ? R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER : doc + ) + ); + const [workflowPrompt, mappingPrompt] = contentsFor("user"); + expect(workflowPrompt.startsWith(`${R_FOLDER_WORKFLOW_PROMPT}\nproj/\n main.R\n\nHere is the code:\n`)).toBe( + true + ); + expect(mappingPrompt).toBe(R_FOLDER_MAPPING_PROMPT); + }); + + it("builds RUDF operators and an R notebook from a folder", async () => { + mockResponses(workflowResponse, JSON.stringify({ UDF1: [[2, 2]] })); + const folder = buildFolderDocument([{ path: "main.R", source: "x <- 1" }], { language: "r" }); + + const { workflowJSON, notebook } = await makeLLM().convertFolderToWorkflow(folder, "r"); + + expect(workflowJSON.operators.map((op: any) => op.operatorType)).toEqual(["RUDF", "RUDF"]); + expect(notebook.metadata?.["kernelspec"]?.name).toBe("ir"); + }); + it("builds Table API RUDF operators", async () => { mockResponses(workflowResponse, JSON.stringify({ UDF1: ["CELL1"] })); @@ -499,6 +530,9 @@ describe("NotebookMigrationLLM", () => { "R notebook migration is disabled" ); await expect(llm.convertScriptToWorkflow("x <- 1", "r")).rejects.toThrow("R notebook migration is disabled"); + await expect(llm.convertFolderToWorkflow(buildFolderDocument([], { language: "r" }), "r")).rejects.toThrow( + "R notebook migration is disabled" + ); expect(callModelSpy).not.toHaveBeenCalled(); }); 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 a8040a737d..58cf17de06 100644 --- a/frontend/src/app/workspace/service/notebook-migration/migration-llm.ts +++ b/frontend/src/app/workspace/service/notebook-migration/migration-llm.ts @@ -57,6 +57,9 @@ import { R_MAPPING_PROMPT, R_SCRIPT_WORKFLOW_PROMPT, R_SCRIPT_MAPPING_PROMPT, + R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER, + R_FOLDER_WORKFLOW_PROMPT, + R_FOLDER_MAPPING_PROMPT, } from "./migration-prompts-r"; import { DerivedCell, ScriptSegmentation, segmentScript, splitScriptLines } from "./script-segmentation"; import { FolderDocument, resolveEntryPoint, scopeSegmentationToSpan } from "./folder-assembly"; @@ -166,6 +169,10 @@ 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 ); +const R_FOLDER_DOCUMENTATION: string[] = R_SCRIPT_DOCUMENTATION.map(doc => + doc === R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT ? R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER : doc +); + export type MigrationLanguage = "python" | "r"; interface UdfOperator { @@ -181,6 +188,9 @@ interface MigrationPromptSet { scriptDocumentation: string[]; scriptWorkflowPrompt: string; scriptMappingPrompt: string; + folderDocumentation: string[]; + folderWorkflowPrompt: string; + folderMappingPrompt: string; operator: UdfOperator; notebookMetadata: Notebook["metadata"]; } @@ -193,6 +203,9 @@ const PROMPT_SETS: Record<MigrationLanguage, MigrationPromptSet> = { scriptDocumentation: PYTHON_SCRIPT_DOCUMENTATION, scriptWorkflowPrompt: SCRIPT_WORKFLOW_PROMPT, scriptMappingPrompt: SCRIPT_MAPPING_PROMPT, + folderDocumentation: PYTHON_FOLDER_DOCUMENTATION, + folderWorkflowPrompt: FOLDER_WORKFLOW_PROMPT, + folderMappingPrompt: FOLDER_MAPPING_PROMPT, operator: { type: "PythonUDFV2", properties: {} }, notebookMetadata: { kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, @@ -206,6 +219,9 @@ const PROMPT_SETS: Record<MigrationLanguage, MigrationPromptSet> = { scriptDocumentation: R_SCRIPT_DOCUMENTATION, scriptWorkflowPrompt: R_SCRIPT_WORKFLOW_PROMPT, scriptMappingPrompt: R_SCRIPT_MAPPING_PROMPT, + folderDocumentation: R_FOLDER_DOCUMENTATION, + folderWorkflowPrompt: R_FOLDER_WORKFLOW_PROMPT, + folderMappingPrompt: R_FOLDER_MAPPING_PROMPT, // The prompts only teach the Table API. operator: { type: "RUDF", properties: { useTupleAPI: false } }, notebookMetadata: { @@ -526,17 +542,20 @@ export class NotebookMigrationLLM { * reports is in that file's lines, so clicking an operator highlights the call that runs it. * Still keyed on cell uuids, so nothing downstream learns the input was a folder. */ - public async convertFolderToWorkflow(document: FolderDocument): Promise<SourceConversion> { + public async convertFolderToWorkflow( + document: FolderDocument, + language: MigrationLanguage = "python" + ): Promise<SourceConversion> { this.assertEnabled(); if (!this.initialized) { throw new Error("LLM session not initialized"); } - const prompts = PROMPT_SETS.python; + const prompts = this.promptsFor(language); const { workflowJSON, udfIdToOperatorId, workflowResponse, reportedRanges } = await this.requestConversion( - PYTHON_FOLDER_DOCUMENTATION, - FOLDER_WORKFLOW_PROMPT, - FOLDER_MAPPING_PROMPT, + prompts.folderDocumentation, + prompts.folderWorkflowPrompt, + prompts.folderMappingPrompt, prompts.operator, document.source, // The layout is prompt text, never part of the numbered document: numbering it would shift 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 index f7b9341fd5..ed413f1a38 100644 --- 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 @@ -19,7 +19,9 @@ import { R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION, + R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER, R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT, + R_FOLDER_MAPPING_PROMPT, R_MAPPING_PROMPT, R_SCRIPT_MAPPING_PROMPT, } from "./migration-prompts-r"; @@ -44,6 +46,7 @@ describe("R migration prompts", () => { [ ["notebook", R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION], ["script", R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_SCRIPT], + ["folder", R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER], ].forEach(([input, example]) => { describe(`${input} worked example`, () => { const conversion: Conversion = JSON.parse(fencedBlock(example, "json")); @@ -61,6 +64,8 @@ describe("R migration prompts", () => { expect(code.startsWith(`# ${udfId}\n`)).toBe(true); expect(code).toContain("function(table, port)"); expect(code).not.toContain("coro"); + // R rejects \/ as an escape, so a UDF holding one fails to parse. + expect(code).not.toContain("\\/"); }); }); @@ -95,4 +100,57 @@ describe("R migration prompts", () => { expect(lines[last - 1]).toMatch(new RegExp(`^ *${last}\\| +\\S`)); }); }); + + describe("folder worked example", () => { + const lines = fencedBlock(R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER, "r").split("\n"); + const conversion: Conversion & { entry_point: string } = JSON.parse( + fencedBlock(R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER, "json") + ); + const bannerLines = lines + .map((line, index) => ({ path: line.match(/^ *\d+\| # ===== FILE: (.+) =====$/)?.[1], number: index + 1 })) + .filter(banner => banner.path !== undefined); + const definedFunctions = lines + .map(line => line.match(/^ *\d+\| (\w+) <- function\(/)?.[1]) + .filter((name): name is string => name !== undefined); + + it("names an entry point the folder contains", () => { + expect(bannerLines.map(banner => banner.path)).toContain(conversion.entry_point); + }); + + it("copies each called definition into the UDF instead of sourcing it", () => { + Object.values(conversion.code).forEach(code => { + expect(code).not.toContain("source("); + definedFunctions + .filter(name => code.includes(`${name}(`)) + .forEach(name => expect(code).toContain(`${name} <- function(`)); + }); + // Data loading is replaced by the source operator, so its helper lands in no UDF. + expect(Object.values(conversion.code).some(code => code.includes("load_data"))).toBe(false); + }); + + it("names a file in the layout that is not in the document", () => { + const layout = R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER.split("Folder layout:\n")[1].split("\n\n")[0]; + + expect(layout).toContain(" README.md"); + expect(bannerLines.map(banner => banner.path)).not.toContain("README.md"); + }); + + it("maps every UDF to non-blank lines of the entry point", () => { + const start = bannerLines.find(banner => banner.path === conversion.entry_point)!.number; + const next = bannerLines.find(banner => banner.number > start); + const end = next ? next.number - 1 : lines.length; + const mapping = mappingIn(R_FOLDER_MAPPING_PROMPT) as Record<string, [number, number][]>; + + expect(Object.keys(mapping).sort()).toEqual(Object.keys(conversion.code).sort()); + Object.values(mapping) + .flat() + .forEach(([first, last]) => { + expect(first).toBeGreaterThan(start); + expect(last).toBeLessThanOrEqual(end); + expect(first).toBeLessThanOrEqual(last); + 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 index 0f77f97e4c..3c40556018 100644 --- a/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.ts +++ b/frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.ts @@ -67,6 +67,7 @@ To show a plot, a UDF returns a single column named html-content holding a compl 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. +4. Write closing tags such as </script> exactly as shown. Do not escape the slash: R rejects '\\/' as an unrecognized escape and the UDF fails to parse. json <- plotly_json(ggplotly(p), jsonedit = FALSE) html <- paste0( @@ -462,3 +463,247 @@ Here is an example of a mapping generated between the given example R code and t } 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 [...] `; + +export const R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION_FOLDER = ` +Here is an example of breaking up a folder of R files 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 "entry_point" key names the one file that c [...] + +The folder's files are shown as one document, concatenated in the order given. A line of the form '# ===== FILE: <path> =====' marks where a file begins, and each line is prefixed by its line number and a '|'. Line numbers run continuously across the whole document and do not restart at each file. Both the banners and the number 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. + +Note that main.R is the entry point: it is the file that actually runs, sourcing the other two files and calling the functions they define. Each UDF copies in the definition of the function it calls, and the source() calls on lines 23 and 24 appear in no generated UDF. load_data is copied into no UDF, because the workflow's source operator replaces the data loading. Note also that the layout names README.md, which is not R source and so does not appear in the document. + +Folder layout: +diabetes_analysis/ + README.md + data_prep.R + main.R + models.R + +Original Code: +\`\`\`r + 1| # ===== FILE: data_prep.R ===== + 2| library(ggplot2) + 3| + 4| load_data <- function(file_path) { + 5| read.csv(file_path) + 6| } + 7| + 8| clean <- function(data) { + 9| data <- unique(data) +10| na.omit(data) +11| } +12| +13| summarize <- function(data) { +14| list(min = sapply(data, min), max = sapply(data, max), mean = colMeans(data)) +15| } +16| +17| boxplot_glucose <- function(data) { +18| ggplot(data, aes(x = factor(Outcome), y = Glucose)) + +19| geom_boxplot() + +20| labs(x = 'Outcome', y = 'Glucose', title = 'Glucose by Outcome') +21| } +22| # ===== FILE: main.R ===== +23| source('data_prep.R') +24| source('models.R') +25| +26| data <- load_data('diabetes.csv') +27| +28| data <- clean(data) +29| stats <- summarize(data) +30| print(stats) +31| +32| print(boxplot_glucose(data)) +33| +34| splits <- split_and_scale(data) +35| +36| glm_accuracy <- train_logistic_regression(splits$train, splits$test) +37| print(sprintf('Logistic Regression Accuracy: %.2f%%', 100 * glm_accuracy)) +38| +39| tree_accuracy <- train_decision_tree(splits$train, splits$test) +40| print(sprintf('Decision Tree Accuracy: %.2f%%', 100 * tree_accuracy)) +41| # ===== FILE: models.R ===== +42| library(rpart) +43| +44| split_and_scale <- function(data) { +45| set.seed(42) +46| train_idx <- sample(seq_len(nrow(data)), size = floor(0.8 * nrow(data))) +47| train <- data[train_idx, ] +48| test <- data[-train_idx, ] +49| features <- setdiff(names(data), 'Outcome') +50| centers <- sapply(train[features], mean) +51| spreads <- sapply(train[features], sd) +52| train[features] <- scale(train[features], center = centers, scale = spreads) +53| test[features] <- scale(test[features], center = centers, scale = spreads) +54| list(train = train, test = test) +55| } +56| +57| train_logistic_regression <- function(train, test) { +58| glm_model <- glm(Outcome ~ ., data = train, family = binomial) +59| glm_pred <- ifelse(predict(glm_model, test, type = 'response') > 0.5, 1, 0) +60| mean(glm_pred == test$Outcome) +61| } +62| +63| train_decision_tree <- function(train, test) { +64| tree_model <- rpart(factor(Outcome) ~ ., data = train, method = 'class') +65| tree_pred <- predict(tree_model, test, type = 'class') +66| mean(as.character(tree_pred) == as.character(test$Outcome)) +67| } +\`\`\` + +Texera UDF conversion: +\`\`\`json +{ + "entry_point": "main.R", + "code": { + "UDF1": "# UDF1\\nclean <- function(data) {\\n data <- unique(data)\\n na.omit(data)\\n}\\n\\nfunction(table, port) {\\n data <- clean(table)\\n\\n # One row of serialized objects for the downstream UDFs\\n data.frame(data = I(list(serialize(data, NULL))))\\n}", + "UDF2": "# UDF2\\nsummarize <- function(data) {\\n list(min = sapply(data, min), max = sapply(data, max), mean = colMeans(data))\\n}\\n\\nfunction(table, port) {\\n data <- unserialize(table$data[[1]])\\n stats <- summarize(data)\\n\\n # No UDF reads this one, so its columns are character\\n data.frame(\\n min_values = paste(capture.output(print(stats$min)), collapse = '\\\\n'),\\n max_values = paste(capture.output(print(stats$max)), collapse = '\\\\n'),\\n mean_val [...] + "UDF3": "# UDF3\\nlibrary(ggplot2)\\nlibrary(plotly)\\n\\nboxplot_glucose <- function(data) {\\n ggplot(data, aes(x = factor(Outcome), y = Glucose)) +\\n geom_boxplot() +\\n labs(x = 'Outcome', y = 'Glucose', title = 'Glucose by Outcome')\\n}\\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' = htm [...] + "UDF4": "# UDF4\\nsplit_and_scale <- function(data) {\\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 features <- setdiff(names(data), 'Outcome')\\n centers <- sapply(train[features], mean)\\n spreads <- sapply(train[features], sd)\\n train[features] <- scale(train[features], center = centers, scale = spreads)\\n test[features] <- scale(test[features], center = cent [...] + "UDF5": "# UDF5\\ntrain_logistic_regression <- function(train, test) {\\n glm_model <- glm(Outcome ~ ., data = train, family = binomial)\\n glm_pred <- ifelse(predict(glm_model, test, type = 'response') > 0.5, 1, 0)\\n mean(glm_pred == test$Outcome)\\n}\\n\\nfunction(table, port) {\\n train <- unserialize(table$train[[1]])\\n test <- unserialize(table$test[[1]])\\n glm_accuracy <- train_logistic_regression(train, test)\\n\\n # No UDF reads this one, so its columns are char [...] + "UDF6": "# UDF6\\nlibrary(rpart)\\n\\ntrain_decision_tree <- function(train, test) {\\n tree_model <- rpart(factor(Outcome) ~ ., data = train, method = 'class')\\n tree_pred <- predict(tree_model, test, type = 'class')\\n mean(as.character(tree_pred) == as.character(test$Outcome))\\n}\\n\\nfunction(table, port) {\\n train <- unserialize(table$train[[1]])\\n test <- unserialize(table$test[[1]])\\n tree_accuracy <- train_decision_tree(train, test)\\n\\n # No UDF reads this o [...] + }, + "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_FOLDER_WORKFLOW_PROMPT = `You are an expert in R coding and workflow systems. +Many users of Texera system are non-technical, but the R projects they provide are written by technical people. +They want to convert a folder of R files into a single Texera workflow. +Your goal is to help convert these folders 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 folder's R files 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). 'entry_point', '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: +{ +"entry_point": "path/to/main.R", +"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. +The "entry_point" value is the path of the one file whose code calls the pipeline's steps in order: the file +with top-level code that sources the others and calls the functions they define. +If that file only delegates, calling a single function in another file and doing nothing else, name the file +that defines that function instead, because that is where the steps actually are. A file holding one source() +call and one function call is never the right answer. +Give the path exactly as it appears in the banner and the layout, and name a file that is actually in the +folder. If no file clearly runs the others, give the one a reader should open first. +Settle the entry point before you write any UDF code, and give it as the first key of your reply. +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. +You are given the folder's layout first, then its R files as one document. The layout is there so you +know what exists before you read any of it; use it to tell which file a source() call refers to. Files in the +layout that are not R source are named but not included in the document, so you know they exist +without their contents. The layout itself is not code and its lines are not numbered. + +In the document that follows the layout, a line of the form '# ===== FILE: <path> =====' marks where a file +begins, and every line is prefixed with its line number followed by '| '. Line numbers run continuously +across the whole document and do not restart at each file. Both the banners and the number prefixes are +annotations so that line ranges can be referred to later; never reproduce either in any generated UDF code. + +A Texera UDF runs on its own and cannot read another file of this folder, so never call source() in a UDF. +Wherever a UDF uses a function or value that another file of the folder defines, copy that definition into +the UDF before its function(table, port). Packages are still loaded with library() as normal. +Where one file uses a value that another file produced, represent that with an edge between the two UDFs +rather than with source(): in the example, the values main.R passes from one call to the next are what +become the edges, and neither of its source() calls on lines 23 and 24 appears in any generated UDF. +A file that only defines functions and runs nothing of its own does not need a UDF of its own; its definitions +belong inside the UDFs that use them. +One file calls the pipeline's steps in order; you will name it as the entry point, and the mapping you give +afterwards will refer to its lines, so work out which file that is as you read. +Convert following the instructions and examples given. Here is the folder layout: +`; + +export const R_FOLDER_MAPPING_PROMPT = ` +Here is an example of a mapping generated between the given example folder and the Texera UDFs. Every range refers to lines of the entry point you named, and to no other file. 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. The format should be kept the same. +In the example, main.R is the entry point and occupies lines 22 to 40, so every range below falls inside it: UDF1 is the cleaning, which main.R performs on line 28; UDF2 is the statistics, computed and printed on lines 29 and 30; UDF3 is the boxplot, drawn on line 32; and so on. +{ +"UDF1": [[28, 28]], +"UDF2": [[29, 30]], +"UDF3": [[32, 32]], +"UDF4": [[34, 34]], +"UDF5": [[36, 37]], +"UDF6": [[39, 40]] +} +Now create a mapping for the UDFs and the original code you were given. For each UDF, report the line ranges of the entry point at which that UDF's work happens. When the entry point calls a function that another file defines, the line of that call is what the UDF built from that function maps to. Report ranges inside the entry point only: never a line from another file, never the banner lines, and never a line outside the entry point's own span. Lines of the entry point that no UDF corr [...] +`; 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 a5de565f63..d9d868409b 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 @@ -469,6 +469,15 @@ describe("NotebookMigrationService", () => { ); expect(createMigrationLLM).not.toHaveBeenCalled(); }); + + it("rejects an R folder before creating or pinging a client", async () => { + const folder = { source: "x <- 1", forcedBoundaries: [1], files: [], tree: "proj/" }; + + await expect(service.sendFolderToAIGenerateWorkflow(folder, "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 @@ -657,10 +666,18 @@ describe("NotebookMigrationService", () => { mappingContent: { m: 2 }, notebook: conversion.notebook, }); - expect(fakeLLM.convertFolderToWorkflow).toHaveBeenCalledWith(folder); + expect(fakeLLM.convertFolderToWorkflow).toHaveBeenCalledWith(folder, "python"); expect(fakeLLM.close).toHaveBeenCalled(); }); + it("passes the source language to the conversion", async () => { + fakeLLM.convertFolderToWorkflow.mockResolvedValue(conversion); + + await service.sendFolderToAIGenerateWorkflow(folder, "gpt-4", "r"); + + expect(fakeLLM.convertFolderToWorkflow).toHaveBeenCalledWith(folder, "r"); + }); + it("rejects when the connection cannot be verified, and still closes the client", async () => { fakeLLM.verifyConnection.mockResolvedValue(false); @@ -795,5 +812,33 @@ describe("NotebookMigrationService", () => { await expect(service.parseFolder([pickedFile("proj/main.py", "main()")])).rejects.toThrow(/Failed to read/); }); + + it("keeps R source for R and names the Python files in the layout instead", async () => { + const folder = await service.parseFolder( + [ + pickedFile("proj/main.R", "main()"), + pickedFile("proj/R/helpers.r", "helper <- function() 1"), + pickedFile("proj/legacy.py", "print(1)"), + pickedFile("proj/renv/activate.R", "renv"), + ], + "r" + ); + + expect(folder.files.map(file => file.path)).toEqual(["main.R", "R/helpers.r"]); + expect(folder.tree).toBe(["proj/", " legacy.py", " main.R", " R/", " helpers.r"].join("\n")); + expect(folder.source).not.toContain("print(1)"); + }); + + it("names R when an R selection has no R source", async () => { + await expect(service.parseFolder([pickedFile("proj/main.py", "main()")], "r")).rejects.toThrow( + "No R files were found in the selected folder." + ); + }); + + it("names R when every R file is blank", async () => { + await expect(service.parseFolder([pickedFile("proj/empty.R", " \n")], "r")).rejects.toThrow( + "The R files in the selected folder are all empty." + ); + }); }); }); 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 f710761f22..0af785e150 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 @@ -29,7 +29,7 @@ import { folderRelativePath, folderRootName, isExcludedPath, - isMigratablePythonPath, + isMigratableSourcePath, } from "./folder-assembly"; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { NotificationService } from "src/app/common/service/notification/notification.service"; @@ -159,7 +159,7 @@ export class NotebookMigrationService { } /** - * Convert a folder of Python files, already assembled by parseFolder, into a workflow. + * Convert a folder of source files, already assembled by parseFolder, into a workflow. * * Identical to the script path from the caller's side: the folder is one document by the time * it gets here, so the derived notebook and the mapping have the same shape and are stored the @@ -167,10 +167,11 @@ export class NotebookMigrationService { */ public async sendFolderToAIGenerateWorkflow( folder: FolderDocument, - modelType: string + modelType: string, + language: MigrationLanguage = "python" ): Promise<GeneratedWorkflowContent> { - return this.generateFromSource(modelType, "folder", "python", migrationLLM => - migrationLLM.convertFolderToWorkflow(folder) + return this.generateFromSource(modelType, "folder", language, migrationLLM => + migrationLLM.convertFolderToWorkflow(folder, language) ); } @@ -409,15 +410,16 @@ export class NotebookMigrationService { /** * Read a directory selection into the one document a folder conversion is run against. * - * Keeps only project Python source, reads it, and assembles it in a fixed order. The file-count - * and byte checks run before anything is read, so an over-broad or oversized selection fails at - * once rather than after thousands of reads or one enormous one. + * Keeps only project source in the given language, reads it, and assembles it in a fixed order. + * The file-count and byte checks run before anything is read, so an over-broad or oversized + * selection fails at once rather than after thousands of reads or one enormous one. */ - public async parseFolder(files: readonly File[]): Promise<FolderDocument> { + public async parseFolder(files: readonly File[], language: MigrationLanguage = "python"): Promise<FolderDocument> { const picked = files.map(file => ({ file, path: folderRelativePath(file) })); - const selected = picked.filter(entry => isMigratablePythonPath(entry.path)); - this.refuse(checkFolderFileCount(selected.length)); - this.refuse(checkFolderByteSize(selected.reduce((sum, entry) => sum + entry.file.size, 0))); + const selected = picked.filter(entry => isMigratableSourcePath(entry.path, language)); + this.refuse(checkFolderFileCount(selected.length, language)); + const totalBytes = selected.reduce((sum, entry) => sum + entry.file.size, 0); + this.refuse(checkFolderByteSize(totalBytes, language)); const sources = await Promise.all( selected.map(async entry => ({ @@ -430,13 +432,14 @@ export class NotebookMigrationService { rootName: folderRootName(files[0]?.webkitRelativePath ?? "") ?? "project", // Named in the layout but never read. Caches and hidden directories stay out entirely. otherPaths: picked - .filter(entry => !isMigratablePythonPath(entry.path) && !isExcludedPath(entry.path)) + .filter(entry => !isMigratableSourcePath(entry.path, language) && !isExcludedPath(entry.path, language)) .map(entry => entry.path), + language, }); // Run against what the document actually holds: blank files are dropped during assembly, // and the character cap needs the assembled size. - this.refuse(checkFolderDocument(folder)); + this.refuse(checkFolderDocument(folder, language)); return folder; } diff --git a/frontend/src/assets/notebook_migration_tool/r_folder_diagram.png b/frontend/src/assets/notebook_migration_tool/r_folder_diagram.png new file mode 100644 index 0000000000..e7659cb620 Binary files /dev/null and b/frontend/src/assets/notebook_migration_tool/r_folder_diagram.png differ
