All files / components/transcript tool.ts

98.11% Statements 104/106
87.5% Branches 91/104
100% Functions 16/16
100% Lines 95/95

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 2815x 5x               5x           5x 5x   5x           5x                       4x 4x   4x   1x         2x 3x   9x     3x 13x 12x     18x 40x   40x         7x 7x   6x         3x   2x       1x       1x 1x             3x 3x 2x 2x     6x     3x     7x 7x 1x     6x   6x   2x 2x               1x 1x               1x 1x               1x 1x               1x                 7x 7x 1x     6x 6x   6x   2x                 1x   1x         1x   1x                                 9x 9x 2x     7x 7x 1x     6x 6x 1x     5x     5x 4x 3x 2x 1x   4x 4x 4x 4x     4x         4x     4x 4x   4x                         8x 13x 9x     4x   4x           5x 5x 5x 5x   5x 1x     4x    
import { isToolUIPart, type UIMessage } from "ai";
import { CHAT_TRANSCRIPT_COPY } from "@/constants/chat";
import type {
  ApproveTeamRequestInput,
  CancelTimeOffInput,
  RejectTeamRequestInput,
  SubmitTimeOffInput,
} from "@/types/tool";
import type { MessageMetadata } from "@/agents/chat-core";
import { formatHumanDateRange } from "@/utils/date";
import {
  asRecord,
  asString,
  asOptionalString,
  compactLeaveTypeLabel,
} from "./utils";
import { leaveTypeLabel } from "@/utils/leave";
 
export const TOOL_STATUS_TONE_CLASS: Record<"success" | "error" | "neutral", string> = {
  error:   "border border-rose-400/28 bg-rose-500/12 text-rose-200 font-dm-sans shadow-tool-error",
  success: "border border-emerald-400/28 bg-emerald-500/12 text-emerald-100 font-dm-sans shadow-tool-success",
  neutral: "border border-white/10 bg-white/7 text-white/72 font-dm-sans shadow-tool-neutral",
};
 
export const TOOL_FRIENDLY_LABEL_BY_NAME: Record<string, string> = {
  get_my_time_off_balance: "My leave balance",
  list_my_time_off_requests: "My time-off requests",
  list_employees: "All employees",
  list_team_members: "Team members",
  list_team_time_off_requests: "Team time-off requests",
  submit_my_time_off_request: "Submit time-off request",
  cancel_my_time_off_request: "Cancel time-off request",
  approve_team_time_off_request: "Approve team request",
  reject_team_time_off_request: "Reject team request",
};
 
export function getToolParts(message: UIMessage) {
  const toolParts = message.parts.filter((part) => isToolUIPart(part));
 
  return Array.from(
    new Map(
      toolParts.map((part, index) => [part.toolCallId ?? `tool-${index}`, part]),
    ).values(),
  );
}
 
export function humanizeToolName(toolName: string) {
  return toolName
    .replaceAll("_", " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}
 
export function getFriendlyToolLabelByName(toolName: string | null) {
  if (!toolName) return CHAT_TRANSCRIPT_COPY.toolFallbackLabel;
  return TOOL_FRIENDLY_LABEL_BY_NAME[toolName] ?? humanizeToolName(toolName);
}
 
export function getToolName(part: UIMessage["parts"][number]) {
  Iif (!isToolUIPart(part)) return null;
 
  return part.type === "dynamic-tool"
    ? part.toolName
    : part.type.replace("tool-", "");
}
 
export function getToolStepText(part: UIMessage["parts"][number]) {
  if (!isToolUIPart(part)) return null;
 
  switch (part.state) {
    case "input-streaming":
    case "input-available":
    case "output-available":
    case "output-error":
      return `Call tool: ${getFriendlyToolLabelByName(getToolName(part))}`;
    case "approval-responded":
      return part.approval.approved
        ? `Call tool: ${getFriendlyToolLabelByName(getToolName(part))}`
        : null;
    default:
      return null;
  }
}
 
export function isDatePickerToolPart(part: UIMessage["parts"][number]): boolean {
  return (
    isToolUIPart(part) &&
    getToolName(part) === "collect_date_range" &&
    part.state === "output-available"
  );
}
 
export function getDatePickerLeaveType(part: UIMessage["parts"][number]): string {
  if (!isToolUIPart(part)) return "";
  const input = part.input as Record<string, unknown> | null;
  return typeof input?.leaveType === "string" ? input.leaveType : "";
}
 
export function isApprovalRequestedToolPart(
  part: UIMessage["parts"][number],
): part is Extract<UIMessage["parts"][number], { approval: { id: string } }> {
  return isToolUIPart(part) && part.state === "approval-requested";
}
 
export function getApprovalCardContent(part: UIMessage["parts"][number]) {
  if (!isToolUIPart(part) || part.state !== "approval-requested") {
    return null;
  }
 
  const toolName = getToolName(part);
 
  switch (toolName) {
    case "submit_my_time_off_request": {
      const i = part.input as SubmitTimeOffInput;
      return {
        title: CHAT_TRANSCRIPT_COPY.toolApproval.submitRequest.title,
        description: `${leaveTypeLabel(i.leaveType)} from ${i.startDate ?? "—"} to ${i.endDate ?? "—"}${i.reason ? `. Reason: ${i.reason}.` : "."}`,
        confirmLabel: CHAT_TRANSCRIPT_COPY.toolApproval.submitRequest.confirmLabel,
        cancelLabel: CHAT_TRANSCRIPT_COPY.toolApproval.submitRequest.cancelLabel,
      };
    }
    case "cancel_my_time_off_request": {
      const i = part.input as CancelTimeOffInput;
      return {
        title: CHAT_TRANSCRIPT_COPY.toolApproval.cancelRequest.title,
        description: `${CHAT_TRANSCRIPT_COPY.toolApproval.cancelRequest.descriptionPrefix} ${i.requestQuery ?? CHAT_TRANSCRIPT_COPY.toolApproval.selectedRequestFallback}.`,
        confirmLabel: CHAT_TRANSCRIPT_COPY.toolApproval.cancelRequest.confirmLabel,
        cancelLabel: CHAT_TRANSCRIPT_COPY.toolApproval.cancelRequest.cancelLabel,
      };
    }
    case "approve_team_time_off_request": {
      const i = part.input as ApproveTeamRequestInput;
      return {
        title: CHAT_TRANSCRIPT_COPY.toolApproval.approveRequest.title,
        description: `${CHAT_TRANSCRIPT_COPY.toolApproval.approveRequest.descriptionPrefix} ${i.requestQuery ?? CHAT_TRANSCRIPT_COPY.toolApproval.selectedRequestFallback}${i.comment ? `. ${CHAT_TRANSCRIPT_COPY.toolApproval.approveRequest.commentLabel} ${i.comment}.` : "."}`,
        confirmLabel: CHAT_TRANSCRIPT_COPY.toolApproval.approveRequest.confirmLabel,
        cancelLabel: CHAT_TRANSCRIPT_COPY.toolApproval.approveRequest.cancelLabel,
      };
    }
    case "reject_team_time_off_request": {
      const i = part.input as RejectTeamRequestInput;
      return {
        title: CHAT_TRANSCRIPT_COPY.toolApproval.rejectRequest.title,
        description: `${CHAT_TRANSCRIPT_COPY.toolApproval.rejectRequest.descriptionPrefix} ${i.requestQuery ?? CHAT_TRANSCRIPT_COPY.toolApproval.selectedRequestFallback}${i.comment ? `. ${CHAT_TRANSCRIPT_COPY.toolApproval.rejectRequest.reasonLabel} ${i.comment}.` : "."}`,
        confirmLabel: CHAT_TRANSCRIPT_COPY.toolApproval.rejectRequest.confirmLabel,
        cancelLabel: CHAT_TRANSCRIPT_COPY.toolApproval.rejectRequest.cancelLabel,
      };
    }
    default:
      return {
        title: CHAT_TRANSCRIPT_COPY.toolApproval.default.title,
        description: CHAT_TRANSCRIPT_COPY.toolApproval.default.description,
        confirmLabel: CHAT_TRANSCRIPT_COPY.toolApproval.default.confirmLabel,
        cancelLabel: CHAT_TRANSCRIPT_COPY.toolApproval.default.cancelLabel,
      };
  }
}
 
export function getToolStatusCopy(part: UIMessage["parts"][number]) {
  if (!isToolUIPart(part)) {
    return null;
  }
 
  const toolName = getToolName(part);
  const shortLabel = getFriendlyToolLabelByName(toolName);
 
  switch (part.state) {
    case "approval-responded":
      return {
        tone: "neutral" as const,
        text: part.approval.approved
          ? `${shortLabel} ${CHAT_TRANSCRIPT_COPY.toolStatus.confirmedSuffix}`
          : `${shortLabel} ${CHAT_TRANSCRIPT_COPY.toolStatus.cancelledSuffix}`,
      };
    case "output-error":
      // Never surface raw errorText (may contain Zod/JSON validation details).
      // The agent's text response already explains what went wrong to the user.
      return null;
    case "output-denied":
      return {
        tone: "neutral" as const,
        text: `${shortLabel} ${CHAT_TRANSCRIPT_COPY.toolStatus.cancelledSuffix}`,
      };
    case "output-available":
      return null;
    default:
      return null;
  }
}
 
export type MutationSuccessCard = {
  key: string;
  title: string;
  employeeName: string;
  employeeAvatar?: string;
  team?: string;
  leaveTypeLabel: string;
  dateRange: string;
  days: number;
  rawStatus: string;
  reviewComment?: string;
};
 
export function getMutationSuccessCard(part: UIMessage["parts"][number]) {
  if (!isToolUIPart(part) || part.state !== "output-available" || part.preliminary) {
    return null;
  }
 
  const output = asRecord(part.output);
  if (!output || output.ok !== true) {
    return null;
  }
 
  const request = asRecord(output.request);
  if (!request) {
    return null;
  }
 
  const toolName = getToolName(part);
 
  let title: string;
  if (toolName === "approve_team_time_off_request") title = "Request approved";
  else if (toolName === "reject_team_time_off_request") title = "Request rejected";
  else if (toolName === "cancel_my_time_off_request") title = "Request cancelled";
  else if (toolName === "submit_my_time_off_request") title = "Request submitted";
  else return null;
 
  const employeeName = asString(request.employeeName, "Employee");
  const employeeAvatar = asOptionalString(request.employeeAvatar)?.trim() || undefined;
  const team = asOptionalString(request.team)?.trim() || undefined;
  const label = compactLeaveTypeLabel(
    asString(request.leaveTypeLabel, asString(request.leaveType, "Leave")),
  );
  const dateRange = formatHumanDateRange(
    asString(request.startDate, ""),
    asString(request.endDate, ""),
  );
  const days =
    typeof request.days === "number" && Number.isFinite(request.days)
      ? (request.days as number)
      : 0;
  const rawStatus = asString(request.status, "");
  const reviewComment = asOptionalString(request.reviewComment)?.trim() || undefined;
 
  return {
    title,
    employeeName,
    employeeAvatar,
    team,
    leaveTypeLabel: label,
    dateRange,
    days,
    rawStatus,
    reviewComment,
  };
}
 
export function readMessageMeta(message: UIMessage) {
  if (!message.metadata || typeof message.metadata !== "object") {
    return null;
  }
 
  const metadata = message.metadata as Partial<MessageMetadata>;
 
  return {
    agent: metadata.agent ?? CHAT_TRANSCRIPT_COPY.defaultAgentName,
    agentLabel: metadata.agentLabel ?? CHAT_TRANSCRIPT_COPY.defaultAgentLabel,
  };
}
 
export function getAssistantInitials(message: UIMessage) {
  const metadata = readMessageMeta(message);
  const badgeMap = CHAT_TRANSCRIPT_COPY.assistantBadgeByAgent;
  const agent = metadata?.agent;
 
  if (agent && agent in badgeMap) {
    return badgeMap[agent as keyof typeof badgeMap];
  }
 
  return badgeMap[CHAT_TRANSCRIPT_COPY.defaultAgentName];
}