Files
simbarag/raggr-frontend/src/components/ScheduledMessagesPanel.tsx
T
ryan 5809ad3adb
CI / backend (pull_request) Successful in 42s
CI / frontend (pull_request) Failing after 7s
CI / backend (push) Successful in 41s
CI / frontend (push) Failing after 7s
Add durable chat runs, shared agent runtime, reliable jobs, history tools and citations
Shared runtime
- One agent entry point (runtime.invoke_agent_for_user / prepare_agent_turn) for
  web, email, iMessage, WhatsApp, scheduled and cron, so identity, permissions,
  memories, summaries and metrics match across channels.
- Serialize turns per checkpoint thread; /query validates input and returns 409
  while a durable run owns the conversation.

Reconnectable chat (durable runs)
- POST /runs creates an idempotent, owner-scoped run; GET .../events replays an
  ordered SSE log by cursor, so generation survives refresh and device switches.
  Stop cancels; disconnect only detaches. /stream-query is a compatibility adapter.
- Coalesce streamed deltas (150 ms) and wake same-process subscribers instead of
  polling; keep buffered text when a run is stopped.
- Drain runs on shutdown; serve via Hypercorn with a shutdown timeout covering
  the drain (and no longer in debug mode). CHAT_RUN_* settings are forwarded.

Scheduled messages and cron
- Atomic delivery claims, attempt history and explicit retries; ambiguous sends
  become "uncertain" and are never resent automatically.
- Cron triggers need a run_id/Idempotency-Key; legacy jobs need an explicit owner.
- Cancelling never rewrites a started delivery; series stop via tombstones.
  Legacy sent rows are not forked into new series. Malformed bodies return 400.

History, integrations and retrieval
- Message-content search, pinned conversations, JSON/Markdown export and a
  memory editor.
- Integration status panel and YNAB data-freshness provenance.
- Date-filtered document/note search with stable citations and a source viewer.

Migration 20 is generated by aerich.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 23:11:04 -04:00

437 lines
18 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
import { X, Clock, Send, Trash2, XCircle, RotateCcw, Repeat, Bot } from "lucide-react";
import { cn } from "../lib/utils";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Badge } from "./ui/badge";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "./ui/table";
import { useScheduledMessages } from "../hooks/useScheduledMessages";
import {
scheduledMessageService,
canRetryScheduledMessage,
type DeliveryStatus,
type ScheduledDelivery,
type ScheduledMessage,
type CreateScheduledMessage,
} from "../api/scheduledMessageService";
type Props = {
onClose: () => void;
};
const STATUS_BADGE: Record<string, "amber" | "default" | "destructive" | "muted"> = {
pending: "amber",
processing: "amber",
sending: "amber",
uncertain: "destructive",
sent: "default",
failed: "destructive",
cancelled: "muted",
};
export const DELIVERY_STATUS_LABELS: Record<DeliveryStatus, string> = {
pending: "Pending",
processing: "Processing",
sending: "Sending",
sent: "Sent",
failed: "Failed",
uncertain: "Uncertain — needs reconciliation",
cancelled: "Cancelled",
};
export const UNCERTAIN_DELIVERY_HELP = "Delivery may already have occurred. Reconcile with the provider or recipient before any resend; uncertain deliveries cannot be retried.";
export function DeliveryHistory({ deliveries }: { deliveries: ScheduledDelivery[] }) {
if (deliveries.length === 0) return <p className="text-xs text-warm-gray">No delivery attempts yet.</p>;
return (
<div className="space-y-3">
{deliveries.map((delivery) => (
<div key={delivery.id} className="rounded-xl border border-sand-light p-3 text-xs space-y-2">
<p className="break-all">Run: {delivery.run_id}</p>
<Badge variant={STATUS_BADGE[delivery.status]}>{DELIVERY_STATUS_LABELS[delivery.status]}</Badge>
{delivery.error && <p className="text-red-500 break-words">{delivery.error}</p>}
{delivery.status === "uncertain" && <p>{UNCERTAIN_DELIVERY_HELP}</p>}
{delivery.attempts.length === 0 ? <p>No attempts recorded.</p> : (
<ol className="space-y-2">
{delivery.attempts.map((attempt, index) => (
<li key={attempt.id}>
<p>Attempt {index + 1}: {DELIVERY_STATUS_LABELS[attempt.status]}</p>
<p>Started: {new Date(attempt.started_at).toLocaleString()}</p>
<p>{attempt.finished_at ? `Finished: ${new Date(attempt.finished_at).toLocaleString()}` : "Not finished"}</p>
{attempt.error && <p className="text-red-500 break-words">{attempt.error}</p>}
</li>
))}
</ol>
)}
</div>
))}
</div>
);
}
export const ScheduledMessagesPanel = ({ onClose }: Props) => {
const { messages, loading, error: listError, refresh } = useScheduledMessages();
const [channel, setChannel] = useState<"imessage" | "email">("imessage");
const [recipient, setRecipient] = useState("");
const [subject, setSubject] = useState("");
const [content, setContent] = useState("");
const [scheduledAt, setScheduledAt] = useState("");
const [recurrence, setRecurrence] = useState<"none" | "daily" | "weekly" | "monthly">("none");
const [useAgent, setUseAgent] = useState(false);
const [error, setError] = useState("");
const [submitting, setSubmitting] = useState(false);
const [busyId, setBusyId] = useState<string | null>(null);
const actionInFlight = useRef(false);
const [historyId, setHistoryId] = useState<string | null>(null);
const [deliveries, setDeliveries] = useState<ScheduledDelivery[]>([]);
const [historyLoading, setHistoryLoading] = useState(false);
const [historyError, setHistoryError] = useState("");
const [historyVersion, setHistoryVersion] = useState(0);
useEffect(() => {
if (!historyId) return;
let active = true;
setHistoryLoading(true);
setHistoryError("");
setDeliveries([]);
scheduledMessageService.deliveries(historyId)
.then((result) => { if (active) setDeliveries(result); })
.catch((err) => {
if (active) setHistoryError(err instanceof Error ? err.message : "Failed to load delivery history");
})
.finally(() => { if (active) setHistoryLoading(false); });
return () => { active = false; };
}, [historyId, historyVersion]);
const handleCreate = async () => {
setError("");
if (!recipient || !content || !scheduledAt) {
setError("Recipient, content, and scheduled time are required.");
return;
}
if (channel === "email" && !subject) {
setError("Subject is required for email.");
return;
}
setSubmitting(true);
try {
const data: CreateScheduledMessage = {
recipient,
channel,
content,
scheduled_at: new Date(scheduledAt).toISOString(),
recurrence,
use_agent: useAgent,
};
if (channel === "email") data.subject = subject;
await scheduledMessageService.create(data);
setRecipient("");
setSubject("");
setContent("");
setScheduledAt("");
setRecurrence("none");
setUseAgent(false);
refresh();
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to schedule message");
} finally {
setSubmitting(false);
}
};
const runAction = async (message: ScheduledMessage, action: "cancel" | "delete" | "retry") => {
if (actionInFlight.current) return;
if (action === "retry" && !canRetryScheduledMessage(message)) {
setError("Only failed, retryable deliveries can be retried.");
return;
}
actionInFlight.current = true;
setBusyId(message.id);
setError("");
try {
if (action === "cancel") await scheduledMessageService.update(message.id, { status: "cancelled" });
if (action === "delete") {
await scheduledMessageService.remove(message.id);
if (historyId === message.id) setHistoryId(null);
}
if (action === "retry") await scheduledMessageService.retry(message.id);
} catch (err) {
setError(err instanceof Error ? err.message : `Failed to ${action} scheduled message`);
} finally {
// A rejected retry can still have changed the delivery to failed or uncertain.
await refresh();
setHistoryVersion((version) => version + 1);
actionInFlight.current = false;
setBusyId(null);
}
};
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-charcoal/40 backdrop-blur-sm"
onClick={(e) => e.target === e.currentTarget && onClose()}
>
<div
className={cn(
"bg-warm-white rounded-3xl shadow-2xl shadow-charcoal/20",
"w-full max-w-3xl mx-4 max-h-[85vh] flex flex-col",
"border border-sand-light/60",
)}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-sand-light/60">
<div className="flex items-center gap-2.5">
<div className="w-8 h-8 rounded-xl bg-amber-pale flex items-center justify-center">
<Clock size={14} className="text-amber-glow" />
</div>
<h2 className="text-sm font-semibold text-charcoal">
Scheduled Messages
</h2>
</div>
<button
onClick={onClose}
className="w-7 h-7 rounded-lg flex items-center justify-center text-warm-gray hover:text-charcoal hover:bg-cream-dark transition-colors cursor-pointer"
>
<X size={15} />
</button>
</div>
<div className="overflow-y-auto flex-1 rounded-b-3xl">
{/* Create form */}
<div className="px-6 py-5 border-b border-sand-light/60 space-y-3">
<div className="flex items-center gap-2">
<button
onClick={() => setChannel("imessage")}
className={cn(
"px-3 py-1.5 rounded-lg text-xs font-medium transition-colors cursor-pointer",
channel === "imessage"
? "bg-leaf-pale text-leaf-dark"
: "bg-sand-light/40 text-warm-gray hover:text-charcoal",
)}
>
iMessage
</button>
<button
onClick={() => setChannel("email")}
className={cn(
"px-3 py-1.5 rounded-lg text-xs font-medium transition-colors cursor-pointer",
channel === "email"
? "bg-leaf-pale text-leaf-dark"
: "bg-sand-light/40 text-warm-gray hover:text-charcoal",
)}
>
Email
</button>
</div>
<div className="flex gap-2">
<Input
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
placeholder={channel === "imessage" ? "+15551234567" : "user@example.com"}
className="flex-1"
/>
<Input
type="datetime-local"
value={scheduledAt}
onChange={(e) => setScheduledAt(e.target.value)}
className="w-52"
/>
</div>
<div className="flex items-center gap-2">
<Repeat size={12} className="text-warm-gray" />
<span className="text-xs text-warm-gray">Repeat:</span>
{(["none", "daily", "weekly", "monthly"] as const).map((r) => (
<button
key={r}
onClick={() => setRecurrence(r)}
className={cn(
"px-2.5 py-1 rounded-lg text-xs font-medium transition-colors cursor-pointer",
recurrence === r
? "bg-amber-pale text-amber-glow"
: "bg-sand-light/40 text-warm-gray hover:text-charcoal",
)}
>
{r === "none" ? "Once" : r.charAt(0).toUpperCase() + r.slice(1)}
</button>
))}
</div>
<div className="flex items-center gap-2">
<button
onClick={() => setUseAgent(!useAgent)}
className={cn(
"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors cursor-pointer",
useAgent
? "bg-leaf-pale text-leaf-dark"
: "bg-sand-light/40 text-warm-gray hover:text-charcoal",
)}
>
<Bot size={12} />
Ask Simba
</button>
<span className="text-xs text-warm-gray">
{useAgent ? "Content is a prompt — Simba's response will be sent" : "Content sent as-is"}
</span>
</div>
{channel === "email" && (
<Input
value={subject}
onChange={(e) => setSubject(e.target.value)}
placeholder="Subject"
/>
)}
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={useAgent ? "Enter a prompt for Simba..." : "Message content..."}
rows={3}
className="w-full rounded-xl border border-sand bg-cream-light px-3 py-2 text-sm text-charcoal placeholder:text-warm-gray/50 focus:outline-none focus:ring-2 focus:ring-leaf/30 resize-none"
/>
{error && <p role="alert" className="text-xs text-red-500">{error}</p>}
<Button onClick={handleCreate} disabled={submitting} size="sm">
<Send size={12} />
{submitting ? "Scheduling..." : "Schedule"}
</Button>
</div>
{/* Message list */}
{listError && (
<div role="alert" className="px-6 py-3 text-xs text-red-500">
{listError} <Button size="sm" variant="ghost-dark" onClick={() => void refresh()}>Refresh messages</Button>
</div>
)}
{loading ? (
<div className="px-6 py-12 text-center text-warm-gray text-sm">
<div className="flex justify-center gap-1.5 mb-3">
<span className="loading-dot w-2 h-2 rounded-full bg-amber-soft inline-block" />
<span className="loading-dot w-2 h-2 rounded-full bg-amber-soft inline-block" />
<span className="loading-dot w-2 h-2 rounded-full bg-amber-soft inline-block" />
</div>
Loading...
</div>
) : messages.length === 0 ? (
<div className="px-6 py-12 text-center text-warm-gray text-sm">
{listError ? "Scheduled messages could not be loaded." : "No scheduled messages yet."}
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Channel</TableHead>
<TableHead>Recipient</TableHead>
<TableHead>Content</TableHead>
<TableHead>Scheduled</TableHead>
<TableHead>Repeat</TableHead>
<TableHead>Status</TableHead>
<TableHead className="w-28">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{messages.map((msg) => (
<TableRow key={msg.id}>
<TableCell className="capitalize text-xs">
{msg.channel}
</TableCell>
<TableCell className="text-xs truncate max-w-[140px]" title={msg.recipient}>
{msg.recipient}
</TableCell>
<TableCell className="text-xs max-w-[180px]" title={msg.content}>
<div className="flex items-center gap-1">
{msg.use_agent && <Bot size={10} className="text-leaf-dark shrink-0" />}
<span className="truncate">
{msg.content.length > 60
? msg.content.slice(0, 60) + "..."
: msg.content}
</span>
</div>
</TableCell>
<TableCell className="text-xs text-warm-gray">
{new Date(msg.scheduled_at).toLocaleString()}
</TableCell>
<TableCell className="text-xs text-warm-gray capitalize">
{msg.recurrence === "none" ? "—" : msg.recurrence}
</TableCell>
<TableCell>
<Badge variant={STATUS_BADGE[msg.status]}>{DELIVERY_STATUS_LABELS[msg.status]}</Badge>
{msg.error_message && <p className="text-xs text-red-500 mt-1 break-words">{msg.error_message}</p>}
{msg.status === "uncertain" && <p className="text-xs text-warm-gray mt-1">{UNCERTAIN_DELIVERY_HELP}</p>}
</TableCell>
<TableCell>
<div className="flex gap-1">
<Button size="sm" variant="ghost-dark" onClick={() => setHistoryId(msg.id)} aria-label={`Delivery history for ${msg.recipient}`} title="Delivery history">
<Clock size={11} />
</Button>
{(msg.status === "pending" || msg.status === "failed" || (msg.recurrence !== "none" && msg.status !== "cancelled")) && (
<Button
size="sm"
variant="ghost-dark"
onClick={() => void runAction(msg, "cancel")}
disabled={busyId !== null}
aria-label={msg.recurrence === "none" ? "Cancel message" : "Cancel series"}
title={msg.recurrence === "none" ? "Cancel message" : "Cancel series — stop future occurrences; an in-flight delivery may still complete"}
>
<XCircle size={11} />
</Button>
)}
{canRetryScheduledMessage(msg) && (
<Button
size="sm"
variant="ghost-dark"
onClick={() => void runAction(msg, "retry")}
disabled={busyId !== null}
aria-label="Retry failed delivery"
title="Retry failed delivery"
>
<RotateCcw size={11} />
</Button>
)}
{(msg.status === "pending" || msg.status === "cancelled") && (
<Button
size="sm"
variant="destructive"
onClick={() => void runAction(msg, "delete")}
disabled={busyId !== null}
aria-label={msg.recurrence === "none" ? "Delete message" : "Delete occurrence and cancel series"}
title={msg.recurrence === "none" ? "Delete message" : "Delete occurrence and cancel series"}
>
<Trash2 size={11} />
</Button>
)}
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
{historyId && (
<section aria-label="Delivery attempt history" className="px-6 py-4 border-t border-sand-light space-y-3">
<div className="flex items-center justify-between gap-2">
<h3 className="text-sm font-semibold">Delivery attempt history</h3>
<Button size="sm" variant="ghost-dark" onClick={() => setHistoryVersion((version) => version + 1)} disabled={historyLoading}>Refresh history</Button>
<Button size="sm" variant="ghost-dark" onClick={() => setHistoryId(null)}>Close history</Button>
</div>
<p className="text-xs break-all">Message: {historyId}</p>
{historyLoading ? <p role="status" className="text-xs">Loading delivery history...</p> : historyError ? <p role="alert" className="text-xs text-red-500">{historyError}</p> : <DeliveryHistory deliveries={deliveries} />}
</section>
)}
</div>
</div>
</div>
);
};