"use client"; import type { ToolCallMessagePartProps } from "@assistant-ui/react"; import { useSetAtom } from "jotai"; import { CornerDownLeftIcon, MailIcon, Pen, UserIcon, UsersIcon } from "lucide-react"; import { useCallback, useEffect, useState } from "react"; import type { ExtraField } from "@/atoms/chat/hitl-edit-panel.atom"; import { openHitlEditPanelAtom } from "@/atoms/chat/hitl-edit-panel.atom"; import { PlateEditor } from "@/components/editor/plate-editor"; import { TextShimmerLoader } from "@/components/prompt-kit/loader"; import { Button } from "@/components/ui/button"; import { useHitlPhase } from "@/hooks/use-hitl-phase"; import type { HitlDecision, InterruptResult } from "@/lib/hitl"; import { isInterruptResult, useHitlDecision } from "@/lib/hitl"; interface GmailAccount { id: number; name: string; email: string; auth_expired?: boolean; } interface GmailMessage { message_id: string; thread_id?: string; subject: string; sender: string; date: string; connector_id: number; document_id: number; } type GmailUpdateDraftContext = { account?: GmailAccount; email?: GmailMessage; draft_id?: string; existing_body?: string; error?: string; }; interface SuccessResult { status: "success"; draft_id?: string; message?: string; } interface ErrorResult { status: "error"; message: string; } interface NotFoundResult { status: "not_found"; message: string; } interface AuthErrorResult { status: "auth_error"; message: string; connector_type?: string; } interface InsufficientPermissionsResult { status: "insufficient_permissions"; connector_id: number; message: string; } type UpdateGmailDraftResult = | InterruptResult | SuccessResult | ErrorResult | NotFoundResult | InsufficientPermissionsResult | AuthErrorResult; function isErrorResult(result: unknown): result is ErrorResult { return ( typeof result === "object" && result !== null && "status" in result && (result as ErrorResult).status === "error" ); } function isNotFoundResult(result: unknown): result is NotFoundResult { return ( typeof result === "object" && result !== null && "status" in result && (result as NotFoundResult).status === "not_found" ); } function isAuthErrorResult(result: unknown): result is AuthErrorResult { return ( typeof result === "object" && result !== null && "status" in result && (result as AuthErrorResult).status === "auth_error" ); } function isInsufficientPermissionsResult(result: unknown): result is InsufficientPermissionsResult { return ( typeof result === "object" && result !== null && "status" in result && (result as InsufficientPermissionsResult).status === "insufficient_permissions" ); } function ApprovalCard({ args, interruptData, onDecision, }: { args: { draft_subject_or_id: string; body: string; to?: string; subject?: string; cc?: string; bcc?: string; }; interruptData: InterruptResult; onDecision: (decision: HitlDecision) => void; }) { const { phase, setProcessing, setRejected } = useHitlPhase(interruptData); const [isPanelOpen, setIsPanelOpen] = useState(false); const openHitlEditPanel = useSetAtom(openHitlEditPanelAtom); const [pendingEdits, setPendingEdits] = useState<{ subject: string; body: string; to: string; cc: string; bcc: string; } | null>(null); const context = interruptData.context; const account = context?.account; const email = context?.email; const draftId = context?.draft_id; const existingBody = context?.existing_body; const reviewConfig = interruptData.review_configs?.[0]; const allowedDecisions = reviewConfig?.allowed_decisions ?? ["approve", "reject"]; const canEdit = allowedDecisions.includes("edit"); const currentSubject = pendingEdits?.subject ?? args.subject ?? email?.subject ?? args.draft_subject_or_id; const currentBody = pendingEdits?.body ?? args.body; const currentTo = pendingEdits?.to ?? args.to ?? ""; const currentCc = pendingEdits?.cc ?? args.cc ?? ""; const currentBcc = pendingEdits?.bcc ?? args.bcc ?? ""; const editableBody = currentBody || existingBody || ""; const handleApprove = useCallback(() => { if (phase !== "pending") return; if (isPanelOpen) return; if (!allowedDecisions.includes("approve")) return; const isEdited = pendingEdits !== null; setProcessing(); onDecision({ type: isEdited ? "edit" : "approve", edited_action: { name: interruptData.action_requests[0].name, args: { message_id: email?.message_id, draft_id: draftId, to: currentTo, subject: currentSubject, body: editableBody, cc: currentCc, bcc: currentBcc, connector_id: email?.connector_id ?? account?.id, }, }, }); }, [ phase, isPanelOpen, allowedDecisions, setProcessing, onDecision, interruptData, email, account?.id, draftId, pendingEdits, currentSubject, editableBody, currentTo, currentCc, currentBcc, ]); useEffect(() => { const handler = (e: KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) { handleApprove(); } }; window.addEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler); }, [handleApprove]); return (
{/* Header */}

{phase === "rejected" ? "Draft Update Rejected" : phase === "processing" || phase === "complete" ? "Draft Update Approved" : "Update Gmail Draft"}

{phase === "processing" ? ( ) : phase === "complete" ? (

{pendingEdits ? "Draft updated with your changes" : "Draft updated"}

) : phase === "rejected" ? (

Draft update was cancelled

) : (

Requires your approval to proceed

)}
{phase === "pending" && canEdit && ( )}
{/* Context — account and draft info in pending/processing/complete */} {phase !== "rejected" && context && ( <>
{context.error ? (

{context.error}

) : ( <> {account && (

Gmail Account

{account.name}
)} {email && (

Draft to Update

{email.subject}
)} )}
)} {/* Email headers + body preview — visible in ALL phases */}
{currentTo && (
To: {currentTo}
)} {currentCc && currentCc.trim() !== "" && (
CC: {currentCc}
)} {currentBcc && currentBcc.trim() !== "" && (
BCC: {currentBcc}
)}
{currentSubject != null && (

{currentSubject}

)} {editableBody ? (
) : null}
{/* Action buttons — only in pending */} {phase === "pending" && ( <>
{allowedDecisions.includes("approve") && ( )} {allowedDecisions.includes("reject") && ( )}
)}
); } function ErrorCard({ result }: { result: ErrorResult }) { return (

Failed to update Gmail draft

{result.message}

); } function AuthErrorCard({ result }: { result: AuthErrorResult }) { return (

Gmail authentication expired

{result.message}

); } function InsufficientPermissionsCard({ result }: { result: InsufficientPermissionsResult }) { return (

Additional Gmail permissions required

{result.message}

); } function NotFoundCard({ result }: { result: NotFoundResult }) { return (

Draft not found

{result.message}

); } function SuccessCard({ result }: { result: SuccessResult }) { return (

{result.message || "Gmail draft updated successfully"}

); } export const UpdateGmailDraftToolUI = ({ args, result, }: ToolCallMessagePartProps< { draft_subject_or_id: string; body: string; to?: string; subject?: string; cc?: string; bcc?: string; }, UpdateGmailDraftResult >) => { const { dispatch } = useHitlDecision(); if (!result) return null; if (isInterruptResult(result)) { return ( } onDecision={(decision) => dispatch([decision])} /> ); } if ( typeof result === "object" && result !== null && "status" in result && (result as { status: string }).status === "rejected" ) { return null; } if (isAuthErrorResult(result)) return ; if (isInsufficientPermissionsResult(result)) return ; if (isNotFoundResult(result)) return ; if (isErrorResult(result)) return ; return ; };