Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agent): presence v3 + execution log + trigger summary (#1823)
Naiyuan Qingf745a3bbbe10
diff --git a/packages/core/agents/constants.ts b/packages/core/agents/constants.tsnew file mode 100644index 0000000000..6749aea7ff--- /dev/null+++ b/packages/core/agents/constants.ts@@ -0,0 +1,4 @@+// User-facing limits enforced symmetrically on the front-end (UI counter ++// disabled save) and the back-end (handler validation + DB CHECK constraint).+// Kept in core so both apps and the test suite read from one source.+export const AGENT_DESCRIPTION_MAX_LENGTH = 255;diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.tsindex e7708cc31e..62369c67a3 100644--- a/packages/core/agents/derive-presence.test.ts+++ b/packages/core/agents/derive-presence.test.ts@@ -1,10 +1,11 @@import { describe, expect, it } from "vitest";-import type { Agent, AgentRuntime, AgentTask, TaskFailureReason } from "../types";+import type { Agent, AgentRuntime, AgentTask } from "../types";import {buildPresenceMap,deriveAgentAvailability,deriveAgentPresenceDetail,- deriveLastTaskState,+ deriveWorkload,+ deriveWorkloadDetail,} from "./derive-presence";function makeAgent(overrides: Partial<Agent> = {}): Agent {@@ -80,8 +81,7 @@ function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {describe("deriveAgentAvailability", () => {// Reachability dimension only — runtime + clock decide it; tasks are- // irrelevant. The whole point of splitting from LastTaskState is that- // these tests can ignore task fixtures entirely.+ // irrelevant to this axis.it("returns online when runtime is fresh-online", () => {expect(deriveAgentAvailability(makeRuntime(), NOW)).toBe("online");@@ -120,128 +120,111 @@ describe("deriveAgentAvailability", () => {});});-describe("deriveLastTaskState", () => {- // Task dimension only — runtime status is not consulted.+describe("deriveWorkload", () => {+ // Atomic 3-way classifier — used by both Agent (per-agent task counts)+ // and Runtime (per-runtime aggregated counts). Pure functional mapping+ // from a count pair to a workload label.++ it("returns working when runningCount > 0", () => {+ expect(deriveWorkload({ runningCount: 1, queuedCount: 0 })).toBe("working");+ expect(deriveWorkload({ runningCount: 3, queuedCount: 5 })).toBe("working");+ });++ it("returns queued when nothing running but queuedCount > 0", () => {+ expect(deriveWorkload({ runningCount: 0, queuedCount: 1 })).toBe("queued");+ expect(deriveWorkload({ runningCount: 0, queuedCount: 5 })).toBe("queued");+ });++ it("returns idle when both counts are zero", () => {+ expect(deriveWorkload({ runningCount: 0, queuedCount: 0 })).toBe("idle");+ });+});++describe("deriveWorkloadDetail", () => {+ // Aggregates a task list into running/queued counts before classifying.+ // Terminal statuses (completed / failed / cancelled) are silently+ // ignored — workload is "what's on the plate right now", not history.it("returns idle when no tasks at all", () => {- const r = deriveLastTaskState([]);- expect(r.state).toBe("idle");+ const r = deriveWorkloadDetail([]);+ expect(r.workload).toBe("idle");expect(r.runningCount).toBe(0);expect(r.queuedCount).toBe(0);});- it("returns running when at least one task is running", () => {- const r = deriveLastTaskState([makeTask({ status: "running" })]);- expect(r.state).toBe("running");+ it("returns working when at least one task is running", () => {+ const r = deriveWorkloadDetail([makeTask({ status: "running" })]);+ expect(r.workload).toBe("working");expect(r.runningCount).toBe(1);+ expect(r.queuedCount).toBe(0);});- it("returns running when only queued / dispatched tasks exist (no running yet)", () => {- const r = deriveLastTaskState([+ it("returns queued when only queued / dispatched tasks exist (no running)", () => {+ // The "stuck on offline runtime" scenario in isolation: runningCount=0,+ // queuedCount>0 surfaces as `queued` so the UI can honestly say+ // "Queued · N" instead of misleading "Running 0/3 +Nq".+ const r = deriveWorkloadDetail([makeTask({ status: "queued" }),makeTask({ id: "t2", status: "dispatched" }),]);- expect(r.state).toBe("running");+ expect(r.workload).toBe("queued");expect(r.runningCount).toBe(0);expect(r.queuedCount).toBe(2);});- it("returns running even when an older terminal exists (active wins over historical)", () => {- const r = deriveLastTaskState([- makeTask({- id: "old-failed",- status: "failed",- completed_at: "2026-04-27T10:00:00Z",- }),- makeTask({ id: "new-running", status: "running" }),+ it("returns working when running coexists with queued (overflow)", () => {+ // Capacity-saturated agent: still running, but with a queue building.+ // The chip says "Working" with the queue expressed as a `+Nq` badge.+ const r = deriveWorkloadDetail([+ makeTask({ id: "t1", status: "running" }),+ makeTask({ id: "t2", status: "queued" }),+ makeTask({ id: "t3", status: "queued" }),]);- expect(r.state).toBe("running");+ expect(r.workload).toBe("working");+ expect(r.runningCount).toBe(1);+ expect(r.queuedCount).toBe(2);});- it("returns the latest terminal state when no tasks are active (latest = failed)", () => {- const r = deriveLastTaskState([- makeTask({- id: "old",- status: "completed",- completed_at: "2026-04-27T10:00:00Z",- }),+ it("ignores terminal statuses entirely (no historical state in workload)", () => {+ // Failed / completed / cancelled tasks contribute no count and don't+ // change the verdict — Recent Work + Inbox handle history, not workload.+ const r = deriveWorkloadDetail([makeTask({- id: "new",+ id: "t-failed",status: "failed",completed_at: "2026-04-27T11:30:00Z",}),- ]);- expect(r.state).toBe("failed");- expect(r.lastTaskCompletedAt).toBe("2026-04-27T11:30:00Z");- });-- it("returns the latest terminal state when no tasks are active (latest = completed)", () => {- const r = deriveLastTaskState([- makeTask({- id: "old",- status: "failed",- completed_at: "2026-04-27T10:00:00Z",- }),makeTask({- id: "new",+ id: "t-completed",status: "completed",- completed_at: "2026-04-27T11:30:00Z",- }),- ]);- expect(r.state).toBe("completed");- });-- it("surfaces failure_reason on a failed latest terminal", () => {- const reason: TaskFailureReason = "runtime_offline";- const r = deriveLastTaskState([- makeTask({- status: "failed",- completed_at: "2026-04-27T11:30:00Z",- failure_reason: reason,+ completed_at: "2026-04-27T11:00:00Z",}),- ]);- expect(r.state).toBe("failed");- expect(r.failureReason).toBe(reason);- });-- it("leaves failureReason undefined when the failed terminal has empty failure_reason", () => {- const r = deriveLastTaskState([- makeTask({- status: "failed",- completed_at: "2026-04-27T11:30:00Z",- failure_reason: "",- }),- ]);- expect(r.state).toBe("failed");- expect(r.failureReason).toBeUndefined();- });-- it("returns cancelled when the latest terminal is cancelled", () => {- // Under the new model cancelled is a real state — the dot is- // availability-driven so honestly surfacing it doesn't lie.- const r = deriveLastTaskState([makeTask({+ id: "t-cancelled",status: "cancelled",- completed_at: "2026-04-27T11:30:00Z",+ completed_at: "2026-04-27T10:30:00Z",}),]);- expect(r.state).toBe("cancelled");+ expect(r.workload).toBe("idle");+ expect(r.runningCount).toBe(0);+ expect(r.queuedCount).toBe(0);});- it("ignores terminals without completed_at (treated as not-terminal)", () => {- // Defensive: a malformed row (no completed_at) shouldn't derail the- // latest-terminal scan. With nothing else in flight, idle.- const r = deriveLastTaskState([makeTask({ status: "failed", completed_at: null })]);- expect(r.state).toBe("idle");+ it("classifies running over queued when both present, regardless of order", () => {+ const r = deriveWorkloadDetail([+ makeTask({ id: "t1", status: "queued" }),+ makeTask({ id: "t2", status: "running" }),+ ]);+ expect(r.workload).toBe("working");});});describe("deriveAgentPresenceDetail", () => {// Composition: the two dimensions are derived independently and the- // detail object exposes both. No cross-axis override (the old "unstable- // overrides failed" rule is gone — they coexist now).+ // detail object exposes both. No cross-axis override — workload never+ // colours the dot, availability never overrides workload.- it("composes online + running for the common busy case", () => {+ it("composes online + working for the common busy case", () => {const detail = deriveAgentPresenceDetail({agent: makeAgent(),runtime: makeRuntime(),@@ -252,53 +235,53 @@ describe("deriveAgentPresenceDetail", () => {now: NOW,});expect(detail.availability).toBe("online");- expect(detail.lastTask).toBe("running");+ expect(detail.workload).toBe("working");expect(detail.runningCount).toBe(1);expect(detail.queuedCount).toBe(1);expect(detail.capacity).toBe(6);});- it("composes online + failed — agent is reachable but last task failed (no longer sticky red dot)", () => {- // The whole motivation for the split: this combination was previously- // collapsed to a single red "failed" state, hiding the fact that the- // runtime is fine. Now the two dimensions are visible separately.+ it("composes offline + queued — the canonical 'stuck' case (was previously misleading 'running 0/N')", () => {+ // The motivation for the redesign: runtime offline + queued tasks+ // used to surface as `running` with `0/3 +2q` counts (literally false).+ // Workload now returns `queued` honestly, paired with offline+ // availability — UI reads "Offline · Queued · 2".const detail = deriveAgentPresenceDetail({agent: makeAgent(),- runtime: makeRuntime(),+ runtime: makeRuntime({+ status: "offline",+ last_seen_at: "2026-04-27T11:50:00Z",+ }),tasks: [- makeTask({- status: "failed",- completed_at: "2026-04-27T11:30:00Z",- failure_reason: "agent_error",- }),+ makeTask({ status: "queued" }),+ makeTask({ id: "t2", status: "queued" }),],now: NOW,});- expect(detail.availability).toBe("online");- expect(detail.lastTask).toBe("failed");- expect(detail.failureReason).toBe("agent_error");- expect(detail.lastTaskCompletedAt).toBe("2026-04-27T11:30:00Z");+ expect(detail.availability).toBe("offline");+ expect(detail.workload).toBe("queued");+ expect(detail.runningCount).toBe(0);+ expect(detail.queuedCount).toBe(2);});- it("composes unstable + running — runtime hiccup with queued tasks still in flight", () => {- // Previously "unstable" overrode "working"; now both signals are- // surfaced. The UI shows amber dot AND running chip — user sees both- // "connection issue" and "queue is paused".+ it("composes unstable + working — runtime hiccup with tasks still in flight", () => {+ // Recently-lost runtime, but a task is still recorded as running.+ // Both signals surface independently — amber dot AND working chip —+ // so the user sees "connection wobbling" alongside "agent is busy".const detail = deriveAgentPresenceDetail({agent: makeAgent(),runtime: makeRuntime({status: "offline",last_seen_at: "2026-04-27T11:59:00Z",}),- tasks: [makeTask({ status: "queued" })],+ tasks: [makeTask({ status: "running" })],now: NOW,});expect(detail.availability).toBe("unstable");- expect(detail.lastTask).toBe("running");- expect(detail.queuedCount).toBe(1);+ expect(detail.workload).toBe("working");});- it("composes offline + idle for a brand-new agent on a dead runtime", () => {+ it("composes offline + idle for an unreachable agent with no tasks pending", () => {const detail = deriveAgentPresenceDetail({agent: makeAgent(),runtime: makeRuntime({@@ -309,34 +292,34 @@ describe("deriveAgentPresenceDetail", () => {now: NOW,});expect(detail.availability).toBe("offline");- expect(detail.lastTask).toBe("idle");+ expect(detail.workload).toBe("idle");});- it("handles a missing runtime by reporting offline + the task-driven last state", () => {+ it("handles a missing runtime by reporting offline + the task-driven workload", () => {const detail = deriveAgentPresenceDetail({agent: makeAgent(),runtime: null,- tasks: [- makeTask({- status: "completed",- completed_at: "2026-04-27T11:30:00Z",- }),- ],+ tasks: [makeTask({ status: "running" })],now: NOW,});expect(detail.availability).toBe("offline");- expect(detail.lastTask).toBe("completed");+ expect(detail.workload).toBe("working");});- it("leaves failureReason / lastTaskCompletedAt undefined when not relevant", () => {+ it("returns idle workload when only terminal tasks are present (history doesn't bleed in)", () => {const detail = deriveAgentPresenceDetail({agent: makeAgent(),runtime: makeRuntime(),- tasks: [makeTask({ status: "running" })],+ tasks: [+ makeTask({+ status: "failed",+ completed_at: "2026-04-27T11:30:00Z",+ }),+ ],now: NOW,});- expect(detail.failureReason).toBeUndefined();- expect(detail.lastTaskCompletedAt).toBeUndefined();+ expect(detail.availability).toBe("online");+ expect(detail.workload).toBe("idle");});it("mirrors agent.max_concurrent_tasks into capacity", () => {@@ -359,21 +342,16 @@ describe("buildPresenceMap", () => {runtimes: [makeRuntime()],snapshot: [makeTask({ id: "t1", agent_id: "a", status: "running" }),- makeTask({- id: "t2",- agent_id: "b",- status: "failed",- completed_at: "2026-04-27T11:30:00Z",- }),+ makeTask({ id: "t2", agent_id: "b", status: "queued" }),],now: NOW,});const a = map.get("a");const b = map.get("b");expect(a?.availability).toBe("online");- expect(a?.lastTask).toBe("running");+ expect(a?.workload).toBe("working");expect(b?.availability).toBe("online");- expect(b?.lastTask).toBe("failed");+ expect(b?.workload).toBe("queued");});it("returns offline availability for agents whose runtime_id has no matching runtime", () => {@@ -386,8 +364,8 @@ describe("buildPresenceMap", () => {});const o = map.get("orphan");expect(o?.availability).toBe("offline");- // Task dimension still resolves independently — running task counts.- expect(o?.lastTask).toBe("running");+ // Workload still resolves independently — running task counts.+ expect(o?.workload).toBe("working");});it("threads the same `now` so every agent on a shared runtime gets the same availability", () => {@@ -406,19 +384,35 @@ describe("buildPresenceMap", () => {],snapshot: [makeTask({ id: "t1", agent_id: "a", status: "queued" }),+ makeTask({ id: "t2", agent_id: "b", status: "running" }),+ ],+ now: NOW,+ });+ expect(map.get("a")?.availability).toBe("unstable");+ expect(map.get("b")?.availability).toBe("unstable");+ // Workload remains independent: a is queued (waiting), b is working.+ expect(map.get("a")?.workload).toBe("queued");+ expect(map.get("b")?.workload).toBe("working");+ });++ it("ignores terminal tasks in the snapshot when building per-agent workload", () => {+ // Snapshot intentionally still includes each agent's most recent+ // terminal task (back-end SQL didn't change); the front-end now+ // filters them out at the workload-derivation step.+ const agentA = makeAgent({ id: "a", runtime_id: "rt-1" });+ const map = buildPresenceMap({+ agents: [agentA],+ runtimes: [makeRuntime()],+ snapshot: [makeTask({- id: "t2",- agent_id: "b",+ id: "t-terminal",+ agent_id: "a",status: "failed",- completed_at: "2026-04-27T11:00:00Z",+ completed_at: "2026-04-27T11:30:00Z",}),],now: NOW,});- expect(map.get("a")?.availability).toBe("unstable");- expect(map.get("b")?.availability).toBe("unstable");- // Last-task remains independent: a is running (queued), b is failed.- expect(map.get("a")?.lastTask).toBe("running");- expect(map.get("b")?.lastTask).toBe("failed");+ expect(map.get("a")?.workload).toBe("idle");});});diff --git a/packages/core/agents/derive-presence.ts b/packages/core/agents/derive-presence.tsindex e6d375df8e..5c72398651 100644--- a/packages/core/agents/derive-presence.ts+++ b/packages/core/agents/derive-presence.ts@@ -4,18 +4,19 @@// dimensions://// 1. AgentAvailability — derived from runtime reachability only.-// 2. LastTaskState — derived from the task snapshot only.+// 2. Workload — derived from the task counts only.//// They are computed independently and assembled into AgentPresenceDetail.-// No cross-dimension override logic — that was the source of the previous-// model's "sticky red dot" confusion.+// Workload is strictly "what's on the plate right now" — no historical+// terminal state. Past failures / completions live on the detail page+// (Recent Work, failure_reason) and Inbox.import { deriveRuntimeHealth } from "../runtimes/derive-health";-import type { Agent, AgentRuntime, AgentTask, TaskFailureReason } from "../types";+import type { Agent, AgentRuntime, AgentTask } from "../types";import type {AgentAvailability,AgentPresenceDetail,- LastTaskState,+ Workload,} from "./types";// AgentAvailability mirrors RuntimeHealth's reachability buckets but folds@@ -33,76 +34,44 @@ export function deriveAgentAvailability(return "offline"; // offline | about_to_gc collapse here}-interface LastTaskResult {- state: LastTaskState;+// Atomic workload derivation: pure 3-way classification of running/queued+// counts. Exported so Runtime-level views (which already aggregate counts+// per-runtime in their own indices) can plug into the same vocabulary+// without re-deriving from raw task arrays.+export function deriveWorkload(counts: {runningCount: number;queuedCount: number;- failureReason?: TaskFailureReason;- lastTaskCompletedAt?: string;+}): Workload {+ if (counts.runningCount > 0) return "working";+ if (counts.queuedCount > 0) return "queued";+ return "idle";}-// Single pass: count actives + track latest terminal by completed_at. A-// running OR queued task means the agent is currently busy ("running"-// state); only when nothing is in flight do we fall through to the latest-// terminal (which can be completed / failed / cancelled). With no terminal-// history at all, we report `idle`.-//-// Cancelled is no longer filtered out — under the new model the dot is-// availability-driven so honestly surfacing "cancelled" doesn't risk-// lying about whether the agent works. The previous "exclude cancelled-// to keep red sticky" hack is gone.-export function deriveLastTaskState(tasks: readonly AgentTask[]): LastTaskResult {+interface WorkloadDetail {+ workload: Workload;+ runningCount: number;+ queuedCount: number;+}++// Aggregates a task list into running/queued counts, then classifies via+// deriveWorkload. Caller pre-filters to the relevant scope (per-agent or+// per-runtime) — we don't filter again here.+export function deriveWorkloadDetail(tasks: readonly AgentTask[]): WorkloadDetail {let runningCount = 0;let queuedCount = 0;- let latestTerminal: AgentTask | null = null;- let latestTerminalAt = -Infinity;-for (const t of tasks) {if (t.status === "running") {runningCount += 1;} else if (t.status === "queued" || t.status === "dispatched") {queuedCount += 1;- } else if (t.completed_at) {- const ts = new Date(t.completed_at).getTime();- if (!Number.isNaN(ts) && ts > latestTerminalAt) {- latestTerminalAt = ts;- latestTerminal = t;- }}+ // Terminal statuses (completed / failed / cancelled) intentionally+ // ignored — workload is "what's on the plate right now", not history.}-- if (runningCount + queuedCount > 0) {- return { state: "running", runningCount, queuedCount };- }-- if (!latestTerminal) {- return { state: "idle", runningCount: 0, queuedCount: 0 };- }-- const completedAt = latestTerminal.completed_at ?? undefined;- if (latestTerminal.status === "failed") {- return {- state: "failed",- runningCount: 0,- queuedCount: 0,- failureReason: latestTerminal.failure_reason || undefined,- lastTaskCompletedAt: completedAt,- };- }- if (latestTerminal.status === "cancelled") {- return {- state: "cancelled",- runningCount: 0,- queuedCount: 0,- lastTaskCompletedAt: completedAt,- };- }- // completedreturn {- state: "completed",- runningCount: 0,- queuedCount: 0,- lastTaskCompletedAt: completedAt,+ workload: deriveWorkload({ runningCount, queuedCount }),+ runningCount,+ queuedCount,};}@@ -119,16 +88,14 @@ interface DerivePresenceInput {export function deriveAgentPresenceDetail(input: DerivePresenceInput): AgentPresenceDetail {const availability = deriveAgentAvailability(input.runtime, input.now);- const last = deriveLastTaskState(input.tasks);+ const detail = deriveWorkloadDetail(input.tasks);return {availability,- lastTask: last.state,- runningCount: last.runningCount,- queuedCount: last.queuedCount,+ workload: detail.workload,+ runningCount: detail.runningCount,+ queuedCount: detail.queuedCount,capacity: input.agent.max_concurrent_tasks,- failureReason: last.failureReason,- lastTaskCompletedAt: last.lastTaskCompletedAt,};}@@ -138,9 +105,10 @@ export function deriveAgentPresenceDetail(input: DerivePresenceInput): AgentPresexport function buildPresenceMap(args: {agents: readonly Agent[];runtimes: readonly AgentRuntime[];- // The workspace agent task snapshot: every active task + each agent's+ // The workspace agent task snapshot: every active task plus each agent's// most recent terminal task. Comes straight from getAgentTaskSnapshot()- // — no pre-filtering needed.+ // — no pre-filtering needed. Terminal rows are silently ignored by+ // deriveWorkloadDetail (workload is current-state only).snapshot: readonly AgentTask[];now: number;}): Map<string, AgentPresenceDetail> {diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.tsindex 5770bce513..eb16ac257e 100644--- a/packages/core/agents/index.ts+++ b/packages/core/agents/index.ts@@ -4,3 +4,4 @@ export * from "./queries";export * from "./use-agent-presence";export * from "./use-agent-activity";export * from "./use-workspace-presence-prefetch";+export * from "./constants";diff --git a/packages/core/agents/types.ts b/packages/core/agents/types.tsindex 34df759c36..51619a5024 100644--- a/packages/core/agents/types.ts+++ b/packages/core/agents/types.ts@@ -3,23 +3,25 @@// front-end from raw server data (agent + runtime + recent tasks); the// back-end never knows about these enums.//-// Two orthogonal dimensions, derived independently:+// Two orthogonal dimensions, derived independently and answering only+// "what's true right now?" — historical / error context lives on the+// agent detail page (Recent Work, failure_reason) and Inbox, not in the+// list-level summary state://// 1. AgentAvailability — "Can this agent take work right now?"// Depends only on runtime reachability. The dot colour everywhere in// the app reflects this single dimension; never sticky-red because of// a past task outcome.//-// 2. LastTaskState — "What was the last thing this agent did?"-// Depends only on the workspace task snapshot. Surfaced as text + icon-// on focused surfaces (hover card, agent detail, agent list, runtime-// detail). Never colours the dot.-//-// The previous single 5-state union conflated the two: a runtime-healthy-// agent whose last task failed would show a red dot indistinguishable from-// a daemon-dead agent. Splitting them lets each signal be unambiguous.--import type { TaskFailureReason } from "../types";+// 2. Workload — "What is on this agent's plate right now?"+// Depends only on the workspace task snapshot. Three states, each+// pointing at a clear user action:+// working → tasks running, normal+// queued → tasks queued but nothing running (= stuck if availability+// is offline/unstable; momentary if online)+// idle → nothing to do+// No `failed` / `completed` / `cancelled` states — those are historical,+// surfaced via Recent Work + Inbox.// Runtime-reachability dimension. `unstable` is the transient amber state// during the runtime sweeper's grace window (offline < 5 min); it decays@@ -30,40 +32,31 @@ export type AgentAvailability =| "unstable" // 🟡 runtime recently_lost (< 5 min) — transient| "offline"; // ⚫ runtime long offline / missing / never registered-// Last-task dimension. Active and terminal merged into one enum because-// only one applies at a time: while there's any in-flight task the state-// is `running`; once everything terminates we read the latest outcome;-// with no history at all, `idle`.+// Current task load on this agent. Three states — never historical,+// never an error predictor (Inbox + Recent Work handle that)://-// `running` covers both `running` and `queued/dispatched` tasks because-// from the user's perspective "agent is busy" is the same answer; the-// running/queued counts on the detail object preserve the breakdown.+// working → runningCount > 0. The runningCount/queuedCount on the detail+// object preserve the breakdown for display.+// queued → no running task but ≥1 queued/dispatched. Most often means+// the runtime is offline and tasks are stuck waiting; a brief+// flash on online runtimes between dispatch and run is a+// harmless race.+// idle → nothing on the plate.//-// `cancelled` is included as a discrete state (vs. folding into the-// previous filter that excluded cancelled from terminal selection). With-// the dot no longer colour-coded by task state, surfacing "cancelled"-// honestly is fine — it doesn't risk lying about availability.-export type LastTaskState =- | "running" // ≥1 task running or queued right now- | "completed" // latest terminal: completed- | "failed" // latest terminal: failed- | "cancelled" // latest terminal: cancelled- | "idle"; // no active task and no terminal history+// Pair with availability for the full picture: `online + working` is+// normal; `offline + queued` is the "stuck" state we explicitly surface;+// `offline + idle` is "agent unavailable, nothing waiting" — both honest.+export type Workload =+ | "working" // ≥1 task currently running+ | "queued" // nothing running, but ≥1 queued/dispatched+ | "idle"; // nothing on the plateexport interface AgentPresenceDetail {availability: AgentAvailability;- lastTask: LastTaskState;+ workload: Workload;runningCount: number;queuedCount: number;// Mirrors agent.max_concurrent_tasks — pulled into the detail so the UI// can render `running / capacity` ratios without re-fetching the agent.capacity: number;- // Set only when lastTask === "failed". The label lookup happens at the- // UI layer; deriving exposes the raw classifier so the UI can choose copy.- failureReason?: TaskFailureReason;- // Wall-clock timestamp of the latest terminal task. Set whenever- // lastTask is one of completed / failed / cancelled. Used to render- // "Last run: failed · 12 min ago" copy. Undefined for `running` (no- // terminal yet) and `idle` (no history).- lastTaskCompletedAt?: string;}diff --git a/packages/core/agents/use-agent-presence.ts b/packages/core/agents/use-agent-presence.tsindex 9c1de00bc0..a4d5fd774a 100644--- a/packages/core/agents/use-agent-presence.ts+++ b/packages/core/agents/use-agent-presence.ts@@ -110,7 +110,7 @@ export function useWorkspacePresenceMap(wsId: string | undefined): {// skeleton spinning forever.const MISSING_AGENT_DETAIL: AgentPresenceDetail = {availability: "offline",- lastTask: "idle",+ workload: "idle",runningCount: 0,queuedCount: 0,capacity: 0,diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex dd1a35679b..f36952ac43 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -22,6 +22,12 @@ export const issueKeys = {subscribers: (issueId: string) =>["issues", "subscribers", issueId] as const,usage: (issueId: string) => ["issues", "usage", issueId] as const,+ /** Per-issue task list (issue-detail Execution log section). */+ tasks: (issueId: string) => ["issues", "tasks", issueId] as const,+ /** Prefix-match key for invalidating tasks across all issues — used by+ * the global WS task: prefix path so any task lifecycle event refreshes+ * every per-issue list, regardless of which issue is currently mounted. */+ tasksAll: () => ["issues", "tasks"] as const,};export type MyIssuesFilter = Pick<diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 52b21fd24f..34f19f95b5 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -14,7 +14,12 @@ import { projectKeys } from "../projects/queries";import { pinKeys } from "../pins/queries";import { autopilotKeys } from "../autopilots/queries";import { runtimeKeys } from "../runtimes/queries";-import { agentTaskSnapshotKeys, agentActivityKeys, agentRunCountsKeys } from "../agents/queries";+import {+ agentTaskSnapshotKeys,+ agentActivityKeys,+ agentRunCountsKeys,+ agentTasksKeys,+} from "../agents/queries";import {onIssueCreated,onIssueUpdated,@@ -162,6 +167,15 @@ export function useRealtimeSync(qc.invalidateQueries({ queryKey: agentActivityKeys.last30d(wsId) });// 30-day run count likewise increments per task lifecycle event.qc.invalidateQueries({ queryKey: agentRunCountsKeys.last30d(wsId) });+ // Per-agent task list (Activity tab "Recent work"). Prefix match+ // catches every agent's list — the per-agent detail key sits+ // under agentTasks/<wsId>/<agentId>.+ qc.invalidateQueries({ queryKey: agentTasksKeys.all(wsId) });+ // Per-issue task list (issue-detail Execution log). Prefix match+ // across all issues — keeps the contract "any task: event makes+ // every list-of-tasks query stale" so cache stays fresh even+ // when the relevant component isn't currently mounted.+ qc.invalidateQueries({ queryKey: ["issues", "tasks"] });},};diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 773007a140..ef30665b04 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -74,6 +74,21 @@ export interface AgentTask {chat_session_id?: string;/** Non-empty when the task was spawned by an autopilot run. */autopilot_run_id?: string;+ /** Set when this task was created as an auto-retry of a parent task. */+ parent_task_id?: string;+ /** 1-based attempt counter; >1 means this is a retry. */+ attempt?: number;+ /** Set when an issue comment triggered this task (@mention or assignee comment). */+ trigger_comment_id?: string;+ /**+ * Canonical short description of what triggered this task — snapshot+ * taken at creation time. For comment-triggered tasks it's the+ * comment text (truncated to ~200 chars); for autopilot it's the+ * autopilot title; NULL for direct assignments and chat tasks.+ * Persists even if the source comment / autopilot is later edited+ * or deleted.+ */+ trigger_summary?: string;}export interface Agent {diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex d4660c75b4..ebb117a2c9 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -19,6 +19,7 @@ export type WSEventType =| "agent:created"| "agent:archived"| "agent:restored"+ | "task:queued"| "task:dispatch"| "task:progress"| "task:completed"diff --git a/packages/ui/components/ui/data-table-column-header.tsx b/packages/ui/components/ui/data-table-column-header.tsxnew file mode 100644index 0000000000..8e9c603199--- /dev/null+++ b/packages/ui/components/ui/data-table-column-header.tsx@@ -0,0 +1,106 @@+"use client";++import type { Column } from "@tanstack/react-table";+import {+ ChevronDown,+ ChevronsUpDown,+ ChevronUp,+ EyeOff,+ X,+} from "lucide-react";+import type * as React from "react";++import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { cn } from "@multica/ui/lib/utils";++interface DataTableColumnHeaderProps<TData, TValue>+ extends React.ComponentProps<typeof DropdownMenuTrigger> {+ column: Column<TData, TValue>;+ label: string;+}++// Sort/hide-aware column header, adapted from Dice UI+// (https://diceui.com/r/data-table). Renders the label as plain text when+// the column has neither sorting nor hiding enabled (so non-interactive+// columns don't expose a useless dropdown). Otherwise wraps the label in+// a dropdown-menu trigger that toggles sort direction and hides the+// column on demand.+export function DataTableColumnHeader<TData, TValue>({+ column,+ label,+ className,+ ...props+}: DataTableColumnHeaderProps<TData, TValue>) {+ if (!column.getCanSort() && !column.getCanHide()) {+ return <div className={cn(className)}>{label}</div>;+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ className={cn(+ "-ml-1.5 flex h-8 items-center gap-1.5 rounded-md px-2 py-1.5 hover:bg-accent focus:outline-none focus:ring-1 focus:ring-ring data-[state=open]:bg-accent [&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-muted-foreground",+ className,+ )}+ {...props}+ >+ {label}+ {column.getCanSort() &&+ (column.getIsSorted() === "desc" ? (+ <ChevronDown />+ ) : column.getIsSorted() === "asc" ? (+ <ChevronUp />+ ) : (+ <ChevronsUpDown />+ ))}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-28">+ {column.getCanSort() && (+ <>+ <DropdownMenuCheckboxItem+ className="relative pr-8 pl-2 [&>span:first-child]:right-2 [&>span:first-child]:left-auto [&_svg]:text-muted-foreground"+ checked={column.getIsSorted() === "asc"}+ onClick={() => column.toggleSorting(false)}+ >+ <ChevronUp />+ Asc+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem+ className="relative pr-8 pl-2 [&>span:first-child]:right-2 [&>span:first-child]:left-auto [&_svg]:text-muted-foreground"+ checked={column.getIsSorted() === "desc"}+ onClick={() => column.toggleSorting(true)}+ >+ <ChevronDown />+ Desc+ </DropdownMenuCheckboxItem>+ {column.getIsSorted() && (+ <DropdownMenuItem+ className="pl-2 [&_svg]:text-muted-foreground"+ onClick={() => column.clearSorting()}+ >+ <X />+ Reset+ </DropdownMenuItem>+ )}+ </>+ )}+ {column.getCanHide() && (+ <DropdownMenuCheckboxItem+ className="relative pr-8 pl-2 [&>span:first-child]:right-2 [&>span:first-child]:left-auto [&_svg]:text-muted-foreground"+ checked={!column.getIsVisible()}+ onClick={() => column.toggleVisibility(false)}+ >+ <EyeOff />+ Hide+ </DropdownMenuCheckboxItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/packages/ui/components/ui/data-table.tsx b/packages/ui/components/ui/data-table.tsxnew file mode 100644index 0000000000..6d2c9600fd--- /dev/null+++ b/packages/ui/components/ui/data-table.tsx@@ -0,0 +1,183 @@+"use client";++import {+ flexRender,+ type Row,+ type Table as TanstackTable,+} from "@tanstack/react-table";+import type * as React from "react";++// We deliberately use the lower-level shadcn primitives (TableHeader /+// TableBody / TableRow / TableHead / TableCell) but NOT the wrapping+// <Table> component. shadcn's <Table> nests the <table> inside an+// `overflow-x-auto` <div>, which would compete with our outer scroll+// container and pin the horizontal scrollbar to the bottom of the+// table rather than the viewport.+import {+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@multica/ui/components/ui/table";+import { getCellStyle } from "@multica/ui/lib/data-table";+import { cn } from "@multica/ui/lib/utils";++interface DataTableProps<TData> extends React.ComponentProps<"div"> {+ table: TanstackTable<TData>;+ // Optional bar shown below the table when ≥1 row is selected. We+ // don't currently use selection — kept on the API surface for parity+ // with Dice UI's component so future row-select features just work.+ actionBar?: React.ReactNode;+ // Override for the empty-state cell text.+ emptyMessage?: React.ReactNode;+ // Called when the user clicks a row (anywhere outside an interactive+ // descendant — buttons / dropdowns inside cells should call+ // event.stopPropagation in their own handlers). Used to navigate to+ // a detail page on row click without nesting an <a> around <tr>,+ // which is invalid HTML.+ onRowClick?: (row: Row<TData>) => void;+}++// Headless data-table shell — adapted from Dice UI's data-table+// registry (https://diceui.com/r/data-table). Renders a TanStack Table+// instance using shadcn/ui's table primitives.+//+// Layout behaviour:+// - `w-full` + `table-fixed` keeps the table at viewport width and+// makes each column's width come from its first row's <th>+// inline width. column.size is authoritative for sized columns.+// - Columns flagged `meta.grow: true` skip their inline width, so+// fixed table-layout assigns them the leftover space (no spacer+// column needed).+// - The table's `min-width` is the sum of every column's TanStack+// size (`table.getTotalSize()`). That gives grow columns a real+// floor — fixed mode ignores cell-level min-width, but it does+// respect `min-width` on the table itself. When the container is+// wider than min-width the table tracks it; when narrower, the+// table pins to min-width and the outer overflow-auto scrolls.+export function DataTable<TData>({+ table,+ actionBar,+ emptyMessage = "No results.",+ onRowClick,+ className,+ ...props+}: DataTableProps<TData>) {+ return (+ <div+ className={cn("flex min-h-0 flex-1 flex-col", className)}+ {...props}+ >+ <div className="flex min-h-0 flex-1 flex-col overflow-auto bg-background">+ <table+ className="w-full table-fixed caption-bottom text-sm"+ style={{ minWidth: `${table.getTotalSize()}px` }}+ >+ <TableHeader className="sticky top-0 z-10 bg-muted/30 backdrop-blur">+ {table.getHeaderGroups().map((headerGroup) => (+ <TableRow key={headerGroup.id} className="hover:bg-transparent">+ {headerGroup.headers.map((header) => {+ const isPinned = header.column.getIsPinned();+ return (+ <TableHead+ key={header.id}+ colSpan={header.colSpan}+ // Header typography overrides for a "spreadsheet+ // header" look: smaller, all-caps, wider letter+ // spacing, muted colour. shadcn's <TableHead>+ // defaults to text-sm + text-foreground ++ // font-medium, which reads as too heavy here.+ // h-8 (32px) tightens the strip vs the default+ // h-10 (40px).+ // overflow-hidden caps any cell content that+ // exceeds column.size. Tooltip / dropdown /+ // hover-card bodies are portaled, so they are+ // unaffected.+ // Pinned header cell uses muted/30 so it blends+ // into the header strip rather than appearing as+ // a white block under sticky scroll.+ className={cn(+ "h-8 overflow-hidden px-4 py-2 text-xs uppercase tracking-wider text-muted-foreground",+ isPinned && "bg-muted/30 backdrop-blur",+ )}+ style={getCellStyle(header.column, { withBorder: true })}+ >+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext(),+ )}+ </TableHead>+ );+ })}+ </TableRow>+ ))}+ </TableHeader>+ <TableBody>+ {table.getRowModel().rows?.length ? (+ table.getRowModel().rows.map((row) => (+ <TableRow+ key={row.id}+ data-state={row.getIsSelected() && "selected"}+ onClick={+ onRowClick ? () => onRowClick(row) : undefined+ }+ // `group` lets pinned cells track row hover via+ // group-hover (their bg is in className, not on the+ // row, so they stay opaque enough to cover content+ // scrolling beneath them).+ className={cn(+ "group",+ onRowClick && "cursor-pointer",+ )}+ >+ {row.getVisibleCells().map((cell) => {+ const isPinned = cell.column.getIsPinned();+ return (+ <TableCell+ key={cell.id}+ // px-4 across the board so cell content+ // aligns with the surrounding toolbar's+ // px-4. Narrow trailing columns (chevron /+ // actions) declare a column.size large enough+ // to fit the icon plus 16+16 padding.+ // Pinned cells need an opaque bg + group-+ // hover so they cover content scrolling+ // beneath them and follow row hover state.+ className={cn(+ "overflow-hidden px-4 py-2",+ isPinned &&+ "bg-background group-hover:bg-muted/50",+ )}+ style={getCellStyle(cell.column, { withBorder: true })}+ >+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </TableCell>+ );+ })}+ </TableRow>+ ))+ ) : (+ <TableRow>+ <TableCell+ colSpan={table.getAllColumns().length}+ className="h-24 text-center text-muted-foreground"+ >+ {emptyMessage}+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </table>+ </div>+ {actionBar &&+ table.getFilteredSelectedRowModel().rows.length > 0 &&+ actionBar}+ </div>+ );+}diff --git a/packages/ui/components/ui/hover-card.tsx b/packages/ui/components/ui/hover-card.tsxindex 4ce214ebe2..ed83f8f079 100644--- a/packages/ui/components/ui/hover-card.tsx+++ b/packages/ui/components/ui/hover-card.tsx@@ -21,18 +21,33 @@ function HoverCardContent({align = "center",alignOffset = 4,onClick,+ onContextMenu,+ onAuxClick,+ onDoubleClick,...props}: PreviewCardPrimitive.Popup.Props &Pick<PreviewCardPrimitive.Positioner.Props,"align" | "alignOffset" | "side" | "sideOffset">) {- // Stop click events from bubbling out of the popover. Base UI portals the- // popup to <body> so the DOM is detached, but React's synthetic event+ // Stop interaction events from bubbling out of the popup. Base UI portals+ // the popup to <body> so the DOM is detached, but React's synthetic event// system still bubbles through the React component tree — without this,- // clicks on links / buttons inside the card would also fire onClick on- // any ancestor link the trigger was nested in (e.g. issue list rows).- // Consumer-supplied onClick is forwarded after the stop.+ // events on the popup would also fire on any ancestor of the trigger+ // (e.g. a clickable issue list row, a wrapping <a>).+ //+ // We stop the safe set: click / contextmenu / auxclick / dblclick.+ // We deliberately do NOT stop pointerdown / mousedown — Base UI's+ // outside-click dismiss listens to pointerdown on document and uses an+ // "inside React tree" check to decide whether to close. Stopping+ // pointerdown inside the popup would make the dismiss handler wrongly+ // think the click happened outside, requiring two clicks to close+ // (mirrors radix-ui/primitives#2782).+ const stop = <E extends React.SyntheticEvent>(forwarded?: (e: E) => void) =>+ (e: E) => {+ e.stopPropagation()+ forwarded?.(e)+ }return (<PreviewCardPrimitive.Portal data-slot="hover-card-portal"><PreviewCardPrimitive.Positioner@@ -44,10 +59,10 @@ function HoverCardContent({><PreviewCardPrimitive.Popupdata-slot="hover-card-content"- onClick={(e) => {- e.stopPropagation()- onClick?.(e)- }}+ onClick={stop(onClick)}+ onContextMenu={stop(onContextMenu)}+ onAuxClick={stop(onAuxClick)}+ onDoubleClick={stop(onDoubleClick)}className={cn("z-50 w-64 origin-(--transform-origin) rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",classNamediff --git a/packages/ui/lib/data-table.ts b/packages/ui/lib/data-table.tsnew file mode 100644index 0000000000..8df5857992--- /dev/null+++ b/packages/ui/lib/data-table.ts@@ -0,0 +1,58 @@+import type { Column, RowData } from "@tanstack/react-table";+import type * as React from "react";++// Extend TanStack Table's ColumnMeta with a `grow` flag. TanStack merges+// a default `size: 150` into every columnDef, so "no explicit size" can't+// be detected by inspecting columnDef.size (it's always a number). Setting+// `meta: { grow: true }` is the official extension point — DataTable then+// skips the inline width for these columns and lets fixed table-layout+// assign them the leftover space (Linear / GitHub-PR-list pattern: title+// column grows, others stay at their declared widths).+declare module "@tanstack/react-table" {+ interface ColumnMeta<TData extends RowData, TValue> {+ grow?: boolean;+ }+}++// Combined sizing + pinning style for a `<th>` / `<td>` cell. Width is+// emitted unless the column is flagged `meta.grow` (those rely on+// fixed-layout's leftover-space distribution). Pinned columns get+// sticky positioning — see notes below.+//+// Background is intentionally NOT set inline — the upstream Dice UI+// version writes `background: var(--background)` here, which can't+// react to `:hover`. Consumers set bg via Tailwind classes paired with+// `group-hover:`.+export function getCellStyle<TData>(+ column: Column<TData>,+ options?: { withBorder?: boolean },+): React.CSSProperties {+ const grow = column.columnDef.meta?.grow;+ const width = grow ? undefined : column.columnDef.size;++ const isPinned = column.getIsPinned();+ if (!isPinned) {+ return width !== undefined ? { width } : {};+ }++ const withBorder = options?.withBorder ?? false;+ const isLastLeftPinned =+ isPinned === "left" && column.getIsLastColumn("left");+ const isFirstRightPinned =+ isPinned === "right" && column.getIsFirstColumn("right");++ return {+ width,+ position: "sticky",+ left: isPinned === "left" ? `${column.getStart("left")}px` : undefined,+ right: isPinned === "right" ? `${column.getAfter("right")}px` : undefined,+ zIndex: 1,+ boxShadow: withBorder+ ? isLastLeftPinned+ ? "-4px 0 4px -4px var(--border) inset"+ : isFirstRightPinned+ ? "4px 0 4px -4px var(--border) inset"+ : undefined+ : undefined,+ };+}diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 6253c38c6b..85e985e35c 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -16,12 +16,14 @@"./markdown/mentions": "./markdown/mentions.ts","./hooks/*": "./hooks/*.ts","./lib/utils": "./lib/utils.ts",+ "./lib/data-table": "./lib/data-table.ts","./styles/tokens.css": "./styles/tokens.css","./styles/base.css": "./styles/base.css"},"dependencies": {"@base-ui/react": "^1.3.0","@emoji-mart/data": "^1.2.1",+ "@tanstack/react-table": "catalog:","class-variance-authority": "catalog:","clsx": "catalog:","cmdk": "^1.1.1",diff --git a/packages/views/agents/components/agent-columns.tsx b/packages/views/agents/components/agent-columns.tsxnew file mode 100644index 0000000000..703eddaf55--- /dev/null+++ b/packages/views/agents/components/agent-columns.tsx@@ -0,0 +1,368 @@+"use client";++import { Cloud, Lock, Monitor } from "lucide-react";+import type { ColumnDef } from "@tanstack/react-table";+import type { Agent, AgentRuntime } from "@multica/core/types";+import {+ type AgentActivity,+ type AgentPresenceDetail,+ summarizeActivityWindow,+} from "@multica/core/agents";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { ActorAvatar } from "../../common/actor-avatar";+import { availabilityConfig, workloadConfig } from "../presence";+import { AgentRowActions } from "./agent-row-actions";+import { Sparkline } from "./sparkline";++// Per-row data shape. We assemble agent + runtime + presence + activity ++// run count into one struct at the page level so the column cells just+// read off `row.original` without each pulling its own queries.+export interface AgentRow {+ agent: Agent;+ runtime: AgentRuntime | null;+ presence: AgentPresenceDetail | null | undefined;+ activity: AgentActivity | null | undefined;+ runCount: number;+ // Inline owner avatar — non-null when the page wants to attribute the+ // agent to a teammate (typically All scope on someone else's agent).+ ownerIdToShow: string | null;+ // True when the current user can archive / cancel-tasks on this agent.+ canManage: boolean;+}++// Sized columns render at exactly `size` in fixed table-layout mode —+// column.size doubles as the cell's effective max-width: truncatable+// cells with `truncate` inside hit ellipsis at the column edge.+//+// The Agent column has `meta.grow: true` so DataTable skips its inline+// `width` — that lets fixed table-layout assign it the leftover space+// (= container width − sum of other columns), so the table fills the+// viewport without an empty spacer column.+//+// The Agent column also keeps `size: 240` even though it isn't used for+// rendering. TanStack folds this into `table.getTotalSize()`, which+// DataTable applies as the table's `min-width`. That's how the agent+// column gets a real 240px floor: when the viewport drops below+// `sum + 240`, the table refuses to shrink further and the container+// scrolls instead. (Fixed table-layout ignores cell-level min-width+// per spec, so the floor has to live on the table itself.)+const COL_WIDTHS = {+ agent: 240,+ status: 120,+ workload: 140,+ runtime: 200,+ activity: 100,+ runs: 64,+ // 60 = 16 left padding + 28 kebab + 16 right padding. Keeps the+ // kebab's right edge 16px from the card so it lines up with the+ // toolbar's px-4 right inset.+ actions: 60,+} as const;++export function createAgentColumns({+ onDuplicate,+}: {+ onDuplicate: (agent: Agent) => void;+}): ColumnDef<AgentRow>[] {+ return [+ {+ id: "agent",+ header: "Agent",+ size: COL_WIDTHS.agent,+ meta: { grow: true },+ cell: ({ row }) => <AgentNameCell row={row.original} />,+ },+ {+ id: "status",+ header: "Status",+ size: COL_WIDTHS.status,+ cell: ({ row }) => {+ if (row.original.agent.archived_at) {+ return <span className="text-xs text-muted-foreground">—</span>;+ }+ return <AvailabilityCell presence={row.original.presence} />;+ },+ },+ {+ id: "workload",+ header: "Workload",+ size: COL_WIDTHS.workload,+ cell: ({ row }) => {+ if (row.original.agent.archived_at) {+ return <span className="text-xs text-muted-foreground">—</span>;+ }+ return <WorkloadCell presence={row.original.presence} />;+ },+ },+ {+ id: "runtime",+ header: "Runtime",+ size: COL_WIDTHS.runtime,+ cell: ({ row }) => <RuntimeCell row={row.original} />,+ },+ {+ id: "activity",+ header: "Activity (7d)",+ size: COL_WIDTHS.activity,+ cell: ({ row }) => <ActivityCell row={row.original} />,+ },+ {+ id: "runs",+ header: () => <div className="text-right">Runs</div>,+ size: COL_WIDTHS.runs,+ cell: ({ row }) => (+ <div className="text-right font-mono text-xs tabular-nums text-muted-foreground">+ {row.original.runCount == null+ ? "—"+ : row.original.runCount.toLocaleString()}+ </div>+ ),+ },+ {+ id: "actions",+ header: () => null,+ size: COL_WIDTHS.actions,+ cell: ({ row }) => (+ <div+ className="flex justify-end"+ // The kebab dropdown owns its own click target. Stop the row+ // click handler from firing as a side-effect.+ onClick={(e) => e.stopPropagation()}+ >+ <AgentRowActions+ agent={row.original.agent}+ presence={row.original.presence}+ canManage={row.original.canManage}+ onDuplicate={onDuplicate}+ />+ </div>+ ),+ },+ ];+}++// ---------------------------------------------------------------------------+// Cell renderers+// ---------------------------------------------------------------------------++function AgentNameCell({ row }: { row: AgentRow }) {+ const { agent, ownerIdToShow } = row;+ const isArchived = !!agent.archived_at;+ const isPrivate = agent.visibility === "private";++ return (+ <div className="flex min-w-0 items-center gap-3">+ <ActorAvatar+ actorType="agent"+ actorId={agent.id}+ size={28}+ className={`shrink-0 rounded-md ${isArchived ? "opacity-50 grayscale" : ""}`}+ showStatusDot+ />+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2">+ <span+ className={`min-w-0 truncate font-medium ${+ isArchived ? "text-muted-foreground" : ""+ }`}+ >+ {agent.name}+ </span>+ {isPrivate && !isArchived && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Lock className="h-3 w-3 shrink-0 text-muted-foreground/60" />+ }+ />+ <TooltipContent>+ Private — only the owner can assign work+ </TooltipContent>+ </Tooltip>+ )}+ {ownerIdToShow && (+ <ActorAvatar+ actorType="member"+ actorId={ownerIdToShow}+ size={14}+ />+ )}+ {isArchived && (+ <span className="shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">+ Archived+ </span>+ )}+ </div>+ <div+ className={`mt-0.5 truncate text-xs ${+ agent.description+ ? "text-muted-foreground"+ : "italic text-muted-foreground/50"+ }`}+ >+ {agent.description || "No description"}+ </div>+ </div>+ </div>+ );+}++function AvailabilityCell({+ presence,+}: {+ presence: AgentPresenceDetail | null | undefined;+}) {+ if (!presence) {+ return (+ <span className="inline-flex h-3 w-16 animate-pulse rounded bg-muted/60" />+ );+ }+ const av = availabilityConfig[presence.availability];+ return (+ <span className="inline-flex items-center gap-1.5">+ <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${av.dotClass}`} />+ <span className={`text-xs ${av.textClass}`}>{av.label}</span>+ </span>+ );+}++function WorkloadCell({+ presence,+}: {+ presence: AgentPresenceDetail | null | undefined;+}) {+ if (!presence) {+ return (+ <span className="inline-flex h-3 w-20 animate-pulse rounded bg-muted/60" />+ );+ }+ // All three workload states render with the same shape (icon + label ++ // optional counts). Idle agents show "Idle" rather than a bare em-dash+ // — that hyphen used to mean both "no presence data" and "agent is+ // idle", which conflated two distinct things. Em-dash is now reserved+ // for archived rows / undefined presence (handled at the column level).+ const wl = workloadConfig[presence.workload];+ const isWorking = presence.workload === "working";+ const isQueued = presence.workload === "queued";+ // Queued's amber from workloadConfig is the severe tone for "stuck on+ // offline runtime". On an online runtime queued is just a brief race+ // between enqueue and daemon claim, where amber misreads as a warning.+ // Compose with availability so the colour matches the actual signal.+ const queuedTone =+ presence.availability === "online" ? "text-muted-foreground" : wl.textClass;+ const labelTone = isQueued ? queuedTone : wl.textClass;+ // Working: show running/capacity, optionally with +Nq when overflow.+ // Queued (= nothing running, things waiting — typically a stuck-on-+ // offline-runtime signal): show the queued count directly so the user+ // sees "Queued · 2" instead of misleading "Running 0/3 +2q".+ // Idle: no counts — the label alone carries the meaning.+ const counts = isWorking+ ? presence.queuedCount > 0+ ? `${presence.runningCount}/${presence.capacity} +${presence.queuedCount}q`+ : `${presence.runningCount}/${presence.capacity}`+ : isQueued+ ? `${presence.queuedCount}`+ : null;+ return (+ <span className="inline-flex items-center gap-1 text-xs">+ {/* Icon only renders for working/queued — those carry visual meaning+ (spinner = in motion, clock = waiting). Idle adding an icon read+ as a warning marker, which is the wrong signal. */}+ {presence.workload !== "idle" && (+ <wl.icon+ className={`h-3 w-3 shrink-0 ${labelTone} ${isWorking ? "animate-spin" : ""}`}+ />+ )}+ <span className={`shrink-0 ${labelTone}`}>{wl.label}</span>+ {counts && (+ <span className="truncate text-muted-foreground">{counts}</span>+ )}+ </span>+ );+}++function RuntimeCell({ row }: { row: AgentRow }) {+ const { agent, runtime } = row;+ const isCloud = agent.runtime_mode === "cloud";+ const RuntimeIcon = isCloud ? Cloud : Monitor;+ const runtimeLabel = runtime?.name ?? (isCloud ? "Cloud" : "Local");++ return (+ <div className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">+ <RuntimeIcon className="h-3 w-3 shrink-0" />+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="block min-w-0 truncate">{runtimeLabel}</span>+ }+ />+ <TooltipContent>{runtimeLabel}</TooltipContent>+ </Tooltip>+ </div>+ );+}++function ActivityCell({ row }: { row: AgentRow }) {+ const { agent, activity } = row;+ if (agent.archived_at) {+ return <span className="text-xs text-muted-foreground/50">—</span>;+ }+ if (!activity) {+ return (+ <span+ className="inline-block animate-pulse rounded bg-muted/60"+ style={{ width: 64, height: 20 }}+ />+ );+ }+ const summary = summarizeActivityWindow(activity, 7);+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <div className="inline-flex cursor-default items-center">+ <Sparkline buckets={summary.buckets} width={64} height={20} />+ </div>+ }+ />+ <TooltipContent>+ <ActivityTooltipBody activity={activity} />+ </TooltipContent>+ </Tooltip>+ );+}++function ActivityTooltipBody({ activity }: { activity: AgentActivity }) {+ const summary = summarizeActivityWindow(activity, 7);+ const { totalRuns, totalFailed } = summary;+ const { daysSinceCreated } = activity;++ const isPartial = daysSinceCreated < 7;+ const headerText = isPartial+ ? `Created ${daysSinceCreated === 0 ? "today" : `${daysSinceCreated} day${daysSinceCreated === 1 ? "" : "s"} ago`}`+ : "Last 7 days";++ let bodyText: string;+ if (totalRuns === 0) {+ bodyText = "No activity";+ } else {+ const failedFragment =+ totalFailed > 0+ ? ` · ${totalFailed} failed (${Math.round((totalFailed / totalRuns) * 100)}%)`+ : "";+ bodyText = `${totalRuns} run${totalRuns === 1 ? "" : "s"}${failedFragment}`;+ }++ return (+ <div className="flex flex-col gap-0.5">+ <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">+ {headerText}+ </span>+ <span className="text-xs">{bodyText}</span>+ </div>+ );+}diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsxindex 7ac315bf84..fb46312f63 100644--- a/packages/views/agents/components/agent-detail-inspector.tsx+++ b/packages/views/agents/components/agent-detail-inspector.tsx@@ -13,13 +13,23 @@ import type {AgentRuntime,MemberWithUser,} from "@multica/core/types";-import type { AgentPresenceDetail } from "@multica/core/agents";+import {+ AGENT_DESCRIPTION_MAX_LENGTH,+ type AgentPresenceDetail,+} from "@multica/core/agents";import { api } from "@multica/core/api";import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { timeAgo } from "@multica/core/utils";import { Button } from "@multica/ui/components/ui/button";import { ActorAvatar } from "../../common/actor-avatar";import { Input } from "@multica/ui/components/ui/input";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";import {Popover,PopoverContent,@@ -27,6 +37,7 @@ import {} from "@multica/ui/components/ui/popover";import { PropRow } from "../../common/prop-row";import { availabilityConfig } from "../presence";+import { CharCounter } from "./char-counter";import { ConcurrencyPicker } from "./inspector/concurrency-picker";import { ModelPicker } from "./inspector/model-picker";import { RuntimePicker } from "./inspector/runtime-picker";@@ -283,34 +294,139 @@ function NameAndDescription({)}</InlineEditPopover>- <InlineEditPopover+ <DescriptionEditorvalue={agent.description ?? ""}onSave={(v) => onUpdate({ description: v })}- kind="textarea"- title="Edit description"- placeholder="What does this agent do?"+ />+ </div>+ );+}++// Description editor — modal because the description benefits from a roomy+// composition surface (the inline popover was 288 px wide × 3 rows, too+// cramped to read or edit anything substantial). Name stays in the inline+// popover above: a single line is the right shape for it.+//+// The editor body is split into a child component that mounts only while+// the dialog is open. That way the draft state is initialised from `value`+// at mount time and never reset by an external update mid-edit — closing+// the dialog unmounts the body, reopening starts fresh with the latest+// value. This is the React-recommended replacement for the+// `useEffect(reset, [value])` anti-pattern (see "You Might Not Need an+// Effect" — Resetting state with a key / mount).+function DescriptionEditor({+ value,+ onSave,+}: {+ value: string;+ onSave: (next: string) => Promise<void>;+}) {+ const [open, setOpen] = useState(false);++ return (+ <>+ <button+ type="button"+ onClick={() => setOpen(true)}+ className="group -mx-1 inline-flex items-start gap-1.5 self-start rounded px-1 text-left text-xs leading-relaxed transition-colors hover:bg-accent/50">- {(triggerProps) => (- <button- type="button"- {...triggerProps}- className="group -mx-1 inline-flex items-start gap-1.5 self-start rounded px-1 text-left text-xs leading-relaxed transition-colors hover:bg-accent/50"- >- {agent.description ? (- <span className="text-muted-foreground">{agent.description}</span>- ) : (- <span className="italic text-muted-foreground/50">- No description- </span>- )}- <Pencil className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/0 transition-colors group-hover:text-muted-foreground" />- </button>+ {value ? (+ <span className="text-muted-foreground">{value}</span>+ ) : (+ <span className="italic text-muted-foreground/50">No description</span>)}- </InlineEditPopover>- </div>+ <Pencil className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/0 transition-colors group-hover:text-muted-foreground" />+ </button>++ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="sm:max-w-lg">+ {open && (+ <DescriptionEditorBody+ initialValue={value}+ onSave={onSave}+ onClose={() => setOpen(false)}+ />+ )}+ </DialogContent>+ </Dialog>+ </>+ );+}++function DescriptionEditorBody({+ initialValue,+ onSave,+ onClose,+}: {+ initialValue: string;+ onSave: (next: string) => Promise<void>;+ onClose: () => void;+}) {+ const [draft, setDraft] = useState(initialValue);+ const [saving, setSaving] = useState(false);++ const length = [...draft].length;+ const overLimit = length > AGENT_DESCRIPTION_MAX_LENGTH;+ const dirty = draft !== initialValue;++ const commit = async () => {+ if (overLimit || !dirty) return;+ setSaving(true);+ try {+ await onSave(draft);+ onClose();+ } catch {+ // toast handled by parent's onUpdate+ } finally {+ setSaving(false);+ }+ };++ return (+ <>+ <DialogHeader>+ <DialogTitle>Edit description</DialogTitle>+ </DialogHeader>+ <div className="flex flex-col gap-2">+ <textarea+ autoFocus+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ placeholder="What does this agent do?"+ rows={6}+ onKeyDown={(e) => {+ if (e.key === "Escape") onClose();+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ void commit();+ }+ }}+ className="w-full resize-none rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:border-input"+ />+ <CharCounter length={length} max={AGENT_DESCRIPTION_MAX_LENGTH} />+ </div>+ <DialogFooter>+ <Button+ variant="ghost"+ size="sm"+ onClick={onClose}+ disabled={saving}+ >+ Cancel+ </Button>+ <Button+ size="sm"+ onClick={() => void commit()}+ disabled={saving || overLimit || !dirty}+ >+ {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Save"}+ </Button>+ </DialogFooter>+ </>);}+// Generic single-field popover editor used for name / description. Keeps the// trigger styling fully in the caller's hands by using a render prop.function InlineEditPopover({diff --git a/packages/views/agents/components/agent-list-item.tsx b/packages/views/agents/components/agent-list-item.tsxdeleted file mode 100644index d3cc530a4e..0000000000--- a/packages/views/agents/components/agent-list-item.tsx+++ /dev/null@@ -1,354 +0,0 @@-"use client";--import { Cloud, Lock, Monitor } from "lucide-react";-import type { Agent, AgentRuntime } from "@multica/core/types";-import {- type AgentActivity,- type AgentPresenceDetail,- summarizeActivityWindow,-} from "@multica/core/agents";-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from "@multica/ui/components/ui/tooltip";-import { ActorAvatar } from "../../common/actor-avatar";-import { AppLink } from "../../navigation";-import { availabilityConfig, taskStateConfig } from "../presence";-import { AgentPresenceIndicator } from "./agent-presence-indicator";-import { AgentRowActions } from "./agent-row-actions";-import { Sparkline } from "./sparkline";--// Shared grid template used by both the list header and every row, so the-// sticky header columns stay aligned with the rows below it.-//-// Why grid (not <Table table-fixed>): table-fixed forces every column to a-// declared width, which means the Status column was always reserving space-// for the worst case ("Working · 0 / 6 · +5 queued"), even when no agent in-// the workspace was in that state. Switching to grid + `max-content` lets the-// column shrink automatically when the longest cell is just "Available", and-// only widen when there's an agent that actually needs the room. The freed-// space flows into the Agent column (the primary content), via its `1.6fr`-// share — same ratio Skills uses, so the two list pages read as one family.-//-// Leading-avatar column (1.75rem) is a dedicated grid track so the header's-// "Agent" label sits on the same x as the row's name text. Without this the-// avatar (28px) + the internal flex gap pushes the name 40px right of the-// header label, which reads as misalignment. Same pattern is used in Runtimes-// (icon-box and Health dot extracted into their own tracks).-//-// Responsive strategy mirrors the previous table:-// <md → [avatar] Agent · Status (compact dot only) · Actions-// md+ → adds Last run + Runtime + Runs-// lg+ → adds Activity sparkline-// Cells use `hidden md:block` / `hidden lg:block` so they participate in the-// grid only at their breakpoint; the grid template at each tier matches the-// number of visible cells exactly.-//-// Two presence columns at md+ (Status + Last run) instead of one merged-// cell — splitting them lets the user scan each axis independently. The-// dot column is the same 3-color availability everywhere; the Last run-// column shows the task icon + label (running/completed/failed/etc).-export const AGENT_LIST_GRID =- "grid items-center gap-4 " +- "grid-cols-[1.75rem_minmax(0,1fr)_max-content_2.5rem] " +- "md:grid-cols-[1.75rem_minmax(0,1.4fr)_5rem_minmax(0,max-content)_minmax(0,0.8fr)_4rem_2.5rem] " +- "lg:grid-cols-[1.75rem_minmax(0,1.5fr)_5rem_minmax(0,max-content)_minmax(0,0.8fr)_5rem_4rem_2.5rem]";--interface AgentListItemProps {- agent: Agent;- runtime: AgentRuntime | null;- presence: AgentPresenceDetail | null | undefined;- // 30d activity series for this agent. Page derives once for the whole- // workspace and passes a row-specific slice here, so the row component- // doesn't subscribe to its own query (avoids N timers / N subscriptions).- // The list only surfaces the trailing 7 days; we still take the 30d- // shape so the cache stays aligned with the agent detail panel.- activity: AgentActivity | null | undefined;- // 30-day cumulative run count for the RUNS column. Same single-source pattern.- runCount: number | null | undefined;- // Inline owner avatar — non-null when the page wants to attribute the- // agent to a teammate (typically All scope on someone else's agent).- // The page does the "scope === all && owner !== me" decision so the row- // stays pure presentation.- ownerIdToShow: string | null;- // True when the current user can archive / cancel-tasks on this agent.- // Mirrors the back-end's canManageAgent check; the row uses it to gate- // entries in the actions dropdown.- canManage: boolean;- // Page-level callback to open Create dialog with this agent as a- // template (Duplicate action).- onDuplicate: (agent: Agent) => void;- href: string;-}--export function AgentListItem({- agent,- runtime,- presence,- activity,- runCount,- ownerIdToShow,- canManage,- onDuplicate,- href,-}: AgentListItemProps) {- const isArchived = !!agent.archived_at;- const isPrivate = agent.visibility === "private";- const isCloud = agent.runtime_mode === "cloud";- const RuntimeIcon = isCloud ? Cloud : Monitor;- const runtimeLabel = runtime?.name ?? (isCloud ? "Cloud" : "Local");-- return (- <AppLink- href={href}- className={`${AGENT_LIST_GRID} group border-b px-4 py-3 text-sm transition-colors last:border-b-0 hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none`}- >- {/* Avatar — dedicated leading column so the header label "Agent"- aligns with the name text below it. */}- <ActorAvatar- actorType="agent"- actorId={agent.id}- size={28}- className={`rounded-md ${isArchived ? "opacity-50 grayscale" : ""}`}- showStatusDot- />-- {/* Agent — primary text column, eats remaining space. */}- <div className="min-w-0">- <div className="flex items-center gap-2">- <span- className={`truncate font-medium ${- isArchived ? "text-muted-foreground" : ""- }`}- >- {agent.name}- </span>- {/* Lock = private visibility — back-end rejects assignment by- non-owners, so flag it visually. We deliberately do NOT- filter private agents out of the list (mirrors server's- ListAgents behaviour); the icon warns the viewer that- picking this in a picker will fail. */}- {isPrivate && !isArchived && (- <Tooltip>- <TooltipTrigger- render={- <Lock className="h-3 w-3 shrink-0 text-muted-foreground/60" />- }- />- <TooltipContent>- Private — only the owner can assign work- </TooltipContent>- </Tooltip>- )}- {/* Owner attribution — only set in "All" scope when the agent- isn't yours. Tiny avatar (14px) keeps it lightweight; the- hover card on the agent's main avatar already covers the- full owner detail. */}- {ownerIdToShow && (- <ActorAvatar- actorType="member"- actorId={ownerIdToShow}- size={14}- />- )}- {isArchived && (- <span className="shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">- Archived- </span>- )}- </div>- <div- className={`mt-0.5 line-clamp-1 text-xs ${- agent.description- ? "text-muted-foreground"- : "italic text-muted-foreground/50"- }`}- >- {agent.description || "No description"}- </div>- </div>-- {/* Status — availability dimension only. Compact dot under md;- dot + label at md+. Always 3 colours. */}- <div className="flex items-center">- {isArchived ? (- <span className="text-xs text-muted-foreground">—</span>- ) : (- <>- <span className="md:hidden">- <AgentPresenceIndicator detail={presence} compact />- </span>- <span className="hidden md:inline-flex">- <AvailabilityCell presence={presence} />- </span>- </>- )}- </div>-- {/* Last run — md+. Task icon + label + (running counts | reason | time).- Dedicated column so the user can scan "what just happened" without- merging it into the availability cell. */}- <div className="hidden items-center md:flex">- {isArchived ? (- <span className="text-xs text-muted-foreground">—</span>- ) : (- <LastRunCell presence={presence} />- )}- </div>-- {/* Runtime — md+. Sans-font label fits ~25% more chars per pixel than- the previous mono treatment, so most hostnames no longer truncate. */}- <div className="hidden min-w-0 items-center gap-1.5 text-xs text-muted-foreground md:flex">- <RuntimeIcon className="h-3 w-3 shrink-0" />- <Tooltip>- <TooltipTrigger- render={<span className="min-w-0 truncate">{runtimeLabel}</span>}- />- <TooltipContent>{runtimeLabel}</TooltipContent>- </Tooltip>- </div>-- {/* Activity (7d) — lg+. The 7d sparkline is sliced off the 30d- workspace cache here (single source of truth shared with the- detail panel); no extra request. */}- <div className="hidden lg:block">- {isArchived ? (- <span className="text-xs text-muted-foreground/50">—</span>- ) : !activity ? (- <span- className="inline-block animate-pulse rounded bg-muted/60"- style={{ width: 64, height: 20 }}- />- ) : (- <Tooltip>- <TooltipTrigger- render={- <div className="inline-flex cursor-default items-center">- <Sparkline- buckets={summarizeActivityWindow(activity, 7).buckets}- width={64}- height={20}- />- </div>- }- />- <TooltipContent>- <ActivityTooltip activity={activity} />- </TooltipContent>- </Tooltip>- )}- </div>-- {/* Runs (30d) — md+. tabular-nums + right-align keeps the digit column- visually clean across orders of magnitude. */}- <div className="hidden text-right font-mono text-xs tabular-nums text-muted-foreground md:block">- {runCount == null ? "—" : runCount.toLocaleString()}- </div>-- {/* Actions — kebab dropdown, always visible. Empty cell is preserved- (the column has fixed width) when the user has no operable- actions, so column alignment stays stable across rows. */}- <div className="flex justify-end">- <AgentRowActions- agent={agent}- presence={presence}- canManage={canManage}- onDuplicate={onDuplicate}- />- </div>- </AppLink>- );-}--// Availability cell — dot + label, colour from availabilityConfig. Three-// states only; the colour reflects "can the agent take work right now".-function AvailabilityCell({- presence,-}: {- presence: AgentPresenceDetail | null | undefined;-}) {- if (!presence) {- return <span className="inline-flex h-3 w-16 animate-pulse rounded bg-muted/60" />;- }- const av = availabilityConfig[presence.availability];- return (- <span className="inline-flex items-center gap-1.5">- <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${av.dotClass}`} />- <span className={`text-xs ${av.textClass}`}>{av.label}</span>- </span>- );-}--// Last-run cell — task icon + label, with running counts only when active.-// No timestamp: it eats horizontal space and the relative age of a-// completed task isn't actionable in a scan. Hidden when idle so brand--// new agents show "—" instead of "Idle" everywhere.-function LastRunCell({- presence,-}: {- presence: AgentPresenceDetail | null | undefined;-}) {- if (!presence) {- return <span className="inline-flex h-3 w-20 animate-pulse rounded bg-muted/60" />;- }- if (presence.lastTask === "idle") {- return <span className="text-xs text-muted-foreground/50">—</span>;- }- const ts = taskStateConfig[presence.lastTask];- const isRunning = presence.lastTask === "running";- const counts =- isRunning && presence.queuedCount > 0- ? `${presence.runningCount}/${presence.capacity} +${presence.queuedCount}q`- : isRunning- ? `${presence.runningCount}/${presence.capacity}`- : null;- return (- <span className="inline-flex min-w-0 items-center gap-1 text-xs">- <ts.icon className={`h-3 w-3 shrink-0 ${ts.textClass}`} />- <span className={`shrink-0 ${ts.textClass}`}>{ts.label}</span>- {counts && (- <span className="truncate text-muted-foreground">{counts}</span>- )}- </span>- );-}--/**- * Tooltip body for the activity sparkline. Header = window label, body =- * the actual counts (rolled up from the same 7-day slice the bars- * render). Two short lines so the eye lands on the numbers immediately- * on hover.- */-function ActivityTooltip({ activity }: { activity: AgentActivity }) {- const summary = summarizeActivityWindow(activity, 7);- const { totalRuns, totalFailed } = summary;- const { daysSinceCreated } = activity;-- // Header: when the agent is younger than the rendered window, label by- // age so an empty sparkline reads as "new agent" not "broken agent".- const isPartial = daysSinceCreated < 7;- const headerText = isPartial- ? `Created ${daysSinceCreated === 0 ? "today" : `${daysSinceCreated} day${daysSinceCreated === 1 ? "" : "s"} ago`}`- : "Last 7 days";-- let bodyText: string;- if (totalRuns === 0) {- bodyText = "No activity";- } else {- const failedFragment =- totalFailed > 0- ? ` · ${totalFailed} failed (${Math.round((totalFailed / totalRuns) * 100)}%)`- : "";- bodyText = `${totalRuns} run${totalRuns === 1 ? "" : "s"}${failedFragment}`;- }-- return (- <div className="flex flex-col gap-0.5">- <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">- {headerText}- </span>- <span className="text-xs">{bodyText}</span>- </div>- );-}diff --git a/packages/views/agents/components/agent-presence-indicator.tsx b/packages/views/agents/components/agent-presence-indicator.tsxindex 893a35e0c0..b432c4685b 100644--- a/packages/views/agents/components/agent-presence-indicator.tsx+++ b/packages/views/agents/components/agent-presence-indicator.tsx@@ -2,7 +2,7 @@import { Skeleton } from "@multica/ui/components/ui/skeleton";import type { AgentPresenceDetail } from "@multica/core/agents";-import { availabilityConfig, taskStateConfig } from "../presence";+import { availabilityConfig, workloadConfig } from "../presence";interface PresenceIndicatorProps {// null/undefined = still loading. Caller passes the detail computed at@@ -10,16 +10,16 @@ interface PresenceIndicatorProps {// views). Keeping this as a prop avoids per-row hook subscriptions in// long lists.detail: AgentPresenceDetail | null | undefined;- // Compact = dot only, no label / no last-task chip. Used in dense rows.+ // Compact = dot only, no label / no workload chip. Used in dense rows.compact?: boolean;}/*** Renders an agent's two-dimension presence: an availability dot + an- * optional last-task chip. The dot's colour reads only from the+ * optional workload chip. The dot's colour reads only from the* availability dimension (3 colours), so a runtime-healthy agent whose- * last task failed shows a green dot + a red "Failed" chip — the dot- * stops being sticky-red.+ * last task failed shows a green dot — workload no longer carries+ * historical state at all.** Compact mode collapses to dot-only — used in dense surfaces where the* full chip would crowd the row.@@ -42,15 +42,24 @@ export function AgentPresenceIndicator({}const av = availabilityConfig[detail.availability];- const ts = taskStateConfig[detail.lastTask];- const isRunning = detail.lastTask === "running";- const showQueueBadge = isRunning && detail.queuedCount > 0;+ const wl = workloadConfig[detail.workload];+ const isWorking = detail.workload === "working";+ const isQueued = detail.workload === "queued";+ const showQueueBadge = isWorking && detail.queuedCount > 0;+ // Queued's amber comes from workloadConfig as the *severe* tone — meant+ // for "stuck on offline runtime", which is the dominant cause. But on a+ // healthy runtime, queued is just a brief race between enqueue and the+ // daemon's claim, and amber there reads as a warning that isn't there.+ // Compose with availability: online ⇒ muted (transient), otherwise ⇒+ // keep amber (genuine stuck signal).+ const queuedTone =+ detail.availability === "online" ? "text-muted-foreground" : wl.textClass;if (compact) {return (<spanclassName="inline-flex items-center"- title={`${av.label}${detail.lastTask !== "idle" ? ` · ${ts.label}` : ""}`}+ title={`${av.label}${detail.workload !== "idle" ? ` · ${wl.label}` : ""}`}><span className={`h-1.5 w-1.5 shrink-0 rounded-full ${av.dotClass}`} /></span>@@ -65,24 +74,39 @@ export function AgentPresenceIndicator({<span className={`text-xs ${av.textClass}`}>{av.label}</span></span>- {/* Last task — separator + label, with running counts when active.- Hidden for `idle` to keep brand-new agents clean. */}- {detail.lastTask !== "idle" && (- <span className="inline-flex items-center gap-1">- <span className="text-xs text-muted-foreground">·</span>- <span className={`text-xs ${ts.textClass}`}>{ts.label}</span>- {isRunning && (- <span className="font-mono text-xs tabular-nums text-muted-foreground">- {detail.runningCount} / {detail.capacity}- </span>- )}- {showQueueBadge && (- <span className="rounded-md bg-muted px-1 py-0 text-xs font-medium text-muted-foreground">- +{detail.queuedCount} queued- </span>- )}+ {/* Workload — separator + label, with counts when working/queued.+ All three workload states render here for symmetry: idle gets+ its own "Idle" label so the difference between "no presence+ data" (no chip at all) and "agent is idle" (explicit Idle chip)+ is visible. */}+ <span className="inline-flex items-center gap-1">+ <span className="text-xs text-muted-foreground">·</span>+ <span+ className={`text-xs ${+ isQueued ? queuedTone : wl.textClass+ }`}+ >+ {wl.label}</span>- )}+ {isWorking && (+ <span className="font-mono text-xs tabular-nums text-muted-foreground">+ {detail.runningCount} / {detail.capacity}+ </span>+ )}+ {showQueueBadge && (+ <span className="rounded-md bg-muted px-1 py-0 text-xs font-medium text-muted-foreground">+ +{detail.queuedCount} queued+ </span>+ )}+ {/* Queued (no running) — show the queued count directly, since+ there's no running/capacity ratio to anchor on. Honestly+ surfaces "stuck" on offline runtimes. */}+ {isQueued && (+ <span className="font-mono text-xs tabular-nums text-muted-foreground">+ {detail.queuedCount}+ </span>+ )}+ </span></span>);}diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsxindex d9b05a7c0a..0b8ea0c674 100644--- a/packages/views/agents/components/agents-page.tsx+++ b/packages/views/agents/components/agents-page.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import {AlertCircle,ArrowLeft,@@ -10,10 +10,10 @@ import {Search,} from "lucide-react";import { useQuery, useQueryClient } from "@tanstack/react-query";+import { getCoreRowModel, useReactTable } from "@tanstack/react-table";import type { Agent, AgentRuntime, CreateAgentRequest } from "@multica/core/types";import {type AgentAvailability,- type LastTaskState,agentRunCounts30dOptions,summarizeActivityWindow,useWorkspaceActivityMap,@@ -38,56 +38,27 @@ import {} from "@multica/ui/components/ui/dropdown-menu";import { Input } from "@multica/ui/components/ui/input";import { Skeleton } from "@multica/ui/components/ui/skeleton";-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from "@multica/ui/components/ui/tooltip";-import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";+import { DataTable } from "@multica/ui/components/ui/data-table";import { useNavigation } from "../../navigation";import { PageHeader } from "../../layout/page-header";-import {- availabilityConfig,- availabilityOrder,- lastTaskOrder,- taskStateConfig,-} from "../presence";+import { availabilityConfig, availabilityOrder } from "../presence";import { CreateAgentDialog } from "./create-agent-dialog";-import { AGENT_LIST_GRID, AgentListItem } from "./agent-list-item";+import { type AgentRow, createAgentColumns } from "./agent-columns";-// Filter axes layered top → bottom by frequency:+// Filter axes://-// View = which dataset are we looking at (Active vs Archived).-// Archived is low-frequency, so it is NOT a top-level-// segment — it is a ghost link in the toolbar.+// View = active vs archived dataset. Archived is low-frequency,+// accessed through a ghost link in the toolbar.// Scope = ownership lens (All vs Mine). Layer-1 segment.-// Availability = "Can it take work?" — 3-state chip group.-// Last task = "What was the last thing it did?" — 5-state chip group.-//-// Availability and Last task are independent axes (Option B). Filter is-// the intersection: "online + last failed" is a meaningful combination-// (find broken-but-alive agents). Counts on each chip reflect "if I-// selected this chip on this axis (with the other axis's current-// selection), this many agents would match".+// Availability = "Can the agent take work right now?" — 3-state chip+// group (online / unstable / offline) sourced from+// AgentAvailability. The only chip filter we keep —+// the previous Workload axis was dropped because its+// "queued / failed / cancelled" buckets became+// meaningless once Failed left the workload model.type View = "active" | "archived";type Scope = "all" | "mine";type AvailabilityFilter = "all" | AgentAvailability;-type LastTaskFilter = "all" | LastTaskState;--const AVAILABILITY_DESCRIPTION: Record<AgentAvailability, string> = {- online: "Runtime online — agent ready to take work",- unstable:- "Runtime just dropped (< 5 min) — queued work is paused, system is auto-retrying",- offline: "Runtime unreachable",-};--const LAST_TASK_DESCRIPTION: Record<LastTaskState, string> = {- running: "At least one task running or queued right now",- completed: "Most recent task completed successfully",- failed: "Most recent task failed — needs attention",- cancelled: "Most recent task was cancelled",- idle: "No task history yet",-};type SortKey = "recent" | "name" | "runs" | "created";const SORT_KEYS: SortKey[] = ["recent", "name", "runs", "created"];@@ -131,7 +102,6 @@ export function AgentsPage() {const [scope, setScope] = useState<Scope>("mine");const [availabilityFilter, setAvailabilityFilter] =useState<AvailabilityFilter>("all");- const [lastTaskFilter, setLastTaskFilter] = useState<LastTaskFilter>("all");const [sort, setSort] = useState<SortKey>("recent");const [search, setSearch] = useState("");const [showCreate, setShowCreate] = useState(false);@@ -143,9 +113,6 @@ export function AgentsPage() {null,);- const scrollRef = useRef<HTMLDivElement>(null);- const fadeStyle = useScrollFade(scrollRef);-const runtimesById = useMemo(() => {const m = new Map<string, AgentRuntime>();for (const r of runtimes) m.set(r.id, r);@@ -190,88 +157,53 @@ export function AgentsPage() {}, [inView, currentUser]);const inScope = useMemo(() => {+ // Archived view ignores Mine / All — its toolbar has no scope+ // segment, so silently filtering by `scope` would hide other+ // people's archived agents without any UI to explain why.+ if (view === "archived") return inView;if (scope === "all" || !currentUser) return inView;return inView.filter((a) => a.owner_id === currentUser.id);- }, [inView, scope, currentUser]);-- // Layer 2 — chip counts on each axis. Counts cross-filter against the- // OTHER axis so the displayed number is "if I clicked this chip with- // the other axis as-is, this many agents would match". Stable mental- // model: numbers don't dance unless the user actually changes scope.- const availabilityCounts = useMemo(() => {- const counts: Record<AgentAvailability, number> = {- online: 0,- unstable: 0,- offline: 0,- };- let total = 0;- for (const a of inScope) {- const detail = presenceMap.get(a.id);- if (!detail) continue;- if (lastTaskFilter !== "all" && detail.lastTask !== lastTaskFilter) {- continue;- }- counts[detail.availability] += 1;- total += 1;- }- return { counts, total };- }, [inScope, presenceMap, lastTaskFilter]);-- const lastTaskCounts = useMemo(() => {- const counts: Record<LastTaskState, number> = {- running: 0,- completed: 0,- failed: 0,- cancelled: 0,- idle: 0,- };- let total = 0;- for (const a of inScope) {- const detail = presenceMap.get(a.id);- if (!detail) continue;- if (- availabilityFilter !== "all" &&- detail.availability !== availabilityFilter- ) {- continue;- }- counts[detail.lastTask] += 1;- total += 1;- }- return { counts, total };- }, [inScope, presenceMap, availabilityFilter]);+ }, [inView, scope, currentUser, view]);- // Final cut — apply both axes + search.+ // Final cut — availability chip + search.const filteredAgents = useMemo(() => {const q = search.trim().toLowerCase();return inScope.filter((a) => {- // Filter chips only apply to the Active view; Archived hides the- // chip rows entirely (presence is undefined for archived agents).- if (view === "active") {+ // Availability chip filter only applies to the Active view —+ // archived agents have no presence to match against.+ if (view === "active" && availabilityFilter !== "all") {const detail = presenceMap.get(a.id);- if (- availabilityFilter !== "all" &&- detail?.availability !== availabilityFilter- ) {- return false;- }- if (- lastTaskFilter !== "all" &&- detail?.lastTask !== lastTaskFilter- ) {- return false;- }+ if (detail?.availability !== availabilityFilter) return false;}if (q) {if (!a.name.toLowerCase().includes(q) &&!(a.description ?? "").toLowerCase().includes(q)- )+ ) {return false;+ }}return true;});- }, [inScope, availabilityFilter, lastTaskFilter, view, search, presenceMap]);+ }, [inScope, view, availabilityFilter, presenceMap, search]);++ // Per-availability counts for the chip badges. Computed against+ // `inScope` (ignoring the availability filter itself) so the numbers+ // reflect "if I clicked this chip, this many agents would match"+ // rather than collapsing to 0 for the unselected chips.+ const availabilityCounts = useMemo(() => {+ const counts: Record<AgentAvailability, number> = {+ online: 0,+ unstable: 0,+ offline: 0,+ };+ for (const a of inScope) {+ const detail = presenceMap.get(a.id);+ if (!detail) continue;+ counts[detail.availability] += 1;+ }+ return counts;+ }, [inScope, presenceMap]);const sortedAgents = useMemo(() => {const xs = [...filteredAgents];@@ -353,10 +285,59 @@ export function AgentsPage() {navigation.push(paths.agentDetail(agent.id));};- const handleDuplicate = (agent: Agent) => {+ const handleDuplicate = useCallback((agent: Agent) => {setDuplicateTemplate(agent);setShowCreate(true);- };+ }, []);++ // Assemble per-row data once per render — agent + runtime + presence ++ // activity + role flags. The columns reach into `row.original` and never+ // pull their own queries, which keeps each cell a pure function.+ const agentRows = useMemo<AgentRow[]>(() => {+ return sortedAgents.map((agent) => {+ const isOwner =+ !!currentUser?.id && agent.owner_id === currentUser.id;+ const canManage = isWorkspaceAdmin || isOwner;+ const ownerIdToShow =+ scope === "all" &&+ agent.owner_id &&+ agent.owner_id !== currentUser?.id+ ? agent.owner_id+ : null;+ return {+ agent,+ runtime: runtimesById.get(agent.runtime_id) ?? null,+ presence: presenceMap.get(agent.id) ?? null,+ activity: activityMap.get(agent.id) ?? null,+ runCount: runCountsById.get(agent.id) ?? 0,+ ownerIdToShow,+ canManage,+ };+ });+ }, [+ sortedAgents,+ currentUser,+ isWorkspaceAdmin,+ scope,+ runtimesById,+ presenceMap,+ activityMap,+ runCountsById,+ ]);++ const columns = useMemo(+ () => createAgentColumns({ onDuplicate: handleDuplicate }),+ [handleDuplicate],+ );++ const table = useReactTable({+ data: agentRows,+ columns,+ getCoreRowModel: getCoreRowModel(),+ // Pin the kebab column right so it stays accessible during horizontal+ // scroll — matches the pattern in Linear / Notion / GitHub.+ initialState: { columnPinning: { right: ["actions"] } },+ });// ---- Loading ----if (isLoading) {@@ -439,21 +420,17 @@ export function AgentsPage() {setSort={setSort}search={search}setSearch={setSearch}- />- <PresenceFilterRows- availabilityFilter={availabilityFilter}- setAvailabilityFilter={setAvailabilityFilter}- availabilityCounts={availabilityCounts.counts}- availabilityTotal={availabilityCounts.total}- lastTaskFilter={lastTaskFilter}- setLastTaskFilter={setLastTaskFilter}- lastTaskCounts={lastTaskCounts.counts}- lastTaskTotal={lastTaskCounts.total}visibleCount={sortedAgents.length}totalCount={inScope.length}archivedCount={archivedCount}onShowArchived={() => setView("archived")}/>+ <AvailabilityFilterRow+ value={availabilityFilter}+ onChange={setAvailabilityFilter}+ counts={availabilityCounts}+ totalCount={inScope.length}+ /></>) : (<ArchivedToolbarRow@@ -465,76 +442,14 @@ export function AgentsPage() {)}{sortedAgents.length === 0 ? (- <NoMatches- view={view}- search={search}- hasFilter={- availabilityFilter !== "all" || lastTaskFilter !== "all"+ <NoMatches view={view} search={search} scope={scope} />+ ) : (+ <DataTable+ table={table}+ onRowClick={(row) =>+ navigation.push(paths.agentDetail(row.original.agent.id))}- scope={scope}/>- ) : (- <div- ref={scrollRef}- style={fadeStyle}- className="flex-1 min-h-0 overflow-y-auto"- >- {/*- Layout strategy — CSS Grid + `max-content` on Status, ratio- fr's elsewhere. The Status column shrinks to fit when no- agent is in a high-load Working state, and only widens- when the data demands it; the freed space flows into the- Agent (1.6fr) primary column. See AGENT_LIST_GRID for the- full breakpoint ladder. Sticky header reuses the same grid- template so column edges align with rows pixel-for-pixel.- */}- <div- role="row"- className={`${AGENT_LIST_GRID} sticky top-0 z-10 border-b bg-muted/30 px-4 py-2 text-xs font-medium uppercase tracking-wider text-muted-foreground backdrop-blur`}- >- {/* Avatar leading slot — empty header cell so the "Agent"- label below aligns with the row's name text, not the- avatar's left edge. */}- <span aria-hidden />- <span>Agent</span>- <span>Status</span>- <span className="hidden md:block">Last run</span>- <span className="hidden md:block">Runtime</span>- <span className="hidden lg:block">Activity (7d)</span>- <span className="hidden text-right md:block">Runs</span>- {/* Operations column header — kept silent; the kebab- cell speaks for itself. */}- <span aria-label="Actions" />- </div>- {sortedAgents.map((agent) => {- const isOwner =- !!currentUser?.id && agent.owner_id === currentUser.id;- const canManage = isWorkspaceAdmin || isOwner;- // Inline owner avatar only in All scope on a teammate's- // agent — Mine scope means owner is always you, so a- // self-avatar everywhere would be visual noise.- const ownerIdToShow =- scope === "all" &&- agent.owner_id &&- agent.owner_id !== currentUser?.id- ? agent.owner_id- : null;- return (- <AgentListItem- key={agent.id}- agent={agent}- runtime={runtimesById.get(agent.runtime_id) ?? null}- presence={presenceMap.get(agent.id) ?? null}- activity={activityMap.get(agent.id) ?? null}- runCount={runCountsById.get(agent.id) ?? 0}- ownerIdToShow={ownerIdToShow}- canManage={canManage}- onDuplicate={handleDuplicate}- href={paths.agentDetail(agent.id)}- />- );- })}- </div>)}</div>)}@@ -616,6 +531,10 @@ function ActiveToolbarRow({setSort,search,setSearch,+ visibleCount,+ totalCount,+ archivedCount,+ onShowArchived,}: {scope: Scope;setScope: (v: Scope) => void;@@ -624,13 +543,18 @@ function ActiveToolbarRow({setSort: (v: SortKey) => void;search: string;setSearch: (v: string) => void;+ visibleCount: number;+ totalCount: number;+ archivedCount: number;+ onShowArchived: () => void;}) {- // Layout follows Skills: [Search] [Mine|All] [Sort ▼]- // Search and the scope segment cluster on the left (Skills puts its- // filter buttons immediately after the search the same way). Sort- // gets pushed to the far right via ml-auto.+ // Layout: [Search] [Mine|All] ......... [Show archived] [N of M] [Sort ▼]+ // Filter chips were removed (status / workload chips on a small team+ // gain less than they cost), so the toolbar collapses to a single row.+ // Visible/total count and the archived link inherit their old position+ // from the deleted PresenceFilterRows.return (- <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">+ <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4"><div className="relative"><Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" /><Input@@ -641,7 +565,19 @@ function ActiveToolbarRow({/></div><ScopeSegment scope={scope} setScope={setScope} counts={scopeCounts} />- <div className="ml-auto">+ <div className="ml-auto flex items-center gap-3">+ {archivedCount > 0 && (+ <button+ type="button"+ onClick={onShowArchived}+ className="text-xs text-muted-foreground transition-colors hover:text-foreground"+ >+ Show archived ({archivedCount}) →+ </button>+ )}+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">+ {visibleCount} of {totalCount}+ </span><SortDropdown sort={sort} setSort={setSort} /></div></div>@@ -747,161 +683,76 @@ function SortDropdown({}// ----------------------------------------------------------------------------// Active view — Layer 2: two independent filter axes (availability + last-// task) + visible/total count. The right edge hosts the low-frequency-// "Show archived" link, kept out of Layer 1 so the primary toolbar stays-// uncluttered.-//-// Two rows because cramming both axes into a single row makes the chip-// labels feel ambiguous ("Online" and "Failed" side by side reads as a-// single stack of facets, but they're on different axes). Two rows with-// a leading label make the axis split obvious.+// Availability chip row — All / Online / Unstable / Offline. Only shown+// in the Active view; archived agents have no presence.// ----------------------------------------------------------------------------function PresenceFilterRows({- availabilityFilter,- setAvailabilityFilter,- availabilityCounts,- availabilityTotal,- lastTaskFilter,- setLastTaskFilter,- lastTaskCounts,- lastTaskTotal,- visibleCount,+function AvailabilityFilterRow({+ value,+ onChange,+ counts,totalCount,- archivedCount,- onShowArchived,}: {- availabilityFilter: AvailabilityFilter;- setAvailabilityFilter: (v: AvailabilityFilter) => void;- availabilityCounts: Record<AgentAvailability, number>;- availabilityTotal: number;- lastTaskFilter: LastTaskFilter;- setLastTaskFilter: (v: LastTaskFilter) => void;- lastTaskCounts: Record<LastTaskState, number>;- lastTaskTotal: number;- visibleCount: number;+ value: AvailabilityFilter;+ onChange: (v: AvailabilityFilter) => void;+ counts: Record<AgentAvailability, number>;totalCount: number;- archivedCount: number;- onShowArchived: () => void;}) {return (- <div className="flex shrink-0 flex-col gap-1.5 border-b px-4 py-2.5">- {/* Row 1: Availability — 3 chips. */}- <div className="flex items-center gap-2">- <span className="w-16 shrink-0 text-xs text-muted-foreground">- Status- </span>- <PresenceChip- active={availabilityFilter === "all"}- onClick={() => setAvailabilityFilter("all")}- label="All"- count={availabilityTotal}- description="No availability filter"- />- {availabilityOrder.map((a) => {- const cfg = availabilityConfig[a];- return (- <PresenceChip- key={a}- active={availabilityFilter === a}- onClick={() => setAvailabilityFilter(a)}- label={cfg.label}- count={availabilityCounts[a]}- dotClass={cfg.dotClass}- description={AVAILABILITY_DESCRIPTION[a]}- />- );- })}- <div className="ml-auto flex items-center gap-3">- {archivedCount > 0 && (- <button- type="button"- onClick={onShowArchived}- className="text-xs text-muted-foreground transition-colors hover:text-foreground"- >- Show archived ({archivedCount}) →- </button>- )}- <span className="font-mono text-xs tabular-nums text-muted-foreground/70">- {visibleCount} of {totalCount}- </span>- </div>- </div>- {/* Row 2: Last task — 5 chips. */}- <div className="flex items-center gap-2">- <span className="w-16 shrink-0 text-xs text-muted-foreground">- Last run- </span>- <PresenceChip- active={lastTaskFilter === "all"}- onClick={() => setLastTaskFilter("all")}- label="All"- count={lastTaskTotal}- description="No last-run filter"- />- {lastTaskOrder.map((t) => {- const cfg = taskStateConfig[t];- return (- <PresenceChip- key={t}- active={lastTaskFilter === t}- onClick={() => setLastTaskFilter(t)}- label={cfg.label}- count={lastTaskCounts[t]}- description={LAST_TASK_DESCRIPTION[t]}- />- );- })}- </div>+ <div className="flex h-11 shrink-0 items-center gap-2 border-b px-4">+ <AvailabilityChip+ active={value === "all"}+ onClick={() => onChange("all")}+ label="All"+ count={totalCount}+ />+ {availabilityOrder.map((a) => {+ const cfg = availabilityConfig[a];+ return (+ <AvailabilityChip+ key={a}+ active={value === a}+ onClick={() => onChange(a)}+ label={cfg.label}+ count={counts[a]}+ dotClass={cfg.dotClass}+ />+ );+ })}</div>);}-// Same Button + Tooltip pattern Skills uses for its scope filters. Selected-// state mirrors Skills' `bg-accent text-accent-foreground hover:bg-accent/80`,-// so any future global tweak to that token cascades here for free.-function PresenceChip({+function AvailabilityChip({active,onClick,label,count,dotClass,- description,}: {active: boolean;onClick: () => void;label: string;count: number;dotClass?: string;- description: string;}) {return (- <Tooltip>- <TooltipTrigger- render={- <Button- variant="outline"- size="sm"- onClick={onClick}- className={- active- ? "bg-accent text-accent-foreground hover:bg-accent/80"- : "text-muted-foreground"- }- >- {dotClass && (- <span className={`h-1.5 w-1.5 rounded-full ${dotClass}`} />- )}- <span>{label}</span>- <span className="font-mono tabular-nums text-muted-foreground/70">- {count}- </span>- </Button>- }- />- <TooltipContent side="top">{description}</TooltipContent>- </Tooltip>+ <Button+ variant="outline"+ size="sm"+ onClick={onClick}+ className={+ active+ ? "bg-accent text-accent-foreground hover:bg-accent/80"+ : "text-muted-foreground"+ }+ >+ {dotClass && <span className={`h-1.5 w-1.5 rounded-full ${dotClass}`} />}+ <span>{label}</span>+ <span className="font-mono tabular-nums text-muted-foreground/70">+ {count}+ </span>+ </Button>);}@@ -969,16 +820,17 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {function NoMatches({view,search,- hasFilter: filterActive,scope,}: {view: View;search: string;- hasFilter: boolean;scope: Scope;}) {const hasSearch = search.length > 0;- const hasFilter = filterActive || scope === "mine";+ // "mine" is the only remaining narrowing dimension after chip filters+ // were dropped — keep the wording aware of it so an empty Mine view+ // doesn't suggest the workspace itself is empty.+ const hasFilter = scope === "mine";let body: string;if (view === "archived") {diff --git a/packages/views/agents/components/char-counter.tsx b/packages/views/agents/components/char-counter.tsxnew file mode 100644index 0000000000..64eace0c1c--- /dev/null+++ b/packages/views/agents/components/char-counter.tsx@@ -0,0 +1,19 @@+// Soft warn at 90 % of the cap, hard error past it. Shared between the+// description editor (modal) and the create-agent dialog so both surfaces+// read the same way. Renders a single inline line so it can sit under any+// textarea / input without disturbing surrounding spacing.+export function CharCounter({ length, max }: { length: number; max: number }) {+ const over = length > max;+ const near = !over && length >= Math.floor(max * 0.9);+ const tone = over+ ? "text-destructive"+ : near+ ? "text-warning"+ : "text-muted-foreground";+ return (+ <div className={`text-right text-xs tabular-nums ${tone}`}>+ {length} / {max}+ {over && ` · ${length - max} over limit`}+ </div>+ );+}diff --git a/packages/views/agents/components/create-agent-dialog.tsx b/packages/views/agents/components/create-agent-dialog.tsxindex 7107b9acba..d2c4fcab16 100644--- a/packages/views/agents/components/create-agent-dialog.tsx+++ b/packages/views/agents/components/create-agent-dialog.tsx@@ -29,6 +29,8 @@ import { Button } from "@multica/ui/components/ui/button";import { Input } from "@multica/ui/components/ui/input";import { Label } from "@multica/ui/components/ui/label";import { toast } from "sonner";+import { AGENT_DESCRIPTION_MAX_LENGTH } from "@multica/core/agents";+import { CharCounter } from "./char-counter";type RuntimeFilter = "mine" | "all";@@ -175,8 +177,15 @@ export function CreateAgentDialog({value={description}onChange={(e) => setDescription(e.target.value)}placeholder="What does this agent do?"+ maxLength={AGENT_DESCRIPTION_MAX_LENGTH}className="mt-1"/>+ <div className="mt-1">+ <CharCounter+ length={[...description].length}+ max={AGENT_DESCRIPTION_MAX_LENGTH}+ />+ </div></div><div>diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsxindex cc33f9e64d..808bb28ccc 100644--- a/packages/views/agents/components/tabs/activity-tab.tsx+++ b/packages/views/agents/components/tabs/activity-tab.tsx@@ -1,14 +1,16 @@"use client";import type { ReactNode } from "react";-import { useMemo } from "react";+import { useMemo, useState } from "react";import {ArrowUpRight,CircleHelp,Hash,MessageSquare,Workflow,+ X,} from "lucide-react";+import { toast } from "sonner";import {Tooltip,TooltipContent,@@ -28,6 +30,7 @@ import {summarizeActivityWindow,useWorkspaceActivityMap,} from "@multica/core/agents";+import { api } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { issueDetailOptions } from "@multica/core/issues/queries";@@ -35,11 +38,16 @@ import { timeAgo } from "@multica/core/utils";import { AppLink } from "../../../navigation";import { TranscriptButton } from "../../../common/task-transcript";import { taskStatusConfig } from "../../config";-import { failureReasonLabel } from "../../presence";+import { failureReasonLabel } from "./task-failure";import { Sparkline } from "../sparkline";const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;-const RECENT_LIMIT = 5;+// Recent work pagination: small initial cohort to keep the section+// scannable, then "Show more" reveals 20 at a time. Tasks are already+// fully cached client-side (one listAgentTasks for the whole agent), so+// "more" is a pure state flip — zero extra fetches.+const RECENT_INITIAL = 5;+const RECENT_PAGE = 20;interface ActivityTabProps {agent: Agent;@@ -66,10 +74,19 @@ export function ActivityTab({ agent }: ActivityTabProps) {const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);const activity = activityMap.get(agent.id);+ const [recentDisplayLimit, setRecentDisplayLimit] = useState(RECENT_INITIAL);++ // Chat tasks are intentionally hidden across every Agent-scoped surface+ // (list / detail / activity). They have their own UI in the chat+ // experience; mixing them in here muddies "what is this agent doing+ // for the team" with "what is this agent doing in private chat".+ const isWorkflowTask = (t: AgentTask) => !t.chat_session_id;+const activeTasks = useMemo(() => {return snapshot.filter((t) =>t.agent_id === agent.id &&+ isWorkflowTask(t) &&(t.status === "running" ||t.status === "queued" ||t.status === "dispatched"),@@ -78,11 +95,12 @@ export function ActivityTab({ agent }: ActivityTabProps) {// Most recent terminal tasks. Includes cancelled — users searching// "what just happened" want to see cancellations alongside completions- // and failures.- const recentTasks = useMemo(() => {+ // and failures. Chat sessions filtered out for the same reason as above.+ const recentTasksAll = useMemo(() => {return [...agentTasks].filter((t) =>+ isWorkflowTask(t) &&!!t.completed_at &&(t.status === "completed" ||t.status === "failed" ||@@ -92,10 +110,15 @@ export function ActivityTab({ agent }: ActivityTabProps) {(a, b) =>new Date(b.completed_at!).getTime() -new Date(a.completed_at!).getTime(),- )- .slice(0, RECENT_LIMIT);+ );}, [agentTasks]);+ const recentTasks = useMemo(+ () => recentTasksAll.slice(0, recentDisplayLimit),+ [recentTasksAll, recentDisplayLimit],+ );+ const hasMoreRecent = recentTasksAll.length > recentTasks.length;+const avgDurationMs = useMemo(() => deriveAvgDurationLast30d(agentTasks, Date.now()),[agentTasks],@@ -133,6 +156,11 @@ export function ActivityTab({ agent }: ActivityTabProps) {<Last30dSection activity={activity} avgDurationMs={avgDurationMs} /><RecentWorkSectiontasks={recentTasks}+ totalCount={recentTasksAll.length}+ hasMore={hasMoreRecent}+ onShowMore={() =>+ setRecentDisplayLimit((n) => n + RECENT_PAGE)+ }issueMap={issueMap}agent={agent}/>@@ -244,31 +272,52 @@ function Last30dSection({function RecentWorkSection({tasks,+ totalCount,+ hasMore,+ onShowMore,issueMap,agent,}: {tasks: AgentTask[];+ totalCount: number;+ hasMore: boolean;+ onShowMore: () => void;issueMap: Map<string, Issue>;agent: Agent;}) {+ // Subtitle phrasing: "5 of 47" once we know the total is bigger than+ // what we're rendering, otherwise "5 latest". Total comes from+ // recentTasksAll (already filtered for chat / terminals) so it+ // accurately reflects what would appear if the user kept clicking+ // "Show more" — not the raw on-the-wire row count.+ const subtitle =+ tasks.length === 0+ ? "Nothing finished yet"+ : totalCount > tasks.length+ ? `${tasks.length} of ${totalCount}`+ : `${tasks.length} latest`;return (- <Section- title="Recent work"- subtitle={- tasks.length === 0- ? "Nothing finished yet"- : `${tasks.length} latest`- }- >+ <Section title="Recent work" subtitle={subtitle}>{tasks.length === 0 ? (<EmptyText>This agent hasn't completed anything yet.</EmptyText>) : (- <TaskList- tasks={tasks}- issueMap={issueMap}- timeMode="completed"- agent={agent}- />+ <>+ <TaskList+ tasks={tasks}+ issueMap={issueMap}+ timeMode="completed"+ agent={agent}+ />+ {hasMore && (+ <button+ type="button"+ onClick={onShowMore}+ className="mt-2 self-start rounded text-xs text-muted-foreground transition-colors hover:text-foreground"+ >+ Show more →+ </button>+ )}+ </>)}</Section>);@@ -312,6 +361,7 @@ function TaskRow({agent: Agent;}) {const paths = useWorkspacePaths();+ const [cancelling, setCancelling] = useState(false);const cfg = taskStatusConfig[task.status] ?? taskStatusConfig.queued!;const Icon = cfg.icon;const hasIssue = task.issue_id !== "";@@ -320,6 +370,27 @@ function TaskRow({// Queued tasks have no messages yet — hiding the transcript button avoids// a guaranteed "No execution data recorded." dialog open.const showTranscript = task.status !== "queued";+ // Cancel only makes sense for the three active states. Terminal rows+ // (completed / failed / cancelled) hide the button entirely.+ const showCancel =+ timeMode === "active" &&+ (task.status === "queued" ||+ task.status === "dispatched" ||+ task.status === "running");++ const handleCancel = async () => {+ if (cancelling) return;+ setCancelling(true);+ try {+ await api.cancelTaskById(task.id);+ // No manual invalidate needed — the task:cancelled WS event flows+ // through useRealtimeSync's `task:` prefix path which already+ // invalidates snapshot + per-agent + per-issue task lists.+ } catch (e) {+ toast.error(e instanceof Error ? e.message : "Failed to cancel task");+ setCancelling(false);+ }+ };const sourceFallback = !hasIssue? task.chat_session_id@@ -375,7 +446,7 @@ function TaskRow({}const rowClass = `group flex items-center gap-3 rounded-md border px-3 py-2.5 ${- isRunning ? "border-success/40 bg-success/5" : ""+ isRunning ? "border-brand/40 bg-brand/5" : ""}`;return (@@ -396,12 +467,40 @@ function TaskRow({{issue.identifier}</span>)}- <span className="truncate text-sm">- {issue?.title ??- (hasIssue- ? `Issue ${task.issue_id.slice(0, 8)}…`- : (sourceFallback ?? "Untracked"))}- </span>+ {task.trigger_summary ? (+ // Hover surfaces "why this task ran" — the snapshot lets the+ // agent-side row stay anchored on issue.title (the+ // identification axis here) while still letting the user+ // dwell to see the trigger context. Same pattern as+ // GitHub Actions surfacing the commit message on hover.+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="truncate text-sm">+ {issue?.title ??+ (hasIssue+ ? `Issue ${task.issue_id.slice(0, 8)}…`+ : (sourceFallback ?? "Untracked"))}+ </span>+ }+ />+ <TooltipContent className="max-w-md">+ <div className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/80">+ Triggered by+ </div>+ <div className="mt-0.5 whitespace-pre-wrap text-xs">+ {task.trigger_summary}+ </div>+ </TooltipContent>+ </Tooltip>+ ) : (+ <span className="truncate text-sm">+ {issue?.title ??+ (hasIssue+ ? `Issue ${task.issue_id.slice(0, 8)}…`+ : (sourceFallback ?? "Untracked"))}+ </span>+ )}</div><div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground"><span>{timeText}</span>@@ -445,6 +544,26 @@ function TaskRow({title="View transcript"/>)}+ {showCancel && (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={handleCancel}+ disabled={cancelling}+ aria-label="Cancel task"+ />+ }+ className="flex items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:cursor-not-allowed disabled:opacity-50"+ >+ <X className="h-3.5 w-3.5" />+ </TooltipTrigger>+ <TooltipContent>+ {cancelling ? "Cancelling…" : "Cancel task"}+ </TooltipContent>+ </Tooltip>+ )}</div></div>);diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.tsnew file mode 100644index 0000000000..3df05a2a79--- /dev/null+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -0,0 +1,16 @@+import type { TaskFailureReason } from "@multica/core/types";++// Human-readable copy for the back-end task failure reason enum. Surfaced+// in the agent detail Recent Work tab when a task ended in failure — the+// only place the front-end exposes failure_reason directly to the user.+//+// Lives next to the consuming tab (rather than in agents/presence) because+// failed tasks no longer have a top-level workload state; failure context+// is purely a detail-page concern now.+export const failureReasonLabel: Record<TaskFailureReason, string> = {+ agent_error: "Agent execution error",+ timeout: "Task timed out",+ runtime_offline: "Daemon offline",+ runtime_recovery: "Daemon restarted",+ manual: "Cancelled by user",+};diff --git a/packages/views/agents/config.ts b/packages/views/agents/config.tsindex a1319238a5..8d51db2f90 100644--- a/packages/views/agents/config.ts+++ b/packages/views/agents/config.ts@@ -9,7 +9,7 @@ import {export const taskStatusConfig: Record<string, { label: string; icon: typeof CheckCircle2; color: string }> = {queued: { label: "Queued", icon: Clock, color: "text-muted-foreground" },dispatched: { label: "Dispatched", icon: Play, color: "text-info" },- running: { label: "Running", icon: Loader2, color: "text-success" },+ running: { label: "Running", icon: Loader2, color: "text-brand" },completed: { label: "Completed", icon: CheckCircle2, color: "text-success" },failed: { label: "Failed", icon: XCircle, color: "text-destructive" },cancelled: { label: "Cancelled", icon: XCircle, color: "text-muted-foreground" },diff --git a/packages/views/agents/presence.ts b/packages/views/agents/presence.tsindex f54b65df57..a548f00731 100644--- a/packages/views/agents/presence.ts+++ b/packages/views/agents/presence.ts@@ -1,21 +1,18 @@import {AlertCircle,- CheckCircle2,CircleDot,CircleSlash,+ Clock,Loader2,- PauseCircle,PlugZap,- XCircle,type LucideIcon,} from "lucide-react";-import type { AgentAvailability, LastTaskState } from "@multica/core/agents";-import type { TaskFailureReason } from "@multica/core/types";+import type { AgentAvailability, Workload } from "@multica/core/agents";// Visual mapping for the two presence dimensions, kept in matching shape// so consumers can pick which to render. The two are independent — the-// dot reads only from availabilityConfig, the last-task chip reads only-// from taskStateConfig.+// dot reads only from availabilityConfig, the workload chip reads only+// from workloadConfig.//// Color tokens map to project semantic tokens (no hardcoded Tailwind colors)://@@ -24,16 +21,17 @@ import type { TaskFailureReason } from "@multica/core/types";// unstable → warning (amber) — pairs with the runtime card's amber// offline → muted-foreground (gray)//-// LAST TASK STATE (drives the optional last-task chip on focused surfaces):-// running → brand (blue) has activity-// completed → success (green) all good-// failed → destructive (red)-// cancelled → muted (gray)-// idle → muted (gray) no history+// WORKLOAD (drives the optional workload chip on focused surfaces):+// working → brand (blue) has activity+// queued → warning (amber) anomaly: nothing running but tasks+// waiting (typically stuck on offline+// runtime; brief flash on online is+// a harmless race)+// idle → muted (gray) nothing on the plate//-// Critically: `failed` colour appears ONLY in the last-task chip, never-// on the dot. A runtime-healthy agent whose last task failed shows a-// green dot + a red "Failed" chip — the dot stops being sticky-red.+// `failed` / `completed` / `cancelled` deliberately have no top-level visual+// — those are historical context, surfaced via Recent Work + Inbox, not+// list-level summary state.export interface AvailabilityVisual {label: string;@@ -74,7 +72,7 @@ export const availabilityOrder: AgentAvailability[] = ["offline",];-export interface TaskStateVisual {+export interface WorkloadVisual {label: string;// Foreground colour for icon + label text.textClass: string;@@ -82,26 +80,19 @@ export interface TaskStateVisual {icon: LucideIcon;}-export const taskStateConfig: Record<LastTaskState, TaskStateVisual> = {- running: {- label: "Running",+export const workloadConfig: Record<Workload, WorkloadVisual> = {+ working: {+ label: "Working",textClass: "text-brand",icon: Loader2,},- completed: {- label: "Completed",- textClass: "text-success",- icon: CheckCircle2,- },- failed: {- label: "Failed",- textClass: "text-destructive",- icon: XCircle,- },- cancelled: {- label: "Cancelled",- textClass: "text-muted-foreground",- icon: PauseCircle,+ queued: {+ // Amber chip: nothing running but tasks waiting. On an offline runtime+ // this is the "stuck" signal we explicitly surface (replacing the old+ // misleading "Running 0/N +Mq" copy).+ label: "Queued",+ textClass: "text-warning",+ icon: Clock,},idle: {label: "Idle",@@ -110,22 +101,5 @@ export const taskStateConfig: Record<LastTaskState, TaskStateVisual> = {},};-// Order used by last-run filter chips. Actionable signals first-// (running / failed) before passive ones (idle / cancelled).-export const lastTaskOrder: LastTaskState[] = [- "running",- "failed",- "completed",- "cancelled",- "idle",-];--// Human-readable copy for the back-end task failure reason enum. Surfaced-// in the hover card and detail header when lastTask === "failed".-export const failureReasonLabel: Record<TaskFailureReason, string> = {- agent_error: "Agent execution error",- timeout: "Task timed out",- runtime_offline: "Daemon offline",- runtime_recovery: "Daemon restarted",- manual: "Cancelled by user",-};+// Order used in any future workload chip group; actionable signals first.+export const workloadOrder: Workload[] = ["working", "queued", "idle"];diff --git a/packages/views/issues/components/agent-live-card.tsx b/packages/views/issues/components/agent-live-card.tsxindex a4dcdb6cb4..c46f0e4382 100644--- a/packages/views/issues/components/agent-live-card.tsx+++ b/packages/views/issues/components/agent-live-card.tsx@@ -1,23 +1,35 @@"use client";import { useState, useEffect, useCallback, useRef } from "react";-import { Bot, ChevronRight, ChevronDown, Loader2, ArrowDown, Brain, AlertCircle, Clock, CheckCircle2, XCircle, Square } from "lucide-react";+import { Bot, Loader2, Square } from "lucide-react";import { api } from "@multica/core/api";import { useWSEvent } from "@multica/core/realtime";-import type { TaskMessagePayload, TaskCompletedPayload, TaskFailedPayload, TaskCancelledPayload } from "@multica/core/types/events";+import type { TaskMessagePayload } from "@multica/core/types/events";import type { AgentTask } from "@multica/core/types/agent";-import { cn } from "@multica/ui/lib/utils";import { toast } from "sonner";import { ActorAvatar } from "../../common/actor-avatar";-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@multica/ui/components/ui/collapsible";import { useActorName } from "@multica/core/workspace/hooks";import {TranscriptButton,buildTimeline,- redactSecrets,type TimelineItem,} from "../../common/task-transcript";+// AgentLiveCard renders a sticky banner at the top of the issue's main+// column for every active task. Each banner shows "agent X is working",+// elapsed time, tool count, and Cancel/Transcript actions.+//+// The full timeline (live execution log) used to live inside an+// expandable area on this card. It now lives in the right panel via+// ExecutionLogSection — this card is just a header-style anchor that+// answers "is anyone working on this issue right now?" at a glance.+//+// We still maintain per-task TimelineItem[] state here so the live+// TranscriptButton on the sticky banner can open the dialog with live+// items already attached (the dialog stays in sync via WS as messages+// arrive). The right-panel rows use the lazy mode of TranscriptButton+// instead — a one-shot fetch when opened. Both modes coexist.+function formatElapsed(startedAt: string): string {const elapsed = Date.now() - new Date(startedAt).getTime();const seconds = Math.floor(elapsed / 1000);@@ -27,60 +39,11 @@ function formatElapsed(startedAt: string): string {return `${minutes}m ${secs}s`;}-function formatDuration(start: string, end: string): string {- const ms = new Date(end).getTime() - new Date(start).getTime();- const seconds = Math.floor(ms / 1000);- if (seconds < 60) return `${seconds}s`;- const minutes = Math.floor(seconds / 60);- const secs = seconds % 60;- return `${minutes}m ${secs}s`;-}--function shortenPath(p: string): string {- const parts = p.split("/");- if (parts.length <= 3) return p;- return ".../" + parts.slice(-2).join("/");-}--function getToolSummary(item: TimelineItem): string {- if (!item.input) return "";- const inp = item.input as Record<string, string>;-- // WebSearch / web search- if (inp.query) return inp.query;- // File operations- if (inp.file_path) return shortenPath(inp.file_path);- if (inp.path) return shortenPath(inp.path);- if (inp.pattern) return inp.pattern;- // Bash- if (inp.description) return String(inp.description);- if (inp.command) {- const cmd = String(inp.command);- return cmd.length > 100 ? cmd.slice(0, 100) + "..." : cmd;- }- // Agent- if (inp.prompt) {- const p = String(inp.prompt);- return p.length > 100 ? p.slice(0, 100) + "..." : p;- }- // Skill- if (inp.skill) return String(inp.skill);- // Fallback: show first string value- for (const v of Object.values(inp)) {- if (typeof v === "string" && v.length > 0 && v.length < 120) return v;- }- return "";-}--// ─── Per-task state ─────────────────────────────────────────────────────────-interface TaskState {task: AgentTask;items: TimelineItem[];}-// ─── AgentLiveCard (real-time view for multiple agents) ───────────────────-interface AgentLiveCardProps {issueId: string;}@@ -107,7 +70,9 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {return next;});- // Load messages per task in the background+ // Load messages per task in the background — these feed the live+ // TranscriptButton, not an inline timeline (timeline UI moved to+ // the right panel).for (const task of tasks) {api.listTaskMessages(task.id).then((msgs) => {if (cancelled) return;@@ -117,7 +82,6 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {const next = new Map(prev);const existing = next.get(task.id);if (existing) {- // Merge: keep any WS-delivered items not in the loaded batchconst loadedSeqs = new Set(timeline.map((i) => i.seq));const wsOnly = existing.items.filter((i) => !loadedSeqs.has(i.seq));const merged = [...timeline, ...wsOnly].sort((a, b) => a.seq - b.seq);@@ -134,7 +98,7 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {return () => { cancelled = true; };}, [issueId]);- // Handle real-time task messages — route by task_id+ // Real-time messages — route by task_id and dedupe by seq.useWSEvent("task:message",useCallback((payload: unknown) => {@@ -160,13 +124,14 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {const items = [...existing.items, item].sort((a, b) => a.seq - b.seq);next.set(msg.task_id, { ...existing, items });}- // If we don't have this task yet, the dispatch handler will pick it upreturn next;});}, [issueId]),);- // Handle task end events — remove only the specific task+ // Task end — drop the banner. The right-panel ExecutionLogSection+ // will pick the same task back up under "Past runs" via its own WS+ // invalidate path.const handleTaskEnd = useCallback((payload: unknown) => {const p = payload as { task_id: string; issue_id: string };if (p.issue_id !== issueId) return;@@ -181,25 +146,30 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {useWSEvent("task:failed", handleTaskEnd);useWSEvent("task:cancelled", handleTaskEnd);- // Pick up newly dispatched tasks- useWSEvent(- "task:dispatch",- useCallback((payload: unknown) => {- const p = payload as { issue_id?: string };- if (p.issue_id && p.issue_id !== issueId) return;- api.getActiveTasksForIssue(issueId).then(({ tasks }) => {- setTaskStates((prev) => {- const next = new Map(prev);- for (const task of tasks) {- if (!next.has(task.id)) {- next.set(task.id, { task, items: [] });- }+ // Newly active tasks — both queued and dispatched land here. Subscribing+ // to both events matters because retry creates a queued child without+ // emitting task:dispatch (only the daemon's claim does), so listening+ // to dispatch alone leaves the banner stale during the queued window.+ // The handler is idempotent (only inserts unseen task IDs), so it's+ // safe to fire once per event even when both arrive in quick succession.+ const handleTaskActive = useCallback((payload: unknown) => {+ const p = payload as { issue_id?: string };+ if (p.issue_id && p.issue_id !== issueId) return;+ api.getActiveTasksForIssue(issueId).then(({ tasks }) => {+ setTaskStates((prev) => {+ const next = new Map(prev);+ for (const task of tasks) {+ if (!next.has(task.id)) {+ next.set(task.id, { task, items: [] });}- return next;- });- }).catch(console.error);- }, [issueId]),- );+ }+ return next;+ });+ }).catch(console.error);+ }, [issueId]);++ useWSEvent("task:queued", handleTaskActive);+ useWSEvent("task:dispatch", handleTaskActive);if (taskStates.size === 0) return null;@@ -209,7 +179,7 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {return (<>- {/* Primary agent — sticky at top of the Activity section */}+ {/* Primary agent — sticky at the top of the activity area */}<div className="mt-4 sticky top-4 z-10"><SingleAgentLiveCardtask={firstEntry.task}@@ -218,7 +188,7 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {agentName={firstEntry.task.agent_id ? getActorName("agent", firstEntry.task.agent_id) : "Agent"}/></div>- {/* Additional agents — scroll with the page */}+ {/* Additional agents — non-sticky, scroll with the page */}{restEntries.length > 0 && (<div className="mt-1.5 space-y-1.5">{restEntries.map(({ task, items }) => (@@ -236,7 +206,7 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {);}-// ─── SingleAgentLiveCard (one card per running task) ──────────────────────+// ─── SingleAgentLiveCard (header-only banner per active task) ──────────────interface SingleAgentLiveCardProps {task: AgentTask;@@ -247,12 +217,9 @@ interface SingleAgentLiveCardProps {function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiveCardProps) {const [elapsed, setElapsed] = useState("");- const [open, setOpen] = useState(false);- const [autoScroll, setAutoScroll] = useState(true);const [cancelling, setCancelling] = useState(false);- const scrollRef = useRef<HTMLDivElement>(null);- // Elapsed time+ // Elapsed time — ticks every second so users see the agent is alive.useEffect(() => {if (!task.started_at && !task.dispatched_at) return;const startRef = task.started_at ?? task.dispatched_at!;@@ -261,23 +228,6 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLivreturn () => clearInterval(interval);}, [task.started_at, task.dispatched_at]);- // Auto-scroll timeline to bottom- useEffect(() => {- if (autoScroll && scrollRef.current) {- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;- }- }, [items, autoScroll]);-- const handleScroll = useCallback(() => {- if (!scrollRef.current) return;- const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;- setAutoScroll(scrollHeight - scrollTop - clientHeight < 40);- }, []);-- const toggleOpen = useCallback(() => {- setOpen(!open);- }, [open]);-const handleCancel = useCallback(async () => {if (cancelling) return;setCancelling(true);@@ -293,20 +243,7 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLivreturn (<div className="rounded-lg border border-info/20 bg-info/5 backdrop-blur-sm">- {/* Header — click to toggle timeline */}- <div- className="group flex items-center gap-2 px-3 py-2 cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors"- role="button"- tabIndex={0}- aria-expanded={open}- onClick={toggleOpen}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- toggleOpen();- }- }}- >+ <div className="flex items-center gap-2 px-3 py-2 text-muted-foreground">{task.agent_id ? (<ActorAvatar actorType="agent" actorId={task.agent_id} size={20} enableHoverCard showStatusDot />) : (@@ -316,7 +253,7 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiv)}<div className="flex items-center gap-1.5 text-xs min-w-0"><Loader2 className="h-3 w-3 animate-spin text-info shrink-0" />- <span className="cursor-pointer font-medium text-foreground truncate">{agentName} is working</span>+ <span className="font-medium text-foreground truncate">{agentName} is working</span><span className="text-muted-foreground tabular-nums shrink-0">{elapsed}</span>{toolCount > 0 && (<span className="text-muted-foreground shrink-0">{toolCount} tools</span>@@ -331,7 +268,7 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLivtitle="View transcript"/><button- onClick={(e) => { e.stopPropagation(); handleCancel(); }}+ onClick={handleCancel}disabled={cancelling}className="flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50"title="Stop agent"@@ -339,306 +276,8 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiv{cancelling ? <Loader2 className="h-3 w-3 animate-spin" /> : <Square className="h-3 w-3" />}<span>Stop</span></button>- <ChevronDown className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-180")} />- </div>- </div>-- {/* Timeline — grid-rows animation for smooth collapse/expand */}- <div- className={cn(- "grid transition-[grid-template-rows] duration-200 ease-out",- open ? "grid-rows-[1fr]" : "grid-rows-[0fr]",- )}- >- <div className="overflow-hidden">- {items.length > 0 ? (- <div- ref={scrollRef}- onScroll={handleScroll}- className="relative max-h-80 overflow-y-auto overscroll-y-contain border-t border-info/10 px-3 py-2 space-y-0.5"- >- {items.map((item, idx) => (- <TimelineRow key={`${item.seq}-${idx}`} item={item} />- ))}-- {!autoScroll && (- <button- onClick={(e) => {- e.stopPropagation();- if (scrollRef.current) {- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;- setAutoScroll(true);- }- }}- className="sticky bottom-0 left-1/2 -translate-x-1/2 flex items-center gap-1 rounded-full bg-background border px-2 py-0.5 text-xs text-muted-foreground hover:text-foreground shadow-sm"- >- <ArrowDown className="h-3 w-3" />- Latest- </button>- )}- </div>- ) : (- <div className="border-t border-info/10 px-3 py-3">- <p className="text-xs text-muted-foreground">- Live log is not available for this agent provider. Results will appear when the task completes.- </p>- </div>- )}</div></div>-- </div>- );-}--// ─── TaskRunHistory (past execution logs) ──────────────────────────────────--interface TaskRunHistoryProps {- issueId: string;-}--export function TaskRunHistory({ issueId }: TaskRunHistoryProps) {- const [tasks, setTasks] = useState<AgentTask[]>([]);- const [open, setOpen] = useState(false);-- useEffect(() => {- api.listTasksByIssue(issueId).then(setTasks).catch(console.error);- }, [issueId]);-- // Refresh when a task completes- useWSEvent(- "task:completed",- useCallback((payload: unknown) => {- const p = payload as TaskCompletedPayload;- if (p.issue_id !== issueId) return;- api.listTasksByIssue(issueId).then(setTasks).catch(console.error);- }, [issueId]),- );-- useWSEvent(- "task:failed",- useCallback((payload: unknown) => {- const p = payload as TaskFailedPayload;- if (p.issue_id !== issueId) return;- api.listTasksByIssue(issueId).then(setTasks).catch(console.error);- }, [issueId]),- );-- // Refresh when a task is cancelled- useWSEvent(- "task:cancelled",- useCallback((payload: unknown) => {- const p = payload as TaskCancelledPayload;- if (p.issue_id !== issueId) return;- api.listTasksByIssue(issueId).then(setTasks).catch(console.error);- }, [issueId]),- );-- const completedTasks = tasks.filter((t) => t.status === "completed" || t.status === "failed" || t.status === "cancelled");- if (completedTasks.length === 0) return null;-- return (- <Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="flex w-full items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors py-1">- <ChevronRight className={cn("h-3 w-3 transition-transform", open && "rotate-90")} />- <Clock className="h-3 w-3" />- <span>Execution history ({completedTasks.length})</span>- </CollapsibleTrigger>- <CollapsibleContent>- <div className="mt-1 space-y-2">- {completedTasks.map((task) => (- <TaskRunEntry key={task.id} task={task} />- ))}- </div>- </CollapsibleContent>- </Collapsible>- );-}--function TaskRunEntry({ task }: { task: AgentTask }) {- const { getActorName } = useActorName();- const [open, setOpen] = useState(false);- const [items, setItems] = useState<TimelineItem[] | null>(null);-- const loadMessages = useCallback(() => {- if (items !== null) return; // already loaded- api.listTaskMessages(task.id).then((msgs) => {- setItems(buildTimeline(msgs));- }).catch((e) => {- console.error(e);- setItems([]);- });- }, [task.id, items]);-- useEffect(() => {- if (open) loadMessages();- }, [open, loadMessages]);-- const agentName = task.agent_id ? getActorName("agent", task.agent_id) : "Agent";-- const duration = task.started_at && task.completed_at- ? formatDuration(task.started_at, task.completed_at)- : null;-- return (- <Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent/30 transition-colors border border-transparent hover:border-border">- <ChevronRight className={cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")} />- {task.status === "completed" ? (- <CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-success" />- ) : (- <XCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />- )}- <span className="text-muted-foreground">- {new Date(task.created_at).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })}- </span>- {duration && <span className="text-muted-foreground">{duration}</span>}- <span className={cn("ml-auto capitalize", task.status === "completed" ? "text-success" : "text-destructive")}>- {task.status}- </span>- <TranscriptButton- task={task}- agentName={agentName}- items={items ?? undefined}- title="View transcript"- />- </CollapsibleTrigger>- <CollapsibleContent>- <div className="ml-5 mt-1 max-h-64 overflow-y-auto rounded border bg-muted/30 px-3 py-2 space-y-0.5">- {items === null ? (- <div className="flex items-center gap-2 text-xs text-muted-foreground py-2">- <Loader2 className="h-3 w-3 animate-spin" />- Loading...- </div>- ) : items.length === 0 ? (- <p className="text-xs text-muted-foreground py-2">No execution data recorded.</p>- ) : (- items.map((item, idx) => (- <TimelineRow key={`${item.seq}-${idx}`} item={item} />- ))- )}- </div>- </CollapsibleContent>- </Collapsible>- );-}--// ─── Shared timeline row rendering ──────────────────────────────────────────--function TimelineRow({ item }: { item: TimelineItem }) {- switch (item.type) {- case "tool_use":- return <ToolCallRow item={item} />;- case "tool_result":- return <ToolResultRow item={item} />;- case "thinking":- return <ThinkingRow item={item} />;- case "text":- return <TextRow item={item} />;- case "error":- return <ErrorRow item={item} />;- default:- return null;- }-}--function ToolCallRow({ item }: { item: TimelineItem }) {- const [open, setOpen] = useState(false);- const summary = getToolSummary(item);- const hasInput = item.input && Object.keys(item.input).length > 0;-- return (- <Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="flex w-full items-center gap-1.5 rounded px-1 -mx-1 py-0.5 text-xs hover:bg-accent/30 transition-colors">- <ChevronRight- className={cn(- "h-3 w-3 shrink-0 text-muted-foreground transition-transform",- open && "rotate-90",- !hasInput && "invisible",- )}- />- <span className="font-medium text-foreground shrink-0">{item.tool}</span>- {summary && <span className="truncate text-muted-foreground">{summary}</span>}- </CollapsibleTrigger>- {hasInput && (- <CollapsibleContent>- <pre className="ml-[18px] mt-0.5 max-h-32 overflow-auto rounded bg-muted/50 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-all">- {redactSecrets(JSON.stringify(item.input, null, 2))}- </pre>- </CollapsibleContent>- )}- </Collapsible>- );-}--function ToolResultRow({ item }: { item: TimelineItem }) {- const [open, setOpen] = useState(false);- const output = item.output ?? "";- if (!output) return null;-- const preview = output.length > 120 ? output.slice(0, 120) + "..." : output;-- return (- <Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="flex w-full items-start gap-1.5 rounded px-1 -mx-1 py-0.5 text-xs hover:bg-accent/30 transition-colors">- <ChevronRight- className={cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform mt-0.5", open && "rotate-90")}- />- <span className="text-muted-foreground/70 truncate">- {item.tool ? `${item.tool} result: ` : "result: "}{preview}- </span>- </CollapsibleTrigger>- <CollapsibleContent>- <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-muted/50 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-all">- {output.length > 4000 ? output.slice(0, 4000) + "\n... (truncated)" : output}- </pre>- </CollapsibleContent>- </Collapsible>- );-}--function ThinkingRow({ item }: { item: TimelineItem }) {- const [open, setOpen] = useState(false);- const text = item.content ?? "";- if (!text) return null;-- const preview = text.length > 150 ? text.slice(0, 150) + "..." : text;-- return (- <Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="flex w-full items-start gap-1.5 rounded px-1 -mx-1 py-0.5 text-xs hover:bg-accent/30 transition-colors">- <Brain className="h-3 w-3 shrink-0 text-info/60 mt-0.5" />- <span className="text-muted-foreground italic truncate">{preview}</span>- </CollapsibleTrigger>- <CollapsibleContent>- <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-info/5 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-words">- {text}- </pre>- </CollapsibleContent>- </Collapsible>- );-}--function TextRow({ item }: { item: TimelineItem }) {- const text = item.content ?? "";- if (!text.trim()) return null;- const lines = text.trim().split("\n").filter(Boolean);- const last = lines[lines.length - 1] ?? "";- if (!last) return null;-- return (- <div className="flex items-start gap-1.5 px-1 -mx-1 py-0.5 text-xs">- <span className="h-3 w-3 shrink-0" />- <span className="text-muted-foreground/60 truncate">{last}</span>- </div>- );-}--function ErrorRow({ item }: { item: TimelineItem }) {- return (- <div className="flex items-start gap-1.5 px-1 -mx-1 py-0.5 text-xs">- <AlertCircle className="h-3 w-3 shrink-0 text-destructive mt-0.5" />- <span className="text-destructive">{item.content}</span></div>);}diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxnew file mode 100644index 0000000000..93a2b3e31f--- /dev/null+++ b/packages/views/issues/components/execution-log-section.tsx@@ -0,0 +1,392 @@+"use client";++import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { ChevronRight, Loader2, Square } from "lucide-react";+import { toast } from "sonner";+import { api } from "@multica/core/api";+import { issueKeys } from "@multica/core/issues/queries";+import type { AgentTask, TaskFailureReason } from "@multica/core/types";+import { timeAgo } from "@multica/core/utils";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { ActorAvatar } from "../../common/actor-avatar";+import { TranscriptButton } from "../../common/task-transcript";+import { failureReasonLabel } from "../../agents/components/tabs/task-failure";++// Mask gradient that fades the trigger-summary text into transparency at+// the right edge. Mirrors the pattern used by the desktop tab bar+// (apps/desktop/.../tab-bar.tsx) and the sidebar pin item+// (packages/views/layout/app-sidebar.tsx) — gives the row a smooth+// visual ramp toward the trailing actions instead of a hard truncate ++// ellipsis cut.+const TRIGGER_MASK_STYLE: React.CSSProperties = {+ maskImage: "linear-gradient(to right, black calc(100% - 12px), transparent)",+ WebkitMaskImage:+ "linear-gradient(to right, black calc(100% - 12px), transparent)",+};++// Right-panel section that lists every agent run for this issue. Active+// runs sit at the top (always visible when present); past runs (terminal+// statuses) collapse behind a "Show past runs (N)" toggle.+//+// Replaces:+// - the click-to-expand timeline that used to live inside AgentLiveCard+// (sticky card stays as a header-only banner)+// - the standalone <TaskRunHistory> below the main content+//+// Row layout — three columns, left to right:+// 1. Agent avatar (no status dot — agent availability is not the+// story here; the row's right column carries the task status)+// 2. Trigger description (e.g. "From comment", "Autopilot", "Retry"),+// truncated with ellipsis when narrow+// 3. Status + relative time, swapped to hover actions (cancel /+// transcript) on hover+//+// One query (`listTasksByIssue`) drives both buckets — the back-end+// returns every status, the front-end filters into active vs past on the+// client. WS task:* events for this issue trigger an invalidate so the+// list updates without polling.++interface ExecutionLogSectionProps {+ issueId: string;+}++// Past-runs sort priority: failed first (needs attention), then+// cancelled (procedural noise), then completed (the boring 'done'+// case sinks to the bottom). Within each group, newest first.+const PAST_STATUS_RANK: Record<string, number> = {+ failed: 0,+ cancelled: 1,+ completed: 2,+};++export function ExecutionLogSection({ issueId }: ExecutionLogSectionProps) {+ const [open, setOpen] = useState(true);+ const [showPast, setShowPast] = useState(false);++ // Cache key registered in `issueKeys.tasks` (packages/core/issues/queries.ts)+ // so the global useRealtimeSync `task:` prefix path invalidates it via+ // a `["issues", "tasks"]` prefix-match — no local WS subscriptions+ // needed, and the cache stays fresh even when this component isn't+ // mounted (e.g. user cancels from agent-side, then navigates here).+ const { data: tasks = [] } = useQuery({+ queryKey: issueKeys.tasks(issueId),+ queryFn: () => api.listTasksByIssue(issueId),+ staleTime: 30_000,+ refetchOnWindowFocus: true,+ });++ const activeTasks = useMemo(+ () =>+ tasks.filter(+ (t) =>+ t.status === "queued" ||+ t.status === "dispatched" ||+ t.status === "running",+ ),+ [tasks],+ );++ const pastTasks = useMemo(() => {+ const past = tasks.filter(+ (t) =>+ t.status === "completed" ||+ t.status === "failed" ||+ t.status === "cancelled",+ );+ // Stable sort: failed first, cancelled second, completed last.+ // Within group: newest completed_at first (fall back to created_at+ // for malformed rows missing completed_at).+ return [...past].sort((a, b) => {+ const rankDiff =+ (PAST_STATUS_RANK[a.status] ?? 99) -+ (PAST_STATUS_RANK[b.status] ?? 99);+ if (rankDiff !== 0) return rankDiff;+ const at = a.completed_at ?? a.created_at;+ const bt = b.completed_at ?? b.created_at;+ return new Date(bt).getTime() - new Date(at).getTime();+ });+ }, [tasks]);++ if (activeTasks.length === 0 && pastTasks.length === 0) return null;++ return (+ <div>+ <button+ className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors mb-2 hover:bg-accent/70 ${+ open ? "" : "text-muted-foreground hover:text-foreground"+ }`}+ onClick={() => setOpen(!open)}+ >+ Execution log+ <ChevronRight+ className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${+ open ? "rotate-90" : ""+ }`}+ />+ {activeTasks.length > 0 && (+ <span className="ml-auto inline-flex items-center gap-1 text-info">+ <span className="h-1.5 w-1.5 rounded-full bg-info animate-pulse" />+ <span className="font-mono tabular-nums">{activeTasks.length}</span>+ </span>+ )}+ </button>+ {open && (+ <div className="space-y-0.5 pl-2">+ {activeTasks.map((task) => (+ <ActiveRow key={task.id} task={task} issueId={issueId} />+ ))}++ {pastTasks.length > 0 && (+ <>+ {activeTasks.length > 0 && (+ <div className="my-1.5 border-t border-border/60" />+ )}+ <button+ type="button"+ onClick={() => setShowPast(!showPast)}+ className="flex w-full items-center gap-1 rounded px-1 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"+ >+ <ChevronRight+ className={`!size-3 shrink-0 stroke-[2.5] transition-transform ${+ showPast ? "rotate-90" : ""+ }`}+ />+ {showPast ? "Hide" : "Show"} past runs ({pastTasks.length})+ </button>+ {showPast && (+ <div className="mt-0.5 space-y-0.5">+ {pastTasks.map((task) => (+ <PastRow key={task.id} task={task} />+ ))}+ </div>+ )}+ </>+ )}+ </div>+ )}+ </div>+ );+}++// ─── Trigger description ────────────────────────────────────────────────────++// Primary source: the canonical snapshot taken at task creation time+// (comment text / autopilot title). Survives source edits/deletes and+// is information-dense — far better than a structural label.+//+// Retry tasks inherit the parent's trigger_summary on the DB side (so the+// snapshot survives across attempts), but a row that just shows the+// inherited summary is indistinguishable from its parent. We prepend+// "Retry #N" when parent_task_id is set so retries are scannable as+// retries even when their summary is inherited.+//+// Fallback chain for legacy tasks created before the snapshot field+// shipped, OR for sources we don't snapshot (direct assignment / chat):+// degrade to a short structural label by trigger source. New tasks+// (post-061 migration) almost always hit the snapshot path.+function buildTriggerText(task: AgentTask): string {+ const isRetry = !!task.parent_task_id;+ const retryPrefix = isRetry+ ? task.attempt && task.attempt > 1+ ? `Retry #${task.attempt} · `+ : "Retry · "+ : "";++ if (task.trigger_summary) return retryPrefix + task.trigger_summary;+ if (isRetry) {+ return task.attempt && task.attempt > 1 ? `Retry #${task.attempt}` : "Retry";+ }+ if (task.autopilot_run_id) return "Autopilot run";+ if (task.trigger_comment_id) return "Comment trigger";+ return "Initial run";+}++// ─── Row visual config ─────────────────────────────────────────────────────++const STATUS_VISUAL: Record<+ AgentTask["status"],+ { label: string; tone: string }+> = {+ queued: { label: "Queued", tone: "text-warning" },+ dispatched: { label: "Starting", tone: "text-warning" },+ running: { label: "Working", tone: "text-info" },+ completed: { label: "Completed", tone: "text-success" },+ failed: { label: "Failed", tone: "text-destructive" },+ cancelled: { label: "Cancelled", tone: "text-muted-foreground" },+};++// Time anchor depends on status. Active rows want "Started 2m ago" /+// "Queued 30s ago" — what's happening now. Past rows want "5m ago" — when+// the verdict landed.+function activeTimeText(task: AgentTask): string {+ if (task.status === "running" && task.started_at) {+ return timeAgo(task.started_at);+ }+ if (task.status === "dispatched" && task.dispatched_at) {+ return timeAgo(task.dispatched_at);+ }+ return timeAgo(task.created_at);+}++// ─── Active row ────────────────────────────────────────────────────────────++function ActiveRow({ task, issueId }: { task: AgentTask; issueId: string }) {+ const [cancelling, setCancelling] = useState(false);+ const cfg = STATUS_VISUAL[task.status];+ const trigger = buildTriggerText(task);+ const time = activeTimeText(task);++ // Transcript only meaningful once messages exist — pure-queued tasks+ // have nothing to show yet.+ const showTranscript = task.status !== "queued";++ const handleCancel = async () => {+ if (cancelling) return;+ setCancelling(true);+ try {+ await api.cancelTask(issueId, task.id);+ } catch (e) {+ toast.error(e instanceof Error ? e.message : "Failed to cancel task");+ setCancelling(false);+ }+ };++ return (+ <RowShell task={task}>+ <TriggerText text={trigger} />+ {/* Status + time always visible — actions append on hover, never+ replace. Same pattern as desktop tab bar / sidebar pins. */}+ <span className="shrink-0 whitespace-nowrap text-xs">+ <span className={cfg.tone}>{cfg.label}</span>+ <span className="text-muted-foreground"> · {time}</span>+ </span>+ <RowActions>+ {showTranscript && (+ <TranscriptButton+ task={task}+ agentName=""+ isLive+ title="View transcript"+ />+ )}+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={handleCancel}+ disabled={cancelling}+ aria-label="Cancel task"+ />+ }+ className="flex items-center justify-center rounded p-1 text-destructive transition-colors hover:bg-destructive/10 disabled:cursor-not-allowed disabled:opacity-50"+ >+ {cancelling ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Square className="h-3.5 w-3.5" />+ )}+ </TooltipTrigger>+ <TooltipContent>Cancel task</TooltipContent>+ </Tooltip>+ </RowActions>+ </RowShell>+ );+}++// ─── Past row ──────────────────────────────────────────────────────────────++function PastRow({ task }: { task: AgentTask }) {+ const cfg = STATUS_VISUAL[task.status];+ const trigger = buildTriggerText(task);+ const time = task.completed_at ? timeAgo(task.completed_at) : "—";+ const failureLabel =+ task.status === "failed" && task.failure_reason+ ? failureReasonLabel[task.failure_reason as TaskFailureReason]+ : null;++ return (+ <RowShell task={task}>+ <TriggerText text={trigger} />+ <span className="shrink-0 whitespace-nowrap text-xs">+ <span className={cfg.tone}>{failureLabel ?? cfg.label}</span>+ <span className="text-muted-foreground"> · {time}</span>+ </span>+ <RowActions>+ <TranscriptButton task={task} agentName="" title="View transcript" />+ </RowActions>+ </RowShell>+ );+}++// ─── Shared row chrome ─────────────────────────────────────────────────────++function RowShell({+ task,+ children,+}: {+ task: AgentTask;+ children: React.ReactNode;+}) {+ // `relative` so the absolute-positioned RowActions slot anchors to this+ // row instead of an outer container.+ return (+ <div className="group relative flex items-center gap-2 rounded px-1 py-1.5 transition-colors hover:bg-accent/40">+ {task.agent_id ? (+ <ActorAvatar+ actorType="agent"+ actorId={task.agent_id}+ size={20}+ enableHoverCard+ />+ ) : (+ <span className="inline-block h-5 w-5 shrink-0 rounded-full bg-muted" />+ )}+ {children}+ </div>+ );+}++// Trigger description with a mask-gradient right edge — text fades into+// transparency in the trailing 12px for the same reason desktop tab /+// sidebar pin do it: avoids a hard truncate cut against neighbouring+// content.+function TriggerText({ text }: { text: string }) {+ return (+ <span+ className="min-w-0 flex-1 overflow-hidden whitespace-nowrap text-xs text-muted-foreground"+ style={TRIGGER_MASK_STYLE}+ >+ {text}+ </span>+ );+}++// Hover-only action slot — absolute-positioned over the row's right edge.+// Status + time stay anchored in the layout; on hover the action buttons+// fade in on top of them with a left-fading gradient backdrop, so the+// status copy is gracefully covered (not hard-clipped) and the row+// content never reflows. Mirrors the "actions sticky over content" idiom+// used by GitHub PR rows, Linear issue rows, etc.+function RowActions({ children }: { children: React.ReactNode }) {+ return (+ <div+ className={[+ "pointer-events-none absolute inset-y-0 right-1 flex items-center gap-0.5 pl-6 opacity-0 transition-opacity",+ // The gradient backdrop blends the row's hover background (accent/40)+ // from the right and fades to transparent on the left, so the+ // status text underneath is dimmed gracefully rather than cut.+ "bg-gradient-to-l from-accent/95 via-accent/80 to-transparent",+ "group-hover:pointer-events-auto group-hover:opacity-100",+ "group-focus-within:pointer-events-auto group-focus-within:opacity-100",+ ].join(" ")}+ >+ {children}+ </div>+ );+}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 60de4c7c79..ebde2092bf 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -42,7 +42,8 @@ import { IssueActionsDropdown, useIssueActions } from "../actions";import { ProjectPicker } from "../../projects/components/project-picker";import { CommentCard } from "./comment-card";import { CommentInput } from "./comment-input";-import { AgentLiveCard, TaskRunHistory } from "./agent-live-card";+import { AgentLiveCard } from "./agent-live-card";+import { ExecutionLogSection } from "./execution-log-section";import { useQuery } from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";@@ -439,6 +440,11 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo</div>}</div>+ {/* Execution log — active runs + collapsed past runs. Self-contained;+ owns its own collapse state and WS subscriptions. Hides itself+ when there are no runs to show. */}+ <ExecutionLogSection issueId={id} />+{/* Token usage */}{usage && usage.task_count > 0 && (<div>@@ -835,17 +841,14 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo</div></div>- {/* Agent live output — sticky inside the Activity section so it- stays pinned while scrolling through TaskRunHistory + comments.- Keyed by issue id so switching issues remounts the card and- clears any in-flight task state from the previous issue. */}+ {/* Agent live output — sticky banner in the activity section,+ keyed by issue id so switching issues remounts the card and+ clears any in-flight task state from the previous issue.+ The execution log itself (per-task timeline + past runs)+ lives in the right panel via ExecutionLogSection — this+ card is just a header-style "agent is working" anchor. */}<AgentLiveCard key={id} issueId={id} />- {/* Agent execution history */}- <div className="mt-3">- <TaskRunHistory key={id} issueId={id} />- </div>-{/* Timeline entries */}<div className="mt-4 flex flex-col gap-3">{(() => {diff --git a/packages/views/package.json b/packages/views/package.jsonindex 68abbcf312..159fd0623e 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -85,6 +85,7 @@},"peerDependencies": {"@tanstack/react-query": "catalog:",+ "@tanstack/react-table": "catalog:","lucide-react": "catalog:","react": "catalog:","react-dom": "catalog:",diff --git a/packages/views/runtimes/components/runtime-columns.tsx b/packages/views/runtimes/components/runtime-columns.tsxnew file mode 100644index 0000000000..aa71efd869--- /dev/null+++ b/packages/views/runtimes/components/runtime-columns.tsx@@ -0,0 +1,548 @@+"use client";++import { useMemo, useState } from "react";+import {+ ArrowUpCircle,+ MoreHorizontal,+ Trash2,+} from "lucide-react";+import { toast } from "sonner";+import type { ColumnDef } from "@tanstack/react-table";+import { useQuery } from "@tanstack/react-query";+import type { AgentRuntime, MemberWithUser } from "@multica/core/types";+import { deriveWorkload } from "@multica/core/agents";+import {+ deriveRuntimeHealth,+ runtimeUsageOptions,+} from "@multica/core/runtimes";+import { useDeleteRuntime } from "@multica/core/runtimes/mutations";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { ActorAvatar } from "../../common/actor-avatar";+import { workloadConfig } from "../../agents/presence";+import { ProviderLogo } from "./provider-logo";+import { HealthIcon, healthLabel } from "./shared";+import {+ computeCostInWindow,+ formatLastSeen,+ isVersionNewer,+ pctChange,+} from "../utils";++// Per-row data assembled at the page level. The columns reach into+// `row.original` and never pull their own data — except for the per-runtime+// usage query in CostCell, which intentionally keeps its 180-day cache key+// shared with the runtime-detail page (clicking a row pre-warms detail).+export interface RuntimeRow {+ runtime: AgentRuntime;+ ownerMember: MemberWithUser | null;+ workload: { agentIds: string[]; runningCount: number; queuedCount: number };+ canDelete: boolean;+}++// Column widths in px. The Runtime column has `meta.grow: true` so+// DataTable skips its inline width — fixed table-layout assigns it the+// leftover space. Its `size: 240` still flows into table.getTotalSize()+// to set the table's `min-width`, giving the runtime column a 240px+// floor below which the container scrolls horizontally instead of+// shrinking the column further.+const COL_WIDTHS = {+ runtime: 240,+ health: 200,+ owner: 60,+ agents: 100,+ workload: 140,+ cost: 100,+ cli: 140,+ // 60 = 16 left padding + 28 kebab + 16 right padding. Keeps the+ // kebab's right edge 16px from the card so it lines up with the+ // toolbar's px-4 right inset.+ actions: 60,+} as const;++interface CreateColumnsArgs {+ showOwner: boolean;+ latestCliVersion: string | null;+ wsId: string;+ now: number;+}++export function createRuntimeColumns({+ showOwner,+ latestCliVersion,+ wsId,+ now,+}: CreateColumnsArgs): ColumnDef<RuntimeRow>[] {+ const cols: ColumnDef<RuntimeRow>[] = [+ {+ id: "runtime",+ header: "Runtime",+ size: COL_WIDTHS.runtime,+ meta: { grow: true },+ cell: ({ row }) => <RuntimeNameCell runtime={row.original.runtime} />,+ },+ {+ id: "health",+ header: "Health",+ size: COL_WIDTHS.health,+ cell: ({ row }) => (+ <HealthCell runtime={row.original.runtime} now={now} />+ ),+ },+ ];++ if (showOwner) {+ cols.push({+ id: "owner",+ header: "Owner",+ size: COL_WIDTHS.owner,+ cell: ({ row }) =>+ row.original.ownerMember ? (+ <ActorAvatar+ actorType="member"+ actorId={row.original.ownerMember.user_id}+ size={18}+ />+ ) : (+ <span className="text-xs text-muted-foreground/50">—</span>+ ),+ });+ }++ cols.push(+ {+ id: "agents",+ header: "Agents",+ size: COL_WIDTHS.agents,+ cell: ({ row }) => (+ <AgentStack agentIds={row.original.workload.agentIds} />+ ),+ },+ {+ id: "workload",+ header: "Workload",+ size: COL_WIDTHS.workload,+ cell: ({ row }) => {+ const health = deriveRuntimeHealth(row.original.runtime, now);+ const offline = health === "offline" || health === "about_to_gc";+ return (+ <WorkloadCell+ running={row.original.workload.runningCount}+ queued={row.original.workload.queuedCount}+ offline={offline}+ />+ );+ },+ },+ {+ id: "cost",+ header: () => <div className="text-right">Cost · 7d</div>,+ size: COL_WIDTHS.cost,+ cell: ({ row }) => <CostCell runtimeId={row.original.runtime.id} />,+ },+ {+ id: "cli",+ header: "CLI",+ size: COL_WIDTHS.cli,+ cell: ({ row }) => (+ <CliCell+ runtime={row.original.runtime}+ latestCliVersion={latestCliVersion}+ />+ ),+ },+ {+ id: "actions",+ header: () => null,+ size: COL_WIDTHS.actions,+ cell: ({ row }) => (+ <div+ className="flex justify-end"+ onClick={(e) => e.stopPropagation()}+ >+ <RowMenu+ runtime={row.original.runtime}+ wsId={wsId}+ canDelete={row.original.canDelete}+ />+ </div>+ ),+ },+ );++ return cols;+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++// Backend formats `runtime.name` as `"<base> (<hostname>)"`. Every runtime on+// the same machine repeats the hostname suffix, so it dominates column width+// while carrying near-zero scan value once seen on the first row. Split it+// so the base name stays emphasised and the hostname renders muted.+export function splitRuntimeName(name: string): {+ base: string;+ hostname: string | null;+} {+ const m = name.match(/^(.+?)\s+\(([^)]+)\)$/);+ if (!m || !m[1] || !m[2]) return { base: name, hostname: null };+ return { base: m[1], hostname: m[2] };+}++// ---------------------------------------------------------------------------+// Cell renderers+// ---------------------------------------------------------------------------++function RuntimeNameCell({ runtime }: { runtime: AgentRuntime }) {+ const { base: baseName, hostname } = splitRuntimeName(runtime.name);+ return (+ <div className="flex min-w-0 items-center gap-2">+ <div className="flex h-8 w-8 shrink-0 items-center justify-center">+ <ProviderLogo provider={runtime.provider} className="h-5 w-5" />+ </div>+ <div className="flex min-w-0 flex-1 items-center gap-1.5">+ <span className="block min-w-0 truncate text-sm font-medium">+ {baseName}+ </span>+ {hostname && (+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="block min-w-0 truncate text-xs text-muted-foreground/70">+ ({hostname})+ </span>+ }+ />+ <TooltipContent>{hostname}</TooltipContent>+ </Tooltip>+ )}+ </div>+ </div>+ );+}++function HealthCell({+ runtime,+ now,+}: {+ runtime: AgentRuntime;+ now: number;+}) {+ const health = deriveRuntimeHealth(runtime, now);+ const lastSeen = formatLastSeen(runtime.last_seen_at);+ return (+ <div className="flex min-w-0 items-center gap-1.5">+ <HealthIcon health={health} />+ <span className="block min-w-0 truncate text-sm">+ {healthLabel(health)}+ {health !== "online" && runtime.last_seen_at && (+ <span className="text-muted-foreground"> · {lastSeen}</span>+ )}+ </span>+ </div>+ );+}++// Mirrors AgentPresenceIndicator's workload chip — same workloadConfig+// vocabulary applied to runtime-level aggregated counts. Offline runtime+// rows still render `—` (the runtime's Health column already says it+// all; redundant Idle here would just be noise). Online idle runtimes+// show "Idle" explicitly to match the agent-side three-state symmetry.+function WorkloadCell({+ running,+ queued,+ offline,+}: {+ running: number;+ queued: number;+ offline: boolean;+}) {+ if (offline) {+ return <span className="text-xs text-muted-foreground/50">—</span>;+ }+ const workload = deriveWorkload({+ runningCount: running,+ queuedCount: queued,+ });+ const wl = workloadConfig[workload];+ // Working: running count, with +Nq overflow tail. Queued: bare queued+ // count. Idle: no counts at all — the label is the whole signal.+ const counts =+ workload === "working"+ ? queued > 0+ ? `${running} +${queued}q`+ : `${running}`+ : workload === "queued"+ ? `${queued}`+ : null;+ return (+ <span className="inline-flex items-center gap-1 text-xs">+ {/* Icon only for working/queued — see WorkloadCell in agent-columns. */}+ {workload !== "idle" && (+ <wl.icon+ className={`h-3 w-3 shrink-0 ${wl.textClass} ${workload === "working" ? "animate-spin" : ""}`}+ />+ )}+ <span className={`shrink-0 ${wl.textClass}`}>{wl.label}</span>+ {counts && (+ <span className="truncate font-mono tabular-nums text-muted-foreground">+ {counts}+ </span>+ )}+ </span>+ );+}++// Per-row cost — fetches the same 180-day usage window used by the+// runtime-detail page so clicking a row makes detail render instantly from+// cache. Cold load incurs N parallel requests, but each is cheap and they+// all share the same query key.+function CostCell({ runtimeId }: { runtimeId: string }) {+ const { data: usage = [] } = useQuery(runtimeUsageOptions(runtimeId, 180));+ const cost7d = useMemo(() => computeCostInWindow(usage, 7), [usage]);+ const costPrev7d = useMemo(+ () => computeCostInWindow(usage, 7, 7),+ [usage],+ );+ const delta = pctChange(cost7d, costPrev7d);++ if (usage.length === 0) {+ return (+ <div className="text-right">+ <span className="text-xs text-muted-foreground/50">—</span>+ </div>+ );+ }+ const fmt = cost7d >= 100 ? `$${cost7d.toFixed(0)}` : `$${cost7d.toFixed(2)}`;+ const deltaTone =+ delta == null+ ? "text-muted-foreground"+ : delta > 0+ ? "text-warning"+ : delta < 0+ ? "text-success"+ : "text-muted-foreground";+ const deltaLabel =+ delta == null+ ? null+ : delta === 0+ ? "flat"+ : `${delta > 0 ? "↑" : "↓"}${Math.abs(delta)}%`;+ return (+ <div className="flex flex-col items-end leading-tight">+ <span className="text-sm font-medium tabular-nums">{fmt}</span>+ {deltaLabel && (+ <span className={`text-[11px] tabular-nums ${deltaTone}`}>+ {deltaLabel}+ </span>+ )}+ </div>+ );+}++function CliCell({+ runtime,+ latestCliVersion,+}: {+ runtime: AgentRuntime;+ latestCliVersion: string | null;+}) {+ if (runtime.runtime_mode === "cloud") {+ return <span className="text-xs text-muted-foreground/50">—</span>;+ }+ const meta = runtime.metadata as Record<string, unknown> | null;+ const cliVersion =+ meta && typeof meta.cli_version === "string" ? meta.cli_version : null;+ const launchedBy =+ meta && typeof meta.launched_by === "string" ? meta.launched_by : null;+ const isManaged = launchedBy === "desktop";++ if (!cliVersion) {+ return <span className="text-xs text-muted-foreground/50">—</span>;+ }++ // Desktop-managed daemons can never self-update from this page (the+ // Electron app ships and replaces the binary), so the upgrade marker+ // would lie — suppress regardless of version comparison.+ const hasUpdate =+ !isManaged &&+ !!latestCliVersion &&+ isVersionNewer(latestCliVersion, cliVersion);++ return (+ <div className="flex min-w-0 items-center gap-1 text-xs">+ {isManaged && (+ <span className="shrink-0 rounded-sm bg-muted px-1 py-0.5 text-[10px] font-medium text-muted-foreground">+ Desktop+ </span>+ )}+ <span+ className={`truncate font-mono ${+ hasUpdate ? "text-warning" : "text-muted-foreground"+ }`}+ >+ {cliVersion}+ </span>+ {hasUpdate && latestCliVersion && (+ <Tooltip>+ <TooltipTrigger+ render={+ <ArrowUpCircle+ className="h-3 w-3 shrink-0 text-warning"+ aria-label="Update available"+ />+ }+ />+ <TooltipContent>+ Update available: {latestCliVersion}+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ );+}++// Stacks up to 3 agent avatars, then a "+N" pill if more bind to this+// runtime. Each avatar uses the wrapping ActorAvatar so hover automatically+// surfaces AgentProfileCard.+function AgentStack({ agentIds }: { agentIds: string[] }) {+ if (agentIds.length === 0) {+ return <span className="text-xs text-muted-foreground/50">—</span>;+ }+ const visible = agentIds.slice(0, 3);+ const extra = agentIds.length - visible.length;+ return (+ <div className="flex items-center -space-x-1.5">+ {visible.map((id) => (+ <span+ key={id}+ className="inline-flex rounded-full ring-2 ring-background"+ >+ <ActorAvatar+ actorType="agent"+ actorId={id}+ size={22}+ enableHoverCard+ />+ </span>+ ))}+ {extra > 0 && (+ <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground ring-2 ring-background">+ +{extra}+ </span>+ )}+ </div>+ );+}++function RowMenu({+ runtime,+ wsId,+ canDelete,+}: {+ runtime: AgentRuntime;+ wsId: string;+ canDelete: boolean;+}) {+ const deleteMutation = useDeleteRuntime(wsId);+ const [deleteOpen, setDeleteOpen] = useState(false);++ if (!canDelete) {+ return <span aria-hidden />;+ }++ const handleDelete = () => {+ deleteMutation.mutate(runtime.id, {+ onSuccess: () => {+ toast.success("Runtime deleted");+ setDeleteOpen(false);+ },+ onError: (e) => {+ toast.error(+ e instanceof Error ? e.message : "Failed to delete runtime",+ );+ },+ });+ };++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Row actions"+ onClick={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ />+ }+ >+ <MoreHorizontal className="h-4 w-4 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-40"+ onClick={(e) => e.stopPropagation()}+ >+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleteOpen(true)}+ >+ <Trash2 className="h-3.5 w-3.5" />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <AlertDialog+ open={deleteOpen}+ onOpenChange={(v) => {+ if (deleteMutation.isPending) return;+ setDeleteOpen(v);+ }}+ >+ <AlertDialogContent onClick={(e) => e.stopPropagation()}>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete Runtime</AlertDialogTitle>+ <AlertDialogDescription>+ Are you sure you want to delete “{runtime.name}”?+ This action cannot be undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={handleDelete}+ disabled={deleteMutation.isPending}+ >+ {deleteMutation.isPending ? "Deleting..." : "Delete"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsxindex 3cdee55734..faba56b6e4 100644--- a/packages/views/runtimes/components/runtime-detail.tsx+++ b/packages/views/runtimes/components/runtime-detail.tsx@@ -39,7 +39,7 @@ import {} from "@multica/ui/components/ui/tooltip";import { ActorAvatar } from "../../common/actor-avatar";import { AppLink } from "../../navigation";-import { availabilityConfig, taskStateConfig } from "../../agents/presence";+import { availabilityConfig, workloadConfig } from "../../agents/presence";import { formatLastSeen } from "../utils";import { HealthBadge } from "./shared";import { ProviderLogo } from "./provider-logo";@@ -206,6 +206,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {<ServingAgentsCardagents={servingAgents}presenceMap={presenceMap}+ agentHref={(id) => paths.agentDetail(id)}/><DiagnosticsCardruntime={runtime}@@ -401,9 +402,11 @@ function Fact({function ServingAgentsCard({agents,presenceMap,+ agentHref,}: {agents: Agent[];presenceMap: Map<string, AgentPresenceDetail>;+ agentHref: (agentId: string) => string;}) {return (<div className="rounded-lg border">@@ -427,17 +430,18 @@ function ServingAgentsCard({const av = detail? availabilityConfig[detail.availability]: availabilityConfig.offline;- const ts = detail ? taskStateConfig[detail.lastTask] : null;+ const wl = detail ? workloadConfig[detail.workload] : null;const running = detail?.runningCount ?? 0;const queued = detail?.queuedCount ?? 0;return (- <div+ <AppLinkkey={agent.id}- className="flex items-center gap-2 px-4 py-2"+ href={agentHref(agent.id)}+ className="group flex items-center gap-2 px-4 py-2 transition-colors hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none"><ActorAvatar actorType="agent" actorId={agent.id} size={20} enableHoverCard showStatusDot /><div className="min-w-0 flex-1">- <div className="cursor-pointer truncate text-xs font-medium">+ <div className="truncate text-xs font-medium">{agent.name}</div><div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs">@@ -445,11 +449,13 @@ function ServingAgentsCard({<span className={`h-1.5 w-1.5 rounded-full ${av.dotClass}`} /><span className={av.textClass}>{av.label}</span></span>- {ts && detail && detail.lastTask !== "idle" && (- <span className={`inline-flex items-center gap-1 ${ts.textClass}`}>+ {wl && detail && detail.workload !== "idle" && (+ <span className={`inline-flex items-center gap-1 ${wl.textClass}`}><span className="text-muted-foreground">·</span>- <ts.icon className="h-3 w-3" />- {ts.label}+ <wl.icon+ className={`h-3 w-3 ${detail.workload === "working" ? "animate-spin" : ""}`}+ />+ {wl.label}{running > 0 && (<span className="text-muted-foreground">· {running} running</span>)}@@ -460,7 +466,8 @@ function ServingAgentsCard({)}</div></div>- </div>+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-muted-foreground" />+ </AppLink>);})}</div>diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsxindex ee6237baca..51b5a043ef 100644--- a/packages/views/runtimes/components/runtime-list.tsx+++ b/packages/views/runtimes/components/runtime-list.tsx@@ -1,66 +1,26 @@"use client";-import { useMemo, useRef, useState } from "react";-import {- ArrowUpCircle,- MoreHorizontal,- Trash2,- Cloud,- Monitor,-} from "lucide-react";-import { toast } from "sonner";+import { useMemo } from "react";import { useQuery } from "@tanstack/react-query";-import type { AgentRuntime, AgentTask, Agent, MemberWithUser } from "@multica/core/types";+import { getCoreRowModel, useReactTable } from "@tanstack/react-table";+import type {+ Agent,+ AgentRuntime,+ AgentTask,+ MemberWithUser,+} from "@multica/core/types";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";-import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";import {- deriveRuntimeHealth,- runtimeUsageOptions,- latestCliVersionOptions,-} from "@multica/core/runtimes";-import { useDeleteRuntime } from "@multica/core/runtimes/mutations";+ agentListOptions,+ memberListOptions,+} from "@multica/core/workspace/queries";+import { latestCliVersionOptions } from "@multica/core/runtimes";import { agentTaskSnapshotOptions } from "@multica/core/agents";import { paths, useWorkspaceSlug } from "@multica/core/paths";-import { AppLink } from "../../navigation";-import { ActorAvatar } from "../../common/actor-avatar";-import { Button } from "@multica/ui/components/ui/button";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@multica/ui/components/ui/alert-dialog";-import {- DropdownMenu,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,-} from "@multica/ui/components/ui/dropdown-menu";-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from "@multica/ui/components/ui/tooltip";-import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";-import { HealthIcon, healthLabel } from "./shared";-import {- formatLastSeen,- computeCostInWindow,- pctChange,- isVersionNewer,-} from "../utils";--// ----------------------------------------------------------------------------// Per-runtime workload snapshot — agent IDs serving this runtime (drives the-// avatar stack; .length doubles as the agent count) plus task counts split-// by status. Built once per render off the workspace-wide-// agents / agent-task-snapshot caches; filtered locally — zero extra requests.-// ---------------------------------------------------------------------------+import { DataTable } from "@multica/ui/components/ui/data-table";+import { useNavigation } from "../../navigation";+import { type RuntimeRow, createRuntimeColumns } from "./runtime-columns";interface RuntimeWorkload {agentIds: string[];@@ -74,6 +34,10 @@ const EMPTY_WORKLOAD: RuntimeWorkload = {queuedCount: 0,};+// Per-runtime workload snapshot — agent IDs serving this runtime (drives+// the avatar stack; .length doubles as the agent count) plus task counts+// split by status. Built once per render off the workspace-wide+// agents / agent-task-snapshot caches; filtered locally — no extra requests.function buildWorkloadIndex(agents: Agent[],tasks: AgentTask[],@@ -105,89 +69,43 @@ function buildWorkloadIndex(return result;}-// ----------------------------------------------------------------------------// Grid template. Two variants because the Owner column only earns its keep-// in workspaces with multiple runtime owners — single-owner workspaces just-// see an entire column of identical avatars, which is noise. We pick at-// list-mount time and pass the chosen template down so the header and every-// row stay byte-identically aligned.-//-// Leading-visual columns are dedicated tracks so header labels sit on the-// same x as the row text, with no per-cell padding hacks. Same pattern as-// Agents (avatar) and Skills (source icon).-//-// Width choices (left → right):-// IconBox: 2rem — 32px Cloud / Monitor mode badge-// Runtime: minmax(0,1fr) — primary, fills remainder, truncates first-// HealthIcon: 0.875rem — 12px wifi-style icon-// Health: minmax(0,1fr) — text label, can shrink + truncate at-// narrow widths so it never overlaps the-// Runtime column. ("Recently lost · 2m-// 14s ago" is the worst case; the long-// suffix truncates first.)-// Owner: 2rem — single 18px avatar (multi-owner only)-// Agents: 6rem — 3 avatars overlapped + "+N" pill-// Active: 5rem — "2 +5q" worst case, right-aligned-// Cost: 7rem — "$879.00" + "↑18%" stacked, right-aligned-// CLI: 8rem — "Desktop · v0.2.17" worst case-// Kebab: 2.5rem — icon button-//-// Switched Health from a fixed 9.5rem to minmax(0,1fr) so it competes-// fairly with Runtime under width pressure. The previous fixed-width-// reservation guaranteed the worst-case copy fit, but at intermediate-// viewports the Runtime column was squeezed below its content width and-// overflowed visually.-// -----------------------------------------------------------------------------const GRID_WITH_OWNER =- "grid items-center gap-4 " +- "grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_2rem_2.5rem] " +- "md:grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_2rem_6rem_5rem_7rem_2.5rem] " +- "lg:grid-cols-[2rem_minmax(0,1.2fr)_0.875rem_minmax(0,1fr)_2rem_6rem_5rem_7rem_8rem_2.5rem]";--const GRID_NO_OWNER =- "grid items-center gap-4 " +- "grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_2.5rem] " +- "md:grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_6rem_5rem_7rem_2.5rem] " +- "lg:grid-cols-[2rem_minmax(0,1.2fr)_0.875rem_minmax(0,1fr)_6rem_5rem_7rem_8rem_2.5rem]";-export function RuntimeList({runtimes,updatableIds,now,}: {runtimes: AgentRuntime[];- // Kept on the API surface for callers (currently a noop here — the CLI- // column re-derives from `metadata.cli_version` + the GitHub-release query- // so per-row state is co-located. Removing it would break the page-level- // wrapper that still computes the set; left in place to avoid scope creep.)+ // Kept on the API surface for callers — the CLI column re-derives+ // update state per row via metadata.cli_version + the GitHub-release+ // query, so this prop is now unused. Left to avoid scope creep on the+ // page-level wrapper that still computes the set.updatableIds?: Set<string>;now: number;}) {- // Kept to avoid an unused-prop lint; the data path is now per-row.void updatableIds;const wsId = useWorkspaceId();const slug = useWorkspaceSlug();+ const navigation = useNavigation();const user = useAuthStore((s) => s.user);+const { data: agents = [] } = useQuery(agentListOptions(wsId));const { data: members = [] } = useQuery(memberListOptions(wsId));+ const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));+ const { data: latestCliVersion = null } = useQuery(latestCliVersionOptions());+const currentMember = user? members.find((m) => m.user_id === user.id): null;const isAdmin = currentMember? currentMember.role === "owner" || currentMember.role === "admin": false;- // Snapshot also includes each agent's latest terminal task; the workload- // index iterates by status and only counts active ones, so terminal rows- // are silently ignored.- const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));- const { data: latestCliVersion = null } = useQuery(latestCliVersionOptions());const workloadIndex = useMemo(() => buildWorkloadIndex(agents, snapshot),[agents, snapshot],);+const memberById = useMemo(() => {const map = new Map<string, MemberWithUser>();for (const m of members) map.set(m.user_id, m);@@ -195,7 +113,8 @@ export function RuntimeList({}, [members]);// Owner column only earns its space when the page actually has multiple- // distinct owners; otherwise it's a column of identical avatars.+ // distinct owners — otherwise it would just be a column of identical+ // avatars.const showOwner = useMemo(() => {const owners = new Set<string>();for (const r of runtimes) {@@ -204,469 +123,46 @@ export function RuntimeList({return owners.size > 1;}, [runtimes]);- const gridClass = showOwner ? GRID_WITH_OWNER : GRID_NO_OWNER;-- const scrollRef = useRef<HTMLDivElement | null>(null);- const fadeStyle = useScrollFade(scrollRef);-- return (- <div- ref={scrollRef}- style={fadeStyle}- className="flex-1 min-h-0 overflow-y-auto"- >- <div- role="row"- className={`${gridClass} sticky top-0 z-10 border-b bg-muted/30 px-4 py-2 text-xs font-medium uppercase tracking-wider text-muted-foreground backdrop-blur`}- >- {/* Icon-box leading slot — empty in header so "Runtime" aligns with- the row's name text rather than the mode-badge edge. */}- <span aria-hidden />- <span>Runtime</span>- {/* Health-dot leading slot — empty in header so "Health" aligns- with the row's status text rather than the dot edge. */}- <span aria-hidden />- <span>Health</span>- {showOwner && <span className="hidden md:block">Owner</span>}- <span className="hidden md:block">Agents</span>- <span className="hidden text-right md:block">Active</span>- <span className="hidden text-right md:block">Cost · 7d</span>- <span className="hidden lg:block">CLI</span>- <span aria-label="Actions" />- </div>- {runtimes.map((runtime) => (- <RuntimeRow- key={runtime.id}- runtime={runtime}- now={now}- gridClass={gridClass}- showOwner={showOwner}- workload={workloadIndex.get(runtime.id) ?? EMPTY_WORKLOAD}- ownerMember={- runtime.owner_id ? memberById.get(runtime.owner_id) ?? null : null- }- latestCliVersion={latestCliVersion}- href={slug ? paths.workspace(slug).runtimeDetail(runtime.id) : "#"}- wsId={wsId}- canDelete={- isAdmin || (!!user && runtime.owner_id === user.id)- }- />- ))}- </div>+ const rows = useMemo<RuntimeRow[]>(() => {+ return runtimes.map((runtime) => ({+ runtime,+ ownerMember: runtime.owner_id+ ? memberById.get(runtime.owner_id) ?? null+ : null,+ workload: workloadIndex.get(runtime.id) ?? EMPTY_WORKLOAD,+ canDelete: isAdmin || (!!user && runtime.owner_id === user.id),+ }));+ }, [runtimes, memberById, workloadIndex, isAdmin, user]);++ const columns = useMemo(+ () =>+ createRuntimeColumns({+ showOwner,+ latestCliVersion,+ wsId,+ now,+ }),+ [showOwner, latestCliVersion, wsId, now],);-}-// ----------------------------------------------------------------------------// Backend formats `runtime.name` as `"<base> (<hostname>)"` (e.g.-// "Claude (qingnaiyuandebijibendiannao-8.local)"). Every runtime on the same-// machine repeats the same hostname suffix, so it carries near-zero scan-// value once the eye has seen it on the first row — yet it dominates the-// column width by character count. Split it so the base name stays-// emphasised and the hostname renders muted + truncates first when the cell-// is tight. Falls back to the raw name when the format doesn't match.-// -----------------------------------------------------------------------------function splitRuntimeName(name: string): {- base: string;- hostname: string | null;-} {- const m = name.match(/^(.+?)\s+\(([^)]+)\)$/);- if (!m || !m[1] || !m[2]) return { base: name, hostname: null };- return { base: m[1], hostname: m[2] };-}--function RuntimeRow({- runtime,- now,- gridClass,- showOwner,- workload,- ownerMember,- latestCliVersion,- href,- wsId,- canDelete,-}: {- runtime: AgentRuntime;- now: number;- gridClass: string;- showOwner: boolean;- workload: RuntimeWorkload;- ownerMember: MemberWithUser | null;- latestCliVersion: string | null;- href: string;- wsId: string;- canDelete: boolean;-}) {- const health = deriveRuntimeHealth(runtime, now);- const lastSeen = formatLastSeen(runtime.last_seen_at);- const { base: baseName, hostname } = splitRuntimeName(runtime.name);- const isOffline = health === "offline" || health === "about_to_gc";-- // Per-row cost fetch reuses the SAME cache key as the runtime-detail page- // (`runtimeUsageOptions(rid, 180)`). On cold load that's N parallel- // requests, but every one of them populates the same cache the detail- // page reads — so clicking a row to drill in is instant.- const { data: usage = [] } = useQuery(runtimeUsageOptions(runtime.id, 180));-- const cost7d = useMemo(() => computeCostInWindow(usage, 7), [usage]);- const costPrev7d = useMemo(() => computeCostInWindow(usage, 7, 7), [usage]);- const costDelta = pctChange(cost7d, costPrev7d);+ const table = useReactTable({+ data: rows,+ columns,+ getCoreRowModel: getCoreRowModel(),+ // Pin the kebab column right so it stays accessible during horizontal+ // scroll — matches the pattern in Linear / Notion / GitHub.+ initialState: { columnPinning: { right: ["actions"] } },+ });return (- <AppLink- href={href}- className={`${gridClass} group border-b px-4 py-3 text-sm transition-colors last:border-b-0 hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none`}- >- {/* MODE BADGE — leading column so the "Runtime" header aligns with the- name text rather than the badge edge. */}- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-card">- {runtime.runtime_mode === "cloud" ? (- <Cloud className="h-4 w-4 text-muted-foreground" />- ) : (- <Monitor className="h-4 w-4 text-muted-foreground" />- )}- </div>-- {/* RUNTIME — base name + (hostname). Both can truncate at narrow- widths so the cell never overflows into the adjacent Health- column. The base name takes precedence (truncate later) by- virtue of being the first child; the hostname (more disposable)- shrinks first. Provider lives in the right-side CLI column. */}- <div className="flex min-w-0 items-center gap-1.5">- <span className="min-w-0 truncate text-sm font-medium">{baseName}</span>- {hostname && (- <span className="min-w-0 truncate text-xs text-muted-foreground/70">- ({hostname})- </span>- )}- </div>-- {/* HEALTH icon — wifi-style indicator carries both shape (Wifi / WifiOff)- and colour (success / warning / muted / destructive) for the four- health buckets. Leading column for the same alignment reason as- the icon-box on the left. */}- <HealthIcon health={health} />-- {/* HEALTH label — last_seen folded in only when it carries information- (everything except the always-"Just now" online case). */}- <span className="min-w-0 truncate text-sm">- {healthLabel(health)}- {health !== "online" && runtime.last_seen_at && (- <span className="text-muted-foreground"> · {lastSeen}</span>- )}- </span>-- {/* OWNER — small avatar only; name lives in the hover card. Conditional- on the workspace having more than one distinct owner. */}- {showOwner && (- <div className="hidden md:flex">- {ownerMember ? (- <ActorAvatar- actorType="member"- actorId={ownerMember.user_id}- size={18}- />- ) : (- <span className="text-xs text-muted-foreground/50">—</span>- )}- </div>- )}-- {/* AGENTS — avatar stack (3 + "+N"). */}- <div className="hidden md:block">- <AgentStack agentIds={workload.agentIds} />- </div>-- {/* ACTIVE — running count is the headline (brand colour) when active;- queued count piggy-backs as a smaller "+Nq" suffix when non-zero.- Offline runtimes show "—" instead of "0" because zero on an offline- row is a tautology, not information. */}- <div className="hidden text-right md:block">- <ActiveCell- running={workload.runningCount}- queued={workload.queuedCount}- offline={isOffline}- />- </div>-- {/* COST · 7D — main number + trend delta stacked. The 7d window is- fixed (vs the period selector on the detail page) so the column- stays comparable across rows. */}- <div className="hidden text-right md:block">- <CostCell cost={cost7d} delta={costDelta} hasData={usage.length > 0} />- </div>-- {/* CLI — source badge + version + ↑ marker if behind. Pure status,- no clickable upgrade button — the actual upgrade lives on the- detail page where polling/error state has room to breathe. */}- <div className="hidden lg:block">- <CliCell runtime={runtime} latestCliVersion={latestCliVersion} />- </div>-- {/* ⋯ menu */}- <div className="flex justify-end">- <RowMenu runtime={runtime} wsId={wsId} canDelete={canDelete} />- </div>- </AppLink>- );-}--function ActiveCell({- running,- queued,- offline,-}: {- running: number;- queued: number;- offline: boolean;-}) {- if (offline) {- return <span className="text-xs text-muted-foreground/50">—</span>;- }- if (running === 0 && queued === 0) {- return <span className="text-sm text-muted-foreground">0</span>;- }- return (- <div className="flex items-center justify-end gap-1.5 text-sm tabular-nums">- {running > 0 ? (- <>- <span className="h-1.5 w-1.5 rounded-full bg-brand" />- <span className="text-brand">{running}</span>- </>- ) : (- <span className="text-muted-foreground">0</span>- )}- {queued > 0 && (- <span className="text-xs text-warning">+{queued}q</span>- )}- </div>- );-}--function CostCell({- cost,- delta,- hasData,-}: {- cost: number;- delta: number | null;- hasData: boolean;-}) {- if (!hasData) {- return <span className="text-xs text-muted-foreground/50">—</span>;- }- const fmt = cost >= 100 ? `$${cost.toFixed(0)}` : `$${cost.toFixed(2)}`;- // Tone choice: rising cost is a "watch out" signal (warning), falling is- // good news (success), no comparable prior is silent.- const deltaTone =- delta == null- ? "text-muted-foreground"- : delta > 0- ? "text-warning"- : delta < 0- ? "text-success"- : "text-muted-foreground";- const deltaLabel =- delta == null- ? null- : delta === 0- ? "flat"- : `${delta > 0 ? "↑" : "↓"}${Math.abs(delta)}%`;- return (- <div className="flex flex-col items-end leading-tight">- <span className="text-sm font-medium tabular-nums">{fmt}</span>- {deltaLabel && (- <span className={`text-[11px] tabular-nums ${deltaTone}`}>- {deltaLabel}- </span>- )}- </div>- );-}--function CliCell({- runtime,- latestCliVersion,-}: {- runtime: AgentRuntime;- latestCliVersion: string | null;-}) {- if (runtime.runtime_mode === "cloud") {- return <span className="text-xs text-muted-foreground/50">—</span>;- }- const meta = runtime.metadata as Record<string, unknown> | null;- const cliVersion =- meta && typeof meta.cli_version === "string" ? meta.cli_version : null;- const launchedBy =- meta && typeof meta.launched_by === "string" ? meta.launched_by : null;- const isManaged = launchedBy === "desktop";-- if (!cliVersion) {- return <span className="text-xs text-muted-foreground/50">—</span>;- }-- // Desktop-managed daemons can never self-update from this page (the- // Electron app ships and replaces the binary), so the "↑" upgrade marker- // would be a lie — suppress it regardless of version comparison.- const hasUpdate =- !isManaged &&- !!latestCliVersion &&- isVersionNewer(latestCliVersion, cliVersion);-- return (- <div className="flex min-w-0 items-center gap-1 text-xs">- {isManaged && (- <span className="shrink-0 rounded-sm bg-muted px-1 py-0.5 text-[10px] font-medium text-muted-foreground">- Desktop- </span>- )}- <span- className={`min-w-0 truncate font-mono ${- hasUpdate ? "text-warning" : "text-muted-foreground"- }`}- >- {cliVersion}- </span>- {hasUpdate && latestCliVersion && (- <Tooltip>- <TooltipTrigger- render={- <ArrowUpCircle- className="h-3 w-3 shrink-0 text-warning"- aria-label="Update available"- />- }- />- <TooltipContent>- Update available: {latestCliVersion}- </TooltipContent>- </Tooltip>- )}- </div>- );-}--// Stacks up to 3 agent avatars, then a "+N" pill if more bind to this-// runtime. Each avatar uses the wrapping ActorAvatar so hover automatically-// surfaces AgentProfileCard — same hover affordance Agents/Skills already-// use, no per-row extra wiring.-function AgentStack({ agentIds }: { agentIds: string[] }) {- if (agentIds.length === 0) {- return <span className="text-xs text-muted-foreground/50">—</span>;- }- const visible = agentIds.slice(0, 3);- const extra = agentIds.length - visible.length;- return (- <div className="flex items-center -space-x-1.5">- {visible.map((id) => (- <span- key={id}- className="inline-flex rounded-full ring-2 ring-background"- >- <ActorAvatar actorType="agent" actorId={id} size={22} enableHoverCard />- </span>- ))}- {extra > 0 && (- <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground ring-2 ring-background">- +{extra}- </span>- )}- </div>- );-}--function RowMenu({- runtime,- wsId,- canDelete,-}: {- runtime: AgentRuntime;- wsId: string;- canDelete: boolean;-}) {- const deleteMutation = useDeleteRuntime(wsId);- const [deleteOpen, setDeleteOpen] = useState(false);-- if (!canDelete) {- // Keep the grid cell occupied so column alignment doesn't shift between- // rows the user can act on and rows they can't.- return <span aria-hidden />;- }-- const handleDelete = () => {- deleteMutation.mutate(runtime.id, {- onSuccess: () => {- toast.success("Runtime deleted");- setDeleteOpen(false);- },- onError: (e) => {- toast.error(- e instanceof Error ? e.message : "Failed to delete runtime",+ <DataTable+ table={table}+ onRowClick={(row) => {+ if (!slug) return;+ navigation.push(+ paths.workspace(slug).runtimeDetail(row.original.runtime.id),);- },- });- };-- return (- <>- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="ghost"- size="icon-sm"- aria-label="Row actions"- onClick={(e) => e.stopPropagation()}- onKeyDown={(e) => e.stopPropagation()}- />- }- >- <MoreHorizontal className="h-4 w-4 text-muted-foreground" />- </DropdownMenuTrigger>- <DropdownMenuContent- align="end"- className="w-40"- // Prevent the row's anchor navigation from firing if a click on a- // menu item somehow bubbles back through the portal.- onClick={(e) => e.stopPropagation()}- >- <DropdownMenuItem- variant="destructive"- onClick={() => setDeleteOpen(true)}- >- <Trash2 className="h-3.5 w-3.5" />- Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- <AlertDialog- open={deleteOpen}- onOpenChange={(v) => {- if (deleteMutation.isPending) return;- setDeleteOpen(v);- }}- >- <AlertDialogContent onClick={(e) => e.stopPropagation()}>- <AlertDialogHeader>- <AlertDialogTitle>Delete Runtime</AlertDialogTitle>- <AlertDialogDescription>- Are you sure you want to delete “{runtime.name}”? This action cannot be undone.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- variant="destructive"- onClick={handleDelete}- disabled={deleteMutation.isPending}- >- {deleteMutation.isPending ? "Deleting..." : "Delete"}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- </>+ }}+ />);}diff --git a/packages/views/skills/components/skill-columns.tsx b/packages/views/skills/components/skill-columns.tsxnew file mode 100644index 0000000000..3a2579c0e2--- /dev/null+++ b/packages/views/skills/components/skill-columns.tsx@@ -0,0 +1,239 @@+"use client";++import {+ ChevronRight,+ Download,+ FileText,+ HardDrive,+ Lock,+ Pencil,+} from "lucide-react";+import type { ColumnDef } from "@tanstack/react-table";+import type {+ Agent,+ AgentRuntime,+ MemberWithUser,+ Skill,+} from "@multica/core/types";+import { timeAgo } from "@multica/core/utils";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { readOrigin, totalFileCount } from "../lib/origin";++// Per-row data assembled at the page level. The columns reach into+// `row.original` and never pull their own queries.+export interface SkillRow {+ skill: Skill;+ agents: Agent[];+ creator: MemberWithUser | null;+ // Originating runtime when the skill was imported from a runtime-local+ // store; null for manually-created or remotely-sourced skills.+ runtime: AgentRuntime | null;+ canEdit: boolean;+}++// Column widths in px. Both Name and Source carry `meta.grow: true`,+// so DataTable skips their inline widths and fixed table-layout splits+// the leftover space between them equally — a single grow column would+// dump all the slack into the Name column, leaving Source perpetually+// truncated while Name accumulates wasteful right-side whitespace.+//+// Each column's `size` is its floor: the values still flow into+// table.getTotalSize() and become the table's min-width, so when the+// viewport drops below the sum, the container scrolls horizontally+// instead of letting either column shrink past its floor.+const COL_WIDTHS = {+ name: 240,+ usedBy: 140,+ source: 220,+ updated: 100,+ // 48 = 16 left padding + 16 chevron icon + 16 right padding. Keeps+ // the chevron's right edge 16px from the card so it lines up with+ // the toolbar's px-4 right inset.+ chevron: 48,+} as const;++export function createSkillColumns(): ColumnDef<SkillRow>[] {+ return [+ {+ id: "name",+ header: "Name",+ size: COL_WIDTHS.name,+ meta: { grow: true },+ cell: ({ row }) => <SkillNameCell row={row.original} />,+ },+ {+ id: "usedBy",+ header: "Used by",+ size: COL_WIDTHS.usedBy,+ cell: ({ row }) => <AgentAssignees agents={row.original.agents} />,+ },+ {+ id: "source",+ header: "Source · Added by",+ size: COL_WIDTHS.source,+ meta: { grow: true },+ cell: ({ row }) => (+ <SourceCell+ skill={row.original.skill}+ creator={row.original.creator}+ runtime={row.original.runtime}+ />+ ),+ },+ {+ id: "updated",+ header: "Updated",+ size: COL_WIDTHS.updated,+ cell: ({ row }) => (+ <span className="whitespace-nowrap text-xs text-muted-foreground">+ {timeAgo(row.original.skill.updated_at)}+ </span>+ ),+ },+ {+ // Trailing chevron — purely a "this row is clickable" affordance,+ // matches the convention from the pre-data-table SkillRow. The+ // colour deepens on row hover via the row's `group` class.+ id: "_chevron",+ header: () => null,+ size: COL_WIDTHS.chevron,+ cell: () => (+ <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-muted-foreground" />+ ),+ },+ ];+}++// ---------------------------------------------------------------------------+// Cell renderers+// ---------------------------------------------------------------------------++function SkillNameCell({ row }: { row: SkillRow }) {+ const { skill, canEdit } = row;+ return (+ <div className="min-w-0">+ <div className="flex min-w-0 items-center gap-2">+ <span className="block min-w-0 truncate font-medium">{skill.name}</span>+ {!canEdit && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Lock className="h-3 w-3 shrink-0 text-muted-foreground/60" />+ }+ />+ <TooltipContent>+ Read-only — only creator or admin can edit+ </TooltipContent>+ </Tooltip>+ )}+ <span className="inline-flex shrink-0 items-center gap-0.5 font-mono text-xs text-muted-foreground/70">+ <FileText className="h-3 w-3" />+ {totalFileCount(skill)}+ </span>+ </div>+ {/* `max-w-xl` (36rem) caps how wide the description gets on+ large viewports. The Name column is `meta.grow`, so on a+ 24" desktop it can balloon past 800px — without this cap,+ a long single-line description would stretch all the way+ across, reading more like a paragraph than a table cell. */}+ <div+ className={`mt-0.5 max-w-xl truncate text-xs ${+ skill.description+ ? "text-muted-foreground"+ : "italic text-muted-foreground/50"+ }`}+ >+ {skill.description || "No description"}+ </div>+ </div>+ );+}++function AgentAssignees({ agents }: { agents: Agent[] }) {+ if (agents.length === 0) {+ return <span className="text-xs text-muted-foreground/70">— unused</span>;+ }+ const visible = agents.slice(0, 3);+ const extra = agents.length - visible.length;+ return (+ <div className="flex items-center -space-x-1.5">+ {visible.map((a) => (+ <Tooltip key={a.id}>+ <TooltipTrigger+ render={+ <span className="inline-flex rounded-full ring-2 ring-background">+ <ActorAvatar+ name={a.name}+ initials={a.name.slice(0, 2).toUpperCase()}+ avatarUrl={a.avatar_url}+ isAgent+ size={22}+ />+ </span>+ }+ />+ <TooltipContent>{a.name}</TooltipContent>+ </Tooltip>+ ))}+ {extra > 0 && (+ <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground ring-2 ring-background">+ +{extra}+ </span>+ )}+ </div>+ );+}++function SourceCell({+ skill,+ creator,+ runtime,+}: {+ skill: Skill;+ creator: MemberWithUser | null;+ runtime: AgentRuntime | null;+}) {+ const origin = readOrigin(skill);++ let icon = <Pencil className="h-3 w-3 shrink-0" />;+ let label = "Created manually";+ if (origin.type === "runtime_local") {+ icon = <HardDrive className="h-3 w-3 shrink-0" />;+ label = runtime+ ? `From ${runtime.name}`+ : origin.provider+ ? `From ${origin.provider} runtime`+ : "From a runtime";+ } else if (origin.type === "clawhub") {+ icon = <Download className="h-3 w-3 shrink-0" />;+ label = "From ClawHub";+ } else if (origin.type === "skills_sh") {+ icon = <Download className="h-3 w-3 shrink-0" />;+ label = "From Skills.sh";+ }++ return (+ <div className="min-w-0">+ <div className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">+ <span className="shrink-0">{icon}</span>+ <span className="block min-w-0 truncate">{label}</span>+ </div>+ {creator && (+ <div className="mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">+ <ActorAvatar+ name={creator.name}+ initials={creator.name.slice(0, 2).toUpperCase()}+ avatarUrl={creator.avatar_url}+ size={14}+ />+ <span className="truncate">by {creator.name}</span>+ </div>+ )}+ </div>+ );+}diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsxindex cf8d86f3ce..cac95dc976 100644--- a/packages/views/skills/components/skills-page.tsx+++ b/packages/views/skills/components/skills-page.tsx@@ -1,27 +1,20 @@"use client";-import { useMemo, useRef, useState } from "react";+import { useMemo, useState } from "react";import {AlertCircle,AlertTriangle,BookOpen,- ChevronRight,- Download,- FileText,- HardDrive,- Lock,- Pencil,Plus,Search,} from "lucide-react";import type {- Agent,AgentRuntime,MemberWithUser,Skill,} from "@multica/core/types";import { useQuery } from "@tanstack/react-query";-import { timeAgo } from "@multica/core/utils";+import { getCoreRowModel, useReactTable } from "@tanstack/react-table";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";@@ -32,8 +25,8 @@ import {skillListOptions,} from "@multica/core/workspace/queries";import { runtimeListOptions } from "@multica/core/runtimes";-import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";import { Button } from "@multica/ui/components/ui/button";+import { DataTable } from "@multica/ui/components/ui/data-table";import { Input } from "@multica/ui/components/ui/input";import { Skeleton } from "@multica/ui/components/ui/skeleton";import {@@ -41,219 +34,15 @@ import {TooltipContent,TooltipTrigger,} from "@multica/ui/components/ui/tooltip";-import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";-import { AppLink, useNavigation } from "../../navigation";+import { useNavigation } from "../../navigation";import { PageHeader } from "../../layout/page-header";import { canEditSkill } from "../hooks/use-can-edit-skill";-import { readOrigin, totalFileCount } from "../lib/origin";+import { readOrigin } from "../lib/origin";import { CreateSkillDialog } from "./create-skill-dialog";+import { type SkillRow, createSkillColumns } from "./skill-columns";type FilterKey = "all" | "used" | "unused" | "mine";-// ----------------------------------------------------------------------------// Source cell — "Source · Added by" column (order matches column header).-// -----------------------------------------------------------------------------function SourceCell({- skill,- creator,- runtime,-}: {- skill: Skill;- creator: MemberWithUser | null;- runtime: AgentRuntime | null;-}) {- const origin = readOrigin(skill);-- let icon = <Pencil className="h-3 w-3 shrink-0" />;- let label = "Created manually";- if (origin.type === "runtime_local") {- icon = <HardDrive className="h-3 w-3 shrink-0" />;- label = runtime- ? `From ${runtime.name}`- : origin.provider- ? `From ${origin.provider} runtime`- : "From a runtime";- } else if (origin.type === "clawhub") {- icon = <Download className="h-3 w-3 shrink-0" />;- label = "From ClawHub";- } else if (origin.type === "skills_sh") {- icon = <Download className="h-3 w-3 shrink-0" />;- label = "From Skills.sh";- }-- // Two grid cells: leading icon track, then the text block. The icon needs- // `self-start` + a 1-line top inset so it lands on the top text row instead- // of the cell's vertical middle (the cell is 2-line when `creator` exists).- return (- <>- <span className="self-start pt-[3px] text-muted-foreground">{icon}</span>- <div className="min-w-0">- <div className="min-w-0 truncate text-xs text-muted-foreground">- {label}- </div>- {creator && (- <div className="mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">- <ActorAvatar- name={creator.name}- initials={creator.name.slice(0, 2).toUpperCase()}- avatarUrl={creator.avatar_url}- size={14}- />- <span className="min-w-0 truncate">by {creator.name}</span>- </div>- )}- </div>- </>- );-}--// ----------------------------------------------------------------------------// Agent avatar stack-// -----------------------------------------------------------------------------function AgentAssignees({ agents }: { agents: Agent[] }) {- if (agents.length === 0) {- return <span className="text-xs text-muted-foreground/70">— unused</span>;- }- const visible = agents.slice(0, 3);- const extra = agents.length - visible.length;- return (- <div className="flex items-center -space-x-1.5">- {visible.map((a) => (- <Tooltip key={a.id}>- <TooltipTrigger- render={- <span className="inline-flex rounded-full ring-2 ring-background">- <ActorAvatar- name={a.name}- initials={a.name.slice(0, 2).toUpperCase()}- avatarUrl={a.avatar_url}- isAgent- size={22}- />- </span>- }- />- <TooltipContent>{a.name}</TooltipContent>- </Tooltip>- ))}- {extra > 0 && (- <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground ring-2 ring-background">- +{extra}- </span>- )}- </div>- );-}--// ----------------------------------------------------------------------------// Row + header-// -----------------------------------------------------------------------------// Source column has a leading 12px icon (HardDrive / Download / Pencil) that-// would otherwise push its text 18px right of the column header, so we extract-// the icon into its own 0.875rem track. `<SourceCell>` returns two cells (icon-// + body) and the header inserts a placeholder cell to match.-//-// Same pattern as Agents (avatar) and Runtimes (icon-box, Health dot) — header-// label and row primary text share the same x without per-column padding hacks.-// Responsive column strategy:-// <md → Name + Used by + Chevron (drop Source / Updated to free room)-// md+ → adds Source · Added by + Updated-// Source icon leading slot (0.875rem) is part of the Source group, hidden-// together at <md. Each visible column uses minmax(0,…fr) so it can shrink-// and the cell content (with min-w-0 + truncate) trims gracefully instead-// of overflowing into adjacent cells.-const ROW_GRID =- "grid items-center gap-4 " +- "grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_auto] " +- "md:grid-cols-[minmax(0,1.6fr)_minmax(0,0.8fr)_0.875rem_minmax(0,1.2fr)_minmax(0,6rem)_auto]";--function SkillRow({- skill,- agents,- creator,- runtime,- canEdit,- href,-}: {- skill: Skill;- agents: Agent[];- creator: MemberWithUser | null;- runtime: AgentRuntime | null;- canEdit: boolean;- href: string;-}) {- return (- <AppLink- href={href}- className={`group ${ROW_GRID} border-b px-4 py-3 text-sm transition-colors hover:bg-accent/60`}- >- <div className="min-w-0">- <div className="flex items-center gap-2">- <span className="truncate font-medium">{skill.name}</span>- {!canEdit && (- <Tooltip>- <TooltipTrigger- render={- <Lock className="h-3 w-3 shrink-0 text-muted-foreground/60" />- }- />- <TooltipContent>- Read-only — only creator or admin can edit- </TooltipContent>- </Tooltip>- )}- <span className="inline-flex shrink-0 items-center gap-0.5 font-mono text-xs text-muted-foreground/70">- <FileText className="h-3 w-3" />- {totalFileCount(skill)}- </span>- </div>- <div- className={`mt-0.5 line-clamp-1 text-xs ${- skill.description- ? "text-muted-foreground"- : "italic text-muted-foreground/50"- }`}- >- {skill.description || "No description"}- </div>- </div>- <div className="min-w-0">- <AgentAssignees agents={agents} />- </div>- {/* Source group (icon + label) — md+. The icon is its own grid cell- for header alignment; both hide together at <md. */}- <span className="hidden md:contents">- <SourceCell skill={skill} creator={creator} runtime={runtime} />- </span>- <div className="hidden min-w-0 whitespace-nowrap text-xs text-muted-foreground md:block">- {timeAgo(skill.updated_at)}- </div>- <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-muted-foreground" />- </AppLink>- );-}--function ListColumnHeader() {- return (- <div- className={`${ROW_GRID} shrink-0 border-b bg-muted/30 px-4 py-2 text-xs font-medium uppercase tracking-wider text-muted-foreground`}- >- <span>Name</span>- <span>Used by</span>- {/* Source icon leading slot — empty in header so the label below- aligns with the row's "From X" / "Created manually" text.- Hidden together with the Source label at <md. */}- <span aria-hidden className="hidden md:block" />- <span className="hidden md:block">Source · Added by</span>- <span className="hidden md:block">Updated</span>- <span className="w-4" />- </div>- );-}-// ---------------------------------------------------------------------------// Scope tab — matches Issues/MyIssues header pattern// ---------------------------------------------------------------------------@@ -415,9 +204,6 @@ export default function SkillsPage() {const [filter, setFilter] = useState<FilterKey>("all");const [createOpen, setCreateOpen] = useState(false);- const scrollRef = useRef<HTMLDivElement>(null);- const fadeStyle = useScrollFade(scrollRef);-// Derive assignments ONCE per agents-identity. Stable reference across// unrelated agent refetches — see selectSkillAssignments' doc.const assignments = useMemo(@@ -464,6 +250,46 @@ export default function SkillsPage() {navigation.push(paths.skillDetail(skill.id));};+ // Assemble per-row data once per render — skill + agents + creator ++ // origin-runtime + permission flag. The table's column cells read off+ // `row.original` and never pull their own queries.+ const skillRows = useMemo<SkillRow[]>(() => {+ return filtered.map((skill) => {+ const origin = readOrigin(skill);+ const runtime =+ origin.type === "runtime_local" && origin.runtime_id+ ? runtimesById.get(origin.runtime_id) ?? null+ : null;+ return {+ skill,+ agents: assignments.get(skill.id) ?? [],+ creator: skill.created_by+ ? membersById.get(skill.created_by) ?? null+ : null,+ runtime,+ canEdit: canEditSkill(skill, {+ userId: currentUserId,+ role: myRole,+ }),+ };+ });+ }, [+ filtered,+ assignments,+ membersById,+ runtimesById,+ currentUserId,+ myRole,+ ]);++ const columns = useMemo(() => createSkillColumns(), []);++ const table = useReactTable({+ data: skillRows,+ columns,+ getCoreRowModel: getCoreRowModel(),+ });+// --- Loading ---if (isLoading) {return (@@ -547,10 +373,25 @@ export default function SkillsPage() {</div>)}- {/* Page body — padding here keeps the card from touching the chrome.- The "what is a skill" tagline now lives in the page header (right- of the title); body starts directly with the table card. */}+ {/* Page body — padding here keeps the card from touching the chrome,+ and `gap-4` separates the intro banner from the table card. */}<div className="flex flex-1 min-h-0 flex-col gap-4 p-6">+ {!showEmpty && (+ // Brand-coloured intro banner — explains the sharing model+ // for skills (workspace-wide vs. local runtime). Pre-#1794+ // this lived in the body; #1794 dropped it without a clear+ // reason. Restored intentionally.+ <div className="max-w-3xl rounded-r-md border-l-2 border-l-brand bg-brand/5 px-4 py-3 text-xs leading-relaxed text-muted-foreground">+ <span className="font-medium text-foreground">+ Shared with your workspace.+ </span>{" "}+ Anyone can create a skill, import one from a URL, or copy one+ from their local runtime — and every agent can use it.{" "}+ <span className="font-semibold text-brand">+ Local runtime skills stay private until you copy one here.+ </span>+ </div>+ )}{showEmpty ? (<div className="flex flex-1 items-center justify-center"><EmptyState onCreate={() => setCreateOpen(true)} />@@ -575,42 +416,12 @@ export default function SkillsPage() {</p></div>) : (- <>- <ListColumnHeader />- <div- ref={scrollRef}- style={fadeStyle}- className="flex-1 min-h-0 overflow-y-auto"- >- <div>- {filtered.map((skill) => {- const origin = readOrigin(skill);- const runtime =- origin.type === "runtime_local" && origin.runtime_id- ? runtimesById.get(origin.runtime_id) ?? null- : null;- return (- <SkillRow- key={skill.id}- skill={skill}- agents={assignments.get(skill.id) ?? []}- creator={- skill.created_by- ? membersById.get(skill.created_by) ?? null- : null- }- runtime={runtime}- canEdit={canEditSkill(skill, {- userId: currentUserId,- role: myRole,- })}- href={paths.skillDetail(skill.id)}- />- );- })}- </div>- </div>- </>+ <DataTable+ table={table}+ onRowClick={(row) =>+ navigation.push(paths.skillDetail(row.original.skill.id))+ }+ />)}</div>)}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8dc131c8ec..6b36eb77de 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -12,6 +12,9 @@ catalogs:'@tanstack/react-query':specifier: ^5.96.2version: 5.96.2+ '@tanstack/react-table':+ specifier: ^8.21.3+ version: 8.21.3'@testing-library/jest-dom':specifier: ^6.9.1version: 6.9.1@@ -525,6 +528,9 @@ importers:'@emoji-mart/data':specifier: ^1.2.1version: 1.2.1+ '@tanstack/react-table':+ specifier: 'catalog:'class-variance-authority:specifier: 'catalog:'version: 0.7.1@@ -652,6 +658,9 @@ importers:'@tanstack/react-query':specifier: 'catalog:'version: 5.96.2([email protected])+ '@tanstack/react-table':+ specifier: 'catalog:''@tiptap/core':specifier: ^3.22.1version: 3.22.1(@tiptap/[email protected])@@ -2607,6 +2616,17 @@ packages:peerDependencies:react: ^18 || ^19+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==}+ engines: {node: '>=12'}+ peerDependencies:+ react: '>=16.8'+ react-dom: '>=16.8'++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}+ engines: {node: '>=12'}+'@testing-library/[email protected]':resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}engines: {node: '>=18'}@@ -9192,6 +9212,14 @@ snapshots:'@tanstack/query-core': 5.96.2react: 19.2.3+ dependencies:+ '@tanstack/table-core': 8.21.3+ react: 19.2.3+ react-dom: 19.2.3([email protected])++ '@tanstack/[email protected]': {}+'@testing-library/[email protected]':dependencies:'@babel/code-frame': 7.29.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex cb77874173..b15fc06dfa 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -16,6 +16,7 @@ catalog:# State Managementzustand: "^5.0.0""@tanstack/react-query": "^5.96.2"+ "@tanstack/react-table": "^8.21.3"# UI & Stylingtailwindcss: "^4"diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 5f245c72e6..b28769959e 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -8,6 +8,7 @@ import ("io""log/slog""net/http"+ "unicode/utf8""github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgconn"@@ -19,6 +20,12 @@ import ("github.com/multica-ai/multica/server/pkg/protocol")+// Mirrors AGENT_DESCRIPTION_MAX_LENGTH in packages/core/agents/constants.ts+// and the agent_description_length CHECK constraint in migration 060. Counted+// in unicode code points (utf8.RuneCountInString), matching Postgres+// char_length and the front-end's String.prototype.length-with-counter UX.+const maxAgentDescriptionLength = 255+type AgentResponse struct {ID string `json:"id"`WorkspaceID string `json:"workspace_id"`@@ -137,6 +144,7 @@ type AgentTaskResponse struct {PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issueTriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this taskTriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment+ TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletesTriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering commentTriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment authorChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks@@ -190,6 +198,7 @@ func taskToResponse(t db.AgentTaskQueue) AgentTaskResponse {ParentTaskID: uuidToPtr(t.ParentTaskID),CreatedAt: timestampToString(t.CreatedAt),TriggerCommentID: uuidToPtr(t.TriggerCommentID),+ TriggerSummary: textToPtr(t.TriggerSummary),// Surface task source so the UI can distinguish issue-linked tasks// from chat-spawned or autopilot-spawned ones; all three may arrive// with issue_id = "" once a task has no linked issue.@@ -344,6 +353,10 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "name is required")return}+ if utf8.RuneCountInString(req.Description) > maxAgentDescriptionLength {+ writeError(w, http.StatusBadRequest, fmt.Sprintf("description must be %d characters or fewer", maxAgentDescriptionLength))+ return+ }if req.RuntimeID == "" {writeError(w, http.StatusBadRequest, "runtime_id is required")return@@ -545,6 +558,10 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {params.Name = pgtype.Text{String: *req.Name, Valid: true}}if req.Description != nil {+ if utf8.RuneCountInString(*req.Description) > maxAgentDescriptionLength {+ writeError(w, http.StatusBadRequest, fmt.Sprintf("description must be %d characters or fewer", maxAgentDescriptionLength))+ return+ }params.Description = pgtype.Text{String: *req.Description, Valid: true}}if req.Instructions != nil {diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex f114a0049c..64d470d450 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -192,6 +192,13 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,RuntimeID: agent.RuntimeID,Priority: 0,AutopilotRunID: run.ID,+ // Snapshot the autopilot title so task rows self-describe later+ // without joining back to autopilot. Truncated for the same+ // transmission-cost reason as comment-driven summaries.+ TriggerSummary: pgtype.Text{+ String: truncateForSummary(ap.Title, triggerSummaryMaxLen),+ Valid: ap.Title != "",+ },})if err != nil {return fmt.Errorf("create autopilot task: %w", err)diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex d34fd834aa..d6a667b26e 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -8,6 +8,7 @@ import ("log/slog""strconv"+ "strings""time""github.com/jackc/pgx/v5"@@ -33,6 +34,56 @@ type TaskWakeupNotifier interface {NotifyTaskAvailable(runtimeID, taskID string)}+// triggerSummaryMaxLen caps the snapshot length so the row stays cheap to+// transmit (it ends up in every task list response). 200 is enough for a+// recognisable preview of a one-paragraph comment.+const triggerSummaryMaxLen = 200++// truncateForSummary returns s shortened to maxRunes, with a trailing+// `…` when truncated. Operates on runes (not bytes) so multibyte characters+// — Chinese / emoji — count as one each. Strips surrounding whitespace+// first so a leading newline doesn't waste budget.+func truncateForSummary(s string, maxRunes int) string {+ // strings.Builder + Grow avoids the O(N²) realloc cycle of `+=` in+ // a loop. Grow uses byte length, which is an upper bound for the+ // rune-equivalent output (replacing \n/\r/\t with space is byte-equal+ // for ASCII whitespace), so we never reallocate.+ var b strings.Builder+ b.Grow(len(s))+ for _, r := range s {+ switch r {+ case '\n', '\r', '\t':+ b.WriteByte(' ')+ default:+ b.WriteRune(r)+ }+ }+ rs := []rune(strings.TrimSpace(b.String()))+ if len(rs) <= maxRunes {+ return string(rs)+ }+ return string(rs[:maxRunes]) + "…"+}++// buildCommentTriggerSummary fetches the comment content and truncates+// it for storage on the task row. Returns an invalid pgtype.Text when+// the comment is missing (deleted / wrong workspace / etc) so the column+// stays NULL — front-end falls back to a structural label in that case.+func (s *TaskService) buildCommentTriggerSummary(ctx context.Context, commentID pgtype.UUID) pgtype.Text {+ if !commentID.Valid {+ return pgtype.Text{}+ }+ comment, err := s.Queries.GetComment(ctx, commentID)+ if err != nil {+ return pgtype.Text{}+ }+ summary := truncateForSummary(comment.Content, triggerSummaryMaxLen)+ if summary == "" {+ return pgtype.Text{}+ }+ return pgtype.Text{String: summary, Valid: true}+}+func NewTaskService(q *db.Queries, tx TxStarter, hub *realtime.Hub, bus *events.Bus, wakeups ...TaskWakeupNotifier) *TaskService {var wakeup TaskWakeupNotifierif len(wakeups) > 0 {@@ -75,6 +126,7 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, tIssueID: issue.ID,Priority: priorityToInt(issue.Priority),TriggerCommentID: commentID,+ TriggerSummary: s.buildCommentTriggerSummary(ctx, commentID),})if err != nil {slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", err)@@ -82,6 +134,13 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, t}slog.Info("task enqueued", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(issue.AssigneeID))+ // Order matters: broadcast first, notify daemon second. notifyTaskAvailable+ // kicks an in-process channel that the daemon picks up over HTTP and+ // claims; the claim path then emits its own task:dispatch. Doing the+ // queued broadcast afterwards risks the dispatch event reaching clients+ // before the queued one (rare but unsafe-by-construction). Publishing+ // in the desired observe-order makes correctness independent of timing.+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)s.notifyTaskAvailable(task)return task, nil}@@ -110,6 +169,7 @@ func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue,IssueID: issue.ID,Priority: priorityToInt(issue.Priority),TriggerCommentID: triggerCommentID,+ TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),})if err != nil {slog.Error("mention task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)@@ -117,6 +177,8 @@ func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue,}slog.Info("mention task enqueued", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))+ // See EnqueueTaskForIssue for ordering rationale.+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)s.notifyTaskAvailable(task)return task, nil}@@ -210,6 +272,8 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe}slog.Info("chat task enqueued", "task_id", util.UUIDToString(task.ID), "chat_session_id", util.UUIDToString(chatSession.ID), "agent_id", util.UUIDToString(chatSession.AgentID))+ // See EnqueueTaskForIssue for ordering rationale.+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)s.notifyTaskAvailable(task)return task, nil}@@ -760,8 +824,11 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT"attempt", child.Attempt,"max_attempts", child.MaxAttempts,)+ // Retry creates a fresh queued row, same status transition (∅ → queued)+ // as EnqueueTaskFor*. Broadcast queued first, then notify the daemon —+ // see EnqueueTaskForIssue for ordering rationale.+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, child)s.notifyTaskAvailable(child)- s.broadcastTaskEvent(ctx, protocol.EventTaskDispatch, child)return &child, nil}diff --git a/server/migrations/060_agent_description_length.down.sql b/server/migrations/060_agent_description_length.down.sqlnew file mode 100644index 0000000000..49aa7aeb76--- /dev/null+++ b/server/migrations/060_agent_description_length.down.sql@@ -0,0 +1 @@+ALTER TABLE agent DROP CONSTRAINT IF EXISTS agent_description_length;diff --git a/server/migrations/060_agent_description_length.up.sql b/server/migrations/060_agent_description_length.up.sqlnew file mode 100644index 0000000000..0d8fbeb836--- /dev/null+++ b/server/migrations/060_agent_description_length.up.sql@@ -0,0 +1,29 @@+-- Cap agent.description at 255 characters so the column matches the+-- product-side limit enforced by the UI (counter + disabled save) and the+-- handler validation. The TEXT type stays — char_length is a constraint+-- on top, not a type change, which keeps the existing column data intact+-- and avoids a rewrite of the table.+--+-- Pre-flight truncate: any existing row that already exceeds the new+-- ceiling gets clipped to 255 chars. Without this the constraint add+-- would abort on the first over-limit row. Affected rows are rare (no UI+-- ever encouraged long descriptions), but defensive trimming keeps+-- self-hosted installs from blocking on the migration.+UPDATE agent+SET description = substring(description from 1 for 255)+WHERE char_length(description) > 255;++-- Two-step add: NOT VALID skips the table scan and only briefly takes an+-- ACCESS EXCLUSIVE lock to register the constraint, so concurrent writes+-- are not blocked. New inserts/updates are enforced from this point on.+-- The follow-up VALIDATE CONSTRAINT runs the actual scan under SHARE+-- UPDATE EXCLUSIVE, which permits concurrent writes during the scan.+--+-- At today's agent-table size the difference is invisible, but the+-- pattern is free defensively and matches Squawk's recommended migration+-- shape (https://squawkhq.com/docs/constraint-missing-not-valid).+ALTER TABLE agent+ ADD CONSTRAINT agent_description_length+ CHECK (char_length(description) <= 255) NOT VALID;++ALTER TABLE agent VALIDATE CONSTRAINT agent_description_length;diff --git a/server/migrations/061_task_trigger_summary.down.sql b/server/migrations/061_task_trigger_summary.down.sqlnew file mode 100644index 0000000000..9df1344a14--- /dev/null+++ b/server/migrations/061_task_trigger_summary.down.sql@@ -0,0 +1 @@+ALTER TABLE agent_task_queue DROP COLUMN trigger_summary;diff --git a/server/migrations/061_task_trigger_summary.up.sql b/server/migrations/061_task_trigger_summary.up.sqlnew file mode 100644index 0000000000..d38bd7004c--- /dev/null+++ b/server/migrations/061_task_trigger_summary.up.sql@@ -0,0 +1,6 @@+-- Snapshot the trigger context (comment text, autopilot title, etc) into+-- the task row at creation time. Lets every task row self-describe across+-- surfaces (issue detail Execution log, agent activity tooltip, inbox)+-- without joining back to the originating row, and survives later edits+-- or deletes of that source.+ALTER TABLE agent_task_queue ADD COLUMN trigger_summary TEXT;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 4734c0b635..28ebb013a6 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -55,7 +55,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {@@ -85,6 +85,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}@@ -93,7 +94,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`// Bulk-cancel every active (queued/dispatched/running) task for an agent.@@ -134,6 +135,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -149,7 +151,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`// Cancels every active task on the issue and returns the affected rows so the@@ -190,6 +192,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -205,7 +208,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgenUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`type CancelAgentTasksByIssueAndAgentParams struct {@@ -250,6 +253,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -265,7 +269,7 @@ const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerCommUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`// Cancels active tasks whose trigger is the given comment. Called when a@@ -306,6 +310,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -344,7 +349,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:@@ -383,6 +388,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}@@ -426,7 +432,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :oneUPDATE agent_task_queueSET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4WHERE id = $1 AND status = 'running'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`type CompleteAgentTaskParams struct {@@ -468,6 +474,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}@@ -557,9 +564,9 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent}const createAgentTask = `-- name: CreateAgentTask :one-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id)-VALUES ($1, $2, $3, 'queued', $4, $5)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id, trigger_summary)+VALUES ($1, $2, $3, 'queued', $4, $5, $6)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`type CreateAgentTaskParams struct {@@ -568,6 +575,7 @@ type CreateAgentTaskParams struct {IssueID pgtype.UUID `json:"issue_id"`Priority int32 `json:"priority"`TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`}func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams) (AgentTaskQueue, error) {@@ -577,6 +585,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsarg.IssueID,arg.Priority,arg.TriggerCommentID,+ arg.TriggerSummary,)var i AgentTaskQueueerr := row.Scan(@@ -603,6 +612,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}@@ -662,18 +672,18 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCreaconst createRetryTask = `-- name: CreateRetryTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,- status, priority, trigger_comment_id, context,+ status, priority, trigger_comment_id, trigger_summary, context,session_id, work_dir,attempt, max_attempts, parent_task_id)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,- 'queued', p.priority, p.trigger_comment_id, p.context,+ 'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,p.session_id, p.work_dir,p.attempt + 1, p.max_attempts, p.idFROM agent_task_queue pWHERE p.id = $1-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`// Clones a parent task into a fresh queued attempt. Carries forward the@@ -707,6 +717,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}@@ -720,7 +731,7 @@ SET status = 'failed',session_id = COALESCE($4, session_id),work_dir = COALESCE($5, work_dir)WHERE id = $1 AND status IN ('dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`type FailAgentTaskParams struct {@@ -773,6 +784,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}@@ -783,7 +795,7 @@ SET status = 'failed', completed_at = now(), error = 'task timed out',failure_reason = 'timeout'WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => $1::double precision))OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`type FailStaleTasksParams struct {@@ -827,6 +839,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -912,7 +925,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa}const getAgentTask = `-- name: GetAgentTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary FROM agent_task_queueWHERE id = $1`@@ -943,6 +956,7 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}@@ -1131,7 +1145,7 @@ func (q *Queries) HasPendingTaskForIssueAndAgent(ctx context.Context, arg HasPen}const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary FROM agent_task_queueWHERE issue_id = $1 AND status IN ('dispatched', 'running')ORDER BY created_at DESC`@@ -1169,6 +1183,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -1181,7 +1196,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI}const listAgentTasks = `-- name: ListAgentTasks :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary FROM agent_task_queueWHERE agent_id = $1ORDER BY created_at DESC`@@ -1219,6 +1234,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -1327,7 +1343,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([}const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC`@@ -1365,6 +1381,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -1377,7 +1394,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp}const listTasksByIssue = `-- name: ListTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC`@@ -1415,6 +1432,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -1427,15 +1445,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]}const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.last_heartbeat_at FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.last_heartbeat_at, atq.trigger_summary FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1AND atq.status IN ('queued', 'dispatched', 'running')UNION ALL-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.last_heartbeat_at FROM (- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.last_heartbeat_at+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.last_heartbeat_at, t.trigger_summary FROM (+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.last_heartbeat_at, atq.trigger_summaryFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1@@ -1495,6 +1513,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -1513,7 +1532,7 @@ SET status = 'failed',error = 'daemon restarted while task was in flight',failure_reason = 'runtime_recovery'WHERE runtime_id = $1 AND status IN ('dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`// Called by the daemon at startup. Atomically fails any dispatched/running@@ -1553,6 +1572,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}@@ -1643,7 +1663,7 @@ const startAgentTask = `-- name: StartAgentTask :oneUPDATE agent_task_queueSET status = 'running', started_at = now()WHERE id = $1 AND status = 'dispatched'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {@@ -1673,6 +1693,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 270719f2de..9f4709fc39 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -202,9 +202,9 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRunconst createAutopilotTask = `-- name: CreateAutopilotTask :one-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id)-VALUES ($1, $2, NULL, 'queued', $3, $4)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)+VALUES ($1, $2, NULL, 'queued', $3, $4, $5)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`type CreateAutopilotTaskParams struct {@@ -212,6 +212,7 @@ type CreateAutopilotTaskParams struct {RuntimeID pgtype.UUID `json:"runtime_id"`Priority int32 `json:"priority"`AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`}// =====================@@ -223,6 +224,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTaarg.RuntimeID,arg.Priority,arg.AutopilotRunID,+ arg.TriggerSummary,)var i AgentTaskQueueerr := row.Scan(@@ -249,6 +251,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 9f3275413b..acf11d1afb 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -93,7 +93,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPaconst createChatTask = `-- name: CreateChatTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id)VALUES ($1, $2, NULL, 'queued', $3, $4)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`type CreateChatTaskParams struct {@@ -135,6 +135,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 45613342af..6866fc5a2f 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -90,6 +90,7 @@ type AgentTaskQueue struct {ParentTaskID pgtype.UUID `json:"parent_task_id"`FailureReason pgtype.Text `json:"failure_reason"`LastHeartbeatAt pgtype.Timestamptz `json:"last_heartbeat_at"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`}type Attachment struct {diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex a08d8ff272..fcef693abb 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -84,7 +84,7 @@ WHERE status IN ('dispatched', 'running')AND runtime_id IN (SELECT id FROM agent_runtime WHERE status = 'offline')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at, trigger_summary`// Marks dispatched/running tasks as failed when their runtime is offline.@@ -122,6 +122,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ&i.ParentTaskID,&i.FailureReason,&i.LastHeartbeatAt,+ &i.TriggerSummary,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 5e1fa8ae16..e8776af7af 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -65,8 +65,8 @@ WHERE agent_id = $1ORDER BY created_at DESC;-- name: CreateAgentTask :one-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id)-VALUES ($1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id))+INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id, trigger_summary)+VALUES ($1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id), sqlc.narg(trigger_summary))RETURNING *;-- name: CreateQuickCreateTask :one@@ -84,13 +84,13 @@ RETURNING *;-- max_attempts and trigger_comment_id are inherited.INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,- status, priority, trigger_comment_id, context,+ status, priority, trigger_comment_id, trigger_summary, context,session_id, work_dir,attempt, max_attempts, parent_task_id)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,- 'queued', p.priority, p.trigger_comment_id, p.context,+ 'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,p.session_id, p.work_dir,p.attempt + 1, p.max_attempts, p.idFROM agent_task_queue pdiff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 3c316de3bf..075be3d5df 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -157,8 +157,8 @@ RETURNING t.*, a.workspace_id AS autopilot_workspace_id;-- =====================-- name: CreateAutopilotTask :one-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id)-VALUES ($1, $2, NULL, 'queued', $3, $4)+INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)+VALUES ($1, $2, NULL, 'queued', $3, $4, sqlc.narg(trigger_summary))RETURNING *;-- =====================diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 1ca5d9ee7e..47810746e7 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -22,13 +22,18 @@ const (EventAgentArchived = "agent:archived"EventAgentRestored = "agent:restored"- // Task events (server <-> daemon)- EventTaskDispatch = "task:dispatch"+ // Task events (server <-> daemon).+ // Each event maps to a status transition on agent_task_queue. Front-end+ // subscribes by `task:` prefix and invalidates the workspace task+ // snapshot, so the granularity here is "what does the user want to see+ // change" — not "every internal status flip".+ EventTaskQueued = "task:queued" // ∅ → queued (enqueue / retry create)+ EventTaskDispatch = "task:dispatch" // queued → dispatched (daemon claim)EventTaskProgress = "task:progress"- EventTaskCompleted = "task:completed"- EventTaskFailed = "task:failed"+ EventTaskCompleted = "task:completed" // running → completed+ EventTaskFailed = "task:failed" // running → failedEventTaskMessage = "task:message"- EventTaskCancelled = "task:cancelled"+ EventTaskCancelled = "task:cancelled" // * → cancelled// Inbox eventsEventInboxNew = "inbox:new"