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.

improvement: support completions in wasm (#842)

Myles Scolnick31a0bbdb8928
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 6f9bb8072a..d95723fb3f 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -155,7 +155,6 @@ export const UserConfigForm: React.FC = () => {
/>
<FormField
control={form.control}
- disabled={isWasm}
name="completion.activate_on_typing"
render={({ field }) => (
<div className="flex flex-col space-y-1">
diff --git a/frontend/src/core/pyodide/worker/bootstrap.ts b/frontend/src/core/pyodide/worker/bootstrap.ts
index b9204ddd9e..5480a73a56 100644
--- a/frontend/src/core/pyodide/worker/bootstrap.ts
+++ b/frontend/src/core/pyodide/worker/bootstrap.ts
@@ -20,7 +20,7 @@ export async function bootstrap() {
const pyodide = await loadPyodide({
// Perf: These get loaded while pyodide is being bootstrapped
// The packages can be found here: https://pyodide.org/en/stable/usage/packages-in-pyodide.html
- packages: ["micropip", "docutils", "Pygments"],
+ packages: ["micropip", "docutils", "Pygments", "jedi"],
// Without this, this fails in Firefox with
// `Could not extract indexURL path from pyodide module`
// This fixes for Firefox and does not break Chrome/others
@@ -45,10 +45,6 @@ export async function bootstrap() {
"multiprocessing.shared_memory": None,
"multiprocessing.spawn": None,
})
- micropip.add_mock_package("jedi", "*", modules={
- "jedi": None,
- "jedi.api": None,
- })
await micropip.install(
[
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index c779c4465a..5cd2f06da9 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -305,7 +305,6 @@ def launch_pyodide_kernel(
app_metadata: AppMetadata,
) -> RestartableTask:
LOGGER.debug("Launching kernel")
- del completion_queue
# Create communication channels
stream = PyodideStream(on_message, input_queue)
@@ -333,12 +332,24 @@ def launch_pyodide_kernel(
register_formatters()
- async def listen() -> None:
+ async def listen_messages() -> None:
while True:
request = await control_queue.get()
LOGGER.debug("received request %s", request)
await kernel.handle_message(request)
+ async def listen_completion() -> None:
+ while True:
+ request = await completion_queue.get()
+ LOGGER.debug("received completion request %s", request)
+ # 5 is arbitrary, but is a good limit:
+ # too high will cause long load times
+ # too low can be not as useful
+ kernel.code_completion(request, docstrings_limit=5)
+
+ async def listen() -> None:
+ await asyncio.gather(listen_messages(), listen_completion())
+
return RestartableTask(listen)
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index 2cb51df290..da9c472b4b 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -200,7 +200,7 @@ def _drain_queue(
return request
-def complete(
+def completion_worker(
completion_queue: QueueType[CompletionRequest],
graph: dataflow.DirectedGraph,
stream: Stream,
@@ -209,80 +209,94 @@ def complete(
while True:
request = _drain_queue(completion_queue)
- if not request.document.strip():
- _write_no_completions(stream, request.id)
- continue
-
- with graph.lock:
- codes = [
- graph.cells[cid].code
- for cid in dataflow.topological_sort(
- graph,
- set(graph.cells.keys()) - set([request.cell_id]),
- )
- ]
+ complete(request, graph, stream)
- try:
- script = jedi.Script("\n".join(codes + [request.document]))
- completions = script.complete()
- prefix_length = (
- completions[0].get_completion_prefix_length()
- if completions
- else 0
+
+def complete(
+ request: CompletionRequest,
+ graph: dataflow.DirectedGraph,
+ stream: Stream,
+ docstrings_limit: int = 1000,
+) -> None:
+ if not request.document.strip():
+ _write_no_completions(stream, request.id)
+ return
+
+ with graph.lock:
+ codes = [
+ graph.cells[cid].code
+ for cid in dataflow.topological_sort(
+ graph,
+ set(graph.cells.keys()) - set([request.cell_id]),
)
+ ]
- # Only complete an empty symbol (prefix length == 0) when we're
- # using dot notation; this prevents autocomplete from kicking in at
- # awkward times, such as when parentheses are first opened
- if (
- prefix_length == 0
- and len(request.document) >= 1
- and request.document[-1] != "."
- ):
- # Don't complete ...
- completions = []
-
- # Get docstring in function context. A bit of a hack, since
- # this isn't actually a completion, just a tooltip.
- #
- # If no completions, we might be getting a signature ...
- # for example, if the document is "mo.ui.slider(start=1,
- signatures = script.get_signatures()
- if signatures:
- _write_completion_result(
- stream=stream,
- completion_id=request.id,
- prefix_length=0,
- options=[
- CompletionOption(
- name=signatures[0].name,
- type="tooltip",
- completion_info=_get_completion_info(
- signatures[0]
- ),
- )
- ],
- )
- continue
-
- if not completions:
- # If there are still no completions, then bail.
- _write_no_completions(stream, request.id)
- continue
-
- prefix = request.document[-prefix_length:]
+ try:
+ script = jedi.Script("\n".join(codes + [request.document]))
+ completions = script.complete()
+ prefix_length = (
+ completions[0].get_completion_prefix_length() if completions else 0
+ )
+
+ # Only complete an empty symbol (prefix length == 0) when we're
+ # using dot notation; this prevents autocomplete from kicking in at
+ # awkward times, such as when parentheses are first opened
+ if (
+ prefix_length == 0
+ and len(request.document) >= 1
+ and request.document[-1] != "."
+ ):
+ # Don't complete ...
+ completions = []
+
+ # Get docstring in function context. A bit of a hack, since
+ # this isn't actually a completion, just a tooltip.
+ #
+ # If no completions, we might be getting a signature ...
+ # for example, if the document is "mo.ui.slider(start=1,
+ signatures = script.get_signatures()
+ if signatures:
+ _write_completion_result(
+ stream=stream,
+ completion_id=request.id,
+ prefix_length=0,
+ options=[
+ CompletionOption(
+ name=signatures[0].name,
+ type="tooltip",
+ completion_info=_get_completion_info(
+ signatures[0]
+ ),
+ )
+ ],
+ )
+ return
+
+ if not completions:
+ # If there are still no completions, then bail.
+ _write_no_completions(stream, request.id)
+ return
+
+ prefix = request.document[-prefix_length:]
+ if len(completions) < docstrings_limit:
options = [
_get_completion_options(c, script)
for c in completions
if _should_include_name(c.name, prefix)
]
- _write_completion_result(
- stream=stream,
- completion_id=request.id,
- prefix_length=prefix_length,
- options=options,
- )
- except Exception as e:
- # jedi failed to provide completion
- LOGGER.debug("Completion with jedi failed: ", str(e))
- _write_no_completions(stream, request.id)
+ else:
+ options = [
+ CompletionOption(name=c.name, type=c.type, completion_info="")
+ for c in completions
+ if _should_include_name(c.name, prefix)
+ ]
+ _write_completion_result(
+ stream=stream,
+ completion_id=request.id,
+ prefix_length=prefix_length,
+ options=options,
+ )
+ except Exception as e:
+ # jedi failed to provide completion
+ LOGGER.debug("Completion with jedi failed: ", str(e))
+ _write_no_completions(stream, request.id)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 14e2e1cdf4..caf30f946f 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -61,7 +61,7 @@ from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import MarimoConvertValueException
from marimo._runtime import cell_runner, dataflow, marimo_pdb, patches
-from marimo._runtime.complete import complete
+from marimo._runtime.complete import complete, completion_worker
from marimo._runtime.context import (
ContextNotInitializedError,
get_context,
@@ -235,11 +235,16 @@ class Kernel:
) -> None:
"""Must be called after context is initialized"""
threading.Thread(
- target=complete,
+ target=completion_worker,
args=(completion_queue, self.graph, get_context().stream),
daemon=True,
).start()
+ def code_completion(
+ self, request: CompletionRequest, docstrings_limit: int
+ ) -> None:
+ complete(request, self.graph, get_context().stream, docstrings_limit)
+
@contextlib.contextmanager
def _install_execution_context(
self, cell_id: CellId_t, setting_element_value: bool = False