Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Remove code snippets interactivity
Tomas Valentabd22d9a58959
diff --git a/apps/docs/package.json b/apps/docs/package.jsonindex 94a90f6e3..69c80a43e 100644--- a/apps/docs/package.json+++ b/apps/docs/package.json@@ -34,7 +34,6 @@"autoprefixer": "^10.4.7","class-variance-authority": "^0.7.0","clsx": "^1.2.1",- "e2b": "^0.12.5","fast-glob": "^3.3.0","flexsearch": "^0.7.31","framer-motion": "7.8.1",diff --git a/apps/docs/src/components/Code.tsx b/apps/docs/src/components/Code.tsxindex d18169a08..013547db7 100644--- a/apps/docs/src/components/Code.tsx+++ b/apps/docs/src/components/Code.tsx@@ -1,23 +1,17 @@'use client'+import Image from 'next/image'-import { Children, createContext, isValidElement, useContext, useEffect, useReducer, useRef, useState } from 'react'+import { Children, createContext, isValidElement, useContext, useEffect, useRef, useState } from 'react'import { Tab } from '@headlessui/react'import clsx from 'clsx'import { create } from 'zustand'import {- LoaderIcon,- PlayIcon,File,Terminal,} from 'lucide-react'import { CopyButton } from '@/components/CopyButton'-import { useApiKey } from '@/utils/useUser'-import { ProcessMessage } from 'e2b'-import { useSandboxStore } from '@/utils/useSandbox'-import { useSignIn } from '@/utils/useSignIn'-import { LangShort, languageNames, mdLangToLangShort } from '@/utils/consts'-import { usePostHog } from 'posthog-js/react'+import { LangShort, languageNames } from '@/utils/consts'import logoNode from '@/images/logos/node.svg'import logoPython from '@/images/logos/python.svg'@@ -40,112 +34,15 @@ export function getPanelTitle({function CodePanel({children,code,- lang,- isRunnable = true,}: {children: React.ReactNode;code?: string;lang?: LangShort;isRunnable?: boolean;}) {- const signIn = useSignIn()- const apiKey = useApiKey()- const posthog = usePostHog()-- const codeGroupContext = useContext(CodeGroupContext)-- const sandboxDef = useSandboxStore((s) => s.sandbox)- const initSandbox = useSandboxStore((s) => s.initSandbox)- const { outputLines, dispatch } = useOutputReducer()- const [isRunning, setIsRunning] = useState(false)-- function appendOutput(out: ProcessMessage) {- dispatch({ type: 'push', payload: out.line })- }-- function filterAndMaybeAppendOutput(out: ProcessMessage) {- if (out.line.includes('Cannot refresh sandbox')) return- if (out.line.includes('Trying to reconnect')) return- console.log(`⚠️ Sandbox stderr ${out.line}`)- // appendOutput(out) // TODO: Reconsider logging to console after making the runs more stable- }-- function handleSandboxCreationError(err: Error) {- console.error(err)- setIsRunning(false)- dispatch({ type: 'clear' })- }-- async function onRun() {- if (!apiKey) {- window.alert('You need to sign in to run code snippets')- void signIn()- return- }- dispatch({ type: 'clear' })- setIsRunning(true)- posthog?.capture('run code snippet', {- language: lang,- snippetPath: codeGroupContext?.path ?? 'unknown snippet',- })-- let sandbox = sandboxDef?.sandbox- try {- if (!sandbox) {- if (sandboxDef?.promise) {- console.log('Sandbox is still being created, waiting...')- sandbox = await sandboxDef.promise- } else {- console.log('Sandbox not ready yet, creating...')- sandbox = await initSandbox(apiKey)- }- }- } catch (err) {- handleSandboxCreationError(err)- return- }-- if (!sandbox) {- console.warn(- 'This should not happen, sandbox is null, debug & fix properly later',- )- setIsRunning(false)- return- }-- let runtime = `E2B_API_KEY=${apiKey}`- if (lang === LangShort.js) {- runtime += ' node'- const filename = '/code/index.js'- await sandbox.filesystem.write(filename, code)- sandbox.process.start({- cmd: `${runtime} ${filename}`,- onStdout: appendOutput,- onStderr: filterAndMaybeAppendOutput,- onExit: () => setIsRunning(false), // TODO: Inspect why it's exiting so late- })- } else if (lang === LangShort.py) {- runtime += ' python3'- const filename = '/main.py'- await sandbox.filesystem.write(filename, code)- sandbox.process.start({- cmd: `${runtime} ${filename}`,- cwd: '/code',- onStdout: appendOutput,- onStderr: filterAndMaybeAppendOutput,- onExit: () => setIsRunning(false),- })- } else {- throw new Error('Unsupported runtime for playground')- }- }-const child = Children.only(children)if (isValidElement(child)) code = child.props.code ?? code // Get code from child if available- if (isValidElement(child)) {- // @ts-ignore- lang = mdLangToLangShort[child.props.language ?? lang] // Get lang from child if available- }+if (!code) {throw new Error('`CodePanel` requires a `code` prop, or a child with a `code` prop.',@@ -161,51 +58,9 @@ function CodePanel({top-[-40px]">- {isRunnable && (- <button- className={clsx(- `- group- flex cursor-pointer- items-center- space-x-2 rounded-md bg-transparent p-1 text-xs- transition-all- `,- isRunning && 'cursor-wait',- )}- disabled={isRunning}- onClick={onRun}- >- {isRunning ? (- <>- <span>Running</span>- <LoaderIcon- className="h-4 w-4 animate-spin text-brand-400 transition-all group-hover:text-brand-300"- strokeWidth={2.5}- />- </>- ) : (- <>- <span>Run</span>- <PlayIcon- className="h-4 w-4 text-brand-400 transition-all group-hover:text-brand-300"- strokeWidth={2.5}- />- </>- )}- </button>- )}</div><pre className="overflow-x-auto p-4 text-xs text-white">{children}</pre>- {(outputLines.length > 0 || isRunning) && (- <div className="flex max-h-[200px] flex-col items-start justify-start bg-zinc-800 px-4 py-1 font-mono">- <span className="font-mono text-xs text-zinc-500">Output</span>- <pre className="h-full w-full overflow-auto whitespace-pre text-xs text-white">- {outputLines.join('\n')}- </pre>- </div>- )}<CopyButton code={code} /></div>)@@ -435,27 +290,6 @@ export function useTabGroupProps(availableLanguages: Array<string>) {const CodeGroupContext = createContext(null)-function useOutputReducer() {- const [outputLines, dispatch] = useReducer(- (- state: string[],- action: {- type: 'push' | 'clear';- payload?: string;- },- ) => {- switch (action.type) {- case 'push':- return [...state, action.payload]- case 'clear':- return []- }- },- [],- )- return { outputLines, dispatch }-}-export function CodeGroup({children,title,diff --git a/apps/docs/src/utils/useSandbox.tsx b/apps/docs/src/utils/useSandbox.tsxdeleted file mode 100644index f63f446e9..000000000--- a/apps/docs/src/utils/useSandbox.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { Sandbox } from 'e2b'-import { create } from 'zustand'-import { docsSandboxName } from '@/utils/consts'--function log(message?: any, ...optionalParams: any[]) {- if (process.env.NODE_ENV === 'production') return- else console.log(message, optionalParams)-}--// const envIds = {-// js: 'rki5dems9wqfm4r03t7g',-// py: 'rki5dems9wqfm4r03t7g',-// }--// const preps = {-// js: 'npm init es6 -y && npm install e2b',-// py: 'pip install e2b',-// }--// TODO: Consider using immer for easier state updates-export const useSandboxStore = create<SandboxStore>((set, get) => ({- sandbox: null,- initSandbox: async (apiKey: string): Promise<Sandbox> => {- // eslint-disable-next-line no-async-promise-executor- return new Promise(async (resolve, reject) => {- const maybeExistingSandbox = get().sandbox- if (maybeExistingSandbox?.sandbox) {- log('Sandbox already ready')- resolve(maybeExistingSandbox.sandbox)- return- } else if (maybeExistingSandbox?.promise) {- log('Sandbox in progress, waiting...')- await maybeExistingSandbox.promise- resolve(maybeExistingSandbox.sandbox)- } else {- log('Sandbox creating...')- try {- const sandboxP = Sandbox.create({- id: docsSandboxName,- apiKey,- })- // set promise to store so that other calls to initSandbox will wait for this one to finish- set((state) => ({- sandbox: {- ...state.sandbox,- sandbox: null,- promise: sandboxP,- }- }))- const newSandbox = await sandboxP // await creation- log('Sandbox created')- // set sandbox to store, so it can be used instead of creating a new one- set((state) => ({- sandbox: {- ...state.sandbox,- sandbox: newSandbox,- }- }))- resolve(newSandbox) // also resolve with the new sandbox for the initSandbox caller- } catch (err) {- console.info('Sandbox creation failed:', err)- reject(err)- }- }- })- },-}))--type SandboxMeta = {- sandbox: Sandbox;- promise: Promise<Sandbox>;-}--export type SandboxStore = {- sandbox: SandboxMeta;- initSandbox: (apiKey: string) => Promise<Sandbox>;-}diff --git a/apps/docs/src/utils/useUser.tsx b/apps/docs/src/utils/useUser.tsxindex f5eb21574..0d19402ab 100644--- a/apps/docs/src/utils/useUser.tsx+++ b/apps/docs/src/utils/useUser.tsx@@ -5,7 +5,6 @@ import { User } from '@supabase/supabase-auth-helpers/react'import { createPagesBrowserClient } from '@supabase/auth-helpers-nextjs'import { type Session } from '@supabase/supabase-js'import * as Sentry from '@sentry/nextjs'-import { useSandboxStore } from '@/utils/useSandbox'type Team = {id: string@@ -46,7 +45,6 @@ export const CustomUserContextProvider = (props) => {const [error, setError] = useState(null)const [isLoading, setIsLoading] = useState(true)const mounted = useRef<boolean>(false)- const initSandbox = useSandboxStore((state) => state.initSandbox)useEffect(() => {mounted.current = true@@ -142,13 +140,6 @@ export const CustomUserContextProvider = (props) => {.in('team_id', teams?.map((team) => team.id)) // Due to RLS, we could also safely just fetch all, but let's be explicit for sureif (apiKeysError) Sentry.captureException(apiKeysError)- // as soon as we have apiKey, start initializing sandboxes, so they are ready when user want to use them- const apiKey = apiKeys?.[0]?.api_key- if (apiKey) {- // We don't care about awaiting this, we just want to start it- void initSandbox(apiKey)- }-const defaultTeamId = defaultTeam?.id // TODO: Adjust when user can be part of multiple teamsconst { data: accessToken, error: accessTokenError } = await supabasediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 233f5d763..f24938789 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -99,9 +99,6 @@ importers:clsx:specifier: ^1.2.1version: 1.2.1- e2b:- specifier: ^0.12.5- version: 0.12.5([email protected])fast-glob:specifier: ^3.3.0version: 3.3.1@@ -4856,24 +4853,6 @@ packages:utf-8-validate: 6.0.3dev: false- resolution: {integrity: sha512-cRR8lghYbOU5fifqytil3Zb85Y3vy/wBt2z+1AuDR8aswouM+xYmayV80B7fRdXaa67kmvsa2HQiV8yCSQGToQ==}- engines: {node: '>=18'}- peerDependencies:- openai: ^4.17.4- dependencies:- isomorphic-ws: 5.0.0([email protected])- normalize-path: 3.0.0- openai: 4.17.4- openapi-typescript-fetch: 1.1.3- path-browserify: 1.0.1- platform: 1.3.6- ws: 8.15.1([email protected])([email protected])- optionalDependencies:- bufferutil: 4.0.8- utf-8-validate: 6.0.3- dev: false-resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}@@ -5171,7 +5150,7 @@ packages:eslint: 8.49.0eslint-import-resolver-node: 0.3.9eslint-import-resolver-typescript: 3.6.0(@typescript-eslint/[email protected])([email protected])([email protected])([email protected])- eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected])([email protected])+ eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected])([email protected])([email protected])eslint-plugin-jsx-a11y: 6.7.1([email protected])eslint-plugin-react: 7.33.2([email protected])eslint-plugin-react-hooks: 4.6.0([email protected])@@ -5202,7 +5181,7 @@ packages:enhanced-resolve: 5.15.0eslint: 8.49.0eslint-module-utils: 2.8.0(@typescript-eslint/[email protected])([email protected])([email protected])([email protected])- eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected])([email protected])+ eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected])([email protected])([email protected])fast-glob: 3.3.1get-tsconfig: 4.7.0is-core-module: 2.13.0@@ -5244,36 +5223,7 @@ packages:- supports-colordev: true- resolution: {integrity: sha512-aWajIYfsqCKRDgUfjEXNN/JlrzauMuSEy5sbd7WXbtW3EH6A6MpwEh42c7qD+MqQo9QMJ6fWLAeIJynx0g6OAw==}- engines: {node: '>=4'}- peerDependencies:- '@typescript-eslint/parser': '*'- eslint: '*'- eslint-import-resolver-node: '*'- eslint-import-resolver-typescript: '*'- eslint-import-resolver-webpack: '*'- peerDependenciesMeta:- '@typescript-eslint/parser':- optional: true- eslint:- optional: true- eslint-import-resolver-node:- optional: true- eslint-import-resolver-typescript:- optional: true- eslint-import-resolver-webpack:- optional: true- dependencies:- '@typescript-eslint/parser': 6.7.2([email protected])([email protected])- debug: 3.2.7- eslint: 8.49.0- eslint-import-resolver-node: 0.3.9- transitivePeerDependencies:- - supports-color- dev: true-resolution: {integrity: sha512-9I9hFlITvOV55alzoKBI+K9q74kv0iKMeY6av5+umsNwayt59fz692daGyjR+oStBQgx6nwR9rXldDev3Clw+A==}engines: {node: '>=4'}peerDependencies:@@ -5283,7 +5233,7 @@ packages:'@typescript-eslint/parser':optional: truedependencies:- '@typescript-eslint/parser': 6.7.2([email protected])([email protected])+ '@typescript-eslint/parser': 6.7.2([email protected])([email protected])array-includes: 3.1.7array.prototype.findlastindex: 1.2.3array.prototype.flat: 1.3.2@@ -5292,7 +5242,7 @@ packages:doctrine: 2.1.0eslint: 8.49.0eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected])([email protected])([email protected])+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected])([email protected])([email protected])([email protected])has: 1.0.3is-core-module: 2.13.0is-glob: 4.0.3@@ -6819,7 +6769,7 @@ packages:resolution: {integrity: sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==}engines: {node: '>= 10.13.0'}dependencies:- '@types/node': 20.11.24+ '@types/node': 20.6.3merge-stream: 2.0.0supports-color: 8.1.1dev: false