-
Notifications
You must be signed in to change notification settings - Fork 1
Add JavaScript runtime with eval-based execution and interrupt via worker termination #91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
7cd8b2a
Initial plan
Copilot f0b2004
Add JavaScript runtime implementation
Copilot 6d2a86f
Fix interrupt implementation to properly wait for worker restart
Copilot dc2e3d2
Improve error handling in JavaScript runtime
Copilot 6b0ede3
Add JavaScript syntax highlighting support
Copilot 4730d8a
Fix JavaScript worker to use direct eval for state persistence
Copilot d3dd4f4
Fix code review issues: prevent infinite recursion and add timeout to…
Copilot bdfa2a1
Address PR feedback: fix payload types, move executedCommands to runt…
Copilot 35244c8
consoleとinterruptを修正
na-trium-144 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| "use client"; | ||
|
|
||
| import { EditorComponent } from "../editor"; | ||
| import { ReplTerminal } from "../repl"; | ||
|
|
||
| export default function JavaScriptPage() { | ||
| return ( | ||
| <div className="p-4 flex flex-col gap-4"> | ||
| <ReplTerminal | ||
| terminalId="" | ||
| language="javascript" | ||
| initContent={"> console.log('hello, world!')\nhello, world!"} | ||
| /> | ||
| <EditorComponent | ||
| language="javascript" | ||
| filename="main.js" | ||
| initContent="console.log('hello, world!');" | ||
| /> | ||
| </div> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| "use client"; | ||
|
|
||
| import { | ||
| useState, | ||
| useRef, | ||
| useCallback, | ||
| ReactNode, | ||
| createContext, | ||
| useContext, | ||
| useEffect, | ||
| } from "react"; | ||
| import { SyntaxStatus, ReplOutput, ReplCommand } from "../repl"; | ||
| import { Mutex, MutexInterface } from "async-mutex"; | ||
| import { RuntimeContext } from "../runtime"; | ||
|
|
||
| const JavaScriptContext = createContext<RuntimeContext>(null!); | ||
|
|
||
| export function useJavaScript(): RuntimeContext { | ||
| const context = useContext(JavaScriptContext); | ||
| if (!context) { | ||
| throw new Error("useJavaScript must be used within a JavaScriptProvider"); | ||
| } | ||
| return context; | ||
| } | ||
|
|
||
| type MessageToWorker = | ||
| | { | ||
| type: "init"; | ||
| payload?: undefined; | ||
| } | ||
| | { | ||
| type: "runJavaScript"; | ||
| payload: { code: string }; | ||
| } | ||
| | { | ||
| type: "checkSyntax"; | ||
| payload: { code: string }; | ||
| } | ||
| | { | ||
| type: "restoreState"; | ||
| payload: { commands: string[] }; | ||
| }; | ||
|
|
||
| type MessageFromWorker = | ||
| | { id: number; payload: unknown } | ||
| | { id: number; error: string }; | ||
|
|
||
| type InitPayloadFromWorker = { success: boolean }; | ||
| type RunPayloadFromWorker = { | ||
| output: ReplOutput[]; | ||
| updatedFiles: [string, string][]; | ||
| }; | ||
| type StatusPayloadFromWorker = { status: SyntaxStatus }; | ||
|
|
||
| export function JavaScriptProvider({ children }: { children: ReactNode }) { | ||
| const workerRef = useRef<Worker | null>(null); | ||
| const [ready, setReady] = useState<boolean>(false); | ||
| const mutex = useRef<MutexInterface>(new Mutex()); | ||
| const messageCallbacks = useRef< | ||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| Map<number, [(payload: any) => void, (error: string) => void]> | ||
| >(new Map()); | ||
| const nextMessageId = useRef<number>(0); | ||
| const executedCommands = useRef<string[]>([]); | ||
|
|
||
| function postMessage<T>({ type, payload }: MessageToWorker) { | ||
| const id = nextMessageId.current++; | ||
| return new Promise<T>((resolve, reject) => { | ||
| messageCallbacks.current.set(id, [resolve, reject]); | ||
| workerRef.current?.postMessage({ id, type, payload }); | ||
| }); | ||
| } | ||
|
|
||
| const initializeWorker = useCallback(() => { | ||
| const worker = new Worker("/javascript.worker.js"); | ||
| workerRef.current = worker; | ||
|
|
||
| worker.onmessage = (event) => { | ||
| const data = event.data as MessageFromWorker; | ||
| if (messageCallbacks.current.has(data.id)) { | ||
| const [resolve, reject] = messageCallbacks.current.get(data.id)!; | ||
| if ("error" in data) { | ||
| reject(data.error); | ||
| } else { | ||
| resolve(data.payload); | ||
| } | ||
| messageCallbacks.current.delete(data.id); | ||
| } | ||
| }; | ||
|
|
||
| return postMessage<InitPayloadFromWorker>({ | ||
| type: "init", | ||
| }).then(({ success }) => { | ||
| if (success) { | ||
| setReady(true); | ||
| } | ||
| return worker; | ||
| }); | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| let worker: Worker | null = null; | ||
| initializeWorker().then((w) => { | ||
| worker = w; | ||
| }); | ||
|
|
||
| return () => { | ||
| worker?.terminate(); | ||
| }; | ||
| }, [initializeWorker]); | ||
|
|
||
| const interrupt = useCallback(() => { | ||
| // Since we can't interrupt JavaScript execution directly, | ||
| // we terminate the worker and restart it, then restore state | ||
|
|
||
| // Reject all pending callbacks before terminating | ||
| const error = "Worker interrupted"; | ||
| messageCallbacks.current.forEach(([, reject]) => reject(error)); | ||
| messageCallbacks.current.clear(); | ||
|
|
||
| // Terminate the current worker | ||
| workerRef.current?.terminate(); | ||
|
|
||
| // Reset ready state | ||
| setReady(false); | ||
|
|
||
| mutex.current.runExclusive(async () => { | ||
| // Create a new worker and wait for it to be ready | ||
| await initializeWorker(); | ||
|
|
||
| // Restore state by re-executing previous commands | ||
| if (executedCommands.current.length > 0) { | ||
| await postMessage<{ success: boolean }>({ | ||
| type: "restoreState", | ||
| payload: { commands: executedCommands.current }, | ||
| }); | ||
| } | ||
| }); | ||
| }, [initializeWorker]); | ||
|
|
||
| const runCommand = useCallback( | ||
| async (code: string): Promise<ReplOutput[]> => { | ||
| if (!mutex.current.isLocked()) { | ||
| throw new Error( | ||
| "mutex of JavaScriptContext must be locked for runCommand" | ||
| ); | ||
| } | ||
| if (!workerRef.current || !ready) { | ||
| return [{ type: "error", message: "JavaScript runtime is not ready yet." }]; | ||
| } | ||
|
|
||
| try { | ||
| const { output } = await postMessage<RunPayloadFromWorker>({ | ||
| type: "runJavaScript", | ||
| payload: { code }, | ||
| }); | ||
| // Save successfully executed command | ||
| executedCommands.current.push(code); | ||
| return output; | ||
| } catch (error) { | ||
| // Handle errors (including "Worker interrupted") | ||
| if (error instanceof Error) { | ||
| return [{ type: "error", message: error.message }]; | ||
| } | ||
| return [{ type: "error", message: String(error) }]; | ||
| } | ||
| }, | ||
| [ready] | ||
| ); | ||
|
|
||
| const checkSyntax = useCallback( | ||
| async (code: string): Promise<SyntaxStatus> => { | ||
| if (!workerRef.current || !ready) return "invalid"; | ||
| const { status } = await mutex.current.runExclusive(() => | ||
| postMessage<StatusPayloadFromWorker>({ | ||
| type: "checkSyntax", | ||
| payload: { code }, | ||
| }) | ||
| ); | ||
| return status; | ||
| }, | ||
| [ready] | ||
| ); | ||
|
|
||
| const runFiles = useCallback( | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| async (_filenames: string[]): Promise<ReplOutput[]> => { | ||
| return [ | ||
| { | ||
| type: "error", | ||
| message: "JavaScript file execution is not supported in this runtime", | ||
| }, | ||
| ]; | ||
| }, | ||
| [] | ||
| ); | ||
|
|
||
| const splitReplExamples = useCallback((content: string): ReplCommand[] => { | ||
| const initCommands: { command: string; output: ReplOutput[] }[] = []; | ||
| for (const line of content.split("\n")) { | ||
| if (line.startsWith("> ")) { | ||
| // Remove the prompt from the command | ||
| initCommands.push({ command: line.slice(2), output: [] }); | ||
| } else { | ||
| // Lines without prompt are output from the previous command | ||
| if (initCommands.length > 0) { | ||
| initCommands[initCommands.length - 1].output.push({ | ||
| type: "stdout", | ||
| message: line, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| return initCommands; | ||
| }, []); | ||
|
|
||
| const getCommandlineStr = useCallback( | ||
| (filenames: string[]) => `node ${filenames[0]}`, | ||
| [] | ||
| ); | ||
|
|
||
| return ( | ||
| <JavaScriptContext.Provider | ||
| value={{ | ||
| ready, | ||
| runCommand, | ||
| checkSyntax, | ||
| mutex: mutex.current, | ||
| runFiles, | ||
| interrupt, | ||
| splitReplExamples, | ||
| getCommandlineStr, | ||
| }} | ||
| > | ||
| {children} | ||
| </JavaScriptContext.Provider> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@copilot
error: Property 'payload' does not exist on type 'MessageToWorker'.
initとrestorestateメッセージに空のpayloadを追加すると解決すると思います。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in bdfa2a1. Added
payload?: undefinedto init type andpayload: { commands: string[] }to restoreState type.