diff --git a/backend/app/agent_runs/running.py b/backend/app/agent_runs/running.py new file mode 100644 index 00000000..d4ca5f89 --- /dev/null +++ b/backend/app/agent_runs/running.py @@ -0,0 +1,109 @@ +"""Runs at work now, described once for every screen that lists them: the Dashboard's Running now and the Agents +pages. A run works on a task (or a chat's round), answers a question, runs a cron or writes a Knowledge Base draft.""" + +import uuid +from collections.abc import Collection + +from sqlalchemy import ColumnElement, Select, func, select +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import aliased + +from app.a2a.models import Question +from app.agent_runs.models import AgentRun, RunStatus +from app.agent_runs.schemas import RunningItem +from app.agents.models import Agent +from app.chats.models import Chat +from app.chats.service import chat_link +from app.crons.models import Cron, CronRun +from app.dashboard.scope import task_link +from app.projects.models import Project +from app.tasks.models import Task +from app.workflow.models import DocKind, DocStatus, Stage, TaskWorkflow, WorkflowDocument + + +def run_targets(*columns) -> Select: + """A select over runs with what each works on joined: its task, its question, or its cron run and cron.""" + return ( + select(*columns).select_from(AgentRun) + .outerjoin(Task, Task.id == AgentRun.task_id) + .outerjoin(Question, Question.id == AgentRun.question_id) + .outerjoin(CronRun, CronRun.id == AgentRun.cron_run_id) + .outerjoin(Cron, Cron.id == CronRun.cron_id) + ) + + +def run_project_id() -> ColumnElement[uuid.UUID]: + """The project a run works in (over run_targets): its task's, its question's target, or its cron's; None for a + Knowledge Base draft.""" + return func.coalesce(Task.project_id, Question.target_project_id, Cron.project_id) + + +async def _running( + db: AsyncSession, where: ColumnElement[bool], openable: Collection[uuid.UUID] | None +) -> list[tuple[uuid.UUID, RunningItem]]: + """(agent id, item) for each running run matching `where`, newest started first. `openable`: the projects the + viewer can open (None: all); a run elsewhere keeps its text but loses its link.""" + asking_task, asking_project = aliased(Task), aliased(Project) + project_id = run_project_id() + steps_total = ( + select(func.jsonb_array_length(WorkflowDocument.steps)) + .where(WorkflowDocument.task_id == AgentRun.task_id, WorkflowDocument.kind == DocKind.plan, + WorkflowDocument.status == DocStatus.approved) + .order_by(WorkflowDocument.version.desc()).limit(1).scalar_subquery() + ) + stmt = ( + run_targets(AgentRun.agent_id, AgentRun.id, Agent.name, AgentRun.started_at, project_id, Project.key, + Task.number, Task.title, Task.chat_id, Task.in_chat, Chat.title, AgentRun.stage, AgentRun.step, + steps_total, TaskWorkflow.review_round, AgentRun.question_id, Question.number, + asking_project.key, Cron.id, Cron.name) + .join(Agent, Agent.id == AgentRun.agent_id) + .outerjoin(Project, Project.id == project_id) + .outerjoin(Chat, Chat.id == Task.chat_id) + .outerjoin(TaskWorkflow, TaskWorkflow.task_id == AgentRun.task_id) + .outerjoin(asking_task, asking_task.id == Question.from_task_id) + .outerjoin(asking_project, asking_project.id == asking_task.project_id) + .where(AgentRun.status == RunStatus.running, where) + .order_by(AgentRun.started_at.desc().nulls_last(), AgentRun.id) + ) + out = [] + for (agent_id, run_id, name, started, pid, key, number, task_title, chat_id, in_chat, chat_title, stage, step, + total, rounds, question_id, question_number, asked_from, cron_id, cron_name) in (await db.execute(stmt)).all(): + title = question_key = link = None + if number is not None and in_chat and chat_id: # a chat's round; added to the board it is a plain task + kind, title, link = "chat", chat_title, chat_link(chat_id) + elif number is not None: + kind, title, link = "task", task_title, task_link(key, number) + elif question_id is not None: + kind, question_key, link = "question", f"{key}-Q{question_number}", f"/questions/{question_id}" + elif cron_id is not None: + kind, title, link = "cron", cron_name, f"/projects/{key}/crons/{cron_id}" + else: + kind = "draft" # only the draft's person can open it + if openable is not None and pid not in openable: + link = None + out.append((agent_id, RunningItem( + run_id=run_id, agent_name=name, started_at=started, kind=kind, title=title, + task_key=f"{key}-{number}" if number is not None else None, question_key=question_key, + stage=stage, step=step if stage == Stage.build else None, + steps_total=total if stage == Stage.build else None, + review_round=rounds if stage == Stage.review else None, + question_from=asked_from if question_id else None, + link=link, chat_id=chat_id if kind == "chat" else None, + ))) + return out + + +async def running_items(db: AsyncSession, where: ColumnElement[bool]) -> list[RunningItem]: + """The running runs matching `where` (a condition over run_targets), newest started first.""" + return [item for _, item in await _running(db, where, None)] + + +async def running_by_agent( + db: AsyncSession, agent_ids: Collection[uuid.UUID], openable: Collection[uuid.UUID] | None +) -> dict[uuid.UUID, list[RunningItem]]: + """Each agent's running runs, drafts and cron runs too, newest started first; agents with none are left out.""" + by_agent: dict[uuid.UUID, list[RunningItem]] = {} + if agent_ids: + for agent_id, item in await _running(db, AgentRun.agent_id.in_(set(agent_ids)), openable): + by_agent.setdefault(agent_id, []).append(item) + return by_agent diff --git a/backend/app/agent_runs/schemas.py b/backend/app/agent_runs/schemas.py index c72c0c38..e2bf63a5 100644 --- a/backend/app/agent_runs/schemas.py +++ b/backend/app/agent_runs/schemas.py @@ -1,10 +1,14 @@ import uuid from datetime import datetime +from typing import Literal from pydantic import BaseModel from app.agent_runs.models import RunPolicy, RunStatus from app.agents.models import AgentProgram +from app.workflow.models import Stage + +RunKind = Literal["task", "chat", "question", "cron", "draft"] class RunAgentOut(BaseModel): @@ -26,3 +30,22 @@ class RunOut(BaseModel): created_at: datetime started_at: datetime | None finished_at: datetime | None + + +class RunningItem(BaseModel): + """A run at work now, as the Dashboard's Running now and the Agents pages list it.""" + + run_id: uuid.UUID + agent_name: str + started_at: datetime | None + kind: RunKind + title: str | None = None # the task's title, the chat's title or the cron's name + task_key: str | None + question_key: str | None = None # answering runs: -Q + stage: Stage | None + step: int | None + steps_total: int | None + review_round: int | None + question_from: str | None # answering runs: the asking task's project key + link: str | None # None: a Knowledge Base draft, or a run in a project the viewer cannot open + chat_id: uuid.UUID | None = None diff --git a/backend/app/agents/schemas.py b/backend/app/agents/schemas.py index e9d1b089..77be6a9b 100644 --- a/backend/app/agents/schemas.py +++ b/backend/app/agents/schemas.py @@ -3,6 +3,7 @@ from pydantic import AfterValidator, BaseModel, Field +from app.agent_runs.schemas import RunningItem from app.agents.models import AgentProgram, AnswerMode from app.auth.schemas import UserOut from app.core.text import NoNulStr @@ -99,6 +100,7 @@ class AgentOut(BaseModel): owner: UserOut status: str # busy: every one of its max_concurrent_runs slots is taken running: int = 0 # its running runs; above max_concurrent_runs after the owner lowered it + runs: list[RunningItem] = [] # owner and admins only: what it works on now, newest first problems: list[str] = [] bindings: list[BindingOut] runner: RunnerInfo | None = None # None while the owner's runner is offline @@ -114,4 +116,4 @@ class ProjectAgentOut(AgentOut): class AdminAgentOut(AgentOut): - current_run: dict | None = None + """An agent on Admin → Agents (every agent in the workspace).""" diff --git a/backend/app/agents/service.py b/backend/app/agents/service.py index eccd2928..0d0bd74b 100644 --- a/backend/app/agents/service.py +++ b/backend/app/agents/service.py @@ -1,6 +1,5 @@ import re import uuid -from datetime import UTC, datetime from fastapi import HTTPException, status from sqlalchemy import ColumnElement, func, or_, select, update @@ -32,7 +31,6 @@ WORKFLOW_PROBLEM, registry, ) -from app.tasks.models import Task from app.teams.models import TeamMember from app.teams.service import user_team_ids from app.workflow.models import TaskWorkflow, WorkflowStatus @@ -246,7 +244,8 @@ async def publish_agents_updated( async def _base_fields(db: AsyncSession, agents: list[Agent], viewer: User) -> list[dict]: """Common AgentOut fields. Bindings are limited to projects the viewer can see; - local_path only goes to the owner.""" + local_path only goes to the owner. Runs go to the owner and admins only, and a run in a project the viewer + cannot open has no link.""" if not agents: return [] owners = { @@ -265,6 +264,10 @@ async def _base_fields(db: AsyncSession, agents: list[Agent], viewer: User) -> l statuses = await agent_statuses(db, list(owner_of), {a.id: a.max_concurrent_runs for a in agents}) running = await running_counts(db, list(owner_of)) allowed = await accessible_project_ids(db, viewer) + from app.agent_runs.running import running_by_agent # local: app.chats.service, which it uses, imports this module + + private = [a.id for a in agents if a.owner_id == viewer.id or viewer.role == Role.admin] + runs = await running_by_agent(db, private, allowed) rows = await db.execute( select(AgentBinding, Project.key) .join(Project, Project.id == AgentBinding.project_id) @@ -292,6 +295,7 @@ async def _base_fields(db: AsyncSession, agents: list[Agent], viewer: User) -> l "owner": UserOut.model_validate(owners[a.owner_id]), "status": statuses[a.id], "running": running.get(a.id, 0), + "runs": runs.get(a.id, []), "problems": agent_problems( a.id, a.owner_id, viewer, bool(a.model or a.effort), a.program, stages=bool(a.stage_models) ), @@ -330,35 +334,5 @@ async def project_agents_out( ] -def _newest(running: dict, agent_id: uuid.UUID, run: dict) -> None: - """Keep the most recently started run per agent (a run without a start time counts as oldest).""" - oldest = datetime.min.replace(tzinfo=UTC) - current = running.get(agent_id) - if current is None or (run["started_at"] or oldest) > (current["started_at"] or oldest): - running[agent_id] = run - - async def admin_agents_out(db: AsyncSession, agents: list[Agent], viewer: User) -> list[AdminAgentOut]: - fields = await _base_fields(db, agents, viewer) - from app.a2a.models import Question # local: a2a imports this module - - ids = [a.id for a in agents] - running: dict = {} - # ADM-3: what each agent works on now, a task or (§6.6) a question it answers; the newest run wins - for agent_id, run_id, pkey, num, run_status, started_at in await db.execute( - select(AgentRun.agent_id, AgentRun.id, Project.key, Task.number, AgentRun.status, AgentRun.started_at) - .join(Task, Task.id == AgentRun.task_id) - .join(Project, Project.id == Task.project_id) - .where(AgentRun.agent_id.in_(ids), AgentRun.status == RunStatus.running) - ): - _newest(running, agent_id, {"id": run_id, "kind": "task", "task_key": f"{pkey}-{num}", "status": run_status, - "started_at": started_at}) - for agent_id, run_id, pkey, num, run_status, started_at in await db.execute( - select(AgentRun.agent_id, AgentRun.id, Project.key, Question.number, AgentRun.status, AgentRun.started_at) - .join(Question, Question.id == AgentRun.question_id) - .join(Project, Project.id == Question.target_project_id) - .where(AgentRun.agent_id.in_(ids), AgentRun.status == RunStatus.running) - ): - _newest(running, agent_id, {"id": run_id, "kind": "question", "task_key": f"{pkey}-Q{num}", - "status": run_status, "started_at": started_at}) - return [AdminAgentOut(**f, current_run=running.get(f["id"])) for f in fields] + return [AdminAgentOut(**f) for f in await _base_fields(db, agents, viewer)] diff --git a/backend/app/dashboard/agents.py b/backend/app/dashboard/agents.py index ac2af45f..8c90da83 100644 --- a/backend/app/dashboard/agents.py +++ b/backend/app/dashboard/agents.py @@ -1,38 +1,35 @@ """Agents and their runs: who is working, idle or offline, what is running and queued, and failed runs. A run is in -scope through its task's project, or (a run answering another project's question) the question's target project.""" +scope through its project: its task's, the question's target project (a run answering another project's question), +or its cron's.""" from datetime import UTC, datetime, timedelta -from sqlalchemy import exists, func, select +from sqlalchemy import ColumnElement, and_, exists, func, select from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.orm import aliased -from app.a2a.models import Question from app.agent_runs.models import AgentRun, RunStatus +from app.agent_runs.running import run_project_id, run_targets, running_items from app.agents.models import Agent, AgentBinding from app.agents.service import agent_statuses, runner_info -from app.chats.service import chat_link from app.dashboard.schemas import AgentItem, Queued, QueuedItem, RunningItem from app.dashboard.scope import Scope, task_link from app.projects.models import Project from app.tasks.models import Task -from app.workflow.models import DocKind, DocStatus, Stage, TaskWorkflow, WorkflowDocument QUEUED_SHOWN = 5 _ORDER = {"busy": 0, "busy_elsewhere": 1, "online": 2, "offline": 3} +def _in_scope(scope: Scope) -> ColumnElement[bool]: + """Runs in scope, over run_targets: through their project (a task's, a question's target or a cron's).""" + # a Knowledge Base draft's turns are its person's own: not on anyone's dashboard + cond = and_(AgentRun.draft_id.is_(None), scope.in_projects(run_project_id())) + return and_(cond, AgentRun.agent_id.in_(scope.agent_ids)) if scope.name == "mine" else cond + + def _runs(scope: Scope, *columns): - """A select over runs in scope, with the run's task (if any) and question (if any) joined.""" - stmt = ( - select(*columns).select_from(AgentRun) - .outerjoin(Task, Task.id == AgentRun.task_id).outerjoin(Question, Question.id == AgentRun.question_id) - # a Knowledge Base draft's turns are its person's own: not on anyone's dashboard - .where(AgentRun.draft_id.is_(None), scope.in_projects(func.coalesce(Task.project_id, Question.target_project_id))) - ) - if scope.name == "mine": - stmt = stmt.where(AgentRun.agent_id.in_(scope.agent_ids)) - return stmt + """A select over runs in scope, with the run's task, question and cron joined.""" + return run_targets(*columns).where(_in_scope(scope)) async def agents(db: AsyncSession, scope: Scope) -> list[AgentItem]: @@ -67,39 +64,7 @@ async def agents(db: AsyncSession, scope: Scope) -> list[AgentItem]: async def running(db: AsyncSession, scope: Scope) -> list[RunningItem]: - asking_task, asking_project = aliased(Task), aliased(Project) - steps_total = ( - select(func.jsonb_array_length(WorkflowDocument.steps)) - .where(WorkflowDocument.task_id == AgentRun.task_id, WorkflowDocument.kind == DocKind.plan, - WorkflowDocument.status == DocStatus.approved) - .order_by(WorkflowDocument.version.desc()).limit(1).scalar_subquery() - ) - stmt = ( - _runs(scope, AgentRun.id, Agent.name, AgentRun.started_at, Project.key, Task.number, AgentRun.stage, - AgentRun.step, steps_total, TaskWorkflow.review_round, AgentRun.question_id, asking_project.key, - Task.chat_id, Task.in_chat) - .join(Agent, Agent.id == AgentRun.agent_id) - .outerjoin(Project, Project.id == Task.project_id) - .outerjoin(TaskWorkflow, TaskWorkflow.task_id == AgentRun.task_id) - .outerjoin(asking_task, asking_task.id == Question.from_task_id) - .outerjoin(asking_project, asking_project.id == asking_task.project_id) - .where(AgentRun.status == RunStatus.running) - .order_by(AgentRun.started_at.desc().nulls_last()) - ) - out = [] - for run_id, name, started, key, number, stage, step, total, rounds, question_id, asked_from, chat_id, in_chat in ( - await db.execute(stmt) - ).all(): - out.append(RunningItem( - run_id=run_id, agent_name=name, started_at=started, task_key=f"{key}-{number}" if key else None, - stage=stage, step=step if stage == Stage.build else None, - steps_total=total if stage == Stage.build else None, - review_round=rounds if stage == Stage.review else None, - question_from=asked_from if question_id else None, - link=(chat_link(chat_id) if in_chat else task_link(key, number)) if key else f"/questions/{question_id}", - chat_id=chat_id if in_chat else None, - )) - return out + return await running_items(db, _in_scope(scope)) async def queued(db: AsyncSession, scope: Scope) -> Queued: diff --git a/backend/app/dashboard/schemas.py b/backend/app/dashboard/schemas.py index c917263d..7d6bd204 100644 --- a/backend/app/dashboard/schemas.py +++ b/backend/app/dashboard/schemas.py @@ -4,6 +4,7 @@ from pydantic import BaseModel +from app.agent_runs.schemas import RunningItem from app.agents.schemas import RunnerInfo from app.workflow.models import Stage @@ -53,20 +54,6 @@ class MyTask(BaseModel): link: str -class RunningItem(BaseModel): - run_id: uuid.UUID - agent_name: str - started_at: datetime | None - task_key: str | None - stage: Stage | None - step: int | None - steps_total: int | None - review_round: int | None - question_from: str | None # answering runs: the asking task's project key - link: str - chat_id: uuid.UUID | None = None - - class QueuedItem(BaseModel): task_key: str | None stage: Stage | None diff --git a/backend/tests/agent_runs/test_audit_and_cancel.py b/backend/tests/agent_runs/test_audit_and_cancel.py index 7a960b5c..3789c57f 100644 --- a/backend/tests/agent_runs/test_audit_and_cancel.py +++ b/backend/tests/agent_runs/test_audit_and_cancel.py @@ -109,4 +109,4 @@ async def test_admin_agents_shows_answering_run(client, client_factory, db): finally: _cleanup(m1) [row] = [r for r in rows if r["id"] == a1["id"]] - assert row["current_run"]["kind"] == "question" and row["current_run"]["task_key"] == "QBB-Q1" + assert [(r["kind"], r["question_key"]) for r in row["runs"]] == [("question", "QBB-Q1")] diff --git a/backend/tests/agent_runs/test_dispatch.py b/backend/tests/agent_runs/test_dispatch.py index 1d68ddc3..121ae1a6 100644 --- a/backend/tests/agent_runs/test_dispatch.py +++ b/backend/tests/agent_runs/test_dispatch.py @@ -382,20 +382,20 @@ async def test_deactivation_cancels_runs(db, tc_factory): assert rows == {running["id"]: "cancelled", queued["id"]: "cancelled"} -async def test_delete_agent_with_active_runs_409_and_current_run(client, client_factory, db): +async def test_delete_agent_with_active_runs_409_and_runs(client, client_factory, db): _me, agent, runs = await _offline_runs(client, db) r = await client.delete(f"/api/agents/{agent['id']}") assert r.status_code == 409 and r.json()["detail"] == "agent_has_active_runs" admin = await make_user(db, role=Role.admin) ac = client_factory() await login(ac, admin) - assert (await ac.get("/api/admin/agents")).json()[0]["current_run"] is None # queued, not running + assert (await ac.get("/api/admin/agents")).json()[0]["runs"] == [] # queued, not running await db.execute(update(AgentRun).values(status="running")) await db.commit() row = (await ac.get("/api/admin/agents")).json()[0] assert row["status"] == "busy" - assert row["current_run"]["id"] == runs[0]["id"] and row["current_run"]["status"] == "running" - assert row["current_run"]["task_key"].startswith("PAY-") + assert [(r["run_id"], r["kind"]) for r in row["runs"]] == [(runs[0]["id"], "task")] + assert row["runs"][0]["task_key"].startswith("PAY-") await db.execute(update(AgentRun).values(status="completed")) await db.commit() assert (await client.delete(f"/api/agents/{agent['id']}")).status_code == 204 diff --git a/backend/tests/agents/test_agents.py b/backend/tests/agents/test_agents.py index 157e5e87..1f6f6235 100644 --- a/backend/tests/agents/test_agents.py +++ b/backend/tests/agents/test_agents.py @@ -165,7 +165,7 @@ async def test_admin_agents_overview_admin_only(client, client_factory, db): rows = (await ac.get("/api/admin/agents")).json() assert len(rows) == 1 assert rows[0]["owner"]["id"] == str(owner.id) - assert rows[0]["status"] == "offline" and rows[0]["current_run"] is None + assert rows[0]["status"] == "offline" and rows[0]["runs"] == [] and "current_run" not in rows[0] async def test_can_use_agent_rule(client, db): diff --git a/backend/tests/agents/test_working_on.py b/backend/tests/agents/test_working_on.py new file mode 100644 index 00000000..1c66bee7 --- /dev/null +++ b/backend/tests/agents/test_working_on.py @@ -0,0 +1,62 @@ +"""What an agent works on now (AgentOut.runs): every running run, newest first, for its owner and admins only.""" + +from datetime import UTC, datetime, timedelta + +from app.auth.models import Role +from tests.dashboard.conftest import World, add_chat, add_cron_run, add_draft, add_question, add_run, add_task, world # noqa: F401 (world is a fixture) +from tests.factories import login, make_user + + +def _row(agents: list[dict], name: str) -> dict: + return next(a for a in agents if a["name"] == name) + + +async def _get(client, url: str) -> list[dict]: + r = await client.get(url) + assert r.status_code == 200, r.text + return r.json() + + +async def test_admin_list_has_every_running_run_newest_first(client, db, world: World): + now = datetime.now(UTC) + task = await add_task(db, world.pay) + await add_run(db, world.agent, task=task, started_at=now - timedelta(minutes=5)) + chat = await add_chat(db, world.pay, title="Pricing ideas") + await add_run(db, world.agent, task=await add_task(db, world.pay, chat=chat), started_at=now - timedelta(minutes=4)) + q = await add_question(db, world.pay, status="routed") + await add_run(db, world.agent, question=q, started_at=now - timedelta(minutes=3)) + cron_run = await add_cron_run(db, world.pay, name="Nightly check") + await add_run(db, world.agent, cron_run=cron_run, started_at=now - timedelta(minutes=2)) + draft = await add_draft(db, world.viewer, world.agent, world.pay) + await add_run(db, world.agent, draft=draft, started_at=now - timedelta(minutes=1)) + await add_run(db, world.agent, task=await add_task(db, world.pay), status="queued") + await login(client, await make_user(db, role=Role.admin)) + runs = _row(await _get(client, "/api/admin/agents"), "Viewer bot")["runs"] + assert [r["kind"] for r in runs] == ["draft", "cron", "question", "chat", "task"] + drafted, cron, question, chatting, working = runs + assert (drafted["link"], drafted["title"]) == (None, None) + assert cron["link"] == f"/projects/PAY/crons/{cron_run.cron_id}" + assert question["question_key"] == f"PAY-Q{q.number}" + assert (chatting["title"], chatting["link"]) == ("Pricing ideas", f"/chats/{chat.id}") + assert working["link"] == f"/projects/PAY/board?task={task.key}" + + +async def test_my_agents_lists_the_owners_runs_without_links_they_cannot_open(client, db, world: World): + now = datetime.now(UTC) + pay = await add_task(db, world.pay) + await add_run(db, world.agent, task=pay, started_at=now - timedelta(minutes=2)) + web = await add_task(db, world.web) + await add_run(db, world.agent, task=web, started_at=now - timedelta(minutes=1)) + await login(client, world.viewer) + runs = _row(await _get(client, "/api/agents/mine"), "Viewer bot")["runs"] + assert [(r["task_key"], r["link"]) for r in runs] == [ + (web.key, None), (pay.key, f"/projects/PAY/board?task={pay.key}")] + assert web.key.startswith("WEB-") + + +async def test_project_agents_show_runs_only_to_the_owner_and_admins(client, db, world: World): + await add_run(db, world.agent, task=await add_task(db, world.pay), started_at=datetime.now(UTC)) + await login(client, world.pay_manager) + assert _row(await _get(client, "/api/projects/PAY/agents"), "Viewer bot")["runs"] == [] + await login(client, world.viewer) + assert len(_row(await _get(client, "/api/projects/PAY/agents"), "Viewer bot")["runs"]) == 1 diff --git a/backend/tests/dashboard/conftest.py b/backend/tests/dashboard/conftest.py index 40cdb600..785fad93 100644 --- a/backend/tests/dashboard/conftest.py +++ b/backend/tests/dashboard/conftest.py @@ -12,6 +12,10 @@ from app.agent_runs.models import AgentRun from app.agents.models import Agent, AgentBinding from app.auth.models import Role, User +from app.chats.models import Chat +from app.crons.models import Cron, CronRun +from app.kb import access +from app.kb_drafts.models import KbDraft from app.projects.models import BoardColumn, Project from app.tasks.models import Task from app.teams.models import Team @@ -65,7 +69,7 @@ async def column_id(db, project: Project, category: str) -> uuid.UUID: async def add_task(db, project: Project, *, type: str = "task", category: str = "before", user: User | None = None, agent: Agent | None = None, due: date | None = None, completed_at: datetime | None = None, - title: str = "T") -> Task: + title: str = "T", chat: Chat | None = None) -> Task: number = await db.scalar( update(Project).where(Project.id == project.id).values(next_task_number=Project.next_task_number + 1) .returning(Project.next_task_number) @@ -73,7 +77,7 @@ async def add_task(db, project: Project, *, type: str = "task", category: str = task = Task(project_id=project.id, number=number, type=type, title=title, column_id=await column_id(db, project, category), position=float(number), assignee_user_id=user.id if user else None, assignee_agent_id=agent.id if agent else None, - due_date=due, completed_at=completed_at) + due_date=due, completed_at=completed_at, chat_id=chat.id if chat else None, in_chat=chat is not None) db.add(task) await db.commit() task.key = f"{project.key}-{number}" # plain attribute, for task_key() @@ -99,8 +103,10 @@ async def add_workflow(db, task: Task, *, stage: str, status: str, needs: str | async def add_run(db, agent: Agent, *, task: Task | None = None, question: Question | None = None, status: str = "running", stage: str | None = None, step: int | None = None, - started_at: datetime | None = None, finished_at: datetime | None = None) -> AgentRun: + started_at: datetime | None = None, finished_at: datetime | None = None, + cron_run: CronRun | None = None, draft: KbDraft | None = None) -> AgentRun: run = AgentRun(task_id=task.id if task else None, question_id=question.id if question else None, + cron_run_id=cron_run.id if cron_run else None, draft_id=draft.id if draft else None, agent_id=agent.id, requested_by=agent.owner_id, policy="workspace", prompt="", status=status, stage=stage, step=step, started_at=started_at, finished_at=finished_at) db.add(run) @@ -122,6 +128,31 @@ async def add_question(db, project: Project, *, status: str, from_task: Task | N return q +async def add_chat(db, project: Project, *, title: str = "Chat title") -> Chat: + chat = Chat(project_id=project.id, title=title) + db.add(chat) + await db.commit() + return chat + + +async def add_cron_run(db, project: Project, *, name: str = "Nightly check") -> CronRun: + cron = Cron(project_id=project.id, name=name, prompt="", schedule="0 3 * * *", timezone="UTC") + db.add(cron) + await db.flush() + cron_run = CronRun(cron_id=cron.id, scheduled_at=datetime.now(UTC), status="running") + db.add(cron_run) + await db.commit() + return cron_run + + +async def add_draft(db, user: User, agent: Agent, project: Project) -> KbDraft: + space = await access.space_for_project(db, project.id) + draft = KbDraft(user_id=user.id, agent_id=agent.id, space_id=space.id, brief="A runbook", sources=[]) + db.add(draft) + await db.commit() + return draft + + async def dash(client, scope: str | None = None) -> dict: r = await client.get("/api/dashboard", params={"scope": scope} if scope else None) assert r.status_code == 200, r.text diff --git a/backend/tests/dashboard/test_agents.py b/backend/tests/dashboard/test_agents.py index f6924c94..f5f57795 100644 --- a/backend/tests/dashboard/test_agents.py +++ b/backend/tests/dashboard/test_agents.py @@ -8,7 +8,17 @@ from app.agents.models import Agent, AgentBinding from app.runner.registry import RunnerRegistry, registry from app.workflow.models import WorkflowDocument -from tests.dashboard.conftest import add_question, add_run, add_task, add_workflow, dash, task_key +from tests.dashboard.conftest import ( + add_chat, + add_cron_run, + add_draft, + add_question, + add_run, + add_task, + add_workflow, + dash, + task_key, +) from tests.factories import login @@ -51,6 +61,39 @@ async def test_running_rows_show_build_progress_and_answering_runs(client, db, w assert rows[0]["link"] == f"/questions/{q.id}" +async def test_running_rows_carry_kind_title_and_question_key(client, db, world): + now = datetime.now(UTC) + await add_run(db, world.agent, task=await add_task(db, world.pay, title="Fix the login"), + started_at=now - timedelta(minutes=3)) + chat = await add_chat(db, world.pay, title="Pricing ideas") + await add_run(db, world.agent, task=await add_task(db, world.pay, chat=chat), started_at=now - timedelta(minutes=2)) + q = await add_question(db, world.pay, status="routed") + await add_run(db, world.agent, question=q, started_at=now - timedelta(minutes=1)) + await login(client, world.viewer) + rows = (await dash(client))["running"] + assert [(r["kind"], r["title"], r["question_key"]) for r in rows] == [ + ("question", None, f"PAY-Q{q.number}"), ("chat", "Pricing ideas", None), ("task", "Fix the login", None)] + assert (rows[1]["link"], rows[1]["chat_id"]) == (f"/chats/{chat.id}", str(chat.id)) + + +async def test_a_cron_run_is_in_scope_through_its_project_and_links_to_its_cron(client, db, world): + cron_run = await add_cron_run(db, world.pay, name="Nightly check") + await add_run(db, world.agent, cron_run=cron_run, started_at=datetime.now(UTC)) + await add_run(db, world.other_agent, cron_run=await add_cron_run(db, world.web), started_at=datetime.now(UTC)) + await login(client, world.viewer) + [row] = (await dash(client))["running"] + assert (row["kind"], row["title"], row["link"], row["task_key"]) == ( + "cron", "Nightly check", f"/projects/PAY/crons/{cron_run.cron_id}", None) + + +async def test_a_draft_run_is_not_on_the_dashboard(client, db, world): + draft = await add_draft(db, world.viewer, world.agent, world.pay) + await add_run(db, world.agent, draft=draft, started_at=datetime.now(UTC)) + await login(client, world.viewer) + assert (await dash(client))["running"] == [] + assert (await dash(client, "mine"))["running"] == [] + + async def test_queued_lists_five_and_counts_all(client, db, world): for _ in range(7): await add_run(db, world.agent, task=await add_task(db, world.pay), status="queued", stage="plan") diff --git a/docs/superpowers/plans/MC-37-plan.md b/docs/superpowers/plans/MC-37-plan.md new file mode 100644 index 00000000..53a717cf --- /dev/null +++ b/docs/superpowers/plans/MC-37-plan.md @@ -0,0 +1,417 @@ +# MC-37 implementation plan: every running run on the Agents pages, link first in "Running now" + +## Goal +Both Agents pages list every task, chat, question, cron and draft an agent is working on, each as a link. The Dashboard's "Running now" rows begin with that link, on two lines. + +## Architecture +- **Backend.** `backend/app/agent_runs/running.py` is the one query that describes "a run at work now" as a `RunningItem` (moved to `app/agent_runs/schemas.py`, with new fields `kind`, `title`, `question_key` and a nullable `link`). The Dashboard calls it with its scope filter. `agents/service.py::_base_fields` calls it with the agents' ids and fills the new `AgentOut.runs`, for the owner and for admins only. `AdminAgentOut.current_run` and its two queries go away. +- **Frontend.** `src/lib/runs.ts` holds the stage labels, the status text and the ticking-clock hook. `components/runs/RunLink.tsx` draws the link part. `components/runs/WorkingOn.tsx` draws an agent's list, optionally collapsed to the newest run plus "+N more". RunningNow, Admin → Agents and My agents only arrange these pieces. + +## Conventions for every step +- Work on the current branch `megoo/MC-37-ui-ux-improvements` (it comes from `develop`). One commit per step. The subject is the one given in the step. The body says why and what in plain sentences, and the message ends with `Co-Authored-By: Claude Opus 5.5 `. Never commit `.megoocolab/`. +- TDD: write the test, run it and watch it fail, implement, then run it again. +- Backend checks: `cd backend; uv run pytest -q`, and the full `uv run pytest -q` before committing. Never start two pytest runs at the same time. +- Frontend checks: `cd frontend; npx tsc --noEmit; npx eslint ; npm test`. Don't run Prettier. +- **`frontend/src/lib/api-types.ts` is regenerated (`cd frontend; npm run gen:api`) only in steps 3 and 5.** Those are the steps whose frontend code consumes the changed schema. Steps 1 and 2 change the API but leave the generated types alone, so `tsc` stays green between steps. +- Import cycles: `app.chats.service` imports `app.agents.service`. So `agents/service.py` imports the shared query **inside** `_base_fields`, with a comment, like the existing `from app.a2a.models import Question # local: a2a imports this module`. `running.py` itself imports everything at the top. + +## File map +| File | Change | Responsibility | +|---|---|---| +| `backend/app/agent_runs/schemas.py` | modify | `RunKind`, `RunningItem` (moved here, new fields) | +| `backend/app/agent_runs/running.py` | create | `run_targets`, `run_project_id`, `running_items`, `running_by_agent` | +| `backend/app/dashboard/schemas.py` | modify | drop its own `RunningItem`, import it from `app.agent_runs.schemas` | +| `backend/app/dashboard/agents.py` | modify | `_in_scope`, `_runs` on `run_targets`, `running()` calls `running_items` | +| `backend/app/agents/schemas.py` | modify | `AgentOut.runs`; `AdminAgentOut` loses `current_run` (step 5) | +| `backend/app/agents/service.py` | modify | `_base_fields` fills `runs`; `_newest` and the admin queries removed (step 5) | +| `backend/tests/dashboard/conftest.py` | modify | helpers `add_chat`, `add_cron_run`, `add_draft`; `add_task(chat=)`, `add_run(cron_run=, draft=)` | +| `backend/tests/dashboard/test_agents.py` | modify | new running-row tests | +| `backend/tests/agents/test_working_on.py` | create | runs on admin, mine and project agent lists | +| `backend/tests/agents/test_agents.py`, `tests/agent_runs/test_dispatch.py`, `tests/agent_runs/test_audit_and_cancel.py` | modify | read `runs` instead of `current_run` (step 5) | +| `frontend/src/lib/api-types.ts` | regenerate | steps 3 and 5 | +| `frontend/src/lib/runs.ts` (+ `src/lib/__tests__/runs.test.ts`) | create | `STAGE_LABEL`, `runStatus`, `useNow` | +| `frontend/src/components/runs/RunLink.tsx` (+ `__tests__/RunLink.test.tsx`) | create | the link part of a run | +| `frontend/src/components/runs/WorkingOn.tsx` (+ `__tests__/WorkingOn.test.tsx`) | create | an agent's list of runs, optionally collapsed | +| `frontend/src/components/dashboard/RunningNow.tsx` (+ test, `__tests__/fixture.ts`) | modify | two-line rows | +| `frontend/src/components/dashboard/StageBars.tsx` | modify | import `STAGE_LABEL` from `@/lib/runs` | +| `frontend/src/app/(app)/admin/agents/page.tsx` (+ test) | modify | "Working on" column, runs count in Status | +| `frontend/src/components/agents/AgentsTab.tsx` (+ test) | modify | "Working on" section in `AgentDetails` | +| `frontend/e2e/parallel.spec.ts` | modify | both Agents pages list the three runs | + +## Code A: `backend/app/agent_runs/schemas.py` additions +```python +from typing import Literal +from app.workflow.models import Stage + +RunKind = Literal["task", "chat", "question", "cron", "draft"] + + +class RunningItem(BaseModel): + """A run at work now, as the Dashboard's Running now and the Agents pages list it.""" + + run_id: uuid.UUID + agent_name: str + started_at: datetime | None + kind: RunKind + title: str | None = None # the task's title, the chat's title or the cron's name + task_key: str | None + question_key: str | None = None # answering runs: -Q + stage: Stage | None + step: int | None + steps_total: int | None + review_round: int | None + question_from: str | None # answering runs: the asking task's project key + link: str | None # None: a Knowledge Base draft, or a run in a project the viewer cannot open + chat_id: uuid.UUID | None = None +``` + +## Code B: `backend/app/agent_runs/running.py` +```python +"""Runs at work now, described once for every screen that lists them: the Dashboard's Running now and the Agents +pages. A run works on a task (or a chat's round), answers a question, runs a cron or writes a Knowledge Base draft.""" + +import uuid +from collections.abc import Collection + +from sqlalchemy import ColumnElement, Select, func, select +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import aliased + +from app.a2a.models import Question +from app.agent_runs.models import AgentRun, RunStatus +from app.agent_runs.schemas import RunningItem +from app.agents.models import Agent +from app.chats.models import Chat +from app.chats.service import chat_link +from app.crons.models import Cron, CronRun +from app.dashboard.scope import task_link +from app.projects.models import Project +from app.tasks.models import Task +from app.workflow.models import DocKind, DocStatus, Stage, TaskWorkflow, WorkflowDocument + + +def run_targets(*columns) -> Select: + """A select over runs with what each works on joined: its task, its question, or its cron run and cron.""" + return ( + select(*columns).select_from(AgentRun) + .outerjoin(Task, Task.id == AgentRun.task_id) + .outerjoin(Question, Question.id == AgentRun.question_id) + .outerjoin(CronRun, CronRun.id == AgentRun.cron_run_id) + .outerjoin(Cron, Cron.id == CronRun.cron_id) + ) + + +def run_project_id() -> ColumnElement[uuid.UUID]: + """The project a run works in (over run_targets): its task's, its question's target, or its cron's; None for a + Knowledge Base draft.""" + return func.coalesce(Task.project_id, Question.target_project_id, Cron.project_id) + + +async def _running( + db: AsyncSession, where: ColumnElement[bool], openable: Collection[uuid.UUID] | None +) -> list[tuple[uuid.UUID, RunningItem]]: + """(agent id, item) for each running run matching `where`, newest started first. `openable`: the projects the + viewer can open (None: all); a run elsewhere keeps its text but loses its link.""" + asking_task, asking_project = aliased(Task), aliased(Project) + project_id = run_project_id() + steps_total = ( + select(func.jsonb_array_length(WorkflowDocument.steps)) + .where(WorkflowDocument.task_id == AgentRun.task_id, WorkflowDocument.kind == DocKind.plan, + WorkflowDocument.status == DocStatus.approved) + .order_by(WorkflowDocument.version.desc()).limit(1).scalar_subquery() + ) + stmt = ( + run_targets(AgentRun.agent_id, AgentRun.id, Agent.name, AgentRun.started_at, project_id, Project.key, + Task.number, Task.title, Task.chat_id, Task.in_chat, Chat.title, AgentRun.stage, AgentRun.step, + steps_total, TaskWorkflow.review_round, AgentRun.question_id, Question.number, + asking_project.key, Cron.id, Cron.name) + .join(Agent, Agent.id == AgentRun.agent_id) + .outerjoin(Project, Project.id == project_id) + .outerjoin(Chat, Chat.id == Task.chat_id) + .outerjoin(TaskWorkflow, TaskWorkflow.task_id == AgentRun.task_id) + .outerjoin(asking_task, asking_task.id == Question.from_task_id) + .outerjoin(asking_project, asking_project.id == asking_task.project_id) + .where(AgentRun.status == RunStatus.running, where) + .order_by(AgentRun.started_at.desc().nulls_last(), AgentRun.id) + ) + out = [] + for (agent_id, run_id, name, started, pid, key, number, task_title, chat_id, in_chat, chat_title, stage, step, + total, rounds, question_id, question_number, asked_from, cron_id, cron_name) in (await db.execute(stmt)).all(): + title = question_key = link = None + if number is not None and in_chat and chat_id: # a chat's round; added to the board it is a plain task + kind, title, link = "chat", chat_title, chat_link(chat_id) + elif number is not None: + kind, title, link = "task", task_title, task_link(key, number) + elif question_id is not None: + kind, question_key, link = "question", f"{key}-Q{question_number}", f"/questions/{question_id}" + elif cron_id is not None: + kind, title, link = "cron", cron_name, f"/projects/{key}/crons/{cron_id}" + else: + kind = "draft" # only the draft's person can open it + if openable is not None and pid not in openable: + link = None + out.append((agent_id, RunningItem( + run_id=run_id, agent_name=name, started_at=started, kind=kind, title=title, + task_key=f"{key}-{number}" if number is not None else None, question_key=question_key, + stage=stage, step=step if stage == Stage.build else None, + steps_total=total if stage == Stage.build else None, + review_round=rounds if stage == Stage.review else None, + question_from=asked_from if question_id else None, + link=link, chat_id=chat_id if kind == "chat" else None, + ))) + return out + + +async def running_items(db: AsyncSession, where: ColumnElement[bool]) -> list[RunningItem]: + """The running runs matching `where` (a condition over run_targets), newest started first.""" + return [item for _, item in await _running(db, where, None)] + + +async def running_by_agent( + db: AsyncSession, agent_ids: Collection[uuid.UUID], openable: Collection[uuid.UUID] | None +) -> dict[uuid.UUID, list[RunningItem]]: + """Each agent's running runs, drafts and cron runs too, newest started first; agents with none are left out.""" + by_agent: dict[uuid.UUID, list[RunningItem]] = {} + if agent_ids: + for agent_id, item in await _running(db, AgentRun.agent_id.in_(set(agent_ids)), openable): + by_agent.setdefault(agent_id, []).append(item) + return by_agent +``` + +## Code C: `backend/app/dashboard/agents.py` changes +```python +from sqlalchemy import and_, exists, func, select +from app.agent_runs.running import run_project_id, run_targets, running_items + + +def _in_scope(scope: Scope) -> ColumnElement[bool]: + """Runs in scope, over run_targets: through their project (a task's, a question's target or a cron's).""" + # a Knowledge Base draft's turns are its person's own: not on anyone's dashboard + cond = and_(AgentRun.draft_id.is_(None), scope.in_projects(run_project_id())) + return and_(cond, AgentRun.agent_id.in_(scope.agent_ids)) if scope.name == "mine" else cond + + +def _runs(scope: Scope, *columns): + """A select over runs in scope, with the run's task, question and cron joined.""" + return run_targets(*columns).where(_in_scope(scope)) + + +async def running(db: AsyncSession, scope: Scope) -> list[RunningItem]: + return await running_items(db, _in_scope(scope)) +``` +Update the module docstring: a run is in scope through its task's project, the question's target project, or its cron's project. Remove the imports that are no longer used (`aliased`, `chat_link`, `Project` only if `queued` stops using it (it still does), `TaskWorkflow`, `WorkflowDocument`, `DocKind`, `DocStatus`, `Stage`). `from sqlalchemy import ColumnElement` is needed for the type hint. `RunningItem` keeps coming from `app.dashboard.schemas`. + +## Code D: test helpers in `backend/tests/dashboard/conftest.py` +```python +from app.chats.models import Chat +from app.crons.models import Cron, CronRun +from app.kb import access +from app.kb_drafts.models import KbDraft + +# add_task gains `chat: Chat | None = None`: Task(..., chat_id=chat.id if chat else None, in_chat=chat is not None) +# add_run gains `cron_run: CronRun | None = None, draft: KbDraft | None = None`: +# AgentRun(..., cron_run_id=cron_run.id if cron_run else None, draft_id=draft.id if draft else None) + + +async def add_chat(db, project: Project, *, title: str = "Chat title") -> Chat: + chat = Chat(project_id=project.id, title=title) + db.add(chat) + await db.commit() + return chat + + +async def add_cron_run(db, project: Project, *, name: str = "Nightly check") -> CronRun: + cron = Cron(project_id=project.id, name=name, prompt="", schedule="0 3 * * *", timezone="UTC") + db.add(cron) + await db.flush() + cron_run = CronRun(cron_id=cron.id, scheduled_at=datetime.now(UTC), status="running") + db.add(cron_run) + await db.commit() + return cron_run + + +async def add_draft(db, user: User, agent: Agent, project: Project) -> KbDraft: + space = await access.space_for_project(db, project.id) + draft = KbDraft(user_id=user.id, agent_id=agent.id, space_id=space.id, brief="A runbook", sources=[]) + db.add(draft) + await db.commit() + return draft +``` + +## Code E: `frontend/src/lib/runs.ts` +```ts +import { useEffect, useState } from "react"; + +import type { RunningItem } from "@/lib/dashboard"; +import { STAGES } from "@/lib/workflow"; + +/** A run in the Done stage is the finish run. */ +export const STAGE_LABEL: Record = { + ...Object.fromEntries(STAGES.map((s) => [s.id, s.label])), + done: "Finishing", +}; + +/** What a run with no workflow stage is doing. */ +const NO_STAGE: Record = { + task: "Working", chat: "Working", question: "Answering", cron: "Running", draft: "Writing", +}; + +/** A run's status: the stage, with the step in Build and the round past the first in Review. */ +export function runStatus(run: RunningItem): string { + if (!run.stage) return NO_STAGE[run.kind]; + const stage = STAGE_LABEL[run.stage]; + if (run.stage === "build" && run.step && run.steps_total) return `${stage} · Step ${run.step} of ${run.steps_total}`; + if (run.stage === "review" && run.review_round && run.review_round > 1) return `${stage}, round ${run.review_round}`; + return stage; +} + +/** The time now, ticking every second, for running times counted in the browser. */ +export function useNow(): number { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const id = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(id); + }, []); + return now; +} +``` + +## Code F: `frontend/src/components/runs/RunLink.tsx` +```tsx +import Link from "next/link"; + +import type { RunningItem } from "@/lib/dashboard"; + +const TAG = { chat: "border-violet text-violet", cron: "border-line text-muted-foreground" } as const; + +/** What a run works on, as a link: a task's key, a chat's or cron's tag and title, a question's key. A draft, or a + * run the viewer cannot open, is the same text without the link. A key never shortens; a title does. */ +export function RunLink({ run }: { run: RunningItem }) { + const keyed = run.kind === "task" || run.kind === "question"; + const text = + run.kind === "task" ? run.task_key + : run.kind === "question" ? run.question_key + : run.kind === "draft" ? "Knowledge Base draft" + : run.title; + const look = keyed ? "shrink-0 font-mono text-xs" : "min-w-0 truncate"; + const tag = run.kind === "chat" || run.kind === "cron" ? run.kind : null; + return ( + <> + {tag && {tag}} + {run.link ? ( + + {text ?? run.kind} + + ) : ( + {text ?? run.kind} + )} + + ); +} +``` + +## Code G: RunningNow row (replaces the `running.map` body) +```tsx +
  • +
    + + + {run.kind === "task" && run.title && {run.title}} +
    +
    + {run.agent_name} + {runStatus(run)} + {run.started_at && {shortDuration(now - Date.parse(run.started_at))}} +
    +
  • +``` + +## Code H: `frontend/src/components/runs/WorkingOn.tsx` +```tsx +"use client"; + +import { useId, useState } from "react"; + +import { RunLink } from "@/components/runs/RunLink"; +import { type RunningItem, shortDuration } from "@/lib/dashboard"; +import { runStatus, useNow } from "@/lib/runs"; + +/** What an agent is working on, newest first. `collapsed`: the newest only, the rest behind "+N more" (the + * Admin table keeps its rows one height). `titles`: a task's title after its key. No run: a dash. */ +export function WorkingOn({ runs, collapsed = false, titles = false }: { runs: RunningItem[]; collapsed?: boolean; titles?: boolean }) { + const [open, setOpen] = useState(false); + const now = useNow(); + const id = useId(); + if (runs.length === 0) return —; + const shown = collapsed && !open ? runs.slice(0, 1) : runs; + return ( +
    +
      + {shown.map((run) => ( +
    • + + {titles && run.kind === "task" && run.title && {run.title}} + {runStatus(run)} + {run.started_at && ( + {shortDuration(now - Date.parse(run.started_at))} + )} +
    • + ))} +
    + {collapsed && runs.length > 1 && ( + + )} +
    + ); +} +``` + +## Steps + +### 1. Shared running-runs query on the backend; the Dashboard uses it and counts cron runs through their project +See the step detail. It uses Code A to D. + +### 2. Agents carry their running runs (`AgentOut.runs`) for the owner and admins +See the step detail. + +### 3. Dashboard "Running now": two-line rows with the link first (lib/runs.ts, RunLink) +See the step detail. It uses Code E to G. + +### 4. WorkingOn component: an agent's runs, optionally collapsed behind "+N more" +See the step detail. It uses Code H. + +### 5. Admin → Agents: "Working on" column and run count; `current_run` removed +See the step detail. + +### 6. My agents: "Working on" section on the agent's card +See the step detail. + +### 7. Browser test: both Agents pages list an agent's three runs at once +See the step detail. + +(The step details in the `steps` array are the full instructions for each step.) + +## Final verification +``` +cd backend; uv run pytest -q +cd frontend; npx tsc --noEmit; npx eslint src/lib/runs.ts src/components/runs src/components/dashboard/RunningNow.tsx src/components/dashboard/StageBars.tsx "src/app/(app)/admin/agents/page.tsx" src/components/agents/AgentsTab.tsx e2e/parallel.spec.ts; npm test +``` +Then run the browser tests on a fresh e2e stack, as AGENTS.md describes (`npx playwright test --reporter=line`). They must all pass, `parallel.spec.ts` included. `dashboard.spec.ts` and `agents.spec.ts` don't read the old row text, so they need no change. They must still pass. + +Requirement check: +- Every run is listed on both Agents pages: steps 2, 5 and 6. +- Admin "newest + more": steps 4 and 5. +- My agents not collapsed and hidden when idle: step 6. +- Link first on two lines in "Running now": step 3. +- Cron and draft rules, chat title, question key: steps 1 and 3. +- `link` null when the viewer can't open the run: steps 1 and 2. +- Run count in the Admin status cell: step 5. +- `current_run` removed: step 5. +- Browser tests: step 7. diff --git a/docs/superpowers/specs/MC-37-design.md b/docs/superpowers/specs/MC-37-design.md new file mode 100644 index 00000000..b854e8d5 --- /dev/null +++ b/docs/superpowers/specs/MC-37-design.md @@ -0,0 +1,93 @@ +# MC-37: show all of an agent's running work, and put the link first in "Running now" + +This design goes with mockup **v4** ("Final: Running now (two lines), Admin Agents (newest + more), My agents (Working on)"). + +## Goal + +- On the two Agents pages, an agent shows **every** task, chat and other run it is working on, each as a link. Today Admin → Agents shows only the newest run as plain text, and My agents shows only a count. +- On the Dashboard, each "Running now" row starts with the link to the task or chat, then the agent, then the status. Today the agent's name comes first and a long name pushes the link out of view. + +## Decisions + +| Question | Answer | Rejected | +|---|---|---| +| Admin → Agents: how to list the runs | **C: the newest run, the rest behind a "+N more" button** that opens them in place (chosen by the human) | A: one line per run, always open. B: chips. | +| Dashboard "Running now" row | **B: two lines**: line 1 the link with the title, line 2 agent, status chip, time (chosen by the human) | A: one line. C: aligned columns. | +| Which Agents pages | **Both**: Admin → Agents and My agents (chosen by the human) | Admin → Agents only. | + +Decisions I made, for you to confirm by approving: + +1. **My agents lists every run, with nothing to open.** The agent's card has room, so the "+N more" button is used only in the Admin table, where rows should keep one height. +2. **Cron runs and Knowledge Base drafts are listed too.** An agent's count ("3 of 3 running") includes them, so a list that left them out would not add up. A cron run links to its cron page. A draft is plain text ("Knowledge Base draft"), because only the draft's person can open it. The Dashboard keeps leaving drafts out, as it does today. +3. **A chat shows its title** (with the "chat" tag) instead of the word "chat", and **a question shows its key** (for example `MC-Q12`), on all three screens. +4. **A run the viewer cannot open is shown without a link.** This can only happen on My agents, when the owner lost access to a project while their agent was still running there. +5. **The Admin table's status cell also says how many runs are in use** ("3 of 3 running"), with the wording My agents already uses. +6. **`current_run` is removed** from the admin API and replaced by the new `runs` list. Only the Admin → Agents page reads it. + +## Architecture + +One description of "a run that is running now" is built in one place on the backend and drawn by one set of components on the frontend. The three screens then differ only in layout. + +### Backend + +- **New `backend/app/agent_runs/running.py`**: the shared query. It takes a filter (the dashboard's scope, or a list of agent ids) and the viewer, and returns `RunningItem` rows, newest started first. It holds the joins that `dashboard/agents.py::running` has today (task, project, workflow, plan steps, question and asking project) plus chat (for the title), cron run and cron (for the name and project). +- **`backend/app/dashboard/agents.py`**: `running()` calls the shared query with the scope. `_runs` adds the cron's project to the scope check, so a cron run is in scope through its project like any other run. `RunningItem` moves to `agent_runs` and `dashboard/schemas.py` imports it from there, so the API name stays the same. +- **`backend/app/agents/service.py`**: `_base_fields` fills a new `runs` field, for the agent's owner and for admins only (the same rule `_machine` uses). Other viewers get an empty list, so the project's agent list does not reveal work in projects a member cannot see. `admin_agents_out` loses its two queries and the `_newest` helper. +- **`backend/app/agents/schemas.py`**: `AgentOut.runs: list[RunningItem] = []`; `AdminAgentOut.current_run` is removed. + +No migration, no new endpoint, no new live event. Runs already publish `agents.updated` when they start and finish, which refreshes both Agents pages; the Dashboard already refreshes on live events. + +### Frontend + +- **New `frontend/src/lib/runs.ts`**: `STAGE_LABEL` and the status text (moved out of `RunningNow.tsx`), plus a `useNow()` hook for the ticking time (also moved out of `RunningNow.tsx`). +- **New `frontend/src/components/runs/RunLink.tsx`**: the link part of a row. Task: the key in mono. Chat: "chat" tag and the title. Question: the question key. Cron: "cron" tag and the cron's name. Draft: "Knowledge Base draft". No `link`: the same text, not clickable. +- **New `frontend/src/components/runs/WorkingOn.tsx`**: the list of an agent's runs for the Agents pages, with a `collapsed` option (newest run plus a "+N more" / "Show less" button with `aria-expanded`). The open state is kept in the component, per row, and is not saved. +- **`components/dashboard/RunningNow.tsx`**: each row becomes two lines, as in the mockup. Line 1: dot, `RunLink`, title. Line 2: agent name (this is what shortens), status chip, time. The queued line and the "All runs" link do not change. +- **`app/(app)/admin/agents/page.tsx`**: the "Current run" column becomes "Working on" and renders `WorkingOn collapsed`; the status cell adds `runsLabel(...)`. The phone card gets the same content under the "Working on" label. +- **`components/agents/AgentsTab.tsx`**: `AgentDetails` gets a "Working on" section between the header and Settings, rendering `WorkingOn` (not collapsed, with titles). It is hidden while the agent runs nothing. The list on the left does not change. +- `frontend/src/lib/api-types.ts` is regenerated with `npm run gen:api`. + +## Data and interfaces + +`RunningItem` (returned in `DashboardOut.running`, and now in `AgentOut.runs`): + +| Field | Change | Meaning | +|---|---|---| +| `kind` | new | `task`, `chat`, `question`, `cron` or `draft` | +| `title` | new | the task's title, the chat's title or the cron's name; null for a question and a draft | +| `question_key` | new | `-Q` for an answering run, else null | +| `link` | now nullable | null for a draft, and for a run in a project the viewer cannot open | +| `run_id`, `agent_name`, `started_at`, `task_key`, `stage`, `step`, `steps_total`, `review_round`, `question_from`, `chat_id` | unchanged | | + +Links: a task opens the board with its drawer (`task_link`), a chat round opens the chat (`chat_link`), a question opens `/questions/`, a cron opens `/projects//crons/`. + +Status text: the stage label, with "Step 2 of 5" in Build and the round in Review, as today. For a run with no stage: "Answering" (question), "Running" (cron), "Writing" (draft), "Working" (a freestyle chat turn). + +`GET /api/admin/agents`: `current_run` is gone, `runs` is there. `GET /api/agents/mine` (and the create, patch and bindings responses, which share `AgentOut`): `runs` is filled. + +## Error handling and edge cases + +- **More runs than the limit** (the owner lowered "Runs at once" while runs were going): all of them are listed, and the count reads "3 running, limit 2" as it does today. +- **One run**: no "+N more" button. **No run**: "—" in the Admin table; no "Working on" section on My agents. +- **A run with no start time** sorts last and shows no time. +- **A chat round that was added to the board** is an ordinary task and shows as one (the existing `in_chat` rule). +- **Cron runs on the Dashboard**: today, under "Everything", a cron run appears as "Answering a question" with a link to `/questions/None`. With this change it shows as a cron row with a working link, in every scope its project belongs to. +- **Long titles and names** shorten with an ellipsis. The link's key never shortens, and the full task title is in the link's tooltip in the Admin table. +- **Phone**: the Admin card and the My agents card use the same lists; the lines wrap under the "Working on" label. + +## Testing + +Tests are written first, as the repository's rules ask. + +- **Backend, `tests/agents`**: the admin list returns every running run of an agent, newest first, covering a task, a chat (with its title and chat link), a question (with its key), a cron (name and link) and a draft (no link); queued runs are not listed. `/api/agents/mine` returns the owner's runs. A run in a project the owner cannot access comes back with `link` null. The project agents list returns no runs to a member who is neither owner nor admin. +- **Backend, `tests/dashboard/test_agents.py`**: running rows carry `kind`, `title` and `question_key`; a cron run is in scope through its project and links to the cron page; a draft is still left out. +- **Backend, existing tests that read `current_run`** (`test_dispatch.py`, `test_audit_and_cancel.py`, `tests/agents/test_agents.py`) are changed to read `runs`. +- **Frontend (Vitest)**: `RunningNow.test.tsx`: the link comes before the agent and the status in each row, a chat shows its title, a question its key, the time still ticks. Admin page test: the labels are Owner, Agent, Program, Status, "Working on"; "+2 more" opens the other runs and "Show less" closes them; entries are links. `AgentsTab.test.tsx`: the card lists every run and hides the section when there is none. `RunLink`: a row without a link is not clickable. +- **Browser tests**: `dashboard.spec.ts`, `agents.spec.ts` and `parallel.spec.ts` are updated where they read the old row text, and `parallel.spec.ts` checks that two runs at once both show on the Agents page. + +## Out of scope + +- The Dashboard's "Agents" card and the "Queued" line. +- The project's agent list and the team page. +- Stopping or opening a run's log from these lists. +- Any change to how runs are counted, limited or dispatched. diff --git a/frontend/e2e/parallel.spec.ts b/frontend/e2e/parallel.spec.ts index 4ba524f7..74f6d00d 100644 --- a/frontend/e2e/parallel.spec.ts +++ b/frontend/e2e/parallel.spec.ts @@ -83,6 +83,18 @@ test("an agent works on three chats at once, and its limit can be raised and low await card.getByRole("button", { name: "Save runs at once" }).click(); await expect(card.getByText("3 of 3 running")).toBeVisible({ timeout: 30_000 }); await expect(card.getByText("Busy")).toBeVisible(); + // every run shows on the card, each a link to its chat + const list = card.getByRole("list", { name: "Working on" }); + await expect(list.getByRole("listitem")).toHaveCount(3); + await expect(list.getByRole("link")).toHaveCount(3); + // Admin → Agents: the newest, and the other two behind +2 more + await page.goto("/admin/agents"); + const row = page.getByRole("row").filter({ hasText: AGENT_NAME }); + await expect(row.getByText("3 of 3 running")).toBeVisible(); + await expect(row.getByRole("list", { name: "Working on" }).getByRole("listitem")).toHaveCount(1); + await row.getByRole("button", { name: "+2 more" }).click(); + await expect(row.getByRole("list", { name: "Working on" }).getByRole("listitem")).toHaveCount(3); + await page.goto(`/settings/agents?agent=${agent.id}`); // 3. lowered to 1 while all three run: they keep going, and the card says so await card.getByLabel("Runs at once", { exact: true }).fill("1"); diff --git a/frontend/src/app/(app)/admin/agents/__tests__/page.test.tsx b/frontend/src/app/(app)/admin/agents/__tests__/page.test.tsx index 6f28fde8..16acbe20 100644 --- a/frontend/src/app/(app)/admin/agents/__tests__/page.test.tsx +++ b/frontend/src/app/(app)/admin/agents/__tests__/page.test.tsx @@ -1,5 +1,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, render, screen } from "@testing-library/react"; +import { cleanup, render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { afterEach, describe, expect, it, vi } from "vitest"; vi.mock("next/navigation", () => ({ @@ -8,10 +9,11 @@ vi.mock("next/navigation", () => ({ })); import AdminAgentsPage from "@/app/(app)/admin/agents/page"; +import { run } from "@/components/dashboard/__tests__/fixture"; const AGENT = { id: "a1", name: "Mo's Claude Code", program: "claude_code", model: null, effort: null, status: "online", - owner: { id: "u1", name: "Mo" }, machine: null, runner: null, current_run: null, + owner: { id: "u1", name: "Mo" }, machine: null, runner: null, running: 0, max_concurrent_runs: 3, runs: [], }; afterEach(() => { @@ -19,24 +21,54 @@ afterEach(() => { vi.unstubAllGlobals(); }); +function renderPage(agents: unknown[]) { + vi.stubGlobal( + "fetch", + vi.fn(async (url: string) => + new Response(JSON.stringify(url === "/api/auth/me" ? { user: { id: "u1", role: "admin" } } : agents), { status: 200 }), + ), + ); + render( + + + , + ); +} + +const row = async () => (await screen.findByText("Mo's Claude Code")).closest("tr")!; + describe("admin agents", () => { it("on phones each agent is a card with labelled values", async () => { - vi.stubGlobal( - "fetch", - vi.fn(async (url: string) => - new Response(JSON.stringify(url === "/api/auth/me" ? { user: { id: "u1", role: "admin" } } : [AGENT]), { status: 200 }), - ), - ); - render( - - - , - ); + renderPage([AGENT]); const cell = (await screen.findByText("Mo's Claude Code")).closest("td")!; const table = cell.closest("table")!; expect(table).toHaveClass("max-md:block"); expect(table.querySelector("thead")).toHaveClass("max-md:hidden"); const labels = Array.from(cell.closest("tr")!.querySelectorAll("td")).map((td) => td.getAttribute("data-label")); - expect(labels).toEqual(["Owner", "Agent", "Program", "Status", "Current run"]); + expect(labels).toEqual(["Owner", "Agent", "Program", "Status", "Working on"]); + }); + + it("lists the newest run and opens the rest", async () => { + const user = userEvent.setup(); + const runs = [ + run(), + run({ run_id: "r2", kind: "chat", title: "Pricing ideas", task_key: null, chat_id: "c1", link: "/chats/c1", stage: null }), + run({ run_id: "r3", kind: "question", title: null, task_key: null, question_key: "PAY-Q12", link: "/questions/q1", stage: null }), + ]; + renderPage([{ ...AGENT, status: "busy", running: 3, runs }]); + const tr = await row(); + expect(within(tr).getByText("3 of 3 running")).toBeInTheDocument(); + expect(within(tr).getAllByRole("link").map((a) => a.textContent)).toEqual(["PAY-14"]); + await user.click(within(tr).getByRole("button", { name: "+2 more" })); + expect(within(tr).getAllByRole("link")).toHaveLength(3); + await user.click(within(tr).getByRole("button", { name: "Show less" })); + expect(within(tr).getAllByRole("link")).toHaveLength(1); + }); + + it("an agent with no runs shows a dash under Working on", async () => { + renderPage([AGENT]); + const cell = (await row()).querySelector('td[data-label="Working on"]')!; + expect(cell).toHaveTextContent("—"); + expect(within(await row()).queryByText(/running/)).toBeNull(); }); }); diff --git a/frontend/src/app/(app)/admin/agents/page.tsx b/frontend/src/app/(app)/admin/agents/page.tsx index 0ab80393..96e96099 100644 --- a/frontend/src/app/(app)/admin/agents/page.tsx +++ b/frontend/src/app/(app)/admin/agents/page.tsx @@ -5,6 +5,8 @@ import { useQuery } from "@tanstack/react-query"; import { AdminOnly } from "@/components/admin/AdminOnly"; import { AgentStatusDot } from "@/components/agents/AgentStatusDot"; import { RunnerUpdateArrow } from "@/components/agents/RunnerUpdateArrow"; +import { runsLabel } from "@/components/agents/RunsField"; +import { WorkingOn } from "@/components/runs/WorkingOn"; import { CARD_TABLE } from "@/components/ui/cardTable"; import { PageHeader } from "@/components/ui/PageHeader"; import { ScrollX } from "@/components/ui/ScrollX"; @@ -29,29 +31,35 @@ function AdminAgentsPageContent() { Agent Program Status - Current run + Working on - {agents.data?.map((a) => ( - - {a.owner.name} - {a.name} - - {PROGRAM_LABEL[a.program]} - {a.model && · {a.model}} - {a.effort && · {effortName(a.effort)}} - - - - - {a.machine && on {a.machine.name}} - - - - {runLabel(a.current_run)} - - ))} + {agents.data?.map((a) => { + const runs = runsLabel(a.running ?? 0, a.max_concurrent_runs); + return ( + + {a.owner.name} + {a.name} + + {PROGRAM_LABEL[a.program]} + {a.model && · {a.model}} + {a.effort && · {effortName(a.effort)}} + + + + + {runs && {runs}} + {a.machine && on {a.machine.name}} + + + + + + + + ); + })} {agents.data?.length === 0 && ( No agents yet. )} @@ -62,11 +70,6 @@ function AdminAgentsPageContent() { ); } -function runLabel(run: AdminAgent["current_run"]): string { - const key = run && typeof run.task_key === "string" ? run.task_key : null; - return key ?? "—"; -} - export default function AdminAgentsPage() { usePageTitle("Agents", "Admin"); return ( diff --git a/frontend/src/components/agents/AgentsTab.tsx b/frontend/src/components/agents/AgentsTab.tsx index ac28115a..ad577ff3 100644 --- a/frontend/src/components/agents/AgentsTab.tsx +++ b/frontend/src/components/agents/AgentsTab.tsx @@ -11,6 +11,7 @@ import { ProjectBindings } from "@/components/agents/ProjectBindings"; import { RunnerUpdateArrow } from "@/components/agents/RunnerUpdateArrow"; import { RunsField, runsLabel } from "@/components/agents/RunsField"; import { StageModelsField } from "@/components/agents/StageModelsField"; +import { WorkingOn } from "@/components/runs/WorkingOn"; import { Badge } from "@/components/ui/Badge"; import { ListDetail, ListRow, pickChosen, useChosenParam } from "@/components/ui/ListDetail"; import { api } from "@/lib/api"; @@ -69,6 +70,12 @@ function AgentDetails({ void onChanged()} onDeleted={onDeleted} onError={setError} /> {error &&

    {error}

    } + {(agent.runs ?? []).length > 0 && ( +
    +

    Working on

    + +
    + )}

    Settings

    diff --git a/frontend/src/components/agents/__tests__/AgentsTab.test.tsx b/frontend/src/components/agents/__tests__/AgentsTab.test.tsx index a4604182..6ac7f8d4 100644 --- a/frontend/src/components/agents/__tests__/AgentsTab.test.tsx +++ b/frontend/src/components/agents/__tests__/AgentsTab.test.tsx @@ -4,6 +4,7 @@ import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { AgentsTab } from "@/components/agents/AgentsTab"; +import { run } from "@/components/dashboard/__tests__/fixture"; import type { AccessToken, Agent, Project } from "@/lib/types"; let search = ""; @@ -20,7 +21,7 @@ const agent = (over: Partial): Agent => ({ id: "a1", name: "Mo's Claude Code", program: "claude_code", answer_mode: "manual", max_concurrent_runs: 1, running: 0, status: "online", problems: [], bindings: [], owner: OWNER, model: null, effort: null, - known_models: [], machine: null, runner: null, ...over, + known_models: [], machine: null, runner: null, runs: [], ...over, }) as Agent; const AGENTS = [ @@ -150,6 +151,33 @@ describe("AgentsTab", () => { expect(await screen.findByText("Haiku 4.5 has no Max effort, so Plan's effort went back to As above.")).toBeInTheDocument(); }); + it("the card lists every run the agent is working on", () => { + search = `agent=a1`; + show([ + agent({ + running: 2, max_concurrent_runs: 3, + runs: [ + run(), + run({ run_id: "r2", kind: "chat", title: "Pricing ideas", task_key: null, chat_id: "c1", link: "/chats/c1", stage: null }), + ], + }), + ]); + const card = screen.getByRole("region", { name: AGENTS[0].name }); + expect(within(card).getByRole("heading", { level: 3, name: "Working on" })).toBeInTheDocument(); + expect(within(within(card).getByRole("list", { name: "Working on" })).getAllByRole("listitem")).toHaveLength(2); + expect(within(card).getByRole("link", { name: "PAY-14" })).toBeInTheDocument(); + expect(within(card).getByRole("link", { name: /Pricing ideas/ })).toBeInTheDocument(); + expect(within(card).getByText("Fix the login")).toBeInTheDocument(); + expect(within(card).queryByRole("button", { name: "+1 more" })).not.toBeInTheDocument(); + }); + + it("hides Working on while the agent runs nothing", () => { + search = `agent=a1`; + show(); + const card = screen.getByRole("region", { name: AGENTS[0].name }); + expect(within(card).queryByRole("heading", { name: "Working on" })).not.toBeInTheDocument(); + }); + it("points to the Runner tab when there are no machines", () => { show([], false); expect(screen.getByText("No agents yet.")).toBeInTheDocument(); diff --git a/frontend/src/components/dashboard/RunningNow.tsx b/frontend/src/components/dashboard/RunningNow.tsx index 6bb56f37..70caec1c 100644 --- a/frontend/src/components/dashboard/RunningNow.tsx +++ b/frontend/src/components/dashboard/RunningNow.tsx @@ -2,24 +2,12 @@ import { Activity } from "lucide-react"; import Link from "next/link"; -import { Fragment, useEffect, useState } from "react"; +import { Fragment } from "react"; import { Dot, Empty, Widget } from "@/components/dashboard/Widget"; +import { RunLink } from "@/components/runs/RunLink"; import { type Queued, type RunningItem, shortDuration } from "@/lib/dashboard"; -import { STAGES } from "@/lib/workflow"; - -/** A run in the Done stage is the finish run. */ -export const STAGE_LABEL: Record = { - ...Object.fromEntries(STAGES.map((s) => [s.id, s.label])), - done: "Finishing", -}; - -/** Where the run is: the stage, with the review round past the first. */ -function where(run: RunningItem): string { - const stage = run.stage ? STAGE_LABEL[run.stage] : ""; - if (run.stage === "review" && run.review_round && run.review_round > 1) return `${stage}, round ${run.review_round}`; - return stage; -} +import { STAGE_LABEL, runStatus, useNow } from "@/lib/runs"; function QueuedLine({ queued }: { queued: Queued }) { const more = queued.total - queued.items.length; @@ -44,11 +32,7 @@ function QueuedLine({ queued }: { queued: Queued }) { /** Agent runs at work now, with their time ticking in the browser, and what waits in the queue. */ export function RunningNow({ running, queued, isAdmin }: { running: RunningItem[]; queued: Queued; isAdmin: boolean }) { - const [now, setNow] = useState(() => Date.now()); - useEffect(() => { - const id = setInterval(() => setNow(Date.now()), 1000); - return () => clearInterval(id); - }, []); + const now = useNow(); return ( {running.length === 0 && queued.total === 0 ? ( @@ -61,34 +45,17 @@ export function RunningNow({ running, queued, isAdmin }: { running: RunningItem[ )} {running.map((run) => ( -
  • - - - {run.agent_name} - {" · "} - {run.task_key ? ( - <> - {run.chat_id && chat} - - {run.chat_id ? "chat" : run.task_key} - {" "} - {where(run)} - {run.stage === "build" && run.step && run.steps_total && ( - <> - {" · "} - {`Step ${run.step} of ${run.steps_total}`} - - )} - - ) : ( - - {run.question_from ? `Answering a question from ${run.question_from}` : "Answering a question"} - - )} - - {run.started_at && ( - {shortDuration(now - Date.parse(run.started_at))} - )} +
  • +
    + + + {run.kind === "task" && run.title && {run.title}} +
    +
    + {run.agent_name} + {runStatus(run)} + {run.started_at && {shortDuration(now - Date.parse(run.started_at))}} +
  • ))} {queued.total > 0 && ( diff --git a/frontend/src/components/dashboard/StageBars.tsx b/frontend/src/components/dashboard/StageBars.tsx index 7c6c04bc..cbb64053 100644 --- a/frontend/src/components/dashboard/StageBars.tsx +++ b/frontend/src/components/dashboard/StageBars.tsx @@ -1,8 +1,8 @@ import { GitBranch } from "lucide-react"; -import { STAGE_LABEL } from "@/components/dashboard/RunningNow"; import { Empty, Widget } from "@/components/dashboard/Widget"; import type { Stages } from "@/lib/dashboard"; +import { STAGE_LABEL } from "@/lib/runs"; const SEGMENTS = [ { key: "running", label: "agent working", className: "bg-cyan" }, diff --git a/frontend/src/components/dashboard/__tests__/RunningNow.test.tsx b/frontend/src/components/dashboard/__tests__/RunningNow.test.tsx index 9d99305d..0d070478 100644 --- a/frontend/src/components/dashboard/__tests__/RunningNow.test.tsx +++ b/frontend/src/components/dashboard/__tests__/RunningNow.test.tsx @@ -22,17 +22,35 @@ describe("RunningNow", () => { expect(screen.getByText("13 m")).toBeInTheDocument(); }); - it("shows Build progress and answering runs", () => { + it("puts the link before the agent and the status", () => { + render(); + const rows = screen.getAllByRole("listitem"); + expect(rows).toHaveLength(2); + for (const li of rows) { + const text = li.textContent!; + expect(text.indexOf("PAY-14")).toBeGreaterThanOrEqual(0); + expect(text.indexOf("PAY-14")).toBeLessThan(text.indexOf("Vera's Claude Code")); + expect(text.indexOf("Vera's Claude Code")).toBeLessThan(text.indexOf("Build · Step 2 of 3")); + } + }); + + it("a chat shows its title and a question its key", () => { render( , ); - expect(screen.getByText("Step 2 of 3")).toBeInTheDocument(); - expect(screen.getByRole("link", { name: "PAY-14" })).toHaveAttribute("href", "/projects/PAY/board?task=PAY-14"); - expect(screen.getByRole("link", { name: "Answering a question from WEB" })).toHaveAttribute("href", "/questions/q1"); + expect(screen.getByRole("link", { name: "Pricing ideas" })).toHaveAttribute("href", "/chats/c1"); + expect(screen.getByRole("link", { name: "PAY-Q12" })).toHaveAttribute("href", "/questions/q1"); + expect(screen.getByText("Answering")).toBeInTheDocument(); }); it("lists five queued keys then the rest as a number", () => { diff --git a/frontend/src/components/dashboard/__tests__/fixture.ts b/frontend/src/components/dashboard/__tests__/fixture.ts index fb7068fc..f9f30fdd 100644 --- a/frontend/src/components/dashboard/__tests__/fixture.ts +++ b/frontend/src/components/dashboard/__tests__/fixture.ts @@ -28,7 +28,8 @@ export function need(kind: NeedItem["kind"], ref: string, title: string, over: P export function run(over: Partial = {}): RunningItem { return { - run_id: "r1", agent_name: "Vera's Claude Code", started_at: "2026-10-28T10:00:00Z", task_key: "PAY-14", + run_id: "r1", agent_name: "Vera's Claude Code", started_at: "2026-10-28T10:00:00Z", kind: "task", + title: "Fix the login", task_key: "PAY-14", question_key: null, stage: "build", step: 2, steps_total: 3, review_round: null, question_from: null, link: "/projects/PAY/board?task=PAY-14", ...over, }; diff --git a/frontend/src/components/runs/RunLink.tsx b/frontend/src/components/runs/RunLink.tsx new file mode 100644 index 00000000..d5eb40e1 --- /dev/null +++ b/frontend/src/components/runs/RunLink.tsx @@ -0,0 +1,34 @@ +import Link from "next/link"; + +import type { RunningItem } from "@/lib/dashboard"; + +const TAG = { chat: "border-violet text-violet", cron: "border-line text-muted-foreground" } as const; + +/** What a run works on, as a link: a task's key, a chat's or cron's tag and title, a question's key. A draft, or a + * run the viewer cannot open, is the same text without the link. A key never shortens; a title does. */ +export function RunLink({ run }: { run: RunningItem }) { + const keyed = run.kind === "task" || run.kind === "question"; + const text = + run.kind === "task" ? run.task_key + : run.kind === "question" ? run.question_key + : run.kind === "draft" ? "Knowledge Base draft" + : run.title; + const look = keyed ? "shrink-0 font-mono text-xs" : "min-w-0 truncate"; + const tag = run.kind === "chat" || run.kind === "cron" ? run.kind : null; + return ( + <> + {tag && {tag}} + {run.link ? ( + + {text ?? run.kind} + + ) : ( + {text ?? run.kind} + )} + + ); +} diff --git a/frontend/src/components/runs/WorkingOn.tsx b/frontend/src/components/runs/WorkingOn.tsx new file mode 100644 index 00000000..bd788187 --- /dev/null +++ b/frontend/src/components/runs/WorkingOn.tsx @@ -0,0 +1,39 @@ +"use client"; + +import { useId, useState } from "react"; + +import { RunLink } from "@/components/runs/RunLink"; +import { type RunningItem, shortDuration } from "@/lib/dashboard"; +import { runStatus, useNow } from "@/lib/runs"; + +/** What an agent is working on, newest first. `collapsed`: the newest only, the rest behind "+N more" (the + * Admin table keeps its rows one height). `titles`: a task's title after its key. No run: a dash. */ +export function WorkingOn({ runs, collapsed = false, titles = false }: { runs: RunningItem[]; collapsed?: boolean; titles?: boolean }) { + const [open, setOpen] = useState(false); + const now = useNow(); + const id = useId(); + if (runs.length === 0) return —; + const shown = collapsed && !open ? runs.slice(0, 1) : runs; + return ( +
    +
      + {shown.map((run) => ( +
    • + + {titles && run.kind === "task" && run.title && {run.title}} + {runStatus(run)} + {run.started_at && ( + {shortDuration(now - Date.parse(run.started_at))} + )} +
    • + ))} +
    + {collapsed && runs.length > 1 && ( + + )} +
    + ); +} diff --git a/frontend/src/components/runs/__tests__/RunLink.test.tsx b/frontend/src/components/runs/__tests__/RunLink.test.tsx new file mode 100644 index 00000000..ba952dbe --- /dev/null +++ b/frontend/src/components/runs/__tests__/RunLink.test.tsx @@ -0,0 +1,45 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; + +import { run } from "@/components/dashboard/__tests__/fixture"; +import { RunLink } from "@/components/runs/RunLink"; + +afterEach(cleanup); + +describe("RunLink", () => { + it("links a task by its key, with its title on hover", () => { + render(); + const link = screen.getByRole("link", { name: "PAY-14" }); + expect(link).toHaveAttribute("href", "/projects/PAY/board?task=PAY-14"); + expect(link).toHaveAttribute("title", "Fix the login"); + }); + + it("tags a chat and links it by its title", () => { + render(); + expect(screen.getByText("chat")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Pricing ideas" })).toHaveAttribute("href", "/chats/c1"); + }); + + it("links a question by its key", () => { + render(); + expect(screen.getByRole("link", { name: "PAY-Q12" })).toHaveAttribute("href", "/questions/q1"); + }); + + it("tags a cron and links it by its name", () => { + render(); + expect(screen.getByText("cron")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Nightly check" })).toHaveAttribute("href", "/projects/PAY/crons/k1"); + }); + + it("shows a draft as text", () => { + render(); + expect(screen.getByText("Knowledge Base draft")).toBeInTheDocument(); + expect(screen.queryByRole("link")).toBeNull(); + }); + + it("shows a run the viewer cannot open without a link", () => { + render(); + expect(screen.getByText("WEB-3")).toBeInTheDocument(); + expect(screen.queryByRole("link")).toBeNull(); + }); +}); diff --git a/frontend/src/components/runs/__tests__/WorkingOn.test.tsx b/frontend/src/components/runs/__tests__/WorkingOn.test.tsx new file mode 100644 index 00000000..06330dfa --- /dev/null +++ b/frontend/src/components/runs/__tests__/WorkingOn.test.tsx @@ -0,0 +1,62 @@ +import { cleanup, render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, describe, expect, it } from "vitest"; + +import { run } from "@/components/dashboard/__tests__/fixture"; +import { WorkingOn } from "@/components/runs/WorkingOn"; + +afterEach(cleanup); + +const runs = [ + run(), + run({ run_id: "r2", kind: "chat", title: "Pricing ideas", task_key: null, chat_id: "c1", link: "/chats/c1", stage: null }), + run({ run_id: "r3", kind: "question", title: null, task_key: null, question_key: "PAY-Q12", link: "/questions/q1", stage: null }), +]; + +const list = () => screen.getByRole("list", { name: "Working on" }); + +describe("WorkingOn", () => { + it("lists every run when not collapsed", () => { + render(); + expect(within(list()).getAllByRole("listitem")).toHaveLength(3); + expect(within(list()).getAllByRole("link")).toHaveLength(3); + expect(screen.queryByRole("button", { name: "+2 more" })).toBeNull(); + }); + + it("with titles shows a task's title after its key", () => { + const { unmount } = render(); + expect(screen.getByText("Fix the login")).toBeInTheDocument(); + unmount(); + render(); + expect(screen.queryByText("Fix the login")).toBeNull(); + expect(screen.getByRole("link", { name: "PAY-14" })).toHaveAttribute("title", "Fix the login"); + }); + + it("collapsed shows the newest and opens the rest in place", async () => { + const user = userEvent.setup(); + render(); + expect(within(list()).getAllByRole("listitem")).toHaveLength(1); + const more = screen.getByRole("button", { name: "+2 more" }); + expect(more).toHaveAttribute("aria-expanded", "false"); + await user.click(more); + expect(within(list()).getAllByRole("listitem")).toHaveLength(3); + const less = screen.getByRole("button", { name: "Show less" }); + expect(less).toHaveAttribute("aria-expanded", "true"); + await user.click(less); + expect(within(list()).getAllByRole("listitem")).toHaveLength(1); + }); + + it("one run has no button; none shows a dash", () => { + const { unmount } = render(); + expect(screen.queryByRole("button")).toBeNull(); + unmount(); + render(); + expect(screen.getByText("—")).toBeInTheDocument(); + expect(screen.queryByRole("list")).toBeNull(); + }); + + it("each entry shows its status", () => { + render(); + expect(screen.getByText("Build · Step 2 of 3")).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/lib/__tests__/runs.test.ts b/frontend/src/lib/__tests__/runs.test.ts new file mode 100644 index 00000000..00d43698 --- /dev/null +++ b/frontend/src/lib/__tests__/runs.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; + +import { run } from "@/components/dashboard/__tests__/fixture"; +import { runStatus } from "@/lib/runs"; + +const idle = { stage: null, step: null, steps_total: null }; + +describe("runStatus", () => { + it("gives the Build step", () => { + expect(runStatus(run())).toBe("Build · Step 2 of 3"); + }); + + it("gives the Review round past the first", () => { + expect(runStatus(run({ stage: "review", step: null, steps_total: null, review_round: 2 }))).toBe("Review, round 2"); + expect(runStatus(run({ stage: "review", step: null, steps_total: null, review_round: 1 }))).toBe("Review"); + }); + + it("says what a run with no stage is doing", () => { + expect(runStatus(run({ ...idle, kind: "question" }))).toBe("Answering"); + expect(runStatus(run({ ...idle, kind: "cron" }))).toBe("Running"); + expect(runStatus(run({ ...idle, kind: "draft" }))).toBe("Writing"); + expect(runStatus(run({ ...idle, kind: "chat" }))).toBe("Working"); + }); +}); diff --git a/frontend/src/lib/api-types.ts b/frontend/src/lib/api-types.ts index a6ac6e8e..47c3ce5a 100644 --- a/frontend/src/lib/api-types.ts +++ b/frontend/src/lib/api-types.ts @@ -4089,7 +4089,10 @@ export interface components { [key: string]: string; }; }; - /** AdminAgentOut */ + /** + * AdminAgentOut + * @description An agent on Admin → Agents (every agent in the workspace). + */ AdminAgentOut: { /** * Id @@ -4110,6 +4113,11 @@ export interface components { * @default 0 */ running: number; + /** + * Runs + * @default [] + */ + runs: components["schemas"]["RunningItem"][]; /** * Problems * @default [] @@ -4135,10 +4143,6 @@ export interface components { stage_models: { [key: string]: components["schemas"]["StageChoice"]; }; - /** Current Run */ - current_run?: { - [key: string]: unknown; - } | null; }; /** AdminSettingsIn */ AdminSettingsIn: { @@ -4305,6 +4309,11 @@ export interface components { * @default 0 */ running: number; + /** + * Runs + * @default [] + */ + runs: components["schemas"]["RunningItem"][]; /** * Problems * @default [] @@ -6680,6 +6689,11 @@ export interface components { * @default 0 */ running: number; + /** + * Runs + * @default [] + */ + runs: components["schemas"]["RunningItem"][]; /** * Problems * @default [] @@ -7364,7 +7378,10 @@ export interface components { /** Url */ url: string; }; - /** RunningItem */ + /** + * RunningItem + * @description A run at work now, as the Dashboard's Running now and the Agents pages list it. + */ RunningItem: { /** * Run Id @@ -7375,8 +7392,17 @@ export interface components { agent_name: string; /** Started At */ started_at: string | null; + /** + * Kind + * @enum {string} + */ + kind: "task" | "chat" | "question" | "cron" | "draft"; + /** Title */ + title?: string | null; /** Task Key */ task_key: string | null; + /** Question Key */ + question_key?: string | null; stage: components["schemas"]["Stage"] | null; /** Step */ step: number | null; @@ -7387,7 +7413,7 @@ export interface components { /** Question From */ question_from: string | null; /** Link */ - link: string; + link: string | null; /** Chat Id */ chat_id?: string | null; }; diff --git a/frontend/src/lib/runs.ts b/frontend/src/lib/runs.ts new file mode 100644 index 00000000..4318a081 --- /dev/null +++ b/frontend/src/lib/runs.ts @@ -0,0 +1,34 @@ +import { useEffect, useState } from "react"; + +import type { RunningItem } from "@/lib/dashboard"; +import { STAGES } from "@/lib/workflow"; + +/** A run in the Done stage is the finish run. */ +export const STAGE_LABEL: Record = { + ...Object.fromEntries(STAGES.map((s) => [s.id, s.label])), + done: "Finishing", +}; + +/** What a run with no workflow stage is doing. */ +const NO_STAGE: Record = { + task: "Working", chat: "Working", question: "Answering", cron: "Running", draft: "Writing", +}; + +/** A run's status: the stage, with the step in Build and the round past the first in Review. */ +export function runStatus(run: RunningItem): string { + if (!run.stage) return NO_STAGE[run.kind]; + const stage = STAGE_LABEL[run.stage]; + if (run.stage === "build" && run.step && run.steps_total) return `${stage} · Step ${run.step} of ${run.steps_total}`; + if (run.stage === "review" && run.review_round && run.review_round > 1) return `${stage}, round ${run.review_round}`; + return stage; +} + +/** The time now, ticking every second, for running times counted in the browser. */ +export function useNow(): number { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const id = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(id); + }, []); + return now; +}