Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Remove old code

Tomas Valentad3379745089f
diff --git a/apps/dashboard/components/AgentRunLogContent.tsx b/apps/dashboard/components/AgentRunLogContent.tsx
deleted file mode 100644
index 0c4f974b8..000000000
--- a/apps/dashboard/components/AgentRunLogContent.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import {
- useCallback,
- useMemo,
-} from 'react'
-import Splitter from '@devbookhq/splitter'
-import clsx from 'clsx'
-import { useRouter } from 'next/router'
-import Link from 'next/link'
-import { GithubIcon } from 'lucide-react'
-
-import { DeploymentAuthData } from 'pages/api/agent'
-import {
- LiteDeploymentLog,
-} from 'utils/agentLogs'
-import { useLocalStorage } from 'hooks/useLocalStorage'
-import useDeploymentRunLog from 'hooks/useDeploymentRunLog'
-
-import AgentRunLogDetail from './AgentRunLogDetail'
-import AgentDeploymentStepsList from './AgentDeploymentsStepsList'
-import Spinner from './Spinner'
-
-export interface Props {
- log: LiteDeploymentLog
-}
-
-function AgentRunLogContent({
- log: initialLog,
-}: Props) {
- const [splitterSizes, setSplitterSizes] = useLocalStorage('log-content-splitter', [40, 60])
- const router = useRouter()
- const selectedStepID = router.query.stepID as string
-
- const slug = router.query.slug as string
-
- const setSizes = useCallback((pairIdx: number, sizes: number[]) => {
- setSplitterSizes(sizes)
- }, [setSplitterSizes])
-
- const log = useDeploymentRunLog(initialLog)
- const selectedStep = useMemo(() => {
- return log.content?.find((c: any) => c.id === selectedStepID)
- }, [log.content, selectedStepID])
-
- const runSteps = log.content && log.content.filter((c: any) => c.type === 'Run')
- const isRunOlderThanTimeout = useMemo(() => {
- const oneHourAgo = new Date(Date.now() - (60 * 60 * 1000))
- return initialLog.created_at < oneHourAgo
- }, [initialLog.created_at])
- const isRunning = initialLog.deployments.enabled && !isRunOlderThanTimeout && runSteps.length === 1
- const pr = useMemo(() => {
- const gh = (log.deployments.auth as unknown as DeploymentAuthData).github
- return {
- url: `https://github.com/${gh.owner}/${gh.repo}/pull/${gh.pr_number}`,
- repository: `${gh.owner}/${gh.repo}`,
- prNumber: gh.pr_number,
- }
- }, [log.deployments.auth])
-
- return (
- <main className="overflow-hidden flex flex-col max-h-full flex-1 rounded-md">
- <header className="flex items-center px-4 py-3 border-b border-b-white/5 justify-between">
- <div className="flex items-center space-x-2">
- <h1 className="text-xl font-semibold text-white">Agent Run Logs</h1>
- {isRunning &&
- <div className="mt-1">
- <Spinner />
- </div>
- }
- </div>
- <div className="flex space-x-4">
- {log.deployments.secrets &&
- <span className="text-xs text-gray-500">
- Open AI API - using your own API key
- </span>
- }
- {!log.deployments.secrets &&
- <span className="text-xs text-gray-500">
- {'Open AI API - using e2b\'s API key'}
- </span>
- }
- <Link
- href={pr.url}
- target="_blank"
- rel="noreferrer"
- className="flex items-center space-x-1 text-sm text-gray-400 hover:text-white transition-all"
- >
- <GithubIcon size="16px" />
- <span>
- {pr.repository}
- </span>
- </Link>
- </div>
- </header>
- <div className="flex-1 flex space-x-2 items-start justify-start overflow-hidden my-4">
- <Splitter
- gutterClassName={clsx(
- 'bg-gray-900 hover:bg-[#6366F1] transition-all delay-75 duration-[400ms] px-0.5 rounded-sm group',
- )}
- draggerClassName={clsx(
- 'bg-gray-700 group-hover:bg-[#6366F1] transition-all delay-75 duration-[400ms] w-0.5 h-full',
- )}
- classes={['pr-2 overflow-auto', 'bg-gray-900 pl-2 pr-1']}
- initialSizes={splitterSizes}
- onResizeFinished={setSizes}
- minWidths={[120, 120]}
- >
- <AgentDeploymentStepsList
- steps={log.content as any}
- />
- <AgentRunLogDetail
- step={selectedStep}
- />
- </Splitter>
- </div>
- </main>
- )
-}
-
-export default AgentRunLogContent
diff --git a/apps/dashboard/components/Layout.tsx b/apps/dashboard/components/Layout.tsx
index 9c78d5f76..7e671bc83 100644
--- a/apps/dashboard/components/Layout.tsx
+++ b/apps/dashboard/components/Layout.tsx
@@ -65,7 +65,7 @@ function Layout({ children }: PropsWithChildren) {
const view = process.env.NEXT_PUBLIC_SHOW_UPLOADED_LOGS === '1'
const showView = router.query['view'] === 'logs' ? 'logs' : view
- const navigation = []
+ const navigation: any[] = []
// {
// name: showView === 'logs' ? 'Agent Logs' : 'Agent Deployments',
// icon: List,
diff --git a/apps/dashboard/components/RunItem.tsx b/apps/dashboard/components/RunItem.tsx
index 63e86f4ca..827525c94 100644
--- a/apps/dashboard/components/RunItem.tsx
+++ b/apps/dashboard/components/RunItem.tsx
@@ -3,7 +3,7 @@ import Link from 'next/link'
import { usePostHog } from 'posthog-js/react'
import {
FileProps,
-} from '../../../filesystem'
+} from 'filesystem'
function RunItem({
name,
diff --git a/apps/dashboard/components/SelectRepository/ExistingRepositories/RepositoriesList.tsx b/apps/dashboard/components/SelectRepository/ExistingRepositories/RepositoriesList.tsx
deleted file mode 100644
index b089c590f..000000000
--- a/apps/dashboard/components/SelectRepository/ExistingRepositories/RepositoriesList.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import {
- Github,
-} from 'lucide-react'
-
-import { Repos, RepoSetup } from 'utils/repoSetup'
-
-export interface Props {
- repos: Repos
- onRepoSelection: (repo: RepoSetup) => void
-}
-
-function RepositoriesList({
- repos,
- onRepoSelection,
-}: Props) {
- return (
- <ul role="list" className="w-full overflow-auto divide-y divide-gray-700">
- {repos?.map((r) => (
- <li key={r.id} className="px-2 flex items-center justify-between h-[60px]">
- <div className="flex flex-col items-start justify-start">
- <div className="flex items-center space-x-1">
- <Github color="#fff" size={14} />
- <p className="text-xs leading-6 text-white">{r.owner.login}</p>
- <p className="text-xs text-white">/</p>
- <p className="text-sm font-semibold leading-6 text-white">{r.name}</p>
- </div>
- {r.language && (
- <p className="text-xs leading-6 text-gray-400">{r.language}</p>
- )}
- </div>
- <button
- type="button"
- className="rounded bg-white/10 px-2 py-1 text-sm font-medium text-white shadow-sm hover:bg-white/20"
- onClick={() => onRepoSelection({
- installationID: r.installation_id,
- defaultBranch: r.default_branch,
- fullName: r.full_name,
- owner: r.owner.login,
- repo: r.name,
- repositoryID: r.id,
- url: r.url,
- })}
- >
- Select
- </button>
- </li>
- ))}
- </ul>
- )
-}
-
-export default RepositoriesList
\ No newline at end of file
diff --git a/apps/dashboard/components/SelectRepository/ExistingRepositories/index.tsx b/apps/dashboard/components/SelectRepository/ExistingRepositories/index.tsx
deleted file mode 100644
index 984371d05..000000000
--- a/apps/dashboard/components/SelectRepository/ExistingRepositories/index.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import clsx from 'clsx'
-
-import ConfigureGitHubButton from 'components/ConfigureGitHubButton'
-import SpinnerIcon from 'components/Spinner'
-import { RepoSetup, Repos } from 'utils/repoSetup'
-
-import RepositoriesList from './RepositoriesList'
-
-export interface Props {
- accessToken?: string
- repos?: Repos
- onConfigureGitHubAppClick: (e: any) => void
- onRepoSelection: (repo: RepoSetup) => void
-}
-
-function ExistingRepositories({
- accessToken,
- repos,
- onConfigureGitHubAppClick,
- onRepoSelection,
-}: Props) {
-
- return (
- <div className={clsx(
- repos && repos.length > 0 ? 'justify-start' : 'justify-center',
- 'overflow-hidden flex-1 flex flex-col items-center border border-gray-700 rounded-md'
- )}>
- {!accessToken && (
- <ConfigureGitHubButton
- onClick={onConfigureGitHubAppClick}
- />
- )}
-
- {accessToken && (
- <>
- {!repos && (
- <div className="flex justify-center">
- <SpinnerIcon className="text-slate-400" />
- </div>
- )}
- {repos && repos.length === 0 && (
- <>
- <span className="mb-2 text-sm text-gray-400 font-semibold">
- No connected repositories found
- </span>
- <ConfigureGitHubButton
- onClick={onConfigureGitHubAppClick}
- />
- </>
- )}
- {repos && repos.length > 0 && (
- <RepositoriesList
- repos={repos.sort((a, b) => (new Date(b.updated_at || b.created_at!) as any) - (new Date(a.updated_at || b.created_at!) as any))}
- onRepoSelection={onRepoSelection}
- />
- )}
- </>
- )}
- </div>
- )
-}
-
-export default ExistingRepositories
\ No newline at end of file
diff --git a/apps/dashboard/components/SelectRepository/NewRepository/PermissionsModal.tsx b/apps/dashboard/components/SelectRepository/NewRepository/PermissionsModal.tsx
deleted file mode 100644
index 19eb1c9a3..000000000
--- a/apps/dashboard/components/SelectRepository/NewRepository/PermissionsModal.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { Fragment, useState } from 'react'
-
-import { Dialog, Transition } from '@headlessui/react'
-
-function PermissionsModal() {
- const [open, setOpen] = useState(true)
-
- return (
- <Transition.Root show={open} as={Fragment}>
- <Dialog as="div" className="relative z-10" onClose={setOpen}>
- <Transition.Child
- as={Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0"
- enterTo="opacity-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
- >
- <div className="fixed inset-0 bg-gray-500/75 transition-opacity" />
- </Transition.Child>
-
- <div className="fixed inset-0 z-10 overflow-y-auto">
- <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
- <Transition.Child
- as={Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- enterTo="opacity-100 translate-y-0 sm:scale-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100 translate-y-0 sm:scale-100"
- leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- >
- <Dialog.Panel className="relative overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-sm sm:p-6">
- <div>
- <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
- <span>icon</span>
- {/* <CheckIcon className="h-6 w-6 text-green-600" aria-hidden="true" /> */}
- </div>
- <div className="mt-3 text-center sm:mt-5">
- <Dialog.Title as="h3" className="text-base font-semibold leading-6 text-gray-900">
- Payment successful
- </Dialog.Title>
- <div className="mt-2">
- <p className="text-sm text-gray-500">
- Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur amet labore.
- </p>
- </div>
- </div>
- </div>
- <div className="mt-5 sm:mt-6">
- <button
- type="button"
- className="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
- onClick={() => setOpen(false)}
- >
- Go back to dashboard
- </button>
- </div>
- </Dialog.Panel>
- </Transition.Child>
- </div>
- </div>
- </Dialog>
- </Transition.Root>
- )
-}
-
-export default PermissionsModal
\ No newline at end of file
diff --git a/apps/dashboard/components/SelectRepository/NewRepository/RepoAccountSelect.tsx b/apps/dashboard/components/SelectRepository/NewRepository/RepoAccountSelect.tsx
deleted file mode 100644
index 455483d28..000000000
--- a/apps/dashboard/components/SelectRepository/NewRepository/RepoAccountSelect.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import {
- Fragment,
-} from 'react'
-import { Listbox, Transition } from '@headlessui/react'
-import clsx from 'clsx'
-import {
- ChevronsUpDown,
- Check,
- Github,
- Plus,
-} from 'lucide-react'
-
-import { GitHubAccount } from 'utils/github'
-
-export interface Props {
- accounts: GitHubAccount[]
- selectedAccount: GitHubAccount | null
- onSelectedAccountChange: (account: GitHubAccount) => void
- onAddGithubAccountClick: () => void
-}
-
-function RepoAccountSelect({
- accounts,
- selectedAccount,
- onSelectedAccountChange,
- onAddGithubAccountClick,
-}: Props) {
- return (
- <Listbox value={selectedAccount} onChange={onSelectedAccountChange}>
- {({ open }) => (
- <div className="w-full">
- <Listbox.Label className="block text-sm font-medium leading-6 text-gray-400">Account</Listbox.Label>
- <div className="relative mt-2">
- <Listbox.Button
- className={clsx(
- open ? 'ring-gray-300' : 'ring-gray-400',
- 'relative w-full cursor-pointer rounded-md bg-transparent py-1.5 pl-3 pr-10 text-left text-gray-100 shadow-sm ring-1 ring-inset hover:ring-gray-300 focus:outline-none sm:text-sm sm:leading-6 transition-all'
- )
- }>
- <div className="flex items-center space-x-2">
- <Github size={14} />
- <span className="block truncate">{selectedAccount?.name}</span>
- </div>
- <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
- <ChevronsUpDown size={16} className="text-gray-400" aria-hidden="true" />
- </span>
- </Listbox.Button>
-
- <Transition
- show={open}
- as={Fragment}
- leave="transition ease-in duration-100"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
- >
- <Listbox.Options
- className="p-2 absolute mt-1 max-h-60 w-full overflow-auto rounded-md bg-gray-800 text-base shadow-lg border border-gray-400 focus:outline-none sm:text-sm"
- >
- {accounts.map((acc) => (
- <Listbox.Option
- key={acc.name}
- className={({ active }) =>
- clsx(
- active ? 'bg-gray-700' : '',
- 'rounded-md relative cursor-pointer select-none py-2 pl-3 pr-9 text-gray-100'
- )
- }
- value={acc}
- >
- {({ selected, active }) => (
- <div className="flex items-center space-x-2">
- <Github size={14} />
- <span className={clsx(selected ? 'font-semibold' : 'font-normal', 'block truncate')}>
- {acc.name}
- </span>
-
- {selected ? (
- <span
- className="absolute inset-y-0 right-0 flex items-center pr-4 text-gray-100"
- >
- <Check size={16} aria-hidden="true" />
- </span>
- ) : null}
- </div>
- )}
- </Listbox.Option>
- ))}
- <button
- className="w-full rounded-md flex items-center space-x-2 py-2 px-3 cursor-pointer text-gray-100 hover:bg-gray-700"
- onClick={onAddGithubAccountClick}
- >
- <Plus size={14} />
- <span>Add GitHub Account</span>
- </button>
- </Listbox.Options>
- </Transition>
- </div>
- </div>
- )
- }
- </Listbox >
- )
-}
-
-export default RepoAccountSelect
\ No newline at end of file
diff --git a/apps/dashboard/components/SelectRepository/NewRepository/RepoNameInput.tsx b/apps/dashboard/components/SelectRepository/NewRepository/RepoNameInput.tsx
deleted file mode 100644
index 15d9bf405..000000000
--- a/apps/dashboard/components/SelectRepository/NewRepository/RepoNameInput.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-export interface Props {
- value: string
- onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
-}
-
-function RepoNameInput({
- value,
- onChange,
-}: Props) {
-
- return (
- <div className="w-full">
- <label className="text-sm font-medium leading-6 text-gray-400">
- Repository Name
- </label>
- <div className="mt-2">
- <input
- className="bg-gray-800 block w-full rounded-md border-0 px-3 py-1.5 text-gray-100 shadow-sm ring-1 ring-inset ring-gray-400 placeholder:text-gray-400 focus:ring-gray-300 outline-none sm:text-sm sm:leading-6 transition-all"
- placeholder="new-repo-name"
- value={value}
- onChange={onChange}
- />
- </div>
- </div>
- )
-}
-
-export default RepoNameInput
\ No newline at end of file
diff --git a/apps/dashboard/components/SelectRepository/NewRepository/index.tsx b/apps/dashboard/components/SelectRepository/NewRepository/index.tsx
deleted file mode 100644
index 9f71fddb3..000000000
--- a/apps/dashboard/components/SelectRepository/NewRepository/index.tsx
+++ /dev/null
@@ -1,150 +0,0 @@
-import {
- useEffect,
- useReducer,
-} from 'react'
-import clsx from 'clsx'
-import { usePostHog } from 'posthog-js/react'
-
-import ConfigureGitHubButton from 'components/ConfigureGitHubButton'
-import AlertError from 'components/AlertError'
-import {
- configureGitHubApp,
- GitHubAccount,
-} from 'utils/github'
-import { useGitHubClient } from 'hooks/useGitHubClient'
-import SpinnerIcon from 'components/Spinner'
-import { createRepo } from 'github/repo'
-import { RepoSetup } from 'utils/repoSetup'
-
-import RepoAccountSelect from './RepoAccountSelect'
-import RepoNameInput from './RepoNameInput'
-import PermissionsModal from './PermissionsModal'
-import {
- creationReducer,
- ActionType,
-} from './newRepoState'
-
-export interface Props {
- accessToken?: string
- accounts: GitHubAccount[]
- onConfigureGitHubAppClick: (e: any) => void
- onRepoSelection: (repo: RepoSetup) => void
-}
-
-function NewRepository({
- accessToken,
- accounts,
- onConfigureGitHubAppClick,
- onRepoSelection,
-}: Props) {
- const ghClient = useGitHubClient(accessToken)
- const posthog = usePostHog()
-
- const [state, dispatch] = useReducer(creationReducer, {
- name: '',
- account: null,
- isCreating: false,
- requiresPermissions: false,
- })
-
- async function handleCreateClick() {
- if (!accessToken || !ghClient) return
- if (!state.account) return
- if (!state.name) return
- if (state.isCreating) return
-
- posthog?.capture('created repository', {
- account: state.account.name,
- repository: `${state.account.name}/${state.name}`,
- })
-
- try {
- dispatch({ type: ActionType.Create, payload: {} })
- const newRepo = await createRepo({
- client: ghClient,
- org: state.account.isOrg ? state.account.name : undefined,
- name: state.name,
- })
- dispatch({ type: ActionType.Success, payload: {} })
-
- onRepoSelection({
- fullName: newRepo.full_name,
- defaultBranch: newRepo.default_branch,
- repositoryID: newRepo.id,
- owner: newRepo.owner.login,
- installationID: state.account.installationID,
- repo: newRepo.name,
- url: newRepo.url,
- })
- } catch (err: any) {
- console.error('Error creating repository', err)
- dispatch({ type: ActionType.Fail, payload: { error: err } })
- }
- }
-
- useEffect(function selectDefaultAccount() {
- if (accounts.length === 0) return
- dispatch({ type: ActionType.SelectAccount, payload: { account: accounts[0] } })
- }, [accounts])
-
- return (
- <div
- className={clsx(
- 'p-2 flex-1 flex flex-col space-y-4 items-center justify-start rounded-md',
- !accessToken && 'border border-gray-700',
- )}
- >
- {!accessToken && (
- <div className="flex-1 flex flex-col items-center justify-center">
- <span className="mb-2 text-sm text-gray-400 font-semibold text-center">
- We need access to a GitHub account to create new repositories
- </span>
- <ConfigureGitHubButton
- onClick={onConfigureGitHubAppClick}
- />
- </div>
- )}
-
- {accessToken && (
- <>
- <RepoAccountSelect
- accounts={accounts}
- selectedAccount={state.account}
- onSelectedAccountChange={acc => dispatch({ type: ActionType.SelectAccount, payload: { account: acc } })}
- onAddGithubAccountClick={configureGitHubApp}
- />
-
- <RepoNameInput
- value={state.name}
- onChange={e => dispatch({ type: ActionType.UpdateName, payload: { name: e.target.value } })}
- />
-
- <button
- className="w-8 min-w-[64px] h-[24px] min-h-[24px] flex items-center justify-center rounded bg-white/10 px-2 py-1 text-sm text-white font-medium hover:bg-white/20"
- onClick={handleCreateClick}
- >
- {state.isCreating ? (
- <SpinnerIcon />
- ) : (
- <span>Create</span>
- )}
- </button>
-
-
- {state.requiresPermissions && (
- <PermissionsModal />
- )}
-
- {state.error && (
- <AlertError
- title="Error creating repository"
- infoItems={[state.error.message]}
- />
- )}
- </>
- )}
- </div>
- )
-}
-
-export default NewRepository
diff --git a/apps/dashboard/components/SelectRepository/NewRepository/newRepoState.ts b/apps/dashboard/components/SelectRepository/NewRepository/newRepoState.ts
deleted file mode 100644
index e4f0ff109..000000000
--- a/apps/dashboard/components/SelectRepository/NewRepository/newRepoState.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { GitHubAccount } from 'utils/github'
-
-export enum ActionType {
- Initial,
- SelectAccount,
- UpdateName,
- Create,
- Fail,
- Success,
- RequestPermissions,
- SelectRepo,
-}
-
-export interface Create {
- type: ActionType.Create
- payload: {}
-}
-
-export interface Success {
- type: ActionType.Success
- payload: {}
-}
-
-export interface SelectAccount {
- type: ActionType.SelectAccount
- payload: {
- account: GitHubAccount
- }
-}
-
-export interface UpdateName {
- type: ActionType.UpdateName
- payload: {
- name: string
- }
-}
-
-export interface Fail {
- type: ActionType.Fail
- payload: {
- error: Error
- }
-}
-
-export interface RequestPermissions {
- type: ActionType.RequestPermissions
- payload: {}
-}
-
-export interface SelectRepo {
- type: ActionType.SelectRepo;
- payload: {
- repo: any
- }
-}
-
-export type Action = Create |
- Success |
- UpdateName |
- SelectAccount |
- Fail |
- RequestPermissions |
- SelectRepo
-
-export interface State {
- name: string
- account: GitHubAccount | null
- isCreating: boolean
- error?: Error
- // TODO: Maybe pass the whole repo?
- selectedRepo?: number
- requiresPermissions: boolean
-}
-
-export function creationReducer(state: State, action: Action) {
- const { type, payload } = action
- switch (type) {
- case ActionType.Create:
- return {
- ...state,
- isCreating: true,
- error: undefined,
- }
- case ActionType.Success:
- return {
- ...state,
- isCreating: false,
- }
- case ActionType.Fail:
- return {
- ...state,
- error: payload.error,
- isCreating: false,
- }
- case ActionType.UpdateName:
- return {
- ...state,
- name: payload.name,
- }
- case ActionType.SelectAccount:
- return {
- ...state,
- account: payload.account,
- }
- case ActionType.RequestPermissions:
- return {
- ...state,
- requiresPermissions: true,
- }
- case ActionType.SelectRepo:
- return {
- ...state,
- // TODO: Maybe pass the whole repo?
- selectedRepo: payload.repo,
- }
- default:
- return state
- }
-}
diff --git a/apps/dashboard/components/SelectRepository/RepoSwitch.tsx b/apps/dashboard/components/SelectRepository/RepoSwitch.tsx
deleted file mode 100644
index 9a343877f..000000000
--- a/apps/dashboard/components/SelectRepository/RepoSwitch.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import clsx from 'clsx'
-
-export interface Props {
- value: 'existing' | 'new'
- onChange: (value: 'existing' | 'new') => void
-}
-
-const baseClasses = 'text-xs font-semibold py-1 px-2 rounded-md transition-all cursor-pointer'
-const unselectedClasses = 'text-gray-500 hover:bg-indigo-400/10 hover:text-indigo-400 border border-transparent hover:border-indigo-400/20'
-const selectedClasses = 'bg-indigo-400/10 text-indigo-400 border border-indigo-400/20'
-
-function RepoSwitch({
- value,
- onChange,
-}: Props) {
- return (
- <div>
- <div className="mb-2 flex items-center justify-center space-x-2">
- <div
- className={clsx(
- baseClasses,
- value === 'new' ? selectedClasses : unselectedClasses,
- )}
- onClick={() => onChange('new')}
- >
- Create New Repository
- </div>
- <div
- className={clsx(
- baseClasses,
- value === 'existing' ? selectedClasses : unselectedClasses,
- )}
- onClick={() => onChange('existing')}
- >
- Select Existing Repository
- </div>
- </div>
- </div>
- )
-}
-
-export default RepoSwitch
diff --git a/apps/dashboard/components/SelectRepository/index.tsx b/apps/dashboard/components/SelectRepository/index.tsx
deleted file mode 100644
index a55efa018..000000000
--- a/apps/dashboard/components/SelectRepository/index.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import {
- useState,
-} from 'react'
-import {
- ArrowRight,
-} from 'lucide-react'
-import {
- useUser,
-} from '@supabase/auth-helpers-react'
-
-import {
- configureGitHubApp,
- GitHubAccount,
-} from 'utils/github'
-import SpinnerIcon from 'components/Spinner'
-import { usePostHog } from 'posthog-js/react'
-import { RepoSetup, Repos } from 'utils/repoSetup'
-
-import RepoSwitch from './RepoSwitch'
-import ExistingRepositories from './ExistingRepositories'
-import NewRepository from './NewRepository'
-
-export interface Props {
- repos?: Repos
- accessToken?: string
- onRepoSelection: (repo: RepoSetup) => void
- githubAccounts: GitHubAccount[]
-}
-
-function SelectRepository({
- repos,
- accessToken,
- onRepoSelection,
- githubAccounts,
-}: Props) {
- const [selected, setSelected] = useState<'existing' | 'new'>('new')
- const user = useUser()
- const posthog = usePostHog()
-
- function configure() {
- posthog?.capture('started github app configuration')
- configureGitHubApp()
- }
-
- function selectRepo(repo: RepoSetup) {
- if (selected === 'new') {
- posthog?.capture('created new repository', {
- repository: repo.fullName,
- })
- } else if (selected === 'existing') {
- posthog?.capture('selected existing repository', {
- repository: repo.fullName,
- })
- }
-
- onRepoSelection(repo)
- }
-
- return (
- <>
- <h2 className="text-3xl font-bold tracking-tight sm:text-4xl">
- Deploy <a className="text-indigo-400 hover:text-indigo-500 transition-all" href="https://github.com/smol-ai/developer" target="_blank" rel="noreferrer noopener">Smol Developer</a>
- </h2>
- <p className="mt-2 mb-6 text-lg leading-8 text-gray-400">
- Select a git repository to which you want to give the AI agent access.
- </p>
-
- {!user && (
- <div className="
- flex
- justify-center
- ">
- <SpinnerIcon className="text-slate-400" />
- </div>
- )}
-
- {user && (
- <>
- <RepoSwitch
- value={selected}
- onChange={v => {
- setSelected(v)
- posthog?.capture(`selected ${v} repository tab`)
- }}
- />
- {selected === 'existing' && (
- <ExistingRepositories
- accessToken={accessToken}
- repos={repos}
- onConfigureGitHubAppClick={configure}
- onRepoSelection={selectRepo}
- />
- )}
- {selected === 'new' && (
- <NewRepository
- accounts={githubAccounts}
- accessToken={accessToken}
- onConfigureGitHubAppClick={configure}
- onRepoSelection={selectRepo}
- />
- )}
-
- <button
- type="button"
- className="flex justify-start items-center text-xs font-medium space-x-1 text-gray-400 hover:text-white transition-all mt-4 rounded-md"
- onClick={configure}
- >
- <span>Configure GitHub Permissions</span>
- <ArrowRight size={14} />
- </button>
- </>
- )}
- </>
- )
-}
-
-export default SelectRepository
diff --git a/apps/dashboard/components/Settings.tsx b/apps/dashboard/components/Settings.tsx
index 27d0342a8..fc2ded6ff 100644
--- a/apps/dashboard/components/Settings.tsx
+++ b/apps/dashboard/components/Settings.tsx
@@ -1,4 +1,4 @@
-import APIKey from './Settings/APIKey.tsx'
+import APIKey from './Settings/APIKey'
export interface Props {
@@ -14,9 +14,9 @@ function Settings({ apiKey }: Props) {
</div>
</header>
<div className="space-x-4 overflow-hidden m-4">
- <div className="text-xl font-semibold text-white">API key</div>
- <APIKey apiKey={apiKey} />
- </div>
+ <div className="text-xl font-semibold text-white">API key</div>
+ <APIKey apiKey={apiKey} />
+ </div>
</main>
)
}
diff --git a/apps/dashboard/filesystem/index.ts b/apps/dashboard/filesystem/index.ts
index 181707b8d..e8c25bdbf 100644
--- a/apps/dashboard/filesystem/index.ts
+++ b/apps/dashboard/filesystem/index.ts
@@ -9,7 +9,7 @@ import DirWrapper from '../components/DirWrapper'
export type {
Props as DirWrapperProps,
DirProps,
-} from '../apps/dashboard/components/DirWrapper'
+} from 'components/DirWrapper'
export { NodeType } from './node'
export type { Metadata } from './node'
diff --git a/apps/dashboard/github/pullRequest.ts b/apps/dashboard/github/pullRequest.ts
deleted file mode 100644
index bad51f34c..000000000
--- a/apps/dashboard/github/pullRequest.ts
+++ /dev/null
@@ -1,366 +0,0 @@
-import { Configuration, OpenAIApi } from 'openai'
-import { backOff } from 'exponential-backoff'
-
-import api from 'api-client/api'
-import { deployments, prisma } from 'db/prisma'
-
-import { GitHubClient } from './client'
-
-
-export async function prTitleFromInstructions(instructions: string, openAIKey?: string) {
- const configuration = new Configuration({
- apiKey: openAIKey || process.env.OPENAI_API_KEY,
- })
-
- const openai = new OpenAIApi(configuration)
-
- try {
- const result = await backOff(() => openai.createChatCompletion({
- model: 'gpt-3.5-turbo',
- messages: [
- {
- content: `${instructions}\n\nTl;dr in one sentence (around 50 characters) describing what to build. Don't use pronouns, just describe the thing:`,
- role: 'user',
- }
- ],
- }))
- return result.data.choices[0].message?.content
- } catch (error: any) {
- if (error.response) {
- console.log(error.response)
- throw new Error(error.response.data.error.message)
- } else {
- throw new Error(error.message)
- }
- }
-}
-
-// All PRs are also issues - GH API endpoint for issues is used for the shared functionality
-export async function createPR({
- client,
- title,
- body,
- owner,
- repo,
- defaultBranch,
- branch,
- commitMessage,
-}: {
- commitMessage: string,
- defaultBranch: string,
- client: GitHubClient,
- title: string,
- body: string,
- owner: string,
- repo: string,
- branch: string,
-}) {
- let baseBranchRefSHA: string | undefined
-
- try {
- const baseBranchRef = await client.git.getRef({
- owner,
- repo,
- ref: `heads/${defaultBranch}`,
- })
- baseBranchRefSHA = baseBranchRef.data.object.sha
- } catch (error: any) {
- // Make sure we are not overwriting an existing branch
- // and only create a new branch and init repo if the repo is empty
- if (error.message !== 'Git Repository is empty.') throw error
- console.log('Repository is empty - creating initial empty commit')
-
- // TODO: Create empty commit without placeholder file by deleting the file,
- // creating an empty commit and then updating the default branch to point to the empty commit
- // This behavious is not clearly documented and it seems that sometimes the empty commit can get automatically pruned before the ref can be updated
-
- // Create placeholder file to create the default branch
- console.log('Creating placeholder file')
- const file = await client.repos.createOrUpdateFileContents({
- owner,
- repo,
- branch: defaultBranch,
- path: 'README.md',
- message: 'Initial commit',
- content: Buffer.from(`# ${repo}`, 'utf8').toString('base64'),
- })
- console.log('Finished creating placeholder file')
-
- baseBranchRefSHA = file.data.commit.sha
- }
-
- const newBranchRef = await client.git.createRef({
- owner,
- repo,
- ref: `refs/heads/${branch}`,
- sha: baseBranchRefSHA!,
- })
-
- const currentCommit = await client.git.getCommit({
- owner,
- repo,
- commit_sha: newBranchRef.data.object.sha,
- })
-
- const newCommit = await client.git.createCommit({
- owner,
- repo,
- message: commitMessage,
- tree: currentCommit.data.tree.sha,
- parents: [currentCommit.data.sha],
- })
-
- await client.git.updateRef({
- owner,
- repo,
- ref: `heads/${branch}`,
- sha: newCommit.data.sha,
- })
-
- const pr = await client.pulls.create({
- owner,
- repo,
- head: branch,
- base: defaultBranch,
- title,
- body,
- })
-
- return {
- issueID: pr.data.id,
- number: pr.data.number,
- url: pr.data.html_url,
- }
-}
-
-export async function getPromptFromPR({
- issueNumber,
- client,
- repo,
- owner,
- body,
-}: {
- body?: string,
- owner: string,
- repo: string,
- client: GitHubClient,
- // Number identifying the issue in the repo (this is not issueID)
- issueNumber: number,
-}): Promise<string> {
-
- const [
- issueResult,
- commentsResult,
- ] = await Promise.all([
- body === undefined ? client.issues.get({
- issue_number: issueNumber,
- owner,
- repo,
- }) : Promise.resolve(undefined),
- client.issues.listComments({
- issue_number: issueNumber,
- owner,
- repo,
- // TODO: Handle pagination
- page: 1,
- per_page: 100,
- }),
- ])
-
- const prBody = issueResult?.data.body || body!
- const comments = commentsResult.data
- .filter(c => c.user?.type !== 'Bot')
- .map(c => c.body)
- .join('\n')
-
-
- // Remove everything from the prBody string after the last '---'
- // This is the separator between the PR description and the PR body
- const indexOfSeparator = prBody.lastIndexOf('---')
- const prBodyWithoutSeparator = prBody.substring(0, indexOfSeparator)
- return `${prBodyWithoutSeparator}\n\n${comments}`
-}
-
-export async function getDeploymentsForPR({
- installationID,
- issueID,
- repositoryID,
- enabled,
-}: {
- enabled: boolean | undefined,
- repositoryID: number,
- issueID: number,
- installationID: number,
-}) {
- return await prisma.deployments.findMany({
- include: {
- _count: {
- select: {
- log_files: true,
- },
- },
- projects: {
- include: {
- teams: {
- include: {
- users_teams: {
- include: {
- users: true,
- },
- },
- },
- },
- },
- },
- },
- where: {
- enabled,
- AND: [
- {
- auth: {
- path: ['github', 'repository_id'],
- equals: repositoryID,
- },
- },
- {
- auth: {
- path: ['github', 'issue_id'],
- equals: issueID,
- },
- },
- {
- auth: {
- path: ['github', 'installation_id'],
- equals: installationID,
- },
- },
- ],
- },
- })
-}
-
-export const interactWithAgent = api
- .path('/deployments/{id}/interactions')
- .method('post')
- .create()
-
-export const createAgentDeployment = api
- .path('/deployments')
- .method('put')
- .create({
- project_id: true,
- })
-
-export const disableAgentDeployment = api
- .path('/deployments/{id}')
- .method('delete')
- .create()
-
-export async function triggerSmolDevAgentRun({
- client,
- deployment,
- prompt,
- accessToken,
- commitMessage,
- slug,
- owner,
- repo,
- pullNumber,
- totalRuns,
-}: {
- totalRuns: number,
- slug: string | null,
- pullNumber: number,
- client: GitHubClient,
- owner: string,
- repo: string,
- commitMessage: string,
- deployment: deployments,
- prompt: string,
- accessToken: string,
-}) {
- if (!slug) throw new Error('slug is required')
-
- console.log('Triggering smol dev agent run:', { owner, repo, pullNumber, prompt })
- await addCommentToPR({
- body: `Started smol developer [agent run](https://app.e2b.dev/logs/${slug}-run-${totalRuns}?utm_source=github).`,
- client,
- owner,
- repo,
- pullNumber,
- })
-
- await interactWithAgent({
- id: deployment.id,
- type: 'start',
- data: {
- instructions: {
- // This provisioned access token has default expiry of 1 hour
- AccessToken: accessToken,
- CommitMessage: commitMessage,
- Prompt: prompt,
- GitHubAppName: (deployment?.auth as any)?.['github']?.['app_name'],
- GitHubAppEmail: (deployment?.auth as any)?.['github']?.['app_email'],
- Owner: owner,
- Repo: repo,
- Branch: (deployment?.auth as any)?.['github']?.['branch'],
- },
- } as any,
- })
-}
-
-export async function getGHAccessToken({
- client,
- installationID,
- repositoryID,
-}: {
- client: GitHubClient,
- installationID: number,
- repositoryID: number,
-}) {
- const result = await client.apps.createInstallationAccessToken({
- installation_id: installationID,
- repository_ids: [repositoryID],
- permissions: {
- contents: 'write',
- },
- })
-
- return result.data.token
-}
-
-export async function getGHAppInfo({
- client,
-}: {
- client: GitHubClient,
-}) {
- const result = await client.apps.getAuthenticated()
- const id = result.data.id
- const name = `${result.data.slug}[bot]`
-
- return {
- name,
- email: `${id}+${name}@users.noreply.github.com`
- }
-}
-
-export async function addCommentToPR({
- pullNumber,
- repo,
- owner,
- client,
- body,
-}: {
- pullNumber: number,
- repo: string,
- owner: string,
- client: GitHubClient,
- body: string,
-}) {
- await client.issues.createComment({
- owner,
- repo,
- issue_number: pullNumber,
- body,
- })
-}
diff --git a/apps/dashboard/github/webhooks.ts b/apps/dashboard/github/webhooks.ts
deleted file mode 100644
index 8efae450a..000000000
--- a/apps/dashboard/github/webhooks.ts
+++ /dev/null
@@ -1,381 +0,0 @@
-import type { HandlerFunction } from '@octokit/webhooks/dist-types/types'
-import {
- Webhooks,
- createNodeMiddleware,
-} from '@octokit/webhooks'
-
-import { prisma } from 'db/prisma'
-import { client as posthog } from 'utils/posthog'
-import { DeploymentAuthData } from 'pages/api/agent'
-import { smolDeveloperTemplateID } from 'utils/smolTemplates'
-
-import {
- disableAgentDeployment,
- getDeploymentsForPR,
- getGHAccessToken,
- getPromptFromPR,
- triggerSmolDevAgentRun,
-} from './pullRequest'
-import { getGHInstallationClient } from './installationClient'
-
-export async function getGitHubWebhooksMiddleware() {
- const webhooks = new Webhooks({
- secret: process.env.GITHUB_APP_WEBHOOK_SECRET!,
- })
-
- webhooks.on('issue_comment', issueCommentHandler)
- webhooks.on('pull_request.edited', pullRequestEditHandler)
- webhooks.on('pull_request.reopened', pullRequestReopenedHandler)
- webhooks.on('pull_request.closed', pullRequestClosedHandler)
-
- return createNodeMiddleware(webhooks, {
- path: '/api/github/webhook',
- log: {
- debug: console.log,
- info: console.log,
- warn: console.log,
- error: console.error,
- },
- })
-}
-
-const pullRequestReopenedHandler: HandlerFunction<'pull_request.reopened', unknown> = async (event) => {
- const { payload } = event
-
- const installationID = payload.installation?.id
- const repositoryID = payload.repository.id
-
- // Every PR is also an issues - GH API endpoint for issues is used for the shared functionality
- const issueID = payload.pull_request.id
-
- if (!installationID) {
- throw new Error('InstallationID not found')
- }
-
- const deployments = await getDeploymentsForPR({ issueID, installationID, repositoryID, enabled: undefined })
-
- if (deployments.length === 0) {
- console.log('No deployments found')
- return
- }
-
- const res = await Promise.allSettled(deployments.map(async d => {
- await prisma.deployments.update({
- where: {
- id: d.id,
- },
- data: {
- enabled: true,
- },
- })
-
- const auth: DeploymentAuthData = {
- ...d.auth as any,
- github: {
- ...(d.auth as unknown as DeploymentAuthData).github,
- pr_status: payload.pull_request.state,
- pr_merged: payload.pull_request.merged,
- pr_closed_at: payload.pull_request.closed_at,
- }
- }
-
- await prisma.deployments.update({
- where: {
- id: d.id,
- },
- data: {
- auth: auth as any,
- },
- })
-
- d
- .projects
- .teams
- .users_teams
- .map(team => team.users)
- .flat()
- .forEach(user => {
- posthog?.capture({
- distinctId: user.id,
- event: 'reopened PR created by agent',
- properties: {
- agent_deployment_id: d.id,
- agent: smolDeveloperTemplateID,
- repository: payload.repository.full_name,
- repository_url: payload.repository.html_url,
-
- pr_action: payload.action,
- pr_url: payload.pull_request.html_url,
- pr_number: payload.pull_request.number,
-
- prompt: d.last_finished_prompt,
- title: payload.pull_request.title,
- merged: payload.pull_request.merged,
- },
- })
- })
- }))
-
- await posthog?.shutdownAsync()
-
- console.log('Reopened PRs', res)
-}
-
-const pullRequestClosedHandler: HandlerFunction<'pull_request.closed', unknown> = async (event) => {
- const { payload } = event
- const installationID = payload.installation?.id
- const repositoryID = payload.repository.id
-
- // Every PR is also an issues - GH API endpoint for issues is used for the shared functionality
- const issueID = payload.pull_request.id
-
- if (!installationID) {
- throw new Error('InstallationID not found')
- }
-
- const deployments = await getDeploymentsForPR({ issueID, installationID, repositoryID, enabled: undefined })
-
- if (deployments.length === 0) {
- console.log('No deployments found')
- return
- }
-
- const res = await Promise.allSettled(deployments.map(async d => {
- await disableAgentDeployment({
- id: d.id,
- })
-
- const auth: DeploymentAuthData = {
- ...d.auth as any,
- github: {
- ...(d.auth as unknown as DeploymentAuthData).github,
- pr_status: payload.pull_request.state,
- pr_merged: payload.pull_request.merged,
- pr_closed_at: payload.pull_request.closed_at,
- }
- }
-
- await prisma.deployments.update({
- where: {
- id: d.id,
- },
- data: {
- auth: auth as any,
- },
- })
-
- d
- .projects
- .teams
- .users_teams
- .map(team => team.users)
- .flat()
- .forEach(user => {
- posthog?.capture({
- distinctId: user.id,
- event: 'closed PR created by agent',
- properties: {
- agent_deployment_id: d.id,
- agent: smolDeveloperTemplateID,
- repository: payload.repository.full_name,
- repository_url: payload.repository.html_url,
-
- pr_action: payload.action,
- pr_url: payload.pull_request.html_url,
- pr_number: payload.pull_request.number,
-
- prompt: d.last_finished_prompt,
- title: payload.pull_request.title,
- merged: payload.pull_request.merged,
- },
- })
- })
- }))
-
- await posthog?.shutdownAsync()
- console.log('Closed PRs', res)
-}
-
-const pullRequestEditHandler: HandlerFunction<'pull_request.edited', unknown> = async (event) => {
- const { payload } = event
-
- const installationID = payload.installation?.id
- const repositoryID = payload.repository.id
- const owner = payload.repository.owner.login
- const repo = payload.repository.name
-
- // Every PR is also an issues - GH API endpoint for issues is used for the shared functionality
- const issueID = payload.pull_request.id
- const issueNumber = payload.pull_request.number
- const body = payload.pull_request.body || ''
-
- if (!installationID) {
- throw new Error('InstallationID not found')
- }
-
- const client = getGHInstallationClient({ installationID })
-
- const [prompt, deployments] = await Promise.all([
- getPromptFromPR({ client, issueNumber, repo, owner, body }),
- getDeploymentsForPR({ issueID, installationID, repositoryID, enabled: true }),
- ])
-
- if (deployments.length === 0) {
- console.log('No deployments found')
- return
- }
-
- const res = await Promise.allSettled(
- deployments.map(async d => {
- const accessToken = await getGHAccessToken({
- client,
- installationID,
- repositoryID,
- })
- await triggerSmolDevAgentRun({
- prompt,
- deployment: d,
- accessToken,
- commitMessage: 'Update based on PR comments',
- owner,
- repo,
- client,
- totalRuns: d._count.log_files,
- slug: d.projects.slug,
- pullNumber: issueNumber,
- })
-
- d
- .projects
- .teams
- .users_teams
- .map(team => team.users)
- .flat()
- .forEach(user => {
- posthog?.capture({
- distinctId: user.id,
- event: 'triggered agent with PR action',
- properties: {
- agent_deployment_id: d.id,
- agent: smolDeveloperTemplateID,
- repository: payload.repository.full_name,
- repository_url: payload.repository.html_url,
-
- pr_action: payload.action,
- pr_url: payload.pull_request.html_url,
- pr_number: issueNumber,
-
- prompt,
- title: payload.pull_request.title,
- pr_body: payload.pull_request.body,
- },
- })
- })
- }))
-
- await posthog?.shutdownAsync()
- console.log('Trigger results', res)
-}
-
-function getPRNumber(pr_url?: string) {
- const prNumber = pr_url?.split('/').pop()
- if (prNumber) {
- return parseInt(prNumber, 10)
- }
-}
-
-const issueCommentHandler: HandlerFunction<'issue_comment', unknown> = async (event) => {
- const { payload } = event
-
- if (payload.comment.user.type === 'Bot') {
- console.log('Comment was made by a GitHub bot, ignoring')
- return
- }
-
- const installationID = payload.installation?.id
- const repositoryID = payload.repository.id
-
- const owner = payload.repository.owner.login
- const repo = payload.repository.name
-
- // Every PR is also an issues - GH API endpoint for issues is used for the shared functionality
- // This issueID is not the PR issue id though, it's the issue id of the comment
- if (!installationID) {
- throw new Error('InstallationID not found')
- }
-
- const client = getGHInstallationClient({ installationID })
- const pullNumber = getPRNumber(payload.issue.pull_request?.url)
- if (!pullNumber) {
- throw new Error('PR number not found')
- }
-
- const pr = await client.pulls.get({
- owner,
- repo,
- pull_number: pullNumber,
- })
-
- const body = pr.data.body || ''
-
- const [prompt, deployments] = await Promise.all([
- getPromptFromPR({ client, issueNumber: pullNumber, repo, owner, body }),
- getDeploymentsForPR({ issueID: pr.data.id, installationID, repositoryID, enabled: true }),
- ])
-
- if (deployments.length === 0) {
- console.log('No deployments found')
- return
- }
-
- const res = await Promise.allSettled(
- deployments.map(async d => {
- const accessToken = await getGHAccessToken({
- client,
- installationID,
- repositoryID,
- })
- await triggerSmolDevAgentRun({
- prompt,
- deployment: d,
- slug: d.projects.slug,
- totalRuns: d._count.log_files,
- accessToken,
- owner,
- repo,
- commitMessage: 'Update based on PR comments',
- client,
- pullNumber,
- })
- d
- .projects
- .teams
- .users_teams
- .map(team => team.users)
- .flat()
- .forEach(user => {
- posthog?.capture({
- distinctId: user.id,
- event: 'triggered agent by PR comment action',
- properties: {
- agent_deployment_id: d.id,
- agent: smolDeveloperTemplateID,
- repository: payload.repository.full_name,
- repository_url: payload.repository.html_url,
-
- pr_comment_action: payload.action,
- pr_url: pr.data.html_url,
- pr_number: pr.data.number,
-
- prompt,
- title: pr.data.title,
- comment_body: payload.comment.body,
- },
- })
- })
- }))
-
- await posthog?.shutdownAsync()
-
- console.log('Trigger results', res)
-}
diff --git a/apps/dashboard/pages/agent/smol-developer/index.tsx b/apps/dashboard/pages/agent/smol-developer/index.tsx
deleted file mode 100644
index a45910ec9..000000000
--- a/apps/dashboard/pages/agent/smol-developer/index.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-import { Github } from 'lucide-react'
-import { useRouter } from 'next/router'
-import { useEffect } from 'react'
-import Link from 'next/link'
-import Image from 'next/image'
-import { useSupabaseClient } from '@supabase/auth-helpers-react'
-import {
- useUser,
- useSessionContext,
-} from '@supabase/auth-helpers-react'
-import { usePostHog } from 'posthog-js/react'
-
-import SpinnerIcon from 'components/Spinner'
-import StarUs from 'components/StarUs'
-
-function SmolDeveloper() {
- const supabaseClient = useSupabaseClient()
- const user = useUser()
- const sessionCtx = useSessionContext()
- const router = useRouter()
- const posthog = usePostHog()
-
- useEffect(() => {
- if (user) {
- router.push('/agent/smol-developer/setup')
- }
- }, [user, router])
-
- async function signInWithGitHub() {
- await supabaseClient.auth.signInWithOAuth({
- provider: 'github',
- options: {
- redirectTo: window.location.href,
- scopes: 'email',
- }
- })
- }
-
- return (
- <div className="h-full">
- <div className="m-auto h-full max-w-full">
- <div className="h-full relative isolate overflow-x-hidden md:overflow-hidden bg-gray-900 px-6 pt-16 shadow-2xl sm:px-16 md:pt-24 lg:flex lg:gap-x-20 lg:px-24 lg:pt-0">
- <svg
- viewBox="0 0 1024 1024"
- className="absolute left-1/2 top-1/2 -z-10 h-[64rem] w-[64rem] -translate-y-1/2 [mask-image:radial-gradient(closest-side,white,transparent)] sm:left-full sm:-ml-80 lg:left-1/2 lg:ml-0 lg:-translate-x-1/2 lg:translate-y-0"
- aria-hidden="true"
- >
- <circle cx={512} cy={512} r={512} fill="url(#759c1415-0410-454c-8f7c-9a820de03641)" fillOpacity="0.7" />
- <defs>
- <radialGradient id="759c1415-0410-454c-8f7c-9a820de03641">
- <stop stopColor="#7775D6" />
- <stop offset={1} stopColor="#E935C1" />
- </radialGradient>
- </defs>
- </svg>
- <div className="m-auto max-w-xl text-center lg:mx-0 lg:flex-auto lg:py-32 lg:text-left">
- <div className="flex flex-col space-y-4 items-center lg:items-start">
- <span className="flex space-x-4">
- <Link
- href="/" className="inline-flex space-x-6"
- onMouseDown={() => posthog?.capture('clicked link to e2b homepage')}
- >
- <span className="rounded-full bg-indigo-400/10 px-3 py-1 text-sm font-semibold leading-6 text-indigo-400 ring-1 ring-inset ring-indigo-400/20">
- Runs on <b>e2b</b>
- </span>
- </Link>
- <StarUs />
- </span>
- <h2 className="text-3xl font-bold tracking-tight text-white sm:text-4xl">
- Your personal AI developer.
- <br />
- With a single click.
- </h2>
- </div>
- <p className="mt-6 text-lg leading-8 text-gray-300">
- Get your own AI developer that&apos;s powered by the
- {' '}<a
- className="text-indigo-400 cursor-pointer font-bold"
- href="https://github.com/smol-ai/developer"
- rel="noreferer noopener"
- target="_blank"
- onMouseDown={() => posthog?.capture('clicked link', { url: 'https://github.com/smol-ai/developer' })}
- >smol developer
- </a>{' '}
- AI agent.
- You specify the instructions and then let smol developer do the work for you.
- </p>
- <div className="mt-6 flex flex-col space-y-4">
- <div className="flex flex-col space-y-2">
- <span className="text-gray-400">Powered by smol ai&apos;s agent</span>
- <a
- className="cursor-pointer flex justify-between py-2 px-4 w-full rounded-md bg-white/5 ring-1 ring-white/10 text-white font-semibold"
- href="https://github.com/smol-ai/developer"
- rel="noreferer noopener"
- target="_blank"
- onMouseDown={() => posthog?.capture('clicked link', { url: 'https://github.com/smol-ai/developer' })}
- >
- <span>smol-ai/developer</span>
- <span>Stars 10k</span>
- </a>
- </div>
- <div className="w-full flex items-center justify-between gap-x-6">
- {/* Also show the spinner when session is loaded and the user is also loaded because we're just waiting for the redirect to /setup */}
- {!sessionCtx.isLoading && user && (
- <div
- className="
- flex
- justify-center
- "
- >
- <SpinnerIcon className="text-slate-400" />
- </div>
- )}
- <div className="w-full flex flex-col md:flex-row items-center md:items-center justify-center md:justify-between space-y-2 md:space-y-0">
- {sessionCtx.isLoading && (
- <div
- className="
- flex
- justify-center
- "
- >
- <SpinnerIcon className="text-slate-400" />
- </div>
- )}
- {!sessionCtx.isLoading && !user &&
- <button
- className="flex items-center space-x-2 rounded-md bg-white px-3.5 py-2.5 text-sm font-semibold text-gray-900 shadow-sm hover:bg-gray-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
- onClick={signInWithGitHub}
- >
- <Github size={16} />
- <span>Continue with GitHub</span>
- </button>
- }
- <a
- className="text-sm font-semibold leading-6 text-white"
- href="https://github.com/smol-ai/developer"
- rel="noreferer noopener"
- target="_blank"
- onMouseDown={() => posthog?.capture('clicked link', { url: 'https://github.com/smol-ai/developer' })}
- >
- Learn about smol developer <span aria-hidden="true">→</span>
- </a>
- </div>
- </div>
- </div>
- </div>
- <div className="relative mb-8 md:mb-8 md:h-full">
- <Image
- alt="App screenshot"
- width={1824}
- height={1080}
- priority={true}
- className="absolute w-[57rem] top-4 lg:top-1/2 lg:-translate-y-1/2 max-w-none rounded-md bg-white/5 ring-1 ring-white/10"
- // src="https://tailwindui.com/img/component-images/dark-project-app-screenshot.png"
- src="/graphics.png"
- />
- </div>
- </div>
- </div>
- </div>
- )
-}
-
-export default SmolDeveloper
diff --git a/apps/dashboard/pages/agent/smol-developer/setup.tsx b/apps/dashboard/pages/agent/smol-developer/setup.tsx
deleted file mode 100644
index 7e0283a92..000000000
--- a/apps/dashboard/pages/agent/smol-developer/setup.tsx
+++ /dev/null
@@ -1,321 +0,0 @@
-import {
- useState,
- useCallback,
- useEffect,
-} from 'react'
-import useSWRMutation from 'swr/mutation'
-import type { GetServerSideProps } from 'next'
-import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import {
- useUser,
- useSupabaseClient,
-} from '@supabase/auth-helpers-react'
-import { usePostHog } from 'posthog-js/react'
-import { nanoid } from 'nanoid'
-import { useRouter } from 'next/router'
-
-import Steps from 'components/Steps'
-import SelectRepository from 'components/SelectRepository'
-import AgentInstructions from 'components/AgentInstructions'
-import DeployAgent from 'components/DeployAgent'
-import { serverCreds } from 'db/credentials'
-import { useGitHubClient } from 'hooks/useGitHubClient'
-import { useRepositories } from 'hooks/useRepositories'
-import { useLocalStorage } from 'hooks/useLocalStorage'
-import useListenOnMessage from 'hooks/useListenOnMessage'
-import { GitHubAccount } from 'utils/github'
-import { RepoSetup } from 'utils/repoSetup'
-import StarUs from 'components/StarUs'
-import { smolDeveloperTemplateID } from 'utils/smolTemplates'
-import ChooseOpenAIKey from 'components/ChooseOpenAIKey'
-
-export interface PostAgentBody {
- // ID of the installation of the GitHub App
- installationID: number
- // ID of the repository
- repositoryID: number
- // Title of the PR
- title: string
- // Default branch against which to create the PR
- defaultBranch: string
- // Initial prompt used as a body text for the PR (can be markdown)
- body: string
- // Owner of the repo (user or org)
- owner: string
- // Name of the repo
- repo: string
- // Name of the branch created for the PR
- branch: string
- // Commit message for the PR first empty commit
- commitMessage: string
- templateID: typeof smolDeveloperTemplateID
- openAIKey?: string
- openAIModel: string
-}
-
-const steps = [
- { name: 'Select Repository' },
- { name: 'Your Instructions' },
- { name: 'OpenAI API Key' },
- { name: 'Overview & Deploy' },
-]
-
-const openAIModels = [
- { displayName: 'GPT-4', value: 'gpt-4' },
- { displayName: 'GPT-4 32k', value: 'gpt-4-32k' },
- { displayName: 'GPT-3.5 Turbo', value: 'gpt-3.5-turbo' },
- { displayName: 'GPT-3.5 Turbo 16k', value: 'gpt-3.5-turbo-16k' },
-]
-
-export const getServerSideProps: GetServerSideProps = async (ctx) => {
- const supabase = createServerSupabaseClient(ctx, serverCreds)
- const {
- data: { session },
- } = await supabase.auth.getSession()
-
- if (!session) {
- return {
- redirect: {
- destination: '/agent/smol-developer',
- permanent: false,
- },
- }
- }
- return { props: {} }
-}
-
-export interface PostAgentResponse {
- issueID: number
- owner: string
- repo: string
- pullURL: string
- pullNumber: number
- projectID: string
- projectSlug: string
-}
-
-async function handlePostAgent(url: string, { arg }: { arg: PostAgentBody }) {
- const response = await fetch(url, {
- method: 'POST',
- body: JSON.stringify(arg),
- headers: {
- 'Content-Type': 'application/json',
- },
- })
- return await response.json() as PostAgentResponse
-}
-
-function Setup() {
- const user = useUser()
- const supabaseClient = useSupabaseClient()
- const [accessToken, setAccessToken] = useLocalStorage<string | undefined>('gh_access_token', undefined)
- const github = useGitHubClient(accessToken)
- const [githubAccounts, setGitHubAccounts] = useState<GitHubAccount[]>([])
- const [currentStepIdx, setCurrentStepIdx] = useState(0)
- const [selectedRepository, setSelectedRepository] = useState<RepoSetup>()
- const { repos, refetch } = useRepositories(github)
- const [instructions, setInstructions] = useState('')
- const posthog = usePostHog()
- const router = useRouter()
- const [isDeploying, setIsDeploying] = useState(false)
- const [selectedOpenAIKeyType, setSelectedOpenAIKeyType] = useState('e2b')
- const [userOpenAIKey, setUserOpenAIKey] = useState('')
- const [errorMessage, setErrorMessage] = useState('')
- const [selectedOpenAIModel, setSelectedOpenAIModel] = useState(openAIModels[0])
-
- const handleMessageEvent = useCallback((event: MessageEvent) => {
- if (event.data.accessToken) {
- setAccessToken(event.data.accessToken)
- } else if (event.data.installationID) {
- refetch()
- }
- }, [refetch, setAccessToken])
- useListenOnMessage(handleMessageEvent)
-
- const handleSelectOpenAIModel = useCallback((value: string) => {
- const model = openAIModels.find((model) => model.value === value)
- if (!model) throw new Error(`Invalid OpenAI model: ${value}`)
- setSelectedOpenAIModel(model)
- }, [])
-
- const handleOpenAIKeyChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
- setUserOpenAIKey(event.target.value)
- }, [])
-
- const {
- trigger: createAgent,
- } = useSWRMutation('/api/agent', handlePostAgent)
-
- async function deployAgent() {
- if (!selectedRepository) {
- console.error('No repository selected')
- return
- }
- if (!instructions) {
- console.error('No instructions provided')
- return
- }
- setErrorMessage('')
- try {
- setIsDeploying(true)
- const response = await createAgent({
- defaultBranch: selectedRepository.defaultBranch,
- installationID: selectedRepository.installationID,
- owner: selectedRepository.owner,
- repo: selectedRepository.repo,
- repositoryID: selectedRepository.repositoryID,
- title: 'Smol PR',
- branch: `pr/smol-dev/${nanoid(6).toLowerCase()}`,
- body: instructions,
- commitMessage: 'Initial commit',
- templateID: smolDeveloperTemplateID,
- openAIKey: userOpenAIKey,
- openAIModel: selectedOpenAIModel.value,
- })
-
- posthog?.capture('clicked on deploy agent', {
- repository: `${selectedRepository.owner}/${selectedRepository.repo}`,
- instructions,
- hasUserProvidedOpenAIKey: !!userOpenAIKey,
- })
-
- // Redirect to the dashboard.
- if (response) {
- if ((response as any).statusCode === 500) {
- console.log('Error response', response)
- setErrorMessage((response as any).message)
- setIsDeploying(false)
- return
- }
-
- router.push({
- pathname: '/logs/[slug]',
- query: {
- slug: `${response.projectSlug}-run-0`,
- },
- })
- } else {
- console.error('No response from agent creation')
- }
- } catch (error: any) {
- setIsDeploying(false)
- }
- }
-
- function nextStep() {
- setCurrentStepIdx(currentStepIdx + 1)
- }
-
- function previousStep() {
- setCurrentStepIdx(currentStepIdx - 1)
- posthog?.capture('clicked previous step', {
- step: currentStepIdx - 1,
- })
- }
-
- function handleRepoSelection(repo: any) {
- setSelectedRepository(repo)
- nextStep()
- }
-
- async function signOut() {
- await supabaseClient.auth.signOut()
- posthog?.reset(true)
- location.reload()
- }
-
- useEffect(function getGitHubAccounts() {
- async function getAccounts() {
- if (!github) return
- const installations = await github.apps.listInstallationsForAuthenticatedUser()
- const accounts: GitHubAccount[] = []
- installations.data.installations.forEach(i => {
- if (i.account) {
- const ghAccType = (i.account as any)['type']
- const ghLogin = (i.account as any)['login']
- // Filter out user accounts that are not the current user (when a user has access to repos that aren't theirs)
- if (ghAccType === 'User' && ghLogin !== user?.user_metadata?.user_name) return
- accounts.push({ name: ghLogin, isOrg: ghAccType === 'Organization', installationID: i.id })
- }
- })
- setGitHubAccounts(accounts)
- }
- getAccounts()
- }, [github, user])
-
- return (
- <div className="h-full flex flex-col items-center justify-start bg-gray-800 py-8 px-6 space-y-8">
- <div className="mb-4 w-full flex items-center justify-between">
- <button
- className="text-sm font-semibold text-gray-400 hover:text-white transition-all"
- onClick={signOut}
- >
- Sign out
- </button>
- <StarUs />
- </div>
- <div className="overflow-hidden flex-1 mx-auto w-full max-w-lg flex flex-col">
- <Steps
- currentIdx={currentStepIdx}
- steps={steps}
- />
- <div className="h-px bg-gray-700 my-8" />
- {currentStepIdx === 0 && (
- <SelectRepository
- repos={repos}
- onRepoSelection={handleRepoSelection}
- accessToken={accessToken}
- githubAccounts={githubAccounts}
- />
- )}
- {currentStepIdx === 1 && (
- <AgentInstructions
- value={instructions}
- onTemplateSelect={t => { console.log(t); setInstructions(t) }}
- onChange={setInstructions}
- onBack={previousStep}
- onNext={nextStep}
- />
- )}
- {currentStepIdx === 2 && (
- <ChooseOpenAIKey
- selectedOpenAIKeyType={selectedOpenAIKeyType}
-
- onSelectedOpenAIKeyTypeChange={setSelectedOpenAIKeyType}
- userOpenAIKey={userOpenAIKey}
- onUserOpenAIKeyChange={handleOpenAIKeyChange}
-
- openAIModels={openAIModels}
- selectedOpenAIModel={selectedOpenAIModel}
- onOpenAIModelChange={handleSelectOpenAIModel}
-
- onNext={nextStep}
- onBack={previousStep}
- />
- )}
- {currentStepIdx === 3 && (
- <DeployAgent
- selectedRepo={selectedRepository!}
- instructions={instructions}
- onInstructionsChange={setInstructions}
- onChangeRepo={() => {
- setCurrentStepIdx(0)
- posthog?.capture('returned to repository selection step')
- }}
- error={errorMessage}
- onChangeTemplate={() => {
- setCurrentStepIdx(1)
- posthog?.capture('returned to the instructions step')
- }}
- onBack={previousStep}
- onDeploy={deployAgent}
- isDeploying={isDeploying}
- selectedOpenAIKeyType={selectedOpenAIKeyType}
- />
- )}
- </div>
- </div>
- )
-}
-
-export default Setup
diff --git a/apps/dashboard/pages/api/agent/index.ts b/apps/dashboard/pages/api/agent/index.ts
deleted file mode 100644
index 8ba9335e3..000000000
--- a/apps/dashboard/pages/api/agent/index.ts
+++ /dev/null
@@ -1,282 +0,0 @@
-import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import { NextApiRequest, NextApiResponse } from 'next'
-import { nanoid } from 'nanoid'
-import { client as posthog } from 'utils/posthog'
-
-import { PostAgentResponse } from 'pages/agent/smol-developer/setup'
-import { prisma } from 'db/prisma'
-import { serverCreds } from 'db/credentials'
-import { PostAgentBody } from 'pages/agent/smol-developer/setup'
-import { getGHInstallationClient } from 'github/installationClient'
-import {
- createAgentDeployment,
- createPR, getGHAccessToken,
- getGHAppInfo,
- prTitleFromInstructions,
- triggerSmolDevAgentRun,
-} from 'github/pullRequest'
-
-export interface DeploymentAuthData {
- github: {
- app_name: string,
- app_email: string,
- installation_id: number,
- repository_id: number,
- issue_id: number,
- pr_number: number,
- branch: string,
- owner: string,
- repo: string,
- pr_status: string,
- merged: boolean
- closed_at: null | string,
- }
-}
-
-export const prInfoText = `
----
-*Trigger the agent again by adding instructions in a new PR comment or by editing existing instructions.*
-
-*Powered by [e2b](https://app.e2b.dev/agent/smol-developer?utm_source=github)*
-`
-
-async function postAgent(req: NextApiRequest, res: NextApiResponse) {
- const {
- installationID,
- repositoryID,
- title,
- body,
- owner,
- templateID,
- branch,
- commitMessage,
- openAIKey,
- defaultBranch,
- repo,
- openAIModel,
- } = req.body as PostAgentBody
-
- try {
- const supabase = createServerSupabaseClient({ req, res }, serverCreds)
- const { data: { session } } = await supabase.auth.getSession()
- if (!session) {
- return res.status(401).json({
- error: 'not_authenticated',
- description: 'The user does not have an active session or is not authenticated',
- })
- }
-
- const user = await prisma.auth_users.findUnique({
- where: {
- id: session.user.id,
- },
- include: {
- users_teams: {
- include: {
- teams: true,
- },
- }
- },
- })
- if (!user) {
- return res.status(401).json({
- error: 'invalid_user',
- })
- }
-
- const defaultTeam = user.users_teams.find(t => t.teams.is_default)
- const client = getGHInstallationClient({ installationID })
-
- const appInfoPromise = getGHAppInfo({ client })
-
- const accessTokenPromise = getGHAccessToken({
- client,
- installationID,
- repositoryID,
- })
-
- const prTitle = await prTitleFromInstructions(body, openAIKey)
-
- if (!prTitle) {
- throw new Error('Generated PR title is empty')
- }
-
- const bodyWithInfo = `${body}${prInfoText}`
-
- const { issueID, number: pullNumber, url: pullURL } = await createPR({
- client,
- title: prTitle,
- defaultBranch,
- branch,
- commitMessage,
- body: bodyWithInfo,
- owner,
- repo,
- })
-
- posthog?.capture({
- distinctId: user.id,
- event: 'created PR when deploying agent',
- properties: {
- agent: templateID,
- repository: `${owner}/${repo}`,
-
- pr_action: 'created',
- pr_url: pullURL,
- pr_number: pullNumber,
- },
- })
-
- const appInfo = await appInfoPromise
- const authData: DeploymentAuthData = {
- github: {
- app_name: appInfo.name,
- app_email: appInfo.email,
- installation_id: installationID,
- repository_id: repositoryID,
- issue_id: issueID,
- pr_number: pullNumber,
- branch,
- owner,
- repo,
- pr_status: 'opened',
- merged: false,
- closed_at: null,
- },
- }
-
- const slug = `smoldev-${nanoid(3)}-${owner}-${repo}-pr-${pullNumber}`.toLowerCase()
- const project = await prisma.projects.create({
- data: {
- id: nanoid(),
- name: 'Smol developer',
- slug,
- deployments: {
- create: {
- auth: authData as any,
- enabled: false,
- config: {
- templateID,
- // OpenAI Model if OpenAI Key is provided
- ...(openAIKey && { openAIModel }),
- } as any,
- ...openAIKey && { secrets: JSON.stringify({ openAIKey }) },
- },
- },
- teams: {
- ...defaultTeam
- ? {
- connect: {
- id: defaultTeam.teams.id,
- },
- }
- : {
- create: {
- name: session.user.email || session.user.id,
- is_default: true,
- users_teams: {
- create: {
- users: {
- connect: {
- id: session.user.id,
- },
- },
- },
- },
- },
- }
- },
- },
- include: {
- deployments: true,
- }
- })
-
- await createAgentDeployment({
- project_id: project.id,
- config: {
- templateID,
- // OpenAI Model if OpenAI Key is provided
- ...(openAIKey && { openAIModel }),
- } as any,
- secrets: { openAIKey } as any,
- })
-
- const deployment = project.deployments[0]
- // We started the process of getting the token earlier but we await it only now because we need in now
- const accessToken = await accessTokenPromise
-
- posthog?.capture({
- distinctId: user.id,
- event: 'created agent deployment',
- properties: {
- agent_deployment_id: deployment.id,
- agent: templateID,
- pr_url: pullURL,
- pr_number: pullNumber,
- repository: `${owner}/${repo}`,
- hasUserProvidedOpenAIKey: !!openAIKey,
- },
- })
-
- await triggerSmolDevAgentRun({
- deployment,
- prompt: body,
- accessToken,
- commitMessage: 'Add code based on the PR instructions',
- owner,
- repo,
- client,
- slug,
- totalRuns: 0,
- pullNumber,
- })
-
- const response: PostAgentResponse = {
- pullNumber,
- pullURL,
- issueID,
- owner,
- repo,
- projectID: project.id,
- projectSlug: slug,
- }
-
- posthog?.capture({
- distinctId: user.id,
- event: 'triggered deployed agent initial run',
- properties: {
- agent_deployment_id: deployment.id,
- agent: templateID,
- repository: `${owner}/${repo}`,
-
- pr_url: pullURL,
- pr_number: pullNumber,
-
- title,
- prompt: body,
- },
- })
-
- res.status(200).json(response)
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method === 'POST') {
- await postAgent(req, res)
- return
- }
-
- res.setHeader('Allow', 'POST')
- res.status(405).json({ statusCode: 405, message: 'Method Not Allowed' })
- return
-}
-
-export default handler
diff --git a/apps/dashboard/pages/api/agent/run.ts b/apps/dashboard/pages/api/agent/run.ts
deleted file mode 100644
index e5a623307..000000000
--- a/apps/dashboard/pages/api/agent/run.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next'
-
-import { prisma } from 'db/prisma'
-import { getGHInstallationClient } from 'github/installationClient'
-import { addCommentToPR } from 'github/pullRequest'
-import { client as posthog } from 'utils/posthog'
-
-import { DeploymentAuthData } from '.'
-import { smolDeveloperTemplateID } from 'utils/smolTemplates'
-
-// Indicate that the agent state changed (run finished)
-async function postRun(req: NextApiRequest, res: NextApiResponse) {
- try {
- const {
- deployment_id,
- prompt,
- run_id,
- } = req.body as {
- prompt: string,
- deployment_id: string,
- run_id: string,
- }
-
- const header = req.headers.authorization
- // Extract the token from the header
- const token = header?.split(' ')[1]
- if (process.env.SECRET_TOKEN && token !== process.env.SECRET_TOKEN) {
- console.log('Invalid token', token, process.env.SECRET_TOKEN)
- throw new Error('Invalid token')
- }
-
- const deployment = await prisma.deployments.update({
- where: {
- id: deployment_id,
- },
- data: {
- last_finished_prompt: prompt,
- },
- include: {
- _count: {
- select: {
- log_files: true,
- },
- },
- projects: {
- include: {
- teams: {
- include: {
- users_teams: {
- include: {
- users: true,
- },
- },
- },
- },
- },
- },
- },
- })
-
- const authData = deployment.auth as unknown as DeploymentAuthData
- const client = getGHInstallationClient({ installationID: authData.github.installation_id })
-
- // TODO: Should we maybe just edit the previous comment?
- // Or should we do that only if the previous run was cancelled
- await addCommentToPR({
- body: `Finished smol developer [agent run](https://app.e2b.dev/logs/${deployment.projects.slug}-run-${deployment._count.log_files - 1}?utm_source=github).\n\n*Trigger the agent again by adding instructions in a new PR comment or by editing existing instructions.*`,
- client,
- owner: authData.github.owner,
- repo: authData.github.repo,
- pullNumber: authData.github.pr_number,
- })
-
- const users = deployment
- .projects
- .teams
- .users_teams
- .map(u => u.users)
- .flat()
-
- const result = await Promise.allSettled(users.map(async u => {
- posthog?.capture({
- distinctId: u.id,
- event: 'finished agent run',
- properties: {
- agent_deployment_id: deployment.id,
- agent: smolDeveloperTemplateID,
- repository: `${authData.github.owner}/${authData.github.repo}`,
- run_id,
-
- pr_number: authData.github.pr_number,
- },
- })
- }))
-
- await posthog?.shutdownAsync()
- console.log('Analytics logged', result)
-
- res.status(200).json({})
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-// Indicate that the agent state changed (run cancelled)
-async function deleteRun(req: NextApiRequest, res: NextApiResponse) {
- try {
- const {
- deployment_id,
- run_id,
- } = req.body as {
- deployment_id: string,
- run_id: string,
- }
-
- const header = req.headers.authorization
- // Extract the token from the header
- const token = header?.split(' ')[1]
- if (process.env.SECRET_TOKEN && token !== process.env.SECRET_TOKEN) {
- console.log('Invalid token', token, process.env.SECRET_TOKEN)
- throw new Error('Invalid token')
- }
-
- const deployment = await prisma.deployments.findUniqueOrThrow({
- where: {
- id: deployment_id,
- },
- include: {
- _count: {
- select: {
- log_files: true,
- },
- },
- projects: {
- include: {
- teams: {
- include: {
- users_teams: {
- include: {
- users: true,
- },
- },
- },
- },
- },
- },
- },
- })
-
- const authData = deployment.auth as unknown as DeploymentAuthData
- const client = getGHInstallationClient({ installationID: authData.github.installation_id })
-
- if (deployment.enabled) {
- // Add comment about the run being cancelled
- await addCommentToPR({
- body: `Cancelled smol developer [agent run](https://app.e2b.dev/logs/${deployment.projects.slug}-run-${deployment._count.log_files - 1}?utm_source=github).`,
- client,
- owner: authData.github.owner,
- repo: authData.github.repo,
- pullNumber: authData.github.pr_number,
- })
- }
-
- const users = deployment
- .projects
- .teams
- .users_teams
- .map(u => u.users)
- .flat()
-
- const result = await Promise.allSettled(users.map(async u => {
- posthog?.capture({
- distinctId: u.id,
- event: 'cancelled agent run',
- properties: {
- agent_deployment_id: deployment.id,
- agent: smolDeveloperTemplateID,
- repository: `${authData.github.owner}/${authData.github.repo}`,
- run_id,
-
- pr_number: authData.github.pr_number,
- },
- })
- }))
-
- await posthog?.shutdownAsync()
- console.log('Analytics logged', result)
-
- res.status(200).json({})
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method === 'POST') {
- await postRun(req, res)
- return
- }
- if (req.method === 'DELETE') {
- await deleteRun(req, res)
- return
- }
-
- res.setHeader('Allow', ['POST', 'DELETE'])
- res.status(405).json({ statusCode: 405, message: 'Method Not Allowed' })
- return
-}
-
-export default handler
diff --git a/apps/dashboard/pages/api/github/oauth.ts b/apps/dashboard/pages/api/github/oauth.ts
deleted file mode 100644
index 68d061e7d..000000000
--- a/apps/dashboard/pages/api/github/oauth.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { NextApiRequest, NextApiResponse } from 'next'
-import url from 'url'
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
-
- if (!req.url) {
- res.writeHead(400, { 'Content-Type': 'text/html' })
- res.end('No request URL')
- return
- }
-
- const { code }: { code?: string } = url.parse(req.url, true).query
- if (!code) {
- res.writeHead(400, { 'Content-Type': 'text/html' })
- res.end('No code param in query')
- return
- }
-
- const exchangeURL = new URL('login/oauth/access_token', 'https://github.com')
- exchangeURL.searchParams.set('client_id', process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID!)
- exchangeURL.searchParams.set('client_secret', process.env.GITHUB_CLIENT_SECRET!)
- exchangeURL.searchParams.set('code', code)
-
- const response = await fetch(exchangeURL.toString(), {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- }
- })
-
- const redirectionURL = new URL('github/callback', `${process.env.NODE_ENV === 'production' ? 'https' : 'http'}://${req.headers.host}`)
-
- const { access_token }: { access_token: string } = await response.json()
- redirectionURL.searchParams.set('gha_access_token', access_token)
-
- res.writeHead(302, { 'Location': redirectionURL.toString() })
- res.end()
-}
diff --git a/apps/dashboard/pages/api/github/webhook.ts b/apps/dashboard/pages/api/github/webhook.ts
deleted file mode 100644
index 5642b4fd1..000000000
--- a/apps/dashboard/pages/api/github/webhook.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next'
-import Cors from 'micro-cors'
-
-import { getGitHubWebhooksMiddleware } from 'github/webhooks'
-
-const webhookHandler = getGitHubWebhooksMiddleware()
-
-export const config = {
- api: {
- bodyParser: false,
- },
-}
-
-const cors = Cors({
- allowMethods: ['POST', 'HEAD'],
-})
-
-async function handler(req: NextApiRequest, res: NextApiResponse) {
- await (await webhookHandler)(req, res)
-}
-
-export default cors(handler as any)
diff --git a/apps/dashboard/pages/api/log_upload/index.ts b/apps/dashboard/pages/api/log_upload/index.ts
deleted file mode 100644
index dd592b0d3..000000000
--- a/apps/dashboard/pages/api/log_upload/index.ts
+++ /dev/null
@@ -1,261 +0,0 @@
-import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import { NextApiRequest, NextApiResponse } from 'next'
-
-import { prisma } from 'db/prisma'
-import { serverCreds } from 'db/credentials'
-import { PostLogUpload } from 'hooks/useUploadLogUpload'
-import { DeleteLogUpload } from 'hooks/useDeleteLogUpload'
-import { PatchLogUpload } from 'hooks/useRenameLogUpload'
-
-async function deleteLogUpload(req: NextApiRequest, res: NextApiResponse) {
- const {
- id,
- } = req.body as DeleteLogUpload
-
- try {
- const supabase = createServerSupabaseClient({ req, res }, serverCreds)
- const { data: { session } } = await supabase.auth.getSession()
- if (!session) {
- return res.status(401).json({
- error: 'not_authenticated',
- description: 'The user does not have an active session or is not authenticated',
- })
- }
-
- const user = await prisma.auth_users.findUnique({
- where: {
- id: session.user.id,
- },
- include: {
- users_teams: {
- include: {
- teams: {
- include: {
- projects: {
- include: {
- log_uploads: {
- where: {
- id,
- },
- },
- },
- },
- },
- },
- },
- },
- },
- })
-
- if (!user) {
- return res.status(401).json({
- error: 'invalid_user',
- })
- }
-
- const hasAccessToLogs = user
- .users_teams
- .flatMap(t => t.teams.projects)
- .flatMap(p => p.log_uploads)
- .some(l => l.id === id)
-
- if (!hasAccessToLogs) {
- return res.status(401).json({
- error: 'logs_does_not_belong_to_user',
- })
- }
-
- await prisma.log_uploads.delete({
- where: {
- id,
- },
- })
-
- res.status(200).json({})
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-async function postLogUpload(req: NextApiRequest, res: NextApiResponse) {
- const {
- logFiles,
- projectID,
- } = req.body as PostLogUpload
-
- try {
- const supabase = createServerSupabaseClient({ req, res }, serverCreds)
- const { data: { session } } = await supabase.auth.getSession()
- if (!session) {
- return res.status(401).json({
- error: 'not_authenticated',
- description: 'The user does not have an active session or is not authenticated',
- })
- }
-
- const user = await prisma.auth_users.findUnique({
- where: {
- id: session.user.id,
- },
- include: {
- users_teams: {
- include: {
- teams: {
- include: {
- projects: {
- select: {
- id: true,
- },
- },
- },
- },
- },
- },
- },
- })
-
- if (!user) {
- return res.status(401).json({
- error: 'invalid_user',
- })
- }
-
- const isInProject = user
- .users_teams
- .flatMap(t => t.teams.projects)
- .some(p => p.id === projectID)
-
- if (!isInProject) {
- return res.status(401).json({
- error: 'user_not_in_project',
- })
- }
-
- const logs = await prisma.log_uploads.create({
- data: {
- projects: {
- connect: {
- id: projectID,
- },
- },
- log_files: {
- createMany: {
- data: logFiles.map(l => ({
- ...l,
- project_id: projectID,
- })),
- },
- },
- },
- })
-
- res.status(200).json({
- id: logs.id,
- })
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-
-async function patchLogUpload(req: NextApiRequest, res: NextApiResponse) {
- const {
- logUploadID,
- displayName,
- } = req.body as PatchLogUpload
-
- try {
- const supabase = createServerSupabaseClient({ req, res }, serverCreds)
- const { data: { session } } = await supabase.auth.getSession()
- if (!session) {
- return res.status(401).json({
- error: 'not_authenticated',
- description: 'The user does not have an active session or is not authenticated',
- })
- }
-
- const user = await prisma.auth_users.findUnique({
- where: {
- id: session.user.id,
- },
- include: {
- users_teams: {
- include: {
- teams: {
- include: {
- projects: {
- include: {
- log_uploads: {
- where: {
- id: logUploadID,
- },
- },
- },
- },
- },
- },
- },
- },
- },
- })
-
- if (!user) {
- return res.status(401).json({
- error: 'invalid_user',
- })
- }
-
- const hasAccessToLogs = user
- .users_teams
- .flatMap(t => t.teams.projects)
- .flatMap(p => p.log_uploads)
- .some(l => l.id === logUploadID)
-
- if (!hasAccessToLogs) {
- return res.status(401).json({
- error: 'logs_does_not_belong_to_user',
- })
- }
-
- await prisma.log_uploads.update({
- where: {
- id: logUploadID,
- },
- data: {
- display_name: displayName,
- },
- })
- res.status(200).json({})
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method === 'POST') {
- await postLogUpload(req, res)
- return
- }
-
- if (req.method === 'DELETE') {
- await deleteLogUpload(req, res)
- return
- }
-
- if (req.method === 'PATCH') {
- await patchLogUpload(req, res)
- return
- }
-
- res.setHeader('Allow', ['POST', 'DELETE', 'PATCH'])
- res.status(405).json({ statusCode: 405, message: 'Method Not Allowed' })
- return
-}
-
-export default handler
diff --git a/apps/dashboard/pages/api/log_upload/tag.ts b/apps/dashboard/pages/api/log_upload/tag.ts
deleted file mode 100644
index df5dced79..000000000
--- a/apps/dashboard/pages/api/log_upload/tag.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import { NextApiRequest, NextApiResponse } from 'next'
-
-import { prisma } from 'db/prisma'
-import { serverCreds } from 'db/credentials'
-import { DeleteLogUploadTag } from 'hooks/useDeleteLogUploadTag'
-import { PostLogUploadTag } from 'hooks/useAddLogUploadTag'
-
-async function deleteLogUploadTag(req: NextApiRequest, res: NextApiResponse) {
- const {
- id,
- tag,
- } = req.body as DeleteLogUploadTag
-
- try {
- const supabase = createServerSupabaseClient({ req, res }, serverCreds)
- const { data: { session } } = await supabase.auth.getSession()
- if (!session) {
- return res.status(401).json({
- error: 'not_authenticated',
- description: 'The user does not have an active session or is not authenticated',
- })
- }
-
- const log = await prisma.log_uploads.findFirstOrThrow({
- where: {
- id,
- projects: {
- teams: {
- users_teams: {
- some: {
- user_id: session.user.id,
- },
- },
- },
- },
- },
- })
-
- await prisma.log_uploads.update({
- where: {
- id,
- },
- data: {
- tags: (log.tags as any[]).filter(t => t.path !== tag.path || t.text !== tag.text),
- },
- })
-
- res.status(200).json({})
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-async function postLogUploadTag(req: NextApiRequest, res: NextApiResponse) {
- const {
- id,
- tag,
- } = req.body as PostLogUploadTag
-
- try {
- const supabase = createServerSupabaseClient({ req, res }, serverCreds)
- const { data: { session } } = await supabase.auth.getSession()
- if (!session) {
- return res.status(401).json({
- error: 'not_authenticated',
- description: 'The user does not have an active session or is not authenticated',
- })
- }
-
- const log = await prisma.log_uploads.findFirstOrThrow({
- where: {
- id,
- projects: {
- teams: {
- users_teams: {
- some: {
- user_id: session.user.id,
- },
- },
- },
- },
- },
- })
-
- await prisma.log_uploads.update({
- where: {
- id,
- },
- data: {
- tags: [...log.tags as any[], tag],
- },
- })
-
- res.status(200).json({})
- } catch (err: any) {
- console.error(err)
- res.status(500).json({ statusCode: 500, message: err.message })
- }
-}
-
-async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method === 'POST') {
- await postLogUploadTag(req, res)
- return
- }
-
- if (req.method === 'DELETE') {
- await deleteLogUploadTag(req, res)
- return
- }
-
- res.setHeader('Allow', ['POST', 'DELETE'])
- res.status(405).json({ statusCode: 405, message: 'Method Not Allowed' })
- return
-}
-
-export default handler
diff --git a/apps/dashboard/pages/api/supabase/[...all].ts b/apps/dashboard/pages/api/supabase/[...all].ts
deleted file mode 100644
index daaa37796..000000000
--- a/apps/dashboard/pages/api/supabase/[...all].ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { createProxyMiddleware } from 'http-proxy-middleware'
-import type { NextApiRequest, NextApiResponse } from 'next'
-
-export const config = {
- api: {
- responseLimit: false,
- // Proxy middleware will handle requests itself, so Next.js should
- // ignore that our handler doesn't directly return a response
- externalResolver: true,
- // Pass request bodies through unmodified so that the origin API server
- // receives them in the intended format
- bodyParser: false,
- },
-}
-
-const pathPrefix = '/api/supabase'
-
-const target = process.env.NEXT_PUBLIC_SUPABASE_URL!
-const isSecure = target.startsWith('https://')
-
-const proxy = createProxyMiddleware<NextApiRequest, NextApiResponse>({
- target,
- ws: true,
- secure: !isSecure,
- changeOrigin: true,
- pathRewrite: { [`^${pathPrefix}`]: '' }, // remove prefix
-})
-
-export default function handler(req: NextApiRequest, res: NextApiResponse) {
- proxy(req, res, (result: unknown) => {
- if (result instanceof Error) {
- throw result
- }
- })
-}
diff --git a/apps/dashboard/pages/logs/[slug].tsx b/apps/dashboard/pages/logs/[slug].tsx
deleted file mode 100644
index 27f21353d..000000000
--- a/apps/dashboard/pages/logs/[slug].tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import type { GetServerSideProps } from 'next'
-import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'
-import type { ParsedUrlQuery } from 'querystring'
-
-import { prisma, log_files, deployments } from 'db/prisma'
-import { serverCreds } from 'db/credentials'
-import { LiteDeploymentLog } from 'utils/agentLogs'
-import AgentRunLogContent from 'components/AgentRunLogContent'
-import { wait } from 'utils/wait'
-
-interface PathProps extends ParsedUrlQuery {
- slug: string
-}
-
-export const getServerSideProps: GetServerSideProps<Props, PathProps> = async (ctx) => {
- const slug = ctx.params?.slug
- if (!slug) {
- return {
- redirect: {
- destination: '/',
- permanent: false,
- }
- }
- }
-
- const supabase = createServerSupabaseClient(ctx, serverCreds)
- const {
- data: { session },
- } = await supabase.auth.getSession()
-
- if (!session) {
- return {
- redirect: {
- destination: '/sign',
- permanent: false,
- },
- }
- }
-
- const splittedLogSlug = slug.split('-')
- const projectSlug = splittedLogSlug.slice(0, splittedLogSlug.length - 2).join('-')
- const logNumber = parseInt(splittedLogSlug.length > 1 ? splittedLogSlug[splittedLogSlug.length - 1] : '0')
-
- let log: (log_files & {
- deployments: (deployments & {
- projects: {
- name: string;
- };
- }) | null;
- }) | null = null
-
- // Poll the DB in case the log is not yet available
- for (let i = 0; i < 6; i++) {
- log = await prisma.log_files.findFirst({
- orderBy: [
- { created_at: 'asc' },
- { id: 'asc', },
- ],
- skip: logNumber,
- where: {
- deployments: {
- projects: {
- slug: {
- equals: projectSlug,
- mode: 'insensitive',
- }
- }
- },
- projects: {
- teams: {
- users_teams: {
- some: {
- user_id: session.user.id,
- },
- },
- },
- },
- },
- include: {
- deployments: {
- include: {
- projects: {
- select: {
- name: true,
- },
- },
- },
- },
- },
- })
-
- if (log) {
- break
- }
-
- await wait(200 * (i + 1))
- }
-
- if (!log || !log.deployments) {
- return {
- notFound: true,
- }
- }
-
- return {
- props: {
- log: {
- ...log,
- content: JSON.parse(log.content),
- } as any,
- }
- }
-}
-
-interface Props {
- log: LiteDeploymentLog
-}
-
-function ProjectPage({ log }: Props) {
- return (
- <AgentRunLogContent log={log} />
- )
-}
-
-export default ProjectPage
diff --git a/apps/dashboard/pages/settings/index.tsx b/apps/dashboard/pages/settings/index.tsx
index bc2066cad..790d782d8 100644
--- a/apps/dashboard/pages/settings/index.tsx
+++ b/apps/dashboard/pages/settings/index.tsx
@@ -4,8 +4,8 @@ import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'
import { prisma } from 'db/prisma'
import { serverCreds } from 'db/credentials'
import Settings from 'components/Settings'
-import { client as posthog } from '../../utils/posthog.ts'
-import { generateApiKey } from '../../utils/apiKey.ts'
+import { client as posthog } from 'utils/posthog'
+import { generateApiKey } from 'utils/apiKey'
export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
const supabase = createServerSupabaseClient(ctx, serverCreds)
@@ -21,8 +21,9 @@ export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
},
}
}
+ let apiKeyValue: string | undefined
- let apiKey = await prisma.team_api_keys.findFirst({
+ const apiKey = await prisma.team_api_keys.findFirst({
include: {
teams: {
include: {
@@ -38,8 +39,10 @@ export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
},
})
+ apiKeyValue = apiKey?.api_key
+
if (!apiKey) {
- const user = await prisma.auth_users.findUnique({
+ const user = await prisma.auth_users.findUniqueOrThrow({
where: {
id: session.user.id,
},
@@ -51,11 +54,6 @@ export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
},
},
})
- if (!user) {
- return res.status(401).json({
- error: 'invalid_user',
- })
- }
const defaultTeam = user.users_teams.find((t) => t.teams.is_default)
if (!defaultTeam) {
return {
@@ -66,17 +64,18 @@ export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
}
}
- while (true) {
- const generatedApiKey = generateApiKey()
+ for (let i = 0; i < 100; i++) {
+ apiKeyValue = generateApiKey()
try {
- apiKey = await prisma.team_api_keys.create({
+ await prisma.team_api_keys.create({
data: {
team_id: defaultTeam.teams.id,
- api_key: generatedApiKey,
+ api_key: apiKeyValue,
},
})
break
- } catch (e) {
+ } catch (e: any) {
+ // TODO: Get prisma typed error
// Duplicate key error
if (e.code !== 'P2002') {
throw e
@@ -87,19 +86,19 @@ export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
posthog?.capture({
distinctId: user.id,
event: 'created API key',
- team: defaultTeam.teams.team_id,
+ team: defaultTeam.teams.id,
})
}
return {
props: {
- apiKey: apiKey.api_key,
- },
+ apiKey: apiKey?.api_key!,
+ }
}
}
interface Props {
- apiKey: string;
+ apiKey: string
}
function SettingsPage({ apiKey }: Props) {
diff --git a/apps/dashboard/utils/github.ts b/apps/dashboard/utils/github.ts
deleted file mode 100644
index 4bade856c..000000000
--- a/apps/dashboard/utils/github.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { openPopupModal } from 'utils/popupModal'
-
-export interface GitHubAccount {
- name: string
- isOrg: boolean
- installationID: number
-}
-
-export function configureGitHubApp() {
- const url = new URL('https://github.com/apps/e2b-for-github/installations/new')
-
- const hostname = window.location.hostname
- const protocol = window.location.protocol
- const redirectURI = `${protocol}//${hostname}/api/github/oauth`
- url.searchParams.append('redirect_uri', redirectURI)
-
- openPopupModal(url)
-}
diff --git a/apps/dashboard/utils/popupModal.ts b/apps/dashboard/utils/popupModal.ts
deleted file mode 100644
index 9e87e69d1..000000000
--- a/apps/dashboard/utils/popupModal.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-export function openPopupModal(url: URL) {
- const features = {
- popup: 'yes',
- width: 820,
- height: 700,
- top: 'auto',
- left: 'auto',
- toolbar: 'no',
- menubar: 'no',
- }
- const strWindowsFeatures = Object.entries(features)
- .reduce((str, [key, value]) => {
- if (value == 'auto') {
- if (key === 'top') {
- const v = Math.round(
- window.innerHeight / 2 - features.height / 2
- )
- str += `top=${v},`
- } else if (key === 'left') {
- const v = Math.round(
- window.innerWidth / 2 - features.width / 2
- )
- str += `left=${v},`
- }
- return str
- }
-
- str += `${key}=${value},`
- return str
- }, '')
- .slice(0, -1) // remove last ',' (comma)
- return window.open(url, '_blank', strWindowsFeatures)
-}