Merge branch 'main' into feat/profile-page

This commit is contained in:
Hamzat Victor Oluwabori 2024-11-25 23:10:21 +01:00 committed by GitHub
commit c653d34bc1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
79 changed files with 2716 additions and 5837 deletions

View File

@ -1,6 +1,7 @@
{ {
"tabWidth": 2, "tabWidth": 2,
"semi": false, "semi": false,
"singleQuote": false, "singleQuote": false,
"insertFinalNewline": true "insertFinalNewline": true,
} "useTabs": false
}

3
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"recommendations": ["esbenp.prettier-vscode"]
}

View File

@ -8,5 +8,6 @@
"tailwindCSS.experimental.classRegex": [ "tailwindCSS.experimental.classRegex": [
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"], ["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"],
["cx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"] ["cx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]
] ],
"editor.defaultFormatter": "esbenp.prettier-vscode"
} }

View File

@ -198,11 +198,13 @@ DOKKU_KEY=
Anyone can contribute a custom template for integration in Sandbox. Since Sandbox is built on E2B, there is no limitation to what langauge or runtime a Sandbox can use. Anyone can contribute a custom template for integration in Sandbox. Since Sandbox is built on E2B, there is no limitation to what langauge or runtime a Sandbox can use.
Currently there are four templates: Currently there are five templates:
- [jamesmurdza/dokku-reactjs-template](https://github.com/jamesmurdza/dokku-reactjs-template) - [jamesmurdza/dokku-reactjs-template](https://github.com/jamesmurdza/dokku-reactjs-template)
- [jamesmurdza/dokku-vanillajs-template](https://github.com/jamesmurdza/dokku-vanillajs-template) - [jamesmurdza/dokku-vanillajs-template](https://github.com/jamesmurdza/dokku-vanillajs-template)
- [jamesmurdza/dokku-nextjs-template](https://github.com/jamesmurdza/dokku-nextjs-template) - [jamesmurdza/dokku-nextjs-template](https://github.com/jamesmurdza/dokku-nextjs-template)
- [jamesmurdza/dokku-streamlit-template](https://github.com/jamesmurdza/dokku-streamlit-template) - [jamesmurdza/dokku-streamlit-template](https://github.com/jamesmurdza/dokku-streamlit-template)
- [omarrwd/dokku-php-template](https://github.com/omarrwd/dokku-php-template)
To create your own template, you can fork one of the above templates or start with a new blank repository. The template should have at least an `e2b.Dockerfile`, which is used by E2B to create the development environment. Optionally, a `Dockerfile` can be added which will be used to create the project build when it is deployed. To create your own template, you can fork one of the above templates or start with a new blank repository. The template should have at least an `e2b.Dockerfile`, which is used by E2B to create the development environment. Optionally, a `Dockerfile` can be added which will be used to create the project build when it is deployed.
@ -236,6 +238,7 @@ If you've done this and it works, let us know and we'll add your template to San
Note: In the future, we will add a way to specify the command triggered by the "Run" button (e.g. "npm run dev"). Note: In the future, we will add a way to specify the command triggered by the "Run" button (e.g. "npm run dev").
For more information, see: For more information, see:
- [Custom E2B Sandboxes](https://e2b.dev/docs/sandbox-template) - [Custom E2B Sandboxes](https://e2b.dev/docs/sandbox-template)
- [Dokku Builders](https://dokku.com/docs/deployment/builders/builder-management/) - [Dokku Builders](https://dokku.com/docs/deployment/builders/builder-management/)
@ -260,13 +263,13 @@ backend/
└── ai └── ai
``` ```
| Path | Description | | Path | Description |
| ------------------ | ------------------------------------------------------------ | | ------------------ | -------------------------------------------------------------------------- |
| `frontend` | The Next.js application for the frontend. | | `frontend` | The Next.js application for the frontend. |
| `backend/server` | The Express websocket server. | | `backend/server` | The Express websocket server. |
| `backend/database` | API for interfacing with the D1 database (SQLite). | | `backend/database` | API for interfacing with the D1 database (SQLite). |
| `backend/storage` | API for interfacing with R2 storage. Service-bound to `/backend/database`. | | `backend/storage` | API for interfacing with R2 storage. Service-bound to `/backend/database`. |
| `backend/ai` | API for making requests to Workers AI . | | `backend/ai` | API for making requests to Workers AI . |
### Development ### Development
@ -287,6 +290,10 @@ cd sandbox
git checkout -b my-new-branch git checkout -b my-new-branch
``` ```
### Code formatting
This repository uses [Prettier](https://marketplace.cursorapi.com/items?itemName=esbenp.prettier-vscode) for code formatting, which you will be prompted to install when you open the project. The formatting rules are specified in [.prettierrc](.prettierrc).
### Commit convention ### Commit convention
Before you create a Pull Request, please check that you use the [Conventional Commits format](https://www.conventionalcommits.org/en/v1.0.0/) Before you create a Pull Request, please check that you use the [Conventional Commits format](https://www.conventionalcommits.org/en/v1.0.0/)

View File

@ -1,12 +0,0 @@
# http://editorconfig.org
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_style = space

172
backend/ai/.gitignore vendored
View File

@ -1,172 +0,0 @@
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
\*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
\*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
\*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*
# wrangler project
.dev.vars
.wrangler/

File diff suppressed because it is too large Load Diff

View File

@ -1,22 +0,0 @@
{
"name": "ai",
"version": "0.0.0",
"private": true,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"start": "wrangler dev",
"test": "vitest",
"cf-typegen": "wrangler types"
},
"devDependencies": {
"@cloudflare/vitest-pool-workers": "^0.1.0",
"@cloudflare/workers-types": "^4.20240512.0",
"typescript": "^5.0.4",
"vitest": "1.3.0",
"wrangler": "^3.0.0"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.27.2"
}
}

View File

@ -1,128 +0,0 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { MessageParam } from "@anthropic-ai/sdk/src/resources/messages.js"
export interface Env {
ANTHROPIC_API_KEY: string
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Handle CORS preflight requests
if (request.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
},
})
}
if (request.method !== "GET" && request.method !== "POST") {
return new Response("Method Not Allowed", { status: 405 })
}
let body
let isEditCodeWidget = false
if (request.method === "POST") {
body = (await request.json()) as {
messages: unknown
context: unknown
activeFileContent: string
}
} else {
const url = new URL(request.url)
const fileName = url.searchParams.get("fileName") || ""
const code = url.searchParams.get("code") || ""
const line = url.searchParams.get("line") || ""
const instructions = url.searchParams.get("instructions") || ""
body = {
messages: [{ role: "human", content: instructions }],
context: `File: ${fileName}\nLine: ${line}\nCode:\n${code}`,
activeFileContent: code,
}
isEditCodeWidget = true
}
const messages = body.messages
const context = body.context
const activeFileContent = body.activeFileContent
if (!Array.isArray(messages) || messages.length === 0) {
return new Response("Invalid or empty messages", { status: 400 })
}
let systemMessage
if (isEditCodeWidget) {
systemMessage = `You are an AI code editor. Your task is to modify the given code based on the user's instructions. Only output the modified code, without any explanations or markdown formatting. The code should be a direct replacement for the existing code.
Context:
${context}
Active File Content:
${activeFileContent}
Instructions: ${messages[0].content}
Respond only with the modified code that can directly replace the existing code.`
} else {
systemMessage = `You are an intelligent programming assistant. Please respond to the following request concisely. If your response includes code, please format it using triple backticks (\`\`\`) with the appropriate language identifier. For example:
\`\`\`python
print("Hello, World!")
\`\`\`
Provide a clear and concise explanation along with any code snippets. Keep your response brief and to the point.
${context ? `Context:\n${context}\n` : ""}
${activeFileContent ? `Active File Content:\n${activeFileContent}\n` : ""}`
}
const anthropicMessages = messages.map((msg) => ({
role: msg.role === "human" ? "user" : "assistant",
content: msg.content,
})) as MessageParam[]
try {
const anthropic = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY })
const stream = await anthropic.messages.create({
model: "claude-3-5-sonnet-20240620",
max_tokens: 1024,
system: systemMessage,
messages: anthropicMessages,
stream: true,
})
const encoder = new TextEncoder()
const streamResponse = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
if (
chunk.type === "content_block_delta" &&
chunk.delta.type === "text_delta"
) {
const bytes = encoder.encode(chunk.delta.text)
controller.enqueue(bytes)
}
}
controller.close()
},
})
return new Response(streamResponse, {
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
})
} catch (error) {
console.error("Error:", error)
return new Response("Internal Server Error", { status: 500 })
}
},
}

View File

@ -1,30 +0,0 @@
// test/index.spec.ts
import {
createExecutionContext,
env,
SELF,
waitOnExecutionContext,
} from "cloudflare:test"
import { describe, expect, it } from "vitest"
import worker from "../src/index"
// For now, you'll need to do something like this to get a correctly-typed
// `Request` to pass to `worker.fetch()`.
const IncomingRequest = Request<unknown, IncomingRequestCfProperties>
describe("Hello World worker", () => {
it("responds with Hello World! (unit style)", async () => {
const request = new IncomingRequest("http://example.com")
// Create an empty context to pass to `worker.fetch()`.
const ctx = createExecutionContext()
const response = await worker.fetch(request, env, ctx)
// Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions
await waitOnExecutionContext(ctx)
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`)
})
it("responds with Hello World! (integration style)", async () => {
const response = await SELF.fetch("https://example.com")
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`)
})
})

View File

@ -1,11 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": [
"@cloudflare/workers-types/experimental",
"@cloudflare/vitest-pool-workers"
]
},
"include": ["./**/*.ts", "../src/env.d.ts"],
"exclude": []
}

View File

@ -1,106 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": [
"es2021"
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
"jsx": "react" /* Specify what JSX code is generated. */,
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "es2022" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "Bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
"types": [
"@cloudflare/workers-types/2023-07-01"
] /* Specify type package names to be included without being referenced in a source file. */,
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"resolveJsonModule": true /* Enable importing .json files */,
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
"checkJs": false /* Enable error reporting in type-checked JavaScript files. */,
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true /* Disable emitting files from a compilation. */,
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
"isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
"allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
// "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"exclude": ["test"]
}

View File

@ -1,11 +0,0 @@
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"
export default defineWorkersConfig({
test: {
poolOptions: {
workers: {
wrangler: { configPath: "./wrangler.toml" },
},
},
},
})

View File

@ -1,3 +0,0 @@
// Generated by Wrangler
// After adding bindings to `wrangler.toml`, regenerate this interface via `npm run cf-typegen`
interface Env {}

View File

@ -1,10 +0,0 @@
name = "ai"
main = "src/index.ts"
compatibility_date = "2024-05-12"
compatibility_flags = ["nodejs_compat"]
[ai]
binding = "AI"
[vars]
ANTHROPIC_API_KEY = ""

View File

@ -1,7 +1,7 @@
{ {
"version": "5", "version": "5",
"dialect": "sqlite", "dialect": "sqlite",
"id": "afe10bff-362b-402c-bdb5-038341692f35", "id": "1288b006-6410-4b1c-8c96-d9797878a116",
"prevId": "00000000-0000-0000-0000-000000000000", "prevId": "00000000-0000-0000-0000-000000000000",
"tables": { "tables": {
"sandbox": { "sandbox": {
@ -140,13 +140,6 @@
"autoincrement": false, "autoincrement": false,
"default": "CURRENT_TIMESTAMP" "default": "CURRENT_TIMESTAMP"
}, },
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"generations": { "generations": {
"name": "generations", "name": "generations",
"type": "integer", "type": "integer",
@ -154,6 +147,28 @@
"notNull": false, "notNull": false,
"autoincrement": false, "autoincrement": false,
"default": 0 "default": 0
},
"tier": {
"name": "tier",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'FREE'"
},
"tierExpiresAt": {
"name": "tierExpiresAt",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lastResetDate": {
"name": "lastResetDate",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
} }
}, },
"indexes": { "indexes": {

View File

@ -1,236 +0,0 @@
{
"version": "5",
"dialect": "sqlite",
"id": "e570d5ac-700d-4e62-8a46-482b21ae1fe1",
"prevId": "afe10bff-362b-402c-bdb5-038341692f35",
"tables": {
"sandbox": {
"name": "sandbox",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"visibility": {
"name": "visibility",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"createdAt": {
"name": "createdAt",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"likeCount": {
"name": "likeCount",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"viewCount": {
"name": "viewCount",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
}
},
"indexes": {
"sandbox_id_unique": {
"name": "sandbox_id_unique",
"columns": [
"id"
],
"isUnique": true
}
},
"foreignKeys": {
"sandbox_user_id_user_id_fk": {
"name": "sandbox_user_id_user_id_fk",
"tableFrom": "sandbox",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
},
"user": {
"name": "user",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"username": {
"name": "username",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"avatarUrl": {
"name": "avatarUrl",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"createdAt": {
"name": "createdAt",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
},
"generations": {
"name": "generations",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
}
},
"indexes": {
"user_id_unique": {
"name": "user_id_unique",
"columns": [
"id"
],
"isUnique": true
},
"user_username_unique": {
"name": "user_username_unique",
"columns": [
"username"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
},
"users_to_sandboxes": {
"name": "users_to_sandboxes",
"columns": {
"userId": {
"name": "userId",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sandboxId": {
"name": "sandboxId",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sharedOn": {
"name": "sharedOn",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"users_to_sandboxes_userId_user_id_fk": {
"name": "users_to_sandboxes_userId_user_id_fk",
"tableFrom": "users_to_sandboxes",
"tableTo": "user",
"columnsFrom": [
"userId"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"users_to_sandboxes_sandboxId_sandbox_id_fk": {
"name": "users_to_sandboxes_sandboxId_sandbox_id_fk",
"tableFrom": "users_to_sandboxes",
"tableTo": "sandbox",
"columnsFrom": [
"sandboxId"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
}
},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
}
}

View File

@ -5,29 +5,8 @@
{ {
"idx": 0, "idx": 0,
"version": "5", "version": "5",
"when": 1731288423588, "when": 1732568535771,
"tag": "0000_cuddly_patriot", "tag": "0000_rapid_korath",
"breakpoints": true
},
{
"idx": 1,
"version": "5",
"when": 1731290863632,
"tag": "0001_opposite_newton_destine",
"breakpoints": true
},
{
"idx": 2,
"version": "5",
"when": 1731296235880,
"tag": "0002_rainy_fantastic_four",
"breakpoints": true
},
{
"idx": 3,
"version": "5",
"when": 1731297339306,
"tag": "0003_lying_snowbird",
"breakpoints": true "breakpoints": true
} }
] ]

View File

@ -245,114 +245,6 @@ export default {
return success return success
} else return methodNotAllowed } else return methodNotAllowed
} else if (path === "/api/sandbox/generate" && method === "POST") {
const generateSchema = z.object({
userId: z.string(),
})
const body = await request.json()
const { userId } = generateSchema.parse(body)
const dbUser = await db.query.user.findFirst({
where: (user, { eq }) => eq(user.id, userId),
})
if (!dbUser) {
return new Response("User not found.", { status: 400 })
}
if (dbUser.generations !== null && dbUser.generations >= 10) {
return new Response("You reached the maximum # of generations.", {
status: 400,
})
}
await db
.update(user)
.set({ generations: sql`${user.generations} + 1` })
.where(eq(user.id, userId))
.get()
return success
} else if (path === "/api/sandbox/like") {
if (method === "POST") {
const likeSchema = z.object({
sandboxId: z.string(),
userId: z.string(),
})
try {
const body = await request.json()
const { sandboxId, userId } = likeSchema.parse(body)
// Check if user has already liked
const existingLike = await db.query.sandboxLikes.findFirst({
where: (likes, { and, eq }) =>
and(eq(likes.sandboxId, sandboxId), eq(likes.userId, userId)),
})
if (existingLike) {
// Unlike
await db
.delete(sandboxLikes)
.where(
and(
eq(sandboxLikes.sandboxId, sandboxId),
eq(sandboxLikes.userId, userId)
)
)
await db
.update(sandbox)
.set({
likeCount: sql`${sandbox.likeCount} - 1`,
})
.where(eq(sandbox.id, sandboxId))
return json({
message: "Unlike successful",
liked: false,
})
} else {
// Like
await db.insert(sandboxLikes).values({
sandboxId,
userId,
createdAt: new Date(),
})
await db
.update(sandbox)
.set({
likeCount: sql`${sandbox.likeCount} + 1`,
})
.where(eq(sandbox.id, sandboxId))
return json({
message: "Like successful",
liked: true,
})
}
} catch (error) {
return new Response("Invalid request format", { status: 400 })
}
} else if (method === "GET") {
const params = url.searchParams
const sandboxId = params.get("sandboxId")
const userId = params.get("userId")
if (!sandboxId || !userId) {
return invalidRequest
}
const like = await db.query.sandboxLikes.findFirst({
where: (likes, { and, eq }) =>
and(eq(likes.sandboxId, sandboxId), eq(likes.userId, userId)),
})
return json({
liked: !!like,
})
} else {
return methodNotAllowed
}
} else if (path === "/api/user") { } else if (path === "/api/user") {
if (method === "GET") { if (method === "GET") {
const params = url.searchParams const params = url.searchParams
@ -426,12 +318,14 @@ export default {
avatarUrl: z.string().optional(), avatarUrl: z.string().optional(),
createdAt: z.string().optional(), createdAt: z.string().optional(),
generations: z.number().optional(), generations: z.number().optional(),
tier: z.enum(["FREE", "PRO", "ENTERPRISE"]).optional(),
tierExpiresAt: z.number().optional(),
lastResetDate: z.number().optional(),
}) })
const body = await request.json() const body = await request.json()
const { id, name, email, username, avatarUrl, createdAt, generations } =
userSchema.parse(body)
const { id, name, email, username, avatarUrl, createdAt, generations, tier, tierExpiresAt, lastResetDate } = userSchema.parse(body)
const res = await db const res = await db
.insert(user) .insert(user)
.values({ .values({
@ -442,6 +336,9 @@ export default {
avatarUrl, avatarUrl,
createdAt: createdAt ? new Date(createdAt) : new Date(), createdAt: createdAt ? new Date(createdAt) : new Date(),
generations, generations,
tier,
tierExpiresAt,
lastResetDate,
}) })
.returning() .returning()
.get() .get()
@ -521,6 +418,76 @@ export default {
return json({ exists: !!exists }) return json({ exists: !!exists })
} }
return methodNotAllowed return methodNotAllowed
} else if (path === "/api/user/increment-generations" && method === "POST") {
const schema = z.object({
userId: z.string(),
})
const body = await request.json()
const { userId } = schema.parse(body)
await db
.update(user)
.set({ generations: sql`${user.generations} + 1` })
.where(eq(user.id, userId))
.get()
return success
} else if (path === "/api/user/update-tier" && method === "POST") {
const schema = z.object({
userId: z.string(),
tier: z.enum(["FREE", "PRO", "ENTERPRISE"]),
tierExpiresAt: z.date(),
})
const body = await request.json()
const { userId, tier, tierExpiresAt } = schema.parse(body)
await db
.update(user)
.set({
tier,
tierExpiresAt: tierExpiresAt.getTime(),
// Reset generations when upgrading tier
generations: 0
})
.where(eq(user.id, userId))
.get()
return success
} else if (path === "/api/user/check-reset" && method === "POST") {
const schema = z.object({
userId: z.string(),
})
const body = await request.json()
const { userId } = schema.parse(body)
const dbUser = await db.query.user.findFirst({
where: (user, { eq }) => eq(user.id, userId),
})
if (!dbUser) {
return new Response("User not found", { status: 404 })
}
const now = new Date()
const lastReset = dbUser.lastResetDate ? new Date(dbUser.lastResetDate) : new Date(0)
if (now.getMonth() !== lastReset.getMonth() || now.getFullYear() !== lastReset.getFullYear()) {
await db
.update(user)
.set({
generations: 0,
lastResetDate: now.getTime()
})
.where(eq(user.id, userId))
.get()
return new Response("Reset successful", { status: 200 })
}
return new Response("No reset needed", { status: 200 })
} else return notFound } else return notFound
}, },
} }

View File

@ -16,6 +16,9 @@ export const user = sqliteTable("user", {
sql`CURRENT_TIMESTAMP` sql`CURRENT_TIMESTAMP`
), ),
generations: integer("generations").default(0), generations: integer("generations").default(0),
tier: text("tier", { enum: ["FREE", "PRO", "ENTERPRISE"] }).default("FREE"),
tierExpiresAt: integer("tierExpiresAt"),
lastResetDate: integer("lastResetDate"),
}) })
export type User = typeof user.$inferSelect export type User = typeof user.$inferSelect

File diff suppressed because it is too large Load Diff

View File

@ -14,8 +14,9 @@
"concurrently": "^8.2.2", "concurrently": "^8.2.2",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"e2b": "^0.16.2-beta.47", "e2b": "^1.0.5",
"express": "^4.19.2", "express": "^4.19.2",
"jzip": "^1.0.0",
"rate-limiter-flexible": "^5.0.3", "rate-limiter-flexible": "^5.0.3",
"simple-git": "^3.25.0", "simple-git": "^3.25.0",
"socket.io": "^4.7.5", "socket.io": "^4.7.5",
@ -25,10 +26,11 @@
"devDependencies": { "devDependencies": {
"@types/cors": "^2.8.17", "@types/cors": "^2.8.17",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/jszip": "^3.4.1",
"@types/node": "^20.12.7", "@types/node": "^20.12.7",
"@types/ssh2": "^1.15.0", "@types/ssh2": "^1.15.0",
"nodemon": "^3.1.0", "nodemon": "^3.1.0",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "^5.4.5" "typescript": "^5.4.5"
} }
} }

View File

@ -1,90 +0,0 @@
// AIWorker class for handling AI-related operations
export class AIWorker {
private aiWorkerUrl: string
private cfAiKey: string
private databaseWorkerUrl: string
private workersKey: string
// Constructor to initialize AIWorker with necessary URLs and keys
constructor(
aiWorkerUrl: string,
cfAiKey: string,
databaseWorkerUrl: string,
workersKey: string
) {
this.aiWorkerUrl = aiWorkerUrl
this.cfAiKey = cfAiKey
this.databaseWorkerUrl = databaseWorkerUrl
this.workersKey = workersKey
}
// Method to generate code based on user input
async generateCode(
userId: string,
fileName: string,
code: string,
line: number,
instructions: string
): Promise<{ response: string; success: boolean }> {
try {
const fetchPromise = fetch(
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({
userId: userId,
}),
}
)
// Generate code from cloudflare workers AI
const generateCodePromise = fetch(
`${process.env.AI_WORKER_URL}/api?fileName=${encodeURIComponent(
fileName
)}&code=${encodeURIComponent(code)}&line=${encodeURIComponent(
line
)}&instructions=${encodeURIComponent(instructions)}`,
{
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.CF_AI_KEY}`,
},
}
)
const [fetchResponse, generateCodeResponse] = await Promise.all([
fetchPromise,
generateCodePromise,
])
if (!generateCodeResponse.ok) {
throw new Error(`HTTP error! status: ${generateCodeResponse.status}`)
}
const reader = generateCodeResponse.body?.getReader()
const decoder = new TextDecoder()
let result = ""
if (reader) {
while (true) {
const { done, value } = await reader.read()
if (done) break
result += decoder.decode(value, { stream: true })
}
}
// The result should now contain only the modified code
return { response: result.trim(), success: true }
} catch (e: any) {
console.error("Error generating code:", e)
return {
response: "Error generating code. Please try again.",
success: false,
}
}
}
}

View File

@ -1,58 +1,61 @@
import { Socket } from "socket.io" import { Socket } from "socket.io"
class Counter { class Counter {
private count: number = 0 private count: number = 0
increment() { increment() {
this.count++ this.count++
} }
decrement() { decrement() {
this.count = Math.max(0, this.count - 1) this.count = Math.max(0, this.count - 1)
} }
getValue(): number { getValue(): number {
return this.count return this.count
} }
} }
// Owner Connection Management // Owner Connection Management
export class ConnectionManager { export class ConnectionManager {
// Counts how many times the owner is connected to a sandbox // Counts how many times the owner is connected to a sandbox
private ownerConnections: Record<string, Counter> = {} private ownerConnections: Record<string, Counter> = {}
// Stores all sockets connected to a given sandbox // Stores all sockets connected to a given sandbox
private sockets: Record<string, Set<Socket>> = {} private sockets: Record<string, Set<Socket>> = {}
// Checks if the owner of a sandbox is connected // Checks if the owner of a sandbox is connected
ownerIsConnected(sandboxId: string): boolean { ownerIsConnected(sandboxId: string): boolean {
return this.ownerConnections[sandboxId]?.getValue() > 0 return this.ownerConnections[sandboxId]?.getValue() > 0
}
// Adds a connection for a sandbox
addConnectionForSandbox(socket: Socket, sandboxId: string, isOwner: boolean) {
this.sockets[sandboxId] ??= new Set()
this.sockets[sandboxId].add(socket)
// If the connection is for the owner, increments the owner connection counter
if (isOwner) {
this.ownerConnections[sandboxId] ??= new Counter()
this.ownerConnections[sandboxId].increment()
} }
}
// Adds a connection for a sandbox // Removes a connection for a sandbox
addConnectionForSandbox(socket: Socket, sandboxId: string, isOwner: boolean) { removeConnectionForSandbox(
this.sockets[sandboxId] ??= new Set() socket: Socket,
this.sockets[sandboxId].add(socket) sandboxId: string,
isOwner: boolean
) {
this.sockets[sandboxId]?.delete(socket)
// If the connection is for the owner, increments the owner connection counter // If the connection being removed is for the owner, decrements the owner connection counter
if (isOwner) { if (isOwner) {
this.ownerConnections[sandboxId] ??= new Counter() this.ownerConnections[sandboxId]?.decrement()
this.ownerConnections[sandboxId].increment()
}
} }
}
// Removes a connection for a sandbox // Returns the set of sockets connected to a given sandbox
removeConnectionForSandbox(socket: Socket, sandboxId: string, isOwner: boolean) { connectionsForSandbox(sandboxId: string): Set<Socket> {
this.sockets[sandboxId]?.delete(socket) return this.sockets[sandboxId] ?? new Set()
}
// If the connection being removed is for the owner, decrements the owner connection counter }
if (isOwner) {
this.ownerConnections[sandboxId]?.decrement()
}
}
// Returns the set of sockets connected to a given sandbox
connectionsForSandbox(sandboxId: string): Set<Socket> {
return this.sockets[sandboxId] ?? new Set();
}
}

View File

@ -1,4 +1,5 @@
import { FilesystemEvent, Sandbox, WatchHandle } from "e2b" import { FilesystemEvent, Sandbox, WatchHandle } from "e2b"
import JSZip from "jszip"
import path from "path" import path from "path"
import RemoteFileStorage from "./RemoteFileStorage" import RemoteFileStorage from "./RemoteFileStorage"
import { MAX_BODY_SIZE } from "./ratelimit" import { MAX_BODY_SIZE } from "./ratelimit"
@ -23,7 +24,11 @@ function generateFileStructure(paths: string[]): (TFolder | TFile)[] {
} }
} else { } else {
if (isFile) { if (isFile) {
const file: TFile = { id: `/${parts.join("/")}`, type: "file", name: part } const file: TFile = {
id: `/${parts.join("/")}`,
type: "file",
name: part,
}
current.children.push(file) current.children.push(file)
} else { } else {
const folder: TFolder = { const folder: TFolder = {
@ -75,7 +80,9 @@ export class FileManager {
if (isFile) { if (isFile) {
const fileId = `/${parts.join("/")}` const fileId = `/${parts.join("/")}`
const data = await RemoteFileStorage.fetchFileContent(`projects/${this.sandboxId}${fileId}`) const data = await RemoteFileStorage.fetchFileContent(
`projects/${this.sandboxId}${fileId}`
)
fileData.push({ id: fileId, data }) fileData.push({ id: fileId, data })
} }
} }
@ -91,7 +98,7 @@ export class FileManager {
// Convert remote file path to local file path // Convert remote file path to local file path
private getLocalFileId(remoteId: string): string | undefined { private getLocalFileId(remoteId: string): string | undefined {
const allParts = remoteId.split("/") const allParts = remoteId.split("/")
if (allParts[1] !== this.sandboxId) return undefined; if (allParts[1] !== this.sandboxId) return undefined
return allParts.slice(2).join("/") return allParts.slice(2).join("/")
} }
@ -99,7 +106,7 @@ export class FileManager {
private getLocalFileIds(remoteIds: string[]): string[] { private getLocalFileIds(remoteIds: string[]): string[] {
return remoteIds return remoteIds
.map(this.getLocalFileId.bind(this)) .map(this.getLocalFileId.bind(this))
.filter((id) => id !== undefined); .filter((id) => id !== undefined)
} }
// Download files from remote storage // Download files from remote storage
@ -118,9 +125,21 @@ export class FileManager {
return this.files return this.files
} }
private async loadLocalFiles() {
// Reload file list from the container to include template files
const result = await this.sandbox.commands.run(
`find "${this.dirName}" -type f`
) // List all files recursively
const localPaths = result.stdout.split("\n").filter((path) => path) // Split the output into an array and filter out empty strings
const relativePaths = localPaths.map((filePath) =>
path.posix.relative(this.dirName, filePath)
) // Convert absolute paths to relative paths
this.files = generateFileStructure(relativePaths)
}
// Initialize the FileManager // Initialize the FileManager
async initialize() { async initialize() {
// Download files from remote file storage // Download files from remote file storage
await this.updateFileStructure() await this.updateFileStructure()
await this.updateFileData() await this.updateFileData()
@ -140,11 +159,7 @@ export class FileManager {
}) })
await Promise.all(promises) await Promise.all(promises)
// Reload file list from the container to include template files await this.loadLocalFiles()
const result = await this.sandbox.commands.run(`find "${this.dirName}" -type f`); // List all files recursively
const localPaths = result.stdout.split('\n').filter(path => path); // Split the output into an array and filter out empty strings
const relativePaths = localPaths.map(filePath => path.posix.relative(this.dirName, filePath)); // Convert absolute paths to relative paths
this.files = generateFileStructure(relativePaths);
// Make the logged in user the owner of all project files // Make the logged in user the owner of all project files
this.fixPermissions() this.fixPermissions()
@ -169,9 +184,7 @@ export class FileManager {
// Change the owner of the project directory to user // Change the owner of the project directory to user
private async fixPermissions() { private async fixPermissions() {
try { try {
await this.sandbox.commands.run( await this.sandbox.commands.run(`sudo chown -R user "${this.dirName}"`)
`sudo chown -R user "${this.dirName}"`
)
} catch (e: any) { } catch (e: any) {
console.log("Failed to fix permissions: " + e) console.log("Failed to fix permissions: " + e)
} }
@ -180,7 +193,7 @@ export class FileManager {
// Watch a directory for changes // Watch a directory for changes
async watchDirectory(directory: string): Promise<WatchHandle | undefined> { async watchDirectory(directory: string): Promise<WatchHandle | undefined> {
try { try {
const handle = await this.sandbox.files.watch( const handle = await this.sandbox.files.watchDir(
directory, directory,
async (event: FilesystemEvent) => { async (event: FilesystemEvent) => {
try { try {
@ -193,7 +206,10 @@ export class FileManager {
// This is the absolute file path in the container // This is the absolute file path in the container
const containerFilePath = path.posix.join(directory, event.name) const containerFilePath = path.posix.join(directory, event.name)
// This is the file path relative to the project directory // This is the file path relative to the project directory
const sandboxFilePath = removeDirName(containerFilePath, this.dirName) const sandboxFilePath = removeDirName(
containerFilePath,
this.dirName
)
// This is the directory being watched relative to the project directory // This is the directory being watched relative to the project directory
const sandboxDirectory = removeDirName(directory, this.dirName) const sandboxDirectory = removeDirName(directory, this.dirName)
@ -210,77 +226,13 @@ export class FileManager {
// Handle file/directory creation event // Handle file/directory creation event
if (event.type === "create") { if (event.type === "create") {
const folder = findFolderById( await this.loadLocalFiles()
this.files,
sandboxDirectory
) as TFolder
const isDir = await this.isDirectory(containerFilePath)
const newItem = isDir
? ({
id: sandboxFilePath,
name: event.name,
type: "folder",
children: [],
} as TFolder)
: ({
id: sandboxFilePath,
name: event.name,
type: "file",
} as TFile)
if (folder) {
// If the folder exists, add the new item (file/folder) as a child
folder.children.push(newItem)
} else {
// If folder doesn't exist, add the new item to the root
this.files.push(newItem)
}
if (!isDir) {
const fileData = await this.sandbox.files.read(
containerFilePath
)
const fileContents =
typeof fileData === "string" ? fileData : ""
this.fileData.push({
id: sandboxFilePath,
data: fileContents,
})
}
console.log(`Create ${sandboxFilePath}`) console.log(`Create ${sandboxFilePath}`)
} }
// Handle file/directory removal or rename event // Handle file/directory removal or rename event
else if (event.type === "remove" || event.type == "rename") { else if (event.type === "remove" || event.type == "rename") {
const folder = findFolderById( await this.loadLocalFiles()
this.files,
sandboxDirectory
) as TFolder
const isDir = await this.isDirectory(containerFilePath)
const isFileMatch = (file: TFolder | TFile | TFileData) =>
file.id === sandboxFilePath ||
file.id.startsWith(containerFilePath + "/")
if (folder) {
// Remove item from its parent folder
folder.children = folder.children.filter(
(file: TFolder | TFile) => !isFileMatch(file)
)
} else {
// Remove from the root if it's not inside a folder
this.files = this.files.filter(
(file: TFolder | TFile) => !isFileMatch(file)
)
}
// Also remove any corresponding file data
this.fileData = this.fileData.filter(
(file: TFileData) => !isFileMatch(file)
)
console.log(`Removed: ${sandboxFilePath}`) console.log(`Removed: ${sandboxFilePath}`)
} }
@ -330,7 +282,7 @@ export class FileManager {
) )
} }
}, },
{ timeout: 0 } { timeoutMs: 0 }
) )
this.fileWatchers.push(handle) this.fileWatchers.push(handle)
return handle return handle
@ -361,7 +313,9 @@ export class FileManager {
// Get folder content // Get folder content
async getFolder(folderId: string): Promise<string[]> { async getFolder(folderId: string): Promise<string[]> {
const remotePaths = await RemoteFileStorage.getFolder(this.getRemoteFileId(folderId)) const remotePaths = await RemoteFileStorage.getFolder(
this.getRemoteFileId(folderId)
)
return this.getLocalFileIds(remotePaths) return this.getLocalFileIds(remotePaths)
} }
@ -373,11 +327,20 @@ export class FileManager {
throw new Error("File size too large. Please reduce the file size.") throw new Error("File size too large. Please reduce the file size.")
} }
await RemoteFileStorage.saveFile(this.getRemoteFileId(fileId), body) await RemoteFileStorage.saveFile(this.getRemoteFileId(fileId), body)
const file = this.fileData.find((f) => f.id === fileId)
if (!file) return
file.data = body
await this.sandbox.files.write(path.posix.join(this.dirName, file.id), body) let file = this.fileData.find((f) => f.id === fileId)
if (file) {
file.data = body
} else {
// If the file wasn't in our cache, add it
file = {
id: fileId,
data: body,
}
this.fileData.push(file)
}
await this.sandbox.files.write(path.posix.join(this.dirName, fileId), body)
this.fixPermissions() this.fixPermissions()
} }
@ -400,7 +363,11 @@ export class FileManager {
fileData.id = newFileId fileData.id = newFileId
file.id = newFileId file.id = newFileId
await RemoteFileStorage.renameFile(this.getRemoteFileId(fileId), this.getRemoteFileId(newFileId), fileData.data) await RemoteFileStorage.renameFile(
this.getRemoteFileId(fileId),
this.getRemoteFileId(newFileId),
fileData.data
)
return this.updateFileStructure() return this.updateFileStructure()
} }
@ -432,22 +399,88 @@ export class FileManager {
await this.sandbox.files.write(path.posix.join(this.dirName, id), "") await this.sandbox.files.write(path.posix.join(this.dirName, id), "")
await this.fixPermissions() await this.fixPermissions()
this.files.push({
id,
name,
type: "file",
})
this.fileData.push({
id,
data: "",
})
await RemoteFileStorage.createFile(this.getRemoteFileId(id)) await RemoteFileStorage.createFile(this.getRemoteFileId(id))
return true return true
} }
public async loadFileContent(): Promise<TFileData[]> {
// Get all file paths, excluding node_modules
const result = await this.sandbox.commands.run(
`find "${this.dirName}" -path "${this.dirName}/node_modules" -prune -o -type f -print`
)
const filePaths = result.stdout.split("\n").filter((path) => path) ?? []
console.log("Paths found for download (excluding node_modules):", filePaths)
// Add files to zip with synchronized content
for (const filePath of filePaths) {
const relativePath = filePath.replace(this.dirName, "") // Remove base directory from path
try {
// Read the file content from the sandbox
const content = await this.sandbox.files.read(filePath)
// Find the existing file data entry or create a new one
const fileDataEntry = this.fileData.find(
(f) => f.id === relativePath
) || {
id: relativePath,
data: typeof content === "string" ? content : "",
}
// Update the file data entry if it already exists, otherwise add it to the list
if (!this.fileData.includes(fileDataEntry)) {
this.fileData.push(fileDataEntry)
} else {
fileDataEntry.data = typeof content === "string" ? content : ""
}
} catch (error) {
console.error(`Failed to read content for ${relativePath}:`, error)
}
}
return this.fileData
}
public async getFilesForDownload(): Promise<string> {
// Create new JSZip instance
const zip = new JSZip()
await this.loadFileContent()
if (this.fileData.length === 0) {
console.error(
"No files found in the sandbox project directory for download."
)
return ""
}
// Add files to zip with synchronized content
for (const fileDataEntry of this.fileData) {
const relativePath = fileDataEntry.id
const content = fileDataEntry.data
zip.file(relativePath, content)
console.log(`Added file to ZIP: ${relativePath}`)
}
// Generate zip file
const zipBlob = await zip.generateAsync({
type: "blob",
compression: "DEFLATE",
compressionOptions: {
level: 6,
},
})
// Convert Blob to Base64
const zipBlobArrayBuffer = await zipBlob.arrayBuffer()
const zipBlobBase64 = btoa(
String.fromCharCode(...new Uint8Array(zipBlobArrayBuffer))
)
return zipBlobBase64
}
// Create a new folder // Create a new folder
async createFolder(name: string): Promise<void> { async createFolder(name: string): Promise<void> {
const id = `/${name}` const id = `/${name}`
@ -465,7 +498,11 @@ export class FileManager {
await this.moveFileInContainer(fileId, newFileId) await this.moveFileInContainer(fileId, newFileId)
await this.fixPermissions() await this.fixPermissions()
await RemoteFileStorage.renameFile(this.getRemoteFileId(fileId), this.getRemoteFileId(newFileId), fileData.data) await RemoteFileStorage.renameFile(
this.getRemoteFileId(fileId),
this.getRemoteFileId(newFileId),
fileData.data
)
fileData.id = newFileId fileData.id = newFileId
file.id = newFileId file.id = newFileId
@ -477,9 +514,6 @@ export class FileManager {
if (!file) return this.files if (!file) return this.files
await this.sandbox.files.remove(path.posix.join(this.dirName, fileId)) await this.sandbox.files.remove(path.posix.join(this.dirName, fileId))
this.fileData = this.fileData.filter(
(f) => f.id !== fileId
)
await RemoteFileStorage.deleteFile(this.getRemoteFileId(fileId)) await RemoteFileStorage.deleteFile(this.getRemoteFileId(fileId))
return this.updateFileStructure() return this.updateFileStructure()
@ -487,14 +521,13 @@ export class FileManager {
// Delete a folder // Delete a folder
async deleteFolder(folderId: string): Promise<(TFolder | TFile)[]> { async deleteFolder(folderId: string): Promise<(TFolder | TFile)[]> {
const files = await RemoteFileStorage.getFolder(this.getRemoteFileId(folderId)) const files = await RemoteFileStorage.getFolder(
this.getRemoteFileId(folderId)
)
await Promise.all( await Promise.all(
files.map(async (file) => { files.map(async (file) => {
await this.sandbox.files.remove(path.posix.join(this.dirName, file)) await this.sandbox.files.remove(path.posix.join(this.dirName, file))
this.fileData = this.fileData.filter(
(f) => f.id !== file
)
await RemoteFileStorage.deleteFile(this.getRemoteFileId(file)) await RemoteFileStorage.deleteFile(this.getRemoteFileId(file))
}) })
) )
@ -506,7 +539,7 @@ export class FileManager {
async closeWatchers() { async closeWatchers() {
await Promise.all( await Promise.all(
this.fileWatchers.map(async (handle: WatchHandle) => { this.fileWatchers.map(async (handle: WatchHandle) => {
await handle.close() await handle.stop()
}) })
) )
} }

View File

@ -61,11 +61,7 @@ export const RemoteFileStorage = {
return res.ok return res.ok
}, },
renameFile: async ( renameFile: async (fileId: string, newFileId: string, data: string) => {
fileId: string,
newFileId: string,
data: string
) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, { const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, {
method: "POST", method: "POST",
headers: { headers: {
@ -111,7 +107,7 @@ export const RemoteFileStorage = {
} }
) )
return (await res.json()).size return (await res.json()).size
} },
} }
export default RemoteFileStorage export default RemoteFileStorage

View File

@ -1,262 +1,269 @@
import { Sandbox as E2BSandbox } from "e2b" import { Sandbox as E2BSandbox } from "e2b"
import { Socket } from "socket.io" import { Socket } from "socket.io"
import { AIWorker } from "./AIWorker"
import { CONTAINER_TIMEOUT } from "./constants" import { CONTAINER_TIMEOUT } from "./constants"
import { DokkuClient } from "./DokkuClient" import { DokkuClient } from "./DokkuClient"
import { FileManager } from "./FileManager" import { FileManager } from "./FileManager"
import { import {
createFileRL, createFileRL,
createFolderRL, createFolderRL,
deleteFileRL, deleteFileRL,
renameFileRL, renameFileRL,
saveFileRL, saveFileRL,
} from "./ratelimit" } from "./ratelimit"
import { SecureGitClient } from "./SecureGitClient" import { SecureGitClient } from "./SecureGitClient"
import { TerminalManager } from "./TerminalManager" import { TerminalManager } from "./TerminalManager"
import { TFile, TFileData, TFolder } from "./types" import { TFile, TFolder } from "./types"
import { LockManager } from "./utils" import { LockManager } from "./utils"
const lockManager = new LockManager() const lockManager = new LockManager()
// Define a type for SocketHandler functions // Define a type for SocketHandler functions
type SocketHandler<T = Record<string, any>> = (args: T) => any; type SocketHandler<T = Record<string, any>> = (args: T) => any
// Extract port number from a string // Extract port number from a string
function extractPortNumber(inputString: string): number | null { function extractPortNumber(inputString: string): number | null {
const cleanedString = inputString.replace(/\x1B\[[0-9;]*m/g, "") const cleanedString = inputString.replace(/\x1B\[[0-9;]*m/g, "")
const regex = /http:\/\/localhost:(\d+)/ const regex = /http:\/\/localhost:(\d+)/
const match = cleanedString.match(regex) const match = cleanedString.match(regex)
return match ? parseInt(match[1]) : null return match ? parseInt(match[1]) : null
} }
type ServerContext = { type ServerContext = {
aiWorker: AIWorker; dokkuClient: DokkuClient | null
dokkuClient: DokkuClient | null; gitClient: SecureGitClient | null
gitClient: SecureGitClient | null; }
};
export class Sandbox { export class Sandbox {
// Sandbox properties:
sandboxId: string
type: string
fileManager: FileManager | null
terminalManager: TerminalManager | null
container: E2BSandbox | null
// Server context:
dokkuClient: DokkuClient | null
gitClient: SecureGitClient | null
constructor(
sandboxId: string,
type: string,
{ dokkuClient, gitClient }: ServerContext
) {
// Sandbox properties: // Sandbox properties:
sandboxId: string; this.sandboxId = sandboxId
type: string; this.type = type
fileManager: FileManager | null; this.fileManager = null
terminalManager: TerminalManager | null; this.terminalManager = null
container: E2BSandbox | null; this.container = null
// Server context: // Server context:
dokkuClient: DokkuClient | null; this.dokkuClient = dokkuClient
gitClient: SecureGitClient | null; this.gitClient = gitClient
aiWorker: AIWorker; }
constructor(sandboxId: string, type: string, { aiWorker, dokkuClient, gitClient }: ServerContext) { // Initializes the container for the sandbox environment
// Sandbox properties: async initialize(
this.sandboxId = sandboxId; fileWatchCallback: ((files: (TFolder | TFile)[]) => void) | undefined
this.type = type; ) {
this.fileManager = null; // Acquire a lock to ensure exclusive access to the sandbox environment
this.terminalManager = null; await lockManager.acquireLock(this.sandboxId, async () => {
this.container = null; // Check if a container already exists and is running
// Server context: if (this.container && (await this.container.isRunning())) {
this.aiWorker = aiWorker; console.log(`Found existing container ${this.sandboxId}`)
this.dokkuClient = dokkuClient; } else {
this.gitClient = gitClient; console.log("Creating container", this.sandboxId)
} // Create a new container with a specified template and timeout
const templateTypes = [
// Initializes the container for the sandbox environment "vanillajs",
async initialize( "reactjs",
fileWatchCallback: ((files: (TFolder | TFile)[]) => void) | undefined "nextjs",
) { "streamlit",
// Acquire a lock to ensure exclusive access to the sandbox environment "php",
await lockManager.acquireLock(this.sandboxId, async () => { ]
// Check if a container already exists and is running const template = templateTypes.includes(this.type)
if (this.container && await this.container.isRunning()) { ? `gitwit-${this.type}`
console.log(`Found existing container ${this.sandboxId}`) : `base`
} else { this.container = await E2BSandbox.create(template, {
console.log("Creating container", this.sandboxId) timeoutMs: CONTAINER_TIMEOUT,
// Create a new container with a specified template and timeout
const templateTypes = ["vanillajs", "reactjs", "nextjs", "streamlit"];
const template = templateTypes.includes(this.type)
? `gitwit-${this.type}`
: `base`;
this.container = await E2BSandbox.create(template, {
timeoutMs: CONTAINER_TIMEOUT,
})
}
}) })
// Ensure a container was successfully created }
if (!this.container) throw new Error("Failed to create container") })
// Ensure a container was successfully created
if (!this.container) throw new Error("Failed to create container")
// Initialize the terminal manager if it hasn't been set up yet // Initialize the terminal manager if it hasn't been set up yet
if (!this.terminalManager) { if (!this.terminalManager) {
this.terminalManager = new TerminalManager(this.container) this.terminalManager = new TerminalManager(this.container)
console.log(`Terminal manager set up for ${this.sandboxId}`) console.log(`Terminal manager set up for ${this.sandboxId}`)
}
// Initialize the file manager if it hasn't been set up yet
if (!this.fileManager) {
this.fileManager = new FileManager(
this.sandboxId,
this.container,
fileWatchCallback ?? null
)
// Initialize the file manager and emit the initial files
await this.fileManager.initialize()
}
} }
// Called when the client disconnects from the Sandbox // Initialize the file manager if it hasn't been set up yet
async disconnect() { if (!this.fileManager) {
// Close all terminals managed by the terminal manager this.fileManager = new FileManager(
await this.terminalManager?.closeAllTerminals() this.sandboxId,
// This way the terminal manager will be set up again if we reconnect this.container,
this.terminalManager = null; fileWatchCallback ?? null
// Close all file watchers managed by the file manager )
await this.fileManager?.closeWatchers() // Initialize the file manager and emit the initial files
// This way the file manager will be set up again if we reconnect await this.fileManager.initialize()
this.fileManager = null; }
}
// Called when the client disconnects from the Sandbox
async disconnect() {
// Close all terminals managed by the terminal manager
await this.terminalManager?.closeAllTerminals()
// This way the terminal manager will be set up again if we reconnect
this.terminalManager = null
// Close all file watchers managed by the file manager
await this.fileManager?.closeWatchers()
// This way the file manager will be set up again if we reconnect
this.fileManager = null
}
handlers(connection: { userId: string; isOwner: boolean; socket: Socket }) {
// Handle heartbeat from a socket connection
const handleHeartbeat: SocketHandler = (_: any) => {
// Only keep the sandbox alive if the owner is still connected
if (connection.isOwner) {
this.container?.setTimeout(CONTAINER_TIMEOUT)
}
} }
handlers(connection: { userId: string, isOwner: boolean, socket: Socket }) { // Handle getting a file
const handleGetFile: SocketHandler = ({ fileId }: any) => {
return this.fileManager?.getFile(fileId)
}
// Handle heartbeat from a socket connection // Handle getting a folder
const handleHeartbeat: SocketHandler = (_: any) => { const handleGetFolder: SocketHandler = ({ folderId }: any) => {
// Only keep the sandbox alive if the owner is still connected return this.fileManager?.getFolder(folderId)
if (connection.isOwner) { }
this.container?.setTimeout(CONTAINER_TIMEOUT)
}
}
// Handle getting a file // Handle saving a file
const handleGetFile: SocketHandler = ({ fileId }: any) => { const handleSaveFile: SocketHandler = async ({ fileId, body }: any) => {
return this.fileManager?.getFile(fileId) await saveFileRL.consume(connection.userId, 1)
} return this.fileManager?.saveFile(fileId, body)
}
// Handle getting a folder // Handle moving a file
const handleGetFolder: SocketHandler = ({ folderId }: any) => { const handleMoveFile: SocketHandler = ({ fileId, folderId }: any) => {
return this.fileManager?.getFolder(folderId) return this.fileManager?.moveFile(fileId, folderId)
} }
// Handle saving a file // Handle listing apps
const handleSaveFile: SocketHandler = async ({ fileId, body }: any) => { const handleListApps: SocketHandler = async (_: any) => {
await saveFileRL.consume(connection.userId, 1); if (!this.dokkuClient)
return this.fileManager?.saveFile(fileId, body) throw Error("Failed to retrieve apps list: No Dokku client")
} return { success: true, apps: await this.dokkuClient.listApps() }
}
// Handle moving a file // Handle deploying code
const handleMoveFile: SocketHandler = ({ fileId, folderId }: any) => { const handleDeploy: SocketHandler = async (_: any) => {
return this.fileManager?.moveFile(fileId, folderId) if (!this.gitClient) throw Error("No git client")
} if (!this.fileManager) throw Error("No file manager")
await this.gitClient.pushFiles(
await this.fileManager?.loadFileContent(),
this.sandboxId
)
return { success: true }
}
// Handle listing apps // Handle creating a file
const handleListApps: SocketHandler = async (_: any) => { const handleCreateFile: SocketHandler = async ({ name }: any) => {
if (!this.dokkuClient) throw Error("Failed to retrieve apps list: No Dokku client") await createFileRL.consume(connection.userId, 1)
return { success: true, apps: await this.dokkuClient.listApps() } return { success: await this.fileManager?.createFile(name) }
} }
// Handle deploying code // Handle creating a folder
const handleDeploy: SocketHandler = async (_: any) => { const handleCreateFolder: SocketHandler = async ({ name }: any) => {
if (!this.gitClient) throw Error("No git client") await createFolderRL.consume(connection.userId, 1)
if (!this.fileManager) throw Error("No file manager") return { success: await this.fileManager?.createFolder(name) }
await this.gitClient.pushFiles(this.fileManager?.fileData, this.sandboxId) }
return { success: true }
}
// Handle creating a file // Handle renaming a file
const handleCreateFile: SocketHandler = async ({ name }: any) => { const handleRenameFile: SocketHandler = async ({
await createFileRL.consume(connection.userId, 1); fileId,
return { "success": await this.fileManager?.createFile(name) } newName,
} }: any) => {
await renameFileRL.consume(connection.userId, 1)
return this.fileManager?.renameFile(fileId, newName)
}
// Handle creating a folder // Handle deleting a file
const handleCreateFolder: SocketHandler = async ({ name }: any) => { const handleDeleteFile: SocketHandler = async ({ fileId }: any) => {
await createFolderRL.consume(connection.userId, 1); await deleteFileRL.consume(connection.userId, 1)
return { "success": await this.fileManager?.createFolder(name) } return this.fileManager?.deleteFile(fileId)
} }
// Handle renaming a file // Handle deleting a folder
const handleRenameFile: SocketHandler = async ({ fileId, newName }: any) => { const handleDeleteFolder: SocketHandler = ({ folderId }: any) => {
await renameFileRL.consume(connection.userId, 1) return this.fileManager?.deleteFolder(folderId)
return this.fileManager?.renameFile(fileId, newName) }
}
// Handle deleting a file // Handle creating a terminal session
const handleDeleteFile: SocketHandler = async ({ fileId }: any) => { const handleCreateTerminal: SocketHandler = async ({ id }: any) => {
await deleteFileRL.consume(connection.userId, 1) await lockManager.acquireLock(this.sandboxId, async () => {
return this.fileManager?.deleteFile(fileId) await this.terminalManager?.createTerminal(
} id,
(responseString: string) => {
// Handle deleting a folder connection.socket.emit("terminalResponse", {
const handleDeleteFolder: SocketHandler = ({ folderId }: any) => { id,
return this.fileManager?.deleteFolder(folderId) data: responseString,
}
// Handle creating a terminal session
const handleCreateTerminal: SocketHandler = async ({ id }: any) => {
await lockManager.acquireLock(this.sandboxId, async () => {
await this.terminalManager?.createTerminal(id, (responseString: string) => {
connection.socket.emit("terminalResponse", { id, data: responseString })
const port = extractPortNumber(responseString)
if (port) {
connection.socket.emit(
"previewURL",
"https://" + this.container?.getHost(port)
)
}
})
}) })
} const port = extractPortNumber(responseString)
if (port) {
// Handle resizing a terminal connection.socket.emit(
const handleResizeTerminal: SocketHandler = ({ dimensions }: any) => { "previewURL",
this.terminalManager?.resizeTerminal(dimensions) "https://" + this.container?.getHost(port)
} )
}
// Handle sending data to a terminal }
const handleTerminalData: SocketHandler = ({ id, data }: any) => { )
return this.terminalManager?.sendTerminalData(id, data) })
}
// Handle closing a terminal
const handleCloseTerminal: SocketHandler = ({ id }: any) => {
return this.terminalManager?.closeTerminal(id)
}
// Handle generating code
const handleGenerateCode: SocketHandler = ({ fileName, code, line, instructions }: any) => {
return this.aiWorker.generateCode(connection.userId, fileName, code, line, instructions)
}
// Handle downloading files by download button
const handleDownloadFiles: SocketHandler = async () => {
if (!this.fileManager) throw Error("No file manager")
// Get all files with their data through fileManager
const files = this.fileManager.fileData.map((file: TFileData) => ({
path: file.id.startsWith('/') ? file.id.slice(1) : file.id,
content: file.data
}))
return { files }
}
return {
"heartbeat": handleHeartbeat,
"getFile": handleGetFile,
"downloadFiles": handleDownloadFiles,
"getFolder": handleGetFolder,
"saveFile": handleSaveFile,
"moveFile": handleMoveFile,
"list": handleListApps,
"deploy": handleDeploy,
"createFile": handleCreateFile,
"createFolder": handleCreateFolder,
"renameFile": handleRenameFile,
"deleteFile": handleDeleteFile,
"deleteFolder": handleDeleteFolder,
"createTerminal": handleCreateTerminal,
"resizeTerminal": handleResizeTerminal,
"terminalData": handleTerminalData,
"closeTerminal": handleCloseTerminal,
"generateCode": handleGenerateCode,
};
} }
} // Handle resizing a terminal
const handleResizeTerminal: SocketHandler = ({ dimensions }: any) => {
this.terminalManager?.resizeTerminal(dimensions)
}
// Handle sending data to a terminal
const handleTerminalData: SocketHandler = ({ id, data }: any) => {
return this.terminalManager?.sendTerminalData(id, data)
}
// Handle closing a terminal
const handleCloseTerminal: SocketHandler = ({ id }: any) => {
return this.terminalManager?.closeTerminal(id)
}
// Handle downloading files by download button
const handleDownloadFiles: SocketHandler = async () => {
if (!this.fileManager) throw Error("No file manager")
// Get the Base64 encoded ZIP string
const zipBase64 = await this.fileManager.getFilesForDownload()
return { zipBlob: zipBase64 }
}
return {
heartbeat: handleHeartbeat,
getFile: handleGetFile,
downloadFiles: handleDownloadFiles,
getFolder: handleGetFolder,
saveFile: handleSaveFile,
moveFile: handleMoveFile,
list: handleListApps,
deploy: handleDeploy,
createFile: handleCreateFile,
createFolder: handleCreateFolder,
renameFile: handleRenameFile,
deleteFile: handleDeleteFile,
deleteFolder: handleDeleteFolder,
createTerminal: handleCreateTerminal,
resizeTerminal: handleResizeTerminal,
terminalData: handleTerminalData,
closeTerminal: handleCloseTerminal,
}
}
}

View File

@ -57,7 +57,7 @@ export class SecureGitClient {
// Add files to the repository // Add files to the repository
for (const { id, data } of fileData) { for (const { id, data } of fileData) {
await git.add(id) await git.add(id.startsWith("/") ? id.slice(1) : id)
} }
// Commit the changes // Commit the changes

View File

@ -1,8 +1,8 @@
import { ProcessHandle, Sandbox } from "e2b" import { CommandHandle, Sandbox } from "e2b"
// Terminal class to manage a pseudo-terminal (PTY) in a sandbox environment // Terminal class to manage a pseudo-terminal (PTY) in a sandbox environment
export class Terminal { export class Terminal {
private pty: ProcessHandle | undefined // Holds the PTY process handle private pty: CommandHandle | undefined // Holds the PTY process handle
private sandbox: Sandbox // Reference to the sandbox environment private sandbox: Sandbox // Reference to the sandbox environment
// Constructor initializes the Terminal with a sandbox // Constructor initializes the Terminal with a sandbox
@ -24,7 +24,7 @@ export class Terminal {
this.pty = await this.sandbox.pty.create({ this.pty = await this.sandbox.pty.create({
rows, rows,
cols, cols,
timeout: 0, timeoutMs: 0,
onData: (data: Uint8Array) => { onData: (data: Uint8Array) => {
onData(new TextDecoder().decode(data)) // Convert received data to string and pass to handler onData(new TextDecoder().decode(data)) // Convert received data to string and pass to handler
}, },

View File

@ -1,2 +1,2 @@
// The amount of time in ms that a container will stay alive without a hearbeat. // The amount of time in ms that a container will stay alive without a hearbeat.
export const CONTAINER_TIMEOUT = 120_000 export const CONTAINER_TIMEOUT = 120_000

View File

@ -4,20 +4,19 @@ import express, { Express } from "express"
import fs from "fs" import fs from "fs"
import { createServer } from "http" import { createServer } from "http"
import { Server, Socket } from "socket.io" import { Server, Socket } from "socket.io"
import { AIWorker } from "./AIWorker"
import { ConnectionManager } from "./ConnectionManager" import { ConnectionManager } from "./ConnectionManager"
import { DokkuClient } from "./DokkuClient" import { DokkuClient } from "./DokkuClient"
import { Sandbox } from "./Sandbox" import { Sandbox } from "./Sandbox"
import { SecureGitClient } from "./SecureGitClient" import { SecureGitClient } from "./SecureGitClient"
import { socketAuth } from "./socketAuth"; // Import the new socketAuth middleware import { socketAuth } from "./socketAuth" // Import the new socketAuth middleware
import { TFile, TFolder } from "./types" import { TFile, TFolder } from "./types"
// Log errors and send a notification to the client // Log errors and send a notification to the client
export const handleErrors = (message: string, error: any, socket: Socket) => { export const handleErrors = (message: string, error: any, socket: Socket) => {
console.error(message, error); console.error(message, error)
socket.emit("error", `${message} ${error.message ?? error}`); socket.emit("error", `${message} ${error.message ?? error}`)
}; }
// Handle uncaught exceptions // Handle uncaught exceptions
process.on("uncaughtException", (error) => { process.on("uncaughtException", (error) => {
@ -64,10 +63,10 @@ if (!process.env.DOKKU_KEY)
const dokkuClient = const dokkuClient =
process.env.DOKKU_HOST && process.env.DOKKU_KEY && process.env.DOKKU_USERNAME process.env.DOKKU_HOST && process.env.DOKKU_KEY && process.env.DOKKU_USERNAME
? new DokkuClient({ ? new DokkuClient({
host: process.env.DOKKU_HOST, host: process.env.DOKKU_HOST,
username: process.env.DOKKU_USERNAME, username: process.env.DOKKU_USERNAME,
privateKey: fs.readFileSync(process.env.DOKKU_KEY), privateKey: fs.readFileSync(process.env.DOKKU_KEY),
}) })
: null : null
dokkuClient?.connect() dokkuClient?.connect()
@ -75,19 +74,11 @@ dokkuClient?.connect()
const gitClient = const gitClient =
process.env.DOKKU_HOST && process.env.DOKKU_KEY process.env.DOKKU_HOST && process.env.DOKKU_KEY
? new SecureGitClient( ? new SecureGitClient(
`dokku@${process.env.DOKKU_HOST}`, `dokku@${process.env.DOKKU_HOST}`,
process.env.DOKKU_KEY process.env.DOKKU_KEY
) )
: null : null
// Add this near the top of the file, after other initializations
const aiWorker = new AIWorker(
process.env.AI_WORKER_URL!,
process.env.CF_AI_KEY!,
process.env.DATABASE_WORKER_URL!,
process.env.WORKERS_KEY!
)
// Handle a client connecting to the server // Handle a client connecting to the server
io.on("connection", async (socket) => { io.on("connection", async (socket) => {
try { try {
@ -110,21 +101,22 @@ io.on("connection", async (socket) => {
try { try {
// Create or retrieve the sandbox manager for the given sandbox ID // Create or retrieve the sandbox manager for the given sandbox ID
const sandbox = sandboxes[data.sandboxId] ?? new Sandbox( const sandbox =
data.sandboxId, sandboxes[data.sandboxId] ??
data.type, new Sandbox(data.sandboxId, data.type, {
{ dokkuClient,
aiWorker, dokkuClient, gitClient, gitClient,
} })
)
sandboxes[data.sandboxId] = sandbox sandboxes[data.sandboxId] = sandbox
// This callback recieves an update when the file list changes, and notifies all relevant connections. // This callback recieves an update when the file list changes, and notifies all relevant connections.
const sendFileNotifications = (files: (TFolder | TFile)[]) => { const sendFileNotifications = (files: (TFolder | TFile)[]) => {
connections.connectionsForSandbox(data.sandboxId).forEach((socket: Socket) => { connections
socket.emit("loaded", files); .connectionsForSandbox(data.sandboxId)
}); .forEach((socket: Socket) => {
}; socket.emit("loaded", files)
})
}
// Initialize the sandbox container // Initialize the sandbox container
// The file manager and terminal managers will be set up if they have been closed // The file manager and terminal managers will be set up if they have been closed
@ -134,26 +126,35 @@ io.on("connection", async (socket) => {
// Register event handlers for the sandbox // Register event handlers for the sandbox
// For each event handler, listen on the socket for that event // For each event handler, listen on the socket for that event
// Pass connection-specific information to the handlers // Pass connection-specific information to the handlers
Object.entries(sandbox.handlers({ Object.entries(
userId: data.userId, sandbox.handlers({
isOwner: data.isOwner, userId: data.userId,
socket isOwner: data.isOwner,
})).forEach(([event, handler]) => { socket,
socket.on(event, async (options: any, callback?: (response: any) => void) => { })
try { ).forEach(([event, handler]) => {
const result = await handler(options) socket.on(
callback?.(result); event,
} catch (e: any) { async (options: any, callback?: (response: any) => void) => {
handleErrors(`Error processing event "${event}":`, e, socket); try {
const result = await handler(options)
callback?.(result)
} catch (e: any) {
handleErrors(`Error processing event "${event}":`, e, socket)
}
} }
}); )
}); })
// Handle disconnection event // Handle disconnection event
socket.on("disconnect", async () => { socket.on("disconnect", async () => {
try { try {
// Deregister the connection // Deregister the connection
connections.removeConnectionForSandbox(socket, data.sandboxId, data.isOwner) connections.removeConnectionForSandbox(
socket,
data.sandboxId,
data.isOwner
)
// If the owner has disconnected from all sockets, close open terminals and file watchers.o // If the owner has disconnected from all sockets, close open terminals and file watchers.o
// The sandbox itself will timeout after the heartbeat stops. // The sandbox itself will timeout after the heartbeat stops.
@ -165,20 +166,18 @@ io.on("connection", async (socket) => {
) )
} }
} catch (e: any) { } catch (e: any) {
handleErrors("Error disconnecting:", e, socket); handleErrors("Error disconnecting:", e, socket)
} }
}) })
} catch (e: any) { } catch (e: any) {
handleErrors(`Error initializing sandbox ${data.sandboxId}:`, e, socket); handleErrors(`Error initializing sandbox ${data.sandboxId}:`, e, socket)
} }
} catch (e: any) { } catch (e: any) {
handleErrors("Error connecting:", e, socket); handleErrors("Error connecting:", e, socket)
} }
}) })
// Start the server // Start the server
httpServer.listen(port, () => { httpServer.listen(port, () => {
console.log(`Server running on port ${port}`) console.log(`Server running on port ${port}`)
}) })

View File

@ -4,72 +4,72 @@ import { Sandbox, User } from "./types"
// Middleware for socket authentication // Middleware for socket authentication
export const socketAuth = async (socket: Socket, next: Function) => { export const socketAuth = async (socket: Socket, next: Function) => {
// Define the schema for handshake query validation // Define the schema for handshake query validation
const handshakeSchema = z.object({ const handshakeSchema = z.object({
userId: z.string(), userId: z.string(),
sandboxId: z.string(), sandboxId: z.string(),
EIO: z.string(), EIO: z.string(),
transport: z.string(), transport: z.string(),
}) })
const q = socket.handshake.query const q = socket.handshake.query
const parseQuery = handshakeSchema.safeParse(q) const parseQuery = handshakeSchema.safeParse(q)
// Check if the query is valid according to the schema // Check if the query is valid according to the schema
if (!parseQuery.success) { if (!parseQuery.success) {
next(new Error("Invalid request.")) next(new Error("Invalid request."))
return return
}
const { sandboxId, userId } = parseQuery.data
// Fetch user data from the database
const dbUser = await fetch(
`${process.env.DATABASE_WORKER_URL}/api/user?id=${userId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
} }
)
const dbUserJSON = (await dbUser.json()) as User
const { sandboxId, userId } = parseQuery.data // Fetch sandbox data from the database
// Fetch user data from the database const dbSandbox = await fetch(
const dbUser = await fetch( `${process.env.DATABASE_WORKER_URL}/api/sandbox?id=${sandboxId}`,
`${process.env.DATABASE_WORKER_URL}/api/user?id=${userId}`, {
{ headers: {
headers: { Authorization: `${process.env.WORKERS_KEY}`,
Authorization: `${process.env.WORKERS_KEY}`, },
},
}
)
const dbUserJSON = (await dbUser.json()) as User
// Fetch sandbox data from the database
const dbSandbox = await fetch(
`${process.env.DATABASE_WORKER_URL}/api/sandbox?id=${sandboxId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
)
const dbSandboxJSON = (await dbSandbox.json()) as Sandbox
// Check if user data was retrieved successfully
if (!dbUserJSON) {
next(new Error("DB error."))
return
} }
)
const dbSandboxJSON = (await dbSandbox.json()) as Sandbox
// Check if the user owns the sandbox or has shared access // Check if user data was retrieved successfully
const sandbox = dbUserJSON.sandbox.find((s) => s.id === sandboxId) if (!dbUserJSON) {
const sharedSandboxes = dbUserJSON.usersToSandboxes.find( next(new Error("DB error."))
(uts) => uts.sandboxId === sandboxId return
) }
// If user doesn't own or have shared access to the sandbox, deny access // Check if the user owns the sandbox or has shared access
if (!sandbox && !sharedSandboxes) { const sandbox = dbUserJSON.sandbox.find((s) => s.id === sandboxId)
next(new Error("Invalid credentials.")) const sharedSandboxes = dbUserJSON.usersToSandboxes.find(
return (uts) => uts.sandboxId === sandboxId
} )
// Set socket data with user information // If user doesn't own or have shared access to the sandbox, deny access
socket.data = { if (!sandbox && !sharedSandboxes) {
userId, next(new Error("Invalid credentials."))
sandboxId: sandboxId, return
isOwner: sandbox !== undefined, }
type: dbSandboxJSON.type
}
// Allow the connection // Set socket data with user information
next() socket.data = {
userId,
sandboxId: sandboxId,
isOwner: sandbox !== undefined,
type: dbSandboxJSON.type,
}
// Allow the connection
next()
} }

View File

@ -20,4 +20,4 @@ export class LockManager {
} }
return await this.locks[key] return await this.locks[key]
} }
} }

View File

@ -1,4 +1,4 @@
import { Room } from "@/components/editor/live/room" // import { Room } from "@/components/editor/live/room"
import Loading from "@/components/editor/loading" import Loading from "@/components/editor/loading"
import Navbar from "@/components/editor/navbar" import Navbar from "@/components/editor/navbar"
import { TerminalProvider } from "@/context/TerminalContext" import { TerminalProvider } from "@/context/TerminalContext"
@ -51,7 +51,11 @@ const getSharedUsers = async (usersToSandboxes: UsersToSandboxes[]) => {
} }
) )
const userData: User = await userRes.json() const userData: User = await userRes.json()
return { id: userData.id, name: userData.name, avatarUrl: userData.avatarUrl } return {
id: userData.id,
name: userData.name,
avatarUrl: userData.avatarUrl,
}
}) })
) )
@ -89,18 +93,20 @@ export default async function CodePage({ params }: { params: { id: string } }) {
return ( return (
<> <>
<div className="overflow-hidden overscroll-none w-screen flex flex-col h-screen bg-background"> <div className="overflow-hidden overscroll-none w-screen flex flex-col h-screen bg-background">
<Room id={sandboxId}> {/* <Room id={sandboxId}> */}
<TerminalProvider> <TerminalProvider>
<Navbar <Navbar
userData={userData} userData={userData}
sandboxData={sandboxData} sandboxData={sandboxData}
shared={shared} shared={
shared as { id: string; name: string; avatarUrl: string }[]
}
/> />
<div className="w-screen flex grow"> <div className="w-screen flex grow">
<CodeEditor userData={userData} sandboxData={sandboxData} /> <CodeEditor userData={userData} sandboxData={sandboxData} />
</div> </div>
</TerminalProvider> </TerminalProvider>
</Room> {/* </Room> */}
</div> </div>
</> </>
) )

View File

@ -0,0 +1,171 @@
import { currentUser } from "@clerk/nextjs"
import { Anthropic } from "@anthropic-ai/sdk"
import { TIERS } from "@/lib/tiers"
import { templateConfigs } from "@/lib/templates"
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY!,
})
export async function POST(request: Request) {
try {
const user = await currentUser()
if (!user) {
return new Response("Unauthorized", { status: 401 })
}
// Check and potentially reset monthly usage
const resetResponse = await fetch(
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user/check-reset`,
{
method: "POST",
headers: {
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ userId: user.id }),
}
)
if (!resetResponse.ok) {
console.error("Failed to check usage reset")
}
// Get user data and check tier
const dbUser = await fetch(
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user?id=${user.id}`,
{
headers: {
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
},
}
)
const userData = await dbUser.json()
// Get tier settings
const tierSettings = TIERS[userData.tier as keyof typeof TIERS] || TIERS.FREE
if (userData.generations >= tierSettings.generations) {
return new Response(
`AI generation limit reached for your ${userData.tier || "FREE"} tier`,
{ status: 429 }
)
}
const {
messages,
context,
activeFileContent,
isEditMode,
fileName,
line,
templateType
} = await request.json()
// Get template configuration
const templateConfig = templateConfigs[templateType]
// Create template context
const templateContext = templateConfig ? `
Project Template: ${templateConfig.name}
File Structure:
${Object.entries(templateConfig.fileStructure)
.map(([path, info]) => `${path} - ${info.description}`)
.join('\n')}
Conventions:
${templateConfig.conventions.join('\n')}
Dependencies:
${JSON.stringify(templateConfig.dependencies, null, 2)}
` : ''
// Create system message based on mode
let systemMessage
if (isEditMode) {
systemMessage = `You are an AI code editor working in a ${templateType} project. Your task is to modify the given code based on the user's instructions. Only output the modified code, without any explanations or markdown formatting. The code should be a direct replacement for the existing code. If there is no code to modify, refer to the active file content and only output the code that is relevant to the user's instructions.
${templateContext}
File: ${fileName}
Line: ${line}
Context:
${context || "No additional context provided"}
Active File Content:
${activeFileContent}
Instructions: ${messages[0].content}
Respond only with the modified code that can directly replace the existing code.`
} else {
systemMessage = `You are an intelligent programming assistant for a ${templateType} project. Please respond to the following request concisely. If your response includes code, please format it using triple backticks (\`\`\`) with the appropriate language identifier. For example:
\`\`\`python
print("Hello, World!")
\`\`\`
Provide a clear and concise explanation along with any code snippets. Keep your response brief and to the point.
This is the project template:
${templateContext}
${context ? `Context:\n${context}\n` : ""}
${activeFileContent ? `Active File Content:\n${activeFileContent}\n` : ""}`
}
// Create stream response
const stream = await anthropic.messages.create({
model: tierSettings.model,
max_tokens: tierSettings.maxTokens,
system: systemMessage,
messages: messages.map((msg: { role: string; content: string }) => ({
role: msg.role === "human" ? "user" : "assistant",
content: msg.content,
})),
stream: true,
})
// Increment user's generation count
await fetch(
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user/increment-generations`,
{
method: "POST",
headers: {
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ userId: user.id }),
}
)
// Return streaming response
const encoder = new TextEncoder()
return new Response(
new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
controller.enqueue(encoder.encode(chunk.delta.text))
}
}
controller.close()
},
}),
{
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
}
)
} catch (error) {
console.error("AI generation error:", error)
return new Response(
error instanceof Error ? error.message : "Internal Server Error",
{ status: 500 }
)
}
}

View File

@ -1,57 +1,61 @@
import { colors } from "@/lib/colors" // import { colors } from "@/lib/colors"
import { User } from "@/lib/types" // import { User } from "@/lib/types"
import { currentUser } from "@clerk/nextjs" import { currentUser } from "@clerk/nextjs"
import { Liveblocks } from "@liveblocks/node" // import { Liveblocks } from "@liveblocks/node"
import { NextRequest } from "next/server" import { NextRequest } from "next/server"
const API_KEY = process.env.LIVEBLOCKS_SECRET_KEY! // const API_KEY = process.env.LIVEBLOCKS_SECRET_KEY!
const liveblocks = new Liveblocks({ // const liveblocks = new Liveblocks({
secret: API_KEY!, // secret: API_KEY!,
}) // })
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const clerkUser = await currentUser() // Temporarily return unauthorized while Liveblocks is disabled
return new Response("Liveblocks collaboration temporarily disabled", { status: 503 })
if (!clerkUser) { // Original implementation commented out:
return new Response("Unauthorized", { status: 401 }) // const clerkUser = await currentUser()
} //
// if (!clerkUser) {
const res = await fetch( // return new Response("Unauthorized", { status: 401 })
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user?id=${clerkUser.id}`, // }
{ //
headers: { // const res = await fetch(
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`, // `${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user?id=${clerkUser.id}`,
}, // {
} // headers: {
) // Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
const user = (await res.json()) as User // },
// }
const colorNames = Object.keys(colors) // )
const randomColor = colorNames[ // const user = (await res.json()) as User
Math.floor(Math.random() * colorNames.length) //
] as keyof typeof colors // const colorNames = Object.keys(colors)
const code = colors[randomColor] // const randomColor = colorNames[
// Math.floor(Math.random() * colorNames.length)
// Create a session for the current user // ] as keyof typeof colors
// userInfo is made available in Liveblocks presence hooks, e.g. useOthers // const code = colors[randomColor]
const session = liveblocks.prepareSession(user.id, { //
userInfo: { // // Create a session for the current user
name: user.name, // // userInfo is made available in Liveblocks presence hooks, e.g. useOthers
email: user.email, // const session = liveblocks.prepareSession(user.id, {
color: randomColor, // userInfo: {
}, // name: user.name,
}) // email: user.email,
// color: randomColor,
// Give the user access to the room // },
user.sandbox.forEach((sandbox) => { // })
session.allow(`${sandbox.id}`, session.FULL_ACCESS) //
}) // // Give the user access to the room
user.usersToSandboxes.forEach((userToSandbox) => { // user.sandbox.forEach((sandbox) => {
session.allow(`${userToSandbox.sandboxId}`, session.FULL_ACCESS) // session.allow(`${sandbox.id}`, session.FULL_ACCESS)
}) // })
// user.usersToSandboxes.forEach((userToSandbox) => {
// Authorize the user and return the result // session.allow(`${userToSandbox.sandboxId}`, session.FULL_ACCESS)
const { body, status } = await session.authorize() // })
return new Response(body, { status }) //
// // Authorize the user and return the result
// const { body, status } = await session.authorize()
// return new Response(body, { status })
} }

View File

@ -0,0 +1,42 @@
import { currentUser } from "@clerk/nextjs"
export async function POST(request: Request) {
try {
const user = await currentUser()
if (!user) {
return new Response("Unauthorized", { status: 401 })
}
const { tier } = await request.json()
// handle payment processing here
const response = await fetch(
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user/update-tier`,
{
method: "POST",
headers: {
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
userId: user.id,
tier,
tierExpiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
}),
}
)
if (!response.ok) {
throw new Error("Failed to upgrade tier")
}
return new Response("Tier upgraded successfully")
} catch (error) {
console.error("Tier upgrade error:", error)
return new Response(
error instanceof Error ? error.message : "Internal Server Error",
{ status: 500 }
)
}
}

View File

@ -1,7 +1,7 @@
import { Toaster } from "@/components/ui/sonner" import { Toaster } from "@/components/ui/sonner"
import { ThemeProvider } from "@/components/ui/theme-provider" import { ThemeProvider } from "@/components/ui/theme-provider"
import { PreviewProvider } from "@/context/PreviewContext" import { PreviewProvider } from "@/context/PreviewContext"
import { SocketProvider } from '@/context/SocketContext' import { SocketProvider } from "@/context/SocketContext"
import { ClerkProvider } from "@clerk/nextjs" import { ClerkProvider } from "@clerk/nextjs"
import { Analytics } from "@vercel/analytics/react" import { Analytics } from "@vercel/analytics/react"
import { GeistMono } from "geist/font/mono" import { GeistMono } from "geist/font/mono"

View File

@ -14,4 +14,4 @@
"components": "@/components", "components": "@/components",
"utils": "@/lib/utils" "utils": "@/lib/utils"
} }
} }

View File

@ -18,11 +18,38 @@ export default function AboutModal({
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>About this project</DialogTitle> <DialogTitle>Help & Support</DialogTitle>
</DialogHeader> </DialogHeader>
<div className="text-sm text-muted-foreground"> <div className="space-y-4">
Sandbox is an open-source cloud-based code editing environment with {/* <div className="text-sm text-muted-foreground">
custom AI code autocompletion and real-time collaboration. Sandbox is an open-source cloud-based code editing environment with
custom AI code autocompletion and real-time collaboration.
</div> */}
<div className="text-sm text-muted-foreground">
Get help and support through our Discord community or by creating issues on GitHub:
</div>
<div className="space-y-2">
<div className="text-sm">
<a
href="https://discord.gitwit.dev/"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
Join our Discord community
</a>
</div>
<div className="text-sm">
<a
href="https://github.com/jamesmurdza/sandbox/issues"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
Report issues on GitHub
</a>
</div>
</div>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>

View File

@ -25,6 +25,7 @@ export default function Dashboard({
type: "react" | "node" type: "react" | "node"
author: string author: string
sharedOn: Date sharedOn: Date
authorAvatarUrl?: string
}[] }[]
}) { }) {
const [screen, setScreen] = useState<TScreen>("projects") const [screen, setScreen] = useState<TScreen>("projects")
@ -77,14 +78,14 @@ export default function Dashboard({
<FolderDot className="w-4 h-4 mr-2" /> <FolderDot className="w-4 h-4 mr-2" />
My Projects My Projects
</Button> </Button>
<Button {/* <Button
variant="ghost" variant="ghost"
onClick={() => setScreen("shared")} onClick={() => setScreen("shared")}
className={activeScreen("shared")} className={activeScreen("shared")}
> >
<Users className="w-4 h-4 mr-2" /> <Users className="w-4 h-4 mr-2" />
Shared With Me Shared With Me
</Button> </Button> */}
{/* <Button {/* <Button
variant="ghost" variant="ghost"
onClick={() => setScreen("settings")} onClick={() => setScreen("settings")}
@ -110,7 +111,7 @@ export default function Dashboard({
className="justify-start font-normal text-muted-foreground" className="justify-start font-normal text-muted-foreground"
> >
<HelpCircle className="w-4 h-4 mr-2" /> <HelpCircle className="w-4 h-4 mr-2" />
About Help
</Button> </Button>
</div> </div>
</div> </div>
@ -121,7 +122,12 @@ export default function Dashboard({
) : null} ) : null}
</> </>
) : screen === "shared" ? ( ) : screen === "shared" ? (
<DashboardSharedWithMe shared={shared} /> <DashboardSharedWithMe
shared={shared.map((item) => ({
...item,
authorAvatarUrl: item.authorAvatarUrl || "",
}))}
/>
) : screen === "settings" ? null : null} ) : screen === "settings" ? null : null}
</div> </div>
</> </>

View File

@ -6,6 +6,7 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table" } from "@/components/ui/table"
import { projectTemplates } from "@/lib/data"
import { ChevronRight } from "lucide-react" import { ChevronRight } from "lucide-react"
import Image from "next/image" import Image from "next/image"
import Link from "next/link" import Link from "next/link"
@ -18,7 +19,7 @@ export default function DashboardSharedWithMe({
shared: { shared: {
id: string id: string
name: string name: string
type: "react" | "node" type: string
author: string author: string
authorAvatarUrl: string authorAvatarUrl: string
sharedOn: Date sharedOn: Date
@ -46,9 +47,8 @@ export default function DashboardSharedWithMe({
<Image <Image
alt="" alt=""
src={ src={
sandbox.type === "react" projectTemplates.find((p) => p.id === sandbox.type)
? "/project-icons/react.svg" ?.icon ?? "/project-icons/node.svg"
: "/project-icons/node.svg"
} }
width={20} width={20}
height={20} height={20}
@ -59,7 +59,7 @@ export default function DashboardSharedWithMe({
</TableCell> </TableCell>
<TableCell> <TableCell>
<div className="flex items-center"> <div className="flex items-center">
<Avatar <Avatar
name={sandbox.author} name={sandbox.author}
avatarUrl={sandbox.authorAvatarUrl} avatarUrl={sandbox.authorAvatarUrl}
className="mr-2" className="mr-2"

View File

@ -1,10 +1,9 @@
import { Send, StopCircle, Image as ImageIcon, Paperclip } from "lucide-react"
import { Button } from "../../ui/button"
import { useEffect } from "react"
import { TFile, TFolder } from "@/lib/types" import { TFile, TFolder } from "@/lib/types"
import { ALLOWED_FILE_TYPES } from "./types" import { Image as ImageIcon, Paperclip, Send, StopCircle } from "lucide-react"
import { useEffect } from "react"
import { Button } from "../../ui/button"
import { looksLikeCode } from "./lib/chatUtils" import { looksLikeCode } from "./lib/chatUtils"
import { ChatInputProps } from "./types" import { ALLOWED_FILE_TYPES, ChatInputProps } from "./types"
export default function ChatInput({ export default function ChatInput({
input, input,
@ -21,12 +20,11 @@ export default function ChatInput({
onRemoveTab, onRemoveTab,
textareaRef, textareaRef,
}: ChatInputProps) { }: ChatInputProps) {
// Auto-resize textarea as content changes // Auto-resize textarea as content changes
useEffect(() => { useEffect(() => {
if (textareaRef.current) { if (textareaRef.current) {
textareaRef.current.style.height = 'auto' textareaRef.current.style.height = "auto"
textareaRef.current.style.height = textareaRef.current.scrollHeight + 'px' textareaRef.current.style.height = textareaRef.current.scrollHeight + "px"
} }
}, [input]) }, [input])
@ -40,7 +38,11 @@ export default function ChatInput({
e.preventDefault() e.preventDefault()
handleSend(false) handleSend(false)
} }
} else if (e.key === "Backspace" && input === "" && contextTabs.length > 0) { } else if (
e.key === "Backspace" &&
input === "" &&
contextTabs.length > 0
) {
e.preventDefault() e.preventDefault()
// Remove the last context tab // Remove the last context tab
const lastTab = contextTabs[contextTabs.length - 1] const lastTab = contextTabs[contextTabs.length - 1]
@ -51,89 +53,92 @@ export default function ChatInput({
// Handle paste events for image and code // Handle paste events for image and code
const handlePaste = async (e: React.ClipboardEvent) => { const handlePaste = async (e: React.ClipboardEvent) => {
// Handle image paste // Handle image paste
const items = Array.from(e.clipboardData.items); const items = Array.from(e.clipboardData.items)
for (const item of items) { for (const item of items) {
if (item.type.startsWith('image/')) { if (item.type.startsWith("image/")) {
e.preventDefault(); e.preventDefault()
const file = item.getAsFile(); const file = item.getAsFile()
if (!file) continue; if (!file) continue
try { try {
// Convert image to base64 string for context tab title and timestamp // Convert image to base64 string for context tab title and timestamp
const reader = new FileReader(); const reader = new FileReader()
reader.onload = () => { reader.onload = () => {
const base64String = reader.result as string; const base64String = reader.result as string
addContextTab( addContextTab(
"image", "image",
`Image ${new Date().toLocaleTimeString('en-US', { `Image ${new Date()
hour12: true, .toLocaleTimeString("en-US", {
hour: '2-digit', hour12: true,
minute: '2-digit' hour: "2-digit",
}).replace(/(\d{2}):(\d{2})/, '$1:$2')}`, minute: "2-digit",
})
.replace(/(\d{2}):(\d{2})/, "$1:$2")}`,
base64String base64String
); )
}; }
reader.readAsDataURL(file); reader.readAsDataURL(file)
} catch (error) { } catch (error) {
console.error('Error processing pasted image:', error); console.error("Error processing pasted image:", error)
} }
return; return
} }
} }
// Get text from clipboard // Get text from clipboard
const text = e.clipboardData.getData('text'); const text = e.clipboardData.getData("text")
// If text doesn't contain newlines or doesn't look like code, let it paste normally // If text doesn't contain newlines or doesn't look like code, let it paste normally
if (!text || !text.includes('\n') || !looksLikeCode(text)) { if (!text || !text.includes("\n") || !looksLikeCode(text)) {
return; return
} }
e.preventDefault(); e.preventDefault()
const editor = editorRef.current; const editor = editorRef.current
const currentSelection = editor?.getSelection(); const currentSelection = editor?.getSelection()
const lines = text.split('\n'); const lines = text.split("\n")
// TODO: FIX THIS: even when i paste the outside code, it shows the active file name,it works when no tabs are open, just does not work when the tab is open // TODO: FIX THIS: even when i paste the outside code, it shows the active file name,it works when no tabs are open, just does not work when the tab is open
// If selection exists in editor, use file name and line numbers // If selection exists in editor, use file name and line numbers
if (currentSelection && !currentSelection.isEmpty()) { if (currentSelection && !currentSelection.isEmpty()) {
addContextTab( addContextTab(
"code", "code",
`${activeFileName} (${currentSelection.startLineNumber}-${currentSelection.endLineNumber})`, `${activeFileName} (${currentSelection.startLineNumber}-${currentSelection.endLineNumber})`,
text, text,
{ start: currentSelection.startLineNumber, end: currentSelection.endLineNumber } {
); start: currentSelection.startLineNumber,
return; end: currentSelection.endLineNumber,
}
)
return
} }
// If we have stored line range from a copy operation in the editor // If we have stored line range from a copy operation in the editor
if (lastCopiedRangeRef.current) { if (lastCopiedRangeRef.current) {
const range = lastCopiedRangeRef.current; const range = lastCopiedRangeRef.current
addContextTab( addContextTab(
"code", "code",
`${activeFileName} (${range.startLine}-${range.endLine})`, `${activeFileName} (${range.startLine}-${range.endLine})`,
text, text,
{ start: range.startLine, end: range.endLine } { start: range.startLine, end: range.endLine }
); )
return; return
} }
// For code pasted from outside the editor // For code pasted from outside the editor
addContextTab( addContextTab("code", `Pasted Code (1-${lines.length})`, text, {
"code", start: 1,
`Pasted Code (1-${lines.length})`, end: lines.length,
text, })
{ start: 1, end: lines.length } }
);
};
// Handle image upload from local machine via input // Handle image upload from local machine via input
const handleImageUpload = () => { const handleImageUpload = () => {
const input = document.createElement('input') const input = document.createElement("input")
input.type = 'file' input.type = "file"
input.accept = 'image/*' input.accept = "image/*"
input.onchange = (e) => { input.onchange = (e) => {
const file = (e.target as HTMLInputElement).files?.[0] const file = (e.target as HTMLInputElement).files?.[0]
if (file) onImageUpload(file) if (file) onImageUpload(file)
@ -155,14 +160,16 @@ export default function ChatInput({
// Handle file upload from local machine via input // Handle file upload from local machine via input
const handleFileUpload = () => { const handleFileUpload = () => {
const input = document.createElement('input') const input = document.createElement("input")
input.type = 'file' input.type = "file"
input.accept = '.txt,.md,.csv,.json,.js,.ts,.html,.css,.pdf' input.accept = ".txt,.md,.csv,.json,.js,.ts,.html,.css,.pdf"
input.onchange = (e) => { input.onchange = (e) => {
const file = (e.target as HTMLInputElement).files?.[0] const file = (e.target as HTMLInputElement).files?.[0]
if (file) { if (file) {
if (!(file.type in ALLOWED_FILE_TYPES)) { if (!(file.type in ALLOWED_FILE_TYPES)) {
alert('Unsupported file type. Please upload text, code, or PDF files.') alert(
"Unsupported file type. Please upload text, code, or PDF files."
)
return return
} }
@ -223,17 +230,16 @@ export default function ChatInput({
<span className="hidden sm:inline">File</span> <span className="hidden sm:inline">File</span>
</Button> </Button>
{/* Render image upload button */} {/* Render image upload button */}
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
className="h-6 px-2 sm:px-3" className="h-6 px-2 sm:px-3"
onClick={handleImageUpload} onClick={handleImageUpload}
> >
<ImageIcon className="h-3 w-3 sm:mr-1" /> <ImageIcon className="h-3 w-3 sm:mr-1" />
<span className="hidden sm:inline">Image</span> <span className="hidden sm:inline">Image</span>
</Button> </Button>
</div> </div>
</div> </div>
) )
} }

View File

@ -3,9 +3,9 @@ import React, { useState } from "react"
import ReactMarkdown from "react-markdown" import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm" import remarkGfm from "remark-gfm"
import { Button } from "../../ui/button" import { Button } from "../../ui/button"
import { copyToClipboard, stringifyContent } from "./lib/chatUtils"
import ContextTabs from "./ContextTabs" import ContextTabs from "./ContextTabs"
import { createMarkdownComponents } from './lib/markdownComponents' import { copyToClipboard, stringifyContent } from "./lib/chatUtils"
import { createMarkdownComponents } from "./lib/markdownComponents"
import { MessageProps } from "./types" import { MessageProps } from "./types"
export default function ChatMessage({ export default function ChatMessage({
@ -14,7 +14,6 @@ export default function ChatMessage({
setIsContextExpanded, setIsContextExpanded,
socket, socket,
}: MessageProps) { }: MessageProps) {
// State for expanded message index // State for expanded message index
const [expandedMessageIndex, setExpandedMessageIndex] = useState< const [expandedMessageIndex, setExpandedMessageIndex] = useState<
number | null number | null
@ -23,7 +22,7 @@ export default function ChatMessage({
// State for copied text // State for copied text
const [copiedText, setCopiedText] = useState<string | null>(null) const [copiedText, setCopiedText] = useState<string | null>(null)
// Render copy button for text content // Render copy button for text content
const renderCopyButton = (text: any) => ( const renderCopyButton = (text: any) => (
<Button <Button
onClick={() => copyToClipboard(stringifyContent(text), setCopiedText)} onClick={() => copyToClipboard(stringifyContent(text), setCopiedText)}
@ -43,26 +42,26 @@ export default function ChatMessage({
const askAboutCode = (code: any) => { const askAboutCode = (code: any) => {
const contextString = stringifyContent(code) const contextString = stringifyContent(code)
const newContext = `Regarding this code:\n${contextString}` const newContext = `Regarding this code:\n${contextString}`
// Format timestamp to match chat message format (HH:MM PM) // Format timestamp to match chat message format (HH:MM PM)
const timestamp = new Date().toLocaleTimeString('en-US', { const timestamp = new Date().toLocaleTimeString("en-US", {
hour12: true, hour12: true,
hour: '2-digit', hour: "2-digit",
minute: '2-digit', minute: "2-digit",
}) })
// Instead of replacing context, append to it // Instead of replacing context, append to it
if (message.role === "assistant") { if (message.role === "assistant") {
// For assistant messages, create a new context tab with the response content and timestamp // For assistant messages, create a new context tab with the response content and timestamp
setContext(newContext, `AI Response (${timestamp})`, { setContext(newContext, `AI Response (${timestamp})`, {
start: 1, start: 1,
end: contextString.split('\n').length end: contextString.split("\n").length,
}) })
} else { } else {
// For user messages, create a new context tab with the selected content and timestamp // For user messages, create a new context tab with the selected content and timestamp
setContext(newContext, `User Chat (${timestamp})`, { setContext(newContext, `User Chat (${timestamp})`, {
start: 1, start: 1,
end: contextString.split('\n').length end: contextString.split("\n").length,
}) })
} }
setIsContextExpanded(false) setIsContextExpanded(false)
@ -127,7 +126,9 @@ export default function ChatMessage({
contextTabs={parseContextToTabs(message.context)} contextTabs={parseContextToTabs(message.context)}
onRemoveTab={() => {}} onRemoveTab={() => {}}
isExpanded={expandedMessageIndex === 0} isExpanded={expandedMessageIndex === 0}
onToggleExpand={() => setExpandedMessageIndex(expandedMessageIndex === 0 ? null : 0)} onToggleExpand={() =>
setExpandedMessageIndex(expandedMessageIndex === 0 ? null : 0)
}
className="[&_div:first-child>div:first-child>div]:bg-[#0D0D0D] [&_button:first-child]:hidden [&_button:last-child]:hidden" className="[&_div:first-child>div:first-child>div]:bg-[#0D0D0D] [&_button:first-child]:hidden [&_button:last-child]:hidden"
/> />
{expandedMessageIndex === 0 && ( {expandedMessageIndex === 0 && (
@ -153,7 +154,7 @@ export default function ChatMessage({
const updatedContext = `Regarding this code:\n${e.target.value}` const updatedContext = `Regarding this code:\n${e.target.value}`
setContext(updatedContext, "Selected Content", { setContext(updatedContext, "Selected Content", {
start: 1, start: 1,
end: e.target.value.split('\n').length end: e.target.value.split("\n").length,
}) })
}} }}
className="w-full p-2 bg-[#1e1e1e] text-white font-mono text-sm rounded" className="w-full p-2 bg-[#1e1e1e] text-white font-mono text-sm rounded"
@ -187,10 +188,7 @@ export default function ChatMessage({
)} )}
{/* Render markdown content */} {/* Render markdown content */}
{message.role === "assistant" ? ( {message.role === "assistant" ? (
<ReactMarkdown <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
remarkPlugins={[remarkGfm]}
components={components}
>
{message.content} {message.content}
</ReactMarkdown> </ReactMarkdown>
) : ( ) : (
@ -201,26 +199,28 @@ export default function ChatMessage({
) )
} }
// Parse context to tabs for context tabs component // Parse context to tabs for context tabs component
function parseContextToTabs(context: string) { function parseContextToTabs(context: string) {
const sections = context.split(/(?=File |Code from )/) const sections = context.split(/(?=File |Code from )/)
return sections.map((section, index) => { return sections
const lines = section.trim().split('\n') .map((section, index) => {
const titleLine = lines[0] const lines = section.trim().split("\n")
let content = lines.slice(1).join('\n').trim() const titleLine = lines[0]
let content = lines.slice(1).join("\n").trim()
// Remove code block markers for display
content = content.replace(/^```[\w-]*\n/, '').replace(/\n```$/, '') // Remove code block markers for display
content = content.replace(/^```[\w-]*\n/, "").replace(/\n```$/, "")
// Determine if the context is a file or code
const isFile = titleLine.startsWith('File ') // Determine if the context is a file or code
const name = titleLine.replace(/^(File |Code from )/, '').replace(':', '') const isFile = titleLine.startsWith("File ")
const name = titleLine.replace(/^(File |Code from )/, "").replace(":", "")
return {
id: `context-${index}`, return {
type: isFile ? "file" as const : "code" as const, id: `context-${index}`,
name: name, type: isFile ? ("file" as const) : ("code" as const),
content: content name: name,
} content: content,
}).filter(tab => tab.content.length > 0) }
})
.filter((tab) => tab.content.length > 0)
} }

View File

@ -1,16 +1,15 @@
import { Plus, X, Image as ImageIcon, FileText } from "lucide-react" import { Input } from "@/components/ui/input"
import { useState } from "react"
import { Button } from "../../ui/button"
import { TFile, TFolder } from "@/lib/types"
import { import {
Popover, Popover,
PopoverContent, PopoverContent,
PopoverTrigger, PopoverTrigger,
} from "@/components/ui/popover" } from "@/components/ui/popover"
import { Input } from "@/components/ui/input" import { TFile, TFolder } from "@/lib/types"
import { ContextTab } from "./types" import { FileText, Image as ImageIcon, Plus, X } from "lucide-react"
import { ContextTabsProps } from "./types" import { useState } from "react"
// Ignore certain folders and files from the file tree import { Button } from "../../ui/button"
import { ContextTab, ContextTabsProps } from "./types"
// Ignore certain folders and files from the file tree
import { ignoredFiles, ignoredFolders } from "./lib/ignored-paths" import { ignoredFiles, ignoredFolders } from "./lib/ignored-paths"
export default function ContextTabs({ export default function ContextTabs({
@ -20,7 +19,6 @@ export default function ContextTabs({
files = [], files = [],
onFileSelect, onFileSelect,
}: ContextTabsProps & { className?: string }) { }: ContextTabsProps & { className?: string }) {
// State for preview tab // State for preview tab
const [previewTab, setPreviewTab] = useState<ContextTab | null>(null) const [previewTab, setPreviewTab] = useState<ContextTab | null>(null)
const [searchQuery, setSearchQuery] = useState("") const [searchQuery, setSearchQuery] = useState("")
@ -28,9 +26,9 @@ export default function ContextTabs({
// Allow preview for images and code selections from editor // Allow preview for images and code selections from editor
const togglePreview = (tab: ContextTab) => { const togglePreview = (tab: ContextTab) => {
if (!tab.lineRange && tab.type !== "image") { if (!tab.lineRange && tab.type !== "image") {
return; return
} }
// Toggle preview for images and code selections from editor // Toggle preview for images and code selections from editor
if (previewTab?.id === tab.id) { if (previewTab?.id === tab.id) {
setPreviewTab(null) setPreviewTab(null)
@ -50,13 +48,21 @@ export default function ContextTabs({
// Get all files from the file tree to search for context // Get all files from the file tree to search for context
const getAllFiles = (items: (TFile | TFolder)[]): TFile[] => { const getAllFiles = (items: (TFile | TFolder)[]): TFile[] => {
return items.reduce((acc: TFile[], item) => { return items.reduce((acc: TFile[], item) => {
// Add file if it's not ignored // Add file if it's not ignored
if (item.type === "file" && !ignoredFiles.some((pattern: string) => if (
item.name.endsWith(pattern.replace('*', '')) || item.name === pattern item.type === "file" &&
)) { !ignoredFiles.some(
(pattern: string) =>
item.name.endsWith(pattern.replace("*", "")) ||
item.name === pattern
)
) {
acc.push(item) acc.push(item)
// Add all files from folder if it's not ignored // Add all files from folder if it's not ignored
} else if (item.type === "folder" && !ignoredFolders.some((folder: string) => folder === item.name)) { } else if (
item.type === "folder" &&
!ignoredFolders.some((folder: string) => folder === item.name)
) {
acc.push(...getAllFiles(item.children)) acc.push(...getAllFiles(item.children))
} }
return acc return acc
@ -65,22 +71,18 @@ export default function ContextTabs({
// Get all files from the file tree to search for context when adding context // Get all files from the file tree to search for context when adding context
const allFiles = getAllFiles(files) const allFiles = getAllFiles(files)
const filteredFiles = allFiles.filter(file => const filteredFiles = allFiles.filter((file) =>
file.name.toLowerCase().includes(searchQuery.toLowerCase()) file.name.toLowerCase().includes(searchQuery.toLowerCase())
) )
return ( return (
<div className={`border-none ${className || ''}`}> <div className={`border-none ${className || ""}`}>
<div className="flex flex-col"> <div className="flex flex-col">
<div className="flex items-center gap-1 overflow-hidden mb-2 flex-wrap"> <div className="flex items-center gap-1 overflow-hidden mb-2 flex-wrap">
{/* Add context tab button */} {/* Add context tab button */}
<Popover> <Popover>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button <Button variant="ghost" size="icon" className="h-6 w-6">
variant="ghost"
size="icon"
className="h-6 w-6"
>
<Plus className="h-4 w-4" /> <Plus className="h-4 w-4" />
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
@ -143,20 +145,23 @@ export default function ContextTabs({
{previewTab && ( {previewTab && (
<div className="p-2 bg-input rounded-md max-h-[200px] overflow-auto mb-2"> <div className="p-2 bg-input rounded-md max-h-[200px] overflow-auto mb-2">
{previewTab.type === "image" ? ( {previewTab.type === "image" ? (
<img <img
src={previewTab.content} src={previewTab.content}
alt={previewTab.name} alt={previewTab.name}
className="max-w-full h-auto" className="max-w-full h-auto"
/> />
) : previewTab.lineRange && ( ) : (
<> previewTab.lineRange && (
<div className="text-xs text-muted-foreground mt-1"> <>
Lines {previewTab.lineRange.start}-{previewTab.lineRange.end} <div className="text-xs text-muted-foreground mt-1">
</div> Lines {previewTab.lineRange.start}-
<pre className="text-xs font-mono whitespace-pre-wrap"> {previewTab.lineRange.end}
{previewTab.content} </div>
</pre> <pre className="text-xs font-mono whitespace-pre-wrap">
</> {previewTab.content}
</pre>
</>
)
)} )}
{/* Render file context tab */} {/* Render file context tab */}
{previewTab.type === "file" && ( {previewTab.type === "file" && (
@ -169,4 +174,4 @@ export default function ContextTabs({
</div> </div>
</div> </div>
) )
} }

View File

@ -1,14 +1,14 @@
import { X } from "lucide-react" import { useSocket } from "@/context/SocketContext"
import { TFile } from "@/lib/types"
import { X, ChevronDown } from "lucide-react"
import { nanoid } from "nanoid"
import { useEffect, useRef, useState } from "react" import { useEffect, useRef, useState } from "react"
import LoadingDots from "../../ui/LoadingDots" import LoadingDots from "../../ui/LoadingDots"
import ChatInput from "./ChatInput" import ChatInput from "./ChatInput"
import ChatMessage from "./ChatMessage" import ChatMessage from "./ChatMessage"
import ContextTabs from "./ContextTabs" import ContextTabs from "./ContextTabs"
import { handleSend, handleStopGeneration } from "./lib/chatUtils" import { handleSend, handleStopGeneration } from "./lib/chatUtils"
import { nanoid } from 'nanoid' import { AIChatProps, ContextTab, Message } from "./types"
import { TFile } from "@/lib/types"
import { useSocket } from "@/context/SocketContext"
import { Message, ContextTab, AIChatProps } from './types'
export default function AIChat({ export default function AIChat({
activeFileContent, activeFileContent,
@ -17,6 +17,7 @@ export default function AIChat({
editorRef, editorRef,
lastCopiedRangeRef, lastCopiedRangeRef,
files, files,
templateType,
}: AIChatProps) { }: AIChatProps) {
// Initialize socket and messages // Initialize socket and messages
const { socket } = useSocket() const { socket } = useSocket()
@ -38,65 +39,96 @@ export default function AIChat({
// Initialize textarea ref // Initialize textarea ref
const textareaRef = useRef<HTMLTextAreaElement>(null) const textareaRef = useRef<HTMLTextAreaElement>(null)
// Scroll to bottom of chat when messages change // state variables for auto scroll and scroll button
useEffect(() => { const [autoScroll, setAutoScroll] = useState(true)
scrollToBottom() const [showScrollButton, setShowScrollButton] = useState(false)
}, [messages])
// Scroll to bottom of chat when messages change // scroll to bottom of chat when messages change
const scrollToBottom = () => { useEffect(() => {
if (chatContainerRef.current) { if (autoScroll) {
setTimeout(() => { scrollToBottom()
chatContainerRef.current?.scrollTo({
top: chatContainerRef.current.scrollHeight,
behavior: "smooth",
})
}, 100)
} }
}, [messages, autoScroll])
// scroll to bottom of chat when messages change
const scrollToBottom = (force: boolean = false) => {
if (!chatContainerRef.current || (!autoScroll && !force)) return
chatContainerRef.current.scrollTo({
top: chatContainerRef.current.scrollHeight,
behavior: force ? "smooth" : "auto",
})
} }
// function to handle scroll events
const handleScroll = () => {
if (!chatContainerRef.current) return
const { scrollTop, scrollHeight, clientHeight } = chatContainerRef.current
const isAtBottom = Math.abs(scrollHeight - scrollTop - clientHeight) < 50
setAutoScroll(isAtBottom)
setShowScrollButton(!isAtBottom)
}
// scroll event listener
useEffect(() => {
const container = chatContainerRef.current
if (container) {
container.addEventListener('scroll', handleScroll)
return () => container.removeEventListener('scroll', handleScroll)
}
}, [])
// Add context tab to context tabs // Add context tab to context tabs
const addContextTab = (type: string, name: string, content: string, lineRange?: { start: number; end: number }) => { const addContextTab = (
type: string,
name: string,
content: string,
lineRange?: { start: number; end: number }
) => {
const newTab = { const newTab = {
id: nanoid(), id: nanoid(),
type: type as "file" | "code" | "image", type: type as "file" | "code" | "image",
name, name,
content, content,
lineRange lineRange,
} }
setContextTabs(prev => [...prev, newTab]) setContextTabs((prev) => [...prev, newTab])
} }
// Remove context tab from context tabs // Remove context tab from context tabs
const removeContextTab = (id: string) => { const removeContextTab = (id: string) => {
setContextTabs(prev => prev.filter(tab => tab.id !== id)) setContextTabs((prev) => prev.filter((tab) => tab.id !== id))
} }
// Add file to context tabs // Add file to context tabs
const handleAddFile = (tab: ContextTab) => { const handleAddFile = (tab: ContextTab) => {
setContextTabs(prev => [...prev, tab]) setContextTabs((prev) => [...prev, tab])
} }
// Format code content to remove starting and ending code block markers if they exist // Format code content to remove starting and ending code block markers if they exist
const formatCodeContent = (content: string) => { const formatCodeContent = (content: string) => {
return content.replace(/^```[\w-]*\n/, '').replace(/\n```$/, '') return content.replace(/^```[\w-]*\n/, "").replace(/\n```$/, "")
} }
// Get combined context from context tabs // Get combined context from context tabs
const getCombinedContext = () => { const getCombinedContext = () => {
if (contextTabs.length === 0) return '' if (contextTabs.length === 0) return ""
return contextTabs.map(tab => { return contextTabs
if (tab.type === 'file') { .map((tab) => {
const fileExt = tab.name.split('.').pop() || 'txt' if (tab.type === "file") {
const cleanContent = formatCodeContent(tab.content) const fileExt = tab.name.split(".").pop() || "txt"
return `File ${tab.name}:\n\`\`\`${fileExt}\n${cleanContent}\n\`\`\`` const cleanContent = formatCodeContent(tab.content)
} else if (tab.type === 'code') { return `File ${tab.name}:\n\`\`\`${fileExt}\n${cleanContent}\n\`\`\``
const cleanContent = formatCodeContent(tab.content) } else if (tab.type === "code") {
return `Code from ${tab.name}:\n\`\`\`typescript\n${cleanContent}\n\`\`\`` const cleanContent = formatCodeContent(tab.content)
} return `Code from ${tab.name}:\n\`\`\`typescript\n${cleanContent}\n\`\`\``
return `${tab.name}:\n${tab.content}` }
}).join('\n\n') return `${tab.name}:\n${tab.content}`
})
.join("\n\n")
} }
// Handle sending message with context // Handle sending message with context
@ -112,7 +144,9 @@ export default function AIChat({
setIsGenerating, setIsGenerating,
setIsLoading, setIsLoading,
abortControllerRef, abortControllerRef,
activeFileContent activeFileContent,
false,
templateType
) )
// Clear context tabs after sending // Clear context tabs after sending
setContextTabs([]) setContextTabs([])
@ -120,9 +154,9 @@ export default function AIChat({
// Set context for the chat // Set context for the chat
const setContext = ( const setContext = (
context: string | null, context: string | null,
name: string, name: string,
range?: { start: number, end: number } range?: { start: number; end: number }
) => { ) => {
if (!context) { if (!context) {
setContextTabs([]) setContextTabs([])
@ -130,7 +164,7 @@ export default function AIChat({
} }
// Always add a new tab instead of updating existing ones // Always add a new tab instead of updating existing ones
addContextTab('code', name, context, range) addContextTab("code", name, context, range)
} }
return ( return (
@ -153,10 +187,10 @@ export default function AIChat({
</div> </div>
<div <div
ref={chatContainerRef} ref={chatContainerRef}
className="flex-grow overflow-y-auto p-4 space-y-4" className="flex-grow overflow-y-auto p-4 space-y-4 relative"
> >
{messages.map((message, messageIndex) => ( {messages.map((message, messageIndex) => (
// Render chat message component for each message // Render chat message component for each message
<ChatMessage <ChatMessage
key={messageIndex} key={messageIndex}
message={message} message={message}
@ -166,6 +200,17 @@ export default function AIChat({
/> />
))} ))}
{isLoading && <LoadingDots />} {isLoading && <LoadingDots />}
{/* Add scroll to bottom button */}
{showScrollButton && (
<button
onClick={() => scrollToBottom(true)}
className="fixed bottom-36 right-6 bg-primary text-primary-foreground rounded-md border border-primary p-0.5 shadow-lg hover:bg-primary/90 transition-all"
aria-label="Scroll to bottom"
>
<ChevronDown className="h-5 w-5" />
</button>
)}
</div> </div>
<div className="p-4 border-t mb-14"> <div className="p-4 border-t mb-14">
{/* Render context tabs component */} {/* Render context tabs component */}
@ -180,9 +225,9 @@ export default function AIChat({
socket={socket} socket={socket}
onFileSelect={(file: TFile) => { onFileSelect={(file: TFile) => {
socket?.emit("getFile", { fileId: file.id }, (response: string) => { socket?.emit("getFile", { fileId: file.id }, (response: string) => {
const fileExt = file.name.split('.').pop() || 'txt' const fileExt = file.name.split(".").pop() || "txt"
const formattedContent = `\`\`\`${fileExt}\n${response}\n\`\`\`` const formattedContent = `\`\`\`${fileExt}\n${response}\n\`\`\``
addContextTab('file', file.name, formattedContent) addContextTab("file", file.name, formattedContent)
if (textareaRef.current) { if (textareaRef.current) {
textareaRef.current.focus() textareaRef.current.focus()
} }
@ -210,9 +255,9 @@ export default function AIChat({
}} }}
lastCopiedRangeRef={lastCopiedRangeRef} lastCopiedRangeRef={lastCopiedRangeRef}
activeFileName={activeFileName} activeFileName={activeFileName}
contextTabs={contextTabs.map(tab => ({ contextTabs={contextTabs.map((tab) => ({
...tab, ...tab,
title: tab.id title: tab.id,
}))} }))}
onRemoveTab={removeContextTab} onRemoveTab={removeContextTab}
/> />

View File

@ -1,6 +1,6 @@
import React from "react" import React from "react"
// Stringify content for chat message component // Stringify content for chat message component
export const stringifyContent = ( export const stringifyContent = (
content: any, content: any,
seen = new WeakSet() seen = new WeakSet()
@ -66,19 +66,19 @@ export const stringifyContent = (
return String(content) return String(content)
} }
// Copy to clipboard for chat message component // Copy to clipboard for chat message component
export const copyToClipboard = ( export const copyToClipboard = (
text: string, text: string,
setCopiedText: (text: string | null) => void setCopiedText: (text: string | null) => void
) => { ) => {
// Copy text to clipboard for chat message component // Copy text to clipboard for chat message component
navigator.clipboard.writeText(text).then(() => { navigator.clipboard.writeText(text).then(() => {
setCopiedText(text) setCopiedText(text)
setTimeout(() => setCopiedText(null), 2000) setTimeout(() => setCopiedText(null), 2000)
}) })
} }
// Handle send for chat message component // Handle send for chat message component
export const handleSend = async ( export const handleSend = async (
input: string, input: string,
context: string | null, context: string | null,
@ -89,27 +89,31 @@ export const handleSend = async (
setIsGenerating: React.Dispatch<React.SetStateAction<boolean>>, setIsGenerating: React.Dispatch<React.SetStateAction<boolean>>,
setIsLoading: React.Dispatch<React.SetStateAction<boolean>>, setIsLoading: React.Dispatch<React.SetStateAction<boolean>>,
abortControllerRef: React.MutableRefObject<AbortController | null>, abortControllerRef: React.MutableRefObject<AbortController | null>,
activeFileContent: string activeFileContent: string,
isEditMode: boolean = false,
templateType: string
) => { ) => {
// Return if input is empty and context is null // Return if input is empty and context is null
if (input.trim() === "" && !context) return if (input.trim() === "" && !context) return
// Get timestamp for chat message component // Get timestamp for chat message component
const timestamp = new Date().toLocaleTimeString('en-US', { const timestamp = new Date()
hour12: true, .toLocaleTimeString("en-US", {
hour: '2-digit', hour12: true,
minute: '2-digit' hour: "2-digit",
}).replace(/(\d{2}):(\d{2})/, '$1:$2') minute: "2-digit",
})
.replace(/(\d{2}):(\d{2})/, "$1:$2")
// Create user message for chat message component // Create user message for chat message component
const userMessage = { const userMessage = {
role: "user" as const, role: "user" as const,
content: input, content: input,
context: context || undefined, context: context || undefined,
timestamp: timestamp timestamp: timestamp,
} }
// Update messages for chat message component // Update messages for chat message component
const updatedMessages = [...messages, userMessage] const updatedMessages = [...messages, userMessage]
setMessages(updatedMessages) setMessages(updatedMessages)
setInput("") setInput("")
@ -120,24 +124,25 @@ export const handleSend = async (
abortControllerRef.current = new AbortController() abortControllerRef.current = new AbortController()
try { try {
// Create anthropic messages for chat message component // Create anthropic messages for chat message component
const anthropicMessages = updatedMessages.map((msg) => ({ const anthropicMessages = updatedMessages.map((msg) => ({
role: msg.role === "user" ? "human" : "assistant", role: msg.role === "user" ? "human" : "assistant",
content: msg.content, content: msg.content,
})) }))
// Fetch AI response for chat message component // Fetch AI response for chat message component
const response = await fetch( const response = await fetch("/api/ai",
`${process.env.NEXT_PUBLIC_AI_WORKER_URL}/api`, {
{ method: "POST",
method: "POST", headers: {
headers: { "Content-Type": "application/json",
"Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
messages: anthropicMessages, messages: anthropicMessages,
context: context || undefined, context: context || undefined,
activeFileContent: activeFileContent, activeFileContent: activeFileContent,
isEditMode: isEditMode,
templateType: templateType,
}), }),
signal: abortControllerRef.current.signal, signal: abortControllerRef.current.signal,
} }
@ -145,22 +150,23 @@ export const handleSend = async (
// Throw error if response is not ok // Throw error if response is not ok
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to get AI response") const error = await response.text()
throw new Error(error)
} }
// Get reader for chat message component // Get reader for chat message component
const reader = response.body?.getReader() const reader = response.body?.getReader()
const decoder = new TextDecoder() const decoder = new TextDecoder()
const assistantMessage = { role: "assistant" as const, content: "" } const assistantMessage = { role: "assistant" as const, content: "" }
setMessages([...updatedMessages, assistantMessage]) setMessages([...updatedMessages, assistantMessage])
setIsLoading(false) setIsLoading(false)
// Initialize buffer for chat message component // Initialize buffer for chat message component
let buffer = "" let buffer = ""
const updateInterval = 100 const updateInterval = 100
let lastUpdateTime = Date.now() let lastUpdateTime = Date.now()
// Read response from reader for chat message component // Read response from reader for chat message component
if (reader) { if (reader) {
while (true) { while (true) {
const { done, value } = await reader.read() const { done, value } = await reader.read()
@ -179,7 +185,7 @@ export const handleSend = async (
} }
} }
// Update messages for chat message component // Update messages for chat message component
setMessages((prev) => { setMessages((prev) => {
const updatedMessages = [...prev] const updatedMessages = [...prev]
const lastMessage = updatedMessages[updatedMessages.length - 1] const lastMessage = updatedMessages[updatedMessages.length - 1]
@ -188,14 +194,14 @@ export const handleSend = async (
}) })
} }
} catch (error: any) { } catch (error: any) {
// Handle abort error for chat message component // Handle abort error for chat message component
if (error.name === "AbortError") { if (error.name === "AbortError") {
console.log("Generation aborted") console.log("Generation aborted")
} else { } else {
console.error("Error fetching AI response:", error) console.error("Error fetching AI response:", error)
const errorMessage = { const errorMessage = {
role: "assistant" as const, role: "assistant" as const,
content: "Sorry, I encountered an error. Please try again.", content: error.message || "Sorry, I encountered an error. Please try again.",
} }
setMessages((prev) => [...prev, errorMessage]) setMessages((prev) => [...prev, errorMessage])
} }
@ -206,7 +212,7 @@ export const handleSend = async (
} }
} }
// Handle stop generation for chat message component // Handle stop generation for chat message component
export const handleStopGeneration = ( export const handleStopGeneration = (
abortControllerRef: React.MutableRefObject<AbortController | null> abortControllerRef: React.MutableRefObject<AbortController | null>
) => { ) => {
@ -215,21 +221,21 @@ export const handleStopGeneration = (
} }
} }
// Check if text looks like code for chat message component // Check if text looks like code for chat message component
export const looksLikeCode = (text: string): boolean => { export const looksLikeCode = (text: string): boolean => {
const codeIndicators = [ const codeIndicators = [
/^import\s+/m, // import statements /^import\s+/m, // import statements
/^function\s+/m, // function declarations /^function\s+/m, // function declarations
/^class\s+/m, // class declarations /^class\s+/m, // class declarations
/^const\s+/m, // const declarations /^const\s+/m, // const declarations
/^let\s+/m, // let declarations /^let\s+/m, // let declarations
/^var\s+/m, // var declarations /^var\s+/m, // var declarations
/[{}\[\]();]/, // common code syntax /[{}\[\]();]/, // common code syntax
/^\s*\/\//m, // comments /^\s*\/\//m, // comments
/^\s*\/\*/m, // multi-line comments /^\s*\/\*/m, // multi-line comments
/=>/, // arrow functions /=>/, // arrow functions
/^export\s+/m, // export statements /^export\s+/m, // export statements
]; ]
return codeIndicators.some(pattern => pattern.test(text)); return codeIndicators.some((pattern) => pattern.test(text))
}; }

View File

@ -1,102 +1,102 @@
// Ignore certain folders and files from the file tree // Ignore certain folders and files from the file tree
export const ignoredFolders = [ export const ignoredFolders = [
// Package managers // Package managers
'node_modules', "node_modules",
'venv', "venv",
'.env', ".env",
'env', "env",
'.venv', ".venv",
'virtualenv', "virtualenv",
'pip-wheel-metadata', "pip-wheel-metadata",
// Build outputs // Build outputs
'.next', ".next",
'dist', "dist",
'build', "build",
'out', "out",
'__pycache__', "__pycache__",
'.webpack', ".webpack",
'.serverless', ".serverless",
'storybook-static', "storybook-static",
// Version control // Version control
'.git', ".git",
'.svn', ".svn",
'.hg', // Mercurial ".hg", // Mercurial
// Cache and temp files // Cache and temp files
'.cache', ".cache",
'coverage', "coverage",
'tmp', "tmp",
'.temp', ".temp",
'.npm', ".npm",
'.pnpm', ".pnpm",
'.yarn', ".yarn",
'.eslintcache', ".eslintcache",
'.stylelintcache', ".stylelintcache",
// IDE specific // IDE specific
'.idea', ".idea",
'.vscode', ".vscode",
'.vs', ".vs",
'.sublime', ".sublime",
// Framework specific // Framework specific
'.streamlit', ".streamlit",
'.next', ".next",
'static', "static",
'.pytest_cache', ".pytest_cache",
'.nuxt', ".nuxt",
'.docusaurus', ".docusaurus",
'.remix', ".remix",
'.parcel-cache', ".parcel-cache",
'public/build', // Remix/Rails "public/build", // Remix/Rails
'.turbo', // Turborepo ".turbo", // Turborepo
// Logs // Logs
'logs', "logs",
'*.log', "*.log",
'npm-debug.log*', "npm-debug.log*",
'yarn-debug.log*', "yarn-debug.log*",
'yarn-error.log*', "yarn-error.log*",
'pnpm-debug.log*', "pnpm-debug.log*",
] as const; ] as const
export const ignoredFiles = [ export const ignoredFiles = [
'.DS_Store', ".DS_Store",
'.env.local', ".env.local",
'.env.development', ".env.development",
'.env.production', ".env.production",
'.env.test', ".env.test",
'.env*.local', ".env*.local",
'.gitignore', ".gitignore",
'.npmrc', ".npmrc",
'.yarnrc', ".yarnrc",
'.editorconfig', ".editorconfig",
'.prettierrc', ".prettierrc",
'.eslintrc', ".eslintrc",
'.browserslistrc', ".browserslistrc",
'tsconfig.tsbuildinfo', "tsconfig.tsbuildinfo",
'*.pyc', "*.pyc",
'*.pyo', "*.pyo",
'*.pyd', "*.pyd",
'*.so', "*.so",
'*.dll', "*.dll",
'*.dylib', "*.dylib",
'*.class', "*.class",
'*.exe', "*.exe",
'package-lock.json', "package-lock.json",
'yarn.lock', "yarn.lock",
'pnpm-lock.yaml', "pnpm-lock.yaml",
'composer.lock', "composer.lock",
'poetry.lock', "poetry.lock",
'Gemfile.lock', "Gemfile.lock",
'*.min.js', "*.min.js",
'*.min.css', "*.min.css",
'*.map', "*.map",
'*.chunk.*', "*.chunk.*",
'*.hot-update.*', "*.hot-update.*",
'.vercel', ".vercel",
'.netlify' ".netlify",
] as const; ] as const

View File

@ -1,21 +1,26 @@
import { CornerUpLeft } from "lucide-react"
import { Components } from "react-markdown" import { Components } from "react-markdown"
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter" import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"
import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism" import { vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism"
import { Button } from "../../../ui/button" import { Button } from "../../../ui/button"
import { CornerUpLeft } from "lucide-react"
import { stringifyContent } from "./chatUtils" import { stringifyContent } from "./chatUtils"
// Create markdown components for chat message component // Create markdown components for chat message component
export const createMarkdownComponents = ( export const createMarkdownComponents = (
renderCopyButton: (text: any) => JSX.Element, renderCopyButton: (text: any) => JSX.Element,
renderMarkdownElement: (props: any) => JSX.Element, renderMarkdownElement: (props: any) => JSX.Element,
askAboutCode: (code: any) => void askAboutCode: (code: any) => void
): Components => ({ ): Components => ({
code: ({ node, className, children, ...props }: { code: ({
node?: import('hast').Element, node,
className?: string, className,
children?: React.ReactNode, children,
[key: string]: any, ...props
}: {
node?: import("hast").Element
className?: string
children?: React.ReactNode
[key: string]: any
}) => { }) => {
const match = /language-(\w+)/.exec(className || "") const match = /language-(\w+)/.exec(className || "")
@ -55,25 +60,30 @@ export const createMarkdownComponents = (
</div> </div>
</div> </div>
) : ( ) : (
<code className={className} {...props}>{children}</code> <code className={className} {...props}>
{children}
</code>
) )
}, },
// Render markdown elements // Render markdown elements
p: ({ node, children, ...props }) => renderMarkdownElement({ node, children, ...props }), p: ({ node, children, ...props }) =>
h1: ({ node, children, ...props }) => renderMarkdownElement({ node, children, ...props }), renderMarkdownElement({ node, children, ...props }),
h2: ({ node, children, ...props }) => renderMarkdownElement({ node, children, ...props }), h1: ({ node, children, ...props }) =>
h3: ({ node, children, ...props }) => renderMarkdownElement({ node, children, ...props }), renderMarkdownElement({ node, children, ...props }),
h4: ({ node, children, ...props }) => renderMarkdownElement({ node, children, ...props }), h2: ({ node, children, ...props }) =>
h5: ({ node, children, ...props }) => renderMarkdownElement({ node, children, ...props }), renderMarkdownElement({ node, children, ...props }),
h6: ({ node, children, ...props }) => renderMarkdownElement({ node, children, ...props }), h3: ({ node, children, ...props }) =>
renderMarkdownElement({ node, children, ...props }),
h4: ({ node, children, ...props }) =>
renderMarkdownElement({ node, children, ...props }),
h5: ({ node, children, ...props }) =>
renderMarkdownElement({ node, children, ...props }),
h6: ({ node, children, ...props }) =>
renderMarkdownElement({ node, children, ...props }),
ul: (props) => ( ul: (props) => (
<ul className="list-disc pl-6 mb-4 space-y-2"> <ul className="list-disc pl-6 mb-4 space-y-2">{props.children}</ul>
{props.children}
</ul>
), ),
ol: (props) => ( ol: (props) => (
<ol className="list-decimal pl-6 mb-4 space-y-2"> <ol className="list-decimal pl-6 mb-4 space-y-2">{props.children}</ol>
{props.children}
</ol>
), ),
}) })

View File

@ -1,28 +1,29 @@
import * as monaco from 'monaco-editor' import { TemplateConfig } from "@/lib/templates"
import { TFile, TFolder } from "@/lib/types" import { TFile, TFolder } from "@/lib/types"
import { Socket } from 'socket.io-client'; import * as monaco from "monaco-editor"
import { Socket } from "socket.io-client"
// Allowed file types for context tabs // Allowed file types for context tabs
export const ALLOWED_FILE_TYPES = { export const ALLOWED_FILE_TYPES = {
// Text files // Text files
'text/plain': true, "text/plain": true,
'text/markdown': true, "text/markdown": true,
'text/csv': true, "text/csv": true,
// Code files // Code files
'application/json': true, "application/json": true,
'text/javascript': true, "text/javascript": true,
'text/typescript': true, "text/typescript": true,
'text/html': true, "text/html": true,
'text/css': true, "text/css": true,
// Documents // Documents
'application/pdf': true, "application/pdf": true,
// Images // Images
'image/jpeg': true, "image/jpeg": true,
'image/png': true, "image/png": true,
'image/gif': true, "image/gif": true,
'image/webp': true, "image/webp": true,
'image/svg+xml': true, "image/svg+xml": true,
} as const; } as const
// Message interface // Message interface
export interface Message { export interface Message {
@ -45,9 +46,16 @@ export interface AIChatProps {
activeFileContent: string activeFileContent: string
activeFileName: string activeFileName: string
onClose: () => void onClose: () => void
editorRef: React.MutableRefObject<monaco.editor.IStandaloneCodeEditor | undefined> editorRef: React.MutableRefObject<
lastCopiedRangeRef: React.MutableRefObject<{ startLine: number; endLine: number } | null> monaco.editor.IStandaloneCodeEditor | undefined
>
lastCopiedRangeRef: React.MutableRefObject<{
startLine: number
endLine: number
} | null>
files: (TFile | TFolder)[] files: (TFile | TFolder)[]
templateType: string
templateConfig?: TemplateConfig
} }
// Chat input props interface // Chat input props interface
@ -58,11 +66,27 @@ export interface ChatInputProps {
handleSend: (useFullContext?: boolean) => void handleSend: (useFullContext?: boolean) => void
handleStopGeneration: () => void handleStopGeneration: () => void
onImageUpload: (file: File) => void onImageUpload: (file: File) => void
addContextTab: (type: string, title: string, content: string, lineRange?: { start: number, end: number }) => void addContextTab: (
type: string,
title: string,
content: string,
lineRange?: { start: number; end: number }
) => void
activeFileName?: string activeFileName?: string
editorRef: React.MutableRefObject<monaco.editor.IStandaloneCodeEditor | undefined> editorRef: React.MutableRefObject<
lastCopiedRangeRef: React.MutableRefObject<{ startLine: number; endLine: number } | null> monaco.editor.IStandaloneCodeEditor | undefined
contextTabs: { id: string; type: string; title: string; content: string; lineRange?: { start: number; end: number } }[] >
lastCopiedRangeRef: React.MutableRefObject<{
startLine: number
endLine: number
} | null>
contextTabs: {
id: string
type: string
title: string
content: string
lineRange?: { start: number; end: number }
}[]
onRemoveTab: (id: string) => void onRemoveTab: (id: string) => void
textareaRef: React.RefObject<HTMLTextAreaElement> textareaRef: React.RefObject<HTMLTextAreaElement>
} }
@ -74,7 +98,11 @@ export interface MessageProps {
content: string content: string
context?: string context?: string
} }
setContext: (context: string | null, name: string, range?: { start: number, end: number }) => void setContext: (
context: string | null,
name: string,
range?: { start: number; end: number }
) => void
setIsContextExpanded: (isExpanded: boolean) => void setIsContextExpanded: (isExpanded: boolean) => void
socket: Socket | null socket: Socket | null
} }

View File

@ -5,14 +5,12 @@ import { Editor } from "@monaco-editor/react"
import { Check, Loader2, RotateCw, Sparkles, X } from "lucide-react" import { Check, Loader2, RotateCw, Sparkles, X } from "lucide-react"
import { usePathname, useRouter } from "next/navigation" import { usePathname, useRouter } from "next/navigation"
import { useCallback, useEffect, useRef, useState } from "react" import { useCallback, useEffect, useRef, useState } from "react"
import { Socket } from "socket.io-client"
import { toast } from "sonner" import { toast } from "sonner"
import { Button } from "../ui/button" import { Button } from "../ui/button"
// import monaco from "monaco-editor" // import monaco from "monaco-editor"
export default function GenerateInput({ export default function GenerateInput({
user, user,
socket,
width, width,
data, data,
editor, editor,
@ -21,7 +19,6 @@ export default function GenerateInput({
onClose, onClose,
}: { }: {
user: User user: User
socket: Socket
width: number width: number
data: { data: {
fileName: string fileName: string
@ -59,32 +56,54 @@ export default function GenerateInput({
}: { }: {
regenerate?: boolean regenerate?: boolean
}) => { }) => {
if (user.generations >= 1000) { try {
toast.error("You reached the maximum # of generations.") setLoading({ generate: !regenerate, regenerate })
return setCurrentPrompt(input)
}
setLoading({ generate: !regenerate, regenerate }) const response = await fetch("/api/ai", {
setCurrentPrompt(input) method: "POST",
socket.emit( headers: {
"generateCode", "Content-Type": "application/json",
{ },
fileName: data.fileName, body: JSON.stringify({
code: data.code, messages: [{
line: data.line, role: "user",
instructions: regenerate ? currentPrompt : input content: regenerate ? currentPrompt : input
}, }],
(res: { response: string; success: boolean }) => { context: null,
console.log("Generated code", res.response, res.success) activeFileContent: data.code,
// if (!res.success) { isEditMode: true,
// toast.error("Failed to generate code."); fileName: data.fileName,
// return; line: data.line
// } }),
})
setCode(res.response) if (!response.ok) {
router.refresh() const error = await response.text()
toast.error(error)
return
} }
)
const reader = response.body?.getReader()
const decoder = new TextDecoder()
let result = ""
if (reader) {
while (true) {
const { done, value } = await reader.read()
if (done) break
result += decoder.decode(value, { stream: true })
}
}
setCode(result.trim())
router.refresh()
} catch (error) {
console.error("Generation error:", error)
toast.error("Failed to generate code")
} finally {
setLoading({ generate: false, regenerate: false })
}
} }
const handleGenerateForm = useCallback( const handleGenerateForm = useCallback(
(e: React.FormEvent<HTMLFormElement>) => { (e: React.FormEvent<HTMLFormElement>) => {

View File

@ -7,11 +7,11 @@ import * as monaco from "monaco-editor"
import { useCallback, useEffect, useRef, useState } from "react" import { useCallback, useEffect, useRef, useState } from "react"
import { toast } from "sonner" import { toast } from "sonner"
import { TypedLiveblocksProvider, useRoom, useSelf } from "@/liveblocks.config" // import { TypedLiveblocksProvider, useRoom, useSelf } from "@/liveblocks.config"
import LiveblocksProvider from "@liveblocks/yjs" // import LiveblocksProvider from "@liveblocks/yjs"
import { MonacoBinding } from "y-monaco" // import { MonacoBinding } from "y-monaco"
import { Awareness } from "y-protocols/awareness" // import { Awareness } from "y-protocols/awareness"
import * as Y from "yjs" // import * as Y from "yjs"
import { import {
ResizableHandle, ResizableHandle,
@ -23,7 +23,6 @@ import { useSocket } from "@/context/SocketContext"
import { parseTSConfigToMonacoOptions } from "@/lib/tsconfig" import { parseTSConfigToMonacoOptions } from "@/lib/tsconfig"
import { Sandbox, TFile, TFolder, TTab, User } from "@/lib/types" import { Sandbox, TFile, TFolder, TTab, User } from "@/lib/types"
import { import {
addNew,
cn, cn,
debounce, debounce,
deepMerge, deepMerge,
@ -46,7 +45,7 @@ import { Button } from "../ui/button"
import Tab from "../ui/tab" import Tab from "../ui/tab"
import AIChat from "./AIChat" import AIChat from "./AIChat"
import GenerateInput from "./generate" import GenerateInput from "./generate"
import { Cursors } from "./live/cursors" // import { Cursors } from "./live/cursors"
import DisableAccessModal from "./live/disableModal" import DisableAccessModal from "./live/disableModal"
import Loading from "./loading" import Loading from "./loading"
import PreviewWindow from "./preview" import PreviewWindow from "./preview"
@ -147,20 +146,20 @@ export default function CodeEditor({
const isOwner = sandboxData.userId === userData.id const isOwner = sandboxData.userId === userData.id
const clerk = useClerk() const clerk = useClerk()
// Liveblocks hooks // // Liveblocks hooks
const room = useRoom() // const room = useRoom()
const [provider, setProvider] = useState<TypedLiveblocksProvider>() // const [provider, setProvider] = useState<TypedLiveblocksProvider>()
const userInfo = useSelf((me) => me.info) // const userInfo = useSelf((me) => me.info)
// Liveblocks providers map to prevent reinitializing providers // // Liveblocks providers map to prevent reinitializing providers
type ProviderData = { // type ProviderData = {
provider: LiveblocksProvider<never, never, never, never> // provider: LiveblocksProvider<never, never, never, never>
yDoc: Y.Doc // yDoc: Y.Doc
yText: Y.Text // yText: Y.Text
binding?: MonacoBinding // binding?: MonacoBinding
onSync: (isSynced: boolean) => void // onSync: (isSynced: boolean) => void
} // }
const providersMap = useRef(new Map<string, ProviderData>()) // const providersMap = useRef(new Map<string, ProviderData>())
// Refs for libraries / features // Refs for libraries / features
const editorContainerRef = useRef<HTMLDivElement>(null) const editorContainerRef = useRef<HTMLDivElement>(null)
@ -173,7 +172,10 @@ export default function CodeEditor({
const previewWindowRef = useRef<{ refreshIframe: () => void }>(null) const previewWindowRef = useRef<{ refreshIframe: () => void }>(null)
// Ref to store the last copied range in the editor to be used in the AIChat component // Ref to store the last copied range in the editor to be used in the AIChat component
const lastCopiedRangeRef = useRef<{ startLine: number; endLine: number } | null>(null); const lastCopiedRangeRef = useRef<{
startLine: number
endLine: number
} | null>(null)
const debouncedSetIsSelected = useRef( const debouncedSetIsSelected = useRef(
debounce((value: boolean) => { debounce((value: boolean) => {
@ -260,14 +262,14 @@ export default function CodeEditor({
// Store the last copied range in the editor to be used in the AIChat component // Store the last copied range in the editor to be used in the AIChat component
editor.onDidChangeCursorSelection((e) => { editor.onDidChangeCursorSelection((e) => {
const selection = editor.getSelection(); const selection = editor.getSelection()
if (selection) { if (selection) {
lastCopiedRangeRef.current = { lastCopiedRangeRef.current = {
startLine: selection.startLineNumber, startLine: selection.startLineNumber,
endLine: selection.endLineNumber endLine: selection.endLineNumber,
}; }
} }
}); })
} }
// Call the function with your file structure // Call the function with your file structure
@ -571,82 +573,82 @@ export default function CodeEditor({
} }
}, [activeFileId, tabs, debouncedSaveData, setIsAIChatOpen, editorRef]) }, [activeFileId, tabs, debouncedSaveData, setIsAIChatOpen, editorRef])
// Liveblocks live collaboration setup effect // // Liveblocks live collaboration setup effect
useEffect(() => { // useEffect(() => {
const tab = tabs.find((t) => t.id === activeFileId) // const tab = tabs.find((t) => t.id === activeFileId)
const model = editorRef?.getModel() // const model = editorRef?.getModel()
if (!editorRef || !tab || !model) return // if (!editorRef || !tab || !model) return
let providerData: ProviderData // let providerData: ProviderData
// When a file is opened for the first time, create a new provider and store in providersMap. // // When a file is opened for the first time, create a new provider and store in providersMap.
if (!providersMap.current.has(tab.id)) { // if (!providersMap.current.has(tab.id)) {
const yDoc = new Y.Doc() // const yDoc = new Y.Doc()
const yText = yDoc.getText(tab.id) // const yText = yDoc.getText(tab.id)
const yProvider = new LiveblocksProvider(room, yDoc) // const yProvider = new LiveblocksProvider(room, yDoc)
// Inserts the file content into the editor once when the tab is changed. // // Inserts the file content into the editor once when the tab is changed.
const onSync = (isSynced: boolean) => { // const onSync = (isSynced: boolean) => {
if (isSynced) { // if (isSynced) {
const text = yText.toString() // const text = yText.toString()
if (text === "") { // if (text === "") {
if (activeFileContent) { // if (activeFileContent) {
yText.insert(0, activeFileContent) // yText.insert(0, activeFileContent)
} else { // } else {
setTimeout(() => { // setTimeout(() => {
yText.insert(0, editorRef.getValue()) // yText.insert(0, editorRef.getValue())
}, 0) // }, 0)
} // }
} // }
} // }
} // }
yProvider.on("sync", onSync) // yProvider.on("sync", onSync)
// Save the provider to the map. // // Save the provider to the map.
providerData = { provider: yProvider, yDoc, yText, onSync } // providerData = { provider: yProvider, yDoc, yText, onSync }
providersMap.current.set(tab.id, providerData) // providersMap.current.set(tab.id, providerData)
} else { // } else {
// When a tab is opened that has been open before, reuse the existing provider. // // When a tab is opened that has been open before, reuse the existing provider.
providerData = providersMap.current.get(tab.id)! // providerData = providersMap.current.get(tab.id)!
} // }
const binding = new MonacoBinding( // const binding = new MonacoBinding(
providerData.yText, // providerData.yText,
model, // model,
new Set([editorRef]), // new Set([editorRef]),
providerData.provider.awareness as unknown as Awareness // providerData.provider.awareness as unknown as Awareness
) // )
providerData.binding = binding // providerData.binding = binding
setProvider(providerData.provider) // setProvider(providerData.provider)
return () => { // return () => {
// Cleanup logic // // Cleanup logic
if (binding) { // if (binding) {
binding.destroy() // binding.destroy()
} // }
if (providerData.binding) { // if (providerData.binding) {
providerData.binding = undefined // providerData.binding = undefined
} // }
} // }
}, [room, activeFileContent]) // }, [room, activeFileContent])
// Added this effect to clean up when the component unmounts // // Added this effect to clean up when the component unmounts
useEffect(() => { // useEffect(() => {
return () => { // return () => {
// Clean up all providers when the component unmounts // // Clean up all providers when the component unmounts
providersMap.current.forEach((data) => { // providersMap.current.forEach((data) => {
if (data.binding) { // if (data.binding) {
data.binding.destroy() // data.binding.destroy()
} // }
data.provider.disconnect() // data.provider.disconnect()
data.yDoc.destroy() // data.yDoc.destroy()
}) // })
providersMap.current.clear() // providersMap.current.clear()
} // }
}, []) // }, [])
// Connection/disconnection effect // Connection/disconnection effect
useEffect(() => { useEffect(() => {
@ -658,7 +660,7 @@ export default function CodeEditor({
// Socket event listener effect // Socket event listener effect
useEffect(() => { useEffect(() => {
const onConnect = () => { } const onConnect = () => {}
const onDisconnect = () => { const onDisconnect = () => {
setTerminals([]) setTerminals([])
@ -786,8 +788,8 @@ export default function CodeEditor({
? numTabs === 1 ? numTabs === 1
? null ? null
: index < numTabs - 1 : index < numTabs - 1
? tabs[index + 1].id ? tabs[index + 1].id
: tabs[index - 1].id : tabs[index - 1].id
: activeFileId : activeFileId
setTabs((prev) => prev.filter((t) => t.id !== id)) setTabs((prev) => prev.filter((t) => t.id !== id))
@ -853,9 +855,7 @@ export default function CodeEditor({
} }
const handleDeleteFile = (file: TFile) => { const handleDeleteFile = (file: TFile) => {
socket?.emit("deleteFile", { fileId: file.id }, (response: (TFolder | TFile)[]) => { socket?.emit("deleteFile", { fileId: file.id })
setFiles(response)
})
closeTab(file.id) closeTab(file.id)
} }
@ -867,10 +867,13 @@ export default function CodeEditor({
closeTabs(response) closeTabs(response)
) )
socket?.emit("deleteFolder", { folderId: folder.id }, (response: (TFolder | TFile)[]) => { socket?.emit(
setFiles(response) "deleteFolder",
setDeletingFolderId("") { folderId: folder.id },
}) (response: (TFolder | TFile)[]) => {
setDeletingFolderId("")
}
)
} }
const togglePreviewPanel = () => { const togglePreviewPanel = () => {
@ -911,7 +914,7 @@ export default function CodeEditor({
<DisableAccessModal <DisableAccessModal
message={disableAccess.message} message={disableAccess.message}
open={disableAccess.isDisabled} open={disableAccess.isDisabled}
setOpen={() => { }} setOpen={() => {}}
/> />
<Loading /> <Loading />
</> </>
@ -946,15 +949,14 @@ export default function CodeEditor({
{generate.show ? ( {generate.show ? (
<GenerateInput <GenerateInput
user={userData} user={userData}
socket={socket!}
width={generate.width - 90} width={generate.width - 90}
data={{ data={{
fileName: tabs.find((t) => t.id === activeFileId)?.name ?? "", fileName: tabs.find((t) => t.id === activeFileId)?.name ?? "",
code: code:
(isSelected && editorRef?.getSelection() (isSelected && editorRef?.getSelection()
? editorRef ? editorRef
?.getModel() ?.getModel()
?.getValueInRange(editorRef?.getSelection()!) ?.getValueInRange(editorRef?.getSelection()!)
: editorRef?.getValue()) ?? "", : editorRef?.getValue()) ?? "",
line: generate.line, line: generate.line,
}} }}
@ -1036,7 +1038,6 @@ export default function CodeEditor({
handleDeleteFolder={handleDeleteFolder} handleDeleteFolder={handleDeleteFolder}
socket={socket!} socket={socket!}
setFiles={setFiles} setFiles={setFiles}
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
deletingFolderId={deletingFolderId} deletingFolderId={deletingFolderId}
toggleAIChat={toggleAIChat} toggleAIChat={toggleAIChat}
isAIChatOpen={isAIChatOpen} isAIChatOpen={isAIChatOpen}
@ -1088,9 +1089,9 @@ export default function CodeEditor({
) : // Note clerk.loaded is required here due to a bug: https://github.com/clerk/javascript/issues/1643 ) : // Note clerk.loaded is required here due to a bug: https://github.com/clerk/javascript/issues/1643
clerk.loaded ? ( clerk.loaded ? (
<> <>
{provider && userInfo ? ( {/* {provider && userInfo ? (
<Cursors yProvider={provider} userInfo={userInfo} /> <Cursors yProvider={provider} userInfo={userInfo} />
) : null} ) : null} */}
<Editor <Editor
height="100%" height="100%"
language={editorLanguage} language={editorLanguage}
@ -1151,10 +1152,10 @@ export default function CodeEditor({
isAIChatOpen && isHorizontalLayout isAIChatOpen && isHorizontalLayout
? "horizontal" ? "horizontal"
: isAIChatOpen : isAIChatOpen
? "vertical" ? "vertical"
: isHorizontalLayout : isHorizontalLayout
? "horizontal" ? "horizontal"
: "vertical" : "vertical"
} }
> >
<ResizablePanel <ResizablePanel
@ -1232,6 +1233,7 @@ export default function CodeEditor({
editorRef={{ current: editorRef }} editorRef={{ current: editorRef }}
lastCopiedRangeRef={lastCopiedRangeRef} lastCopiedRangeRef={lastCopiedRangeRef}
files={files} files={files}
templateType={sandboxData.type}
/> />
</ResizablePanel> </ResizablePanel>
</> </>

View File

@ -1,29 +1,36 @@
import JSZip from 'jszip' // React component for download button
import { useSocket } from "@/context/SocketContext"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { useSocket } from "@/context/SocketContext"
import { Download } from "lucide-react" import { Download } from "lucide-react"
export default function DownloadButton({ name }: { name: string }) { export default function DownloadButton({ name }: { name: string }) {
const { socket } = useSocket() const { socket } = useSocket()
const handleDownload = async () => { const handleDownload = async () => {
socket?.emit("downloadFiles", {}, async (response: {files: {path: string, content: string}[]}) => { socket?.emit(
const zip = new JSZip() "downloadFiles",
{ timestamp: Date.now() },
response.files.forEach(file => { async (response: { zipBlob: string }) => {
zip.file(file.path, file.content) const { zipBlob } = response
})
const blob = await zip.generateAsync({type: "blob"})
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${name}.zip`
a.click()
window.URL.revokeObjectURL(url)
})
}
// Decode Base64 back to binary data
const binary = atob(zipBlob)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
const blob = new Blob([bytes], { type: "application/zip" })
// Create URL and download
const url = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = `${name}.zip`
a.click()
window.URL.revokeObjectURL(url)
}
)
}
return ( return (
<Button variant="outline" onClick={handleDownload}> <Button variant="outline" onClick={handleDownload}>

View File

@ -9,12 +9,12 @@ import { Pencil, Users } from "lucide-react"
import Image from "next/image" import Image from "next/image"
import Link from "next/link" import Link from "next/link"
import { useState } from "react" import { useState } from "react"
import { Avatars } from "../live/avatars" // import { Avatars } from "../live/avatars"
import DeployButtonModal from "./deploy" import DeployButtonModal from "./deploy"
import DownloadButton from "./downloadButton"
import EditSandboxModal from "./edit" import EditSandboxModal from "./edit"
import RunButtonModal from "./run" import RunButtonModal from "./run"
import ShareSandboxModal from "./share" import ShareSandboxModal from "./share"
import DownloadButton from "./downloadButton"
export default function Navbar({ export default function Navbar({
userData, userData,
@ -70,15 +70,15 @@ export default function Navbar({
sandboxData={sandboxData} sandboxData={sandboxData}
/> />
<div className="flex items-center h-full space-x-4"> <div className="flex items-center h-full space-x-4">
<Avatars /> {/* <Avatars /> */}
{isOwner ? ( {isOwner ? (
<> <>
<DeployButtonModal data={sandboxData} userData={userData} /> <DeployButtonModal data={sandboxData} userData={userData} />
<Button variant="outline" onClick={() => setIsShareOpen(true)}> {/* <Button variant="outline" onClick={() => setIsShareOpen(true)}>
<Users className="w-4 h-4 mr-2" /> <Users className="w-4 h-4 mr-2" />
Share Share
</Button> </Button> */}
<DownloadButton name={sandboxData.name} /></> <DownloadButton name={sandboxData.name} /></>
) : null} ) : null}
<ThemeSwitcher /> <ThemeSwitcher />

View File

@ -7,6 +7,7 @@ import { Sandbox } from "@/lib/types"
import { Play, StopCircle } from "lucide-react" import { Play, StopCircle } from "lucide-react"
import { useEffect, useRef } from "react" import { useEffect, useRef } from "react"
import { toast } from "sonner" import { toast } from "sonner"
import { templateConfigs } from "@/lib/templates"
export default function RunButtonModal({ export default function RunButtonModal({
isRunning, isRunning,
@ -34,7 +35,12 @@ export default function RunButtonModal({
} }
} }
}, [terminals, isRunning]) }, [terminals, isRunning])
// commands to run in the terminal
const COMMANDS = {
streamlit: "./venv/bin/streamlit run main.py --server.runOnSave true",
php: "echo http://localhost:80 && npx vite",
default: "npm run dev",
} as const
const handleRun = async () => { const handleRun = async () => {
if (isRunning && lastCreatedTerminalRef.current) { if (isRunning && lastCreatedTerminalRef.current) {
await closeTerminal(lastCreatedTerminalRef.current) await closeTerminal(lastCreatedTerminalRef.current)
@ -42,10 +48,7 @@ export default function RunButtonModal({
setIsPreviewCollapsed(true) setIsPreviewCollapsed(true)
previewPanelRef.current?.collapse() previewPanelRef.current?.collapse()
} else if (!isRunning && terminals.length < 4) { } else if (!isRunning && terminals.length < 4) {
const command = const command = templateConfigs[sandboxData.type]?.runCommand || "npm run dev"
sandboxData.type === "streamlit"
? "./venv/bin/streamlit run main.py --server.runOnSave true"
: "npm run dev"
try { try {
// Create a new terminal with the appropriate command // Create a new terminal with the appropriate command

View File

@ -143,11 +143,7 @@ export default function ShareSandboxModal({
</DialogHeader> </DialogHeader>
<div className="space-y-2"> <div className="space-y-2">
{shared.map((user) => ( {shared.map((user) => (
<SharedUser <SharedUser key={user.id} user={user} sandboxId={data.id} />
key={user.id}
user={user}
sandboxId={data.id}
/>
))} ))}
</div> </div>
</div> </div>

View File

@ -25,7 +25,6 @@ export default function Sidebar({
handleDeleteFolder, handleDeleteFolder,
socket, socket,
setFiles, setFiles,
addNew,
deletingFolderId, deletingFolderId,
toggleAIChat, toggleAIChat,
isAIChatOpen, isAIChatOpen,
@ -43,7 +42,6 @@ export default function Sidebar({
handleDeleteFolder: (folder: TFolder) => void handleDeleteFolder: (folder: TFolder) => void
socket: Socket socket: Socket
setFiles: (files: (TFile | TFolder)[]) => void setFiles: (files: (TFile | TFolder)[]) => void
addNew: (name: string, type: "file" | "folder") => void
deletingFolderId: string deletingFolderId: string
toggleAIChat: () => void toggleAIChat: () => void
isAIChatOpen: boolean isAIChatOpen: boolean
@ -93,7 +91,7 @@ export default function Sidebar({
"moveFile", "moveFile",
{ {
fileId, fileId,
folderId folderId,
}, },
(response: (TFolder | TFile)[]) => { (response: (TFolder | TFile)[]) => {
setFiles(response) setFiles(response)
@ -176,7 +174,6 @@ export default function Sidebar({
stopEditing={() => { stopEditing={() => {
setCreatingNew(null) setCreatingNew(null)
}} }}
addNew={addNew}
/> />
) : null} ) : null}
</> </>
@ -203,20 +200,18 @@ export default function Sidebar({
variant="ghost" variant="ghost"
className={cn( className={cn(
"w-full justify-start text-sm font-normal h-8 px-2 mb-2 border-t", "w-full justify-start text-sm font-normal h-8 px-2 mb-2 border-t",
isAIChatOpen isAIChatOpen
? "bg-muted-foreground/25 text-foreground" ? "bg-muted-foreground/25 text-foreground"
: "text-muted-foreground" : "text-muted-foreground"
)} )}
onClick={toggleAIChat} onClick={toggleAIChat}
aria-disabled={false} aria-disabled={false}
style={{ opacity: 1 }} style={{ opacity: 1 }}
> >
<MessageSquareMore <MessageSquareMore
className={cn( className={cn(
"h-4 w-4 mr-2", "h-4 w-4 mr-2",
isAIChatOpen isAIChatOpen ? "text-indigo-500" : "text-indigo-500 opacity-70"
? "text-indigo-500"
: "text-indigo-500 opacity-70"
)} )}
/> />
AI Chat AI Chat

View File

@ -9,12 +9,10 @@ export default function New({
socket, socket,
type, type,
stopEditing, stopEditing,
addNew,
}: { }: {
socket: Socket socket: Socket
type: "file" | "folder" type: "file" | "folder"
stopEditing: () => void stopEditing: () => void
addNew: (name: string, type: "file" | "folder") => void
}) { }) {
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
@ -25,19 +23,9 @@ export default function New({
const valid = validateName(name, "", type) const valid = validateName(name, "", type)
if (valid.status) { if (valid.status) {
if (type === "file") { if (type === "file") {
socket.emit( socket.emit("createFile", { name })
"createFile",
{ name },
({ success }: { success: boolean }) => {
if (success) {
addNew(name, type)
}
}
)
} else { } else {
socket.emit("createFolder", { name }, () => { socket.emit("createFolder", { name })
addNew(name, type)
})
} }
} }
} }

View File

@ -694,4 +694,4 @@
} }
], ],
"encodedTokensColors": [] "encodedTokensColors": []
} }

View File

@ -45,9 +45,14 @@ export default function Landing() {
<h1 className="text-2xl font-medium text-center mt-16"> <h1 className="text-2xl font-medium text-center mt-16">
A Collaborative + AI-Powered Code Environment A Collaborative + AI-Powered Code Environment
</h1> </h1>
<p className="text-muted-foreground mt-4 text-center "> {/* <p className="text-muted-foreground mt-4 text-center ">
Sandbox is an open-source cloud-based code editing environment with Sandbox is an open-source cloud-based code editing environment with
custom AI code autocompletion and real-time collaboration. custom AI code autocompletion and real-time collaboration.
</p> */}
<p className="text-muted-foreground mt-4 text-center ">
A cloud-based code editor featuring real-time collaboration,
intelligent code autocompletion, and an AI assistant to help you code
faster and smarter.
</p> </p>
<div className="mt-8 flex space-x-4"> <div className="mt-8 flex space-x-4">
<Link href="/sign-up"> <Link href="/sign-up">

View File

@ -1,5 +1,5 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority" import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
@ -56,4 +56,4 @@ const AlertDescription = React.forwardRef<
)) ))
AlertDescription.displayName = "AlertDescription" AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription } export { Alert, AlertDescription, AlertTitle }

View File

@ -6,4 +6,3 @@ import { type ThemeProviderProps } from "next-themes/dist/types"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) { export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider> return <NextThemesProvider {...props}>{children}</NextThemesProvider>
} }

View File

@ -1,7 +1,7 @@
"use client" "use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip" import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import * as React from "react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
@ -29,4 +29,4 @@ const TooltipContent = React.forwardRef<
)) ))
TooltipContent.displayName = TooltipPrimitive.Content.displayName TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger }

View File

@ -11,27 +11,85 @@ import { MAX_FREE_GENERATION } from "@/lib/constant"
import { User } from "@/lib/types" import { User } from "@/lib/types"
import { useClerk } from "@clerk/nextjs" import { useClerk } from "@clerk/nextjs"
import { import {
Crown,
LayoutDashboard, LayoutDashboard,
LogOut, LogOut,
Sparkles, Sparkles,
User as UserIcon, User as UserIcon,
} from "lucide-react" } from "lucide-react"
import Link from "next/link" import Link from "next/link"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import Avatar from "./avatar" import Avatar from "./avatar"
import { Button } from "./button"
import { TIERS } from "@/lib/tiers"
export default function UserButton({ userData }: { userData: User }) { // TODO: Remove this once we have a proper tier system
if (!userData) return null const TIER_INFO = {
FREE: {
color: "text-gray-500",
icon: Sparkles,
limit: TIERS.FREE.generations,
},
PRO: {
color: "text-blue-500",
icon: Crown,
limit: TIERS.PRO.generations,
},
ENTERPRISE: {
color: "text-purple-500",
icon: Crown,
limit: TIERS.ENTERPRISE.generations,
},
} as const
export default function UserButton({ userData: initialUserData }: { userData: User }) {
const [userData, setUserData] = useState<User>(initialUserData)
const [isOpen, setIsOpen] = useState(false)
const { signOut } = useClerk() const { signOut } = useClerk()
const router = useRouter() const router = useRouter()
const fetchUserData = async () => {
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_DATABASE_WORKER_URL}/api/user?id=${userData.id}`,
{
headers: {
Authorization: `${process.env.NEXT_PUBLIC_WORKERS_KEY}`,
},
cache: 'no-store'
}
)
if (res.ok) {
const updatedUserData = await res.json()
setUserData(updatedUserData)
}
} catch (error) {
console.error("Failed to fetch user data:", error)
}
}
useEffect(() => {
if (isOpen) {
fetchUserData()
}
}, [isOpen])
const tierInfo = TIER_INFO[userData.tier as keyof typeof TIER_INFO] || TIER_INFO.FREE
const TierIcon = tierInfo.icon
const usagePercentage = Math.floor((userData.generations || 0) * 100 / tierInfo.limit)
const handleUpgrade = async () => {
router.push('/upgrade')
}
return ( return (
<DropdownMenu> <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenuTrigger> <DropdownMenuTrigger>
<Avatar name={userData.name} avatarUrl={userData.avatarUrl} /> <Avatar name={userData.name} avatarUrl={userData.avatarUrl} />
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent className="w-48" align="end"> <DropdownMenuContent className="w-64" align="end">
<div className="py-1.5 px-2 w-full"> <div className="py-1.5 px-2 w-full">
<div className="font-medium">{userData.name}</div> <div className="font-medium">{userData.name}</div>
<div className="text-sm w-full overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground"> <div className="text-sm w-full overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground">
@ -40,20 +98,8 @@ export default function UserButton({ userData }: { userData: User }) {
</div> </div>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem>
<Sparkles className="size-4 mr-2 text-indigo-500" />
<div className="w-full flex flex-col items-start text-sm">
<span className="text-sm">{`AI Usage: ${userData.generations}/${MAX_FREE_GENERATION}`}</span>
<div className="rounded-full w-full mt-1 h-1.5 overflow-hidden bg-secondary border border-muted-foreground">
<div
className="h-full bg-indigo-500 rounded-full"
style={{
width: `${(userData.generations * 100) / 1000}%`,
}}
/>
</div>
</div>
</DropdownMenuItem>
<DropdownMenuItem className="cursor-pointer" asChild> <DropdownMenuItem className="cursor-pointer" asChild>
<Link href={"/dashboard"}> <Link href={"/dashboard"}>
<LayoutDashboard className="mr-2 size-4" /> <LayoutDashboard className="mr-2 size-4" />
@ -68,6 +114,52 @@ export default function UserButton({ userData }: { userData: User }) {
<DropdownMenuSeparator /> <DropdownMenuSeparator />
</Link> </Link>
</DropdownMenuItem> </DropdownMenuItem>
<div className="py-1.5 px-2 w-full">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5">
<TierIcon className={`h-4 w-4 ${tierInfo.color}`} />
<span className="text-sm font-medium">{userData.tier || "FREE"} Plan</span>
</div>
{/* {(userData.tier === "FREE" || userData.tier === "PRO") && (
<Button
variant="ghost"
size="sm"
className="h-7 text-xs border-b hover:border-b-foreground"
onClick={handleUpgrade}
>
Upgrade
</Button>
)} */}
</div>
</div>
<DropdownMenuSeparator />
<DropdownMenuItem>
<Sparkles className="size-4 mr-2 text-indigo-500" />
<div className="w-full">
<div className="flex items-center justify-between text-sm text-muted-foreground mb-2">
<span>AI Usage</span>
<span>{userData.generations}/{tierInfo.limit}</span>
</div>
<div className="rounded-full w-full h-2 overflow-hidden bg-secondary">
<div
className={`h-full rounded-full transition-all duration-300 ${
usagePercentage > 90 ? 'bg-red-500' :
usagePercentage > 75 ? 'bg-yellow-500' :
tierInfo.color.replace('text-', 'bg-')
}`}
style={{
width: `${Math.min(usagePercentage, 100)}%`,
}}
/>
</div>
</div>
</DropdownMenuItem>
<DropdownMenuSeparator />
{/* <DropdownMenuItem className="cursor-pointer"> {/* <DropdownMenuItem className="cursor-pointer">
<Pencil className="mr-2 size-4" /> <Pencil className="mr-2 size-4" />
<span>Edit Profile</span> <span>Edit Profile</span>
@ -83,3 +175,4 @@ export default function UserButton({ userData }: { userData: User }) {
</DropdownMenu> </DropdownMenu>
) )
} }

View File

@ -63,7 +63,7 @@ export const TerminalProvider: React.FC<{ children: React.ReactNode }> = ({
terminals, terminals,
setTerminals, setTerminals,
setActiveTerminalId, setActiveTerminalId,
setClosingTerminal: () => { }, setClosingTerminal: () => {},
socket, socket,
activeTerminalId, activeTerminalId,
}) })

View File

@ -16,7 +16,7 @@ export const projectTemplates: {
id: "vanillajs", id: "vanillajs",
name: "HTML/JS", name: "HTML/JS",
icon: "/project-icons/more.svg", icon: "/project-icons/more.svg",
description: "More coming soon, feel free to contribute on GitHub", description: "A simple HTML/JS project for building web apps",
disabled: false, disabled: false,
}, },
{ {
@ -33,4 +33,11 @@ export const projectTemplates: {
description: "A faster way to build and share data apps", description: "A faster way to build and share data apps",
disabled: false, disabled: false,
}, },
{
id: "php",
name: "PHP",
description: "PHP development environment",
icon: "/project-icons/php.svg",
disabled: false
},
] ]

View File

@ -38,7 +38,7 @@
"csl": "xml", "csl": "xml",
"cson": "coffeescript", "cson": "coffeescript",
"csproj": "xml", "csproj": "xml",
"css":"css", "css": "css",
"ct": "xml", "ct": "xml",
"ctp": "php", "ctp": "php",
"cxx": "cpp", "cxx": "cpp",

View File

@ -0,0 +1,248 @@
export interface TemplateConfig {
id: string
name: string,
runCommand: string,
fileStructure: {
[key: string]: {
purpose: string
description: string
}
}
conventions: string[]
dependencies?: {
[key: string]: string
}
scripts?: {
[key: string]: string
}
}
export const templateConfigs: { [key: string]: TemplateConfig } = {
reactjs: {
id: "reactjs",
name: "React",
runCommand: "npm run dev",
fileStructure: {
"src/": {
purpose: "source",
description: "Contains all React components and application logic"
},
"src/components/": {
purpose: "components",
description: "Reusable React components"
},
"src/lib/": {
purpose: "utilities",
description: "Utility functions and shared code"
},
"src/App.tsx": {
purpose: "entry",
description: "Main application component"
},
"src/index.tsx": {
purpose: "entry",
description: "Application entry point"
},
"src/index.css": {
purpose: "styles",
description: "Global CSS styles"
},
"public/": {
purpose: "static",
description: "Static assets and index.html"
},
"tsconfig.json": {
purpose: "config",
description: "TypeScript configuration"
},
"vite.config.ts": {
purpose: "config",
description: "Vite bundler configuration"
},
"package.json": {
purpose: "config",
description: "Project dependencies and scripts"
}
},
conventions: [
"Use functional components with hooks",
"Follow React naming conventions (PascalCase for components)",
"Keep components small and focused",
"Use TypeScript for type safety"
],
dependencies: {
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-slot": "^1.1.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"lucide-react": "^0.441.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7"
},
scripts: {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
}
},
// Next.js template config
nextjs: {
id: "nextjs",
name: "NextJS",
runCommand: "npm run dev",
fileStructure: {
"pages/": {
purpose: "routing",
description: "Page components and API routes"
},
"pages/api/": {
purpose: "api",
description: "API route handlers"
},
"pages/_app.tsx": {
purpose: "entry",
description: "Application wrapper component"
},
"pages/index.tsx": {
purpose: "page",
description: "Homepage component"
},
"public/": {
purpose: "static",
description: "Static assets and files"
},
"styles/": {
purpose: "styles",
description: "CSS modules and global styles"
},
"styles/globals.css": {
purpose: "styles",
description: "Global CSS styles"
},
"styles/Home.module.css": {
purpose: "styles",
description: "Homepage-specific styles"
},
"next.config.js": {
purpose: "config",
description: "Next.js configuration"
},
"next-env.d.ts": {
purpose: "types",
description: "Next.js TypeScript declarations"
},
"tsconfig.json": {
purpose: "config",
description: "TypeScript configuration"
},
"package.json": {
purpose: "config",
description: "Project dependencies and scripts"
}
},
conventions: [
"Use file-system based routing",
"Keep API routes in pages/api",
"Use CSS Modules for component styles",
"Follow Next.js data fetching patterns"
],
dependencies: {
"next": "^14.1.0",
"react": "^18.2.0",
"react-dom": "18.2.0",
"tailwindcss": "^3.4.1"
},
scripts: {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
}
},
// Streamlit template config
streamlit: {
id: "streamlit",
name: "Streamlit",
runCommand: "./venv/bin/streamlit run main.py --server.runOnSave true",
fileStructure: {
"main.py": {
purpose: "entry",
description: "Main Streamlit application file"
},
"requirements.txt": {
purpose: "dependencies",
description: "Python package dependencies"
},
"Procfile": {
purpose: "deployment",
description: "Deployment configuration for hosting platforms"
},
"venv/": {
purpose: "environment",
description: "Python virtual environment directory"
}
},
conventions: [
"Use Streamlit components for UI",
"Follow PEP 8 style guide",
"Keep dependencies in requirements.txt",
"Use virtual environment for isolation"
],
dependencies: {
"streamlit": "^1.40.0",
"altair": "^5.5.0"
},
scripts: {
"start": "streamlit run main.py",
"dev": "./venv/bin/streamlit run main.py --server.runOnSave true"
}
},
// HTML template config
vanillajs: {
id: "vanillajs",
name: "HTML/JS",
runCommand: "npm run dev",
fileStructure: {
"index.html": {
purpose: "entry",
description: "Main HTML entry point"
},
"style.css": {
purpose: "styles",
description: "Global CSS styles"
},
"script.js": {
purpose: "scripts",
description: "JavaScript application logic"
},
"package.json": {
purpose: "config",
description: "Project dependencies and scripts"
},
"package-lock.json": {
purpose: "config",
description: "Locked dependency versions"
},
"vite.config.js": {
purpose: "config",
description: "Vite bundler configuration"
}
},
conventions: [
"Use semantic HTML elements",
"Keep CSS modular and organized",
"Write clean, modular JavaScript",
"Follow modern ES6+ practices"
],
dependencies: {
"vite": "^5.0.12"
},
scripts: {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
}

View File

@ -83,8 +83,8 @@ export const closeTerminal = ({
? numTerminals === 1 ? numTerminals === 1
? null ? null
: index < numTerminals - 1 : index < numTerminals - 1
? terminals[index + 1].id ? terminals[index + 1].id
: terminals[index - 1].id : terminals[index - 1].id
: activeTerminalId : activeTerminalId
setTerminals((prev) => prev.filter((t) => t.id !== term.id)) setTerminals((prev) => prev.filter((t) => t.id !== term.id))

19
frontend/lib/tiers.ts Normal file
View File

@ -0,0 +1,19 @@
export const TIERS = {
FREE: {
// generations: 100,
// maxTokens: 1024,
generations: 1000,
maxTokens: 4096,
model: "claude-3-5-sonnet-20240620",
},
PRO: {
generations: 500,
maxTokens: 2048,
model: "claude-3-5-sonnet-20240620",
},
ENTERPRISE: {
generations: 1000,
maxTokens: 4096,
model: "claude-3-5-sonnet-20240620",
},
}

View File

@ -74,10 +74,10 @@ function mapModule(module: string): monaco.languages.typescript.ModuleKind {
} }
function mapJSX(jsx: string | undefined): monaco.languages.typescript.JsxEmit { function mapJSX(jsx: string | undefined): monaco.languages.typescript.JsxEmit {
if (!jsx || typeof jsx !== 'string') { if (!jsx || typeof jsx !== "string") {
return monaco.languages.typescript.JsxEmit.React // Default value return monaco.languages.typescript.JsxEmit.React // Default value
} }
const jsxMap: { [key: string]: monaco.languages.typescript.JsxEmit } = { const jsxMap: { [key: string]: monaco.languages.typescript.JsxEmit } = {
preserve: monaco.languages.typescript.JsxEmit.Preserve, preserve: monaco.languages.typescript.JsxEmit.Preserve,
react: monaco.languages.typescript.JsxEmit.React, react: monaco.languages.typescript.JsxEmit.React,

View File

@ -10,6 +10,9 @@ export type User = {
generations: number generations: number
sandbox: Sandbox[] sandbox: Sandbox[]
usersToSandboxes: UsersToSandboxes[] usersToSandboxes: UsersToSandboxes[]
tier: "FREE" | "PRO" | "ENTERPRISE"
tierExpiresAt: Date
lastResetDate?: number
} }
export type Sandbox = { export type Sandbox = {

View File

@ -1,82 +1,181 @@
// Constants for username generation // Constants for username generation
const WORDS = { const WORDS = {
adjectives: [ adjectives: [
"azure", "crimson", "golden", "silver", "violet", "emerald", "cobalt", "amber", "coral", "jade", "azure",
"cyber", "digital", "quantum", "neural", "binary", "cosmic", "stellar", "atomic", "crypto", "nano", "crimson",
"swift", "brave", "clever", "wise", "noble", "rapid", "bright", "sharp", "keen", "bold", "golden",
"dynamic", "epic", "mega", "ultra", "hyper", "super", "prime", "elite", "alpha", "omega", "silver",
"pixel", "vector", "sonic", "laser", "matrix", "nexus", "proxy", "cloud", "data", "tech", "violet",
], "emerald",
nouns: [ "cobalt",
"coder", "hacker", "dev", "ninja", "guru", "wizard", "admin", "mod", "chief", "boss", "amber",
"wolf", "eagle", "phoenix", "dragon", "tiger", "falcon", "shark", "lion", "hawk", "bear", "coral",
"byte", "bit", "node", "stack", "cache", "chip", "core", "net", "web", "app", "jade",
"star", "nova", "pulsar", "comet", "nebula", "quasar", "cosmos", "orbit", "astro", "solar", "cyber",
"mind", "soul", "spark", "pulse", "force", "power", "wave", "storm", "flash", "surge", "digital",
], "quantum",
prefixes: [ "neural",
"the", "mr", "ms", "dr", "pro", "master", "lord", "captain", "chief", "agent", "binary",
], "cosmic",
} as const; "stellar",
"atomic",
// Helper function to get random element from array "crypto",
const getRandomElement = <T>(array: readonly T[]): T => { "nano",
return array[Math.floor(Math.random() * array.length)]; "swift",
}; "brave",
"clever",
// Username pattern generators "wise",
const usernamePatterns = { "noble",
basic: (): string => { "rapid",
const adjective = getRandomElement(WORDS.adjectives); "bright",
const noun = getRandomElement(WORDS.nouns); "sharp",
const number = Math.floor(Math.random() * 10000); "keen",
return `${adjective}${noun}${number}`; "bold",
}, "dynamic",
"epic",
prefixed: (): string => { "mega",
const prefix = getRandomElement(WORDS.prefixes); "ultra",
const noun = getRandomElement(WORDS.nouns); "hyper",
const number = Math.floor(Math.random() * 100); "super",
return `${prefix}${noun}${number}`; "prime",
}, "elite",
"alpha",
doubleAdjective: (): string => { "omega",
const adj1 = getRandomElement(WORDS.adjectives); "pixel",
const adj2 = getRandomElement(WORDS.adjectives); "vector",
const noun = getRandomElement(WORDS.nouns); "sonic",
return `${adj1}${adj2}${noun}`; "laser",
}, "matrix",
"nexus",
doubleNoun: (): string => { "proxy",
const noun1 = getRandomElement(WORDS.nouns); "cloud",
const noun2 = getRandomElement(WORDS.nouns); "data",
const number = Math.floor(Math.random() * 100); "tech",
return `${noun1}${number}${noun2}`; ],
}, nouns: [
}; "coder",
"hacker",
export function generateUsername(): string { "dev",
const patterns = Object.values(usernamePatterns); "ninja",
const selectedPattern = getRandomElement(patterns); "guru",
return selectedPattern(); "wizard",
"admin",
"mod",
"chief",
"boss",
"wolf",
"eagle",
"phoenix",
"dragon",
"tiger",
"falcon",
"shark",
"lion",
"hawk",
"bear",
"byte",
"bit",
"node",
"stack",
"cache",
"chip",
"core",
"net",
"web",
"app",
"star",
"nova",
"pulsar",
"comet",
"nebula",
"quasar",
"cosmos",
"orbit",
"astro",
"solar",
"mind",
"soul",
"spark",
"pulse",
"force",
"power",
"wave",
"storm",
"flash",
"surge",
],
prefixes: [
"the",
"mr",
"ms",
"dr",
"pro",
"master",
"lord",
"captain",
"chief",
"agent",
],
} as const
// Helper function to get random element from array
const getRandomElement = <T>(array: readonly T[]): T => {
return array[Math.floor(Math.random() * array.length)]
}
// Username pattern generators
const usernamePatterns = {
basic: (): string => {
const adjective = getRandomElement(WORDS.adjectives)
const noun = getRandomElement(WORDS.nouns)
const number = Math.floor(Math.random() * 10000)
return `${adjective}${noun}${number}`
},
prefixed: (): string => {
const prefix = getRandomElement(WORDS.prefixes)
const noun = getRandomElement(WORDS.nouns)
const number = Math.floor(Math.random() * 100)
return `${prefix}${noun}${number}`
},
doubleAdjective: (): string => {
const adj1 = getRandomElement(WORDS.adjectives)
const adj2 = getRandomElement(WORDS.adjectives)
const noun = getRandomElement(WORDS.nouns)
return `${adj1}${adj2}${noun}`
},
doubleNoun: (): string => {
const noun1 = getRandomElement(WORDS.nouns)
const noun2 = getRandomElement(WORDS.nouns)
const number = Math.floor(Math.random() * 100)
return `${noun1}${number}${noun2}`
},
}
export function generateUsername(): string {
const patterns = Object.values(usernamePatterns)
const selectedPattern = getRandomElement(patterns)
return selectedPattern()
}
export async function generateUniqueUsername(
checkExists: (username: string) => Promise<boolean>
): Promise<string> {
const MAX_ATTEMPTS = 10
let attempts = 0
let username = generateUsername()
while ((await checkExists(username)) && attempts < MAX_ATTEMPTS) {
username = generateUsername()
attempts++
} }
export async function generateUniqueUsername( if (attempts >= MAX_ATTEMPTS) {
checkExists: (username: string) => Promise<boolean> // Add a large random number to ensure uniqueness
): Promise<string> { username = generateUsername() + Math.floor(Math.random() * 1000000)
const MAX_ATTEMPTS = 10; }
let attempts = 0;
let username = generateUsername(); return username
}
while (await checkExists(username) && attempts < MAX_ATTEMPTS) {
username = generateUsername();
attempts++;
}
if (attempts >= MAX_ATTEMPTS) {
// Add a large random number to ensure uniqueness
username = generateUsername() + Math.floor(Math.random() * 1000000);
}
return username;
}

View File

@ -2,7 +2,7 @@ import { type ClassValue, clsx } from "clsx"
// import { toast } from "sonner" // import { toast } from "sonner"
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge"
import fileExtToLang from "./file-extension-to-language.json" import fileExtToLang from "./file-extension-to-language.json"
import { Sandbox, TFile, TFolder } from "./types" import { TFile, TFolder } from "./types"
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs))
@ -38,31 +38,6 @@ export function validateName(
return { status: true, message: "" } return { status: true, message: "" }
} }
export function addNew(
name: string,
type: "file" | "folder",
setFiles: React.Dispatch<React.SetStateAction<(TFolder | TFile)[]>>,
sandboxData: Sandbox
) {
if (type === "file") {
setFiles((prev) => [
...prev,
{ id: `projects/${sandboxData.id}/${name}`, name, type: "file" },
])
} else {
console.log("adding folder")
setFiles((prev) => [
...prev,
{
id: `projects/${sandboxData.id}/${name}`,
name,
type: "folder",
children: [],
},
])
}
}
export function debounce<T extends (...args: any[]) => void>( export function debounce<T extends (...args: any[]) => void>(
func: T, func: T,
wait: number wait: number

View File

@ -1,5 +1,5 @@
import { createClient } from "@liveblocks/client" import { createClient } from "@liveblocks/client"
import { createRoomContext, createLiveblocksContext } from "@liveblocks/react" import { createLiveblocksContext, createRoomContext } from "@liveblocks/react"
import YLiveblocksProvider from "@liveblocks/yjs" import YLiveblocksProvider from "@liveblocks/yjs"
import { colors } from "./lib/colors" import { colors } from "./lib/colors"

View File

@ -8,6 +8,7 @@
"name": "sandbox", "name": "sandbox",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.32.1",
"@atlaskit/pragmatic-drag-and-drop": "^1.1.7", "@atlaskit/pragmatic-drag-and-drop": "^1.1.7",
"@clerk/nextjs": "^4.29.12", "@clerk/nextjs": "^4.29.12",
"@clerk/themes": "^1.7.12", "@clerk/themes": "^1.7.12",
@ -127,6 +128,54 @@
"nun": "bin/nun.mjs" "nun": "bin/nun.mjs"
} }
}, },
"node_modules/@anthropic-ai/sdk": {
"version": "0.32.1",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.32.1.tgz",
"integrity": "sha512-U9JwTrDvdQ9iWuABVsMLj8nJVwAyQz6QXvgLsVhryhCEPkLsbcP/MXxm+jYcAwLoV8ESbaTTjnD4kuAFa+Hyjg==",
"license": "MIT",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7"
}
},
"node_modules/@anthropic-ai/sdk/node_modules/@types/node": {
"version": "18.19.65",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.65.tgz",
"integrity": "sha512-Ay5BZuO1UkTmVHzZJNvZKw/E+iB3GQABb6kijEz89w2JrfhNA+M/ebp18pfz9Gqe9ywhMC8AA8yC01lZq48J+Q==",
"license": "MIT",
"dependencies": {
"undici-types": "~5.26.4"
}
},
"node_modules/@anthropic-ai/sdk/node_modules/@types/node-fetch": {
"version": "2.6.12",
"resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.12.tgz",
"integrity": "sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA==",
"license": "MIT",
"dependencies": {
"@types/node": "*",
"form-data": "^4.0.0"
}
},
"node_modules/@anthropic-ai/sdk/node_modules/form-data": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz",
"integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/@atlaskit/pragmatic-drag-and-drop": { "node_modules/@atlaskit/pragmatic-drag-and-drop": {
"version": "1.1.7", "version": "1.1.7",
"resolved": "https://registry.npmjs.org/@atlaskit/pragmatic-drag-and-drop/-/pragmatic-drag-and-drop-1.1.7.tgz", "resolved": "https://registry.npmjs.org/@atlaskit/pragmatic-drag-and-drop/-/pragmatic-drag-and-drop-1.1.7.tgz",
@ -4165,6 +4214,18 @@
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz", "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",
"integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==" "integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A=="
}, },
"node_modules/abort-controller": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
"license": "MIT",
"dependencies": {
"event-target-shim": "^5.0.0"
},
"engines": {
"node": ">=6.5"
}
},
"node_modules/agent-base": { "node_modules/agent-base": {
"version": "7.1.1", "version": "7.1.1",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
@ -4177,6 +4238,18 @@
"node": ">= 14" "node": ">= 14"
} }
}, },
"node_modules/agentkeepalive": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz",
"integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==",
"license": "MIT",
"dependencies": {
"humanize-ms": "^1.2.1"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/ansi-regex": { "node_modules/ansi-regex": {
"version": "6.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz",
@ -5093,6 +5166,15 @@
"url": "https://opencollective.com/unified" "url": "https://opencollective.com/unified"
} }
}, },
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/execa": { "node_modules/execa": {
"version": "7.2.0", "version": "7.2.0",
"resolved": "https://registry.npmjs.org/execa/-/execa-7.2.0.tgz", "resolved": "https://registry.npmjs.org/execa/-/execa-7.2.0.tgz",
@ -5253,6 +5335,12 @@
"node": ">= 6" "node": ">= 6"
} }
}, },
"node_modules/form-data-encoder": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",
"integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==",
"license": "MIT"
},
"node_modules/format": { "node_modules/format": {
"version": "0.2.2", "version": "0.2.2",
"resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz", "resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz",
@ -5261,6 +5349,28 @@
"node": ">=0.4.x" "node": ">=0.4.x"
} }
}, },
"node_modules/formdata-node": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",
"integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",
"license": "MIT",
"dependencies": {
"node-domexception": "1.0.0",
"web-streams-polyfill": "4.0.0-beta.3"
},
"engines": {
"node": ">= 12.20"
}
},
"node_modules/formdata-node/node_modules/web-streams-polyfill": {
"version": "4.0.0-beta.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",
"integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"node_modules/formdata-polyfill": { "node_modules/formdata-polyfill": {
"version": "4.0.10", "version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
@ -5617,6 +5727,15 @@
"node": ">=14.18.0" "node": ">=14.18.0"
} }
}, },
"node_modules/humanize-ms": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
"integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.0.0"
}
},
"node_modules/ieee754": { "node_modules/ieee754": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",

View File

@ -9,6 +9,7 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.32.1",
"@atlaskit/pragmatic-drag-and-drop": "^1.1.7", "@atlaskit/pragmatic-drag-and-drop": "^1.1.7",
"@clerk/nextjs": "^4.29.12", "@clerk/nextjs": "^4.29.12",
"@clerk/themes": "^1.7.12", "@clerk/themes": "^1.7.12",

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="16" cy="16" r="14" fill="#8892BF"/>
<path d="M14.4392 10H16.1192L15.6444 12.5242H17.154C17.9819 12.5419 18.5986 12.7269 19.0045 13.0793C19.4184 13.4316 19.5402 14.1014 19.3698 15.0881L18.5541 19.4889H16.8497L17.6288 15.2863C17.7099 14.8457 17.6856 14.533 17.5558 14.348C17.426 14.163 17.146 14.0705 16.7158 14.0705L15.3644 14.0573L14.3661 19.4889H12.6861L14.4392 10Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M6.74092 12.5243H10.0036C10.9612 12.533 11.6552 12.8327 12.0854 13.4229C12.5156 14.0132 12.6576 14.8193 12.5115 15.8414C12.4548 16.3085 12.3289 16.7665 12.1341 17.2159C11.9474 17.6652 11.6878 18.0704 11.355 18.4317C10.9491 18.8898 10.5149 19.1805 10.0523 19.304C9.58969 19.4274 9.11076 19.489 8.61575 19.489H7.15484L6.69222 22H5L6.74092 12.5243ZM7.43485 17.9956L8.16287 14.0441H8.40879C8.49815 14.0441 8.5914 14.0396 8.6888 14.0309C9.33817 14.0221 9.87774 14.0882 10.308 14.2291C10.7462 14.37 10.8923 14.9031 10.7462 15.8282C10.5678 16.9296 10.2186 17.5727 9.69926 17.7577C9.1799 17.934 8.53053 18.0176 7.75138 18.0088H7.58094C7.53224 18.0088 7.48355 18.0043 7.43485 17.9956Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M24.4365 12.5243H21.1738L19.4329 22H21.1251L21.5878 19.489H23.0487C23.5437 19.489 24.0226 19.4274 24.4852 19.304C24.9479 19.1805 25.382 18.8898 25.7879 18.4317C26.1207 18.0704 26.3803 17.6652 26.567 17.2159C26.7618 16.7665 26.8877 16.3085 26.9444 15.8414C27.0905 14.8193 26.9486 14.0132 26.5183 13.4229C26.0881 12.8327 25.3942 12.533 24.4365 12.5243ZM22.5958 14.0441L21.8678 17.9956C21.9165 18.0043 21.9652 18.0088 22.0139 18.0088H22.1843C22.9635 18.0176 23.6128 17.934 24.1322 17.7577C24.6515 17.5727 25.0007 16.9296 25.1792 15.8282C25.3253 14.9031 25.1792 14.37 24.7409 14.2291C24.3107 14.0882 23.7711 14.0221 23.1217 14.0309C23.0243 14.0396 22.9311 14.0441 22.8417 14.0441H22.5958Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@ -1,3 +1,2 @@
declare module 'react-syntax-highlighter'; declare module "react-syntax-highlighter"
declare module 'react-syntax-highlighter/dist/esm/styles/prism'; declare module "react-syntax-highlighter/dist/esm/styles/prism"