Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
refine edit tool results and request logging
Abi Raja47b29667c365
diff --git a/backend/agent/tools/definitions.py b/backend/agent/tools/definitions.pyindex d29f4c79..c6af1f8d 100644--- a/backend/agent/tools/definitions.py+++ b/backend/agent/tools/definitions.py@@ -117,7 +117,8 @@ def canonical_tool_definitions(name="edit_file",description=("Edit the main HTML file using exact string replacements. Do not "- "regenerate the entire file. Returns the updated file content."+ "regenerate the entire file. Returns a success message plus edit "+ "details, including a unified diff and first changed line."),parameters=_edit_schema(),),diff --git a/backend/agent/tools/runtime.py b/backend/agent/tools/runtime.pyindex b1680507..33e5d487 100644--- a/backend/agent/tools/runtime.py+++ b/backend/agent/tools/runtime.py@@ -1,5 +1,6 @@# pyright: reportUnknownVariableType=falseimport asyncio+import difflibfrom typing import Any, Dict, List, Optional, Tuple, Unionfrom codegen.utils import extract_html_content@@ -88,6 +89,32 @@ class AgentToolRuntime:updated_content=self.file_state.content,)+ @staticmethod+ def _generate_diff(old_content: str, new_content: str, path: str) -> Dict[str, Any]:+ """Generate a unified diff between old and new content."""+ old_lines = old_content.splitlines(keepends=True)+ new_lines = new_content.splitlines(keepends=True)+ diff_lines = list(+ difflib.unified_diff(old_lines, new_lines, fromfile=path, tofile=path)+ )+ diff_str = "".join(diff_lines)++ first_changed_line: Optional[int] = None+ for line in diff_lines:+ if not line.startswith("@@"):+ continue+ try:+ plus_part = line.split("+")[1].split("@@")[0].strip()+ first_changed_line = int(plus_part.split(",")[0])+ except (IndexError, ValueError):+ pass+ break++ return {+ "diff": diff_str,+ "firstChangedLine": first_changed_line,+ }+def _apply_single_edit(self,content: str,@@ -131,6 +158,7 @@ class AgentToolRuntime:)content = self.file_state.content+ original_content = contentsummary_edits: List[Dict[str, Any]] = []for edit in edits:old_text = ensure_str(edit.get("old_text"))@@ -163,14 +191,21 @@ class AgentToolRuntime:)self.file_state.content = content+ path = self.file_state.path or "index.html"+ diff_info = self._generate_diff(original_content, content, path)summary = {- "path": self.file_state.path,+ "path": path,"edits": summary_edits,"contentLength": len(self.file_state.content),+ "diff": diff_info["diff"],+ "firstChangedLine": diff_info["firstChangedLine"],}result = {- "path": self.file_state.path,- "content": self.file_state.content,+ "content": f"Successfully edited file at {path}.",+ "details": {+ "diff": diff_info["diff"],+ "firstChangedLine": diff_info["firstChangedLine"],+ },}return ToolExecutionResult(ok=True,diff --git a/backend/fs_logging/openai_turn_inputs.py b/backend/fs_logging/openai_turn_inputs.pyindex 53573c4b..b09ade16 100644--- a/backend/fs_logging/openai_turn_inputs.py+++ b/backend/fs_logging/openai_turn_inputs.py@@ -68,21 +68,6 @@ def _to_serializable(value: Any) -> Any:return ensure_str(value)-def _truncate_nested_strings(value: Any, max_len: int = 400) -> Any:- if isinstance(value, str):- if len(value) <= max_len:- return value- return f"{value[:max_len]}... (truncated {len(value) - max_len} chars)"- if isinstance(value, list):- return [_truncate_nested_strings(v, max_len=max_len) for v in value]- if isinstance(value, dict):- return {- ensure_str(k): _truncate_nested_strings(v, max_len=max_len)- for k, v in value.items()- }- return value--def _summarize_content_part(part: Any) -> str:part_dict = _as_dict(part)if part_dict is None:@@ -116,6 +101,128 @@ def _summarize_content_part(part: Any) -> str:return f"{part_type}(keys={sorted(part_dict.keys())})"+def _summarize_function_call_output_payload(output_text: str) -> str:+ try:+ parsed = json.loads(output_text)+ except json.JSONDecodeError:+ return (+ f"output_chars={len(output_text)} "+ f"preview='{_truncate_for_log(output_text)}'"+ )++ if not isinstance(parsed, dict):+ return (+ f"output_type={type(parsed).__name__} "+ f"preview='{_truncate_for_log(parsed)}'"+ )++ if "error" in parsed:+ error_text = ensure_str(parsed.get("error"))+ return f"error='{_truncate_for_log(error_text)}'"++ summary_parts: list[str] = []++ content_text = ensure_str(parsed.get("content"))+ if content_text:+ summary_parts.append(f"content='{_truncate_for_log(content_text, max_len=80)}'")++ details = parsed.get("details")+ if isinstance(details, dict):+ path = ensure_str(details.get("path"))++ diff_text = details.get("diff")+ if (not path) and isinstance(diff_text, str) and diff_text:+ for line in diff_text.splitlines():+ if line.startswith("--- "):+ path = line.removeprefix("--- ").strip()+ break++ if path:+ summary_parts.append(f"path={path}")++ edits = details.get("edits")+ if isinstance(edits, list):+ summary_parts.append(f"edits={len(edits)}")++ content_length = details.get("contentLength")+ if isinstance(content_length, int):+ summary_parts.append(f"content_length={content_length}")++ first_changed_line = details.get("firstChangedLine")+ if isinstance(first_changed_line, int):+ summary_parts.append(f"first_changed_line={first_changed_line}")++ if isinstance(diff_text, str) and diff_text:+ diff_lines = diff_text.count("\n")+ summary_parts.append(f"diff_chars={len(diff_text)}")+ summary_parts.append(f"diff_lines={diff_lines}")++ if not summary_parts:+ summary_parts.append(f"keys={sorted(parsed.keys())}")++ return " ".join(summary_parts)+++def _render_json_scalar(value: Any) -> str:+ if value is None:+ return "<span class='json-null'>null</span>"+ if isinstance(value, bool):+ return f"<span class='json-bool'>{str(value).lower()}</span>"+ if isinstance(value, (int, float)):+ return f"<span class='json-number'>{escape(ensure_str(value))}</span>"+ text = ensure_str(value)+ if "\n" not in text and len(text) <= 160:+ return f"<code class='json-string'>{escape(text)}</code>"+ return (+ "<details class='json-string-block'>"+ f"<summary>string ({len(text)} chars)</summary>"+ f"<pre>{escape(text)}</pre>"+ "</details>"+ )+++def _render_json_node(value: Any, label: str | None = None) -> str:+ label_html = ""+ if label is not None:+ label_html = f"<span class='json-key'>{escape(label)}</span>: "++ if isinstance(value, dict):+ parts = [+ "<details class='json-node'>",+ (+ f"<summary>{label_html}"+ f"<span class='json-type'>object ({len(value)} keys)</span></summary>"+ ),+ "<div class='json-children'>",+ ]+ for child_key, child_value in value.items():+ parts.append(_render_json_node(child_value, ensure_str(child_key)))+ parts.append("</div>")+ parts.append("</details>")+ return "".join(parts)++ if isinstance(value, list):+ parts = [+ "<details class='json-node'>",+ (+ f"<summary>{label_html}"+ f"<span class='json-type'>array ({len(value)} items)</span></summary>"+ ),+ "<div class='json-children'>",+ ]+ for index, child_value in enumerate(value):+ parts.append(_render_json_node(child_value, f"[{index}]"))+ parts.append("</div>")+ parts.append("</details>")+ return "".join(parts)++ return (+ "<div class='json-leaf'>"+ f"{label_html}{_render_json_scalar(value)}"+ "</div>"+ )++def _summarize_responses_input_item(index: int, item: Any) -> str:item_dict = _as_dict(item)if item_dict is None:@@ -157,8 +264,7 @@ def _summarize_responses_input_item(index: int, item: Any) -> str:output_text = ensure_str(item_dict.get("output", ""))return (f"{index:02d} type=function_call_output call_id={item_dict.get('call_id')} "- f"output_chars={len(output_text)} "- f"preview='{_truncate_for_log(output_text)}'"+ f"{_summarize_function_call_output_payload(output_text)}")if item_type == "message":@@ -251,7 +357,7 @@ class OpenAITurnInputLogger:OpenAITurnInputItem(index=index,summary=_summarize_responses_input_item(index, item),- payload=_truncate_nested_strings(_to_serializable(item)),+ payload=_to_serializable(item),)for index, item in enumerate(input_items)]@@ -324,6 +430,16 @@ class OpenAITurnInputLogger:" .usage-table { width: auto; min-width: 540px; margin-top: 10px; }"," .usage-table th { width: 180px; }"," .usage-none { margin-top: 10px; color: #6b7280; font-style: italic; }",+ " .payload-wrap { margin-top: 10px; }",+ " .json-view { margin-top: 8px; padding: 10px; border: 1px solid #e5e7eb; border-radius: 8px; background: #fcfcfd; }",+ " .json-node, .json-string-block { margin: 6px 0; }",+ " .json-node > summary, .json-string-block > summary { cursor: pointer; color: #1f2937; }",+ " .json-children { margin-left: 16px; border-left: 1px solid #e5e7eb; padding-left: 10px; }",+ " .json-leaf { margin: 6px 0; }",+ " .json-key { color: #7c3aed; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }",+ " .json-type { color: #2563eb; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }",+ " .json-number, .json-bool, .json-null { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: #0f766e; }",+ " .json-string { white-space: pre-wrap; overflow-wrap: anywhere; }"," </style>","</head>","<body>",@@ -403,13 +519,18 @@ class OpenAITurnInputLogger:item.payload,indent=2,ensure_ascii=False,- sort_keys=True,)- html_parts.append(" <details>")+ html_parts.append(" <details class='payload-wrap'>")html_parts.append(f" <summary>Item {item.index:02d} payload</summary>")- html_parts.append(f" <pre>{escape(payload_json)}</pre>")+ html_parts.append(" <div class='json-view'>")+ html_parts.append(_render_json_node(item.payload, "root"))+ html_parts.append(" </div>")+ html_parts.append(" <details>")+ html_parts.append(" <summary>Raw JSON payload</summary>")+ html_parts.append(f" <pre>{escape(payload_json)}</pre>")+ html_parts.append(" </details>")html_parts.append(" </details>")html_parts.append(" </section>")diff --git a/backend/routes/model_choice_sets.py b/backend/routes/model_choice_sets.pyindex 0a38a5fb..79153e1f 100644--- a/backend/routes/model_choice_sets.py+++ b/backend/routes/model_choice_sets.py@@ -26,11 +26,11 @@ ALL_KEYS_MODELS_TEXT_CREATE = (Llm.GEMINI_3_1_PRO_PREVIEW_LOW,)-# Text + Video (Update)+# Image + Text (Update)ALL_KEYS_MODELS_UPDATE = (Llm.GEMINI_3_FLASH_PREVIEW_MINIMAL,- Llm.GPT_5_2_CODEX_LOW,+ Llm.GPT_5_3_CODEX_LOW,)# Key subset fallbacks.diff --git a/backend/tests/test_agent_tool_runtime.py b/backend/tests/test_agent_tool_runtime.pynew file mode 100644index 00000000..247dfeb9--- /dev/null+++ b/backend/tests/test_agent_tool_runtime.py@@ -0,0 +1,60 @@+import pytest++from agent.state import AgentFileState+from agent.tools.runtime import AgentToolRuntime+from agent.tools.types import ToolCall+++def test_edit_file_returns_structured_result_with_diff() -> None:+ runtime = AgentToolRuntime(+ file_state=AgentFileState(+ path="index.html",+ content="<div>before</div>\n<p>keep</p>\n",+ ),+ should_generate_images=False,+ openai_api_key=None,+ openai_base_url=None,+ )++ result = runtime._edit_file(+ {+ "old_text": "<div>before</div>",+ "new_text": "<div>after</div>",+ }+ )++ assert result.ok is True+ assert result.updated_content == "<div>after</div>\n<p>keep</p>\n"+ assert result.result["content"] == "Successfully edited file at index.html."+ assert set(result.result["details"].keys()) == {"diff", "firstChangedLine"}+ assert result.result["details"]["firstChangedLine"] == 1+ assert "--- index.html" in result.result["details"]["diff"]+ assert "+++ index.html" in result.result["details"]["diff"]+ assert "-<div>before</div>" in result.result["details"]["diff"]+ assert "+<div>after</div>" in result.result["details"]["diff"]+ assert result.summary["firstChangedLine"] == 1+ assert result.summary["diff"] == result.result["details"]["diff"]+++async def test_execute_edit_file_uses_updated_result_shape() -> None:+ runtime = AgentToolRuntime(+ file_state=AgentFileState(path="index.html", content="<main>old</main>"),+ should_generate_images=False,+ openai_api_key=None,+ openai_base_url=None,+ )++ result = await runtime.execute(+ ToolCall(+ id="call-1",+ name="edit_file",+ arguments={"old_text": "old", "new_text": "new"},+ )+ )++ # execute() is sync for edit_file and should preserve the structured payload.+ assert result.ok is True+ assert result.result["content"] == "Successfully edited file at index.html."+ assert set(result.result["details"].keys()) == {"diff", "firstChangedLine"}+ assert "--- index.html" in result.result["details"]["diff"]diff --git a/backend/tests/test_agent_tools.py b/backend/tests/test_agent_tools.pyindex e85e1fa5..20b47b14 100644--- a/backend/tests/test_agent_tools.py+++ b/backend/tests/test_agent_tools.py@@ -9,3 +9,12 @@ def test_canonical_tool_definitions_include_generate_images_when_enabled() -> Nodef test_canonical_tool_definitions_exclude_generate_images_when_disabled() -> None:tool_names = [tool.name for tool in canonical_tool_definitions(False)]assert "generate_images" not in tool_names+++def test_edit_file_tool_description_matches_runtime_output_shape() -> None:+ edit_tool = next(+ tool for tool in canonical_tool_definitions(True) if tool.name == "edit_file"+ )++ assert "success message" in edit_tool.description+ assert "unified diff" in edit_tool.descriptiondiff --git a/backend/tests/test_model_selection.py b/backend/tests/test_model_selection.pyindex 015651e2..66acd9b6 100644--- a/backend/tests/test_model_selection.py+++ b/backend/tests/test_model_selection.py@@ -44,7 +44,7 @@ class TestModelSelectionAllKeys:expected = [Llm.GEMINI_3_FLASH_PREVIEW_MINIMAL,- Llm.GPT_5_2_CODEX_LOW,+ Llm.GPT_5_3_CODEX_LOW,]assert models == expected@@ -61,7 +61,7 @@ class TestModelSelectionAllKeys:expected = [Llm.GEMINI_3_FLASH_PREVIEW_MINIMAL,- Llm.GPT_5_2_CODEX_LOW,+ Llm.GPT_5_3_CODEX_LOW,]assert models == expecteddiff --git a/backend/tests/test_openai_turn_input_logging.py b/backend/tests/test_openai_turn_input_logging.pyindex 884d557a..e0e50a41 100644--- a/backend/tests/test_openai_turn_input_logging.py+++ b/backend/tests/test_openai_turn_input_logging.py@@ -52,7 +52,7 @@ def test_openai_turn_input_logger_writes_html_report(tmp_path, monkeypatch) -> Nassert "$" in html-def test_openai_turn_input_logger_truncates_large_payloads(+def test_openai_turn_input_logger_preserves_full_large_payloads(tmp_path, monkeypatch) -> None:monkeypatch.setenv("LOGS_PATH", str(tmp_path))@@ -62,7 +62,7 @@ def test_openai_turn_input_logger_truncates_large_payloads([{"role": "user",- "content": [{"type": "input_text", "text": "x" * 450}],+ "content": [{"type": "input_text", "text": "BEGIN-" + ("x" * 450) + "-END"}],}])@@ -72,7 +72,11 @@ def test_openai_turn_input_logger_truncates_large_payloads(assert report_path is not Nonehtml = Path(report_path).read_text(encoding="utf-8")assert "Usage unavailable for this turn." in html- assert "truncated 50 chars" in html+ assert "Raw JSON payload" in html+ assert "string (460 chars)" in html+ assert "BEGIN-" in html+ assert "-END" in html+ assert "truncated 50 chars" not in htmldef test_openai_turn_input_logger_disabled_writes_nothing(tmp_path, monkeypatch) -> None:@@ -86,3 +90,34 @@ def test_openai_turn_input_logger_disabled_writes_nothing(tmp_path, monkeypatch)assert report_path is Noneassert not (tmp_path / "run_logs").exists()+++def test_openai_turn_input_logger_summarizes_function_call_output(+ tmp_path, monkeypatch+) -> None:+ monkeypatch.setenv("LOGS_PATH", str(tmp_path))++ logger = OpenAITurnInputLogger(model=Llm.GPT_5_2_CODEX_LOW, enabled=True)+ logger.record_turn_input(+ [+ {+ "type": "function_call_output",+ "call_id": "call-1",+ "output": (+ '{"content":"Successfully edited file at index.html.",'+ '"details":{"diff":"--- index.html\\n+++ index.html\\n@@ -1 +1 @@\\n-a\\n+b\\n",'+ '"firstChangedLine":1}}'+ ),+ }+ ]+ )++ report_path = logger.write_html_report()++ assert report_path is not None+ html = Path(report_path).read_text(encoding="utf-8")+ assert "type=function_call_output call_id=call-1" in html+ assert "path=index.html" in html+ assert "first_changed_line=1" in html+ assert "diff_chars=" in html+ assert 'preview='{"content":' not in html