Skip to content

Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.

fix(panel): fix WebView2 Access-Denied and wire chat to CLI agents

A. Sam Mohammadc58f59c9f9bf
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/agent_bridge.py b/packages/mcp-server-revit/src/revit_mcp_server/agent_bridge.py
new file mode 100644
index 0000000..41b5493
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/agent_bridge.py
@@ -0,0 +1,213 @@
+"""Shells out to an already-installed AI coding CLI (Claude Code, Codex) so the
+Revit dockable panel can have a real chat surface without this hub reimplementing
+an LLM agent loop, tool-calling, or a model provider SDK.
+
+Both CLIs already speak MCP as clients. This hub already speaks MCP as a stdio
+server (mcp_server.py). So a chat turn is: launch the CLI non-interactively,
+point it at this same server via its own MCP-client config, capture its final
+reply. The CLI owns the model call, the tool-calling loop, and (for Claude)
+permission handling; this module only owns process plumbing and provider
+dispatch. Mutating Revit tool calls still pass through ApprovalGate exactly as
+they do for every other caller — nothing here bypasses that.
+
+Personal-use scope only (see docs/product/DECISIONS_AND_RISKS.md): this
+assumes the operator's own machine has `claude` and/or `codex` on PATH and
+already authenticated. Shipping this to other users would need a very
+different trust model (bundled/managed CLI, no reliance on the operator's own
+CLI session) — do not extend this to the general product surface without
+revisiting that.
+"""
+from __future__ import annotations
+
+import json
+import logging
+import os
+import shutil
+import subprocess
+import tempfile
+import uuid
+from typing import Any, Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+_TURN_TIMEOUT_SECONDS = 180
+_MCP_SERVER_NAME = "aec-model-bridge"
+_CODEX_REGISTRATION_CHECKED = False
+
+
+def _mcp_server_command() -> list[str]:
+ """The exact launch command every switch already uses for this hub's stdio
+ server, so the CLI's own MCP session and a stdio MCP client see the same
+ process shape (mirrors PanelHubLauncher.cs's `python -m revit_mcp_server...`).
+
+ Deliberately the bare "python" on PATH, not sys.executable: verified live
+ that passing this process's own sys.executable (a WindowsApps App
+ Execution Alias full path) as the command silently fails to hand the CLI
+ working MCP tools, while the same bare command resolved via PATH by the
+ CLI's own child-process spawner works every time. Matches
+ PanelHubLauncher.cs's own bare "python"/"py" convention (see its docstring
+ on D-010) rather than inventing a different resolution strategy here."""
+ return ["python", "-m", "revit_mcp_server.mcp_server"]
+
+
+def run_agent_turn(provider: str, message: str, session_id: Optional[str]) -> Dict[str, Any]:
+ """Runs one chat turn against the requested CLI provider.
+
+ Returns {"ok": True, "response": str, "session_id": str} on success, or
+ {"ok": False, "error": str} — never raises for expected failure modes
+ (missing CLI, timeout, non-zero exit) so panel_server.py can pass this
+ straight through as the response body.
+ """
+ if provider == "claude":
+ return _run_claude_turn(message, session_id)
+ if provider == "codex":
+ return _run_codex_turn(message, session_id)
+ return {"ok": False, "error": f"Unknown agent provider '{provider}' (expected 'claude' or 'codex')"}
+
+
+def _run_claude_turn(message: str, session_id: Optional[str]) -> Dict[str, Any]:
+ # subprocess.run (no shell) resolves a bare name via CreateProcess, which
+ # does not search PATHEXT for .cmd/.bat shims the way shutil.which (and a
+ # real shell) do. claude.EXE happens to work bare; resolving explicitly
+ # here makes that not matter, and fixes the exact failure hit live with
+ # codex's npm-installed codex.CMD shim below.
+ claude_path = shutil.which("claude")
+ if claude_path is None:
+ return {"ok": False, "error": "'claude' CLI not found on PATH. Install Claude Code and sign in first."}
+
+ resolved_session_id = session_id or str(uuid.uuid4())
+ mcp_config = json.dumps({
+ "mcpServers": {
+ _MCP_SERVER_NAME: {
+ "command": _mcp_server_command()[0],
+ "args": _mcp_server_command()[1:],
+ }
+ }
+ })
+
+ args = [
+ claude_path, "-p", message,
+ "--mcp-config", mcp_config,
+ "--strict-mcp-config",
+ # Disable Claude Code's own built-in tools (Bash/Edit/Read/...) so this
+ # chat surface can only ever touch Revit through the MCP tools above —
+ # it should not become a general-purpose shell into the user's machine.
+ "--tools", "",
+ # --permission-mode only covers Claude Code's own built-in tools (Edit,
+ # Bash, ...) — it does NOT auto-approve MCP tool calls. Without an
+ # explicit grant, a headless run (no TTY to answer a permission prompt)
+ # silently blocks every MCP tool call, and the model may report a
+ # plausible-looking fake result instead of the block (verified against
+ # a live `claude -p` run). --allowedTools scoped to just this MCP
+ # server is what actually lets Revit tool calls proceed; ApprovalGate
+ # on the Revit side is still the real safety boundary for mutations.
+ "--allowedTools", f"mcp__{_MCP_SERVER_NAME}",
+ "--permission-mode", "acceptEdits",
+ "--output-format", "json",
+ ]
+ args += ["--resume", resolved_session_id] if session_id else ["--session-id", resolved_session_id]
+
+ # mcp_server.py takes ~2s just to import (Speckle/APS client init etc.) —
+ # verified live that without raising MCP_TIMEOUT, Claude Code sometimes
+ # gives up waiting for the MCP handshake and silently proceeds with no
+ # Revit tools at all, and the model then fabricates a plausible-looking
+ # answer instead of reporting that. 30s is comfortably above the observed
+ # worst case.
+ env = {**os.environ, "MCP_TIMEOUT": "30000"}
+
+ try:
+ proc = subprocess.run(args, capture_output=True, encoding="utf-8", stdin=subprocess.DEVNULL, timeout=_TURN_TIMEOUT_SECONDS, env=env)
+ except subprocess.TimeoutExpired:
+ return {"ok": False, "error": f"claude did not respond within {_TURN_TIMEOUT_SECONDS}s"}
+ except OSError as e:
+ return {"ok": False, "error": f"Failed to launch claude: {e}"}
+
+ if proc.returncode != 0:
+ logger.warning("claude exited %s: %s", proc.returncode, proc.stderr)
+ return {"ok": False, "error": (proc.stderr or proc.stdout or f"claude exited {proc.returncode}").strip()[:2000]}
+
+ text, returned_session_id = _parse_claude_output(proc.stdout)
+ return {"ok": True, "response": text, "session_id": returned_session_id or resolved_session_id}
+
+
+def _parse_claude_output(stdout: str) -> tuple[str, Optional[str]]:
+ try:
+ payload = json.loads(stdout)
+ except json.JSONDecodeError:
+ return stdout.strip(), None
+ text = payload.get("result") or payload.get("response") or ""
+ return text, payload.get("session_id")
+
+
+def _run_codex_turn(message: str, session_id: Optional[str]) -> Dict[str, Any]:
+ codex_path = shutil.which("codex")
+ if codex_path is None:
+ return {"ok": False, "error": "'codex' CLI not found on PATH. Install Codex CLI and sign in first."}
+
+ _ensure_codex_mcp_registered(codex_path)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ out_path = os.path.join(tmp_dir, "last_message.txt")
+ base = [codex_path, "exec"]
+ if session_id:
+ base += ["resume", session_id]
+ base += [message, "--sandbox", "read-only", "--skip-git-repo-check", "--json", "-o", out_path]
+
+ try:
+ proc = subprocess.run(base, capture_output=True, encoding="utf-8", stdin=subprocess.DEVNULL, timeout=_TURN_TIMEOUT_SECONDS)
+ except subprocess.TimeoutExpired:
+ return {"ok": False, "error": f"codex did not respond within {_TURN_TIMEOUT_SECONDS}s"}
+ except OSError as e:
+ return {"ok": False, "error": f"Failed to launch codex: {e}"}
+
+ if proc.returncode != 0:
+ logger.warning("codex exited %s: %s", proc.returncode, proc.stderr)
+ return {"ok": False, "error": (proc.stderr or proc.stdout or f"codex exited {proc.returncode}").strip()[:2000]}
+
+ returned_session_id = _parse_codex_session_id(proc.stdout) or session_id
+ try:
+ with open(out_path, "r", encoding="utf-8") as f:
+ text = f.read().strip()
+ except OSError:
+ text = proc.stdout.strip()
+
+ return {"ok": True, "response": text, "session_id": returned_session_id}
+
+
+def _parse_codex_session_id(stdout: str) -> Optional[str]:
+ for line in stdout.splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ for key in ("session_id", "conversation_id", "thread_id"):
+ value = event.get(key)
+ if value:
+ return value
+ return None
+
+
+def _ensure_codex_mcp_registered(codex_path: str) -> None:
+ """Registers this hub as a Codex MCP server once. Codex has no per-call
+ equivalent of Claude's --mcp-config; `codex mcp add` is the CLI's own
+ persistent-config mechanism, so this uses it rather than hand-editing
+ ~/.codex/config.toml."""
+ global _CODEX_REGISTRATION_CHECKED
+ if _CODEX_REGISTRATION_CHECKED:
+ return
+ _CODEX_REGISTRATION_CHECKED = True
+
+ try:
+ listed = subprocess.run([codex_path, "mcp", "list"], capture_output=True, encoding="utf-8", stdin=subprocess.DEVNULL, timeout=15)
+ if _MCP_SERVER_NAME in (listed.stdout or ""):
+ return
+ subprocess.run(
+ [codex_path, "mcp", "add", _MCP_SERVER_NAME, "--", *_mcp_server_command()],
+ capture_output=True, encoding="utf-8", stdin=subprocess.DEVNULL, timeout=15,
+ )
+ logger.info("Registered '%s' as a Codex MCP server", _MCP_SERVER_NAME)
+ except Exception:
+ logger.warning("Could not verify/register the Codex MCP server", exc_info=True)
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py b/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py
index 3908439..36fa928 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/panel_server.py
@@ -22,6 +22,7 @@ import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Dict
+from .agent_bridge import run_agent_turn
from .errors import RevitMCPError
from .registry_factory import build_registry
from .security.audit import redact_data
@@ -83,6 +84,10 @@ class PanelRequestHandler(BaseHTTPRequestHandler):
self._send_json(404, {"ok": False, "error": f"Unknown path '{self.path}'"})
def do_POST(self) -> None: # noqa: N802
+ if self.path == "/agent/chat":
+ self._handle_agent_chat()
+ return
+
if self.path != "/execute":
self._send_json(404, {"ok": False, "error": f"Unknown path '{self.path}'"})
return
@@ -109,6 +114,33 @@ class PanelRequestHandler(BaseHTTPRequestHandler):
except Exception as e:
self._send_json(500, {"ok": False, "error": redact_data(str(e))})
+ def _handle_agent_chat(self) -> None:
+ length = int(self.headers.get("Content-Length", "0") or "0")
+ raw = self.rfile.read(length) if length else b"{}"
+ try:
+ body = json.loads(raw or b"{}")
+ except json.JSONDecodeError:
+ self._send_json(400, {"ok": False, "error": "Request body must be valid JSON"})
+ return
+
+ message = body.get("message")
+ if not message or not isinstance(message, str):
+ self._send_json(400, {"ok": False, "error": "Request body must include a string 'message' field"})
+ return
+
+ provider = body.get("provider") or "claude"
+ session_id = body.get("session_id")
+
+ try:
+ result = run_agent_turn(provider, message, session_id)
+ except Exception as e:
+ self._send_json(500, {"ok": False, "error": redact_data(str(e))})
+ return
+
+ if not result.get("ok"):
+ result["error"] = redact_data(result.get("error", ""))
+ self._send_json(200 if result.get("ok") else 502, result)
+
def build_server(port: int | None = None, workspace: WorkspaceMonitor | None = None) -> ThreadingHTTPServer:
registry, approval_provider, _job_manager, _module_registry, _workspace = build_registry(workspace=workspace)
diff --git a/packages/mcp-server-revit/tests/test_agent_bridge.py b/packages/mcp-server-revit/tests/test_agent_bridge.py
new file mode 100644
index 0000000..5453efe
--- /dev/null
+++ b/packages/mcp-server-revit/tests/test_agent_bridge.py
@@ -0,0 +1,152 @@
+"""Tests for agent_bridge.py's CLI-shelling logic.
+
+None of these invoke a real `claude`/`codex` process — subprocess.run and
+shutil.which are monkeypatched so the tests exercise argument construction,
+output parsing, and error handling without depending on those CLIs being
+installed or authenticated in CI.
+"""
+from __future__ import annotations
+
+import json
+import subprocess
+
+from revit_mcp_server import agent_bridge
+
+
+def _completed(args, returncode=0, stdout="", stderr=""):
+ return subprocess.CompletedProcess(args=args, returncode=returncode, stdout=stdout, stderr=stderr)
+
+
+def test_unknown_provider_returns_error():
+ result = agent_bridge.run_agent_turn("gpt-nobody", "hello", None)
+ assert result == {"ok": False, "error": "Unknown agent provider 'gpt-nobody' (expected 'claude' or 'codex')"}
+
+
+def test_claude_missing_cli(monkeypatch):
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: None)
+ result = agent_bridge.run_agent_turn("claude", "hello", None)
+ assert result["ok"] is False
+ assert "claude" in result["error"]
+
+
+def test_claude_first_turn_uses_session_id_and_returns_response(monkeypatch):
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: "/usr/bin/claude")
+
+ captured = {}
+
+ def fake_run(args, **kwargs):
+ captured["args"] = args
+ payload = json.dumps({"result": "3 doors found on Level 1", "session_id": "abc-123"})
+ return _completed(args, stdout=payload)
+
+ monkeypatch.setattr(agent_bridge.subprocess, "run", fake_run)
+
+ result = agent_bridge.run_agent_turn("claude", "how many doors on level 1?", None)
+
+ assert result == {"ok": True, "response": "3 doors found on Level 1", "session_id": "abc-123"}
+ assert "--session-id" in captured["args"]
+ assert "--resume" not in captured["args"]
+ assert "--strict-mcp-config" in captured["args"]
+ # Built-in tools must be disabled — chat should only reach Revit via MCP.
+ tools_index = captured["args"].index("--tools")
+ assert captured["args"][tools_index + 1] == ""
+
+
+def test_claude_resumes_existing_session(monkeypatch):
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: "/usr/bin/claude")
+
+ captured = {}
+
+ def fake_run(args, **kwargs):
+ captured["args"] = args
+ return _completed(args, stdout=json.dumps({"result": "ok", "session_id": "abc-123"}))
+
+ monkeypatch.setattr(agent_bridge.subprocess, "run", fake_run)
+
+ result = agent_bridge.run_agent_turn("claude", "and level 2?", "abc-123")
+
+ assert result["session_id"] == "abc-123"
+ assert "--resume" in captured["args"]
+ resume_index = captured["args"].index("--resume")
+ assert captured["args"][resume_index + 1] == "abc-123"
+
+
+def test_claude_nonzero_exit_returns_error(monkeypatch):
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: "/usr/bin/claude")
+ monkeypatch.setattr(
+ agent_bridge.subprocess, "run",
+ lambda args, **kwargs: _completed(args, returncode=1, stderr="boom"),
+ )
+
+ result = agent_bridge.run_agent_turn("claude", "hi", None)
+ assert result == {"ok": False, "error": "boom"}
+
+
+def test_claude_timeout_returns_error(monkeypatch):
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: "/usr/bin/claude")
+
+ def fake_run(args, **kwargs):
+ raise subprocess.TimeoutExpired(cmd=args, timeout=kwargs.get("timeout"))
+
+ monkeypatch.setattr(agent_bridge.subprocess, "run", fake_run)
+
+ result = agent_bridge.run_agent_turn("claude", "hi", None)
+ assert result["ok"] is False
+ assert "did not respond" in result["error"]
+
+
+def test_claude_non_json_stdout_falls_back_to_raw_text(monkeypatch):
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: "/usr/bin/claude")
+ monkeypatch.setattr(
+ agent_bridge.subprocess, "run",
+ lambda args, **kwargs: _completed(args, stdout="plain text reply\n"),
+ )
+
+ result = agent_bridge.run_agent_turn("claude", "hi", None)
+ assert result["ok"] is True
+ assert result["response"] == "plain text reply"
+
+
+def test_codex_missing_cli(monkeypatch):
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: None)
+ result = agent_bridge.run_agent_turn("codex", "hello", None)
+ assert result["ok"] is False
+ assert "codex" in result["error"]
+
+
+def test_codex_success_reads_last_message_file(monkeypatch, tmp_path):
+ monkeypatch.setattr(agent_bridge, "_CODEX_REGISTRATION_CHECKED", True)
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: "/usr/bin/codex")
+
+ def fake_run(args, **kwargs):
+ out_index = args.index("-o") + 1
+ with open(args[out_index], "w", encoding="utf-8") as f:
+ f.write("42 walls on Level 2")
+ return _completed(args, stdout=json.dumps({"session_id": "codex-session-1"}) + "\n")
+
+ monkeypatch.setattr(agent_bridge.subprocess, "run", fake_run)
+
+ result = agent_bridge.run_agent_turn("codex", "how many walls?", None)
+
+ assert result == {"ok": True, "response": "42 walls on Level 2", "session_id": "codex-session-1"}
+
+
+def test_codex_resume_keeps_session_id_if_not_echoed(monkeypatch):
+ monkeypatch.setattr(agent_bridge, "_CODEX_REGISTRATION_CHECKED", True)
+ monkeypatch.setattr(agent_bridge.shutil, "which", lambda _name: "/usr/bin/codex")
+
+ captured = {}
+
+ def fake_run(args, **kwargs):
+ captured["args"] = args
+ out_index = args.index("-o") + 1
+ with open(args[out_index], "w", encoding="utf-8") as f:
+ f.write("done")
+ return _completed(args, stdout="")
+
+ monkeypatch.setattr(agent_bridge.subprocess, "run", fake_run)
+
+ result = agent_bridge.run_agent_turn("codex", "continue", "codex-session-1")
+
+ assert result["session_id"] == "codex-session-1"
+ assert "resume" in captured["args"]
diff --git a/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.cs b/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.cs
index 3eed972..d93e191 100644
--- a/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.cs
+++ b/packages/revit-bridge-addin/src/UI/BridgePanel.xaml.cs
@@ -16,6 +16,7 @@ namespace RevitBridge.UI
private bool _initialized;
private bool _pageReady;
private readonly Queue<string> _pendingMessages = new Queue<string>();
+ private string? _chatSessionId;
public BridgePanel()
{
@@ -34,7 +35,21 @@ namespace RevitBridge.UI
try
{
- await Browser.EnsureCoreWebView2Async();
+ // Default WebView2 user data folder is next to the host executable —
+ // for a Revit add-in that's Revit.exe under Program Files, which the
+ // current user can't write to (0x80070005 ACCESS_DENIED). Point it at
+ // a writable per-user folder instead; this is Microsoft's documented
+ // fix for any WebView2 host that doesn't run from a writable directory.
+ var userDataFolder = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
+ "AECModelBridge", "WebView2");
+ Directory.CreateDirectory(userDataFolder);
+
+ var environment = await CoreWebView2Environment.CreateAsync(
+ browserExecutableFolder: null,
+ userDataFolder: userDataFolder);
+
+ await Browser.EnsureCoreWebView2Async(environment);
Browser.CoreWebView2.WebMessageReceived += OnWebMessageReceived;
Browser.CoreWebView2.NavigationCompleted += (_, _) =>
{
@@ -86,9 +101,9 @@ namespace RevitBridge.UI
/// <summary>
/// Maps a panel message type to a real hub tool call and posts the result back.
- /// Only the message types app.js currently sends for real workflows are wired;
- /// chat/settings/report-browsing are local-only for now (no corresponding hub
- /// tool) — see docs/product/NEXT_AGENT_HANDOVER.md.
+ /// chat.message shells out to a CLI agent (see agent_bridge.py) rather than
+ /// calling a tool directly; settings/report-browsing remain local-only for now
+ /// (no corresponding hub tool) — see docs/product/NEXT_AGENT_HANDOVER.md.
/// </summary>
private async Task DispatchToHubAsync(string message)
{
@@ -134,6 +149,31 @@ namespace RevitBridge.UI
case "reports.exportExcel":
await RunToolAndPostAsync("report_generator_export_excel", new { }, "reports.updated", type);
break;
+
+ case "chat.message":
+ {
+ var text = root.TryGetProperty("message", out var msgEl) ? msgEl.GetString() : null;
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ break;
+ }
+
+ var provider = root.TryGetProperty("provider", out var providerEl) ? providerEl.GetString() : "claude";
+ var chatResult = await HubClient.ChatAsync(provider ?? "claude", text, _chatSessionId);
+ if (!chatResult.Ok)
+ {
+ PostToPanel(new { type = "chat.error", message = chatResult.Error });
+ break;
+ }
+
+ _chatSessionId = chatResult.SessionId;
+ PostToPanel(new { type = "chat.response", message = chatResult.Response });
+ break;
+ }
+
+ case "chat.reset":
+ _chatSessionId = null;
+ break;
}
}
diff --git a/packages/revit-bridge-addin/src/UI/HubClient.cs b/packages/revit-bridge-addin/src/UI/HubClient.cs
index f9162fc..124349a 100644
--- a/packages/revit-bridge-addin/src/UI/HubClient.cs
+++ b/packages/revit-bridge-addin/src/UI/HubClient.cs
@@ -17,6 +17,11 @@ namespace RevitBridge.UI
{
private static readonly HttpClient Client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
+ // Chat turns shell out to a CLI (agent_bridge.py) that can call the model and
+ // run several tool calls before replying — matches that module's own
+ // 180s subprocess ceiling with headroom, well past the 30s tool-call timeout above.
+ private static readonly HttpClient ChatClient = new HttpClient { Timeout = TimeSpan.FromSeconds(200) };
+
private static int Port
{
get
@@ -45,6 +50,25 @@ namespace RevitBridge.UI
}
}
+ public static async Task<ChatResult> ChatAsync(string provider, string message, string sessionId)
+ {
+ var requestBody = JsonSerializer.Serialize(new { provider, message, session_id = sessionId });
+
+ try
+ {
+ using (var content = new StringContent(requestBody, Encoding.UTF8, "application/json"))
+ using (var response = await ChatClient.PostAsync($"http://127.0.0.1:{Port}/agent/chat", content).ConfigureAwait(false))
+ {
+ var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
+ return ParseChatResponse(text, (int)response.StatusCode);
+ }
+ }
+ catch (Exception ex)
+ {
+ return ChatResult.Failure($"Could not reach the AEC Model Bridge hub on 127.0.0.1:{Port}: {ex.Message}");
+ }
+ }
+
private static HubResult ParseResponse(string text, int statusCode)
{
try
@@ -67,6 +91,30 @@ namespace RevitBridge.UI
return HubResult.Failure($"Hub returned an unparseable response (HTTP {statusCode})");
}
}
+
+ private static ChatResult ParseChatResponse(string text, int statusCode)
+ {
+ try
+ {
+ using (var doc = JsonDocument.Parse(text))
+ {
+ var root = doc.RootElement;
+ var ok = root.TryGetProperty("ok", out var okEl) && okEl.ValueKind == JsonValueKind.True;
+ if (ok && root.TryGetProperty("response", out var responseEl))
+ {
+ var sessionId = root.TryGetProperty("session_id", out var sidEl) ? sidEl.GetString() : null;
+ return ChatResult.Success(responseEl.GetString() ?? string.Empty, sessionId);
+ }
+
+ var error = root.TryGetProperty("error", out var errEl) ? errEl.GetString() : null;
+ return ChatResult.Failure(error ?? $"Hub returned HTTP {statusCode}");
+ }
+ }
+ catch (JsonException)
+ {
+ return ChatResult.Failure($"Hub returned an unparseable response (HTTP {statusCode})");
+ }
+ }
}
internal readonly struct HubResult
@@ -86,4 +134,24 @@ namespace RevitBridge.UI
public static HubResult Failure(string error) => new HubResult(false, default, error);
}
+
+ internal readonly struct ChatResult
+ {
+ public bool Ok { get; }
+ public string Response { get; }
+ public string SessionId { get; }
+ public string Error { get; }
+
+ private ChatResult(bool ok, string response, string sessionId, string error)
+ {
+ Ok = ok;
+ Response = response;
+ SessionId = sessionId;
+ Error = error;
+ }
+
+ public static ChatResult Success(string response, string sessionId) => new ChatResult(true, response, sessionId, null);
+
+ public static ChatResult Failure(string error) => new ChatResult(false, null, null, error);
+ }
}
diff --git a/panel/app.js b/panel/app.js
index d140a96..14547a2 100644
--- a/panel/app.js
+++ b/panel/app.js
@@ -30,6 +30,8 @@ const subtitle = document.getElementById("view-subtitle");
const chatFeed = document.getElementById("chat-feed");
const chatForm = document.getElementById("chat-form");
const chatInput = document.getElementById("chat-input");
+const chatProvider = document.getElementById("chat-provider");
+const chatReset = document.getElementById("chat-reset");
const planList = document.getElementById("plan-list");
const findingList = document.getElementById("finding-list");
const reportList = document.getElementById("report-list");
@@ -168,6 +170,21 @@ function appendMessage(role, text) {
item.innerHTML = `<div class="meta">${role === "user" ? "You" : "AMB"}</div><div>${escapeHtml(text)}</div>`;
chatFeed.appendChild(item);
chatFeed.scrollTop = chatFeed.scrollHeight;
+ return item;
+}
+
+let pendingChatMessage = null;
+
+function resolvePendingChatMessage(text, isError) {
+ if (!pendingChatMessage) {
+ appendMessage("assistant", text);
+ return;
+ }
+ pendingChatMessage.classList.remove("pending");
+ pendingChatMessage.classList.toggle("error", !!isError);
+ pendingChatMessage.querySelector("div:last-child").textContent = text;
+ pendingChatMessage = null;
+ chatFeed.scrollTop = chatFeed.scrollHeight;
}
function renderPlans() {
@@ -315,9 +332,17 @@ chatForm.addEventListener("submit", (event) => {
}
appendMessage("user", text);
chatInput.value = "";
- postToHost("chat.message", { text });
- appendMessage("assistant", "Request sent to the host.");
- addLog("Chat message sent", text);
+ postToHost("chat.message", { message: text, provider: chatProvider.value });
+ pendingChatMessage = appendMessage("assistant", "Thinking…");
+ pendingChatMessage.classList.add("pending");
+ addLog("Chat message sent", `[${chatProvider.value}] ${text}`);
+});
+
+chatReset.addEventListener("click", () => {
+ postToHost("chat.reset");
+ pendingChatMessage = null;
+ renderChat();
+ addLog("Chat reset", "Started a new conversation.");
});
severityFilter.addEventListener("change", renderFindings);
@@ -400,6 +425,14 @@ if (window.chrome && window.chrome.webview) {
if (event.data?.type === "tool.error") {
addLog(`Error: ${event.data.action || "tool"}`, event.data.message || "Unknown error");
}
+ if (event.data?.type === "chat.response") {
+ resolvePendingChatMessage(event.data.message || "(empty response)", false);
+ addLog("Chat response received", "");
+ }
+ if (event.data?.type === "chat.error") {
+ resolvePendingChatMessage(`Error: ${event.data.message || "Unknown error"}`, true);
+ addLog("Chat error", event.data.message || "Unknown error");
+ }
if (event.data?.type === "panel.view" && views[event.data.view]) {
setView(event.data.view);
if (event.data.action) {
diff --git a/panel/index.html b/panel/index.html
index aab60c6..d19cb74 100644
--- a/panel/index.html
+++ b/panel/index.html
@@ -48,8 +48,13 @@
<section class="view is-active" id="view-chat" aria-labelledby="view-title">
<div class="chat-feed" id="chat-feed"></div>
<form class="composer" id="chat-form">
+ <select id="chat-provider" aria-label="Agent">
+ <option value="claude">Claude</option>
+ <option value="codex">Codex</option>
+ </select>
<input id="chat-input" name="message" autocomplete="off" placeholder="Ask about the active model">
<button type="submit">Send</button>
+ <button type="button" id="chat-reset" title="Start a new conversation">New</button>
</form>
</section>
diff --git a/panel/styles.css b/panel/styles.css
index 8fced2f..82b195c 100644
--- a/panel/styles.css
+++ b/panel/styles.css
@@ -274,6 +274,17 @@ p {
background: #eff6ff;
}
+.message.pending {
+ color: var(--muted);
+ font-style: italic;
+}
+
+.message.error {
+ border-color: #f3b4ae;
+ background: #fef2f2;
+ color: var(--red);
+}
+
.message .meta,
.event .meta {
color: var(--muted);
@@ -283,10 +294,15 @@ p {
.composer {
display: grid;
- grid-template-columns: minmax(0, 1fr) auto;
+ grid-template-columns: auto minmax(0, 1fr) auto auto;
gap: 8px;
}
+.composer select {
+ width: auto;
+ max-width: 110px;
+}
+
.composer button,
.settings button,
[data-action="approve-selected"] {
@@ -385,4 +401,9 @@ p {
background: #172554;
border-color: #1d4ed8;
}
+
+ .message.error {
+ background: #3f1d1d;
+ border-color: #7f1d1d;
+ }
}