feat(python): add a Python Console tool window (#5164)

Adds a Python Console tool window: an interactive interpreter of the project's Python (the one Settings and the status bar show; in a workspace, the member the active file is in), started in the project root with the source roots on `PYTHONPATH`. It uses IPython when the interpreter has it and plain Python otherwise, in its own `__main__`. Enter runs the input, Shift+Enter adds a line, Up/Down recall earlier inputs, and while code runs a typed line answers its `input()`. A Variables pane lists the console's globals after each run. Execute Selection in Python Console (`python.console.executeSelection`, Alt+Shift+E, also in the editor context menu of Python files) sends the selection or the current line, starting the console if needed; a selection inside an indented block is dedented. The console is a small driver script run on the existing Run process host, so there are no backend changes.

Closes #5148

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
LU XIANGRUI
2026-11-22 14:34:50 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent 88f494ca50
commit c632dfa01c
17 changed files with 898 additions and 0 deletions
+142
View File
@@ -0,0 +1,142 @@
/** Python Console tool window: output, the input box below it, and the console's variables beside them. */
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { executeAction } from "@/platform/actions";
import { useConsoleFont } from "@/platform/consoleFont";
import { useTx } from "@/platform/i18n";
import { Button, EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { spanStyle } from "@/ui/ansi";
import { clearOutput, execute, restartConsole, sendInput, startConsole, stopConsole, useConsole } from "./store";
import styles from "./PythonConsole.module.css";
export function ConsoleView() {
const { status, header, output, variables, noInterpreter } = useConsole();
const font = useConsoleFont();
const t = useTx();
const outputRef = useRef<HTMLDivElement>(null);
const follow = useRef(true);
useEffect(() => void startConsole(), []);
useLayoutEffect(() => {
const el = outputRef.current;
if (el && follow.current) el.scrollTop = el.scrollHeight;
}, [output]);
if (noInterpreter && status === "stopped") {
return (
<EmptyState
title="No Python interpreter"
actions={
<>
<Button onClick={() => void executeAction("python.interpreterSettings")}>
<T>Interpreter Settings…</T>
</Button>
<Button onClick={() => void startConsole()}>
<T>Retry</T>
</Button>
</>
}
>
<T>Select an interpreter for this project to use the Python Console.</T>
</EmptyState>
);
}
const fontStyle = { fontFamily: font.family, fontSize: font.size, lineHeight: `${font.rowHeight}px` };
return (
<div className={styles.view}>
<div className={styles.toolbar}>
<IconButton icon="rerun" title="Restart Console" size="small" onClick={restartConsole} />
<IconButton
icon="stop"
title="Stop Console"
size="small"
disabled={status === "stopped"}
onClick={stopConsole}
/>
<IconButton icon="trash" title="Clear" size="small" onClick={clearOutput} />
<span className={styles.header}>{header ?? (status === "starting" ? <T>Starting…</T> : null)}</span>
</div>
<SplitGroup orientation="horizontal" id="python-console-split" storageKey="openidea.pythonConsole.split">
<SplitPanel id="console" minSize={200} className={styles.main}>
<div
ref={outputRef}
className={styles.output}
style={fontStyle}
role="log"
aria-label={t("Python Console output")}
tabIndex={0}
onScroll={(e) => {
const el = e.currentTarget;
follow.current = el.scrollHeight - el.scrollTop - el.clientHeight < 4;
}}
>
{output.map((s, i) => (
<span key={i} style={spanStyle(s)}>
{s.text}
</span>
))}
</div>
<ConsoleInput style={fontStyle} busy={status === "busy"} />
</SplitPanel>
<SplitHandle />
<SplitPanel id="variables" minSize={140} defaultSize="30%" className={styles.variables}>
{variables.length ? (
<div role="list" aria-label={t("Console variables")} className={styles.varList}>
{variables.map((v) => (
<div role="listitem" key={v.name} className={styles.varRow} title={v.value}>
<span className={styles.varName}>{v.name}</span>
<span className={styles.varType}>{v.type}</span>
<span className={styles.varValue}>{v.value}</span>
</div>
))}
</div>
) : (
<EmptyState title="No variables" />
)}
</SplitPanel>
</SplitGroup>
</div>
);
}
/** Enter runs the input (or, while code runs, answers its `input()`); Shift+Enter adds a line; ↑/↓ recall. */
function ConsoleInput({ style, busy }: { style: React.CSSProperties; busy: boolean }) {
const [text, setText] = useState("");
const browse = useRef<number | null>(null);
const t = useTx();
return (
<textarea
className={styles.input}
style={style}
rows={Math.min(8, text.split("\n").length)}
value={text}
spellCheck={false}
aria-label={t(busy ? "Input for the running code" : "Python Console input")}
placeholder={busy ? t("Input for the running code") : ">>>"}
onChange={(e) => {
browse.current = null;
setText(e.target.value);
}}
onKeyDown={(e) => {
const el = e.currentTarget;
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
if (busy) sendInput(text);
else execute(text);
browse.current = null;
setText("");
return;
}
const { history } = useConsole.getState();
const up = e.key === "ArrowUp" && !el.value.slice(0, el.selectionStart).includes("\n");
const down = e.key === "ArrowDown" && !el.value.slice(el.selectionEnd).includes("\n");
if ((!up && !down) || !history.length || busy) return;
e.preventDefault();
const at = browse.current ?? history.length;
const next = Math.max(0, Math.min(history.length, at + (up ? -1 : 1)));
browse.current = next;
setText(history[next] ?? "");
}}
/>
);
}
@@ -0,0 +1,85 @@
.view {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
background: var(--bg-editor);
}
.toolbar {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--border);
background: var(--bg-elev);
}
.header {
margin-left: var(--space-2);
color: var(--fg-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.main {
display: flex;
flex-direction: column;
min-height: 0;
}
.output {
flex: 1;
min-height: 0;
overflow: auto;
padding: var(--space-1) var(--space-2);
white-space: pre-wrap;
overflow-wrap: anywhere;
color: var(--fg-editor);
user-select: text;
-webkit-user-select: text;
cursor: text;
}
.input {
flex: none;
resize: none;
border: 0;
border-top: 1px solid var(--border);
padding: var(--space-1) var(--space-2);
background: var(--bg-editor);
color: var(--fg-editor);
/* Like the Debug Console's prompt: the caret shows focus; a ring would be cut by the window's rounded corner. */
outline: none;
}
.variables {
overflow: auto;
border-left: 1px solid var(--border);
}
.varList {
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.varRow {
display: flex;
gap: var(--space-2);
padding: var(--space-0-5) var(--space-2);
white-space: nowrap;
}
.varName {
color: var(--fg-editor);
}
.varType {
color: var(--fg-muted);
}
.varValue {
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-editor);
}
+103
View File
@@ -0,0 +1,103 @@
# The Python Console's driver. Reads one JSON request per stdin line ({"code": ...}),
# runs it in IPython when installed, else in a plain namespace, and after each run writes
# a record-separator line (\x1e + JSON) with the console's variables.
import json
import reprlib
import sys
import textwrap
import types
RS = "\x1e"
_out = sys.stdout
_repr = reprlib.Repr()
_repr.maxstring = _repr.maxother = 200
_hidden = set()
def _send(message):
sys.stdout.flush()
sys.stderr.flush()
_out.write(RS + json.dumps(message) + "\n")
_out.flush()
def _variables(namespace):
rows = []
for name, value in list(namespace.items()):
if name.startswith("_") or name in _hidden or isinstance(value, types.ModuleType):
continue
try:
text = _repr.repr(value)
except Exception as error: # a broken __repr__ must not break the console
text = "<repr failed: %s>" % type(error).__name__
rows.append({"name": name, "type": type(value).__name__, "value": text})
rows.sort(key=lambda row: row["name"])
return rows
try:
from IPython.core.interactiveshell import InteractiveShell
import IPython
_shell = InteractiveShell.instance(colors="Neutral") # readable on light and dark themes
namespace = _shell.user_ns
_hidden = set(_shell.user_ns_hidden) # what IPython put there itself (%who hides it too)
flavour = "IPython " + IPython.__version__
# exit() / quit() ask the shell to end, which only the terminal shell implements.
_shell.ask_exit = lambda: setattr(_shell, "exit_now", True)
def run(code):
_shell.run_cell(code, store_history=True)
return _shell.exit_now
except ImportError:
import ast
import code as _code
# The console's own __main__, so its classes pickle and `import __main__` sees its names.
_main = types.ModuleType("__main__")
sys.modules["__main__"] = _main
namespace = _main.__dict__
_console = _code.InteractiveInterpreter(namespace)
flavour = None
def run(code):
# Like a notebook cell: a trailing expression prints its value, as at the >>> prompt.
try:
tree = ast.parse(code, "<console>")
except (SyntaxError, ValueError, OverflowError):
_console.showsyntaxerror("<console>")
return
last = tree.body[-1:] if tree.body and isinstance(tree.body[-1], ast.Expr) else []
body = tree.body[: len(tree.body) - len(last)]
try:
exec(compile(ast.Module(body=body, type_ignores=[]), "<console>", "exec"), namespace)
if last:
exec(compile(ast.Interactive(body=last), "<console>", "single"), namespace)
except SystemExit:
raise
except BaseException:
_console.showtraceback()
_send({"ready": {"version": sys.version.split()[0], "ipython": flavour}})
while True:
line = sys.stdin.readline()
if not line:
break
try:
request = json.loads(line)
except ValueError:
request = None
if not isinstance(request, dict) or not isinstance(request.get("code"), str):
continue # input typed while code ran that nothing read
try:
if run(textwrap.dedent(request["code"])):
break
except SystemExit:
raise # the console ends with the code's exit status
except BaseException:
import traceback
traceback.print_exc()
_send({"done": {"variables": _variables(namespace)}})
@@ -0,0 +1,67 @@
// @vitest-environment node
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { request, stdoutParser, type ConsoleMessage } from "./protocol";
const DRIVER = fileURLToPath(new URL("./console.py", import.meta.url));
const PYTHON = ["python3", "python"].find((p) => spawnSync(p, ["--version"]).status === 0);
// An interpreter with IPython, for the IPython path (OPENIDEA_TEST_IPYTHON, else none: skipped).
const IPYTHON = process.env.OPENIDEA_TEST_IPYTHON;
function run(codes: string[], input = "", python = PYTHON!) {
const stdin = codes.map(request).join("") + input;
// -I -S: no site-packages, so the plain-Python path even where IPython is installed.
const flags = python === PYTHON ? ["-I", "-S", "-u"] : ["-u"];
const result = spawnSync(python, [...flags, DRIVER], { input: stdin, encoding: "utf8" });
return { ...stdoutParser()(result.stdout), stderr: result.stderr, status: result.status };
}
const variables = (messages: ConsoleMessage[]) =>
messages.flatMap((m) => ("done" in m ? [m.done.variables.map((v) => `${v.name}: ${v.type} = ${v.value}`)] : []));
it.skipIf(!PYTHON)("runs code like the >>> prompt and reports the globals after each run", () => {
const { text, messages, stderr } = run(
[
"import os\nx = 1\nx + 1",
" def double(a):\n return a * 2\n print(double(x))",
"1/0",
"name = input()\nname",
],
// Lines typed while code ran that nothing read are not requests.
`Ada\n"stray"\n42\nstray\n${request("name * 2")}`,
);
expect(messages[0]).toEqual({ ready: { version: expect.any(String), ipython: null } });
expect(text).toBe("2\n2\n'Ada'\n'AdaAda'\n");
expect(stderr).toContain("ZeroDivisionError: division by zero");
expect(stderr.match(/Traceback/g)).toHaveLength(1);
const after = variables(messages);
expect(after[0]).toEqual(["x: int = 1"]);
expect(after[1]).toEqual([expect.stringMatching(/^double: function = <function double/), "x: int = 1"]);
expect(after[3]).toContain("name: str = 'Ada'");
});
it.skipIf(!PYTHON)("gives console code its own __main__, so its classes pickle", () => {
const { text, messages } = run(
[
"class Point:\n pass\nimport pickle\ntype(pickle.loads(pickle.dumps(Point()))).__name__",
"import __main__\nsorted(n for n in ('Point', '_send') if hasattr(__main__, n))",
],
// A JSON value without code, typed while nothing read it, is not a request either.
"{}\n",
);
expect(text).toBe("'Point'\n['Point']\n");
expect(messages.filter((m) => "done" in m)).toHaveLength(2);
});
it.skipIf(!PYTHON)("ends at sys.exit() with its code", () => {
const { text, status } = run(["import sys\nsys.exit(3)", "1 + 1"]);
expect([text, status]).toEqual(["", 3]);
});
it.skipIf(!IPYTHON)("ends at exit() under IPython", () => {
const { text, messages, status } = run(["x = 1", "exit()", "1 + 1"], "", IPYTHON);
expect(messages[0]).toEqual({ ready: { version: expect.any(String), ipython: expect.stringMatching(/^IPython /) } });
expect([text, messages.length, status]).toEqual(["", 2, 0]);
});
+57
View File
@@ -0,0 +1,57 @@
/** Python Console: an interactive interpreter of the project's Python, fed from the editor too. */
import { activeEditor } from "@/editor/api";
import { registerActions } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { lazyComponent } from "@/ui";
import { registerMenuGroup, registerToolWindow, toolWindowService } from "@/workbench/contributions";
import { selectionCode } from "./selection";
import { execute, installConsole } from "./store";
const ID = "pythonConsole";
export function activate(): () => void {
const disposers = [
installConsole(),
registerToolWindow({
id: ID,
title: "Python Console",
icon: "file-python",
anchor: "bottom",
// Listed under the stripe's "…" until first opened: most projects are not Python ones.
stripe: "onUse",
order: 27,
component: lazyComponent(() => import("./ConsoleView").then((m) => m.ConsoleView)),
}),
registerActions([
{
id: "python.console.show",
title: "Python Console",
category: "Tools",
when: "projectOpen",
run: () => toolWindowService().show(ID, true),
},
{
id: "python.console.executeSelection",
title: "Execute Selection in Python Console",
category: "Tools",
when: "editorLangId == python",
keyWhen: "editorTextFocus",
run: () => {
const state = activeEditor()?.view.state;
const code = state && selectionCode(state);
if (!code?.trim()) return;
toolWindowService().show(ID, false);
execute(code);
},
},
]),
registerMenuGroup({
id: "pythonConsole.editor",
menus: ["editor"],
order: 45,
items: () =>
getContext().editorLangId === "python" ? [{ kind: "action", action: "python.console.executeSelection" }] : [],
}),
];
return () => disposers.reverse().forEach((d) => d());
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { request, stdoutParser } from "./protocol";
describe("stdoutParser", () => {
it("separates driver messages from output", () => {
const parse = stdoutParser();
expect(parse('Out[1]: 2\n\x1e{"done":{"variables":[]}}\nafter')).toEqual({
text: "Out[1]: 2\nafter",
messages: [{ done: { variables: [] } }],
});
});
it("waits for a message cut across chunks", () => {
const parse = stdoutParser();
expect(parse('hi\x1e{"ready":{"vers')).toEqual({ text: "hi", messages: [] });
expect(parse('ion":"3.12.1","ipython":null}}\n')).toEqual({
text: "",
messages: [{ ready: { version: "3.12.1", ipython: null } }],
});
});
it("keeps a line that only looks like a message as output", () => {
expect(stdoutParser()("a\x1enot json\nb")).toEqual({ text: "a\x1enot json\nb", messages: [] });
});
it("reads the message after output that printed \\x1e without ending its line", () => {
const parse = stdoutParser();
expect(parse("x\x1ey")).toEqual({ text: "x", messages: [] });
expect(parse('\x1e{"done":{"variables":[]}}\n')).toEqual({
text: "\x1ey",
messages: [{ done: { variables: [] } }],
});
});
});
it("encodes code as one stdin line", () => {
expect(request("x = 1\nprint(x)")).toBe('{"code":"x = 1\\nprint(x)"}\n');
});
+43
View File
@@ -0,0 +1,43 @@
// The console driver (console.py) prints ordinary output as it is and its own messages
// as `\x1e<json>\n` lines on stdout.
export type ConsoleVariable = { name: string; type: string; value: string };
export type ConsoleMessage =
| { ready: { version: string; ipython: string | null } }
| { done: { variables: ConsoleVariable[] } };
const RS = "\x1e";
/** Splits stdout into the text to show and the driver's messages; a message cut across chunks waits for the rest. */
export function stdoutParser() {
let pending = "";
return (chunk: string): { text: string; messages: ConsoleMessage[] } => {
let rest = pending + chunk;
pending = "";
let text = "";
const messages: ConsoleMessage[] = [];
for (;;) {
const first = rest.indexOf(RS);
if (first < 0) break;
const end = rest.indexOf("\n", first);
if (end < 0) {
pending = rest.slice(first);
rest = rest.slice(0, first);
break;
}
// A message starts a line's last \x1e: an earlier one there is output that didn't end its line.
const start = rest.lastIndexOf(RS, end);
text += rest.slice(0, start);
try {
messages.push(JSON.parse(rest.slice(start + 1, end)) as ConsoleMessage);
} catch {
text += rest.slice(start, end + 1);
}
rest = rest.slice(end + 1);
}
return { text: text + rest, messages };
};
}
/** The stdin line that asks the driver to run `code`. */
export const request = (code: string) => `${JSON.stringify({ code })}\n`;
@@ -0,0 +1,20 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { expect, it } from "vitest";
import { selectionCode } from "./selection";
const DOC = "def f():\n for i in range(2):\n print(i)\n print('done')\n";
const at = (from: number, to = from) =>
selectionCode(EditorState.create({ doc: DOC, selection: EditorSelection.single(from, to) }));
it("sends the caret's line when nothing is selected", () => {
expect(at(DOC.indexOf("print(i)"))).toBe(" print(i)");
});
it("gives a selection that starts after the indentation its indentation back", () => {
// Selected from `for` (as a double-click or Shift+Down from there selects) to the end.
expect(at(DOC.indexOf("for"), DOC.length)).toBe(" for i in range(2):\n print(i)\n print('done')\n");
});
it("leaves a selection that starts mid-statement as it is", () => {
expect(at(DOC.indexOf("range"), DOC.indexOf(":\n print"))).toBe("range(2)");
});
+12
View File
@@ -0,0 +1,12 @@
import type { EditorState } from "@codemirror/state";
/**
* The selection, or the caret's line when nothing is selected. A selection that starts after a
* line's indentation gets that indentation back, so its lines dedent together.
*/
export function selectionCode(state: EditorState): string {
const sel = state.selection.main;
if (sel.empty) return state.doc.lineAt(sel.head).text;
const lead = state.sliceDoc(state.doc.lineAt(sel.from).from, sel.from);
return (/^[ \t]*$/.test(lead) ? lead : "") + state.sliceDoc(sel.from, sel.to);
}
+85
View File
@@ -0,0 +1,85 @@
import { beforeEach, expect, it, vi } from "vitest";
import type { OutputChunk } from "@/platform/ipc";
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
const ipc = vi.hoisted(() => ({
exited: (_e: { run: number; code: number | null }) => {},
started: null as null | { resolve: (id: number) => void; channel: { onmessage?: (c: OutputChunk) => void } },
stdin: vi.fn(),
}));
vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} }));
vi.mock("@/platform/auxWindow", () => ({ windowLabel: () => "main" }));
vi.mock("@/workbench/contributions", () => ({ editorService: () => ({ activePath: () => null }) }));
vi.mock("@/platform/project", () => ({
dirname: (p: string) => p,
useProject: { getState: () => ({ project: { root: "/p" } }), subscribe: () => () => {} },
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
onIdeEvent: (_type: string, handler: typeof ipc.exited) => {
ipc.exited = handler;
return () => {};
},
commands: {
runList: () => Promise.resolve([]),
sdkPythonEffective: () => ok("/venv/bin/python"),
runStart: (_config: unknown, channel: NonNullable<typeof ipc.started>["channel"]) =>
new Promise((resolve) => {
ipc.started = { channel, resolve: (id) => resolve({ status: "ok", data: { id } }) };
}),
runStdin: (id: number, data: string) => {
ipc.stdin(id, data);
return ok(null);
},
runStop: () => ok(null),
},
};
});
const { execute, installConsole, stopConsole, tail, useConsole } = await import("./store");
const { request } = await import("./protocol");
const settle = () => new Promise((r) => setTimeout(r, 0));
const text = () =>
useConsole
.getState()
.output.map((s) => s.text)
.join("");
installConsole();
beforeEach(() => {
stopConsole();
ipc.started = null;
ipc.stdin.mockClear();
});
it("runs code sent while starting once the driver is ready, even before the start call returns", async () => {
execute("x = 1");
await settle();
ipc.started!.channel.onmessage!({ kind: "stdout", text: '\x1e{"ready":{"version":"3.12.1","ipython":null}}\n' });
expect(ipc.stdin).not.toHaveBeenCalled();
ipc.started!.resolve(7);
await settle();
expect(ipc.stdin).toHaveBeenCalledWith(7, request("x = 1"));
expect(useConsole.getState().status).toBe("busy");
});
it("reports an interpreter that exits before the start call returns", async () => {
execute("x = 1");
await settle();
ipc.exited({ run: 8, code: 1 });
ipc.started!.resolve(8);
await settle();
expect(useConsole.getState().status).toBe("stopped");
expect(text()).toContain("exit code 1");
expect(ipc.stdin).not.toHaveBeenCalled();
});
it("keeps the newest output within the cap, cutting into the oldest kept span", () => {
const spans = [{ text: "aaaa" }, { text: "bb", fg: "red" }, { text: "cc" }];
expect(tail(spans, 10)).toBe(spans);
expect(tail(spans, 5)).toEqual([{ text: "a" }, { text: "bb", fg: "red" }, { text: "cc" }]);
expect(tail(spans, 3)).toEqual([{ text: "b", fg: "red" }, { text: "cc" }]);
});
+221
View File
@@ -0,0 +1,221 @@
/** The Python Console's process: the project interpreter running console.py on the Run process host. */
import { Channel } from "@tauri-apps/api/core";
import { create } from "zustand";
import { call, commands, onIdeEvent, type OutputChunk, type RunConfig, type RunId } from "@/platform/ipc";
import { windowLabel } from "@/platform/auxWindow";
import { dirname, useProject } from "@/platform/project";
import { tx } from "@/platform/i18n";
import { AnsiStream, appendSpans, type Span } from "@/ui/ansi";
import { editorService } from "@/workbench/contributions";
import DRIVER from "./console.py?raw";
import { request, stdoutParser, type ConsoleMessage, type ConsoleVariable } from "./protocol";
export type ConsoleStatus = "stopped" | "starting" | "idle" | "busy";
interface ConsoleState {
status: ConsoleStatus;
/** "Python 3.12.1 (IPython 8.20.0)" once the driver is up. */
header: string | null;
output: Span[];
variables: ConsoleVariable[];
/** No interpreter is selected for the project. */
noInterpreter: boolean;
history: string[];
}
const initial = (): ConsoleState => ({
status: "stopped",
header: null,
output: [],
variables: [],
noInterpreter: false,
history: [],
});
export const useConsole = create<ConsoleState>(initial);
// ponytail: the oldest output goes past the cap; a virtualised list if consoles need more.
const MAX_CHARS = 1_000_000;
let runId: RunId | null = null;
let generation = 0;
const queue: string[] = [];
/** Exits that arrived before their start call returned (an interpreter that fails at once). */
const earlyExits = new Map<RunId, number | null>();
/** The last `max` characters of `spans`. */
export function tail(spans: Span[], max = MAX_CHARS): Span[] {
let total = 0;
let i = spans.length;
while (i > 0 && total + spans[i - 1]!.text.length <= max) total += spans[--i]!.text.length;
if (i === 0) return spans;
const cut = spans[i - 1]!;
return [{ ...cut, text: cut.text.slice(cut.text.length - (max - total)) }, ...spans.slice(i)];
}
function append(spans: Span[]) {
if (spans.length) useConsole.setState({ output: tail(appendSpans(useConsole.getState().output, spans)) });
}
const note = (text: string) => append([{ text, dim: true }]);
function echo(code: string) {
const lines = code.replace(/\n+$/, "").split("\n");
append([{ text: lines.map((l, i) => (i ? "... " : ">>> ") + l).join("\n") + "\n", fg: "var(--accent)" }]);
}
function next() {
// Before the start call returns there is no run to write to yet: the code waits.
if (runId === null) return;
const code = queue.shift();
if (code === undefined) return;
useConsole.setState({ status: "busy" });
echo(code);
void call(commands.runStdin(runId, request(code))).catch((e) => note(`${String(e)}\n`));
}
function onMessage(message: ConsoleMessage) {
if ("ready" in message) {
const { version, ipython } = message.ready;
useConsole.setState({ header: ipython ? `Python ${version} (${ipython})` : `Python ${version}`, status: "idle" });
} else {
useConsole.setState({ variables: message.done.variables, status: "idle" });
}
next();
}
/** Run ids of this window's consoles: a reloaded page finds the ones its previous load left running. */
const PREFIX = `python-console:${windowLabel()}:`;
function config(python: string, cwd: string): RunConfig {
return {
id: `${PREFIX}${crypto.randomUUID()}`,
name: "Python Console",
// "python" puts the project's source roots on PYTHONPATH and unbuffers output.
kind: "python",
command: python,
args: ["-u", "-c", DRIVER],
cwd,
env: {},
detected: true,
isTest: false,
debugAdapter: null,
emulateTerminal: false,
};
}
export async function startConsole() {
if (useConsole.getState().status !== "stopped") return;
const root = useProject.getState().project?.root;
if (!root) return;
const mine = ++generation;
useConsole.setState({ status: "starting", noInterpreter: false, header: null, variables: [] });
earlyExits.clear();
try {
// The interpreter the status bar shows: in a workspace, the one of the member the active file is in.
const active = editorService().activePath();
const python = await call(commands.sdkPythonEffective(active ? dirname(active) : null));
if (mine !== generation) return;
if (!python) {
queue.length = 0;
useConsole.setState({ status: "stopped", noInterpreter: true });
return;
}
const out = new AnsiStream();
const err = new AnsiStream();
const parse = stdoutParser();
const channel = new Channel<OutputChunk>();
channel.onmessage = (chunk) => {
if (mine !== generation) return;
if (chunk.kind === "stdout") {
const { text, messages } = parse(chunk.text);
append(out.parse(text));
messages.forEach(onMessage);
} else if (chunk.kind === "stderr") {
append(err.parse(chunk.text).map((s) => (s.fg ? s : { ...s, fg: "var(--ansi-red)" })));
}
// "system" chunks echo the command line, which is the driver's source here.
};
const info = await call(commands.runStart(config(python, root), channel, null));
if (mine !== generation) void call(commands.runStop(info.id)).catch(() => {});
else {
runId = info.id;
if (earlyExits.has(info.id)) onExit(info.id, earlyExits.get(info.id)!);
// The driver may be ready before the start call returns.
else if (useConsole.getState().status === "idle") next();
}
earlyExits.clear();
} catch (e) {
if (mine !== generation) return;
queue.length = 0;
useConsole.setState({ status: "stopped" });
note(`${e instanceof Error ? e.message : String(e)}\n`);
}
}
/** Runs `code` now, or after the statement in progress (starting the console first if needed). */
export function execute(code: string) {
if (!code.trim()) return;
const { history } = useConsole.getState();
if (history[history.length - 1] !== code) useConsole.setState({ history: [...history, code].slice(-200) });
queue.push(code);
const { status } = useConsole.getState();
if (status === "stopped") void startConsole();
else if (status === "idle") next();
}
/** A line typed while code runs: what its `input()` reads. */
export function sendInput(line: string) {
if (runId === null) return;
append([{ text: `${line}\n` }]);
void call(commands.runStdin(runId, `${line}\n`)).catch(() => {});
}
export function stopConsole() {
generation++;
queue.length = 0;
const id = runId;
runId = null;
if (id !== null) void call(commands.runStop(id)).catch(() => {});
useConsole.setState({ status: "stopped", variables: [] });
}
export function restartConsole() {
stopConsole();
useConsole.setState({ output: [] });
void startConsole();
}
export const clearOutput = () => useConsole.setState({ output: [] });
function onExit(id: RunId, code: number | null) {
if (id !== runId) return;
runId = null;
queue.length = 0;
useConsole.setState({ status: "stopped" });
note(`${tx`\n[Process finished with exit code ${String(code ?? "?")}]`}\n`);
}
/** Exit reporting, and a fresh console for each project. */
export function installConsole(): () => void {
void commands
.runList()
.then((runs) => {
for (const r of runs)
if (r.running && r.id !== runId && r.configId.startsWith(PREFIX)) void commands.runStop(r.id);
})
.catch(() => {});
const offExit = onIdeEvent("runExited", (e) => {
if (e.run === runId) onExit(e.run, e.code);
else if (runId === null && useConsole.getState().status === "starting") earlyExits.set(e.run, e.code);
});
const offProject = useProject.subscribe((s, prev) => {
if (s.project?.root === prev.project?.root) return;
stopConsole();
useConsole.setState(initial());
});
return () => {
offExit();
offProject();
stopConsole();
};
}