import {
  AgentInteractivePromptSurface,
  AgentMessageMarkdown,
  CustomScrollArea,
  approvalOptionDisplayLabel,
  cn,
  getPromptToolDetails,
  isPromptRequestIdTitle,
  managedAgentRoundedIconUrl,
  user_avatar_placeholder_default,
  workspaceAgentActivityStatusLabel
} from "../chunk-VBNWIBNV.js";
import {
  resolveWorkspaceAgentSessionSortTimeUnixMs,
  workspaceAgentProviderLabel
} from "../chunk-3D5VTIKP.js";
import {
  normalizeAgentTitleText
} from "../chunk-GCBDIQDX.js";
import {
  AgentGuiI18nProvider,
  useTranslation
} from "../chunk-ZAVQMGAX.js";
import "../chunk-PJP5BUU6.js";
import "../chunk-ZU3FKYMG.js";

// agent-message-center/WorkspaceAgentMessageCenterPanel.tsx
import {
  memo,
  useCallback as useCallback2,
  useEffect as useEffect2,
  useLayoutEffect as useLayoutEffect2,
  useMemo,
  useRef as useRef2,
  useState as useState2
} from "react";
import {
  Button as Button3,
  cn as cn4,
  Drawer,
  DrawerContent,
  TooltipProvider
} from "@tutti-os/ui-system";

// shared/AgentVerticalScrollArea.tsx
import {
  forwardRef
} from "react";
import { jsx } from "react/jsx-runtime";
var AgentVerticalScrollArea = forwardRef(function AgentVerticalScrollArea2({
  children,
  className,
  viewportClassName,
  scrollbarClassName,
  scrollbarThumbClassName,
  syncKey,
  ...props
}, forwardedRef) {
  "use memo";
  return /* @__PURE__ */ jsx(
    CustomScrollArea,
    {
      ref: forwardedRef,
      className: cn("agent-vertical-scroll-area min-h-0 min-w-0", className),
      viewportClassName: cn(
        "min-h-0 min-w-0 overflow-x-hidden overflow-y-auto",
        viewportClassName
      ),
      scrollbarClassName: cn(
        "agent-vertical-scroll-area__scrollbar top-2 right-2 bottom-2",
        scrollbarClassName
      ),
      scrollbarThumbClassName: cn(
        "agent-vertical-scroll-area__scrollbar-thumb",
        scrollbarThumbClassName
      ),
      syncKey: syncKey ?? children,
      ...props,
      children
    }
  );
});

// agent-message-center/WorkspaceAgentMessageCenterViewControls.tsx
import { ListFilter } from "lucide-react";
import {
  Button,
  cn as cn2,
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from "@tutti-os/ui-system";

// agent-message-center/workspaceAgentMessageCenterModel.ts
import {
  selectNeedsAttentionItems,
  selectSessionDisplayStatuses
} from "@tutti-os/agent-activity-core";
var EMPTY_COUNTS = {
  all: 0,
  working: 0,
  waiting: 0,
  completed: 0,
  failed: 0
};
function buildWorkspaceAgentMessageCenterModel(snapshot, options = {}) {
  const needsAttentionBySessionId = latestNeedsAttentionBySessionId(
    selectNeedsAttentionItems(snapshot)
  );
  const displayStatuses = selectSessionDisplayStatuses(snapshot);
  const items = snapshot.sessions.filter((session) => session.visible !== false).map((session) => {
    const messages = resolveSessionMessages(snapshot, session);
    const needsAttention = needsAttentionBySessionId.get(session.agentSessionId) ?? null;
    const pendingPrompt = pendingPromptFromMessages(messages) ?? fallbackPromptFromNeedsAttention(
      needsAttention,
      options.promptFallbackLabels
    );
    const status = displayStatuses.get(session.agentSessionId) ?? "idle";
    const lastAgentMessage = latestAgentMessage(messages);
    const title = resolveSessionTitle(session, messages);
    const sortTimeUnixMs = resolveWorkspaceAgentSessionSortTimeUnixMs(
      session,
      {
        messages
      }
    );
    return {
      id: `message-center-${session.agentSessionId}`,
      agentSessionId: session.agentSessionId,
      provider: session.provider,
      userId: session.userId?.trim() || null,
      title,
      identity: resolveMessageCenterIdentity(
        session.agentSessionId,
        options.identityBySessionId
      ),
      cwd: session.cwd,
      status,
      lastAgentMessageSummary: lastAgentMessage?.summary ?? needsAttention?.summary ?? title,
      lastAgentMessageAtUnixMs: lastAgentMessage?.occurredAtUnixMs ?? null,
      pendingPrompt,
      needsAttentionKind: needsAttention?.kind ?? null,
      needsAttentionSummary: needsAttention?.summary ?? null,
      sortTimeUnixMs
    };
  });
  return {
    waitingCount: items.filter(isWaitingMessageCenterItem).length,
    items: items.sort(compareMessageCenterItems),
    counts: countMessageCenterItems(items)
  };
}
function resolveMessageCenterIdentity(agentSessionId, identityBySessionId) {
  const identity = identityBySessionId?.[agentSessionId];
  if (!identity) {
    return null;
  }
  const userName = identity.userName.trim();
  const agentName = identity.agentName.trim();
  if (!userName || !agentName) {
    return null;
  }
  const userAvatarUrl = identity.userAvatarUrl?.trim() ?? "";
  const agentAvatarUrl = identity.agentAvatarUrl?.trim() ?? "";
  return {
    userName,
    ...userAvatarUrl ? { userAvatarUrl } : {},
    agentName,
    ...agentAvatarUrl ? { agentAvatarUrl } : {}
  };
}
function isWaitingMessageCenterItem(item) {
  return item.pendingPrompt !== null || item.needsAttentionKind !== null;
}
function isCompletedMessageCenterItem(item) {
  return item.status === "completed" || item.status === "canceled" || item.status === "idle";
}
function latestNeedsAttentionBySessionId(items) {
  const bySessionId = /* @__PURE__ */ new Map();
  for (const item of items) {
    const previous = bySessionId.get(item.agentSessionId);
    if (!previous || item.occurredAtUnixMs > previous.occurredAtUnixMs) {
      bySessionId.set(item.agentSessionId, item);
    }
  }
  return bySessionId;
}
function resolveSessionMessages(snapshot, session) {
  for (const sessionId of [session.agentSessionId, session.providerSessionId]) {
    const normalized = sessionId?.trim() ?? "";
    if (normalized && snapshot.sessionMessagesById[normalized]) {
      return snapshot.sessionMessagesById[normalized];
    }
  }
  return [];
}
function resolveSessionTitle(session, messages) {
  const title = session.title.trim();
  if (title) {
    return title;
  }
  return firstUserMessageText(messages) || session.provider || session.agentSessionId;
}
function firstUserMessageText(messages) {
  for (const message of messages) {
    if (message.role.trim().toLowerCase() !== "user") {
      continue;
    }
    const summary = messageSummary(message);
    if (summary) {
      return summary;
    }
  }
  return "";
}
function pendingPromptFromMessages(messages) {
  for (const message of [...messages].sort(compareMessagesByRecentTime)) {
    if (isTerminalMessageStatus(message.status)) {
      continue;
    }
    const approval = approvalPromptFromMessage(message);
    if (approval) {
      return approval;
    }
    const askUser = askUserPromptFromMessage(message);
    if (askUser) {
      return askUser;
    }
    const exitPlan = exitPlanPromptFromMessage(message);
    if (exitPlan) {
      return exitPlan;
    }
  }
  return null;
}
function approvalPromptFromMessage(message) {
  if (!isPermissionMessage(message)) {
    return null;
  }
  const payload = recordValue(message.payload);
  const input = recordValue(payload.input);
  const requestId = stringValue(input.requestId) ?? stringValue(payload.requestId) ?? stringValue(payload.approvalRequestId) ?? message.messageId;
  const options = [
    ...arrayValue(input.options),
    ...arrayValue(payload.options)
  ].flatMap((option) => {
    const record = recordValue(option);
    const id = stringValue(record.optionId) ?? stringValue(record.id) ?? stringValue(record.kind);
    if (!id) {
      return [];
    }
    return [
      {
        id,
        label: stringValue(record.name) ?? stringValue(record.label) ?? stringValue(record.title) ?? id,
        kind: stringValue(record.kind) ?? id,
        ...stringValue(record.description) ? { description: stringValue(record.description) } : {}
      }
    ];
  });
  if (options.length === 0) {
    return null;
  }
  return {
    kind: "approval",
    id: `approval:${requestId}`,
    turnId: message.turnId ?? "turn:unknown",
    requestId,
    callId: stringValue(payload.callId) ?? message.messageId,
    title: firstNonEmptyString(
      stringValue(payload.summary),
      stringValue(payload.title),
      stringValue(input.title),
      stringValue(input.command),
      messageSummary(message),
      message.kind
    ),
    toolName: stringValue(payload.toolName) ?? stringValue(payload.name) ?? stringValue(payload.tool),
    status: message.status ?? stringValue(payload.status),
    input: Object.keys(input).length > 0 ? input : payload,
    options,
    output: null,
    occurredAtUnixMs: messageTimeUnixMs(message) || null
  };
}
function askUserPromptFromMessage(message) {
  if (!isQuestionMessage(message)) {
    return null;
  }
  const payload = recordValue(message.payload);
  const questions = arrayValue(payload.questions).flatMap((value, index) => {
    const question = recordValue(value);
    const id = stringValue(question.id) ?? `question-${index + 1}`;
    const label = stringValue(question.question) ?? stringValue(question.header) ?? stringValue(question.label);
    if (!label) {
      return [];
    }
    return [
      {
        id,
        header: stringValue(question.header) ?? label,
        question: label,
        options: arrayValue(question.options).flatMap((optionValue) => {
          const option = recordValue(optionValue);
          const optionLabel = stringValue(option.label);
          return optionLabel ? [
            {
              label: optionLabel,
              description: stringValue(option.description) ?? ""
            }
          ] : [];
        }),
        multiSelect: Boolean(question.multiSelect),
        answer: null
      }
    ];
  });
  if (questions.length === 0) {
    return null;
  }
  return {
    kind: "ask-user",
    requestId: stringValue(payload.requestId) ?? stringValue(payload.interactiveRequestId) ?? message.messageId,
    title: stringValue(payload.title) ?? stringValue(payload.summary) ?? messageSummary(message),
    questions
  };
}
function exitPlanPromptFromMessage(message) {
  if (!includesAny(normalizedMetadataValues(message), ["exitplanmode"])) {
    return null;
  }
  const payload = recordValue(message.payload);
  return {
    kind: "exit-plan",
    requestId: stringValue(payload.requestId) ?? message.messageId,
    title: stringValue(payload.title) ?? stringValue(payload.summary) ?? messageSummary(message)
  };
}
function latestAgentMessage(messages) {
  return messages.reduce(
    (latest, message) => {
      if (!isAgentMessageRole(message.role)) {
        return latest;
      }
      const summary = messageSummary(message);
      if (!summary) {
        return latest;
      }
      const occurredAtUnixMs = messageTimeUnixMs(message);
      if (!latest || occurredAtUnixMs >= latest.occurredAtUnixMs) {
        return { summary, occurredAtUnixMs };
      }
      return latest;
    },
    null
  );
}
function fallbackPromptFromNeedsAttention(item, labels) {
  if (!item || item.kind === "permission" || !labels) {
    return null;
  }
  return {
    kind: "ask-user",
    requestId: requestIdFromNeedsAttentionItem(item),
    title: item.summary || item.title || labels.title,
    questions: [
      {
        id: "response",
        header: item.kind === "constraint" ? labels.constraintHeader : labels.inputHeader,
        question: item.summary || item.title || labels.question,
        options: [],
        multiSelect: false,
        answer: null
      }
    ]
  };
}
function requestIdFromNeedsAttentionItem(item) {
  const [, messageId] = item.id.split(":", 2);
  return messageId?.trim() || item.id;
}
function countMessageCenterItems(items) {
  return items.reduce(
    (counts, item) => {
      counts.all += 1;
      if (isWaitingMessageCenterItem(item)) {
        counts.waiting += 1;
        return counts;
      }
      if (isCompletedMessageCenterItem(item)) {
        counts.completed += 1;
        return counts;
      }
      switch (item.status) {
        case "working":
          counts.working += 1;
          break;
        case "failed":
          counts.failed += 1;
          break;
        default:
          break;
      }
      return counts;
    },
    { ...EMPTY_COUNTS }
  );
}
function compareMessageCenterItems(left, right) {
  const leftWaiting = isWaitingMessageCenterItem(left);
  const rightWaiting = isWaitingMessageCenterItem(right);
  if (leftWaiting !== rightWaiting) {
    return leftWaiting ? -1 : 1;
  }
  return right.sortTimeUnixMs - left.sortTimeUnixMs || left.agentSessionId.localeCompare(right.agentSessionId);
}
function isAgentMessageRole(role) {
  const normalized = role.trim().toLowerCase();
  return normalized === "assistant" || normalized === "agent";
}
function isTerminalMessageStatus(status) {
  switch (status?.trim().toLowerCase()) {
    case "answered":
    case "canceled":
    case "cancelled":
    case "completed":
    case "failed":
    case "rejected":
    case "resolved":
      return true;
    default:
      return false;
  }
}
function isPermissionMessage(message) {
  return includesAny(normalizedMetadataValues(message), [
    "permission",
    "approval"
  ]);
}
function isQuestionMessage(message) {
  return includesAny(normalizedMetadataValues(message), [
    "ask_user",
    "ask-user",
    "askuserquestion",
    "question"
  ]);
}
function normalizedMetadataValues(message) {
  const payload = recordValue(message.payload);
  const input = recordValue(payload.input);
  return [
    message.kind,
    message.status ?? "",
    stringValue(payload.type) ?? "",
    stringValue(payload.action) ?? "",
    stringValue(payload.requestType) ?? "",
    stringValue(payload.callType) ?? "",
    stringValue(payload.toolName) ?? "",
    stringValue(payload.name) ?? "",
    stringValue(payload.status) ?? "",
    stringValue(input.type) ?? "",
    stringValue(input.action) ?? "",
    stringValue(input.requestType) ?? "",
    stringValue(input.callType) ?? "",
    stringValue(input.toolName) ?? "",
    stringValue(input.name) ?? "",
    stringValue(input.status) ?? ""
  ].join(" ").replace(/[_\s-]+/g, "").toLowerCase();
}
function compareMessagesByRecentTime(left, right) {
  return messageTimeUnixMs(right) - messageTimeUnixMs(left) || right.version - left.version || right.messageId.localeCompare(left.messageId);
}
function includesAny(value, needles) {
  return needles.some(
    (needle) => value.includes(needle.replace(/[_\s-]+/g, "").toLowerCase())
  );
}
function messageSummary(message) {
  return firstNonEmptyString(
    stringValue(message.payload.summary),
    stringValue(message.payload.text),
    stringValue(message.payload.content),
    stringValue(message.payload.message),
    stringValue(message.payload.body),
    stringValue(message.payload.title)
  );
}
function messageTimeUnixMs(message) {
  return positiveNumber(message.occurredAtUnixMs) ?? positiveNumber(message.completedAtUnixMs) ?? positiveNumber(message.startedAtUnixMs) ?? positiveNumber(message.version) ?? 0;
}
function firstNonEmptyString(...values) {
  return values.find((value) => value !== null && value.length > 0) ?? "";
}
function stringValue(value) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
function recordValue(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}
function arrayValue(value) {
  return Array.isArray(value) ? value : [];
}
function positiveNumber(value) {
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
}

// agent-message-center/workspaceAgentMessageCenterViewModel.ts
function partitionMessageCenterItemsByAgentUser(items) {
  const stacks = /* @__PURE__ */ new Map();
  for (const item of items) {
    const stackId = messageCenterAgentUserStackId(item);
    const stack = stacks.get(stackId);
    if (stack) {
      stack.items.push(item);
    } else {
      stacks.set(stackId, {
        id: stackId,
        provider: item.provider,
        userId: item.userId,
        items: [item]
      });
    }
  }
  return [...stacks.values()];
}
function messageCenterAgentUserStackId(item) {
  const provider = item.provider.trim().toLowerCase() || "unknown-agent";
  const userId = item.userId?.trim() || "unknown-user";
  return `agent-user:${provider}:${userId}`;
}
function buildMessageCenterStatusOptions(counts, t) {
  return [
    {
      count: counts.waiting,
      label: t("agentHost.workspaceAgentMessageCenterFilterWaiting"),
      value: "waiting"
    },
    {
      count: counts.failed,
      label: t("agentHost.workspaceAgentMessageCenterFilterFailed"),
      value: "failed"
    },
    {
      count: counts.working,
      label: t("agentHost.workspaceAgentMessageCenterFilterWorking"),
      value: "working"
    },
    {
      count: counts.completed,
      label: t("agentHost.workspaceAgentMessageCenterFilterCompleted"),
      value: "completed"
    }
  ];
}
function buildMessageCenterProviderOptions(items) {
  const counts = /* @__PURE__ */ new Map();
  for (const item of items) {
    counts.set(item.provider, (counts.get(item.provider) ?? 0) + 1);
  }
  return [...counts.entries()].map(([value, count]) => ({
    count,
    label: workspaceAgentProviderLabel(value),
    value
  })).sort((left, right) => left.label.localeCompare(right.label));
}
function itemMatchesViewFilters({
  item,
  providerFilters,
  statusFilters
}) {
  if (statusFilters && !statusFilters.has(messageCenterStatusFilterValue(item))) {
    return false;
  }
  if (providerFilters && !providerFilters.has(item.provider)) {
    return false;
  }
  return true;
}
function messageCenterStatusFilterValue(item) {
  if (isWaitingMessageCenterItem(item)) {
    return "waiting";
  }
  if (item.status === "failed") {
    return "failed";
  }
  if (item.status === "working") {
    return "working";
  }
  return "completed";
}
function groupMessageCenterItems(items, groupBy, t) {
  switch (groupBy) {
    case "status":
      return groupByFixedDefinitions(items, [
        {
          id: "waiting",
          label: t("agentHost.workspaceAgentMessageCenterFilterWaiting"),
          match: (item) => messageCenterStatusFilterValue(item) === "waiting"
        },
        {
          id: "failed",
          label: t("agentHost.workspaceAgentMessageCenterFilterFailed"),
          match: (item) => messageCenterStatusFilterValue(item) === "failed"
        },
        {
          id: "working",
          label: t("agentHost.workspaceAgentMessageCenterFilterWorking"),
          match: (item) => messageCenterStatusFilterValue(item) === "working"
        },
        {
          id: "completed",
          label: t("agentHost.workspaceAgentMessageCenterFilterCompleted"),
          match: (item) => messageCenterStatusFilterValue(item) === "completed"
        }
      ]);
    case "agent":
      return groupByDynamicKey(items, (item) => ({
        id: messageCenterAgentUserStackId(item),
        identity: item.identity,
        label: messageCenterAgentUserGroupLabel(item),
        provider: item.provider,
        userId: item.userId
      }));
    case "time":
      return groupByFixedDefinitions(items, [
        {
          id: "today",
          label: t("agentHost.workspaceAgentMessageCenterGroupToday"),
          match: (item) => messageCenterTimeGroup(item) === "today"
        },
        {
          id: "yesterday",
          label: t("agentHost.workspaceAgentMessageCenterGroupYesterday"),
          match: (item) => messageCenterTimeGroup(item) === "yesterday"
        },
        {
          id: "previous-seven-days",
          label: t(
            "agentHost.workspaceAgentMessageCenterGroupPreviousSevenDays"
          ),
          match: (item) => messageCenterTimeGroup(item) === "previous-seven-days"
        },
        {
          id: "older",
          label: t("agentHost.workspaceAgentMessageCenterGroupOlder"),
          match: (item) => messageCenterTimeGroup(item) === "older"
        }
      ]);
    case "priority":
    default: {
      const nowUnixMs = Date.now();
      return groupByFixedDefinitions(items, [
        {
          id: "needs-attention",
          label: t("agentHost.workspaceAgentMessageCenterGroupNeedsAttention"),
          match: (item) => messageCenterStatusFilterValue(item) === "waiting" || messageCenterStatusFilterValue(item) === "failed"
        },
        {
          id: "working",
          label: t("agentHost.workspaceAgentMessageCenterFilterWorking"),
          match: (item) => messageCenterStatusFilterValue(item) === "working"
        },
        {
          id: "recently-completed",
          label: t(
            "agentHost.workspaceAgentMessageCenterGroupRecentlyCompleted"
          ),
          match: (item) => isRecentlyCompletedMessageCenterItem(item, nowUnixMs)
        },
        {
          id: "completed",
          label: t("agentHost.workspaceAgentMessageCenterFilterCompleted"),
          match: (item) => messageCenterStatusFilterValue(item) === "completed" && !isRecentlyCompletedMessageCenterItem(item, nowUnixMs)
        }
      ]);
    }
  }
}
function messageCenterAgentUserGroupLabel(item) {
  if (item.identity) {
    return `${item.identity.userName} & ${item.identity.agentName}`;
  }
  return workspaceAgentProviderLabel(item.provider);
}
var RECENTLY_COMPLETED_WINDOW_MS = 10 * 60 * 1e3;
function isRecentlyCompletedMessageCenterItem(item, nowUnixMs) {
  if (messageCenterStatusFilterValue(item) !== "completed") {
    return false;
  }
  const completedAtUnixMs = item.sortTimeUnixMs || item.lastAgentMessageAtUnixMs || 0;
  if (completedAtUnixMs <= 0) {
    return false;
  }
  return completedAtUnixMs >= nowUnixMs - RECENTLY_COMPLETED_WINDOW_MS;
}
function messageCenterGroupLabel(groupBy, t) {
  switch (groupBy) {
    case "status":
      return t("agentHost.workspaceAgentMessageCenterGroupStatus");
    case "agent":
      return t("agentHost.workspaceAgentMessageCenterGroupAgent");
    case "time":
      return t("agentHost.workspaceAgentMessageCenterGroupTime");
    case "priority":
    default:
      return t("agentHost.workspaceAgentMessageCenterGroupPriority");
  }
}
function statusFilterSummary(statusFilters, statusOptions) {
  if (statusFilters === null || statusFilters.size === statusOptions.length) {
    return statusOptions.map((option) => option.label).join(", ");
  }
  return statusOptions.filter((option) => statusFilters.has(option.value)).map((option) => option.label).join(", ");
}
function groupByFixedDefinitions(items, definitions) {
  return definitions.map((definition) => ({
    id: definition.id,
    label: definition.label,
    items: items.filter(definition.match)
  })).filter((group) => group.items.length > 0);
}
function groupByDynamicKey(items, keyForItem) {
  const groups = /* @__PURE__ */ new Map();
  for (const item of items) {
    const key = keyForItem(item);
    const group = groups.get(key.id);
    if (group) {
      group.items.push(item);
      if (!group.identity && key.identity) {
        group.identity = key.identity;
        group.label = key.label;
      }
    } else {
      groups.set(key.id, { ...key, items: [item] });
    }
  }
  return [...groups.values()];
}
function messageCenterTimeGroup(item) {
  const timestamp = item.sortTimeUnixMs || item.lastAgentMessageAtUnixMs || 0;
  if (timestamp <= 0) {
    return "older";
  }
  const ageMs = Date.now() - timestamp;
  const dayMs = 24 * 60 * 60 * 1e3;
  if (ageMs < dayMs) {
    return "today";
  }
  if (ageMs < dayMs * 2) {
    return "yesterday";
  }
  if (ageMs < dayMs * 7) {
    return "previous-seven-days";
  }
  return "older";
}

// agent-message-center/WorkspaceAgentMessageCenterViewControls.tsx
import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
function MessageCenterViewMenu({
  filtersActive = false,
  groupBy,
  providerFilters,
  providerOptions,
  statusFilters,
  statusOptions,
  onClearFilters,
  onGroupByChange,
  onProviderToggle,
  onStatusToggle
}) {
  "use memo";
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs(DropdownMenu, { modal: false, children: [
    /* @__PURE__ */ jsx2(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "ghost",
        size: "icon",
        "aria-label": t("agentHost.workspaceAgentMessageCenterViewOptions"),
        title: t("agentHost.workspaceAgentMessageCenterViewOptions"),
        className: cn2(
          "relative size-8 shrink-0 rounded-md border bg-[var(--background-fronted)] shadow-none",
          filtersActive ? "border-[var(--border-focus)] text-[var(--accent)]" : "border-[var(--line-2)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
        ),
        children: [
          /* @__PURE__ */ jsx2(ListFilter, { className: "size-4", strokeWidth: 2.1, "aria-hidden": "true" }),
          filtersActive ? /* @__PURE__ */ jsx2(
            "span",
            {
              "aria-label": t(
                "agentHost.workspaceAgentMessageCenterFilterActive"
              ),
              className: "absolute -right-0.5 -top-0.5 size-2 rounded-full border border-[var(--background-panel)] bg-[var(--accent)]"
            }
          ) : null
        ]
      }
    ) }),
    /* @__PURE__ */ jsxs(
      DropdownMenuContent,
      {
        align: "end",
        sideOffset: 8,
        className: "min-w-[240px] p-1.5",
        style: { zIndex: "var(--z-dialog-popover)" },
        children: [
          /* @__PURE__ */ jsx2(DropdownMenuLabel, { children: t("agentHost.workspaceAgentMessageCenterGroupBy") }),
          /* @__PURE__ */ jsx2(
            DropdownMenuRadioGroup,
            {
              value: groupBy,
              onValueChange: (value) => onGroupByChange(value),
              children: ["priority", "status", "agent", "time"].map((value) => /* @__PURE__ */ jsx2(DropdownMenuRadioItem, { value, children: messageCenterGroupLabel(value, t) }, value))
            }
          ),
          /* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
          /* @__PURE__ */ jsx2(DropdownMenuLabel, { children: t("agentHost.workspaceAgentMessageCenterFilterStatus") }),
          /* @__PURE__ */ jsx2(DropdownMenuGroup, { children: statusOptions.map((option) => /* @__PURE__ */ jsxs(
            DropdownMenuCheckboxItem,
            {
              "aria-label": `${option.label} ${option.count}`,
              checked: statusFilters === null || statusFilters.has(option.value),
              onCheckedChange: () => onStatusToggle(option.value),
              onSelect: (event) => event.preventDefault(),
              children: [
                /* @__PURE__ */ jsx2("span", { className: "min-w-0 flex-1 truncate", children: option.label }),
                /* @__PURE__ */ jsx2("span", { className: "ml-auto text-[11px] text-[var(--text-tertiary)]", children: option.count })
              ]
            },
            option.value
          )) }),
          providerOptions.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
            /* @__PURE__ */ jsx2(DropdownMenuLabel, { children: t("agentHost.workspaceAgentMessageCenterFilterAgent") }),
            /* @__PURE__ */ jsx2(DropdownMenuGroup, { children: providerOptions.map((option) => /* @__PURE__ */ jsxs(
              DropdownMenuCheckboxItem,
              {
                "aria-label": `${option.label} ${option.count}`,
                checked: providerFilters === null || providerFilters.has(option.value),
                onCheckedChange: () => onProviderToggle(option.value),
                onSelect: (event) => event.preventDefault(),
                children: [
                  /* @__PURE__ */ jsx2("span", { className: "min-w-0 flex-1 truncate", children: option.label }),
                  /* @__PURE__ */ jsx2("span", { className: "ml-auto text-[11px] text-[var(--text-tertiary)]", children: option.count })
                ]
              },
              option.value
            )) })
          ] }) : null,
          /* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
          /* @__PURE__ */ jsx2(DropdownMenuGroup, { children: /* @__PURE__ */ jsx2(DropdownMenuItem, { onClick: onClearFilters, children: t("agentHost.workspaceAgentMessageCenterClearFilters") }) })
        ]
      }
    )
  ] });
}

// agent-message-center/WorkspaceAgentMessageCenterCard.tsx
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState
} from "react";
import { ChevronDown, ChevronUp, ExternalLink, Info } from "lucide-react";
import {
  Button as Button2,
  cn as cn3,
  StatusDot,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@tutti-os/ui-system";
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
function stopMessageCenterTextPointerPropagation(event) {
  event.stopPropagation();
}
function WorkspaceAgentMessageCenterCard({
  cardRef,
  highlighted = false,
  item,
  isSubmitting,
  onLinkAction,
  onOpenChat,
  onSubmitPrompt
}) {
  "use memo";
  const { t } = useTranslation();
  const prompt = item.pendingPrompt;
  const displayTitle = normalizeAgentTitleText(item.title);
  const summary = messageCenterVisibleSummary(item);
  const displayStatus = statusClass(item);
  const statusLabel = workspaceAgentActivityStatusLabel(displayStatus, t);
  return /* @__PURE__ */ jsxs2(
    "article",
    {
      ref: cardRef,
      className: cn3(
        "workspace-agent-message-center__card group/message-card flex min-w-0 flex-col gap-2.5 rounded-lg border border-[var(--line-2)] bg-[var(--background-fronted)] p-3.5 outline outline-0 outline-offset-2 outline-transparent transition-[background-color,border-color,outline-color]",
        isWaitingMessageCenterItem(item) && "agent-gui-edge-glow border-[var(--tutti-purple-border)] bg-[var(--tutti-purple-bg)]",
        highlighted && "outline-2 outline-[var(--accent)]"
      ),
      "data-highlighted": highlighted ? "true" : void 0,
      "data-message-center-item-id": item.id,
      "data-waiting": isWaitingMessageCenterItem(item) ? "true" : void 0,
      "data-status": displayStatus,
      tabIndex: highlighted ? -1 : void 0,
      children: [
        /* @__PURE__ */ jsxs2("div", { className: "flex min-w-0 items-center justify-between gap-2.5", children: [
          /* @__PURE__ */ jsxs2("div", { className: "flex min-w-0 items-center gap-1.5", children: [
            /* @__PURE__ */ jsxs2(Tooltip, { children: [
              /* @__PURE__ */ jsx3(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx3(
                "h3",
                {
                  className: "workspace-agent-message-center__copy-text min-w-0 truncate text-[13px] font-bold leading-5 text-[var(--text-secondary)]",
                  onPointerDown: stopMessageCenterTextPointerPropagation,
                  children: displayTitle
                }
              ) }),
              /* @__PURE__ */ jsx3(
                TooltipContent,
                {
                  side: "top",
                  align: "start",
                  className: "max-w-[min(360px,calc(100vw-32px))] whitespace-normal text-left [overflow-wrap:anywhere]",
                  children: displayTitle
                }
              )
            ] }),
            item.cwd ? /* @__PURE__ */ jsx3(ProjectPathInfo, { path: item.cwd }) : null
          ] }),
          /* @__PURE__ */ jsxs2(
            "span",
            {
              className: "workspace-agent-message-center__status inline-flex shrink-0 items-center gap-1.5 text-[11px] font-semibold leading-4 text-[var(--text-secondary)]",
              "data-status": displayStatus,
              title: statusLabel,
              children: [
                /* @__PURE__ */ jsx3(
                  StatusDot,
                  {
                    tone: messageCenterStatusTone(item),
                    pulse: isWaitingMessageCenterItem(item) || item.status === "working",
                    size: "sm",
                    title: statusLabel
                  }
                ),
                /* @__PURE__ */ jsx3("span", { children: statusLabel })
              ]
            }
          )
        ] }),
        summary ? /* @__PURE__ */ jsx3(
          MessageCenterSummary,
          {
            item,
            onLinkAction,
            summary,
            emptyLabel: t("agentHost.workspaceAgentMessageCenterNoSummary")
          }
        ) : null,
        prompt ? /* @__PURE__ */ jsx3("div", { className: "min-w-0", children: /* @__PURE__ */ jsx3(
          AgentInteractivePromptSurface,
          {
            embedded: true,
            keyboardShortcuts: false,
            prompt,
            isSubmitting,
            onSubmit: onSubmitPrompt,
            labels: buildWorkspaceAgentInteractivePromptLabels(
              t,
              item.provider
            )
          }
        ) }) : null,
        /* @__PURE__ */ jsx3(
          MessageCenterOpenChatButton,
          {
            provider: item.provider,
            item,
            label: t("agentHost.workspaceAgentMessageCenterOpenChat"),
            onOpenChat
          }
        )
      ]
    }
  );
}
var STACK_PRESENCE_FALLBACK_MS = 380;
function useStackRegionPresence(visible) {
  const [mounted, setMounted] = useState(visible);
  const closing = mounted && !visible;
  useLayoutEffect(() => {
    if (visible) {
      setMounted(true);
    }
  }, [visible]);
  useEffect(() => {
    if (!closing) {
      return void 0;
    }
    const timeoutId = window.setTimeout(() => {
      setMounted(false);
    }, STACK_PRESENCE_FALLBACK_MS);
    return () => {
      window.clearTimeout(timeoutId);
    };
  }, [closing]);
  const onAnimationEnd = useCallback(
    (event) => {
      if (event.target === event.currentTarget && closing) {
        setMounted(false);
      }
    },
    [closing]
  );
  return { closing, mounted, onAnimationEnd };
}
function WorkspaceAgentMessageCenterStack({
  className,
  expanded,
  groupId,
  items,
  renderCard,
  onCollapse,
  onExpand
}) {
  "use memo";
  const { t } = useTranslation();
  const summaryRegion = useStackRegionPresence(!expanded);
  const cardsRegion = useStackRegionPresence(expanded);
  if (items.length < 2) {
    return null;
  }
  const collapseLabel = t(
    "agentHost.workspaceAgentMessageCenterCollapseStackAria"
  );
  return /* @__PURE__ */ jsxs2(
    "div",
    {
      className: cn3("relative flex min-w-0 flex-col", className),
      "data-stack-count": items.length,
      "data-stack-motion": "smooth",
      "data-stack-state": expanded ? "expanded" : "collapsed",
      "data-stack-top-item-id": items[0]?.id,
      "data-testid": `workspace-agent-message-stack-${groupId}`,
      children: [
        summaryRegion.mounted ? /* @__PURE__ */ jsx3(
          "div",
          {
            className: cn3(
              "workspace-agent-message-center__stack-rest min-w-0",
              summaryRegion.closing ? "workspace-agent-message-center__stack-rest--closing" : "workspace-agent-message-center__stack-rest--opening"
            ),
            onAnimationEnd: summaryRegion.onAnimationEnd,
            children: /* @__PURE__ */ jsx3(
              "div",
              {
                className: "min-h-0 min-w-0 overflow-hidden",
                "aria-hidden": summaryRegion.closing ? true : void 0,
                inert: summaryRegion.closing ? true : void 0,
                children: /* @__PURE__ */ jsx3(
                  MessageCenterStackSummary,
                  {
                    groupId,
                    items,
                    onExpand
                  }
                )
              }
            )
          }
        ) : null,
        cardsRegion.mounted ? /* @__PURE__ */ jsx3(
          "div",
          {
            className: cn3(
              "workspace-agent-message-center__stack-rest min-w-0",
              cardsRegion.closing ? "workspace-agent-message-center__stack-rest--closing" : "workspace-agent-message-center__stack-rest--opening"
            ),
            onAnimationEnd: cardsRegion.onAnimationEnd,
            children: /* @__PURE__ */ jsxs2(
              "div",
              {
                className: "min-h-0 min-w-0 overflow-hidden",
                "aria-hidden": cardsRegion.closing ? true : void 0,
                inert: cardsRegion.closing ? true : void 0,
                children: [
                  /* @__PURE__ */ jsxs2("div", { className: "flex min-w-0 items-center justify-between gap-2 px-0.5 pb-1.5", children: [
                    /* @__PURE__ */ jsxs2("span", { className: "flex min-w-0 items-center gap-1.5 text-[13px] font-semibold leading-4 text-[var(--text-tertiary)]", children: [
                      /* @__PURE__ */ jsx3(
                        MessageCenterIdentityAvatarMark,
                        {
                          identity: items[0]?.identity ?? null,
                          provider: items[0]?.provider ?? "",
                          userId: items[0]?.userId ?? null
                        }
                      ),
                      /* @__PURE__ */ jsx3("span", { className: "min-w-0 truncate", children: t("agentHost.workspaceAgentMessageCenterStackSummaryCount", {
                        count: items.length
                      }) })
                    ] }),
                    /* @__PURE__ */ jsxs2(Tooltip, { children: [
                      /* @__PURE__ */ jsx3(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx3(
                        Button2,
                        {
                          type: "button",
                          variant: "ghost",
                          size: "icon-sm",
                          "aria-label": collapseLabel,
                          className: "size-6 text-[var(--text-tertiary)] hover:text-[var(--text-primary)]",
                          onClick: onCollapse,
                          children: /* @__PURE__ */ jsx3(ChevronUp, { className: "size-3.5", "aria-hidden": "true" })
                        }
                      ) }),
                      /* @__PURE__ */ jsx3(TooltipContent, { side: "top", align: "center", children: collapseLabel })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsx3("div", { className: "flex min-w-0 flex-col gap-2.5", children: items.map(
                    (item, stackedIndex) => renderCard(item, { stackedIndex })
                  ) })
                ]
              }
            )
          }
        ) : null
      ]
    }
  );
}
function MessageCenterStackSummary({
  groupId,
  items,
  onExpand
}) {
  "use memo";
  const { t } = useTranslation();
  const firstItem = items[0];
  const hasWaiting = items.some((item) => isWaitingMessageCenterItem(item));
  if (!firstItem) {
    return null;
  }
  return /* @__PURE__ */ jsx3(
    "button",
    {
      type: "button",
      "aria-label": t("agentHost.workspaceAgentMessageCenterExpandStackAria", {
        count: items.length
      }),
      className: cn3(
        "group/stack-peek relative block w-full min-w-0 rounded-lg text-left outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)]",
        items.length > 2 ? "pb-[18px]" : "pb-[10px]"
      ),
      "data-stack-summary-count": items.length,
      "data-stack-provider": firstItem.provider,
      "data-stack-user-id": firstItem.userId ?? "",
      "data-testid": `workspace-agent-message-stack-summary-${groupId}`,
      onClick: onExpand,
      children: /* @__PURE__ */ jsxs2(
        "span",
        {
          className: cn3(
            "relative z-10 flex min-w-0 flex-col gap-2 rounded-lg border border-[var(--line-2)] bg-[var(--background-fronted)] p-3.5 transition-[background-color,border-color] duration-200 group-hover/stack-peek:bg-[var(--transparency-hover)]",
            items.length > 2 ? "shadow-[0_7px_0_-4px_var(--background-fronted),0_7px_0_-3px_var(--line-2),0_14px_0_-8px_var(--background-fronted),0_14px_0_-7px_var(--line-2)]" : "shadow-[0_7px_0_-4px_var(--background-fronted),0_7px_0_-3px_var(--line-2)]",
            hasWaiting && "border-[var(--tutti-purple-border)] bg-[var(--tutti-purple-bg)]"
          ),
          children: [
            /* @__PURE__ */ jsxs2("span", { className: "flex min-w-0 items-center justify-between gap-2.5", children: [
              /* @__PURE__ */ jsxs2("span", { className: "flex min-w-0 items-center gap-2", children: [
                /* @__PURE__ */ jsx3(
                  MessageCenterIdentityAvatarMark,
                  {
                    identity: firstItem.identity,
                    provider: firstItem.provider,
                    userId: firstItem.userId
                  }
                ),
                /* @__PURE__ */ jsx3("span", { className: "min-w-0 truncate text-[13px] font-bold leading-5 text-[var(--text-secondary)]", children: t("agentHost.workspaceAgentMessageCenterStackSummaryCount", {
                  count: items.length
                }) })
              ] }),
              /* @__PURE__ */ jsx3(
                ChevronDown,
                {
                  className: "size-4 shrink-0 text-[var(--text-tertiary)] transition-transform duration-200 group-hover/stack-peek:translate-y-0.5 motion-reduce:transition-none",
                  "aria-hidden": "true"
                }
              )
            ] }),
            /* @__PURE__ */ jsx3("span", { className: "min-w-0 rounded-md bg-transparency-block p-2.5 text-[13px] leading-[1.45] text-[var(--text-primary)]", children: /* @__PURE__ */ jsx3("span", { className: "line-clamp-2 min-w-0 [overflow-wrap:anywhere]", children: messageCenterStackPreviewText(firstItem) }) })
          ]
        }
      )
    }
  );
}
function messageCenterStackPreviewText(item) {
  return item.lastAgentMessageSummary.trim() || normalizeAgentTitleText(item.title);
}
function resolveMessageCenterNotificationAction(item, input) {
  if (input.action) {
    return normalizeMessageCenterNotificationAction(input.action);
  }
  if (!input.optionId) {
    return null;
  }
  const prompt = item.pendingPrompt;
  const option = prompt && "options" in prompt ? prompt.options.find((candidate) => candidate.id === input.optionId) : null;
  const optionToken = `${option?.kind ?? ""}:${input.optionId}`.toLowerCase();
  if (optionToken.includes("allow") || optionToken.includes("accept")) {
    return "accept";
  }
  if (optionToken.includes("deny") || optionToken.includes("reject") || optionToken.includes("disallow")) {
    return "reject";
  }
  return input.optionId;
}
function buildWorkspaceAgentInteractivePromptLabels(t, provider) {
  return {
    approvalLead: t("agentHost.agentGui.approvalRequired", {
      provider: provider ? workspaceAgentProviderLabel(provider) : t("agentHost.workspaceAgentsGenericAgentName")
    }),
    planLead: t("agentHost.agentGui.planLead"),
    planModes: [
      {
        id: "acceptEdits",
        label: t("agentHost.agentGui.planModes.acceptEdits.label"),
        description: t("agentHost.agentGui.planModes.acceptEdits.description")
      },
      {
        id: "default",
        label: t("agentHost.agentGui.planModes.askFirst.label"),
        description: t("agentHost.agentGui.planModes.askFirst.description")
      },
      {
        id: "bypassPermissions",
        label: t("agentHost.agentGui.planModes.allowAll.label"),
        description: t("agentHost.agentGui.planModes.allowAll.description")
      }
    ],
    stayInPlan: t("agentHost.agentGui.stayInPlan"),
    sendFeedback: t("agentHost.agentGui.sendFeedback"),
    feedbackPlaceholder: t("agentHost.agentGui.feedbackPlaceholder"),
    previousQuestion: t("agentHost.agentGui.previousQuestion"),
    nextQuestion: t("agentHost.agentGui.nextQuestion"),
    submitAnswers: t("agentHost.agentGui.submitAnswers"),
    answerPlaceholder: t("agentHost.agentGui.answerPlaceholder"),
    waitingForAnswer: t("agentHost.agentGui.waitingForAnswer")
  };
}
function normalizeMessageCenterNotificationAction(action) {
  switch (action) {
    case "allow":
      return "accept";
    case "deny":
      return "reject";
    default:
      return action;
  }
}
function messageCenterVisibleSummary(item) {
  const summary = item.lastAgentMessageSummary.trim();
  if (item.pendingPrompt?.kind === "approval" && isGenericApprovalSummary(summary)) {
    return "";
  }
  return summary;
}
function isGenericApprovalSummary(summary) {
  const normalized = summary.trim().toLowerCase();
  return normalized === "approval";
}
function MessageCenterSummary({
  emptyLabel,
  item,
  onLinkAction,
  summary
}) {
  "use memo";
  const summaryRef = useRef(null);
  const [isOverflowing, setIsOverflowing] = useState(false);
  const handleLinkAction = useCallback(
    (action) => {
      onLinkAction?.(
        action.type === "open-agent-session" && !action.provider ? { ...action, provider: item.provider } : action
      );
    },
    [item.provider, onLinkAction]
  );
  useLayoutEffect(() => {
    const element = summaryRef.current;
    if (!element) {
      return;
    }
    const updateOverflowState = () => {
      setIsOverflowing(element.scrollHeight > element.clientHeight + 1);
    };
    updateOverflowState();
    const resizeObserver = new ResizeObserver(updateOverflowState);
    resizeObserver.observe(element);
    return () => {
      resizeObserver.disconnect();
    };
  }, [summary]);
  return /* @__PURE__ */ jsx3(
    AgentVerticalScrollArea,
    {
      ref: summaryRef,
      className: cn3(
        "workspace-agent-message-center__summary workspace-agent-message-center__copy-text max-h-[160px] min-w-0 rounded-md bg-transparency-block text-[13px] leading-[1.45] text-[var(--text-primary)] [overflow-wrap:anywhere]",
        isOverflowing && "workspace-agent-message-center__summary--overflowing"
      ),
      viewportClassName: "workspace-agent-message-center__copy-text max-h-[160px] p-2.5 pr-4",
      onPointerDown: stopMessageCenterTextPointerPropagation,
      scrollbarClassName: "top-2 bottom-2 right-1.5",
      syncKey: summary,
      children: summary ? /* @__PURE__ */ jsx3(
        AgentMessageMarkdown,
        {
          content: summary,
          className: "[&_a]:text-[var(--tutti-purple)] [&_code]:text-[var(--text-secondary)] [&_hr]:border-t-[color-mix(in_srgb,var(--text-primary)_14%,transparent)] [&_ol]:!bg-transparent [&_p]:m-0 [&_th]:bg-[color-mix(in_srgb,var(--background-panel)_94%,var(--text-primary))] [&_th]:text-[var(--text-primary)] [&_ul]:!bg-transparent text-[var(--text-primary)]",
          onLinkAction: handleLinkAction,
          workspaceLinkContext: {
            workspaceRoot: item.cwd || null,
            basePath: item.cwd,
            source: "agent-markdown"
          },
          enableImageZoom: true
        }
      ) : emptyLabel
    }
  );
}
function MessageCenterOpenChatButton({
  item,
  label,
  onOpenChat,
  provider
}) {
  "use memo";
  return /* @__PURE__ */ jsxs2("div", { className: "workspace-agent-message-center__footer flex min-w-0 items-center justify-between gap-2", children: [
    /* @__PURE__ */ jsx3(
      MessageCenterIdentityLabel,
      {
        identity: item.identity,
        provider
      }
    ),
    /* @__PURE__ */ jsxs2(
      Button2,
      {
        type: "button",
        variant: "ghost",
        size: "default",
        className: "workspace-agent-message-center__open-chat-button invisible h-auto gap-1.5 border-0 bg-transparent p-0 text-[var(--agent-gui-accent)] opacity-0 shadow-none transition-[color,opacity,visibility] group-hover/message-card:visible group-hover/message-card:opacity-100 group-focus-within/message-card:visible group-focus-within/message-card:opacity-100 hover:bg-transparent hover:text-[var(--agent-gui-accent)] focus-visible:bg-transparent focus-visible:text-[var(--agent-gui-accent)] active:bg-transparent",
        onClick: () => onOpenChat({
          agentSessionId: item.agentSessionId,
          provider: item.provider
        }),
        children: [
          /* @__PURE__ */ jsx3(
            ExternalLink,
            {
              className: "size-[15px]",
              strokeWidth: 2.2,
              "aria-hidden": "true"
            }
          ),
          label
        ]
      }
    )
  ] });
}
function MessageCenterIdentityLabel({
  identity,
  provider
}) {
  "use memo";
  if (!identity) {
    return /* @__PURE__ */ jsx3(AgentProviderLabel, { provider });
  }
  const agentAvatarUrl = identity.agentAvatarUrl?.trim() || managedAgentRoundedIconUrl(provider);
  const title = `${identity.userName} & ${identity.agentName}`;
  return /* @__PURE__ */ jsxs2(
    "span",
    {
      className: "workspace-agent-message-center__identity inline-flex min-w-0 max-w-full items-center gap-2",
      title,
      children: [
        /* @__PURE__ */ jsx3(
          MessageCenterIdentityAvatarStack,
          {
            userAvatarUrl: identity.userAvatarUrl,
            userName: identity.userName,
            agentAvatarUrl
          }
        ),
        /* @__PURE__ */ jsxs2("span", { className: "workspace-agent-message-center__identity-names flex min-w-0 items-center gap-1 truncate text-[var(--text-secondary)]", children: [
          /* @__PURE__ */ jsx3("span", { className: "min-w-0 truncate", children: identity.userName }),
          /* @__PURE__ */ jsx3("span", { className: "shrink-0 text-[var(--text-tertiary)]", children: "&" }),
          /* @__PURE__ */ jsx3("span", { className: "min-w-0 truncate", children: identity.agentName })
        ] })
      ]
    }
  );
}
function MessageCenterIdentityAvatarMark({
  identity,
  provider,
  userId
}) {
  "use memo";
  const userName = identity?.userName.trim() || userId?.trim() || "";
  if (!userName) {
    return /* @__PURE__ */ jsx3(
      "img",
      {
        src: managedAgentRoundedIconUrl(provider),
        alt: "",
        className: "size-5 shrink-0 rounded-full",
        decoding: "async",
        loading: "lazy",
        draggable: false,
        "aria-hidden": "true"
      }
    );
  }
  return /* @__PURE__ */ jsx3(
    MessageCenterIdentityAvatarStack,
    {
      userAvatarUrl: identity?.userAvatarUrl,
      userName,
      agentAvatarUrl: identity?.agentAvatarUrl?.trim() || managedAgentRoundedIconUrl(provider)
    }
  );
}
function MessageCenterIdentityAvatarStack({
  agentAvatarUrl,
  userAvatarUrl: rawUserAvatarUrl,
  userName
}) {
  "use memo";
  const [userAvatarFailed, setUserAvatarFailed] = useState(false);
  const userAvatarUrl = rawUserAvatarUrl?.trim() ?? "";
  const userImageUrl = userAvatarUrl.length > 0 && !userAvatarFailed ? userAvatarUrl : user_avatar_placeholder_default;
  useEffect(() => {
    setUserAvatarFailed(false);
  }, [userAvatarUrl]);
  return /* @__PURE__ */ jsxs2(
    "span",
    {
      className: "workspace-agent-message-center__identity-avatar-stack inline-flex w-9 shrink-0 items-center",
      "aria-hidden": "true",
      children: [
        /* @__PURE__ */ jsx3("span", { className: "inline-flex size-5 shrink-0 overflow-hidden rounded-full bg-[var(--transparency-block)] ring-2 ring-[var(--background-fronted)]", children: /* @__PURE__ */ jsx3(
          "img",
          {
            src: userImageUrl,
            alt: userName,
            className: "size-full object-cover",
            decoding: "async",
            loading: "lazy",
            referrerPolicy: "no-referrer",
            draggable: false,
            onError: () => {
              setUserAvatarFailed(true);
            }
          }
        ) }),
        /* @__PURE__ */ jsx3("span", { className: "-ml-1.5 inline-flex size-5 shrink-0 overflow-hidden rounded-full bg-[var(--transparency-block)] ring-2 ring-[var(--background-fronted)]", children: /* @__PURE__ */ jsx3(
          "img",
          {
            src: agentAvatarUrl,
            alt: "",
            className: "size-full object-cover",
            decoding: "async",
            loading: "lazy",
            draggable: false
          }
        ) })
      ]
    }
  );
}
function ProjectPathInfo({ path }) {
  "use memo";
  return /* @__PURE__ */ jsxs2(Tooltip, { children: [
    /* @__PURE__ */ jsx3(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx3(
      "button",
      {
        type: "button",
        className: "workspace-agent-message-center__project-info-button invisible inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-[var(--text-secondary)] opacity-0 transition-[background-color,color,opacity,visibility] group-hover/message-card:visible group-hover/message-card:opacity-100 group-focus-within/message-card:visible group-focus-within/message-card:opacity-100 hover:bg-[var(--transparency-hover)] hover:text-[var(--text-primary)] focus-visible:bg-[var(--transparency-hover)] focus-visible:text-[var(--text-primary)] focus-visible:outline-none",
        "aria-label": path,
        children: /* @__PURE__ */ jsx3(Info, { className: "size-3.5", strokeWidth: 2, "aria-hidden": "true" })
      }
    ) }),
    /* @__PURE__ */ jsx3(
      TooltipContent,
      {
        side: "top",
        align: "start",
        className: "max-w-[320px] text-[11px] [overflow-wrap:anywhere]",
        children: path
      }
    )
  ] });
}
function AgentProviderLabel({ provider }) {
  "use memo";
  const label = workspaceAgentProviderLabel(provider);
  return /* @__PURE__ */ jsxs2("span", { className: "workspace-agent-message-center__provider inline-flex min-w-0 max-w-full items-center gap-1.5", children: [
    /* @__PURE__ */ jsx3(
      "img",
      {
        src: managedAgentRoundedIconUrl(provider),
        alt: "",
        className: "workspace-agent-message-center__provider-icon size-5 shrink-0 rounded-full",
        decoding: "async",
        loading: "lazy",
        draggable: false,
        "aria-hidden": "true"
      }
    ),
    /* @__PURE__ */ jsx3("span", { className: "workspace-agent-message-center__provider-name min-w-0 truncate text-[var(--text-secondary)]", children: label })
  ] });
}
function statusClass(item) {
  if (isWaitingMessageCenterItem(item)) {
    return "waiting";
  }
  if (item.status === "idle") {
    return "completed";
  }
  return item.status;
}
function messageCenterStatusTone(item) {
  if (isWaitingMessageCenterItem(item)) {
    return "amber";
  }
  if (item.status === "completed" || item.status === "idle") {
    return "green";
  }
  if (item.status === "canceled") {
    return "amber";
  }
  if (item.status === "failed") {
    return "red";
  }
  if (item.status === "working") {
    return "blue";
  }
  return "neutral";
}

// agent-message-center/WorkspaceAgentMessageCenterPanel.tsx
import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
var MESSAGE_CENTER_TOOLTIP_DELAY_MS = 300;
var WorkspaceAgentMessageCenterPanel = memo(
  function WorkspaceAgentMessageCenterPanel2({
    open,
    i18n,
    locale,
    model,
    highlightedItemId = null,
    portalContainer = null,
    onClose,
    onHighlightedItemSettled,
    onLinkAction,
    onNotificationActioned,
    onOpenChat,
    onSubmitPrompt
  }) {
    "use memo";
    return /* @__PURE__ */ jsx4(AgentGuiI18nProvider, { runtime: i18n, locale, children: /* @__PURE__ */ jsx4(
      WorkspaceAgentMessageCenterPanelContent,
      {
        open,
        model,
        highlightedItemId,
        portalContainer,
        onClose,
        onHighlightedItemSettled,
        onLinkAction,
        onNotificationActioned,
        onOpenChat,
        onSubmitPrompt
      }
    ) });
  }
);
function WorkspaceAgentMessageCenterPanelContent({
  open,
  model,
  highlightedItemId = null,
  portalContainer = null,
  onClose,
  onHighlightedItemSettled,
  onLinkAction,
  onNotificationActioned,
  onOpenChat,
  onSubmitPrompt
}) {
  "use memo";
  const { t } = useTranslation();
  const [groupBy, setGroupBy] = useState2("priority");
  const [statusFilters, setStatusFilters] = useState2(null);
  const [providerFilters, setProviderFilters] = useState2(
    null
  );
  const [expandedStackIds, setExpandedStackIds] = useState2(
    () => /* @__PURE__ */ new Set()
  );
  const [submittingPromptKey, setSubmittingPromptKey] = useState2(
    null
  );
  const itemNodesRef = useRef2(/* @__PURE__ */ new Map());
  const lastScrolledHighlightedItemIdRef = useRef2(null);
  const lastFilterResetHighlightedItemIdRef = useRef2(null);
  const statusOptions = useMemo(
    () => buildMessageCenterStatusOptions(model.counts, t),
    [model.counts, t]
  );
  const providerOptions = useMemo(
    () => buildMessageCenterProviderOptions(model.items),
    [model.items]
  );
  const visibleItems = useMemo(
    () => model.items.filter(
      (item) => itemMatchesViewFilters({
        item,
        providerFilters,
        statusFilters
      })
    ),
    [model.items, providerFilters, statusFilters]
  );
  const itemGroups = useMemo(
    () => groupMessageCenterItems(visibleItems, groupBy, t),
    [groupBy, t, visibleItems]
  );
  const highlightedItem = useMemo(
    () => highlightedItemId ? model.items.find((item) => item.id === highlightedItemId) ?? null : null,
    [highlightedItemId, model.items]
  );
  const activeStatusSummary = statusFilterSummary(statusFilters, statusOptions);
  const hasActiveFilters = statusFilters !== null || providerFilters !== null;
  const headerSummary = useMemo(() => {
    if (hasActiveFilters) {
      return t("agentHost.workspaceAgentMessageCenterSummaryFiltered", {
        count: visibleItems.length,
        total: model.counts.all
      });
    }
    if (model.counts.waiting > 0) {
      return t("agentHost.workspaceAgentMessageCenterSummaryWaiting", {
        count: model.counts.all,
        waiting: model.counts.waiting
      });
    }
    if (model.counts.completed > 0) {
      return t("agentHost.workspaceAgentMessageCenterSummaryCompleted", {
        count: model.counts.all,
        completed: model.counts.completed
      });
    }
    return t("agentHost.workspaceAgentMessageCenterSummaryCount", {
      count: model.counts.all
    });
  }, [
    hasActiveFilters,
    model.counts.all,
    model.counts.completed,
    model.counts.waiting,
    t,
    visibleItems.length
  ]);
  const submitPrompt = useCallback2(
    async (item, input) => {
      const promptKey = `${item.agentSessionId}:${input.requestId}`;
      setSubmittingPromptKey(promptKey);
      try {
        const notificationAction = resolveMessageCenterNotificationAction(
          item,
          input
        );
        if (notificationAction) {
          onNotificationActioned?.({
            action: notificationAction,
            provider: item.provider
          });
        }
        await onSubmitPrompt({
          ...input,
          agentSessionId: item.agentSessionId
        });
      } finally {
        setSubmittingPromptKey(
          (current) => current === promptKey ? null : current
        );
      }
    },
    [onNotificationActioned, onSubmitPrompt]
  );
  const setItemNode = useCallback2(
    (itemId, node) => {
      if (node) {
        itemNodesRef.current.set(itemId, node);
      } else {
        itemNodesRef.current.delete(itemId);
      }
    },
    []
  );
  const toggleStatusFilter = useCallback2(
    (status) => {
      setStatusFilters((current) => {
        const next = new Set(
          current ?? statusOptions.map((option) => option.value)
        );
        if (next.has(status)) {
          next.delete(status);
        } else {
          next.add(status);
        }
        return next.size === statusOptions.length ? null : next;
      });
    },
    [statusOptions]
  );
  const toggleProviderFilter = useCallback2(
    (provider) => {
      setProviderFilters((current) => {
        const next = new Set(
          current ?? providerOptions.map((option) => option.value)
        );
        if (next.has(provider)) {
          next.delete(provider);
        } else {
          next.add(provider);
        }
        return next.size === providerOptions.length ? null : next;
      });
    },
    [providerOptions]
  );
  const clearFilters = useCallback2(() => {
    setStatusFilters(null);
    setProviderFilters(null);
  }, []);
  const expandStack = useCallback2((groupId) => {
    setExpandedStackIds((current) => {
      if (current.has(groupId)) {
        return current;
      }
      const next = new Set(current);
      next.add(groupId);
      return next;
    });
  }, []);
  const collapseStack = useCallback2((groupId) => {
    setExpandedStackIds((current) => {
      if (!current.has(groupId)) {
        return current;
      }
      const next = new Set(current);
      next.delete(groupId);
      return next;
    });
  }, []);
  useLayoutEffect2(() => {
    if (!open || !highlightedItem) {
      return;
    }
    if (lastFilterResetHighlightedItemIdRef.current === highlightedItem.id) {
      return;
    }
    if (itemMatchesViewFilters({
      item: highlightedItem,
      providerFilters,
      statusFilters
    })) {
      return;
    }
    lastFilterResetHighlightedItemIdRef.current = highlightedItem.id;
    setStatusFilters(null);
    setProviderFilters(null);
  }, [highlightedItem, open, providerFilters, statusFilters]);
  useLayoutEffect2(() => {
    if (!open || !highlightedItemId) {
      return;
    }
    for (const group of itemGroups) {
      for (const stack of partitionMessageCenterItemsByAgentUser(group.items)) {
        if (stack.items.length > 1 && stack.items.some((item) => item.id === highlightedItemId)) {
          expandStack(`${group.id}:${stack.id}`);
          return;
        }
      }
    }
  }, [expandStack, highlightedItemId, itemGroups, open]);
  useLayoutEffect2(() => {
    if (!open || !highlightedItemId) {
      lastScrolledHighlightedItemIdRef.current = null;
      return;
    }
    if (highlightedItem && !itemMatchesViewFilters({
      item: highlightedItem,
      providerFilters,
      statusFilters
    })) {
      return;
    }
    if (lastScrolledHighlightedItemIdRef.current === highlightedItemId) {
      return;
    }
    const target = itemNodesRef.current.get(highlightedItemId);
    if (!target) {
      return;
    }
    lastScrolledHighlightedItemIdRef.current = highlightedItemId;
    target.scrollIntoView({ behavior: "smooth", block: "center" });
    target.focus({ preventScroll: true });
  }, [
    expandedStackIds,
    highlightedItem,
    highlightedItemId,
    open,
    providerFilters,
    statusFilters,
    visibleItems
  ]);
  useEffect2(() => {
    if (!open || !highlightedItemId) {
      return void 0;
    }
    const timeoutId = window.setTimeout(() => {
      onHighlightedItemSettled?.(highlightedItemId);
    }, 3200);
    return () => {
      window.clearTimeout(timeoutId);
    };
  }, [highlightedItemId, onHighlightedItemSettled, open]);
  return /* @__PURE__ */ jsx4(
    Drawer,
    {
      open,
      direction: "right",
      handleOnly: true,
      onOpenChange: (nextOpen) => {
        if (!nextOpen) {
          onClose();
        }
      },
      children: /* @__PURE__ */ jsx4(
        DrawerContent,
        {
          className: cn4(
            "t-modal nodrag min-h-0 w-[min(440px,calc(100vw-16px))] max-w-none overflow-hidden rounded-none border-y-0 border-r-0 bg-[var(--background-panel)] text-[var(--text-primary)] shadow-side-panel data-[vaul-drawer-direction=right]:rounded-none",
            "[-webkit-app-region:no-drag]"
          ),
          "data-testid": "workspace-agent-message-center",
          portalContainer: portalContainer ?? void 0,
          showOverlay: false,
          "aria-label": t("agentHost.workspaceAgentMessageCenterTitle"),
          children: /* @__PURE__ */ jsxs3(TooltipProvider, { delayDuration: MESSAGE_CENTER_TOOLTIP_DELAY_MS, children: [
            /* @__PURE__ */ jsx4("div", { className: "flex-none border-b border-[var(--border-1)] px-3.5 pt-3 pb-3", children: /* @__PURE__ */ jsxs3("div", { className: "flex min-w-0 items-center justify-between gap-3", children: [
              /* @__PURE__ */ jsxs3("div", { className: "min-w-0", children: [
                /* @__PURE__ */ jsx4("div", { className: "truncate text-[13px] font-semibold leading-5 text-[var(--text-primary)]", children: t("agentHost.workspaceAgentMessageCenterTitle") }),
                /* @__PURE__ */ jsx4("div", { className: "truncate text-[11px] leading-4 text-[var(--text-tertiary)]", children: headerSummary })
              ] }),
              /* @__PURE__ */ jsx4(
                MessageCenterViewMenu,
                {
                  filtersActive: hasActiveFilters,
                  groupBy,
                  providerFilters,
                  providerOptions,
                  statusFilters,
                  statusOptions,
                  onClearFilters: clearFilters,
                  onGroupByChange: setGroupBy,
                  onProviderToggle: toggleProviderFilter,
                  onStatusToggle: toggleStatusFilter
                }
              )
            ] }) }),
            /* @__PURE__ */ jsx4(
              AgentVerticalScrollArea,
              {
                className: "min-h-0 flex-1",
                viewportClassName: "flex h-full w-full flex-col px-3.5 pt-4 pb-4",
                scrollbarClassName: "top-4 bottom-4",
                syncKey: `${groupBy}:${activeStatusSummary}:${visibleItems.map((item) => item.id).join("|")}`,
                children: visibleItems.length > 0 ? /* @__PURE__ */ jsx4("div", { className: "flex w-full min-w-0 flex-col gap-4", children: itemGroups.map((group) => /* @__PURE__ */ jsxs3(
                  "section",
                  {
                    className: "flex min-w-0 flex-col gap-2.5",
                    "aria-label": `${group.label} ${group.items.length}`,
                    children: [
                      /* @__PURE__ */ jsx4("div", { className: "flex min-w-0 items-center justify-between gap-3 px-0.5", children: /* @__PURE__ */ jsx4(MessageCenterGroupHeading, { group }) }),
                      (() => {
                        const renderCard = (item, options = {}) => {
                          const highlighted = item.id === highlightedItemId;
                          const card = /* @__PURE__ */ jsx4(
                            MessageCenterCard,
                            {
                              cardRef: (node) => setItemNode(item.id, node),
                              highlighted,
                              item,
                              isSubmitting: submittingPromptKey === `${item.agentSessionId}:${item.pendingPrompt?.requestId}`,
                              onLinkAction,
                              onOpenChat,
                              onSubmitPrompt: (input) => void submitPrompt(item, input)
                            },
                            item.agentSessionId
                          );
                          if (options.stackedIndex === void 0) {
                            return card;
                          }
                          return /* @__PURE__ */ jsx4(
                            "div",
                            {
                              className: "min-w-0 motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-top-1 motion-safe:duration-200 motion-safe:ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:animate-none",
                              style: {
                                animationDelay: `${Math.min(options.stackedIndex * 24, 96)}ms`
                              },
                              children: card
                            },
                            item.agentSessionId
                          );
                        };
                        return partitionMessageCenterItemsByAgentUser(
                          group.items
                        ).map((stack) => {
                          const firstItem = stack.items[0];
                          if (!firstItem) {
                            return null;
                          }
                          if (stack.items.length === 1) {
                            return renderCard(firstItem);
                          }
                          const stackId = group.id === stack.id ? stack.id : `${group.id}:${stack.id}`;
                          return /* @__PURE__ */ jsx4(
                            MessageCenterStack,
                            {
                              expanded: expandedStackIds.has(stackId),
                              groupId: stackId,
                              items: stack.items,
                              renderCard,
                              onCollapse: () => collapseStack(stackId),
                              onExpand: () => expandStack(stackId)
                            },
                            stackId
                          );
                        });
                      })()
                    ]
                  },
                  group.id
                )) }) : model.items.length > 0 ? /* @__PURE__ */ jsxs3("div", { className: "flex min-h-0 flex-1 flex-col items-center justify-center gap-2.5 px-6 py-8 text-center text-[13px] text-[var(--text-tertiary)]", children: [
                  /* @__PURE__ */ jsx4("span", { children: t("agentHost.workspaceAgentMessageCenterFilteredEmpty") }),
                  /* @__PURE__ */ jsx4(
                    Button3,
                    {
                      type: "button",
                      variant: "ghost",
                      size: "sm",
                      className: "border border-[var(--line-2)] bg-[var(--background-fronted)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]",
                      onClick: clearFilters,
                      children: t("agentHost.workspaceAgentMessageCenterClearFilters")
                    }
                  )
                ] }) : /* @__PURE__ */ jsx4("div", { className: "flex min-h-0 flex-1 items-center justify-center px-6 py-8 text-center text-[13px] text-[var(--text-tertiary)]", children: t("agentHost.workspaceAgentMessageCenterEmpty") })
              }
            )
          ] })
        }
      )
    }
  );
}
var MessageCenterCard = WorkspaceAgentMessageCenterCard;
var MessageCenterStack = WorkspaceAgentMessageCenterStack;
function MessageCenterGroupHeading({
  group
}) {
  "use memo";
  if (group.provider) {
    return /* @__PURE__ */ jsxs3(
      "h3",
      {
        "aria-label": `${group.label} \xB7 ${group.items.length}`,
        className: "flex min-w-0 items-center gap-1.5 text-[11px] font-normal leading-4 text-[var(--text-tertiary)]",
        title: `${group.label} \xB7 ${group.items.length}`,
        children: [
          group.identity ? /* @__PURE__ */ jsx4(
            MessageCenterIdentityLabel,
            {
              identity: group.identity,
              provider: group.provider
            }
          ) : /* @__PURE__ */ jsxs3("span", { className: "inline-flex min-w-0 items-center gap-1.5", children: [
            /* @__PURE__ */ jsx4(
              MessageCenterIdentityAvatarMark,
              {
                identity: null,
                provider: group.provider,
                userId: group.userId ?? null
              }
            ),
            /* @__PURE__ */ jsx4("span", { className: "min-w-0 truncate", children: group.label })
          ] }),
          /* @__PURE__ */ jsxs3("span", { className: "shrink-0", children: [
            "\xB7 ",
            group.items.length
          ] })
        ]
      }
    );
  }
  return /* @__PURE__ */ jsxs3("h3", { className: "truncate text-[11px] font-normal leading-4 text-[var(--text-tertiary)]", children: [
    group.label,
    " \xB7 ",
    group.items.length
  ] });
}
export {
  AgentInteractivePromptSurface,
  WorkspaceAgentMessageCenterCard,
  WorkspaceAgentMessageCenterPanel,
  approvalOptionDisplayLabel,
  buildWorkspaceAgentInteractivePromptLabels,
  buildWorkspaceAgentMessageCenterModel,
  getPromptToolDetails,
  isPromptRequestIdTitle,
  isWaitingMessageCenterItem,
  managedAgentRoundedIconUrl
};
//# sourceMappingURL=index.js.map