Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

[codex] add compact audio backlog modal (#3395)

Louis Beaumont60b45f3e705e
diff --git a/apps/screenpipe-app-tauri/components/screenpipe-status.tsx b/apps/screenpipe-app-tauri/components/screenpipe-status.tsx
index 7831c2811..2d9f14e75 100644
--- a/apps/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/apps/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -15,7 +15,7 @@ import { toast } from "./ui/use-toast";
import { Button } from "./ui/button";
import { Separator } from "./ui/separator";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
-import { Folder, Activity, Mic, RefreshCw, AlertTriangle } from "lucide-react";
+import { Folder, Mic, RefreshCw, AlertTriangle } from "lucide-react";
import { open as openUrl } from "@tauri-apps/plugin-shell";
import { commands } from "@/lib/utils/tauri";
@@ -140,7 +140,6 @@ const HealthStatus = ({ className }: { className?: string }) => {
health?.audio_status ?? "",
settings.disableAudio
);
-
const handleOpenStatusDialog = async () => {
try {
const dir = await getDataDir();
diff --git a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
index 796e0d091..b987cc218 100644
--- a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
@@ -44,6 +44,8 @@ import {
Shield,
Zap,
Music,
+ FileAudio,
+ FileText,
User,
Users,
ChevronUp,
@@ -54,6 +56,11 @@ import {
Upload,
Trash2,
Search,
+ ListTodo,
+ Pause,
+ Play,
+ Rewind,
+ FastForward,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
@@ -73,7 +80,9 @@ import {
import { useTeam } from "@/lib/hooks/use-team";
import { useToast } from "@/components/ui/use-toast";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
+import { localFetch } from "@/lib/api";
import { Badge } from "@/components/ui/badge";
+import { Skeleton } from "@/components/ui/skeleton";
import { HelpTooltip } from "@/components/ui/help-tooltip";
import { Switch } from "@/components/ui/switch";
import { Slider } from "@/components/ui/slider";
@@ -87,9 +96,11 @@ import { ToastAction } from "@/components/ui/toast";
import { open as openUrl } from "@tauri-apps/plugin-shell";
import { listen } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/core";
+import { getMediaFile } from "@/lib/actions/video-actions";
import { Dialog, DialogContent, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { Card, CardContent } from "@/components/ui/card";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { MultiSelect } from "@/components/ui/multi-select";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";
@@ -208,6 +219,843 @@ const getAudioFallbackMessage = (reason: AudioEngineFallbackReason) => {
}
};
+type AudioPipelineSnapshot = {
+ transcription_mode?: string;
+ segments_deferred?: number;
+ segments_batch_processed?: number;
+ batch_paused_reason?: string | null;
+ pending_transcription_segments?: number;
+ oldest_pending_transcription_at?: string | null;
+ transcription_paused?: boolean;
+};
+
+const formatBacklogAge = (timestamp?: string | null) => {
+ if (!timestamp) return "n/a";
+ const ms = new Date(timestamp).getTime();
+ if (!Number.isFinite(ms)) return "n/a";
+ const seconds = Math.max(0, Math.floor((Date.now() - ms) / 1000));
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ${minutes % 60}m`;
+ const days = Math.floor(hours / 24);
+ return `${days}d ${hours % 24}h`;
+};
+
+type AudioReconciliationBacklogItem = {
+ audio_chunk_id: number;
+ captured_at: string;
+ age_seconds: number;
+ file_path: string;
+ file_size_bytes?: number | null;
+ likely_empty?: boolean;
+ status: string;
+};
+
+type AudioReconciliationBacklogResponse = {
+ pending: number;
+ items: AudioReconciliationBacklogItem[];
+};
+
+const formatBacklogSeconds = (seconds?: number | null) => {
+ if (seconds == null || !Number.isFinite(seconds)) return "n/a";
+ const safeSeconds = Math.max(0, Math.floor(seconds));
+ if (safeSeconds < 60) return `${safeSeconds}s`;
+ const minutes = Math.floor(safeSeconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ${minutes % 60}m`;
+ const days = Math.floor(hours / 24);
+ return `${days}d ${hours % 24}h`;
+};
+
+const getAudioFileName = (filePath: string) => {
+ const name = filePath.split(/[\\/]/).pop();
+ return name || filePath;
+};
+
+const formatBacklogFileSize = (bytes?: number | null) => {
+ if (bytes == null || !Number.isFinite(bytes)) return "n/a";
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+};
+
+const getAudioPreviewMimeType = (filePath: string) => {
+ const ext = filePath.split(".").pop()?.toLowerCase();
+ if (ext === "wav") return "audio/wav";
+ if (ext === "mp3") return "audio/mpeg";
+ if (ext === "ogg") return "audio/ogg";
+ if (ext === "webm") return "audio/webm";
+ return "audio/mp4";
+};
+
+const createAudioPreviewUrl = async (filePath: string) => {
+ const { data } = await getMediaFile(filePath);
+ const binaryData = atob(data);
+ const bytes = new Uint8Array(binaryData.length);
+ for (let i = 0; i < binaryData.length; i += 1) {
+ bytes[i] = binaryData.charCodeAt(i);
+ }
+ return URL.createObjectURL(
+ new Blob([bytes], { type: getAudioPreviewMimeType(filePath) })
+ );
+};
+
+const formatAudioPreviewTime = (seconds: number) => {
+ if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
+ const safeSeconds = Math.floor(seconds);
+ const minutes = Math.floor(safeSeconds / 60);
+ const remainder = safeSeconds % 60;
+ return `${minutes}:${remainder.toString().padStart(2, "0")}`;
+};
+
+const formatBacklogCapturedAt = (timestamp: string) => {
+ const date = new Date(timestamp);
+ if (!Number.isFinite(date.getTime())) return "n/a";
+
+ const time = date.toLocaleTimeString([], {
+ hour: "numeric",
+ minute: "2-digit",
+ });
+ if (date.toDateString() === new Date().toDateString()) return time;
+
+ return `${date.toLocaleDateString([], {
+ month: "numeric",
+ day: "numeric",
+ })} ${time}`;
+};
+
+const getFetchErrorMessage = async (response: Response) => {
+ try {
+ const body = await response.json();
+ if (body?.error) return String(body.error);
+ } catch {
+ // Fall through to the status text.
+ }
+ return response.statusText || `request failed (${response.status})`;
+};
+
+function BackgroundTranscriptionDialog({
+ audioPipeline,
+}: {
+ audioPipeline?: AudioPipelineSnapshot | null;
+}) {
+ const [open, setOpen] = useState(false);
+ const [items, setItems] = useState<AudioReconciliationBacklogItem[]>([]);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [showQuietChunks, setShowQuietChunks] = useState(false);
+ const [previewItem, setPreviewItem] = useState<AudioReconciliationBacklogItem | null>(null);
+ const [previewSrc, setPreviewSrc] = useState<string | null>(null);
+ const [previewLoadingId, setPreviewLoadingId] = useState<number | null>(null);
+ const [previewPlaying, setPreviewPlaying] = useState(false);
+ const [previewCurrentTime, setPreviewCurrentTime] = useState(0);
+ const [previewDuration, setPreviewDuration] = useState(0);
+ const [pendingTotal, setPendingTotal] = useState<number | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [runningId, setRunningId] = useState<number | null>(null);
+ const [droppingId, setDroppingId] = useState<number | null>(null);
+ const audioRef = React.useRef<HTMLAudioElement | null>(null);
+ const previewSrcRef = React.useRef<string | null>(null);
+ const { toast } = useToast();
+
+ const pending = audioPipeline?.pending_transcription_segments ?? 0;
+ const visiblePending = pendingTotal ?? pending;
+ const workerState = audioPipeline?.batch_paused_reason
+ ? audioPipeline.batch_paused_reason
+ : audioPipeline?.transcription_paused
+ ? "paused"
+ : audioPipeline
+ ? "running"
+ : "waiting";
+
+ const clearPreviewSrc = useCallback(() => {
+ if (previewSrcRef.current) {
+ URL.revokeObjectURL(previewSrcRef.current);
+ previewSrcRef.current = null;
+ }
+ setPreviewSrc(null);
+ }, []);
+
+ const refreshItems = useCallback(async (
+ options: { showLoading?: boolean } = {}
+ ) => {
+ const showLoading = options.showLoading !== false;
+ if (showLoading) {
+ setLoading(true);
+ }
+ try {
+ const response = await localFetch("/audio/reconciliation/backlog");
+ if (!response.ok) {
+ throw new Error(await getFetchErrorMessage(response));
+ }
+ const data = (await response.json()) as AudioReconciliationBacklogResponse;
+ setItems(data.items ?? []);
+ setPendingTotal(data.pending ?? data.items?.length ?? 0);
+ } catch (error) {
+ toast({
+ title: "could not load backlog",
+ description: error instanceof Error ? error.message : String(error),
+ variant: "destructive",
+ });
+ } finally {
+ if (showLoading) {
+ setLoading(false);
+ }
+ }
+ }, [toast]);
+
+ useEffect(() => {
+ if (open) {
+ void refreshItems();
+ }
+ }, [open, refreshItems]);
+
+ useEffect(() => {
+ return () => {
+ if (previewSrcRef.current) {
+ URL.revokeObjectURL(previewSrcRef.current);
+ }
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!previewItem) {
+ audioRef.current?.pause();
+ clearPreviewSrc();
+ setPreviewLoadingId(null);
+ setPreviewPlaying(false);
+ setPreviewCurrentTime(0);
+ setPreviewDuration(0);
+ return;
+ }
+
+ let canceled = false;
+ const previewId = previewItem.audio_chunk_id;
+ clearPreviewSrc();
+ setPreviewLoadingId(previewId);
+ setPreviewPlaying(false);
+ setPreviewCurrentTime(0);
+ setPreviewDuration(0);
+
+ void createAudioPreviewUrl(previewItem.file_path)
+ .then((url) => {
+ if (canceled) {
+ URL.revokeObjectURL(url);
+ return;
+ }
+ previewSrcRef.current = url;
+ setPreviewSrc(url);
+ })
+ .catch((error) => {
+ if (canceled) return;
+ toast({
+ title: "could not load audio",
+ description: error instanceof Error ? error.message : String(error),
+ variant: "destructive",
+ });
+ })
+ .finally(() => {
+ if (!canceled) {
+ setPreviewLoadingId(null);
+ }
+ });
+
+ return () => {
+ canceled = true;
+ };
+ }, [clearPreviewSrc, previewItem?.audio_chunk_id, previewItem?.file_path, toast]);
+
+ const quietItems = useMemo(
+ () => items.filter((item) => item.likely_empty),
+ [items]
+ );
+ const readyItems = useMemo(
+ () => items.filter((item) => !item.likely_empty),
+ [items]
+ );
+ const activeItems = useMemo(
+ () => showQuietChunks ? items : readyItems,
+ [items, readyItems, showQuietChunks]
+ );
+ const filteredItems = useMemo(() => {
+ const query = searchQuery.trim().toLowerCase();
+ if (!query) return activeItems;
+
+ return activeItems.filter((item) => {
+ const haystack = [
+ item.audio_chunk_id.toString(),
+ item.likely_empty ? "quiet likely empty" : "needs transcription",
+ item.status,
+ item.file_path,
+ getAudioFileName(item.file_path),
+ formatBacklogCapturedAt(item.captured_at),
+ formatBacklogSeconds(item.age_seconds),
+ formatBacklogFileSize(item.file_size_bytes),
+ ].join(" ").toLowerCase();
+ return haystack.includes(query);
+ });
+ }, [activeItems, searchQuery]);
+
+ const previewItemId = previewItem?.audio_chunk_id ?? null;
+
+ useEffect(() => {
+ if (previewItemId == null) return;
+ if (!activeItems.some((item) => item.audio_chunk_id === previewItemId)) {
+ audioRef.current?.pause();
+ setPreviewItem(null);
+ setPreviewLoadingId(null);
+ clearPreviewSrc();
+ setPreviewPlaying(false);
+ setPreviewCurrentTime(0);
+ setPreviewDuration(0);
+ }
+ }, [activeItems, clearPreviewSrc, previewItemId]);
+
+ const handlePreviewAudio = useCallback((item: AudioReconciliationBacklogItem) => {
+ const isCurrentPreview = previewItem?.audio_chunk_id === item.audio_chunk_id;
+ if (isCurrentPreview) {
+ audioRef.current?.pause();
+ setPreviewItem(null);
+ setPreviewLoadingId(null);
+ clearPreviewSrc();
+ setPreviewPlaying(false);
+ setPreviewCurrentTime(0);
+ setPreviewDuration(0);
+ return;
+ }
+
+ setPreviewItem(item);
+ }, [clearPreviewSrc, previewItem?.audio_chunk_id]);
+
+ const handlePreviewPlayback = useCallback(() => {
+ const audio = audioRef.current;
+ if (!audio || !previewSrc) return;
+
+ if (!audio.paused) {
+ audio.pause();
+ return;
+ }
+
+ void audio.play().catch(() => {
+ toast({
+ title: "could not play audio",
+ description: "the audio file could not be opened for preview",
+ variant: "destructive",
+ });
+ });
+ }, [previewSrc, toast]);
+
+ const seekPreview = useCallback((seconds: number) => {
+ const audio = audioRef.current;
+ if (!audio) return;
+
+ const duration = Number.isFinite(audio.duration) ? audio.duration : previewDuration;
+ const max = duration > 0 ? duration : seconds;
+ const nextTime = Math.min(Math.max(seconds, 0), Math.max(max, 0));
+ audio.currentTime = nextTime;
+ setPreviewCurrentTime(nextTime);
+ }, [previewDuration]);
+
+ const stepPreview = useCallback((seconds: number) => {
+ const audio = audioRef.current;
+ const currentTime = audio?.currentTime ?? previewCurrentTime;
+ seekPreview(currentTime + seconds);
+ }, [previewCurrentTime, seekPreview]);
+
+ const handleForceRun = useCallback(async (audioChunkId: number) => {
+ setRunningId(audioChunkId);
+ try {
+ const response = await localFetch("/audio/retranscribe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ audio_chunk_ids: [audioChunkId] }),
+ });
+ if (!response.ok) {
+ throw new Error(await getFetchErrorMessage(response));
+ }
+ const result = await response.json();
+ toast({
+ title: result.chunks_processed > 0 ? "chunk transcribed" : "nothing processed",
+ description:
+ result.chunks_processed > 0
+ ? `audio chunk ${audioChunkId} was processed`
+ : `audio chunk ${audioChunkId} did not produce a transcript`,
+ });
+ await refreshItems({ showLoading: false });
+ } catch (error) {
+ toast({
+ title: "could not run transcription",
+ description: error instanceof Error ? error.message : String(error),
+ variant: "destructive",
+ });
+ } finally {
+ setRunningId(null);
+ }
+ }, [refreshItems, toast]);
+
+ const handleDrop = useCallback(async (item: AudioReconciliationBacklogItem) => {
+ const ok = window.confirm(
+ `drop audio chunk ${item.audio_chunk_id} from the background transcription backlog?`
+ );
+ if (!ok) return;
+
+ setDroppingId(item.audio_chunk_id);
+ try {
+ const response = await localFetch(
+ `/audio/reconciliation/backlog/${item.audio_chunk_id}`,
+ { method: "DELETE" }
+ );
+ if (!response.ok) {
+ throw new Error(await getFetchErrorMessage(response));
+ }
+ setItems((current) =>
+ current.filter((row) => row.audio_chunk_id !== item.audio_chunk_id)
+ );
+ setPendingTotal((current) => Math.max(0, (current ?? visiblePending) - 1));
+ toast({
+ title: "audio chunk dropped",
+ description: getAudioFileName(item.file_path),
+ });
+ } catch (error) {
+ toast({
+ title: "could not drop chunk",
+ description: error instanceof Error ? error.message : String(error),
+ variant: "destructive",
+ });
+ } finally {
+ setDroppingId(null);
+ }
+ }, [toast, visiblePending]);
+
+ const oldestPending = pending > 0
+ ? formatBacklogAge(audioPipeline?.oldest_pending_transcription_at)
+ : "none";
+ const showingLimitedRows = visiblePending > items.length;
+ const showInitialSkeleton = loading && items.length === 0;
+ const skeletonRows = Array.from({ length: 10 });
+
+ return (
+ <>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="relative h-7 w-7 shrink-0 border border-border bg-background text-foreground hover:bg-muted hover:text-foreground active:bg-muted"
+ aria-label="open background transcription backlog"
+ title="background transcription backlog"
+ onClick={() => setOpen(true)}
+ >
+ <ListTodo className="h-3.5 w-3.5" />
+ {visiblePending > 0 && (
+ <span className="absolute -right-1.5 -top-1.5 min-w-[1rem] rounded-full border border-background bg-foreground px-1 text-[9px] leading-4 text-background">
+ {visiblePending > 99 ? "99+" : visiblePending}
+ </span>
+ )}
+ </Button>
+
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ setOpen(nextOpen);
+ if (!nextOpen) {
+ audioRef.current?.pause();
+ setPreviewItem(null);
+ setPreviewLoadingId(null);
+ clearPreviewSrc();
+ setPreviewPlaying(false);
+ setPreviewCurrentTime(0);
+ setPreviewDuration(0);
+ }
+ }}
+ >
+ <DialogContent className="flex h-[min(760px,calc(100vh-4rem))] w-[min(920px,calc(100vw-3rem))] max-w-none flex-col gap-3 overflow-hidden p-4 sm:p-5">
+ <div className="flex shrink-0 items-start justify-between gap-3 pr-8">
+ <div>
+ <DialogTitle>Background transcription backlog</DialogTitle>
+ <DialogDescription className="mt-1 text-xs">
+ Audio chunks waiting for background transcription reconciliation.
+ </DialogDescription>
+ </div>
+ <Badge variant="outline" className="mt-0.5 shrink-0 rounded-none font-mono text-[10px]">
+ worker {workerState}
+ </Badge>
+ </div>
+
+ <div className="grid shrink-0 grid-cols-2 gap-2 text-xs sm:grid-cols-4">
+ <div className="border border-border px-2 py-1.5">
+ <div className="text-muted-foreground">ready loaded</div>
+ <div className="font-mono text-sm">{readyItems.length.toLocaleString()}</div>
+ </div>
+ <div className="border border-border px-2 py-1.5">
+ <div className="text-muted-foreground">quiet loaded</div>
+ <div className="font-mono text-sm">{quietItems.length.toLocaleString()}</div>
+ </div>
+ <div className="border border-border px-2 py-1.5">
+ <div className="text-muted-foreground">total candidates</div>
+ <div className="font-mono text-sm">{visiblePending.toLocaleString()}</div>
+ </div>
+ <div className="border border-border px-2 py-1.5">
+ <div className="text-muted-foreground">oldest candidate</div>
+ <div className="font-mono text-sm">{oldestPending}</div>
+ </div>
+ </div>
+
+ <div className="flex shrink-0 flex-wrap items-center gap-2">
+ <div className="relative min-w-[220px] flex-1">
+ <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={searchQuery}
+ onChange={(event) => setSearchQuery(event.target.value)}
+ placeholder="search chunk, time, or file..."
+ className="h-8 pl-7 text-xs"
+ spellCheck={false}
+ />
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-8 shrink-0 gap-1 border border-border bg-background px-2 text-xs text-foreground hover:bg-muted hover:text-foreground active:bg-muted",
+ showQuietChunks && "bg-muted"
+ )}
+ onClick={() => setShowQuietChunks((value) => !value)}
+ >
+ {showQuietChunks ? (
+ <Eye className="h-3 w-3" />
+ ) : (
+ <EyeOff className="h-3 w-3" />
+ )}
+ {showQuietChunks ? "quiet shown" : "quiet hidden"}
+ <span className="font-mono text-[10px] text-muted-foreground">
+ {quietItems.length.toLocaleString()}
+ </span>
+ </Button>
+ <Badge variant="secondary" className="h-8 shrink-0 rounded-none px-2 font-mono text-[10px]">
+ {filteredItems.length.toLocaleString()} shown
+ </Badge>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-8 shrink-0 gap-1 border border-border bg-background px-2 text-xs text-foreground hover:bg-muted hover:text-foreground active:bg-muted"
+ disabled={loading}
+ onClick={() => void refreshItems()}
+ >
+ <RefreshCw className={cn("h-3 w-3", loading && "animate-spin")} />
+ refresh
+ </Button>
+ </div>
+
+ <div className="relative min-h-0 flex-1 overflow-auto border border-border/60" aria-busy={loading}>
+ <table className="w-full min-w-[720px] table-fixed text-xs">
+ <thead className="sticky top-0 z-10 bg-background">
+ <tr className="border-b border-border/60 bg-muted/30 text-left text-muted-foreground">
+ <th className="w-[72px] px-2 py-1.5 font-medium">chunk</th>
+ <th className="w-[64px] px-2 py-1.5 font-medium">age</th>
+ <th className="w-[92px] px-2 py-1.5 font-medium">captured</th>
+ <th className="px-2 py-1.5 font-medium">file</th>
+ <th className="w-[92px] px-2 py-1.5 font-medium">status</th>
+ <th className="w-[120px] px-2 py-1.5 text-right font-medium">actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {showInitialSkeleton && skeletonRows.map((_, index) => (
+ <tr key={`backlog-skeleton-${index}`} className="border-b border-border/60">
+ <td className="px-2 py-2">
+ <Skeleton className="h-3 w-12" />
+ </td>
+ <td className="px-2 py-2">
+ <Skeleton className="h-3 w-10" />
+ </td>
+ <td className="px-2 py-2">
+ <Skeleton className="h-3 w-14" />
+ </td>
+ <td className="px-2 py-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <Skeleton className="h-3 flex-1" />
+ <Skeleton className="h-3 w-12 shrink-0" />
+ </div>
+ </td>
+ <td className="px-2 py-2">
+ <Skeleton className="h-5 w-16" />
+ </td>
+ <td className="px-2 py-2">
+ <div className="flex justify-end gap-1">
+ <Skeleton className="h-7 w-7" />
+ <Skeleton className="h-7 w-7" />
+ <Skeleton className="h-7 w-7" />
+ </div>
+ </td>
+ </tr>
+ ))}
+ {!showInitialSkeleton && filteredItems.length === 0 && (
+ <tr>
+ <td colSpan={6} className="px-2 py-6 text-center text-muted-foreground">
+ {items.length === 0
+ ? "no waiting chunks"
+ : activeItems.length === 0 && !showQuietChunks
+ ? "only quiet/no-speech chunks are loaded"
+ : "no matching chunks"}
+ </td>
+ </tr>
+ )}
+ {!showInitialSkeleton && filteredItems.map((item) => {
+ const isPreviewing = previewItem?.audio_chunk_id === item.audio_chunk_id;
+ const statusLabel = item.likely_empty ? "quiet" : item.status;
+
+ return (
+ <React.Fragment key={item.audio_chunk_id}>
+ <tr
+ className={cn(
+ "cursor-pointer border-b border-border/60",
+ item.likely_empty && "bg-muted/20",
+ isPreviewing && "bg-muted/40"
+ )}
+ onClick={() => handlePreviewAudio(item)}
+ >
+ <td className="px-2 py-1.5 font-mono text-foreground">
+ {item.audio_chunk_id}
+ </td>
+ <td className="px-2 py-1.5 font-mono text-foreground whitespace-nowrap">
+ {formatBacklogSeconds(item.age_seconds)}
+ </td>
+ <td
+ className="px-2 py-1.5 font-mono text-muted-foreground whitespace-nowrap"
+ title={new Date(item.captured_at).toLocaleString()}
+ >
+ {formatBacklogCapturedAt(item.captured_at)}
+ </td>
+ <td
+ className="px-2 py-1.5 font-mono text-muted-foreground"
+ title={item.file_path}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate">
+ {getAudioFileName(item.file_path)}
+ </span>
+ {item.file_size_bytes != null && (
+ <span className="shrink-0 text-[10px] text-muted-foreground/80">
+ {formatBacklogFileSize(item.file_size_bytes)}
+ </span>
+ )}
+ </div>
+ </td>
+ <td className="px-2 py-1.5">
+ <Badge
+ variant={item.likely_empty ? "secondary" : "outline"}
+ className="font-mono text-[10px]"
+ >
+ {statusLabel}
+ </Badge>
+ </td>
+ <td className="px-2 py-1.5">
+ <TooltipProvider delayDuration={150}>
+ <div className="flex justify-end gap-1">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "h-7 w-7 border border-border bg-background text-foreground hover:bg-muted hover:text-foreground active:bg-muted",
+ isPreviewing && "bg-muted"
+ )}
+ aria-label={`preview audio chunk ${item.audio_chunk_id}`}
+ disabled={droppingId === item.audio_chunk_id}
+ onClick={(event) => {
+ event.stopPropagation();
+ handlePreviewAudio(item);
+ }}
+ >
+ {previewLoadingId === item.audio_chunk_id ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <FileAudio className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="top">
+ {isPreviewing ? "close audio controls" : "open audio controls"}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 border border-border bg-background text-foreground hover:bg-muted hover:text-foreground active:bg-muted"
+ aria-label={`transcribe audio chunk ${item.audio_chunk_id}`}
+ disabled={runningId === item.audio_chunk_id || droppingId === item.audio_chunk_id}
+ onClick={(event) => {
+ event.stopPropagation();
+ void handleForceRun(item.audio_chunk_id);
+ }}
+ >
+ {runningId === item.audio_chunk_id ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <FileText className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="top">transcribe this chunk now</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 border border-border bg-background text-muted-foreground hover:bg-muted hover:text-destructive active:bg-muted"
+ aria-label={`drop audio chunk ${item.audio_chunk_id}`}
+ disabled={droppingId === item.audio_chunk_id || runningId === item.audio_chunk_id}
+ onClick={(event) => {
+ event.stopPropagation();
+ void handleDrop(item);
+ }}
+ >
+ {droppingId === item.audio_chunk_id ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Trash2 className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="top">drop this waiting chunk</TooltipContent>
+ </Tooltip>
+ </div>
+ </TooltipProvider>
+ </td>
+ </tr>
+ </React.Fragment>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+
+ {previewItem && (
+ <div className="shrink-0 border border-border/60 bg-muted/20 p-2">
+ <div className="mb-2 flex min-w-0 items-center gap-2">
+ <FileAudio className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-mono text-xs text-foreground">
+ {previewItem.audio_chunk_id} - {getAudioFileName(previewItem.file_path)}
+ </div>
+ <div className="font-mono text-[10px] text-muted-foreground">
+ {formatBacklogFileSize(previewItem.file_size_bytes)}
+ {previewItem.likely_empty ? " - quiet" : ""}
+ </div>
+ </div>
+ </div>
+ {previewLoadingId === previewItem.audio_chunk_id && !previewSrc ? (
+ <div className="flex h-9 items-center gap-2 bg-muted/60 px-3 text-[11px] text-muted-foreground">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ loading audio
+ </div>
+ ) : previewSrc ? (
+ <div className="flex h-9 min-w-0 items-center gap-2 bg-muted/60 px-2">
+ <audio
+ key={previewItem.audio_chunk_id}
+ ref={audioRef}
+ preload="metadata"
+ className="hidden"
+ src={previewSrc}
+ onLoadedMetadata={(event) => {
+ const duration = event.currentTarget.duration;
+ setPreviewDuration(Number.isFinite(duration) ? duration : 0);
+ }}
+ onTimeUpdate={(event) => {
+ setPreviewCurrentTime(event.currentTarget.currentTime);
+ }}
+ onPlay={() => setPreviewPlaying(true)}
+ onPause={() => setPreviewPlaying(false)}
+ onEnded={(event) => {
+ event.currentTarget.currentTime = 0;
+ setPreviewPlaying(false);
+ setPreviewCurrentTime(0);
+ }}
+ onError={() => setPreviewPlaying(false)}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 shrink-0 border border-border bg-background text-foreground hover:bg-muted hover:text-foreground active:bg-muted"
+ onClick={handlePreviewPlayback}
+ aria-label={previewPlaying ? "pause audio preview" : "play audio preview"}
+ >
+ {previewPlaying ? (
+ <Pause className="h-3.5 w-3.5" />
+ ) : (
+ <Play className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 shrink-0 border border-border bg-background text-foreground hover:bg-muted hover:text-foreground active:bg-muted"
+ onClick={() => stepPreview(-10)}
+ aria-label="back 10 seconds"
+ disabled={previewDuration <= 0}
+ >
+ <Rewind className="h-3.5 w-3.5" />
+ </Button>
+ <input
+ type="range"
+ min={0}
+ max={Math.max(previewDuration, 0)}
+ step={0.1}
+ value={Math.min(previewCurrentTime, previewDuration || 0)}
+ onChange={(event) => seekPreview(Number(event.target.value))}
+ disabled={previewDuration <= 0}
+ className="h-1 min-w-[180px] flex-1 accent-foreground"
+ aria-label="audio preview position"
+ />
+ <span className="w-[76px] shrink-0 text-right font-mono text-[10px] text-muted-foreground">
+ {formatAudioPreviewTime(previewCurrentTime)} / {formatAudioPreviewTime(previewDuration)}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 shrink-0 border border-border bg-background text-foreground hover:bg-muted hover:text-foreground active:bg-muted"
+ onClick={() => stepPreview(10)}
+ aria-label="forward 10 seconds"
+ disabled={previewDuration <= 0}
+ >
+ <FastForward className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ ) : (
+ <div className="flex h-9 items-center bg-muted/60 px-3 text-[11px] text-muted-foreground">
+ audio unavailable
+ </div>
+ )}
+ </div>
+ )}
+
+ <div className="flex shrink-0 items-center justify-between gap-3 text-xs text-muted-foreground">
+ <span className="min-w-0 truncate">
+ showing {filteredItems.length.toLocaleString()} of{" "}
+ {(showQuietChunks ? items.length : readyItems.length).toLocaleString()}{" "}
+ {showQuietChunks ? "loaded chunks" : "ready loaded chunks"}
+ {!showQuietChunks && quietItems.length > 0 ? ` - ${quietItems.length.toLocaleString()} quiet hidden` : ""}
+ {showingLimitedRows ? ` - ${visiblePending.toLocaleString()} total candidates incl. quiet` : ""}
+ </span>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
+
const createWindowOptions = (
windowItems: { name: string; count: number; app_name?: string }[],
existingPatterns: string[]
@@ -596,6 +1444,7 @@ export function RecordingSettings() {
const [isUpdating, setIsUpdating] = useState(false);
const { health } = useHealthCheck();
const isDisabled = health?.status_code === 500;
+ const audioPipeline = health?.audio_pipeline ?? null;
const [isMacOS, setIsMacOS] = useState(false);
const [showApiKey, setShowApiKey] = useState(false);
const [showOpenAIApiKey, setShowOpenAIApiKey] = useState(false);
@@ -1301,37 +2150,42 @@ Your screen is a pipe. Everything you see, hear, and type flows through it. Scre
<HelpTooltip text="Cloud engines send audio to a server for fast, accurate transcription. Offline engines run on your device — fully private but use more CPU/RAM." />
</h3>
</div>
- <Select
- value={settings.audioTranscriptionEngine}
- onValueChange={(value) => handleAudioTranscriptionModelChange(value)}
- >
- <SelectTrigger className="w-[200px] h-7 text-xs">
- <SelectValue placeholder="Select engine" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectLabel className="text-[10px] text-muted-foreground/70 uppercase tracking-wider">cloud</SelectLabel>
- <SelectItem value="screenpipe-cloud" disabled={!settings.user?.cloud_subscribed}>
- Screenpipe Cloud {!settings.user?.cloud_subscribed && "(pro)"}{hwCapability?.recommendedEngine === "screenpipe-cloud" && " ★"}
- </SelectItem>
- <SelectItem value="deepgram">Deepgram</SelectItem>
- </SelectGroup>
- <SelectGroup>
- <SelectLabel className="text-[10px] text-muted-foreground/70 uppercase tracking-wider">offline</SelectLabel>
- <SelectItem value="whisper-large-v3-turbo">Whisper Turbo</SelectItem>
- <SelectItem value="whisper-large-v3-turbo-quantized">Whisper Turbo (fast)</SelectItem>
- <SelectItem value="whisper-tiny">Whisper Tiny</SelectItem>
- <SelectItem value="whisper-tiny-quantized">Whisper Tiny (fast)</SelectItem>
- {!isMacOS && <SelectItem value="qwen3-asr">Qwen3-ASR</SelectItem>}
- <SelectItem value="parakeet">Parakeet{isMacOS ? " (experimental)" : ""}</SelectItem>
- </SelectGroup>
- <SelectGroup>
- <SelectLabel className="text-[10px] text-muted-foreground/70 uppercase tracking-wider">other</SelectLabel>
- <SelectItem value="openai-compatible">OpenAI Compatible</SelectItem>
- <SelectItem value="disabled">Disabled (capture only)</SelectItem>
- </SelectGroup>
- </SelectContent>
- </Select>
+ <div className="flex items-center gap-2">
+ {settings.audioTranscriptionEngine !== "disabled" && (
+ <BackgroundTranscriptionDialog audioPipeline={audioPipeline} />
+ )}
+ <Select
+ value={settings.audioTranscriptionEngine}
+ onValueChange={(value) => handleAudioTranscriptionModelChange(value)}
+ >
+ <SelectTrigger className="w-[200px] h-7 text-xs">
+ <SelectValue placeholder="Select engine" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectLabel className="text-[10px] text-muted-foreground/70 uppercase tracking-wider">cloud</SelectLabel>
+ <SelectItem value="screenpipe-cloud" disabled={!settings.user?.cloud_subscribed}>
+ Screenpipe Cloud {!settings.user?.cloud_subscribed && "(pro)"}{hwCapability?.recommendedEngine === "screenpipe-cloud" && " ★"}
+ </SelectItem>
+ <SelectItem value="deepgram">Deepgram</SelectItem>
+ </SelectGroup>
+ <SelectGroup>
+ <SelectLabel className="text-[10px] text-muted-foreground/70 uppercase tracking-wider">offline</SelectLabel>
+ <SelectItem value="whisper-large-v3-turbo">Whisper Turbo</SelectItem>
+ <SelectItem value="whisper-large-v3-turbo-quantized">Whisper Turbo (fast)</SelectItem>
+ <SelectItem value="whisper-tiny">Whisper Tiny</SelectItem>
+ <SelectItem value="whisper-tiny-quantized">Whisper Tiny (fast)</SelectItem>
+ {!isMacOS && <SelectItem value="qwen3-asr">Qwen3-ASR</SelectItem>}
+ <SelectItem value="parakeet">Parakeet{isMacOS ? " (experimental)" : ""}</SelectItem>
+ </SelectGroup>
+ <SelectGroup>
+ <SelectLabel className="text-[10px] text-muted-foreground/70 uppercase tracking-wider">other</SelectLabel>
+ <SelectItem value="openai-compatible">OpenAI Compatible</SelectItem>
+ <SelectItem value="disabled">Disabled (capture only)</SelectItem>
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </div>
</div>
{audioEngineResolution.fallbackReason && (
<Alert
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-health-check.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
index 4775abd69..03f3407c9 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
@@ -22,6 +22,12 @@ interface AudioPipelineHealth {
db_inserted: number;
total_words: number;
words_per_minute: number;
+ transcription_mode?: string;
+ segments_deferred?: number;
+ segments_batch_processed?: number;
+ batch_paused_reason?: string | null;
+ pending_transcription_segments?: number;
+ oldest_pending_transcription_at?: string | null;
transcription_paused?: boolean;
meeting_detected?: boolean;
meeting_app?: string;
@@ -56,7 +62,9 @@ function isHealthChanged(
oldHealth.frame_status !== newHealth.frame_status ||
oldHealth.audio_status !== newHealth.audio_status ||
oldHealth.ui_status !== newHealth.ui_status ||
- oldHealth.message !== newHealth.message
+ oldHealth.message !== newHealth.message ||
+ JSON.stringify(oldHealth.audio_pipeline) !==
+ JSON.stringify(newHealth.audio_pipeline)
);
}
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index efc89ba53..81c30a1eb 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -1107,6 +1107,98 @@ impl DatabaseManager {
Ok(rows)
}
+ /// Returns one orphaned audio chunk if it is currently eligible for
+ /// background transcription reconciliation.
+ pub async fn get_reconciliation_candidate_chunk_by_id(
+ &self,
+ chunk_id: i64,
+ since: DateTime<Utc>,
+ older_than: DateTime<Utc>,
+ ) -> Result<Option<UntranscribedChunk>, sqlx::Error> {
+ let row = sqlx::query_as::<_, UntranscribedChunk>(
+ "SELECT ac.id, ac.file_path, ac.timestamp
+ FROM audio_chunks ac
+ LEFT JOIN audio_transcriptions at ON ac.id = at.audio_chunk_id
+ WHERE ac.id = ?1
+ AND at.id IS NULL
+ AND ac.timestamp >= ?2
+ AND ac.timestamp <= ?3
+ AND ac.file_path NOT LIKE 'cloud://%'
+ AND NOT EXISTS (
+ SELECT 1
+ FROM meetings m
+ WHERE EXISTS (
+ SELECT 1
+ FROM meeting_transcript_segments mts
+ WHERE mts.meeting_id = m.id
+ )
+ AND julianday(ac.timestamp) >= julianday(datetime(m.meeting_start, '-60 seconds'))
+ AND julianday(ac.timestamp) <= julianday(datetime(
+ COALESCE(
+ m.meeting_end,
+ (
+ SELECT datetime(MAX(mts2.captured_at), '+10 minutes')
+ FROM meeting_transcript_segments mts2
+ WHERE mts2.meeting_id = m.id
+ )
+ ),
+ '+60 seconds'
+ ))
+ )
+ LIMIT 1",
+ )
+ .bind(chunk_id)
+ .bind(since)
+ .bind(older_than)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row)
+ }
+
+ /// Returns a compact summary of audio chunks that are ready for background
+ /// transcription reconciliation.
+ pub async fn get_reconciliation_backlog_summary(
+ &self,
+ since: DateTime<Utc>,
+ older_than: DateTime<Utc>,
+ ) -> Result<(i64, Option<DateTime<Utc>>), sqlx::Error> {
+ let summary = sqlx::query_as::<_, (i64, Option<DateTime<Utc>>)>(
+ "SELECT COUNT(*) as count, MIN(ac.timestamp) as oldest_timestamp
+ FROM audio_chunks ac
+ LEFT JOIN audio_transcriptions at ON ac.id = at.audio_chunk_id
+ WHERE at.id IS NULL
+ AND ac.timestamp >= ?1
+ AND ac.timestamp <= ?2
+ AND ac.file_path NOT LIKE 'cloud://%'
+ AND NOT EXISTS (
+ SELECT 1
+ FROM meetings m
+ WHERE EXISTS (
+ SELECT 1
+ FROM meeting_transcript_segments mts
+ WHERE mts.meeting_id = m.id
+ )
+ AND julianday(ac.timestamp) >= julianday(datetime(m.meeting_start, '-60 seconds'))
+ AND julianday(ac.timestamp) <= julianday(datetime(
+ COALESCE(
+ m.meeting_end,
+ (
+ SELECT datetime(MAX(mts2.captured_at), '+10 minutes')
+ FROM meeting_transcript_segments mts2
+ WHERE mts2.meeting_id = m.id
+ )
+ ),
+ '+60 seconds'
+ ))
+ )",
+ )
+ .bind(since)
+ .bind(older_than)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(summary)
+ }
+
/// Returns true if there are audio transcriptions from output devices
/// within the given number of seconds. Used by meeting detection to keep
/// browser-based meetings alive when the user switches tabs but audio is
diff --git a/crates/screenpipe-engine/src/routes/health.rs b/crates/screenpipe-engine/src/routes/health.rs
index a9342cd8a..f8f393fc9 100644
--- a/crates/screenpipe-engine/src/routes/health.rs
+++ b/crates/screenpipe-engine/src/routes/health.rs
@@ -5,7 +5,7 @@
use axum::{extract::State, http::StatusCode, response::Json as JsonResponse};
use oasgen::{oasgen, OaSchema};
-use chrono::{TimeZone, Utc};
+use chrono::{DateTime, TimeZone, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -24,9 +24,16 @@ use crate::ui_recorder::{tree_walker_snapshot, TreeWalkerSnapshot};
/// times per second. The response only changes meaningfully every ~1s.
static HEALTH_CACHE: std::sync::LazyLock<RwLock<(u64, Option<HealthCheckResponse>)>> =
std::sync::LazyLock::new(|| RwLock::new((0, None)));
+type AudioReconciliationBacklogCache = (i64, Option<(u64, Option<DateTime<Utc>>)>);
+static AUDIO_RECONCILIATION_BACKLOG_CACHE: std::sync::LazyLock<
+ RwLock<AudioReconciliationBacklogCache>,
+> = std::sync::LazyLock::new(|| RwLock::new((0, None)));
/// Minimum interval between full health recomputations (in seconds).
const HEALTH_CACHE_TTL_SECS: u64 = 1;
+const AUDIO_RECONCILIATION_LOOKBACK_HOURS: i64 = 24 * 7;
+const AUDIO_RECONCILIATION_FRESHNESS_DELAY_SECS: i64 = 10 * 60;
+const AUDIO_RECONCILIATION_BACKLOG_CACHE_TTL_SECS: i64 = 30;
/// Describe the most likely cause of a DB-write stall from pool stats.
/// Old message always said "pool exhaustion likely" which was wrong when the
@@ -164,6 +171,10 @@ pub struct AudioPipelineHealthInfo {
pub segments_batch_processed: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub batch_paused_reason: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pending_transcription_segments: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub oldest_pending_transcription_at: Option<chrono::DateTime<Utc>>,
// Meeting detection fields (smart mode)
#[serde(skip_serializing_if = "Option::is_none")]
pub meeting_detected: Option<bool>,
@@ -201,6 +212,42 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
JsonResponse(response)
}
+async fn get_audio_reconciliation_backlog(
+ state: &Arc<AppState>,
+ now: DateTime<Utc>,
+) -> Option<(u64, Option<DateTime<Utc>>)> {
+ {
+ let cache = AUDIO_RECONCILIATION_BACKLOG_CACHE.read().await;
+ if now.timestamp().saturating_sub(cache.0) < AUDIO_RECONCILIATION_BACKLOG_CACHE_TTL_SECS {
+ return cache.1.clone();
+ }
+ }
+
+ let since = now - chrono::Duration::hours(AUDIO_RECONCILIATION_LOOKBACK_HOURS);
+ let older_than = now - chrono::Duration::seconds(AUDIO_RECONCILIATION_FRESHNESS_DELAY_SECS);
+ let result = match state
+ .db
+ .get_reconciliation_backlog_summary(since, older_than)
+ .await
+ {
+ Ok((count, oldest)) => Some((count.max(0) as u64, oldest)),
+ Err(err) => {
+ warn!(
+ "health_check: failed to query audio transcription backlog: {}",
+ err
+ );
+ None
+ }
+ };
+
+ {
+ let mut cache = AUDIO_RECONCILIATION_BACKLOG_CACHE.write().await;
+ *cache = (now.timestamp(), result.clone());
+ }
+
+ result
+}
+
async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -266,11 +313,22 @@ async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
} else {
None
};
-
let last_audio_ts = audio_snap.last_db_write_ts;
let now = Utc::now();
let now_ts = now.timestamp() as u64;
+ let audio_reconciliation_backlog = if !state.audio_disabled {
+ get_audio_reconciliation_backlog(state, now).await
+ } else {
+ None
+ };
+ let pending_transcription_segments = audio_reconciliation_backlog
+ .as_ref()
+ .map(|(count, _)| *count)
+ .filter(|count| *count > 0);
+ let oldest_pending_transcription_at =
+ audio_reconciliation_backlog.and_then(|(_, oldest)| oldest);
+
// 60 seconds — tight enough to detect real stalls, loose enough to
// tolerate adaptive FPS (0.1-0.5 fps) and brief DB contention spikes.
let threshold_secs = 60u64;
@@ -725,6 +783,8 @@ async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
None
},
batch_paused_reason: None, // populated by idle detector if available
+ pending_transcription_segments,
+ oldest_pending_transcription_at,
meeting_detected,
meeting_app,
})
diff --git a/crates/screenpipe-engine/src/routes/retranscribe.rs b/crates/screenpipe-engine/src/routes/retranscribe.rs
index 140b844fb..a3726171d 100644
--- a/crates/screenpipe-engine/src/routes/retranscribe.rs
+++ b/crates/screenpipe-engine/src/routes/retranscribe.rs
@@ -85,6 +85,29 @@ pub struct MeetingRetranscribeResponse {
pub replaced_segments: u64,
}
+#[derive(Debug, Serialize)]
+pub struct AudioReconciliationBacklogItem {
+ pub audio_chunk_id: i64,
+ pub captured_at: DateTime<Utc>,
+ pub age_seconds: i64,
+ pub file_path: String,
+ pub file_size_bytes: Option<u64>,
+ pub likely_empty: bool,
+ pub status: String,
+}
+
+#[derive(Debug, Serialize)]
+pub struct AudioReconciliationBacklogResponse {
+ pub pending: usize,
+ pub items: Vec<AudioReconciliationBacklogItem>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct AudioReconciliationDropResponse {
+ pub audio_chunk_id: i64,
+ pub dropped: bool,
+}
+
#[derive(Debug, Clone, Eq, PartialEq)]
struct ChunkDevice {
name: String,
@@ -102,6 +125,10 @@ struct PendingMeetingSegment {
const MEETING_RETRANSCRIBE_MAX_DURATION_SECS: i64 = 2 * 60 * 60;
const MEETING_RETRANSCRIBE_MAX_GAP_SECS: i64 = 60;
const ASSUMED_AUDIO_CHUNK_SECS: u64 = 30;
+const AUDIO_RECONCILIATION_LOOKBACK_HOURS: i64 = 24 * 7;
+const AUDIO_RECONCILIATION_FRESHNESS_DELAY_SECS: i64 = 10 * 60;
+const AUDIO_RECONCILIATION_BACKLOG_LIMIT: i64 = 100;
+const AUDIO_RECONCILIATION_LIKELY_EMPTY_BYTES: u64 = 32 * 1024;
fn error_response(status: StatusCode, msg: String) -> Response {
(status, JsonResponse(json!({"error": msg}))).into_response()
@@ -121,6 +148,118 @@ fn into_vocabulary(entries: Vec<MeetingRetranscribeVocabularyEntry>) -> Vec<Voca
.collect()
}
+fn audio_reconciliation_window() -> (DateTime<Utc>, DateTime<Utc>, DateTime<Utc>) {
+ let now = Utc::now();
+ let since = now - chrono::Duration::hours(AUDIO_RECONCILIATION_LOOKBACK_HOURS);
+ let older_than = now - chrono::Duration::seconds(AUDIO_RECONCILIATION_FRESHNESS_DELAY_SECS);
+ (now, since, older_than)
+}
+
+pub async fn audio_reconciliation_backlog_handler(State(state): State<Arc<AppState>>) -> Response {
+ let (now, since, older_than) = audio_reconciliation_window();
+ let pending = match state
+ .db
+ .get_reconciliation_backlog_summary(since, older_than)
+ .await
+ {
+ Ok((count, _)) => count.max(0) as usize,
+ Err(e) => {
+ error!(
+ "failed to query audio reconciliation backlog summary: {}",
+ e
+ );
+ return error_response(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("db query failed: {}", e),
+ );
+ }
+ };
+
+ let chunks = match state
+ .db
+ .get_reconciliation_candidate_chunks(since, older_than, AUDIO_RECONCILIATION_BACKLOG_LIMIT)
+ .await
+ {
+ Ok(chunks) => chunks,
+ Err(e) => {
+ error!("failed to query audio reconciliation backlog items: {}", e);
+ return error_response(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("db query failed: {}", e),
+ );
+ }
+ };
+
+ let items = chunks
+ .into_iter()
+ .map(|chunk| {
+ let file_size_bytes = std::fs::metadata(&chunk.file_path)
+ .ok()
+ .map(|metadata| metadata.len());
+
+ AudioReconciliationBacklogItem {
+ audio_chunk_id: chunk.id,
+ captured_at: chunk.timestamp,
+ age_seconds: (now - chunk.timestamp).num_seconds().max(0),
+ file_path: chunk.file_path,
+ file_size_bytes,
+ likely_empty: file_size_bytes
+ .is_some_and(|size| size < AUDIO_RECONCILIATION_LIKELY_EMPTY_BYTES),
+ status: "waiting".to_string(),
+ }
+ })
+ .collect();
+
+ JsonResponse(json!(AudioReconciliationBacklogResponse { pending, items })).into_response()
+}
+
+pub async fn drop_audio_reconciliation_chunk_handler(
+ State(state): State<Arc<AppState>>,
+ Path(audio_chunk_id): Path<i64>,
+) -> Response {
+ let (_, since, older_than) = audio_reconciliation_window();
+ match state
+ .db
+ .get_reconciliation_candidate_chunk_by_id(audio_chunk_id, since, older_than)
+ .await
+ {
+ Ok(Some(_)) => {}
+ Ok(None) => {
+ return error_response(
+ StatusCode::CONFLICT,
+ "audio chunk is no longer waiting for background transcription".into(),
+ );
+ }
+ Err(e) => {
+ error!(
+ "failed to verify audio reconciliation chunk {}: {}",
+ audio_chunk_id, e
+ );
+ return error_response(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("db query failed: {}", e),
+ );
+ }
+ }
+
+ if let Err(e) = state.db.delete_audio_chunk(audio_chunk_id).await {
+ error!(
+ "failed to drop audio reconciliation chunk {}: {}",
+ audio_chunk_id, e
+ );
+ return error_response(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("db delete failed: {}", e),
+ );
+ }
+
+ JsonResponse(json!(AudioReconciliationDropResponse {
+ audio_chunk_id,
+ dropped: true,
+ }))
+ .into_response()
+}
+
pub async fn retranscribe_handler(
State(state): State<Arc<AppState>>,
Json(request): Json<RetranscribeRequest>,
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index 06b4f806f..d34ac13b9 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -680,6 +680,16 @@ impl SCServer {
.route("/vision/metrics", get(vision_metrics_handler))
.route("/audio/metrics", get(audio_metrics_handler))
// Retranscribe/transcribe (not in OpenAPI spec — opaque Response / multipart)
+ .route(
+ "/audio/reconciliation/backlog",
+ get(crate::routes::retranscribe::audio_reconciliation_backlog_handler),
+ )
+ .route(
+ "/audio/reconciliation/backlog/:audio_chunk_id",
+ axum::routing::delete(
+ crate::routes::retranscribe::drop_audio_reconciliation_chunk_handler,
+ ),
+ )
.route(
"/audio/retranscribe",
axum::routing::post(crate::routes::retranscribe::retranscribe_handler),
diff --git a/docs/assets/audio-transcription-backlog-status.png b/docs/assets/audio-transcription-backlog-status.png
new file mode 100644
index 000000000..a72fbb56a
Binary files /dev/null and b/docs/assets/audio-transcription-backlog-status.png differ
diff --git a/docs/assets/audio-transcription-backlog-status.svg b/docs/assets/audio-transcription-backlog-status.svg
new file mode 100644
index 000000000..1bee3fd71
--- /dev/null
+++ b/docs/assets/audio-transcription-backlog-status.svg
@@ -0,0 +1,122 @@
+<svg width="1200" height="760" viewBox="0 0 1200 760" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect width="1200" height="760" fill="#050505"/>
+ <rect x="36" y="34" width="1128" height="692" rx="18" fill="#0A0A0A" stroke="#FFFFFF" stroke-opacity="0.26"/>
+
+ <rect x="64" y="62" width="214" height="636" rx="14" fill="#080808" stroke="#FFFFFF" stroke-opacity="0.14"/>
+ <text x="88" y="108" fill="#FFFFFF" font-size="22" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">settings</text>
+ <text x="88" y="166" fill="#FFFFFF" fill-opacity="0.44" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">app</text>
+ <text x="98" y="207" fill="#FFFFFF" fill-opacity="0.56" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">display</text>
+ <text x="98" y="247" fill="#FFFFFF" fill-opacity="0.56" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">general</text>
+ <text x="98" y="287" fill="#FFFFFF" fill-opacity="0.56" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">ai models</text>
+ <rect x="82" y="314" width="172" height="42" rx="10" fill="#FFFFFF"/>
+ <text x="98" y="341" fill="#050505" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">recording</text>
+ <text x="98" y="392" fill="#FFFFFF" fill-opacity="0.56" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">shortcuts</text>
+ <text x="88" y="454" fill="#FFFFFF" fill-opacity="0.44" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">data</text>
+ <text x="98" y="496" fill="#FFFFFF" fill-opacity="0.56" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">usage</text>
+ <text x="98" y="536" fill="#FFFFFF" fill-opacity="0.56" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">privacy</text>
+ <text x="98" y="576" fill="#FFFFFF" fill-opacity="0.56" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">storage</text>
+
+ <rect x="308" y="62" width="828" height="636" rx="14" fill="#0D0D0D" stroke="#FFFFFF" stroke-opacity="0.14"/>
+ <rect x="308" y="62" width="828" height="74" rx="14" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.12"/>
+ <text x="342" y="107" fill="#FFFFFF" font-size="24" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">recording</text>
+ <text x="342" y="166" fill="#FFFFFF" fill-opacity="0.58" font-size="15" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">Screen and audio recording preferences</text>
+
+ <text x="342" y="219" fill="#FFFFFF" fill-opacity="0.5" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="700">audio</text>
+
+ <rect x="342" y="242" width="760" height="68" rx="10" fill="#080808" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <text x="374" y="274" fill="#FFFFFF" font-size="17" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">audio recording</text>
+ <text x="374" y="295" fill="#FFFFFF" fill-opacity="0.52" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">Capture audio from microphone and system</text>
+ <rect x="1010" y="263" width="58" height="26" rx="13" fill="#FFFFFF"/>
+ <circle cx="1055" cy="276" r="10" fill="#050505"/>
+
+ <rect x="342" y="326" width="760" height="76" rx="10" fill="#080808" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <text x="374" y="360" fill="#FFFFFF" font-size="17" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">transcription engine</text>
+ <rect x="776" y="345" width="34" height="34" rx="8" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.26"/>
+ <path d="M787 354H799M787 361H799M787 368H795" stroke="#FFFFFF" stroke-opacity="0.82" stroke-width="2" stroke-linecap="round"/>
+ <rect x="800" y="336" width="32" height="20" rx="10" fill="#FFFFFF"/>
+ <text x="807" y="350" fill="#050505" font-size="10" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="900">18</text>
+ <rect x="822" y="345" width="246" height="34" rx="8" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.18"/>
+ <text x="846" y="367" fill="#FFFFFF" fill-opacity="0.78" font-size="14" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">Whisper Turbo (fast)</text>
+
+ <rect x="342" y="422" width="760" height="88" rx="10" fill="#080808" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <text x="374" y="456" fill="#FFFFFF" font-size="17" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">live meeting notes</text>
+ <text x="374" y="480" fill="#FFFFFF" fill-opacity="0.52" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">Meeting-only live captions, separate from background transcription</text>
+ <rect x="1010" y="452" width="58" height="26" rx="13" fill="#FFFFFF" fill-opacity="0.18"/>
+ <circle cx="1023" cy="465" r="10" fill="#FFFFFF" fill-opacity="0.9"/>
+
+ <rect x="342" y="530" width="760" height="76" rx="10" fill="#080808" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <text x="374" y="564" fill="#FFFFFF" font-size="17" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">batch transcription</text>
+ <text x="374" y="588" fill="#FFFFFF" fill-opacity="0.52" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">Longer audio chunks for better transcription quality</text>
+ <rect x="1010" y="554" width="58" height="26" rx="13" fill="#FFFFFF" fill-opacity="0.18"/>
+ <circle cx="1023" cy="567" r="10" fill="#FFFFFF" fill-opacity="0.9"/>
+
+ <rect x="0" y="0" width="1200" height="760" fill="#000000" fill-opacity="0.52"/>
+ <rect x="230" y="122" width="740" height="516" rx="14" fill="#0B0B0B" stroke="#FFFFFF" stroke-opacity="0.28"/>
+ <text x="266" y="174" fill="#FFFFFF" font-size="22" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">background transcription backlog</text>
+ <text x="266" y="204" fill="#FFFFFF" fill-opacity="0.56" font-size="14" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">Audio chunks waiting for background transcription reconciliation.</text>
+
+ <rect x="266" y="232" width="190" height="58" rx="6" fill="#070707" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <text x="286" y="256" fill="#FFFFFF" fill-opacity="0.54" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">waiting</text>
+ <text x="286" y="278" fill="#FFFFFF" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">18</text>
+ <rect x="476" y="232" width="190" height="58" rx="6" fill="#070707" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <text x="496" y="256" fill="#FFFFFF" fill-opacity="0.54" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">oldest</text>
+ <text x="496" y="278" fill="#FFFFFF" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">24m</text>
+ <rect x="686" y="232" width="218" height="58" rx="6" fill="#070707" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <text x="706" y="256" fill="#FFFFFF" fill-opacity="0.54" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">worker</text>
+ <text x="706" y="278" fill="#FFFFFF" font-size="16" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-weight="800">running</text>
+
+ <rect x="266" y="318" width="638" height="220" rx="4" fill="#050505" stroke="#FFFFFF" stroke-opacity="0.18"/>
+ <rect x="266" y="318" width="638" height="36" fill="#121212"/>
+ <line x1="266" y1="354" x2="904" y2="354" stroke="#FFFFFF" stroke-opacity="0.16"/>
+ <line x1="342" y1="318" x2="342" y2="538" stroke="#FFFFFF" stroke-opacity="0.12"/>
+ <line x1="420" y1="318" x2="420" y2="538" stroke="#FFFFFF" stroke-opacity="0.12"/>
+ <line x1="552" y1="318" x2="552" y2="538" stroke="#FFFFFF" stroke-opacity="0.12"/>
+ <line x1="730" y1="318" x2="730" y2="538" stroke="#FFFFFF" stroke-opacity="0.12"/>
+ <line x1="808" y1="318" x2="808" y2="538" stroke="#FFFFFF" stroke-opacity="0.12"/>
+
+ <text x="282" y="341" fill="#FFFFFF" fill-opacity="0.55" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">chunk</text>
+ <text x="358" y="341" fill="#FFFFFF" fill-opacity="0.55" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">age</text>
+ <text x="436" y="341" fill="#FFFFFF" fill-opacity="0.55" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">captured</text>
+ <text x="568" y="341" fill="#FFFFFF" fill-opacity="0.55" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">file</text>
+ <text x="746" y="341" fill="#FFFFFF" fill-opacity="0.55" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">status</text>
+ <text x="824" y="341" fill="#FFFFFF" fill-opacity="0.55" font-size="12" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">actions</text>
+
+ <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="12">
+ <text x="282" y="382" fill="#FFFFFF">39102</text>
+ <text x="358" y="382" fill="#FFFFFF">24m</text>
+ <text x="436" y="382" fill="#FFFFFF" fill-opacity="0.64">7:18 AM</text>
+ <text x="568" y="382" fill="#FFFFFF" fill-opacity="0.64">mic_0718.wav</text>
+ <rect x="746" y="366" width="52" height="22" rx="11" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <text x="758" y="382" fill="#FFFFFF" fill-opacity="0.72">wait</text>
+ <rect x="824" y="362" width="28" height="28" rx="6" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <path d="M835 370L845 376L835 382V370Z" fill="#FFFFFF" fill-opacity="0.86"/>
+ <rect x="860" y="362" width="28" height="28" rx="6" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <path d="M870 370H878M872 370V382M876 370V382M870 382H878" stroke="#FFFFFF" stroke-opacity="0.72" stroke-width="1.5" stroke-linecap="round"/>
+
+ <text x="282" y="424" fill="#FFFFFF">39103</text>
+ <text x="358" y="424" fill="#FFFFFF">23m</text>
+ <text x="436" y="424" fill="#FFFFFF" fill-opacity="0.64">7:19 AM</text>
+ <text x="568" y="424" fill="#FFFFFF" fill-opacity="0.64">system_0719.wav</text>
+ <rect x="746" y="408" width="52" height="22" rx="11" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <text x="758" y="424" fill="#FFFFFF" fill-opacity="0.72">wait</text>
+ <rect x="824" y="404" width="28" height="28" rx="6" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <path d="M835 412L845 418L835 424V412Z" fill="#FFFFFF" fill-opacity="0.86"/>
+ <rect x="860" y="404" width="28" height="28" rx="6" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <path d="M870 412H878M872 412V424M876 412V424M870 424H878" stroke="#FFFFFF" stroke-opacity="0.72" stroke-width="1.5" stroke-linecap="round"/>
+
+ <text x="282" y="466" fill="#FFFFFF">39104</text>
+ <text x="358" y="466" fill="#FFFFFF">22m</text>
+ <text x="436" y="466" fill="#FFFFFF" fill-opacity="0.64">7:20 AM</text>
+ <text x="568" y="466" fill="#FFFFFF" fill-opacity="0.64">mic_0720.wav</text>
+ <rect x="746" y="450" width="52" height="22" rx="11" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <text x="758" y="466" fill="#FFFFFF" fill-opacity="0.72">wait</text>
+ <rect x="824" y="446" width="28" height="28" rx="6" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <path d="M835 454L845 460L835 466V454Z" fill="#FFFFFF" fill-opacity="0.86"/>
+ <rect x="860" y="446" width="28" height="28" rx="6" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.22"/>
+ <path d="M870 454H878M872 454V466M876 454V466M870 466H878" stroke="#FFFFFF" stroke-opacity="0.72" stroke-width="1.5" stroke-linecap="round"/>
+ </g>
+
+ <text x="266" y="577" fill="#FFFFFF" fill-opacity="0.48" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">A small icon keeps settings compact; the modal handles row-level review and cleanup.</text>
+ <rect x="812" y="558" width="92" height="34" rx="8" fill="#111111" stroke="#FFFFFF" stroke-opacity="0.24"/>
+ <text x="836" y="580" fill="#FFFFFF" fill-opacity="0.78" font-size="13" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">refresh</text>
+</svg>