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]
Update inspector with messages
carlosejimenez867310b357d1
diff --git a/sweagent/inspector/fileViewer.js b/sweagent/inspector/fileViewer.jsindex f7533ffb..6737994c 100644--- a/sweagent/inspector/fileViewer.js+++ b/sweagent/inspector/fileViewer.js@@ -1,20 +1,17 @@-let currentFileName = null; // Store the current file name-let trajectoryDirectory = ""; // Global variable to store the directory-let timeoutIds = []; // Store timeout IDs for pending operations+let currentFileName = null;+let trajectoryDirectory = "";+let timeoutIds = [];function getBaseUrl() {const protocol = window.location.protocol;const host = window.location.hostname;const port = window.location.port;-- // Use the default port if the port number is empty (for standard HTTP/HTTPS)const defaultPort =protocol === "http:" && !port? "80": protocol === "https:" && !port? "443": port;-return `${protocol}//${host}:${defaultPort}`;}@@ -34,26 +31,96 @@ function fetchFiles() {});}-// translate item.role to what we show the user-const roleMap = {- user: "Environment",- assistant: "SWE-Agent",- subroutine: "SWE-Agent subroutine",- default: "Default",- system: "System",- demo: "Demonstration",- model_patch: "Model Patch",-};--function getRoleText(role) {- return roleMap[role] || role;+function createTrajectoryItem(item, index) {+ const elementId = `trajectoryItem${index}`;+ const hasMessages = item.messages && item.messages.length > 0;++ const escapeHtml = (text) => {+ return text+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'");+ };++ const messagesContent = hasMessages+ ? item.messages+ .map((msg, msgIndex) => {+ let content = `----Item ${msgIndex}-----\n`;+ content += `role: ${msg.role}\n`;+ content += `content: |\n${escapeHtml(msg.content)}\n`;++ if (msg.tool_calls && msg.tool_calls.length > 0) {+ msg.tool_calls.forEach((tool, idx) => {+ content += `- tool call ${idx + 1}:\n`;+ if (tool.function) {+ content += ` - name: ${tool.function.name}\n`;+ // Handle arguments based on type+ let args = tool.function.arguments;+ try {+ if (typeof args === "string") {+ args = JSON.parse(args);+ }+ content += ` - arguments: ${JSON.stringify(args, null, 2).replace(/\n/g, "\n ")}\n`;+ } catch (e) {+ content += ` - arguments: ${escapeHtml(String(args))}\n`;+ }+ }+ content += ` - id: ${tool.id}\n`;+ });+ }++ if (msg.is_demo) {+ return `<span class="demo-message">${content}</span>`;+ }+ return content;+ })+ .join("\n")+ : "";++ return `+ <div class="trajectory-item fade-in" id="${elementId}">+ <div class="trajectory-main">+ <div class="response-section" data-title="Response">+ <div class="content-wrapper">+ <pre><code class="language-python">Response:+${escapeHtml(item.response)}++Action:+${escapeHtml(item.action)}</code></pre>+ </div>+ </div>+ <div class="observation-section" data-title="Environment Observation">+ <div class="content-wrapper">+ <pre><code class="language-python">${escapeHtml(item.observation)}</code></pre>+ </div>+ </div>+ ${+ item.execution_time+ ? `<div class="execution-time">Execution time: ${item.execution_time}s</div>`+ : ""+ }+ </div>+ ${+ hasMessages+ ? `+ <div class="messages-section" data-title="Messages">+ <div class="content-wrapper">+ <pre>${messagesContent}</pre>+ </div>+ </div>+ `+ : ""+ }+ </div>+ `;}function viewFile(fileName) {- currentFileName = fileName; // Store the current file name- // Clear any pending message loading from previous files+ currentFileName = fileName;timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));- timeoutIds = []; // Reset the list of timeout IDs+ timeoutIds = [];const baseUrl = getBaseUrl();const showDemos = document.getElementById("showDemos").checked;@@ -67,67 +134,20 @@ function viewFile(fileName) {}).then((content) => {const container = document.getElementById("fileContent");- container.innerHTML = ""; // Clear existing content-- if (content.history && Array.isArray(content.history)) {- let delay = 200; // Initial delay- const delayIncrement = 50; // Delay between each message, in milliseconds-- // Step through the history and add each message to the container- content.history.forEach((item, index) => {- const timeoutId = setTimeout(() => {- let contentText = item.content- ? item.content.replace(/</g, "<").replace(/>/g, ">")- : "";- if (item.tool_calls && item.tool_calls.length > 0) {- contentText = `${item.thought}\n\`\`\`\n${item.action}\n\`\`\``;- }- // Skip demo items if checkbox is unchecked- let roleClass =- item.agent && item.agent !== "primary"- ? "subroutine"- : item.role- ? item.role.toLowerCase().replaceAll(" ", "-")- : "default";- const elementId = "historyItem" + index;- const historyItem = document.createElement("div");- historyItem.className = `history-item ${roleClass} fade-in`;- historyItem.id = elementId;- let isDemo = false;- if (contentText.includes("--- DEMONSTRATION ---")) {- item.role = "demo";- isDemo = true;- } else if ("is_demo" in item && item.is_demo === true) {- item.role += "[demo]";- isDemo = true;- }- if (!showDemos && isDemo) {- return;- }- historyItem.innerHTML = `- <div class="role-bar ${roleClass}">- <strong>- <span>${getRoleText(item.role)}</span>- </strong>- </div>- <div class="content-container">- <pre><code class="language-python">${contentText}</code></pre>- </div>- <div class="shadow"></div>- `;- container.appendChild(historyItem);-- // Highlight the code after adding it to the DOM- historyItem.querySelectorAll("pre code").forEach((block) => {- hljs.highlightElement(block);- });- }, delay);+ container.innerHTML = "";++ if (content.trajectory && Array.isArray(content.trajectory)) {+ content.trajectory.forEach((item, index) => {+ container.innerHTML += createTrajectoryItem(item, index);- delay += delayIncrement; // Increment delay for the next message- timeoutIds.push(timeoutId); // Store the timeout ID+ // Highlight code blocks after adding them+ const newItem = document.getElementById(`trajectoryItem${index}`);+ newItem.querySelectorAll("pre code").forEach((block) => {+ hljs.highlightElement(block);+ });});} else {- container.textContent = "No history content found.";+ container.textContent = "No trajectory content found.";}}).catch((error) => {@@ -136,7 +156,7 @@ function viewFile(fileName) {"Error loading content. " + error;});- // Highlight the selected file in the list+ // Highlight selected filedocument.querySelectorAll("#fileList li").forEach((li) => {li.classList.remove("selected");if (li.textContent.split(" ")[0] === fileName) {@@ -149,8 +169,7 @@ function refreshCurrentFile() {if (currentFileName) {const currentScrollPosition =document.documentElement.scrollTop || document.body.scrollTop;- viewFile(currentFileName.split(" ")[0]); // Reload the current file- // Restore the scroll position after the content is loaded+ viewFile(currentFileName.split(" ")[0]);setTimeout(() => {window.scrollTo(0, currentScrollPosition);}, 100);@@ -163,7 +182,7 @@ function fetchDirectoryInfo() {.then((response) => response.json()).then((data) => {if (data.directory) {- trajectoryDirectory = data.directory; // Store the directory+ trajectoryDirectory = data.directory;document.title = `Trajectory Viewer: ${data.directory}`;document.querySelector("h1").textContent =`Trajectory Viewer: ${data.directory}`;diff --git a/sweagent/inspector/index.html b/sweagent/inspector/index.htmlindex 48887f7c..8fd0f535 100644--- a/sweagent/inspector/index.html+++ b/sweagent/inspector/index.html@@ -15,7 +15,7 @@<input type="checkbox" id="showDemos" onchange="refreshCurrentFile()"> Show demonstrations</label><h2>Conversation History</h2>- <pre id="fileContent">No file selected.</pre>+ <div id="fileContent" class="trajectory-container">No file selected.</div><div class="button-container"><button id="refreshButton" onclick="refreshCurrentFile()">Refresh Current File</button></div>diff --git a/sweagent/inspector/server.py b/sweagent/inspector/server.pyindex a91053a9..27e2529b 100644--- a/sweagent/inspector/server.py+++ b/sweagent/inspector/server.py@@ -13,55 +13,50 @@ import yamldef append_exit(content):- last_entry = content["history"][-1]- if last_entry["role"] == "system":- return content-exit_status = content.get("info", {}).get("exit_status", None)-if exit_status is None:return contentif exit_status.startswith("submitted"):if "submission" in content["info"]:- submission = content["info"]["submission"]- content["history"].append(+ content["trajectory"].append({- "role": "model_patch",- "content": submission,- },+ "thought": "Submitting solution",+ "action": "Model Submission",+ "response": "Submitting solution",+ "observation": content["info"]["submission"],+ "messages": [{"role": "system", "content": f"Submission generated - {exit_status}"}],+ })- # else submission should be in history alreadyelse:msg = "No submission in history or info"raise ValueError(msg)- # elif content.get("info", {}).get("exit_status", None) is not None:- # content["history"].append({- # "role": "system",- # "content": f"Exited - {content['info']['exit_status']}",- # })return contentdef append_patch(instance_id, content, patches, patch_type):if content.get("info", {}).get("exit_status", None) is not None:if instance_id in patches:- content["history"].append(+ content["trajectory"].append({- "role": f"{patch_type} Patch",- "content": patches[instance_id],- },+ "thought": f"Showing {patch_type} patch",+ "response": f"Showing {patch_type} patch",+ "action": f"{patch_type} Patch",+ "observation": patches[instance_id],+ })return content-def append_results(traj_path: Path, instance_id: str, content, results, results_file, scorecards, scorecards_file):+def append_results(traj_path: Path, instance_id: str, content, results, results_file):stats: list[str] = []model_stats = {}if traj_path.exists():data = json.loads(traj_path.read_text())info = data.get("info", {})model_stats = info.get("model_stats", {})++ # Build stats sectionexit_status = info.get("exit_status", "N/A")instance_cost = model_stats.get("instance_cost", None)instance_cost = f"{instance_cost:.2f}" if instance_cost is not None else "N/A"@@ -71,12 +66,15 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_tokens_received = f"{tokens_received:,}" if tokens_received is not None else "N/A"api_calls = model_stats.get("api_calls", None)api_calls = f"{api_calls:,}" if api_calls is not None else "N/A"+stats.append("**** Run Stats ****")stats.append(f"Exit Status: {exit_status}")stats.append(f"Instance Cost: ${instance_cost}")stats.append(f"Tokens Sent: {tokens_sent}")stats.append(f"Tokens Received: {tokens_received}")stats.append(f"API Calls: {api_calls}\n")++ # Build status sectionstatus = []if results is None:status.append("Evaluation results not found")@@ -86,55 +84,39 @@ def append_results(traj_path: Path, instance_id: str, content, results, results_is_resolved = instance_id in results["resolved_ids"]status.append("**** Statuses ****")- status.append(- f" {'✅' if is_completed else '❌'} Completed (The agent successfully ran)",- )- status.append(- f" {'✅' if is_submitted else '❌'} Submitted (The agent successfully submitted a pull request)",- )+ status.append(f" {'✅' if is_completed else '❌'} Completed (The agent successfully ran)")+ status.append(f" {'✅' if is_submitted else '❌'} Submitted (The agent successfully submitted a pull request)")status.append(f" {'✅' if is_resolved else '❌'} Resolved (The pull request {'' if is_resolved else 'has not '}"- "successfully resolved the issue during eval)",+ "successfully resolved the issue during eval)")else:status.append("Results format not recognized")- if scorecards is not None:- scorecard = [x for x in scorecards if x["instance_id"] == instance_id][0]- if (- "test_results" in scorecard- and "failure" in scorecard["test_results"]- and (- len(scorecard["test_results"]["failure"]["FAIL_TO_PASS"]) > 0- or len(scorecard["test_results"]["failure"]["PASS_TO_PASS"]) > 0- )- ):- tests_failing = [f" - {x}" for x in scorecard["test_results"]["failure"]["FAIL_TO_PASS"]] + [- f" - {x}" for x in scorecard["test_results"]["failure"]["PASS_TO_PASS"]- ]- status.extend(["", "**** Test Results ****", "🧪 Tests Failed"] + tests_failing[:7])- if len(tests_failing) > 7:- status.append(f" ... and {len(tests_failing) - 7} more")- status.append("")-if status == []:status.append("Instance not found in results")else:status.append("---------------------------")status.append(- "Note that the evaluation results here may not be accurate or up to date, since they are computed separately from the agent run itself.",+ "Note that the evaluation results here may not be accurate or up to date, since they are computed separately from the agent run itself.")status.append(f"Check {results_file} for the most accurate evaluation results.")status.append("")status.append(f"Instance ID: {instance_id}")- # status.append("Based on results:")- # status.append(json.dumps(results, indent=4))++ # Add evaluation report as first and last items in trajectoryeval_report = {- "role": "Evaluation Report",- "content": "\n".join([*stats, *status]),+ "thought": "Evaluation Report",+ "action": "Showing evaluation results",+ "response": "Showing evaluation results",+ "observation": "\n".join([*stats, *status]),+ "messages": [{"role": "system", "content": "Showing evaluation results and statistics"}],}- content["history"].insert(0, eval_report)- content["history"].append(eval_report)++ if not content.get("trajectory"):+ content["trajectory"] = []+ content["trajectory"].insert(0, eval_report)+ content["trajectory"].append(eval_report)return content@@ -144,13 +126,7 @@ def load_content(file_name, gold_patches, test_patches) -> dict[str, Any]:results_file = Path(file_name).parent / "results.json"results = load_results(results_file)- scorecards_file = Path(file_name).parent / "scorecards.json"- scorecards = None- if scorecards_file.exists():- with open(scorecards_file) as infile:- scorecards = json.load(infile)-- content = append_exit(content) # accommodate new and old format+ content = append_exit(content)content = append_patch(Path(file_name).stem, content, gold_patches, "Gold")content = append_patch(Path(file_name).stem, content, test_patches, "Test")return append_results(@@ -159,8 +135,6 @@ def load_content(file_name, gold_patches, test_patches) -> dict[str, Any]:content,results,results_file,- scorecards,- scorecards_file,)@@ -323,6 +297,8 @@ def get_parser():def run_from_cli(args: list[str] | None = None):# Hack to make sure all the templates and all are foundparsed_args = get_parser().parse_args(args)+ # convert directory, relative to the absolute path+ parsed_args.directory = str(Path(parsed_args.directory).resolve().absolute())os.chdir(Path(__file__).parent)main(**vars(parsed_args))diff --git a/sweagent/inspector/style.css b/sweagent/inspector/style.cssindex f4165972..60d1f0a5 100644--- a/sweagent/inspector/style.css+++ b/sweagent/inspector/style.css@@ -2,11 +2,11 @@ body {font-family: Arial, sans-serif;margin: 0;padding: 20px;- background-color: #f4f4f4;+ background-color: #1e1e1e;}h1,h2 {- color: #333;+ color: #d4d4d4;}#fileList {list-style-type: none;@@ -14,31 +14,33 @@ h2 {max-height: 400px;overflow-y: auto;margin: 0;- background-color: #eee;+ background-color: #252526;border: 3px solid #1697e2;border-radius: 10px;}#fileList li {cursor: pointer;padding: 10px;- background-color: #fff;+ background-color: #2d2d2d;margin-bottom: 5px;- border: 2px solid #333;+ border: 2px solid #454545;border-radius: 5px;transition: background-color 0.3s;+ color: #d4d4d4;}#fileList li:hover {- background-color: #bbb;+ background-color: #3e3e3e;}#fileList li.selected {border-color: #fabb00;}#fileContent {- background-color: #fff;- border: 1px solid #ddd;+ background-color: #1e1e1e;+ border: 1px solid #454545;padding: 10px;margin-top: 20px;white-space: pre-wrap;+ color: #d4d4d4;}.button-container {display: flex;@@ -114,95 +116,6 @@ h2 {margin: 0 auto; /* Centers the container */padding: 20px; /* Optional: for some inner spacing */}-.role-bar {- background-color: #fff;- padding: 5px 10px;- margin: 0;- border-bottom: 1px solid #fff;- font-size: 18px;- display: flex;- align-items: center;- background-repeat: no-repeat;- background-size: 22px 22px;- padding-left: 35px; /* Adjust according to your icon size */- padding-right: 35px; /* Same padding on the right for balance */-}-.role-bar.user {- background-image: url("icons/computer.png");- background-color: #9cdcff;- justify-content: flex-end; /* Aligns content to the right */- background-position: right 10px center; /* Moves the image to the right */- text-align: right; /* Text aligned right */-}-.role-bar.tool {- background-image: url("icons/computer.png");- background-color: #1eacf8;- justify-content: flex-end; /* Aligns content to the right */- background-position: right 10px center; /* Moves the image to the right */- text-align: right; /* Text aligned right */-}-.role-bar.system {- background-image: url("icons/computer.png");- background-color: #8aa8bd;- justify-content: center; /* Center the flex container contents */- background-position: calc(50% - 32px) center; /* Adjust position */- text-align: center; /* Center the text */-}-.role-bar.system span {- padding-left: 32px;-}-.role-bar.subroutine {- background-image: url("icons/computer.png");- background-color: #7bb776;- justify-content: center;- background-position: calc(50% - 45px) center;- text-align: center;-}-.role-bar.subroutine span {- padding-left: 45px;-}-.role-bar.model-patch {- background-image: url("icons/swellama_blue.png");- background-color: #bdbdbd;- justify-content: center;- background-position: calc(50% - 45px) center;- text-align: center;-}-.role-bar.gold-patch {- background-image: url("icons/swellama_blue.png");- background-color: #ffc65b;- justify-content: center;- background-position: calc(50% - 46px) center;- text-align: center;-}-.role-bar.gold-patch span {- padding-left: 46px;-}-.role-bar.test-patch {- background-image: url("icons/swellama_blue.png");- background-color: #8888ff;- justify-content: center;- background-position: calc(50% - 46px) center;- text-align: center;-}-.role-bar.test-patch span {- padding-left: 46px;-}-.role-bar.assistant {- background-image: url("icons/swe-agent-logo-50.png");- background-color: #fff7ec;- background-position: left 10px center;-}-.role-bar.evaluation-report {- background-image: url("icons/swellama_blue.png");- background-color: #86ad7a;- justify-content: center;- background-position: calc(50% - 96px) center;- text-align: center;-}-.role-bar.evaluation-report span {- padding-left: 23px;-}.history-item.user {border-color: #1697e2;}@@ -236,14 +149,15 @@ h2 {font-size: 16px;gap: 10px;padding: 5px;- background-color: #f4f4f4;+ background-color: #2d2d2d;}.part {- border: 1px solid #ddd;+ border: 1px solid #454545;white-space: nowrap; /* Prevents wrapping within parts */padding: 5px;- background-color: #fff;+ background-color: #3e3e3e;border-radius: 5px;+ color: #d4d4d4;}@keyframes fadeIn {@@ -258,3 +172,203 @@ h2 {.fade-in {animation: fadeIn 1s ease-out;}++.trajectory-container {+ position: relative;+ width: 100%;+}++.trajectory-item {+ display: flex;+ flex-direction: column;+ margin-bottom: 0px;+ border: 3px solid #1697e2;+ border-radius: 5px;+ position: relative;+ background: #2d2d2d;+ min-height: fit-content; /* Added to ensure proper expansion */+ height: auto; /* Added to ensure proper expansion */+ overflow: visible; /* Changed from hidden/auto to visible */+}++.trajectory-main {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 0;+}++.response-section,+.observation-section,+.messages-section {+ padding: 0 4px;+ position: relative;+ min-height: 30px;+ height: 400px;+ max-height: min-content;+ display: flex;+ flex-direction: column;+ resize: vertical;+ overflow: hidden;+ width: calc(100% - 16px);+}++.response-section {+ background-color: #252526;+ border-bottom: 1px solid #454545;+ color: #d4d4d4;+}++.observation-section {+ background-color: #2d2d2d;+ color: #d4d4d4;+}++/* Add section headers */+.response-section::before,+.observation-section::before,+.messages-section::before {+ content: attr(data-title);+ font-weight: bold;+ padding: 8px 12px; /* Keep this comfortable padding */+ background: rgba(255, 255, 255, 0.05);+ margin: 0 0 8px 0; /* Add some bottom margin to separate from content */+ border-bottom: 1px solid #454545;+ position: sticky;+ top: 0;+ width: 100%;+ box-sizing: border-box;+ color: #d4d4d4;+}++/* Scrollable content containers */+.content-wrapper {+ overflow-y: auto;+ flex: 1;+ padding: 0;+ margin: 0;+ display: flex; /* Add flex display */+ flex-direction: column; /* Stack children vertically */+}++.content-wrapper pre {+ margin: 0;+ padding: 0;+ flex: 1; /* Allow pre to fill the space */+ display: flex; /* Make pre a flex container */+ flex-direction: column; /* Stack children vertically */+}++.content-wrapper pre code {+ margin: 0;+ padding: 0;+ flex: 1; /* Allow code to fill the space */+}++.messages-section {+ padding: 4px;+ position: relative;+ min-height: 30px;+ height: 30px;+ max-height: min-content; /* Only expand to fit content */+ background: #252526;+ border-top: 1px solid #454545;+ display: flex;+ flex-direction: column;+ resize: vertical;+ overflow: hidden;+ width: calc(100% - 16px);+ color: #d4d4d4;+}++.messages-section::before {+ content: attr(data-title);+ font-weight: bold;+ padding: 8px 12px; /* Increased padding around title text */+ background: rgba(255, 255, 255, 0.05);+ margin: -8px -8px 5px -8px; /* Reduced bottom margin */+ border-bottom: 1px solid #454545;+ position: sticky;+ top: -8px;+ width: calc(100% + 16px);+ box-sizing: border-box;+ color: #d4d4d4;+}++.messages-toggle {+ display: none;+}++.execution-time {+ font-size: 0.8em;+ color: #666;+ text-align: right;+ padding: 5px;+ border-top: 1px solid #ddd;+}++/* Add a visual indicator for resizable areas */+.response-section:hover,+.observation-section:hover,+.messages-section.expanded:hover {+ outline: 1px dashed #999;+}++.demo-message {+ color: #2ecc71;+ font-weight: bold;+}++/* Syntax highlighting overrides for dark theme */+.hljs {+ background: #1e1e1e !important;+ color: #d4d4d4 !important;+}++.hljs-keyword,+.hljs-selector-tag,+.hljs-built_in,+.hljs-name,+.hljs-tag {+ color: #569cd6 !important; /* Blue */+}++.hljs-string,+.hljs-title,+.hljs-section,+.hljs-attribute,+.hljs-literal,+.hljs-template-tag,+.hljs-template-variable,+.hljs-type {+ color: #ce9178 !important; /* Orange/Pink */+}++.hljs-comment,+.hljs-quote {+ color: #6a9955 !important; /* Green */+}++.hljs-number,+.hljs-regexp,+.hljs-symbol,+.hljs-variable,+.hljs-template-variable,+.hljs-link,+.hljs-selector-attr,+.hljs-selector-pseudo {+ color: #b5cea8 !important; /* Light green */+}++label {+ color: #d4d4d4; /* Matches the theme's text color */+ display: flex;+ align-items: center;+ gap: 5px;+}++input[type="checkbox"] {+ margin: 0;+ cursor: pointer;+}