- Add conversations.tasks hub bridge (backend/plugins/hubtasks.py) and
retire legacy /api/conversation-task-{output,stop} routes & schemas.
- Add generic plugin points: aiAgentPlugin.openDetails(slotId?),
ui.toolCards match.hasField='taskId', match.hasInput, bare, and
inThreadWhile='active', plus task fields on toolCardInit/Update.
- Remove BackgroundShellsCard, BackgroundToolWidgets, and their
visibility/i18n wiring; keep liveBackgroundWork + StatusChip in core
and migrate DETAIL_CARD_RENAMES.backgroundShells.
- Wire background-shells mock harness and tests.
193 lines
8.4 KiB
Python
193 lines
8.4 KiB
Python
"""``conversations.tasks`` — one conversation's background shells and Monitors
|
|
(since 2026-11-27, when the Details drawer's *Background shells* card, header
|
|
chip and background-work tool cards left the core for the ``background-shells``
|
|
plugin).
|
|
|
|
``AIA_TOOLS_URL/plugins/<id>/hub/conversations/{cid}/tasks…``:
|
|
|
|
* ``GET …/tasks`` — every ``run_in_background`` shell and ``claude:Monitor`` of
|
|
the conversation, with its state, events, unread/read stamps, ``meta.taskStops``
|
|
and whether the caller may stop live ones;
|
|
* ``GET …/tasks/{task_id}/output?lines=20`` — tail of ``tasks/<id>.output`` from
|
|
the runner the session lives on (host sidecar or worker, ``_session_worker``);
|
|
* ``POST …/tasks/{task_id}/stop`` — SIGTERM → SIGKILL to the task's process
|
|
group on its runner (the Monitor's command comes from the conversation's own
|
|
card, never the client), stamped on ``meta.taskStops`` and published as SSE
|
|
``meta`` (the plugin's own handlers only).
|
|
|
|
The caller's own visible conversations only; stop checks ``ensure_runs_here``
|
|
and ``can_send(stop=True)``. Not an operator capability.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from core import liveruns
|
|
from runs.service import _session_worker
|
|
from runs.sidecar_client import _sidecar_call
|
|
from users import access
|
|
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
CAP = "conversations.tasks"
|
|
TASK_TOOLS = ("shell", "claude:Monitor")
|
|
MAX_LINES = 200
|
|
_TASK_ID_RE = re.compile(r"^[A-Za-z0-9_.-]{1,120}$")
|
|
_BASE = "/proxy/tools/plugins/{pid}/hub/conversations/{cid:path}/tasks"
|
|
|
|
|
|
def _message(e: HTTPException) -> str:
|
|
d = e.detail
|
|
return d.get("message", str(d)) if isinstance(d, dict) else str(d)
|
|
|
|
|
|
def _resolve_conv(deps, caller, raw_cid: str) -> tuple[str, dict]:
|
|
"""Resolve ``raw_cid`` (conversation id, session id or transcript relpath),
|
|
enforce caller visibility, and return ``(real_cid, parsed_detail)``."""
|
|
from conversations.catalog import _resolve_transcript # noqa: PLC0415
|
|
from conversations.routes import _parse_full_snapshot, _public_id # noqa: PLC0415
|
|
from plugins.hubchecks import locate # noqa: PLC0415
|
|
|
|
hit = locate(deps, raw_cid)
|
|
cid = hit[0] if hit else _public_id(deps, raw_cid)
|
|
access.ensure_visible(deps, caller, cid)
|
|
data, _, _ = _parse_full_snapshot(_resolve_transcript(cid))
|
|
return cid, data
|
|
|
|
|
|
def _task_row(item: dict, task_stops: dict) -> dict:
|
|
inp = item.get("input") if isinstance(item.get("input"), dict) else {}
|
|
cmd = inp.get("command") if isinstance(inp.get("command"), str) else ""
|
|
desc = inp.get("description") if isinstance(inp.get("description"), str) else ""
|
|
tid = item["taskId"]
|
|
kind = "monitor" if item.get("name") == "claude:Monitor" else "shell"
|
|
stop = task_stops.get(tid)
|
|
timeout = inp.get("timeout_ms")
|
|
return {
|
|
"taskId": tid,
|
|
"kind": kind,
|
|
"toolUseId": item.get("toolUseId"),
|
|
"label": desc or (cmd.split("\n", 1)[0] if cmd else "") or tid,
|
|
"command": cmd,
|
|
"description": desc,
|
|
"timeoutMs": timeout if isinstance(timeout, (int, float)) and not isinstance(timeout, bool) else None,
|
|
"ts": item.get("ts"),
|
|
"result": (item.get("result") or "")[:400],
|
|
"isError": bool(item.get("isError")),
|
|
"taskState": item.get("taskState"),
|
|
"taskExitCode": item.get("taskExitCode"),
|
|
"taskEvents": item.get("taskEvents") or [],
|
|
"taskEventsDropped": item.get("taskEventsDropped") or 0,
|
|
"taskUnreadAt": item.get("taskUnreadAt"),
|
|
"taskReadAt": item.get("taskReadAt"),
|
|
"stoppedAt": round(stop * 1000) if isinstance(stop, (int, float)) else None,
|
|
}
|
|
|
|
|
|
def _find_task(deps, caller, conv_id: str, task_id: str) -> tuple[str, dict]:
|
|
if not _TASK_ID_RE.match(task_id or ""):
|
|
raise HTTPException(404, "no such background task in this conversation")
|
|
_, data = _resolve_conv(deps, caller, conv_id)
|
|
sid = data.get("sessionId")
|
|
item = next((it for it in data.get("thread") or []
|
|
if it.get("kind") == "tool_use" and it.get("taskId") == task_id
|
|
and it.get("name") in TASK_TOOLS), None)
|
|
if not sid or item is None:
|
|
raise HTTPException(404, "no such background task in this conversation")
|
|
return sid, item
|
|
|
|
|
|
async def _run(request: Request, pid: str, fn, *, handler_only: bool = False):
|
|
from plugins.hubbridge import _caller_for_who, _check_cap # noqa: PLC0415
|
|
from plugins.proxyroutes import _error # noqa: PLC0415
|
|
|
|
deps, who, _rec, err = _check_cap(request, pid, CAP, handler_only=handler_only)
|
|
if err:
|
|
return err
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
return _error(403, "unknown user", "auth")
|
|
try:
|
|
return await run_in_threadpool(fn, deps, caller)
|
|
except HTTPException as e:
|
|
d = e.detail
|
|
msg = d.get("message") if isinstance(d, dict) else str(d)
|
|
kind = (d.get("kind") if isinstance(d, dict) else None) or (
|
|
"not_found" if e.status_code == 404 else "forbidden" if e.status_code == 403 else "error")
|
|
return _error(e.status_code, msg or "error", kind)
|
|
|
|
|
|
@router.get(_BASE + "/{task_id}/output")
|
|
async def hub_task_output(pid: str, cid: str, task_id: str, request: Request, lines: int = 20):
|
|
"""The last ``lines`` lines a background shell / Monitor wrote."""
|
|
def _do(deps, caller):
|
|
sid, _ = _find_task(deps, caller, cid, task_id)
|
|
try:
|
|
out = _sidecar_call(deps, "/tasks/output",
|
|
{"sessionId": sid, "taskId": task_id,
|
|
"lines": max(1, min(lines, MAX_LINES))},
|
|
timeout=8, worker=_session_worker(deps, sid))
|
|
except HTTPException as e:
|
|
if e.status_code in (404, 409, 502, 503):
|
|
return {"taskId": task_id, "available": False, "lines": [], "reason": _message(e)}
|
|
raise
|
|
return {**out, "taskId": task_id, "available": True}
|
|
|
|
return await _run(request, pid, _do)
|
|
|
|
|
|
@router.post(_BASE + "/{task_id}/stop")
|
|
async def hub_task_stop(pid: str, cid: str, task_id: str, request: Request):
|
|
"""Stop one background shell / Monitor of a live run."""
|
|
def _do(deps, caller):
|
|
sid, item = _find_task(deps, caller, cid, task_id)
|
|
access.ensure_runs_here(deps, caller, sid)
|
|
if not caller.is_owner and not access.can_send(deps, caller, sid, stop=True):
|
|
raise HTTPException(403, "you can read this conversation but not stop it")
|
|
monitor = item.get("name") == "claude:Monitor"
|
|
inp = item.get("input") if isinstance(item.get("input"), dict) else {}
|
|
out = _sidecar_call(deps, "/tasks/stop",
|
|
{"sessionId": sid, "taskId": task_id,
|
|
"kind": "monitor" if monitor else "shell",
|
|
"command": inp.get("command") if monitor else None},
|
|
timeout=20, worker=_session_worker(deps, sid))
|
|
stops = dict(deps.meta_store.peek(sid).get("taskStops") or {})
|
|
stops[task_id] = round(time.time(), 3)
|
|
deps.meta_store.update(sid, {"taskStops": stops})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
return {"ok": True, "taskId": task_id, "forced": bool(out.get("forced"))}
|
|
|
|
return await _run(request, pid, _do, handler_only=True)
|
|
|
|
|
|
@router.get(_BASE)
|
|
async def hub_tasks_list(pid: str, cid: str, request: Request):
|
|
"""Every background shell and Monitor of one conversation, oldest first."""
|
|
def _do(deps, caller):
|
|
real_cid, data = _resolve_conv(deps, caller, cid)
|
|
sid = data.get("sessionId") or ""
|
|
meta = deps.meta_store.peek(sid) or {} if sid else {}
|
|
task_stops = meta.get("taskStops") if isinstance(meta.get("taskStops"), dict) else {}
|
|
running = bool(sid and (liveruns.alive(sid) or meta.get("state") == "running"))
|
|
can_stop = bool(caller.is_owner or (sid and access.can_send(deps, caller, sid, stop=True)))
|
|
tasks = [
|
|
_task_row(it, task_stops)
|
|
for it in data.get("thread") or []
|
|
if it.get("kind") == "tool_use" and it.get("taskId") and it.get("name") in TASK_TOOLS
|
|
]
|
|
return {
|
|
"sessionId": sid,
|
|
"conversationId": real_cid,
|
|
"running": running,
|
|
"canStop": can_stop,
|
|
"taskStops": task_stops,
|
|
"tasks": tasks,
|
|
}
|
|
|
|
return await _run(request, pid, _do)
|