Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(lists): rebuild all six list surfaces on a shared Linear-style list grid (#4038)
Naiyuan Qing63cf0ed3081a
diff --git a/packages/core/agents/stores/index.ts b/packages/core/agents/stores/index.tsindex e646ead233..49cc100936 100644--- a/packages/core/agents/stores/index.ts+++ b/packages/core/agents/stores/index.ts@@ -1,7 +1,15 @@export {useAgentsViewStore,+ AGENT_SCOPES,+ AGENT_SORT_DEFAULT_DIRECTION,+ AGENT_DEFAULT_HIDDEN_COLUMNS,+ EMPTY_AGENT_FILTERS,type AgentsScope,type AgentsViewState,+ type AgentSortField,+ type AgentSortDirection,+ type AgentColumnKey,+ type AgentListFilters,} from "./view-store";export {useTranscriptViewStore,diff --git a/packages/core/agents/stores/view-store.test.ts b/packages/core/agents/stores/view-store.test.tsindex 8465a80c69..7cb5397da4 100644--- a/packages/core/agents/stores/view-store.test.ts+++ b/packages/core/agents/stores/view-store.test.ts@@ -44,7 +44,7 @@ describe("useAgentsViewStore", () => {expect(useAgentsViewStore.getState().scope).toBe("all");});- it("partialize persists only scope under the workspace-namespaced key", async () => {+ it("partialize persists only view prefs (no actions) under the workspace-namespaced key", async () => {setCurrentWorkspace("acme", "ws_a");await flush();useAgentsViewStore.getState().setScope("all");@@ -52,7 +52,14 @@ describe("useAgentsViewStore", () => {const raw = localStorage.getItem("multica_agents_view:acme");expect(raw).not.toBeNull();const parsed = JSON.parse(raw as string);- expect(parsed.state).toEqual({ scope: "all" });+ expect(Object.keys(parsed.state).sort()).toEqual([+ "filters",+ "hiddenColumns",+ "scope",+ "sortDirection",+ "sortField",+ ]);+ expect(parsed.state.scope).toBe("all");});it("rehydrates a different saved scope on workspace switch", async () => {@@ -93,4 +100,25 @@ describe("useAgentsViewStore", () => {expect(useAgentsViewStore.getState().scope).toBe("mine");expect(localStorage.getItem("multica_agents_view:acme")).not.toBeNull();});++ it("backfills new filter dimensions when rehydrating a pre-owners payload", async () => {+ // A payload persisted before the `owners` filter existed must not drop+ // the key to undefined (the agents list filter predicate reads+ // `filters.owners.length` and would crash).+ localStorage.setItem(+ "multica_agents_view:acme",+ JSON.stringify({+ state: { filters: { availability: ["online"], runtimes: [] } },+ version: 0,+ }),+ );++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ const filters = useAgentsViewStore.getState().filters;+ expect(filters.owners).toEqual([]);+ expect(filters.availability).toEqual(["online"]);+ });});diff --git a/packages/core/agents/stores/view-store.ts b/packages/core/agents/stores/view-store.tsindex 8267e4127b..94e6e8bc0e 100644--- a/packages/core/agents/stores/view-store.ts+++ b/packages/core/agents/stores/view-store.ts@@ -8,30 +8,181 @@ import {} from "../../platform/workspace-storage";import { defaultStorage } from "../../platform/storage";-export type AgentsScope = "mine" | "all";+// View preferences for the agents list page: scope, sort, column visibility,+// and filters. Persisted per workspace, per user/device. Row selection is+// session-scoped on purpose (same rationale as the skills/autopilots view+// stores).++// Scope mixes the ownership lens (mine/all) with the archived lifecycle+// stage. Impure on paper, but the three are mutually exclusive in practice+// and "mine" is the historical product default; the archived view ignores+// the ownership lens entirely (showing only *my* archived agents would hide+// other people's archived agents with no UI to explain why).+export type AgentsScope = "mine" | "all" | "archived";++export const AGENT_SCOPES: AgentsScope[] = ["mine", "all", "archived"];++export type AgentSortField = "lastActive" | "name" | "runs" | "created";++export type AgentSortDirection = "asc" | "desc";++/** Per-field direction applied when the user switches TO that field. */+export const AGENT_SORT_DEFAULT_DIRECTION: Record<+ AgentSortField,+ AgentSortDirection+> = {+ lastActive: "desc",+ name: "asc",+ runs: "desc",+ created: "desc",+};++/** Multi-select filter state. Empty array per dimension = inactive. */+export interface AgentListFilters {+ /** AgentAvailability values (online / unstable / offline). */+ availability: string[];+ /** Runtime ids. */+ runtimes: string[];+ /** Owner user ids. Owner is the same person-axis as the Mine scope: the+ * "mine" scope is the clean no-filter personal view, and applying any+ * filter (owner or otherwise) leaves it for "all" — see setScope /+ * toggleFilter. So owner-as-filter and Mine never coexist, which keeps+ * the axis orthogonal (no "mine + owner=someone-else = empty" state). */+ owners: string[];+ /** Runtime-native model identifiers (e.g. claude / codex / gpt-…). */+ models: string[];+}++export const EMPTY_AGENT_FILTERS: AgentListFilters = {+ availability: [],+ runtimes: [],+ owners: [],+ models: [],+};++// User-hideable columns. Name and the structural columns (checkbox, kebab)+// are always visible.+export type AgentColumnKey =+ | "status"+ | "owner"+ | "runtime"+ | "lastActive"+ | "runs"+ | "model"+ | "created";++/** Model and created are opt-in: hidden until the user enables them. Owner+ * is shown by default (the user wants to see who owns each agent). */+export const AGENT_DEFAULT_HIDDEN_COLUMNS: AgentColumnKey[] = [+ "model",+ "created",+];export interface AgentsViewState {scope: AgentsScope;+ sortField: AgentSortField;+ sortDirection: AgentSortDirection;+ hiddenColumns: AgentColumnKey[];+ filters: AgentListFilters;setScope: (scope: AgentsScope) => void;+ /** Header click: toggles direction on the active field, otherwise switches+ * to the field with its default direction. */+ toggleSort: (field: AgentSortField) => void;+ /** Display panel select: switches field (default direction), no toggle. */+ setSortField: (field: AgentSortField) => void;+ setSortDirection: (direction: AgentSortDirection) => void;+ toggleColumn: (key: AgentColumnKey) => void;+ toggleFilter: (key: keyof AgentListFilters, value: string) => void;+ clearFilters: () => void;}+const DEFAULTS = {+ // "mine" is the historical default — most members care about their own+ // agents first; admins flip to "all".+ scope: "mine" as AgentsScope,+ sortField: "lastActive" as AgentSortField,+ sortDirection: AGENT_SORT_DEFAULT_DIRECTION.lastActive,+ hiddenColumns: AGENT_DEFAULT_HIDDEN_COLUMNS,+ filters: EMPTY_AGENT_FILTERS,+};+export const useAgentsViewStore = create<AgentsViewState>()(persist((set) => ({- scope: "mine",- setScope: (scope) => set({ scope }),+ ...DEFAULTS,+ // "Mine" is the clean personal view: entering it clears all filters,+ // so Mine never carries filters. Switching to all/archived leaves+ // filters intact (you can carry "owner = Bob" between them).+ setScope: (scope) =>+ set(scope === "mine" ? { scope, filters: EMPTY_AGENT_FILTERS } : { scope }),+ toggleSort: (field) =>+ set((state) =>+ state.sortField === field+ ? {+ sortDirection: state.sortDirection === "asc" ? "desc" : "asc",+ }+ : {+ sortField: field,+ sortDirection: AGENT_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortField: (field) =>+ set((state) =>+ state.sortField === field+ ? {}+ : {+ sortField: field,+ sortDirection: AGENT_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortDirection: (direction) => set({ sortDirection: direction }),+ toggleColumn: (key) =>+ set((state) => ({+ hiddenColumns: state.hiddenColumns.includes(key)+ ? state.hiddenColumns.filter((k) => k !== key)+ : [...state.hiddenColumns, key],+ })),+ toggleFilter: (key, value) =>+ set((state) => {+ const list = state.filters[key] as string[];+ const next = list.includes(value)+ ? list.filter((v) => v !== value)+ : [...list, value];+ // Applying any filter leaves the clean "mine" view for "all" —+ // Mine is the no-filter mode (see setScope). Archived keeps its+ // own scope (it can carry filters).+ const scope = state.scope === "mine" ? "all" : state.scope;+ return { scope, filters: { ...state.filters, [key]: next } };+ }),+ clearFilters: () => set({ filters: EMPTY_AGENT_FILTERS }),}),{name: "multica_agents_view",- storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),- partialize: (state) => ({ scope: state.scope }),+ storage: createJSONStorage(() =>+ createWorkspaceAwareStorage(defaultStorage),+ ),+ partialize: (state) => ({+ scope: state.scope,+ sortField: state.sortField,+ sortDirection: state.sortDirection,+ hiddenColumns: state.hiddenColumns,+ filters: state.filters,+ }),// On rehydrate, if the new workspace has no persisted value, reset to- // the default "mine" instead of leaving the previous workspace's in-- // memory scope in place. Default merge keeps current state when- // persisted is undefined, which would leak "all" across workspaces.+ // the defaults instead of leaving the previous workspace's in-memory+ // view state in place. Default merge keeps current state when+ // persisted is undefined, which would leak state across workspaces.merge: (persisted, current) => {- if (!persisted) return { ...current, scope: "mine" };- return { ...current, ...(persisted as Partial<AgentsViewState>) };+ if (!persisted) return { ...current, ...DEFAULTS };+ const p = persisted as Partial<AgentsViewState>;+ // Deep-merge filters so a payload persisted before a new filter+ // dimension existed (e.g. `owners`) still gets that key's default+ // instead of dropping it to `undefined` and crashing `.length`.+ return {+ ...current,+ ...p,+ filters: { ...EMPTY_AGENT_FILTERS, ...(p.filters ?? {}) },+ };},},),diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 903ac538b3..2b92306853 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -163,6 +163,8 @@ import {AppConfigSchema,type AppConfigResponse,GroupedIssuesResponseSchema,+ ListAutopilotsResponseSchema,+ EMPTY_LIST_AUTOPILOTS_RESPONSE,ListIssuesResponseSchema,ListWebhookDeliveriesResponseSchema,RuntimeHourlyActivityListSchema,@@ -1545,6 +1547,16 @@ export class ApiClient {});}+ // Incremental attach: POST /skills/add only inserts the given ids (the+ // server upserts with ON CONFLICT DO NOTHING), so callers don't need to+ // read the agent's current skill set first.+ async addAgentSkills(agentId: string, data: SetAgentSkillsRequest): Promise<void> {+ await this.fetch(`/api/agents/${agentId}/skills/add`, {+ method: "POST",+ body: JSON.stringify(data),+ });+ }+// Personal Access Tokensasync listPersonalAccessTokens(): Promise<PersonalAccessToken[]> {return this.fetch("/api/tokens");@@ -1942,7 +1954,13 @@ export class ApiClient {async listAutopilots(params?: { status?: string }): Promise<ListAutopilotsResponse> {const search = new URLSearchParams();if (params?.status) search.set("status", params.status);- return this.fetch(`/api/autopilots?${search}`);+ const raw = await this.fetch<unknown>(`/api/autopilots?${search}`);+ return parseWithFallback(+ raw,+ ListAutopilotsResponseSchema,+ EMPTY_LIST_AUTOPILOTS_RESPONSE as ListAutopilotsResponse,+ { endpoint: "GET /api/autopilots" },+ );}async getAutopilot(id: string): Promise<GetAutopilotResponse> {diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex af0e1848ba..ae7d1c9ce4 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -91,6 +91,67 @@ describe("ApiClient schema fallback", () => {});});+ describe("listAutopilots", () => {+ const baseAutopilot = {+ id: "ap-1",+ workspace_id: "ws-1",+ title: "Daily triage",+ description: null,+ assignee_id: "agent-1",+ status: "active",+ execution_mode: "run_only",+ issue_title_template: null,+ created_by_type: "member",+ created_by_id: "user-1",+ last_run_at: null,+ created_at: "2026-06-01T00:00:00Z",+ updated_at: "2026-06-01T00:00:00Z",+ };++ it("falls back to an empty list when the response is malformed", async () => {+ stubFetchJson({ autopilots: "not-an-array", total: 1 });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listAutopilots();+ expect(res).toEqual({ autopilots: [], total: 0 });+ });++ it("accepts an old-server row without assignee_type or derived fields", async () => {+ // Pre-MUL-2429 servers omit assignee_type; servers older than the+ // list-derived-fields change omit trigger_kinds/next_run_at/+ // last_run_status. Both must parse, not fall back.+ stubFetchJson({ autopilots: [baseAutopilot], total: 1 });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listAutopilots();+ expect(res.autopilots).toHaveLength(1);+ expect(res.autopilots[0]?.assignee_type).toBe("agent");+ expect(res.autopilots[0]?.trigger_kinds).toBeUndefined();+ expect(res.autopilots[0]?.last_run_status).toBeUndefined();+ });++ it("passes derived fields through and tolerates enum drift", async () => {+ stubFetchJson({+ autopilots: [+ {+ ...baseAutopilot,+ assignee_type: "squad",+ trigger_kinds: ["schedule", "some_future_kind"],+ next_run_at: "2026-06-13T09:00:00Z",+ last_run_status: "some_future_status",+ },+ ],+ total: 1,+ });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listAutopilots();+ expect(res.autopilots[0]?.trigger_kinds).toEqual([+ "schedule",+ "some_future_kind",+ ]);+ expect(res.autopilots[0]?.next_run_at).toBe("2026-06-13T09:00:00Z");+ expect(res.autopilots[0]?.last_run_status).toBe("some_future_status");+ });+ });+describe("getConfig", () => {it("drops malformed daemon setup URLs instead of throwing", async () => {stubFetchJson({diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 110b6baf62..e660bc0ed1 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -735,6 +735,47 @@ export const EMPTY_LIST_WEBHOOK_DELIVERIES_RESPONSE: ListWebhookDeliveriesRespontotal: 0,};+// ---------------------------------------------------------------------------+// Autopilot list schema. Enums (`status`, `execution_mode`, `trigger_kinds`,+// `last_run_status`) stay `z.string()` so future server-side values degrade+// to a generic UI fallback. The three derived fields (trigger_kinds /+// next_run_at / last_run_status) are list-endpoint-only and absent on older+// servers — optional by contract, the list renders "—" without them.+// ---------------------------------------------------------------------------++const AutopilotListItemSchema = z.object({+ id: z.string(),+ workspace_id: z.string(),+ title: z.string(),+ description: z.string().nullable().optional(),+ project_id: z.string().nullable().optional(),+ // Older servers (pre-MUL-2429) omit assignee_type; "agent" is the+ // documented default.+ assignee_type: z.string().default("agent"),+ assignee_id: z.string(),+ status: z.string(),+ execution_mode: z.string(),+ issue_title_template: z.string().nullable().optional(),+ created_by_type: z.string(),+ created_by_id: z.string(),+ last_run_at: z.string().nullable().optional(),+ created_at: z.string(),+ updated_at: z.string(),+ trigger_kinds: z.array(z.string()).optional(),+ next_run_at: z.string().nullable().optional(),+ last_run_status: z.string().nullable().optional(),+}).loose();++export const ListAutopilotsResponseSchema = z.object({+ autopilots: z.array(AutopilotListItemSchema).default([]),+ total: z.number().default(0),+}).loose();++export const EMPTY_LIST_AUTOPILOTS_RESPONSE = {+ autopilots: [],+ total: 0,+};+export const EMPTY_WEBHOOK_DELIVERY: WebhookDelivery = {id: "",workspace_id: "",diff --git a/packages/core/autopilots/stores/index.ts b/packages/core/autopilots/stores/index.tsnew file mode 100644index 0000000000..c28c482aab--- /dev/null+++ b/packages/core/autopilots/stores/index.ts@@ -0,0 +1,13 @@+export {+ useAutopilotsViewStore,+ AUTOPILOT_SCOPES,+ AUTOPILOT_SORT_DEFAULT_DIRECTION,+ AUTOPILOT_DEFAULT_HIDDEN_COLUMNS,+ EMPTY_AUTOPILOT_FILTERS,+ type AutopilotScope,+ type AutopilotSortField,+ type AutopilotSortDirection,+ type AutopilotColumnKey,+ type AutopilotListFilters,+ type AutopilotsViewState,+} from "./view-store";diff --git a/packages/core/autopilots/stores/view-store.ts b/packages/core/autopilots/stores/view-store.tsnew file mode 100644index 0000000000..419bfeaf83--- /dev/null+++ b/packages/core/autopilots/stores/view-store.ts@@ -0,0 +1,176 @@+"use client";++import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";+import {+ createWorkspaceAwareStorage,+ registerForWorkspaceRehydration,+} from "../../platform/workspace-storage";+import { defaultStorage } from "../../platform/storage";++// View preferences for the autopilots list page: scope, sort, column+// visibility, and filters. Persisted per workspace (workspace-aware storage),+// per user/device (localStorage). Search text and row selection are+// deliberately NOT stored — they are session-scoped (same rationale as the+// skills view store).++// Status is the promoted SCOPE dimension (lifecycle stage, mutually+// exclusive) — it therefore does NOT appear in `filters`; one dimension+// lives in exactly one place. "all" = active + paused. There is no+// archived scope because the product has no UI archiving flow (the DB+// status value exists but nothing in the UI can set it); add the scope+// back together with archive actions if that flow ever ships.+export type AutopilotScope = "all" | "active" | "paused";++export const AUTOPILOT_SCOPES: AutopilotScope[] = ["all", "active", "paused"];++export type AutopilotSortField = "name" | "lastRun" | "nextRun" | "created";++export type AutopilotSortDirection = "asc" | "desc";++/** Per-field direction applied when the user switches TO that field. */+export const AUTOPILOT_SORT_DEFAULT_DIRECTION: Record<+ AutopilotSortField,+ AutopilotSortDirection+> = {+ name: "asc",+ lastRun: "desc",+ nextRun: "asc",+ created: "desc",+};++/** Multi-select filter state. Empty array per dimension = inactive. */+export interface AutopilotListFilters {+ assignees: string[];+ modes: string[];+ triggerKinds: string[];+ creators: string[];+}++export const EMPTY_AUTOPILOT_FILTERS: AutopilotListFilters = {+ assignees: [],+ modes: [],+ triggerKinds: [],+ creators: [],+};++// User-hideable columns. Name and the structural columns (checkbox, kebab)+// are always visible.+export type AutopilotColumnKey =+ | "assignee"+ | "trigger"+ | "lastRun"+ | "nextRun"+ | "mode"+ | "creator"+ | "created";++/** Mode, creator and created are opt-in: hidden until the user enables them. */+export const AUTOPILOT_DEFAULT_HIDDEN_COLUMNS: AutopilotColumnKey[] = [+ "mode",+ "creator",+ "created",+];++export interface AutopilotsViewState {+ scope: AutopilotScope;+ sortField: AutopilotSortField;+ sortDirection: AutopilotSortDirection;+ hiddenColumns: AutopilotColumnKey[];+ filters: AutopilotListFilters;+ setScope: (scope: AutopilotScope) => void;+ /** Header click: toggles direction on the active field, otherwise switches+ * to the field with its default direction. */+ toggleSort: (field: AutopilotSortField) => void;+ /** Display panel select: switches field (default direction), no toggle. */+ setSortField: (field: AutopilotSortField) => void;+ setSortDirection: (direction: AutopilotSortDirection) => void;+ toggleColumn: (key: AutopilotColumnKey) => void;+ toggleFilter: (key: keyof AutopilotListFilters, value: string) => void;+ clearFilters: () => void;+}++const DEFAULTS = {+ scope: "all" as AutopilotScope,+ sortField: "lastRun" as AutopilotSortField,+ sortDirection: AUTOPILOT_SORT_DEFAULT_DIRECTION.lastRun,+ hiddenColumns: AUTOPILOT_DEFAULT_HIDDEN_COLUMNS,+ filters: EMPTY_AUTOPILOT_FILTERS,+};++export const useAutopilotsViewStore = create<AutopilotsViewState>()(+ persist(+ (set) => ({+ ...DEFAULTS,+ setScope: (scope) => set({ scope }),+ toggleSort: (field) =>+ set((state) =>+ state.sortField === field+ ? {+ sortDirection: state.sortDirection === "asc" ? "desc" : "asc",+ }+ : {+ sortField: field,+ sortDirection: AUTOPILOT_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortField: (field) =>+ set((state) =>+ state.sortField === field+ ? {}+ : {+ sortField: field,+ sortDirection: AUTOPILOT_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortDirection: (direction) => set({ sortDirection: direction }),+ toggleColumn: (key) =>+ set((state) => ({+ hiddenColumns: state.hiddenColumns.includes(key)+ ? state.hiddenColumns.filter((k) => k !== key)+ : [...state.hiddenColumns, key],+ })),+ toggleFilter: (key, value) =>+ set((state) => {+ const list = state.filters[key] as string[];+ const next = list.includes(value)+ ? list.filter((v) => v !== value)+ : [...list, value];+ return { filters: { ...state.filters, [key]: next } };+ }),+ clearFilters: () => set({ filters: EMPTY_AUTOPILOT_FILTERS }),+ }),+ {+ name: "multica_autopilots_view",+ storage: createJSONStorage(() =>+ createWorkspaceAwareStorage(defaultStorage),+ ),+ partialize: (state) => ({+ scope: state.scope,+ sortField: state.sortField,+ sortDirection: state.sortDirection,+ hiddenColumns: state.hiddenColumns,+ filters: state.filters,+ }),+ // On rehydrate, if the new workspace has no persisted value, reset to+ // the defaults instead of leaving the previous workspace's in-memory+ // view state in place (same rationale as the skills view store).+ merge: (persisted, current) => {+ if (!persisted) return { ...current, ...DEFAULTS };+ const p = persisted as Partial<AutopilotsViewState>;+ // Deep-merge filters so a payload persisted before a new filter+ // dimension existed still gets that key's default instead of+ // dropping it to undefined (which crashes `.length` reads).+ return {+ ...current,+ ...p,+ filters: { ...EMPTY_AUTOPILOT_FILTERS, ...(p.filters ?? {}) },+ };+ },+ },+ ),+);++registerForWorkspaceRehydration(() =>+ useAutopilotsViewStore.persist.rehydrate(),+);diff --git a/packages/core/package.json b/packages/core/package.jsonindex 83d3621830..1f8ff61a36 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -103,7 +103,9 @@"./i18n/react": "./i18n/react.ts","./i18n/browser": "./i18n/browser.ts","./skills": "./skills/index.ts",- "./skills/frontmatter": "./skills/frontmatter.ts"+ "./skills/frontmatter": "./skills/frontmatter.ts",+ "./skills/stores": "./skills/stores/index.ts",+ "./autopilots/stores": "./autopilots/stores/index.ts"},"dependencies": {"@formatjs/intl-localematcher": "catalog:",diff --git a/packages/core/projects/index.ts b/packages/core/projects/index.tsindex a93f334331..cf1b6e602f 100644--- a/packages/core/projects/index.ts+++ b/packages/core/projects/index.ts@@ -1,7 +1,17 @@export { projectKeys, projectListOptions, projectDetailOptions } from "./queries";export { useCreateProject, useUpdateProject, useDeleteProject } from "./mutations";export { useProjectDraftStore } from "./draft-store";-export { useProjectViewStore } from "./stores/view-store";+export {+ useProjectViewStore,+ PROJECT_SORT_DEFAULT_DIRECTION,+ PROJECT_DEFAULT_HIDDEN_COLUMNS,+ EMPTY_PROJECT_FILTERS,+ type ProjectViewMode,+ type ProjectSortField,+ type ProjectSortDirection,+ type ProjectColumnKey,+ type ProjectListFilters,+} from "./stores/view-store";export {projectResourceKeys,projectResourcesOptions,diff --git a/packages/core/projects/stores/view-store.test.ts b/packages/core/projects/stores/view-store.test.tsindex b7eab112f7..7d35c93f7e 100644--- a/packages/core/projects/stores/view-store.test.ts+++ b/packages/core/projects/stores/view-store.test.ts@@ -44,7 +44,7 @@ describe("useProjectViewStore", () => {expect(useProjectViewStore.getState().viewMode).toBe("comfortable");});- it("partialize persists only viewMode under the workspace-namespaced key", async () => {+ it("partialize persists view prefs (no actions) under the workspace-namespaced key", async () => {setCurrentWorkspace("acme", "ws_a");await flush();useProjectViewStore.getState().setViewMode("comfortable");@@ -52,7 +52,14 @@ describe("useProjectViewStore", () => {const raw = localStorage.getItem("multica_projects_view:acme");expect(raw).not.toBeNull();const parsed = JSON.parse(raw as string);- expect(parsed.state).toEqual({ viewMode: "comfortable" });+ expect(Object.keys(parsed.state).sort()).toEqual([+ "filters",+ "hiddenColumns",+ "sortDirection",+ "sortField",+ "viewMode",+ ]);+ expect(parsed.state.viewMode).toBe("comfortable");});it("rehydrates a different saved viewMode on workspace switch", async () => {diff --git a/packages/core/projects/stores/view-store.ts b/packages/core/projects/stores/view-store.tsindex e823220e72..e4de867fac 100644--- a/packages/core/projects/stores/view-store.ts+++ b/packages/core/projects/stores/view-store.ts@@ -5,29 +5,139 @@ import { createJSONStorage, persist } from "zustand/middleware";import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";import { defaultStorage } from "../../platform/storage";+// Projects is the one dual-view list: a dense table (compact) and a card+// grid (comfortable), toggled by viewMode. Sort + filters feed both views;+// hiddenColumns only applies to the table. No scope (lead is optional and+// often an agent, so there's no strong personal axis; status is a 5-value+// lifecycle better expressed as a filter). Search stays session-local.export type ProjectViewMode = "compact" | "comfortable";+export type ProjectSortField = "name" | "priority" | "status" | "progress" | "created";++export type ProjectSortDirection = "asc" | "desc";++export const PROJECT_SORT_DEFAULT_DIRECTION: Record<+ ProjectSortField,+ ProjectSortDirection+> = {+ name: "asc",+ priority: "desc",+ status: "asc",+ progress: "desc",+ created: "desc",+};++/** Multi-select filters. Empty array per dimension = inactive. */+export interface ProjectListFilters {+ /** ProjectStatus values. */+ statuses: string[];+ /** ProjectPriority values. */+ priorities: string[];+ /** Composite "type:id" lead refs (member or agent). */+ leads: string[];+}++export const EMPTY_PROJECT_FILTERS: ProjectListFilters = {+ statuses: [],+ priorities: [],+ leads: [],+};++// Hideable table columns. Name + status are the always-visible core (status+// is the project's defining lifecycle field), so they're not in this set.+export type ProjectColumnKey = "priority" | "progress" | "lead" | "issues" | "created";++/** Issues count is opt-in; the rest show by default (matching the prior+ * compact table). */+export const PROJECT_DEFAULT_HIDDEN_COLUMNS: ProjectColumnKey[] = ["issues"];+export interface ProjectViewState {viewMode: ProjectViewMode;+ sortField: ProjectSortField;+ sortDirection: ProjectSortDirection;+ hiddenColumns: ProjectColumnKey[];+ filters: ProjectListFilters;setViewMode: (mode: ProjectViewMode) => void;+ toggleSort: (field: ProjectSortField) => void;+ setSortField: (field: ProjectSortField) => void;+ setSortDirection: (direction: ProjectSortDirection) => void;+ toggleColumn: (key: ProjectColumnKey) => void;+ toggleFilter: (key: keyof ProjectListFilters, value: string) => void;+ clearFilters: () => void;}+const DEFAULTS = {+ viewMode: "compact" as ProjectViewMode,+ sortField: "created" as ProjectSortField,+ sortDirection: PROJECT_SORT_DEFAULT_DIRECTION.created,+ hiddenColumns: PROJECT_DEFAULT_HIDDEN_COLUMNS,+ filters: EMPTY_PROJECT_FILTERS,+};+export const useProjectViewStore = create<ProjectViewState>()(persist((set) => ({- viewMode: "compact",+ ...DEFAULTS,setViewMode: (mode) => set({ viewMode: mode }),+ toggleSort: (field) =>+ set((state) =>+ state.sortField === field+ ? { sortDirection: state.sortDirection === "asc" ? "desc" : "asc" }+ : {+ sortField: field,+ sortDirection: PROJECT_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortField: (field) =>+ set((state) =>+ state.sortField === field+ ? {}+ : {+ sortField: field,+ sortDirection: PROJECT_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortDirection: (direction) => set({ sortDirection: direction }),+ toggleColumn: (key) =>+ set((state) => ({+ hiddenColumns: state.hiddenColumns.includes(key)+ ? state.hiddenColumns.filter((k) => k !== key)+ : [...state.hiddenColumns, key],+ })),+ toggleFilter: (key, value) =>+ set((state) => {+ const list = state.filters[key] as string[];+ const next = list.includes(value)+ ? list.filter((v) => v !== value)+ : [...list, value];+ return { filters: { ...state.filters, [key]: next } };+ }),+ clearFilters: () => set({ filters: EMPTY_PROJECT_FILTERS }),}),{name: "multica_projects_view",storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),- partialize: (state) => ({ viewMode: state.viewMode }),+ partialize: (state) => ({+ viewMode: state.viewMode,+ sortField: state.sortField,+ sortDirection: state.sortDirection,+ hiddenColumns: state.hiddenColumns,+ filters: state.filters,+ }),+ // Deep-merge filters so a payload persisted before a filter dimension+ // existed still gets that key's default (avoids `.length` on+ // undefined). Same hardening as the other view stores.merge: (persisted, current) => {- if (!persisted) return { ...current, viewMode: "compact" };- return { ...current, ...(persisted as Partial<ProjectViewState>) };+ if (!persisted) return { ...current, ...DEFAULTS };+ const p = persisted as Partial<ProjectViewState>;+ return {+ ...current,+ ...p,+ filters: { ...EMPTY_PROJECT_FILTERS, ...(p.filters ?? {}) },+ };},}));-registerForWorkspaceRehydration(() => useProjectViewStore.persist.rehydrate());\ No newline at end of file+registerForWorkspaceRehydration(() => useProjectViewStore.persist.rehydrate());diff --git a/packages/core/skills/stores/index.ts b/packages/core/skills/stores/index.tsnew file mode 100644index 0000000000..958d8480e9--- /dev/null+++ b/packages/core/skills/stores/index.ts@@ -0,0 +1,12 @@+export {+ useSkillsViewStore,+ DEFAULT_HIDDEN_COLUMNS,+ EMPTY_SKILL_FILTERS,+ SKILL_SORT_DEFAULT_DIRECTION,+ type SkillColumnKey,+ type SkillListFilters,+ type SkillOriginType,+ type SkillSortDirection,+ type SkillSortField,+ type SkillsViewState,+} from "./view-store";diff --git a/packages/core/skills/stores/view-store.ts b/packages/core/skills/stores/view-store.tsnew file mode 100644index 0000000000..6b4b984d4f--- /dev/null+++ b/packages/core/skills/stores/view-store.ts@@ -0,0 +1,158 @@+"use client";++import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";+import {+ createWorkspaceAwareStorage,+ registerForWorkspaceRehydration,+} from "../../platform/workspace-storage";+import { defaultStorage } from "../../platform/storage";++// View preferences for the skills list page: sort, column visibility, and+// filters. Persisted per workspace (workspace-aware storage), per user/device+// (localStorage). Search text and row selection are deliberately NOT stored —+// they are session-scoped, and persisting them would greet returning users+// with an inexplicably narrowed list.++export type SkillSortField = "name" | "usedBy" | "updated" | "created";++export type SkillSortDirection = "asc" | "desc";++/** Per-field direction applied when the user switches TO that field. */+export const SKILL_SORT_DEFAULT_DIRECTION: Record<+ SkillSortField,+ SkillSortDirection+> = {+ name: "asc",+ usedBy: "desc",+ updated: "desc",+ created: "desc",+};++export type SkillOriginType =+ | "manual"+ | "runtime_local"+ | "clawhub"+ | "skills_sh"+ | "github";++/** Multi-select filter state. Empty array per dimension = inactive. */+export interface SkillListFilters {+ usage: ("used" | "unused")[];+ origins: SkillOriginType[];+ agents: string[];+ creators: string[];+}++export const EMPTY_SKILL_FILTERS: SkillListFilters = {+ usage: [],+ origins: [],+ agents: [],+ creators: [],+};++// User-hideable columns. Name and the structural columns (checkbox, kebab)+// are always visible.+export type SkillColumnKey =+ | "usedBy"+ | "source"+ | "creator"+ | "updated"+ | "created";++/** Source and created are opt-in: hidden until the user enables them. */+export const DEFAULT_HIDDEN_COLUMNS: SkillColumnKey[] = ["source", "created"];++export interface SkillsViewState {+ sortField: SkillSortField;+ sortDirection: SkillSortDirection;+ hiddenColumns: SkillColumnKey[];+ filters: SkillListFilters;+ /** Header click: toggles direction on the active field, otherwise switches+ * to the field with its default direction. */+ toggleSort: (field: SkillSortField) => void;+ /** Display panel select: switches field (default direction), no toggle. */+ setSortField: (field: SkillSortField) => void;+ setSortDirection: (direction: SkillSortDirection) => void;+ toggleColumn: (key: SkillColumnKey) => void;+ toggleFilter: (key: keyof SkillListFilters, value: string) => void;+ clearFilters: () => void;+}++const DEFAULTS = {+ sortField: "updated" as SkillSortField,+ sortDirection: SKILL_SORT_DEFAULT_DIRECTION.updated,+ hiddenColumns: DEFAULT_HIDDEN_COLUMNS,+ filters: EMPTY_SKILL_FILTERS,+};++export const useSkillsViewStore = create<SkillsViewState>()(+ persist(+ (set) => ({+ ...DEFAULTS,+ toggleSort: (field) =>+ set((state) =>+ state.sortField === field+ ? {+ sortDirection: state.sortDirection === "asc" ? "desc" : "asc",+ }+ : {+ sortField: field,+ sortDirection: SKILL_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortField: (field) =>+ set((state) =>+ state.sortField === field+ ? {}+ : {+ sortField: field,+ sortDirection: SKILL_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortDirection: (direction) => set({ sortDirection: direction }),+ toggleColumn: (key) =>+ set((state) => ({+ hiddenColumns: state.hiddenColumns.includes(key)+ ? state.hiddenColumns.filter((k) => k !== key)+ : [...state.hiddenColumns, key],+ })),+ toggleFilter: (key, value) =>+ set((state) => {+ const list = state.filters[key] as string[];+ const next = list.includes(value)+ ? list.filter((v) => v !== value)+ : [...list, value];+ return { filters: { ...state.filters, [key]: next } };+ }),+ clearFilters: () => set({ filters: EMPTY_SKILL_FILTERS }),+ }),+ {+ name: "multica_skills_view",+ storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),+ partialize: (state) => ({+ sortField: state.sortField,+ sortDirection: state.sortDirection,+ hiddenColumns: state.hiddenColumns,+ filters: state.filters,+ }),+ // On rehydrate, if the new workspace has no persisted value, reset to+ // the defaults instead of leaving the previous workspace's in-memory+ // view state in place (same rationale as the agents view store).+ merge: (persisted, current) => {+ if (!persisted) return { ...current, ...DEFAULTS };+ const p = persisted as Partial<SkillsViewState>;+ // Deep-merge filters so a payload persisted before a new filter+ // dimension existed still gets that key's default instead of+ // dropping it to undefined (which crashes `.length` reads).+ return {+ ...current,+ ...p,+ filters: { ...EMPTY_SKILL_FILTERS, ...(p.filters ?? {}) },+ };+ },+ },+ ),+);++registerForWorkspaceRehydration(() => useSkillsViewStore.persist.rehydrate());diff --git a/packages/core/squads/stores/index.ts b/packages/core/squads/stores/index.tsindex 6a7bb49212..5ae3becc20 100644--- a/packages/core/squads/stores/index.ts+++ b/packages/core/squads/stores/index.ts@@ -1,5 +1,13 @@export {useSquadsViewStore,+ SQUAD_SCOPES,+ SQUAD_SORT_DEFAULT_DIRECTION,+ SQUAD_DEFAULT_HIDDEN_COLUMNS,+ EMPTY_SQUAD_FILTERS,type SquadsScope,type SquadsViewState,+ type SquadSortField,+ type SquadSortDirection,+ type SquadColumnKey,+ type SquadListFilters,} from "./view-store";diff --git a/packages/core/squads/stores/view-store.test.ts b/packages/core/squads/stores/view-store.test.tsindex ca2c8dabcd..af22d66ccd 100644--- a/packages/core/squads/stores/view-store.test.ts+++ b/packages/core/squads/stores/view-store.test.ts@@ -44,7 +44,7 @@ describe("useSquadsViewStore", () => {expect(useSquadsViewStore.getState().scope).toBe("all");});- it("partialize persists only scope under the workspace-namespaced key", async () => {+ it("partialize persists view prefs (no actions) under the workspace-namespaced key", async () => {setCurrentWorkspace("acme", "ws_a");await flush();useSquadsViewStore.getState().setScope("all");@@ -52,7 +52,14 @@ describe("useSquadsViewStore", () => {const raw = localStorage.getItem("multica_squads_view:acme");expect(raw).not.toBeNull();const parsed = JSON.parse(raw as string);- expect(parsed.state).toEqual({ scope: "all" });+ expect(Object.keys(parsed.state).sort()).toEqual([+ "filters",+ "hiddenColumns",+ "scope",+ "sortDirection",+ "sortField",+ ]);+ expect(parsed.state.scope).toBe("all");});it("rehydrates a different saved scope on workspace switch", async () => {diff --git a/packages/core/squads/stores/view-store.ts b/packages/core/squads/stores/view-store.tsindex 2e21bfc35d..f572be04b2 100644--- a/packages/core/squads/stores/view-store.ts+++ b/packages/core/squads/stores/view-store.ts@@ -8,30 +8,146 @@ import {} from "../../platform/workspace-storage";import { defaultStorage } from "../../platform/storage";+// View preferences for the squads list page: scope, sort, column visibility.+// Persisted per workspace, per user/device. No filters (the set is tiny);+// no search (scope-bearing list). Mirrors the agents/skills view stores.++// Scope is the ownership lens (creator-based). No "archived" scope: the+// list endpoint hard-filters archived squads and there is no restore+// endpoint, so archived squads can't be surfaced or managed.export type SquadsScope = "mine" | "all";+export const SQUAD_SCOPES: SquadsScope[] = ["mine", "all"];++export type SquadSortField = "name" | "members" | "created";++export type SquadSortDirection = "asc" | "desc";++/** Per-field direction applied when the user switches TO that field. */+export const SQUAD_SORT_DEFAULT_DIRECTION: Record<+ SquadSortField,+ SquadSortDirection+> = {+ name: "asc",+ members: "desc",+ created: "desc",+};++// User-hideable columns. Name and leader (the squad's defining relationship)+// are always visible.+export type SquadColumnKey = "members" | "creator" | "created";++/** Created (date) is opt-in. Creator ("Created by") is shown by default —+ * the user wants to see who made each squad. Note it's "Created by", NOT+ * "Owner": the squad creator holds no management rights (archiving is+ * workspace-admin only), so labelling it Owner would mislead. */+export const SQUAD_DEFAULT_HIDDEN_COLUMNS: SquadColumnKey[] = ["created"];++/** Multi-select filters — the categorical columns (leader, creator). Empty+ * array per dimension = inactive. */+export interface SquadListFilters {+ /** Leader agent ids. */+ leaders: string[];+ /** Creator member user ids. */+ creators: string[];+}++export const EMPTY_SQUAD_FILTERS: SquadListFilters = {+ leaders: [],+ creators: [],+};+export interface SquadsViewState {scope: SquadsScope;+ sortField: SquadSortField;+ sortDirection: SquadSortDirection;+ hiddenColumns: SquadColumnKey[];+ filters: SquadListFilters;setScope: (scope: SquadsScope) => void;+ /** Header click: toggles direction on the active field, otherwise switches+ * to the field with its default direction. */+ toggleSort: (field: SquadSortField) => void;+ /** Display panel select: switches field (default direction), no toggle. */+ setSortField: (field: SquadSortField) => void;+ setSortDirection: (direction: SquadSortDirection) => void;+ toggleColumn: (key: SquadColumnKey) => void;+ toggleFilter: (key: keyof SquadListFilters, value: string) => void;+ clearFilters: () => void;}+const DEFAULTS = {+ scope: "mine" as SquadsScope,+ sortField: "name" as SquadSortField,+ sortDirection: SQUAD_SORT_DEFAULT_DIRECTION.name,+ hiddenColumns: SQUAD_DEFAULT_HIDDEN_COLUMNS,+ filters: EMPTY_SQUAD_FILTERS,+};+export const useSquadsViewStore = create<SquadsViewState>()(persist((set) => ({- scope: "mine",+ ...DEFAULTS,setScope: (scope) => set({ scope }),+ toggleSort: (field) =>+ set((state) =>+ state.sortField === field+ ? {+ sortDirection: state.sortDirection === "asc" ? "desc" : "asc",+ }+ : {+ sortField: field,+ sortDirection: SQUAD_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortField: (field) =>+ set((state) =>+ state.sortField === field+ ? {}+ : {+ sortField: field,+ sortDirection: SQUAD_SORT_DEFAULT_DIRECTION[field],+ },+ ),+ setSortDirection: (direction) => set({ sortDirection: direction }),+ toggleColumn: (key) =>+ set((state) => ({+ hiddenColumns: state.hiddenColumns.includes(key)+ ? state.hiddenColumns.filter((k) => k !== key)+ : [...state.hiddenColumns, key],+ })),+ toggleFilter: (key, value) =>+ set((state) => {+ const list = state.filters[key] as string[];+ const next = list.includes(value)+ ? list.filter((v) => v !== value)+ : [...list, value];+ return { filters: { ...state.filters, [key]: next } };+ }),+ clearFilters: () => set({ filters: EMPTY_SQUAD_FILTERS }),}),{name: "multica_squads_view",- storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),- partialize: (state) => ({ scope: state.scope }),+ storage: createJSONStorage(() =>+ createWorkspaceAwareStorage(defaultStorage),+ ),+ partialize: (state) => ({+ scope: state.scope,+ sortField: state.sortField,+ sortDirection: state.sortDirection,+ hiddenColumns: state.hiddenColumns,+ filters: state.filters,+ }),// On rehydrate, if the new workspace has no persisted value, reset to- // the default "mine" instead of leaving the previous workspace's in-- // memory scope in place. Default merge keeps current state when- // persisted is undefined, which would leak "all" across workspaces.+ // the defaults instead of leaking the previous workspace's state.+ // Deep-merge filters so a pre-filters payload backfills defaults.merge: (persisted, current) => {- if (!persisted) return { ...current, scope: "mine" };- return { ...current, ...(persisted as Partial<SquadsViewState>) };+ if (!persisted) return { ...current, ...DEFAULTS };+ const p = persisted as Partial<SquadsViewState>;+ return {+ ...current,+ ...p,+ filters: { ...EMPTY_SQUAD_FILTERS, ...(p.filters ?? {}) },+ };},},),diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsindex 23a8949ede..658ab110a2 100644--- a/packages/core/types/autopilot.ts+++ b/packages/core/types/autopilot.ts@@ -39,6 +39,13 @@ export interface Autopilot {last_run_at: string | null;created_at: string;updated_at: string;+ // List-endpoint-only derived fields; absent on detail/create/update+ // responses and on older servers. Enabled triggers only. `trigger_kinds`+ // and `last_run_status` are server-driven strings — render unknown values+ // through a generic fallback, never an exhaustive switch.+ trigger_kinds?: string[];+ next_run_at?: string | null;+ last_run_status?: string | null;}export interface WebhookEventFilter {diff --git a/packages/ui/components/ui/checkbox.tsx b/packages/ui/components/ui/checkbox.tsxindex 3d3fd8e033..3986766d2f 100644--- a/packages/ui/components/ui/checkbox.tsx+++ b/packages/ui/components/ui/checkbox.tsx@@ -3,14 +3,15 @@import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"import { cn } from "@multica/ui/lib/utils"-import { CheckIcon } from "lucide-react"+import { CheckIcon, MinusIcon } from "lucide-react"-function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {+function Checkbox({ className, indeterminate, ...props }: CheckboxPrimitive.Root.Props) {return (<CheckboxPrimitive.Rootdata-slot="checkbox"+ indeterminate={indeterminate}className={cn(- "peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",+ "peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-indeterminate:border-primary data-indeterminate:bg-primary data-indeterminate:text-primary-foreground dark:data-indeterminate:bg-primary",className)}{...props}@@ -19,8 +20,7 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {data-slot="checkbox-indicator"className="grid place-content-center text-current transition-none [&>svg]:size-3.5">- <CheckIcon- />+ {indeterminate ? <MinusIcon /> : <CheckIcon />}</CheckboxPrimitive.Indicator></CheckboxPrimitive.Root>)diff --git a/packages/ui/components/ui/list-grid.tsx b/packages/ui/components/ui/list-grid.tsxnew file mode 100644index 0000000000..3d194273aa--- /dev/null+++ b/packages/ui/components/ui/list-grid.tsx@@ -0,0 +1,223 @@+"use client";++import { cloneElement } from "react";+import { ArrowDown, ArrowUp } from "lucide-react";++import { cn } from "../../lib/utils";++// Linear-style list grid. The container declares every column track once via+// a literal `grid-cols-[...]` class (plus responsive variants); the header and+// each row span the full template with `grid-cols-subgrid`, so column widths+// have a single source of truth and never drift between header, rows, and+// skeletons.+//+// Conventions the container class must follow:+// - First and last tracks are edge-padding columns (e.g. 1.25rem) so row+// hover backgrounds stay full-bleed while content aligns with page chrome.+// ListGridHeader/ListGridRow render the matching placeholder cells.+// - Responsiveness is TWO-ZONE and CONTAINER-query driven (wrap the ListGrid+// in a `@container` element; `@<bp>:` variants, never viewport `sm:`/`lg:`,+// so sidebars and split panes are accounted for):+// - ≥ @2xl: WYSIWYG — every user-enabled column renders. The grid carries+// `@2xl:min-w-[var(--…-minw)]` (Σ enabled tracks + gaps, computed from+// the page's column-width constants) and the wrapper has+// `overflow-x-auto`, so an over-provisioned column set scrolls instead+// of clipping. An enabled column must NEVER be silently hidden behind a+// width tier — that "dead toggle" bug shipped twice.+// - < @2xl: a static core template (name + one key column), no horizontal+// scroll, column toggles don't apply. Non-core cells carry+// `hidden @2xl:flex`; display:none cells drop out of subgrid+// auto-placement so the remaining cells fill the right tracks.+// - Keep the class a literal string in the page source so Tailwind sees it.++export type ListGridSortDirection = "asc" | "desc";++function ListGrid({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) {+ return (+ <div+ role="table"+ className={cn("grid w-full min-w-0 content-start gap-x-3", className)}+ {...props}+ />+ );+}++function ListGridHeader({+ className,+ children,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) {+ return (+ <div+ role="row"+ className={cn(+ "group/header sticky top-0 z-10 col-span-full grid h-9 grid-cols-subgrid items-center bg-background after:pointer-events-none after:absolute after:inset-x-0 after:top-full after:h-3 after:bg-gradient-to-b after:from-background after:to-transparent",+ className,+ )}+ {...props}+ >+ <span aria-hidden="true" />+ {children}+ <span aria-hidden="true" />+ </div>+ );+}++interface ListGridHeaderCellProps+ extends React.HTMLAttributes<HTMLDivElement> {+ /** Current sort state of this column; `false` when not the active sort. */+ sorted?: ListGridSortDirection | false;+ /** When provided the header renders as a sort button. */+ onSort?: () => void;+ align?: "left" | "right";+}++function ListGridHeaderCell({+ sorted = false,+ onSort,+ align = "left",+ className,+ children,+ ...props+}: ListGridHeaderCellProps) {+ if (!onSort) {+ return (+ <div+ className={cn(+ "flex min-w-0 items-center px-2 text-xs text-muted-foreground",+ align === "right" && "justify-end",+ className,+ )}+ {...props}+ >+ {children}+ </div>+ );+ }+ const Arrow = sorted === "asc" ? ArrowUp : ArrowDown;+ return (+ <div+ className={cn(+ "flex min-w-0 items-center px-2",+ align === "right" && "justify-end",+ className,+ )}+ {...props}+ >+ <button+ type="button"+ onClick={onSort}+ className={cn(+ "group/sort flex h-6 items-center gap-0.5 rounded-md text-xs transition-colors",+ // Active sort column: emphasis via weight + full foreground color+ // only — no background, so the header row stays quiet.+ sorted+ ? "font-medium text-foreground"+ : "text-muted-foreground hover:bg-accent hover:text-accent-foreground",+ align === "right" ? "-mr-1.5 flex-row-reverse pl-1 pr-1.5" : "-ml-1.5 pl-1.5 pr-1",+ )}+ >+ {children}+ <Arrow+ className={cn(+ "size-3 shrink-0",+ sorted ? "opacity-100" : "opacity-0 group-hover/sort:opacity-50",+ )}+ />+ </button>+ </div>+ );+}++// Rows area — a plain subgrid passthrough that groups the rows and carries+// the virtualization padding. It does NOT scroll: both scroll axes live on+// the single outer wrapper (`overflow-auto @container`), with the sticky+// header pinning inside that scroller. Splitting horizontal scrolling+// (wrapper) from vertical scrolling (this element) connected by an h-full+// percentage bridge caused a non-converging layout loop (flickering double+// scrollbars), clipped the last row under the horizontal scrollbar, and+// let a classic vertical scrollbar shift row tracks relative to the header.+function ListGridBody({+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ className={cn(+ "col-span-full grid grid-cols-subgrid content-start",+ className,+ )}+ {...props}+ />+ );+}++// Bottom clearance appended to the rows area's padding so the last row can+// scroll clear of floating UI anchored to the pane's bottom edge (the chat+// FAB at bottom-right covers ~48px; the batch toolbar ~62px). One row of+// extra runway keeps both off the final row's kebab.+export const LIST_GRID_BOTTOM_CLEARANCE = 64;++interface ListGridRowProps extends React.HTMLAttributes<HTMLElement> {+ /**+ * Base UI-style render prop: pass an element (e.g. `<AppLink href={...} />`)+ * to use it as the row root; the row classes and cells are merged onto it.+ */+ render?: React.ReactElement<{+ className?: string;+ children?: React.ReactNode;+ }>;+}++function ListGridRow({ render, className, children, ...props }: ListGridRowProps) {+ const rowClassName = cn(+ "group/row col-span-full grid h-12 grid-cols-subgrid items-center transition-colors hover:bg-accent/40",+ className,+ );+ const content = (+ <>+ <span aria-hidden="true" />+ {children}+ <span aria-hidden="true" />+ </>+ );+ if (render) {+ return cloneElement(+ render,+ { ...props, className: cn(rowClassName, render.props.className) },+ content,+ );+ }+ return (+ <div className={rowClassName} {...props}>+ {content}+ </div>+ );+}++// Cells and header cells carry the same default horizontal padding so the+// header can never drift out of alignment with row content. Structural+// columns (checkbox, kebab) opt out with `px-0`.+function ListGridCell({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) {+ return (+ <div+ className={cn("flex min-w-0 items-center px-2", className)}+ {...props}+ />+ );+}++export {+ ListGrid,+ ListGridBody,+ ListGridHeader,+ ListGridHeaderCell,+ ListGridRow,+ ListGridCell,+};diff --git a/packages/views/agents/components/agent-columns.tsx b/packages/views/agents/components/agent-columns.tsxdeleted file mode 100644index ee29cd2944..0000000000--- a/packages/views/agents/components/agent-columns.tsx+++ /dev/null@@ -1,399 +0,0 @@-"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,- VISIBILITY_TOOLTIP,-} 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";-import { useT } from "../../i18n";--// 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 owns this agent (drives the "You" badge).- isOwnedByMe: boolean;- // 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 and Runtime columns have `meta.grow: true` so DataTable skips-// their inline widths until the user resizes them. Fixed table-layout splits-// the leftover space between them, which keeps Agent from monopolising wide-// viewports while still giving both columns a real floor.-//-// The grow columns also keep their `size` values even though those widths-// are skipped for initial rendering. TanStack folds them into-// `table.getTotalSize()`, which DataTable applies as the table's `min-width`.-// That's how the grow columns get real floors: when the viewport drops below-// the summed column sizes, the table refuses to shrink further and the-// container scrolls instead.-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;--type ColumnHeaderT = ReturnType<typeof useT<"agents">>["t"];--function makeHeaderRenderer(t: ColumnHeaderT, key: "agent" | "status" | "workload" | "runtime" | "activity_7d" | "runs") {- return key === "runs"- ? () => <div className="text-right">{t(($) => $.columns.runs)}</div>- : () => t(($) => $.columns[key]);-}--export function createAgentColumns({- onDuplicate,- t,-}: {- onDuplicate: (agent: Agent) => void;- t: ColumnHeaderT;-}): ColumnDef<AgentRow>[] {- return [- {- id: "agent",- header: makeHeaderRenderer(t, "agent"),- size: COL_WIDTHS.agent,- meta: { grow: true },- cell: ({ row }) => <AgentNameCell row={row.original} />,- },- {- id: "status",- header: makeHeaderRenderer(t, "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: makeHeaderRenderer(t, "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: makeHeaderRenderer(t, "runtime"),- size: COL_WIDTHS.runtime,- meta: { grow: true },- cell: ({ row }) => <RuntimeCell row={row.original} />,- },- {- id: "activity",- header: makeHeaderRenderer(t, "activity_7d"),- size: COL_WIDTHS.activity,- cell: ({ row }) => <ActivityCell row={row.original} />,- },- {- id: "runs",- header: makeHeaderRenderer(t, "runs"),- 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,- enableResizing: false,- 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 { t } = useT("agents");- const { agent, ownerIdToShow, isOwnedByMe } = 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>- {VISIBILITY_TOOLTIP.private}- </TooltipContent>- </Tooltip>- )}- {isOwnedByMe && !ownerIdToShow && (- <span className="shrink-0 rounded bg-muted px-1 text-[10px] font-medium text-muted-foreground">- {t(($) => $.row.you)}- </span>- )}- {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">- {t(($) => $.row.archived)}- </span>- )}- </div>- <div- className={`mt-0.5 truncate text-xs ${- agent.description- ? "text-muted-foreground"- : "italic text-muted-foreground/50"- }`}- >- {agent.description || t(($) => $.row.no_description)}- </div>- </div>- </div>- );-}--function AvailabilityCell({- presence,-}: {- presence: AgentPresenceDetail | null | undefined;-}) {- const { t } = useT("agents");- 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}`}>{t(($) => $.availability[presence.availability])}</span>- </span>- );-}--function WorkloadCell({- presence,-}: {- presence: AgentPresenceDetail | null | undefined;-}) {- const { t } = useT("agents");- 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}`}>{t(($) => $.workload[presence.workload])}</span>- {counts && (- <span className="truncate text-muted-foreground">{counts}</span>- )}- </span>- );-}--function RuntimeCell({ row }: { row: AgentRow }) {- const { t } = useT("agents");- const { agent, runtime } = row;- const isCloud = agent.runtime_mode === "cloud";- const RuntimeIcon = isCloud ? Cloud : Monitor;- const runtimeLabel = runtime?.name ?? (isCloud ? t(($) => $.row.fallback_runtime_cloud) : t(($) => $.row.fallback_runtime_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 { t } = useT("agents");- const summary = summarizeActivityWindow(activity, 7);- const { totalRuns, totalFailed } = summary;- const { daysSinceCreated } = activity;-- const isPartial = daysSinceCreated < 7;- const headerText = isPartial- ? daysSinceCreated === 0- ? t(($) => $.activity_tooltip.created_today)- : t(($) => $.activity_tooltip.created_days_ago, { count: daysSinceCreated })- : t(($) => $.activity_tooltip.last_7_days);-- let bodyText: string;- if (totalRuns === 0) {- bodyText = t(($) => $.activity_tooltip.no_activity);- } else {- const runsText = t(($) => $.activity_tooltip.runs, { count: totalRuns });- const failedFragment =- totalFailed > 0- ? t(($) => $.activity_tooltip.failed_suffix, {- count: totalFailed,- percent: Math.round((totalFailed / totalRuns) * 100),- })- : "";- bodyText = `${runsText}${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-list-toolbar.tsx b/packages/views/agents/components/agent-list-toolbar.tsxnew file mode 100644index 0000000000..c6ac0ba79f--- /dev/null+++ b/packages/views/agents/components/agent-list-toolbar.tsx@@ -0,0 +1,551 @@+"use client";++import {+ ArrowDown,+ ArrowUp,+ ChevronDown,+ Filter,+ X,+} from "lucide-react";+import type { AgentAvailability } from "@multica/core/agents";+import type { MemberWithUser } from "@multica/core/types";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";+import {+ AGENT_SCOPES,+ type AgentColumnKey,+ type AgentListFilters,+ type AgentsScope,+ type AgentSortDirection,+ type AgentSortField,+} from "@multica/core/agents/stores";+import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { Switch } from "@multica/ui/components/ui/switch";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";+import { availabilityConfig } from "../presence";+import { useT } from "../../i18n";+import type { AgentListRow } from "./agents-page";++const COLUMN_KEYS: AgentColumnKey[] = [+ "status",+ "owner",+ "runtime",+ "lastActive",+ "runs",+ "model",+ "created",+];++const SORT_FIELDS: AgentSortField[] = [+ "lastActive",+ "name",+ "runs",+ "created",+];++const AVAILABILITY_VALUES: AgentAvailability[] = [+ "online",+ "unstable",+ "offline",+];++export function countActiveFilterDimensions(+ filters: AgentListFilters,+): number {+ let count = 0;+ if (filters.availability.length > 0) count++;+ if (filters.runtimes.length > 0) count++;+ if (filters.owners.length > 0) count++;+ if (filters.models.length > 0) count++;+ return count;+}++export function AgentListToolbar({+ scope,+ onScopeChange,+ scopeCounts,+ filters,+ onToggleFilter,+ onClearFilters,+ sortField,+ sortDirection,+ onSortFieldChange,+ onSortDirectionChange,+ hiddenColumns,+ onToggleColumn,+ allRows,+ members,+ visibleCount,+}: {+ scope: AgentsScope;+ onScopeChange: (scope: AgentsScope) => void;+ /** Per-scope totals from the FULL set — scope counts ignore filters. */+ scopeCounts: Record<AgentsScope, number>;+ filters: AgentListFilters;+ onToggleFilter: (key: keyof AgentListFilters, value: string) => void;+ onClearFilters: () => void;+ sortField: AgentSortField;+ sortDirection: AgentSortDirection;+ onSortFieldChange: (field: AgentSortField) => void;+ onSortDirectionChange: (direction: AgentSortDirection) => void;+ hiddenColumns: AgentColumnKey[];+ onToggleColumn: (key: AgentColumnKey) => void;+ /** Rows within the current scope, unfiltered — filter option lists and+ * counts derive from this set. */+ allRows: AgentListRow[];+ members: MemberWithUser[];+ /** Rows surviving the filters — shown as "n / total" when narrowed. */+ visibleCount: number;+}) {+ const { t } = useT("agents");++ const activeCount = countActiveFilterDimensions(filters);+ const hasActiveFilters = activeCount > 0;++ // Option lists with counts, derived from the scope's unfiltered rows so+ // toggling one dimension doesn't make the others' options vanish.+ const availabilityCounts = new Map<string, number>();+ const runtimeOptions = new Map<string, { name: string; count: number }>();+ for (const row of allRows) {+ if (row.presence) {+ availabilityCounts.set(+ row.presence.availability,+ (availabilityCounts.get(row.presence.availability) ?? 0) + 1,+ );+ }+ const rt = row.runtime;+ if (rt) {+ const entry = runtimeOptions.get(rt.id);+ if (entry) entry.count += 1;+ else runtimeOptions.set(rt.id, { name: rt.name, count: 1 });+ }+ }++ // Owner options: members who own at least one agent in the current scope.+ const memberById = new Map(members.map((m) => [m.user_id, m]));+ const ownerCounts = new Map<string, number>();+ const modelCounts = new Map<string, number>();+ for (const row of allRows) {+ const oid = row.agent.owner_id;+ if (oid) ownerCounts.set(oid, (ownerCounts.get(oid) ?? 0) + 1);+ const model = row.agent.model;+ if (model) modelCounts.set(model, (modelCounts.get(model) ?? 0) + 1);+ }++ const SCOPE_LABELS: Record<AgentsScope, string> = {+ mine: t(($) => $.scope.mine),+ all: t(($) => $.scope.all),+ archived: t(($) => $.scope.archived),+ };++ const SORT_LABELS: Record<AgentSortField, string> = {+ lastActive: t(($) => $.columns.last_active),+ name: t(($) => $.columns.agent),+ runs: t(($) => $.columns.runs),+ created: t(($) => $.columns.created),+ };++ const COLUMN_LABELS: Record<AgentColumnKey, string> = {+ status: t(($) => $.columns.status),+ owner: t(($) => $.columns.owner),+ runtime: t(($) => $.columns.runtime),+ lastActive: t(($) => $.columns.last_active),+ runs: t(($) => $.columns.runs),+ model: t(($) => $.columns.model),+ created: t(($) => $.columns.created),+ };+ const sortLabel = SORT_LABELS[sortField];++ const countBadge = (n: number) => (+ <span className="ml-auto pl-3 text-xs text-muted-foreground">{n}</span>+ );++ return (+ <div className="flex h-12 shrink-0 items-center justify-between gap-2 px-5">+ {/* Left: scope buttons + result count. Scope mixes the ownership lens+ (mine/all) with the archived lifecycle stage; no search box (scope+ partitions the small set). Button styling and the <md dropdown+ collapse follow the issues header's scope buttons. */}+ <div className="flex min-w-0 items-center gap-2">+ <div className="hidden shrink-0 items-center gap-1 md:flex">+ {AGENT_SCOPES.map((s) => (+ <Button+ key={s}+ variant="outline"+ size="sm"+ className={+ scope === s+ ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"+ : "gap-1.5 text-muted-foreground"+ }+ onClick={() => onScopeChange(s)}+ >+ {SCOPE_LABELS[s]}+ <span className="tabular-nums text-xs text-muted-foreground/70">+ {scopeCounts[s]}+ </span>+ </Button>+ ))}+ </div>++ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="shrink-0 gap-1 text-muted-foreground md:hidden"+ >+ <span className="truncate">{SCOPE_LABELS[scope]}</span>+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={scope}+ onValueChange={(value) => onScopeChange(value as AgentsScope)}+ >+ {AGENT_SCOPES.map((s) => (+ <DropdownMenuRadioItem key={s} value={s}>+ {SCOPE_LABELS[s]}+ <span className="ml-2 tabular-nums text-xs text-muted-foreground/70">+ {scopeCounts[s]}+ </span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>++ {hasActiveFilters && (+ <span+ title={t(($) => $.toolbar.result_count_title)}+ className="hidden shrink-0 text-xs tabular-nums text-muted-foreground md:inline"+ >+ {visibleCount} / {allRows.length}+ </span>+ )}+ </div>++ <div className="flex shrink-0 items-center gap-1">+ {/* Filter */}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant={hasActiveFilters ? "default" : "outline"}+ size="sm"+ className={+ hasActiveFilters+ ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"+ : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ }+ >+ <Filter className="size-3.5" />+ {hasActiveFilters ? (+ <>+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_active_count, {+ count: activeCount,+ })}+ </span>+ <span className="tabular-nums md:hidden">+ {activeCount}+ </span>+ </>+ ) : (+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_label)}+ </span>+ )}+ {hasActiveFilters && (+ <span+ role="button"+ tabIndex={-1}+ aria-label={t(($) => $.toolbar.clear_filters)}+ className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onClearFilters();+ }}+ onPointerDown={(e) => e.stopPropagation()}+ >+ <X className="size-3" />+ </span>+ )}+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-auto">+ {/* Availability */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_availability)}+ </span>+ {filters.availability.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.availability.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-44">+ {AVAILABILITY_VALUES.map((value) => {+ const visual = availabilityConfig[value];+ return (+ <DropdownMenuCheckboxItem+ key={value}+ checked={filters.availability.includes(value)}+ onCheckedChange={() =>+ onToggleFilter("availability", value)+ }+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck+ checked={filters.availability.includes(value)}+ />+ <span+ className={`size-1.5 shrink-0 rounded-full ${visual.dotClass}`}+ />+ {t(($) => $.availability[value])}+ {countBadge(availabilityCounts.get(value) ?? 0)}+ </DropdownMenuCheckboxItem>+ );+ })}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Runtime */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_runtime)}+ </span>+ {filters.runtimes.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.runtimes.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {[...runtimeOptions.entries()].map(([id, { name, count }]) => (+ <DropdownMenuCheckboxItem+ key={id}+ checked={filters.runtimes.includes(id)}+ onCheckedChange={() => onToggleFilter("runtimes", id)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.runtimes.includes(id)} />+ <span className="min-w-0 truncate">{name}</span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Owner — the same person-axis as the Mine scope. Picking an+ owner here leaves the clean "mine" view for "all" (store+ rule), so Mine + owner never coexist. */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_owner)}+ </span>+ {filters.owners.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.owners.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {[...ownerCounts.entries()].map(([userId, count]) => {+ const m = memberById.get(userId);+ return (+ <DropdownMenuCheckboxItem+ key={userId}+ checked={filters.owners.includes(userId)}+ onCheckedChange={() => onToggleFilter("owners", userId)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.owners.includes(userId)} />+ <ActorAvatar+ name={m?.name ?? userId.slice(0, 8)}+ initials={(m?.name ?? "?").slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(m?.avatar_url ?? null)}+ size={16}+ />+ <span className="min-w-0 truncate">+ {m?.name ?? userId.slice(0, 8)}+ </span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ );+ })}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Model — runtime-native model id (categorical column → filter) */}+ {modelCounts.size > 0 && (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_model)}+ </span>+ {filters.models.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.models.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-44 overflow-y-auto">+ {[...modelCounts.entries()].map(([model, count]) => (+ <DropdownMenuCheckboxItem+ key={model}+ checked={filters.models.includes(model)}+ onCheckedChange={() => onToggleFilter("models", model)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.models.includes(model)} />+ <span className="min-w-0 truncate">{model}</span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}+ </DropdownMenuContent>+ </DropdownMenu>++ {/* Display settings */}+ <Popover>+ <Tooltip>+ <PopoverTrigger+ render={+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ <span className="hidden md:inline">{sortLabel}</span>+ </Button>+ }+ />+ }+ />+ <TooltipContent side="bottom">+ {t(($) => $.toolbar.display)}+ </TooltipContent>+ </Tooltip>+ <PopoverContent align="end" className="w-64 p-0">+ <div className="border-b px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.sort_by)}+ </span>+ <div className="mt-2 flex items-center gap-1.5">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="flex-1 justify-between text-xs"+ >+ {sortLabel}+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={sortField}+ onValueChange={(v) =>+ onSortFieldChange(v as AgentSortField)+ }+ >+ {SORT_FIELDS.map((field) => (+ <DropdownMenuRadioItem key={field} value={field}>+ {SORT_LABELS[field]}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ <Button+ variant="outline"+ size="icon-sm"+ onClick={() =>+ onSortDirectionChange(+ sortDirection === "asc" ? "desc" : "asc",+ )+ }+ title={+ sortDirection === "asc"+ ? t(($) => $.toolbar.direction_asc)+ : t(($) => $.toolbar.direction_desc)+ }+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ </Button>+ </div>+ </div>++ <div className="px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.section_columns)}+ </span>+ <div className="mt-2 space-y-2">+ {COLUMN_KEYS.map((key) => (+ <label+ key={key}+ className="flex cursor-pointer items-center justify-between"+ >+ <span className="text-sm">{COLUMN_LABELS[key]}</span>+ <Switch+ size="sm"+ checked={!hiddenColumns.includes(key)}+ onCheckedChange={() => onToggleColumn(key)}+ />+ </label>+ ))}+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ </div>+ );+}diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsxindex bd7572a7a8..f54a6f194d 100644--- a/packages/views/agents/components/agents-page.tsx+++ b/packages/views/agents/components/agents-page.tsx@@ -1,29 +1,44 @@"use client";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";import {AlertCircle,- ArrowLeft,- ArrowUpDown,+ Archive,+ ArchiveRestore,Bot,+ Loader2,+ Lock,Plus,- Search,+ X,} 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 { useVirtualizer } from "@tanstack/react-virtual";+import { toast } from "sonner";+import type {+ Agent,+ AgentRuntime,+ CreateAgentRequest,+ MemberWithUser,+} from "@multica/core/types";import {- type AgentAvailability,+ type AgentActivity,agentRunCounts30dOptions,- summarizeActivityWindow,useWorkspaceActivityMap,useWorkspacePresenceMap,+ VISIBILITY_TOOLTIP,+ type AgentPresenceDetail,} from "@multica/core/agents";-import { useAgentsViewStore } from "@multica/core/agents/stores";+import {+ useAgentsViewStore,+ AGENT_DEFAULT_HIDDEN_COLUMNS,+ AGENT_SCOPES,+ type AgentColumnKey,+ type AgentsScope,+ type AgentSortField,+} from "@multica/core/agents/stores";import { api } from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";-import { canAssignAgentToIssue } from "@multica/core/permissions";import { useWorkspacePaths } from "@multica/core/paths";import {agentListOptions,@@ -32,608 +47,134 @@ import {} from "@multica/core/workspace/queries";import { runtimeListOptions } from "@multica/core/runtimes";import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@multica/ui/components/ui/dropdown-menu";-import { Input } from "@multica/ui/components/ui/input";+ LIST_GRID_BOTTOM_CLEARANCE,+ ListGrid,+ ListGridBody,+ ListGridCell,+ ListGridHeader,+ ListGridHeaderCell,+ ListGridRow,+ type ListGridSortDirection,+} from "@multica/ui/components/ui/list-grid";import { Skeleton } from "@multica/ui/components/ui/skeleton";-import { DataTable } from "@multica/ui/components/ui/data-table";-import { useNavigation } from "../../navigation";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { AppLink, useNavigation } from "../../navigation";+import { ActorAvatar } from "../../common/actor-avatar";import { PageHeader } from "../../layout/page-header";-import { availabilityConfig, availabilityOrder } from "../presence";+import { availabilityConfig } from "../presence";import { CreateAgentDialog } from "./create-agent-dialog";-import { type AgentRow, createAgentColumns } from "./agent-columns";+import { AgentRowActions } from "./agent-row-actions";+import { AgentListToolbar } from "./agent-list-toolbar";import { useT } from "../../i18n";-import { matchesPinyin } from "../../editor/extensions/pinyin-match";-import {- buildRuntimeMachines,- type RuntimeMachine,-} from "../../runtimes/components/runtime-machines";-import { RuntimeMachineFilterDropdown } from "./runtime-machine-filter-dropdown";-// Filter axes:+// Column template — single source of truth for header, rows, and skeletons.+// Same conventions as the skills/autopilots lists (see list-grid.tsx):+// deterministic var-width tracks, two-zone responsiveness (≥@2xl WYSIWYG+// with min-width + horizontal-scroll escape valve; <@2xl static core set of+// name + status, toggles don't apply).//-// 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.-// Runtime machine = "Which host is the agent bound to?" — dropdown-// filter grouped by section (Local / Remote / Cloud).-// Mirrors the machine grouping on the Runtimes page-// so a user can drill from a machine into the agents-// hosted on it.-// 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 SortKey = "recent" | "name" | "runs" | "created";-const SORT_KEYS: SortKey[] = ["recent", "name", "runs", "created"];-const SORT_LABEL_KEY: Record<SortKey, "label_recent" | "label_name" | "label_runs" | "label_created"> = {- recent: "label_recent",- name: "label_name",- runs: "label_runs",- created: "label_created",-};--export interface AgentsPageProps {- /**- * Desktop-only daemon id for the current host. Forwarded into- * `buildRuntimeMachines` so the local machine renders under the- * "Local" section (rather than "Remote") on the same host that owns- * the daemon. Web omits this — the SaaS shell doesn't bundle a- * daemon, so the local section never has a real candidate anyway.- */- localDaemonId?: string | null;- /**- * Desktop-only friendly device name for the local daemon. Paired- * with `localDaemonId` for the "Local" section title; web omits.- */- localMachineName?: string | null;- /**- * Desktop-only signal that this host always owns a local machine- * row, even when no server-side runtime is currently registered- * (daemon stopped, not yet started, or runtime GC'd). Mirrors- * `RuntimesPage.hasLocalMachine`. The filter dropdown uses the- * synthesized placeholder to keep "Local" available for selection- * in the empty window.- */- hasLocalMachine?: boolean;-}--export function AgentsPage({- localDaemonId = null,- localMachineName = null,- hasLocalMachine = false,-}: AgentsPageProps = {}) {- const { t } = useT("agents");- const wsId = useWorkspaceId();- const paths = useWorkspacePaths();- const navigation = useNavigation();- const qc = useQueryClient();- const currentUser = useAuthStore((s) => s.user);-- const {- data: agents = [],- isLoading,- error: listError,- refetch: refetchList,- } = useQuery(agentListOptions(wsId));- const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(- runtimeListOptions(wsId),- );- const { data: members = [] } = useQuery(memberListOptions(wsId));- const { data: runCountsRaw = [] } = useQuery(agentRunCounts30dOptions(wsId));-- // Single source of truth for derived agent state. The hook owns the- // 30s tick + the runtime/null/task orchestration; the page only reads- // the resulting Maps. Replaces the 24-line useMemo presenceMap +- // 12-line activityMap that lived here previously.- const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);- const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);-- const [view, setView] = useState<View>("active");- // Scope (Mine/All) is persisted per workspace so it survives list →- // detail → back navigation. Default is "mine" on first visit.- const scope = useAgentsViewStore((s) => s.scope);- const setScope = useAgentsViewStore((s) => s.setScope);- const [availabilityFilter, setAvailabilityFilter] =- useState<AvailabilityFilter>("all");- // `null` means "all runtimes" (the default). When set, the value is a- // RuntimeMachine id from `buildRuntimeMachines` (the same grouping the- // Runtimes page uses), so the user can drill from a machine on that- // page into the agents bound to it.- const [runtimeMachineId, setRuntimeMachineId] = useState<string | null>(null);- const [sort, setSort] = useState<SortKey>("recent");- const [search, setSearch] = useState("");- const [showCreate, setShowCreate] = useState(false);- // When set, the Create dialog opens pre-populated with this agent's- // config — driven by the row-level "Duplicate" action. We keep this- // separate from `showCreate` so a stray null-template doesn't open the- // dialog: the dialog opens iff `showCreate || duplicateTemplate`.- const [duplicateTemplate, setDuplicateTemplate] = useState<Agent | null>(- null,- );-- const runtimesById = useMemo(() => {- const m = new Map<string, AgentRuntime>();- for (const r of runtimes) m.set(r.id, r);- return m;- }, [runtimes]);-- const runCountsById = useMemo(() => {- const m = new Map<string, number>();- for (const r of runCountsRaw) m.set(r.agent_id, r.run_count);- return m;- }, [runCountsRaw]);-- // Workspace role of the current user, used to gate row-level "manage"- // operations (archive / cancel-tasks). Mirrors the back-end's- // canManageAgent rule: workspace owner/admin OR the agent's owner.- const myRole = useMemo(() => {- if (!currentUser) return null;- return members.find((m) => m.user_id === currentUser.id)?.role ?? null;- }, [members, currentUser]);- const isWorkspaceAdmin = myRole === "owner" || myRole === "admin";-- // Layer 1a — view (active / archived).- const inView = useMemo(- () =>- agents.filter((a) =>- view === "archived" ? !!a.archived_at : !a.archived_at,- ),- [agents, view],- );-- // Layer 1b — visibility. Personal (visibility=private) agents owned by- // someone else are hidden from regular members; workspace owners/admins- // still see everything. Mirrors the assign-to-issue gate so the list- // only ever shows agents the user could actually act on. Backend keeps- // returning all agents, so admin tools (and the API itself) are- // unaffected — this is a UI-only filter.- const visibleInView = useMemo(() => {- return inView.filter((a) =>- canAssignAgentToIssue(a, {- userId: currentUser?.id ?? null,- role: myRole,- }).allowed,- );- }, [inView, currentUser?.id, myRole]);-- // Layer 1c — ownership scope. Counts shown on the segment are- // computed against the visibleInView set so the numbers always reflect- // "what would I see if I clicked this".- const scopeCounts = useMemo(() => {- let mine = 0;- if (currentUser) {- for (const a of visibleInView) {- if (a.owner_id === currentUser.id) mine += 1;- }- }- return { all: visibleInView.length, mine };- }, [visibleInView, currentUser]);+// Agents are identity-type entities (few, avatar + persona), so rows are+// the TWO-LINE form: avatar left, name + description right, 64px tall —+// the documented exception to the single-line management-list rule.+const GRID_COLS =+ "grid-cols-[0.75rem_1rem_minmax(120px,1fr)_var(--agc-status)_1.75rem_0.75rem] " ++ "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_var(--agc-status)_var(--agc-owner)_var(--agc-runtime)_var(--agc-lastactive)_var(--agc-runs)_var(--agc-model)_var(--agc-created)_1.75rem_0.75rem]";- 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 visibleInView;- if (scope === "all" || !currentUser) return visibleInView;- return visibleInView.filter((a) => a.owner_id === currentUser.id);- }, [visibleInView, scope, currentUser, view]);+// Two-line rows; the virtualizer's fixed-size contract.+const ROW_HEIGHT = 64;- // Build the workspace's runtime machines (local / remote / cloud- // groupings) the same way the Runtimes page does, so the filter- // dropdown labels match the machines the user sees there. The- // `now` clock only affects health rollups — we don't render health- // chips in this list, so a snapshot from mount time is fine. We- // also forward `localDaemonId` / `localMachineName` /- // `hasLocalMachine` so the Local section (and the synthesized- // placeholder on Desktop) appears here the same way it does on the- // Runtimes page; `currentUserId` gates device-name consolidation- // so a remote member's identically-named host doesn't get claimed- // as the viewer's local machine.- const [machinesNow] = useState(() => Date.now());- const machines = useMemo(- () =>- buildRuntimeMachines(runtimes, {- now: machinesNow,- localDaemonId,- localMachineName,- currentUserId: currentUser?.id ?? null,- ensureLocalMachine: hasLocalMachine,- }),- [runtimes, machinesNow, localDaemonId, localMachineName, currentUser?.id, hasLocalMachine],- );-- // Reverse map: runtime_id → machine id. Lets the filter step look up- // an agent's machine in O(1). Built off the machine grouping rather- // than `runtimesById` so a runtime's machine identity matches the- // dropdown labels (machines dedupe across providers by daemon).- const runtimeIdToMachineId = useMemo(() => {- const m = new Map<string, string>();- for (const machine of machines) {- for (const r of machine.runtimes) m.set(r.id, machine.id);- }- return m;- }, [machines]);-- // Per-machine agent counts in `inScope` — used both for the chip- // badges in the dropdown AND to make the runtime filter respect the- // current scope (e.g. "Mine" only shows machines that have one of- // my agents). Computed against `inScope` (not `visibleInView`).- // Agents whose runtime doesn't map to a current machine- // (e.g. bound to a GC'd runtime) are intentionally skipped here- // — they still appear in the list when the filter is "All- // runtimes", just not bucketed under any per-machine chip. The- // "All runtimes" badge uses `inScope.length` directly so it stays- // consistent with the unfiltered list.- const agentCountByMachine = useMemo(() => {- const counts = new Map<string, number>();- for (const a of inScope) {- const machineId = runtimeIdToMachineId.get(a.runtime_id);- if (!machineId) continue;- counts.set(machineId, (counts.get(machineId) ?? 0) + 1);- }- return counts;- }, [inScope, runtimeIdToMachineId]);-- // If the selected machine is GC'd while we're on the page (daemon- // stopped, runtime deleted), the filter would zero out the list with- // no UI to clear it. Bounce back to "all" so the user always sees- // something actionable.- useEffect(() => {- if (- runtimeMachineId !== null &&- !machines.some((machine) => machine.id === runtimeMachineId)- ) {- setRuntimeMachineId(null);- }- }, [runtimeMachineId, machines]);+// Single source for hideable column widths: track vars and the grid's+// min-width derive from the same numbers.+const COLUMN_WIDTHS: Record<AgentColumnKey, number> = {+ // Sized for the worst case "Online · 2 tasks" (~140px incl. padding);+ // idle rows show only the dot + label and leave some in-track slack.+ status: 144,+ owner: 144,+ runtime: 144,+ lastActive: 120,+ runs: 88,+ model: 120,+ created: 104,+};- // Resolved title for the current machine filter — used by the- // no-matches state so the user sees "No agents on `dev.local`" rather- // than a bare "No agents match this filter" when the search is empty- // but the machine filter is doing the narrowing.- const selectedMachine = useMemo(- () =>- runtimeMachineId === null- ? null- : machines.find((machine) => machine.id === runtimeMachineId) ?? null,- [runtimeMachineId, machines],- );+// Fixed tracks (edges 12+12, checkbox 16, name min 200, kebab 28) plus the+// 11 gap-x-3 gaps between the wide template's 12 tracks (zero-width tracks+// still carry gaps).+const FIXED_TRACKS_WIDTH = 268 + 11 * 12;- // Machine-scoped list: `inScope` narrowed by the selected runtime- // machine, but NOT by the availability chip or search. The- // availability row needs this intermediate step so its chips show- // counts for "agents on this machine", not "agents on every machine"- // — once a machine is selected, the chips further narrow the- // already-machine-scoped list. The `inScope.length` total stays- // available for the dropdown's "All runtimes" badge (the count the- // user would see if they cleared the machine filter).- const inScopeOnMachine = useMemo(() => {- if (view !== "active") return inScope;- if (runtimeMachineId === null) return inScope;- return inScope.filter(- (a) => runtimeIdToMachineId.get(a.runtime_id) === runtimeMachineId,+function columnTrackVars(+ isVisible: (key: AgentColumnKey) => boolean,+): React.CSSProperties {+ const width = (key: AgentColumnKey) =>+ isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";+ const minWidth =+ FIXED_TRACKS_WIDTH ++ (Object.keys(COLUMN_WIDTHS) as AgentColumnKey[]).reduce(+ (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),+ 0,);- }, [inScope, view, runtimeMachineId, runtimeIdToMachineId]);-- // Final cut — availability chip + search. Starts from- // `inScopeOnMachine` so a selected machine filter is already- // applied; the availability chip and search refine within it.- const filteredAgents = useMemo(() => {- const q = search.trim().toLowerCase();- return inScopeOnMachine.filter((a) => {- // 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 (detail?.availability !== availabilityFilter) return false;- }- if (q) {- if (- !a.name.toLowerCase().includes(q) &&- !matchesPinyin(a.name, q) &&- !(a.description ?? "").toLowerCase().includes(q)- ) {- return false;- }- }- return true;- });- }, [- inScopeOnMachine,- view,- availabilityFilter,- presenceMap,- search,- ]);-- // Per-availability counts for the chip badges. Computed against- // `inScopeOnMachine` (ignoring the availability filter itself) so- // the numbers reflect "if I clicked this chip, this many agents- // would match on the currently-selected machine" rather than- // collapsing to 0 for the unselected chips.- const availabilityCounts = useMemo(() => {- const counts: Record<AgentAvailability, number> = {- online: 0,- unstable: 0,- offline: 0,- // Active-view scope excludes archived agents, so this bucket stays 0- // here; present only to satisfy the exhaustive availability Record.- archived: 0,- };- for (const a of inScopeOnMachine) {- const detail = presenceMap.get(a.id);- if (!detail) continue;- counts[detail.availability] += 1;- }- return counts;- }, [inScopeOnMachine, presenceMap]);-- const sortedAgents = useMemo(() => {- const xs = [...filteredAgents];- switch (sort) {- case "name":- xs.sort((a, b) => a.name.localeCompare(b.name));- break;- case "runs":- xs.sort(- (a, b) =>- (runCountsById.get(b.id) ?? 0) - (runCountsById.get(a.id) ?? 0),- );- break;- case "created":- xs.sort((a, b) => +new Date(b.created_at) - +new Date(a.created_at));- break;- case "recent":- default:- // "Recent activity" prioritises 7d total completions (the same- // window the row's sparkline shows), then 30d run count, then- // created_at. We don't have a precise last-touched timestamp on- // Agent today; this approximates it closely without a new column.- xs.sort((a, b) => {- const aSum = summarizeActivityWindow(- activityMap.get(a.id),- 7,- ).totalRuns;- const bSum = summarizeActivityWindow(- activityMap.get(b.id),- 7,- ).totalRuns;- if (aSum !== bSum) return bSum - aSum;- const aRuns = runCountsById.get(a.id) ?? 0;- const bRuns = runCountsById.get(b.id) ?? 0;- if (aRuns !== bRuns) return bRuns - aRuns;- return +new Date(b.created_at) - +new Date(a.created_at);- });- break;- }- return xs;- }, [filteredAgents, sort, runCountsById, activityMap]);-- const archivedCount = useMemo(- () => agents.filter((a) => !!a.archived_at).length,- [agents],- );-- const totalActiveCount = useMemo(- () => agents.filter((a) => !a.archived_at).length,- [agents],- );-- // Auto-bounce out of Archived if the population empties (e.g. user- // restored the last archived agent from another surface).- useEffect(() => {- if (view === "archived" && archivedCount === 0) setView("active");- }, [view, archivedCount]);-- const handleCreate = async (data: CreateAgentRequest): Promise<Agent> => {- const agent = await api.createAgent(data);- // Skill follow-up is now owned by the dialog (it reads the user's- // form selection, which already includes the duplicate source's- // skills as a default when applicable). The dialog will call- // setAgentSkills after we return; we just have to surface the- // created agent so it can.- qc.setQueryData<Agent[]>(workspaceKeys.agents(wsId), (current = []) => {- const exists = current.some((a) => a.id === agent.id);- return exists- ? current.map((a) => (a.id === agent.id ? agent : a))- : [...current, agent];- });- setShowCreate(false);- setDuplicateTemplate(null);- navigation.push(paths.agentDetail(agent.id));- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });- return 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,- isOwnedByMe: isOwner,- canManage,- };- });- }, [- sortedAgents,- currentUser,- isWorkspaceAdmin,- scope,- runtimesById,- presenceMap,- activityMap,- runCountsById,- ]);-- const columns = useMemo(- () => createAgentColumns({ onDuplicate: handleDuplicate, t }),- [handleDuplicate, t],- );-- const table = useReactTable({- data: agentRows,- columns,- getCoreRowModel: getCoreRowModel(),- enableColumnResizing: true,- // Pin the kebab column right so it stays accessible during horizontal- // scroll — matches the pattern in Linear / Notion / GitHub.- initialState: { columnPinning: { right: ["actions"] } },- });+ return {+ "--agc-status": width("status"),+ "--agc-owner": width("owner"),+ "--agc-runtime": width("runtime"),+ "--agc-lastactive": width("lastActive"),+ "--agc-runs": width("runs"),+ "--agc-model": width("model"),+ "--agc-created": width("created"),+ "--agc-minw": `${minWidth}px`,+ } as React.CSSProperties;+}- // ---- Loading ----- if (isLoading) {- return (- <div className="flex flex-1 min-h-0 flex-col">- <PageHeaderBar totalCount={0} onCreate={() => setShowCreate(true)} />- <div className="flex flex-1 min-h-0 flex-col gap-4 p-6">- <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border">- <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">- <Skeleton className="h-7 w-32 rounded-md" />- <Skeleton className="h-7 w-32 rounded-md" />- </div>- <div className="flex h-11 shrink-0 items-center gap-2 border-b px-4">- <Skeleton className="h-6 w-16 rounded-full" />- <Skeleton className="h-6 w-24 rounded-full" />- <Skeleton className="h-6 w-20 rounded-full" />- </div>- <div className="space-y-2 p-4">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-14 w-full rounded-md" />- ))}- </div>- </div>- </div>- </div>- );- }+export interface AgentListRow {+ agent: Agent;+ runtime: AgentRuntime | null;+ presence: AgentPresenceDetail | null;+ activity: AgentActivity | null;+ runCount: number;+ /** Days since the last bucket with runs; null = nothing in the window. */+ lastActiveDays: number | null;+ owner: MemberWithUser | null;+ isOwnedByMe: boolean;+ canManage: boolean;+}- // ---- List request error ----- if (listError) {- return <ListError onCreate={() => setShowCreate(true)} listError={listError} onRetry={refetchList} />;+// Most recent activity bucket with runs, as "days ago" (0 = today).+// Day-granularity by design — derived from the same 30-day buckets the+// detail page charts, no extra API.+function lastActiveDaysAgo(activity: AgentActivity | null): number | null {+ if (!activity) return null;+ for (let i = activity.buckets.length - 1; i >= 0; i--) {+ const bucket = activity.buckets[i];+ if (bucket && bucket.total > 0) return activity.buckets.length - 1 - i;}+ return null;+}- const showEmpty = totalActiveCount === 0 && archivedCount === 0;-- return (- <div className="flex flex-1 min-h-0 flex-col">- <PageHeaderBar- totalCount={totalActiveCount}- onCreate={() => setShowCreate(true)}- />-- <div className="flex flex-1 min-h-0 flex-col gap-4 p-6">- {showEmpty ? (- <div className="flex flex-1 items-center justify-center">- <EmptyState onCreate={() => setShowCreate(true)} />- </div>- ) : (- <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border bg-background">- {view === "active" ? (- <>- <ActiveToolbarRow- scope={scope}- setScope={setScope}- scopeCounts={scopeCounts}- sort={sort}- setSort={setSort}- search={search}- setSearch={setSearch}- visibleCount={sortedAgents.length}- totalCount={inScope.length}- archivedCount={archivedCount}- onShowArchived={() => setView("archived")}- machines={machines}- runtimeMachineId={runtimeMachineId}- onRuntimeMachineChange={setRuntimeMachineId}- agentCountByMachine={agentCountByMachine}- />- <AvailabilityFilterRow- value={availabilityFilter}- onChange={setAvailabilityFilter}- counts={availabilityCounts}- totalCount={inScopeOnMachine.length}- />- </>- ) : (- <ArchivedToolbarRow- onBack={() => setView("active")}- archivedCount={archivedCount}- sort={sort}- setSort={setSort}- />- )}-- {sortedAgents.length === 0 ? (- <NoMatches- view={view}- search={search}- scope={scope}- runtimeMachineTitle={selectedMachine?.title ?? null}- />- ) : (- <DataTable- table={table}- onRowClick={(row) =>- navigation.push(paths.agentDetail(row.original.agent.id))- }- />- )}- </div>- )}- </div>-- {showCreate && (- <CreateAgentDialog- runtimes={runtimes}- runtimesLoading={runtimesLoading}- members={members}- currentUserId={currentUser?.id ?? null}- template={duplicateTemplate}- onClose={() => {- setShowCreate(false);- setDuplicateTemplate(null);- }}- onCreate={handleCreate}- />- )}- </div>- );+export interface AgentsPageProps {+ /** Desktop-only daemon wiring, currently unused by the list (kept for+ * platform-layer compatibility; the runtime filter lists runtimes by+ * name rather than grouped machines). */+ localDaemonId?: string | null;+ localMachineName?: string | null;+ hasLocalMachine?: boolean;}// ----------------------------------------------------------------------------// Page header — icon + title + count + create CTA. Unchanged.+// Page header// ---------------------------------------------------------------------------function PageHeaderBar({@@ -654,7 +195,6 @@ function PageHeaderBar({{totalCount}</span>)}- {/* Tagline next to the title — mirrors Runtimes / Skills. */}<p className="ml-2 hidden text-xs text-muted-foreground md:block">{t(($) => $.page.tagline)}{" "}<a@@ -667,9 +207,18 @@ function PageHeaderBar({</a></p></div>- <Button type="button" size="sm" onClick={onCreate}>- <Plus className="h-3 w-3" />- {t(($) => $.page.new_agent)}+ {/* Quiet chrome button (outline, icon-only below md) — primary is+ reserved for the empty state's CTA. */}+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-8 w-8 gap-1 px-0 md:w-auto md:px-2.5"+ aria-label={t(($) => $.page.new_agent)}+ onClick={onCreate}+ >+ <Plus className="h-3.5 w-3.5" />+ <span className="hidden md:inline">{t(($) => $.page.new_agent)}</span></Button></PageHeader>);@@ -691,19 +240,16 @@ function ListError({<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center"><AlertCircle className="h-8 w-8 text-destructive" /><div>- <p className="text-sm font-medium">{t(($) => $.page.list_load_failed)}</p>+ <p className="text-sm font-medium">+ {t(($) => $.page.list_load_failed)}+ </p><p className="mt-1 text-xs text-muted-foreground">{listError instanceof Error? listError.message: t(($) => $.page.list_load_failed_default)}</p></div>- <Button- type="button"- variant="outline"- size="sm"- onClick={onRetry}- >+ <Button type="button" variant="outline" size="sm" onClick={onRetry}>{t(($) => $.page.try_again)}</Button></div>@@ -711,360 +257,974 @@ function ListError({);}+function EmptyState({ onCreate }: { onCreate: () => void }) {+ const { t } = useT("agents");+ return (+ <div className="flex flex-1 flex-col items-center justify-center px-6 py-16 text-center">+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">+ <Bot className="h-6 w-6 text-muted-foreground" />+ </div>+ <h2 className="mt-4 text-base font-semibold">+ {t(($) => $.empty.title)}+ </h2>+ <p className="mt-1 max-w-md text-sm text-muted-foreground">+ {t(($) => $.empty.description)}+ </p>+ <Button type="button" onClick={onCreate} size="sm" className="mt-5">+ <Plus className="h-3 w-3" />+ {t(($) => $.page.new_agent)}+ </Button>+ </div>+ );+}+// ----------------------------------------------------------------------------// Active view — Layer 1: scope segment + sort + search + archived link + live+// Cells// ----------------------------------------------------------------------------function ActiveToolbarRow({- scope,- setScope,- scopeCounts,- sort,- setSort,- search,- setSearch,- visibleCount,- totalCount,- archivedCount,- onShowArchived,- machines,- runtimeMachineId,- onRuntimeMachineChange,- agentCountByMachine,+function CheckboxCell({+ checked,+ onToggle,}: {- scope: Scope;- setScope: (v: Scope) => void;- scopeCounts: { all: number; mine: number };- sort: SortKey;- setSort: (v: SortKey) => void;- search: string;- setSearch: (v: string) => void;- visibleCount: number;- totalCount: number;- archivedCount: number;- onShowArchived: () => void;- machines: RuntimeMachine[];- runtimeMachineId: string | null;- onRuntimeMachineChange: (id: string | null) => void;- agentCountByMachine: Map<string, number>;+ checked: boolean;+ onToggle: () => void;}) {- const { t } = useT("agents");return (- <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- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder={t(($) => $.page.search_placeholder)}- className="h-8 w-64 pl-8 text-sm"- />- </div>- <ScopeSegment scope={scope} setScope={setScope} counts={scopeCounts} />- <div className="ml-auto flex items-center gap-3">- <RuntimeMachineFilterDropdown- machines={machines}- value={runtimeMachineId}- onChange={onRuntimeMachineChange}- agentCountByMachine={agentCountByMachine}- totalAgentCount={totalCount}+ <ListGridCell className="justify-center px-0">+ <button+ type="button"+ aria-pressed={checked}+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onToggle();+ }}+ className={`-m-1.5 flex items-center p-1.5 ${+ checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"+ }`}+ >+ <Checkbox+ checked={checked}+ tabIndex={-1}+ className="pointer-events-none"/>- {archivedCount > 0 && (- <button- type="button"- onClick={onShowArchived}- className="text-xs text-muted-foreground transition-colors hover:text-foreground"+ </button>+ </ListGridCell>+ );+}++// Two-line identity cell: avatar left, name + description right. The+// documented exception to the single-line rule — agents are few and+// identity-rich, so this is the "team roster" form (GitHub org members,+// Slack member list).+function NameCell({ row }: { row: AgentListRow }) {+ const { t } = useT("agents");+ const { agent, isOwnedByMe } = row;+ const isArchived = !!agent.archived_at;+ const isPrivate = agent.visibility === "private";+ return (+ <ListGridCell className="gap-3">+ <ActorAvatar+ actorType="agent"+ actorId={agent.id}+ size={32}+ 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 text-sm font-medium ${+ isArchived ? "text-muted-foreground" : ""+ }`}>- {t(($) => $.page.show_archived, { count: archivedCount })}- </button>- )}- <span className="font-mono text-xs tabular-nums text-muted-foreground/70">- {t(($) => $.page.of_total, { visible: visibleCount, total: totalCount })}- </span>- <SortDropdown sort={sort} setSort={setSort} />+ {agent.name}+ </span>+ {isPrivate && !isArchived && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Lock className="h-3 w-3 shrink-0 text-muted-foreground/60" />+ }+ />+ <TooltipContent>{VISIBILITY_TOOLTIP.private}</TooltipContent>+ </Tooltip>+ )}+ {isOwnedByMe && (+ <span className="shrink-0 rounded bg-muted px-1 text-[10px] font-medium text-muted-foreground">+ {t(($) => $.row.you)}+ </span>+ )}+ </div>+ {agent.description ? (+ <div className="mt-0.5 truncate text-xs text-muted-foreground">+ {agent.description}+ </div>+ ) : null}</div>- </div>+ </ListGridCell>);}-function ScopeSegment({- scope,- setScope,- counts,-}: {- scope: Scope;- setScope: (v: Scope) => void;- counts: { all: number; mine: number };-}) {+// Availability dot + label, with the workload folded in as a suffix+// ("Online · 2 tasks") — a 0-2 integer doesn't earn its own column.+function StatusCell({ row }: { row: AgentListRow }) {const { t } = useT("agents");+ const { agent, presence } = row;+ if (agent.archived_at) {+ return (+ <ListGridCell>+ <span className="text-xs text-muted-foreground/60">+ {t(($) => $.row.archived)}+ </span>+ </ListGridCell>+ );+ }+ if (!presence) {+ return (+ <ListGridCell>+ <span className="text-xs text-muted-foreground/40">—</span>+ </ListGridCell>+ );+ }+ const visual = availabilityConfig[presence.availability];+ const active = presence.runningCount + presence.queuedCount;return (- <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">- <ScopeButton- active={scope === "mine"}- label={t(($) => $.scope.mine)}- count={counts.mine}- onClick={() => setScope("mine")}- />- <ScopeButton- active={scope === "all"}- label={t(($) => $.scope.all)}- count={counts.all}- onClick={() => setScope("all")}- />- </div>+ <ListGridCell className="gap-1.5">+ <span className={`size-1.5 shrink-0 rounded-full ${visual.dotClass}`} />+ <span className={`truncate text-xs ${visual.textClass}`}>+ {t(($) => $.availability[presence.availability])}+ {active > 0 && (+ <span className="text-muted-foreground">+ {" · "}+ {t(($) => $.row.task_count, { count: active })}+ </span>+ )}+ </span>+ </ListGridCell>);}-function ScopeButton({- active,- label,- count,- onClick,-}: {- active: boolean;- label: string;- count: number;- onClick: () => void;-}) {+// Owner = the agent's owner_id, which is set to the creator at creation and+// never transferred (so owner ≡ creator). It carries management rights, so+// the column is "Owner", not "Created by".+function OwnerCell({ row }: { row: AgentListRow }) {+ const { agent, owner } = row;+ if (!agent.owner_id) {+ return (+ <ListGridCell className="hidden @2xl:flex">+ <span className="text-xs text-muted-foreground/40">—</span>+ </ListGridCell>+ );+ }return (- <button- type="button"- onClick={onClick}- className={`inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-xs font-medium transition-colors ${- active- ? "bg-background text-foreground shadow-sm"- : "text-muted-foreground hover:text-foreground"- }`}- >- <span>{label}</span>- <span- className={`font-mono tabular-nums ${- active ? "text-muted-foreground/80" : "text-muted-foreground/50"- }`}- >- {count}+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ <ActorAvatar actorType="member" actorId={agent.owner_id} size={18} />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {owner?.name ?? agent.owner_id.slice(0, 8)}</span>- </button>+ </ListGridCell>);}-function SortDropdown({- sort,- setSort,-}: {- sort: SortKey;- setSort: (v: SortKey) => void;-}) {+function RuntimeCell({ row }: { row: AgentListRow }) {+ const runtime = row.runtime;+ return (+ <ListGridCell className="hidden @2xl:flex">+ {runtime ? (+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {runtime.name}+ </span>+ ) : (+ <span className="text-xs text-muted-foreground/40">—</span>+ )}+ </ListGridCell>+ );+}++function LastActiveCell({ row }: { row: AgentListRow }) {const { t } = useT("agents");+ const days = row.lastActiveDays;return (- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="ghost"- size="sm"- className="h-8 gap-1.5 text-xs text-muted-foreground hover:text-foreground"- />- }- >- <ArrowUpDown className="h-3 w-3" />- {t(($) => $.sort[SORT_LABEL_KEY[sort]])}- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-auto">- {SORT_KEYS.map((k) => (- <DropdownMenuItem- key={k}- onClick={() => setSort(k)}- className="text-xs"- >- {t(($) => $.sort[SORT_LABEL_KEY[k]])}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>+ <ListGridCell className="hidden @2xl:flex">+ {days === null ? (+ <span className="truncate text-xs text-muted-foreground/40">+ {row.agent.archived_at ? "—" : t(($) => $.last_active.none)}+ </span>+ ) : (+ <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">+ {days === 0+ ? t(($) => $.last_active.today)+ : t(($) => $.last_active.days_ago, { count: days })}+ </span>+ )}+ </ListGridCell>);}// ----------------------------------------------------------------------------// Availability chip row — All / Online / Unstable / Offline. Only shown-// in the Active view; archived agents have no presence.+// Header row + skeleton// ----------------------------------------------------------------------------function AvailabilityFilterRow({- value,- onChange,- counts,- totalCount,+function AgentListHeader({+ sortField,+ sortDirection,+ onSort,+ allSelected,+ someSelected,+ onToggleAll,+ isColVisible,}: {- value: AvailabilityFilter;- onChange: (v: AvailabilityFilter) => void;- counts: Record<AgentAvailability, number>;- totalCount: number;+ sortField: AgentSortField;+ sortDirection: ListGridSortDirection;+ onSort: (field: AgentSortField) => void;+ allSelected: boolean;+ someSelected: boolean;+ onToggleAll: () => void;+ isColVisible: (key: AgentColumnKey) => boolean;}) {const { t } = useT("agents");+ const sorted = (field: AgentSortField) =>+ sortField === field ? sortDirection : false;+ const anySelected = allSelected || someSelected;return (- <div className="flex h-11 shrink-0 items-center gap-2 border-b px-4">- <AvailabilityChip- active={value === "all"}- onClick={() => onChange("all")}- label={t(($) => $.availability.all)}- count={totalCount}- />- {availabilityOrder.map((a) => {- const cfg = availabilityConfig[a];- return (- <AvailabilityChip- key={a}- active={value === a}- onClick={() => onChange(a)}- label={t(($) => $.availability[a])}- count={counts[a]}- dotClass={cfg.dotClass}+ <ListGridHeader>+ <div className="flex items-center justify-center">+ <button+ type="button"+ aria-pressed={allSelected}+ onClick={onToggleAll}+ className={`-m-1.5 flex items-center p-1.5 ${+ anySelected+ ? ""+ : "opacity-0 transition-opacity group-hover/header:opacity-100"+ }`}+ >+ <Checkbox+ checked={allSelected}+ indeterminate={someSelected && !allSelected}+ tabIndex={-1}+ className="pointer-events-none"/>- );- })}- </div>+ </button>+ </div>+ <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>+ {t(($) => $.columns.agent)}+ </ListGridHeaderCell>+ {isColVisible("status") ? (+ <ListGridHeaderCell>{t(($) => $.columns.status)}</ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="px-0" />+ )}+ {isColVisible("owner") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.columns.owner)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("runtime") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.columns.runtime)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("lastActive") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("lastActive")}+ onSort={() => onSort("lastActive")}+ >+ {t(($) => $.columns.last_active)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("runs") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ align="right"+ sorted={sorted("runs")}+ onSort={() => onSort("runs")}+ >+ {t(($) => $.columns.runs)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("model") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.columns.model)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("created")}+ onSort={() => onSort("created")}+ >+ {t(($) => $.columns.created)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ <span aria-hidden="true" />+ </ListGridHeader>);}-function AvailabilityChip({- active,- onClick,- label,- count,- dotClass,-}: {- active: boolean;- onClick: () => void;- label: string;- count: number;- dotClass?: string;-}) {+function LoadingSkeleton() {return (- <Button- variant="outline"- size="sm"- onClick={onClick}- className={- active- ? "bg-accent text-accent-foreground hover:bg-accent/80"- : "text-muted-foreground"- }+ <ListGrid+ className={GRID_COLS}+ style={columnTrackVars(+ (key) => !AGENT_DEFAULT_HIDDEN_COLUMNS.includes(key),+ )}>- {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>+ <ListGridHeader>+ <span aria-hidden="true" />+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-14" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-14" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-14" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-10" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridHeader>+ {Array.from({ length: 5 }).map((_, i) => (+ <ListGridRow key={i} className="h-16 hover:bg-transparent">+ <span aria-hidden="true" />+ <ListGridCell className="gap-3">+ <Skeleton className="size-8 rounded-md" />+ <div className="min-w-0 flex-1 space-y-1.5">+ <Skeleton className="h-3.5 w-32 max-w-full" />+ <Skeleton className="h-3 w-48 max-w-full" />+ </div>+ </ListGridCell>+ <ListGridCell>+ <Skeleton className="h-3 w-16" />+ </ListGridCell>+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ <Skeleton className="size-5 rounded-full" />+ <Skeleton className="h-3 w-12" />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-16" />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-12" />+ </ListGridCell>+ <ListGridCell className="hidden justify-end @2xl:flex">+ <Skeleton className="h-3 w-8" />+ </ListGridCell>+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridRow>+ ))}+ </ListGrid>);}// ----------------------------------------------------------------------------// Archived view — single toolbar row (back link + title + count + sort).-// No presence chip row: presence is undefined for archived agents.+// Batch toolbar — archive (with confirm; archiving cancels active tasks) and+// restore, mirroring the single-row actions. No delete: the API has none.// ----------------------------------------------------------------------------function ArchivedToolbarRow({- onBack,- archivedCount,- sort,- setSort,+function AgentBatchToolbar({+ rows,+ onClear,}: {- onBack: () => void;- archivedCount: number;- sort: SortKey;- setSort: (v: SortKey) => void;+ rows: AgentListRow[];+ onClear: () => void;}) {const { t } = useT("agents");+ const wsId = useWorkspaceId();+ const qc = useQueryClient();+ const [confirmArchive, setConfirmArchive] = useState(false);+ const [busy, setBusy] = useState(false);++ if (rows.length === 0) return null;++ const allManageable = rows.every((r) => r.canManage);+ const anyActive = rows.some((r) => !r.agent.archived_at);+ const anyArchived = rows.some((r) => !!r.agent.archived_at);++ const invalidate = () =>+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });++ const runBatch = async (+ fn: (id: string) => Promise<unknown>,+ targets: AgentListRow[],+ ) => {+ setBusy(true);+ try {+ for (const row of targets) {+ await fn(row.agent.id);+ }+ invalidate();+ onClear();+ } catch (e) {+ invalidate();+ toast.error(e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(false);+ }+ };+return (- <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">- <button- type="button"- onClick={onBack}- className="inline-flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground"- >- <ArrowLeft className="h-3 w-3" />- {t(($) => $.archived.active_link)}- </button>- <span className="text-muted-foreground/40">/</span>- <span className="text-xs font-medium">{t(($) => $.archived.title)}</span>- <span className="font-mono text-xs tabular-nums text-muted-foreground/70">- {archivedCount}- </span>- <div className="ml-auto">- <SortDropdown sort={sort} setSort={setSort} />+ <>+ {/* Anchored to the page root (relative), NOT the viewport. */}+ <div className="absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg">+ <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">+ <span className="text-sm font-medium">+ {t(($) => $.actions.selected, { count: rows.length })}+ </span>+ <button+ type="button"+ aria-label={t(($) => $.actions.clear_selection)}+ onClick={onClear}+ className="rounded p-0.5 transition-colors hover:bg-accent"+ >+ <X className="size-3.5 text-muted-foreground" />+ </button>+ </div>++ {anyActive && (+ <Button+ variant="ghost"+ size="sm"+ disabled={!allManageable || busy}+ onClick={() => setConfirmArchive(true)}+ >+ <Archive className="mr-1 size-3.5" />+ {t(($) => $.row_actions.archive)}+ </Button>+ )}+ {anyArchived && (+ <Button+ variant="ghost"+ size="sm"+ disabled={!allManageable || busy}+ onClick={() =>+ runBatch(+ (id) => api.restoreAgent(id),+ rows.filter((r) => !!r.agent.archived_at),+ )+ }+ >+ <ArchiveRestore className="mr-1 size-3.5" />+ {t(($) => $.row_actions.restore)}+ </Button>+ )}</div>- </div>++ <Dialog open={confirmArchive} onOpenChange={setConfirmArchive}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {t(($) => $.row_actions.archive_dialog_title, {+ name:+ rows.length === 1 && rows[0]+ ? rows[0].agent.name+ : String(rows.length),+ })}+ </DialogTitle>+ <DialogDescription>+ {t(($) => $.row_actions.archive_dialog_description)}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={() => setConfirmArchive(false)}+ >+ {t(($) => $.row_actions.archive_dialog_cancel)}+ </Button>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ disabled={busy}+ onClick={async () => {+ await runBatch(+ (id) => api.archiveAgent(id),+ rows.filter((r) => !r.agent.archived_at),+ );+ setConfirmArchive(false);+ }}+ >+ {busy ? (+ <Loader2 className="mr-1 size-3.5 animate-spin" />+ ) : null}+ {t(($) => $.row_actions.archive_dialog_confirm)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>);}// ----------------------------------------------------------------------------// Empty / no-matches states+// Page// ----------------------------------------------------------------------------function EmptyState({ onCreate }: { onCreate: () => void }) {+export function AgentsPage(_props: AgentsPageProps = {}) {const { t } = useT("agents");- return (- <div className="flex flex-1 flex-col items-center justify-center px-6 py-16 text-center">- <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">- <Bot className="h-6 w-6 text-muted-foreground" />- </div>- <h2 className="mt-4 text-base font-semibold">{t(($) => $.empty.title)}</h2>- <p className="mt-1 max-w-md text-sm text-muted-foreground">- {t(($) => $.empty.description)}- </p>- <Button type="button" onClick={onCreate} size="sm" className="mt-5">- <Plus className="h-3 w-3" />- {t(($) => $.page.new_agent)}- </Button>- </div>+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const navigation = useNavigation();+ const qc = useQueryClient();+ const currentUser = useAuthStore((s) => s.user);++ const {+ data: agents = [],+ isLoading,+ error: listError,+ refetch: refetchList,+ } = useQuery(agentListOptions(wsId));+ const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(+ runtimeListOptions(wsId),);-}+ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const { data: runCountsRaw = [] } = useQuery(agentRunCounts30dOptions(wsId));+ const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);+ const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);-function NoMatches({- view,- search,- scope,- runtimeMachineTitle,-}: {- view: View;- search: string;- scope: Scope;- runtimeMachineTitle: string | null;-}) {- const { t } = useT("agents");- const hasSearch = search.length > 0;- const hasFilter = scope === "mine";- const hasRuntimeFilter = runtimeMachineTitle !== null;+ const [showCreate, setShowCreate] = useState(false);+ const [duplicateTemplate, setDuplicateTemplate] = useState<Agent | null>(+ null,+ );+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(+ new Set(),+ );++ const rawScope = useAgentsViewStore((s) => s.scope);+ const scope = AGENT_SCOPES.includes(rawScope) ? rawScope : "mine";+ const setScope = useAgentsViewStore((s) => s.setScope);+ const sortField = useAgentsViewStore((s) => s.sortField);+ const sortDirection = useAgentsViewStore((s) => s.sortDirection);+ const hiddenColumns = useAgentsViewStore((s) => s.hiddenColumns);+ const filters = useAgentsViewStore((s) => s.filters);+ const handleSort = useAgentsViewStore((s) => s.toggleSort);+ const handleSortFieldSelect = useAgentsViewStore((s) => s.setSortField);+ const setSortDirection = useAgentsViewStore((s) => s.setSortDirection);+ const toggleColumn = useAgentsViewStore((s) => s.toggleColumn);+ const toggleFilter = useAgentsViewStore((s) => s.toggleFilter);+ const clearFilters = useAgentsViewStore((s) => s.clearFilters);++ const isColVisible = (key: AgentColumnKey) => !hiddenColumns.includes(key);++ const toggleSelected = (id: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ const runtimesById = useMemo(() => {+ const m = new Map<string, AgentRuntime>();+ for (const r of runtimes) m.set(r.id, r);+ return m;+ }, [runtimes]);++ const runCountsById = useMemo(() => {+ const m = new Map<string, number>();+ for (const r of runCountsRaw) m.set(r.agent_id, r.run_count);+ return m;+ }, [runCountsRaw]);++ const membersById = useMemo(() => {+ const m = new Map<string, MemberWithUser>();+ for (const mem of members) m.set(mem.user_id, mem);+ return m;+ }, [members]);++ const isWorkspaceAdmin = useMemo(() => {+ if (!currentUser) return false;+ const me = members.find((m) => m.user_id === currentUser.id);+ return me?.role === "owner" || me?.role === "admin";+ }, [members, currentUser]);++ // Scope counts come from the FULL set (filters never affect them).+ // Archived ignores the ownership lens (see the view store comment).+ const scopeCounts = useMemo<Record<AgentsScope, number>>(() => {+ let mine = 0;+ let all = 0;+ let archived = 0;+ for (const a of agents) {+ if (a.archived_at) {+ archived++;+ continue;+ }+ all++;+ if (currentUser && a.owner_id === currentUser.id) mine++;+ }+ return { mine, all, archived };+ }, [agents, currentUser]);++ // Rows within the current scope, unfiltered, fully assembled — the+ // toolbar's option lists and the "n / total" denominator derive from+ // this; cells never pull their own queries.+ const scopeRows = useMemo<AgentListRow[]>(() => {+ const inScope = agents.filter((a) => {+ if (scope === "archived") return !!a.archived_at;+ if (a.archived_at) return false;+ if (scope === "mine") {+ return !!currentUser && a.owner_id === currentUser.id;+ }+ return true;+ });+ return inScope.map((agent) => {+ const isOwner = !!currentUser?.id && agent.owner_id === currentUser.id;+ const activity = activityMap.get(agent.id) ?? null;+ return {+ agent,+ runtime: runtimesById.get(agent.runtime_id) ?? null,+ presence: presenceMap.get(agent.id) ?? null,+ activity,+ runCount: runCountsById.get(agent.id) ?? 0,+ lastActiveDays: lastActiveDaysAgo(activity),+ owner: agent.owner_id ? membersById.get(agent.owner_id) ?? null : null,+ isOwnedByMe: isOwner,+ canManage: isWorkspaceAdmin || isOwner,+ };+ });+ }, [+ agents,+ scope,+ currentUser,+ runtimesById,+ membersById,+ presenceMap,+ activityMap,+ runCountsById,+ isWorkspaceAdmin,+ ]);- let body: string;- if (view === "archived") {- body = hasSearch- ? t(($) => $.no_matches.search_archived, { query: search })- : t(($) => $.no_matches.no_archived);- } else if (hasSearch && hasRuntimeFilter) {- body = t(($) => $.no_matches.search_runtime_filtered, {- query: search,- machine: runtimeMachineTitle,+ // Visible rows: filters, then sort.+ const rows = useMemo<AgentListRow[]>(() => {+ const filtered = scopeRows.filter((row) => {+ if (+ filters.availability.length > 0 &&+ (!row.presence ||+ !filters.availability.includes(row.presence.availability))+ ) {+ return false;+ }+ if (+ filters.runtimes.length > 0 &&+ !filters.runtimes.includes(row.agent.runtime_id)+ ) {+ return false;+ }+ if (+ filters.owners.length > 0 &&+ (!row.agent.owner_id || !filters.owners.includes(row.agent.owner_id))+ ) {+ return false;+ }+ if (+ filters.models.length > 0 &&+ !filters.models.includes(row.agent.model)+ ) {+ return false;+ }+ return true;});- } else if (hasSearch) {- body = hasFilter- ? t(($) => $.no_matches.search_active_filtered, { query: search })- : t(($) => $.no_matches.search_active, { query: search });- } else if (hasRuntimeFilter) {- body = t(($) => $.no_matches.runtime_filtered, {- machine: runtimeMachineTitle,++ const dir = sortDirection === "asc" ? 1 : -1;+ filtered.sort((a, b) => {+ if (sortField === "name") {+ return a.agent.name.localeCompare(b.agent.name) * dir;+ }+ if (sortField === "runs") {+ return (a.runCount - b.runCount) * dir ||+ a.agent.name.localeCompare(b.agent.name);+ }+ if (sortField === "created") {+ return (+ (Date.parse(a.agent.created_at) - Date.parse(b.agent.created_at)) *+ dir+ );+ }+ // lastActive: smaller daysAgo = more recent. "desc" (the default)+ // means most recently active first; never-active rows sort last in+ // both directions. Run count breaks ties.+ const av = a.lastActiveDays ?? Number.POSITIVE_INFINITY;+ const bv = b.lastActiveDays ?? Number.POSITIVE_INFINITY;+ const byDays = sortDirection === "desc" ? av - bv : bv - av;+ return (+ byDays || b.runCount - a.runCount ||+ a.agent.name.localeCompare(b.agent.name)+ );});- } else {- body = t(($) => $.no_matches.no_filter_match);+ return filtered;+ }, [scopeRows, filters, sortField, sortDirection]);++ // Row virtualization — headless math, offsets as padding on the rows+ // wrapper, fixed-height rows. The scroll element is the SINGLE outer+ // scroller (both axes): splitting horizontal scrolling (wrapper) from+ // vertical scrolling (an inner element) connected by an h-full+ // percentage bridge caused a non-converging layout loop (flickering+ // double scrollbars) and clipped the last row under the horizontal+ // scrollbar. The sticky header pins inside this scroller; the vertical+ // scrollbar spans the full pane height (Linear's structure).+ const listScrollRef = useRef<HTMLDivElement | null>(null);+ const rowVirtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => listScrollRef.current,+ estimateSize: () => ROW_HEIGHT,+ overscan: 10,+ });++ const handleCreate = async (data: CreateAgentRequest): Promise<Agent> => {+ const agent = await api.createAgent(data);+ qc.setQueryData<Agent[]>(workspaceKeys.agents(wsId), (current = []) => {+ const exists = current.some((a) => a.id === agent.id);+ return exists+ ? current.map((a) => (a.id === agent.id ? agent : a))+ : [...current, agent];+ });+ setShowCreate(false);+ setDuplicateTemplate(null);+ navigation.push(paths.agentDetail(agent.id));+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });+ return agent;+ };++ const handleDuplicate = useCallback((agent: Agent) => {+ setDuplicateTemplate(agent);+ setShowCreate(true);+ }, []);++ const selectedRows = rows.filter((row) => selectedIds.has(row.agent.id));+ const allSelected = rows.length > 0 && selectedRows.length === rows.length;+ const someSelected = selectedRows.length > 0 && !allSelected;+ const handleToggleAll = () => {+ setSelectedIds(+ allSelected ? new Set() : new Set(rows.map((r) => r.agent.id)),+ );+ };++ const virtualItems = rowVirtualizer.getVirtualItems();+ const firstVirtual = virtualItems[0];+ const lastVirtual = virtualItems[virtualItems.length - 1];+ const virtualPadding = {+ top: firstVirtual ? firstVirtual.start : 0,+ bottom: lastVirtual+ ? rowVirtualizer.getTotalSize() - lastVirtual.end+ : 0,+ };++ if (listError) {+ return (+ <ListError+ onCreate={() => setShowCreate(true)}+ listError={listError}+ onRetry={() => refetchList()}+ />+ );}+ const totalCount = agents.filter((a) => !a.archived_at).length;+ const showEmpty = !isLoading && agents.length === 0;+return (- <div className="flex flex-1 flex-col items-center justify-center gap-2 px-4 py-16 text-center text-muted-foreground">- <Search className="h-8 w-8 text-muted-foreground/40" />- <p className="text-sm">{t(($) => $.no_matches.title)}</p>- <p className="max-w-xs text-xs">{body}</p>+ // relative: positioning anchor for the batch toolbar (page-centered,+ // not viewport-centered).+ <div className="relative flex flex-1 min-h-0 flex-col">+ <PageHeaderBar+ totalCount={totalCount}+ onCreate={() => setShowCreate(true)}+ />++ {isLoading ? (+ <div className="flex-1 overflow-y-auto @container">+ <LoadingSkeleton />+ </div>+ ) : showEmpty ? (+ <div className="flex flex-1 items-center justify-center">+ <EmptyState onCreate={() => setShowCreate(true)} />+ </div>+ ) : (+ <>+ <AgentListToolbar+ scope={scope}+ onScopeChange={setScope}+ scopeCounts={scopeCounts}+ filters={filters}+ onToggleFilter={toggleFilter}+ onClearFilters={clearFilters}+ sortField={sortField}+ sortDirection={sortDirection}+ onSortFieldChange={handleSortFieldSelect}+ onSortDirectionChange={setSortDirection}+ hiddenColumns={hiddenColumns}+ onToggleColumn={toggleColumn}+ allRows={scopeRows}+ members={members}+ visibleCount={rows.length}+ />+ <div+ ref={listScrollRef}+ className="min-h-0 flex-1 overflow-auto @container"+ >+ <ListGrid+ className={`${GRID_COLS} @2xl:min-w-[var(--agc-minw)]`}+ style={columnTrackVars(isColVisible)}+ >+ <AgentListHeader+ sortField={sortField}+ sortDirection={sortDirection}+ onSort={handleSort}+ allSelected={allSelected}+ someSelected={someSelected}+ onToggleAll={handleToggleAll}+ isColVisible={isColVisible}+ />+ <ListGridBody+ style={{+ paddingTop: virtualPadding.top,+ paddingBottom:+ virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,+ }}+ >+ {rows.length === 0 && (+ <div className="col-span-full py-16 text-center text-sm text-muted-foreground">+ {t(($) => $.no_matches.title)}+ </div>+ )}+ {virtualItems.map((vi) => {+ const row = rows[vi.index];+ if (!row) return null;+ return (+ <ListGridRow+ key={row.agent.id}+ className={`h-16 ${+ selectedIds.has(row.agent.id) ? "bg-accent/30" : ""+ }`}+ render={+ <AppLink href={paths.agentDetail(row.agent.id)} />+ }+ >+ <CheckboxCell+ checked={selectedIds.has(row.agent.id)}+ onToggle={() => toggleSelected(row.agent.id)}+ />+ <NameCell row={row} />+ {isColVisible("status") ? (+ <StatusCell row={row} />+ ) : (+ <ListGridCell className="px-0" />+ )}+ {isColVisible("owner") ? (+ <OwnerCell row={row} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("runtime") ? (+ <RuntimeCell row={row} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("lastActive") ? (+ <LastActiveCell row={row} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("runs") ? (+ <ListGridCell className="hidden justify-end font-mono text-xs tabular-nums text-muted-foreground @2xl:flex">+ {row.runCount.toLocaleString()}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("model") ? (+ <ListGridCell className="hidden @2xl:flex">+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {row.agent.model || "—"}+ </span>+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridCell className="hidden whitespace-nowrap text-xs tabular-nums text-muted-foreground @2xl:flex">+ {new Date(+ row.agent.created_at,+ ).toLocaleDateString()}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridCell className="justify-end px-0">+ <span+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ className="flex items-center opacity-0 transition-opacity group-hover/row:opacity-100"+ >+ <AgentRowActions+ agent={row.agent}+ presence={row.presence}+ canManage={row.canManage}+ onDuplicate={handleDuplicate}+ />+ </span>+ </ListGridCell>+ </ListGridRow>+ );+ })}+ </ListGridBody>+ </ListGrid>+ </div>+ </>+ )}++ <AgentBatchToolbar+ rows={selectedRows}+ onClear={() => setSelectedIds(new Set())}+ />++ {showCreate && (+ <CreateAgentDialog+ runtimes={runtimes}+ runtimesLoading={runtimesLoading}+ members={members}+ currentUserId={currentUser?.id ?? null}+ template={duplicateTemplate}+ onClose={() => {+ setShowCreate(false);+ setDuplicateTemplate(null);+ }}+ onCreate={handleCreate}+ />+ )}</div>);}diff --git a/packages/views/autopilots/components/autopilot-list-actions.tsx b/packages/views/autopilots/components/autopilot-list-actions.tsxnew file mode 100644index 0000000000..60a7b80fad--- /dev/null+++ b/packages/views/autopilots/components/autopilot-list-actions.tsx@@ -0,0 +1,278 @@+"use client";++import { useState } from "react";+import {+ Loader2,+ MoreHorizontal,+ Pause,+ Play,+ Trash2,+ X,+} from "lucide-react";+import { toast } from "sonner";+import type { Autopilot } from "@multica/core/types";+import {+ useDeleteAutopilot,+ useUpdateAutopilot,+} from "@multica/core/autopilots";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { useT } from "../../i18n";++// ---------------------------------------------------------------------------+// Delete dialog — single row (kebab) and batch share one implementation.+// ---------------------------------------------------------------------------++export function DeleteAutopilotsDialog({+ rows,+ open,+ onOpenChange,+ onDeleted,+}: {+ rows: Autopilot[];+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onDeleted?: () => void;+}) {+ const { t } = useT("autopilots");+ const deleteAutopilot = useDeleteAutopilot();+ const [deleting, setDeleting] = useState(false);++ const handleDelete = async () => {+ setDeleting(true);+ try {+ for (const row of rows) {+ await deleteAutopilot.mutateAsync(row.id);+ }+ onOpenChange(false);+ onDeleted?.();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : String(err));+ } finally {+ setDeleting(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {t(($) => $.actions.delete_dialog.title)}+ </DialogTitle>+ <DialogDescription>+ {t(($) => $.actions.delete_dialog.description, {+ count: rows.length,+ name: rows[0]?.title ?? "",+ })}+ </DialogDescription>+ </DialogHeader>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.actions.delete_dialog.warning)}+ </p>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={deleting}+ onClick={() => onOpenChange(false)}+ >+ {t(($) => $.actions.delete_dialog.cancel)}+ </Button>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ disabled={deleting}+ onClick={handleDelete}+ >+ {deleting ? (+ <>+ <Loader2 className="mr-1 size-3.5 animate-spin" />+ {t(($) => $.actions.delete_dialog.deleting)}+ </>+ ) : (+ t(($) => $.actions.delete_dialog.confirm)+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++// ---------------------------------------------------------------------------+// Status helpers shared by kebab and batch toolbar.+// ---------------------------------------------------------------------------++function useSetStatus() {+ const updateAutopilot = useUpdateAutopilot();+ return async (rows: Autopilot[], status: "active" | "paused") => {+ try {+ for (const row of rows) {+ if (row.status === status) continue;+ await updateAutopilot.mutateAsync({ id: row.id, status });+ }+ } catch (err) {+ toast.error(err instanceof Error ? err.message : String(err));+ }+ };+}++// ---------------------------------------------------------------------------+// Row kebab — lives inside the row <a>; the wrapper span intercepts clicks+// so opening the menu neither navigates nor triggers AppLink's push (same+// pattern as the skills list).+// ---------------------------------------------------------------------------++export function AutopilotRowActions({ row }: { row: Autopilot }) {+ const { t } = useT("autopilots");+ const [deleteOpen, setDeleteOpen] = useState(false);+ const setStatus = useSetStatus();++ return (+ <span+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ className="flex items-center"+ >+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ aria-label={t(($) => $.actions.row_menu)}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"+ >+ <MoreHorizontal className="size-4" />+ </button>+ }+ />+ <DropdownMenuContent align="end" className="w-48">+ {row.status === "active" && (+ <DropdownMenuItem onClick={() => setStatus([row], "paused")}>+ <Pause className="size-3.5" />+ {t(($) => $.actions.pause)}+ </DropdownMenuItem>+ )}+ {row.status === "paused" && (+ <DropdownMenuItem onClick={() => setStatus([row], "active")}>+ <Play className="size-3.5" />+ {t(($) => $.actions.resume)}+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleteOpen(true)}+ >+ <Trash2 className="size-3.5" />+ {t(($) => $.actions.delete)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <DeleteAutopilotsDialog+ rows={[row]}+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ />+ </span>+ );+}++// ---------------------------------------------------------------------------+// Batch toolbar+// ---------------------------------------------------------------------------++export function AutopilotBatchToolbar({+ rows,+ onClear,+}: {+ rows: Autopilot[];+ onClear: () => void;+}) {+ const { t } = useT("autopilots");+ const [deleteOpen, setDeleteOpen] = useState(false);+ const setStatus = useSetStatus();++ if (rows.length === 0) return null;++ const anyActive = rows.some((r) => r.status === "active");+ const anyPaused = rows.some((r) => r.status === "paused");++ return (+ <>+ {/* Anchored to the page root (relative), NOT the viewport — see the+ skills batch toolbar for the rationale. */}+ <div className="absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg">+ <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">+ <span className="text-sm font-medium">+ {t(($) => $.actions.selected, { count: rows.length })}+ </span>+ <button+ type="button"+ aria-label={t(($) => $.actions.clear_selection)}+ onClick={onClear}+ className="rounded p-0.5 transition-colors hover:bg-accent"+ >+ <X className="size-3.5 text-muted-foreground" />+ </button>+ </div>++ {anyActive && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setStatus(rows, "paused")}+ >+ <Pause className="mr-1 size-3.5" />+ {t(($) => $.actions.pause)}+ </Button>+ )}+ {anyPaused && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setStatus(rows, "active")}+ >+ <Play className="mr-1 size-3.5" />+ {t(($) => $.actions.resume)}+ </Button>+ )}+ <Button+ variant="ghost"+ size="sm"+ className="text-destructive hover:text-destructive"+ onClick={() => setDeleteOpen(true)}+ >+ <Trash2 className="mr-1 size-3.5" />+ {t(($) => $.actions.delete)}+ </Button>+ </div>++ <DeleteAutopilotsDialog+ rows={rows}+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ onDeleted={onClear}+ />+ </>+ );+}diff --git a/packages/views/autopilots/components/autopilot-list-toolbar.tsx b/packages/views/autopilots/components/autopilot-list-toolbar.tsxnew file mode 100644index 0000000000..bd3d5fb74c--- /dev/null+++ b/packages/views/autopilots/components/autopilot-list-toolbar.tsx@@ -0,0 +1,561 @@+"use client";++import {+ ArrowDown,+ ArrowUp,+ ChevronDown,+ Filter,+ X,+} from "lucide-react";+import type { Autopilot } from "@multica/core/types";+import {+ AUTOPILOT_SCOPES,+ type AutopilotColumnKey,+ type AutopilotListFilters,+ type AutopilotScope,+ type AutopilotSortDirection,+ type AutopilotSortField,+} from "@multica/core/autopilots/stores";+import { useActorName } from "@multica/core/workspace/hooks";+import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { Switch } from "@multica/ui/components/ui/switch";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { ActorAvatar } from "../../common/actor-avatar";+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";+import { useT } from "../../i18n";++// Composite "type:id" value for polymorphic actor filter dimensions, so the+// string[] filter store can hold agent/squad/member references alike.+export function actorFilterValue(type: string, id: string): string {+ return `${type}:${id}`;+}++const COLUMN_KEYS: AutopilotColumnKey[] = [+ "assignee",+ "trigger",+ "lastRun",+ "nextRun",+ "mode",+ "creator",+ "created",+];++const SORT_FIELDS: AutopilotSortField[] = [+ "name",+ "lastRun",+ "nextRun",+ "created",+];++const MODES = ["create_issue", "run_only"] as const;+const TRIGGER_KINDS = ["schedule", "webhook", "api"] as const;++export function countActiveFilterDimensions(+ filters: AutopilotListFilters,+): number {+ let count = 0;+ if (filters.assignees.length > 0) count++;+ if (filters.modes.length > 0) count++;+ if (filters.triggerKinds.length > 0) count++;+ if (filters.creators.length > 0) count++;+ return count;+}++export function AutopilotListToolbar({+ scope,+ onScopeChange,+ scopeCounts,+ filters,+ onToggleFilter,+ onClearFilters,+ sortField,+ sortDirection,+ onSortFieldChange,+ onSortDirectionChange,+ hiddenColumns,+ onToggleColumn,+ allRows,+ visibleCount,+}: {+ scope: AutopilotScope;+ onScopeChange: (scope: AutopilotScope) => void;+ /** Per-scope totals from the FULL set — scope counts ignore filters. */+ scopeCounts: Record<AutopilotScope, number>;+ filters: AutopilotListFilters;+ onToggleFilter: (key: keyof AutopilotListFilters, value: string) => void;+ onClearFilters: () => void;+ sortField: AutopilotSortField;+ sortDirection: AutopilotSortDirection;+ onSortFieldChange: (field: AutopilotSortField) => void;+ onSortDirectionChange: (direction: AutopilotSortDirection) => void;+ hiddenColumns: AutopilotColumnKey[];+ onToggleColumn: (key: AutopilotColumnKey) => void;+ /** Rows within the current scope, unfiltered — filter option lists and+ * counts derive from this set. */+ allRows: Autopilot[];+ /** Rows surviving the filters — shown as "n / total" when narrowed. */+ visibleCount: number;+}) {+ const { t } = useT("autopilots");+ const { getActorName } = useActorName();++ const activeCount = countActiveFilterDimensions(filters);+ const hasActiveFilters = activeCount > 0;++ // Option lists with counts, derived from the scope's unfiltered rows so+ // toggling one dimension doesn't make the others' options vanish.+ const assigneeOptions = new Map<+ string,+ { type: string; id: string; count: number }+ >();+ const creatorOptions = new Map<+ string,+ { type: string; id: string; count: number }+ >();+ const modeCounts = new Map<string, number>();+ const triggerKindCounts = new Map<string, number>();+ for (const row of allRows) {+ const aKey = actorFilterValue(row.assignee_type, row.assignee_id);+ const a = assigneeOptions.get(aKey);+ if (a) a.count += 1;+ else+ assigneeOptions.set(aKey, {+ type: row.assignee_type,+ id: row.assignee_id,+ count: 1,+ });+ const cKey = actorFilterValue(row.created_by_type, row.created_by_id);+ const c = creatorOptions.get(cKey);+ if (c) c.count += 1;+ else+ creatorOptions.set(cKey, {+ type: row.created_by_type,+ id: row.created_by_id,+ count: 1,+ });+ modeCounts.set(+ row.execution_mode,+ (modeCounts.get(row.execution_mode) ?? 0) + 1,+ );+ for (const kind of row.trigger_kinds ?? []) {+ triggerKindCounts.set(kind, (triggerKindCounts.get(kind) ?? 0) + 1);+ }+ }++ const SCOPE_LABELS: Record<AutopilotScope, string> = {+ all: t(($) => $.page.scope_all),+ active: t(($) => $.status.active),+ paused: t(($) => $.status.paused),+ };++ const SORT_LABELS: Record<AutopilotSortField, string> = {+ name: t(($) => $.page.table.name),+ lastRun: t(($) => $.page.table.last_run),+ nextRun: t(($) => $.page.table.next_run),+ created: t(($) => $.page.table.created),+ };++ const COLUMN_LABELS: Record<AutopilotColumnKey, string> = {+ assignee: t(($) => $.page.table.assignee),+ trigger: t(($) => $.page.table.trigger),+ lastRun: t(($) => $.page.table.last_run),+ nextRun: t(($) => $.page.table.next_run),+ mode: t(($) => $.page.table.mode),+ creator: t(($) => $.page.table.created_by),+ created: t(($) => $.page.table.created),+ };+ const sortLabel = SORT_LABELS[sortField];++ const countBadge = (n: number) => (+ <span className="ml-auto pl-3 text-xs text-muted-foreground">{n}</span>+ );++ return (+ <div className="flex h-12 shrink-0 items-center justify-between gap-2 px-5">+ {/* Left: scope buttons + result count. Scope is the promoted status+ dimension (it does NOT appear in the filter dropdown). No search+ box: scope buttons already partition the (small) set, so search+ was dropped by product call. The count only appears while filters+ narrow the list. Button styling and the <md dropdown collapse+ follow the issues header's scope buttons. */}+ <div className="flex min-w-0 items-center gap-2">+ <div className="hidden shrink-0 items-center gap-1 md:flex">+ {AUTOPILOT_SCOPES.map((s) => (+ <Button+ key={s}+ variant="outline"+ size="sm"+ className={+ scope === s+ ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"+ : "gap-1.5 text-muted-foreground"+ }+ onClick={() => onScopeChange(s)}+ >+ {SCOPE_LABELS[s]}+ <span className="tabular-nums text-xs text-muted-foreground/70">+ {scopeCounts[s]}+ </span>+ </Button>+ ))}+ </div>++ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="shrink-0 gap-1 text-muted-foreground md:hidden"+ >+ <span className="truncate">{SCOPE_LABELS[scope]}</span>+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={scope}+ onValueChange={(value) =>+ onScopeChange(value as AutopilotScope)+ }+ >+ {AUTOPILOT_SCOPES.map((s) => (+ <DropdownMenuRadioItem key={s} value={s}>+ {SCOPE_LABELS[s]}+ <span className="ml-2 tabular-nums text-xs text-muted-foreground/70">+ {scopeCounts[s]}+ </span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>++ {hasActiveFilters && (+ <span+ title={t(($) => $.toolbar.result_count_title)}+ className="hidden shrink-0 text-xs tabular-nums text-muted-foreground md:inline"+ >+ {visibleCount} / {allRows.length}+ </span>+ )}+ </div>++ <div className="flex shrink-0 items-center gap-1">+ {/* Filter */}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant={hasActiveFilters ? "default" : "outline"}+ size="sm"+ className={+ hasActiveFilters+ ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"+ : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ }+ >+ <Filter className="size-3.5" />+ {hasActiveFilters ? (+ <>+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_active_count, {+ count: activeCount,+ })}+ </span>+ <span className="tabular-nums md:hidden">+ {activeCount}+ </span>+ </>+ ) : (+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_label)}+ </span>+ )}+ {hasActiveFilters && (+ <span+ role="button"+ tabIndex={-1}+ aria-label={t(($) => $.toolbar.clear_filters)}+ className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onClearFilters();+ }}+ onPointerDown={(e) => e.stopPropagation()}+ >+ <X className="size-3" />+ </span>+ )}+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-auto">+ {/* Assignee */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_assignee)}+ </span>+ {filters.assignees.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.assignees.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {[...assigneeOptions.entries()].map(+ ([value, { type, id, count }]) => (+ <DropdownMenuCheckboxItem+ key={value}+ checked={filters.assignees.includes(value)}+ onCheckedChange={() =>+ onToggleFilter("assignees", value)+ }+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck+ checked={filters.assignees.includes(value)}+ />+ <ActorAvatar actorType={type} actorId={id} size={16} />+ <span className="min-w-0 truncate">+ {getActorName(type, id)}+ </span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ ),+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Trigger kind */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_trigger)}+ </span>+ {filters.triggerKinds.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.triggerKinds.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-44">+ {TRIGGER_KINDS.filter((kind) =>+ triggerKindCounts.has(kind),+ ).map((kind) => (+ <DropdownMenuCheckboxItem+ key={kind}+ checked={filters.triggerKinds.includes(kind)}+ onCheckedChange={() =>+ onToggleFilter("triggerKinds", kind)+ }+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck+ checked={filters.triggerKinds.includes(kind)}+ />+ {t(($) => $.trigger_kind[kind])}+ {countBadge(triggerKindCounts.get(kind) ?? 0)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Mode */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_mode)}+ </span>+ {filters.modes.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.modes.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-44">+ {MODES.map((mode) => (+ <DropdownMenuCheckboxItem+ key={mode}+ checked={filters.modes.includes(mode)}+ onCheckedChange={() => onToggleFilter("modes", mode)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.modes.includes(mode)} />+ {t(($) => $.execution_mode[mode])}+ {countBadge(modeCounts.get(mode) ?? 0)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Creator */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_creator)}+ </span>+ {filters.creators.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.creators.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {[...creatorOptions.entries()].map(+ ([value, { type, id, count }]) => (+ <DropdownMenuCheckboxItem+ key={value}+ checked={filters.creators.includes(value)}+ onCheckedChange={() => onToggleFilter("creators", value)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.creators.includes(value)} />+ <ActorAvatar actorType={type} actorId={id} size={16} />+ <span className="min-w-0 truncate">+ {getActorName(type, id)}+ </span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ ),+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>++ {/* Display settings — same paradigm as skills: sort select ++ direction toggle + column switches, mutating the same store the+ list header sort buttons use. */}+ <Popover>+ <Tooltip>+ <PopoverTrigger+ render={+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ <span className="hidden md:inline">{sortLabel}</span>+ </Button>+ }+ />+ }+ />+ <TooltipContent side="bottom">+ {t(($) => $.toolbar.display)}+ </TooltipContent>+ </Tooltip>+ <PopoverContent align="end" className="w-64 p-0">+ <div className="border-b px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.sort_by)}+ </span>+ <div className="mt-2 flex items-center gap-1.5">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="flex-1 justify-between text-xs"+ >+ {sortLabel}+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={sortField}+ onValueChange={(v) =>+ onSortFieldChange(v as AutopilotSortField)+ }+ >+ {SORT_FIELDS.map((field) => (+ <DropdownMenuRadioItem key={field} value={field}>+ {SORT_LABELS[field]}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ <Button+ variant="outline"+ size="icon-sm"+ onClick={() =>+ onSortDirectionChange(+ sortDirection === "asc" ? "desc" : "asc",+ )+ }+ title={+ sortDirection === "asc"+ ? t(($) => $.toolbar.direction_asc)+ : t(($) => $.toolbar.direction_desc)+ }+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ </Button>+ </div>+ </div>++ <div className="px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.section_columns)}+ </span>+ <div className="mt-2 space-y-2">+ {COLUMN_KEYS.map((key) => (+ <label+ key={key}+ className="flex cursor-pointer items-center justify-between"+ >+ <span className="text-sm">{COLUMN_LABELS[key]}</span>+ <Switch+ size="sm"+ checked={!hiddenColumns.includes(key)}+ onCheckedChange={() => onToggleColumn(key)}+ />+ </label>+ ))}+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ </div>+ );+}diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsxindex deb9cf4f14..0fd88abe58 100644--- a/packages/views/autopilots/components/autopilots-page.tsx+++ b/packages/views/autopilots/components/autopilots-page.tsx@@ -1,26 +1,124 @@"use client";-import { useState } from "react";-import { Plus, Zap, Play, Pause, AlertCircle, Newspaper, GitPullRequest, Bug, BarChart3, Shield, FileSearch } from "lucide-react";+import { useMemo, useRef, useState } from "react";+import {+ AlertCircle,+ BarChart3,+ Bug,+ Clock,+ Code,+ FileSearch,+ GitPullRequest,+ Newspaper,+ Pause,+ Plus,+ Shield,+ Webhook,+ Zap,+} from "lucide-react";import { useQuery } from "@tanstack/react-query";+import { useVirtualizer } from "@tanstack/react-virtual";import { autopilotListOptions } from "@multica/core/autopilots/queries";+import {+ useAutopilotsViewStore,+ AUTOPILOT_DEFAULT_HIDDEN_COLUMNS,+ AUTOPILOT_SCOPES,+ type AutopilotColumnKey,+ type AutopilotScope,+ type AutopilotSortField,+} from "@multica/core/autopilots/stores";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";+import type { Autopilot } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import {+ LIST_GRID_BOTTOM_CLEARANCE,+ ListGrid,+ ListGridBody,+ ListGridCell,+ ListGridHeader,+ ListGridHeaderCell,+ ListGridRow,+ type ListGridSortDirection,+} from "@multica/ui/components/ui/list-grid";+import { Skeleton } from "@multica/ui/components/ui/skeleton";import { AppLink } from "../../navigation";import { ActorAvatar } from "../../common/actor-avatar";import { PageHeader } from "../../layout/page-header";-import { Skeleton } from "@multica/ui/components/ui/skeleton";-import { Button } from "@multica/ui/components/ui/button";-import { cn } from "@multica/ui/lib/utils";import { AutopilotDialog } from "./autopilot-dialog";-import type { Autopilot, AutopilotStatus, AutopilotExecutionMode } from "@multica/core/types";+import { AutopilotListToolbar, actorFilterValue } from "./autopilot-list-toolbar";+import {+ AutopilotBatchToolbar,+ AutopilotRowActions,+} from "./autopilot-list-actions";import type { TriggerFrequency } from "./trigger-config";-import { useT } from "../../i18n";+import { useT, useTimeAgo } from "../../i18n";++// Column template — single source of truth for header, rows, and skeletons.+// Same conventions as the skills list (see list-grid.tsx and the comment+// there): deterministic var-width tracks (rows are virtualized), and+// TWO-ZONE responsiveness:+// - Container ≥ @2xl (672px): WYSIWYG — every user-enabled column renders;+// the grid carries min-width = Σ(enabled tracks + gaps) and the wrapper+// scrolls horizontally when the enabled set outgrows the container. An+// enabled column must NEVER silently vanish (the "dead toggle" bug).+// - Container < @2xl: static core set (name + assignee), no horizontal+// scroll, column toggles don't apply.+const GRID_COLS =+ "grid-cols-[0.75rem_1rem_minmax(120px,1fr)_var(--apc-assignee)_1.75rem_0.75rem] " ++ "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_var(--apc-assignee)_var(--apc-trigger)_var(--apc-lastrun)_var(--apc-nextrun)_var(--apc-mode)_var(--apc-creator)_var(--apc-created)_1.75rem_0.75rem]";++// h-12 rows; the virtualizer's fixed-size contract.+const ROW_HEIGHT = 48;++// Single source for hideable column widths: track vars and the grid's+// min-width derive from the same numbers.+const COLUMN_WIDTHS: Record<AutopilotColumnKey, number> = {+ assignee: 144,+ trigger: 144,+ lastRun: 120,+ nextRun: 104,+ mode: 104,+ creator: 144,+ created: 104,+};++// Fixed tracks (edges 12+12, checkbox 16, name min 200, kebab 28) plus the+// 11 gap-x-3 gaps between the wide template's 12 tracks (zero-width tracks+// still carry gaps).+const FIXED_TRACKS_WIDTH = 268 + 11 * 12;++function columnTrackVars(+ isVisible: (key: AutopilotColumnKey) => boolean,+): React.CSSProperties {+ const width = (key: AutopilotColumnKey) =>+ isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";+ const minWidth =+ FIXED_TRACKS_WIDTH ++ (Object.keys(COLUMN_WIDTHS) as AutopilotColumnKey[]).reduce(+ (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),+ 0,+ );+ return {+ "--apc-assignee": width("assignee"),+ "--apc-trigger": width("trigger"),+ "--apc-lastrun": width("lastRun"),+ "--apc-nextrun": width("nextRun"),+ "--apc-mode": width("mode"),+ "--apc-creator": width("creator"),+ "--apc-created": width("created"),+ "--apc-minw": `${minWidth}px`,+ } as React.CSSProperties;+}++// ---------------------------------------------------------------------------+// Templates for the empty state (unchanged from the previous page version).+// Prompts stay raw English because they're injected directly into the+// agent's task input.+// ----------------------------------------------------------------------------// Template-id keyed lookup for the i18n labels. Prompts stay raw English-// because they're injected directly into the agent's task input — translating-// them would also translate the agent's instructions.type TemplateId =| "daily_news"| "pr_review"@@ -107,195 +205,771 @@ const TEMPLATES: AutopilotTemplate[] = [},];-// Hook returning a localized "1d ago / Today" formatter for the row's last_run cell.-function useFormatRelativeDate(): (date: string) => string {+// ---------------------------------------------------------------------------+// Cells+// ---------------------------------------------------------------------------++function CheckboxCell({+ checked,+ onToggle,+}: {+ checked: boolean;+ onToggle: () => void;+}) {+ return (+ <ListGridCell className="justify-center px-0">+ <button+ type="button"+ aria-pressed={checked}+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onToggle();+ }}+ className={`-m-1.5 flex items-center p-1.5 ${+ checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"+ }`}+ >+ <Checkbox+ checked={checked}+ tabIndex={-1}+ className="pointer-events-none"+ />+ </button>+ </ListGridCell>+ );+}++function NameCell({ autopilot }: { autopilot: Autopilot }) {const { t } = useT("autopilots");- return (date: string) => {- const diff = Date.now() - new Date(date).getTime();- const days = Math.floor(diff / (1000 * 60 * 60 * 24));- if (days < 1) return t(($) => $.relative_date.today);- if (days === 1) return t(($) => $.relative_date.one_day_ago);- if (days < 30) return t(($) => $.relative_date.days_ago, { count: days });- const months = Math.floor(days / 30);- return t(($) => $.relative_date.months_ago, { count: months });- };+ return (+ <ListGridCell className="gap-1.5">+ <span className="min-w-0 truncate text-sm font-medium">+ {autopilot.title}+ </span>+ {/* Paused marker: in the "all" scope active and paused rows mix, so a+ paused automation needs an inline signal. */}+ {autopilot.status === "paused" && (+ <span+ title={t(($) => $.status.paused)}+ className="flex shrink-0 items-center text-amber-500"+ >+ <Pause className="size-3" />+ </span>+ )}+ </ListGridCell>+ );+}++function AssigneeCell({ autopilot }: { autopilot: Autopilot }) {+ const { getActorName } = useActorName();+ return (+ <ListGridCell className="gap-1.5">+ <ActorAvatar+ actorType={autopilot.assignee_type}+ actorId={autopilot.assignee_id}+ size={18}+ enableHoverCard={autopilot.assignee_type === "agent"}+ showStatusDot={autopilot.assignee_type === "agent"}+ />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {getActorName(autopilot.assignee_type, autopilot.assignee_id)}+ </span>+ </ListGridCell>+ );}-const STATUS_VISUAL: Record<AutopilotStatus, { color: string; icon: typeof Zap }> = {- active: { color: "text-emerald-500", icon: Play },- paused: { color: "text-amber-500", icon: Pause },- archived: { color: "text-muted-foreground", icon: AlertCircle },+const TRIGGER_ICONS: Record<string, typeof Zap> = {+ schedule: Clock,+ webhook: Webhook,+ api: Code,};-function AutopilotRow({ autopilot }: { autopilot: Autopilot }) {+function TriggerCell({ autopilot }: { autopilot: Autopilot }) {const { t } = useT("autopilots");- const { getActorName } = useActorName();- const wsPaths = useWorkspacePaths();- const formatRelativeDate = useFormatRelativeDate();- const visual = STATUS_VISUAL[autopilot.status as AutopilotStatus] ?? STATUS_VISUAL.active;- const StatusIcon = visual.icon;-+ const kinds = autopilot.trigger_kinds ?? [];+ if (kinds.length === 0) {+ return (+ <ListGridCell className="hidden @2xl:flex">+ <span className="text-xs text-muted-foreground/40">—</span>+ </ListGridCell>+ );+ }return (- <div className="group/row flex flex-col gap-2 border-b px-4 py-3 text-sm transition-colors hover:bg-accent/40 sm:h-11 sm:flex-row sm:items-center sm:gap-2 sm:border-b-0 sm:px-5 sm:py-0">- <AppLink- href={wsPaths.autopilotDetail(autopilot.id)}- className="flex min-w-0 items-center gap-2 sm:flex-1"- >- <Zap className="h-4 w-4 shrink-0 text-muted-foreground" />- <span className="min-w-0 flex-1 truncate font-medium">{autopilot.title}</span>- </AppLink>-- <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 pl-6 text-xs sm:contents sm:pl-0">- {/* Assignee — agent or squad */}- <span className="flex min-w-0 items-center gap-1.5 text-muted-foreground sm:w-32 sm:shrink-0">- <ActorAvatar- actorType={autopilot.assignee_type}- actorId={autopilot.assignee_id}- size={18}- enableHoverCard={autopilot.assignee_type === "agent"}- showStatusDot={autopilot.assignee_type === "agent"}- />- <span className="truncate">- {getActorName(autopilot.assignee_type, autopilot.assignee_id)}+ <ListGridCell className="hidden gap-2 @2xl:flex">+ {kinds.map((kind) => {+ // Server-driven enum: unknown kinds get a generic icon + raw label.+ const Icon = TRIGGER_ICONS[kind] ?? Zap;+ const label =+ kind === "schedule" || kind === "webhook" || kind === "api"+ ? t(($) => $.trigger_kind[kind])+ : kind;+ return (+ <span+ key={kind}+ className="flex min-w-0 items-center gap-1 text-xs text-muted-foreground"+ >+ <Icon className="size-3 shrink-0" />+ <span className="truncate">{label}</span></span>- </span>+ );+ })}+ </ListGridCell>+ );+}- {/* Creator — member or agent, mirror the detail page's Created by field.- Secondary info: below lg only assignee + status survive. */}- <span className="hidden min-w-0 items-center gap-1.5 text-muted-foreground lg:flex lg:w-32 lg:shrink-0">- <ActorAvatar- actorType={autopilot.created_by_type}- actorId={autopilot.created_by_id}- size={18}- enableHoverCard- showStatusDot={autopilot.created_by_type === "agent"}- />- <span className="truncate">- {getActorName(autopilot.created_by_type, autopilot.created_by_id)}- </span>- </span>+// Dot color per last run outcome. Server-driven enum — unknown values fall+// through to the neutral dot, never crash (API compatibility rule).+function runStatusDotClass(status: string | null | undefined): string {+ switch (status) {+ case "completed":+ case "issue_created":+ return "bg-emerald-500";+ case "failed":+ return "bg-red-500";+ case "skipped":+ return "bg-amber-500";+ case "running":+ return "bg-blue-500";+ default:+ return "bg-muted-foreground/40";+ }+}- {/* Mode — secondary info, lg+ only */}- <span className="hidden text-muted-foreground lg:block lg:w-24 lg:shrink-0 lg:text-center">- {t(($) => $.execution_mode[autopilot.execution_mode as AutopilotExecutionMode])}- </span>+function LastRunCell({ autopilot }: { autopilot: Autopilot }) {+ const { t } = useT("autopilots");+ const timeAgo = useTimeAgo();+ if (!autopilot.last_run_at) {+ return (+ <ListGridCell className="hidden @2xl:flex">+ <span className="text-xs text-muted-foreground/40">—</span>+ </ListGridCell>+ );+ }+ const status = autopilot.last_run_status;+ const knownStatus =+ status === "issue_created" ||+ status === "running" ||+ status === "completed" ||+ status === "failed" ||+ status === "skipped"+ ? status+ : null;+ return (+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ <span+ title={knownStatus ? t(($) => $.run_status[knownStatus]) : status ?? undefined}+ className={`size-1.5 shrink-0 rounded-full ${runStatusDotClass(status)}`}+ />+ <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">+ {timeAgo(autopilot.last_run_at)}+ </span>+ </ListGridCell>+ );+}- {/* Status */}- <span className={cn("flex items-center gap-1 sm:w-20 sm:shrink-0 sm:justify-center", visual.color)}>- <StatusIcon className="h-3 w-3" />- {t(($) => $.status[autopilot.status as AutopilotStatus])}+function NextRunCell({ autopilot }: { autopilot: Autopilot }) {+ const next = autopilot.next_run_at;+ return (+ <ListGridCell className="hidden @2xl:flex">+ {next ? (+ <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">+ {new Date(next).toLocaleString(undefined, {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ })}</span>+ ) : (+ <span className="text-xs text-muted-foreground/40">—</span>+ )}+ </ListGridCell>+ );+}- {/* Last run — secondary info, lg+ only */}- <span className="hidden text-muted-foreground tabular-nums lg:block lg:w-20 lg:shrink-0 lg:text-right">- {autopilot.last_run_at ? formatRelativeDate(autopilot.last_run_at) : t(($) => $.page.last_run_empty)}- </span>+function ModeCell({ autopilot }: { autopilot: Autopilot }) {+ const { t } = useT("autopilots");+ const mode = autopilot.execution_mode;+ const label =+ mode === "create_issue" || mode === "run_only"+ ? t(($) => $.execution_mode[mode])+ : mode;+ return (+ <ListGridCell className="hidden @2xl:flex">+ <span className="truncate text-xs text-muted-foreground">{label}</span>+ </ListGridCell>+ );+}++function CreatorCell({ autopilot }: { autopilot: Autopilot }) {+ const { getActorName } = useActorName();+ return (+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ <ActorAvatar+ actorType={autopilot.created_by_type}+ actorId={autopilot.created_by_id}+ size={18}+ />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {getActorName(autopilot.created_by_type, autopilot.created_by_id)}+ </span>+ </ListGridCell>+ );+}++// ---------------------------------------------------------------------------+// Header row+// ---------------------------------------------------------------------------++function AutopilotListHeader({+ sortField,+ sortDirection,+ onSort,+ allSelected,+ someSelected,+ onToggleAll,+ isColVisible,+}: {+ sortField: AutopilotSortField;+ sortDirection: ListGridSortDirection;+ onSort: (field: AutopilotSortField) => void;+ allSelected: boolean;+ someSelected: boolean;+ onToggleAll: () => void;+ isColVisible: (key: AutopilotColumnKey) => boolean;+}) {+ const { t } = useT("autopilots");+ const sorted = (field: AutopilotSortField) =>+ sortField === field ? sortDirection : false;+ const anySelected = allSelected || someSelected;+ return (+ <ListGridHeader>+ <div className="flex items-center justify-center">+ <button+ type="button"+ aria-pressed={allSelected}+ onClick={onToggleAll}+ className={`-m-1.5 flex items-center p-1.5 ${+ anySelected+ ? ""+ : "opacity-0 transition-opacity group-hover/header:opacity-100"+ }`}+ >+ <Checkbox+ checked={allSelected}+ indeterminate={someSelected && !allSelected}+ tabIndex={-1}+ className="pointer-events-none"+ />+ </button></div>- </div>+ <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>+ {t(($) => $.page.table.name)}+ </ListGridHeaderCell>+ {isColVisible("assignee") ? (+ <ListGridHeaderCell>+ {t(($) => $.page.table.assignee)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="px-0" />+ )}+ {isColVisible("trigger") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.page.table.trigger)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("lastRun") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("lastRun")}+ onSort={() => onSort("lastRun")}+ >+ {t(($) => $.page.table.last_run)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("nextRun") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("nextRun")}+ onSort={() => onSort("nextRun")}+ >+ {t(($) => $.page.table.next_run)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("mode") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.page.table.mode)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("creator") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.page.table.created_by)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("created")}+ onSort={() => onSort("created")}+ >+ {t(($) => $.page.table.created)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ <span aria-hidden="true" />+ </ListGridHeader>);}+function LoadingSkeleton() {+ return (+ <ListGrid+ className={GRID_COLS}+ style={columnTrackVars(+ (key) => !AUTOPILOT_DEFAULT_HIDDEN_COLUMNS.includes(key),+ )}+ >+ <ListGridHeader>+ <span aria-hidden="true" />+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-14" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ {/* mode/creator/created are hidden by default — keep their tracks+ mapped with empty placeholders. */}+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridHeader>+ {Array.from({ length: 5 }).map((_, i) => (+ <ListGridRow key={i} className="hover:bg-transparent">+ <span aria-hidden="true" />+ <ListGridCell>+ <Skeleton className="h-3.5 w-40 max-w-full" />+ </ListGridCell>+ <ListGridCell className="gap-1.5">+ <Skeleton className="size-5 rounded-full" />+ <Skeleton className="h-3 w-12" />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-16" />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-14" />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-14" />+ </ListGridCell>+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridRow>+ ))}+ </ListGrid>+ );+}++// ---------------------------------------------------------------------------+// Page+// ---------------------------------------------------------------------------+export function AutopilotsPage() {const { t } = useT("autopilots");const wsId = useWorkspaceId();- const { data: autopilots = [], isLoading } = useQuery(autopilotListOptions(wsId));+ const wsPaths = useWorkspacePaths();+ const {+ data: autopilots = [],+ isLoading,+ error: listError,+ refetch: refetchList,+ } = useQuery(autopilotListOptions(wsId));+const [createOpen, setCreateOpen] = useState(false);- const [selectedTemplate, setSelectedTemplate] = useState<AutopilotTemplate | null>(null);+ const [selectedTemplate, setSelectedTemplate] =+ useState<AutopilotTemplate | null>(null);+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(+ new Set(),+ );+ // Persisted scope may hold a retired value (e.g. "archived" from an older+ // build) — fall back to "all" instead of stranding the user on an+ // unreachable scope.+ const rawScope = useAutopilotsViewStore((s) => s.scope);+ const scope = AUTOPILOT_SCOPES.includes(rawScope) ? rawScope : "all";+ const setScope = useAutopilotsViewStore((s) => s.setScope);+ const sortField = useAutopilotsViewStore((s) => s.sortField);+ const sortDirection = useAutopilotsViewStore((s) => s.sortDirection);+ const hiddenColumns = useAutopilotsViewStore((s) => s.hiddenColumns);+ const filters = useAutopilotsViewStore((s) => s.filters);+ const handleSort = useAutopilotsViewStore((s) => s.toggleSort);+ const handleSortFieldSelect = useAutopilotsViewStore((s) => s.setSortField);+ const setSortDirection = useAutopilotsViewStore((s) => s.setSortDirection);+ const toggleColumn = useAutopilotsViewStore((s) => s.toggleColumn);+ const toggleFilter = useAutopilotsViewStore((s) => s.toggleFilter);+ const clearFilters = useAutopilotsViewStore((s) => s.clearFilters);++ const isColVisible = (key: AutopilotColumnKey) =>+ !hiddenColumns.includes(key);++ const toggleSelected = (id: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ // Scope counts come from the FULL set (filters never affect them — they+ // are stage inventories, not result counts). API-archived rows (no UI+ // flow creates them) are excluded everywhere.+ const scopeCounts = useMemo<Record<AutopilotScope, number>>(() => {+ let active = 0;+ let paused = 0;+ for (const a of autopilots) {+ if (a.status === "archived") continue;+ if (a.status === "paused") paused++;+ else active++;+ }+ return { all: active + paused, active, paused };+ }, [autopilots]);++ // Rows within the current scope, unfiltered — toolbar option lists and+ // the "n / total" denominator derive from this.+ const scopeRows = useMemo<Autopilot[]>(() => {+ if (scope === "all") {+ return autopilots.filter((a) => a.status !== "archived");+ }+ return autopilots.filter((a) => a.status === scope);+ }, [autopilots, scope]);++ // Visible rows: filters, then sort.+ const rows = useMemo<Autopilot[]>(() => {+ const filtered = scopeRows.filter((a) => {+ if (+ filters.assignees.length > 0 &&+ !filters.assignees.includes(+ actorFilterValue(a.assignee_type, a.assignee_id),+ )+ ) {+ return false;+ }+ if (filters.modes.length > 0 && !filters.modes.includes(a.execution_mode)) {+ return false;+ }+ if (+ filters.triggerKinds.length > 0 &&+ !(a.trigger_kinds ?? []).some((k) => filters.triggerKinds.includes(k))+ ) {+ return false;+ }+ if (+ filters.creators.length > 0 &&+ !filters.creators.includes(+ actorFilterValue(a.created_by_type, a.created_by_id),+ )+ ) {+ return false;+ }+ return true;+ });++ const dir = sortDirection === "asc" ? 1 : -1;+ filtered.sort((a, b) => {+ if (sortField === "name") {+ return a.title.localeCompare(b.title) * dir;+ }+ if (sortField === "nextRun") {+ // Missing next run sorts last regardless of direction.+ const av = a.next_run_at ? Date.parse(a.next_run_at) : null;+ const bv = b.next_run_at ? Date.parse(b.next_run_at) : null;+ if (av === null && bv === null) return a.title.localeCompare(b.title);+ if (av === null) return 1;+ if (bv === null) return -1;+ return (av - bv) * dir;+ }+ if (sortField === "created") {+ return (Date.parse(a.created_at) - Date.parse(b.created_at)) * dir;+ }+ // lastRun: never-ran rows sort as oldest.+ const av = a.last_run_at ? Date.parse(a.last_run_at) : 0;+ const bv = b.last_run_at ? Date.parse(b.last_run_at) : 0;+ return (av - bv) * dir || a.title.localeCompare(b.title);+ });+ return filtered;+ }, [scopeRows, filters, sortField, sortDirection]);++ // Row virtualization — same wiring as the skills list: headless math,+ // offsets as padding on the body, fixed-height rows.+ const listScrollRef = useRef<HTMLDivElement | null>(null);+ const rowVirtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => listScrollRef.current,+ estimateSize: () => ROW_HEIGHT,+ overscan: 10,+ });const openCreate = (template?: AutopilotTemplate) => {setSelectedTemplate(template ?? null);setCreateOpen(true);};+ const selectedRows = rows.filter((a) => selectedIds.has(a.id));+ const allSelected = rows.length > 0 && selectedRows.length === rows.length;+ const someSelected = selectedRows.length > 0 && !allSelected;+ const handleToggleAll = () => {+ setSelectedIds(allSelected ? new Set() : new Set(rows.map((a) => a.id)));+ };++ const virtualItems = rowVirtualizer.getVirtualItems();+ const firstVirtual = virtualItems[0];+ const lastVirtual = virtualItems[virtualItems.length - 1];+ const virtualPadding = {+ top: firstVirtual ? firstVirtual.start : 0,+ bottom: lastVirtual+ ? rowVirtualizer.getTotalSize() - lastVirtual.end+ : 0,+ };++ const totalCount = autopilots.length;+ const showEmpty = !isLoading && !listError && totalCount === 0;+return (- <div className="flex h-full flex-col">+ // relative: positioning anchor for the batch toolbar (page-centered,+ // not viewport-centered).+ <div className="relative flex flex-1 min-h-0 flex-col">{/* Header */}<PageHeader className="justify-between px-5"><div className="flex items-center gap-2"><Zap className="h-4 w-4 text-muted-foreground" /><h1 className="text-sm font-medium">{t(($) => $.page.title)}</h1>- {!isLoading && autopilots.length > 0 && (- <span className="text-xs text-muted-foreground tabular-nums">{autopilots.length}</span>+ {totalCount > 0 && (+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">+ {totalCount}+ </span>)}</div>- <Button size="sm" variant="outline" onClick={() => openCreate()}>- <Plus className="h-3.5 w-3.5 mr-1" />- {t(($) => $.page.new_autopilot)}+ {/* Quiet chrome button (outline, icon-only below md) — primary is+ reserved for the empty state's CTAs. */}+ <Button+ size="sm"+ variant="outline"+ className="h-8 w-8 gap-1 px-0 md:w-auto md:px-2.5"+ aria-label={t(($) => $.page.new_autopilot)}+ onClick={() => openCreate()}+ >+ <Plus className="h-3.5 w-3.5" />+ <span className="hidden md:inline">+ {t(($) => $.page.new_autopilot)}+ </span></Button></PageHeader>- {/* Table */}- <div className="flex-1 overflow-y-auto">- {isLoading ? (- <>- <div className="sticky top-0 z-[1] hidden h-8 items-center gap-2 border-b bg-muted/30 px-5 sm:flex">- <span className="shrink-0 w-4" />- <Skeleton className="h-3 w-12 flex-1 max-w-[48px]" />- <Skeleton className="h-3 w-12 shrink-0" />- <Skeleton className="hidden h-3 w-12 shrink-0 lg:block" />- <Skeleton className="hidden h-3 w-10 shrink-0 lg:block" />- <Skeleton className="h-3 w-10 shrink-0" />- <Skeleton className="hidden h-3 w-12 shrink-0 lg:block" />- </div>- <div className="space-y-2 p-4 sm:space-y-1 sm:p-5 sm:pt-1">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-[72px] w-full sm:h-11" />- ))}- </div>- </>- ) : autopilots.length === 0 ? (- <div className="flex flex-col items-center py-16 px-5">- <Zap className="h-10 w-10 mb-3 text-muted-foreground opacity-30" />- <p className="text-sm text-muted-foreground">{t(($) => $.page.empty.title)}</p>- <p className="text-xs text-muted-foreground mt-1 mb-6">- {t(($) => $.page.empty.hint)}- </p>- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 w-full max-w-3xl">- {TEMPLATES.map((tpl) => {- const Icon = tpl.icon;- return (- <button- key={tpl.id}- type="button"- className="flex items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40"- onClick={() => openCreate(tpl)}- >- <Icon className="h-5 w-5 shrink-0 text-muted-foreground mt-0.5" />- <div className="min-w-0">- <div className="text-sm font-medium">- {t(($) => $.templates[tpl.id].title)}- </div>- <div className="text-xs text-muted-foreground mt-0.5 line-clamp-2">- {t(($) => $.templates[tpl.id].summary)}- </div>+ {listError ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">+ <AlertCircle className="h-8 w-8 text-destructive" />+ <p className="text-sm text-muted-foreground">+ {listError instanceof Error ? listError.message : String(listError)}+ </p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => refetchList()}+ >+ {t(($) => $.page.retry)}+ </Button>+ </div>+ ) : isLoading ? (+ <div className="flex-1 overflow-y-auto @container">+ <LoadingSkeleton />+ </div>+ ) : showEmpty ? (+ <div className="flex flex-col items-center px-5 py-16">+ <Zap className="mb-3 h-10 w-10 text-muted-foreground opacity-30" />+ <p className="text-sm text-muted-foreground">+ {t(($) => $.page.empty.title)}+ </p>+ <p className="mb-6 mt-1 text-xs text-muted-foreground">+ {t(($) => $.page.empty.hint)}+ </p>+ <div className="grid w-full max-w-3xl grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {TEMPLATES.map((tpl) => {+ const Icon = tpl.icon;+ return (+ <button+ key={tpl.id}+ type="button"+ className="flex items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40"+ onClick={() => openCreate(tpl)}+ >+ <Icon className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />+ <div className="min-w-0">+ <div className="text-sm font-medium">+ {t(($) => $.templates[tpl.id].title)}</div>- </button>- );- })}- </div>- <Button size="sm" variant="outline" className="mt-4" onClick={() => openCreate()}>- <Plus className="h-3.5 w-3.5 mr-1" />- {t(($) => $.page.start_blank)}- </Button>+ <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">+ {t(($) => $.templates[tpl.id].summary)}+ </div>+ </div>+ </button>+ );+ })}</div>- ) : (- <>- {/* Column headers */}- <div className="sticky top-0 z-[1] hidden h-8 items-center gap-2 border-b bg-muted/30 px-5 text-xs font-medium text-muted-foreground sm:flex">- <span className="shrink-0 w-4" />- <span className="min-w-0 flex-1">{t(($) => $.page.table.name)}</span>- <span className="w-32 shrink-0">{t(($) => $.page.table.agent)}</span>- <span className="hidden w-32 shrink-0 lg:block">{t(($) => $.page.table.created_by)}</span>- <span className="hidden w-24 text-center shrink-0 lg:block">{t(($) => $.page.table.mode)}</span>- <span className="w-20 text-center shrink-0">{t(($) => $.page.table.status)}</span>- <span className="hidden w-20 text-right shrink-0 lg:block">{t(($) => $.page.table.last_run)}</span>- </div>- {autopilots.map((autopilot) => (- <AutopilotRow key={autopilot.id} autopilot={autopilot} />- ))}- </>- )}- </div>+ <Button+ size="sm"+ variant="outline"+ className="mt-4"+ onClick={() => openCreate()}+ >+ <Plus className="mr-1 h-3.5 w-3.5" />+ {t(($) => $.page.start_blank)}+ </Button>+ </div>+ ) : (+ <>+ <AutopilotListToolbar+ scope={scope}+ onScopeChange={setScope}+ scopeCounts={scopeCounts}+ filters={filters}+ onToggleFilter={toggleFilter}+ onClearFilters={clearFilters}+ sortField={sortField}+ sortDirection={sortDirection}+ onSortFieldChange={handleSortFieldSelect}+ onSortDirectionChange={setSortDirection}+ hiddenColumns={hiddenColumns}+ onToggleColumn={toggleColumn}+ allRows={scopeRows}+ visibleCount={rows.length}+ />+ <div+ ref={listScrollRef}+ className="min-h-0 flex-1 overflow-auto @container"+ >+ <ListGrid+ className={`${GRID_COLS} @2xl:min-w-[var(--apc-minw)]`}+ style={columnTrackVars(isColVisible)}+ >+ <AutopilotListHeader+ sortField={sortField}+ sortDirection={sortDirection}+ onSort={handleSort}+ allSelected={allSelected}+ someSelected={someSelected}+ onToggleAll={handleToggleAll}+ isColVisible={isColVisible}+ />+ <ListGridBody+ style={{+ paddingTop: virtualPadding.top,+ paddingBottom:+ virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,+ }}+ >+ {rows.length === 0 && (+ <div className="col-span-full py-16 text-center text-sm text-muted-foreground">+ {t(($) => $.page.no_matches)}+ </div>+ )}+ {virtualItems.map((vi) => {+ const autopilot = rows[vi.index];+ if (!autopilot) return null;+ return (+ <ListGridRow+ key={autopilot.id}+ className={+ selectedIds.has(autopilot.id)+ ? "bg-accent/30"+ : undefined+ }+ render={+ <AppLink href={wsPaths.autopilotDetail(autopilot.id)} />+ }+ >+ <CheckboxCell+ checked={selectedIds.has(autopilot.id)}+ onToggle={() => toggleSelected(autopilot.id)}+ />+ <NameCell autopilot={autopilot} />+ {isColVisible("assignee") ? (+ <AssigneeCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="px-0" />+ )}+ {isColVisible("trigger") ? (+ <TriggerCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("lastRun") ? (+ <LastRunCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("nextRun") ? (+ <NextRunCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("mode") ? (+ <ModeCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("creator") ? (+ <CreatorCell autopilot={autopilot} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridCell className="hidden whitespace-nowrap text-xs tabular-nums text-muted-foreground @2xl:flex">+ {new Date(autopilot.created_at).toLocaleDateString()}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridCell className="justify-end px-0">+ <AutopilotRowActions row={autopilot} />+ </ListGridCell>+ </ListGridRow>+ );+ })}+ </ListGridBody>+ </ListGrid>+ </div>+ </>+ )}++ <AutopilotBatchToolbar+ rows={selectedRows}+ onClear={() => setSelectedIds(new Set())}+ />{createOpen && (<AutopilotDialog@@ -315,7 +989,10 @@ export function AutopilotsPage() {}initialTriggerConfig={selectedTemplate- ? { frequency: selectedTemplate.frequency, time: selectedTemplate.time }+ ? {+ frequency: selectedTemplate.frequency,+ time: selectedTemplate.time,+ }: undefined}/>diff --git a/packages/views/common/hover-check.tsx b/packages/views/common/hover-check.tsxnew file mode 100644index 0000000000..57a5792dfb--- /dev/null+++ b/packages/views/common/hover-check.tsx@@ -0,0 +1,23 @@+"use client";++import { Check } from "lucide-react";++// shadcn official pattern (PR #6862): a checkbox indicator that appears on+// item hover/focus inside DropdownMenuCheckboxItem rows. Pair it with+// FILTER_ITEM_CLASS on the item (hides the built-in indicator and names the+// hover group). Extracted from issues-header so every filter dropdown shares+// one implementation.++export const FILTER_ITEM_CLASS =+ "group/fitem pr-1.5! [&>[data-slot=dropdown-menu-checkbox-item-indicator]]:hidden";++export function HoverCheck({ checked }: { checked: boolean }) {+ return (+ <div+ className="border-input data-[selected=true]:border-primary data-[selected=true]:bg-primary data-[selected=true]:text-primary-foreground pointer-events-none size-4 shrink-0 rounded-[4px] border transition-all select-none *:[svg]:opacity-0 data-[selected=true]:*:[svg]:opacity-100 opacity-0 group-hover/fitem:opacity-100 group-focus/fitem:opacity-100 data-[selected=true]:opacity-100"+ data-selected={checked}+ >+ <Check className="size-3.5 text-current" />+ </div>+ );+}diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsxindex 1427425135..995eed179c 100644--- a/packages/views/issues/components/issues-header.tsx+++ b/packages/views/issues/components/issues-header.tsx@@ -5,7 +5,6 @@ import {ArrowDown,ArrowUp,ChartGantt,- Check,ChevronDown,CircleDot,Columns3,@@ -74,25 +73,9 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/import type { Issue } from "@multica/core/types";import { useT } from "../../i18n";import { matchesPinyin } from "../../editor/extensions/pinyin-match";+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";import { WorkspaceAgentWorkingChip } from "./workspace-agent-working-chip";-// ----------------------------------------------------------------------------// HoverCheck — shadcn official pattern (PR #6862)-// -----------------------------------------------------------------------------const FILTER_ITEM_CLASS =- "group/fitem pr-1.5! [&>[data-slot=dropdown-menu-checkbox-item-indicator]]:hidden";--function HoverCheck({ checked }: { checked: boolean }) {- return (- <div- className="border-input data-[selected=true]:border-primary data-[selected=true]:bg-primary data-[selected=true]:text-primary-foreground pointer-events-none size-4 shrink-0 rounded-[4px] border transition-all select-none *:[svg]:opacity-0 data-[selected=true]:*:[svg]:opacity-100 opacity-0 group-hover/fitem:opacity-100 group-focus/fitem:opacity-100 data-[selected=true]:opacity-100"- data-selected={checked}- >- <Check className="size-3.5 text-current" />- </div>- );-}// ---------------------------------------------------------------------------// Helpersdiff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 344f3f57cf..663b9c6b45 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -13,7 +13,8 @@},"scope": {"mine": "Mine",- "all": "All"+ "all": "All",+ "archived": "Archived"},"sort": {"label_recent": "Recent activity",@@ -66,7 +67,11 @@"workload": "Workload","runtime": "Runtime","activity_7d": "Activity (7d)",- "runs": "Runs"+ "runs": "Runs",+ "last_active": "Last active",+ "model": "Model",+ "created": "Created",+ "owner": "Owner"},"row": {"you": "You",@@ -74,7 +79,9 @@"no_description": "No description","fallback_runtime_cloud": "Cloud","fallback_runtime_local": "Local",- "actions_aria": "Row actions"+ "actions_aria": "Row actions",+ "task_count_one": "{{count}} task",+ "task_count_other": "{{count}} tasks"},"activity_tooltip": {"created_today": "Created today",@@ -465,5 +472,32 @@"runtime_offline": "Daemon offline","runtime_recovery": "Daemon restarted","manual": "Cancelled by user"+ },+ "last_active": {+ "today": "Today",+ "days_ago_one": "{{count}} day ago",+ "days_ago_other": "{{count}} days ago",+ "none": "No activity (30d)"+ },+ "toolbar": {+ "result_count_title": "Matching agents / agents in scope",+ "filter_label": "Filter",+ "filter_active_count_one": "{{count}} filter",+ "filter_active_count_other": "{{count}} filters",+ "clear_filters": "Clear filters",+ "section_availability": "Availability",+ "section_runtime": "Runtime",+ "display": "Display",+ "sort_by": "Sort by",+ "direction_asc": "Ascending",+ "direction_desc": "Descending",+ "section_columns": "Columns",+ "section_owner": "Owner",+ "section_model": "Model"+ },+ "actions": {+ "selected_one": "{{count}} selected",+ "selected_other": "{{count}} selected",+ "clear_selection": "Clear selection"}}diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex 108f018bbf..744b19045a 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -9,13 +9,20 @@"created_by": "Created by","mode": "Mode","status": "Status",- "last_run": "Last run"+ "last_run": "Last run",+ "assignee": "Assignee",+ "trigger": "Trigger",+ "next_run": "Next run",+ "created": "Created"},"last_run_empty": "--","empty": {"title": "No autopilots yet","hint": "Schedule recurring tasks for your AI agents. Pick a template or start from scratch."- }+ },+ "scope_all": "All",+ "no_matches": "No automations match",+ "retry": "Retry"},"status": {"active": "Active",@@ -97,8 +104,7 @@"running": "Running","skipped": "Skipped","completed": "Completed",- "failed": "Failed",- "skipped": "Skipped"+ "failed": "Failed"},"run_source": {"schedule": "Schedule",@@ -348,5 +354,39 @@},"timezone_picker": {"search_placeholder": "Search timezone..."+ },+ "toolbar": {+ "result_count_title": "Matching automations / all automations",+ "filter_label": "Filter",+ "filter_active_count_one": "{{count}} filter",+ "filter_active_count_other": "{{count}} filters",+ "clear_filters": "Clear filters",+ "section_assignee": "Assignee",+ "section_mode": "Mode",+ "section_trigger": "Trigger",+ "section_creator": "Created by",+ "display": "Display",+ "sort_by": "Sort by",+ "direction_asc": "Ascending",+ "direction_desc": "Descending",+ "section_columns": "Columns"+ },+ "actions": {+ "row_menu": "Automation actions",+ "pause": "Pause",+ "resume": "Resume",+ "delete": "Delete",+ "selected_one": "{{count}} selected",+ "selected_other": "{{count}} selected",+ "clear_selection": "Clear selection",+ "delete_dialog": {+ "title": "Delete automation?",+ "description_one": "This will permanently delete \"{{name}}\" and its run history.",+ "description_other": "This will permanently delete {{count}} automations and their run history.",+ "warning": "This action cannot be undone.",+ "cancel": "Cancel",+ "confirm": "Delete permanently",+ "deleting": "Deleting…"+ }}}diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.jsonindex 51f40647b8..a2f608640c 100644--- a/packages/views/locales/en/projects.json+++ b/packages/views/locales/en/projects.json@@ -7,7 +7,17 @@"view_compact": "Compact","view_comfortable": "Comfortable","search_placeholder": "Search projects...",- "no_search_results": "No results match your search"+ "no_search_results": "No results match your search",+ "view_table": "Table",+ "view_cards": "Cards",+ "row_menu": "Project actions",+ "pin": "Pin to sidebar",+ "unpin": "Unpin",+ "delete": "Delete",+ "no_matches": "No projects match",+ "selected_one": "{{count}} selected",+ "selected_other": "{{count}} selected",+ "clear_selection": "Clear selection"},"table": {"name": "Name",@@ -15,7 +25,8 @@"status": "Status","progress": "Progress","lead": "Lead",- "created": "Created"+ "created": "Created",+ "issues": "Issues"},"status": {"planned": "Planned",@@ -116,5 +127,21 @@},"chip": {"fallback_label": "Project"+ },+ "toolbar": {+ "result_count_title": "Matching projects / all projects",+ "filter_label": "Filter",+ "filter_active_count_one": "{{count}} filter",+ "filter_active_count_other": "{{count}} filters",+ "clear_filters": "Clear filters",+ "section_status": "Status",+ "section_priority": "Priority",+ "section_lead": "Lead",+ "display": "Display",+ "sort_by": "Sort by",+ "direction_asc": "Ascending",+ "direction_desc": "Descending",+ "section_columns": "Columns",+ "view": "View"}}diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex 45da062d3d..4177520a3b 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -257,7 +257,6 @@"col_health": "Health","col_owner": "Owner","col_agents": "Agents",- "col_workload": "Workload","col_cost": "Cost · 7d","col_cli": "CLI","cost_delta_flat": "flat",diff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.jsonindex 6287901417..12880dbd5a 100644--- a/packages/views/locales/en/skills.json+++ b/packages/views/locales/en/skills.json@@ -36,10 +36,11 @@},"table": {"name": "Name",+ "created_by": "Added by","used_by": "Used by",- "source": "Source · Added by",+ "source": "Source","updated": "Updated",- "no_description": "No description",+ "created": "Created","lock_tooltip": "Read-only — only creator or admin can edit","unused": "— unused","by_creator": "by {{name}}",@@ -51,6 +52,46 @@"source_skills_sh": "From Skills.sh","source_github": "From GitHub"},+ "actions": {+ "row_menu": "Actions",+ "add_to_agent": "Add to agent",+ "my_agents": "My agents",+ "other_agents": "Other agents",+ "no_agents": "No agents available",+ "has_partial": "{{owned}}/{{total}} added",+ "added_toast": "Added to {{name}}",+ "add_failed_toast": "Failed to add skill",+ "delete": "Delete",+ "selected": "{{count}} selected",+ "clear_selection": "Clear selection",+ "delete_no_permission": "Selection includes skills only their creator or an admin can delete",+ "delete_dialog_title_one": "Delete {{count}} skill?",+ "delete_dialog_title_other": "Delete {{count}} skills?",+ "delete_dialog_desc_one": "This will permanently delete the selected skill and remove it from all agents.",+ "delete_dialog_desc_other": "This will permanently delete the {{count}} selected skills and remove them from all agents.",+ "deleted_toast_one": "Deleted {{count}} skill",+ "deleted_toast_other": "Deleted {{count}} skills",+ "delete_failed_toast": "Failed to delete skills",+ "add_dialog_description": "Select the agents that should get the selected skills.",+ "cancel": "Cancel",+ "add_confirm": "Add ({{num}})",+ "adding": "Adding...",+ "added_multi_toast_one": "Added to {{count}} agent",+ "added_multi_toast_other": "Added to {{count}} agents"+ },+ "toolbar": {+ "result_count_title": "Matching skills / all skills",+ "filter_label": "Filter",+ "filter_active_count_one": "{{count}} filter",+ "filter_active_count_other": "{{count}} filters",+ "clear_filters": "Clear filters",+ "section_usage": "Usage",+ "display": "Display",+ "sort_by": "Sort by",+ "direction_asc": "Ascending",+ "direction_desc": "Descending",+ "section_columns": "Columns"+ },"detail": {"all_skills": "All skills","read_only": "Read-only",diff --git a/packages/views/locales/en/squads.json b/packages/views/locales/en/squads.jsonindex ec5f63ab04..dfb1f7d0d6 100644--- a/packages/views/locales/en/squads.json+++ b/packages/views/locales/en/squads.json@@ -3,7 +3,17 @@"title": "Squads","new_button": "New Squad","empty_no_squads": "No squads yet. Create one to get started.",- "empty_no_match": "No squads match your filters."+ "empty_no_match": "No squads match your filters.",+ "table": {+ "name": "Squad",+ "leader": "Leader",+ "members": "Members",+ "creator": "Created by",+ "created": "Created"+ },+ "no_matches": "No squads match",+ "row_menu": "Squad actions",+ "archive_action": "Archive"},"inspector": {"details_section": "Details",@@ -14,7 +24,8 @@"description": "\"{{name}}\" will be archived. Issues currently assigned to this squad will be transferred to its leader. This can't be undone — create a new squad if you need the routing back.","cancel": "Cancel","confirm": "Archive",- "archiving": "Archiving…"+ "archiving": "Archiving…",+ "success": "Squad archived"},"name_editor": {"cancel": "Cancel"@@ -72,5 +83,21 @@"description": "Squad instructions are injected into the leader agent's prompt whenever it works on an issue assigned to this squad. Use them to give the leader squad-wide guidance, working agreements, or context the leader should follow on every task.","unsaved_changes": "Unsaved changes","save_button": "Save"+ },+ "scope": {+ "mine": "Mine",+ "all": "All"+ },+ "toolbar": {+ "display": "Display",+ "sort_by": "Sort by",+ "direction_asc": "Ascending",+ "direction_desc": "Descending",+ "section_columns": "Columns",+ "result_count_title": "Matching squads / all squads",+ "filter_label": "Filter",+ "filter_active_count_one": "{{count}} filter",+ "filter_active_count_other": "{{count}} filters",+ "clear_filters": "Clear filters"}}diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 98da4952c3..c05cd93048 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -13,7 +13,8 @@},"scope": {"mine": "自分のもの",- "all": "すべて"+ "all": "すべて",+ "archived": "アーカイブ済み"},"sort": {"label_recent": "最近のアクティビティ",@@ -57,7 +58,11 @@"workload": "作業量","runtime": "ランタイム","activity_7d": "アクティビティ(7日)",- "runs": "実行"+ "runs": "実行",+ "last_active": "最終アクティブ",+ "model": "モデル",+ "created": "作成日時",+ "owner": "オーナー"},"row": {"you": "あなた",@@ -65,7 +70,9 @@"no_description": "説明なし","fallback_runtime_cloud": "クラウド","fallback_runtime_local": "ローカル",- "actions_aria": "行の操作"+ "actions_aria": "行の操作",+ "task_count_one": "{{count}} 件のタスク",+ "task_count_other": "{{count}} 件のタスク"},"activity_tooltip": {"created_today": "今日作成",@@ -453,5 +460,32 @@"section_cloud": "クラウド","agent_count_other": "エージェント {{count}} 件","empty": "まだマシンがありません"+ },+ "last_active": {+ "today": "今日",+ "days_ago_one": "{{count}} 日前",+ "days_ago_other": "{{count}} 日前",+ "none": "30 日間アクティビティなし"+ },+ "toolbar": {+ "result_count_title": "該当エージェント / スコープ内全体",+ "filter_label": "フィルター",+ "filter_active_count_one": "{{count}} 件のフィルター",+ "filter_active_count_other": "{{count}} 件のフィルター",+ "clear_filters": "フィルターをクリア",+ "section_availability": "可用性",+ "section_runtime": "ランタイム",+ "display": "表示",+ "sort_by": "並び替え",+ "direction_asc": "昇順",+ "direction_desc": "降順",+ "section_columns": "列",+ "section_owner": "オーナー",+ "section_model": "モデル"+ },+ "actions": {+ "selected_one": "{{count}} 件選択中",+ "selected_other": "{{count}} 件選択中",+ "clear_selection": "選択を解除"}}diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex 27bedaf627..caab517a7b 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -9,13 +9,20 @@"created_by": "作成者","mode": "モード","status": "ステータス",- "last_run": "最終実行"+ "last_run": "最終実行",+ "assignee": "担当",+ "trigger": "トリガー",+ "next_run": "次回実行",+ "created": "作成日時"},"last_run_empty": "--","empty": {"title": "まだオートパイロットがありません","hint": "AI エージェントの繰り返しタスクをスケジュールしましょう。テンプレートを選ぶか、ゼロから始められます。"- }+ },+ "scope_all": "すべて",+ "no_matches": "該当する自動化はありません",+ "retry": "再試行"},"status": {"active": "アクティブ",@@ -347,5 +354,39 @@},"timezone_picker": {"search_placeholder": "タイムゾーンを検索..."+ },+ "toolbar": {+ "result_count_title": "該当する自動化 / すべての自動化",+ "filter_label": "フィルター",+ "filter_active_count_one": "{{count}} 件のフィルター",+ "filter_active_count_other": "{{count}} 件のフィルター",+ "clear_filters": "フィルターをクリア",+ "section_assignee": "担当",+ "section_mode": "モード",+ "section_trigger": "トリガー",+ "section_creator": "作成者",+ "display": "表示",+ "sort_by": "並び替え",+ "direction_asc": "昇順",+ "direction_desc": "降順",+ "section_columns": "列"+ },+ "actions": {+ "row_menu": "自動化の操作",+ "pause": "一時停止",+ "resume": "再開",+ "delete": "削除",+ "selected_one": "{{count}} 件選択中",+ "selected_other": "{{count}} 件選択中",+ "clear_selection": "選択を解除",+ "delete_dialog": {+ "title": "自動化を削除しますか?",+ "description_one": "「{{name}}」とその実行履歴を完全に削除します。",+ "description_other": "{{count}} 件の自動化とその実行履歴を完全に削除します。",+ "warning": "この操作は取り消せません。",+ "cancel": "キャンセル",+ "confirm": "完全に削除",+ "deleting": "削除中…"+ }}}diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.jsonindex 87a761c7be..5e10de688d 100644--- a/packages/views/locales/ja/projects.json+++ b/packages/views/locales/ja/projects.json@@ -7,7 +7,17 @@"view_compact": "コンパクト","view_comfortable": "ゆったり","search_placeholder": "プロジェクトを検索...",- "no_search_results": "検索条件に一致する結果はありません"+ "no_search_results": "検索条件に一致する結果はありません",+ "view_table": "テーブル",+ "view_cards": "カード",+ "row_menu": "プロジェクトの操作",+ "pin": "サイドバーにピン留め",+ "unpin": "ピン留め解除",+ "delete": "削除",+ "no_matches": "該当するプロジェクトはありません",+ "selected_one": "{{count}} 件選択中",+ "selected_other": "{{count}} 件選択中",+ "clear_selection": "選択を解除"},"table": {"name": "名前",@@ -15,7 +25,8 @@"status": "ステータス","progress": "進捗","lead": "リード",- "created": "作成日"+ "created": "作成日",+ "issues": "Issue 数"},"status": {"planned": "計画中",@@ -116,5 +127,21 @@},"chip": {"fallback_label": "プロジェクト"+ },+ "toolbar": {+ "result_count_title": "該当プロジェクト / すべてのプロジェクト",+ "filter_label": "フィルター",+ "filter_active_count_one": "{{count}} 件のフィルター",+ "filter_active_count_other": "{{count}} 件のフィルター",+ "clear_filters": "フィルターをクリア",+ "section_status": "ステータス",+ "section_priority": "優先度",+ "section_lead": "リード",+ "display": "表示",+ "sort_by": "並び替え",+ "direction_asc": "昇順",+ "direction_desc": "降順",+ "section_columns": "列",+ "view": "ビュー"}}diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.jsonindex 622f2f78d1..fdb985c6db 100644--- a/packages/views/locales/ja/runtimes.json+++ b/packages/views/locales/ja/runtimes.json@@ -245,7 +245,6 @@"col_health": "状態","col_owner": "所有者","col_agents": "エージェント",- "col_workload": "作業量","col_cost": "コスト · 7 日","col_cli": "CLI","cost_delta_flat": "変化なし",diff --git a/packages/views/locales/ja/skills.json b/packages/views/locales/ja/skills.jsonindex ae72a940a7..c1fe96fea6 100644--- a/packages/views/locales/ja/skills.json+++ b/packages/views/locales/ja/skills.json@@ -36,10 +36,11 @@},"table": {"name": "名前",+ "created_by": "追加者","used_by": "使用中",- "source": "ソース · 追加者",+ "source": "ソース","updated": "更新日",- "no_description": "説明なし",+ "created": "作成日","lock_tooltip": "読み取り専用 — 作成者または管理者のみが編集できます","unused": "— 未使用","by_creator": "{{name}}",@@ -51,6 +52,46 @@"source_skills_sh": "Skills.sh から","source_github": "GitHub から"},+ "actions": {+ "row_menu": "操作",+ "add_to_agent": "エージェントに追加",+ "my_agents": "自分のエージェント",+ "other_agents": "その他のエージェント",+ "no_agents": "利用可能なエージェントがありません",+ "has_partial": "{{owned}}/{{total}} 追加済み",+ "added_toast": "{{name}} に追加しました",+ "add_failed_toast": "スキルの追加に失敗しました",+ "delete": "削除",+ "selected": "{{count}} 件選択中",+ "clear_selection": "選択を解除",+ "delete_no_permission": "作成者または管理者のみ削除できるスキルが含まれています",+ "delete_dialog_title_one": "{{count}} 件のスキルを削除しますか?",+ "delete_dialog_title_other": "{{count}} 件のスキルを削除しますか?",+ "delete_dialog_desc_one": "選択したスキルを完全に削除し、すべてのエージェントから取り外します。",+ "delete_dialog_desc_other": "選択した {{count}} 件のスキルを完全に削除し、すべてのエージェントから取り外します。",+ "deleted_toast_one": "{{count}} 件のスキルを削除しました",+ "deleted_toast_other": "{{count}} 件のスキルを削除しました",+ "delete_failed_toast": "スキルの削除に失敗しました",+ "add_dialog_description": "選択したスキルを追加するエージェントを選んでください。",+ "cancel": "キャンセル",+ "add_confirm": "追加({{num}})",+ "adding": "追加中...",+ "added_multi_toast_one": "{{count}} 件のエージェントに追加しました",+ "added_multi_toast_other": "{{count}} 件のエージェントに追加しました"+ },+ "toolbar": {+ "result_count_title": "該当スキル / 全スキル",+ "filter_label": "フィルター",+ "filter_active_count_one": "{{count}} 件のフィルター",+ "filter_active_count_other": "{{count}} 件のフィルター",+ "clear_filters": "フィルターを解除",+ "section_usage": "使用状況",+ "display": "表示",+ "sort_by": "並び替え",+ "direction_asc": "昇順",+ "direction_desc": "降順",+ "section_columns": "表示する列"+ },"detail": {"all_skills": "すべてのスキル","read_only": "読み取り専用",diff --git a/packages/views/locales/ja/squads.json b/packages/views/locales/ja/squads.jsonindex af578a672b..e593cf892f 100644--- a/packages/views/locales/ja/squads.json+++ b/packages/views/locales/ja/squads.json@@ -3,7 +3,17 @@"title": "スクワッド","new_button": "新規スクワッド","empty_no_squads": "スクワッドはまだありません。作成して始めましょう。",- "empty_no_match": "フィルターに一致するスクワッドはありません。"+ "empty_no_match": "フィルターに一致するスクワッドはありません。",+ "table": {+ "name": "スカッド",+ "leader": "リーダー",+ "members": "メンバー",+ "creator": "作成者",+ "created": "作成日時"+ },+ "no_matches": "該当するスカッドはありません",+ "row_menu": "スカッドの操作",+ "archive_action": "アーカイブ"},"inspector": {"details_section": "詳細",@@ -14,7 +24,8 @@"description": "\"{{name}}\" がアーカイブされます。現在このスクワッドに割り当てられているイシューはリーダーに引き継がれます。この操作は取り消せません。ルーティングを元に戻すには、新しいスクワッドを作成してください。","cancel": "キャンセル","confirm": "アーカイブ",- "archiving": "アーカイブ中…"+ "archiving": "アーカイブ中…",+ "success": "スカッドをアーカイブしました"},"name_editor": {"cancel": "キャンセル"@@ -69,5 +80,21 @@"description": "スクワッドの指示は、リーダーエージェントがこのスクワッドに割り当てられたイシューに取り組むたびに、そのプロンプトに挿入されます。スクワッド全体の方針、作業上の取り決め、リーダーがすべてのタスクで従うべきコンテキストを伝えるために使用します。","unsaved_changes": "保存していない変更","save_button": "保存"+ },+ "scope": {+ "mine": "自分",+ "all": "すべて"+ },+ "toolbar": {+ "display": "表示",+ "sort_by": "並び替え",+ "direction_asc": "昇順",+ "direction_desc": "降順",+ "section_columns": "列",+ "result_count_title": "該当スカッド / すべてのスカッド",+ "filter_label": "フィルター",+ "filter_active_count_one": "{{count}} 件のフィルター",+ "filter_active_count_other": "{{count}} 件のフィルター",+ "clear_filters": "フィルターをクリア"}}diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 7db3eeb359..8082c20783 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -13,7 +13,8 @@},"scope": {"mine": "내 것",- "all": "전체"+ "all": "전체",+ "archived": "보관됨"},"sort": {"label_recent": "최근 활동",@@ -66,7 +67,11 @@"workload": "작업량","runtime": "런타임","activity_7d": "활동(7일)",- "runs": "실행"+ "runs": "실행",+ "last_active": "최근 활동",+ "model": "모델",+ "created": "생성일",+ "owner": "소유자"},"row": {"you": "나",@@ -74,7 +79,9 @@"no_description": "설명 없음","fallback_runtime_cloud": "클라우드","fallback_runtime_local": "로컬",- "actions_aria": "행 작업"+ "actions_aria": "행 작업",+ "task_count_one": "태스크 {{count}}개",+ "task_count_other": "태스크 {{count}}개"},"activity_tooltip": {"created_today": "오늘 생성됨",@@ -465,5 +472,32 @@"runtime_offline": "데몬 오프라인","runtime_recovery": "데몬 재시작됨","manual": "사용자가 취소함"+ },+ "last_active": {+ "today": "오늘",+ "days_ago_one": "{{count}}일 전",+ "days_ago_other": "{{count}}일 전",+ "none": "30일간 활동 없음"+ },+ "toolbar": {+ "result_count_title": "일치하는 에이전트 / 범위 내 전체",+ "filter_label": "필터",+ "filter_active_count_one": "필터 {{count}}개",+ "filter_active_count_other": "필터 {{count}}개",+ "clear_filters": "필터 지우기",+ "section_availability": "가용성",+ "section_runtime": "런타임",+ "display": "표시",+ "sort_by": "정렬",+ "direction_asc": "오름차순",+ "direction_desc": "내림차순",+ "section_columns": "열",+ "section_owner": "소유자",+ "section_model": "모델"+ },+ "actions": {+ "selected_one": "{{count}}개 선택됨",+ "selected_other": "{{count}}개 선택됨",+ "clear_selection": "선택 해제"}}diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex edfbcbcff6..7876704d20 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -9,13 +9,20 @@"created_by": "생성자","mode": "모드","status": "상태",- "last_run": "마지막 실행"+ "last_run": "마지막 실행",+ "assignee": "담당",+ "trigger": "트리거",+ "next_run": "다음 실행",+ "created": "생성일"},"last_run_empty": "--","empty": {"title": "아직 오토파일럿이 없습니다","hint": "AI 에이전트의 반복 작업을 예약하세요. 템플릿을 고르거나 처음부터 시작할 수 있습니다."- }+ },+ "scope_all": "전체",+ "no_matches": "일치하는 자동화가 없습니다",+ "retry": "다시 시도"},"status": {"active": "활성",@@ -347,5 +354,39 @@},"timezone_picker": {"search_placeholder": "시간대 검색..."+ },+ "toolbar": {+ "result_count_title": "일치하는 자동화 / 전체 자동화",+ "filter_label": "필터",+ "filter_active_count_one": "필터 {{count}}개",+ "filter_active_count_other": "필터 {{count}}개",+ "clear_filters": "필터 지우기",+ "section_assignee": "담당",+ "section_mode": "모드",+ "section_trigger": "트리거",+ "section_creator": "생성자",+ "display": "표시",+ "sort_by": "정렬",+ "direction_asc": "오름차순",+ "direction_desc": "내림차순",+ "section_columns": "열"+ },+ "actions": {+ "row_menu": "자동화 작업",+ "pause": "일시중지",+ "resume": "재개",+ "delete": "삭제",+ "selected_one": "{{count}}개 선택됨",+ "selected_other": "{{count}}개 선택됨",+ "clear_selection": "선택 해제",+ "delete_dialog": {+ "title": "자동화를 삭제할까요?",+ "description_one": "\"{{name}}\" 및 실행 기록이 영구 삭제됩니다.",+ "description_other": "자동화 {{count}}개와 실행 기록이 영구 삭제됩니다.",+ "warning": "이 작업은 되돌릴 수 없습니다.",+ "cancel": "취소",+ "confirm": "영구 삭제",+ "deleting": "삭제 중…"+ }}}diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.jsonindex b3b89ccd12..7735bb222d 100644--- a/packages/views/locales/ko/projects.json+++ b/packages/views/locales/ko/projects.json@@ -7,7 +7,17 @@"view_compact": "간결하게","view_comfortable": "넓게","search_placeholder": "프로젝트 검색...",- "no_search_results": "검색 결과가 없습니다"+ "no_search_results": "검색 결과가 없습니다",+ "view_table": "테이블",+ "view_cards": "카드",+ "row_menu": "프로젝트 작업",+ "pin": "사이드바에 고정",+ "unpin": "고정 해제",+ "delete": "삭제",+ "no_matches": "일치하는 프로젝트가 없습니다",+ "selected_one": "{{count}}개 선택됨",+ "selected_other": "{{count}}개 선택됨",+ "clear_selection": "선택 해제"},"table": {"name": "이름",@@ -15,7 +25,8 @@"status": "상태","progress": "진행률","lead": "리드",- "created": "생성일"+ "created": "생성일",+ "issues": "이슈 수"},"status": {"planned": "계획됨",@@ -116,5 +127,21 @@},"chip": {"fallback_label": "프로젝트"+ },+ "toolbar": {+ "result_count_title": "일치하는 프로젝트 / 전체 프로젝트",+ "filter_label": "필터",+ "filter_active_count_one": "필터 {{count}}개",+ "filter_active_count_other": "필터 {{count}}개",+ "clear_filters": "필터 지우기",+ "section_status": "상태",+ "section_priority": "우선순위",+ "section_lead": "리드",+ "display": "표시",+ "sort_by": "정렬",+ "direction_asc": "오름차순",+ "direction_desc": "내림차순",+ "section_columns": "열",+ "view": "보기"}}diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.jsonindex 49b398ff08..7ee3a856e6 100644--- a/packages/views/locales/ko/runtimes.json+++ b/packages/views/locales/ko/runtimes.json@@ -257,7 +257,6 @@"col_health": "상태","col_owner": "소유자","col_agents": "에이전트",- "col_workload": "작업량","col_cost": "비용 · 7일","col_cli": "CLI","cost_delta_flat": "변화 없음",diff --git a/packages/views/locales/ko/skills.json b/packages/views/locales/ko/skills.jsonindex 562bcdf6f1..590174b3bf 100644--- a/packages/views/locales/ko/skills.json+++ b/packages/views/locales/ko/skills.json@@ -36,10 +36,11 @@},"table": {"name": "이름",+ "created_by": "추가한 사람","used_by": "사용 중",- "source": "출처 · 추가한 사람",+ "source": "출처","updated": "수정일",- "no_description": "설명 없음",+ "created": "생성일","lock_tooltip": "읽기 전용 — 생성자 또는 관리자만 수정할 수 있습니다","unused": "— 미사용","by_creator": "{{name}}님",@@ -51,6 +52,46 @@"source_skills_sh": "Skills.sh에서 가져옴","source_github": "GitHub에서 가져옴"},+ "actions": {+ "row_menu": "작업",+ "add_to_agent": "에이전트에 추가",+ "my_agents": "내 에이전트",+ "other_agents": "다른 에이전트",+ "no_agents": "사용 가능한 에이전트가 없습니다",+ "has_partial": "{{owned}}/{{total}} 보유",+ "added_toast": "{{name}}에 추가했습니다",+ "add_failed_toast": "스킬 추가에 실패했습니다",+ "delete": "삭제",+ "selected": "{{count}}개 선택됨",+ "clear_selection": "선택 해제",+ "delete_no_permission": "작성자 또는 관리자만 삭제할 수 있는 스킬이 포함되어 있습니다",+ "delete_dialog_title_one": "스킬 {{count}}개를 삭제할까요?",+ "delete_dialog_title_other": "스킬 {{count}}개를 삭제할까요?",+ "delete_dialog_desc_one": "선택한 스킬을 영구 삭제하고 모든 에이전트에서 제거합니다.",+ "delete_dialog_desc_other": "선택한 스킬 {{count}}개를 영구 삭제하고 모든 에이전트에서 제거합니다.",+ "deleted_toast_one": "스킬 {{count}}개를 삭제했습니다",+ "deleted_toast_other": "스킬 {{count}}개를 삭제했습니다",+ "delete_failed_toast": "스킬 삭제에 실패했습니다",+ "add_dialog_description": "선택한 스킬을 추가할 에이전트를 선택하세요.",+ "cancel": "취소",+ "add_confirm": "추가 ({{num}})",+ "adding": "추가 중...",+ "added_multi_toast_one": "에이전트 {{count}}개에 추가했습니다",+ "added_multi_toast_other": "에이전트 {{count}}개에 추가했습니다"+ },+ "toolbar": {+ "result_count_title": "일치하는 스킬 / 전체 스킬",+ "filter_label": "필터",+ "filter_active_count_one": "필터 {{count}}개",+ "filter_active_count_other": "필터 {{count}}개",+ "clear_filters": "필터 해제",+ "section_usage": "사용 상태",+ "display": "표시",+ "sort_by": "정렬",+ "direction_asc": "오름차순",+ "direction_desc": "내림차순",+ "section_columns": "표시 열"+ },"detail": {"all_skills": "모든 스킬","read_only": "읽기 전용",diff --git a/packages/views/locales/ko/squads.json b/packages/views/locales/ko/squads.jsonindex cf2bbce8da..7376c29372 100644--- a/packages/views/locales/ko/squads.json+++ b/packages/views/locales/ko/squads.json@@ -3,7 +3,17 @@"title": "스쿼드","new_button": "새 스쿼드","empty_no_squads": "아직 스쿼드가 없습니다. 하나 만들어 시작하세요.",- "empty_no_match": "필터와 일치하는 스쿼드가 없습니다."+ "empty_no_match": "필터와 일치하는 스쿼드가 없습니다.",+ "table": {+ "name": "스쿼드",+ "leader": "리더",+ "members": "멤버",+ "creator": "생성자",+ "created": "생성일"+ },+ "no_matches": "일치하는 스쿼드가 없습니다",+ "row_menu": "스쿼드 작업",+ "archive_action": "보관"},"inspector": {"details_section": "세부 정보",@@ -14,7 +24,8 @@"description": "\"{{name}}\"이(가) 보관됩니다. 현재 이 스쿼드에 할당된 이슈는 리더에게 이전됩니다. 이 작업은 되돌릴 수 없습니다. 라우팅을 다시 쓰려면 새 스쿼드를 만드세요.","cancel": "취소","confirm": "보관",- "archiving": "보관하는 중..."+ "archiving": "보관하는 중...",+ "success": "스쿼드를 보관했습니다"},"name_editor": {"cancel": "취소"@@ -72,5 +83,21 @@"description": "스쿼드에 할당된 이슈를 리더 에이전트가 처리할 때마다 스쿼드 지침이 리더 프롬프트에 포함됩니다. 스쿼드 전체의 방향, 작업 합의, 매 작업마다 따라야 할 맥락을 리더에게 전달할 때 사용하세요.","unsaved_changes": "저장하지 않은 변경사항","save_button": "저장"+ },+ "scope": {+ "mine": "내 스쿼드",+ "all": "전체"+ },+ "toolbar": {+ "display": "표시",+ "sort_by": "정렬",+ "direction_asc": "오름차순",+ "direction_desc": "내림차순",+ "section_columns": "열",+ "result_count_title": "일치하는 스쿼드 / 전체 스쿼드",+ "filter_label": "필터",+ "filter_active_count_one": "필터 {{count}}개",+ "filter_active_count_other": "필터 {{count}}개",+ "clear_filters": "필터 지우기"}}diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 45bf90e36d..ac15274752 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -13,7 +13,8 @@},"scope": {"mine": "我的",- "all": "全部"+ "all": "全部",+ "archived": "已归档"},"sort": {"label_recent": "最近活跃",@@ -65,7 +66,11 @@"workload": "工作负载","runtime": "运行时","activity_7d": "活动(7 天)",- "runs": "运行次数"+ "runs": "运行次数",+ "last_active": "最近活跃",+ "model": "模型",+ "created": "创建时间",+ "owner": "Owner"},"row": {"you": "你",@@ -73,7 +78,9 @@"no_description": "暂无描述","fallback_runtime_cloud": "云端","fallback_runtime_local": "本地",- "actions_aria": "行操作"+ "actions_aria": "行操作",+ "task_count_one": "{{count}} 个任务",+ "task_count_other": "{{count}} 个任务"},"activity_tooltip": {"created_today": "今天创建",@@ -453,5 +460,32 @@"runtime_offline": "守护进程离线","runtime_recovery": "守护进程已重启","manual": "用户取消"+ },+ "last_active": {+ "today": "今天",+ "days_ago_one": "{{count}} 天前",+ "days_ago_other": "{{count}} 天前",+ "none": "30 天内无活动"+ },+ "toolbar": {+ "result_count_title": "当前结果 / 范围内全部",+ "filter_label": "筛选",+ "filter_active_count_one": "{{count}} 项筛选",+ "filter_active_count_other": "{{count}} 项筛选",+ "clear_filters": "清除筛选",+ "section_availability": "可用性",+ "section_runtime": "运行时",+ "display": "显示",+ "sort_by": "排序",+ "direction_asc": "升序",+ "direction_desc": "降序",+ "section_columns": "列",+ "section_owner": "Owner",+ "section_model": "模型"+ },+ "actions": {+ "selected_one": "已选 {{count}} 项",+ "selected_other": "已选 {{count}} 项",+ "clear_selection": "清除选择"}}diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex ae674cda6e..9229ed1708 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -9,13 +9,20 @@"created_by": "创建者","mode": "模式","status": "状态",- "last_run": "上次运行"+ "last_run": "上次运行",+ "assignee": "执行者",+ "trigger": "触发器",+ "next_run": "下次运行",+ "created": "创建时间"},"last_run_empty": "--","empty": {"title": "还没有自动化","hint": "为你的智能体安排周期性 task。从模板选一个,或从空白开始。"- }+ },+ "scope_all": "全部",+ "no_matches": "没有匹配的自动化",+ "retry": "重试"},"status": {"active": "启用",@@ -97,8 +104,7 @@"running": "运行中","skipped": "已跳过","completed": "已完成",- "failed": "失败",- "skipped": "已跳过"+ "failed": "失败"},"run_source": {"schedule": "时间表",@@ -348,5 +354,39 @@},"timezone_picker": {"search_placeholder": "搜索时区..."+ },+ "toolbar": {+ "result_count_title": "当前结果 / 全部自动化",+ "filter_label": "筛选",+ "filter_active_count_one": "{{count}} 项筛选",+ "filter_active_count_other": "{{count}} 项筛选",+ "clear_filters": "清除筛选",+ "section_assignee": "执行者",+ "section_mode": "模式",+ "section_trigger": "触发器",+ "section_creator": "创建者",+ "display": "显示",+ "sort_by": "排序",+ "direction_asc": "升序",+ "direction_desc": "降序",+ "section_columns": "列"+ },+ "actions": {+ "row_menu": "自动化操作",+ "pause": "暂停",+ "resume": "恢复",+ "delete": "删除",+ "selected_one": "已选 {{count}} 项",+ "selected_other": "已选 {{count}} 项",+ "clear_selection": "清除选择",+ "delete_dialog": {+ "title": "删除自动化?",+ "description_one": "将永久删除“{{name}}”及其运行历史。",+ "description_other": "将永久删除 {{count}} 个自动化及其运行历史。",+ "warning": "此操作无法撤销。",+ "cancel": "取消",+ "confirm": "永久删除",+ "deleting": "删除中…"+ }}}diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.jsonindex 6f8ff926b3..a346136acc 100644--- a/packages/views/locales/zh-Hans/projects.json+++ b/packages/views/locales/zh-Hans/projects.json@@ -7,7 +7,17 @@"view_compact": "紧凑视图","view_comfortable": "舒适视图","search_placeholder": "搜索项目...",- "no_search_results": "未找到匹配的项目"+ "no_search_results": "未找到匹配的项目",+ "view_table": "表格",+ "view_cards": "卡片",+ "row_menu": "项目操作",+ "pin": "钉到侧边栏",+ "unpin": "取消钉选",+ "delete": "删除",+ "no_matches": "没有匹配的项目",+ "selected_one": "已选 {{count}} 项",+ "selected_other": "已选 {{count}} 项",+ "clear_selection": "清除选择"},"table": {"name": "名称",@@ -15,7 +25,8 @@"status": "状态","progress": "进度","lead": "负责人",- "created": "创建时间"+ "created": "创建时间",+ "issues": "Issue 数"},"status": {"planned": "计划中",@@ -116,5 +127,21 @@},"chip": {"fallback_label": "项目"+ },+ "toolbar": {+ "result_count_title": "当前结果 / 全部项目",+ "filter_label": "筛选",+ "filter_active_count_one": "{{count}} 项筛选",+ "filter_active_count_other": "{{count}} 项筛选",+ "clear_filters": "清除筛选",+ "section_status": "状态",+ "section_priority": "优先级",+ "section_lead": "负责人",+ "display": "显示",+ "sort_by": "排序",+ "direction_asc": "升序",+ "direction_desc": "降序",+ "section_columns": "列",+ "view": "视图"}}diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex 4e0d6ca52f..8b7153b4c4 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -245,7 +245,6 @@"col_health": "健康度","col_owner": "所有者","col_agents": "智能体",- "col_workload": "工作负载","col_cost": "费用 · 7 天","col_cli": "CLI","cost_delta_flat": "持平",diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.jsonindex 484cb4be64..3e8c1bdbc5 100644--- a/packages/views/locales/zh-Hans/skills.json+++ b/packages/views/locales/zh-Hans/skills.json@@ -48,10 +48,11 @@},"table": {"name": "名称",+ "created_by": "添加者","used_by": "被谁使用",- "source": "来源 · 添加者",+ "source": "来源","updated": "更新时间",- "no_description": "无描述",+ "created": "创建时间","lock_tooltip": "只读——只有创建者或管理员能编辑","unused": "— 未使用","by_creator": "由 {{name}} 创建",@@ -63,6 +64,46 @@"source_skills_sh": "来自 Skills.sh","source_github": "来自 GitHub"},+ "actions": {+ "row_menu": "操作",+ "add_to_agent": "添加到智能体",+ "my_agents": "我的智能体",+ "other_agents": "其他智能体",+ "no_agents": "暂无可用智能体",+ "has_partial": "已有 {{owned}}/{{total}}",+ "added_toast": "已添加到 {{name}}",+ "add_failed_toast": "添加 skill 失败",+ "delete": "删除",+ "selected": "已选 {{count}} 项",+ "clear_selection": "清除选择",+ "delete_no_permission": "选中项包含仅创建者或管理员可删除的 skill",+ "delete_dialog_title_one": "删除 {{count}} 个 skill?",+ "delete_dialog_title_other": "删除 {{count}} 个 skill?",+ "delete_dialog_desc_one": "将永久删除选中的 skill,并从所有智能体上移除。",+ "delete_dialog_desc_other": "将永久删除选中的 {{count}} 个 skill,并从所有智能体上移除。",+ "deleted_toast_one": "已删除 {{count}} 个 skill",+ "deleted_toast_other": "已删除 {{count}} 个 skill",+ "delete_failed_toast": "删除 skill 失败",+ "add_dialog_description": "选择要获得所选 skill 的智能体。",+ "cancel": "取消",+ "add_confirm": "添加({{num}})",+ "adding": "添加中...",+ "added_multi_toast_one": "已添加到 {{count}} 个智能体",+ "added_multi_toast_other": "已添加到 {{count}} 个智能体"+ },+ "toolbar": {+ "result_count_title": "当前结果 / 全部 skill",+ "filter_label": "筛选",+ "filter_active_count_one": "{{count}} 项筛选",+ "filter_active_count_other": "{{count}} 项筛选",+ "clear_filters": "清除筛选",+ "section_usage": "使用状态",+ "display": "显示",+ "sort_by": "排序",+ "direction_asc": "升序",+ "direction_desc": "降序",+ "section_columns": "显示列"+ },"detail": {"all_skills": "全部 skill","read_only": "只读",diff --git a/packages/views/locales/zh-Hans/squads.json b/packages/views/locales/zh-Hans/squads.jsonindex d19616e5d6..f9fb893287 100644--- a/packages/views/locales/zh-Hans/squads.json+++ b/packages/views/locales/zh-Hans/squads.json@@ -3,7 +3,17 @@"title": "小队","new_button": "新建小队","empty_no_squads": "还没有小队,创建一个开始吧。",- "empty_no_match": "没有匹配筛选条件的小队。"+ "empty_no_match": "没有匹配筛选条件的小队。",+ "table": {+ "name": "小队",+ "leader": "队长",+ "members": "成员",+ "creator": "创建者",+ "created": "创建时间"+ },+ "no_matches": "没有匹配的小队",+ "row_menu": "小队操作",+ "archive_action": "归档"},"inspector": {"details_section": "详情",@@ -14,7 +24,8 @@"description": "“{{name}}” 将被归档,该小队当前承接的 issue 会转交给小队负责人。此操作无法撤销,如需恢复路由请新建小队。","cancel": "取消","confirm": "归档",- "archiving": "归档中…"+ "archiving": "归档中…",+ "success": "已归档小队"},"name_editor": {"cancel": "取消"@@ -72,5 +83,21 @@"description": "小队指引会在 Leader 智能体处理分配给该小队的 issue 时注入到它的 prompt 中。可用来给 Leader 提供贯穿全队的指导、协作规范,或每次任务都应遵循的上下文。","unsaved_changes": "有未保存的修改","save_button": "保存"+ },+ "scope": {+ "mine": "我的",+ "all": "全部"+ },+ "toolbar": {+ "display": "显示",+ "sort_by": "排序",+ "direction_asc": "升序",+ "direction_desc": "降序",+ "section_columns": "列",+ "result_count_title": "当前结果 / 全部小队",+ "filter_label": "筛选",+ "filter_active_count_one": "{{count}} 项筛选",+ "filter_active_count_other": "{{count}} 项筛选",+ "clear_filters": "清除筛选"}}diff --git a/packages/views/package.json b/packages/views/package.jsonindex 895a2eb5a9..f48a753646 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -62,6 +62,7 @@"@floating-ui/dom": "^1.7.6","@multica/core": "workspace:*","@multica/ui": "workspace:*",+ "@tanstack/react-virtual": "catalog:","@tiptap/core": "^3.22.1","@tiptap/extension-code-block-lowlight": "^3.22.1","@tiptap/extension-document": "^3.22.1",@@ -97,10 +98,10 @@"recharts": "3.8.0","rehype-katex": "catalog:","rehype-raw": "^7.0.0",+ "rehype-sanitize": "^6.0.0","remark-breaks": "^4.0.0","remark-gfm": "^4.0.1","remark-math": "catalog:",- "rehype-sanitize": "^6.0.0","sonner": "^2.0.7"},"peerDependencies": {diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsxindex ecfd5f0535..f43e35c87e 100644--- a/packages/views/projects/components/projects-page.tsx+++ b/packages/views/projects/components/projects-page.tsx@@ -1,73 +1,588 @@"use client";import { useCallback, useMemo, useState } from "react";-import { Plus, FolderKanban, Rows3, LayoutGrid, Search } from "lucide-react";+import {+ ArrowDown,+ ArrowUp,+ ChevronDown,+ Filter,+ FolderKanban,+ LayoutGrid,+ MoreHorizontal,+ Pin,+ PinOff,+ Plus,+ Rows3,+ Search,+ Trash2,+ X,+} from "lucide-react";import { useQuery } from "@tanstack/react-query";-import { projectListOptions } from "@multica/core/projects/queries";-import { useUpdateProject } from "@multica/core/projects/mutations";+import { toast } from "sonner";+import {+ projectListOptions,+ useUpdateProject,+ useDeleteProject,+ useProjectViewStore,+ type ProjectColumnKey,+ type ProjectListFilters,+ type ProjectSortField,+} from "@multica/core/projects";+import {+ pinListOptions,+ useCreatePin,+ useDeletePin,+} from "@multica/core/pins";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";+import { useAuthStore } from "@multica/core/auth";+import { useActorName } from "@multica/core/workspace/hooks";+import { memberListOptions } from "@multica/core/workspace/queries";import { useModalStore } from "@multica/core/modals";import { AppLink } from "../../navigation";import { ActorAvatar } from "../../common/actor-avatar";+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";import { Input } from "@multica/ui/components/ui/input";-import { cn } from "@multica/ui/lib/utils";-import type { Project, UpdateProjectRequest } from "@multica/core/types";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ ListGrid,+ ListGridCell,+ ListGridHeader,+ ListGridHeaderCell,+ ListGridRow,+ LIST_GRID_BOTTOM_CLEARANCE,+ type ListGridSortDirection,+} from "@multica/ui/components/ui/list-grid";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { Switch } from "@multica/ui/components/ui/switch";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import type {+ MemberWithUser,+ Project,+ ProjectPriority,+ ProjectStatus,+ UpdateProjectRequest,+} from "@multica/core/types";import { PageHeader } from "../../layout/page-header";import { ProjectIcon } from "./project-icon";import { useT } from "../../i18n";import { matchesPinyin } from "../../editor/extensions/pinyin-match";import { useFormatRelativeDate } from "./labels";-import { useProjectViewStore } from "@multica/core/projects";import { ProjectStatusBadge, ProjectPriorityBadge } from "./project-badge";import { ProjectLeadPicker } from "./project-lead-picker";-const COMPACT_GRID = "grid w-full min-w-[740px] grid-cols-[24px_minmax(200px,1fr)_96px_96px_80px_80px_80px]";+// Sort order maps for the enum columns (header sort needs a total order).+const PRIORITY_ORDER: Record<ProjectPriority, number> = {+ urgent: 4,+ high: 3,+ medium: 2,+ low: 1,+ none: 0,+};+const STATUS_ORDER: Record<ProjectStatus, number> = {+ planned: 0,+ in_progress: 1,+ paused: 2,+ completed: 3,+ cancelled: 4,+};-function ProjectCard({ project }: { project: Project }) {+const progressOf = (p: Project) =>+ p.issue_count > 0 ? p.done_count / p.issue_count : -1;++// Composite "type:id" lead value so the string[] filter holds member/agent+// refs alike.+function leadFilterValue(p: Project): string | null {+ return p.lead_type && p.lead_id ? `${p.lead_type}:${p.lead_id}` : null;+}++// ---------------------------------------------------------------------------+// Table (compact) view — ListGrid. Name + status are the core columns;+// priority/progress/lead/issues/created collapse below @2xl, with min-width+// + the wrapper's overflow as the escape valve. Rows are NOT whole-row+// links: the name is the navigation target and the rest of the row is+// inline-editable (status/priority/lead pickers), matching the prior+// behaviour and avoiding navigate-vs-edit conflicts.+// ---------------------------------------------------------------------------++const COLUMN_WIDTHS: Record<ProjectColumnKey, number> = {+ priority: 116,+ progress: 88,+ lead: 132,+ issues: 80,+ created: 104,+};++// Fixed tracks: edges 12+12, checkbox 16, name min 200, status 116,+// kebab 28 = 384, plus the 10 gap-x-3 gaps between the wide template's+// 11 tracks.+const FIXED_TRACKS_WIDTH = 384 + 10 * 12;++// Render/track order: checkbox, name, status (core, fixed 116px), priority,+// progress, lead, issues, created, kebab. MUST be a literal string —+// Tailwind can't see interpolated `grid-cols-[...]` arbitrary values, so an+// interpolated width silently drops the whole template and the grid+// collapses to one column.+const GRID_COLS =+ "grid-cols-[0.75rem_1rem_minmax(120px,1fr)_116px_1.75rem_0.75rem] " ++ "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_116px_var(--pjc-priority)_var(--pjc-progress)_var(--pjc-lead)_var(--pjc-issues)_var(--pjc-created)_1.75rem_0.75rem]";++function columnTrackVars(+ isVisible: (key: ProjectColumnKey) => boolean,+): React.CSSProperties {+ const width = (key: ProjectColumnKey) =>+ isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";+ const minWidth =+ FIXED_TRACKS_WIDTH ++ (Object.keys(COLUMN_WIDTHS) as ProjectColumnKey[]).reduce(+ (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),+ 0,+ );+ return {+ "--pjc-priority": width("priority"),+ "--pjc-progress": width("progress"),+ "--pjc-lead": width("lead"),+ "--pjc-issues": width("issues"),+ "--pjc-created": width("created"),+ "--pjc-minw": `${minWidth}px`,+ } as React.CSSProperties;+}++function ProgressRing({ project }: { project: Project }) {+ if (project.issue_count === 0) {+ return <span className="text-xs text-muted-foreground/40">—</span>;+ }+ const pct = Math.round((project.done_count / project.issue_count) * 100);+ return (+ <span className="flex items-center gap-1.5">+ <span className="relative h-3.5 w-3.5">+ <svg className="h-3.5 w-3.5 -rotate-90" viewBox="0 0 16 16">+ <circle className="text-muted" strokeWidth="2" stroke="currentColor" fill="none" r="6" cx="8" cy="8" />+ <circle+ className="text-emerald-500"+ strokeWidth="2"+ stroke="currentColor"+ fill="none"+ r="6"+ cx="8"+ cy="8"+ strokeDasharray={`${pct * 0.377} 37.7`}+ strokeLinecap="round"+ />+ </svg>+ </span>+ <span className="text-xs tabular-nums text-muted-foreground">+ {project.done_count}/{project.issue_count}+ </span>+ </span>+ );+}++// Interactive cell wrapper: the inline pickers live in a non-navigating row,+// so they need no stopPropagation, but keep edits from bubbling oddly.+function ProjectRowActions({+ project,+ pinned,+ canDelete,+}: {+ project: Project;+ pinned: boolean;+ canDelete: boolean;+}) {const { t } = useT("projects");+ const createPin = useCreatePin();+ const deletePin = useDeletePin();+ const deleteProject = useDeleteProject();+ const [deleteOpen, setDeleteOpen] = useState(false);++ const togglePin = () => {+ if (pinned) deletePin.mutate({ itemType: "project", itemId: project.id });+ else createPin.mutate({ item_type: "project", item_id: project.id });+ };++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ aria-label={t(($) => $.page.row_menu)}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"+ >+ <MoreHorizontal className="size-4" />+ </button>+ }+ />+ <DropdownMenuContent align="end" className="w-44">+ <DropdownMenuItem onClick={togglePin}>+ {pinned ? (+ <PinOff className="size-3.5" />+ ) : (+ <Pin className="size-3.5" />+ )}+ {pinned ? t(($) => $.page.unpin) : t(($) => $.page.pin)}+ </DropdownMenuItem>+ {canDelete && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleteOpen(true)}+ >+ <Trash2 className="size-3.5" />+ {t(($) => $.page.delete)}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>++ <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t(($) => $.delete_dialog.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.delete_dialog.description)}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => setDeleteOpen(false)}+ >+ {t(($) => $.delete_dialog.cancel)}+ </Button>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={() => {+ deleteProject.mutate(project.id, {+ onError: (err) =>+ toast.error(+ err instanceof Error ? err.message : String(err),+ ),+ });+ setDeleteOpen(false);+ }}+ >+ {t(($) => $.delete_dialog.confirm)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}++function CheckboxCell({+ checked,+ onToggle,+}: {+ checked: boolean;+ onToggle: () => void;+}) {+ return (+ <ListGridCell className="justify-center px-0">+ <button+ type="button"+ aria-pressed={checked}+ onClick={onToggle}+ className={`-m-1.5 flex items-center p-1.5 ${+ checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"+ }`}+ >+ <Checkbox checked={checked} tabIndex={-1} className="pointer-events-none" />+ </button>+ </ListGridCell>+ );+}++function ProjectTableRow({+ project,+ pinned,+ canDelete,+ isColVisible,+ selected,+ onToggleSelect,+}: {+ project: Project;+ pinned: boolean;+ canDelete: boolean;+ isColVisible: (key: ProjectColumnKey) => boolean;+ selected: boolean;+ onToggleSelect: () => void;+}) {const wsPaths = useWorkspacePaths();const formatRelativeDate = useFormatRelativeDate();const updateProject = useUpdateProject();-const handleUpdate = useCallback(- (data: UpdateProjectRequest) => {- updateProject.mutate({ id: project.id, ...data });- },+ (data: UpdateProjectRequest) => updateProject.mutate({ id: project.id, ...data }),[project.id, updateProject],);- const progressPercent = project.issue_count > 0 ? Math.round((project.done_count / project.issue_count) * 100) : 0;+ return (+ <ListGridRow className={`h-11 ${selected ? "bg-accent/30" : ""}`}>+ <CheckboxCell checked={selected} onToggle={onToggleSelect} />+ <ListGridCell className="gap-2">+ <ProjectIcon project={project} size="sm" />+ <AppLink+ href={wsPaths.projectDetail(project.id)}+ className="min-w-0 truncate text-sm font-medium hover:underline"+ >+ {project.title}+ </AppLink>+ </ListGridCell>++ {/* status — core column, always visible */}+ <ListGridCell>+ <ProjectStatusBadge project={project} handleUpdate={handleUpdate} align="start" />+ </ListGridCell>++ {isColVisible("priority") ? (+ <ListGridCell className="hidden @2xl:flex">+ <ProjectPriorityBadge project={project} handleUpdate={handleUpdate} align="start" />+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}++ {isColVisible("progress") ? (+ <ListGridCell className="hidden @2xl:flex">+ <ProgressRing project={project} />+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}++ {isColVisible("lead") ? (+ <ListGridCell className="hidden @2xl:flex">+ <ProjectLeadPicker+ project={project}+ handleUpdate={handleUpdate}+ align="start"+ renderTrigger={(leadName) => (+ <button+ type="button"+ className="flex min-w-0 items-center gap-1.5 rounded px-1 py-0.5 transition-colors hover:bg-accent/60"+ >+ {project.lead_type && project.lead_id ? (+ <ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size={18} enableHoverCard />+ ) : (+ <span className="inline-flex h-[18px] w-[18px] rounded-full border border-dashed border-muted-foreground/30" />+ )}+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {leadName ?? "—"}+ </span>+ </button>+ )}+ />+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}++ {isColVisible("issues") ? (+ <ListGridCell className="hidden justify-end font-mono text-xs tabular-nums text-muted-foreground @2xl:flex">+ {project.issue_count}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}++ {isColVisible("created") ? (+ <ListGridCell className="hidden whitespace-nowrap text-xs tabular-nums text-muted-foreground @2xl:flex">+ {formatRelativeDate(project.created_at)}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}++ <ListGridCell className="justify-end px-0">+ <ProjectRowActions project={project} pinned={pinned} canDelete={canDelete} />+ </ListGridCell>+ </ListGridRow>+ );+}++function ProjectTableHeader({+ sortField,+ sortDirection,+ onSort,+ isColVisible,+ allSelected,+ someSelected,+ onToggleAll,+}: {+ sortField: ProjectSortField;+ sortDirection: ListGridSortDirection;+ onSort: (field: ProjectSortField) => void;+ isColVisible: (key: ProjectColumnKey) => boolean;+ allSelected: boolean;+ someSelected: boolean;+ onToggleAll: () => void;+}) {+ const { t } = useT("projects");+ const sorted = (field: ProjectSortField) =>+ sortField === field ? sortDirection : false;+ const anySelected = allSelected || someSelected;+ return (+ <ListGridHeader>+ <div className="flex items-center justify-center">+ <button+ type="button"+ aria-pressed={allSelected}+ onClick={onToggleAll}+ className={`-m-1.5 flex items-center p-1.5 ${+ anySelected ? "" : "opacity-0 transition-opacity group-hover/header:opacity-100"+ }`}+ >+ <Checkbox+ checked={allSelected}+ indeterminate={someSelected && !allSelected}+ tabIndex={-1}+ className="pointer-events-none"+ />+ </button>+ </div>+ <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>+ {t(($) => $.table.name)}+ </ListGridHeaderCell>+ <ListGridHeaderCell sorted={sorted("status")} onSort={() => onSort("status")}>+ {t(($) => $.table.status)}+ </ListGridHeaderCell>+ {isColVisible("priority") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("priority")}+ onSort={() => onSort("priority")}+ >+ {t(($) => $.table.priority)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("progress") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("progress")}+ onSort={() => onSort("progress")}+ >+ {t(($) => $.table.progress)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("lead") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.table.lead)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("issues") ? (+ <ListGridHeaderCell className="hidden justify-end @2xl:flex" align="right">+ {t(($) => $.table.issues)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("created")}+ onSort={() => onSort("created")}+ >+ {t(($) => $.table.created)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ <span aria-hidden="true" />+ </ListGridHeader>+ );+}++// ---------------------------------------------------------------------------+// Card (comfortable) view — kept from the prior page.+// ---------------------------------------------------------------------------++function ProjectCard({+ project,+ pinned,+ canDelete,+}: {+ project: Project;+ pinned: boolean;+ canDelete: boolean;+}) {+ const { t } = useT("projects");+ const wsPaths = useWorkspacePaths();+ const formatRelativeDate = useFormatRelativeDate();+ const updateProject = useUpdateProject();+ const handleUpdate = useCallback(+ (data: UpdateProjectRequest) => updateProject.mutate({ id: project.id, ...data }),+ [project.id, updateProject],+ );+ const progressPercent =+ project.issue_count > 0+ ? Math.round((project.done_count / project.issue_count) * 100)+ : 0;return (- <div className="group/card flex flex-col rounded-md border bg-card hover:border-primary/50 transition-colors">+ <div className="group/card group/row flex flex-col rounded-md border bg-card transition-colors hover:border-primary/50"><div className="p-3 pb-2"><div className="flex items-center gap-2"><AppLinkhref={wsPaths.projectDetail(project.id)}- className="flex items-center gap-2 min-w-0 flex-1"+ className="flex min-w-0 flex-1 items-center gap-2"><ProjectIcon project={project} size="sm" />- <h3 className="font-medium text-sm truncate">{project.title}</h3>+ <h3 className="truncate text-sm font-medium">{project.title}</h3></AppLink>+ <ProjectRowActions project={project} pinned={pinned} canDelete={canDelete} /><ProjectStatusBadge project={project} handleUpdate={handleUpdate} triggerClassName="shrink-0" /></div>{project.issue_count > 0 ? (- <div className="flex justify-end items-center gap-1.5 pt-2">+ <div className="flex items-center justify-end gap-1.5 pt-2"><div className="relative h-4 w-4"><svg className="h-4 w-4 -rotate-90" viewBox="0 0 16 16">- <circle- className="text-muted"- strokeWidth="2"- stroke="currentColor"- fill="none"- r="6"- cx="8"- cy="8"- />+ <circle className="text-muted" strokeWidth="2" stroke="currentColor" fill="none" r="6" cx="8" cy="8" /><circleclassName="text-emerald-500"strokeWidth="2"@@ -81,33 +596,34 @@ function ProjectCard({ project }: { project: Project }) {/></svg></div>- <span className="text-[10px] text-muted-foreground tabular-nums">+ <span className="text-[10px] tabular-nums text-muted-foreground">{project.done_count}/{project.issue_count}</span></div>) : (- <span className="text-[10px] text-muted-foreground pt-2 flex justify-end">{t(($) => $.detail.no_issues_yet)}</span>+ <span className="flex justify-end pt-2 text-[10px] text-muted-foreground">+ {t(($) => $.detail.no_issues_yet)}+ </span>)}</div>- <div className="flex items-center justify-between px-3 pb-3 border-t mt-0 pt-2">+ <div className="mt-0 flex items-center justify-between border-t px-3 pb-3 pt-2"><ProjectLeadPickerproject={project}handleUpdate={handleUpdate}renderTrigger={(leadName) => (- <button type="button" className="flex items-center gap-1.5 rounded px-1.5 py-0.5 -mx-1.5 hover:bg-accent/60 transition-colors cursor-pointer">+ <button type="button" className="-mx-1.5 flex items-center gap-1.5 rounded px-1.5 py-0.5 transition-colors hover:bg-accent/60">{project.lead_type && project.lead_id ? (<ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size={20} enableHoverCard />) : (<span className="inline-flex h-5 w-5 rounded-full border border-dashed border-muted-foreground/30" />)}- <span className="text-[10px] text-muted-foreground truncate max-w-[60px]">+ <span className="max-w-[60px] truncate text-[10px] text-muted-foreground">{leadName ?? t(($) => $.lead.no_lead)}</span></button>)}/>-<div className="flex items-center gap-2"><ProjectPriorityBadge project={project} handleUpdate={handleUpdate} align="start" /><span className="text-[10px] text-muted-foreground">@@ -119,224 +635,636 @@ function ProjectCard({ project }: { project: Project }) {);}-function ProjectCardCompact({ project }: { project: Project }) {- const wsPaths = useWorkspacePaths();- const formatRelativeDate = useFormatRelativeDate();- const updateProject = useUpdateProject();+// ---------------------------------------------------------------------------+// Toolbar — search + result count + filter + display (compact only) + view+// toggle.+// ---------------------------------------------------------------------------- const handleUpdate = useCallback(- (data: UpdateProjectRequest) => {- updateProject.mutate({ id: project.id, ...data });- },- [project.id, updateProject],- );+const STATUS_VALUES: ProjectStatus[] = [+ "planned",+ "in_progress",+ "paused",+ "completed",+ "cancelled",+];+const PRIORITY_VALUES: ProjectPriority[] = ["urgent", "high", "medium", "low", "none"];+const COLUMN_KEYS: ProjectColumnKey[] = ["priority", "progress", "lead", "issues", "created"];+const SORT_FIELDS: ProjectSortField[] = ["name", "priority", "status", "progress", "created"];- return (- <div className={cn(COMPACT_GRID, "h-10 items-center gap-2 px-4 text-sm transition-colors hover:bg-accent/40 border-b")}>- <ProjectIcon project={project} size="sm" />- <AppLink- href={wsPaths.projectDetail(project.id)}- className="flex items-center justify-start gap-2 min-w-0 overflow-hidden"- >- <span className="font-medium truncate text-left">{project.title}</span>- </AppLink>-- <div className="flex items-center justify-start">- <ProjectPriorityBadge project={project} handleUpdate={handleUpdate} align="start" />- </div>+function countActiveFilters(f: ProjectListFilters): number {+ let c = 0;+ if (f.statuses.length) c++;+ if (f.priorities.length) c++;+ if (f.leads.length) c++;+ return c;+}- <div className="flex items-center justify-start">- <ProjectStatusBadge project={project} handleUpdate={handleUpdate} align="start" />- </div>+// Batch toolbar — page-anchored (not viewport). Pin all selected (any+// member) + Delete (workspace admin). Mirrors the other lists.+function ProjectBatchToolbar({+ rows,+ pinnedIds,+ canDelete,+ onClear,+}: {+ rows: Project[];+ pinnedIds: Set<string>;+ canDelete: boolean;+ onClear: () => void;+}) {+ const { t } = useT("projects");+ const createPin = useCreatePin();+ const deleteProject = useDeleteProject();+ const [confirmDelete, setConfirmDelete] = useState(false);- <span className="flex items-center justify-start gap-1.5 text-xs text-muted-foreground tabular-nums">- {project.issue_count > 0 ? `${project.done_count}/${project.issue_count}` : "--"}- </span>+ if (rows.length === 0) return null;+ const anyUnpinned = rows.some((p) => !pinnedIds.has(p.id));- <ProjectLeadPicker- project={project}- handleUpdate={handleUpdate}- align="start"- renderTrigger={(leadName) => (- <button type="button" className="flex items-center justify-start gap-1.5 rounded px-1 py-0.5 hover:bg-accent/60 transition-colors cursor-pointer">- <span className="shrink-0">- {project.lead_type && project.lead_id ? (- <ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size={20} enableHoverCard />- ) : (- <span className="inline-flex h-5 w-5 rounded-full border border-dashed border-muted-foreground/30" />- )}- </span>- <span className="text-xs text-muted-foreground truncate max-w-[50px]">- {leadName ?? "--"}- </span>+ return (+ <>+ <div className="absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg">+ <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">+ <span className="text-sm font-medium">+ {t(($) => $.page.selected, { count: rows.length })}+ </span>+ <button+ type="button"+ aria-label={t(($) => $.page.clear_selection)}+ onClick={onClear}+ className="rounded p-0.5 transition-colors hover:bg-accent"+ >+ <X className="size-3.5 text-muted-foreground" /></button>+ </div>+ {anyUnpinned && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => {+ for (const p of rows) {+ if (!pinnedIds.has(p.id)) {+ createPin.mutate({ item_type: "project", item_id: p.id });+ }+ }+ onClear();+ }}+ >+ <Pin className="mr-1 size-3.5" />+ {t(($) => $.page.pin)}+ </Button>)}- />+ {canDelete && (+ <Button+ variant="ghost"+ size="sm"+ className="text-destructive hover:text-destructive"+ onClick={() => setConfirmDelete(true)}+ >+ <Trash2 className="mr-1 size-3.5" />+ {t(($) => $.page.delete)}+ </Button>+ )}+ </div>- <span className="text-left text-xs text-muted-foreground tabular-nums">- {formatRelativeDate(project.created_at)}- </span>- </div>+ <Dialog open={confirmDelete} onOpenChange={setConfirmDelete}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t(($) => $.delete_dialog.title)}</DialogTitle>+ <DialogDescription>{t(($) => $.delete_dialog.description)}</DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button type="button" variant="outline" size="sm" onClick={() => setConfirmDelete(false)}>+ {t(($) => $.delete_dialog.cancel)}+ </Button>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={() => {+ for (const p of rows) deleteProject.mutate(p.id);+ setConfirmDelete(false);+ onClear();+ }}+ >+ {t(($) => $.delete_dialog.confirm)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>);}+// ---------------------------------------------------------------------------+// Page+// ---------------------------------------------------------------------------+export function ProjectsPage() {const { t } = useT("projects");const wsId = useWorkspaceId();+ const currentUser = useAuthStore((s) => s.user);+ const { getActorName } = useActorName();+const viewMode = useProjectViewStore((s) => s.viewMode);const setViewMode = useProjectViewStore((s) => s.setViewMode);+ const sortField = useProjectViewStore((s) => s.sortField);+ const sortDirection = useProjectViewStore((s) => s.sortDirection);+ const hiddenColumns = useProjectViewStore((s) => s.hiddenColumns);+ const filters = useProjectViewStore((s) => s.filters);+ const toggleSort = useProjectViewStore((s) => s.toggleSort);+ const setSortField = useProjectViewStore((s) => s.setSortField);+ const setSortDirection = useProjectViewStore((s) => s.setSortDirection);+ const toggleColumn = useProjectViewStore((s) => s.toggleColumn);+ const toggleFilter = useProjectViewStore((s) => s.toggleFilter);+ const clearFilters = useProjectViewStore((s) => s.clearFilters);const isCompact = viewMode === "compact";+ const isColVisible = (key: ProjectColumnKey) => !hiddenColumns.includes(key);+const { data: projects = [], isLoading } = useQuery(projectListOptions(wsId));+ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const { data: pins = [] } = useQuery({+ ...pinListOptions(wsId, currentUser?.id ?? ""),+ enabled: !!wsId && !!currentUser?.id,+ });const openCreateProject = () => useModalStore.getState().open("create-project");+ const isWorkspaceAdmin = useMemo(() => {+ if (!currentUser) return false;+ const me = members.find((m: MemberWithUser) => m.user_id === currentUser.id);+ return me?.role === "owner" || me?.role === "admin";+ }, [members, currentUser]);++ const pinnedProjectIds = useMemo(() => {+ const s = new Set<string>();+ for (const pin of pins) if (pin.item_type === "project") s.add(pin.item_id);+ return s;+ }, [pins]);+const [search, setSearch] = useState("");- const filteredProjects = useMemo(() => {+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(new Set());+ const toggleSelected = (id: string) =>+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });++ const activeFilterCount = countActiveFilters(filters);+ const hasActiveFilters = activeFilterCount > 0;++ // Filter option counts derive from the full set so toggling one dimension+ // doesn't make the others vanish.+ const leadOptions = useMemo(() => {+ const m = new Map<string, { type: string; id: string; count: number }>();+ for (const p of projects) {+ const v = leadFilterValue(p);+ if (!v || !p.lead_type || !p.lead_id) continue;+ const e = m.get(v);+ if (e) e.count += 1;+ else m.set(v, { type: p.lead_type, id: p.lead_id, count: 1 });+ }+ return m;+ }, [projects]);++ const visible = useMemo(() => {const q = search.trim().toLowerCase();- if (!q) return projects;- return projects.filter((p) =>- p.title.toLowerCase().includes(q) || matchesPinyin(p.title, q)- );- }, [projects, search]);+ const filtered = projects.filter((p) => {+ if (q && !p.title.toLowerCase().includes(q) && !matchesPinyin(p.title, q)) {+ return false;+ }+ if (filters.statuses.length && !filters.statuses.includes(p.status)) return false;+ if (filters.priorities.length && !filters.priorities.includes(p.priority)) {+ return false;+ }+ if (filters.leads.length) {+ const v = leadFilterValue(p);+ if (!v || !filters.leads.includes(v)) return false;+ }+ return true;+ });+ const dir = sortDirection === "asc" ? 1 : -1;+ const sorted = [...filtered];+ sorted.sort((a, b) => {+ if (sortField === "name") return a.title.localeCompare(b.title) * dir;+ if (sortField === "priority") {+ return (+ (PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority]) * dir ||+ a.title.localeCompare(b.title)+ );+ }+ if (sortField === "status") {+ return (+ (STATUS_ORDER[a.status] - STATUS_ORDER[b.status]) * dir ||+ a.title.localeCompare(b.title)+ );+ }+ if (sortField === "progress") {+ return (progressOf(a) - progressOf(b)) * dir || a.title.localeCompare(b.title);+ }+ return (Date.parse(a.created_at) - Date.parse(b.created_at)) * dir;+ });+ return sorted;+ }, [projects, search, filters, sortField, sortDirection]);++ const selectedProjects = visible.filter((p) => selectedIds.has(p.id));+ const allSelected = visible.length > 0 && selectedProjects.length === visible.length;+ const someSelected = selectedProjects.length > 0 && !allSelected;+ const handleToggleAll = () =>+ setSelectedIds(allSelected ? new Set() : new Set(visible.map((p) => p.id)));++ const sortLabel = (f: ProjectSortField) =>+ f === "name"+ ? t(($) => $.table.name)+ : f === "priority"+ ? t(($) => $.table.priority)+ : f === "status"+ ? t(($) => $.table.status)+ : f === "progress"+ ? t(($) => $.table.progress)+ : t(($) => $.table.created);+ const columnLabel = (k: ProjectColumnKey) =>+ k === "priority"+ ? t(($) => $.table.priority)+ : k === "progress"+ ? t(($) => $.table.progress)+ : k === "lead"+ ? t(($) => $.table.lead)+ : k === "issues"+ ? t(($) => $.table.issues)+ : t(($) => $.table.created);++ const showEmpty = !isLoading && projects.length === 0;+ const countBadge = (n: number) => (+ <span className="ml-auto pl-3 text-xs text-muted-foreground">{n}</span>+ );return (- <div className="flex flex-1 min-h-0 flex-col">+ // relative: positioning anchor for the page-centered batch toolbar.+ <div className="relative flex flex-1 min-h-0 flex-col"><PageHeader className="justify-between px-5"><div className="flex items-center gap-2"><FolderKanban className="h-4 w-4 text-muted-foreground" /><h1 className="text-sm font-medium">{t(($) => $.page.title)}</h1>- {!isLoading && projects.length > 0 && (- <span className="text-xs text-muted-foreground tabular-nums">{projects.length}</span>+ {projects.length > 0 && (+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">+ {projects.length}+ </span>)}</div>- <Button size="sm" variant="outline" onClick={openCreateProject}>- <Plus className="h-3.5 w-3.5 mr-1" />- {t(($) => $.page.new_project)}+ <Button+ size="sm"+ variant="outline"+ className="h-8 w-8 gap-1 px-0 md:w-auto md:px-2.5"+ aria-label={t(($) => $.page.new_project)}+ onClick={openCreateProject}+ >+ <Plus className="h-3.5 w-3.5" />+ <span className="hidden md:inline">{t(($) => $.page.new_project)}</span></Button></PageHeader>- <div className="flex flex-1 min-h-0 flex-col overflow-hidden">- {(projects.length > 0 || isLoading) && (- <div className="flex h-12 shrink-0 items-center justify-between border-b px-4 gap-2 sm:gap-3">- <div className="relative flex-1 sm:flex-none">- <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- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder={t(($) => $.page.search_placeholder)}- className="h-8 w-full sm:w-64 pl-8 text-sm"- />+ {showEmpty ? (+ <div className="flex flex-1 flex-col items-center justify-center py-24 text-muted-foreground">+ <FolderKanban className="mb-3 h-10 w-10 opacity-30" />+ <p className="text-sm">{t(($) => $.page.empty)}</p>+ <Button size="sm" variant="outline" className="mt-3" onClick={openCreateProject}>+ {t(($) => $.page.create_first)}+ </Button>+ </div>+ ) : (+ <>+ {/* Toolbar */}+ <div className="flex h-12 shrink-0 items-center justify-between gap-2 px-5">+ <div className="flex min-w-0 items-center gap-2">+ <div className="relative hidden md:block">+ <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+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={t(($) => $.page.search_placeholder)}+ className="h-8 w-56 pl-8 text-sm"+ />+ </div>+ {(hasActiveFilters || search.trim().length > 0) && (+ <span+ title={t(($) => $.toolbar.result_count_title)}+ className="hidden shrink-0 text-xs tabular-nums text-muted-foreground md:inline"+ >+ {visible.length} / {projects.length}+ </span>+ )}</div>- <div className="flex items-center gap-2 sm:gap-4 shrink-0">- <span className="hidden sm:inline-block font-mono text-xs tabular-nums text-muted-foreground/70">- {filteredProjects.length} / {projects.length}- </span>- <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">- <button- type="button"- onClick={() => setViewMode("compact")}- className={cn(- "inline-flex items-center gap-1.5 rounded p-1 sm:px-2.5 sm:py-1 text-xs font-medium transition-colors",- isCompact ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"- )}- >- <Rows3 className="size-3.5" />- <span className="hidden sm:inline-block">{t(($) => $.page.view_compact)}</span>- </button>- <button- type="button"- onClick={() => setViewMode("comfortable")}- className={cn(- "inline-flex items-center gap-1.5 rounded p-1 sm:px-2.5 sm:py-1 text-xs font-medium transition-colors",- !isCompact ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"- )}- >- <LayoutGrid className="size-3.5" />- <span className="hidden sm:inline-block">{t(($) => $.page.view_comfortable)}</span>- </button>- </div>+ <div className="flex shrink-0 items-center gap-1">+ {/* Filter */}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant={hasActiveFilters ? "default" : "outline"}+ size="sm"+ className={+ hasActiveFilters+ ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"+ : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ }+ >+ <Filter className="size-3.5" />+ {hasActiveFilters ? (+ <>+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_active_count, { count: activeFilterCount })}+ </span>+ <span className="tabular-nums md:hidden">{activeFilterCount}</span>+ </>+ ) : (+ <span className="hidden md:inline">{t(($) => $.toolbar.filter_label)}</span>+ )}+ {hasActiveFilters && (+ <span+ role="button"+ tabIndex={-1}+ aria-label={t(($) => $.toolbar.clear_filters)}+ className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ clearFilters();+ }}+ onPointerDown={(e) => e.stopPropagation()}+ >+ <X className="size-3" />+ </span>+ )}+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-auto">+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.toolbar.section_status)}</span>+ {filters.statuses.length > 0 && (+ <span className="text-xs font-medium text-primary">{filters.statuses.length}</span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-44">+ {STATUS_VALUES.map((s) => (+ <DropdownMenuCheckboxItem+ key={s}+ checked={filters.statuses.includes(s)}+ onCheckedChange={() => toggleFilter("statuses", s)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.statuses.includes(s)} />+ {t(($) => $.status[s])}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.toolbar.section_priority)}</span>+ {filters.priorities.length > 0 && (+ <span className="text-xs font-medium text-primary">{filters.priorities.length}</span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-44">+ {PRIORITY_VALUES.map((pr) => (+ <DropdownMenuCheckboxItem+ key={pr}+ checked={filters.priorities.includes(pr)}+ onCheckedChange={() => toggleFilter("priorities", pr)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.priorities.includes(pr)} />+ {t(($) => $.priority[pr])}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.toolbar.section_lead)}</span>+ {filters.leads.length > 0 && (+ <span className="text-xs font-medium text-primary">{filters.leads.length}</span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {[...leadOptions.entries()].map(([value, { type, id, count }]) => (+ <DropdownMenuCheckboxItem+ key={value}+ checked={filters.leads.includes(value)}+ onCheckedChange={() => toggleFilter("leads", value)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.leads.includes(value)} />+ <ActorAvatar actorType={type} actorId={id} size={16} />+ <span className="min-w-0 truncate">{getActorName(type, id)}</span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>++ {/* Display (sort + columns). Always present — view mode is a+ pure presentation choice and must not reshape the toolbar.+ Sort applies to both views; the columns section is shown+ only in the table view (cards have no columns). */}+ <Popover>+ <Tooltip>+ <PopoverTrigger+ render={+ <TooltipTrigger+ render={+ <Button variant="outline" size="sm" className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5">+ {sortDirection === "asc" ? <ArrowUp className="size-3.5" /> : <ArrowDown className="size-3.5" />}+ <span className="hidden md:inline">{sortLabel(sortField)}</span>+ </Button>+ }+ />+ }+ />+ <TooltipContent side="bottom">{t(($) => $.toolbar.display)}</TooltipContent>+ </Tooltip>+ <PopoverContent align="end" className="w-64 p-0">+ <div className="border-b px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">{t(($) => $.toolbar.sort_by)}</span>+ <div className="mt-2 flex items-center gap-1.5">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button variant="outline" size="sm" className="flex-1 justify-between text-xs">+ {sortLabel(sortField)}+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={sortField}+ onValueChange={(v) => setSortField(v as ProjectSortField)}+ >+ {SORT_FIELDS.map((f) => (+ <DropdownMenuRadioItem key={f} value={f}>+ {sortLabel(f)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ <Button+ variant="outline"+ size="icon-sm"+ onClick={() => setSortDirection(sortDirection === "asc" ? "desc" : "asc")}+ title={sortDirection === "asc" ? t(($) => $.toolbar.direction_asc) : t(($) => $.toolbar.direction_desc)}+ >+ {sortDirection === "asc" ? <ArrowUp className="size-3.5" /> : <ArrowDown className="size-3.5" />}+ </Button>+ </div>+ </div>+ {isCompact && (+ <div className="px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">{t(($) => $.toolbar.section_columns)}</span>+ <div className="mt-2 space-y-2">+ {COLUMN_KEYS.map((key) => (+ <label key={key} className="flex cursor-pointer items-center justify-between">+ <span className="text-sm">{columnLabel(key)}</span>+ <Switch size="sm" checked={!hiddenColumns.includes(key)} onCheckedChange={() => toggleColumn(key)} />+ </label>+ ))}+ </div>+ </div>+ )}+ </PopoverContent>+ </Popover>++ {/* View toggle — a single button that flips table ⇄ cards.+ Pure presentation; coupled to nothing else. */}+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ onClick={() => setViewMode(isCompact ? "comfortable" : "compact")}+ >+ {isCompact ? (+ <Rows3 className="size-3.5" />+ ) : (+ <LayoutGrid className="size-3.5" />+ )}+ <span className="hidden md:inline">+ {isCompact ? t(($) => $.page.view_table) : t(($) => $.page.view_cards)}+ </span>+ </Button>+ }+ />+ <TooltipContent side="bottom">+ {isCompact ? t(($) => $.page.view_cards) : t(($) => $.page.view_table)}+ </TooltipContent>+ </Tooltip></div></div>- )}- <div key={viewMode} className={cn("flex-1", isCompact ? "overflow-hidden flex flex-col" : "overflow-y-auto")}>+ {/* Body */}{isLoading ? (- isCompact ? (- <div className="pt-4 mx-5 overflow-x-auto rounded-md border pb-4 mb-5">- <div className="min-w-[740px]">- <div className={cn(COMPACT_GRID, "h-10 items-center gap-2 px-4 border-b")}>- <Skeleton className="h-6 w-6 rounded" />- <Skeleton className="h-4 w-48" />- </div>- {Array.from({ length: 6 }).map((_, i) => (- <div key={i} className={cn(COMPACT_GRID, "h-10 items-center gap-2 px-4 border-b")}>- <Skeleton className="h-6 w-6 rounded" />- <Skeleton className="h-4 w-48" />- </div>- ))}- </div>- </div>- ) : (- <div className="pt-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 px-5">- {Array.from({ length: 8 }).map((_, i) => (- <div key={i} className="flex flex-col rounded-md border p-3 gap-2">- <div className="flex items-center gap-2">- <Skeleton className="h-8 w-8 rounded" />- <Skeleton className="h-4 w-3/4" />- </div>- <div className="flex gap-1.5">- <Skeleton className="h-5 w-16 rounded" />- <Skeleton className="h-5 w-20 rounded" />- </div>- <div className="flex items-center justify-between">- <Skeleton className="h-5 w-5 rounded-full" />- <Skeleton className="h-3 w-12" />- </div>- </div>- ))}- </div>- )- ) : projects.length === 0 ? (- <div className="flex flex-col items-center justify-center py-24 text-muted-foreground">- <FolderKanban className="h-10 w-10 mb-3 opacity-30" />- <p className="text-sm">{t(($) => $.page.empty)}</p>- <Button size="sm" variant="outline" className="mt-3" onClick={openCreateProject}>- {t(($) => $.page.create_first)}- </Button>- </div>- ) : filteredProjects.length === 0 ? (- <div className="flex flex-col items-center justify-center py-24 text-muted-foreground">- <Search className="h-10 w-10 mb-3 opacity-30" />- <p className="text-sm">{t(($) => $.page.no_search_results)}</p>+ <LoadingState isCompact={isCompact} />+ ) : visible.length === 0 ? (+ <div className="flex flex-1 flex-col items-center justify-center py-24 text-muted-foreground">+ <Search className="mb-3 h-10 w-10 opacity-30" />+ <p className="text-sm">{t(($) => $.page.no_matches)}</p></div>) : isCompact ? (- <div className="mt-4 mx-5 rounded-md border mb-5 overflow-auto flex-1">- <div className="min-w-[740px]">- <div className={cn(COMPACT_GRID, "h-8 shrink-0 items-center gap-2 px-4 text-xs font-medium text-muted-foreground border-b bg-muted/30 backdrop-blur sticky top-0 z-10")}>- <span />- <span className="text-left">{t(($) => $.table.name)}</span>- <span className="text-left">{t(($) => $.table.priority)}</span>- <span className="text-left">{t(($) => $.table.status)}</span>- <span className="text-left">{t(($) => $.table.progress)}</span>- <span className="text-left">{t(($) => $.table.lead)}</span>- <span className="text-left">{t(($) => $.table.created)}</span>- </div>- <div className="pb-4">- {filteredProjects.map((project) => (- <ProjectCardCompact key={project.id} project={project} />- ))}- </div>- </div>+ <div className="min-h-0 flex-1 overflow-auto @container">+ <ListGrid+ className={`${GRID_COLS} @2xl:min-w-[var(--pjc-minw)]`}+ style={{+ ...columnTrackVars(isColVisible),+ paddingBottom: LIST_GRID_BOTTOM_CLEARANCE,+ }}+ >+ <ProjectTableHeader+ sortField={sortField}+ sortDirection={sortDirection}+ onSort={toggleSort}+ isColVisible={isColVisible}+ allSelected={allSelected}+ someSelected={someSelected}+ onToggleAll={handleToggleAll}+ />+ {visible.map((project) => (+ <ProjectTableRow+ key={project.id}+ project={project}+ pinned={pinnedProjectIds.has(project.id)}+ canDelete={isWorkspaceAdmin}+ isColVisible={isColVisible}+ selected={selectedIds.has(project.id)}+ onToggleSelect={() => toggleSelected(project.id)}+ />+ ))}+ </ListGrid></div>) : (- <div className="pt-4 pb-5 px-5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">- {filteredProjects.map((project) => (- <ProjectCard key={project.id} project={project} />- ))}+ <div className="min-h-0 flex-1 overflow-y-auto px-5 pt-4">+ <div+ className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4"+ style={{ paddingBottom: LIST_GRID_BOTTOM_CLEARANCE }}+ >+ {visible.map((project) => (+ <ProjectCard+ key={project.id}+ project={project}+ pinned={pinnedProjectIds.has(project.id)}+ canDelete={isWorkspaceAdmin}+ />+ ))}+ </div></div>)}++ <ProjectBatchToolbar+ rows={selectedProjects}+ pinnedIds={pinnedProjectIds}+ canDelete={isWorkspaceAdmin}+ onClear={() => setSelectedIds(new Set())}+ />+ </>+ )}+ </div>+ );+}++function LoadingState({ isCompact }: { isCompact: boolean }) {+ if (isCompact) {+ return (+ <div className="min-h-0 flex-1 overflow-auto px-5 pt-4">+ <div className="space-y-2">+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} className="h-11 w-full rounded-md" />+ ))}</div></div>+ );+ }+ return (+ <div className="grid grid-cols-1 gap-3 px-5 pt-4 sm:grid-cols-2 lg:grid-cols-4">+ {Array.from({ length: 8 }).map((_, i) => (+ <div key={i} className="flex flex-col gap-2 rounded-md border p-3">+ <div className="flex items-center gap-2">+ <Skeleton className="h-8 w-8 rounded" />+ <Skeleton className="h-4 w-3/4" />+ </div>+ <div className="flex gap-1.5">+ <Skeleton className="h-5 w-16 rounded" />+ <Skeleton className="h-5 w-20 rounded" />+ </div>+ </div>+ ))}</div>);}diff --git a/packages/views/runtimes/components/runtime-columns.tsx b/packages/views/runtimes/components/runtime-columns.tsxdeleted file mode 100644index 4d9562bcb5..0000000000--- a/packages/views/runtimes/components/runtime-columns.tsx+++ /dev/null@@ -1,488 +0,0 @@-"use client";--import { useMemo, useState } from "react";-import { Globe, 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 { 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 { useViewingTimezone } from "../../common/use-viewing-timezone";-import { workloadConfig } from "../../agents/presence";-import { ProviderLogo } from "./provider-logo";-import { HealthIcon, useHealthLabel } from "./shared";-import { DeleteRuntimeDialog } from "./delete-runtime-dialog";-import {- computeCostInWindow,- formatLastSeen,- isSelfHealingRuntime,- pctChange,-} from "../utils";-import { splitRuntimeName } from "./runtime-machines";-import { useT } from "../../i18n";--// 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 fetches its own narrow 14-day window-// (just enough for the cell's 7d cost + 7d prior-window delta).-export interface RuntimeRow {- runtime: AgentRuntime;- ownerMember: MemberWithUser | null;- workload: { agentIds: string[]; runningCount: number; queuedCount: number };- canDelete: boolean;-}--// Column widths in px. Runtime is the primary scanning column, so it keeps-// the only grow slot and receives the extra width until the user resizes it.-// The size values still flow into table.getTotalSize() to set the table's-// min-width, giving each column a real floor below which the container-// scrolls horizontally instead of shrinking further.-const COL_WIDTHS = {- runtime: 340,- health: 150,- owner: 72,- agents: 92,- workload: 120,- cost: 96,- cli: 112,- // 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;--type RuntimesT = ReturnType<typeof useT<"runtimes">>["t"];--interface CreateColumnsArgs {- showOwner: boolean;- wsId: string;- now: number;- t: RuntimesT;-}--export function createRuntimeColumns({- showOwner,- wsId,- now,- t,-}: CreateColumnsArgs): ColumnDef<RuntimeRow>[] {- const cols: ColumnDef<RuntimeRow>[] = [- {- id: "runtime",- header: () => t(($) => $.list.col_runtime),- size: COL_WIDTHS.runtime,- meta: { grow: true },- cell: ({ row }) => <RuntimeNameCell runtime={row.original.runtime} />,- },- {- id: "health",- header: () => t(($) => $.list.col_health),- size: COL_WIDTHS.health,- cell: ({ row }) => (- <HealthCell runtime={row.original.runtime} now={now} />- ),- },- ];-- if (showOwner) {- cols.push({- id: "owner",- header: () => t(($) => $.list.col_owner),- size: COL_WIDTHS.owner,- cell: ({ row }) =>- row.original.ownerMember ? (- <span className="inline-flex min-w-0 items-center gap-1.5">- <ActorAvatar- actorType="member"- actorId={row.original.ownerMember.user_id}- size={18}- />- <span className="truncate text-xs text-muted-foreground">- {row.original.ownerMember.name}- </span>- </span>- ) : (- <span className="text-xs text-muted-foreground/50">—</span>- ),- });- }-- cols.push(- {- id: "agents",- header: () => t(($) => $.list.col_agents),- size: COL_WIDTHS.agents,- cell: ({ row }) => (- <AgentStack agentIds={row.original.workload.agentIds} />- ),- },- {- id: "workload",- header: () => t(($) => $.list.col_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">{t(($) => $.list.col_cost)}</div>,- size: COL_WIDTHS.cost,- cell: ({ row }) => <CostCell runtimeId={row.original.runtime.id} />,- },- {- id: "cli",- header: () => t(($) => $.list.col_cli),- size: COL_WIDTHS.cli,- cell: ({ row }) => <CliCell runtime={row.original.runtime} />,- },- {- id: "actions",- header: () => null,- size: COL_WIDTHS.actions,- enableResizing: false,- 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-// -----------------------------------------------------------------------------// ----------------------------------------------------------------------------// Cell renderers-// -----------------------------------------------------------------------------function RuntimeNameCell({ runtime }: { runtime: AgentRuntime }) {- const { base: baseName } = 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 shrink truncate text-sm font-medium">- {baseName}- </span>- <VisibilityBadge runtime={runtime} />- </div>- </div>- );-}--// Only public is worth a badge — private is the default and rendering a-// `🔒 Private` chip on every row turns the whole column into noise.-function VisibilityBadge({ runtime }: { runtime: AgentRuntime }) {- const { t } = useT("runtimes");- if (runtime.visibility !== "public") return null;- return (- <Tooltip>- <TooltipTrigger- render={- <span className="shrink-0 inline-flex items-center gap-0.5 rounded bg-info/10 px-1 text-[10px] font-medium text-info">- <Globe className="h-2.5 w-2.5" />- {t(($) => $.detail.visibility_label.public)}- </span>- }- />- <TooltipContent>{t(($) => $.detail.visibility_hint.public)}</TooltipContent>- </Tooltip>- );-}--function HealthCell({- runtime,- now,-}: {- runtime: AgentRuntime;- now: number;-}) {- const labelOf = useHealthLabel();- 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">- {labelOf(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;-}) {- const { t: tAgents } = useT("agents");- if (offline) {- return <span className="text-xs text-muted-foreground/50">—</span>;- }- const workload = deriveWorkload({- runningCount: running,- queuedCount: queued,- });- const wl = workloadConfig[workload];- 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">- {workload !== "idle" && (- <wl.icon- className={`h-3 w-3 shrink-0 ${wl.textClass} ${workload === "working" ? "animate-spin" : ""}`}- />- )}- <span className={`shrink-0 ${wl.textClass}`}>{tAgents(($) => $.workload[workload])}</span>- {counts && (- <span className="truncate font-mono tabular-nums text-muted-foreground">- {counts}- </span>- )}- </span>- );-}--// Per-row cost — only renders a 7d total + delta vs the prior 7d, so we-// only need 14 days of usage. Previously this fetched a 180-day window to-// share the cache key with the runtime-detail page, but that turned the-// list page into N × 180d in-line aggregations against `task_usage` (one-// per runtime row) and dominated DB load for this view. Detail still-// fetches its own 180d window on navigation; the cold-load difference for-// detail is one extra request, while the steady-state savings on the list-// page are large.-const COST_CELL_DAYS = 14;--function CostCell({ runtimeId }: { runtimeId: string }) {- const { t } = useT("runtimes");- const tz = useViewingTimezone();- const { data: usage = [] } = useQuery(- runtimeUsageOptions(runtimeId, COST_CELL_DAYS, tz),- );- const cost7d = useMemo(- () => computeCostInWindow(usage, 7, tz),- [usage, tz],- );- const costPrev7d = useMemo(- () => computeCostInWindow(usage, 7, tz, 7),- [usage, tz],- );- 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- ? t(($) => $.list.cost_delta_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 }: { runtime: AgentRuntime }) {- if (runtime.runtime_mode === "cloud") {- return <span className="text-xs text-muted-foreground/50">—</span>;- }- const meta = runtime.metadata as Record<string, unknown> | null;- // `version` is the agent's own underlying CLI tool version — distinct per- // provider (e.g. "2.1.5 (Claude Code)", "codex-cli 0.118.0", "0.42.0").- // The separate `cli_version` is the shared multica daemon CLI, identical- // for every runtime on one machine; surfacing it here made all agents- // show the same number (#3838). The daemon CLI version and its update- // prompt belong to the machine — they live in the machine meta strip and- // the detail page's UpdateSection, not on a per-agent row.- const version =- meta && typeof meta.version === "string" ? meta.version : null;-- if (!version) {- return <span className="text-xs text-muted-foreground/50">—</span>;- }-- return (- <div className="flex min-w-0 items-center text-xs">- <span className="truncate font-mono text-muted-foreground">- {version}- </span>- </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 { t } = useT("runtimes");- const [deleteOpen, setDeleteOpen] = useState(false);- // Delete is currently the only row action; if the row can't run it, drop- // the kebab entirely so the column doesn't render an empty popover. The- // self-healing case (local + online) is the runtime-detail parity fix —- // see isSelfHealingRuntime for the rationale.- const selfHealing = isSelfHealingRuntime(runtime);-- if (!canDelete || selfHealing) {- return <span aria-hidden />;- }-- return (- <>- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="ghost"- size="icon-sm"- aria-label={t(($) => $.list.row_actions_aria)}- 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)}- title={t(($) => $.list.delete_permission_hint)}- >- <Trash2 className="h-3.5 w-3.5" />- {t(($) => $.list.delete_action)}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- <DeleteRuntimeDialog- open={deleteOpen}- onOpenChange={setDeleteOpen}- runtime={runtime}- wsId={wsId}- onDeleted={() => {- setDeleteOpen(false);- toast.success(t(($) => $.detail.toast_deleted));- }}- />- </>- );-}diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsxindex 798805398d..bcf8940cfc 100644--- a/packages/views/runtimes/components/runtime-list.tsx+++ b/packages/views/runtimes/components/runtime-list.tsx@@ -1,8 +1,9 @@"use client";-import { useMemo } from "react";+import { useMemo, useState } from "react";+import { Globe, MoreHorizontal, Trash2 } from "lucide-react";+import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";-import { getCoreRowModel, useReactTable } from "@tanstack/react-table";import type {Agent,AgentRuntime,@@ -16,12 +17,99 @@ import {memberListOptions,} from "@multica/core/workspace/queries";import { agentTaskSnapshotOptions } from "@multica/core/agents";-import { paths, useWorkspaceSlug } from "@multica/core/paths";-import { DataTable } from "@multica/ui/components/ui/data-table";-import { useNavigation } from "../../navigation";-import { type RuntimeRow, createRuntimeColumns } from "./runtime-columns";+import {+ deriveRuntimeHealth,+ runtimeUsageOptions,+} from "@multica/core/runtimes";+import { useWorkspacePaths } from "@multica/core/paths";+import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ ListGrid,+ ListGridCell,+ ListGridHeader,+ ListGridHeaderCell,+ ListGridRow,+} from "@multica/ui/components/ui/list-grid";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { AppLink } from "../../navigation";+import { ActorAvatar } from "../../common/actor-avatar";+import { useViewingTimezone } from "../../common/use-viewing-timezone";+import { ProviderLogo } from "./provider-logo";+import { HealthIcon, useHealthLabel } from "./shared";+import { DeleteRuntimeDialog } from "./delete-runtime-dialog";+import {+ computeCostInWindow,+ formatLastSeen,+ isSelfHealingRuntime,+ pctChange,+} from "../utils";+import { splitRuntimeName } from "./runtime-machines";import { useT } from "../../i18n";+// The machine detail's runtimes table on the shared ListGrid. Paradigm+// pieces are taken À LA CARTE here: subgrid template + var-width tracks ++// two-zone responsiveness (the detail pane gets squeezed by the machine+// list, so the container-driven core-set collapse matters more than on the+// full-width pages), but NO virtualization / sorting / filters / column+// toggles / batch selection — a machine hosts 1-5 runtimes, those would all+// be dead weight, and batch-deleting runtimes (a cascade-confirm heavy+// operation) is deliberately not offered.+const GRID_COLS =+ "grid-cols-[0.75rem_minmax(120px,1fr)_var(--rtc-health)_var(--rtc-kebab)_0.75rem] " ++ "@2xl:grid-cols-[0.75rem_minmax(140px,1fr)_var(--rtc-health)_var(--rtc-owner)_var(--rtc-agents)_var(--rtc-cost)_var(--rtc-cli)_var(--rtc-kebab)_0.75rem]";++const COLUMN_WIDTHS = {+ // Health folds the workload in as a suffix ("Healthy · 2 running") —+ // same merge as the agents list's status cell.+ health: 176,+ owner: 96,+ agents: 92,+ cost: 96,+ cli: 112,+} as const;++// Fixed tracks (edges 12+12, name min 140) plus the 8 gap-x-3 gaps+// between the wide template's 9 tracks (zero-width tracks still carry+// gaps).+const FIXED_TRACKS_WIDTH = 164 + 8 * 12;++// The kebab track is conditional like the owner column: on a healthy+// local machine EVERY row's only action (delete) is hidden by the+// self-healing rule, and an unconditionally reserved 28px action track+// would hang a permanent dead zone off the last column.+function columnTrackVars(+ showOwner: boolean,+ showActions: boolean,+): React.CSSProperties {+ const minWidth =+ FIXED_TRACKS_WIDTH ++ COLUMN_WIDTHS.health ++ (showOwner ? COLUMN_WIDTHS.owner : 0) ++ COLUMN_WIDTHS.agents ++ COLUMN_WIDTHS.cost ++ COLUMN_WIDTHS.cli ++ (showActions ? 28 : 0);+ return {+ "--rtc-health": `${COLUMN_WIDTHS.health}px`,+ "--rtc-owner": showOwner ? `${COLUMN_WIDTHS.owner}px` : "0px",+ "--rtc-agents": `${COLUMN_WIDTHS.agents}px`,+ "--rtc-cost": `${COLUMN_WIDTHS.cost}px`,+ "--rtc-cli": `${COLUMN_WIDTHS.cli}px`,+ "--rtc-kebab": showActions ? "1.75rem" : "0px",+ "--rtc-minw": `${minWidth}px`,+ } as React.CSSProperties;+}+interface RuntimeWorkload {agentIds: string[];runningCount: number;@@ -34,6 +122,13 @@ const EMPTY_WORKLOAD: RuntimeWorkload = {queuedCount: 0,};+export interface RuntimeRow {+ runtime: AgentRuntime;+ ownerMember: MemberWithUser | null;+ workload: RuntimeWorkload;+ canDelete: boolean;+}+// 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@@ -69,6 +164,279 @@ export function buildWorkloadIndex(return result;}+// ---------------------------------------------------------------------------+// Cells+// ---------------------------------------------------------------------------++function RuntimeNameCell({ runtime }: { runtime: AgentRuntime }) {+ const { base: baseName } = splitRuntimeName(runtime.name);+ return (+ <ListGridCell className="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 shrink truncate text-sm font-medium">+ {baseName}+ </span>+ <VisibilityBadge runtime={runtime} />+ </div>+ </ListGridCell>+ );+}++// Only public is worth a badge — private is the default and rendering a+// `🔒 Private` chip on every row turns the whole column into noise.+function VisibilityBadge({ runtime }: { runtime: AgentRuntime }) {+ const { t } = useT("runtimes");+ if (runtime.visibility !== "public") return null;+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="inline-flex shrink-0 items-center gap-0.5 rounded bg-info/10 px-1 text-[10px] font-medium text-info">+ <Globe className="h-2.5 w-2.5" />+ {t(($) => $.detail.visibility_label.public)}+ </span>+ }+ />+ <TooltipContent>+ {t(($) => $.detail.visibility_hint.public)}+ </TooltipContent>+ </Tooltip>+ );+}++// Health with the load folded in as a "· N tasks" suffix — verbatim the+// same form as the agents list's status cell, so the two surfaces speak+// one language. The suffix is a unit-bearing count (running + queued);+// offline-ish rows skip it (health already says it all), idle rows skip+// it (idle is the unremarkable default). If "queued but nothing running"+// ever becomes a signal worth surfacing, it belongs to the HEALTH layer+// (a new deriveRuntimeHealth state), not to vocabulary hints here.+function HealthCell({+ runtime,+ workload,+ now,+}: {+ runtime: AgentRuntime;+ workload: RuntimeWorkload;+ now: number;+}) {+ const { t: tAgents } = useT("agents");+ const labelOf = useHealthLabel();+ const health = deriveRuntimeHealth(runtime, now);+ const offline = health === "offline" || health === "about_to_gc";+ const lastSeen = formatLastSeen(runtime.last_seen_at);+ const active = workload.runningCount + workload.queuedCount;++ return (+ <ListGridCell className="gap-1.5">+ <HealthIcon health={health} />+ <span className="block min-w-0 truncate text-xs">+ {labelOf(health)}+ {health !== "online" && runtime.last_seen_at && (+ <span className="text-muted-foreground"> · {lastSeen}</span>+ )}+ {!offline && active > 0 && (+ <span className="text-muted-foreground">+ {" · "}+ {tAgents(($) => $.row.task_count, { count: active })}+ </span>+ )}+ </span>+ </ListGridCell>+ );+}++// Per-row cost — only renders a 7d total + delta vs the prior 7d, so we+// only need 14 days of usage. Previously this fetched a 180-day window to+// share the cache key with the runtime-detail page, but that turned the+// list page into N × 180d in-line aggregations against `task_usage` (one+// per runtime row) and dominated DB load for this view. Detail still+// fetches its own 180d window on navigation; the cold-load difference for+// detail is one extra request, while the steady-state savings on the list+// page are large.+const COST_CELL_DAYS = 14;++export function CostCell({ runtimeId }: { runtimeId: string }) {+ const { t } = useT("runtimes");+ const tz = useViewingTimezone();+ const { data: usage = [] } = useQuery(+ runtimeUsageOptions(runtimeId, COST_CELL_DAYS, tz),+ );+ const cost7d = useMemo(() => computeCostInWindow(usage, 7, tz), [usage, tz]);+ const costPrev7d = useMemo(+ () => computeCostInWindow(usage, 7, tz, 7),+ [usage, tz],+ );+ const delta = pctChange(cost7d, costPrev7d);++ if (usage.length === 0) {+ return (+ <div className="w-full 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+ ? t(($) => $.list.cost_delta_flat)+ : `${delta > 0 ? "↑" : "↓"}${Math.abs(delta)}%`;+ return (+ <div className="flex w-full 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>+ );+}++export function CliCell({ runtime }: { runtime: AgentRuntime }) {+ if (runtime.runtime_mode === "cloud") {+ return <span className="text-xs text-muted-foreground/50">—</span>;+ }+ const meta = runtime.metadata as Record<string, unknown> | null;+ // `version` is the agent's own underlying CLI tool version — distinct per+ // provider (e.g. "2.1.5 (Claude Code)", "codex-cli 0.118.0", "0.42.0").+ // The separate `cli_version` is the shared multica daemon CLI, identical+ // for every runtime on one machine; surfacing it here made all agents+ // show the same number (#3838). The daemon CLI version and its update+ // prompt belong to the machine — they live in the machine meta strip and+ // the detail page's UpdateSection, not on a per-agent row.+ const version =+ meta && typeof meta.version === "string" ? meta.version : null;++ if (!version) {+ return <span className="text-xs text-muted-foreground/50">—</span>;+ }++ return (+ <div className="flex min-w-0 items-center text-xs">+ <span className="truncate font-mono text-muted-foreground">+ {version}+ </span>+ </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>+ );+}++export function RuntimeRowMenu({+ runtime,+ wsId,+ canDelete,+}: {+ runtime: AgentRuntime;+ wsId: string;+ canDelete: boolean;+}) {+ const { t } = useT("runtimes");+ const [deleteOpen, setDeleteOpen] = useState(false);+ // Delete is currently the only row action; if the row can't run it, drop+ // the kebab entirely so the column doesn't render an empty popover. The+ // self-healing case (local + online) is the runtime-detail parity fix —+ // see isSelfHealingRuntime for the rationale.+ const selfHealing = isSelfHealingRuntime(runtime);++ if (!canDelete || selfHealing) {+ return <span aria-hidden />;+ }++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t(($) => $.list.row_actions_aria)}+ 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)}+ title={t(($) => $.list.delete_permission_hint)}+ >+ <Trash2 className="h-3.5 w-3.5" />+ {t(($) => $.list.delete_action)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <DeleteRuntimeDialog+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ runtime={runtime}+ wsId={wsId}+ onDeleted={() => {+ setDeleteOpen(false);+ toast.success(t(($) => $.detail.toast_deleted));+ }}+ />+ </>+ );+}++// ---------------------------------------------------------------------------+// List+// ---------------------------------------------------------------------------+export function RuntimeList({runtimes,updatableIds,@@ -87,8 +455,7 @@ export function RuntimeList({const { t } = useT("runtimes");const wsId = useWorkspaceId();- const slug = useWorkspaceSlug();- const navigation = useNavigation();+ const wsPaths = useWorkspacePaths();const user = useAuthStore((s) => s.user);const { data: agents = [] } = useQuery(agentListOptions(wsId));@@ -135,36 +502,99 @@ export function RuntimeList({}));}, [runtimes, memberById, workloadIndex, isAdmin, user]);- const columns = useMemo(- () =>- createRuntimeColumns({- showOwner,- wsId,- now,- t,- }),- [showOwner, wsId, now, t],+ // Mirrors RuntimeRowMenu's render guard: the kebab track only earns its+ // width when at least one row will actually show the menu.+ const showActions = rows.some(+ (row) => row.canDelete && !isSelfHealingRuntime(row.runtime),);- const table = useReactTable({- data: rows,- columns,- getCoreRowModel: getCoreRowModel(),- enableColumnResizing: true,- // Pin the kebab column right so it stays accessible during horizontal- // scroll — matches the pattern in Linear / Notion / GitHub.- initialState: { columnPinning: { right: ["actions"] } },- });-return (- <DataTable- table={table}- onRowClick={(row) => {- if (!slug) return;- navigation.push(- paths.workspace(slug).runtimeDetail(row.original.runtime.id),- );- }}- />+ <div className="overflow-x-auto overflow-y-hidden @container">+ <ListGrid+ className={`${GRID_COLS} @2xl:min-w-[var(--rtc-minw)]`}+ style={columnTrackVars(showOwner, showActions)}+ >+ <ListGridHeader>+ <ListGridHeaderCell>+ {t(($) => $.list.col_runtime)}+ </ListGridHeaderCell>+ <ListGridHeaderCell>{t(($) => $.list.col_health)}</ListGridHeaderCell>+ {showOwner ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.list.col_owner)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.list.col_agents)}+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex" align="right">+ {t(($) => $.list.col_cost)}+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.list.col_cli)}+ </ListGridHeaderCell>+ <span aria-hidden="true" />+ </ListGridHeader>+ {rows.map((row) => (+ <ListGridRow+ key={row.runtime.id}+ render={<AppLink href={wsPaths.runtimeDetail(row.runtime.id)} />}+ >+ <RuntimeNameCell runtime={row.runtime} />+ <HealthCell+ runtime={row.runtime}+ workload={row.workload}+ now={now}+ />+ {showOwner ? (+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ {row.ownerMember ? (+ <>+ <ActorAvatar+ actorType="member"+ actorId={row.ownerMember.user_id}+ size={18}+ />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {row.ownerMember.name}+ </span>+ </>+ ) : (+ <span className="text-xs text-muted-foreground/50">—</span>+ )}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridCell className="hidden @2xl:flex">+ <AgentStack agentIds={row.workload.agentIds} />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <CostCell runtimeId={row.runtime.id} />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <CliCell runtime={row.runtime} />+ </ListGridCell>+ <ListGridCell className="justify-end px-0">+ <span+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ className="flex items-center"+ >+ <RuntimeRowMenu+ runtime={row.runtime}+ wsId={wsId}+ canDelete={row.canDelete}+ />+ </span>+ </ListGridCell>+ </ListGridRow>+ ))}+ </ListGrid>+ </div>);}diff --git a/packages/views/runtimes/components/runtime-row-menu.test.tsx b/packages/views/runtimes/components/runtime-row-menu.test.tsxindex 57fc6a010b..35152dafcc 100644--- a/packages/views/runtimes/components/runtime-row-menu.test.tsx+++ b/packages/views/runtimes/components/runtime-row-menu.test.tsx@@ -76,8 +76,7 @@ vi.mock("./shared", () => ({useHealthLabel: () => () => "Online",}));-import { createRuntimeColumns, type RuntimeRow } from "./runtime-columns";-import { useT } from "../../i18n";+import { CliCell, RuntimeRowMenu, type RuntimeRow } from "./runtime-list";function makeRuntime(overrides: Partial<AgentRuntime>): AgentRuntime {return {@@ -109,39 +108,19 @@ function makeRow(runtime: AgentRuntime, canDelete = true): RuntimeRow {};}-// The row menu lives inside the "actions" column cell. To exercise it-// without rendering the entire DataTable, we resolve the cell renderer from-// createRuntimeColumns and render its output directly inside a minimal table-// row (the cell expects React table context, but our shape — `row.original`-// — is the only field RowMenu reads, so a hand-built shim suffices).+// The row menu is a plain exported component on the ListGrid version of the+// list — render it directly with the row fields it reads.function renderActionsCell(row: RuntimeRow) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });- function Harness() {- const { t } = useT("runtimes");- const columns = createRuntimeColumns({- showOwner: false,- wsId: "ws-1",- now: Date.now(),- t,- });- const actions = columns.find((c) => c.id === "actions");- if (!actions || typeof actions.cell !== "function") {- throw new Error("actions column missing or has no cell renderer");- }- // The cell renderer only reads `row.original`. Casting through unknown- // keeps us honest about not implementing the full tanstack-table cell- // context.- const cell = actions.cell({- row: { original: row },- } as unknown as Parameters<typeof actions.cell>[0]);- return <>{cell}</>;- }-return render(<I18nProvider locale="en" resources={TEST_RESOURCES}><QueryClientProvider client={qc}>- <Harness />+ <RuntimeRowMenu+ runtime={row.runtime}+ wsId="ws-1"+ canDelete={row.canDelete}+ /></QueryClientProvider></I18nProvider>,);@@ -187,33 +166,15 @@ describe("runtime list row menu", () => {});});-// The CLI column lives in its own cell renderer; resolve it from-// createRuntimeColumns and render it in isolation, mirroring renderActionsCell.+// The CLI cell is a plain exported component — render it in isolation,+// mirroring renderActionsCell.function renderCliCell(row: RuntimeRow) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });- function Harness() {- const { t } = useT("runtimes");- const columns = createRuntimeColumns({- showOwner: false,- wsId: "ws-1",- now: Date.now(),- t,- });- const cli = columns.find((c) => c.id === "cli");- if (!cli || typeof cli.cell !== "function") {- throw new Error("cli column missing or has no cell renderer");- }- const cell = cli.cell({- row: { original: row },- } as unknown as Parameters<typeof cli.cell>[0]);- return <>{cell}</>;- }-return render(<I18nProvider locale="en" resources={TEST_RESOURCES}><QueryClientProvider client={qc}>- <Harness />+ <CliCell runtime={row.runtime} /></QueryClientProvider></I18nProvider>,);diff --git a/packages/views/runtimes/components/runtimes-page.tsx b/packages/views/runtimes/components/runtimes-page.tsxindex 8349f29a6e..95504ffe27 100644--- a/packages/views/runtimes/components/runtimes-page.tsx+++ b/packages/views/runtimes/components/runtimes-page.tsx@@ -204,7 +204,7 @@ export function RuntimesPage({<EmptyState onConnectRemote={() => setShowConnectDialog(true)} /></div>) : isMobile ? (- <div className="flex min-h-0 flex-1 flex-col border-t bg-background">+ <div className="flex min-h-0 flex-1 flex-col bg-background"><MachineSidebarmachines={filteredMachines}totalMachines={machines.length}@@ -227,7 +227,7 @@ export function RuntimesPage({/></div>) : (- <div className="min-h-0 flex-1 border-t bg-background">+ <div className="min-h-0 flex-1 bg-background"><ResizablePanelGrouporientation="horizontal"className="min-h-0 flex-1"@@ -320,9 +320,20 @@ function PageHeaderBar({{t(($) => $.cloud_runtime.action)}</Button>)}- <Button type="button" size="sm" onClick={onConnectRemote}>- <Plus className="h-3 w-3" />- {t(($) => $.page.connect_remote)}+ {/* Quiet chrome button (outline, icon-only below md) — primary is+ reserved for the empty state's CTA. */}+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-8 w-8 gap-1 px-0 md:w-auto md:px-2.5"+ aria-label={t(($) => $.page.connect_remote)}+ onClick={onConnectRemote}+ >+ <Plus className="h-3.5 w-3.5" />+ <span className="hidden md:inline">+ {t(($) => $.page.connect_remote)}+ </span></Button></div></PageHeader>@@ -733,7 +744,7 @@ function RuntimesPageSkeleton() {<PageHeader className="justify-between px-5"><Skeleton className="h-4 w-24" /></PageHeader>- <div className="flex min-h-0 flex-1 border-t">+ <div className="flex min-h-0 flex-1"><div className="hidden w-[300px] shrink-0 border-r p-3 md:block"><Skeleton className="h-9 w-full rounded-md" /><div className="mt-3 flex gap-2">diff --git a/packages/views/skills/components/skill-columns.tsx b/packages/views/skills/components/skill-columns.tsxdeleted file mode 100644index 7b020b8c48..0000000000--- a/packages/views/skills/components/skill-columns.tsx+++ /dev/null@@ -1,234 +0,0 @@-"use client";--import {- ChevronRight,- Download,- FileText,- HardDrive,- Lock,- Pencil,-} from "lucide-react";-import type { ColumnDef } from "@tanstack/react-table";-import type {- Agent,- AgentRuntime,- MemberWithUser,- SkillSummary,-} from "@multica/core/types";-import { useTimeAgo } from "../../i18n";-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";-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";-import { useT } from "../../i18n";--// Per-row data assembled at the page level. The columns reach into-// `row.original` and never pull their own queries. `skill` is the list-shape-// `SkillSummary`; the body and files are loaded only when the user opens the-// detail page.-export interface SkillRow {- skill: SkillSummary;- 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;-}--const COL_WIDTHS = {- name: 240,- usedBy: 140,- source: 220,- updated: 100,- chevron: 48,-} as const;--// Hook returns column defs that close over a translation function. Defining-// columns inside a hook (rather than as a module-level static) is the i18n-// price for header strings — same pattern used by inbox `useTypeLabels`.-export function useSkillColumns(): ColumnDef<SkillRow>[] {- const { t } = useT("skills");- const timeAgo = useTimeAgo();- return [- {- id: "name",- header: t(($) => $.table.name),- size: COL_WIDTHS.name,- meta: { grow: true },- cell: ({ row }) => <SkillNameCell row={row.original} />,- },- {- id: "usedBy",- header: t(($) => $.table.used_by),- size: COL_WIDTHS.usedBy,- cell: ({ row }) => <AgentAssignees agents={row.original.agents} />,- },- {- id: "source",- header: t(($) => $.table.source),- 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: t(($) => $.table.updated),- size: COL_WIDTHS.updated,- cell: ({ row }) => (- <span className="whitespace-nowrap text-xs text-muted-foreground">- {timeAgo(row.original.skill.updated_at)}- </span>- ),- },- {- id: "_chevron",- header: () => null,- size: COL_WIDTHS.chevron,- enableResizing: false,- 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 { t } = useT("skills");- 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>- {t(($) => $.table.lock_tooltip)}- </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 max-w-xl truncate text-xs ${- skill.description- ? "text-muted-foreground"- : "italic text-muted-foreground/50"- }`}- >- {skill.description || t(($) => $.table.no_description)}- </div>- </div>- );-}--function AgentAssignees({ agents }: { agents: Agent[] }) {- const { t } = useT("skills");- if (agents.length === 0) {- return <span className="text-xs text-muted-foreground/70">{t(($) => $.table.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={resolvePublicFileUrl(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: SkillSummary;- creator: MemberWithUser | null;- runtime: AgentRuntime | null;-}) {- const { t } = useT("skills");- const origin = readOrigin(skill);-- let icon = <Pencil className="h-3 w-3 shrink-0" />;- let label: string = t(($) => $.table.source_manual);- if (origin.type === "runtime_local") {- icon = <HardDrive className="h-3 w-3 shrink-0" />;- label = runtime- ? t(($) => $.table.source_runtime_named, { name: runtime.name })- : origin.provider- ? t(($) => $.table.source_runtime_provider, { provider: origin.provider })- : t(($) => $.table.source_runtime_unknown);- } else if (origin.type === "clawhub") {- icon = <Download className="h-3 w-3 shrink-0" />;- label = t(($) => $.table.source_clawhub);- } else if (origin.type === "skills_sh") {- icon = <Download className="h-3 w-3 shrink-0" />;- label = t(($) => $.table.source_skills_sh);- } else if (origin.type === "github") {- icon = <Download className="h-3 w-3 shrink-0" />;- label = t(($) => $.table.source_github);- }-- 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={resolvePublicFileUrl(creator.avatar_url)}- size={14}- />- <span className="truncate">{t(($) => $.table.by_creator, { name: creator.name })}</span>- </div>- )}- </div>- );-}diff --git a/packages/views/skills/components/skill-list-actions.tsx b/packages/views/skills/components/skill-list-actions.tsxnew file mode 100644index 0000000000..a5b7a97d0b--- /dev/null+++ b/packages/views/skills/components/skill-list-actions.tsx@@ -0,0 +1,637 @@+"use client";++import { useState } from "react";+import {+ Check,+ ChevronRight,+ Loader2,+ MoreHorizontal,+ Plus,+ Trash2,+ X,+} from "lucide-react";+import { useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import type { Agent, SkillSummary } from "@multica/core/types";+import { api } from "@multica/core/api";+import { workspaceKeys } from "@multica/core/workspace/queries";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";+import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@multica/ui/components/ui/collapsible";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../../i18n";+import type { SkillRow } from "./skills-page";++// Shared context the row kebab and the batch toolbar both need. Assembled+// once at the page level.+export interface SkillActionsContext {+ wsId: string;+ agents: Agent[];+ currentUserId: string | null;+ /** Workspace owner/admin — may manage every agent, not only their own. */+ isAdmin: boolean;+}++// ---------------------------------------------------------------------------+// Add-to-agent dialog (multi-select; shared by row kebab and batch toolbar)+// ---------------------------------------------------------------------------++// Attaching is permission-gated by the TARGET agent (its owner, or a+// workspace owner/admin — server/internal/handler/agent.go canManageAgent).+// Members therefore only see their own agents; admins additionally see+// everyone else's. Agents that already have every selected skill render+// checked-out and disabled; partial overlap stays selectable because the+// endpoint is additive ("ensure these skills") and idempotent.+function partitionAgents(ctx: SkillActionsContext) {+ const active = ctx.agents.filter((a) => !a.archived_at);+ const mine = active.filter(+ (a) => a.owner_id !== null && a.owner_id === ctx.currentUserId,+ );+ const others = ctx.isAdmin+ ? active.filter(+ (a) => a.owner_id === null || a.owner_id !== ctx.currentUserId,+ )+ : [];+ return { mine, others };+}++function AgentPickerRow({+ agent,+ skillIds,+ selected,+ onToggle,+}: {+ agent: Agent;+ skillIds: string[];+ selected: boolean;+ onToggle: (agent: Agent) => void;+}) {+ const { t } = useT("skills");+ const owned = skillIds.filter((id) =>+ agent.skills.some((s) => s.id === id),+ ).length;+ const hasAll = owned === skillIds.length;+ return (+ <button+ type="button"+ disabled={hasAll}+ onClick={() => onToggle(agent)}+ aria-pressed={selected}+ className={cn(+ "flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left transition-colors",+ hasAll+ ? "opacity-50"+ : selected+ ? "bg-accent"+ : "hover:bg-accent/50",+ )}+ >+ {/* Indicator only — the wrapping <button> handles clicks. */}+ <Checkbox+ checked={hasAll || selected}+ tabIndex={-1}+ className="pointer-events-none"+ />+ <ActorAvatar+ name={agent.name}+ initials={agent.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(agent.avatar_url)}+ isAgent+ size={22}+ />+ <span className="min-w-0 flex-1 truncate text-sm">{agent.name}</span>+ {hasAll ? (+ <Check className="size-3.5 shrink-0 text-muted-foreground" />+ ) : owned > 0 ? (+ <span className="shrink-0 text-xs text-muted-foreground">+ {t(($) => $.actions.has_partial, { owned, total: skillIds.length })}+ </span>+ ) : null}+ </button>+ );+}++// Shows the first few skill names as chips so the dialog says WHAT is being+// added; the overflow collapses into a "+N" badge with the remaining names+// in a tooltip. Number-agnostic, so single-row and batch share the layout.+const MAX_SKILL_CHIPS = 3;+const MAX_TOOLTIP_NAMES = 10;++function SkillChips({ skills }: { skills: SkillSummary[] }) {+ const visible = skills.slice(0, MAX_SKILL_CHIPS);+ const overflow = skills.slice(MAX_SKILL_CHIPS);+ const chipClass =+ "max-w-[10rem] truncate rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground";+ return (+ <div className="flex flex-wrap items-center gap-1">+ {visible.map((s) => (+ <span key={s.id} className={chipClass}>+ {s.name}+ </span>+ ))}+ {overflow.length > 0 && (+ <Tooltip>+ <TooltipTrigger+ render={+ <span className={cn(chipClass, "font-medium")}>+ +{overflow.length}+ </span>+ }+ />+ <TooltipContent side="bottom" className="max-w-64">+ {overflow+ .slice(0, MAX_TOOLTIP_NAMES)+ .map((s) => s.name)+ .join(", ")}+ {overflow.length > MAX_TOOLTIP_NAMES ? "…" : ""}+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ );+}++// Collapsible agent group; "my agents" opens by default, other people's+// agents start collapsed.+function AgentGroup({+ label,+ agents,+ defaultOpen,+ skillIds,+ selectedIds,+ onToggle,+}: {+ label: string;+ agents: Agent[];+ defaultOpen: boolean;+ skillIds: string[];+ selectedIds: ReadonlySet<string>;+ onToggle: (agent: Agent) => void;+}) {+ if (agents.length === 0) return null;+ return (+ <Collapsible defaultOpen={defaultOpen}>+ <CollapsibleTrigger className="group/trigger flex w-full items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent/50">+ <ChevronRight className="size-3 stroke-[2.5] transition-transform duration-200 group-data-[panel-open]/trigger:rotate-90" />+ <span>{label}</span>+ <span className="text-muted-foreground/60">{agents.length}</span>+ </CollapsibleTrigger>+ <CollapsibleContent className="space-y-0.5">+ {agents.map((agent) => (+ <AgentPickerRow+ key={agent.id}+ agent={agent}+ skillIds={skillIds}+ selected={selectedIds.has(agent.id)}+ onToggle={onToggle}+ />+ ))}+ </CollapsibleContent>+ </Collapsible>+ );+}++export function AddToAgentDialog({+ skills,+ ctx,+ open,+ onOpenChange,+}: {+ skills: SkillSummary[];+ ctx: SkillActionsContext;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useT("skills");+ const qc = useQueryClient();+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(+ new Set(),+ );+ const [saving, setSaving] = useState(false);++ const skillIds = skills.map((s) => s.id);+ const { mine, others } = partitionAgents(ctx);+ const count = selectedIds.size;++ const handleOpenChange = (v: boolean) => {+ if (saving) return;+ if (!v) setSelectedIds(new Set());+ onOpenChange(v);+ };++ const handleToggle = (agent: Agent) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(agent.id)) next.delete(agent.id);+ else next.add(agent.id);+ return next;+ });+ };++ const handleConfirm = async () => {+ const targets = [...mine, ...others].filter((a) => selectedIds.has(a.id));+ if (targets.length === 0) return;+ setSaving(true);+ try {+ for (const agent of targets) {+ const missing = skillIds.filter(+ (id) => !agent.skills.some((s) => s.id === id),+ );+ if (missing.length > 0) {+ await api.addAgentSkills(agent.id, { skill_ids: missing });+ }+ }+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(ctx.wsId) });+ toast.success(+ targets.length === 1 && targets[0]+ ? t(($) => $.actions.added_toast, { name: targets[0].name })+ : t(($) => $.actions.added_multi_toast, { count: targets.length }),+ );+ setSelectedIds(new Set());+ onOpenChange(false);+ } catch (e) {+ toast.error(+ e instanceof Error && e.message+ ? e.message+ : t(($) => $.actions.add_failed_toast),+ );+ } finally {+ setSaving(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ {/* Fixed-height dialog: header/chips/footer stay put, only the agent+ list scrolls (flex-1 + min-h-0). One size up from the default+ confirm dialogs — this is a working picker, not a prompt. */}+ <DialogContent className="flex h-[32rem] max-h-[85svh] max-w-lg flex-col">+ <DialogHeader>+ <DialogTitle className="text-sm">+ {t(($) => $.actions.add_to_agent)}+ </DialogTitle>+ <DialogDescription className="text-xs">+ {t(($) => $.actions.add_dialog_description)}+ </DialogDescription>+ </DialogHeader>++ <SkillChips skills={skills} />++ <div className="min-h-0 flex-1 overflow-y-auto rounded-lg border bg-card p-1.5">+ {mine.length === 0 && others.length === 0 ? (+ <div className="py-6 text-center text-xs text-muted-foreground">+ {t(($) => $.actions.no_agents)}+ </div>+ ) : (+ <>+ <AgentGroup+ label={t(($) => $.actions.my_agents)}+ agents={mine}+ defaultOpen+ skillIds={skillIds}+ selectedIds={selectedIds}+ onToggle={handleToggle}+ />+ <AgentGroup+ label={t(($) => $.actions.other_agents)}+ agents={others}+ defaultOpen={false}+ skillIds={skillIds}+ selectedIds={selectedIds}+ onToggle={handleToggle}+ />+ </>+ )}+ </div>++ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => handleOpenChange(false)}+ disabled={saving}+ >+ {t(($) => $.actions.cancel)}+ </Button>+ <Button+ type="button"+ onClick={handleConfirm}+ disabled={saving || count === 0}+ >+ {saving ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" />+ {t(($) => $.actions.adding)}+ </>+ ) : (+ t(($) => $.actions.add_confirm, { num: count })+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++// ---------------------------------------------------------------------------+// Delete confirmation (single row and batch share one dialog)+// ---------------------------------------------------------------------------++export function DeleteSkillsDialog({+ rows,+ ctx,+ open,+ onOpenChange,+ onDeleted,+}: {+ rows: SkillRow[];+ ctx: SkillActionsContext;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onDeleted?: () => void;+}) {+ const { t } = useT("skills");+ const qc = useQueryClient();+ const [deleting, setDeleting] = useState(false);+ const single = rows.length === 1 ? rows[0] : null;+ const count = rows.length;++ const handleConfirm = async () => {+ setDeleting(true);+ try {+ for (const row of rows) {+ await api.deleteSkill(row.skill.id);+ }+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(ctx.wsId) });+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(ctx.wsId) });+ toast.success(t(($) => $.actions.deleted_toast, { count }));+ onOpenChange(false);+ onDeleted?.();+ } catch (e) {+ toast.error(+ e instanceof Error && e.message+ ? e.message+ : t(($) => $.actions.delete_failed_toast),+ );+ } finally {+ setDeleting(false);+ }+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(v) => {+ if (!deleting) onOpenChange(v);+ }}+ >+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {single+ ? t(($) => $.detail.delete_dialog.title)+ : t(($) => $.actions.delete_dialog_title, { count })}+ </DialogTitle>+ <DialogDescription>+ {single+ ? single.agents.length > 0+ ? t(($) => $.detail.delete_dialog.description_with_agents, {+ name: single.skill.name,+ count: single.agents.length,+ })+ : t(($) => $.detail.delete_dialog.description_no_agents, {+ name: single.skill.name,+ })+ : t(($) => $.actions.delete_dialog_desc, { count })}+ </DialogDescription>+ </DialogHeader>+ <div className="rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">+ {t(($) => $.detail.delete_dialog.warning)}+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={deleting}+ >+ {t(($) => $.detail.delete_dialog.cancel)}+ </Button>+ <Button+ type="button"+ variant="destructive"+ onClick={handleConfirm}+ disabled={deleting}+ >+ {deleting ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" />+ {t(($) => $.detail.delete_dialog.deleting)}+ </>+ ) : (+ <>+ <Trash2 className="h-3 w-3" />+ {t(($) => $.detail.delete_dialog.confirm)}+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++// ---------------------------------------------------------------------------+// Row kebab+// ---------------------------------------------------------------------------++// Lives inside the row <a>; the wrapper span intercepts clicks so opening+// the menu neither navigates (preventDefault kills the anchor's native+// navigation) nor triggers AppLink's push (stopPropagation). Dialog and menu+// contents are portaled, but their React events still bubble through this+// span — which is exactly what keeps them from reaching the row link.+export function SkillRowActions({+ row,+ ctx,+}: {+ row: SkillRow;+ ctx: SkillActionsContext;+}) {+ const { t } = useT("skills");+ const [addOpen, setAddOpen] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);++ return (+ <span+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ className="flex items-center"+ >+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ aria-label={t(($) => $.actions.row_menu)}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"+ >+ <MoreHorizontal className="size-4" />+ </button>+ }+ />+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuItem onClick={() => setAddOpen(true)}>+ <Plus className="size-3.5" />+ {t(($) => $.actions.add_to_agent)}+ </DropdownMenuItem>+ {row.canEdit && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleteOpen(true)}+ >+ <Trash2 className="size-3.5" />+ {t(($) => $.actions.delete)}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ <AddToAgentDialog+ skills={[row.skill]}+ ctx={ctx}+ open={addOpen}+ onOpenChange={setAddOpen}+ />+ <DeleteSkillsDialog+ rows={[row]}+ ctx={ctx}+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ />+ </span>+ );+}++// ---------------------------------------------------------------------------+// Batch toolbar (floating bottom bar, same shape as the issues batch bar)+// ---------------------------------------------------------------------------++export function SkillBatchToolbar({+ rows,+ ctx,+ onClear,+}: {+ rows: SkillRow[];+ ctx: SkillActionsContext;+ onClear: () => void;+}) {+ const { t } = useT("skills");+ const [addOpen, setAddOpen] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);++ if (rows.length === 0) return null;++ const allDeletable = rows.every((r) => r.canEdit);++ const deleteButton = (+ <Button+ variant="ghost"+ size="sm"+ disabled={!allDeletable}+ onClick={() => setDeleteOpen(true)}+ className={cn(+ "text-destructive hover:text-destructive",+ !allDeletable && "pointer-events-none",+ )}+ >+ <Trash2 className="mr-1 size-3.5" />+ {t(($) => $.actions.delete)}+ </Button>+ );++ return (+ <>+ {/* Anchored to the page root (relative), NOT the viewport: with a+ sidebar/split pane open, viewport-centering sits visibly off the+ list's own center. Same rule for every future list page's batch+ toolbar. */}+ <div className="absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg">+ <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">+ <span className="text-sm font-medium">+ {t(($) => $.actions.selected, { count: rows.length })}+ </span>+ <button+ type="button"+ aria-label={t(($) => $.actions.clear_selection)}+ onClick={onClear}+ className="rounded p-0.5 transition-colors hover:bg-accent"+ >+ <X className="size-3.5 text-muted-foreground" />+ </button>+ </div>++ <Button variant="ghost" size="sm" onClick={() => setAddOpen(true)}>+ <Plus className="mr-1 size-3.5" />+ {t(($) => $.actions.add_to_agent)}+ </Button>++ {allDeletable ? (+ deleteButton+ ) : (+ <Tooltip>+ <TooltipTrigger+ render={<span className="inline-flex">{deleteButton}</span>}+ />+ <TooltipContent side="top">+ {t(($) => $.actions.delete_no_permission)}+ </TooltipContent>+ </Tooltip>+ )}+ </div>++ <AddToAgentDialog+ skills={rows.map((r) => r.skill)}+ ctx={ctx}+ open={addOpen}+ onOpenChange={setAddOpen}+ />+ <DeleteSkillsDialog+ rows={rows}+ ctx={ctx}+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ onDeleted={onClear}+ />+ </>+ );+}diff --git a/packages/views/skills/components/skill-list-toolbar.tsx b/packages/views/skills/components/skill-list-toolbar.tsxnew file mode 100644index 0000000000..c0a1b34592--- /dev/null+++ b/packages/views/skills/components/skill-list-toolbar.tsx@@ -0,0 +1,499 @@+"use client";++import {+ ArrowDown,+ ArrowUp,+ ChevronDown,+ Download,+ Filter,+ HardDrive,+ Pencil,+ Search,+ X,+} from "lucide-react";+import type { Agent, MemberWithUser } from "@multica/core/types";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";+import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { Input } from "@multica/ui/components/ui/input";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { Switch } from "@multica/ui/components/ui/switch";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";+import {+ type SkillColumnKey,+ type SkillListFilters,+ type SkillOriginType,+ type SkillSortDirection,+ type SkillSortField,+} from "@multica/core/skills/stores";+import { useT } from "../../i18n";+import type { SkillRow } from "./skills-page";++export type OriginType = SkillOriginType;++const COLUMN_KEYS: SkillColumnKey[] = [+ "usedBy",+ "source",+ "creator",+ "updated",+ "created",+];++const SORT_FIELDS: SkillSortField[] = ["name", "usedBy", "updated", "created"];++export function countActiveFilterDimensions(+ filters: SkillListFilters,+): number {+ let count = 0;+ if (filters.usage.length > 0) count++;+ if (filters.origins.length > 0) count++;+ if (filters.agents.length > 0) count++;+ if (filters.creators.length > 0) count++;+ return count;+}++const ORIGIN_TYPES: OriginType[] = [+ "manual",+ "runtime_local",+ "clawhub",+ "skills_sh",+ "github",+];++function originIcon(type: OriginType) {+ if (type === "manual") return <Pencil className="size-3.5" />;+ if (type === "runtime_local") return <HardDrive className="size-3.5" />;+ return <Download className="size-3.5" />;+}++export function SkillListToolbar({+ search,+ onSearchChange,+ filters,+ onToggleFilter,+ onClearFilters,+ sortField,+ sortDirection,+ onSortFieldChange,+ onSortDirectionChange,+ hiddenColumns,+ onToggleColumn,+ allRows,+ visibleCount,+}: {+ search: string;+ onSearchChange: (v: string) => void;+ filters: SkillListFilters;+ onToggleFilter: (key: keyof SkillListFilters, value: string) => void;+ onClearFilters: () => void;+ sortField: SkillSortField;+ sortDirection: SkillSortDirection;+ onSortFieldChange: (field: SkillSortField) => void;+ onSortDirectionChange: (direction: SkillSortDirection) => void;+ hiddenColumns: SkillColumnKey[];+ onToggleColumn: (key: SkillColumnKey) => void;+ /** Unfiltered rows — option lists and counts derive from the full set. */+ allRows: SkillRow[];+ /** Rows surviving search + filters — shown as "n / total" when narrowed. */+ visibleCount: number;+}) {+ const { t } = useT("skills");++ const activeCount = countActiveFilterDimensions(filters);+ const hasActiveFilters = activeCount > 0;++ // Option lists with counts, derived from the unfiltered rows so toggling+ // one dimension doesn't make the others' options vanish.+ const usedCount = allRows.filter((r) => r.agents.length > 0).length;+ const unusedCount = allRows.length - usedCount;++ const originCounts = new Map<OriginType, number>();+ const agentOptions = new Map<string, { agent: Agent; count: number }>();+ const creatorOptions = new Map<+ string,+ { member: MemberWithUser; count: number }+ >();+ for (const row of allRows) {+ originCounts.set(row.originType, (originCounts.get(row.originType) ?? 0) + 1);+ for (const agent of row.agents) {+ const entry = agentOptions.get(agent.id);+ if (entry) entry.count += 1;+ else agentOptions.set(agent.id, { agent, count: 1 });+ }+ if (row.creator) {+ const entry = creatorOptions.get(row.creator.user_id);+ if (entry) entry.count += 1;+ else creatorOptions.set(row.creator.user_id, { member: row.creator, count: 1 });+ }+ }++ const ORIGIN_LABELS: Record<OriginType, string> = {+ manual: t(($) => $.table.source_manual),+ runtime_local: t(($) => $.table.source_runtime_unknown),+ clawhub: t(($) => $.table.source_clawhub),+ skills_sh: t(($) => $.table.source_skills_sh),+ github: t(($) => $.table.source_github),+ };++ const COLUMN_LABELS: Record<SkillColumnKey, string> = {+ usedBy: t(($) => $.table.used_by),+ source: t(($) => $.table.source),+ creator: t(($) => $.table.created_by),+ updated: t(($) => $.table.updated),+ created: t(($) => $.table.created),+ };++ const SORT_LABELS: Record<SkillSortField, string> = {+ name: t(($) => $.table.name),+ usedBy: t(($) => $.table.used_by),+ updated: t(($) => $.table.updated),+ created: t(($) => $.table.created),+ };+ const sortLabel = SORT_LABELS[sortField];++ const countBadge = (n: number) => (+ <span className="ml-auto pl-3 text-xs text-muted-foreground">{n}</span>+ );++ return (+ <div className="flex h-12 shrink-0 items-center justify-between gap-2 px-5">+ {/* Left: name search + result count. The count only appears while+ search/filters narrow the list — in the idle state it would just+ duplicate the total already shown in the page header. Below md the+ search (and its count) disappear entirely, following the issues+ header's small-screen treatment. */}+ <div className="flex min-w-0 items-center gap-2">+ <div className="relative hidden md:block">+ <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+ value={search}+ onChange={(e) => onSearchChange(e.target.value)}+ placeholder={t(($) => $.page.search_placeholder)}+ className="h-8 w-64 pl-8 text-sm"+ />+ </div>+ {(hasActiveFilters || search.trim().length > 0) && (+ <span+ title={t(($) => $.toolbar.result_count_title)}+ className="hidden shrink-0 text-xs tabular-nums text-muted-foreground md:inline"+ >+ {visibleCount} / {allRows.length}+ </span>+ )}+ </div>++ <div className="flex shrink-0 items-center gap-1">+ {/* Filter */}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant={hasActiveFilters ? "default" : "outline"}+ size="sm"+ className={+ hasActiveFilters+ ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"+ : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ }+ >+ <Filter className="size-3.5" />+ {hasActiveFilters ? (+ <>+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_active_count, {+ count: activeCount,+ })}+ </span>+ <span className="tabular-nums md:hidden">+ {activeCount}+ </span>+ </>+ ) : (+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_label)}+ </span>+ )}+ {hasActiveFilters && (+ <span+ role="button"+ tabIndex={-1}+ aria-label={t(($) => $.toolbar.clear_filters)}+ className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onClearFilters();+ }}+ onPointerDown={(e) => e.stopPropagation()}+ >+ <X className="size-3" />+ </span>+ )}+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-auto">+ {/* Usage */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_usage)}+ </span>+ {filters.usage.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.usage.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-44">+ {(["used", "unused"] as const).map((value) => (+ <DropdownMenuCheckboxItem+ key={value}+ checked={filters.usage.includes(value)}+ onCheckedChange={() => onToggleFilter("usage", value)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.usage.includes(value)} />+ {value === "used"+ ? t(($) => $.page.scopes.used.label)+ : t(($) => $.page.scopes.unused.label)}+ {countBadge(value === "used" ? usedCount : unusedCount)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Source */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.table.source)}</span>+ {filters.origins.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.origins.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-48">+ {ORIGIN_TYPES.filter((type) => originCounts.has(type)).map(+ (type) => (+ <DropdownMenuCheckboxItem+ key={type}+ checked={filters.origins.includes(type)}+ onCheckedChange={() => onToggleFilter("origins", type)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.origins.includes(type)} />+ {originIcon(type)}+ {ORIGIN_LABELS[type]}+ {countBadge(originCounts.get(type) ?? 0)}+ </DropdownMenuCheckboxItem>+ ),+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Used by */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.table.used_by)}</span>+ {filters.agents.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.agents.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {[...agentOptions.values()].map(({ agent, count }) => (+ <DropdownMenuCheckboxItem+ key={agent.id}+ checked={filters.agents.includes(agent.id)}+ onCheckedChange={() => onToggleFilter("agents", agent.id)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.agents.includes(agent.id)} />+ <ActorAvatar+ name={agent.name}+ initials={agent.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(agent.avatar_url)}+ isAgent+ size={16}+ />+ <span className="min-w-0 truncate">{agent.name}</span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ {/* Creator */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.table.created_by)}</span>+ {filters.creators.length > 0 && (+ <span className="text-xs font-medium text-primary">+ {filters.creators.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {[...creatorOptions.values()].map(({ member, count }) => (+ <DropdownMenuCheckboxItem+ key={member.user_id}+ checked={filters.creators.includes(member.user_id)}+ onCheckedChange={() =>+ onToggleFilter("creators", member.user_id)+ }+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck+ checked={filters.creators.includes(member.user_id)}+ />+ <ActorAvatar+ name={member.name}+ initials={member.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(member.avatar_url)}+ size={16}+ />+ <span className="min-w-0 truncate">{member.name}</span>+ {countBadge(count)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>++ {/* Display settings — same paradigm as the issues header: Popover+ with bordered sections, trigger shows the active sort (direction+ arrow + field label), sort row is a nested select + a direction+ toggle button, columns are label+Switch rows. Mutates the same+ sort state pair the list header buttons use. */}+ <Popover>+ <Tooltip>+ <PopoverTrigger+ render={+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ <span className="hidden md:inline">{sortLabel}</span>+ </Button>+ }+ />+ }+ />+ <TooltipContent side="bottom">+ {t(($) => $.toolbar.display)}+ </TooltipContent>+ </Tooltip>+ <PopoverContent align="end" className="w-64 p-0">+ <div className="border-b px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.sort_by)}+ </span>+ <div className="mt-2 flex items-center gap-1.5">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="flex-1 justify-between text-xs"+ >+ {sortLabel}+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={sortField}+ onValueChange={(v) =>+ onSortFieldChange(v as SkillSortField)+ }+ >+ {SORT_FIELDS.map((field) => (+ <DropdownMenuRadioItem key={field} value={field}>+ {SORT_LABELS[field]}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ <Button+ variant="outline"+ size="icon-sm"+ onClick={() =>+ onSortDirectionChange(+ sortDirection === "asc" ? "desc" : "asc",+ )+ }+ title={+ sortDirection === "asc"+ ? t(($) => $.toolbar.direction_asc)+ : t(($) => $.toolbar.direction_desc)+ }+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ </Button>+ </div>+ </div>++ <div className="px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.section_columns)}+ </span>+ <div className="mt-2 space-y-2">+ {COLUMN_KEYS.map((key) => (+ <label+ key={key}+ className="flex cursor-pointer items-center justify-between"+ >+ <span className="text-sm">{COLUMN_LABELS[key]}</span>+ <Switch+ size="sm"+ checked={!hiddenColumns.includes(key)}+ onCheckedChange={() => onToggleColumn(key)}+ />+ </label>+ ))}+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ </div>+ );+}diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsxindex 9ce9763ff0..21b0ea396f 100644--- a/packages/views/skills/components/skills-page.tsx+++ b/packages/views/skills/components/skills-page.tsx@@ -1,21 +1,25 @@"use client";-import { useMemo, useState } from "react";+import { useMemo, useRef, useState } from "react";import {AlertCircle,AlertTriangle,BookOpen,+ Download,+ HardDrive,+ Lock,+ Pencil,Plus,- Search,} from "lucide-react";import type {+ Agent,AgentRuntime,MemberWithUser,Skill,SkillSummary,} from "@multica/core/types";import { useQuery } from "@tanstack/react-query";-import { getCoreRowModel, useReactTable } from "@tanstack/react-table";+import { useVirtualizer } from "@tanstack/react-virtual";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";@@ -26,26 +30,129 @@ import {skillListOptions,} from "@multica/core/workspace/queries";import { runtimeListOptions } from "@multica/core/runtimes";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";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 { Checkbox } from "@multica/ui/components/ui/checkbox";+import {+ LIST_GRID_BOTTOM_CLEARANCE,+ ListGrid,+ ListGridBody,+ ListGridCell,+ ListGridHeader,+ ListGridHeaderCell,+ ListGridRow,+ type ListGridSortDirection,+} from "@multica/ui/components/ui/list-grid";import { Skeleton } from "@multica/ui/components/ui/skeleton";import {Tooltip,TooltipContent,TooltipTrigger,} from "@multica/ui/components/ui/tooltip";-import { useNavigation } from "../../navigation";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";+import { AppLink, useNavigation } from "../../navigation";import { PageHeader } from "../../layout/page-header";import { canEditSkill } from "../hooks/use-can-edit-skill";-import { readOrigin } from "../lib/origin";+import { readOrigin, type OriginInfo } from "../lib/origin";import { CreateSkillDialog } from "./create-skill-dialog";-import { type SkillRow, useSkillColumns } from "./skill-columns";-import { useT } from "../../i18n";+import {+ useSkillsViewStore,+ DEFAULT_HIDDEN_COLUMNS,+ type SkillColumnKey,+ type SkillSortField,+} from "@multica/core/skills/stores";+import { SkillListToolbar } from "./skill-list-toolbar";+import {+ SkillBatchToolbar,+ SkillRowActions,+ type SkillActionsContext,+} from "./skill-list-actions";+import { useT, useTimeAgo } from "../../i18n";++// Column template — single source of truth for header, rows, and skeletons.+// Tracks: [edge 0.75rem] [checkbox 1rem] [name, only fr track]+// [usedBy] [source] [creator] [updated] [created] [kebab 1.75rem]+// [edge 0.75rem].+// Content cells carry a default px-2 from list-grid.tsx+// (structural columns opt out with px-0), so the narrow edge tracks plus+// cell padding land content 20px from the container edge. Non-core cells+// carry `hidden @2xl:flex`. The breakpoint queries the CONTAINER (the page+// wrapper is the `@container`), not the viewport, so sidebars and split+// panes are accounted for.+// Hideable tracks are DETERMINISTIC widths via CSS vars (no max-content):+// rows are virtualized, so with only the visible slice mounted a+// content-driven track would resize as different rows scrolled into view.+// Truncation moved from per-cell max-w caps to the tracks themselves.+// A user-hidden column zeroes its var (columnTrackVars), collapsing the+// track exactly like the old max-content placeholder did; the empty+// placeholder cell stays rendered to keep subgrid auto-placement intact.+//+// TWO-ZONE RESPONSIVENESS (replaces the retired per-tier breakpoints):+// - Container ≥ @2xl (672px): WYSIWYG — every user-enabled column renders.+// The grid carries min-width = Σ(enabled tracks + gaps) so when the+// enabled set outgrows the container the wrapper scrolls horizontally.+// The scrollbar is the escape valve for an over-provisioned column set,+// never the default experience; an enabled column must NEVER silently+// vanish (that "dead toggle" bug shipped twice).+// - Container < @2xl (phones, slim split panes): static core set+// (name + usedBy), no horizontal scroll, column toggles don't apply.+const GRID_COLS =+ "grid-cols-[0.75rem_1rem_minmax(120px,1fr)_var(--lgc-usedby)_1.75rem_0.75rem] " ++ "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_var(--lgc-usedby)_var(--lgc-source)_var(--lgc-creator)_var(--lgc-updated)_var(--lgc-created)_1.75rem_0.75rem]";++// h-12 rows. The virtualizer's fixed-size contract: every row renders at+// exactly this height, which is what lets it skip per-row measurement.+const ROW_HEIGHT = 48;++// Single source for hideable column widths: track vars and the grid's+// min-width derive from the same numbers.+const COLUMN_WIDTHS: Record<SkillColumnKey, number> = {+ usedBy: 144,+ source: 152,+ creator: 144,+ updated: 104,+ created: 104,+};++// Fixed tracks (edges 12+12, checkbox 16, name min 200, kebab 28) plus the+// 9 gap-x-3 gaps between the wide template's 10 tracks (zero-width tracks+// still carry gaps).+const FIXED_TRACKS_WIDTH = 268 + 9 * 12;++function columnTrackVars(+ isVisible: (key: SkillColumnKey) => boolean,+): React.CSSProperties {+ const width = (key: SkillColumnKey) =>+ isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";+ const minWidth =+ FIXED_TRACKS_WIDTH ++ (Object.keys(COLUMN_WIDTHS) as SkillColumnKey[]).reduce(+ (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),+ 0,+ );+ return {+ "--lgc-usedby": width("usedBy"),+ "--lgc-source": width("source"),+ "--lgc-creator": width("creator"),+ "--lgc-updated": width("updated"),+ "--lgc-created": width("created"),+ "--lgc-minw": `${minWidth}px`,+ } as React.CSSProperties;+}-type FilterKey = "all" | "used" | "unused" | "mine";+// Sort/filter/column types and defaults live in the core view store+// (@multica/core/skills/stores/view-store) so the persisted state and the+// UI share one definition. Re-exported here for the toolbar's convenience.+export type SortField = SkillSortField;-const SCOPE_KEYS: FilterKey[] = ["all", "used", "unused", "mine"];+export interface SkillRow {+ skill: SkillSummary;+ agents: Agent[];+ creator: MemberWithUser | null;+ runtime: AgentRuntime | null;+ originType: OriginInfo["type"];+ canEdit: boolean;+}// ---------------------------------------------------------------------------// Page header bar — uses shared PageHeader so the mobile sidebar trigger and@@ -82,67 +189,205 @@ function PageHeaderBar({</a></p></div>- <Button type="button" size="sm" onClick={onCreate}>- <Plus className="h-3 w-3" />- {t(($) => $.page.new_skill)}+ {/* Quiet chrome button (outline, icon-only below md) — primary is+ reserved for the empty state's single CTA. */}+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-8 w-8 gap-1 px-0 md:w-auto md:px-2.5"+ aria-label={t(($) => $.page.new_skill)}+ onClick={onCreate}+ >+ <Plus className="h-3.5 w-3.5" />+ <span className="hidden md:inline">{t(($) => $.page.new_skill)}</span></Button></PageHeader>);}// ----------------------------------------------------------------------------// Card toolbar — search + scope filters+// Cells// ----------------------------------------------------------------------------function CardToolbar({- search,- setSearch,- filter,- setFilter,+// Hover-revealed multi-select checkbox. Same pattern as SkillPickerList:+// the shadcn Checkbox is presentational only (`pointer-events-none`, so the+// Base UI button can never swallow the click) and the wrapping <button> owns+// the interaction — preventDefault kills the row link's native navigation+// (the cell lives inside an <a>), stopPropagation keeps AppLink's push from+// firing, and the manual toggle drives the state.+function CheckboxCell({+ checked,+ onToggle,}: {- search: string;- setSearch: (v: string) => void;- filter: FilterKey;- setFilter: (v: FilterKey) => void;+ checked: boolean;+ onToggle: () => void;}) {+ return (+ <ListGridCell className="justify-center px-0">+ <button+ type="button"+ aria-pressed={checked}+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onToggle();+ }}+ className={`-m-1.5 flex items-center p-1.5 ${+ checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"+ }`}+ >+ <Checkbox+ checked={checked}+ tabIndex={-1}+ className="pointer-events-none"+ />+ </button>+ </ListGridCell>+ );+}++function NameCell({ row }: { row: SkillRow }) {const { t } = useT("skills");+ const { skill, canEdit } = row;return (- <div className="flex h-auto shrink-0 flex-col gap-2 border-b px-3 py-3 sm:h-12 sm:flex-row sm:items-center sm:px-4 sm:py-0">- <div className="relative w-full sm:w-auto">- <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- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder={t(($) => $.page.search_placeholder)}- className="h-8 w-full pl-8 text-sm sm:w-64"+ <ListGridCell className="gap-1.5">+ <span className="min-w-0 truncate text-sm font-medium">+ {skill.name}+ </span>+ {!canEdit && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Lock className="h-3 w-3 shrink-0 text-muted-foreground/60" />+ }+ />+ <TooltipContent>{t(($) => $.table.lock_tooltip)}</TooltipContent>+ </Tooltip>+ )}+ </ListGridCell>+ );+}++function UsedByCell({ agents }: { agents: Agent[] }) {+ const { t } = useT("skills");+ if (agents.length === 0) {+ return (+ <ListGridCell>+ <span className="text-xs text-muted-foreground/70">+ {t(($) => $.table.unused)}+ </span>+ </ListGridCell>+ );+ }+ const soleAgent = agents.length === 1 ? agents[0] : undefined;+ if (soleAgent) {+ const agent = soleAgent;+ return (+ <ListGridCell className="gap-1.5">+ <ActorAvatar+ name={agent.name}+ initials={agent.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(agent.avatar_url)}+ isAgent+ size={22}/>- </div>- <div className="-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 sm:mx-0 sm:overflow-visible sm:px-0 sm:pb-0">- {SCOPE_KEYS.map((scope) => (- <Tooltip key={scope}>+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {agent.name}+ </span>+ </ListGridCell>+ );+ }+ const visible = agents.slice(0, 3);+ const extra = agents.length - visible.length;+ return (+ <ListGridCell>+ <div className="flex items-center -space-x-1.5">+ {visible.map((a) => (+ <Tooltip key={a.id}><TooltipTriggerrender={- <Button- variant="outline"- size="sm"- className={- filter === scope- ? "shrink-0 bg-accent text-accent-foreground hover:bg-accent/80"- : "shrink-0 text-muted-foreground"- }- onClick={() => setFilter(scope)}- >- {t(($) => $.page.scopes[scope].label)}- </Button>+ <span className="inline-flex rounded-full ring-2 ring-background">+ <ActorAvatar+ name={a.name}+ initials={a.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(a.avatar_url)}+ isAgent+ size={22}+ />+ </span>}/>- <TooltipContent side="bottom">- {t(($) => $.page.scopes[scope].description)}- </TooltipContent>+ <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>- </div>+ </ListGridCell>+ );+}++function SourceCell({+ skill,+ runtime,+}: {+ skill: SkillSummary;+ runtime: AgentRuntime | null;+}) {+ const { t } = useT("skills");+ const origin = readOrigin(skill);++ let icon = <Pencil className="h-3 w-3 shrink-0" />;+ let label: string = t(($) => $.table.source_manual);+ if (origin.type === "runtime_local") {+ icon = <HardDrive className="h-3 w-3 shrink-0" />;+ label = runtime+ ? t(($) => $.table.source_runtime_named, { name: runtime.name })+ : origin.provider+ ? t(($) => $.table.source_runtime_provider, {+ provider: origin.provider,+ })+ : t(($) => $.table.source_runtime_unknown);+ } else if (origin.type === "clawhub") {+ icon = <Download className="h-3 w-3 shrink-0" />;+ label = t(($) => $.table.source_clawhub);+ } else if (origin.type === "skills_sh") {+ icon = <Download className="h-3 w-3 shrink-0" />;+ label = t(($) => $.table.source_skills_sh);+ } else if (origin.type === "github") {+ icon = <Download className="h-3 w-3 shrink-0" />;+ label = t(($) => $.table.source_github);+ }++ return (+ <ListGridCell className="hidden gap-1.5 text-xs text-muted-foreground @2xl:flex">+ {icon}+ <span className="min-w-0 truncate">{label}</span>+ </ListGridCell>+ );+}++function CreatorCell({ creator }: { creator: MemberWithUser | null }) {+ return (+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ {creator && (+ <>+ <ActorAvatar+ name={creator.name}+ initials={creator.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(creator.avatar_url)}+ size={22}+ />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {creator.name}+ </span>+ </>+ )}+ </ListGridCell>);}@@ -169,6 +414,161 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {);}+// ---------------------------------------------------------------------------+// List+// ---------------------------------------------------------------------------++function SkillListHeader({+ sortField,+ sortDirection,+ onSort,+ allSelected,+ someSelected,+ onToggleAll,+ isColVisible,+}: {+ sortField: SortField;+ sortDirection: ListGridSortDirection;+ onSort: (field: SortField) => void;+ allSelected: boolean;+ someSelected: boolean;+ onToggleAll: () => void;+ isColVisible: (key: SkillColumnKey) => boolean;+}) {+ const { t } = useT("skills");+ const sorted = (field: SortField) =>+ sortField === field ? sortDirection : false;+ const anySelected = allSelected || someSelected;+ return (+ <ListGridHeader>+ {/* Tri-state select-all in the checkbox track. Same presentational+ Checkbox + interactive wrapper pattern as the row cells; revealed+ on header hover or whenever a selection exists. */}+ <div className="flex items-center justify-center">+ <button+ type="button"+ aria-pressed={allSelected}+ onClick={onToggleAll}+ className={`-m-1.5 flex items-center p-1.5 ${+ anySelected+ ? ""+ : "opacity-0 transition-opacity group-hover/header:opacity-100"+ }`}+ >+ <Checkbox+ checked={allSelected}+ indeterminate={someSelected && !allSelected}+ tabIndex={-1}+ className="pointer-events-none"+ />+ </button>+ </div>+ <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>+ {t(($) => $.table.name)}+ </ListGridHeaderCell>+ {isColVisible("usedBy") ? (+ <ListGridHeaderCell+ sorted={sorted("usedBy")}+ onSort={() => onSort("usedBy")}+ >+ {t(($) => $.table.used_by)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="px-0" />+ )}+ {isColVisible("source") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.table.source)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("creator") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.table.created_by)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("updated") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("updated")}+ onSort={() => onSort("updated")}+ >+ {t(($) => $.table.updated)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("created")}+ onSort={() => onSort("created")}+ >+ {t(($) => $.table.created)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ <span aria-hidden="true" />+ </ListGridHeader>+ );+}++function LoadingSkeleton() {+ return (+ <ListGrid+ className={GRID_COLS}+ style={columnTrackVars((key) => !DEFAULT_HIDDEN_COLUMNS.includes(key))}+ >+ <ListGridHeader>+ <span aria-hidden="true" />+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-14" />+ </ListGridHeaderCell>+ {/* Source and created are hidden by default — keep their tracks+ mapped with empty placeholders so the skeleton matches the+ default layout. */}+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-10" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridHeader>+ {Array.from({ length: 5 }).map((_, i) => (+ <ListGridRow key={i} className="hover:bg-transparent">+ <span aria-hidden="true" />+ <ListGridCell>+ <Skeleton className="h-3.5 w-40 max-w-full" />+ </ListGridCell>+ <ListGridCell>+ <Skeleton className="h-5 w-14" />+ </ListGridCell>+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ <Skeleton className="size-5 rounded-full" />+ <Skeleton className="h-3 w-12" />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-10" />+ </ListGridCell>+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridRow>+ ))}+ </ListGrid>+ );+}+// ---------------------------------------------------------------------------// Page// ---------------------------------------------------------------------------@@ -178,6 +578,7 @@ export default function SkillsPage() {const wsId = useWorkspaceId();const paths = useWorkspacePaths();const navigation = useNavigation();+ const timeAgo = useTimeAgo();const currentUserId = useAuthStore((s) => s.user?.id ?? null);const {@@ -196,14 +597,39 @@ export default function SkillsPage() {runtimeListOptions(wsId),);- const [search, setSearch] = useState("");- const [filter, setFilter] = useState<FilterKey>("all");const [createOpen, setCreateOpen] = useState(false);-- const assignments = useMemo(- () => selectSkillAssignments(agents),- [agents],+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(+ new Set(),);+ const [search, setSearch] = useState("");++ // Persisted view preferences (per workspace, per user/device). Header sort+ // buttons and the toolbar's display panel mutate the SAME store, so both+ // surfaces always agree. Search and selection stay session-local on+ // purpose.+ const sortField = useSkillsViewStore((s) => s.sortField);+ const sortDirection = useSkillsViewStore((s) => s.sortDirection);+ const hiddenColumns = useSkillsViewStore((s) => s.hiddenColumns);+ const filters = useSkillsViewStore((s) => s.filters);+ const handleSort = useSkillsViewStore((s) => s.toggleSort);+ const handleSortFieldSelect = useSkillsViewStore((s) => s.setSortField);+ const setSortDirection = useSkillsViewStore((s) => s.setSortDirection);+ const toggleColumn = useSkillsViewStore((s) => s.toggleColumn);+ const toggleFilter = useSkillsViewStore((s) => s.toggleFilter);+ const clearFilters = useSkillsViewStore((s) => s.clearFilters);++ const isColVisible = (key: SkillColumnKey) => !hiddenColumns.includes(key);++ const toggleSelected = (id: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ const assignments = useMemo(() => selectSkillAssignments(agents), [agents]);const membersById = useMemo(() => {const map = new Map<string, MemberWithUser>();@@ -218,34 +644,20 @@ export default function SkillsPage() {}, [runtimes]);const myRole =- members.find((m) => m.user_id === currentUserId)?.role ?? null;-- const filtered = useMemo(() => {- const q = search.trim().toLowerCase();- const byAssignment = (s: SkillSummary) =>- (assignments.get(s.id)?.length ?? 0) > 0;-- return skills.filter((s) => {- if (- q &&- !s.name.toLowerCase().includes(q) &&- !s.description.toLowerCase().includes(q)- ) {- return false;- }- if (filter === "used" && !byAssignment(s)) return false;- if (filter === "unused" && byAssignment(s)) return false;- if (filter === "mine" && s.created_by !== currentUserId) return false;- return true;- });- }, [skills, assignments, search, filter, currentUserId]);+ members.find((m: MemberWithUser) => m.user_id === currentUserId)?.role ??+ null;+ const isAdmin = myRole === "owner" || myRole === "admin";- const handleCreated = (skill: Skill) => {- navigation.push(paths.skillDetail(skill.id));+ const actionsCtx: SkillActionsContext = {+ wsId,+ agents,+ currentUserId,+ isAdmin,};- const skillRows = useMemo<SkillRow[]>(() => {- return filtered.map((skill) => {+ // Full assembled set — toolbar option lists and counts derive from this.+ const allRows = useMemo<SkillRow[]>(() => {+ return skills.map((skill) => {const origin = readOrigin(skill);const runtime =origin.type === "runtime_local" && origin.runtime_id@@ -258,57 +670,94 @@ export default function SkillsPage() {? membersById.get(skill.created_by) ?? null: null,runtime,- canEdit: canEditSkill(skill, {- userId: currentUserId,- role: myRole,- }),+ originType: origin.type,+ canEdit: canEditSkill(skill, { userId: currentUserId, role: myRole }),};});- }, [- filtered,- assignments,- membersById,- runtimesById,- currentUserId,- myRole,- ]);+ }, [skills, assignments, membersById, runtimesById, currentUserId, myRole]);++ // Visible rows: name search + filters, then sort.+ const rows = useMemo<SkillRow[]>(() => {+ const q = search.trim().toLowerCase();+ const filtered = allRows.filter((row) => {+ if (q && !row.skill.name.toLowerCase().includes(q)) return false;+ if (filters.usage.length > 0) {+ const usage = row.agents.length > 0 ? "used" : "unused";+ if (!filters.usage.includes(usage)) return false;+ }+ if (+ filters.origins.length > 0 &&+ !filters.origins.includes(row.originType)+ ) {+ return false;+ }+ if (+ filters.agents.length > 0 &&+ !row.agents.some((a) => filters.agents.includes(a.id))+ ) {+ return false;+ }+ if (+ filters.creators.length > 0 &&+ (!row.skill.created_by ||+ !filters.creators.includes(row.skill.created_by))+ ) {+ return false;+ }+ return true;+ });- const columns = useSkillColumns();+ const dir = sortDirection === "asc" ? 1 : -1;+ filtered.sort((a, b) => {+ if (sortField === "name") {+ return a.skill.name.localeCompare(b.skill.name) * dir;+ }+ if (sortField === "usedBy") {+ return (+ (a.agents.length - b.agents.length) * dir ||+ a.skill.name.localeCompare(b.skill.name)+ );+ }+ if (sortField === "created") {+ return (+ (Date.parse(a.skill.created_at) - Date.parse(b.skill.created_at)) *+ dir+ );+ }+ return (+ (Date.parse(a.skill.updated_at) - Date.parse(b.skill.updated_at)) * dir+ );+ });+ return filtered;+ }, [allRows, search, filters, sortField, sortDirection]);- const table = useReactTable({- data: skillRows,- columns,- getCoreRowModel: getCoreRowModel(),- enableColumnResizing: true,+ // Row virtualization — Linear-style: the virtualizer only does the math+ // (visible index range + offsets); the DOM stays ours. Offsets become+ // padding on the rows wrapper, so the mounted rows remain direct subgrid+ // children and column alignment is untouched. Fixed ROW_HEIGHT rows mean+ // no per-row measurement. The scroll element is the SINGLE outer+ // scroller (both axes) — see ListGridBody's comment for why the split+ // scroll structure was retired.+ const listScrollRef = useRef<HTMLDivElement | null>(null);+ const rowVirtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => listScrollRef.current,+ estimateSize: () => ROW_HEIGHT,+ overscan: 10,});- // --- Loading ---- if (isLoading) {- return (- <div className="flex flex-1 min-h-0 flex-col">- <PageHeaderBar totalCount={0} onCreate={() => setCreateOpen(true)} />- <div className="flex flex-1 min-h-0 flex-col gap-4 p-3 sm:p-6">- <div className="space-y-3 pl-4">- <Skeleton className="h-5 w-full max-w-2xl rounded-md" />- <Skeleton className="h-14 w-full max-w-3xl rounded-md" />- </div>- <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border">- <div className="flex h-auto shrink-0 flex-col gap-2 border-b px-3 py-3 sm:h-12 sm:flex-row sm:items-center sm:px-4 sm:py-0">- <Skeleton className="h-8 w-full rounded-md sm:w-64" />- <Skeleton className="h-7 w-12 rounded-md" />- <Skeleton className="h-7 w-14 rounded-md" />- <Skeleton className="h-7 w-16 rounded-md" />- </div>- <div className="space-y-2 p-4">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-14 w-full rounded-md" />- ))}- </div>- </div>- </div>- </div>+ const handleCreated = (skill: Skill) => {+ navigation.push(paths.skillDetail(skill.id));+ };++ const selectedRows = rows.filter((row) => selectedIds.has(row.skill.id));+ const allSelected = rows.length > 0 && selectedRows.length === rows.length;+ const someSelected = selectedRows.length > 0 && !allSelected;+ const handleToggleAll = () => {+ setSelectedIds(+ allSelected ? new Set() : new Set(rows.map((r) => r.skill.id)),);- }+ };// --- List request error ---if (listError) {@@ -341,12 +790,26 @@ export default function SkillsPage() {}const totalCount = skills.length;- const showEmpty = totalCount === 0;+ const showEmpty = !isLoading && totalCount === 0;const supportingQueryDown =!!agentsError || !!membersError || !!runtimesError;+ // Unmounted rows above/below the visible slice become padding on the+ // scrolling body, exactly like Linear's --x-paddingTop/Bottom offsets.+ const virtualItems = rowVirtualizer.getVirtualItems();+ const firstVirtual = virtualItems[0];+ const lastVirtual = virtualItems[virtualItems.length - 1];+ const virtualPadding = {+ top: firstVirtual ? firstVirtual.start : 0,+ bottom: lastVirtual+ ? rowVirtualizer.getTotalSize() - lastVirtual.end+ : 0,+ };+return (- <div className="flex flex-1 min-h-0 flex-col">+ // relative: positioning anchor for the batch toolbar (page-centered,+ // not viewport-centered).+ <div className="relative flex flex-1 min-h-0 flex-col"><PageHeaderBartotalCount={totalCount}onCreate={() => setCreateOpen(true)}@@ -362,58 +825,122 @@ export default function SkillsPage() {</div>)}- <div className="flex flex-1 min-h-0 flex-col gap-4 p-3 sm:p-6">- {!showEmpty && (- <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">- {t(($) => $.page.intro_banner.title)}- </span>{" "}- {t(($) => $.page.intro_banner.body)}{" "}- <span className="font-semibold text-brand">- {t(($) => $.page.intro_banner.highlight)}- </span>- </div>- )}- {showEmpty ? (- <div className="flex flex-1 items-center justify-center">- <EmptyState onCreate={() => setCreateOpen(true)} />- </div>- ) : (- <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border bg-background">- <CardToolbar- search={search}- setSearch={setSearch}- filter={filter}- setFilter={setFilter}+ {isLoading ? (+ <div className="flex-1 overflow-y-auto @container">+ <LoadingSkeleton />+ </div>+ ) : showEmpty ? (+ <div className="flex flex-1 items-center justify-center">+ <EmptyState onCreate={() => setCreateOpen(true)} />+ </div>+ ) : (+ <>+ <SkillListToolbar+ search={search}+ onSearchChange={setSearch}+ filters={filters}+ onToggleFilter={toggleFilter}+ onClearFilters={clearFilters}+ sortField={sortField}+ sortDirection={sortDirection}+ onSortFieldChange={handleSortFieldSelect}+ onSortDirectionChange={setSortDirection}+ hiddenColumns={hiddenColumns}+ onToggleColumn={toggleColumn}+ allRows={allRows}+ visibleCount={rows.length}+ />+ <div+ ref={listScrollRef}+ className="min-h-0 flex-1 overflow-auto @container"+ >+ <ListGrid+ className={`${GRID_COLS} @2xl:min-w-[var(--lgc-minw)]`}+ style={columnTrackVars(isColVisible)}+ >+ <SkillListHeader+ sortField={sortField}+ sortDirection={sortDirection}+ onSort={handleSort}+ allSelected={allSelected}+ someSelected={someSelected}+ onToggleAll={handleToggleAll}+ isColVisible={isColVisible}/>- {filtered.length === 0 ? (- <div className="flex flex-1 flex-col items-center justify-center gap-2 px-4 py-16 text-center text-muted-foreground">- <Search className="h-8 w-8 text-muted-foreground/40" />- <p className="text-sm">{t(($) => $.page.no_matches.title)}</p>- <p className="max-w-xs text-xs">- {search- ? t(($) => $.page.no_matches.with_query, {- query: search,- filterSuffix:- filter !== "all"- ? t(($) => $.page.no_matches.with_query_filter_suffix)- : "",- })- : t(($) => $.page.no_matches.filter_only)}- {t(($) => $.page.no_matches.try_different)}- </p>- </div>- ) : (- <DataTable- table={table}- onRowClick={(row) =>- navigation.push(paths.skillDetail(row.original.skill.id))+ <ListGridBody+ style={{+ paddingTop: virtualPadding.top,+ paddingBottom:+ virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,+ }}+ >+ {rows.length === 0 && (+ <div className="col-span-full py-16 text-center text-sm text-muted-foreground">+ {t(($) => $.page.no_matches.title)}+ </div>+ )}+ {virtualItems.map((vi) => {+ const row = rows[vi.index];+ if (!row) return null;+ return (+ <ListGridRow+ key={row.skill.id}+ className={+ selectedIds.has(row.skill.id) ? "bg-accent/30" : undefined}- />- )}+ render={<AppLink href={paths.skillDetail(row.skill.id)} />}+ >+ <CheckboxCell+ checked={selectedIds.has(row.skill.id)}+ onToggle={() => toggleSelected(row.skill.id)}+ />+ <NameCell row={row} />+ {isColVisible("usedBy") ? (+ <UsedByCell agents={row.agents} />+ ) : (+ <ListGridCell className="px-0" />+ )}+ {isColVisible("source") ? (+ <SourceCell skill={row.skill} runtime={row.runtime} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("creator") ? (+ <CreatorCell creator={row.creator} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("updated") ? (+ <ListGridCell className="hidden whitespace-nowrap text-xs tabular-nums text-muted-foreground @2xl:flex">+ {timeAgo(row.skill.updated_at)}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridCell className="hidden whitespace-nowrap text-xs tabular-nums text-muted-foreground @2xl:flex">+ {timeAgo(row.skill.created_at)}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridCell className="justify-end px-0">+ <SkillRowActions row={row} ctx={actionsCtx} />+ </ListGridCell>+ </ListGridRow>+ );+ })}+ </ListGridBody>+ </ListGrid></div>- )}- </div>+ </>+ )}++ <SkillBatchToolbar+ rows={selectedRows}+ ctx={actionsCtx}+ onClear={() => setSelectedIds(new Set())}+ />{createOpen && (<CreateSkillDialogdiff --git a/packages/views/squads/components/squads-page.tsx b/packages/views/squads/components/squads-page.tsxindex 76ce3a1e4f..aa550dd92e 100644--- a/packages/views/squads/components/squads-page.tsx+++ b/packages/views/squads/components/squads-page.tsx@@ -1,25 +1,753 @@"use client";import { useMemo, useState } from "react";-import { useQuery } from "@tanstack/react-query";+import {+ ArrowDown,+ ArrowUp,+ ChevronDown,+ Filter,+ Loader2,+ MoreHorizontal,+ Plus,+ Trash2,+ Users,+ X,+} from "lucide-react";+import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";+import { toast } from "sonner";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";-import { agentListOptions, memberListOptions, squadListOptions } from "@multica/core/workspace/queries";+import {+ agentListOptions,+ memberListOptions,+ squadListOptions,+ workspaceKeys,+} from "@multica/core/workspace/queries";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { useAuthStore } from "@multica/core/auth";-import { useSquadsViewStore } from "@multica/core/squads/stores";-import { AppLink } from "../../navigation";-import { PageHeader } from "../../layout/page-header";-import { Users, Plus, Search, Bot, User } from "lucide-react";+import { api } from "@multica/core/api";+import { useModalStore } from "@multica/core/modals";+import {+ useSquadsViewStore,+ SQUAD_SCOPES,+ SQUAD_DEFAULT_HIDDEN_COLUMNS,+ type SquadColumnKey,+ type SquadListFilters,+ type SquadsScope,+ type SquadSortField,+} from "@multica/core/squads/stores";+import type { Agent, MemberWithUser, Squad } from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";-import { Input } from "@multica/ui/components/ui/input";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ ListGrid,+ ListGridCell,+ ListGridHeader,+ ListGridHeaderCell,+ ListGridRow,+ LIST_GRID_BOTTOM_CLEARANCE,+ type ListGridSortDirection,+} from "@multica/ui/components/ui/list-grid";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { Switch } from "@multica/ui/components/ui/switch";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";-import { useModalStore } from "@multica/core/modals";-import type { Agent, Squad } from "@multica/core/types";+import { ActorAvatar } from "../../common/actor-avatar";+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";+import { AppLink } from "../../navigation";+import { PageHeader } from "../../layout/page-header";import { useT } from "../../i18n";-import { matchesPinyin } from "../../editor/extensions/pinyin-match";-type Scope = "mine" | "all";+// Column template — the simplest member of the ListGrid family (squads are+// the fewest entity, 1-5 rows): subgrid template + var tracks + two-zone+// responsiveness + single scroll container, but NO virtualization, checkbox,+// or batch. Identity two-line rows (avatar + name + description, 64px) like+// the agents list. Name + leader are the core set (<@2xl); members / creator+// / created are @2xl. The kebab track collapses when the viewer can't manage+// any squad (workspace admin only).+const GRID_COLS =+ "grid-cols-[0.75rem_minmax(120px,1fr)_var(--sqc-leader)_var(--sqc-kebab)_0.75rem] " ++ "@2xl:grid-cols-[0.75rem_minmax(200px,1fr)_var(--sqc-leader)_var(--sqc-members)_var(--sqc-creator)_var(--sqc-created)_var(--sqc-kebab)_0.75rem]";++const LEADER_WIDTH = 160;+const COLUMN_WIDTHS: Record<SquadColumnKey, number> = {+ members: 120,+ creator: 144,+ created: 104,+};++// Fixed tracks (edges 12+12, name min 200, leader 160) plus the 7 gap-x-3+// gaps between the wide template's 8 tracks (zero-width tracks still carry+// gaps).+const FIXED_TRACKS_WIDTH = 224 + LEADER_WIDTH + 7 * 12;++function columnTrackVars(+ isVisible: (key: SquadColumnKey) => boolean,+ showActions: boolean,+): React.CSSProperties {+ const width = (key: SquadColumnKey) =>+ isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";+ const minWidth =+ FIXED_TRACKS_WIDTH ++ (Object.keys(COLUMN_WIDTHS) as SquadColumnKey[]).reduce(+ (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),+ 0,+ ) ++ (showActions ? 28 : 0);+ return {+ "--sqc-leader": `${LEADER_WIDTH}px`,+ "--sqc-members": width("members"),+ "--sqc-creator": width("creator"),+ "--sqc-created": width("created"),+ "--sqc-kebab": showActions ? "1.75rem" : "0px",+ "--sqc-minw": `${minWidth}px`,+ } as React.CSSProperties;+}++// ---------------------------------------------------------------------------+// Cells+// ---------------------------------------------------------------------------++function SquadAvatar({ squad }: { squad: Squad }) {+ const initials = squad.name+ .split(" ")+ .map((w) => w[0])+ .join("")+ .toUpperCase()+ .slice(0, 2);+ if (squad.avatar_url) {+ return (+ <ActorAvatarBase+ name={squad.name}+ initials={initials}+ avatarUrl={resolvePublicFileUrl(squad.avatar_url)}+ size={32}+ className="shrink-0 rounded-md"+ />+ );+ }+ return (+ <div+ className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground"+ title={squad.name}+ >+ <Users className="h-4 w-4" />+ </div>+ );+}++// Two-line identity cell — same form as the agents list.+function NameCell({ squad }: { squad: Squad }) {+ return (+ <ListGridCell className="gap-3">+ <SquadAvatar squad={squad} />+ <div className="min-w-0 flex-1">+ <span className="block min-w-0 truncate text-sm font-medium">+ {squad.name}+ </span>+ {squad.description ? (+ <span className="block min-w-0 truncate text-xs text-muted-foreground">+ {squad.description}+ </span>+ ) : null}+ </div>+ </ListGridCell>+ );+}++function LeaderCell({+ leaderId,+ leader,+}: {+ leaderId: string;+ leader: Agent | undefined;+}) {+ return (+ <ListGridCell className="gap-1.5">+ <ActorAvatar actorType="agent" actorId={leaderId} size={18} />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {leader?.name ?? leaderId.slice(0, 8)}+ </span>+ </ListGridCell>+ );+}++// Polymorphic member avatar stack (agent + human members), driven by the+// list payload's member_preview / member_count. NOT AgentAvatarStack, which+// is agent-only.+function MembersCell({ squad }: { squad: Squad }) {+ const preview = squad.member_preview ?? [];+ const count = squad.member_count ?? preview.length;+ if (count === 0) {+ return (+ <ListGridCell className="hidden @2xl:flex">+ <span className="text-xs text-muted-foreground/40">—</span>+ </ListGridCell>+ );+ }+ const visible = preview.slice(0, 3);+ const overflow = count - visible.length;+ return (+ <ListGridCell className="hidden @2xl:flex">+ <div className="flex items-center -space-x-1.5">+ {visible.map((m) => (+ <span+ key={`${m.member_type}-${m.member_id}`}+ className="inline-flex rounded-full ring-2 ring-background"+ >+ <ActorAvatar+ actorType={m.member_type}+ actorId={m.member_id}+ size={22}+ enableHoverCard={m.member_type === "agent"}+ />+ </span>+ ))}+ {overflow > 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">+ +{overflow}+ </span>+ )}+ </div>+ </ListGridCell>+ );+}++// ---------------------------------------------------------------------------+// Archive (= delete) dialog — reuses the existing archive_dialog copy.+// Workspace owner/admin only (backend gate). No restore endpoint exists, so+// once archived a squad is gone from the UI.+// ---------------------------------------------------------------------------++function ArchiveSquadDialog({+ squad,+ open,+ onOpenChange,+}: {+ squad: Squad;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useT("squads");+ const wsId = useCurrentWorkspace()?.id ?? "";+ const qc = useQueryClient();+ const archive = useMutation({+ mutationFn: () => api.deleteSquad(squad.id),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });+ onOpenChange(false);+ toast.success(t(($) => $.archive_dialog.success));+ },+ onError: (err) =>+ toast.error(err instanceof Error ? err.message : String(err)),+ });+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t(($) => $.archive_dialog.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.archive_dialog.description, { name: squad.name })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={archive.isPending}+ onClick={() => onOpenChange(false)}+ >+ {t(($) => $.archive_dialog.cancel)}+ </Button>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ disabled={archive.isPending}+ onClick={() => archive.mutate()}+ >+ {archive.isPending ? (+ <>+ <Loader2 className="mr-1 size-3.5 animate-spin" />+ {t(($) => $.archive_dialog.archiving)}+ </>+ ) : (+ t(($) => $.archive_dialog.confirm)+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++function SquadRowActions({ squad }: { squad: Squad }) {+ const { t } = useT("squads");+ const [archiveOpen, setArchiveOpen] = useState(false);+ return (+ <span+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ className="flex items-center"+ >+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ aria-label={t(($) => $.page.row_menu)}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"+ >+ <MoreHorizontal className="size-4" />+ </button>+ }+ />+ <DropdownMenuContent align="end" className="w-40">+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setArchiveOpen(true)}+ >+ <Trash2 className="size-3.5" />+ {t(($) => $.page.archive_action)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <ArchiveSquadDialog+ squad={squad}+ open={archiveOpen}+ onOpenChange={setArchiveOpen}+ />+ </span>+ );+}++// ---------------------------------------------------------------------------+// Header + toolbar+// ---------------------------------------------------------------------------++function SquadListHeader({+ sortField,+ sortDirection,+ onSort,+ isColVisible,+}: {+ sortField: SquadSortField;+ sortDirection: ListGridSortDirection;+ onSort: (field: SquadSortField) => void;+ isColVisible: (key: SquadColumnKey) => boolean;+}) {+ const { t } = useT("squads");+ const sorted = (field: SquadSortField) =>+ sortField === field ? sortDirection : false;+ return (+ <ListGridHeader>+ <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>+ {t(($) => $.page.table.name)}+ </ListGridHeaderCell>+ <ListGridHeaderCell>{t(($) => $.page.table.leader)}</ListGridHeaderCell>+ {isColVisible("members") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("members")}+ onSort={() => onSort("members")}+ >+ {t(($) => $.page.table.members)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("creator") ? (+ <ListGridHeaderCell className="hidden @2xl:flex">+ {t(($) => $.page.table.creator)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridHeaderCell+ className="hidden @2xl:flex"+ sorted={sorted("created")}+ onSort={() => onSort("created")}+ >+ {t(($) => $.page.table.created)}+ </ListGridHeaderCell>+ ) : (+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ )}+ {/* kebab track placeholder (track width collapses when no actions) */}+ <span aria-hidden="true" />+ </ListGridHeader>+ );+}++const COLUMN_KEYS: SquadColumnKey[] = ["members", "creator", "created"];+const SORT_FIELDS: SquadSortField[] = ["name", "members", "created"];++interface ActorOption {+ id: string;+ name: string;+ count: number;+}++function SquadListToolbar({+ scope,+ onScopeChange,+ scopeCounts,+ filters,+ onToggleFilter,+ onClearFilters,+ leaderOptions,+ creatorOptions,+ visibleCount,+ totalCount,+ sortField,+ sortDirection,+ onSortFieldChange,+ onSortDirectionChange,+ hiddenColumns,+ onToggleColumn,+}: {+ scope: SquadsScope;+ onScopeChange: (scope: SquadsScope) => void;+ scopeCounts: Record<SquadsScope, number>;+ filters: SquadListFilters;+ onToggleFilter: (key: keyof SquadListFilters, value: string) => void;+ onClearFilters: () => void;+ leaderOptions: ActorOption[];+ creatorOptions: ActorOption[];+ visibleCount: number;+ totalCount: number;+ sortField: SquadSortField;+ sortDirection: ListGridSortDirection;+ onSortFieldChange: (field: SquadSortField) => void;+ onSortDirectionChange: (direction: ListGridSortDirection) => void;+ hiddenColumns: SquadColumnKey[];+ onToggleColumn: (key: SquadColumnKey) => void;+}) {+ const { t } = useT("squads");+ const activeFilterCount =+ (filters.leaders.length > 0 ? 1 : 0) ++ (filters.creators.length > 0 ? 1 : 0);+ const hasActiveFilters = activeFilterCount > 0;+ const countBadge = (n: number) => (+ <span className="ml-auto pl-3 text-xs text-muted-foreground">{n}</span>+ );+ const SCOPE_LABELS: Record<SquadsScope, string> = {+ mine: t(($) => $.scope.mine),+ all: t(($) => $.scope.all),+ };+ const SORT_LABELS: Record<SquadSortField, string> = {+ name: t(($) => $.page.table.name),+ members: t(($) => $.page.table.members),+ created: t(($) => $.page.table.created),+ };+ const COLUMN_LABELS: Record<SquadColumnKey, string> = {+ members: t(($) => $.page.table.members),+ creator: t(($) => $.page.table.creator),+ created: t(($) => $.page.table.created),+ };+ const sortLabel = SORT_LABELS[sortField];++ return (+ <div className="flex h-12 shrink-0 items-center justify-between gap-2 px-5">+ <div className="flex min-w-0 items-center gap-2">+ <div className="hidden shrink-0 items-center gap-1 md:flex">+ {SQUAD_SCOPES.map((s) => (+ <Button+ key={s}+ variant="outline"+ size="sm"+ className={+ scope === s+ ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"+ : "gap-1.5 text-muted-foreground"+ }+ onClick={() => onScopeChange(s)}+ >+ {SCOPE_LABELS[s]}+ <span className="tabular-nums text-xs text-muted-foreground/70">+ {scopeCounts[s]}+ </span>+ </Button>+ ))}+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="shrink-0 gap-1 text-muted-foreground md:hidden"+ >+ <span className="truncate">{SCOPE_LABELS[scope]}</span>+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={scope}+ onValueChange={(value) => onScopeChange(value as SquadsScope)}+ >+ {SQUAD_SCOPES.map((s) => (+ <DropdownMenuRadioItem key={s} value={s}>+ {SCOPE_LABELS[s]}+ <span className="ml-2 tabular-nums text-xs text-muted-foreground/70">+ {scopeCounts[s]}+ </span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>++ {hasActiveFilters && (+ <span+ title={t(($) => $.toolbar.result_count_title)}+ className="hidden shrink-0 text-xs tabular-nums text-muted-foreground md:inline"+ >+ {visibleCount} / {totalCount}+ </span>+ )}+ </div>++ <div className="flex shrink-0 items-center gap-1">+ {/* Filter */}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant={hasActiveFilters ? "default" : "outline"}+ size="sm"+ className={+ hasActiveFilters+ ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"+ : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ }+ >+ <Filter className="size-3.5" />+ {hasActiveFilters ? (+ <>+ <span className="hidden md:inline">+ {t(($) => $.toolbar.filter_active_count, { count: activeFilterCount })}+ </span>+ <span className="tabular-nums md:hidden">{activeFilterCount}</span>+ </>+ ) : (+ <span className="hidden md:inline">{t(($) => $.toolbar.filter_label)}</span>+ )}+ {hasActiveFilters && (+ <span+ role="button"+ tabIndex={-1}+ aria-label={t(($) => $.toolbar.clear_filters)}+ className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onClearFilters();+ }}+ onPointerDown={(e) => e.stopPropagation()}+ >+ <X className="size-3" />+ </span>+ )}+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-auto">+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.page.table.leader)}</span>+ {filters.leaders.length > 0 && (+ <span className="text-xs font-medium text-primary">{filters.leaders.length}</span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {leaderOptions.map((o) => (+ <DropdownMenuCheckboxItem+ key={o.id}+ checked={filters.leaders.includes(o.id)}+ onCheckedChange={() => onToggleFilter("leaders", o.id)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.leaders.includes(o.id)} />+ <ActorAvatar actorType="agent" actorId={o.id} size={16} />+ <span className="min-w-0 truncate">{o.name}</span>+ {countBadge(o.count)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">{t(($) => $.page.table.creator)}</span>+ {filters.creators.length > 0 && (+ <span className="text-xs font-medium text-primary">{filters.creators.length}</span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">+ {creatorOptions.map((o) => (+ <DropdownMenuCheckboxItem+ key={o.id}+ checked={filters.creators.includes(o.id)}+ onCheckedChange={() => onToggleFilter("creators", o.id)}+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={filters.creators.includes(o.id)} />+ <ActorAvatar actorType="member" actorId={o.id} size={16} />+ <span className="min-w-0 truncate">{o.name}</span>+ {countBadge(o.count)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>++ {/* Display settings */}+ <Popover>+ <Tooltip>+ <PopoverTrigger+ render={+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ <span className="hidden md:inline">{sortLabel}</span>+ </Button>+ }+ />+ }+ />+ <TooltipContent side="bottom">+ {t(($) => $.toolbar.display)}+ </TooltipContent>+ </Tooltip>+ <PopoverContent align="end" className="w-64 p-0">+ <div className="border-b px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.sort_by)}+ </span>+ <div className="mt-2 flex items-center gap-1.5">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="flex-1 justify-between text-xs"+ >+ {sortLabel}+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="start" className="w-auto">+ <DropdownMenuRadioGroup+ value={sortField}+ onValueChange={(v) =>+ onSortFieldChange(v as SquadSortField)+ }+ >+ {SORT_FIELDS.map((field) => (+ <DropdownMenuRadioItem key={field} value={field}>+ {SORT_LABELS[field]}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ <Button+ variant="outline"+ size="icon-sm"+ onClick={() =>+ onSortDirectionChange(+ sortDirection === "asc" ? "desc" : "asc",+ )+ }+ title={+ sortDirection === "asc"+ ? t(($) => $.toolbar.direction_asc)+ : t(($) => $.toolbar.direction_desc)+ }+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ </Button>+ </div>+ </div>+ <div className="px-3 py-2.5">+ <span className="text-xs font-medium text-muted-foreground">+ {t(($) => $.toolbar.section_columns)}+ </span>+ <div className="mt-2 space-y-2">+ {COLUMN_KEYS.map((key) => (+ <label+ key={key}+ className="flex cursor-pointer items-center justify-between"+ >+ <span className="text-sm">{COLUMN_LABELS[key]}</span>+ <Switch+ size="sm"+ checked={!hiddenColumns.includes(key)}+ onCheckedChange={() => onToggleColumn(key)}+ />+ </label>+ ))}+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Page+// ---------------------------------------------------------------------------export function SquadsPage() {const { t } = useT("squads");@@ -27,6 +755,7 @@ export function SquadsPage() {const wsId = workspace?.id ?? "";const p = useWorkspacePaths();const currentUser = useAuthStore((s) => s.user);+const { data: squads = [], isLoading } = useQuery({...squadListOptions(wsId),enabled: !!wsId,@@ -40,32 +769,112 @@ export function SquadsPage() {return m;}, [agents]);- const membersByUserId = useMemo(() => {- const m = new Map<string, { name: string; avatar_url: string | null }>();- for (const mem of members) m.set(mem.user_id, { name: mem.name, avatar_url: mem.avatar_url });+ const membersById = useMemo(() => {+ const m = new Map<string, MemberWithUser>();+ for (const mem of members) m.set(mem.user_id, mem);return m;}, [members]);+ const isWorkspaceAdmin = useMemo(() => {+ if (!currentUser) return false;+ const me = members.find((mem: MemberWithUser) => mem.user_id === currentUser.id);+ return me?.role === "owner" || me?.role === "admin";+ }, [members, currentUser]);+const scope = useSquadsViewStore((s) => s.scope);const setScope = useSquadsViewStore((s) => s.setScope);- const [search, setSearch] = useState("");+ const sortField = useSquadsViewStore((s) => s.sortField);+ const sortDirection = useSquadsViewStore((s) => s.sortDirection);+ const hiddenColumns = useSquadsViewStore((s) => s.hiddenColumns);+ const handleSort = useSquadsViewStore((s) => s.toggleSort);+ const handleSortFieldSelect = useSquadsViewStore((s) => s.setSortField);+ const setSortDirection = useSquadsViewStore((s) => s.setSortDirection);+ const toggleColumn = useSquadsViewStore((s) => s.toggleColumn);+ const filters = useSquadsViewStore((s) => s.filters);+ const toggleFilter = useSquadsViewStore((s) => s.toggleFilter);+ const clearFilters = useSquadsViewStore((s) => s.clearFilters);- const scopeCounts = useMemo(() => {+ const isColVisible = (key: SquadColumnKey) => !hiddenColumns.includes(key);++ const scopeCounts = useMemo<Record<SquadsScope, number>>(() => {let mine = 0;if (currentUser) {- for (const s of squads) mine += s.creator_id === currentUser.id ? 1 : 0;+ for (const s of squads) if (s.creator_id === currentUser.id) mine++;}- return { all: squads.length, mine };+ return { mine, all: squads.length };}, [squads, currentUser]);- const filtered = useMemo(() => {- const q = search.trim().toLowerCase();+ // Rows within the current scope, unfiltered — filter option lists + the+ // "n / total" denominator derive from this.+ const scopeRows = useMemo<Squad[]>(() => {return squads.filter((s) => {- if (scope === "mine" && currentUser && s.creator_id !== currentUser.id) return false;- if (q && !s.name.toLowerCase().includes(q) && !matchesPinyin(s.name, q) && !s.description.toLowerCase().includes(q)) return false;+ if (scope === "mine") {+ return !!currentUser && s.creator_id === currentUser.id;+ }return true;});- }, [squads, scope, currentUser, search]);+ }, [squads, scope, currentUser]);++ const leaderOptions = useMemo(() => {+ const m = new Map<string, { id: string; name: string; count: number }>();+ for (const s of scopeRows) {+ const e = m.get(s.leader_id);+ if (e) e.count += 1;+ else+ m.set(s.leader_id, {+ id: s.leader_id,+ name: agentsById.get(s.leader_id)?.name ?? s.leader_id.slice(0, 8),+ count: 1,+ });+ }+ return [...m.values()];+ }, [scopeRows, agentsById]);++ const creatorOptions = useMemo(() => {+ const m = new Map<string, { id: string; name: string; count: number }>();+ for (const s of scopeRows) {+ const e = m.get(s.creator_id);+ if (e) e.count += 1;+ else+ m.set(s.creator_id, {+ id: s.creator_id,+ name: membersById.get(s.creator_id)?.name ?? s.creator_id.slice(0, 8),+ count: 1,+ });+ }+ return [...m.values()];+ }, [scopeRows, membersById]);++ const rows = useMemo<Squad[]>(() => {+ const inScope = scopeRows.filter((s) => {+ if (filters.leaders.length > 0 && !filters.leaders.includes(s.leader_id)) {+ return false;+ }+ if (+ filters.creators.length > 0 &&+ !filters.creators.includes(s.creator_id)+ ) {+ return false;+ }+ return true;+ });+ const dir = sortDirection === "asc" ? 1 : -1;+ const sorted = [...inScope];+ sorted.sort((a, b) => {+ if (sortField === "members") {+ const av = a.member_count ?? a.member_preview?.length ?? 0;+ const bv = b.member_count ?? b.member_preview?.length ?? 0;+ return (av - bv) * dir || a.name.localeCompare(b.name);+ }+ if (sortField === "created") {+ return (+ (Date.parse(a.created_at) - Date.parse(b.created_at)) * dir+ );+ }+ return a.name.localeCompare(b.name) * dir;+ });+ return sorted;+ }, [scopeRows, filters, sortField, sortDirection]);return (<div className="flex flex-1 min-h-0 flex-col">@@ -73,167 +882,180 @@ export function SquadsPage() {<div className="flex items-center gap-2"><Users className="h-4 w-4 text-muted-foreground" /><h1 className="text-sm font-medium">{t(($) => $.page.title)}</h1>- {!isLoading && squads.length > 0 && (- <span className="text-xs text-muted-foreground tabular-nums">{squads.length}</span>+ {squads.length > 0 && (+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">+ {squads.length}+ </span>)}</div>- <Button size="sm" variant="outline" onClick={() => useModalStore.getState().open("create-squad")}>- <Plus className="size-3.5 mr-1.5" />- {t(($) => $.page.new_button)}+ {/* Quiet chrome button (outline, icon-only below md) — primary is+ reserved for the empty state. */}+ <Button+ size="sm"+ variant="outline"+ className="h-8 w-8 gap-1 px-0 md:w-auto md:px-2.5"+ aria-label={t(($) => $.page.new_button)}+ onClick={() => useModalStore.getState().open("create-squad")}+ >+ <Plus className="h-3.5 w-3.5" />+ <span className="hidden md:inline">{t(($) => $.page.new_button)}</span></Button></PageHeader>- <div className="flex flex-1 min-h-0 flex-col overflow-hidden">- {isLoading ? (- <SquadsListSkeleton />- ) : squads.length === 0 ? (- <div className="flex flex-col items-center justify-center gap-3 py-16 text-center">- <Users className="size-10 text-muted-foreground/50" />- <p className="text-sm text-muted-foreground">{t(($) => $.page.empty_no_squads)}</p>- </div>- ) : (- <>- <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">- <div className="relative flex-1 min-w-0 max-w-sm">- <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- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder="Search squads..."- className="h-8 w-full pl-8 text-sm"- />- </div>- <ScopeSegment scope={scope} setScope={setScope} counts={scopeCounts} />- <span className="hidden sm:inline font-mono text-xs tabular-nums text-muted-foreground/70">- {filtered.length} / {squads.length}- </span>- </div>-- {filtered.length === 0 ? (- <div className="flex flex-col items-center justify-center gap-2 py-16 text-center">- <p className="text-sm text-muted-foreground">{t(($) => $.page.empty_no_match)}</p>- </div>- ) : (- <div className="flex-1 overflow-y-auto p-4">- <div className="grid gap-3">- {filtered.map((squad) => (- <SquadCard key={squad.id} squad={squad} leader={agentsById.get(squad.leader_id)} creator={membersByUserId.get(squad.creator_id)} href={p.squadDetail(squad.id)} />- ))}+ {isLoading ? (+ <LoadingSkeleton />+ ) : squads.length === 0 ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-16 text-center">+ <Users className="size-10 text-muted-foreground/50" />+ <p className="text-sm text-muted-foreground">+ {t(($) => $.page.empty_no_squads)}+ </p>+ <Button+ size="sm"+ onClick={() => useModalStore.getState().open("create-squad")}+ >+ <Plus className="size-3.5" />+ {t(($) => $.page.new_button)}+ </Button>+ </div>+ ) : (+ <>+ <SquadListToolbar+ scope={scope}+ onScopeChange={setScope}+ scopeCounts={scopeCounts}+ filters={filters}+ onToggleFilter={toggleFilter}+ onClearFilters={clearFilters}+ leaderOptions={leaderOptions}+ creatorOptions={creatorOptions}+ visibleCount={rows.length}+ totalCount={scopeRows.length}+ sortField={sortField}+ sortDirection={sortDirection}+ onSortFieldChange={handleSortFieldSelect}+ onSortDirectionChange={setSortDirection}+ hiddenColumns={hiddenColumns}+ onToggleColumn={toggleColumn}+ />+ <div className="min-h-0 flex-1 overflow-auto @container">+ <ListGrid+ className={`${GRID_COLS} @2xl:min-w-[var(--sqc-minw)]`}+ style={{+ ...columnTrackVars(isColVisible, isWorkspaceAdmin),+ paddingBottom: LIST_GRID_BOTTOM_CLEARANCE,+ }}+ >+ <SquadListHeader+ sortField={sortField}+ sortDirection={sortDirection}+ onSort={handleSort}+ isColVisible={isColVisible}+ />+ {rows.length === 0 ? (+ <div className="col-span-full py-16 text-center text-sm text-muted-foreground">+ {t(($) => $.page.no_matches)}</div>- </div>- )}- </>- )}- </div>+ ) : (+ rows.map((squad) => (+ <ListGridRow+ key={squad.id}+ render={<AppLink href={p.squadDetail(squad.id)} />}+ >+ <NameCell squad={squad} />+ <LeaderCell+ leaderId={squad.leader_id}+ leader={agentsById.get(squad.leader_id)}+ />+ {isColVisible("members") ? (+ <MembersCell squad={squad} />+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("creator") ? (+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ <ActorAvatar+ actorType="member"+ actorId={squad.creator_id}+ size={18}+ />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {membersById.get(squad.creator_id)?.name ??+ squad.creator_id.slice(0, 8)}+ </span>+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ {isColVisible("created") ? (+ <ListGridCell className="hidden whitespace-nowrap text-xs tabular-nums text-muted-foreground @2xl:flex">+ {new Date(squad.created_at).toLocaleDateString()}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridCell className="justify-end px-0">+ {isWorkspaceAdmin ? (+ <SquadRowActions squad={squad} />+ ) : null}+ </ListGridCell>+ </ListGridRow>+ ))+ )}+ </ListGrid>+ </div>+ </>+ )}</div>);}-function SquadCard({ squad, leader, creator, href }: { squad: Squad; leader?: Agent; creator?: { name: string; avatar_url: string | null }; href: string }) {+function LoadingSkeleton() {return (- <AppLink- href={href}- className="flex items-center gap-3 sm:gap-4 rounded-lg border p-3 sm:p-4 hover:bg-accent/50 transition-colors w-full overflow-hidden"- >- <SquadAvatar squad={squad} />- <div className="flex-1 min-w-0 overflow-hidden">- <p className="font-medium truncate">{squad.name}</p>- {squad.description && (- <p className="text-sm text-muted-foreground truncate mt-0.5">{squad.description}</p>+ <div className="min-h-0 flex-1 overflow-auto @container">+ <ListGrid+ className={GRID_COLS}+ style={columnTrackVars(+ (key) => !SQUAD_DEFAULT_HIDDEN_COLUMNS.includes(key),+ true,)}- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-2">- {leader && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground min-w-0">- <Bot className="size-3 shrink-0" />- <span className="truncate">{leader.name}</span>- </div>- )}- {creator && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground min-w-0">- <User className="size-3 shrink-0" />- <span className="truncate">{creator.name}</span>- </div>- )}- </div>- </div>- </AppLink>- );-}--function ScopeSegment({ scope, setScope, counts }: { scope: Scope; setScope: (v: Scope) => void; counts: { all: number; mine: number } }) {- return (- <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">- <ScopeButton active={scope === "mine"} label="Mine" count={counts.mine} onClick={() => setScope("mine")} />- <ScopeButton active={scope === "all"} label="All" count={counts.all} onClick={() => setScope("all")} />- </div>- );-}--function ScopeButton({ active, label, count, onClick }: { active: boolean; label: string; count: number; onClick: () => void }) {- return (- <button- type="button"- onClick={onClick}- className={`inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-xs font-medium transition-colors ${- active ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"- }`}- >- <span>{label}</span>- <span className={`font-mono tabular-nums ${active ? "text-muted-foreground/80" : "text-muted-foreground/50"}`}>- {count}- </span>- </button>- );-}--function SquadsListSkeleton() {- return (- <>- <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">- <Skeleton className="h-8 w-full max-w-sm rounded-md" />- <Skeleton className="h-7 w-32 rounded-md" />- </div>- <div className="flex-1 overflow-y-auto p-4">- <div className="grid gap-3">- {Array.from({ length: 4 }).map((_, i) => (- <div key={i} className="flex items-center gap-3 sm:gap-4 rounded-lg border p-3 sm:p-4">- <Skeleton className="h-9 w-9 shrink-0 rounded-md" />- <div className="flex-1 space-y-2">- <Skeleton className="h-4 w-1/3 rounded" />- <Skeleton className="h-3 w-2/3 rounded" />+ >+ <ListGridHeader>+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell>+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden @2xl:flex">+ <Skeleton className="h-3 w-12" />+ </ListGridHeaderCell>+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <ListGridHeaderCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridHeader>+ {Array.from({ length: 4 }).map((_, i) => (+ <ListGridRow key={i} className="h-16 hover:bg-transparent">+ <ListGridCell className="gap-3">+ <Skeleton className="size-8 rounded-md" />+ <div className="min-w-0 flex-1 space-y-1.5">+ <Skeleton className="h-3.5 w-32 max-w-full" />+ <Skeleton className="h-3 w-48 max-w-full" /></div>- </div>- ))}- </div>- </div>- </>- );-}--function SquadAvatar({ squad }: { squad: Squad }) {- const initials = squad.name- .split(" ")- .map((w) => w[0])- .join("")- .toUpperCase()- .slice(0, 2);- if (squad.avatar_url) {- return (- <ActorAvatarBase- name={squad.name}- initials={initials}- avatarUrl={resolvePublicFileUrl(squad.avatar_url)}- size={36}- className="rounded-md"- />- );- }- return (- <div- className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground"- title={squad.name}- >- <Users className="h-4 w-4" />+ </ListGridCell>+ <ListGridCell className="gap-1.5">+ <Skeleton className="size-5 rounded-full" />+ <Skeleton className="h-3 w-16" />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ <Skeleton className="h-5 w-16" />+ </ListGridCell>+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <ListGridCell className="hidden px-0 @2xl:flex" />+ <span aria-hidden="true" />+ </ListGridRow>+ ))}+ </ListGrid></div>);}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 94f64fe8ac..4e72ed9b2b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -18,6 +18,9 @@ catalogs:'@tanstack/react-table':specifier: ^8.21.3version: 8.21.3+ '@tanstack/react-virtual':+ specifier: ^3.13.0+ version: 3.14.2'@testing-library/jest-dom':specifier: ^6.9.1version: 6.9.1@@ -416,7 +419,7 @@ importers:version: 55.0.15([email protected])([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])expo-router:specifier: ~55.0.14- version: 55.0.14(28857138dad78e037ca803b5df54c4f8)+ version: 55.0.14(fb4q2ydjsib3h2ixce2lptexem)expo-secure-store:specifier: ~55.0.13version: 55.0.14([email protected])@@ -969,6 +972,9 @@ importers:'@tanstack/react-table':specifier: 'catalog:'+ '@tanstack/react-virtual':+ specifier: 'catalog:''@tiptap/core':specifier: ^3.22.1version: 3.22.1(@tiptap/[email protected])@@ -3960,10 +3966,19 @@ packages:react: '>=16.8'react-dom: '>=16.8'+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-IpWnmCLvuymRfeeLNVXIzNEYBFLpd3drVIS91sqV78VTZFyldlChkOocZRCPp1B+Wnk09bcLNme8WaMU/9/9bQ==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+'@tanstack/[email protected]':resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}engines: {node: '>=12'}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-gOxY/hFkPh/XQYhnThBHzkbkX3Ed+z/iushyz+R+JAr213aXxUDgQoTgTdrDpBSRsjFM73P/KfUyWmaF9WHMkQ==}+'@testing-library/[email protected]':resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}engines: {node: '>=18'}@@ -11850,7 +11865,7 @@ snapshots:ws: 8.20.1zod: 3.25.76optionalDependencies:- expo-router: 55.0.14(28857138dad78e037ca803b5df54c4f8)+ expo-router: 55.0.14(fb4q2ydjsib3h2ixce2lptexem)transitivePeerDependencies:- '@expo/dom-webview'@@ -12105,7 +12120,7 @@ snapshots:react: 19.2.0optionalDependencies:'@expo/metro-runtime': 55.0.11(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])- expo-router: 55.0.14(28857138dad78e037ca803b5df54c4f8)+ expo-router: 55.0.14(fb4q2ydjsib3h2ixce2lptexem)react-dom: 19.2.0([email protected])transitivePeerDependencies:- supports-color@@ -14082,8 +14097,16 @@ snapshots:react: 19.2.3react-dom: 19.2.3([email protected])+ dependencies:+ '@tanstack/virtual-core': 3.17.0+ react: 19.2.3+ react-dom: 19.2.3([email protected])+'@tanstack/[email protected]': {}+ '@tanstack/[email protected]': {}+'@testing-library/[email protected]':dependencies:'@babel/code-frame': 7.29.0@@ -17074,7 +17097,7 @@ snapshots:optionalDependencies:react-native-worklets: 0.7.4(@babel/[email protected])([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])- [email protected](28857138dad78e037ca803b5df54c4f8):+ [email protected](fb4q2ydjsib3h2ixce2lptexem):dependencies:'@expo/log-box': 55.0.12(@expo/[email protected])([email protected])([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])'@expo/metro-runtime': 55.0.11(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@types/[email protected])([email protected]))([email protected])diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex c2aaeef43c..aee3d9e668 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -53,6 +53,7 @@ catalog:# Virtualized timeline (issue detail comments)react-virtuoso: "^4.14.0"+ "@tanstack/react-virtual": "^3.13.0"# Product analyticsposthog-js: "^1.176.1"diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 59d9d6956a..0cde75d46e 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -45,6 +45,13 @@ type AutopilotResponse struct {LastRunAt *string `json:"last_run_at"`CreatedAt string `json:"created_at"`UpdatedAt string `json:"updated_at"`++ // List-endpoint-only derived fields (absent on the detail/create/update+ // responses and on older servers — clients must treat them as optional).+ // Enabled triggers only; last_run_status is the most recent run's status.+ TriggerKinds []string `json:"trigger_kinds,omitempty"`+ NextRunAt *string `json:"next_run_at,omitempty"`+ LastRunStatus *string `json:"last_run_status,omitempty"`}type AutopilotTriggerResponse struct {@@ -326,8 +333,17 @@ func (h *Handler) ListAutopilots(w http.ResponseWriter, r *http.Request) {}resp := make([]AutopilotResponse, len(autopilots))- for i, a := range autopilots {- resp[i] = autopilotToResponse(a)+ for i, row := range autopilots {+ r := autopilotToResponse(row.Autopilot)+ r.TriggerKinds = row.TriggerKinds+ if row.NextRunAt.Valid {+ r.NextRunAt = timestampToPtr(row.NextRunAt)+ }+ if row.LastRunStatus != "" {+ s := row.LastRunStatus+ r.LastRunStatus = &s+ }+ resp[i] = r}writeJSON(w, http.StatusOK, map[string]any{"autopilots": resp, "total": len(resp)})}diff --git a/server/internal/handler/autopilot_list_test.go b/server/internal/handler/autopilot_list_test.gonew file mode 100644index 0000000000..b1704c181b--- /dev/null+++ b/server/internal/handler/autopilot_list_test.go@@ -0,0 +1,116 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http/httptest"+ "testing"+)++// insertListTestAutopilot creates a bare autopilot row and registers cleanup.+// Triggers/runs cascade on delete.+func insertListTestAutopilot(t *testing.T, agentID, title string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO autopilot (+ workspace_id, title, assignee_type, assignee_id,+ status, execution_mode, created_by_type, created_by_id+ )+ VALUES ($1, $2, 'agent', $3, 'active', 'run_only', 'member', $4)+ RETURNING id+ `, testWorkspaceID, title, agentID, testUserID).Scan(&id); err != nil {+ t.Fatalf("failed to insert test autopilot: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, id)+ })+ return id+}++// TestListAutopilots_DerivedFields guards the three list-only derived+// columns added for the list UI (trigger badges, next run, last-run+// outcome): trigger_kinds/next_run_at must consider ENABLED triggers only,+// last_run_status must be the most recent run's status, and all three must+// be omitted entirely when there is nothing to derive (the optional-field+// contract older clients rely on).+func TestListAutopilots_DerivedFields(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID := createHandlerTestAgent(t, "autopilot-list-derived-agent", []byte(`[]`))+ withData := insertListTestAutopilot(t, agentID, "list-derived-with-data")+ bare := insertListTestAutopilot(t, agentID, "list-derived-bare")++ // Enabled schedule (carries next_run_at), enabled webhook, and a+ // DISABLED api trigger that must not leak into trigger_kinds.+ for _, q := range []string{+ `INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, timezone, next_run_at)+ VALUES ($1, 'schedule', true, '0 9 * * *', 'UTC', now() + interval '1 hour')`,+ `INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, webhook_token)+ VALUES ($1, 'webhook', true, 'list-derived-tok')`,+ `INSERT INTO autopilot_trigger (autopilot_id, kind, enabled)+ VALUES ($1, 'api', false)`,+ } {+ if _, err := testPool.Exec(ctx, q, withData); err != nil {+ t.Fatalf("failed to insert trigger: %v", err)+ }+ }++ // Older completed run, newer failed run — last_run_status must be the+ // newest by triggered_at, not insertion order.+ for _, q := range []string{+ `INSERT INTO autopilot_run (autopilot_id, source, status, triggered_at)+ VALUES ($1, 'schedule', 'failed', now() - interval '1 hour')`,+ `INSERT INTO autopilot_run (autopilot_id, source, status, triggered_at)+ VALUES ($1, 'schedule', 'completed', now() - interval '2 hour')`,+ } {+ if _, err := testPool.Exec(ctx, q, withData); err != nil {+ t.Fatalf("failed to insert run: %v", err)+ }+ }++ w := httptest.NewRecorder()+ testHandler.ListAutopilots(w, newRequest("GET", "/api/autopilots", nil))+ if w.Code != 200 {+ t.Fatalf("ListAutopilots: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var body struct {+ Autopilots []map[string]any `json:"autopilots"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {+ t.Fatalf("failed to decode body: %v", err)+ }+ rows := make(map[string]map[string]any)+ for _, row := range body.Autopilots {+ rows[row["id"].(string)] = row+ }++ rich, ok := rows[withData]+ if !ok {+ t.Fatalf("autopilot %s missing from list", withData)+ }+ kinds, _ := rich["trigger_kinds"].([]any)+ if len(kinds) != 2 || kinds[0] != "schedule" || kinds[1] != "webhook" {+ t.Errorf("trigger_kinds: expected [schedule webhook] (enabled only, sorted), got %v", rich["trigger_kinds"])+ }+ if s, _ := rich["next_run_at"].(string); s == "" {+ t.Errorf("next_run_at: expected the enabled schedule trigger's time, got %v", rich["next_run_at"])+ }+ if rich["last_run_status"] != "failed" {+ t.Errorf("last_run_status: expected most recent run (failed), got %v", rich["last_run_status"])+ }++ plain, ok := rows[bare]+ if !ok {+ t.Fatalf("autopilot %s missing from list", bare)+ }+ for _, key := range []string{"trigger_kinds", "next_run_at", "last_run_status"} {+ if _, present := plain[key]; present {+ t.Errorf("%s: expected field omitted for autopilot with no triggers/runs, got %v", key, plain[key])+ }+ }+}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex b71c287ef4..ceb322fcc4 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -670,10 +670,29 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.const listAutopilots = `-- name: ListAutopilots :many-SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id FROM autopilot-WHERE workspace_id = $1- AND ($2::text IS NULL OR status = $2)-ORDER BY created_at DESC+SELECT+ a.id, a.workspace_id, a.title, a.description, a.assignee_id, a.status, a.execution_mode, a.issue_title_template, a.created_by_type, a.created_by_id, a.last_run_at, a.created_at, a.updated_at, a.assignee_type, a.project_id,+ (+ SELECT array_agg(DISTINCT t.kind ORDER BY t.kind)+ FROM autopilot_trigger t+ WHERE t.autopilot_id = a.id AND t.enabled+ )::text[] AS trigger_kinds,+ (+ SELECT min(t.next_run_at)+ FROM autopilot_trigger t+ WHERE t.autopilot_id = a.id AND t.enabled AND t.kind = 'schedule'+ )::timestamptz AS next_run_at,+ COALESCE((+ SELECT r.status+ FROM autopilot_run r+ WHERE r.autopilot_id = a.id+ ORDER BY r.triggered_at DESC+ LIMIT 1+ ), '')::text AS last_run_status+FROM autopilot a+WHERE a.workspace_id = $1+ AND ($2::text IS NULL OR a.status = $2)+ORDER BY a.created_at DESC`type ListAutopilotsParams struct {@@ -681,34 +700,50 @@ type ListAutopilotsParams struct {Status pgtype.Text `json:"status"`}+type ListAutopilotsRow struct {+ Autopilot Autopilot `json:"autopilot"`+ TriggerKinds []string `json:"trigger_kinds"`+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`+ LastRunStatus string `json:"last_run_status"`+}+// =====================// Autopilot CRUD// =====================-func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams) ([]Autopilot, error) {+// List rows carry three derived columns the list UI needs (trigger badges,+// next run, last-run outcome) so the page never has to N+1 into the detail+// endpoint. trigger_kinds/next_run_at only consider ENABLED triggers — the+// columns answer "how does this fire today", not "what is configured".+// last_run_status is COALESCEd to ” (never ran) because sqlc cannot infer+// nullability through a scalar subquery; the handler maps ” back to omitted.+func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams) ([]ListAutopilotsRow, error) {rows, err := q.db.Query(ctx, listAutopilots, arg.WorkspaceID, arg.Status)if err != nil {return nil, err}defer rows.Close()- items := []Autopilot{}+ items := []ListAutopilotsRow{}for rows.Next() {- var i Autopilot+ var i ListAutopilotsRowif err := rows.Scan(- &i.ID,- &i.WorkspaceID,- &i.Title,- &i.Description,- &i.AssigneeID,- &i.Status,- &i.ExecutionMode,- &i.IssueTitleTemplate,- &i.CreatedByType,- &i.CreatedByID,- &i.LastRunAt,- &i.CreatedAt,- &i.UpdatedAt,- &i.AssigneeType,- &i.ProjectID,+ &i.Autopilot.ID,+ &i.Autopilot.WorkspaceID,+ &i.Autopilot.Title,+ &i.Autopilot.Description,+ &i.Autopilot.AssigneeID,+ &i.Autopilot.Status,+ &i.Autopilot.ExecutionMode,+ &i.Autopilot.IssueTitleTemplate,+ &i.Autopilot.CreatedByType,+ &i.Autopilot.CreatedByID,+ &i.Autopilot.LastRunAt,+ &i.Autopilot.CreatedAt,+ &i.Autopilot.UpdatedAt,+ &i.Autopilot.AssigneeType,+ &i.Autopilot.ProjectID,+ &i.TriggerKinds,+ &i.NextRunAt,+ &i.LastRunStatus,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex d35101aa80..c33b5a2052 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -3,10 +3,35 @@-- =====================-- name: ListAutopilots :many-SELECT * FROM autopilot-WHERE workspace_id = $1- AND (sqlc.narg('status')::text IS NULL OR status = sqlc.narg('status'))-ORDER BY created_at DESC;+-- List rows carry three derived columns the list UI needs (trigger badges,+-- next run, last-run outcome) so the page never has to N+1 into the detail+-- endpoint. trigger_kinds/next_run_at only consider ENABLED triggers — the+-- columns answer "how does this fire today", not "what is configured".+-- last_run_status is COALESCEd to '' (never ran) because sqlc cannot infer+-- nullability through a scalar subquery; the handler maps '' back to omitted.+SELECT+ sqlc.embed(a),+ (+ SELECT array_agg(DISTINCT t.kind ORDER BY t.kind)+ FROM autopilot_trigger t+ WHERE t.autopilot_id = a.id AND t.enabled+ )::text[] AS trigger_kinds,+ (+ SELECT min(t.next_run_at)+ FROM autopilot_trigger t+ WHERE t.autopilot_id = a.id AND t.enabled AND t.kind = 'schedule'+ )::timestamptz AS next_run_at,+ COALESCE((+ SELECT r.status+ FROM autopilot_run r+ WHERE r.autopilot_id = a.id+ ORDER BY r.triggered_at DESC+ LIMIT 1+ ), '')::text AS last_run_status+FROM autopilot a+WHERE a.workspace_id = $1+ AND (sqlc.narg('status')::text IS NULL OR a.status = sqlc.narg('status'))+ORDER BY a.created_at DESC;-- name: GetAutopilot :oneSELECT * FROM autopilot