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

release-app fix build

Louis Beaumont3caa7a0de6d0
diff --git a/screenpipe-app-tauri/app/identify-speakers/page.tsx b/screenpipe-app-tauri/app/identify-speakers/page.tsx
deleted file mode 100644
index de5488fd7..000000000
--- a/screenpipe-app-tauri/app/identify-speakers/page.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-"use client";
-
-import IdentifySpeakers from "@/components/identify-speakers";
-import { useState } from "react";
-
-export default function IdentifySpeakersPage() {
- const [_, setShowIdentifySpeakers] = useState(true);
- return (
- <IdentifySpeakers
- showIdentifySpeakers={true}
- setShowIdentifySpeakers={setShowIdentifySpeakers}
- />
- );
-}
diff --git a/screenpipe-app-tauri/components/app-sidebar.tsx b/screenpipe-app-tauri/components/app-sidebar.tsx
deleted file mode 100644
index 7b7154172..000000000
--- a/screenpipe-app-tauri/components/app-sidebar.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { History, Trash2 } from "lucide-react"
-import { formatDistanceToNow } from "date-fns"
-import {
- Sidebar,
- SidebarContent,
- SidebarGroup,
- SidebarGroupContent,
- SidebarGroupLabel,
- SidebarMenu,
- SidebarMenuButton,
- SidebarMenuItem,
- SidebarMenuAction,
-} from "@/components/ui/sidebar"
-import { ScrollArea } from "@/components/ui/scroll-area"
-import { SearchHistory } from "@/lib/types/history"
-import { cn } from "@/lib/utils"
-
-interface AppSidebarProps {
- searches?: SearchHistory[]
- currentSearchId?: string | null
- onSelectSearch?: (id: string) => void
- onDeleteSearch?: (id: string) => void
-}
-
-export function AppSidebar({
- searches = [],
- currentSearchId,
- onSelectSearch,
- onDeleteSearch,
-}: AppSidebarProps) {
- return (
- <Sidebar className="border-r bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
- <SidebarContent className="pt-12">
- <ScrollArea className="h-[calc(100vh-4rem)]">
- <SidebarGroup>
- <SidebarGroupLabel className="px-4 py-2 text-xs font-medium text-muted-foreground/70">
- search history
- </SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu className="space-y-0.5 px-2">
- {searches.length === 0 ? (
- <div className="px-4 py-2 text-sm text-muted-foreground">
- no searches yet
- </div>
- ) : (
- searches.map((search) => (
- <SidebarMenuItem
- key={search.id}
- className={cn(
- "group relative",
- "after:absolute after:bottom-0 after:left-3 after:right-3 after:h-px after:bg-border",
- "last:after:hidden" // Hide border on last item
- )}
- >
- <SidebarMenuButton
- isActive={currentSearchId === search.id}
- onClick={() => onSelectSearch?.(search.id)}
- tooltip={search.query || "untitled search"}
- className={cn(
- "relative w-full px-3 py-7 text-sm outline-none transition-colors",
- "hover:bg-accent/40 group/button",
- currentSearchId === search.id && "bg-accent/50"
- )}
- >
- <div className="flex flex-col gap-1 min-w-0 pr-8"> {/* Added right padding for delete icon */}
- <span className="truncate font-medium">
- {search.query || "untitled search"}
- </span>
- <span className="text-[11px] text-muted-foreground/80 truncate">
- {formatDistanceToNow(new Date(search.timestamp), {
- addSuffix: true,
- })}
- </span>
- </div>
- <SidebarMenuAction
- onClick={(e) => {
- e.stopPropagation()
- onDeleteSearch?.(search.id)
- }}
- showOnHover
- className={cn(
- "absolute right-3 top-1/2 -translate-y-1/2",
- "opacity-0 transition-all duration-200",
- "group-hover/button:opacity-100",
- "hover:bg-background/80 hover:text-destructive",
- "h-7 w-7 rounded-md flex items-center justify-center"
- )}
- >
- <Trash2 className="h-4 w-4" />
- </SidebarMenuAction>
- </SidebarMenuButton>
- </SidebarMenuItem>
- ))
- )}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
- </ScrollArea>
- </SidebarContent>
- </Sidebar>
- )
-}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/components/context-usage-indicator.tsx b/screenpipe-app-tauri/components/context-usage-indicator.tsx
deleted file mode 100644
index daa188abd..000000000
--- a/screenpipe-app-tauri/components/context-usage-indicator.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import React from "react";
-import { motion } from "framer-motion";
-import { AlertTriangle } from "lucide-react";
-
-interface ContextUsageIndicatorProps {
- currentSize: number;
- maxSize: number;
-}
-
-export function ContextUsageIndicator({
- currentSize,
- maxSize,
-}: ContextUsageIndicatorProps) {
- const percentage = Math.min((currentSize / maxSize) * 100, 100);
- const circumference = 2 * Math.PI * 14;
-
- return (
- <div className="w-8 h-8 relative">
- <svg width="32" height="32" viewBox="0 0 32 32">
- <circle
- cx="16"
- cy="16"
- r="14"
- fill="none"
- stroke="#e2e8f0"
- strokeWidth="2"
- />
- <motion.circle
- cx="16"
- cy="16"
- r="14"
- fill="none"
- stroke="black"
- strokeWidth="2"
- strokeDasharray={circumference}
- initial={{ strokeDashoffset: circumference }}
- animate={{ strokeDashoffset: circumference - (percentage / 100) * circumference }}
- transition={{ duration: 0.5 }}
- />
- </svg>
- {percentage > 90 && (
- <AlertTriangle className="w-5 h-5 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-red-500" />
- )}
- </div>
- );
-}
diff --git a/screenpipe-app-tauri/components/identify-speakers.tsx b/screenpipe-app-tauri/components/identify-speakers.tsx
deleted file mode 100644
index bf048e844..000000000
--- a/screenpipe-app-tauri/components/identify-speakers.tsx
+++ /dev/null
@@ -1,1350 +0,0 @@
-"use client";
-
-import { useState, useEffect } from "react";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog";
-import { useSettings } from "@/lib/hooks/use-settings";
-import { useToast } from "./ui/use-toast";
-import {
- X,
- Fingerprint,
- Check,
- ChevronRight,
- Save,
- Ghost,
- Trash,
-} from "lucide-react";
-import { usePostHog } from "posthog-js/react";
-import { Badge } from "./ui/badge";
-import { Input } from "./ui/input";
-import { cn, getFileSize, keysToCamelCase } from "@/lib/utils";
-import { VideoComponent } from "./video";
-import { AudioSample, MeetingSegment, Speaker } from "@/lib/types";
-import { isSea } from "node:sea";
-import { motion } from "framer-motion";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "./ui/card";
-
-interface UnnamedSpeaker {
- id: number;
- name: string;
- metadata: string;
-}
-
-export default function IdentifySpeakers({
- showIdentifySpeakers,
- setShowIdentifySpeakers,
- segments,
- className,
-}: {
- showIdentifySpeakers: boolean;
- setShowIdentifySpeakers: (show: boolean) => void;
- segments?: MeetingSegment[];
- className?: string;
-}) {
- const posthog = usePostHog();
- const { settings } = useSettings();
- const [unnamedSpeakers, setUnnamedSpeakers] = useState<Speaker[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const { toast } = useToast();
- const [showError, setShowError] = useState(false);
- const [currentSpeakerIndex, setCurrentSpeakerIndex] = useState(0);
- const [showHallucinationConfirm, setShowHallucinationConfirm] =
- useState(false);
- const [showNameUpdateConfirm, setShowNameUpdateConfirm] = useState(false);
- const [speakerSearchTerm, setSpeakerSearchTerm] = useState<string>("");
- const [speakers, setSpeakers] = useState<Speaker[]>([]);
- const [isSearching, setIsSearching] = useState(false);
- const [showMergeConfirm, setShowMergeConfirm] = useState(false);
- const [selectedExistingSpeaker, setSelectedExistingSpeaker] =
- useState<Speaker | null>(null);
- const [segmentSpeakerIds, setSegmentSpeakerIds] = useState<number[]>([]);
- const [similarSpeakers, setSimilarSpeakers] = useState<Speaker[]>([]);
- const [isFetchingSimilarSpeakers, setIsFetchingSimilarSpeakers] =
- useState(false);
- const [speakerIdentified, setSpeakerIdentified] = useState(false);
- const [similarSpeakerIndex, setSimilarSpeakerIndex] = useState(0);
- const [showRemoveSpeakerConfirm, setShowRemoveSpeakerConfirm] =
- useState(false);
- const [showSpeakerNames, setShowSpeakerNames] = useState(false);
- const [mounted, setMounted] = useState(false);
- useEffect(() => {
- setMounted(true);
- }, []);
- useEffect(() => {
- if (!isSearching && speakers.length > 0) {
- setShowSpeakerNames(true);
- }
- }, [isSearching, speakers]);
-
- useEffect(() => {
- if (speakerSearchTerm) {
- fetchSpeakers(speakerSearchTerm);
- }
- }, [speakerSearchTerm]);
-
- useEffect(() => {
- if (unnamedSpeakers.length > 0) {
- fetchSimilarSpeakers(unnamedSpeakers[currentSpeakerIndex].id);
- }
- }, [currentSpeakerIndex]);
-
- useEffect(() => {
- speakerIdentified &&
- setSimilarSpeakers(similarSpeakers.filter((s) => !s.name));
- }, [speakerIdentified]);
-
- useEffect(() => {
- if (posthog) {
- posthog.identify(settings.userId);
- posthog.people.set({
- userId: settings.userId,
- });
- }
- }, [posthog, settings.userId]);
-
- useEffect(() => {
- if (segments) {
- setSegmentSpeakerIds(segments.map((segment) => segment.speaker.id));
- }
- }, [segments]);
-
- useEffect(() => {
- if (showIdentifySpeakers) {
- loadUnnamedSpeakers();
- posthog?.capture("identify_speakers_opened", {
- userId: settings.userId,
- source: segments ? "meeting_history" : "menu",
- });
- } else {
- posthog?.capture("identify_speakers_closed", {
- userId: settings.userId,
- source: segments ? "meeting_history" : "menu",
- });
- setSpeakerIdentified(false);
- setSelectedExistingSpeaker(null);
- setSpeakerSearchTerm("");
- setSpeakers([]);
- setSimilarSpeakers([]);
- setCurrentSpeakerIndex(0);
- }
- /* eslint-disable-next-line react-hooks/exhaustive-deps */
- }, [showIdentifySpeakers, settings.userId, posthog]);
-
- useEffect(() => {
- setShowError(!!error);
- }, [error]);
-
- useEffect(() => {
- if (showError) {
- setTimeout(() => {
- setShowError(false);
- }, 5000);
- }
- }, [showError]);
-
- async function loadUnnamedSpeakers() {
- setLoading(true);
- try {
- await fetchUnnamedSpeakers();
- } catch (err) {
- setError("failed to load unnamed speakers");
- } finally {
- setLoading(false);
- }
- }
-
- async function fetchSpeakers(searchTerm: string) {
- setIsSearching(true);
-
- try {
- const response = await fetch(
- `http://localhost:3030/speakers/search?name=${searchTerm}`
- );
- if (!response.ok) {
- throw new Error("failed to fetch speakers");
- }
- const result = await response.json();
- setSpeakers(result);
- } catch (error) {
- console.error("error fetching speakers:", error);
- setError("failed to fetch speakers");
- } finally {
- setIsSearching(false);
- }
- }
-
- async function fetchSimilarSpeakers(speakerId: number) {
- setIsFetchingSimilarSpeakers(true);
-
- console.log("fetching similar speakers for", speakerId);
- try {
- const response = await fetch(
- `http://localhost:3030/speakers/similar?speaker_id=${speakerId}&limit=5`
- );
- if (!response.ok) {
- throw new Error("failed to fetch similar speakers");
- }
- const result = await response.json();
-
- const updatedUnnamedSpeakers = result.map((speaker: UnnamedSpeaker) => ({
- ...speaker,
- metadata: speaker.metadata ? JSON.parse(speaker.metadata) : undefined,
- }));
- const camelCaseResult: Speaker[] = updatedUnnamedSpeakers.map(
- keysToCamelCase<Speaker>
- );
-
- let similarSpeakersResult: Speaker[] = [];
- for (const speaker of camelCaseResult) {
- let longestAudioSample = speaker.metadata?.audioSamples[0];
- let longestAudioPathSize = -Infinity;
- for (const sample of speaker.metadata?.audioSamples || []) {
- const size = await getFileSize(sample.path);
- if (size > longestAudioPathSize) {
- longestAudioSample = sample;
- longestAudioPathSize = size;
- }
- }
- similarSpeakersResult.push({
- ...speaker,
- metadata: {
- audioSamples: [
- {
- path: longestAudioSample?.path || "",
- transcript: longestAudioSample?.transcript || "",
- startTime: longestAudioSample?.startTime,
- endTime: longestAudioSample?.endTime,
- },
- ],
- },
- });
- }
-
- setSimilarSpeakers(similarSpeakersResult);
- } catch (error) {
- console.error("error fetching similar speakers:", error);
- setError("failed to fetch similar speakers");
- } finally {
- setIsFetchingSimilarSpeakers(false);
- }
- }
-
- async function fetchUnnamedSpeakers() {
- setLoading(true);
- try {
- // Always fetch from the last 7x24 hours
-
- const response = await fetch(
- `http://localhost:3030/speakers/unnamed?limit=1&offset=0${
- segmentSpeakerIds.length > 0
- ? `&speaker_ids=${segmentSpeakerIds.join(",")}`
- : ""
- }`
- );
- if (!response.ok) {
- throw new Error("failed to fetch unnamed speakers");
- }
- const result = await response.json();
- const updatedUnnamedSpeakers = result.map((speaker: UnnamedSpeaker) => ({
- ...speaker,
- metadata: speaker.metadata ? JSON.parse(speaker.metadata) : undefined,
- }));
- const camelCaseResult = updatedUnnamedSpeakers.map(
- keysToCamelCase<Speaker>
- );
-
- const results: Speaker[] = await camelCaseResult.map(
- async (speaker: Speaker) => {
- const durations: Map<string, number> = new Map();
- for (const sample of speaker.metadata?.audioSamples || []) {
- const size = (sample.endTime ?? 0) - (sample.startTime ?? 0);
- durations.set(sample.path, size);
- }
-
- return {
- ...speaker,
- metadata: {
- ...speaker.metadata,
- audioSamples: speaker.metadata?.audioSamples.sort(
- (a: AudioSample, b: AudioSample) =>
- (durations.get(b.path) || 0) - (durations.get(a.path) || 0)
- ),
- },
- };
- }
- );
-
- let sortedResults = await Promise.all(results);
- console.log("results", sortedResults);
-
- setUnnamedSpeakers(sortedResults);
- } catch (err) {
- setError(
- "some trouble fetching new meetings. please check health status."
- );
- console.error("fetch error:", err);
- } finally {
- setLoading(false);
- }
- }
-
- const handleRefresh = async () => {
- setSpeakers([]);
- try {
- await fetchUnnamedSpeakers();
- toast({
- title: "speakers refreshed",
- description: "your speaker identification has been updated.",
- });
- } catch (error) {
- console.error("error refreshing meetings:", error);
- toast({
- title: "refresh failed",
- description:
- "failed to refresh speaker identification. please try again.",
- variant: "destructive",
- });
- } finally {
- setSpeakerSearchTerm("");
- setSpeakerIdentified(false);
- setSelectedExistingSpeaker(null);
- }
- };
-
- const handleUpdateSpeakerName = async (newName: string) => {
- // use the endpoint /speakers/update to update the name
- try {
- await fetch(`http://localhost:3030/speakers/update`, {
- method: "POST",
- body: JSON.stringify({
- id: unnamedSpeakers[currentSpeakerIndex].id,
- name: newName,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- });
- setSpeakerIdentified(true);
- } catch (error) {
- console.error("error updating speaker name:", error);
- toast({
- title: "error",
- description: "failed to update speaker name. please try again.",
- variant: "destructive",
- });
- }
- };
-
- const handleRemoveSpeaker = async () => {
- try {
- await fetch(`http://localhost:3030/speakers/delete`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- id: unnamedSpeakers[currentSpeakerIndex].id,
- }),
- });
-
- handleRefresh();
- } catch (error) {
- console.error("error removing speaker:", error);
- toast({
- title: "error",
- description: "failed to remove speaker. please try again.",
- variant: "destructive",
- });
- }
- };
-
- const handleMergeSpeakers = async () => {
- if (selectedExistingSpeaker) {
- try {
- // Add API call to merge speakers
- await fetch(`http://localhost:3030/speakers/merge`, {
- method: "POST",
- body: JSON.stringify({
- speaker_to_merge_id: unnamedSpeakers[currentSpeakerIndex].id,
- speaker_to_keep_id: selectedExistingSpeaker.id,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- });
-
- toast({
- title: "speakers merged",
- description: "the speakers have been successfully merged",
- });
-
- if (selectedExistingSpeaker.name) {
- setSpeakerIdentified(true);
- setSpeakerSearchTerm(selectedExistingSpeaker.name);
- }
-
- setSimilarSpeakers(similarSpeakers.filter((s) => !s.name));
-
- setUnnamedSpeakers(
- unnamedSpeakers.map((s) => ({
- ...s,
- id:
- s.id === unnamedSpeakers[currentSpeakerIndex].id
- ? selectedExistingSpeaker.id
- : s.id,
- }))
- );
- } catch (error) {
- console.error("error merging speakers:", error);
- toast({
- title: "error",
- description: "failed to merge speakers. please try again.",
- variant: "destructive",
- });
- }
- }
- setShowMergeConfirm(false);
- };
-
- const handleMarkSpeakerAsHallucination = async () => {
- // use the endpoint /speakers/hallucination to mark the speaker as hallucination
- try {
- await fetch(`http://localhost:3030/speakers/hallucination`, {
- method: "POST",
- body: JSON.stringify({
- speaker_id: unnamedSpeakers[currentSpeakerIndex].id,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- });
- } catch (error) {
- console.error("error ignoring speaker:", error);
- toast({
- title: "error",
- description: "failed to ignore speaker. please try again.",
- variant: "destructive",
- });
- }
- };
-
- // 4. Return null on first render to avoid hydration mismatch
- if (!mounted) {
- return null;
- }
-
- return segments ? (
- <Dialog open={showIdentifySpeakers} onOpenChange={setShowIdentifySpeakers}>
- <DialogTrigger asChild>
- <Button
- onClick={() => setShowIdentifySpeakers(true)}
- size="sm"
- className="text-xs bg-black text-white hover:bg-gray-800"
- >
- <Fingerprint className="mr-2 h-4 w-4" />
- identify speakers
- </Button>
- </DialogTrigger>
- <DialogContent className="max-w-[90vw] w-full max-h-[90vh] h-full">
- <DialogHeader className="py-4">
- <DialogTitle className="flex items-center justify-between">
- <div className="flex items-center">
- identify speakers based on recent audio clips
- <Badge variant="secondary" className="ml-2">
- experimental
- </Badge>
- </div>
- </DialogTitle>
- </DialogHeader>
- <div className="flex-grow overflow-auto min-h-[600px] flex flex-col">
- {loading ? (
- <div className="space-y-6 min-h-[600px]">
- {[1, 2, 3].map((i) => (
- <div key={i} className="p-4 border rounded animate-pulse">
- <div className="h-6 bg-gray-200 rounded w-3/4 mb-4"></div>
- <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
- <div className="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
- <div className="h-20 bg-gray-200 rounded mb-2"></div>
- <div className="h-4 bg-gray-200 rounded w-1/3"></div>
- </div>
- ))}
- </div>
- ) : (
- <div className="min-h-[600px] flex flex-col">
- {showError && error && (
- <div
- className="bg-gray-100 border-l-4 border-black text-gray-700 p-4 mb-4 flex justify-between items-center"
- role="alert"
- >
- <div>
- <p className="font-bold">warning</p>
- <p>{error}</p>
- </div>
- <button
- onClick={() => setShowError(false)}
- className="text-gray-700 hover:text-black"
- >
- <X size={18} />
- </button>
- </div>
- )}
- {unnamedSpeakers.length === 0 && !loading && !error && (
- <p className="text-center">no unnamed speakers found.</p>
- )}
-
- {unnamedSpeakers.length > 0 && (
- <div className="mx-4">
- <div className="p-4 border rounded h-full">
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center space-x-2">
- <span className="font-medium">identify speaker</span>
- </div>
- </div>
- <form
- className="space-y-4"
- onSubmit={async (e) => {
- e.preventDefault();
- setShowNameUpdateConfirm(true);
- await fetchSpeakers(speakerSearchTerm);
- }}
- >
- <div className="flex items-center space-x-2">
- <div className="relative flex-1 max-w-xs">
- <Input
- onFocus={() => {
- setShowSpeakerNames(true);
- }}
- onBlur={(e) => {
- // Add a small delay to allow the click event to fire first
- setTimeout(() => {
- setShowSpeakerNames(false);
- }, 200);
- }}
- value={speakerSearchTerm}
- name="speakerName"
- onChange={(e) => {
- const newValue = e.target.value;
- setSpeakerSearchTerm(newValue);
- // Only filter existing speakers if we have any
- if (speakers.length > 0) {
- setSpeakers(
- speakers.filter((speaker) =>
- speaker.name
- .toLowerCase()
- .includes(newValue.toLowerCase())
- )
- );
- }
- }}
- onKeyDown={(e) => {
- if (e.key === " " && !segments) {
- setSpeakerSearchTerm(speakerSearchTerm + " ");
- }
- }}
- placeholder="Enter speaker name"
- className="w-full"
- />
- {speakerSearchTerm && (
- <div className="absolute z-10 w-full mt-1 bg-white border rounded-md shadow-lg max-h-48 overflow-y-auto">
- {isSearching ? (
- <div className="flex justify-center items-center p-4">
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
- </div>
- ) : (
- showSpeakerNames && (
- <ul className="py-1">
- {speakers.map((speaker) => (
- <li
- key={speaker.id}
- className="px-3 py-2 hover:bg-gray-100 cursor-pointer truncate"
- onClick={(e) => {
- setSpeakerSearchTerm(speaker.name);
- setSelectedExistingSpeaker(speaker);
- setShowMergeConfirm(true);
- setShowSpeakerNames(false);
- }}
- >
- {speaker.name}
- </li>
- ))}
- </ul>
- )
- )}
- </div>
- )}
- </div>
- <Button
- type="submit"
- disabled={!speakerSearchTerm || speakerIdentified}
- size="sm"
- onClick={(e) => {
- e.preventDefault();
- setShowNameUpdateConfirm(true);
- }}
- >
- <Save className="mr-2" />
- update name
- </Button>
- <Button
- type="button"
- variant="outline"
- disabled={speakerIdentified}
- onClick={async (e) => {
- e.preventDefault();
- setShowHallucinationConfirm(true);
- }}
- >
- <Ghost className="mr-2" />
- nobody is speaking
- </Button>
- <Button
- type="button"
- disabled={speakerIdentified}
- variant="secondary"
- onClick={async (e) => {
- e.preventDefault();
- setShowRemoveSpeakerConfirm(true);
- }}
- >
- <Trash className="mr-2" />
- remove speaker
- </Button>
- </div>
- </form>
-
- <div className="mt-4">
- <p className="text-sm text-gray-500 mb-2">
- audio samples:
- </p>
- <div className="grid grid-cols-3 gap-2">
- {unnamedSpeakers[
- currentSpeakerIndex
- ].metadata?.audioSamples
- .slice(0, 3)
- .map((sample, index) => (
- <VideoComponent
- key={index}
- filePath={sample.path}
- startTime={sample.startTime}
- endTime={sample.endTime}
- customDescription={`transcript: ${sample.transcript}`}
- />
- ))}
- </div>
- </div>
- {speakerIdentified && (
- <div className="mt-4 flex justify-end">
- <Button
- onClick={() => {
- handleRefresh();
- }}
- >
- next speaker
- <ChevronRight className="ml-2" />
- </Button>
- </div>
- )}
- <div className="mt-8">
- {similarSpeakers.length > 0 && (
- <p className="text-sm text-gray-500 mb-4">
- is this the same speaker?
- </p>
- )}
- {isFetchingSimilarSpeakers ? (
- <div className="flex justify-center items-center p-4">
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
- </div>
- ) : (
- <div>
- {similarSpeakers.map((speaker, index) => {
- if (similarSpeakerIndex !== index) {
- return null;
- }
- return (
- <div
- className="flex space-x-2 items-center"
- key={speaker.id}
- >
- <span>{speaker.name || ""}</span>
- {speaker.metadata?.audioSamples.map(
- (sample) => (
- <VideoComponent
- key={sample.path}
- filePath={sample.path}
- startTime={sample.startTime}
- endTime={sample.endTime}
- customDescription={`transcript: ${sample.transcript}`}
- className="max-w-[300px]"
- />
- )
- )}
- <Button
- size="default"
- variant="default"
- onClick={() => {
- setSelectedExistingSpeaker(speaker);
- setShowMergeConfirm(true);
- }}
- >
- <Check className="mr-2" />
- same speaker
- </Button>
- <Button
- size="default"
- variant="outline"
- onClick={() => {
- const newSpeakers = similarSpeakers.filter(
- (s) => s.id !== speaker.id
- );
- setSimilarSpeakers(newSpeakers);
- setSimilarSpeakerIndex(
- Math.max(
- 0,
- Math.min(
- similarSpeakerIndex,
- newSpeakers.length - 1
- )
- )
- );
- }}
- >
- <X className="mr-2" />
- different speaker
- </Button>
- <Button
- size="default"
- className={
- similarSpeakers.length === 1 ? "hidden" : ""
- }
- variant="secondary"
- onClick={() => {
- setSimilarSpeakerIndex(
- (index + 1) % similarSpeakers.length
- );
- }}
- >
- skip
- <ChevronRight className="ml-2" />
- </Button>
- </div>
- );
- })}
- </div>
- )}
- </div>
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- </DialogContent>
- <Dialog
- open={showHallucinationConfirm}
- onOpenChange={setShowHallucinationConfirm}
- >
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>confirm</DialogTitle>
- <DialogDescription>
- are you sure you nobody is speaking? this action cannot be undone.
- </DialogDescription>
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button
- variant="outline"
- onClick={() => setShowHallucinationConfirm(false)}
- >
- cancel
- </Button>
- <Button
- variant="default"
- onClick={async () => {
- await handleMarkSpeakerAsHallucination();
- setShowHallucinationConfirm(false);
- toast({
- title: "speaker ignored",
- description:
- "This speaker will be ignored in future processing",
- });
- setSpeakerIdentified(true);
- }}
- >
- confirm
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- <Dialog
- open={showNameUpdateConfirm}
- onOpenChange={setShowNameUpdateConfirm}
- >
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>confirm name update</DialogTitle>
- <DialogDescription>
- are you sure you want to update this speaker&apos;s name to &quot;
- {speakerSearchTerm}
- &quot;?
- </DialogDescription>
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button
- variant="ghost"
- onClick={() => setShowNameUpdateConfirm(false)}
- >
- cancel
- </Button>
- <Button
- onClick={async () => {
- await handleUpdateSpeakerName(speakerSearchTerm);
- setShowNameUpdateConfirm(false);
- toast({
- title: "speaker renamed",
- description: "the speaker name has been updated",
- });
- }}
- >
- confirm
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- <Dialog open={showMergeConfirm} onOpenChange={setShowMergeConfirm}>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>merge speakers</DialogTitle>
- {selectedExistingSpeaker?.name ? (
- <DialogDescription>
- do you want to merge this speaker with existing speaker
- {` "${selectedExistingSpeaker?.name}"`}? this will combine their
- audio samples and future recordings.
- </DialogDescription>
- ) : (
- <DialogDescription>
- do you want to merge this speaker? this will combine their audio
- samples and future recordings.
- </DialogDescription>
- )}
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button variant="ghost" onClick={() => setShowMergeConfirm(false)}>
- cancel
- </Button>
- {selectedExistingSpeaker?.name && (
- <Button
- variant="outline"
- onClick={() => {
- setShowMergeConfirm(false);
- // Still update the name without merging
- handleUpdateSpeakerName(selectedExistingSpeaker?.name || "");
- toast({
- title: "speaker renamed",
- description:
- "the speaker name has been updated without merging",
- });
- }}
- >
- just update name
- </Button>
- )}
-
- <Button onClick={handleMergeSpeakers}>merge speakers</Button>
- </div>
- </DialogContent>
- </Dialog>
- <Dialog
- open={showRemoveSpeakerConfirm}
- onOpenChange={setShowRemoveSpeakerConfirm}
- >
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>confirm remove speaker</DialogTitle>
- <DialogDescription>
- are you sure you want to remove this speaker? this action cannot
- be undone.
- </DialogDescription>
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button
- variant="outline"
- onClick={() => setShowRemoveSpeakerConfirm(false)}
- >
- cancel
- </Button>
- <Button
- onClick={async () => {
- await handleRemoveSpeaker();
- setShowRemoveSpeakerConfirm(false);
- toast({
- title: "speaker removed",
- description: "the speaker has been removed",
- });
- }}
- >
- confirm
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- </Dialog>
- ) : (
- <Card>
- <CardHeader>
- <CardTitle>identify speakers</CardTitle>
- <CardDescription>
- identify speakers based on recent audio clips
- <Badge variant="secondary" className="ml-2">
- experimental
- </Badge>
- </CardDescription>
- </CardHeader>
- <CardContent className="max-w-[90vw] w-full max-h-[90vh] h-full">
- <div className="flex-grow overflow-auto min-h-[600px] flex flex-col">
- {loading ? (
- <div className="space-y-6 min-h-[600px]">
- {[1, 2, 3].map((i) => (
- <div key={i} className="p-4 border rounded animate-pulse">
- <div className="h-6 bg-gray-200 rounded w-3/4 mb-4"></div>
- <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
- <div className="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
- <div className="h-20 bg-gray-200 rounded mb-2"></div>
- <div className="h-4 bg-gray-200 rounded w-1/3"></div>
- </div>
- ))}
- </div>
- ) : (
- <div className="min-h-[600px] flex flex-col">
- {showError && error && (
- <div
- className="bg-gray-100 border-l-4 border-black text-gray-700 p-4 mb-4 flex justify-between items-center"
- role="alert"
- >
- <div>
- <p className="font-bold">warning</p>
- <p>{error}</p>
- </div>
- <button
- onClick={() => setShowError(false)}
- className="text-gray-700 hover:text-black"
- >
- <X size={18} />
- </button>
- </div>
- )}
- {unnamedSpeakers.length === 0 && !loading && !error && (
- <p className="text-center">no unnamed speakers found.</p>
- )}
-
- {unnamedSpeakers.length > 0 && (
- <div className="mx-4">
- <div className="p-4 border rounded h-full">
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center space-x-2">
- <span className="font-medium">identify speaker</span>
- </div>
- </div>
- <form
- className="space-y-4"
- onSubmit={async (e) => {
- e.preventDefault();
- setShowNameUpdateConfirm(true);
- await fetchSpeakers(speakerSearchTerm);
- }}
- >
- <div className="flex items-center space-x-2">
- <div className="relative flex-1 max-w-xs">
- <Input
- onFocus={() => {
- setShowSpeakerNames(true);
- }}
- onBlur={(e) => {
- // Add a small delay to allow the click event to fire first
- setTimeout(() => {
- setShowSpeakerNames(false);
- }, 200);
- }}
- value={speakerSearchTerm}
- name="speakerName"
- onChange={(e) => {
- const newValue = e.target.value;
- setSpeakerSearchTerm(newValue);
- // Only filter existing speakers if we have any
- if (speakers.length > 0) {
- setSpeakers(
- speakers.filter((speaker) =>
- speaker.name
- .toLowerCase()
- .includes(newValue.toLowerCase())
- )
- );
- }
- }}
- onKeyDown={(e) => {
- if (e.key === " " && !segments) {
- setSpeakerSearchTerm(speakerSearchTerm + " ");
- }
- }}
- placeholder="Enter speaker name"
- className="w-full"
- />
- {speakerSearchTerm && (
- <div className="absolute z-10 w-full mt-1 bg-white border rounded-md shadow-lg max-h-48 overflow-y-auto">
- {isSearching ? (
- <div className="flex justify-center items-center p-4">
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
- </div>
- ) : (
- showSpeakerNames && (
- <ul className="py-1">
- {speakers.map((speaker) => (
- <li
- key={speaker.id}
- className="px-3 py-2 hover:bg-gray-100 cursor-pointer truncate"
- onClick={(e) => {
- setSpeakerSearchTerm(speaker.name);
- setSelectedExistingSpeaker(speaker);
- setShowMergeConfirm(true);
- setShowSpeakerNames(false);
- }}
- >
- {speaker.name}
- </li>
- ))}
- </ul>
- )
- )}
- </div>
- )}
- </div>
- <Button
- type="submit"
- disabled={!speakerSearchTerm || speakerIdentified}
- size="sm"
- onClick={(e) => {
- e.preventDefault();
- setShowNameUpdateConfirm(true);
- }}
- >
- <Save className="mr-2" />
- update name
- </Button>
- <Button
- type="button"
- variant="outline"
- disabled={speakerIdentified}
- onClick={async (e) => {
- e.preventDefault();
- setShowHallucinationConfirm(true);
- }}
- >
- <Ghost className="mr-2" />
- nobody is speaking
- </Button>
- <Button
- type="button"
- disabled={speakerIdentified}
- variant="secondary"
- onClick={async (e) => {
- e.preventDefault();
- setShowRemoveSpeakerConfirm(true);
- }}
- >
- <Trash className="mr-2" />
- remove speaker
- </Button>
- </div>
- </form>
-
- <div className="mt-4">
- <p className="text-sm text-gray-500 mb-2">
- audio samples:
- </p>
- <div className="grid grid-cols-3 gap-2">
- {unnamedSpeakers[
- currentSpeakerIndex
- ].metadata?.audioSamples
- .slice(0, 3)
- .map((sample, index) => (
- <VideoComponent
- key={index}
- filePath={sample.path}
- customDescription={`transcript: ${sample.transcript}`}
- startTime={sample.startTime}
- endTime={sample.endTime}
- />
- ))}
- </div>
- </div>
- {speakerIdentified && (
- <div className="mt-4 flex justify-end">
- <Button
- onClick={() => {
- handleRefresh();
- }}
- >
- next speaker
- <ChevronRight className="ml-2" />
- </Button>
- </div>
- )}
- <div className="mt-8">
- {similarSpeakers.length > 0 && (
- <p className="text-sm text-gray-500 mb-4">
- is this the same speaker?
- </p>
- )}
- {isFetchingSimilarSpeakers ? (
- <div className="flex justify-center items-center p-4">
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
- </div>
- ) : (
- <div>
- {similarSpeakers.map((speaker, index) => {
- if (similarSpeakerIndex !== index) {
- return null;
- }
- return (
- <div
- className="flex space-x-2 items-center"
- key={speaker.id}
- >
- <span>{speaker.name || ""}</span>
- {speaker.metadata?.audioSamples.map(
- (sample) => (
- <VideoComponent
- key={sample.path}
- filePath={sample.path}
- customDescription={`transcript: ${sample.transcript}`}
- className="max-w-[300px]"
- startTime={sample.startTime}
- endTime={sample.endTime}
- />
- )
- )}
- <Button
- size="default"
- variant="default"
- onClick={() => {
- setSelectedExistingSpeaker(speaker);
- setShowMergeConfirm(true);
- }}
- >
- <Check className="mr-2" />
- same speaker
- </Button>
- <Button
- size="default"
- variant="outline"
- onClick={() => {
- const newSpeakers = similarSpeakers.filter(
- (s) => s.id !== speaker.id
- );
- setSimilarSpeakers(newSpeakers);
- setSimilarSpeakerIndex(
- Math.max(
- 0,
- Math.min(
- similarSpeakerIndex,
- newSpeakers.length - 1
- )
- )
- );
- }}
- >
- <X className="mr-2" />
- different speaker
- </Button>
- <Button
- size="default"
- className={
- similarSpeakers.length === 1 ? "hidden" : ""
- }
- variant="secondary"
- onClick={() => {
- setSimilarSpeakerIndex(
- (index + 1) % similarSpeakers.length
- );
- }}
- >
- skip
- <ChevronRight className="ml-2" />
- </Button>
- </div>
- );
- })}
- </div>
- )}
- </div>
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- </CardContent>
- <Dialog
- open={showHallucinationConfirm}
- onOpenChange={setShowHallucinationConfirm}
- >
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>confirm</DialogTitle>
- <DialogDescription>
- are you sure you nobody is speaking? this action cannot be undone.
- </DialogDescription>
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button
- variant="outline"
- onClick={() => setShowHallucinationConfirm(false)}
- >
- cancel
- </Button>
- <Button
- variant="default"
- onClick={async () => {
- await handleMarkSpeakerAsHallucination();
- setShowHallucinationConfirm(false);
- toast({
- title: "speaker ignored",
- description:
- "This speaker will be ignored in future processing",
- });
- setSpeakerIdentified(true);
- }}
- >
- confirm
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- <Dialog
- open={showNameUpdateConfirm}
- onOpenChange={setShowNameUpdateConfirm}
- >
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>confirm name update</DialogTitle>
- <DialogDescription>
- are you sure you want to update this speaker&apos;s name to &quot;
- {speakerSearchTerm}
- &quot;?
- </DialogDescription>
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button
- variant="ghost"
- onClick={() => setShowNameUpdateConfirm(false)}
- >
- cancel
- </Button>
- <Button
- onClick={async () => {
- await handleUpdateSpeakerName(speakerSearchTerm);
- setShowNameUpdateConfirm(false);
- toast({
- title: "speaker renamed",
- description: "the speaker name has been updated",
- });
- }}
- >
- confirm
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- <Dialog open={showMergeConfirm} onOpenChange={setShowMergeConfirm}>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>merge speakers</DialogTitle>
- {selectedExistingSpeaker?.name ? (
- <DialogDescription>
- do you want to merge this speaker with existing speaker
- {` "${selectedExistingSpeaker?.name}"`}? this will combine their
- audio samples and future recordings.
- </DialogDescription>
- ) : (
- <DialogDescription>
- do you want to merge this speaker? this will combine their audio
- samples and future recordings.
- </DialogDescription>
- )}
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button variant="ghost" onClick={() => setShowMergeConfirm(false)}>
- cancel
- </Button>
- {selectedExistingSpeaker?.name && (
- <Button
- variant="outline"
- onClick={() => {
- setShowMergeConfirm(false);
- // Still update the name without merging
- handleUpdateSpeakerName(selectedExistingSpeaker?.name || "");
- toast({
- title: "speaker renamed",
- description:
- "the speaker name has been updated without merging",
- });
- }}
- >
- just update name
- </Button>
- )}
-
- <Button onClick={handleMergeSpeakers}>merge speakers</Button>
- </div>
- </DialogContent>
- </Dialog>
- <Dialog
- open={showRemoveSpeakerConfirm}
- onOpenChange={setShowRemoveSpeakerConfirm}
- >
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>confirm remove speaker</DialogTitle>
- <DialogDescription>
- are you sure you want to remove this speaker? this action cannot
- be undone.
- </DialogDescription>
- </DialogHeader>
- <div className="flex justify-end space-x-2">
- <Button
- variant="outline"
- onClick={() => setShowRemoveSpeakerConfirm(false)}
- >
- cancel
- </Button>
- <Button
- onClick={async () => {
- await handleRemoveSpeaker();
- setShowRemoveSpeakerConfirm(false);
- toast({
- title: "speaker removed",
- description: "the speaker has been removed",
- });
- }}
- >
- confirm
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- </Card>
- );
-}
diff --git a/screenpipe-app-tauri/components/meeting-history.tsx b/screenpipe-app-tauri/components/meeting-history.tsx
deleted file mode 100644
index ee8cdf1dc..000000000
--- a/screenpipe-app-tauri/components/meeting-history.tsx
+++ /dev/null
@@ -1,977 +0,0 @@
-"use client";
-
-import React, { useState, useEffect, useCallback, useMemo } from "react";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog";
-import { OpenAI } from "openai";
-import { useSettings } from "@/lib/hooks/use-settings";
-import { useToast } from "./ui/use-toast";
-import ReactMarkdown from "react-markdown";
-import {
- X,
- Copy,
- RefreshCw,
- Trash2,
- Users,
- FileText,
- PlusCircle,
- Calendar,
- ChevronDown,
- ChevronUp,
-} from "lucide-react";
-import { usePostHog } from "posthog-js/react";
-import { Badge } from "./ui/badge";
-import { useCopyToClipboard } from "@/lib/hooks/use-copy-to-clipboard";
-import localforage from "localforage";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import { Input } from "./ui/input";
-import { Textarea } from "./ui/textarea";
-import { cn, keysToCamelCase } from "@/lib/utils";
-import { HelpCircle } from "lucide-react";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { ValueOf } from "next/dist/shared/lib/constants";
-import { Checkbox } from "./ui/checkbox";
-import { useHealthCheck } from "@/lib/hooks/use-health-check";
-import { DropdownMenuItem } from "./ui/dropdown-menu";
-import IdentifySpeakers from "./identify-speakers";
-
-function formatDate(date: string): string {
- const dateObj = new Date(date);
- const formattedDate = dateObj.toLocaleDateString("en-US", {
- month: "long",
- day: "numeric",
- year: "numeric",
- });
- const formattedTime = dateObj.toLocaleTimeString("en-US", {
- hour: "2-digit",
- minute: "2-digit",
- });
- return `${formattedDate} at ${formattedTime}`;
-}
-
-async function setItem(key: string, value: any): Promise<void> {
- try {
- if (typeof window !== "undefined") {
- await localforage.setItem(key, value);
- }
- } catch (error) {
- console.error("error setting item in storage:", error);
- throw error;
- }
-}
-
-async function getItem(key: string): Promise<any> {
- try {
- if (typeof window !== "undefined") {
- return await localforage.getItem(key);
- }
- } catch (error) {
- console.error("error getting item from storage:", error);
- throw error;
- }
- return null;
-}
-
-interface MeetingSegment {
- timestamp: string;
- transcription: string;
- deviceName: string;
- deviceType: string;
- speaker: Speaker;
-}
-
-interface Meeting {
- meetingGroup: number;
- meetingStart: string;
- meetingEnd: string;
- fullTranscription: string;
- name: string | null;
- participants: string | null;
- summary: string | null;
- mergedWith?: number[]; // Array of meeting groups merged with this one
- selectedDevices: Set<string>;
- deviceNames: Set<string>;
- segments: MeetingSegment[];
-}
-
-interface Speaker {
- id: number;
- name: string;
-}
-
-interface AudioContent {
- chunkId: number;
- transcription: string;
- timestamp: string;
- filePath: string;
- offsetIndex: number;
- tags: string[];
- deviceName: string;
- deviceType: string;
- speaker: Speaker;
-}
-
-interface AudioTranscription {
- type: "Audio";
- content: AudioContent;
-}
-
-export default function MeetingHistory({
- showMeetingHistory,
- setShowMeetingHistory,
- className,
-}: {
- showMeetingHistory: boolean;
- setShowMeetingHistory: (show: boolean) => void;
- className?: string;
-}) {
- const posthog = usePostHog();
- const { settings } = useSettings();
- const [meetings, setMeetings] = useState<Meeting[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [isSummarizing, setIsSummarizing] = useState(false);
- const [isIdentifying, setIsIdentifying] = useState(false);
- const { toast } = useToast();
- const [showError, setShowError] = useState(false);
- const { copyToClipboard } = useCopyToClipboard({ timeout: 2000 });
- const [isRefreshing, setIsRefreshing] = useState(false);
- const [customSummaryPrompt, setCustomSummaryPrompt] = useState<string>(
- "please provide a concise summary of the following meeting transcript"
- );
- const [isClearing, setIsClearing] = useState(false);
- const [customIdentifyPrompt, setCustomIdentifyPrompt] = useState<string>(
- "please identify the participants in this meeting transcript. provide a comma-separated list of one or two word names or roles or characteristics. if it's not possible to identify, respond with n/a."
- );
- const [openIdentifyDialogs, setOpenIdentifyDialogs] = useState<{
- [key: number]: boolean;
- }>({});
-
- // Add this function to handle individual dialog states
- const handleIdentifyDialog = (meetingGroup: number, isOpen: boolean) => {
- setOpenIdentifyDialogs((prev) => ({
- ...prev,
- [meetingGroup]: isOpen,
- }));
- };
- const { health } = useHealthCheck();
-
- useEffect(() => {
- if (posthog) {
- posthog.identify(settings.userId);
- }
- }, [posthog, settings.userId]);
-
- useEffect(() => {
- if (showMeetingHistory) {
- loadMeetings();
- posthog?.capture("meeting_history_opened", {
- userId: settings.userId,
- });
- }
- }, [showMeetingHistory]);
-
- useEffect(() => {
- setShowError(!!error);
- }, [error]);
-
- useEffect(() => {
- console.log("Dialog state changed:", showMeetingHistory);
- }, [showMeetingHistory]);
-
- async function loadMeetings() {
- setLoading(true);
- try {
- const storedMeetings = (await getItem("meetings")) || [];
- setMeetings(storedMeetings);
- await fetchMeetings();
- } catch (err) {
- setError("failed to load meetings");
- } finally {
- setLoading(false);
- }
- }
-
- async function fetchMeetings() {
- console.log("fetching meetings...");
- setLoading(true);
- try {
- // Always fetch from the last 7x24 hours
- const startTime = new Date(
- Date.now() - 7 * 24 * 60 * 60 * 1000
- ).toISOString();
- console.log("searching from:", startTime);
-
- const response = await fetch(
- `http://localhost:3030/search?content_type=audio&start_time=${startTime}&limit=1000`
- );
- if (!response.ok) {
- throw new Error("failed to fetch meeting history");
- }
- const result = await response.json();
- const camelCaseResult = keysToCamelCase<{ data: AudioTranscription[] }>(
- result
- );
- console.log("fetch result:", camelCaseResult);
- const newMeetings = processMeetings(camelCaseResult.data);
- console.log("processed new meetings:", newMeetings);
-
- // merge new meetings with stored meetings, updating existing ones
- let updatedMeetings = [...meetings];
- newMeetings.forEach((newMeeting) => {
- const existingMeetingIndex = updatedMeetings.findIndex(
- (m) => m.meetingGroup === newMeeting.meetingGroup
- );
- if (existingMeetingIndex === -1) {
- // add new meeting if it doesn't exist
- updatedMeetings.push(newMeeting);
- } else {
- // update existing meeting with new data
- updatedMeetings[existingMeetingIndex] = {
- ...updatedMeetings[existingMeetingIndex],
- ...newMeeting,
- fullTranscription:
- updatedMeetings[existingMeetingIndex].fullTranscription +
- newMeeting.fullTranscription,
- };
- }
- });
-
- // sort meetings by start time (descending)
- updatedMeetings.sort(
- (a, b) =>
- new Date(b.meetingStart).getTime() -
- new Date(a.meetingStart).getTime()
- );
-
- setMeetings(updatedMeetings);
-
- // store updated meetings
- await setItem("meetings", updatedMeetings);
- } catch (err) {
- setError(
- "some trouble fetching new meetings. please check health status."
- );
- console.error("fetch error:", err);
- } finally {
- console.log("fetch completed");
- setLoading(false);
- }
- }
-
- async function generateSummary(meeting: Meeting) {
- setIsSummarizing(true);
- posthog?.capture("summary_generation_started", {
- userId: settings.userId,
- meetingId: meeting.meetingGroup,
- });
- try {
- const openai = new OpenAI({
- apiKey: settings.openaiApiKey,
- baseURL: settings.aiUrl,
- dangerouslyAllowBrowser: true,
- });
-
- const model = settings.aiModel;
-
- // create an enhanced prompt that includes identified participants
- const enhancedPrompt = meeting.participants
- ? `${customSummaryPrompt}\n\nparticipants: ${meeting.participants}`
- : customSummaryPrompt;
-
- const messages = [
- {
- role: "system" as const,
- content: `you are a helpful assistant that summarizes meetings. `,
- },
- {
- role: "user" as const,
- content: `${enhancedPrompt}:\n\n${meeting.segments
- .map((s) => s.transcription)
- .join("\n")}`,
- },
- ];
-
- const stream = await openai.chat.completions.create({
- model: model,
- messages: messages,
- stream: true,
- });
-
- let summary = "";
- const updatedMeeting = { ...meeting, summary: "" };
-
- for await (const chunk of stream) {
- const content = chunk.choices[0]?.delta?.content || "";
- summary += content;
- updatedMeeting.summary = summary;
-
- // update the meeting with the new summary
- const updatedMeetings = meetings.map((m) =>
- m.meetingGroup === meeting.meetingGroup ? updatedMeeting : m
- );
- setMeetings(updatedMeetings);
- }
-
- // final update after streaming is complete
- const finalUpdatedMeetings = meetings.map((m) =>
- m.meetingGroup === meeting.meetingGroup ? updatedMeeting : m
- );
- setMeetings(finalUpdatedMeetings);
-
- try {
- console.log("updating meetings state...");
- setMeetings(finalUpdatedMeetings);
-
- console.log("storing meetings in storage...");
- await setItem("meetings", finalUpdatedMeetings);
-
- console.log("storage operation completed");
-
- toast({
- title: "summary generated",
- description:
- "the meeting summary has been created and saved successfully.",
- });
- } catch (storageError) {
- console.error("error updating storage:", storageError);
- toast({
- title: "warning",
- description:
- "summary generated but couldn't be saved due to storage limits. older meetings might be removed to make space.",
- variant: "destructive",
- });
-
- // attempt to remove older meetings to make space
- try {
- const oldMeetings = (await getItem("meetings")) || [];
- const meetingsToKeep = oldMeetings.slice(-10); // keep only the last 10 meetings
- await setItem("meetings", meetingsToKeep);
- setMeetings(meetingsToKeep);
- toast({
- title: "storage cleaned",
- description:
- "older meetings were removed to make space for new ones.",
- });
- } catch (cleanupError) {
- console.error("failed to clean up storage:", cleanupError);
- toast({
- title: "error",
- description:
- "failed to clean up storage. please clear your browser data manually.",
- variant: "destructive",
- });
- }
- }
- } catch (error) {
- console.error("error generating summary:", error);
- toast({
- title: "error",
- description: "failed to generate meeting summary. please try again.",
- variant: "destructive",
- });
- } finally {
- setIsSummarizing(false);
- }
- }
-
- function formatTimestamp(timestamp: string): string {
- const date = new Date(timestamp);
- return new Intl.DateTimeFormat("en-US", {
- year: "numeric",
- month: "short",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- timeZoneName: "short",
- }).format(date);
- }
-
- function processMeetings(transcriptions: AudioTranscription[]): Meeting[] {
- console.log("processing transcriptions:", transcriptions);
- let meetings: Meeting[] = [];
- let currentMeeting: Meeting | null = null;
- let meetingGroup = 0;
-
- // sort transcriptions by timestamp
- transcriptions.sort(
- (a, b) =>
- new Date(a.content.timestamp).getTime() -
- new Date(b.content.timestamp).getTime()
- );
-
- transcriptions.forEach((trans, index) => {
- const currentTime = new Date(trans.content.timestamp);
- const prevTime =
- index > 0
- ? new Date(transcriptions[index - 1].content.timestamp)
- : null;
-
- // Get speaker name based on speaker info or device type
- const speakerName =
- trans.content.speaker?.name && trans.content.speaker.name.length > 0
- ? trans.content.speaker.name
- : trans.content.deviceType?.toLowerCase() === "input"
- ? "you"
- : trans.content.deviceType?.toLowerCase() === "output"
- ? "others"
- : "unknown";
-
- if (
- !currentMeeting ||
- (prevTime &&
- currentTime.getTime() - prevTime.getTime() >= 5 * 60 * 1000) // increased to 5 minutes
- ) {
- if (currentMeeting) {
- meetings.push(currentMeeting);
- }
- meetingGroup++;
- currentMeeting = {
- meetingGroup: meetingGroup,
- meetingStart: trans.content.timestamp,
- meetingEnd: trans.content.timestamp,
- fullTranscription: `${formatTimestamp(
- trans.content.timestamp
- )} [${speakerName}] ${trans.content.transcription}\n`,
- name: null,
- participants: null,
- summary: null,
- selectedDevices: new Set([trans.content.deviceName]),
- segments: [
- {
- timestamp: trans.content.timestamp,
- transcription: trans.content.transcription,
- deviceName: trans.content.deviceName,
- deviceType: trans.content.deviceType,
- speaker: trans.content.speaker || {
- id: -1,
- name: speakerName,
- },
- },
- ],
- deviceNames: new Set([trans.content.deviceName]),
- };
- } else if (currentMeeting) {
- currentMeeting.meetingEnd = trans.content.timestamp;
- currentMeeting.fullTranscription += `${formatTimestamp(
- trans.content.timestamp
- )} [${speakerName}] ${trans.content.transcription}\n`;
- currentMeeting.selectedDevices.add(trans.content.deviceName);
- currentMeeting.segments.push({
- timestamp: trans.content.timestamp,
- transcription: trans.content.transcription,
- deviceName: trans.content.deviceName,
- deviceType: trans.content.deviceType,
- speaker: trans.content.speaker || {
- id: -1,
- name: speakerName,
- },
- });
- currentMeeting.deviceNames.add(trans.content.deviceName);
- }
- });
-
- if (currentMeeting) {
- meetings.push(currentMeeting);
- }
-
- // sort meetings by start time
- meetings.sort(
- (a, b) =>
- new Date(b.meetingStart).getTime() - new Date(a.meetingStart).getTime()
- );
-
- // remove duplicate meetings
- meetings = meetings.filter(
- (meeting, index, self) =>
- index === self.findIndex((t) => t.meetingGroup === meeting.meetingGroup)
- );
-
- console.log("processed meetings:", meetings);
- return meetings.filter(
- (m) => m.fullTranscription.replace(/\n/g, "").length >= 200
- );
- }
-
- // Memoize expensive computations
- const sortedMeetings = useMemo(() => {
- return [...meetings].sort(
- (a, b) =>
- new Date(b.meetingStart).getTime() - new Date(a.meetingStart).getTime()
- );
- }, [meetings]);
-
- const copyWithToast = (content: string, type: string) => {
- copyToClipboard(content);
- toast({
- title: "copied to clipboard",
- description: `${type} has been copied to your clipboard.`,
- });
- };
-
- const handleRefresh = async () => {
- setIsRefreshing(true);
- try {
- await fetchMeetings();
- toast({
- title: "meetings refreshed",
- description: "your meeting history has been updated.",
- });
- } catch (error) {
- console.error("error refreshing meetings:", error);
- toast({
- title: "refresh failed",
- description: "failed to refresh meetings. please try again.",
- variant: "destructive",
- });
- } finally {
- setIsRefreshing(false);
- }
- };
-
- const handleClearMeetings = async () => {
- setIsClearing(true);
- try {
- await localforage.removeItem("meetings");
- setMeetings([]);
- toast({
- title: "meeting data cleared",
- description: "all stored meeting data has been removed.",
- });
- posthog?.capture("meeting_data_cleared", {
- userId: settings.userId,
- });
- } catch (error) {
- console.error("error clearing meeting data:", error);
- toast({
- title: "error",
- description: "failed to clear meeting data. please try again.",
- variant: "destructive",
- });
- } finally {
- setIsClearing(false);
- }
- };
-
- const mergeMeetings = (index: number) => {
- posthog?.capture("meeting_merged");
- const updatedMeetings = [...meetings];
- const currentMeeting = updatedMeetings[index];
- const nextMeeting = updatedMeetings[index + 1];
-
- const mergedMeeting: Meeting = {
- ...currentMeeting,
- meetingEnd: new Date(
- Math.max(
- new Date(currentMeeting.meetingEnd).getTime(),
- new Date(nextMeeting.meetingEnd).getTime()
- )
- ).toISOString(),
- meetingStart: new Date(
- Math.min(
- new Date(currentMeeting.meetingStart).getTime(),
- new Date(nextMeeting.meetingStart).getTime()
- )
- ).toISOString(),
- fullTranscription: `${currentMeeting.fullTranscription}\n${nextMeeting.fullTranscription}`,
- mergedWith: [
- ...(currentMeeting.mergedWith || []),
- nextMeeting.meetingGroup,
- ...(nextMeeting.mergedWith || []),
- ],
- segments: [...currentMeeting.segments, ...nextMeeting.segments],
- selectedDevices: new Set([
- ...Array.from(currentMeeting.selectedDevices),
- ...Array.from(nextMeeting.selectedDevices),
- ]),
- };
-
- updatedMeetings[index] = mergedMeeting;
- updatedMeetings.splice(index + 1, 1); // remove the next meeting
- setMeetings(updatedMeetings);
- setItem("meetings", updatedMeetings);
- };
-
- const handleDeviceToggle = useCallback(
- (meetingGroup: number, deviceName: string, isChecked: boolean) => {
- setMeetings((prevMeetings) => {
- return prevMeetings.map((meeting) => {
- if (meeting.meetingGroup === meetingGroup) {
- const updatedSelectedDevices = new Set(meeting.selectedDevices);
- if (isChecked) {
- updatedSelectedDevices.add(deviceName);
- } else {
- updatedSelectedDevices.delete(deviceName);
- }
- return {
- ...meeting,
- selectedDevices: updatedSelectedDevices,
- };
- }
- return meeting;
- });
- });
- },
- []
- );
-
- return (
- <Card>
- <CardContent
- className="h-full"
- onClick={(e) => {
- e.stopPropagation();
- }}
- >
- <CardHeader className="py-4">
- <CardTitle className="flex items-center justify-between">
- <div className="flex items-center">
- meeting and conversation history
- <Badge variant="secondary" className="ml-2">
- experimental
- </Badge>
- </div>
- <div className="flex space-x-2">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- onClick={handleClearMeetings}
- disabled={isClearing}
- size="sm"
- variant="outline"
- className="text-xs"
- >
- {isClearing ? (
- <Trash2 className="h-4 w-4 animate-pulse" />
- ) : (
- <Trash2 className="h-4 w-4" />
- )}
- <span className="ml-2">reset data</span>
- </Button>
- </TooltipTrigger>
- <TooltipContent side="left">
- <p>
- this will restore your meeting data to the original state
- based on transcription timestamps,
- <br />
- without the editing you have done here
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
-
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- onClick={handleRefresh}
- disabled={isRefreshing}
- size="sm"
- variant="outline"
- className="text-xs "
- >
- {isRefreshing ? (
- <RefreshCw className="h-4 w-4 animate-spin" />
- ) : (
- <RefreshCw className="h-4 w-4" />
- )}
- <span className="ml-2">refresh</span>
- </Button>
- </TooltipTrigger>
- <TooltipContent side="left">
- <p>fetch latest meeting data</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </CardTitle>
- </CardHeader>
- <CardDescription className="mb-4">
- <span className="block text-sm text-gray-600">
- this page provides transcriptions and summaries of your daily
- meetings. it uses your ai settings to generate summaries. note:
- phrases like &quot;thank you&quot; or &quot;you know&quot; might be
- transcription errors. for better accuracy, consider using deepgram
- as the engine or adjust your prompt to ignore these.
- </span>
- <span className="block text-sm text-gray-600 mt-2">
- <strong>make sure to setup your ai settings</strong>
- </span>
- </CardDescription>
- <div className="flex-grow overflow-auto">
- {loading ? (
- <div className="space-y-6">
- {[1, 2, 3].map((i) => (
- <div key={i} className="p-4 border rounded animate-pulse">
- <div className="h-6 bg-gray-200 rounded w-3/4 mb-4"></div>
- <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
- <div className="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
- <div className="h-20 bg-gray-200 rounded mb-2"></div>
- <div className="h-4 bg-gray-200 rounded w-1/3"></div>
- </div>
- ))}
- </div>
- ) : (
- <>
- {showError && error && (
- <div
- className="bg-gray-100 border-l-4 border-black text-gray-700 p-4 mb-4 flex justify-between items-center"
- role="alert"
- >
- <div>
- <p className="font-bold">warning</p>
- <p>{error}</p>
- </div>
- <button
- onClick={() => setShowError(false)}
- className="text-gray-700 hover:text-black"
- >
- <X size={18} />
- </button>
- </div>
- )}
- {meetings.length === 0 && !loading && !error && (
- <p className="text-center">no meetings found.</p>
- )}
- <div className="space-y-6">
- {sortedMeetings.map((meeting, index) => (
- <React.Fragment key={index}>
- <Card className="relative">
- <CardHeader>
- <div className="grid grid-cols-2">
- <div>
- <CardTitle className="text-lg font-semibold flex flex-wrap items-center gap-2">
- meeting {meeting.meetingGroup}
- {meeting.mergedWith &&
- meeting.mergedWith.length > 0 && (
- <>
- <Badge variant="secondary">merged</Badge>
- {meeting.mergedWith.map((mergedGroupId) => (
- <Badge
- key={mergedGroupId}
- variant="outline"
- >
- meeting {mergedGroupId}
- </Badge>
- ))}
- </>
- )}
- </CardTitle>
- <CardDescription>
- {formatDate(meeting.meetingStart)} -{" "}
- {formatDate(meeting.meetingEnd)}
- </CardDescription>
- </div>
- <div className="mb-4 text-end">
- <h4 className="font-semibold mb-2">Devices:</h4>
- <div className="flex flex-wrap gap-4 justify-end">
- {Array.from(meeting.deviceNames).map(
- (deviceName) => (
- <label
- key={deviceName}
- className="flex items-center space-x-2"
- >
- <Checkbox
- checked={meeting.selectedDevices.has(
- deviceName
- )}
- onCheckedChange={(checked) =>
- handleDeviceToggle(
- meeting.meetingGroup,
- deviceName,
- checked as boolean
- )
- }
- />
- <span className="text-sm">
- {deviceName}
- </span>
- </label>
- )
- )}
- </div>
- </div>
- </div>
- </CardHeader>
- <CardContent>
- {!meeting.segments.every((s) => s.speaker.name) && (
- <div className="mb-4">
- <div className="flex flex-col space-y-2">
- <div className="flex items-center justify-end mb-1">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="h-5 w-5 cursor-help text-gray-500" />
- </TooltipTrigger>
- <TooltipContent side="top" align="end">
- <p className="max-w-xs">
- identify speakers in your meetings
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <div className="flex items-center justify-end">
- <IdentifySpeakers
- showIdentifySpeakers={
- openIdentifyDialogs[meeting.meetingGroup]
- }
- setShowIdentifySpeakers={(isOpen) =>
- handleIdentifyDialog(
- meeting.meetingGroup,
- isOpen
- )
- }
- segments={meeting.segments}
- />
- </div>
- </div>
- </div>
- )}
- <div className="mb-4 relative">
- <h4 className="font-semibold mb-2">transcription:</h4>
- <Button
- onClick={() =>
- copyWithToast(
- meeting.segments
- .filter((s) =>
- meeting.selectedDevices.has(s.deviceName)
- )
- .map((s) => {
- return `${formatTimestamp(s.timestamp)} [${
- s.speaker
- ? s.speaker.name
- : s.deviceType?.toLowerCase() ===
- "input"
- ? "you"
- : "others"
- }] ${s.transcription}`;
- })
- .join("\n"),
- "transcription"
- )
- }
- className="absolute top-0 right-0 p-1 h-6 w-6"
- variant="outline"
- size="icon"
- >
- <Copy className="h-4 w-4" />
- </Button>
- <pre className="whitespace-pre-wrap bg-gray-100 p-3 rounded text-sm max-h-40 overflow-y-auto">
- {meeting.segments
- .filter((s) =>
- meeting.selectedDevices.has(s.deviceName)
- )
- .sort(
- (a, b) =>
- new Date(a.timestamp).getTime() -
- new Date(b.timestamp).getTime()
- )
- .map((s, i) => (
- <React.Fragment key={i}>
- <span className="font-bold">
- {`${formatTimestamp(s.timestamp)} [${
- s.speaker
- ? s.speaker.name
- : s.deviceType?.toLowerCase() ===
- "input"
- ? "you"
- : "others"
- }]`}
- </span>{" "}
- {s.transcription}
- {"\n"}
- </React.Fragment>
- ))}
- </pre>
- </div>
- <div className="relative">
- <h4 className="font-semibold mb-2">summary:</h4>
- {meeting.summary && (
- <Button
- onClick={() =>
- copyWithToast(meeting.summary || "", "summary")
- }
- className="absolute top-0 right-0 p-1 h-6 w-6"
- variant="outline"
- size="icon"
- >
- <Copy className="h-4 w-4" />
- </Button>
- )}
- {meeting.summary ? (
- <ReactMarkdown className="prose max-w-none">
- {meeting.summary}
- </ReactMarkdown>
- ) : (
- <div className="flex items-center mt-2">
- <Input
- type="text"
- value={customSummaryPrompt}
- onChange={(e) =>
- setCustomSummaryPrompt(e.target.value)
- }
- placeholder="custom summary prompt (optional)"
- className="mr-2 p-2 border rounded text-sm flex-grow"
- />
- <Button
- onClick={() => generateSummary(meeting)}
- disabled={isSummarizing}
- >
- {isSummarizing ? (
- <FileText className="h-4 w-4 mr-2 animate-pulse" />
- ) : (
- <PlusCircle className="h-4 w-4 mr-2" />
- )}
- {isSummarizing
- ? "generating summary..."
- : "generate summary"}
- </Button>
- </div>
- )}
- </div>
- </CardContent>
- </Card>
- {index < sortedMeetings.length - 1 && (
- <div className="flex justify-center my-2">
- <Button
- onClick={() => mergeMeetings(index)}
- size="sm"
- variant="outline"
- className="text-xs"
- >
- <ChevronDown className="h-4 w-4 mr-2" />
- merge with next meeting
- </Button>
- </div>
- )}
- </React.Fragment>
- ))}
- </div>
- </>
- )}
- </div>
- </CardContent>
- </Card>
- );
-}
diff --git a/screenpipe-app-tauri/components/video.tsx b/screenpipe-app-tauri/components/video.tsx
deleted file mode 100644
index 2afcda48c..000000000
--- a/screenpipe-app-tauri/components/video.tsx
+++ /dev/null
@@ -1,294 +0,0 @@
-import { memo, useCallback, useEffect, useState, useRef, useMemo } from "react";
-import { readFile, open } from "@tauri-apps/plugin-fs";
-import { platform } from "@tauri-apps/plugin-os";
-import { cn } from "@/lib/utils";
-
-export const VideoComponent = memo(function VideoComponent({
- filePath,
- customDescription,
- className,
- startTime,
- endTime,
-}: {
- filePath: string;
- customDescription?: string;
- className?: string;
- startTime?: number;
- endTime?: number;
-}) {
- const [mediaSrc, setMediaSrc] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [isAudio, setIsAudio] = useState(false);
-
- const sanitizeFilePath = useCallback((path: string): string => {
- const isWindows = platform() === "windows";
- if (isWindows) {
- return path; // no sanitization on windows
- }
- return path
- .replace(/^["']|["']$/g, "")
- .trim()
- .replace(/\//g, "/");
- }, []);
-
- const renderFileLink = () => (
- <div className="mt-2 text-center text-xs text-gray-500">
- {customDescription || filePath}
- </div>
- );
-
- const getMimeType = (path: string): string => {
- const ext = path.split(".").pop()?.toLowerCase();
- switch (ext) {
- case "mp4":
- return "video/mp4";
- case "webm":
- return "video/webm";
- case "ogg":
- return "video/ogg";
- case "mp3":
- return "audio/mpeg";
- case "wav":
- return "audio/wav";
- default:
- return isAudio ? "audio/mpeg" : "video/mp4";
- }
- };
-
- useEffect(() => {
- async function loadMedia() {
- try {
- console.log("Loading media:", filePath);
- const sanitizedPath = await sanitizeFilePath(filePath);
- console.log("Sanitized path:", sanitizedPath);
-
- const mediaData = await readFile(sanitizedPath);
- const mimeType = getMimeType(sanitizedPath);
-
- // Set isAudio based on path check
- setIsAudio(
- sanitizedPath.toLowerCase().includes("input") ||
- sanitizedPath.toLowerCase().includes("output")
- );
-
- // Create blob URL directly
- const blob = new Blob([mediaData], { type: mimeType });
- setMediaSrc(URL.createObjectURL(blob));
- } catch (error) {
- console.error("Failed to load media:", error);
- setError(
- `Failed to load media: ${
- error instanceof Error ? error.message : "Unknown error"
- }`
- );
- }
- }
-
- loadMedia();
- return () => {
- if (mediaSrc) URL.revokeObjectURL(mediaSrc);
- };
- }, [filePath, sanitizeFilePath]);
-
- if (error) {
- return (
- <div className="w-full p-4 bg-red-100 border border-red-300 rounded-md">
- <p className="text-red-700">{error}</p>
- {renderFileLink()}
- </div>
- );
- }
-
- if (!mediaSrc) {
- return (
- <div
- className={cn(
- "w-full h-48 bg-gray-200 animate-pulse rounded-md flex items-center justify-center",
- className
- )}
- >
- <span className="text-gray-500">Loading media...</span>
- </div>
- );
- }
-
- return (
- <div className={cn("w-full max-w-2xl text-center", className)}>
- {isAudio ? (
- <AudioPlayer
- startTime={startTime}
- endTime={endTime}
- mediaSrc={mediaSrc}
- />
- ) : (
- <video controls className="w-full rounded-md">
- <source src={mediaSrc} type="video/mp4" />
- Your browser does not support the video tag.
- </video>
- )}
- {renderFileLink()}
- </div>
- );
-});
-
-const AudioPlayer = memo(function AudioPlayer({
- startTime,
- endTime,
- mediaSrc,
-}: {
- startTime?: number;
- endTime?: number;
- mediaSrc: string;
-}) {
- const [duration, setDuration] = useState<number>(0);
- const [currentTime, setCurrentTime] = useState<number>(0);
- const [isPlaying, setIsPlaying] = useState(false);
- const audioRef = useRef<HTMLAudioElement>(null);
-
- const audioElement = useMemo(
- () => (
- <audio
- ref={audioRef}
- className="w-full"
- preload="auto"
- onLoadedMetadata={(e) => {
- const audio = e.target as HTMLAudioElement;
- setDuration(audio.duration);
- if (startTime !== undefined) {
- audio.currentTime = startTime;
- }
- }}
- onTimeUpdate={(e) => {
- const audio = e.target as HTMLAudioElement;
- if (Math.abs(audio.currentTime - currentTime) > 0.1) {
- setCurrentTime(audio.currentTime);
- }
- }}
- onPlay={() => setIsPlaying(true)}
- onPause={() => setIsPlaying(false)}
- onEnded={() => setIsPlaying(false)}
- >
- <source src={mediaSrc} type="audio/mpeg" />
- Your browser does not support the audio element.
- </audio>
- ),
- [mediaSrc, startTime, currentTime]
- );
-
- const togglePlay = async () => {
- if (!audioRef.current) return;
-
- try {
- if (isPlaying) {
- audioRef.current.pause();
- } else {
- await audioRef.current.play();
- }
- setIsPlaying(!isPlaying);
- } catch (error) {
- console.error("Playback failed:", error);
- setIsPlaying(false);
- }
- };
-
- const handleTimeChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
- if (!audioRef.current) return;
-
- const time = parseFloat(e.target.value);
- const wasPlaying = isPlaying;
-
- if (wasPlaying) {
- audioRef.current.pause();
- }
-
- // Set the time directly on the audio element first
- audioRef.current.currentTime = time;
- // Then update the state
- setCurrentTime(time);
-
- if (wasPlaying) {
- try {
- await audioRef.current.play();
- } catch (error) {
- console.error("Playback failed:", error);
- setIsPlaying(false);
- }
- }
- };
-
- return (
- <div className="bg-gray-100 px-4 py-6 rounded-md">
- <div className="relative">
- {startTime !== undefined && startTime > 0 && (
- <div
- className="absolute top-[-8px] h-6 w-0.5 bg-black z-10"
- style={{
- left: `calc(88px + ${
- (startTime || 0) / duration
- } * calc(100% - 176px))`,
- }}
- >
- <div className="absolute -top-4 left-1/2 -translate-x-1/2 text-xs">
- Start
- </div>
- </div>
- )}
- {endTime !== undefined && endTime < duration - 0.1 && (
- <div
- className="absolute top-[-8px] h-6 w-0.5 bg-black z-10"
- style={{
- left: `calc(88px + ${
- (endTime || 0) / duration
- } * calc(100% - 176px))`,
- }}
- >
- <div className="absolute -top-4 left-1/2 -translate-x-1/2 text-xs">
- End
- </div>
- </div>
- )}
- <button
- onClick={togglePlay}
- className="absolute left-4 top-1/2 -translate-y-1/2 w-8 h-8 flex items-center justify-center bg-black hover:bg-gray-800 text-white rounded-full"
- >
- {isPlaying ? (
- <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
- <rect x="6" y="4" width="4" height="16" />
- <rect x="14" y="4" width="4" height="16" />
- </svg>
- ) : (
- <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
- <path d="M8 5v14l11-7z" />
- </svg>
- )}
- </button>
- <div className="mx-[88px] relative">
- <div className="h-1 bg-gray-300 rounded-full overflow-hidden">
- <div
- className="h-full bg-black"
- style={{
- width: `${(currentTime / duration) * 100}%`,
- }}
- />
- </div>
- <div
- className="absolute top-1/2 -translate-x-1/3 -translate-y-1/2 w-2 h-2 bg-black rounded-full cursor-pointer hover:bg-gray-800 hover:h-4 hover:w-4"
- style={{
- left: `${(currentTime / duration) * 100}%`,
- }}
- />
- <input
- type="range"
- min={0}
- max={duration}
- value={currentTime}
- onChange={handleTimeChange}
- className="absolute inset-0 w-full opacity-0 cursor-pointer"
- step="any"
- />
- </div>
- {audioElement}
- </div>
- </div>
- );
-});
diff --git a/screenpipe-app-tauri/lib/hooks/use-conversation-history.tsx b/screenpipe-app-tauri/lib/hooks/use-conversation-history.tsx
deleted file mode 100644
index 5672f94df..000000000
--- a/screenpipe-app-tauri/lib/hooks/use-conversation-history.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import { useEffect, useState } from "react";
-import localforage from "localforage";
-import { SearchHistory } from "../types/history";
-
-const HISTORY_KEY = "screenpipe-conversation-history";
-
-export function useConversationHistory() {
- const [conversations, setConversations] = useState<SearchHistory[]>([]);
- const [currentConversationId, setCurrentConversationId] = useState<
- string | null
- >(null);
- const [isLoading, setIsLoading] = useState(true);
-
- useEffect(() => {
- loadConversations();
- }, []);
-
- const loadConversations = async () => {
- try {
- const stored = await localforage.getItem<SearchHistory[]>(HISTORY_KEY);
- setConversations(stored || []);
- } catch (error) {
- console.error("failed to load conversations:", error);
- }
- setIsLoading(false);
- };
-
- const saveConversations = async (updated: SearchHistory[]) => {
- try {
- await localforage.setItem(HISTORY_KEY, updated);
- setConversations(updated);
- } catch (error) {
- console.error("failed to save conversations:", error);
- }
- };
-
- const addMessage = async (
- conversationId: string | null,
- type: "search" | "ai",
- content: string,
- searchQuery?: any
- ) => {
- const timestamp = new Date().toISOString();
- const messageId = crypto.randomUUID();
-
- if (!conversationId) {
- // create new conversation
- const newConversation: SearchHistory = {
- id: crypto.randomUUID(),
- query: content.slice(0, 30) + (content.length > 30 ? "..." : ""),
- timestamp,
- searchParams: {
- ...searchQuery,
- },
- results: [],
- messages: [
- {
- id: messageId,
- type,
- content,
- timestamp,
- },
- ],
- };
-
- const updated = [newConversation, ...conversations];
- await saveConversations(updated);
- setCurrentConversationId(newConversation.id);
- return newConversation.id;
- }
-
- // add to existing conversation
- const updated = conversations.map((conv) => {
- if (conv.id === conversationId) {
- return {
- ...conv,
- lastUpdatedAt: timestamp,
- messages: [
- ...conv.messages,
- {
- id: messageId,
- type,
- content,
- timestamp,
- searchQuery,
- },
- ],
- };
- }
- return conv;
- });
-
- await saveConversations(updated);
- return conversationId;
- };
-
- const deleteConversation = async (id: string) => {
- const updated = conversations.filter((c) => c.id !== id);
- await saveConversations(updated);
- if (currentConversationId === id) {
- setCurrentConversationId(null);
- }
- };
-
- return {
- conversations,
- currentConversationId,
- setCurrentConversationId,
- addMessage,
- deleteConversation,
- isLoading,
- };
-}
diff --git a/screenpipe-app-tauri/lib/hooks/use-input-history.tsx b/screenpipe-app-tauri/lib/hooks/use-input-history.tsx
deleted file mode 100644
index 1b2589e78..000000000
--- a/screenpipe-app-tauri/lib/hooks/use-input-history.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { useState, useEffect } from "react";
-
-export function useInputHistory(key: string, maxHistory: number = 10) {
- const [value, setValue] = useState("");
- const [history, setHistory] = useState<string[]>([]);
-
- useEffect(() => {
- const savedHistory = localStorage.getItem(`${key}_history`);
- if (savedHistory) {
- setHistory(JSON.parse(savedHistory));
- }
- }, [key]);
-
- const updateValue = (newValue: string) => {
- setValue(newValue);
- };
-
- const saveToHistory = () => {
- if (value && !history.includes(value)) {
- const updatedHistory = [value, ...history.slice(0, maxHistory - 1)];
- setHistory(updatedHistory);
- try {
- localStorage.setItem(`${key}_history`, JSON.stringify(updatedHistory));
- } catch (error) {
- console.error(`Failed to save ${key} history:`, error);
- }
- }
- };
-
- return { value, setValue: updateValue, history, saveToHistory };
-}
diff --git a/screenpipe-app-tauri/lib/hooks/use-search-history.tsx b/screenpipe-app-tauri/lib/hooks/use-search-history.tsx
deleted file mode 100644
index bc1ccf504..000000000
--- a/screenpipe-app-tauri/lib/hooks/use-search-history.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-"use client";
-
-import { useEffect, useState } from 'react';
-import localforage from 'localforage';
-import { SearchHistory } from '../types/history';
-
-const HISTORY_KEY = 'screenpipe-search-history';
-
-export function useSearchHistory() {
- const [searches, setSearches] = useState<SearchHistory[]>([]);
- const [currentSearchId, setCurrentSearchId] = useState<string | null>(null);
- const [isLoading, setIsLoading] = useState(true);
- const [isCollapsed, setIsCollapsed] = useState(true);
-
- useEffect(() => {
- loadSearches();
- }, []);
-
- const loadSearches = async () => {
- try {
- const stored = await localforage.getItem<SearchHistory[]>(HISTORY_KEY);
- setSearches(stored || []);
- } catch (error) {
- console.error('failed to load search history:', error);
- }
- setIsLoading(false);
- };
-
- const saveSearches = async (updated: SearchHistory[]) => {
- try {
- await localforage.setItem(HISTORY_KEY, updated);
- setSearches(updated);
- } catch (error) {
- console.error('failed to save search history:', error);
- }
- };
-
- const addSearch = async (searchParams: any, results: any[]) => {
- const timestamp = new Date().toISOString();
- const newSearch: SearchHistory = {
- id: crypto.randomUUID(),
- query: searchParams.q || '',
- timestamp,
- searchParams,
- results,
- messages: [{
- id: crypto.randomUUID(),
- type: 'search' as const,
- content: searchParams.q || '',
- timestamp
- }]
- };
-
- const updated = [newSearch, ...searches];
- await saveSearches(updated);
- setCurrentSearchId(newSearch.id);
- return newSearch.id;
- };
-
- const addAIResponse = async (searchId: string, response: string) => {
- const timestamp = new Date().toISOString();
- const updated = searches.map(search => {
- if (search.id === searchId) {
- return {
- ...search,
- messages: [...search.messages, {
- id: crypto.randomUUID(),
- type: 'ai' as const,
- content: response,
- timestamp
- }]
- };
- }
- return search;
- });
- await saveSearches(updated);
- };
-
- const deleteSearch = async (id: string) => {
- const updated = searches.filter(s => s.id !== id);
- await saveSearches(updated);
- if (currentSearchId === id) {
- setCurrentSearchId(null);
- }
- };
-
- const toggleCollapse = () => {
- setIsCollapsed(!isCollapsed);
- };
-
- return {
- searches,
- currentSearchId,
- setCurrentSearchId,
- addSearch,
- addAIResponse,
- deleteSearch,
- isLoading,
- isCollapsed,
- toggleCollapse
- };
-}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/lib/screenpipe.ts b/screenpipe-app-tauri/lib/screenpipe.ts
deleted file mode 100644
index 30a92b25b..000000000
--- a/screenpipe-app-tauri/lib/screenpipe.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import { z } from "zod";
-import { encode } from "./utils";
-import { Speaker } from "./types";
-
-// Define types based on the server's schema
-export type OCRContent = {
- frame_id: number;
- text: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- app_name: string;
- window_name: string;
- tags: string[];
- frame?: string;
-};
-
-export type AudioContent = {
- chunk_id: number;
- transcription: string;
- timestamp: string;
- file_path: string;
- offset_index: number;
- tags: string[];
- device_name: string;
- device_type: string;
- speaker: Speaker;
- start_time?: number;
- end_time?: number;
-};
-
-export type FTSContent = {
- text_id: number;
- matched_text: string;
- frame_id: number;
- timestamp: string;
- app_name: string;
- window_name: string;
- file_path: string;
- original_frame_text?: string;
- tags: string[];
-};
-
-export type UIContent = {
- frame_id: number;
- timestamp: string;
- file_path: string;
- text: string;
- app_name: string;
- window_name: string;
- tags: string[];
-};
-
-export type ContentItem =
- | { type: "OCR"; content: OCRContent }
- | { type: "Audio"; content: AudioContent }
- | { type: "FTS"; content: FTSContent }
- | { type: "UI"; content: UIContent };
-
-export type PaginationInfo = {
- limit: number;
- offset: number;
- total: number;
-};
-
-export type ScreenpipeResponse = {
- data: ContentItem[];
- pagination: PaginationInfo;
-};
-
-export const screenpipeQuery = z.object({
- q: z
- .string()
- .describe(
- `The search query matching exact keywords.
- Use a single keyword that best matches the user intent.
- This would match either audio transcription or OCR screen text.
-
- Example: do not use 'discuss' the user ask about conversation, this is dumb, won't return any result
- Other example: 'what did i do this morning?' do not use any keywords, just look at everything
-
- In general avoid using "q" as it will filter out all data
- `
- )
- .optional(),
- content_type: z
- .enum(["ocr", "audio", "all"])
- .default("all")
- .describe(
- "The type of content to search for: screenshot data or audio transcriptions"
- ),
- limit: z
- .number()
- .default(50)
- .describe(
- "Number of results to return. Be mindful of the length of the response as it will be fed to an LLM"
- ),
- offset: z.number().default(0).describe("Offset for pagination (default: 0)"),
- start_time: z
- .string()
- // 1 hour ago
- .default(new Date(Date.now() - 3600000).toISOString())
- .describe(`Start time for search range in ISO 8601 format`),
- end_time: z
- .string()
- .default(new Date().toISOString())
- .describe(`End time for search range in ISO 8601 format`),
- app_name: z
- .string()
- .describe(
- `The name of the app the user was using.
- This filter out all audio conversations.
- Only works with screen text.
- Use this to filter on the app context that would give context matching the user intent.
- For example 'cursor'. Use lower case.
- Browser is usually 'arc', 'chrome', 'safari', etc.
- Other apps can be 'whatsapp', 'obsidian', etc.
- `
- )
- .optional(),
- window_name: z
- .string()
- .describe(
- `The name of the window the user was using.
- This helps to further filter the context within the app.
- For example, 'inbox' for email apps, 'project' for project management apps, etc.
- `
- )
- .optional(), // Add window_name with description
- include_frames: z
- .boolean()
- .default(false)
- .describe("Include frames in the response"),
- min_length: z
- .number()
- .default(50)
- .describe("Minimum length of the text to include in the response"),
- max_length: z
- .number()
- .default(10000)
- .describe("Maximum length of the text to include in the response"),
- speaker_ids: z
- .string()
- .describe("Comma separated list of speaker ids to filter by")
- .optional(),
-});
-
-export const screenpipeMultiQuery = z.object({
- queries: z.array(screenpipeQuery),
-});
-
-export async function queryScreenpipeNtimes(
- params: z.infer<typeof screenpipeMultiQuery>
-): Promise<ScreenpipeResponse[]> {
- console.log("queryScreenpipeNtimes", params);
- const results = await Promise.all(params.queries.map(queryScreenpipe));
- return results.filter(
- (result): result is ScreenpipeResponse => result !== null
- );
-}
-
-// Add this new function to handle screenpipe requests
-export async function queryScreenpipe(
- params: z.infer<typeof screenpipeQuery>
-): Promise<ScreenpipeResponse | null> {
- try {
- console.log("params", params);
-
- const queryParams = new URLSearchParams({
- content_type: params.content_type,
- limit: params.limit.toString(),
- offset: params.offset.toString(),
- start_time: params.start_time,
- end_time: params.end_time,
- min_length: params.min_length.toString(),
- max_length: params.max_length.toString(),
- include_frames: params.include_frames.toString(),
- });
-
- if (params.q) queryParams.append("q", params.q);
- if (params.app_name) queryParams.append("app_name", params.app_name);
- if (params.window_name)
- queryParams.append("window_name", params.window_name);
- if (params.speaker_ids)
- queryParams.append("speaker_ids", params.speaker_ids);
- const url = `http://localhost:3030/search?${queryParams.toString()}`;
- console.log("calling screenpipe", url);
-
- const response = await fetch(url);
- if (!response.ok) {
- const text = await response.text();
- throw new Error(`http error! status: ${response.status} ${text}`);
- }
- const result = await response.json();
- console.log("result", result);
- console.log("result", result.data.length);
- return result;
- } catch (error) {
- console.error("error querying screenpipe:", error);
- return null;
- }
-}
diff --git a/screenpipe-app-tauri/lib/types/history.ts b/screenpipe-app-tauri/lib/types/history.ts
deleted file mode 100644
index fdbb60dc2..000000000
--- a/screenpipe-app-tauri/lib/types/history.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-export interface SearchHistory {
- id: string;
- query: string;
- timestamp: string;
- searchParams: {
- q?: string;
- content_type: string;
- limit: number;
- offset: number;
- start_time: string;
- end_time: string;
- app_name?: string;
- window_name?: string;
- include_frames: boolean;
- min_length: number;
- max_length: number;
- };
- results: any[];
- messages: {
- id: string;
- type: 'search' | 'ai';
- content: string;
- timestamp: string;
- }[];
-}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/lib/types/index.ts b/screenpipe-app-tauri/lib/types/index.ts
deleted file mode 100644
index e69de29bb..000000000
diff --git a/screenpipe-app-tauri/lib/types/meeting.ts b/screenpipe-app-tauri/lib/types/meeting.ts
deleted file mode 100644
index 13dc14aca..000000000
--- a/screenpipe-app-tauri/lib/types/meeting.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { Speaker } from "./speaker";
-
-export interface MeetingSegment {
- timestamp: string;
- transcription: string;
- deviceName: string;
- deviceType: string;
- speaker: Speaker;
-}
diff --git a/screenpipe-app-tauri/lib/types/speaker.ts b/screenpipe-app-tauri/lib/types/speaker.ts
deleted file mode 100644
index 3d0eb12fd..000000000
--- a/screenpipe-app-tauri/lib/types/speaker.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export type AudioSample = {
- path: string;
- transcript: string;
- startTime?: number;
- endTime?: number;
-};
-
-export interface Speaker {
- id: number;
- name: string;
- metadata?: {
- audioSamples: AudioSample[];
- };
-}
diff --git a/screenpipe-app-tauri/lib/utils.ts b/screenpipe-app-tauri/lib/utils.ts
index 7c08df633..2822319d9 100644
--- a/screenpipe-app-tauri/lib/utils.ts
+++ b/screenpipe-app-tauri/lib/utils.ts
@@ -2,9 +2,6 @@ import { stat } from "@tauri-apps/plugin-fs";
import { platform } from "@tauri-apps/plugin-os";
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
-import { ContentItem } from "./screenpipe";
-import levenshtein from "js-levenshtein";
-import { Duration } from "date-fns";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
@@ -63,46 +60,6 @@ export function getCliPath() {
}
}
-// Add this pure function outside of the SearchChat component
-export const removeDuplicateSelections = (
- results: ContentItem[],
- selectedResults: Set<number>,
- similarityThreshold: number = 0.9
-): Set<number> => {
- const newSelectedResults = new Set<number>();
- const seenContents: string[] = [];
-
- const getSimilarity = (str1: string, str2: string): number => {
- const maxLength = Math.max(str1.length, str2.length);
- const distance = levenshtein(str1, str2);
- return 1 - distance / maxLength;
- };
-
- const isDuplicate = (content: string): boolean => {
- return seenContents.some(
- (seenContent) =>
- getSimilarity(content, seenContent) >= similarityThreshold
- );
- };
-
- Array.from(selectedResults).forEach((index) => {
- const item = results[index];
- if (!item || !item.type) return;
-
- let content = "";
- if (item.type === "OCR") content = item.content.text;
- else if (item.type === "Audio") content = item.content.transcription;
- else if (item.type === "FTS") content = item.content.matched_text;
-
- if (!isDuplicate(content)) {
- seenContents.push(content);
- newSelectedResults.add(index);
- }
- });
-
- return newSelectedResults;
-};
-
export function parseKeyboardShortcut(shortcut: string): string {
if (typeof window !== "undefined") {
const os = platform();
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index b6085e886..6ffe9c707 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -4966,7 +4966,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "0.18.5"
+version = "0.18.7"
dependencies = [
"anyhow",
"axum",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 935f1a2a6..51e467e32 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.18.6"
+version = "0.18.7"
description = ""
authors = ["you"]
license = ""