π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π₯ refactor(chat): remove orphaned browser Pyodide code-interpreter slice (#20181)
Arvin Xu3c9bac716d5d
diff --git a/packages/types/src/tool/index.ts b/packages/types/src/tool/index.tsindex b65531765fb..fcf0690a02d 100644--- a/packages/types/src/tool/index.ts+++ b/packages/types/src/tool/index.ts@@ -25,7 +25,6 @@ export type LobeToolRenderType = ToolManifestType;export * from './builtin';export * from './crawler';export * from './error';-export * from './interpreter';export * from './intervention';export * from './manifest';export * from './plugin';diff --git a/packages/types/src/tool/interpreter.ts b/packages/types/src/tool/interpreter.tsdeleted file mode 100644index cd62395645e..00000000000--- a/packages/types/src/tool/interpreter.ts+++ /dev/null@@ -1,30 +0,0 @@-export interface CodeInterpreterParams {- code: string;- packages: string[];-}--export interface CodeInterpreterFileItem {- data?: File;- fileId?: string;- filename: string;- previewUrl?: string;-}--export interface PythonOutput {- data: string;- type: 'stdout' | 'stderr';-}--export interface PythonResult {- output?: PythonOutput[];- result?: string;- success: boolean;-}--export interface CodeInterpreterResponse extends PythonResult {- files?: CodeInterpreterFileItem[];-}--export interface CodeInterpreterState {- error?: any;-}diff --git a/src/features/Conversation/utils/operationActivity.test.ts b/src/features/Conversation/utils/operationActivity.test.tsindex 6d753554d06..5e6c7ee918e 100644--- a/src/features/Conversation/utils/operationActivity.test.ts+++ b/src/features/Conversation/utils/operationActivity.test.ts@@ -12,7 +12,6 @@ describe('resolveOperationActivity', () => {'createToolMessage','pluginApi','builtinToolSearch',- 'builtinToolInterpreter','builtinToolPageAgent',];for (const type of toolOps) {diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex eeb2e6cadf8..c0660e04e85 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -594,7 +594,7 @@ export const serverConfigKeys = {// ---- discover (marketplace) ---------------------------------------------// NOTE: discover/eval/ragEval/knowledgeBase/device/userMemory/agentKnowledge/-// agentBot/file/chatTool prefixes are deliberately kept OUT of `CACHE_TIERS`+// agentBot/file prefixes are deliberately kept OUT of `CACHE_TIERS`// (see localStorageProvider.ts) so this key-convergence introduces no new// persistence β they stay memory-only exactly as before.export const discoverKeys = {@@ -1045,11 +1045,6 @@ export const fileKeys = {ttsFile: def('file:ttsFile', (messageId: string) => ['file:ttsFile', messageId]),};-// ---- chat tools ----------------------------------------------------------export const chatToolKeys = {- interpreterFile: def('chat:interpreterFile', (id: string) => ['chat:interpreterFile', id]),-};-// =========================================================================// UI-layer keys (features / routes / components). Prefixes below stay// memory-only unless explicitly listed in `CACHE_TIERS`. Names avoid colliding@@ -1548,7 +1543,6 @@ export const swrKeys = {brief: briefKeys,builtinAgent: builtinAgentKeys,changelog: changelogKeys,- chatTool: chatToolKeys,cron: cronKeys,device: deviceKeys,discover: discoverKeys,diff --git a/src/services/__tests__/python.test.ts b/src/services/__tests__/python.test.tsdeleted file mode 100644index 23c4eceb2e7..00000000000--- a/src/services/__tests__/python.test.ts+++ /dev/null@@ -1,63 +0,0 @@-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(function () {- return 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.tsdeleted file mode 100644index c78b9585954..00000000000--- a/src/services/python.ts+++ /dev/null@@ -1,38 +0,0 @@-import { getPythonInterpreter } from '@lobechat/python-interpreter';-import { type CodeInterpreterResponse } from '@lobechat/types';--import { pythonEnv } from '@/envs/python';--class PythonService {- async runPython(- code: string,- packages: string[],- files: File[],- ): 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!,- });- await interpreter.init();- await interpreter.installPackages(packages.filter((p) => p !== ''));- await interpreter.uploadFiles(files);-- const result = await interpreter.runPython(code);-- const resultFiles = await interpreter.downloadFiles();- return {- files: resultFiles.map((file) => ({- data: file,- filename: file.name,- previewUrl: URL.createObjectURL(file),- })),- ...result,- };- }-}--export const pythonService = new PythonService();diff --git a/src/store/chat/slices/builtinTool/actions/index.ts b/src/store/chat/slices/builtinTool/actions/index.tsindex 2c0440a5b18..9a5c46d74a9 100644--- a/src/store/chat/slices/builtinTool/actions/index.ts+++ b/src/store/chat/slices/builtinTool/actions/index.ts@@ -3,12 +3,10 @@ import { type StateCreator } from 'zustand/vanilla';import { type ChatStore } from '@/store/chat/store';import { flattenActions } from '@/store/utils/flattenActions';-import { type ChatCodeInterpreterAction } from './interpreter';-import { ChatCodeInterpreterActionImpl } from './interpreter';import { type SearchAction } from './search';import { SearchActionImpl } from './search';-export type ChatBuiltinToolAction = SearchAction & ChatCodeInterpreterAction;+export type ChatBuiltinToolAction = SearchAction;export const chatToolSlice: StateCreator<ChatStore,@@ -19,8 +17,4 @@ export const chatToolSlice: StateCreator<...params: Parameters<StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatBuiltinToolAction>>-) =>- flattenActions<ChatBuiltinToolAction>([- new SearchActionImpl(...params),- new ChatCodeInterpreterActionImpl(...params),- ]);+) => flattenActions<ChatBuiltinToolAction>([new SearchActionImpl(...params)]);diff --git a/src/store/chat/slices/builtinTool/actions/interpreter.ts b/src/store/chat/slices/builtinTool/actions/interpreter.tsdeleted file mode 100644index eb0ac6e5fd9..00000000000--- a/src/store/chat/slices/builtinTool/actions/interpreter.ts+++ /dev/null@@ -1,222 +0,0 @@-import { CloudSandboxIdentifier } from '@lobechat/builtin-tool-cloud-sandbox';-import {- type CodeInterpreterFileItem,- type CodeInterpreterParams,- type CodeInterpreterResponse,-} from '@lobechat/types';-import debug from 'debug';-import { produce } from 'immer';-import pMap from 'p-map';-import { type SWRResponse } from 'swr';--import { useClientDataSWR } from '@/libs/swr';-import { chatToolKeys } from '@/libs/swr/keys';-import { fileService } from '@/services/file';-import { dbMessageSelectors } from '@/store/chat/selectors';-import { type ChatStore } from '@/store/chat/store';-import { useFileStore } from '@/store/file';-import { type StoreSetter } from '@/store/types';-import { setNamespace } from '@/utils/storeDebug';--const n = setNamespace('codeInterpreter');-const log = debug('lobe-store:builtin-tool');--type Setter = StoreSetter<ChatStore>;-export const codeInterpreterSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>- new ChatCodeInterpreterActionImpl(set, get, _api);--export class ChatCodeInterpreterActionImpl {- readonly #get: () => ChatStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => ChatStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- python = async (id: string, params: CodeInterpreterParams): Promise<boolean | undefined> => {- // Get parent operationId from messageOperationMap (should be executeToolCall)- const parentOperationId = this.#get().messageOperationMap[id];-- // Create child operation for interpreter execution- // Auto-associates message with this operation via messageId in context- const { operationId: interpreterOpId, abortController } = this.#get().startOperation({- context: {- messageId: id,- },- metadata: {- startTime: Date.now(),- },- parentOperationId,- type: 'builtinToolInterpreter',- });-- log(- '[python] messageId=%s, parentOpId=%s, interpreterOpId=%s, aborted=%s',- id,- parentOperationId,- interpreterOpId,- abortController.signal.aborted,- );-- const context = { operationId: interpreterOpId };-- try {- // TODO: should only download files used by the AI- const files: File[] = [];- for (const message of dbMessageSelectors.dbUserMessages(this.#get())) {- for (const file of message.fileList ?? []) {- // Tombstoned attachment (viewer lost access) β no url to download.- if (file.inaccessible) continue;- const blob = await fetch(file.url).then((res) => res.blob());- files.push(new File([blob], file.name));- }- for (const image of message.imageList ?? []) {- const blob = await fetch(image.url).then((res) => res.blob());- files.push(new File([blob], image.alt));- }- for (const tool of message.tools ?? []) {- if (tool.identifier === CloudSandboxIdentifier) {- const message = dbMessageSelectors.getDbMessageByToolCallId(tool.id)(this.#get());- if (message?.content) {- const content = JSON.parse(message.content) as CodeInterpreterResponse;- for (const file of content.files ?? []) {- const item = await fileService.getFile(file.fileId!);- const blob = await fetch(item.url).then((res) => res.blob());- files.push(new File([blob], file.filename));- }- }- }- }- }-- // 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) {- await this.#get().optimisticUpdateMessageContent(- id,- JSON.stringify(result),- undefined,- context,- );- await this.#get().uploadInterpreterFiles(id, result.files);- } else {- await this.#get().optimisticUpdateMessageContent(- id,- JSON.stringify(result),- undefined,- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- log('[python] Error: messageId=%s, error=%s', id, err.message);-- // Check if it's an abort error- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- log('[python] Request aborted: messageId=%s', id);- // Fail interpreter operation for abort- this.#get().failOperation(interpreterOpId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- // Don't update error message for user aborts- return;- }-- // Fail interpreter operation for other errors- this.#get().failOperation(interpreterOpId, {- message: err.message,- type: 'PluginServerError',- });-- // For other errors, update message- await this.#get().optimisticUpdatePluginState(id, { error }, context);- // If an error occurred during the call, do not trigger the AI message- return;- }- };-- updateInterpreterFileItem = async (- id: string,- updater: (data: CodeInterpreterResponse) => void,- ): Promise<void> => {- const message = dbMessageSelectors.getDbMessageById(id)(this.#get());- if (!message) return;-- const result: CodeInterpreterResponse = JSON.parse(message.content);- if (!result.files) return;-- const nextResult = produce(result, updater);-- await this.#get().optimisticUpdateMessageContent(id, JSON.stringify(nextResult));- };-- uploadInterpreterFiles = async (id: string, files: CodeInterpreterFileItem[]): Promise<void> => {- const { updateInterpreterFileItem } = this.#get();-- if (!files) return;-- await pMap(files, async (file, index) => {- if (!file.data) return;-- try {- const uploadResult = await useFileStore.getState().uploadWithProgress({- file: file.data,- skipCheckFileType: true,- });-- if (uploadResult?.id) {- await updateInterpreterFileItem(id, (draft) => {- if (draft.files?.[index]) {- draft.files[index].fileId = uploadResult.id;- draft.files[index].previewUrl = undefined;- draft.files[index].data = undefined;- }- });- }- } catch (error) {- console.error('Failed to upload CodeInterpreter file:', error);- }- });- };-- useFetchInterpreterFileItem = (id?: string): SWRResponse => {- return useClientDataSWR(id ? chatToolKeys.interpreterFile(id) : null, async () => {- if (!id) return null;-- const item = await fileService.getFile(id);-- this.#set(- produce((draft) => {- if (!draft.codeInterpreterFileMap) {- draft.codeInterpreterFileMap = {};- }- if (draft.codeInterpreterFileMap[id]) return;-- draft.codeInterpreterFileMap[id] = item;- }),- false,- n('useFetchInterpreterFileItem'),- );-- return item;- });- };-}--export type ChatCodeInterpreterAction = Pick<- ChatCodeInterpreterActionImpl,- keyof ChatCodeInterpreterActionImpl->;diff --git a/src/store/chat/slices/builtinTool/initialState.ts b/src/store/chat/slices/builtinTool/initialState.tsindex 7955b48a26b..7790c80291f 100644--- a/src/store/chat/slices/builtinTool/initialState.ts+++ b/src/store/chat/slices/builtinTool/initialState.ts@@ -1,12 +1,5 @@-import { type FileItem } from '@/types/files';-export interface ChatToolState {activePageContentUrl?: string;- codeInterpreterFileMap: Record<string, FileItem>;- codeInterpreterImageMap: Record<string, FileItem>;}-export const initialToolState: ChatToolState = {- codeInterpreterFileMap: {},- codeInterpreterImageMap: {},-};+export const initialToolState: ChatToolState = {};diff --git a/src/store/chat/slices/builtinTool/selectors.test.ts b/src/store/chat/slices/builtinTool/selectors.test.tsindex fafed4f1175..2ef7d406cd9 100644--- a/src/store/chat/slices/builtinTool/selectors.test.ts+++ b/src/store/chat/slices/builtinTool/selectors.test.ts@@ -10,69 +10,6 @@ describe('chatToolSelectors', () => {useChatStore.setState(useChatStore.getInitialState());});- describe('isInterpreterExecuting', () => {- it('should return true when interpreter is executing for message', () => {- const { result } = renderHook(() => useChatStore());-- let opId: string;-- act(() => {- opId = result.current.startOperation({- type: 'builtinToolInterpreter',- context: { sessionId: 'session1', messageId: 'msg1' },- }).operationId;-- result.current.associateMessageWithOperation('msg1', opId);- });-- expect(chatToolSelectors.isInterpreterExecuting('msg1')(result.current)).toBe(true);- });-- it('should return false when no operation exists for message', () => {- const { result } = renderHook(() => useChatStore());-- expect(chatToolSelectors.isInterpreterExecuting('msg1')(result.current)).toBe(false);- });-- it('should return false when operation is not builtinToolInterpreter', () => {- const { result } = renderHook(() => useChatStore());-- let opId: string;-- act(() => {- opId = result.current.startOperation({- type: 'execAgentRuntime',- context: { sessionId: 'session1', messageId: 'msg1' },- }).operationId;-- result.current.associateMessageWithOperation('msg1', opId);- });-- expect(chatToolSelectors.isInterpreterExecuting('msg1')(result.current)).toBe(false);- });-- it('should return false when operation is completed', () => {- const { result } = renderHook(() => useChatStore());-- let opId: string;-- act(() => {- opId = result.current.startOperation({- type: 'builtinToolInterpreter',- context: { sessionId: 'session1', messageId: 'msg1' },- }).operationId;-- result.current.associateMessageWithOperation('msg1', opId);- });-- act(() => {- result.current.completeOperation(opId);- });-- expect(chatToolSelectors.isInterpreterExecuting('msg1')(result.current)).toBe(false);- });- });-describe('isSearXNGSearching', () => {it('should return true when SearXNG search is running for message', () => {const { result } = renderHook(() => useChatStore());@@ -104,7 +41,7 @@ describe('chatToolSelectors', () => {act(() => {opId = result.current.startOperation({- type: 'builtinToolInterpreter',+ type: 'builtinToolLocalSystem',context: { sessionId: 'session1', messageId: 'msg1' },}).operationId;diff --git a/src/store/chat/slices/builtinTool/selectors.ts b/src/store/chat/slices/builtinTool/selectors.tsindex 0b3a12101ce..9e559b573c2 100644--- a/src/store/chat/slices/builtinTool/selectors.ts+++ b/src/store/chat/slices/builtinTool/selectors.ts@@ -1,14 +1,5 @@import { type ChatStoreState } from '@/store/chat';-const isInterpreterExecuting = (id: string) => (s: ChatStoreState) => {- // Check if there's a running builtinToolInterpreter operation for this message- const operationId = s.messageOperationMap[id];- if (!operationId) return false;-- const operation = s.operations[operationId];- return operation?.type === 'builtinToolInterpreter' && operation?.status === 'running';-};-const isSearXNGSearching = (id: string) => (s: ChatStoreState) => {// Check if there's a running builtinToolSearch operation for this messageconst operationId = s.messageOperationMap[id];@@ -28,7 +19,6 @@ const isSearchingLocalFiles = (id: string) => (s: ChatStoreState) => {};export const chatToolSelectors = {- isInterpreterExecuting,isSearXNGSearching,isSearchingLocalFiles,};diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex bce8b0d2607..4587c8add9e 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -51,7 +51,6 @@ export type OperationType =// === (sub-operations of executeToolCall) ===| 'pluginApi' // Plugin API call| 'builtinToolSearch' // Builtin tool: search- | 'builtinToolInterpreter' // Builtin tool: code interpreter| 'builtinToolLocalSystem' // Builtin tool: local system| 'builtinToolKnowledgeBase' // Builtin tool: knowledge base| 'builtinToolMemory' // Builtin tool: user memory