mirror of
https://github.com/multica-ai/multica.git
synced 2026-07-28 05:46:58 +02:00
* feat(agent-status): add workspace live-tasks endpoint and TaskFailureReason type Lays the API + type contract for the front-end agent presence cache: - New `GET /api/active-tasks` returns active (queued/dispatched/running) tasks plus failed tasks within the last 2 minutes for the current workspace. The 2-minute window powers a UI-side auto-clearing "Failed" agent state without back-end pollers. - `agent_task_queue` has no workspace_id column, so the query JOINs agent; `SELECT atq.*` keeps `failure_reason` (migration 055) on the wire. - Adds `TaskFailureReason` to `AgentTask` so the UI can map the 5 backend classifiers (agent_error / timeout / runtime_offline / runtime_recovery / manual) to copy without parsing free-text errors. - New `api.getActiveTasksForWorkspace()` client method; workspace is resolved server-side from the X-Workspace-Slug header (no path param, matching /api/agents and /api/runtimes conventions). Includes the joint engineering plan and designer brief that scope the broader Agent / Runtime status redesign — Phase 0 is this contract plus the front-end derivation layer landing in the next commit. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(agent-status): derive presence/health states with WS sync and desktop IPC bridge Adds the front-end derivation layer that turns raw server data into the user-facing 5-state agent / 4-state runtime enums. UI files are deliberately untouched in this commit — derivation lives behind hooks (useAgentPresence, useRuntimeHealth) that any component can call with zero additional network traffic. Architecture: - Derivation is pure functions in packages/core/{agents,runtimes}; the back-end stays free of UI translation. Agents algorithm: runtime offline > recent failed (2-min window) > running > queued > available. Runtimes algorithm: status + last_seen_at -> online / recently_lost / offline / about_to_gc. - A single workspace-wide active-tasks query backs all per-agent presence reads, eliminating N+1 across hover cards, list rows, and pickers. 30-second tick re-renders the hooks so the failed window expires even when no underlying data changes. - WS task lifecycle events (dispatch / completed / failed / cancelled) invalidate active-tasks via the prefix dispatcher. completed/failed were removed from specificEvents so they go through both the prefix invalidate and the existing chat ws.on() handlers. Reconnect refetch picks up active-tasks too. - Desktop bridges window.daemonAPI.onStatusChange directly into the runtimes cache via setQueryData, giving the local daemon sub-second feedback (vs. 75s server sweep). Bridge is wsId-bound so workspace switches automatically rebind the subscription; daemon_id matching covers the same-daemon-multiple-providers case. 24 derivation unit tests cover all branches plus null/empty/boundary inputs (FAILED_WINDOW_MS edges, null last_seen_at, missing completed_at). Full core suite: 112 tests passing. Typecheck green across all 8 workspace packages. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(agent-status): redesign agent runtime status as two orthogonal dimensions Splits the conflated 5-state agent presence into two independent axes: - AgentAvailability (3-state): online / unstable / offline — drives the dot indicator everywhere a dot appears. Pure runtime reachability; never sticky-red because of a past task outcome. - LastTaskState (5-state): running / completed / failed / cancelled / idle — surfaced as text + icon on focused surfaces (hover card, agent detail page, agents list, runtime detail). Never colours the dot. Major changes: * Domain layer: AgentPresence union → AgentAvailability + LastTaskState. derive-presence split into deriveAgentAvailability + deriveLastTaskState + deriveAgentPresenceDetail orchestrator. Tests reorganised into three groups (availability invariants, last-task invariants, composition). * Visual config: presenceConfig (5 entries) → availabilityConfig (3) + taskStateConfig (5). availabilityOrder + lastTaskOrder for filter chips. * Workspace-level presence prefetch: new useWorkspacePresencePrefetch hook + WorkspacePresencePrefetch mount component, wired into DashboardLayout (web) and WorkspaceRouteLayout (desktop). Hover cards render synchronously with no skeleton flash on first hover. * ActorAvatar hover: flipped default — disableHoverCard removed, enableHoverCard added (default false). Opt-in at ~14 decision-moment surfaces; pickers / decoration sub-chips stay plain. Status dot decoupled (showStatusDot prop) so picker rows can show presence without nesting popovers. * Hover cards: AgentProfileCard simplified — availability dot only, Detail link top-right (logs live on the detail page). New MemberProfileCard mirrors the structure: name + role + email + top-2 owned agents (sorted by 30d run count) with click-through to agent detail. * Agents list: split Status into two columns — availability (3-color dot + label) and Last run (task icon + label, optional running counts). Two independent filter chip groups (Status + Last run); combination acts as intersection ("online + failed" finds broken- but-alive agents). * Other UI surfaces (issue list/board/detail, comments, autopilots, projects, runtimes, mention autocomplete, subscribers picker) updated to the new dot semantics; status dot now strictly 3-color. Server changes accompany the client redesign — workspace-wide agent-task-snapshot endpoint, runtime usage queries, etc. — to feed the derive layer with the data it needs. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(agent-detail): drop last-task chip from detail header + inspector The Recent work section on the agent detail page already shows the same data (with task titles, timestamps, error context) — surfacing "Completed" / "Failed" / etc. up in the header was redundant chrome. Detail surfaces now show only the 3-state availability dot. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(tables): handle narrow viewports across agents / skills / runtimes Three table layouts were squeezing content into adjacent cells at intermediate widths. Each fix is small and targeted: * runtime-list: the Runtime cell's base name had `shrink-0`, so it refused to truncate when its grid column was narrowed under width pressure — the name visually overflowed into the Health column ("ClaudeOnline" etc). Removed shrink-0, added truncate. The Health column was also a fixed 9.5rem reservation for the worst-case "Recently lost · 2m 14s ago" copy; switched to minmax(0,1fr) so it competes fairly with Runtime. * skills-page: had a single grid template with no responsive breakpoints — all 6 columns were rendered at any width and got visually jammed below md. Added a <md template that drops Source + Updated; the row markup hides those cells via `hidden md:block` / `md:contents`. * agent-list-item: the new Last run column was reserved at minmax(8rem, max-content); on narrow md viewports the 8rem floor pushed the row past available width. Changed to minmax(0,max-content) so the cell shrinks under pressure (its content already truncates). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(agent-card): hover-only Detail + add Runtime row + breathing room Three small polish tweaks to the agent hover card: - Detail link gets `mr-1` + fades in only on card hover (group-hover). It was visually flush against the popover edge and competing for attention; now it stays out of the way during a quick glance and surfaces only when the user is dwelling on the card. - Runtime row is back, in the meta block (cloud/local icon + runtime name). The earlier removal was over-aggressive — knowing where an agent runs is part of "who is this agent". The wifi badge stays dropped because the availability dot in the header already conveys reachability. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(runtime): wifi-style health icon (4-state) for runtime list + agent card Replaces the 6px coloured dot with a wifi-shape icon that carries both state (Wifi vs WifiOff) and severity (success/warning/muted/destructive). Mapping: - online → Wifi (success) - recently_lost → WifiHigh (warning) — transient hiccup, fewer bars - offline → WifiOff (muted) — long unreachable - about_to_gc → WifiOff (destructive) — sweeper coming soon Used in two places: - Runtime list: replaces HealthDot in the dedicated leading-icon column. Bumped the column from 0.5rem (dot-sized) to 0.875rem (icon-sized). - Agent profile card RuntimeRow: derives runtime health from runtime + clock (matching the 4-state semantics) and renders HealthIcon next to the runtime name. Cloud runtimes always read as online. The duplicate signal with the header availability dot is intentional — it confirms WHICH runtime is the one currently in the dot's state. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
193 lines
5.8 KiB
TypeScript
193 lines
5.8 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import type { Agent, AgentActivityBucket } from "../types";
|
|
import {
|
|
buildActivityMap,
|
|
deriveAgentActivity,
|
|
summarizeActivityWindow,
|
|
} from "./use-agent-activity";
|
|
|
|
const DAY = 24 * 60 * 60 * 1000;
|
|
|
|
// Fixed anchor — derivation uses local-time start of "today", a real
|
|
// clock would drift. 12:00 also keeps "today" stable across odd timezones.
|
|
const NOW = new Date("2026-04-28T12:00:00").getTime();
|
|
|
|
function bucket(
|
|
agentId: string,
|
|
daysAgo: number,
|
|
taskCount: number,
|
|
failedCount = 0,
|
|
): AgentActivityBucket {
|
|
const t = new Date(NOW);
|
|
t.setHours(0, 0, 0, 0);
|
|
return {
|
|
agent_id: agentId,
|
|
bucket_at: new Date(t.getTime() - daysAgo * DAY).toISOString(),
|
|
task_count: taskCount,
|
|
failed_count: failedCount,
|
|
};
|
|
}
|
|
|
|
const fullHistoryAgent: Agent = {
|
|
id: "a1",
|
|
workspace_id: "w",
|
|
runtime_id: "r1",
|
|
name: "Old Agent",
|
|
description: "",
|
|
instructions: "",
|
|
avatar_url: null,
|
|
runtime_mode: "cloud",
|
|
runtime_config: {},
|
|
custom_env: {},
|
|
custom_args: [],
|
|
custom_env_redacted: false,
|
|
visibility: "workspace",
|
|
status: "idle",
|
|
max_concurrent_tasks: 1,
|
|
model: "",
|
|
owner_id: null,
|
|
skills: [],
|
|
// Older than the window so daysSinceCreated saturates at DAYS.
|
|
created_at: new Date(NOW - 100 * DAY).toISOString(),
|
|
updated_at: new Date(NOW).toISOString(),
|
|
archived_at: null,
|
|
archived_by: null,
|
|
};
|
|
|
|
describe("deriveAgentActivity", () => {
|
|
it("places buckets in oldest→newest slots across 30 days", () => {
|
|
const buckets = [
|
|
bucket("a1", 29, 1), // slot 0
|
|
bucket("a1", 0, 5), // slot 29
|
|
];
|
|
const result = deriveAgentActivity(
|
|
buckets,
|
|
fullHistoryAgent.created_at,
|
|
NOW,
|
|
);
|
|
expect(result.buckets).toHaveLength(30);
|
|
expect(result.buckets[0]).toEqual({ total: 1, failed: 0 });
|
|
expect(result.buckets[29]).toEqual({ total: 5, failed: 0 });
|
|
expect(result.daysSinceCreated).toBe(30);
|
|
});
|
|
|
|
it("clamps daysSinceCreated for young agents", () => {
|
|
const created = new Date(NOW - 3 * DAY - 60 * 1000).toISOString();
|
|
const result = deriveAgentActivity([bucket("fresh", 1, 4)], created, NOW);
|
|
expect(result.daysSinceCreated).toBe(3);
|
|
});
|
|
|
|
it("treats sub-day-old agents as daysSinceCreated = 0", () => {
|
|
const created = new Date(NOW - 2 * 60 * 60 * 1000).toISOString();
|
|
const result = deriveAgentActivity([bucket("fresh", 0, 1)], created, NOW);
|
|
expect(result.daysSinceCreated).toBe(0);
|
|
// Today's bucket still records — pre-life days simply look like zero
|
|
// days, which is on purpose.
|
|
expect(result.buckets[29]).toEqual({ total: 1, failed: 0 });
|
|
});
|
|
|
|
it("ignores buckets older than the 30-day window", () => {
|
|
const result = deriveAgentActivity(
|
|
[bucket("a1", 60, 99)],
|
|
fullHistoryAgent.created_at,
|
|
NOW,
|
|
);
|
|
expect(
|
|
result.buckets.reduce((s, b) => s + b.total, 0),
|
|
).toBe(0);
|
|
});
|
|
|
|
it("zero-fills when the agent has no buckets", () => {
|
|
const result = deriveAgentActivity(
|
|
[],
|
|
fullHistoryAgent.created_at,
|
|
NOW,
|
|
);
|
|
expect(result.buckets).toHaveLength(30);
|
|
expect(result.buckets.every((b) => b.total === 0 && b.failed === 0)).toBe(
|
|
true,
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("summarizeActivityWindow", () => {
|
|
it("rolls up totals across the trailing N buckets", () => {
|
|
// 5 runs total over the 30-day series.
|
|
const result = deriveAgentActivity(
|
|
[
|
|
bucket("a1", 25, 1), // outside 7d, inside 30d
|
|
bucket("a1", 6, 1), // inside 7d
|
|
bucket("a1", 0, 3, 1), // inside 7d
|
|
],
|
|
fullHistoryAgent.created_at,
|
|
NOW,
|
|
);
|
|
const last7 = summarizeActivityWindow(result, 7);
|
|
expect(last7.totalRuns).toBe(4);
|
|
expect(last7.totalFailed).toBe(1);
|
|
expect(last7.buckets).toHaveLength(7);
|
|
|
|
const last30 = summarizeActivityWindow(result, 30);
|
|
expect(last30.totalRuns).toBe(5);
|
|
expect(last30.totalFailed).toBe(1);
|
|
expect(last30.buckets).toHaveLength(30);
|
|
});
|
|
|
|
it("returns an empty summary for missing activity", () => {
|
|
const summary = summarizeActivityWindow(undefined, 7);
|
|
expect(summary.buckets).toEqual([]);
|
|
expect(summary.totalRuns).toBe(0);
|
|
expect(summary.totalFailed).toBe(0);
|
|
expect(summary.windowDays).toBe(7);
|
|
});
|
|
|
|
it("clamps an oversized window to the available bucket count", () => {
|
|
const result = deriveAgentActivity(
|
|
[bucket("a1", 0, 2)],
|
|
fullHistoryAgent.created_at,
|
|
NOW,
|
|
);
|
|
const summary = summarizeActivityWindow(result, 1000);
|
|
expect(summary.buckets).toHaveLength(30);
|
|
expect(summary.totalRuns).toBe(2);
|
|
});
|
|
|
|
it("returns no buckets when window is 0", () => {
|
|
const result = deriveAgentActivity(
|
|
[bucket("a1", 0, 5)],
|
|
fullHistoryAgent.created_at,
|
|
NOW,
|
|
);
|
|
const summary = summarizeActivityWindow(result, 0);
|
|
expect(summary.buckets).toEqual([]);
|
|
expect(summary.totalRuns).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe("buildActivityMap", () => {
|
|
it("groups buckets by agent and yields a derivation per agent", () => {
|
|
const agents: Agent[] = [
|
|
fullHistoryAgent,
|
|
{ ...fullHistoryAgent, id: "a2" },
|
|
];
|
|
const buckets: AgentActivityBucket[] = [
|
|
bucket("a1", 0, 3),
|
|
bucket("a2", 1, 2, 1),
|
|
bucket("a1", 2, 4),
|
|
];
|
|
const map = buildActivityMap(agents, buckets, NOW);
|
|
expect(map.size).toBe(2);
|
|
expect(summarizeActivityWindow(map.get("a1"), 30).totalRuns).toBe(7);
|
|
expect(summarizeActivityWindow(map.get("a2"), 30).totalRuns).toBe(2);
|
|
expect(summarizeActivityWindow(map.get("a2"), 30).totalFailed).toBe(1);
|
|
});
|
|
|
|
it("emits a zero-filled entry for an agent with no buckets", () => {
|
|
const agents: Agent[] = [fullHistoryAgent];
|
|
const map = buildActivityMap(agents, [], NOW);
|
|
const a = map.get("a1");
|
|
expect(a?.buckets).toHaveLength(30);
|
|
expect(summarizeActivityWindow(a, 30).totalRuns).toBe(0);
|
|
});
|
|
});
|