Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

experimental: ai completion (#893)

Myles Scolnick7d7aef8ba4fa
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index bb79ef262d..6147a74d19 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -16,7 +16,7 @@ jobs:
test_frontend:
name: 🖥️ Lint, test, build frontend
runs-on: ubuntu-latest
- timeout-minutes: 10
+ timeout-minutes: 15
defaults:
run:
working-directory: ./frontend
@@ -64,7 +64,7 @@ jobs:
run: pnpm turbo build
test_python:
- name: Tests on ${{ matrix.os }}, Python ${{ matrix.python-version }}
+ name: Tests on ${{ matrix.os }}, Python ${{ matrix.python-version }} with ${{ matrix.dependencies }} dependencies
runs-on: ${{ matrix.os }}
timeout-minutes: 10
defaults:
@@ -74,24 +74,27 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
- python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
- exclude:
- - os: macos-latest
- python-version: "3.8"
- - os: macos-latest
+ dependencies: ["core", "core,optional"]
+ python-version: ["3.8"]
+ include:
+ - os: ubuntu-latest
python-version: "3.9"
- - os: macos-latest
+ dependencies: "core"
+ - os: ubuntu-latest
python-version: "3.11"
- - os: macos-latest
+ dependencies: "core"
+ - os: ubuntu-latest
python-version: "3.12"
- - os: windows-latest
- python-version: "3.8"
- - os: windows-latest
+ dependencies: "core"
+ - os: ubuntu-latest
python-version: "3.9"
- - os: windows-latest
+ dependencies: "core,optional"
+ - os: ubuntu-latest
python-version: "3.11"
- - os: windows-latest
+ dependencies: "core,optional"
+ - os: ubuntu-latest
python-version: "3.12"
+ dependencies: "core,optional"
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
@@ -137,6 +140,7 @@ jobs:
mypy --config-file pyproject.toml marimo/
# Test with minimal dependencies
- name: Test with minimal dependencies
+ if: ${{ matrix.dependencies == 'core' }}
run: |
python -m venv marimo-test-env
if [ "$RUNNER_OS" == "Windows" ]; then
@@ -149,6 +153,7 @@ jobs:
pytest -v tests/ -k "not test_cli"
# Test with optional dependencies
- name: Test with optional dependencies
+ if: ${{ matrix.dependencies == 'core,optional' }}
run: |
python -m venv marimo-test-optional-env
if [ "$RUNNER_OS" == "Windows" ]; then
@@ -158,7 +163,12 @@ jobs:
fi
python -m pip install --upgrade pip
pip install .[testcore,testoptional]
- pytest -v tests/ -k "not test_cli" --cov=marimo --cov-branch
+ # Only collect coverage on the 3.11
+ if [ "${{ matrix.python-version }}" == "3.11" ]; then
+ pytest -v tests/ -k "not test_cli" --cov=marimo --cov-branch
+ else
+ pytest -v tests/ -k "not test_cli"
+ fi
- name: Upload coverage reports to Codecov
if: ${{ matrix.python-version == '3.11' && matrix.os == 'ubuntu-latest' }}
uses: codecov/codecov-action@v3
diff --git a/docs/_static/ai-completion.mp4 b/docs/_static/ai-completion.mp4
new file mode 100644
index 0000000000..93968f62c8
Binary files /dev/null and b/docs/_static/ai-completion.mp4 differ
diff --git a/docs/getting_started/index.md b/docs/getting_started/index.md
index af2235e913..e06c1483f4 100644
--- a/docs/getting_started/index.md
+++ b/docs/getting_started/index.md
@@ -31,17 +31,20 @@ Learn more from the [official Python tutorial](https://docs.python.org/3/tutoria
To install marimo, run the following in a terminal:
-
::::{tab-set}
:::{tab-item} install with pip
+
```bash
pip install marimo
```
+
:::
:::{tab-item} install with conda
+
```bash
conda install -c conda-forge marimo
```
+
:::
::::
@@ -76,7 +79,7 @@ Create and edit notebooks with `marimo edit`.
marimo edit
```
-- marimo saves notebooks as Python files, which you can edit using:
+- marimo saves notebooks as Python files, which you can edit using:
```bash
marimo edit your_notebook.py
@@ -106,9 +109,9 @@ Because marimo is different from traditional notebooks, your converted notebook
will likely have errors that you'll need to fix. marimo will guide you through
fixing them when you open it with `marimo edit`.
-## Github Copilot
+## GitHub Copilot
-The marimo editor natively supports [Github Copilot](https://copilot.github.com/),
+The marimo editor natively supports [GitHub Copilot](https://copilot.github.com/),
an AI pair programmer, similar to VS Code.
_Get started with Copilot_:
diff --git a/docs/guides/ai_completion.md b/docs/guides/ai_completion.md
new file mode 100644
index 0000000000..befc23f33b
--- /dev/null
+++ b/docs/guides/ai_completion.md
@@ -0,0 +1,46 @@
+# AI completion
+
+marimo comes with GitHub Copilot, a tool that helps you write code faster by
+suggesting in-line code suggestions based on the context of your current code.
+
+marimo also comes with the ability to use AI for refactoring a cell, finishing writing a cell, or writing a full cell from scratch.
+This feature is currently experimental and is not enabled by default.
+
+## GitHub Copilot
+
+The marimo editor natively supports [GitHub Copilot](https://copilot.github.com/),
+an AI pair programmer, similar to VS Code.
+
+_Get started with Copilot_:
+
+1. Install [Node.js](https://nodejs.org/en/download).
+2. Enable Copilot via the settings menu in the marimo editor.
+
+_Note_: Copilot is not yet available in our conda distribution; please install
+marimo using `pip` if you need Copilot.
+
+## Using AI to modify cells
+
+This feature is currently experimental and is not enabled by default. To enable it:
+
+1. You need add the following to your `~/.marimo.toml`:
+
+```toml
+[experimental]
+ai = true
+```
+
+2. Add your OpenAI API key to your environment:
+
+```bash
+export OPENAI_API_KEY=your-api-key
+```
+
+Once enabled, you can use AI completion by pressing `Ctrl/Cmd-Shift-e` in a cell. This will open an input to modify the cell using AI.
+
+<div align="center">
+<figure>
+<video src="/_static/ai-completion.mp4" controls="controls" width="100%" height="100%"></video>
+<figcaption>Use AI to modify a cell by pressing `Ctrl/Cmd-Shift-e`.</figcaption>
+</figure>
+</div>
diff --git a/docs/guides/index.md b/docs/guides/index.md
index 5532fdbfd1..f2d2b9cdc3 100644
--- a/docs/guides/index.md
+++ b/docs/guides/index.md
@@ -16,6 +16,7 @@
apps
scripts
wasm
+ ai_completion
best_practices
deploying/index
```
@@ -36,6 +37,7 @@ These guides cover marimo's core concepts.
| {doc}`scripts` | Running notebooks as scripts |
| {doc}`best_practices` | Best practices when working with marimo |
| {doc}`wasm` | Running notebooks in the browser (no backend required!) |
+| {doc}`ai_completion` | Using AI to speed up your coding |
| {doc}`deploying/index` | Deploying marimo notebooks and apps |
```{admonition} Learn by doing!
diff --git a/frontend/package.json b/frontend/package.json
index ad0bda6f25..97dd60cda8 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -69,6 +69,7 @@
"@types/react-grid-layout": "^1.3.5",
"@uiw/codemirror-extensions-langs": "^4.21.23",
"@uiw/react-codemirror": "^4.21.23",
+ "ai": "^3.0.1",
"ansi_up": "^6.0.2",
"blob-polyfill": "^7.0.20220408",
"class-variance-authority": "^0.7.0",
@@ -98,6 +99,7 @@
"plotly.js": "^2.29.1",
"pyodide": "^0.25.0",
"react-arborist": "^3.4.0",
+ "react-codemirror-merge": "^4.21.24",
"react-day-picker": "^8.10.0",
"react-dropzone": "^14.2.3",
"react-error-boundary": "^4.0.12",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index ff198a2b30..64167bf136 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -175,7 +175,10 @@ dependencies:
version: 4.21.23(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
'@uiw/react-codemirror':
specifier: ^4.21.23
+ ai:
+ specifier: ^3.0.1
ansi_up:
specifier: ^6.0.2
version: 6.0.2
@@ -263,6 +266,9 @@ dependencies:
react-arborist:
specifier: ^3.4.0
+ react-codemirror-merge:
+ specifier: ^4.21.24
react-day-picker:
specifier: ^8.10.0
@@ -474,7 +480,6 @@ packages:
dependencies:
'@jridgewell/gen-mapping': 0.3.3
'@jridgewell/trace-mapping': 0.3.18
- dev: true
/@aw-web-design/[email protected]:
resolution: {integrity: sha512-Xk1sIhyNC/esHGGVjL/niHLowM0csl/kFO5uawBy4IrWwy0o1G8LGt3jP6nmWGz+USxeeqbihAmp/oVZju6wug==}
@@ -505,7 +510,7 @@ packages:
'@babel/helper-compilation-targets': 7.22.15
'@babel/helper-module-transforms': 7.23.3(@babel/[email protected])
'@babel/helpers': 7.23.5
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@babel/template': 7.22.15
'@babel/traverse': 7.23.5
'@babel/types': 7.23.5
@@ -743,8 +748,8 @@ packages:
chalk: 2.4.2
js-tokens: 4.0.0
- resolution: {integrity: sha512-hOOqoiNXrmGdFbhgCzu6GiURxUgM27Xwd/aPuu8RfHEZPBzL1Z54okAHAQjXfcQNwvrlkAmAp4SlRTZ45vlthQ==}
+ resolution: {integrity: sha512-QuP/FxEAzMSjXygs8v4N9dvdXzEHN4W1oF3PxuWAtPo08UdM17u89RDMgjLn/mlc56iM0HlLmVkO/wgR+rDgHg==}
engines: {node: '>=6.0.0'}
hasBin: true
dependencies:
@@ -1724,7 +1729,7 @@ packages:
engines: {node: '>=6.9.0'}
dependencies:
'@babel/code-frame': 7.23.5
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@babel/types': 7.23.5
@@ -1737,7 +1742,7 @@ packages:
'@babel/helper-function-name': 7.23.0
'@babel/helper-hoist-variables': 7.22.5
'@babel/helper-split-export-declaration': 7.22.6
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@babel/types': 7.23.5
debug: 4.3.4
globals: 11.12.0
@@ -2054,6 +2059,16 @@ packages:
crelt: 1.0.5
dev: false
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-VXKxm8Jrv2HpEVW9CcYiV4VMVWsFz2XOk34Ve9ouqFT4iKc2r9+IGuMjyeH+g5T0HKUnRGYIv2wayMsPtao7Zw==}
+ dependencies:
+ '@codemirror/language': 6.10.1
+ '@codemirror/state': 6.4.1
+ '@codemirror/view': 6.24.1
+ '@lezer/highlight': 1.2.0
+ style-mod: 4.1.0
+ dev: false
+
/@codemirror/[email protected]:
resolution: {integrity: sha512-rpMgcsh7o0GuCDUXKPvww+muLA1pDJaFrpq/CCHtpQJYz8xopu4D1hPcKRoDD0YlF8gZaqTNIRa4VRBWyhyy7Q==}
dependencies:
@@ -2252,7 +2267,7 @@ packages:
'@emotion/memoize': 0.8.1
'@emotion/unitless': 0.8.1
'@emotion/utils': 1.2.1
- csstype: 3.1.2
+ csstype: 3.1.3
dev: false
/@emotion/[email protected]:
@@ -3122,7 +3137,7 @@ packages:
'@types/react': 18.2.58
'@types/react-transition-group': 4.4.6
clsx: 1.2.1
- csstype: 3.1.2
+ csstype: 3.1.3
prop-types: 15.8.1
react: 18.2.0
react-dom: 18.2.0([email protected])
@@ -3164,7 +3179,7 @@ packages:
'@emotion/cache': 11.11.0
'@emotion/react': 11.11.3(@types/[email protected])([email protected])
'@emotion/styled': 11.11.0(@emotion/[email protected])(@types/[email protected])([email protected])
- csstype: 3.1.2
+ csstype: 3.1.3
prop-types: 15.8.1
react: 18.2.0
dev: false
@@ -3194,7 +3209,7 @@ packages:
'@mui/utils': 5.13.6([email protected])
'@types/react': 18.2.58
clsx: 1.2.1
- csstype: 3.1.2
+ csstype: 3.1.3
prop-types: 15.8.1
react: 18.2.0
dev: false
@@ -5460,7 +5475,7 @@ packages:
express: 4.18.2
find-cache-dir: 3.3.2
fs-extra: 11.1.1
- magic-string: 0.30.5
+ magic-string: 0.30.7
rollup: 3.28.0
typescript: 5.3.3
vite: 5.1.4([email protected])
@@ -5698,7 +5713,7 @@ packages:
resolution: {integrity: sha512-s7XFIi823HhcKxTqHY/uU1QZCujLBjFt6OJa5y3XvwIMoLJWZtuT1PF/QPR0K7iYb9gQnGHwO9lZBfMraUywrQ==}
dependencies:
'@babel/generator': 7.23.5
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@babel/traverse': 7.23.5
'@babel/types': 7.23.5
'@storybook/csf': 0.1.2
@@ -5849,7 +5864,7 @@ packages:
'@storybook/builder-vite': 7.6.14([email protected])([email protected])
'@vitejs/plugin-react': 3.1.0([email protected])
- magic-string: 0.30.5
+ magic-string: 0.30.7
react: 18.2.0
react-docgen: 7.0.1
react-dom: 18.2.0([email protected])
@@ -6229,7 +6244,7 @@ packages:
resolution: {integrity: sha512-+n8dL/9GWblDO0iU6eZAwEIJVr5DWigtle+Q6HLOrh/pdbXOhOtqzq8VPPE2zvNJzSKY4vH/z3iT3tn0A3ypiQ==}
dependencies:
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@babel/types': 7.23.5
'@types/babel__generator': 7.6.4
'@types/babel__template': 7.4.1
@@ -6243,7 +6258,7 @@ packages:
resolution: {integrity: sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==}
dependencies:
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@babel/types': 7.23.5
@@ -6461,6 +6476,10 @@ packages:
resolution: {integrity: sha512-bV/jQlAJ/nPY3XqSatkGpu+nGzou+uSwrH1cROhn+jBFg47yaNH+blW4C7p9KhopC7QxCv/6M86s37k8dMk0Yg==}
dev: true
+ resolution: {integrity: sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==}
+ dev: false
+
resolution: {integrity: sha512-w5jZ0ee+HaPOaX25X2/2oGR/7rgAQSYII7X7pp0m9KgBfMP7uKfMfTvcpl5Dj+eDBbpxKGiqE+flqDr6XTd2RA==}
dev: true
@@ -6694,7 +6713,7 @@ packages:
dependencies:
'@types/prop-types': 15.7.5
'@types/scheduler': 0.16.2
- csstype: 3.1.2
+ csstype: 3.1.3
resolution: {integrity: sha512-BKGK0T1VgB1zD+PwQR4RRf0ais3NyvH1qjLUrHI5SEiccYaJrhLstLuoXFWJ+2Op9whGizSPUMGPJY/Qtb/A2w==}
@@ -6944,8 +6963,8 @@ packages:
eslint-visitor-keys: 3.4.3
dev: true
- /@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected]):
- resolution: {integrity: sha512-8czPnm5f/UthTbByamiaeutvDDUf2ZIbXyfuamrU3J/ThLRVzOxtvv9Su1BWiFbO2enixQfxrKaZd26uuYUbtQ==}
+ /@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected]):
+ resolution: {integrity: sha512-TJYKlPxNAVJNclW1EGumhC7I02jpdMgBon4jZvb5Aju9+tUzS44IwORxUx8BD8ZtH2UHmYS+04rE3kLk/BtnCQ==}
peerDependencies:
'@codemirror/autocomplete': '>=6.0.0'
'@codemirror/commands': '>=6.0.0'
@@ -7008,8 +7027,8 @@ packages:
- '@lezer/lr'
dev: false
- resolution: {integrity: sha512-KCjIQdkb4Y1ZsMvWwj/rGjC81VFvzRNYvcpNpBzBx3D2ZlWdMnCWHV9KJtDuHyKTHQlgpWNp8HMnUjxaQsnisA==}
+ resolution: {integrity: sha512-8zs5OuxbhikHocHBsVBMuW1vqlv4ccZAkt4rFwr7ebLP2Q6RwHsjpsR9GeGyAigAqonKRoeHugqF78UMrkaTgg==}
peerDependencies:
'@babel/runtime': '>=7.11.0'
'@codemirror/state': '>=6.0.0'
@@ -7024,7 +7043,7 @@ packages:
'@codemirror/state': 6.4.1
'@codemirror/theme-one-dark': 6.1.2
'@codemirror/view': 6.24.1
- '@uiw/codemirror-extensions-basic-setup': 4.21.23(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
+ '@uiw/codemirror-extensions-basic-setup': 4.21.24(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
codemirror: 6.0.1(@lezer/[email protected])
react: 18.2.0
react-dom: 18.2.0([email protected])
@@ -7084,7 +7103,7 @@ packages:
resolution: {integrity: sha512-EF++BZbt6RZmOlE3SuTPu/NfwBF6q4ABS37HHXzs2LUVPBLx2QoY/K0fKpRChSo8eLiuxcbCVfqKgx/dplCDuQ==}
dependencies:
- magic-string: 0.30.5
+ magic-string: 0.30.7
pathe: 1.1.1
pretty-format: 29.7.0
dev: true
@@ -7104,6 +7123,79 @@ packages:
pretty-format: 29.7.0
dev: true
+ resolution: {integrity: sha512-MjXawxZf2SbZszLPYxaFCjxfibYrzr3eYbKxwpLR9EQN+oaziSu3qKVbwBERj1IFIB8OLUewxB5m/BFzi613og==}
+ dependencies:
+ '@babel/parser': 7.24.0
+ '@vue/shared': 3.4.21
+ entities: 4.5.0
+ estree-walker: 2.0.2
+ source-map-js: 1.0.2
+ dev: false
+
+ resolution: {integrity: sha512-IZC6FKowtT1sl0CR5DpXSiEB5ayw75oT2bma1BEhV7RRR1+cfwLrxc2Z8Zq/RGFzJ8w5r9QtCOvTjQgdn0IKmA==}
+ dependencies:
+ '@vue/compiler-core': 3.4.21
+ '@vue/shared': 3.4.21
+ dev: false
+
+ resolution: {integrity: sha512-me7epoTxYlY+2CUM7hy9PCDdpMPfIwrOvAXud2Upk10g4YLv9UBW7kL798TvMeDhPthkZ0CONNrK2GoeI1ODiQ==}
+ dependencies:
+ '@babel/parser': 7.24.0
+ '@vue/compiler-core': 3.4.21
+ '@vue/compiler-dom': 3.4.21
+ '@vue/compiler-ssr': 3.4.21
+ '@vue/shared': 3.4.21
+ estree-walker: 2.0.2
+ magic-string: 0.30.7
+ postcss: 8.4.35
+ source-map-js: 1.0.2
+ dev: false
+
+ resolution: {integrity: sha512-M5+9nI2lPpAsgXOGQobnIueVqc9sisBFexh5yMIMRAPYLa7+5wEJs8iqOZc1WAa9WQbx9GR2twgznU8LTIiZ4Q==}
+ dependencies:
+ '@vue/compiler-dom': 3.4.21
+ '@vue/shared': 3.4.21
+ dev: false
+
+ resolution: {integrity: sha512-UhenImdc0L0/4ahGCyEzc/pZNwVgcglGy9HVzJ1Bq2Mm9qXOpP8RyNTjookw/gOCUlXSEtuZ2fUg5nrHcoqJcw==}
+ dependencies:
+ '@vue/shared': 3.4.21
+ dev: false
+
+ resolution: {integrity: sha512-pQthsuYzE1XcGZznTKn73G0s14eCJcjaLvp3/DKeYWoFacD9glJoqlNBxt3W2c5S40t6CCcpPf+jG01N3ULyrA==}
+ dependencies:
+ '@vue/reactivity': 3.4.21
+ '@vue/shared': 3.4.21
+ dev: false
+
+ resolution: {integrity: sha512-gvf+C9cFpevsQxbkRBS1NpU8CqxKw0ebqMvLwcGQrNpx6gqRDodqKqA+A2VZZpQ9RpK2f9yfg8VbW/EpdFUOJw==}
+ dependencies:
+ '@vue/runtime-core': 3.4.21
+ '@vue/shared': 3.4.21
+ csstype: 3.1.3
+ dev: false
+
+ resolution: {integrity: sha512-aV1gXyKSN6Rz+6kZ6kr5+Ll14YzmIbeuWe7ryJl5muJ4uwSwY/aStXTixx76TwkZFJLm1aAlA/HSWEJ4EyiMkg==}
+ peerDependencies:
+ vue: 3.4.21
+ dependencies:
+ '@vue/compiler-ssr': 3.4.21
+ '@vue/shared': 3.4.21
+ vue: 3.4.21([email protected])
+ dev: false
+
+ resolution: {integrity: sha512-PuJe7vDIi6VYSinuEbUIQgMIRZGgM8e4R+G+/dQTk0X1NEdvgvvgv7m+rfmDH1gZzyA1OjjoWskvHlfRNfQf3g==}
+ dev: false
+
/@webassemblyjs/[email protected]:
resolution: {integrity: sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==}
dependencies:
@@ -7343,6 +7435,43 @@ packages:
indent-string: 4.0.0
dev: true
+ resolution: {integrity: sha512-rzBJFhGQAMMzQEPCAWPc2XB4wQ4ce2k/fo9MTWkp2awPsZX2d11DsXF8BMDYFVO/xioEPTeix138jVQEZEpY7g==}
+ engines: {node: '>=14.6'}
+ peerDependencies:
+ react: ^18.2.0
+ solid-js: ^1.7.7
+ svelte: ^3.0.0 || ^4.0.0
+ vue: ^3.3.4
+ zod: ^3.0.0
+ peerDependenciesMeta:
+ react:
+ optional: true
+ solid-js:
+ optional: true
+ svelte:
+ optional: true
+ vue:
+ optional: true
+ zod:
+ optional: true
+ dependencies:
+ eventsource-parser: 1.0.0
+ jsondiffpatch: 0.6.0
+ nanoid: 3.3.6
+ react: 18.2.0
+ solid-js: 1.8.15
+ solid-swr-store: 0.10.7([email protected])([email protected])
+ sswr: 2.0.0([email protected])
+ svelte: 4.2.12
+ swr: 2.2.0([email protected])
+ swr-store: 0.10.6
+ swrv: 1.0.4([email protected])
+ vue: 3.4.21([email protected])
+ zod: 3.22.4
+ zod-to-json-schema: 3.22.4([email protected])
+ dev: false
+
resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==}
peerDependencies:
@@ -7450,7 +7579,6 @@ packages:
resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
dependencies:
dequal: 2.0.3
- dev: true
resolution: {integrity: sha512-8wdW3ZGk6UjMPJx/glyEt0sLzzwAE1bhToPsO1W2pbpR2gULyxe3BjSiuJFheP50T/GgODVPz2fuMUmIywt8cQ==}
@@ -7652,6 +7780,12 @@ packages:
dequal: 2.0.3
dev: true
+ resolution: {integrity: sha512-+60uv1hiVFhHZeO+Lz0RYzsVHy5Wr1ayX0mwda9KPDVLNJgZ1T9Ny7VmFbLDzxsH0D87I86vgj3gFrjTJUYznw==}
+ dependencies:
+ dequal: 2.0.3
+ dev: false
+
resolution: {integrity: sha512-poPX9mZH/5CSanm50Q+1toVci6pv5KSRv/5TWCwtzQS5XEwn40BcCrgIeMFWP9CKKIniKXNxoIOnOq4VVlGXhg==}
peerDependencies:
@@ -7996,6 +8130,11 @@ packages:
ansi-styles: 4.3.0
supports-color: 7.2.0
+ resolution: {integrity: sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==}
+ engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}
+ dev: false
+
resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}
dev: false
@@ -8168,6 +8307,16 @@ packages:
engines: {node: '>=0.10.0'}
dev: false
+ resolution: {integrity: sha512-7qJWqItLA8/VPVlKJlFXU+NBlo/qyfs39aJcuMT/2ere32ZqvF5OSxgdM5xOfJJ7O429gg2HM47y8v9P+9wrNw==}
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.4.15
+ '@types/estree': 1.0.1
+ acorn: 8.11.2
+ estree-walker: 3.0.3
+ periscopic: 3.1.0
+ dev: false
+
resolution: {integrity: sha512-IgNoyK7d4HJicqZMYMC1RgHlpR1pnSEgDHATKIuQrqW68o5QmD8IFZ26M/8UXNI+Usb00Vu4q0EtzMdm92pOAg==}
peerDependencies:
@@ -8660,8 +8809,8 @@ packages:
rrweb-cssom: 0.6.0
dev: true
- resolution: {integrity: sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ==}
+ resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
resolution: {integrity: sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==}
@@ -9294,6 +9443,10 @@ packages:
resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==}
+ resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==}
+ dev: false
+
resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
@@ -9343,7 +9496,7 @@ packages:
resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==}
dependencies:
'@babel/runtime': 7.23.8
- csstype: 3.1.2
+ csstype: 3.1.3
dev: false
@@ -10031,13 +10184,11 @@ packages:
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
- dev: true
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
dependencies:
'@types/estree': 1.0.1
- dev: true
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
@@ -10058,6 +10209,11 @@ packages:
engines: {node: '>=0.8.x'}
dev: false
+ resolution: {integrity: sha512-9jgfSCa3dmEme2ES3mPByGXfgZ87VbP97tng1G2nWwWx6bV2nYxm2AWCrbQjXToSe+yYlqaZNtxffR9IeQr95g==}
+ engines: {node: '>=14.18'}
+ dev: false
+
resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}
engines: {node: '>=10'}
@@ -11444,6 +11600,12 @@ packages:
resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
dev: true
+ resolution: {integrity: sha512-v3rht/LgVcsdZa3O2Nqs+NMowLOxeOm7Ay9+/ARQ2F+qEoANRcqrjAZKGN0v8ymUetZGgkp26LTnGT7H0Qo9Pg==}
+ dependencies:
+ '@types/estree': 1.0.1
+ dev: false
+
resolution: {integrity: sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==}
engines: {node: '>= 0.4'}
@@ -11590,7 +11752,7 @@ packages:
engines: {node: '>=8'}
dependencies:
'@babel/core': 7.23.5
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@istanbuljs/schema': 0.1.3
istanbul-lib-coverage: 3.2.0
semver: 6.3.1
@@ -11750,7 +11912,7 @@ packages:
optional: true
dependencies:
'@babel/core': 7.23.5
- '@babel/parser': 7.23.5
+ '@babel/parser': 7.24.0
'@babel/plugin-transform-class-properties': 7.23.3(@babel/[email protected])
'@babel/plugin-transform-modules-commonjs': 7.23.3(@babel/[email protected])
'@babel/plugin-transform-nullish-coalescing-operator': 7.23.4(@babel/[email protected])
@@ -11883,6 +12045,16 @@ packages:
resolution: {integrity: sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==}
dev: true
+ resolution: {integrity: sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+ dependencies:
+ '@types/diff-match-patch': 1.0.36
+ chalk: 5.3.0
+ diff-match-patch: 1.0.5
+ dev: false
+
resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==}
dependencies:
@@ -12084,6 +12256,10 @@ packages:
pkg-types: 1.0.3
dev: true
+ resolution: {integrity: sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==}
+ dev: false
+
resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==}
engines: {node: '>=6'}
@@ -12190,12 +12366,11 @@ packages:
'@jridgewell/sourcemap-codec': 1.4.15
dev: true
- resolution: {integrity: sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==}
+ resolution: {integrity: sha512-8vBuFF/I/+OSLRmdf2wwFCJCz+nSn0m6DPvGH1fS/KiQoSaR+sETbov0eIk9KhEKy8CYqIkIAnbohxT/4H0kuA==}
engines: {node: '>=12'}
dependencies:
'@jridgewell/sourcemap-codec': 1.4.15
- dev: true
resolution: {integrity: sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==}
@@ -12723,6 +12898,12 @@ packages:
object-assign: 4.1.1
thenify-all: 1.6.0
+ resolution: {integrity: sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+ dev: false
+
resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -13263,6 +13444,14 @@ packages:
resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==}
dev: false
+ resolution: {integrity: sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==}
+ dependencies:
+ '@types/estree': 1.0.1
+ estree-walker: 3.0.3
+ is-reference: 3.0.2
+ dev: false
+
resolution: {integrity: sha512-ESj2+eBxhGrcA1azgHs7lARG5+5iLakc/6nlfbpjcLl00HuuUOIuORhYXN4D1HfvMSKuVtFQjAlnwi1JHEeDIw==}
dev: false
@@ -14096,6 +14285,33 @@ packages:
- '@types/react'
dev: false
+ resolution: {integrity: sha512-apdevGJqzFik2Rb0bDihYKM7K3jw844/lcVD2a5NGxFD/F0azF0+2KbEpYU1L9DuVOoRHpI3ioE22QhzCgYQNw==}
+ peerDependencies:
+ '@babel/runtime': '>=7.11.0'
+ '@codemirror/state': '>=6.0.0'
+ '@codemirror/theme-one-dark': '>=6.0.0'
+ '@codemirror/view': '>=6.0.0'
+ codemirror: '>=6.0.0'
+ react: '>=16.8.0'
+ react-dom: '>=16.8.0'
+ dependencies:
+ '@babel/runtime': 7.23.8
+ '@codemirror/merge': 6.6.0
+ '@codemirror/state': 6.4.1
+ '@codemirror/theme-one-dark': 6.1.2
+ '@codemirror/view': 6.24.1
+ '@uiw/react-codemirror': 4.21.24(@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected])([email protected])
+ codemirror: 6.0.1(@lezer/[email protected])
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ transitivePeerDependencies:
+ - '@codemirror/autocomplete'
+ - '@codemirror/language'
+ - '@codemirror/lint'
+ - '@codemirror/search'
+ dev: false
+
resolution: {integrity: sha512-1exovf0uGTGyq5mXQT0zgQ80uvj2PCwvF8zY1RN9/vbJVSjSo3fsB/4L3ObbF7u70NduSiK4xu4Y6q1MHoUGEw==}
peerDependencies:
@@ -15036,6 +15252,20 @@ packages:
randombytes: 2.1.0
dev: false
+ resolution: {integrity: sha512-DQ2IK6oQVvy8k+c2V5x5YCtUa/GGGsUwUBNN9UqohrZ0rWdUapBFpNMYP1bCyRHoxOJjdKGl+dieacFIpU/i1A==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ seroval: ^1.0
+ dependencies:
+ seroval: 1.0.4
+ dev: false
+
+ resolution: {integrity: sha512-qQs/N+KfJu83rmszFQaTxcoJoPn6KNUruX4KmnmyD0oZkUoiNvJ1rpdYKDf4YHM05k+HOgCxa3yvf15QbVijGg==}
+ engines: {node: '>=10'}
+ dev: false
+
resolution: {integrity: sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==}
engines: {node: '>= 0.8.0'}
@@ -15150,6 +15380,25 @@ packages:
is-fullwidth-code-point: 3.0.0
dev: true
+ resolution: {integrity: sha512-d0QP/efr3UVcwGgWVPveQQ0IHOH6iU7yUhc2piy8arNG8wxKmvUy1kFxyF8owpmfCWGB87usDKMaVnsNYZm+Vw==}
+ dependencies:
+ csstype: 3.1.3
+ seroval: 1.0.4
+ seroval-plugins: 1.0.4([email protected])
+ dev: false
+
+ resolution: {integrity: sha512-A6d68aJmRP471aWqKKPE2tpgOiR5fH4qXQNfKIec+Vap+MGQm3tvXlT8n0I8UgJSlNAsSAUuw2VTviH2h3Vv5g==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ solid-js: ^1.2
+ swr-store: ^0.10
+ dependencies:
+ solid-js: 1.8.15
+ swr-store: 0.10.6
+ dev: false
+
resolution: {integrity: sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==}
engines: {node: '>=0.10.0'}
@@ -15219,6 +15468,15 @@ packages:
tweetnacl: 0.14.5
dev: false
+ resolution: {integrity: sha512-mV0kkeBHcjcb0M5NqKtKVg/uTIYNlIIniyDfSGrSfxpEdM9C365jK0z55pl9K0xAkNTJi2OAOVFQpgMPUk+V0w==}
+ peerDependencies:
+ svelte: ^4.0.0
+ dependencies:
+ svelte: 4.2.12
+ swrev: 4.0.0
+ dev: false
+
resolution: {integrity: sha512-vjUc6sfgtgY0dxCdnc40mK6Oftjo9+2K8H/NG81TMhgL392FtiPA9tn9RLyTxXmTLPJPjF3VyzFp6bsWFLisMQ==}
dev: false
@@ -15616,6 +15874,26 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-d8+wsh5TfPwqVzbm4/HCXC783/KPHV60NvwitJnyTA5lWn1elhXMNWhXGCJ7PwPa8qFUnyJNIyuIRt2mT0WMug==}
+ engines: {node: '>=16'}
+ dependencies:
+ '@ampproject/remapping': 2.2.1
+ '@jridgewell/sourcemap-codec': 1.4.15
+ '@jridgewell/trace-mapping': 0.3.18
+ '@types/estree': 1.0.1
+ acorn: 8.11.2
+ aria-query: 5.3.0
+ axobject-query: 4.0.0
+ code-red: 1.0.4
+ css-tree: 2.3.1
+ estree-walker: 3.0.3
+ is-reference: 3.0.2
+ locate-character: 3.0.0
+ magic-string: 0.30.7
+ periscopic: 3.1.0
+ dev: false
+
resolution: {integrity: sha512-djbJ/vZKZO+gPoSDThGNpKDO+o+bAeA4XQKovvkNCqnIS2t+S4qnLAGQhyyrulhCFRl1WWzAp0wUDV8PpTVU3g==}
dev: false
@@ -15662,6 +15940,34 @@ packages:
engines: {node: '>= 4.7.0'}
dev: false
+ resolution: {integrity: sha512-xPjB1hARSiRaNNlUQvWSVrG5SirCjk2TmaUyzzvk69SZQan9hCJqw/5rG9iL7xElHU784GxRPISClq4488/XVw==}
+ engines: {node: '>=10'}
+ dependencies:
+ dequal: 2.0.3
+ dev: false
+
+ resolution: {integrity: sha512-AjqHOv2lAhkuUdIiBu9xbuettzAzWXmCEcLONNKJRba87WAefz8Ca9d6ds/SzrPc235n1IxWYdhJ2zF3MNUaoQ==}
+ peerDependencies:
+ react: ^16.11.0 || ^17.0.0 || ^18.0.0
+ dependencies:
+ react: 18.2.0
+ use-sync-external-store: 1.2.0([email protected])
+ dev: false
+
+ resolution: {integrity: sha512-LqVcOHSB4cPGgitD1riJ1Hh4vdmITOp+BkmfmXRh4hSF/t7EnS4iD+SOTmq7w5pPm/SiPeto4ADbKS6dHUDWFA==}
+ dev: false
+
+ resolution: {integrity: sha512-zjEkcP8Ywmj+xOJW3lIT65ciY/4AL4e/Or7Gj0MzU3zBJNMdJiT8geVZhINavnlHRMMCcJLHhraLTAiDOTmQ9g==}
+ peerDependencies:
+ vue: '>=3.2.26 < 4'
+ dependencies:
+ vue: 3.4.21([email protected])
+ dev: false
+
resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
dev: true
@@ -16240,7 +16546,6 @@ packages:
resolution: {integrity: sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==}
engines: {node: '>=14.17'}
hasBin: true
- dev: true
resolution: {integrity: sha512-o+ORpgGwaYQXgqGDwd+hkS4PuZ3QnmqMMxRuajK/a38L6fTpcE5GPIfrf+L/KemFzfUpeUQc1rRS1iDBozvnFA==}
@@ -17019,7 +17324,7 @@ packages:
execa: 8.0.1
jsdom: 24.0.0
local-pkg: 0.5.0
- magic-string: 0.30.5
+ magic-string: 0.30.7
pathe: 1.1.1
picocolors: 1.0.0
std-env: 3.6.0
@@ -17067,6 +17372,22 @@ packages:
pbf: 3.2.1
dev: false
+ resolution: {integrity: sha512-5hjyV/jLEIKD/jYl4cavMcnzKwjMKohureP8ejn3hhEjwhWIhWeuzL2kJAjzl/WyVsgPY56Sy4Z40C3lVshxXA==}
+ peerDependencies:
+ typescript: '*'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+ dependencies:
+ '@vue/compiler-dom': 3.4.21
+ '@vue/compiler-sfc': 3.4.21
+ '@vue/runtime-dom': 3.4.21
+ '@vue/server-renderer': 3.4.21([email protected])
+ '@vue/shared': 3.4.21
+ typescript: 5.3.3
+ dev: false
+
resolution: {integrity: sha512-tOhfEwEzFLJzf6d1ZPkYfGj+FWhIpBux9ppoP3rlclw3Z0BZv3N7b7030Z1kYth+6rDuAsXUFr+d0VE6Ed1ikw==}
dev: false
@@ -17525,6 +17846,14 @@ packages:
engines: {node: '>=12.20'}
dev: true
+ resolution: {integrity: sha512-2Ed5dJ+n/O3cU383xSY28cuVi0BCQhF8nYqWU5paEpl7fVdqdAmiLdqLyfblbNdfOFwFfi/mqU4O1pwc60iBhQ==}
+ peerDependencies:
+ zod: ^3.22.4
+ dependencies:
+ zod: 3.22.4
+ dev: false
+
resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==}
dev: false
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index ad62813299..eaee407643 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -41,6 +41,8 @@ import { outputIsStale } from "@/core/cells/cell";
import { RuntimeState } from "@/core/kernel/RuntimeState";
import { isOutputEmpty } from "@/core/cells/outputs";
import { useHotkeysOnElement, useKeydownOnElement } from "@/hooks/useHotkey";
+import { useSetAtom } from "jotai";
+import { aiCompletionCellAtom } from "@/core/ai/state";
/**
* Imperative interface of the cell.
@@ -146,6 +148,7 @@ const CellComponent = (
Logger.debug("Rendering Cell", cellId);
const cellRef = useRef<HTMLDivElement>(null);
const editorView = useRef<EditorView | null>(null);
+ const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
const needsRun = edited || interrupted;
const loading = status === "running" || status === "queued";
@@ -306,6 +309,19 @@ const CellComponent = (
"cell.focusUp": () => moveToNextCell({ cellId, before: true }),
"cell.sendToBottom": () => sendToBottom({ cellId }),
"cell.sendToTop": () => sendToTop({ cellId }),
+ "cell.aiCompletion": () => {
+ let closed = false;
+ setAiCompletionCell((v) => {
+ if (v === cellId) {
+ closed = true;
+ return null;
+ }
+ return cellId;
+ });
+ if (closed) {
+ derefNotNull(editorView).focus();
+ }
+ },
});
useKeydownOnElement(editing ? cellRef.current : null, {
@@ -400,7 +416,6 @@ const CellComponent = (
code={code}
status={status}
serializedEditorState={serializedEditorState}
- mode={mode}
runCell={handleRun}
updateCellCode={updateCellCode}
createNewCell={createNewCell}
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index f866340b21..f7c9e67940 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -18,6 +18,7 @@ import {
TextCursorInputIcon,
EyeIcon,
EyeOffIcon,
+ SparklesIcon,
} from "lucide-react";
import { ActionButton } from "./types";
import { MultiIcon } from "@/components/icons/multi-icon";
@@ -27,6 +28,9 @@ import { saveCellConfig } from "@/core/network/requests";
import { EditorView } from "@codemirror/view";
import { useRunCell } from "../cell/useRunCells";
import { NameCellInput } from "./name-cell-input";
+import { getFeatureFlag } from "@/core/config/feature-flag";
+import { useSetAtom } from "jotai";
+import { aiCompletionCellAtom } from "@/core/ai/state";
export interface CellActionButtonProps
extends Pick<CellData, "name" | "config"> {
@@ -55,6 +59,7 @@ export function useCellActionButtons({
sendToBottom,
} = useCellActions();
const runCell = useRunCell(cellId);
+ const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
const toggleDisabled = async () => {
const newConfig = { disabled: !config.disabled };
@@ -108,6 +113,17 @@ export function useCellActionButtons({
config.disabled === true,
handle: () => runCell(),
},
+ {
+ icon: <SparklesIcon size={13} strokeWidth={1.5} />,
+ label: "AI completion",
+ hidden: !getFeatureFlag("ai"),
+ handle: () => {
+ setAiCompletionCell((current) =>
+ current === cellId ? null : cellId,
+ );
+ },
+ hotkey: "cell.aiCompletion",
+ },
{
icon: <ImageIcon size={13} strokeWidth={1.5} />,
label: "Export output as PNG",
diff --git a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
new file mode 100644
index 0000000000..6f1b137aa6
--- /dev/null
+++ b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
@@ -0,0 +1,183 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { useEffect } from "react";
+import CodeMirrorMerge from "react-codemirror-merge";
+import { useCompletion } from "ai/react";
+import { API } from "@/core/network/api";
+import { EditorView } from "@codemirror/view";
+import { customPythonLanguageSupport } from "@/core/codemirror/language/python";
+import { Button } from "@/components/ui/button";
+import { Loader2Icon, SparklesIcon, XIcon } from "lucide-react";
+
+import "./merge-editor.css";
+import { cn } from "@/utils/cn";
+import { toast } from "@/components/ui/use-toast";
+import { prettyError } from "@/utils/errors";
+import { Label } from "@/components/ui/label";
+import { Tooltip } from "@/components/ui/tooltip";
+import { useAtom } from "jotai";
+import { includeOtherCellsAtom } from "@/core/ai/state";
+import { Checkbox } from "@/components/ui/checkbox";
+import { getCodes } from "@/core/codemirror/copilot/getCodes";
+
+const Original = CodeMirrorMerge.Original;
+const Modified = CodeMirrorMerge.Modified;
+
+interface Props {
+ currentCode: string;
+ onChange: (code: string) => void;
+ declineChange: () => void;
+ acceptChange: (rightHandCode: string) => void;
+ enabled: boolean;
+ /**
+ * Children shown when there is no completion
+ */
+ children: React.ReactNode;
+}
+
+export const AiCompletionEditor: React.FC<Props> = ({
+ onChange,
+ currentCode,
+ declineChange,
+ acceptChange,
+ enabled,
+ children,
+}) => {
+ const [includeOtherCells, setIncludeOtherCells] = useAtom(
+ includeOtherCellsAtom,
+ );
+
+ const {
+ completion,
+ input,
+ stop,
+ isLoading,
+ setCompletion,
+ handleInputChange,
+ handleSubmit,
+ } = useCompletion({
+ api: "/api/ai/completion",
+ headers: API.headers(),
+ body: {
+ includeOtherCode: includeOtherCells ? getCodes(currentCode) : "",
+ code: currentCode,
+ },
+ onError: (error) => {
+ toast({
+ title: "Completion failed",
+ description: prettyError(error),
+ });
+ },
+ });
+
+ const inputRef = React.useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ if (enabled && inputRef.current) {
+ inputRef.current.focus();
+ inputRef.current.select();
+ }
+ }, [enabled]);
+
+ const baseExtensions = [
+ customPythonLanguageSupport(),
+ EditorView.lineWrapping,
+ ];
+
+ return (
+ <div className="flex flex-col w-full rounded-[inherit]">
+ <div
+ className={cn(
+ "flex items-center gap-2 border-b px-3 transition-[height] rounded-[inherit] rounded-b-none duration-300 overflow-hidden",
+ enabled && "h-10 visible",
+ !enabled && "h-0 invisible",
+ )}
+ >
+ <SparklesIcon className="text-[var(--blue-10)]" size={16} />
+ <input
+ className="h-8 outline-none px-2 focus-visible:shadow-none flex-1 rounded-none border-none focus:border-none"
+ value={input}
+ ref={inputRef}
+ onChange={handleInputChange}
+ placeholder="Type for completion"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleSubmit(e as unknown as React.FormEvent<HTMLFormElement>);
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ declineChange();
+ setCompletion("");
+ }
+ }}
+ />
+ {isLoading && (
+ <Button variant="text" size="xs" className="mb-0" onClick={stop}>
+ <Loader2Icon className="animate-spin mr-1" size={14} />
+ Stop
+ </Button>
+ )}
+ {!isLoading && completion && (
+ <Button
+ variant="text"
+ size="xs"
+ className="mb-0"
+ disabled={isLoading}
+ onClick={() => {
+ acceptChange(completion);
+ setCompletion("");
+ }}
+ >
+ <span className="text-[var(--grass-11)] opacity-100">Accept</span>
+ </Button>
+ )}
+ <div className="h-full w-px bg-border mx-2" />
+ <Tooltip content="Include code from other cells">
+ <div className="flex flex-row items-start gap-1">
+ <Checkbox
+ id="include-other-cells"
+ checked={includeOtherCells}
+ onCheckedChange={(checked) =>
+ setIncludeOtherCells(Boolean(checked))
+ }
+ />
+ <Label
+ htmlFor="include-other-cells"
+ className="text-muted-foreground text-xs"
+ >
+ Include all code
+ </Label>
+ </div>
+ </Tooltip>
+ <Button
+ variant="text"
+ size="icon"
+ disabled={isLoading}
+ onClick={() => {
+ stop();
+ declineChange();
+ setCompletion("");
+ }}
+ >
+ <XIcon className="text-[var(--red-10)]" size={16} />
+ </Button>
+ </div>
+ {completion && enabled && (
+ <CodeMirrorMerge className="cm">
+ <Original
+ onChange={onChange}
+ value={currentCode}
+ extensions={baseExtensions}
+ />
+ <Modified
+ value={completion}
+ editable={false}
+ readOnly={true}
+ extensions={baseExtensions}
+ />
+ </CodeMirrorMerge>
+ )}
+ {(!completion || !enabled) && children}
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 45785ce1ff..3bb70f1f13 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -2,17 +2,16 @@
import { historyField } from "@codemirror/commands";
import { EditorState, StateEffect } from "@codemirror/state";
import { EditorView, ViewPlugin } from "@codemirror/view";
-import {
+import React, {
memo,
useCallback,
useEffect,
useRef,
- useLayoutEffect,
useState,
+ useMemo,
} from "react";
import { setupCodeMirror } from "@/core/codemirror/cm";
-import { AppMode } from "@/core/mode";
import useEvent from "react-use-event-hook";
import { CellActions, useCellActions } from "@/core/cells/cells";
import { CellRuntimeState, CellData, CellConfig } from "@/core/cells/types";
@@ -28,6 +27,10 @@ import { LanguageToggle } from "./language-toggle";
import { cn } from "@/utils/cn";
import { saveCellConfig } from "@/core/network/requests";
import { HideCodeButton } from "../../code/readonly-python-code";
+import { AiCompletionEditor } from "./ai-completion-editor";
+import { useAtom } from "jotai";
+import { aiCompletionCellAtom } from "@/core/ai/state";
+import { mergeRefs } from "@/utils/mergeRefs";
export interface CellEditorProps
extends Pick<CellRuntimeState, "status">,
@@ -46,7 +49,6 @@ export interface CellEditorProps
runCell: () => void;
theme: Theme;
showPlaceholder: boolean;
- mode: AppMode;
editorViewRef: React.MutableRefObject<EditorView | null>;
/**
* If true, the cell is allowed to be focus on.
@@ -65,7 +67,6 @@ const CellEditorInternal = ({
code,
status,
serializedEditorState,
- mode,
runCell,
updateCellCode,
createNewCell,
@@ -80,13 +81,11 @@ const CellEditorInternal = ({
hidden,
}: CellEditorProps) => {
const [canUseMarkdown, setCanUseMarkdown] = useState(false);
-
+ const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);
// DOM node where the editorView will be mounted
const editorViewParentRef = useRef<HTMLDivElement>(null);
const loading = status === "running" || status === "queued";
- const editing = mode === "edit";
- const reading = mode === "read";
const { sendToTop, sendToBottom } = useCellActions();
const handleDelete = useEvent(() => {
@@ -131,11 +130,7 @@ const CellEditorInternal = ({
return newConfig.hide_code || false;
});
- useEffect(() => {
- if (reading) {
- return;
- }
-
+ const extensions = useMemo(() => {
const extensions = setupCodeMirror({
cellId,
showPlaceholder,
@@ -155,6 +150,17 @@ const CellEditorInternal = ({
sendToBottom,
moveToNextCell,
toggleHideCode,
+ aiCellCompletion: () => {
+ let closed = false;
+ setAiCompletionCell((v) => {
+ if (v === cellId) {
+ closed = true;
+ return null;
+ }
+ return cellId;
+ });
+ return closed;
+ },
},
completionConfig: userConfig.completion,
keymapConfig: userConfig.keymap,
@@ -175,6 +181,30 @@ const CellEditorInternal = ({
})),
);
+ return extensions;
+ }, [
+ cellId,
+ userConfig.keymap,
+ userConfig.completion,
+ theme,
+ showPlaceholder,
+ createAbove,
+ createBelow,
+ focusUp,
+ focusDown,
+ moveUp,
+ moveDown,
+ moveToNextCell,
+ sendToTop,
+ sendToBottom,
+ toggleHideCode,
+ updateCellCode,
+ handleDelete,
+ runCell,
+ setAiCompletionCell,
+ ]);
+
+ useEffect(() => {
// Should focus will be true if its a newly created editor
let shouldFocus: boolean;
if (serializedEditorState === null) {
@@ -237,43 +267,17 @@ const CellEditorInternal = ({
});
});
}
-
// We don't want to re-run this effect when `allowFocus` or `code` changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
- reading,
+ editorViewRef,
+ extensions,
+ userConfig.completion,
+ clearSerializedEditorState,
cellId,
- userConfig.completion.activate_on_typing,
- userConfig.keymap,
- theme,
- showPlaceholder,
- createAbove,
- createBelow,
- focusUp,
- focusDown,
- moveUp,
- moveDown,
- moveToNextCell,
- updateCellCode,
- handleDelete,
- runCell,
serializedEditorState,
- clearSerializedEditorState,
]);
- useLayoutEffect(() => {
- if (editorViewRef.current === null) {
- return;
- }
- if (
- editing &&
- editorViewParentRef.current !== null &&
- editorViewRef.current !== null
- ) {
- editorViewParentRef.current.replaceChildren(editorViewRef.current.dom);
- }
- }, [editing, editorViewRef]);
-
const showCode = async () => {
if (hidden) {
await saveCellConfig({ configs: { [cellId]: { hide_code: false } } });
@@ -284,22 +288,84 @@ const CellEditorInternal = ({
};
return (
- <>
- {canUseMarkdown && (
- <div className="absolute top-1 right-1">
- <LanguageToggle
- editorView={derefNotNull(editorViewRef)}
- canUseMarkdown={canUseMarkdown}
- />
- </div>
- )}
- {hidden && <HideCodeButton onClick={showCode} />}
- <div
- className={cn("cm", hidden && "opacity-20 h-8 overflow-hidden")}
- ref={editorViewParentRef}
- />
- </>
+ <AiCompletionEditor
+ enabled={aiCompletionCell === cellId}
+ currentCode={code}
+ declineChange={() => {
+ setAiCompletionCell(null);
+ editorViewRef.current?.focus();
+ }}
+ onChange={(newCode) => {
+ editorViewRef.current?.dispatch({
+ changes: {
+ from: 0,
+ to: editorViewRef.current.state.doc.length,
+ insert: newCode,
+ },
+ });
+ }}
+ acceptChange={(newCode) => {
+ editorViewRef.current?.dispatch({
+ changes: {
+ from: 0,
+ to: editorViewRef.current.state.doc.length,
+ insert: newCode,
+ },
+ });
+ editorViewRef.current?.focus();
+ setAiCompletionCell(null);
+ }}
+ >
+ <div className="relative w-full">
+ {canUseMarkdown && (
+ <div className="absolute top-1 right-1">
+ <LanguageToggle
+ editorView={derefNotNull(editorViewRef)}
+ canUseMarkdown={canUseMarkdown}
+ />
+ </div>
+ )}
+ {hidden && <HideCodeButton onClick={showCode} />}
+ <CellCodeMirrorEditor
+ className={cn(hidden && "opacity-20 h-8 overflow-hidden")}
+ editorView={editorViewRef.current}
+ ref={editorViewParentRef}
+ />
+ </div>
+ </AiCompletionEditor>
);
};
+const CellCodeMirrorEditor = React.forwardRef(
+ (
+ props: {
+ className?: string;
+ editorView: EditorView | null;
+ },
+ ref: React.Ref<HTMLDivElement>,
+ ) => {
+ const { className, editorView } = props;
+ const internalRef = useRef<HTMLDivElement>(null);
+
+ // If this gets unmounted/remounted, we need to re-append the editorView
+ useEffect(() => {
+ if (editorView === null) {
+ return;
+ }
+ if (internalRef.current === null) {
+ return;
+ }
+ // Has no children, so we can replaceChildren
+ if (internalRef.current.children.length === 0) {
+ internalRef.current.append(editorView.dom);
+ }
+ }, [editorView, internalRef]);
+
+ return (
+ <div className={cn("cm", className)} ref={mergeRefs(ref, internalRef)} />
+ );
+ },
+);
+CellCodeMirrorEditor.displayName = "CellCodeMirrorEditor";
+
export const CellEditor = memo(CellEditorInternal);
diff --git a/frontend/src/components/editor/cell/code/merge-editor.css b/frontend/src/components/editor/cell/code/merge-editor.css
new file mode 100644
index 0000000000..00aaf72f32
--- /dev/null
+++ b/frontend/src/components/editor/cell/code/merge-editor.css
@@ -0,0 +1,9 @@
+.Cell .cm-mergeViewEditor .cm-editor {
+ padding: 0;
+}
+
+.cm-merge-theme:last-child {
+ overflow: hidden;
+ border-bottom-left-radius: 10px;
+ border-bottom-right-radius: 10px;
+}
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx
index b53762786a..5b0b7749ca 100644
--- a/frontend/src/components/ui/button.tsx
+++ b/frontend/src/components/ui/button.tsx
@@ -56,7 +56,7 @@ const buttonVariants = cva(
"border border-input shadow-smSolid",
activeCommon,
),
- text: cn("opacity-60 hover:opacity-100", "active:opacity-100"),
+ text: cn("opacity-80 hover:opacity-100", "active:opacity-100"),
ghost: cn(
"hover:bg-accent hover:text-accent-foreground hover:shadow-smSolid border border-transparent",
activeCommon,
@@ -69,7 +69,7 @@ const buttonVariants = cva(
xs: "h-7 px-2 rounded-md text-xs",
sm: "h-9 px-3 rounded-md",
lg: "h-11 px-8 rounded-md",
- icon: "h-6 w-6",
+ icon: "h-6 w-6 mb-0",
},
disabled: {
true: "opacity-50 pointer-events-none",
diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.ts
new file mode 100644
index 0000000000..485d34726b
--- /dev/null
+++ b/frontend/src/core/ai/state.ts
@@ -0,0 +1,6 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { atom } from "jotai";
+import { CellId } from "../cells/ids";
+
+export const aiCompletionCellAtom = atom<CellId | null>(null);
+export const includeOtherCellsAtom = atom<boolean>(false);
diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.ts
index f5d8725146..3e30aa7204 100644
--- a/frontend/src/core/codemirror/__tests__/setup.test.ts
+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts
@@ -23,6 +23,7 @@ function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {
showPlaceholder: false,
cellMovementCallbacks: {
onRun: namedFunction("onRun"),
+ aiCellCompletion: namedFunction("aiCellCompletion"),
deleteCell: namedFunction("deleteCell"),
createAbove: namedFunction("createAbove"),
createBelow: namedFunction("createBelow"),
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index faaeb3e183..59f152bc9f 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -21,6 +21,7 @@ export interface MovementCallbacks
focusUp: () => void;
focusDown: () => void;
toggleHideCode: () => boolean;
+ aiCellCompletion: () => boolean;
}
/**
@@ -43,6 +44,7 @@ export function cellMovementBundle(
sendToBottom,
moveToNextCell,
toggleHideCode,
+ aiCellCompletion,
} = callbacks;
const hotkeys: KeyBinding[] = [
@@ -222,6 +224,18 @@ export function cellMovementBundle(
return true;
},
},
+ {
+ key: HOTKEYS.getHotkey("cell.aiCompletion").key,
+ preventDefault: true,
+ stopPropagation: true,
+ run: (ev) => {
+ const closed = aiCellCompletion();
+ if (closed) {
+ ev.contentDOM.focus();
+ }
+ return true;
+ },
+ },
];
// Highest priority so that we can override the default keymap
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index c2f2cf6a9f..ed34b41f8a 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -63,7 +63,9 @@ export const UserConfigSchema = z
cell_output: "above",
}),
experimental: z
- .object({})
+ .object({
+ ai: z.boolean().optional(),
+ })
// Pass through so that we don't remove any extra keys that the user has added.
.passthrough()
.default({}),
diff --git a/frontend/src/core/config/feature-flag.ts b/frontend/src/core/config/feature-flag.ts
index 9dd99122e2..95a59bbda0 100644
--- a/frontend/src/core/config/feature-flag.ts
+++ b/frontend/src/core/config/feature-flag.ts
@@ -5,9 +5,12 @@ import { getUserConfig } from "./config";
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ExperimentalFeatures {
// None yet
+ ai: boolean;
}
-const defaultValues: ExperimentalFeatures = {};
+const defaultValues: ExperimentalFeatures = {
+ ai: process.env.NODE_ENV === "development",
+};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
feature: T,
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index 3d42899223..0fa52c54cd 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -168,6 +168,11 @@ const DEFAULT_HOT_KEY = {
group: "Editing",
key: "Mod-h",
},
+ "cell.aiCompletion": {
+ name: "AI completion",
+ group: "Editing",
+ key: "Mod-Shift-e",
+ },
// Global Actions
"global.hideCode": {
diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.ts
index f9f8b632f4..1354c4237d 100644
--- a/frontend/src/core/network/api.ts
+++ b/frontend/src/core/network/api.ts
@@ -26,9 +26,7 @@ export const API = {
method: "POST",
headers: {
"Content-Type": "application/json",
- "X-Xsrftoken": getXsrfCookie(),
- "Marimo-Session-Id": getSessionId(),
- "Marimo-Server-Token": getServerTokenOnce(),
+ ...API.headers(),
},
body: JSON.stringify(body),
})
@@ -49,4 +47,11 @@ export const API = {
throw error;
});
},
+ headers() {
+ return {
+ "X-Xsrftoken": getXsrfCookie(),
+ "Marimo-Session-Id": getSessionId(),
+ "Marimo-Server-Token": getServerTokenOnce(),
+ };
+ },
};
diff --git a/frontend/src/utils/errors.ts b/frontend/src/utils/errors.ts
index c199fd2c04..575fbe184e 100644
--- a/frontend/src/utils/errors.ts
+++ b/frontend/src/utils/errors.ts
@@ -1,11 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
-export function prettyError(error: unknown) {
- if (typeof error === "string") {
- return error;
+export function prettyError(error: unknown): string {
+ if (!error) {
+ return "Unknown error";
}
if (error instanceof Error) {
- return error.message;
+ return maybeExtractDetails(error.message);
}
try {
return JSON.stringify(error);
@@ -13,3 +13,22 @@ export function prettyError(error: unknown) {
return String(error);
}
}
+
+function maybeExtractDetails(message: string): string {
+ try {
+ const parsed = JSON.parse(message);
+ if (!parsed) {
+ return message;
+ }
+ if (
+ typeof parsed === "object" &&
+ "detail" in parsed &&
+ typeof parsed.detail === "string"
+ ) {
+ return parsed.detail;
+ }
+ } catch {
+ // noop
+ }
+ return message;
+}
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 76e6a7f85b..b6585225bb 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -82,6 +82,11 @@ class DependencyManager:
+ "You can install it with 'pip install plotly'"
) from None
+ @staticmethod
+ def has_openai() -> bool:
+ """Return True if openai is installed."""
+ return importlib.util.find_spec("openai") is not None
+
@staticmethod
def has_pandas() -> bool:
"""Return True if pandas is installed."""
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
new file mode 100644
index 0000000000..894a4c1c4b
--- /dev/null
+++ b/marimo/_server/api/endpoints/ai.py
@@ -0,0 +1,99 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+from typing import Generator
+
+from starlette.authentication import requires
+from starlette.exceptions import HTTPException
+from starlette.requests import Request
+from starlette.responses import StreamingResponse
+
+from marimo import _loggers
+from marimo._server.api.deps import AppState
+from marimo._server.api.status import HTTPStatus
+from marimo._server.api.utils import parse_request
+from marimo._server.models.completion import AiCompletionRequest
+from marimo._server.router import APIRouter
+
+LOGGER = _loggers.marimo_logger()
+
+# Router for file ai
+router = APIRouter()
+
+
[email protected]("/completion")
+@requires("edit")
+async def ai_completion(
+ *,
+ request: Request,
+) -> StreamingResponse:
+ try:
+ from openai import OpenAI # type: ignore[import-not-found]
+ except ImportError:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST, detail="OpenAI not installed"
+ ) from None
+
+ app_state = AppState(request)
+ app_state.require_current_session()
+ body = await parse_request(request, cls=AiCompletionRequest)
+ key = os.environ.get("OPENAI_API_KEY")
+
+ if not key:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="OpenAI API key not found in environment",
+ )
+
+ client = OpenAI(api_key=key)
+
+ system_prompt = (
+ "You are a helpful assistant that can answer questions "
+ "about python code. You can only output python code. "
+ "Do not describe the code, just write the code."
+ "Do not output markdown or backticks."
+ )
+
+ prompt = body.prompt
+ if body.include_other_code:
+ prompt = (
+ f"{prompt}\n\nCode from other cells:\n{body.include_other_code}"
+ )
+ if body.code.strip():
+ prompt = f"{prompt}\n\nCurrent code:\n{body.code}"
+
+ response = client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {
+ "role": "system",
+ "content": system_prompt,
+ },
+ {
+ "role": "user",
+ "content": prompt,
+ },
+ ],
+ temperature=0,
+ stream=True,
+ )
+
+ # If it starts or ends with markdown, remove it
+ def stream_response() -> Generator[str, None, None]:
+ for chunk in response:
+ content = chunk.choices[0].delta.content
+ if content:
+ if content.startswith("```python"):
+ yield content[9:]
+ if content.startswith("```"):
+ yield content[4:]
+ elif content.endswith("```"):
+ yield content[:-3]
+ else:
+ yield content or ""
+
+ return StreamingResponse(
+ content=stream_response(),
+ media_type="application/json",
+ )
diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.py
index a3fd4e4370..d65274308a 100644
--- a/marimo/_server/api/router.py
+++ b/marimo/_server/api/router.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
+from marimo._server.api.endpoints.ai import router as ai_router
from marimo._server.api.endpoints.assets import router as assets_router
from marimo._server.api.endpoints.config import router as config_router
from marimo._server.api.endpoints.editing import router as editing_router
@@ -22,6 +23,7 @@ app_router.include_router(files_router, prefix="/api/kernel", name="files")
app_router.include_router(
file_explorer, prefix="/api/files", name="file_explorer"
)
+app_router.include_router(ai_router, prefix="/api/ai", name="ai")
app_router.include_router(health_router)
app_router.include_router(ws_router)
app_router.include_router(assets_router)
diff --git a/marimo/_server/models/completion.py b/marimo/_server/models/completion.py
new file mode 100644
index 0000000000..5c193185ce
--- /dev/null
+++ b/marimo/_server/models/completion.py
@@ -0,0 +1,8 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class AiCompletionRequest:
+ prompt: str
+ include_other_code: str
+ code: str
diff --git a/marimo/_server/router.py b/marimo/_server/router.py
index fe0b6b0ac0..d425125618 100644
--- a/marimo/_server/router.py
+++ b/marimo/_server/router.py
@@ -7,7 +7,12 @@ from dataclasses import dataclass
from typing import Any, Callable, Optional, TypeVar
from starlette.requests import Request
-from starlette.responses import FileResponse, JSONResponse, Response
+from starlette.responses import (
+ FileResponse,
+ JSONResponse,
+ Response,
+ StreamingResponse,
+)
from starlette.routing import Mount, Router
from marimo import _loggers
@@ -43,6 +48,8 @@ class APIRouter(Router):
response = await func(request=request)
if isinstance(response, FileResponse):
return response
+ if isinstance(response, StreamingResponse):
+ return response
if dataclasses.is_dataclass(response):
return JSONResponse(
diff --git a/pyproject.toml b/pyproject.toml
index 3aa5e0cc1c..9a40c6608c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -112,6 +112,8 @@ testoptional = [
# polars 0.19.13 requires building maturn from source, but we don't
# have the rust toolchain installed on CI
"polars==0.19.12",
+ "anywidget~=0.9.3",
+ "openai~=1.12.0",
]
[project.urls]
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
new file mode 100644
index 0000000000..145b087dec
--- /dev/null
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -0,0 +1,150 @@
+# Copyright 2024 Marimo. All rights reserved.
+import os
+from contextlib import contextmanager
+from dataclasses import dataclass
+from typing import Any, List
+from unittest.mock import MagicMock, patch
+
+import pytest
+from starlette.testclient import TestClient
+
+from marimo._dependencies.dependencies import DependencyManager
+from tests._server.conftest import get_session_manager
+from tests._server.mocks import with_session
+
+SESSION_ID = "session-123"
+HEADERS = {
+ "Marimo-Session-Id": SESSION_ID,
+ "Marimo-Server-Token": "fake-token",
+}
+
+HAS_DEPS = DependencyManager.has_openai()
+
+
+@dataclass
+class Delta:
+ content: str
+
+
+@dataclass
+class Choice:
+ delta: Delta
+
+
+@dataclass
+class FakeChoices:
+ choices: List[Choice]
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+class TestAiEndpoints:
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("openai.OpenAI")
+ def test_completion_without_token(
+ client: TestClient, openai_mock: Any
+ ) -> None:
+ del openai_mock
+ filename = get_session_manager(client).filename
+ assert filename
+
+ response = client.post(
+ "/api/ai/completion",
+ headers=HEADERS,
+ json={
+ "prompt": "Help me create a dataframe",
+ "include_other_code": "",
+ "code": "",
+ },
+ )
+ assert response.status_code == 400, response.text
+ assert response.json() == {
+ "detail": "OpenAI API key not found in environment"
+ }
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @pytest.mark.skipif(
+ not HAS_DEPS, reason="optional dependencies not installed"
+ )
+ @patch("openai.OpenAI")
+ def test_completion_without_code(
+ client: TestClient, openai_mock: Any
+ ) -> None:
+ filename = get_session_manager(client).filename
+ assert filename
+
+ oaiclient = MagicMock()
+ openai_mock.return_value = oaiclient
+
+ oaiclient.chat.completions.create.return_value = [
+ FakeChoices(
+ choices=[Choice(delta=Delta(content="import pandas as pd"))]
+ )
+ ]
+
+ with fake_openai_env():
+ response = client.post(
+ "/api/ai/completion",
+ headers=HEADERS,
+ json={
+ "prompt": "Help me create a dataframe",
+ "include_other_code": "",
+ "code": "",
+ },
+ )
+ assert response.status_code == 200, "nope"
+ # Assert the prompt it was called with
+ prompt = oaiclient.chat.completions.create.call_args.kwargs[
+ "messages"
+ ][1]["content"]
+ assert prompt == ("Help me create a dataframe")
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @pytest.mark.skipif(
+ not HAS_DEPS, reason="optional dependencies not installed"
+ )
+ @patch("openai.OpenAI")
+ def test_completion_with_code(
+ client: TestClient, openai_mock: Any
+ ) -> None:
+ filename = get_session_manager(client).filename
+ assert filename
+
+ oaiclient = MagicMock()
+ openai_mock.return_value = oaiclient
+
+ oaiclient.chat.completions.create.return_value = [
+ FakeChoices(
+ choices=[Choice(delta=Delta(content="import pandas as pd"))]
+ )
+ ]
+
+ with fake_openai_env():
+ response = client.post(
+ "/api/ai/completion",
+ headers=HEADERS,
+ json={
+ "prompt": "Help me create a dataframe",
+ "code": "import pandas as pd",
+ "include_other_code": "",
+ },
+ )
+ assert response.status_code == 200, response.text
+ # Assert the prompt it was called with
+ prompt = oaiclient.chat.completions.create.call_args.kwargs[
+ "messages"
+ ][1]["content"]
+ assert prompt == (
+ "Help me create a dataframe\n\nCurrent code:\nimport pandas as pd" # noqa: E501
+ )
+
+
+@contextmanager
+def fake_openai_env():
+ try:
+ os.environ["OPENAI_API_KEY"] = "fake-key"
+ yield
+ finally:
+ del os.environ["OPENAI_API_KEY"]