Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Fix project routes handling [WIP]

Tomas Valentadc0d825db70b
diff --git a/components/Editor/index.tsx b/components/Editor/index.tsx
index 70c3d5ba0..ab06ea530 100644
--- a/components/Editor/index.tsx
+++ b/components/Editor/index.tsx
@@ -1,12 +1,10 @@
-import { shallow } from 'zustand/shallow'
import useSWRMutation from 'swr/mutation'
import { Fragment, useState } from 'react'
import Hotkeys from 'react-hot-keys'
import { projects } from '@prisma/client'
-import { nanoid } from 'nanoid'
-import { State, Block, methods, Method } from 'state/store'
-import { getStoreContext } from 'state/StoreProvider'
+import { Block, methods, Method } from 'state/store'
+import { useStateStore } from 'state/StoreProvider'
import Select from 'components/Select'
import Button from 'components/Button'
import Text from 'components/Text'
@@ -16,21 +14,14 @@ import BlockEditor from './BlockEditor'
import ConnectionLine from './ConnectionLine'
import AddBlockButton from './AddBlockButton'
import Logs from './Logs'
+import Routes from './Routes'
+import { useRouter } from 'next/router'
-// TODO: Prod api host
+// TODO: Prod API host
const apiHost = process.env.NODE_ENV === 'development' ?
'http://0.0.0.0:5000' :
'https://ai-api-service-7d2cl2hooq-uc.a.run.app'
-const selector = (state: State) => ({
- blocks: state.blocks,
- method: state.method,
- addBlock: state.addBlock,
- removeBlock: state.deleteBlock,
- changeBlock: state.changeBlock,
- changeMethod: state.changeMethod,
-})
-
export type Log = string
export interface Props {
@@ -39,19 +30,20 @@ export interface Props {
async function handlePostGenerate(url: string, { arg }: {
arg: {
- projectID: string,
- blocks: Block[],
- method: Method,
+ projectID: string
+ blocks: Block[]
+ method: Method
+ route: string
},
}) {
return await fetch(url, {
method: 'POST',
body: JSON.stringify({
- projectId: arg.projectID,
+ projectID: arg.projectID,
blocks: arg.blocks.map(b => b.prompt),
method: arg.method.toLowerCase(),
+ route: arg.route,
}),
-
headers: {
'Content-Type': 'application/json',
},
@@ -59,29 +51,32 @@ async function handlePostGenerate(url: string, { arg }: {
}
function Editor({ project }: Props) {
- const useStore = getStoreContext()
-
- const deployment = useLatestDeployment(project)
+ const router = useRouter()
+ const store = useStateStore()
+
+ const routes = store.use.routes()
+ const addBlock = store.use.addBlock()
+ const deleteBlock = store.use.deleteBlock()
+ const changeBlock = store.use.changeBlock()
+ const changeRoute = store.use.changeRoute()
+
+ const selectedRoute =
+ routes.find(r => r.id === router.query.route) ||
+ (routes.length > 0 ? routes[0] : undefined)
+ const deployment = useLatestDeployment(project, selectedRoute)
const logs = deployment?.logs as Log[] | undefined
- const code = deployment?.code
-
- const {
- addBlock,
- blocks,
- method,
- changeBlock,
- removeBlock,
- changeMethod,
- } = useStore(selector, shallow)
const [focusedBlock, setFocusedBlock] = useState({ index: 0 })
const { trigger: generate } = useSWRMutation(`${apiHost}/generate`, handlePostGenerate)
async function deploy() {
+ if (!selectedRoute) return
+
const response = await generate({
- blocks,
+ blocks: selectedRoute.blocks,
projectID: project.id,
- method,
+ method: selectedRoute.method,
+ route: selectedRoute.route,
})
console.log(response.code)
console.log(response.host)
@@ -92,9 +87,10 @@ function Editor({ project }: Props) {
keyName="command+enter,control+enter,shift+command+enter,shift+control+enter"
onKeyDown={(s) => {
if (s === 'command+enter' || s === 'control+enter') {
+ if (!selectedRoute) return
setFocusedBlock(b => {
- if (blocks.length === 0 || b.index === blocks.length - 1) {
- addBlock({ prompt: '', id: nanoid() })
+ if (selectedRoute.blocks.length === 0 || b.index === selectedRoute?.blocks.length - 1) {
+ addBlock(selectedRoute.id)
}
return { index: b.index + 1 }
})
@@ -108,8 +104,13 @@ function Editor({ project }: Props) {
allowRepeat
>
<div className="flex flex-row flex-1 overflow-hidden">
-
- <div className="
+ <Routes
+ routes={routes}
+ projectID={project.id}
+ />
+ {selectedRoute &&
+ <>
+ <div className="
flex
flex-1
p-8
@@ -119,67 +120,69 @@ function Editor({ project }: Props) {
scroller
relative
">
- <div className="flex items-center space-x-2">
- <Text
- text="Incoming"
- className='font-bold'
- />
- <Select
- direction="left"
- selectedValue={{ key: method, title: method.toUpperCase() }}
- values={methods.map(m => ({ key: m, title: m.toUpperCase() }))}
- onChange={m => changeMethod(m.key as Method)}
- />
- <Text
- text="Request"
- className='font-bold'
- />
- </div>
- <div className="
+ <div className="flex items-center space-x-2">
+ <Text
+ text="Incoming"
+ className='font-bold'
+ />
+ <Select
+ direction="left"
+ selectedValue={{ key: selectedRoute.method, title: selectedRoute.method.toUpperCase() }}
+ values={methods.map(m => ({ key: m, title: m.toUpperCase() }))}
+ onChange={m => changeRoute(selectedRoute.id, { method: m.key as Method })}
+ />
+ <Text
+ text="Request"
+ className='font-bold'
+ />
+ </div>
+ <div className="
flex
flex-col
items-center
transition-all
">
- {blocks.map((b, i) =>
- <Fragment
- key={b.id}
- >
- <ConnectionLine className='h-4' />
- <BlockEditor
- block={b}
- onDelete={() => {
- removeBlock(i)
- setTimeout(() => {
- if (i <= focusedBlock.index) {
- setFocusedBlock(b => ({ index: b.index - 1 }))
- } else {
- setFocusedBlock(b => ({ index: b.index }))
- }
- }, 0)
- }}
- onChange={(b) => changeBlock(i, b)}
- index={i}
- focus={focusedBlock}
- onFocus={() => setFocusedBlock({ index: i })}
+ {selectedRoute.blocks.map((b, i) =>
+ <Fragment
+ key={b.id}
+ >
+ <ConnectionLine className='h-4' />
+ <BlockEditor
+ block={b}
+ onDelete={() => {
+ deleteBlock(selectedRoute.id, i)
+ setTimeout(() => {
+ if (i <= focusedBlock.index) {
+ setFocusedBlock(b => ({ index: b.index - 1 }))
+ } else {
+ setFocusedBlock(b => ({ index: b.index }))
+ }
+ }, 0)
+ }}
+ onChange={(b) => changeBlock(selectedRoute.id, i, b)}
+ index={i}
+ focus={focusedBlock}
+ onFocus={() => setFocusedBlock({ index: i })}
+ />
+ </Fragment>
+ )}
+ </div>
+ <ConnectionLine className='min-h-[16px]' />
+ <AddBlockButton addBlock={(block) => {
+ addBlock(selectedRoute.id, block)
+ setTimeout(() => setFocusedBlock({ index: selectedRoute.blocks.length }), 0)
+ }} />
+ <div className="fixed right-3 top-14">
+ <Button
+ text="Deploy"
+ onClick={deploy}
+ variant={Button.variant.Full}
/>
- </Fragment>
- )}
- </div>
- <ConnectionLine className='min-h-[16px]' />
- <AddBlockButton addBlock={(block) => {
- addBlock(block)
- setTimeout(() => setFocusedBlock({ index: blocks.length }), 0)
- }} />
- <div className="fixed right-3 top-14">
- <Button
- text="Deploy"
- onClick={deploy}
- variant={Button.variant.Full}
- />
- </div>
- </div>
- {logs && <Logs logs={logs} />}
+ </div>
+ </div>
+ {logs && <Logs logs={logs} />}
+ </>
+ }
</div>
</Hotkeys>
)
diff --git a/pages/[projectID].tsx b/pages/[projectID].tsx
index fd3dea8b4..086493ec6 100644
--- a/pages/[projectID].tsx
+++ b/pages/[projectID].tsx
@@ -87,7 +87,9 @@ function EditorPage({ project }: Props) {
client={client}
initialState={project}
>
- <Editor project={project} />
+ <Editor
+ project={project}
+ />
</StoreProvider>
)
}
diff --git a/pages/api/project.ts b/pages/api/project.ts
index 1eaebd54f..38cf6cc9d 100644
--- a/pages/api/project.ts
+++ b/pages/api/project.ts
@@ -113,7 +113,7 @@ async function deleteProject(req: NextApiRequest, res: NextApiResponse) {
await prisma.deployments.deleteMany({
where: {
- project_id: project.id,
+ project_id: id,
},
})
diff --git a/state/StoreProvider.tsx b/state/StoreProvider.tsx
index 0ae007f85..e5c6d92b6 100644
--- a/state/StoreProvider.tsx
+++ b/state/StoreProvider.tsx
@@ -10,8 +10,12 @@ import { projects } from '@prisma/client'
import { Database } from 'db/supabase'
import { createStore } from './store'
+import { createSelectors } from './selectors'
-const storeContext = createContext<ReturnType<typeof createStore> | null>(null)
+type StoreType = ReturnType<typeof createStore>
+type SelectorsType = ReturnType<typeof createSelectors<StoreType>>
+
+const storeContext = createContext<SelectorsType | null>(null)
export interface Props extends PropsWithChildren {
initialState?: projects
@@ -24,15 +28,17 @@ export function StoreProvider({
children,
}: Props) {
const store = useMemo(() => createStore(initialState, client), [initialState, client])
+ const selectors = createSelectors(store)
+ const s = store(selectors.use.changeRoute)
return (
- <storeContext.Provider value={store}>
+ <storeContext.Provider value={selectors}>
{children}
</storeContext.Provider>
)
}
-export function getStoreContext() {
+export function useStateStore() {
// eslint-disable-next-line react-hooks/rules-of-hooks
const ctx = useContext(storeContext)
diff --git a/state/selectors.ts b/state/selectors.ts
new file mode 100644
index 000000000..cbacc08bb
--- /dev/null
+++ b/state/selectors.ts
@@ -0,0 +1,17 @@
+import { StoreApi, UseBoundStore } from 'zustand'
+
+type WithSelectors<S> = S extends { getState: () => infer T }
+ ? S & { use: { [K in keyof T]: () => T[K] } }
+ : never
+
+export const createSelectors = <S extends UseBoundStore<StoreApi<object>>>(
+ _store: S
+) => {
+ let store = _store as WithSelectors<typeof _store>
+ store.use = {}
+ for (let k of Object.keys(store.getState())) {
+ ; (store.use as any)[k] = () => store((s) => s[k as keyof typeof s])
+ }
+
+ return store
+}
diff --git a/state/store.ts b/state/store.ts
index 369585e1e..7ea0cab9e 100644
--- a/state/store.ts
+++ b/state/store.ts
@@ -2,10 +2,10 @@ import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { persist } from 'zustand/middleware'
import { SupabaseClient } from '@supabase/supabase-js'
+import { nanoid } from 'nanoid'
+import { projects, Prisma } from '@prisma/client'
import { Database } from 'db/supabase'
-import { nanoid } from 'nanoid'
-import { projects } from '@prisma/client'
import { projectsTable } from 'db/tables'
export interface Tool {
@@ -18,6 +18,13 @@ export interface Block {
prompt: string
}
+export interface Route {
+ blocks: Block[]
+ method: Method
+ route: string
+ id: string
+}
+
export enum Method {
POST = 'post',
GET = 'get',
@@ -31,70 +38,114 @@ export const methods = Object
.filter((item) => isNaN(Number(item)))
.map(v => v.toLowerCase())
-export interface State {
- blocks: Block[]
- method: Method
- changeBlock: (index: number, block: Partial<Block>) => void
- deleteBlock: (index: number) => void
- addBlock: (block: Block) => void
- changeMethod: (method: Method) => void
+export interface SerializedState {
+ routes: Route[]
}
-const defaultBlock: Block = { prompt: '', id: nanoid() }
-const defaultState: Pick<State, 'blocks' | 'method'> = {
- blocks: [defaultBlock],
- method: Method.POST,
+export interface State extends SerializedState {
+ changeBlock: (routeID: string, index: number, block: Partial<Omit<Block, 'id'>>) => void
+ deleteBlock: (routeID: string, index: number) => void
+ addBlock: (routeID: string, block?: Block) => void
+ changeRoute: (id: string, route: Partial<Omit<Route, 'id'>>) => void
+ deleteRoute: (id: string) => void
+ addRoute: (route?: Route) => void
}
-export function createStore(project?: projects, client?: SupabaseClient<Database>) {
- const state = (project?.data as any)?.state as Pick<State, 'blocks' | 'method'> || defaultState
+function getDefaultBlock(): Block {
+ return {
+ prompt: '',
+ id: nanoid(),
+ }
+}
- if (state.blocks.length === 0) {
- state.blocks.push(defaultBlock)
+function getDefaultRoute(): Route {
+ return {
+ blocks: [getDefaultBlock()],
+ method: Method.POST,
+ route: '/',
+ id: nanoid(),
}
+}
- state.blocks.forEach(s => {
- if (!s.id) {
- s.id = nanoid()
- }
- })
+function getDefaultState(): SerializedState {
+ return {
+ routes: [getDefaultRoute()],
+ }
+}
+
+export function getTypedState(data?: Prisma.JsonValue): SerializedState | undefined {
+ if (!data) return
+ if ('state' in (data as any)) {
+ return (data as any)['state'] as SerializedState
+ }
+}
+
+export function createStore(initialState?: projects, client?: SupabaseClient<Database>) {
+ const state = getTypedState(initialState?.data) || getDefaultState()
+
+ if (state.routes.length === 0) {
+ state.routes.push(getDefaultRoute())
+ }
const immerStore = immer<State>((set) => ({
...state,
- changeBlock: (index, block) =>
- set(state => {
- state.blocks[index] = { ...state.blocks[index], ...block }
- }),
- deleteBlock: (index) =>
+ addRoute: (route = getDefaultRoute()) => {
+ state.routes.push(route)
+ },
+ deleteRoute: (id) => {
+ state.routes = state.routes.filter(r => r.id !== id)
+ },
+ changeRoute: (id, route) => {
+ const idx = state.routes.findIndex(r => r.id === id)
+ if (idx > -1) {
+ state.routes[idx] = {
+ ...state.routes[idx],
+ ...route,
+ }
+ }
+ },
+ changeBlock: (routeID, index, block) =>
set(state => {
- state.blocks.splice(index, 1)
+ const idx = state.routes.findIndex(r => r.id === routeID)
+ if (idx > -1) {
+ state.routes[idx].blocks[index] = {
+ ...state.routes[idx].blocks[index],
+ ...block,
+ }
+ }
}),
- addBlock: (block) =>
+ deleteBlock: (routeID, index) =>
set(state => {
- state.blocks.push(block)
+ const idx = state.routes.findIndex(r => r.id === routeID)
+ if (idx > -1) {
+ state.routes[idx].blocks.splice(index, 1)
+ }
}),
- changeMethod: (method) =>
+ addBlock: (routeID, block = getDefaultBlock()) =>
set(state => {
- state.method = method
+ const idx = state.routes.findIndex(r => r.id === routeID)
+ if (idx > -1) {
+ state.routes[idx].blocks.push(block)
+ }
}),
}))
const persistent = persist(immerStore, {
name: 'supabase-storage',
partialize: (state) => state,
- storage: client && project ? {
+ storage: client && initialState ? {
getItem: async (name) => {
// We retrieve the data on the server
return null
},
removeItem: async () => {
- const res = await client.from(projectsTable).update({ data: {} }).eq('id', project.id).single()
+ const res = await client.from(projectsTable).update({ data: {} }).eq('project_id', initialState.id).single()
if (res.error) {
throw res.error
}
},
setItem: async (name, value) => {
- const res = await client.from(projectsTable).update({ data: value as any }).eq('id', project.id)
+ const res = await client.from(projectsTable).update({ data: value as any }).eq('project_id', initialState.id)
if (res.error) {
throw res.error
}