Compare commits

..

16 Commits

Author SHA1 Message Date
44f803ffaf feat: add run button 2024-07-15 15:33:26 -04:00
d9ce147e09 fix: editor on windows 2024-07-08 16:48:06 -04:00
398139ec36 fix: store rooms in map 2024-07-06 18:18:13 -04:00
bd6284df8f docs: add information about E2B 2024-06-19 21:57:40 -04:00
c262fb2a31 fix: add error handling to the backend 2024-06-19 21:57:40 -04:00
ed709210e3 fix: remove hardcoded reference to localhost 2024-06-19 21:57:40 -04:00
97c8598717 fix: count only the current user's sandboxes towards the limit 2024-06-19 21:57:40 -04:00
9ec59bc781 fix: use the container URL for the preview panel 2024-06-19 21:57:40 -04:00
687416e6e9 fix: set project file permissions so that they belong to the terminal user 2024-06-19 21:57:40 -04:00
006c5cea66 fix: sync files to container instead of local file system 2024-06-19 21:57:40 -04:00
869ae6c148 fix: ensure container remains open until all owner connections are closed 2024-06-19 21:57:40 -04:00
7353e88567 fix: wait until terminals are killed to close the container 2024-06-19 21:57:40 -04:00
a0fb905a04 fix: move socket connection to useRef 2024-06-19 21:56:18 -04:00
0df074924f added debounced function in the editor 2024-06-14 12:10:01 -04:00
e5b320d1c5 feat: replace node-pty with E2B sandboxes 2024-06-14 12:02:20 -04:00
b561f1e962 chore: rename utils.ts to fileoperations.ts 2024-06-14 11:57:32 -04:00
18 changed files with 1068 additions and 805 deletions

View File

@ -29,7 +29,9 @@ npm run dev
### Backend ### Backend
The backend consists of a primary Express and Socket.io server, and 3 Cloudflare Workers microservices for the D1 database, R2 storage, and Workers AI. The D1 database also contains a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to the R2 storage worker. The backend consists of a primary Express and Socket.io server, and 3 Cloudflare Workers microservices for the D1 database, R2 storage, and Workers AI. The D1 database also contains a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to the R2 storage worker. Each open sandbox instantiates a secure Linux sandboxes on E2B, which is used for the terminal and live preview.
You will need to make an account on [E2B](https://e2b.dev/) to get an API key.
#### Socket.io server #### Socket.io server
@ -181,3 +183,4 @@ It should be in the form `category(scope or module): message` in your commit mes
- [Express](https://expressjs.com/) - [Express](https://expressjs.com/)
- [Socket.io](https://socket.io/) - [Socket.io](https://socket.io/)
- [Drizzle ORM](https://orm.drizzle.team/) - [Drizzle ORM](https://orm.drizzle.team/)
- [E2B](https://e2b.dev/)

View File

@ -1,19 +0,0 @@
# e2b template build --name "terminal"
# Use a Debian-based base image
FROM ubuntu:22.04
# Install dependencies and customize sandbox
RUN apt update \
&& apt install -y sudo
# Install xterm
RUN apt update \
&& apt install -y xterm
RUN apt update \
&& apt install -y tmux screen
# Clean up
RUN apt clean \
&& rm -rf /var/lib/apt/lists/*

View File

@ -1,14 +0,0 @@
# This is a config for E2B sandbox template.
# You can use 'template_id' (ne8xtb57tq5xw9vwhdyc) or 'template_name (terminal) from this config to spawn a sandbox:
# Python SDK
# from e2b import Sandbox
# sandbox = Sandbox(template='terminal')
# JS SDK
# import { Sandbox } from 'e2b'
# const sandbox = await Sandbox.create({ template: 'terminal' })
dockerfile = "e2b.Dockerfile"
template_name = "terminal"
template_id = "ne8xtb57tq5xw9vwhdyc"

View File

@ -110,8 +110,13 @@ export default {
const body = await request.json() const body = await request.json()
const { type, name, userId, visibility } = initSchema.parse(body) const { type, name, userId, visibility } = initSchema.parse(body)
const allSandboxes = await db.select().from(sandbox).all() const userSandboxes = await db
if (allSandboxes.length >= 8) { .select()
.from(sandbox)
.where(eq(sandbox.userId, userId))
.all()
if (userSandboxes.length >= 8) {
return new Response("You reached the maximum # of sandboxes.", { return new Response("You reached the maximum # of sandboxes.", {
status: 400, status: 400,
}) })

View File

@ -5,3 +5,4 @@ PORT=4000
WORKERS_KEY= WORKERS_KEY=
DATABASE_WORKER_URL= DATABASE_WORKER_URL=
STORAGE_WORKER_URL= STORAGE_WORKER_URL=
E2B_API_KEY=

View File

@ -9,12 +9,11 @@
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@e2b/code-interpreter": "^0.0.7",
"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.1",
"express": "^4.19.2", "express": "^4.19.2",
"node-pty": "^1.0.0",
"rate-limiter-flexible": "^5.0.3", "rate-limiter-flexible": "^5.0.3",
"socket.io": "^4.7.5", "socket.io": "^4.7.5",
"zod": "^3.22.4" "zod": "^3.22.4"
@ -51,39 +50,6 @@
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/@e2b/code-interpreter": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/@e2b/code-interpreter/-/code-interpreter-0.0.7.tgz",
"integrity": "sha512-e8nAY4zXU2b9nKthqq/pCPlTVD7f01dtzCtvabWmhlx7Wq+AUln14Q1Wf+uRVJXHkwS9BDv2CupdZpUChsjoCA==",
"dependencies": {
"e2b": "^0.16.1",
"isomorphic-ws": "^5.0.0",
"ws": "^8.15.1"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@e2b/code-interpreter/node_modules/ws": {
"version": "8.17.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.0.tgz",
"integrity": "sha512-uJq6108EgZMAl20KagGkzCKfMEjxmKvZHG7Tlq0Z6nOky7YF7aq4mOx6xK8TJ/i1LeK4Qus7INktacctDgY8Ow==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/@jridgewell/resolve-uri": { "node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
@ -1281,11 +1247,6 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
}, },
"node_modules/nan": {
"version": "2.19.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.19.0.tgz",
"integrity": "sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw=="
},
"node_modules/negotiator": { "node_modules/negotiator": {
"version": "0.6.3", "version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@ -1305,15 +1266,6 @@
"node-gyp-build-test": "build-test.js" "node-gyp-build-test": "build-test.js"
} }
}, },
"node_modules/node-pty": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.0.0.tgz",
"integrity": "sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA==",
"hasInstallScript": true,
"dependencies": {
"nan": "^2.17.0"
}
},
"node_modules/nodemon": { "node_modules/nodemon": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz",

View File

@ -11,12 +11,11 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@e2b/code-interpreter": "^0.0.7",
"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.1",
"express": "^4.19.2", "express": "^4.19.2",
"node-pty": "^1.0.0",
"rate-limiter-flexible": "^5.0.3", "rate-limiter-flexible": "^5.0.3",
"socket.io": "^4.7.5", "socket.io": "^4.7.5",
"zod": "^3.22.4" "zod": "^3.22.4"

View File

@ -0,0 +1,177 @@
import * as dotenv from "dotenv";
import {
R2FileBody,
R2Files,
Sandbox,
TFile,
TFileData,
TFolder,
} from "./types";
dotenv.config();
export const getSandboxFiles = async (id: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?sandboxId=${id}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
const data: R2Files = await res.json();
const paths = data.objects.map((obj) => obj.key);
const processedFiles = await processFiles(paths, id);
return processedFiles;
};
export const getFolder = async (folderId: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?folderId=${folderId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
const data: R2Files = await res.json();
return data.objects.map((obj) => obj.key);
};
const processFiles = async (paths: string[], id: string) => {
const root: TFolder = { id: "/", type: "folder", name: "/", children: [] };
const fileData: TFileData[] = [];
paths.forEach((path) => {
const allParts = path.split("/");
if (allParts[1] !== id) {
return;
}
const parts = allParts.slice(2);
let current: TFolder = root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isFile = i === parts.length - 1 && part.includes(".");
const existing = current.children.find((child) => child.name === part);
if (existing) {
if (!isFile) {
current = existing as TFolder;
}
} else {
if (isFile) {
const file: TFile = { id: path, type: "file", name: part };
current.children.push(file);
fileData.push({ id: path, data: "" });
} else {
const folder: TFolder = {
// id: path, // todo: wrong id. for example, folder "src" ID is: projects/a7vgttfqbgy403ratp7du3ln/src/App.css
id: `projects/${id}/${parts.slice(0, i + 1).join("/")}`,
type: "folder",
name: part,
children: [],
};
current.children.push(folder);
current = folder;
}
}
}
});
await Promise.all(
fileData.map(async (file) => {
const data = await fetchFileContent(file.id);
file.data = data;
})
);
return {
files: root.children,
fileData,
};
};
const fetchFileContent = async (fileId: string): Promise<string> => {
try {
const fileRes = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?fileId=${fileId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
return await fileRes.text();
} catch (error) {
console.error("ERROR fetching file:", error);
return "";
}
};
export const createFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
});
return res.ok;
};
export const renameFile = async (
fileId: string,
newFileId: string,
data: string
) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, newFileId, data }),
});
return res.ok;
};
export const saveFile = async (fileId: string, data: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/save`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, data }),
});
return res.ok;
};
export const deleteFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
});
return res.ok;
};
export const getProjectSize = async (id: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api/size?sandboxId=${id}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
return (await res.json()).size;
};

View File

@ -1,4 +1,3 @@
import fs from "fs";
import os from "os"; import os from "os";
import path from "path"; import path from "path";
import cors from "cors"; import cors from "cors";
@ -17,8 +16,9 @@ import {
getSandboxFiles, getSandboxFiles,
renameFile, renameFile,
saveFile, saveFile,
} from "./utils"; } from "./fileoperations";
import { Sandbox, Process, ProcessMessage } from "e2b"; import { LockManager } from "./utils";
import { Sandbox, Terminal, FilesystemManager } from "e2b";
import { import {
MAX_BODY_SIZE, MAX_BODY_SIZE,
createFileRL, createFileRL,
@ -43,14 +43,21 @@ const io = new Server(httpServer, {
let inactivityTimeout: NodeJS.Timeout | null = null; let inactivityTimeout: NodeJS.Timeout | null = null;
let isOwnerConnected = false; let isOwnerConnected = false;
const terminals: { const containers: Record<string, Sandbox> = {};
[id: string]: Process; const connections: Record<string, number> = {};
} = {}; const terminals: Record<string, Terminal> = {};
const containers: {
[id: string]: Sandbox;
} = {};
const dirName = path.join(__dirname, ".."); const dirName = "/home/user";
const moveFile = async (
filesystem: FilesystemManager,
filePath: string,
newFilePath: string
) => {
const fileContents = await filesystem.readBytes(filePath);
await filesystem.writeBytes(newFilePath, fileContents);
await filesystem.remove(filePath);
};
io.use(async (socket, next) => { io.use(async (socket, next) => {
const handshakeSchema = z.object({ const handshakeSchema = z.object({
@ -103,33 +110,10 @@ io.use(async (socket, next) => {
next(); next();
}); });
class LockManager {
private locks: { [key: string]: Promise<any> };
constructor() {
this.locks = {};
}
async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> {
if (!this.locks[key]) {
this.locks[key] = new Promise<T>(async (resolve, reject) => {
try {
const result = await task();
resolve(result);
} catch (error) {
reject(error);
} finally {
delete this.locks[key];
}
});
}
return await this.locks[key];
}
}
const lockManager = new LockManager(); const lockManager = new LockManager();
io.on("connection", async (socket) => { io.on("connection", async (socket) => {
try {
if (inactivityTimeout) clearTimeout(inactivityTimeout); if (inactivityTimeout) clearTimeout(inactivityTimeout);
const data = socket.data as { const data = socket.data as {
@ -140,6 +124,7 @@ io.on("connection", async (socket) => {
if (data.isOwner) { if (data.isOwner) {
isOwnerConnected = true; isOwnerConnected = true;
connections[data.sandboxId] = (connections[data.sandboxId] ?? 0) + 1;
} else { } else {
if (!isOwnerConnected) { if (!isOwnerConnected) {
socket.emit("disableAccess", "The sandbox owner is not connected."); socket.emit("disableAccess", "The sandbox owner is not connected.");
@ -148,86 +133,124 @@ io.on("connection", async (socket) => {
} }
await lockManager.acquireLock(data.sandboxId, async () => { await lockManager.acquireLock(data.sandboxId, async () => {
try {
if (!containers[data.sandboxId]) { if (!containers[data.sandboxId]) {
console.log("Creating container ", data.sandboxId); containers[data.sandboxId] = await Sandbox.create();
containers[data.sandboxId] = await Sandbox.create({ console.log("Created container ", data.sandboxId);
template: "terminal", io.emit(
}); "previewURL",
console.log("Created."); "https://" + containers[data.sandboxId].getHostname(5173)
);
}
} catch (e: any) {
console.error(`Error creating container ${data.sandboxId}:`, e);
io.emit("error", `Error: container creation. ${e.message ?? e}`);
} }
}); });
// Change the owner of the project directory to user
const fixPermissions = async () => {
await containers[data.sandboxId].process.startAndWait(
`sudo chown -R user "${path.join(dirName, "projects", data.sandboxId)}"`
);
};
const sandboxFiles = await getSandboxFiles(data.sandboxId); const sandboxFiles = await getSandboxFiles(data.sandboxId);
sandboxFiles.fileData.forEach((file) => { sandboxFiles.fileData.forEach(async (file) => {
const filePath = path.join(dirName, file.id); const filePath = path.join(dirName, file.id);
fs.mkdirSync(path.dirname(filePath), { recursive: true }); await containers[data.sandboxId].filesystem.makeDir(
fs.writeFile(filePath, file.data, function (err) { path.dirname(filePath)
if (err) throw err; );
}); await containers[data.sandboxId].filesystem.write(filePath, file.data);
}); });
fixPermissions();
socket.emit("loaded", sandboxFiles.files); socket.emit("loaded", sandboxFiles.files);
socket.on("getFile", (fileId: string, callback) => { socket.on("getFile", (fileId: string, callback) => {
console.log(fileId);
try {
const file = sandboxFiles.fileData.find((f) => f.id === fileId); const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return; if (!file) return;
callback(file.data); callback(file.data);
} catch (e: any) {
console.error("Error getting file:", e);
io.emit("error", `Error: get file. ${e.message ?? e}`);
}
}); });
socket.on("getFolder", async (folderId: string, callback) => { socket.on("getFolder", async (folderId: string, callback) => {
try {
const files = await getFolder(folderId); const files = await getFolder(folderId);
callback(files); callback(files);
} catch (e: any) {
console.error("Error getting folder:", e);
io.emit("error", `Error: get folder. ${e.message ?? e}`);
}
}); });
// todo: send diffs + debounce for efficiency // todo: send diffs + debounce for efficiency
socket.on("saveFile", async (fileId: string, body: string) => { socket.on("saveFile", async (fileId: string, body: string) => {
try { try {
await saveFileRL.consume(data.userId, 1);
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) { if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
socket.emit( socket.emit(
"rateLimit", "error",
"Rate limited: file size too large. Please reduce the file size." "Error: file size too large. Please reduce the file size."
); );
return; return;
} }
try {
await saveFileRL.consume(data.userId, 1);
await saveFile(fileId, body);
} catch (e) {
io.emit("error", "Rate limited: file saving. Please slow down.");
return;
}
const file = sandboxFiles.fileData.find((f) => f.id === fileId); const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return; if (!file) return;
file.data = body; file.data = body;
fs.writeFile(path.join(dirName, file.id), body, function (err) { await containers[data.sandboxId].filesystem.write(
if (err) throw err; path.join(dirName, file.id),
}); body
await saveFile(fileId, body); );
} catch (e) { fixPermissions();
io.emit("rateLimit", "Rate limited: file saving. Please slow down."); } catch (e: any) {
console.error("Error saving file:", e);
io.emit("error", `Error: file saving. ${e.message ?? e}`);
} }
}); });
socket.on("moveFile", async (fileId: string, folderId: string, callback) => { socket.on(
"moveFile",
async (fileId: string, folderId: string, callback) => {
try {
const file = sandboxFiles.fileData.find((f) => f.id === fileId); const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return; if (!file) return;
const parts = fileId.split("/"); const parts = fileId.split("/");
const newFileId = folderId + "/" + parts.pop(); const newFileId = folderId + "/" + parts.pop();
fs.rename( await moveFile(
containers[data.sandboxId].filesystem,
path.join(dirName, fileId), path.join(dirName, fileId),
path.join(dirName, newFileId), path.join(dirName, newFileId)
function (err) {
if (err) throw err;
}
); );
fixPermissions();
file.id = newFileId; file.id = newFileId;
await renameFile(fileId, newFileId, file.data); await renameFile(fileId, newFileId, file.data);
const newFiles = await getSandboxFiles(data.sandboxId); const newFiles = await getSandboxFiles(data.sandboxId);
callback(newFiles.files); callback(newFiles.files);
}); } catch (e: any) {
console.error("Error moving file:", e);
io.emit("error", `Error: file moving. ${e.message ?? e}`);
}
}
);
socket.on("createFile", async (name: string, callback) => { socket.on("createFile", async (name: string, callback) => {
try { try {
@ -235,19 +258,27 @@ io.on("connection", async (socket) => {
// limit is 200mb // limit is 200mb
if (size > 200 * 1024 * 1024) { if (size > 200 * 1024 * 1024) {
io.emit( io.emit(
"rateLimit", "error",
"Rate limited: project size exceeded. Please delete some files." "Rate limited: project size exceeded. Please delete some files."
); );
callback({ success: false }); callback({ success: false });
return;
} }
try {
await createFileRL.consume(data.userId, 1); await createFileRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: file creation. Please slow down.");
return;
}
const id = `projects/${data.sandboxId}/${name}`; const id = `projects/${data.sandboxId}/${name}`;
fs.writeFile(path.join(dirName, id), "", function (err) { await containers[data.sandboxId].filesystem.write(
if (err) throw err; path.join(dirName, id),
}); ""
);
fixPermissions();
sandboxFiles.files.push({ sandboxFiles.files.push({
id, id,
@ -263,30 +294,42 @@ io.on("connection", async (socket) => {
await createFile(id); await createFile(id);
callback({ success: true }); callback({ success: true });
} catch (e) { } catch (e: any) {
io.emit("rateLimit", "Rate limited: file creation. Please slow down."); console.error("Error creating file:", e);
io.emit("error", `Error: file creation. ${e.message ?? e}`);
} }
}); });
socket.on("createFolder", async (name: string, callback) => { socket.on("createFolder", async (name: string, callback) => {
try {
try { try {
await createFolderRL.consume(data.userId, 1); await createFolderRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: folder creation. Please slow down.");
return;
}
const id = `projects/${data.sandboxId}/${name}`; const id = `projects/${data.sandboxId}/${name}`;
fs.mkdir(path.join(dirName, id), { recursive: true }, function (err) { await containers[data.sandboxId].filesystem.makeDir(
if (err) throw err; path.join(dirName, id)
}); );
callback(); callback();
} catch (e) { } catch (e: any) {
io.emit("rateLimit", "Rate limited: folder creation. Please slow down."); console.error("Error creating folder:", e);
io.emit("error", `Error: folder creation. ${e.message ?? e}`);
} }
}); });
socket.on("renameFile", async (fileId: string, newName: string) => { socket.on("renameFile", async (fileId: string, newName: string) => {
try {
try { try {
await renameFileRL.consume(data.userId, 1); await renameFileRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: file renaming. Please slow down.");
return;
}
const file = sandboxFiles.fileData.find((f) => f.id === fileId); const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return; if (!file) return;
@ -296,29 +339,33 @@ io.on("connection", async (socket) => {
const newFileId = const newFileId =
parts.slice(0, parts.length - 1).join("/") + "/" + newName; parts.slice(0, parts.length - 1).join("/") + "/" + newName;
fs.rename( await moveFile(
containers[data.sandboxId].filesystem,
path.join(dirName, fileId), path.join(dirName, fileId),
path.join(dirName, newFileId), path.join(dirName, newFileId)
function (err) {
if (err) throw err;
}
); );
fixPermissions();
await renameFile(fileId, newFileId, file.data); await renameFile(fileId, newFileId, file.data);
} catch (e) { } catch (e: any) {
io.emit("rateLimit", "Rate limited: file renaming. Please slow down."); console.error("Error renaming folder:", e);
return; io.emit("error", `Error: folder renaming. ${e.message ?? e}`);
} }
}); });
socket.on("deleteFile", async (fileId: string, callback) => { socket.on("deleteFile", async (fileId: string, callback) => {
try {
try { try {
await deleteFileRL.consume(data.userId, 1); await deleteFileRL.consume(data.userId, 1);
} catch (e) {
io.emit("error", "Rate limited: file deletion. Please slow down.");
}
const file = sandboxFiles.fileData.find((f) => f.id === fileId); const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return; if (!file) return;
fs.unlink(path.join(dirName, fileId), function (err) { await containers[data.sandboxId].filesystem.remove(
if (err) throw err; path.join(dirName, fileId)
}); );
sandboxFiles.fileData = sandboxFiles.fileData.filter( sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== fileId (f) => f.id !== fileId
); );
@ -327,8 +374,9 @@ io.on("connection", async (socket) => {
const newFiles = await getSandboxFiles(data.sandboxId); const newFiles = await getSandboxFiles(data.sandboxId);
callback(newFiles.files); callback(newFiles.files);
} catch (e) { } catch (e: any) {
io.emit("rateLimit", "Rate limited: file deletion. Please slow down."); console.error("Error deleting file:", e);
io.emit("error", `Error: file deletion. ${e.message ?? e}`);
} }
}); });
@ -337,13 +385,14 @@ io.on("connection", async (socket) => {
// }); // });
socket.on("deleteFolder", async (folderId: string, callback) => { socket.on("deleteFolder", async (folderId: string, callback) => {
try {
const files = await getFolder(folderId); const files = await getFolder(folderId);
await Promise.all( await Promise.all(
files.map(async (file) => { files.map(async (file) => {
fs.unlink(path.join(dirName, file), function (err) { await containers[data.sandboxId].filesystem.remove(
if (err) throw err; path.join(dirName, file)
}); );
sandboxFiles.fileData = sandboxFiles.fileData.filter( sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== file (f) => f.id !== file
@ -356,74 +405,74 @@ io.on("connection", async (socket) => {
const newFiles = await getSandboxFiles(data.sandboxId); const newFiles = await getSandboxFiles(data.sandboxId);
callback(newFiles.files); callback(newFiles.files);
} catch (e: any) {
console.error("Error deleting folder:", e);
io.emit("error", `Error: folder deletion. ${e.message ?? e}`);
}
}); });
function toBackslashNotation(input: string) {
return input
.replace(/\\/g, "\\\\") // Escape backslashes
.replace(/\n/g, "\\n") // Escape newlines
.replace(/\r/g, "\\r") // Escape carriage returns
.replace(/\t/g, "\\t") // Escape tabs
.replace(/"/g, '\\"') // Escape double quotes
.replace(/'/g, "\\'") // Escape single quotes
.replace(/\f/g, "\\f") // Escape form feeds
.replace(/\b/g, "\\b") // Escape backspaces
.replace(/\v/g, "\\v") // Escape vertical tabs
.replace(/\0/g, "\\0") // Escape null characters
.replace(/\a/g, "\\a") // Escape alert (bell)
.replace(/\e/g, "\\e"); // Escape escape
}
socket.on("createTerminal", async (id: string, callback) => { socket.on("createTerminal", async (id: string, callback) => {
try {
if (terminals[id] || Object.keys(terminals).length >= 4) { if (terminals[id] || Object.keys(terminals).length >= 4) {
return; return;
} }
const onData = (data: ProcessMessage) => {
console.log("process", toBackslashNotation(data.toString()));
io.emit("terminalResponse", {
id,
data: data.toString() + "\r\n",
});
};
await lockManager.acquireLock(data.sandboxId, async () => { await lockManager.acquireLock(data.sandboxId, async () => {
console.log("Creating terminal", id); try {
terminals[id] = await containers[data.sandboxId].process.start({ terminals[id] = await containers[data.sandboxId].terminal.start({
cmd: 'TERM=xterm script -c "screen" /dev/null', // xterm vt100 onData: (data: string) => {
onStdout: onData, io.emit("terminalResponse", { id, data });
onStderr: onData, },
onExit: (code) => console.log("exit :(", code), size: { cols: 80, rows: 20 },
onExit: () => console.log("Terminal exited", id),
}); });
await terminals[id].sendStdin("clear\r\n"); await terminals[id].sendData(
await terminals[id].sendStdin("export PS1='user> '\r\n"); `cd "${path.join(dirName, "projects", data.sandboxId)}"\r`
await terminals[id].sendStdin("clear\r\n"); );
await terminals[id].sendData("export PS1='user> '\rclear\r");
console.log("Created terminal", id); console.log("Created terminal", id);
} catch (e: any) {
console.error(`Error creating terminal ${id}:`, e);
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
}
}); });
callback(); callback();
} catch (e: any) {
console.error(`Error creating terminal ${id}:`, e);
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
}
}); });
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => { socket.on(
/*Object.values(terminals).forEach((t) => { "resizeTerminal",
t.terminal.resize(dimensions.cols, dimensions.rows); (dimensions: { cols: number; rows: number }) => {
});*/ try {
Object.values(terminals).forEach((t) => {
t.resize(dimensions);
}); });
} catch (e: any) {
console.error("Error resizing terminal:", e);
io.emit("error", `Error: terminal resizing. ${e.message ?? e}`);
}
}
);
socket.on("terminalData", (id: string, data: string) => { socket.on("terminalData", (id: string, data: string) => {
try {
if (!terminals[id]) { if (!terminals[id]) {
return; return;
} }
try { terminals[id].sendData(data);
console.log(`Writing ${toBackslashNotation(data)} to ${id}`); } catch (e: any) {
terminals[id].sendStdin(data); console.error("Error writing to terminal:", e);
} catch (e) { io.emit("error", `Error: writing to terminal. ${e.message ?? e}`);
console.log("Error writing to terminal", e);
} }
}); });
socket.on("closeTerminal", async (id: string, callback) => { socket.on("closeTerminal", async (id: string, callback) => {
try {
if (!terminals[id]) { if (!terminals[id]) {
return; return;
} }
@ -432,6 +481,10 @@ io.on("connection", async (socket) => {
delete terminals[id]; delete terminals[id];
callback(); callback();
} catch (e: any) {
console.error("Error closing terminal:", e);
io.emit("error", `Error: closing terminal. ${e.message ?? e}`);
}
}); });
socket.on( socket.on(
@ -443,6 +496,7 @@ io.on("connection", async (socket) => {
instructions: string, instructions: string,
callback callback
) => { ) => {
try {
const fetchPromise = fetch( const fetchPromise = fetch(
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`, `${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
{ {
@ -476,23 +530,36 @@ io.on("connection", async (socket) => {
const json = await generateCodeResponse.json(); const json = await generateCodeResponse.json();
callback({ response: json.response, success: true }); callback({ response: json.response, success: true });
} catch (e: any) {
console.error("Error generating code:", e);
io.emit("error", `Error: code generation. ${e.message ?? e}`);
}
} }
); );
socket.on("disconnect", async () => { socket.on("disconnect", async () => {
try {
if (data.isOwner) { if (data.isOwner) {
Object.entries(terminals).forEach((t) => { connections[data.sandboxId]--;
const terminal = t[1]; }
terminal.kill();
delete terminals[t[0]]; if (data.isOwner && connections[data.sandboxId] <= 0) {
}); await Promise.all(
Object.entries(terminals).map(async ([key, terminal]) => {
await terminal.kill();
delete terminals[key];
})
);
await lockManager.acquireLock(data.sandboxId, async () => { await lockManager.acquireLock(data.sandboxId, async () => {
try {
if (containers[data.sandboxId]) { if (containers[data.sandboxId]) {
console.log("Closing container", data.sandboxId);
await containers[data.sandboxId].close(); await containers[data.sandboxId].close();
delete containers[data.sandboxId]; delete containers[data.sandboxId];
console.log("Closed"); console.log("Closed container", data.sandboxId);
}
} catch (error) {
console.error("Error closing container ", data.sandboxId, error);
} }
}); });
@ -518,7 +585,15 @@ io.on("connection", async (socket) => {
// } else { // } else {
// console.log("number of sockets", sockets.length); // console.log("number of sockets", sockets.length);
// } // }
} catch (e: any) {
console.log("Error disconnecting:", e);
io.emit("error", `Error: disconnecting. ${e.message ?? e}`);
}
}); });
} catch (e: any) {
console.error("Error connecting:", e);
io.emit("error", `Error: connection. ${e.message ?? e}`);
}
}); });
httpServer.listen(port, () => { httpServer.listen(port, () => {

View File

@ -1,177 +1,23 @@
import * as dotenv from "dotenv"; export class LockManager {
import { private locks: { [key: string]: Promise<any> };
R2FileBody,
R2Files,
Sandbox,
TFile,
TFileData,
TFolder,
} from "./types";
dotenv.config(); constructor() {
this.locks = {};
export const getSandboxFiles = async (id: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?sandboxId=${id}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
const data: R2Files = await res.json();
const paths = data.objects.map((obj) => obj.key);
const processedFiles = await processFiles(paths, id);
return processedFiles;
};
export const getFolder = async (folderId: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?folderId=${folderId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
const data: R2Files = await res.json();
return data.objects.map((obj) => obj.key);
};
const processFiles = async (paths: string[], id: string) => {
const root: TFolder = { id: "/", type: "folder", name: "/", children: [] };
const fileData: TFileData[] = [];
paths.forEach((path) => {
const allParts = path.split("/");
if (allParts[1] !== id) {
return;
} }
const parts = allParts.slice(2); async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> {
let current: TFolder = root; if (!this.locks[key]) {
this.locks[key] = new Promise<T>(async (resolve, reject) => {
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isFile = i === parts.length - 1 && part.includes(".");
const existing = current.children.find((child) => child.name === part);
if (existing) {
if (!isFile) {
current = existing as TFolder;
}
} else {
if (isFile) {
const file: TFile = { id: path, type: "file", name: part };
current.children.push(file);
fileData.push({ id: path, data: "" });
} else {
const folder: TFolder = {
// id: path, // todo: wrong id. for example, folder "src" ID is: projects/a7vgttfqbgy403ratp7du3ln/src/App.css
id: `projects/${id}/${parts.slice(0, i + 1).join("/")}`,
type: "folder",
name: part,
children: [],
};
current.children.push(folder);
current = folder;
}
}
}
});
await Promise.all(
fileData.map(async (file) => {
const data = await fetchFileContent(file.id);
file.data = data;
})
);
return {
files: root.children,
fileData,
};
};
const fetchFileContent = async (fileId: string): Promise<string> => {
try { try {
const fileRes = await fetch( const result = await task();
`${process.env.STORAGE_WORKER_URL}/api?fileId=${fileId}`, resolve(result);
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
return await fileRes.text();
} catch (error) { } catch (error) {
console.error("ERROR fetching file:", error); reject(error);
return ""; } finally {
delete this.locks[key];
} }
};
export const createFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
}); });
return res.ok;
};
export const renameFile = async (
fileId: string,
newFileId: string,
data: string
) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, newFileId, data }),
});
return res.ok;
};
export const saveFile = async (fileId: string, data: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/save`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, data }),
});
return res.ok;
};
export const deleteFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
});
return res.ok;
};
export const getProjectSize = async (id: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api/size?sandboxId=${id}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
} }
); return await this.locks[key];
return (await res.json()).size; }
}; }

View File

@ -6,6 +6,7 @@ import { ThemeProvider } from "@/components/layout/themeProvider"
import { ClerkProvider } from "@clerk/nextjs" import { ClerkProvider } from "@clerk/nextjs"
import { Toaster } from "@/components/ui/sonner" import { Toaster } from "@/components/ui/sonner"
import { Analytics } from "@vercel/analytics/react" import { Analytics } from "@vercel/analytics/react"
import { TerminalProvider } from '@/context/TerminalContext';
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Sandbox", title: "Sandbox",
@ -27,7 +28,9 @@ export default function RootLayout({
forcedTheme="dark" forcedTheme="dark"
disableTransitionOnChange disableTransitionOnChange
> >
<TerminalProvider>
{children} {children}
</TerminalProvider>
<Analytics /> <Analytics />
<Toaster position="bottom-left" richColors /> <Toaster position="bottom-left" richColors />
</ThemeProvider> </ThemeProvider>

View File

@ -1,9 +1,9 @@
"use client" "use client"
import { useEffect, useRef, useState } from "react" import { SetStateAction, useCallback, useEffect, useRef, useState } from "react"
import monaco from "monaco-editor" import monaco from "monaco-editor"
import Editor, { BeforeMount, OnMount } from "@monaco-editor/react" import Editor, { BeforeMount, OnMount } from "@monaco-editor/react"
import { io } from "socket.io-client" import { Socket, io } from "socket.io-client"
import { toast } from "sonner" import { toast } from "sonner"
import { useClerk } from "@clerk/nextjs" import { useClerk } from "@clerk/nextjs"
@ -23,7 +23,7 @@ import Tab from "../ui/tab"
import Sidebar from "./sidebar" import Sidebar from "./sidebar"
import GenerateInput from "./generate" import GenerateInput from "./generate"
import { Sandbox, User, TFile, TFolder, TTab } from "@/lib/types" import { Sandbox, User, TFile, TFolder, TTab } from "@/lib/types"
import { addNew, processFileType, validateName } from "@/lib/utils" import { addNew, processFileType, validateName, debounce } from "@/lib/utils"
import { Cursors } from "./live/cursors" import { Cursors } from "./live/cursors"
import { Terminal } from "@xterm/xterm" import { Terminal } from "@xterm/xterm"
import DisableAccessModal from "./live/disableModal" import DisableAccessModal from "./live/disableModal"
@ -41,12 +41,16 @@ export default function CodeEditor({
sandboxData: Sandbox sandboxData: Sandbox
reactDefinitionFile: string reactDefinitionFile: string
}) { }) {
const socket = io( const socketRef = useRef<Socket | null>(null);
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
// Initialize socket connection if it doesn't exist
if (!socketRef.current) {
socketRef.current = io(
`${window.location.protocol}//${window.location.hostname}:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
{ {
timeout: 2000, timeout: 2000,
} }
) );}
const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true) const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true)
const [disableAccess, setDisableAccess] = useState({ const [disableAccess, setDisableAccess] = useState({
@ -90,6 +94,9 @@ export default function CodeEditor({
}[] }[]
>([]) >([])
// Preview state
const [previewURL, setPreviewURL] = useState<string>("");
const isOwner = sandboxData.userId === userData.id const isOwner = sandboxData.userId === userData.id
const clerk = useClerk() const clerk = useClerk()
@ -290,37 +297,58 @@ export default function CodeEditor({
}, [decorations.options]) }, [decorations.options])
// Save file keybinding logic effect // Save file keybinding logic effect
useEffect(() => { const debouncedSaveData = useCallback(
const down = (e: KeyboardEvent) => { debounce((value: string | undefined, activeFileId: string | undefined) => {
if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
setTabs((prev) => setTabs((prev) =>
prev.map((tab) => prev.map((tab) =>
tab.id === activeFileId ? { ...tab, saved: true } : tab tab.id === activeFileId ? { ...tab, saved: true } : tab
) )
) );
console.log(`Saving file...${activeFileId}`);
console.log(`Saving file...${value}`);
socketRef.current?.emit("saveFile", activeFileId, value);
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY)||1000),
[socketRef]
);
socket.emit("saveFile", activeFileId, editorRef?.getValue()) useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
debouncedSaveData(editorRef?.getValue(), activeFileId);
} }
} };
document.addEventListener("keydown", down) document.addEventListener("keydown", down);
return () => { return () => {
document.removeEventListener("keydown", down) document.removeEventListener("keydown", down);
} };
}, [tabs, activeFileId]) }, [activeFileId, tabs, debouncedSaveData]);
// Liveblocks live collaboration setup effect // Liveblocks live collaboration setup effect
type ProviderData = {
provider: LiveblocksProvider<never, never, never, never>;
yDoc: Y.Doc;
yText: Y.Text;
binding?: MonacoBinding;
onSync: (isSynced: boolean) => void;
};
const providersMap = useRef(new Map<string, ProviderData>());
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;
const yDoc = new Y.Doc() let providerData: ProviderData;
const yText = yDoc.getText(tab.id)
const yProvider: any = new LiveblocksProvider(room, yDoc) if (!providersMap.current.has(tab.id)) {
const yDoc = new Y.Doc();
const yText = yDoc.getText(tab.id);
const yProvider = new LiveblocksProvider(room, yDoc);
const onSync = (isSynced: boolean) => { const onSync = (isSynced: boolean) => {
if (isSynced) { if (isSynced) {
@ -337,31 +365,57 @@ export default function CodeEditor({
} }
} }
yProvider.on("sync", onSync) yProvider.on("sync", onSync);
setProvider(yProvider) providerData = { provider: yProvider, yDoc, yText, onSync };
providersMap.current.set(tab.id, providerData);
} else {
providerData = providersMap.current.get(tab.id)!;
}
const binding = new MonacoBinding( const binding = new MonacoBinding(
yText, providerData.yText,
model, model,
new Set([editorRef]), new Set([editorRef]),
yProvider.awareness as Awareness providerData.provider.awareness as unknown as Awareness
) );
providerData.binding = binding;
setProvider(providerData.provider);
return () => { return () => {
yDoc.destroy() // Cleanup logic
yProvider.destroy() if (binding) {
binding.destroy() binding.destroy();
yProvider.off("sync", onSync)
} }
}, [editorRef, room, activeFileContent]) if (providerData.binding) {
providerData.binding = undefined;
}
};
}, [editorRef, room, activeFileContent, activeFileId, tabs]);
// Added this effect to clean up when the component unmounts
useEffect(() => {
return () => {
// Clean up all providers when the component unmounts
providersMap.current.forEach((data) => {
if (data.binding) {
data.binding.destroy();
}
data.provider.disconnect();
data.yDoc.destroy();
});
providersMap.current.clear();
};
}, []);
// Connection/disconnection effect // Connection/disconnection effect
useEffect(() => { useEffect(() => {
socket.connect() socketRef.current?.connect()
return () => { return () => {
socket.disconnect() socketRef.current?.disconnect()
} }
}, []) }, [])
@ -377,7 +431,7 @@ export default function CodeEditor({
setFiles(files) setFiles(files)
} }
const onRateLimit = (message: string) => { const onError = (message: string) => {
toast.error(message) toast.error(message)
} }
@ -396,20 +450,22 @@ export default function CodeEditor({
}) })
} }
socket.on("connect", onConnect) socketRef.current?.on("connect", onConnect)
socket.on("disconnect", onDisconnect) socketRef.current?.on("disconnect", onDisconnect)
socket.on("loaded", onLoadedEvent) socketRef.current?.on("loaded", onLoadedEvent)
socket.on("rateLimit", onRateLimit) socketRef.current?.on("error", onError)
socket.on("terminalResponse", onTerminalResponse) socketRef.current?.on("terminalResponse", onTerminalResponse)
socket.on("disableAccess", onDisableAccess) socketRef.current?.on("disableAccess", onDisableAccess)
socketRef.current?.on("previewURL", setPreviewURL)
return () => { return () => {
socket.off("connect", onConnect) socketRef.current?.off("connect", onConnect)
socket.off("disconnect", onDisconnect) socketRef.current?.off("disconnect", onDisconnect)
socket.off("loaded", onLoadedEvent) socketRef.current?.off("loaded", onLoadedEvent)
socket.off("rateLimit", onRateLimit) socketRef.current?.off("error", onError)
socket.off("terminalResponse", onTerminalResponse) socketRef.current?.off("terminalResponse", onTerminalResponse)
socket.off("disableAccess", onDisableAccess) socketRef.current?.off("disableAccess", onDisableAccess)
socketRef.current?.off("previewURL", setPreviewURL)
} }
// }, []); // }, []);
}, [terminals]) }, [terminals])
@ -417,32 +473,50 @@ export default function CodeEditor({
// Helper functions for tabs: // Helper functions for tabs:
// Select file and load content // Select file and load content
const selectFile = (tab: TTab) => {
if (tab.id === activeFileId) return
setGenerate((prev) => { // Initialize debounced function once
return { const fileCache = useRef(new Map());
...prev,
show: false,
}
})
const exists = tabs.find((t) => t.id === tab.id)
// Debounced function to get file content
const debouncedGetFile = useCallback(
debounce((tabId, callback) => {
socketRef.current?.emit('getFile', tabId, callback);
}, 300), // 300ms debounce delay, adjust as needed
[]
);
const selectFile = useCallback((tab: TTab) => {
if (tab.id === activeFileId) return;
setGenerate((prev) => ({ ...prev, show: false }));
//editor windows fix
function updateTabs(){
const exists = tabs.find((t) => t.id === tab.id);
setTabs((prev) => { setTabs((prev) => {
if (exists) { if (exists) {
setActiveFileId(exists.id) setActiveFileId(exists.id);
return prev return prev;
}
return [...prev, tab];
});
} }
return [...prev, tab]
})
socket.emit("getFile", tab.id, (response: string) => { if (fileCache.current.has(tab.id)) {
setActiveFileContent(response) setActiveFileContent(fileCache.current.get(tab.id));
}) updateTabs();
setEditorLanguage(processFileType(tab.name)) } else {
setActiveFileId(tab.id) debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
fileCache.current.set(tab.id, response);
setActiveFileContent(response);
updateTabs();
});
} }
setEditorLanguage(processFileType(tab.name));
setActiveFileId(tab.id);
}, [activeFileId, tabs, debouncedGetFile]);
// Close tab and remove from tabs // Close tab and remove from tabs
const closeTab = (id: string) => { const closeTab = (id: string) => {
const numTabs = tabs.length const numTabs = tabs.length
@ -515,7 +589,7 @@ export default function CodeEditor({
return false return false
} }
socket.emit("renameFile", id, newName) socketRef.current?.emit("renameFile", id, newName)
setTabs((prev) => setTabs((prev) =>
prev.map((tab) => (tab.id === id ? { ...tab, name: newName } : tab)) prev.map((tab) => (tab.id === id ? { ...tab, name: newName } : tab))
) )
@ -524,7 +598,7 @@ export default function CodeEditor({
} }
const handleDeleteFile = (file: TFile) => { const handleDeleteFile = (file: TFile) => {
socket.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => { socketRef.current?.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
setFiles(response) setFiles(response)
}) })
closeTab(file.id) closeTab(file.id)
@ -534,11 +608,11 @@ export default function CodeEditor({
setDeletingFolderId(folder.id) setDeletingFolderId(folder.id)
console.log("deleting folder", folder.id) console.log("deleting folder", folder.id)
socket.emit("getFolder", folder.id, (response: string[]) => socketRef.current?.emit("getFolder", folder.id, (response: string[]) =>
closeTabs(response) closeTabs(response)
) )
socket.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => { socketRef.current?.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
setFiles(response) setFiles(response)
setDeletingFolderId("") setDeletingFolderId("")
}) })
@ -565,7 +639,7 @@ export default function CodeEditor({
{generate.show && ai ? ( {generate.show && ai ? (
<GenerateInput <GenerateInput
user={userData} user={userData}
socket={socket} socket={socketRef.current}
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 ?? "",
@ -625,7 +699,7 @@ export default function CodeEditor({
handleRename={handleRename} handleRename={handleRename}
handleDeleteFile={handleDeleteFile} handleDeleteFile={handleDeleteFile}
handleDeleteFolder={handleDeleteFolder} handleDeleteFolder={handleDeleteFolder}
socket={socket} socket={socketRef.current}
setFiles={setFiles} setFiles={setFiles}
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)} addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
deletingFolderId={deletingFolderId} deletingFolderId={deletingFolderId}
@ -745,6 +819,7 @@ export default function CodeEditor({
previewPanelRef.current?.expand() previewPanelRef.current?.expand()
setIsPreviewCollapsed(false) setIsPreviewCollapsed(false)
}} }}
src={previewURL}
/> />
</ResizablePanel> </ResizablePanel>
<ResizableHandle /> <ResizableHandle />
@ -754,11 +829,7 @@ export default function CodeEditor({
className="p-2 flex flex-col" className="p-2 flex flex-col"
> >
{isOwner ? ( {isOwner ? (
<Terminals <Terminals/>
terminals={terminals}
setTerminals={setTerminals}
socket={socket}
/>
) : ( ) : (
<div className="w-full h-full flex items-center justify-center text-lg font-medium text-muted-foreground/50 select-none"> <div className="w-full h-full flex items-center justify-center text-lg font-medium text-muted-foreground/50 select-none">
<TerminalSquare className="w-4 h-4 mr-2" /> <TerminalSquare className="w-4 h-4 mr-2" />
@ -772,3 +843,4 @@ export default function CodeEditor({
</> </>
) )
} }

View File

@ -2,7 +2,7 @@
import Image from "next/image"; import Image from "next/image";
import Logo from "@/assets/logo.svg"; import Logo from "@/assets/logo.svg";
import { Pencil, Users } from "lucide-react"; import { Pencil, Users, Play, StopCircle } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { Sandbox, User } from "@/lib/types"; import { Sandbox, User } from "@/lib/types";
import UserButton from "@/components/ui/userButton"; import UserButton from "@/components/ui/userButton";
@ -11,23 +11,30 @@ import { useState } from "react";
import EditSandboxModal from "./edit"; import EditSandboxModal from "./edit";
import ShareSandboxModal from "./share"; import ShareSandboxModal from "./share";
import { Avatars } from "../live/avatars"; import { Avatars } from "../live/avatars";
import RunButtonModal from "./run";
import { Terminal } from "@xterm/xterm";
import { Socket } from "socket.io-client";
import Terminals from "../terminals";
export default function Navbar({ export default function Navbar({
userData, userData,
sandboxData, sandboxData,
shared, shared,
socket,
}: { }: {
userData: User; userData: User;
sandboxData: Sandbox; sandboxData: Sandbox;
shared: { shared: { id: string; name: string }[];
id: string; socket: Socket;
name: string;
}[];
}) { }) {
const [isEditOpen, setIsEditOpen] = useState(false); const [isEditOpen, setIsEditOpen] = useState(false);
const [isShareOpen, setIsShareOpen] = useState(false); const [isShareOpen, setIsShareOpen] = useState(false);
const [isRunning, setIsRunning] = useState(false);
const [terminals, setTerminals] = useState<{ id: string; terminal: Terminal | null }[]>([]);
const [activeTerminalId, setActiveTerminalId] = useState("");
const [creatingTerminal, setCreatingTerminal] = useState(false);
const isOwner = sandboxData.userId === userData.id; const isOwner = sandboxData.userId === userData.id;;
return ( return (
<> <>
@ -62,6 +69,10 @@ export default function Navbar({
) : null} ) : null}
</div> </div>
</div> </div>
<RunButtonModal
isRunning={isRunning}
setIsRunning={setIsRunning}
/>
<div className="flex items-center h-full space-x-4"> <div className="flex items-center h-full space-x-4">
<Avatars /> <Avatars />

View File

@ -0,0 +1,60 @@
"use client";
import { Play, StopCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useTerminal } from "@/context/TerminalContext";
import { closeTerminal } from "@/lib/terminal";
export default function RunButtonModal({
isRunning,
setIsRunning,
}: {
isRunning: boolean;
setIsRunning: (running: boolean) => void;
}) {
const { createNewTerminal, terminals, setTerminals, socket, setActiveTerminalId } = useTerminal();
const handleRun = () => {
if (isRunning) {
console.log('Stopping sandbox...');
console.log('Closing Terminal');
console.log('Closing Preview Window');
// Close all terminals if needed
terminals.forEach(term => {
if (term.terminal) {
// Assuming you have a closeTerminal function similar to createTerminal
closeTerminal({
term,
terminals,
setTerminals,
setActiveTerminalId,
setClosingTerminal: () => { },
socket: socket!,
activeTerminalId: term.id,
});
}
});
} else {
console.log('Running sandbox...');
console.log('Opening Terminal');
console.log('Opening Preview Window');
if (terminals.length < 4) {
createNewTerminal();
} else {
console.error('Maximum number of terminals reached.');
}
}
setIsRunning(!isRunning);
};
return (
<>
<Button variant="outline" onClick={handleRun}>
{isRunning ? <StopCircle className="w-4 h-4 mr-2" /> : <Play className="w-4 h-4 mr-2" />}
{isRunning ? 'Stop' : 'Run'}
</Button>
</>
);
}

View File

@ -15,9 +15,11 @@ import { toast } from "sonner"
export default function PreviewWindow({ export default function PreviewWindow({
collapsed, collapsed,
open, open,
src
}: { }: {
collapsed: boolean collapsed: boolean
open: () => void open: () => void
src: string
}) { }) {
const ref = useRef<HTMLIFrameElement>(null) const ref = useRef<HTMLIFrameElement>(null)
const [iframeKey, setIframeKey] = useState(0) const [iframeKey, setIframeKey] = useState(0)
@ -45,7 +47,7 @@ export default function PreviewWindow({
<PreviewButton <PreviewButton
onClick={() => { onClick={() => {
navigator.clipboard.writeText(`http://localhost:5173`) navigator.clipboard.writeText(src)
toast.info("Copied preview link to clipboard") toast.info("Copied preview link to clipboard")
}} }}
> >
@ -73,7 +75,7 @@ export default function PreviewWindow({
ref={ref} ref={ref}
width={"100%"} width={"100%"}
height={"100%"} height={"100%"}
src={`http://localhost:5173`} src={src}
/> />
</div> </div>
)} )}

View File

@ -2,30 +2,16 @@
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import Tab from "@/components/ui/tab"; import Tab from "@/components/ui/tab";
import { closeTerminal, createTerminal } from "@/lib/terminal"; import { closeTerminal } from "@/lib/terminal";
import { Terminal } from "@xterm/xterm"; import { Terminal } from "@xterm/xterm";
import { Loader2, Plus, SquareTerminal, TerminalSquare } from "lucide-react"; import { Loader2, Plus, SquareTerminal, TerminalSquare } from "lucide-react";
import { Socket } from "socket.io-client";
import { toast } from "sonner"; import { toast } from "sonner";
import EditorTerminal from "./terminal"; import EditorTerminal from "./terminal";
import { useState } from "react"; import { useState } from "react";
import { useTerminal } from "@/context/TerminalContext";
export default function Terminals({ export default function Terminals() {
terminals, const { terminals, setTerminals, socket, createNewTerminal } = useTerminal();
setTerminals,
socket,
}: {
terminals: { id: string; terminal: Terminal | null }[];
setTerminals: React.Dispatch<
React.SetStateAction<
{
id: string;
terminal: Terminal | null;
}[]
>
>;
socket: Socket;
}) {
const [activeTerminalId, setActiveTerminalId] = useState(""); const [activeTerminalId, setActiveTerminalId] = useState("");
const [creatingTerminal, setCreatingTerminal] = useState(false); const [creatingTerminal, setCreatingTerminal] = useState(false);
const [closingTerminal, setClosingTerminal] = useState(""); const [closingTerminal, setClosingTerminal] = useState("");
@ -46,7 +32,7 @@ export default function Terminals({
setTerminals, setTerminals,
setActiveTerminalId, setActiveTerminalId,
setClosingTerminal, setClosingTerminal,
socket, socket: socket!,
activeTerminalId, activeTerminalId,
}) })
} }
@ -64,12 +50,7 @@ export default function Terminals({
toast.error("You reached the maximum # of terminals."); toast.error("You reached the maximum # of terminals.");
return; return;
} }
createTerminal({ createNewTerminal();
setTerminals,
setActiveTerminalId,
setCreatingTerminal,
socket,
});
}} }}
size="smIcon" size="smIcon"
variant={"secondary"} variant={"secondary"}

View File

@ -0,0 +1,99 @@
"use client";
import React, { createContext, useContext, useState, useEffect } from 'react';
import { io, Socket } from 'socket.io-client';
import { Terminal } from '@xterm/xterm';
import { createId } from '@paralleldrive/cuid2';
import { createTerminal as createTerminalHelper, closeTerminal as closeTerminalHelper } from '@/lib/terminal'; // Adjust the import path as necessary
interface TerminalContextType {
socket: Socket | null;
terminals: { id: string; terminal: Terminal | null }[];
setTerminals: React.Dispatch<React.SetStateAction<{ id: string; terminal: Terminal | null }[]>>;
activeTerminalId: string;
setActiveTerminalId: React.Dispatch<React.SetStateAction<string>>;
creatingTerminal: boolean;
setCreatingTerminal: React.Dispatch<React.SetStateAction<boolean>>;
createNewTerminal: () => void;
closeTerminal: (id: string) => void;
}
const TerminalContext = createContext<TerminalContextType | undefined>(undefined);
export const TerminalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [socket, setSocket] = useState<Socket | null>(null);
const [terminals, setTerminals] = useState<{ id: string; terminal: Terminal | null }[]>([]);
const [activeTerminalId, setActiveTerminalId] = useState<string>('');
const [creatingTerminal, setCreatingTerminal] = useState<boolean>(false);
useEffect(() => {
// Replace with your server URL
const socketIo = io(process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001');
setSocket(socketIo);
// Log socket events
socketIo.on('connect', () => {
console.log('Socket connected:', socketIo.id);
});
socketIo.on('disconnect', () => {
console.log('Socket disconnected');
});
return () => {
socketIo.disconnect();
};
}, []);
const createNewTerminal = () => {
if (socket) {
createTerminalHelper({
setTerminals,
setActiveTerminalId,
setCreatingTerminal,
socket,
});
}
};
const closeTerminal = (id: string) => {
const terminalToClose = terminals.find(term => term.id === id);
if (terminalToClose && socket) {
closeTerminalHelper({
term: terminalToClose,
terminals,
setTerminals,
setActiveTerminalId,
setClosingTerminal: () => {}, // Implement if needed
socket,
activeTerminalId,
});
}
};
const value = {
socket,
terminals,
setTerminals,
activeTerminalId,
setActiveTerminalId,
creatingTerminal,
setCreatingTerminal,
createNewTerminal,
closeTerminal,
};
return (
<TerminalContext.Provider value={value}>
{children}
</TerminalContext.Provider>
);
};
export const useTerminal = (): TerminalContextType => {
const context = useContext(TerminalContext);
if (!context) {
throw new Error('useTerminal must be used within a TerminalProvider');
}
return context;
};

View File

@ -61,3 +61,13 @@ export function addNew(
]) ])
} }
} }
export function debounce<T extends (...args: any[]) => void>(func: T, wait: number): T {
let timeout: NodeJS.Timeout | null = null;
return function (...args: Parameters<T>) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => func(...args), wait);
} as T;
}