Skip to content
This repository was archived by the owner on Oct 26, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 47 additions & 6 deletions packages/eaa-core/src/eaa_core/gui/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import queue
import threading
from dataclasses import dataclass, field
from datetime import datetime
from datetime import datetime, timedelta, timezone
from email.utils import formatdate
from typing import Any

Expand Down Expand Up @@ -88,9 +88,11 @@ def __init__(
task_manager: Any,
*,
upload_dir: str = ".tmp",
approval_timeout_seconds: float = 120.0,
) -> None:
self.task_manager = task_manager
self.upload_dir = upload_dir
self.approval_timeout_seconds = approval_timeout_seconds
self.input_queue: queue.Queue[str] = queue.Queue()
self.approval_queue: queue.Queue[bool] = queue.Queue()
self.approval_queues: dict[str, queue.Queue[bool]] = {
Expand All @@ -104,6 +106,7 @@ def __init__(
self.max_log_entries = 500
self.message_event_counter = 0
self.log_event_counter = 0
self.approval_event_counter = 0
self.subagent_counter = 0
self.status = "idle"
self.input_requested = False
Expand Down Expand Up @@ -402,18 +405,29 @@ def request_approval(
),
)
previous_status = conversation.status
self.approval_event_counter += 1
approval_id = f"approval-{self.approval_event_counter}"
requested_at = datetime.now(timezone.utc)
expires_at = requested_at + timedelta(seconds=self.approval_timeout_seconds)
pending_approval = {
"id": approval_id,
"conversation_id": conversation_id,
"tool_name": tool_name,
"arguments": tool_kwargs,
"requested_at": requested_at.isoformat().replace("+00:00", "Z"),
"expires_at": expires_at.isoformat().replace("+00:00", "Z"),
"timeout_seconds": self.approval_timeout_seconds,
}
conversation.pending_approval = dict(pending_approval)
if conversation_id == "primary":
self.pending_approval = dict(pending_approval)
approval_queue = self.approval_queues.setdefault(conversation_id, queue.Queue())
self.publish("approval.requested", pending_approval)
self.set_status("waiting_for_approval", input_requested=True, conversation_id=conversation_id)
approved = approval_queue.get()
try:
approved = approval_queue.get(timeout=self.approval_timeout_seconds)
except queue.Empty:
approved = False
with self.lock:
conversation = self.conversations[conversation_id]
conversation.pending_approval = None
Expand All @@ -422,11 +436,27 @@ def request_approval(
self.set_status(previous_status, input_requested=False, conversation_id=conversation_id)
return approved

def submit_approval(self, approved: bool, conversation_id: str = "primary") -> None:
def submit_approval(
self,
approved: bool,
conversation_id: str = "primary",
approval_id: str | None = None,
*,
require_pending: bool = False,
) -> bool:
"""Queue a tool approval decision."""
with self.lock:
conversation = self.conversations.get(conversation_id)
pending_approval = conversation.pending_approval if conversation else None
if require_pending and pending_approval is None:
return False
if approval_id is not None and (
pending_approval is None or pending_approval.get("id") != approval_id
):
return False
approval_queue = self.approval_queues.setdefault(conversation_id, queue.Queue())
approval_queue.put(approved)
return True

def has_pending_approval(self) -> bool:
"""Return whether a tool approval request is waiting for a response."""
Expand Down Expand Up @@ -595,10 +625,21 @@ async def interrupt() -> dict[str, bool]:
return {"ok": True}

@app.post("/api/approval")
async def approval(payload: dict[str, Any]) -> dict[str, bool]:
async def approval(payload: dict[str, Any]) -> JSONResponse:
conversation_id = str(payload.get("conversation_id") or "primary")
self.controller.submit_approval(bool(payload.get("approved")), conversation_id)
return {"ok": True}
approval_id = payload.get("approval_id")
accepted = self.controller.submit_approval(
bool(payload.get("approved")),
conversation_id,
str(approval_id) if approval_id is not None else None,
require_pending=True,
)
if not accepted:
return JSONResponse(
{"ok": False, "error": "No matching approval request is pending"},
status_code=409,
)
return JSONResponse({"ok": True})

@app.get("/api/skill-catalog")
async def skill_catalog() -> dict[str, list[dict[str, str]]]:
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions packages/eaa-core/src/eaa_core/gui/static/webui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EAA WebUI</title>
<script type="module" crossorigin src="/static/webui/assets/index-BGbkLgDw.js"></script>
<link rel="stylesheet" crossorigin href="/static/webui/assets/index-D-NyMFIS.css">
<script type="module" crossorigin src="/static/webui/assets/index-BGbkLgDw.js?v=approval-timeout-120s"></script>
<link rel="stylesheet" crossorigin href="/static/webui/assets/index-D-NyMFIS.css?v=approval-timeout-120s">
</head>
<body>
<div id="root"></div>
Expand Down
18 changes: 16 additions & 2 deletions packages/eaa-core/src/eaa_core/tool/coding.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,8 +507,8 @@ def execute_code(
)
elif self.sandbox_type == "bubblewrap":
result = self._execute_in_bubblewrap(
[sys.executable, "-c", prepared_code],
env=env,
[os.path.realpath(sys.executable), "-c", prepared_code],
env=self._build_bubblewrap_python_env(env),
timeout=exec_timeout,
input_text=input_text,
workdir=exec_cwd,
Expand Down Expand Up @@ -573,6 +573,20 @@ def _default_python_image() -> str:
"""Return the default Python container image name."""
return f"python:{sys.version_info.major}.{sys.version_info.minor}"

def _build_bubblewrap_python_env(self, env: Dict[str, str]) -> Dict[str, str]:
"""Preserve host import paths when running the resolved interpreter."""
bubblewrap_env = env.copy()
paths = self._bubblewrap_python_import_bind_paths()
paths.extend((env.get("PYTHONPATH") or "").split(os.pathsep))
resolved: list[str] = []
for path in paths:
if not path or path in resolved:
continue
resolved.append(path)
if resolved:
bubblewrap_env["PYTHONPATH"] = os.pathsep.join(resolved)
return bubblewrap_env


class BashCodingTool(CodingTool):
"""Expose a tool that executes Bash code in an isolated subprocess."""
Expand Down
82 changes: 68 additions & 14 deletions packages/eaa-core/webui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,13 @@ const currentImageTimeTitle = () => new Date().toLocaleTimeString([], { hour: "2
const isApprovalMessage = (message: WebUIMessage) =>
String(message.role ?? "") === "system" && /Approve\?\s*\[y\/N\]:/i.test(String(message.content ?? ""));

const formatRemainingTime = (milliseconds: number) => {
const seconds = Math.max(0, Math.ceil(milliseconds / 1000));
const minutes = Math.floor(seconds / 60);
const remainder = seconds % 60;
return `${minutes}:${String(remainder).padStart(2, "0")}`;
};

const formatApproval = (content: unknown) => {
const text = String(content ?? "");
const argsMatch = text.match(/Arguments:\s*([\s\S]*?)\nApprove\?\s*\[y\/N\]:/i);
Expand Down Expand Up @@ -270,11 +277,19 @@ function MessageView({
index: number;
message: WebUIMessage;
onImage: (src: string) => void;
onApproval: (approved: boolean) => Promise<void>;
onApproval: (approved: boolean, approvalId?: string) => Promise<void>;
}) {
const [approvalSubmitted, setApprovalSubmitted] = useState(false);
const [approvalRemainingMs, setApprovalRemainingMs] = useState<number | null>(null);
const role = String(message.role ?? "message");
const content = String(message.content ?? "").trim();
const approvalExpiresAt = useMemo(() => {
if (message.approval_expires_at) return Date.parse(message.approval_expires_at);
if (!message.approval_timeout_seconds) return NaN;
const requestedAt = message.approval_requested_at ? Date.parse(message.approval_requested_at) : Date.now();
return requestedAt + message.approval_timeout_seconds * 1000;
}, [message.approval_expires_at, message.approval_requested_at, message.approval_timeout_seconds]);
const approvalExpired = approvalRemainingMs !== null && approvalRemainingMs <= 0;
const imageSources = useMemo(() => {
const sources: string[] = [];
const seen = new Set<string>();
Expand All @@ -298,9 +313,21 @@ function MessageView({
return sources;
}, [message, role]);

useEffect(() => {
if (!isApprovalMessage(message) || Number.isNaN(approvalExpiresAt)) {
setApprovalRemainingMs(null);
return;
}
const updateRemaining = () => setApprovalRemainingMs(Math.max(0, approvalExpiresAt - Date.now()));
updateRemaining();
const interval = window.setInterval(updateRemaining, 1000);
return () => window.clearInterval(interval);
}, [approvalExpiresAt, message]);

const submitApproval = async (approved: boolean) => {
if (approvalSubmitted || approvalExpired) return;
setApprovalSubmitted(true);
await onApproval(approved);
await onApproval(approved, message.approval_id);
};

return (
Expand Down Expand Up @@ -335,14 +362,31 @@ function MessageView({
</div>
) : null}
{isApprovalMessage(message) ? (
<div className="eaa-approval-actions">
<button className="eaa-approval-button eaa-approval-yes" disabled={approvalSubmitted} type="button" onClick={() => submitApproval(true)}>
Yes
</button>
<button className="eaa-approval-button eaa-approval-no" disabled={approvalSubmitted} type="button" onClick={() => submitApproval(false)}>
No
</button>
</div>
<>
{approvalRemainingMs !== null ? (
<div className={`eaa-approval-timer${approvalExpired ? " eaa-approval-timer-expired" : ""}`}>
{approvalExpired ? "Approval timed out and was rejected." : `Auto-rejects in ${formatRemainingTime(approvalRemainingMs)}`}
</div>
) : null}
<div className="eaa-approval-actions">
<button
className="eaa-approval-button eaa-approval-yes"
disabled={approvalSubmitted || approvalExpired}
type="button"
onClick={() => submitApproval(true)}
>
Yes
</button>
<button
className="eaa-approval-button eaa-approval-no"
disabled={approvalSubmitted || approvalExpired}
type="button"
onClick={() => submitApproval(false)}
>
No
</button>
</div>
</>
) : null}
</div>
</article>
Expand Down Expand Up @@ -696,7 +740,17 @@ function App() {
2,
)}\nApprove? [y/N]: `;
mergeMessages(
[{ id: `approval-${conversationId}-${payload.tool_name || "tool"}-${stringHash(approvalContent)}`, role: "system", content: approvalContent }],
[
{
id: payload.id || `approval-${conversationId}-${payload.tool_name || "tool"}-${stringHash(approvalContent)}`,
role: "system",
content: approvalContent,
approval_id: payload.id,
approval_requested_at: payload.requested_at,
approval_expires_at: payload.expires_at,
approval_timeout_seconds: payload.timeout_seconds,
},
],
conversationId,
);
},
Expand Down Expand Up @@ -774,11 +828,11 @@ function App() {
return () => source.close();
}, [applyStatus, mergeMessages, renderApprovalRequest, upsertConversation]);

const submitApproval = async (approved: boolean, conversationId = activeConversationId) => {
const submitApproval = async (approved: boolean, conversationId = activeConversationId, approvalId?: string) => {
await fetch(config.routes.approval, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ conversation_id: conversationId, approved }),
body: JSON.stringify({ conversation_id: conversationId, approved, approval_id: approvalId }),
});
};

Expand Down Expand Up @@ -1080,7 +1134,7 @@ function App() {
key={messageKey(message, index)}
message={message}
onImage={setPreviewImage}
onApproval={(approved) => submitApproval(approved, activeConversationId)}
onApproval={(approved, approvalId) => submitApproval(approved, activeConversationId, approvalId)}
/>
))}
{activeConversation?.terminated ? <div className="eaa-termination-marker">Subagent terminated</div> : null}
Expand Down
16 changes: 16 additions & 0 deletions packages/eaa-core/webui/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,17 @@ button {
margin-top: 4px;
}

.eaa-approval-timer {
color: #475467;
font-size: 12px;
font-weight: 650;
margin-top: 8px;
}

.eaa-approval-timer-expired {
color: #b42318;
}

.eaa-approval-button {
background: #ffffff;
border: 1px solid #cbd5e1;
Expand All @@ -518,6 +529,11 @@ button {
padding: 7px 12px;
}

.eaa-approval-button:disabled {
cursor: not-allowed;
opacity: 0.55;
}

.eaa-message-images {
display: flex;
flex-wrap: wrap;
Expand Down
8 changes: 8 additions & 0 deletions packages/eaa-core/webui/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ export type WebUIMessage = {
images?: string[];
tool_calls?: unknown;
pending?: boolean;
approval_id?: string;
approval_requested_at?: string;
approval_expires_at?: string;
approval_timeout_seconds?: number;
};

export type RuntimeLogEntry = {
Expand All @@ -50,9 +54,13 @@ export type RuntimeSnapshot = {
};

export type PendingApproval = {
id?: string;
conversation_id?: string;
tool_name?: string;
arguments?: Record<string, unknown>;
requested_at?: string;
expires_at?: string;
timeout_seconds?: number;
};

export type RuntimeConversation = {
Expand Down
Loading
Loading