Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): Python completions, hovers and go-to-definition in the editor
rubenluetke10-beep3060c9862369
diff --git a/docs/code-editor.md b/docs/code-editor.mdindex f291241aaa..9581930cfa 100644--- a/docs/code-editor.md+++ b/docs/code-editor.md@@ -25,7 +25,9 @@ Every file type opens:- Text and code open in the editor (Monaco, bundled locally and loaded onlywhen the first file opens), with completions, hovers and syntax errors for- JSON, CSS/SCSS/Less, HTML and TypeScript/JavaScript.+ JSON, CSS/SCSS/Less, HTML and TypeScript/JavaScript, and completions,+ hovers and go-to-definition for Python (the workspace is the import root,+ so its own packages resolve). **Ctrl+Space** asks for suggestions.- Text in other encodings opens too: UTF-16 with a byte-order mark, andlegacy code pages (Windows-1252, Cyrillic, Greek, …) detected and savedback in the same encoding.@@ -83,16 +85,18 @@ own app.check on a real Mac) — Linux needs no routing- [x] TypeScript/CSS/HTML language services and git change markers in thegutter-- [ ] Python language server (needs a bundled server such as Pyright; not- started)+- [x] Python completions, hovers and go-to-definition (F12 / Ctrl+click,+ also into other workspace files), from jedi's static analysis## Where it lives- Backend: `jarvis/agentic_ide/file_editing.py` (read, save, create, copy,move, delete, encodings), `file_search.py` (search and replace),- `editor_backups.py` (open tabs and unsaved text), and the+ `editor_backups.py` (open tabs and unsaved text), `python_intel.py`+ (Python completions, hovers, definitions), and the`/workspaces/{id}/` routes `text-file`, `text-file/version`, `head-text`,- `file-list`, `search`, `search/replace`, `editor-state`, `entries`,+ `file-list`, `search`, `search/replace`, `python/{action}`,+ `editor-state`, `entries`,`entries/copy`, `entries/move` and `entries/delete` in`jarvis/ui/web/agentic_ide_routes.py`.- Frontend: `components/agentic/editor/`, `store/codeEditor.ts`, the Folderdiff --git a/jarvis/agentic_ide/python_intel.py b/jarvis/agentic_ide/python_intel.pynew file mode 100644index 0000000000..2b90bae2c7--- /dev/null+++ b/jarvis/agentic_ide/python_intel.py@@ -0,0 +1,146 @@+"""Python completions, hovers and go-to-definition for the code editor.++Jedi reads the editor's live buffer together with the workspace on disk, so a+completion after ``from jarvis.core import `` lists that package's names and a+definition can lead into another workspace file. It analyses statically —+nothing in the workspace is imported or run — and its helper process for+compiled modules starts without a console window on Windows.++Jedi is imported lazily: nothing here touches the boot path (AP-26), and a+machine without it answers with empty results instead of an error.+"""++from __future__ import annotations++import os+import threading+from pathlib import Path+from typing import Any++from loguru import logger++from .file_editing import EditError, _resolve++__all__ = ["complete", "definitions", "hover"]++#: Completions returned for one request; Monaco filters further as you type.+MAX_COMPLETIONS = 300+_HOVER_DOC_CHARS = 4000++_projects: dict[str, Any] = {}+_lock = threading.Lock()+++def _jedi() -> Any | None:+ try:+ import jedi # noqa: PLC0415 — lazy, see the module docstring+ except ImportError:+ logger.info("Python language support unavailable: jedi is not installed")+ return None+ return jedi+++def _script(root: str | os.PathLike[str], path: str, text: str) -> tuple[Any, Path] | None:+ jedi = _jedi()+ if jedi is None:+ return None+ _, target = _resolve(root, path)+ base = Path(os.path.realpath(os.fspath(root)))+ key = str(base)+ with _lock:+ project = _projects.get(key)+ if project is None:+ # The workspace is the import root, so its own packages resolve.+ project = jedi.Project(path=str(base), added_sys_path=[str(base)])+ _projects[key] = project+ return jedi.Script(code=text, path=str(target), project=project), base+++def _position(text: str, line: int, column: int) -> tuple[int, int]:+ """Monaco's 1-based line/column as jedi's 1-based line, 0-based column, clamped."""+ lines = text.splitlines() or [""]+ line = max(1, min(line, len(lines)))+ current = lines[line - 1] if line - 1 < len(lines) else ""+ return line, max(0, min(column - 1, len(current)))+++def complete(+ root: str | os.PathLike[str], path: str, text: str, line: int, column: int+) -> list[dict[str, str]]:+ """Names that can follow the cursor."""+ built = _script(root, path, text)+ if built is None:+ return []+ script, _ = built+ try:+ found = script.complete(*_position(text, line, column))+ except Exception as exc: # noqa: BLE001 — a completion must never fail the editor+ logger.debug("Python completion failed in {}: {}", path, exc)+ return []+ return [+ {"name": item.name, "type": item.type, "detail": item.description or ""}+ for item in found[:MAX_COMPLETIONS]+ ]+++def hover(root: str | os.PathLike[str], path: str, text: str, line: int, column: int) -> str | None:+ """Markdown for the name under the cursor: its signature and docstring."""+ built = _script(root, path, text)+ if built is None:+ return None+ script, _ = built+ try:+ names = script.help(*_position(text, line, column))+ except Exception as exc: # noqa: BLE001+ logger.debug("Python hover failed in {}: {}", path, exc)+ return None+ for name in names:+ signature = name.description or name.name+ try:+ # "shout(text: str) -> str" says more than "def shout".+ signatures = [sig.to_string() for sig in name.get_signatures()]+ except Exception: # noqa: BLE001 — not every name has signatures+ signatures = []+ if signatures:+ prefix = "class " if name.type == "class" else "def " if name.type == "function" else ""+ signature = "\n".join(prefix + sig for sig in signatures)+ try:+ doc = name.docstring(raw=True) or ""+ except Exception: # noqa: BLE001 — some compiled names have no source+ doc = ""+ body = f"```python\n{signature}\n```"+ if doc.strip():+ body += "\n\n" + doc.strip()[:_HOVER_DOC_CHARS]+ return body+ return None+++def definitions(+ root: str | os.PathLike[str], path: str, text: str, line: int, column: int+) -> list[dict[str, object]]:+ """Where the name under the cursor is defined, inside this workspace only."""+ built = _script(root, path, text)+ if built is None:+ return []+ script, base = built+ try:+ found = script.goto(*_position(text, line, column), follow_imports=True)+ except Exception as exc: # noqa: BLE001+ logger.debug("Python go-to-definition failed in {}: {}", path, exc)+ return []+ results: list[dict[str, object]] = []+ for name in found:+ module = name.module_path+ if module is None or name.line is None:+ continue+ real = Path(os.path.realpath(module))+ try:+ relative = real.relative_to(base).as_posix()+ except ValueError:+ continue # a library outside the workspace: nothing to open here+ try:+ _resolve(root, relative)+ except EditError:+ continue+ results.append({"path": relative, "line": name.line, "column": (name.column or 0) + 1})+ return resultsdiff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex bc138d6b94..c2978cccc5 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -99,6 +99,7 @@ from jarvis.agentic_ide import (screen_feed,workspace_catalog,)+from jarvis.agentic_ide import python_intel as python_intel_modulefrom jarvis.agentic_ide.activity import has_work_behind_itfrom jarvis.agentic_ide.agent_sessions import has_conversationfrom jarvis.agentic_ide.device import device_name@@ -1047,6 +1048,15 @@ class CopyWorkspaceEntryRequest(BaseModel):)+class PythonIntelRequest(BaseModel):+ """The editor's buffer and cursor, for Python completions and lookups."""++ path: str = Field(min_length=1, max_length=4096)+ text: str = Field(max_length=5 * 1024 * 1024)+ line: int = Field(ge=1, description="1-based line of the cursor.")+ column: int = Field(ge=1, description="1-based column of the cursor.")++class DeleteWorkspaceEntryRequest(BaseModel):"""Delete one file or folder; it goes to the system trash unless permanent."""@@ -2235,6 +2245,29 @@ async def replace_in_workspace_files(return {"workspace_id": workspace_id, **answer}+ "/workspaces/{workspace_id}/python/{action}",+ summary="Python completions, hover text or definitions for the code editor",+)+async def python_intel(+ workspace_id: str,+ action: Literal["complete", "hover", "definition"],+ req: PythonIntelRequest,+) -> dict[str, object]:+ """Static analysis of the live buffer with the workspace as import root."""+ folder = _workspace_folder(workspace_id)+ handler = {+ "complete": python_intel_module.complete,+ "hover": python_intel_module.hover,+ "definition": python_intel_module.definitions,+ }[action]+ try:+ result = await asyncio.to_thread(handler, folder, req.path, req.text, req.line, req.column)+ except file_editing.EditError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"workspace_id": workspace_id, "result": result}++@router.get("/workspaces/{workspace_id}/editor-state",summary="The code editor's open tabs and unsaved text to restore",diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex 743d3ad24b..8db5b83d2a 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -138,6 +138,11 @@ export default function App() {const onKeyDown = (event: KeyboardEvent) => {if (event.repeat || !eventMatchesChord(event, switcherCombo)) return;if (document.querySelector('[data-keybind-recording="true"]')) return;+ // Inside the code editor Ctrl+Space asks for suggestions, as in every+ // code editor; any other switcher chord still works there.+ const inEditor = event.target instanceof Element && event.target.closest(".monaco-editor");+ const ctrlSpace = event.code === "Space" && event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey;+ if (inEditor && ctrlSpace) return;event.preventDefault();event.stopPropagation();useQuickSwitcher.getState().toggle();diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.tsindex ccaea40805..8768c527fb 100644--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts@@ -262,3 +262,35 @@ export function replaceInFiles(}),);}++export interface PythonPosition {+ path: string;+ text: string;+ /** 1-based, as Monaco counts. */+ line: number;+ column: number;+}++export interface PythonCompletion {+ name: string;+ /** Jedi's kind: module, class, function, instance, param, keyword, property, statement, path. */+ type: string;+ detail: string;+}++export interface PythonLocation {+ path: string;+ line: number;+ column: number;+}++/** Python completions, hover text or definitions for the live buffer. */+export async function pythonIntel<T>(+ workspaceId: string,+ action: "complete" | "hover" | "definition",+ position: PythonPosition,+ signal?: AbortSignal,+): Promise<T> {+ const answer = await send<{ result: T }>(`${base(workspaceId)}/python/${action}`, { ...json("POST", position), signal });+ return answer.result;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.tsindex 671d273b37..16edd0b2e1 100644--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts@@ -119,6 +119,18 @@ function createEntry(return entry;}+/** The workspace file behind an editor model or URI, for language features. */+export function fileOfUri(uri: Monaco.Uri): { workspaceId: string; path: string } | null {+ if (uri.scheme !== "file") return null;+ const match = /^\/([^/]+)\/(.+)$/.exec(uri.path);+ if (!match) return null;+ return { workspaceId: decodeURIComponent(match[1]), path: match[2] };+}++export function fileUri(workspaceId: string, path: string): Monaco.Uri {+ return uriFor(workspaceId, path);+}+export function modelOf(fileKey: string): Monaco.editor.ITextModel | null {return entries.get(fileKey)?.model ?? null;}diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.tsindex 91e18fa8b0..26d8f196c9 100644--- a/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts@@ -26,6 +26,7 @@ import HtmlWorker from "monaco-editor/languages/features/html/html.worker?workerimport TsWorker from "monaco-editor/languages/features/typescript/ts.worker?worker";import { setMonaco } from "./editorModels";+import { registerPythonLanguage } from "./pythonLanguage";import "./editorGutter.css";declare global {@@ -62,6 +63,7 @@ for (const defaults of [typescriptDefaults, javascriptDefaults]) {}setMonaco(monaco);+registerPythonLanguage(monaco);let probe: CanvasRenderingContext2D | null | undefined;diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/pythonLanguage.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/pythonLanguage.tsnew file mode 100644index 0000000000..d52a4269ec--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/pythonLanguage.ts@@ -0,0 +1,117 @@+import type * as Monaco from "monaco-editor/editor/editor.api";++import { useCodeEditorStore } from "@/store/codeEditor";+import { pythonIntel, type PythonCompletion, type PythonLocation, type PythonPosition } from "./editorApi";+import { fileOfUri, fileUri } from "./editorModels";++/**+ * Python completions, hovers and go-to-definition in the code editor, answered+ * by the backend's static analysis of the live buffer and the workspace+ * (jarvis/agentic_ide/python_intel.py).+ *+ * A definition in another workspace file opens that file in a tab at the+ * line, through the editor opener registered here.+ */+export function registerPythonLanguage(monaco: typeof Monaco): void {+ const kinds: Record<string, Monaco.languages.CompletionItemKind> = {+ module: monaco.languages.CompletionItemKind.Module,+ class: monaco.languages.CompletionItemKind.Class,+ function: monaco.languages.CompletionItemKind.Function,+ instance: monaco.languages.CompletionItemKind.Variable,+ statement: monaco.languages.CompletionItemKind.Variable,+ param: monaco.languages.CompletionItemKind.Variable,+ keyword: monaco.languages.CompletionItemKind.Keyword,+ property: monaco.languages.CompletionItemKind.Property,+ path: monaco.languages.CompletionItemKind.File,+ };++ const request = (model: Monaco.editor.ITextModel, position: Monaco.Position) => {+ const file = fileOfUri(model.uri);+ if (!file) return null;+ const at: PythonPosition = {+ path: file.path,+ text: model.getValue(),+ line: position.lineNumber,+ column: position.column,+ };+ return { workspaceId: file.workspaceId, at };+ };++ const signalOf = (token: Monaco.CancellationToken) => {+ const controller = new AbortController();+ token.onCancellationRequested(() => controller.abort());+ return controller.signal;+ };++ monaco.languages.registerCompletionItemProvider("python", {+ triggerCharacters: ["."],+ async provideCompletionItems(model, position, _context, token) {+ const call = request(model, position);+ if (!call) return { suggestions: [] };+ let items: PythonCompletion[] = [];+ try {+ items = await pythonIntel<PythonCompletion[]>(call.workspaceId, "complete", call.at, signalOf(token));+ } catch {+ return { suggestions: [] }; // a failed lookup just shows no suggestions+ }+ const word = model.getWordUntilPosition(position);+ const range = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);+ return {+ suggestions: items.map((item, index) => ({+ label: item.name,+ kind: kinds[item.type] ?? monaco.languages.CompletionItemKind.Text,+ detail: item.detail,+ insertText: item.name,+ // Keep jedi's order (it ranks by relevance) under Monaco's filtering.+ sortText: String(index).padStart(5, "0"),+ range,+ })),+ };+ },+ });++ monaco.languages.registerHoverProvider("python", {+ async provideHover(model, position, token) {+ const call = request(model, position);+ if (!call || !model.getWordAtPosition(position)) return null;+ try {+ const text = await pythonIntel<string | null>(call.workspaceId, "hover", call.at, signalOf(token));+ return text ? { contents: [{ value: text }] } : null;+ } catch {+ return null;+ }+ },+ });++ monaco.languages.registerDefinitionProvider("python", {+ async provideDefinition(model, position, token) {+ const call = request(model, position);+ if (!call) return null;+ try {+ const found = await pythonIntel<PythonLocation[]>(call.workspaceId, "definition", call.at, signalOf(token));+ return found.map((location) => ({+ uri: fileUri(call.workspaceId, location.path),+ range: new monaco.Range(location.line, location.column, location.line, location.column),+ }));+ } catch {+ return null;+ }+ },+ });++ // "Go to Definition" into another file: open it as a tab at the line.+ monaco.editor.registerEditorOpener({+ openCodeEditor(_source, resource, selectionOrPosition) {+ const file = fileOfUri(resource);+ if (!file) return false;+ const start =+ selectionOrPosition && "startLineNumber" in selectionOrPosition+ ? { line: selectionOrPosition.startLineNumber, column: selectionOrPosition.startColumn }+ : selectionOrPosition+ ? { line: selectionOrPosition.lineNumber, column: selectionOrPosition.column }+ : { line: 1, column: 1 };+ useCodeEditorStore.getState().openFile(file.workspaceId, file.path, { preview: false, ...start });+ return true;+ },+ });+}diff --git a/pyproject.toml b/pyproject.tomlindex d60408e118..7c1756e800 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -69,6 +69,9 @@ dependencies = [# (lazy import); already installed through requests, declared because# Jarvis imports it directly."charset-normalizer>=3.4",+ # The code editor's Python completions, hovers and go-to-definition+ # (static analysis, lazy import; pure Python).+ "jedi>=0.19",# The code editor's delete moves files to the system trash (Recycle Bin,# macOS Trash, freedesktop trash) instead of erasing them; pure Python."Send2Trash>=1.8.3",diff --git a/requirements.in b/requirements.inindex 93b77ab0c1..0335f9d52e 100644--- a/requirements.in+++ b/requirements.in@@ -33,6 +33,9 @@ json-repair>=0.30# (lazy import); already installed through requests, declared because# Jarvis imports it directly.charset-normalizer>=3.4+# The code editor's Python completions, hovers and go-to-definition+# (static analysis, lazy import; pure Python).+jedi>=0.19# The code editor's delete moves files to the system trash (Recycle Bin,# macOS Trash, freedesktop trash) instead of erasing them; pure Python.Send2Trash>=1.8.3diff --git a/requirements.txt b/requirements.txtindex 979e933275..23933cd413 100644--- a/requirements.txt+++ b/requirements.txt@@ -735,6 +735,10 @@ jaraco-functools==4.5.0 \--hash=sha256:3bb5665ea4a020cf78a7040e89154c77edadb3ca74f366479669c5999aa70b03 \--hash=sha256:79ce39246eddbde4b3a03b77ea5f0f7878dc669b166a66cf3fa8e266aa3fa2f4# via keyring+jedi==0.20.0 \+ --hash=sha256:7bdd9c2634f56713299976f4cbd59cb3fa92165cc5e05ea811fb253480728b67 \+ --hash=sha256:c3f4ccbd276696f4b19c54618d4fb18f9fc24b0aef02acf704b23f487daa1011+ # via personal-jarvis (pyproject.toml)jeepney==0.9.0 ; sys_platform == 'linux' \--hash=sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683 \--hash=sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732@@ -1364,6 +1368,10 @@ packaging==26.2 \# via# personal-jarvis (pyproject.toml)# onnxruntime+parso==0.8.7 \+ --hash=sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c \+ --hash=sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1+ # via jedipillow==12.3.0 \--hash=sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756 \--hash=sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a \diff --git a/tests/unit/agentic_ide/test_python_intel.py b/tests/unit/agentic_ide/test_python_intel.pynew file mode 100644index 0000000000..44d4da7801--- /dev/null+++ b/tests/unit/agentic_ide/test_python_intel.py@@ -0,0 +1,60 @@+"""Python completions, hovers and definitions for the code editor."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.agentic_ide import python_intel+from jarvis.ui.web import agentic_ide_routes as routes++pytest.importorskip("jedi")++SOURCE = 'from pkg.util import shout\nshout("x").upp\n'+++def project(tmp_path: Path) -> Path:+ (tmp_path / "pkg").mkdir()+ (tmp_path / "pkg" / "__init__.py").write_text("", encoding="utf-8")+ (tmp_path / "pkg" / "util.py").write_text(+ 'def shout(text: str) -> str:\n """Upper-case the text."""\n return text.upper()\n',+ encoding="utf-8",+ )+ return tmp_path+++def test_completion_uses_the_live_buffer(project: Path) -> None:+ names = [item["name"] for item in python_intel.complete(project, "main.py", SOURCE, 2, 15)]+ assert "upper" in names+++def test_hover_shows_the_signature_and_docstring(project: Path) -> None:+ text = python_intel.hover(project, "main.py", SOURCE, 2, 2)+ assert text is not None+ assert "shout(text: str) -> str" in text+ assert "Upper-case the text." in text+++def test_definition_leads_into_another_workspace_file(project: Path) -> None:+ assert python_intel.definitions(project, "main.py", SOURCE, 2, 2) == [+ {"path": "pkg/util.py", "line": 1, "column": 5}+ ]+++def test_definitions_outside_the_workspace_are_left_out(project: Path) -> None:+ text = "import os\nos.getcwd()\n"+ assert python_intel.definitions(project, "main.py", text, 2, 5) == []+++async def test_route_answers_each_action(project: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ session = SimpleNamespace(folder=str(project))+ registry = SimpleNamespace(get=lambda wid: session if wid == "w1" else None)+ monkeypatch.setattr(routes, "get_registry", lambda: registry)+ request = routes.PythonIntelRequest(path="main.py", text=SOURCE, line=2, column=2)++ answer = await routes.python_intel("w1", "definition", request)++ assert answer["result"] == [{"path": "pkg/util.py", "line": 1, "column": 5}]