Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(python-interpreter): stop a failed worker from blanking the app (#18271)

Innei6db6c57a5f75
diff --git a/packages/python-interpreter/src/__tests__/interpreter.test.ts b/packages/python-interpreter/src/__tests__/interpreter.test.ts
index c16d24558cb..f08c52c497d 100644
--- a/packages/python-interpreter/src/__tests__/interpreter.test.ts
+++ b/packages/python-interpreter/src/__tests__/interpreter.test.ts
@@ -1,27 +1,67 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
+// A plain function, not an arrow: the interpreter reaches it through `new`.
+const stubWorker = () =>
+ vi.fn().mockImplementation(function () {
+ return {
+ addEventListener: vi.fn(),
+ postMessage: vi.fn(),
+ removeEventListener: vi.fn(),
+ terminate: vi.fn(),
+ };
+ });
+
describe('Python interpreter', () => {
beforeEach(() => {
vi.resetModules();
+ vi.unstubAllGlobals();
});
it('should be undefined if is not in browser', async () => {
- const { PythonInterpreter } = await import('../index');
- expect(PythonInterpreter).toBeUndefined();
+ const { getPythonInterpreter } = await import('../index');
+ expect(getPythonInterpreter()).toBeUndefined();
});
it('should be defined if is in browser', async () => {
- const MockWorker = vi.fn().mockImplementation(() => ({
- postMessage: vi.fn(),
- terminate: vi.fn(),
- addEventListener: vi.fn(),
- removeEventListener: vi.fn(),
- }));
+ vi.stubGlobal('Worker', stubWorker());
+
+ const { getPythonInterpreter } = await import('../index');
+ expect(getPythonInterpreter()).toBeDefined();
+ });
+
+ it('does not construct the worker until it is asked for', async () => {
+ const Worker = stubWorker();
+ vi.stubGlobal('Worker', Worker);
+
+ const { getPythonInterpreter } = await import('../index');
+ expect(Worker).not.toHaveBeenCalled();
+
+ getPythonInterpreter();
+ expect(Worker).toHaveBeenCalledTimes(1);
+ });
+
+ // A cross-origin script URL and a CSP that forbids workers both make the
+ // constructor throw. Swallowing it hands back the same `undefined` a healthy
+ // run can produce, and the caller reports a blocked interpreter as a success.
+ it('replays a construction failure to every caller', async () => {
+ const Worker = vi.fn().mockImplementation(() => {
+ throw new DOMException('cannot be accessed from origin', 'SecurityError');
+ });
+ vi.stubGlobal('Worker', Worker);
+
+ const { getPythonInterpreter } = await import('../index');
+ expect(() => getPythonInterpreter()).toThrow('cannot be accessed from origin');
+ expect(() => getPythonInterpreter()).toThrow('cannot be accessed from origin');
+ expect(Worker).toHaveBeenCalledTimes(1);
+ });
- vi.stubGlobal('Worker', MockWorker);
+ it('constructs the worker once and reuses it', async () => {
+ const Worker = stubWorker();
+ vi.stubGlobal('Worker', Worker);
- const { PythonInterpreter } = await import('../index');
- expect(PythonInterpreter).toBeDefined();
+ const { getPythonInterpreter } = await import('../index');
+ expect(getPythonInterpreter()).toBe(getPythonInterpreter());
+ expect(Worker).toHaveBeenCalledTimes(1);
});
});
diff --git a/packages/python-interpreter/src/index.ts b/packages/python-interpreter/src/index.ts
index c8afca58cb0..019390097ec 100644
--- a/packages/python-interpreter/src/index.ts
+++ b/packages/python-interpreter/src/index.ts
@@ -1,2 +1,2 @@
-export { PythonInterpreter } from './interpreter';
+export { getPythonInterpreter } from './interpreter';
export * from './types';
diff --git a/packages/python-interpreter/src/interpreter.ts b/packages/python-interpreter/src/interpreter.ts
index 3095440e2d4..46244069e4b 100644
--- a/packages/python-interpreter/src/interpreter.ts
+++ b/packages/python-interpreter/src/interpreter.ts
@@ -2,12 +2,37 @@ import * as Comlink from 'comlink';
import type { PythonWorkerType } from './worker';
-export const PythonInterpreter = (() => {
- if (typeof Worker !== 'undefined') {
- const worker = new Worker(new URL('worker.ts', import.meta.url), {
- type: 'module',
- });
- return Comlink.wrap<PythonWorkerType>(worker);
+let interpreter: Comlink.Remote<PythonWorkerType> | undefined;
+let constructionError: unknown;
+let resolved = false;
+
+// Call this from inside the operation that needs the interpreter, never at module
+// scope. `new Worker` throws synchronously β€” a cross-origin script URL and a CSP
+// that forbids workers both do it β€” and an exception raised while a module
+// evaluates propagates to every importer, so a module-scope call turns an
+// unavailable Python interpreter into a blank app.
+//
+// `undefined` means the platform has no workers at all; a construction failure is
+// remembered and replayed to every caller, because a swallowed one leaves the
+// caller unable to tell a blocked interpreter from a successful run.
+export const getPythonInterpreter = (): Comlink.Remote<PythonWorkerType> | undefined => {
+ if (!resolved) {
+ resolved = true;
+
+ if (typeof Worker !== 'undefined') {
+ try {
+ interpreter = Comlink.wrap<PythonWorkerType>(
+ new Worker(new URL('worker.ts', import.meta.url), {
+ type: 'module',
+ }),
+ );
+ } catch (error) {
+ constructionError = error;
+ }
+ }
}
- return undefined;
-})();
+
+ if (constructionError) throw constructionError;
+
+ return interpreter;
+};
diff --git a/src/services/__tests__/python.test.ts b/src/services/__tests__/python.test.ts
new file mode 100644
index 00000000000..328df05d750
--- /dev/null
+++ b/src/services/__tests__/python.test.ts
@@ -0,0 +1,58 @@
+import { getPythonInterpreter } from '@lobechat/python-interpreter';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { pythonService } from '../python';
+
+vi.mock('@lobechat/python-interpreter', () => ({
+ getPythonInterpreter: vi.fn(),
+}));
+
+const stubInterpreter = (result = { result: '42', stdout: '', stderr: '' }) => {
+ const interpreter = {
+ downloadFiles: vi.fn().mockResolvedValue([]),
+ init: vi.fn().mockResolvedValue(undefined),
+ installPackages: vi.fn().mockResolvedValue(undefined),
+ runPython: vi.fn().mockResolvedValue(result),
+ uploadFiles: vi.fn().mockResolvedValue(undefined),
+ };
+
+ return { ctor: vi.fn().mockImplementation(() => Promise.resolve(interpreter)), interpreter };
+};
+
+describe('PythonService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ // Returning undefined here made the caller complete the tool call as a success
+ // and write `JSON.stringify(undefined)` as its content, so a CSP-blocked
+ // interpreter looked like Python that ran and produced nothing.
+ it('rejects when the interpreter is unavailable', async () => {
+ vi.mocked(getPythonInterpreter).mockReturnValue(undefined);
+
+ await expect(pythonService.runPython('print(1)', [], [])).rejects.toThrow(
+ 'Python interpreter is unavailable',
+ );
+ });
+
+ it('propagates a blocked interpreter construction', async () => {
+ vi.mocked(getPythonInterpreter).mockImplementation(() => {
+ throw new DOMException('cannot be accessed from origin', 'SecurityError');
+ });
+
+ await expect(pythonService.runPython('print(1)', [], [])).rejects.toThrow(
+ 'cannot be accessed from origin',
+ );
+ });
+
+ it('runs the code when the interpreter is available', async () => {
+ const { ctor, interpreter } = stubInterpreter();
+ vi.mocked(getPythonInterpreter).mockReturnValue(ctor as never);
+
+ const response = await pythonService.runPython('1 + 41', ['numpy', ''], []);
+
+ expect(interpreter.installPackages).toHaveBeenCalledWith(['numpy']);
+ expect(interpreter.runPython).toHaveBeenCalledWith('1 + 41');
+ expect(response).toEqual({ files: [], result: '42', stdout: '', stderr: '' });
+ });
+});
diff --git a/src/services/python.ts b/src/services/python.ts
index 1a91c405076..c78b9585954 100644
--- a/src/services/python.ts
+++ b/src/services/python.ts
@@ -1,4 +1,4 @@
-import { PythonInterpreter } from '@lobechat/python-interpreter';
+import { getPythonInterpreter } from '@lobechat/python-interpreter';
import { type CodeInterpreterResponse } from '@lobechat/types';
import { pythonEnv } from '@/envs/python';
@@ -8,9 +8,12 @@ class PythonService {
code: string,
packages: string[],
files: File[],
- ): Promise<CodeInterpreterResponse | undefined> {
- if (typeof Worker === 'undefined') return;
- const interpreter = await new PythonInterpreter!({
+ ): Promise<CodeInterpreterResponse> {
+ const PythonInterpreter = getPythonInterpreter();
+ if (!PythonInterpreter)
+ throw new Error('Python interpreter is unavailable: this environment has no Web Worker.');
+
+ const interpreter = await new PythonInterpreter({
pyodideIndexUrl: pythonEnv.NEXT_PUBLIC_PYODIDE_INDEX_URL!,
pypiIndexUrl: pythonEnv.NEXT_PUBLIC_PYODIDE_PIP_INDEX_URL!,
});
diff --git a/src/store/chat/slices/builtinTool/actions/interpreter.ts b/src/store/chat/slices/builtinTool/actions/interpreter.ts
index eb05c8a45f9..eb0ac6e5fd9 100644
--- a/src/store/chat/slices/builtinTool/actions/interpreter.ts
+++ b/src/store/chat/slices/builtinTool/actions/interpreter.ts
@@ -12,7 +12,6 @@ import { type SWRResponse } from 'swr';
import { useClientDataSWR } from '@/libs/swr';
import { chatToolKeys } from '@/libs/swr/keys';
import { fileService } from '@/services/file';
-import { pythonService } from '@/services/python';
import { dbMessageSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
import { useFileStore } from '@/store/file';
@@ -92,12 +91,16 @@ export class ChatCodeInterpreterActionImpl {
}
}
+ // Imported here rather than at module scope: this slice is assembled into the
+ // chat store, so a static import puts Pyodide and Comlink in the bundle every
+ // chat page loads, for a tool most sessions never invoke.
+ const { pythonService } = await import('@/services/python');
const result = await pythonService.runPython(params.code, params.packages, files);
// Complete interpreter operation
this.#get().completeOperation(interpreterOpId);
- if (result?.files) {
+ if (result.files) {
await this.#get().optimisticUpdateMessageContent(
id,
JSON.stringify(result),