Skip to content

SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]

Web feat: Kill running computation

Kilian Lieret48405e6b30f1
diff --git a/sweagent/frontend/src/App.js b/sweagent/frontend/src/App.js
index ae6dd331..983e78b9 100644
--- a/sweagent/frontend/src/App.js
+++ b/sweagent/frontend/src/App.js
@@ -10,7 +10,6 @@ const socket = io(url);
function App() {
const [dataPath, setDataPath] = useState('https://github.com/klieret/swe-agent-test-repo/issues/1');
const [testRun, setTestRun] = useState(true);
- const [responseMessage, setResponseMessage] = useState('');
const [agentFeed, setAgentFeed] = useState([]);
const [envFeed, setEnvFeed] = useState([]);
const [highlightedStep, setHighlightedStep] = useState(null);
@@ -29,15 +28,24 @@ function App() {
const handleSubmit = async (event) => {
event.preventDefault();
try {
- const response = await axios.get(`/run`, { params: { data_path: dataPath, test_run: testRun } });
- setResponseMessage(response.data);
setAgentFeed([]); // Clear the agent feed messages
setEnvFeed([]); // Clear the environment feed messages
+ await axios.get(`/run`, { params: { data_path: dataPath, test_run: testRun } });
} catch (error) {
console.error('Error:', error);
}
};
+
+ const handleStop = async () => {
+ try {
+ const response = await axios.get('/stop');
+ console.log(response.data);
+ } catch (error) {
+ console.error('Error stopping:', error);
+ }
+};
+
// Use effect to listen to socket updates
React.useEffect(() => {
const handleUpdate = (data) => {
@@ -62,7 +70,7 @@ function App() {
<input type="checkbox" checked={testRun} onChange={(e) => setTestRun(e.target.checked)} />
<button type="submit">Run</button>
</form>
- <div>{responseMessage}</div>
+ <button onClick={handleStop}>Stop Computation</button>
<h2>Trajectory</h2>
<div id="container">
<Feed feed={agentFeed} highlightedStep={highlightedStep} handleMouseEnter={handleMouseEnter} selfRef={agentFeedRef} otherRef={envFeedRef} title="Agent Feed" />
diff --git a/sweagent/web/server.py b/sweagent/web/server.py
index 48146fe9..0916f3bb 100644
--- a/sweagent/web/server.py
+++ b/sweagent/web/server.py
@@ -1,5 +1,7 @@
+import ctypes
+import inspect
import os
-from typing import Optional
+from typing import Dict, Optional
from flask import Flask, render_template, request, make_response
import threading
import sys
@@ -11,6 +13,8 @@ from sweagent.environment.swe_env import EnvironmentArguments
import sweagent.environment.utils as env_utils
from flask_socketio import SocketIO
from flask_cors import CORS
+from flask import session
+from uuid import uuid4
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
@@ -20,6 +24,7 @@ app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins='*')
+THREADS: Dict[str, "MainThread"] = {}
@app.route('/')
def index():
@@ -33,10 +38,12 @@ def handle_connect():
class WebUpdate:
+ """This class talks to socketio. It's pretty much a wrapper around socketio.emit.
+ """
def _emit(self, event, data):
+ """Directly wrap around socketio.emit"""
socketio.emit(event, data)
-
def up_agent(
self,
message: str,
@@ -44,6 +51,7 @@ class WebUpdate:
format: str = "markdown",
thought_idx: Optional[int] =None,
):
+ """Update the agent feed"""
self._emit('update', {'feed': 'agent', 'title': title, 'message': message, 'format': format, 'thought_idx': thought_idx})
def up_env(
@@ -53,12 +61,14 @@ class WebUpdate:
title="",
thought_idx: Optional[int] =None,
):
+ """Update the environment feed"""
self._emit('update', {'feed': 'env', 'title': title, 'message': message, 'format': format, 'thought_idx': thought_idx})
class MainUpdateHook(MainHook):
def __init__(self, wu: WebUpdate):
+ """This hooks into the Main class to update the web interface"""
self._wu = wu
def on_start(self):
@@ -73,6 +83,7 @@ class MainUpdateHook(MainHook):
class AgentUpdateHook(AgentHook):
def __init__(self, wu: WebUpdate):
+ """This hooks into the Agent class to update the web interface"""
self._wu = wu
self._sub_action = None
self._thought_idx = 0
@@ -113,8 +124,110 @@ class AgentUpdateHook(AgentHook):
return self._wu.up_agent(title="Demo", message=content, thought_idx=self._thought_idx + 1)
self._wu.up_agent(title="Query", message=content, thought_idx=self._thought_idx + 1)
+
+def ensure_session_id_set():
+ """Ensures a session ID is set for this user"""
+ session_id = session.get('session_id', None)
+ if not session_id:
+ session_id = uuid4().hex
+ session['session_id'] = session_id
+ return session_id
+
+
+
+def _async_raise(tid, exctype):
+ '''Raises an exception in the threads with id tid
+
+ This code is modified from the following SO answer:
+ Author: Philippe F
+ Posted: Nov 28, 2008
+ URL: https://stackoverflow.com/a/325528/
+ '''
+ if not inspect.isclass(exctype):
+ raise TypeError("Only types can be raised (not instances)")
+ res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
+ ctypes.py_object(exctype))
+ if res == 0:
+ raise ValueError("invalid thread id")
+ elif res != 1:
+ # "if it returns a number greater than one, you're in trouble,
+ # and you should call it again with exc=NULL to revert the effect"
+ ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
+ raise SystemError("PyThreadState_SetAsyncExc failed")
+
+
+class ThreadWithExc(threading.Thread):
+ '''A thread class that supports raising an exception in the thread from
+ another thread.
+
+ This code is modified from the following SO answer:
+ Author: Philippe F
+ Posted: Nov 28, 2008
+ URL: https://stackoverflow.com/a/325528/
+ '''
+ def _get_my_tid(self):
+ """determines this (self's) thread id
+
+ CAREFUL: this function is executed in the context of the caller
+ thread, to get the identity of the thread represented by this
+ instance.
+ """
+ if not self.is_alive():
+ raise threading.ThreadError("the thread is not active")
+
+ # do we have it cached?
+ if hasattr(self, "_thread_id"):
+ return self._thread_id
+
+ # no, look for it in the _active dict
+ for tid, tobj in threading._active.items():
+ if tobj is self:
+ self._thread_id = tid
+ return tid
+
+ raise RuntimeError("could not determine the thread's id")
+
+ def raise_exc(self, exctype):
+ """Raises the given exception type in the context of this thread.
+
+ If the thread is busy in a system call (time.sleep(),
+ socket.accept(), ...), the exception is simply ignored.
+
+ If you are sure that your exception should terminate the thread,
+ one way to ensure that it works is:
+
+ t = ThreadWithExc( ... )
+ ...
+ t.raise_exc( SomeException )
+ while t.isAlive():
+ time.sleep( 0.1 )
+ t.raise_exc( SomeException )
+
+ If the exception is to be caught by the thread, you need a way to
+ check that your thread has caught it.
+
+ CAREFUL: this function is executed in the context of the
+ caller thread, to raise an exception in the context of the
+ thread represented by this instance.
+ """
+ _async_raise( self._get_my_tid(), exctype )
+
+
+class MainThread(ThreadWithExc):
+ def __init__(self, main: Main):
+ super().__init__()
+ self._main = main
+
+ def run(self) -> None:
+ self._main.main()
+
+ def stop(self):
+ self.raise_exc(SystemExit)
+
+
@app.route('/run', methods=['GET', 'OPTIONS'])
def run():
+ session_id = ensure_session_id_set()
if request.method == "OPTIONS": # CORS preflight
return _build_cors_preflight_response()
data_path = request.args["data_path"]
@@ -151,10 +264,29 @@ def run():
wu = WebUpdate()
main.add_hook(MainUpdateHook(wu))
main.agent.add_hook(AgentUpdateHook(wu))
- thread = threading.Thread(target=main.main)
+ thread = MainThread(main)
+ global THREADS
+ THREADS[session_id] = thread
+ print("||||||||||||||||||||||||||||||||||||||||||||||")
+ print(f"Starting session {session_id} with {thread}")
+ print("||||||||||||||||||||||||||||||||||||||||||||||")
thread.start()
return 'Commands are being executed', 202
+def stop():
+ session_id = ensure_session_id_set()
+ global THREADS
+ print(f"Stopping session {session_id}")
+ print(THREADS)
+ thread = THREADS.get(session_id)
+ if thread and thread.is_alive():
+ print(f"Thread {thread} is alive")
+ thread.stop()
+ else:
+ print(f"Thread {thread} is not alive")
+ return 'Stopping computation', 202
+
def _build_cors_preflight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
@@ -163,4 +295,6 @@ def _build_cors_preflight_response():
return response
if __name__ == "__main__":
+ # fixme:
+ app.secret_key = 'super secret key'
socketio.run(app, port=5000, debug=True)
\ No newline at end of file