Compare commits
26 Commits
sync-conta
...
fix/path-o
Author | SHA1 | Date | |
---|---|---|---|
2c058b259a | |||
5817b2ea48 | |||
6845e1fef9 | |||
f38919d6cf | |||
7aaa920815 | |||
6bfff62513 | |||
0b7cc51c6e | |||
a353863523 | |||
48731848dd | |||
3fcfe5a3dc | |||
6e8eee246f | |||
982a6edc26 | |||
300de1f03a | |||
02deea9c93 | |||
653142dd1d | |||
ec24e64b17 | |||
b8398cc4c2 | |||
0e4649b2c9 | |||
d74205c909 | |||
fa998d9069 | |||
f5b04f9f49 | |||
169319de14 | |||
2dbdf51fd3 | |||
7b2ed21288 | |||
f4a84bd4b6 | |||
171a9ce3c6 |
@ -22,13 +22,13 @@ export class SecureGitClient {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Create a temporary directory
|
// Create a temporary directory
|
||||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'git-push-'));
|
tempDir = fs.mkdtempSync(path.posix.join(os.tmpdir(), 'git-push-'));
|
||||||
console.log(`Temporary directory created: ${tempDir}`);
|
console.log(`Temporary directory created: ${tempDir}`);
|
||||||
|
|
||||||
// Write files to the temporary directory
|
// Write files to the temporary directory
|
||||||
console.log(`Writing ${fileData.length} files.`);
|
console.log(`Writing ${fileData.length} files.`);
|
||||||
for (const { id, data } of fileData) {
|
for (const { id, data } of fileData) {
|
||||||
const filePath = path.join(tempDir, id);
|
const filePath = path.posix.join(tempDir, id);
|
||||||
const dirPath = path.dirname(filePath);
|
const dirPath = path.dirname(filePath);
|
||||||
|
|
||||||
if (!fs.existsSync(dirPath)) {
|
if (!fs.existsSync(dirPath)) {
|
||||||
|
@ -35,7 +35,6 @@ export class Terminal {
|
|||||||
async sendData(data: string) {
|
async sendData(data: string) {
|
||||||
if (this.pty) {
|
if (this.pty) {
|
||||||
await this.sandbox.pty.sendInput(this.pty.pid, new TextEncoder().encode(data));
|
await this.sandbox.pty.sendInput(this.pty.pid, new TextEncoder().encode(data));
|
||||||
await this.pty.wait();
|
|
||||||
} else {
|
} else {
|
||||||
console.log("Cannot send data because pty is not initialized.");
|
console.log("Cannot send data because pty is not initialized.");
|
||||||
}
|
}
|
||||||
|
@ -6,15 +6,10 @@ import { createServer } from "http";
|
|||||||
import { Server } from "socket.io";
|
import { Server } from "socket.io";
|
||||||
import { DokkuClient } from "./DokkuClient";
|
import { DokkuClient } from "./DokkuClient";
|
||||||
import { SecureGitClient, FileData } from "./SecureGitClient";
|
import { SecureGitClient, FileData } from "./SecureGitClient";
|
||||||
import fs, { readFile } from "fs";
|
import fs from "fs";
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import {
|
import { User } from "./types";
|
||||||
TFile,
|
|
||||||
TFileData,
|
|
||||||
TFolder,
|
|
||||||
User
|
|
||||||
} from "./types";
|
|
||||||
import {
|
import {
|
||||||
createFile,
|
createFile,
|
||||||
deleteFile,
|
deleteFile,
|
||||||
@ -26,7 +21,7 @@ import {
|
|||||||
} from "./fileoperations";
|
} from "./fileoperations";
|
||||||
import { LockManager } from "./utils";
|
import { LockManager } from "./utils";
|
||||||
|
|
||||||
import { Sandbox, Filesystem, FilesystemEvent, EntryInfo } from "e2b";
|
import { Sandbox, Filesystem } from "e2b";
|
||||||
|
|
||||||
import { Terminal } from "./Terminal"
|
import { Terminal } from "./Terminal"
|
||||||
|
|
||||||
@ -39,18 +34,6 @@ import {
|
|||||||
saveFileRL,
|
saveFileRL,
|
||||||
} from "./ratelimit";
|
} from "./ratelimit";
|
||||||
|
|
||||||
process.on('uncaughtException', (error) => {
|
|
||||||
console.error('Uncaught Exception:', error);
|
|
||||||
// Do not exit the process
|
|
||||||
// You can add additional logging or recovery logic here
|
|
||||||
});
|
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, promise) => {
|
|
||||||
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
|
||||||
// Do not exit the process
|
|
||||||
// You can also handle the rejected promise here if needed
|
|
||||||
});
|
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
const app: Express = express();
|
const app: Express = express();
|
||||||
@ -72,14 +55,14 @@ const terminals: Record<string, Terminal> = {};
|
|||||||
|
|
||||||
const dirName = "/home/user";
|
const dirName = "/home/user";
|
||||||
|
|
||||||
const moveFile = async (filesystem: Filesystem, filePath: string, newFilePath: string) => {
|
const moveFile = async (
|
||||||
try {
|
filesystem: Filesystem,
|
||||||
|
filePath: string,
|
||||||
|
newFilePath: string
|
||||||
|
) => {
|
||||||
const fileContents = await filesystem.read(filePath);
|
const fileContents = await filesystem.read(filePath);
|
||||||
await filesystem.write(newFilePath, fileContents);
|
await filesystem.write(newFilePath, fileContents);
|
||||||
await filesystem.remove(filePath);
|
await filesystem.remove(filePath);
|
||||||
} catch (e) {
|
|
||||||
console.error(`Error moving file from ${filePath} to ${newFilePath}:`, e);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
io.use(async (socket, next) => {
|
io.use(async (socket, next) => {
|
||||||
@ -174,12 +157,12 @@ io.on("connection", async (socket) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const createdContainer = await lockManager.acquireLock(data.sandboxId, async () => {
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
try {
|
try {
|
||||||
if (!containers[data.sandboxId]) {
|
// Start a new container if the container doesn't exist or it timed out.
|
||||||
containers[data.sandboxId] = await Sandbox.create({ timeoutMs: 1200000 });
|
if (!containers[data.sandboxId] || !(await containers[data.sandboxId].isRunning())) {
|
||||||
|
containers[data.sandboxId] = await Sandbox.create({ timeoutMs: 1200_000 });
|
||||||
console.log("Created container ", data.sandboxId);
|
console.log("Created container ", data.sandboxId);
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error(`Error creating container ${data.sandboxId}:`, e);
|
console.error(`Error creating container ${data.sandboxId}:`, e);
|
||||||
@ -187,41 +170,19 @@ io.on("connection", async (socket) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
const projectDirectory = path.join(dirName, "projects", data.sandboxId);
|
|
||||||
const containerFiles = containers[data.sandboxId].files;
|
|
||||||
|
|
||||||
// Change the owner of the project directory to user
|
// Change the owner of the project directory to user
|
||||||
const fixPermissions = async (projectDirectory: string) => {
|
const fixPermissions = async () => {
|
||||||
try {
|
|
||||||
await containers[data.sandboxId].commands.run(
|
await containers[data.sandboxId].commands.run(
|
||||||
`sudo chown -R user "${projectDirectory}"`
|
`sudo chown -R user "${path.posix.join(dirName, "projects", data.sandboxId)}"`
|
||||||
);
|
);
|
||||||
} catch (e: any) {
|
|
||||||
console.log("Failed to fix permissions: " + e);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if the given path is a directory
|
|
||||||
const isDirectory = async (projectDirectory: string): Promise<boolean> => {
|
|
||||||
try {
|
|
||||||
const result = await containers[data.sandboxId].commands.run(
|
|
||||||
`[ -d "${projectDirectory}" ] && echo "true" || echo "false"`
|
|
||||||
);
|
|
||||||
return result.stdout.trim() === "true";
|
|
||||||
} catch (e: any) {
|
|
||||||
console.log("Failed to check if directory: " + e);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Only continue to container setup if a new container was created
|
|
||||||
if (createdContainer) {
|
|
||||||
|
|
||||||
// Copy all files from the project to the container
|
// Copy all files from the project to the container
|
||||||
|
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
||||||
|
const containerFiles = containers[data.sandboxId].files;
|
||||||
const promises = sandboxFiles.fileData.map(async (file) => {
|
const promises = sandboxFiles.fileData.map(async (file) => {
|
||||||
try {
|
try {
|
||||||
const filePath = path.join(dirName, file.id);
|
const filePath = path.posix.join(dirName, file.id);
|
||||||
const parentDirectory = path.dirname(filePath);
|
const parentDirectory = path.dirname(filePath);
|
||||||
if (!containerFiles.exists(parentDirectory)) {
|
if (!containerFiles.exists(parentDirectory)) {
|
||||||
await containerFiles.makeDir(parentDirectory);
|
await containerFiles.makeDir(parentDirectory);
|
||||||
@ -233,124 +194,7 @@ io.on("connection", async (socket) => {
|
|||||||
});
|
});
|
||||||
await Promise.all(promises);
|
await Promise.all(promises);
|
||||||
|
|
||||||
// Make the logged in user the owner of all project files
|
fixPermissions();
|
||||||
fixPermissions(projectDirectory);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start filesystem watcher for the project directory
|
|
||||||
const watchDirectory = async (directory: string) => {
|
|
||||||
try {
|
|
||||||
await containerFiles.watch(directory, async (event: FilesystemEvent) => {
|
|
||||||
try {
|
|
||||||
|
|
||||||
function removeDirName(path : string, dirName : string) {
|
|
||||||
return path.startsWith(dirName) ? path.slice(dirName.length) : path;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This is the absolute file path in the container
|
|
||||||
const containerFilePath = path.join(directory, event.name);
|
|
||||||
// This is the file path relative to the home directory
|
|
||||||
const sandboxFilePath = removeDirName(containerFilePath, dirName + "/");
|
|
||||||
// This is the directory being watched relative to the home directory
|
|
||||||
const sandboxDirectory = removeDirName(directory, dirName + "/");
|
|
||||||
|
|
||||||
// Helper function to find a folder by id
|
|
||||||
function findFolderById(files: (TFolder | TFile)[], folderId : string) {
|
|
||||||
return files.find((file : TFolder | TFile) => file.type === "folder" && file.id === folderId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A new file or directory was created.
|
|
||||||
if (event.type === "create") {
|
|
||||||
const folder = findFolderById(sandboxFiles.files, sandboxDirectory) as TFolder;
|
|
||||||
const isDir = await 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
|
|
||||||
sandboxFiles.files.push(newItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isDir) {
|
|
||||||
const fileData = await containers[data.sandboxId].files.read(containerFilePath);
|
|
||||||
const fileContents = typeof fileData === "string" ? fileData : "";
|
|
||||||
sandboxFiles.fileData.push({ id: sandboxFilePath, data: fileContents });
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`Create ${sandboxFilePath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A file or directory was removed or renamed.
|
|
||||||
else if (event.type === "remove" || event.type == "rename") {
|
|
||||||
const folder = findFolderById(sandboxFiles.files, sandboxDirectory) as TFolder;
|
|
||||||
const isDir = await 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
|
|
||||||
sandboxFiles.files = sandboxFiles.files.filter((file: TFolder | TFile) => !isFileMatch(file));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also remove any corresponding file data
|
|
||||||
sandboxFiles.fileData = sandboxFiles.fileData.filter((file: TFileData) => !isFileMatch(file));
|
|
||||||
|
|
||||||
console.log(`Removed: ${sandboxFilePath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The contents of a file were changed.
|
|
||||||
else if (event.type === "write") {
|
|
||||||
const folder = findFolderById(sandboxFiles.files, sandboxDirectory) as TFolder;
|
|
||||||
const fileToWrite = sandboxFiles.fileData.find(file => file.id === sandboxFilePath);
|
|
||||||
|
|
||||||
if (fileToWrite) {
|
|
||||||
fileToWrite.data = await containers[data.sandboxId].files.read(containerFilePath);
|
|
||||||
console.log(`Write to ${sandboxFilePath}`);
|
|
||||||
} else {
|
|
||||||
// If the file is part of a folder structure, locate it and update its data
|
|
||||||
const fileInFolder = folder?.children.find(file => file.id === sandboxFilePath);
|
|
||||||
if (fileInFolder) {
|
|
||||||
const fileData = await containers[data.sandboxId].files.read(containerFilePath);
|
|
||||||
const fileContents = typeof fileData === "string" ? fileData : "";
|
|
||||||
sandboxFiles.fileData.push({ id: sandboxFilePath, data: fileContents });
|
|
||||||
console.log(`Write to ${sandboxFilePath}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tell the client to reload the file list
|
|
||||||
socket.emit("loaded", sandboxFiles.files);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Error handling ${event.type} event for ${event.name}:`, error);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Error watching filesystem:`, error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Watch the project directory
|
|
||||||
await watchDirectory(projectDirectory);
|
|
||||||
|
|
||||||
// Watch all subdirectories of the project directory, but not deeper
|
|
||||||
// This also means directories created after the container is created won't be watched
|
|
||||||
const dirContent = await containerFiles.list(projectDirectory);
|
|
||||||
await Promise.all(dirContent.map(async (item : EntryInfo) => {
|
|
||||||
if (item.type === "dir") {
|
|
||||||
console.log("Watching " + item.path);
|
|
||||||
await watchDirectory(item.path);
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
|
|
||||||
socket.emit("loaded", sandboxFiles.files);
|
socket.emit("loaded", sandboxFiles.files);
|
||||||
|
|
||||||
@ -402,10 +246,10 @@ io.on("connection", async (socket) => {
|
|||||||
file.data = body;
|
file.data = body;
|
||||||
|
|
||||||
await containers[data.sandboxId].files.write(
|
await containers[data.sandboxId].files.write(
|
||||||
path.join(dirName, file.id),
|
path.posix.join(dirName, file.id),
|
||||||
body
|
body
|
||||||
);
|
);
|
||||||
fixPermissions(projectDirectory);
|
fixPermissions();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Error saving file:", e);
|
console.error("Error saving file:", e);
|
||||||
io.emit("error", `Error: file saving. ${e.message ?? e}`);
|
io.emit("error", `Error: file saving. ${e.message ?? e}`);
|
||||||
@ -424,10 +268,10 @@ io.on("connection", async (socket) => {
|
|||||||
|
|
||||||
await moveFile(
|
await moveFile(
|
||||||
containers[data.sandboxId].files,
|
containers[data.sandboxId].files,
|
||||||
path.join(dirName, fileId),
|
path.posix.join(dirName, fileId),
|
||||||
path.join(dirName, newFileId)
|
path.posix.join(dirName, newFileId)
|
||||||
);
|
);
|
||||||
fixPermissions(projectDirectory);
|
fixPermissions();
|
||||||
|
|
||||||
file.id = newFileId;
|
file.id = newFileId;
|
||||||
|
|
||||||
@ -517,10 +361,10 @@ io.on("connection", async (socket) => {
|
|||||||
const id = `projects/${data.sandboxId}/${name}`;
|
const id = `projects/${data.sandboxId}/${name}`;
|
||||||
|
|
||||||
await containers[data.sandboxId].files.write(
|
await containers[data.sandboxId].files.write(
|
||||||
path.join(dirName, id),
|
path.posix.join(dirName, id),
|
||||||
""
|
""
|
||||||
);
|
);
|
||||||
fixPermissions(projectDirectory);
|
fixPermissions();
|
||||||
|
|
||||||
sandboxFiles.files.push({
|
sandboxFiles.files.push({
|
||||||
id,
|
id,
|
||||||
@ -554,7 +398,7 @@ io.on("connection", async (socket) => {
|
|||||||
const id = `projects/${data.sandboxId}/${name}`;
|
const id = `projects/${data.sandboxId}/${name}`;
|
||||||
|
|
||||||
await containers[data.sandboxId].files.makeDir(
|
await containers[data.sandboxId].files.makeDir(
|
||||||
path.join(dirName, id)
|
path.posix.join(dirName, id)
|
||||||
);
|
);
|
||||||
|
|
||||||
callback();
|
callback();
|
||||||
@ -583,10 +427,10 @@ io.on("connection", async (socket) => {
|
|||||||
|
|
||||||
await moveFile(
|
await moveFile(
|
||||||
containers[data.sandboxId].files,
|
containers[data.sandboxId].files,
|
||||||
path.join(dirName, fileId),
|
path.posix.join(dirName, fileId),
|
||||||
path.join(dirName, newFileId)
|
path.posix.join(dirName, newFileId)
|
||||||
);
|
);
|
||||||
fixPermissions(projectDirectory);
|
fixPermissions();
|
||||||
await renameFile(fileId, newFileId, file.data);
|
await renameFile(fileId, newFileId, file.data);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Error renaming folder:", e);
|
console.error("Error renaming folder:", e);
|
||||||
@ -606,7 +450,7 @@ io.on("connection", async (socket) => {
|
|||||||
if (!file) return;
|
if (!file) return;
|
||||||
|
|
||||||
await containers[data.sandboxId].files.remove(
|
await containers[data.sandboxId].files.remove(
|
||||||
path.join(dirName, fileId)
|
path.posix.join(dirName, fileId)
|
||||||
);
|
);
|
||||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||||
(f) => f.id !== fileId
|
(f) => f.id !== fileId
|
||||||
@ -633,7 +477,7 @@ io.on("connection", async (socket) => {
|
|||||||
await Promise.all(
|
await Promise.all(
|
||||||
files.map(async (file) => {
|
files.map(async (file) => {
|
||||||
await containers[data.sandboxId].files.remove(
|
await containers[data.sandboxId].files.remove(
|
||||||
path.join(dirName, file)
|
path.posix.join(dirName, file)
|
||||||
);
|
);
|
||||||
|
|
||||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||||
@ -688,9 +532,15 @@ io.on("connection", async (socket) => {
|
|||||||
rows: 20,
|
rows: 20,
|
||||||
//onExit: () => console.log("Terminal exited", id),
|
//onExit: () => console.log("Terminal exited", id),
|
||||||
});
|
});
|
||||||
await terminals[id].sendData(
|
|
||||||
`cd "${path.join(dirName, "projects", data.sandboxId)}"\rexport PS1='user> '\rclear\r`
|
const defaultDirectory = path.posix.join(dirName, "projects", data.sandboxId);
|
||||||
);
|
const defaultCommands = [
|
||||||
|
`cd "${defaultDirectory}"`,
|
||||||
|
"export PS1='user> '",
|
||||||
|
"clear"
|
||||||
|
]
|
||||||
|
for (const command of defaultCommands) await terminals[id].sendData(command + "\r");
|
||||||
|
|
||||||
console.log("Created terminal", id);
|
console.log("Created terminal", id);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error(`Error creating terminal ${id}:`, e);
|
console.error(`Error creating terminal ${id}:`, e);
|
||||||
@ -725,7 +575,7 @@ io.on("connection", async (socket) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
terminals[id].sendData(data);
|
await terminals[id].sendData(data);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error("Error writing to terminal:", e);
|
console.error("Error writing to terminal:", e);
|
||||||
io.emit("error", `Error: writing to terminal. ${e.message ?? e}`);
|
io.emit("error", `Error: writing to terminal. ${e.message ?? e}`);
|
||||||
|
@ -6,6 +6,7 @@ import { notFound, redirect } from "next/navigation"
|
|||||||
import Loading from "@/components/editor/loading"
|
import Loading from "@/components/editor/loading"
|
||||||
import dynamic from "next/dynamic"
|
import dynamic from "next/dynamic"
|
||||||
import fs from "fs"
|
import fs from "fs"
|
||||||
|
import { TerminalProvider } from "@/context/TerminalContext"
|
||||||
|
|
||||||
export const revalidate = 0
|
export const revalidate = 0
|
||||||
|
|
||||||
@ -87,8 +88,10 @@ 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>
|
||||||
<Navbar userData={userData} sandboxData={sandboxData} shared={shared} />
|
<Navbar userData={userData} sandboxData={sandboxData} shared={shared} />
|
||||||
<div className="w-screen flex grow">
|
<div className="w-screen flex grow">
|
||||||
<CodeEditor
|
<CodeEditor
|
||||||
@ -96,7 +99,9 @@ export default async function CodePage({ params }: { params: { id: string } }) {
|
|||||||
sandboxData={sandboxData}
|
sandboxData={sandboxData}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</TerminalProvider>
|
||||||
</Room>
|
</Room>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ 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';
|
|
||||||
import { PreviewProvider } from "@/context/PreviewContext";
|
import { PreviewProvider } from "@/context/PreviewContext";
|
||||||
import { SocketProvider } from '@/context/SocketContext'
|
import { SocketProvider } from '@/context/SocketContext'
|
||||||
|
|
||||||
@ -32,9 +31,7 @@ export default function RootLayout({
|
|||||||
>
|
>
|
||||||
<SocketProvider>
|
<SocketProvider>
|
||||||
<PreviewProvider>
|
<PreviewProvider>
|
||||||
<TerminalProvider>
|
|
||||||
{children}
|
{children}
|
||||||
</TerminalProvider>
|
|
||||||
</PreviewProvider>
|
</PreviewProvider>
|
||||||
</SocketProvider>
|
</SocketProvider>
|
||||||
<Analytics />
|
<Analytics />
|
||||||
|
@ -51,7 +51,7 @@ export default function Dashboard({
|
|||||||
|
|
||||||
useEffect(() => { // update the dashboard to show a new project
|
useEffect(() => { // update the dashboard to show a new project
|
||||||
router.refresh()
|
router.refresh()
|
||||||
}, [sandboxes])
|
}, [])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
@ -70,6 +70,8 @@ export default function CodeEditor({
|
|||||||
const [activeFileId, setActiveFileId] = useState<string>("")
|
const [activeFileId, setActiveFileId] = useState<string>("")
|
||||||
const [activeFileContent, setActiveFileContent] = useState("")
|
const [activeFileContent, setActiveFileContent] = useState("")
|
||||||
const [deletingFolderId, setDeletingFolderId] = useState("")
|
const [deletingFolderId, setDeletingFolderId] = useState("")
|
||||||
|
// Added this state to track the most recent content for each file
|
||||||
|
const [fileContents, setFileContents] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
// Editor state
|
// Editor state
|
||||||
const [editorLanguage, setEditorLanguage] = useState("plaintext")
|
const [editorLanguage, setEditorLanguage] = useState("plaintext")
|
||||||
@ -257,6 +259,7 @@ export default function CodeEditor({
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}, [editorRef])
|
}, [editorRef])
|
||||||
|
|
||||||
// Generate widget effect
|
// Generate widget effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (generate.show) {
|
if (generate.show) {
|
||||||
@ -335,6 +338,7 @@ export default function CodeEditor({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [generate.show])
|
}, [generate.show])
|
||||||
|
|
||||||
// Suggestion widget effect
|
// Suggestion widget effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!suggestionRef.current || !editorRef) return
|
if (!suggestionRef.current || !editorRef) return
|
||||||
@ -378,12 +382,21 @@ export default function CodeEditor({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const model = editorRef?.getModel()
|
const model = editorRef?.getModel()
|
||||||
const line = model?.getLineContent(cursorLine)
|
// added this because it was giving client side exception - Illegal value for lineNumber when opening an empty file
|
||||||
|
if (model) {
|
||||||
if (line === undefined || line.trim() !== "") {
|
const totalLines = model.getLineCount();
|
||||||
decorations.instance?.clear()
|
// Check if the cursorLine is a valid number, If cursorLine is out of bounds, we fall back to 1 (the first line) as a default safe value.
|
||||||
|
const lineNumber = cursorLine > 0 && cursorLine <= totalLines ? cursorLine : 1; // fallback to a valid line number
|
||||||
|
// If for some reason the content doesn't exist, we use an empty string as a fallback.
|
||||||
|
const line = model.getLineContent(lineNumber) ?? "";
|
||||||
|
// Check if the line is not empty or only whitespace (i.e., `.trim()` removes spaces).
|
||||||
|
// If the line has content, we clear any decorations using the instance of the `decorations` object.
|
||||||
|
// Decorations refer to editor highlights, underlines, or markers, so this clears those if conditions are met.
|
||||||
|
if (line.trim() !== "") {
|
||||||
|
decorations.instance?.clear();
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (decorations.instance) {
|
if (decorations.instance) {
|
||||||
decorations.instance.set(decorations.options)
|
decorations.instance.set(decorations.options)
|
||||||
@ -401,25 +414,33 @@ export default function CodeEditor({
|
|||||||
}, [decorations.options])
|
}, [decorations.options])
|
||||||
|
|
||||||
// Save file keybinding logic effect
|
// Save file keybinding logic effect
|
||||||
|
// Function to save the file content after a debounce period
|
||||||
const debouncedSaveData = useCallback(
|
const debouncedSaveData = useCallback(
|
||||||
debounce((value: string | undefined, activeFileId: string | undefined) => {
|
debounce((activeFileId: string | undefined) => {
|
||||||
|
if (activeFileId) {
|
||||||
|
// Get the current content of the file
|
||||||
|
const content = fileContents[activeFileId];
|
||||||
|
|
||||||
|
// Mark the file as saved in the tabs
|
||||||
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...${activeFileId}`);
|
||||||
console.log(`Saving file...${value}`)
|
console.log(`Saving file...${content}`);
|
||||||
socket?.emit("saveFile", activeFileId, value)
|
socket?.emit("saveFile", activeFileId, content);
|
||||||
|
}
|
||||||
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000),
|
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000),
|
||||||
[socket]
|
[socket, fileContents]
|
||||||
)
|
);
|
||||||
|
|
||||||
|
// Keydown event listener to trigger file save on Ctrl+S or Cmd+S
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const down = (e: KeyboardEvent) => {
|
const down = (e: KeyboardEvent) => {
|
||||||
if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
|
if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
debouncedSaveData(editorRef?.getValue(), activeFileId)
|
debouncedSaveData(activeFileId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
document.addEventListener("keydown", down)
|
document.addEventListener("keydown", down)
|
||||||
@ -586,31 +607,46 @@ export default function CodeEditor({
|
|||||||
} // 300ms debounce delay, adjust as needed
|
} // 300ms debounce delay, adjust as needed
|
||||||
|
|
||||||
const selectFile = (tab: TTab) => {
|
const selectFile = (tab: TTab) => {
|
||||||
if (tab.id === activeFileId) return
|
if (tab.id === activeFileId) return;
|
||||||
|
|
||||||
setGenerate((prev) => ({ ...prev, show: false }))
|
setGenerate((prev) => ({ ...prev, show: false }));
|
||||||
|
|
||||||
const exists = tabs.find((t) => t.id === tab.id)
|
// Check if the tab already exists in the list of open tabs
|
||||||
|
const exists = tabs.find((t) => t.id === tab.id);
|
||||||
setTabs((prev) => {
|
setTabs((prev) => {
|
||||||
if (exists) {
|
if (exists) {
|
||||||
setActiveFileId(exists.id)
|
// If the tab exists, make it the active tab
|
||||||
return prev
|
setActiveFileId(exists.id);
|
||||||
|
return prev;
|
||||||
}
|
}
|
||||||
return [...prev, tab]
|
// If the tab doesn't exist, add it to the list of tabs and make it active
|
||||||
})
|
return [...prev, tab];
|
||||||
|
});
|
||||||
|
|
||||||
if (fileCache.current.has(tab.id)) {
|
// If the file's content is already cached, set it as the active content
|
||||||
setActiveFileContent(fileCache.current.get(tab.id))
|
if (fileContents[tab.id]) {
|
||||||
|
setActiveFileContent(fileContents[tab.id]);
|
||||||
} else {
|
} else {
|
||||||
debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
|
// Otherwise, fetch the content of the file and cache it
|
||||||
fileCache.current.set(tab.id, response)
|
debouncedGetFile(tab.id, (response: string) => {
|
||||||
setActiveFileContent(response)
|
setFileContents(prev => ({ ...prev, [tab.id]: response }));
|
||||||
})
|
setActiveFileContent(response);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setEditorLanguage(processFileType(tab.name))
|
// Set the editor language based on the file type
|
||||||
setActiveFileId(tab.id)
|
setEditorLanguage(processFileType(tab.name));
|
||||||
|
// Set the active file ID to the new tab
|
||||||
|
setActiveFileId(tab.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Added this effect to update fileContents when the editor content changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeFileId) {
|
||||||
|
// Cache the current active file content using the file ID as the key
|
||||||
|
setFileContents(prev => ({ ...prev, [activeFileId]: activeFileContent }));
|
||||||
}
|
}
|
||||||
|
}, [activeFileContent, activeFileId]);
|
||||||
|
|
||||||
// Close tab and remove from tabs
|
// Close tab and remove from tabs
|
||||||
const closeTab = (id: string) => {
|
const closeTab = (id: string) => {
|
||||||
@ -896,15 +932,10 @@ export default function CodeEditor({
|
|||||||
beforeMount={handleEditorWillMount}
|
beforeMount={handleEditorWillMount}
|
||||||
onMount={handleEditorMount}
|
onMount={handleEditorMount}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
if (value === activeFileContent) {
|
// If the new content is different from the cached content, update it
|
||||||
setTabs((prev) =>
|
if (value !== fileContents[activeFileId]) {
|
||||||
prev.map((tab) =>
|
setActiveFileContent(value ?? ""); // Update the active file content
|
||||||
tab.id === activeFileId
|
// Mark the file as unsaved by setting 'saved' to false
|
||||||
? { ...tab, saved: true }
|
|
||||||
: tab
|
|
||||||
)
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
setTabs((prev) =>
|
setTabs((prev) =>
|
||||||
prev.map((tab) =>
|
prev.map((tab) =>
|
||||||
tab.id === activeFileId
|
tab.id === activeFileId
|
||||||
@ -912,6 +943,15 @@ export default function CodeEditor({
|
|||||||
: tab
|
: tab
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
} else {
|
||||||
|
// If the content matches the cached content, mark the file as saved
|
||||||
|
setTabs((prev) =>
|
||||||
|
prev.map((tab) =>
|
||||||
|
tab.id === activeFileId
|
||||||
|
? { ...tab, saved: true }
|
||||||
|
: tab
|
||||||
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
options={{
|
options={{
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import React, { useEffect, useRef } from 'react';
|
||||||
import { Play, StopCircle } from "lucide-react";
|
import { Play, StopCircle } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useTerminal } from "@/context/TerminalContext";
|
import { useTerminal } from "@/context/TerminalContext";
|
||||||
@ -16,53 +17,57 @@ export default function RunButtonModal({
|
|||||||
setIsRunning: (running: boolean) => void;
|
setIsRunning: (running: boolean) => void;
|
||||||
sandboxData: Sandbox;
|
sandboxData: Sandbox;
|
||||||
}) {
|
}) {
|
||||||
const { createNewTerminal, terminals, closeTerminal } = useTerminal();
|
const { createNewTerminal, closeTerminal, terminals } = useTerminal();
|
||||||
const { setIsPreviewCollapsed, previewPanelRef } = usePreview();
|
const { setIsPreviewCollapsed, previewPanelRef } = usePreview();
|
||||||
|
// Ref to keep track of the last created terminal's ID
|
||||||
|
const lastCreatedTerminalRef = useRef<string | null>(null);
|
||||||
|
|
||||||
const handleRun = () => {
|
// Effect to update the lastCreatedTerminalRef when a new terminal is added
|
||||||
if (isRunning) {
|
useEffect(() => {
|
||||||
console.log('Stopping sandbox...');
|
if (terminals.length > 0 && !isRunning) {
|
||||||
console.log('Closing Preview Window');
|
const latestTerminal = terminals[terminals.length - 1];
|
||||||
|
if (latestTerminal && latestTerminal.id !== lastCreatedTerminalRef.current) {
|
||||||
terminals.forEach(term => {
|
lastCreatedTerminalRef.current = latestTerminal.id;
|
||||||
if (term.terminal) {
|
|
||||||
closeTerminal(term.id);
|
|
||||||
console.log('Closing Terminal', term.id);
|
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
}, [terminals, isRunning]);
|
||||||
|
|
||||||
|
const handleRun = async () => {
|
||||||
|
if (isRunning && lastCreatedTerminalRef.current)
|
||||||
|
{
|
||||||
|
await closeTerminal(lastCreatedTerminalRef.current);
|
||||||
|
lastCreatedTerminalRef.current = null;
|
||||||
setIsPreviewCollapsed(true);
|
setIsPreviewCollapsed(true);
|
||||||
previewPanelRef.current?.collapse();
|
previewPanelRef.current?.collapse();
|
||||||
} else {
|
|
||||||
console.log('Running sandbox...');
|
|
||||||
console.log('Opening Terminal');
|
|
||||||
console.log('Opening Preview Window');
|
|
||||||
|
|
||||||
if (terminals.length < 4) {
|
|
||||||
if (sandboxData.type === "streamlit") {
|
|
||||||
createNewTerminal(
|
|
||||||
"pip install -r requirements.txt && streamlit run main.py --server.runOnSave true"
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
createNewTerminal("yarn install && yarn dev");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
toast.error("You reached the maximum # of terminals.");
|
|
||||||
console.error("Maximum number of terminals reached.");
|
|
||||||
}
|
}
|
||||||
|
else if (!isRunning && terminals.length < 4)
|
||||||
|
{
|
||||||
|
const command = sandboxData.type === "streamlit"
|
||||||
|
? "pip install -r requirements.txt && streamlit run main.py --server.runOnSave true"
|
||||||
|
: "yarn install && yarn dev";
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Create a new terminal with the appropriate command
|
||||||
|
await createNewTerminal(command);
|
||||||
setIsPreviewCollapsed(false);
|
setIsPreviewCollapsed(false);
|
||||||
previewPanelRef.current?.expand();
|
previewPanelRef.current?.expand();
|
||||||
|
} catch (error) {
|
||||||
|
toast.error("Failed to create new terminal.");
|
||||||
|
console.error("Error creating new terminal:", error);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
} else if (!isRunning) {
|
||||||
|
toast.error("You've reached the maximum number of terminals.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setIsRunning(!isRunning);
|
setIsRunning(!isRunning);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
<Button variant="outline" onClick={handleRun}>
|
<Button variant="outline" onClick={handleRun}>
|
||||||
{isRunning ? <StopCircle className="w-4 h-4 mr-2" /> : <Play className="w-4 h-4 mr-2" />}
|
{isRunning ? <StopCircle className="w-4 h-4 mr-2" /> : <Play className="w-4 h-4 mr-2" />}
|
||||||
{isRunning ? 'Stop' : 'Run'}
|
{isRunning ? 'Stop' : 'Run'}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
Reference in New Issue
Block a user