mirror of
https://github.com/open-webui/computer.git
synced 2026-11-26 23:29:25 -05:00
refac
This commit is contained in:
1 parent
97bb12095d
commit
ef7ea5f828
14 files changed
+373
-30
No files matched your search
+134
-2
@@ -53,6 +53,11 @@ command_sessions: dict[str, dict] = {}
|
||||
MAX_COMMAND_SESSIONS = 5
|
||||
_MAX_LOG_SIZE = 50 * 1024 * 1024 # 50MB — rotate when exceeded
|
||||
|
||||
VALID_TASK_STATUSES = {"pending", "in_progress", "completed", "cancelled"}
|
||||
MAX_TASK_ITEMS = 256
|
||||
MAX_TASK_CONTENT_CHARS = 4000
|
||||
_TASK_TRUNCATION_MARKER = "... [truncated]"
|
||||
|
||||
|
||||
def _spawn_pty(command: str, cwd: str, env: dict) -> tuple:
|
||||
"""Spawn a command under a PTY (Unix only). Returns (proc, master_fd)."""
|
||||
@@ -831,6 +836,131 @@ async def create_artifact(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_tasks(tasks: Any, existing_tasks: Any = None, merge: bool = False) -> list[dict]:
|
||||
if isinstance(tasks, str):
|
||||
try:
|
||||
tasks = json.loads(tasks)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return []
|
||||
if not isinstance(tasks, list):
|
||||
return []
|
||||
|
||||
existing = _normalize_tasks(existing_tasks) if merge else []
|
||||
by_id: dict[str, dict] = {task["id"]: task for task in existing}
|
||||
order: list[str] = [task["id"] for task in existing]
|
||||
next_index = len(order)
|
||||
for item in tasks:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
task_id = str(item.get("id", "") or "").strip()
|
||||
current = by_id.get(task_id) if merge and task_id else None
|
||||
content_value = item.get("content")
|
||||
content = str(content_value).strip() if content_value is not None else ""
|
||||
if len(content) > MAX_TASK_CONTENT_CHARS:
|
||||
keep = MAX_TASK_CONTENT_CHARS - len(_TASK_TRUNCATION_MARKER)
|
||||
content = content[:keep] + _TASK_TRUNCATION_MARKER
|
||||
if current and not content:
|
||||
content = current["content"]
|
||||
if not content:
|
||||
continue
|
||||
status = str(item.get("status", current.get("status") if current else "pending")).lower()
|
||||
if status not in VALID_TASK_STATUSES:
|
||||
status = "pending"
|
||||
task_id = task_id or str(next_index + 1)
|
||||
if task_id in by_id and task_id in order:
|
||||
order.remove(task_id)
|
||||
else:
|
||||
next_index += 1
|
||||
by_id[task_id] = {"id": task_id, "content": content, "status": status}
|
||||
order.append(task_id)
|
||||
return [by_id[task_id] for task_id in order][:MAX_TASK_ITEMS]
|
||||
|
||||
|
||||
async def update_tasks(
|
||||
tasks: list[dict[str, Any]],
|
||||
merge: bool = False,
|
||||
*,
|
||||
__context__: dict,
|
||||
) -> str:
|
||||
"""Update the visible Tasks list for this chat.
|
||||
:param tasks: Task items to show. Each item may include id, content, and status.
|
||||
:param merge: If true, update existing tasks by id and append new ones. If false, replace the list.
|
||||
"""
|
||||
from cptr.models import Chat
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
chat_id = __context__.get("chat_id")
|
||||
user_id = __context__.get("user_id")
|
||||
if not chat_id:
|
||||
return json.dumps({"error": "Chat context not available"})
|
||||
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat:
|
||||
return json.dumps({"error": "Chat not found"})
|
||||
|
||||
meta = dict(chat.meta or {})
|
||||
next_tasks = _normalize_tasks(tasks, meta.get("tasks"), merge=merge)
|
||||
summary = {
|
||||
"total": len(next_tasks),
|
||||
"pending": sum(1 for task in next_tasks if task["status"] == "pending"),
|
||||
"in_progress": sum(1 for task in next_tasks if task["status"] == "in_progress"),
|
||||
"completed": sum(1 for task in next_tasks if task["status"] == "completed"),
|
||||
"cancelled": sum(1 for task in next_tasks if task["status"] == "cancelled"),
|
||||
}
|
||||
meta["tasks"] = next_tasks
|
||||
await Chat.update_meta(chat_id, meta, now_ms())
|
||||
|
||||
if user_id:
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"type": "chat:tasks",
|
||||
"chat_id": chat_id,
|
||||
"message_id": __context__.get("message_id"),
|
||||
"tasks": next_tasks,
|
||||
"summary": summary,
|
||||
},
|
||||
)
|
||||
|
||||
return json.dumps({"tasks": next_tasks, "summary": summary}, ensure_ascii=False)
|
||||
|
||||
|
||||
async def clear_active_tasks(
|
||||
chat_id: str, user_id: str | None = None, message_id: str | None = None
|
||||
) -> None:
|
||||
from cptr.models import Chat
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat:
|
||||
return
|
||||
meta = dict(chat.meta or {})
|
||||
tasks = _normalize_tasks(meta.get("tasks"))
|
||||
if not any(task["status"] in {"pending", "in_progress"} for task in tasks):
|
||||
return
|
||||
meta["tasks"] = []
|
||||
await Chat.update_meta(chat_id, meta, now_ms())
|
||||
if user_id:
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"type": "chat:tasks",
|
||||
"chat_id": chat_id,
|
||||
"message_id": message_id,
|
||||
"tasks": [],
|
||||
"summary": {
|
||||
"total": 0,
|
||||
"pending": 0,
|
||||
"in_progress": 0,
|
||||
"completed": 0,
|
||||
"cancelled": 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def write_file(path: str, content: str, *, workspace: str) -> str:
|
||||
"""Write or create a file (full content). Prefer edit_file for modifications.
|
||||
:param path: Path relative to workspace root.
|
||||
@@ -2033,6 +2163,7 @@ TOOLS: dict[str, dict] = {
|
||||
"search_chats": {"fn": search_chats, "auto": True},
|
||||
"list_automations": {"fn": list_automations, "auto": True},
|
||||
"view_skill": {"fn": view_skill, "auto": True},
|
||||
"update_tasks": {"fn": update_tasks, "auto": True},
|
||||
# Write / mutate (require approval unless auto_approve_all)
|
||||
"create_file": {"fn": create_file, "auto": False},
|
||||
"display_file": {"fn": display_file, "auto": False},
|
||||
@@ -2084,10 +2215,10 @@ async def _get_subagent_config() -> dict:
|
||||
from cptr.models import Config
|
||||
|
||||
return {
|
||||
"max_concurrent": int(await Config.get("subagents.max_concurrent") or 3),
|
||||
"max_concurrent": int(await Config.get("subagents.max_concurrent") or 20),
|
||||
"background_enabled": (await Config.get("subagents.background_enabled"))
|
||||
in (True, "true", "1"),
|
||||
"max_async": int(await Config.get("subagents.max_async") or 3),
|
||||
"max_async": int(await Config.get("subagents.max_async") or 20),
|
||||
"max_iterations": int(await Config.get("subagents.max_iterations") or 30),
|
||||
"max_output": int(await Config.get("subagents.max_output") or 30_000),
|
||||
"system_prompt": (await Config.get("subagents.system_prompt")) or _DEFAULT_SUBAGENT_SYSTEM,
|
||||
@@ -2354,6 +2485,7 @@ BUILTIN_TOOL_GROUPS: dict[str, tuple[str, ...]] = {
|
||||
"memory": ("update_memory",),
|
||||
"chats": ("search_chats",),
|
||||
"skills": ("view_skill", "manage_skill"),
|
||||
"tasks": ("update_tasks",),
|
||||
"automations": (
|
||||
"list_automations",
|
||||
"create_automation",
|
||||
|
||||
Reference in new issue
Block a user