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

feat: big refactor of obsidian pipe, embed videos, clarify UI, make it possible ot use 2 different models for analysis and logs

Louis Beaumonta9cc7a65d0ab
diff --git a/pipes/obsidian/package.json b/pipes/obsidian/package.json
index 34a892ea5..2530e0a34 100644
--- a/pipes/obsidian/package.json
+++ b/pipes/obsidian/package.json
@@ -1,6 +1,6 @@
{
"name": "obsidian",
- "version": "0.1.20",
+ "version": "0.1.21",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
diff --git a/pipes/obsidian/src/app/api/files/route.ts b/pipes/obsidian/src/app/api/files/route.ts
index fe356fa3f..847504699 100644
--- a/pipes/obsidian/src/app/api/files/route.ts
+++ b/pipes/obsidian/src/app/api/files/route.ts
@@ -120,7 +120,7 @@ export async function GET(request: Request) {
}
const settings = await settingsManager.getAll();
- const initialPath = settings.customSettings?.obsidian?.path;
+ const initialPath = settings.customSettings?.obsidian?.vaultPath;
if (!initialPath) {
return NextResponse.json({ files: [] });
diff --git a/pipes/obsidian/src/app/api/intelligence/route.ts b/pipes/obsidian/src/app/api/intelligence/route.ts
index 929d4cf31..42a62e745 100644
--- a/pipes/obsidian/src/app/api/intelligence/route.ts
+++ b/pipes/obsidian/src/app/api/intelligence/route.ts
@@ -1,172 +1,11 @@
import { NextResponse } from "next/server";
import { z } from "zod";
-import { generateObject } from "ai";
+import { generateObject, generateText, jsonSchema } from "ai";
import { ollama } from "ollama-ai-provider";
import { pipe } from "@screenpipe/js";
import * as fs from "fs/promises";
import * as path from "path";
-
-// rich schema for relationship intelligence
-const contactSchema = z.object({
- name: z.string(),
- company: z.string().optional(),
- lastInteraction: z.string(),
- sentiment: z.number(), // -1 to 1
- topics: z.array(z.string()),
- nextSteps: z.array(z.string()),
-});
-
-const relationshipIntelligence = z.object({
- contacts: z.array(contactSchema),
- insights: z.object({
- followUps: z.array(z.string()),
- opportunities: z.array(z.string()),
- }),
-});
-
-async function analyzeRelationships(
- recentLogs: string,
- model: string
-): Promise<z.infer<typeof relationshipIntelligence>> {
- const prompt = `analyze these work logs and create a comprehensive relationship intelligence report.
- focus on:
- - identifying key people and their roles
- - tracking interaction patterns and sentiment
- - spotting business opportunities
- - suggesting follow-ups and introductions
- - finding patterns in topics discussed
-
- recent logs: ${recentLogs}
-
- todays date: ${new Date().toISOString().split("T")[0]}
- local time: ${new Date().toLocaleTimeString()}
- timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}
-
- return a detailed json object following this structure for relationship intelligence.
-
- example response from you:
-
- {
- "contacts": [
- {
- "name": "John Doe",
- "company": "Acme Inc.",
- "lastInteraction": "2024-01-01",
- "sentiment": 0.8,
- "topics": ["sales", "marketing"],
- "nextSteps": ["schedule a call", "send a follow-up email"]
- }
- ],
- "insights": {
- "followUps": ["schedule a call", "send a follow-up email"],
- "opportunities": ["schedule a call", "send a follow-up email"]
- }
- }
-
- of course adapt the example response to the actual data you have, do not use John Doe in your example response, use the names and companies of the people you see in the logs.
- `;
-
- const provider = ollama(model);
- console.log("prompt", prompt);
- const response = await generateObject({
- model: provider,
- messages: [{ role: "user", content: prompt }],
- schema: relationshipIntelligence,
- maxRetries: 5,
- });
-
- console.log(response.object);
- return response.object;
-}
-
-async function saveToGraph(
- intelligence: z.infer<typeof relationshipIntelligence>,
- obsidianPath: string
-): Promise<string> {
- // normalize path for cross-platform compatibility
- const normalizedPath = path.normalize(obsidianPath);
- const graphPath = path.join(normalizedPath, "relationship-graph");
- await fs.mkdir(graphPath, { recursive: true });
-
- // create markdown file with mermaid graph
- let mermaidGraph = "```mermaid\ngraph TD\n";
-
- // add nodes for each contact
- intelligence.contacts.forEach((contact) => {
- mermaidGraph += ` ${contact.name.replace(/\s+/g, "_")}["${
- contact.name
- }\n${contact.company || ""}"]\n`;
- });
-
- // add basic relationships between contacts that share topics
- const contactsByTopic = new Map<string, string[]>();
- intelligence.contacts.forEach((contact) => {
- contact.topics.forEach((topic) => {
- if (!contactsByTopic.has(topic)) {
- contactsByTopic.set(topic, []);
- }
- contactsByTopic.get(topic)?.push(contact.name);
- });
- });
-
- // create edges for contacts sharing topics
- contactsByTopic.forEach((contacts) => {
- for (let i = 0; i < contacts.length; i++) {
- for (let j = i + 1; j < contacts.length; j++) {
- mermaidGraph += ` ${contacts[i].replace(/\s+/g, "_")} --- ${contacts[
- j
- ].replace(/\s+/g, "_")}\n`;
- }
- }
- });
-
- mermaidGraph += "```\n";
-
- // save as markdown with frontmatter
- const content = `---
-created: ${new Date().toISOString()}
-tags: [relationship-intelligence, crm, network]
----
-
-# relationship intelligence report
-
-## network graph
-${mermaidGraph}
-
-## key contacts
-${intelligence.contacts
- .map(
- (c) => `
-### ${c.name}
-- company: ${c.company || "n/a"}
-- last interaction: ${c.lastInteraction}
-- sentiment: ${c.sentiment}
-- topics: ${c.topics.join(", ")}
-- next steps: ${c.nextSteps.join(", ")}
-`
- )
- .join("\n")}
-
-## insights
-### follow-ups needed
-${intelligence.insights.followUps.map((f) => `- ${f}`).join("\n")}
-
-### opportunities
-${intelligence.insights.opportunities.map((o) => `- ${o}`).join("\n")}
-`;
-
- const filename = `${new Date().toISOString().split("T")[0]}-intelligence.md`;
- await fs.writeFile(path.join(graphPath, filename), content, "utf8");
-
- // get vault name safely for windows paths
- const relativePath = obsidianPath
- .replace(normalizedPath, "")
- .replace(/^\//, "");
- // Return the deep link
- return `obsidian://search?vault=${encodeURIComponent(
- relativePath
- )}&query=relationship-intelligence`;
-}
+import { extractLinkedContent } from "@/lib/actions/obsidian";
async function readRecentLogs(
obsidianPath: string,
@@ -176,7 +15,6 @@ async function readRecentLogs(
const yesterday = since.toISOString().split("T")[0];
try {
- // just read today and yesterday's logs as raw text
const todayContent = await fs
.readFile(path.join(obsidianPath, `${today}.md`), "utf8")
.catch(() => "");
@@ -191,11 +29,106 @@ async function readRecentLogs(
}
}
+async function analyzeWithLLM(
+ content: string,
+ prompt: string,
+ model: string,
+ obsidianPath?: string
+): Promise<any> {
+ const provider = ollama(model);
+
+ let enrichedPrompt = prompt;
+ if (obsidianPath) {
+ enrichedPrompt = await extractLinkedContent(prompt, obsidianPath);
+ }
+
+ const systemPrompt = `You are an intelligent analysis system that processes user activity logs and creates higher-level insights.
+
+Context:
+- You are analyzing logs that were collected every 5 minutes
+- Your task is to create a higher-level synthesis (hourly/daily summaries)
+- Previous logs contain important context for understanding patterns
+- Look for recurring themes, projects, and behavioral patterns
+- Pay special attention to @[[note references]] which indicate important user context
+
+Here are some user instructions:
+${enrichedPrompt}
+
+Previous Logs:
+${content}
+
+Instructions for Media and Formatting:
+- When referencing videos, use: <video src="file:///PATH_TO_VIDEO.mp4" controls/>
+- For links to other notes, use: [[note-name]]
+- For timestamps, use: \`HH:MM\` format
+- Create sections with level-3 headers: ### Section Name
+- Use bullet points for lists and patterns
+- Do not wrap your response in \`\`\`markdown\`\`\` tags
+- Add relevant #tags for categorization
+- Escape any pipe characters (|) in tables with \\|
+- All your outputs will be written directly in Obsidian note taking app so use the formatting of the app in your response to maximize readability,
+embeding links, videos, etc. usually mp4 needs video html component and not the link format
+
+Analysis Structure:
+### Summary
+- High-level overview of the time period
+- Key accomplishments and patterns
+
+### Activity Timeline
+- Chronological breakdown of significant events
+- Include relevant media embeddings
+
+### Patterns & Insights
+- Recurring themes or behaviors
+- Project progress
+- Context switches
+- Time allocation
+
+### Related Notes
+- Link to relevant vault notes
+- Context connections
+
+Generate a structured analysis following the above format.`;
+
+ console.log("systemPrompt", systemPrompt);
+
+ const response = await generateText({
+ model: provider,
+ messages: [{ role: "user", content: systemPrompt }],
+ maxRetries: 5,
+ });
+
+ return response.text;
+}
+
+async function saveMarkdown(
+ content: string,
+ obsidianPath: string,
+ filename: string
+): Promise<string> {
+ const normalizedPath = path.normalize(obsidianPath);
+ await fs.mkdir(normalizedPath, { recursive: true });
+
+ const filePath = path.join(normalizedPath, filename);
+ await fs.writeFile(filePath, content, "utf8");
+
+ const relativePath = obsidianPath
+ .replace(normalizedPath, "")
+ .replace(/^\//, "");
+ return `obsidian://open?vault=${encodeURIComponent(
+ relativePath
+ )}&file=${encodeURIComponent(filename)}`;
+}
+
export async function GET() {
try {
const settings = await pipe.settings.getAll();
const obsidianPath = settings.customSettings?.obsidian?.vaultPath;
- const model = settings.customSettings?.obsidian?.aiModel;
+ const model = settings.customSettings?.obsidian?.analysisModel;
+ const customPrompt = settings.customSettings?.obsidian?.prompt;
+ const timeWindow =
+ settings.customSettings?.obsidian?.analysisTimeWindow ||
+ 1 * 60 * 60 * 1000;
if (!obsidianPath) {
return NextResponse.json(
@@ -204,28 +137,47 @@ export async function GET() {
);
}
- // get last 24 hours of logs
- const today = new Date();
- const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
+ // Read logs within time window
+ const now = new Date();
+ const since = new Date(now.getTime() - timeWindow);
+ const recentLogs = await readRecentLogs(obsidianPath, since);
- const recentLogs = await readRecentLogs(obsidianPath, yesterday);
-
- if (recentLogs.length === 0) {
+ if (!recentLogs) {
return NextResponse.json({ message: "no logs found for analysis" });
}
- const intelligence = await analyzeRelationships(recentLogs, model);
- const deepLink = await saveToGraph(intelligence, obsidianPath);
+ // Analyze with LLM
+ const analysis = await analyzeWithLLM(
+ recentLogs,
+ customPrompt,
+ model,
+ obsidianPath
+ );
+
+ // Save results based on output format
+ const filename = `${now
+ .toLocaleDateString("en-US", {
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ })
+ .split("/")
+ .reverse()
+ .join("-")}-${now.getHours().toString().padStart(2, "0")}-${now
+ .getMinutes()
+ .toString()
+ .padStart(2, "0")}-analysis.md`;
+
+ const deepLink = await saveMarkdown(analysis, obsidianPath, filename);
return NextResponse.json({
- message: "relationship intelligence updated",
- intelligence,
+ message: "analysis completed",
+ intelligence: analysis,
deepLink,
summary: {
- contacts: intelligence.contacts.length,
- opportunities: intelligence.insights.opportunities.length,
- needsFollowUp: intelligence.insights.followUps.length,
+ timeWindow,
logsAnalyzed: recentLogs.length,
+ timestamp: now.toISOString(),
},
});
} catch (error) {
diff --git a/pipes/obsidian/src/app/api/log/route.ts b/pipes/obsidian/src/app/api/log/route.ts
index a793733b0..841b6b5ed 100644
--- a/pipes/obsidian/src/app/api/log/route.ts
+++ b/pipes/obsidian/src/app/api/log/route.ts
@@ -6,11 +6,13 @@ import { ContentItem } from "@screenpipe/js";
import { pipe } from "@screenpipe/js";
import * as fs from "fs/promises";
import * as path from "path";
+import { extractLinkedContent } from "@/lib/actions/obsidian";
const workLog = z.object({
title: z.string(),
description: z.string(),
tags: z.array(z.string()),
+ mediaLinks: z.array(z.string()).optional(),
});
type WorkLog = z.infer<typeof workLog> & {
@@ -18,73 +20,6 @@ type WorkLog = z.infer<typeof workLog> & {
endTime: string;
};
-async function readObsidianFile(filePath: string): Promise<string> {
- try {
- const content = await fs.readFile(filePath, "utf8");
- return content;
- } catch (err) {
- console.error(`failed to read file ${filePath}:`, err);
- return "";
- }
-}
-
-async function findVaultRoot(startPath: string): Promise<string> {
- let currentPath = startPath;
-
- while (currentPath !== "/" && currentPath !== ".") {
- try {
- // Check if .obsidian exists in current directory
- await fs.access(path.join(currentPath, ".obsidian"));
- return currentPath; // Found the vault root
- } catch {
- // Move up one directory
- currentPath = path.dirname(currentPath);
- }
- }
- throw new Error("could not find obsidian vault root (.obsidian folder)");
-}
-
-async function extractLinkedContent(
- prompt: string,
- basePath: string
-): Promise<string> {
- try {
- // Find the vault root first
- const vaultRoot = await findVaultRoot(basePath);
-
- // Match @[[file]] or @[[folder/file]] patterns
- const linkRegex = /@\[\[(.*?)\]\]/g;
- const matches = [...prompt.matchAll(linkRegex)];
-
- let enrichedPrompt = prompt;
-
- for (const match of matches) {
- const relativePath = match[1];
- // Handle .md extension if not present
- const fullPath = path.join(
- vaultRoot,
- relativePath.endsWith(".md") ? relativePath : `${relativePath}.md`
- );
-
- try {
- const content = await readObsidianFile(fullPath);
- // Replace the @[[link]] with actual content
- enrichedPrompt = enrichedPrompt.replace(
- match[0],
- `\n--- Content of ${relativePath} ---\n${content}\n---\n`
- );
- } catch (err) {
- console.error(`failed to process link ${relativePath}:`, err);
- }
- }
-
- return enrichedPrompt;
- } catch (err) {
- console.error("failed to find vault root:", err);
- return prompt; // Return original prompt if we can't process links
- }
-}
-
async function generateWorkLog(
screenData: ContentItem[],
model: string,
@@ -99,25 +34,35 @@ async function generateWorkLog(
enrichedPrompt = await extractLinkedContent(customPrompt, obsidianPath);
}
- const defaultPrompt = `Based on the following screen data, generate a concise work activity log entry.
- Rules:
- - use the screen data to generate the log entry
- - focus on describing the activity and tags
- - use the following context to better understand the user's goals and priorities:
-
+ const defaultPrompt = `You are analyzing screen recording data from Screenpipe, a desktop app that records screens & mics 24/7 to provide context to AI systems.
+ The data includes OCR text, audio transcriptions, and media files from the user's desktop activity.
+
+ Based on the following screen data, generate a concise work activity log entry.
+
+ Here are some user instructions:
${enrichedPrompt}
-
- Screen data: ${JSON.stringify(screenData)}
+ Screen data: ${JSON.stringify(screenData)}
+
+ Rules:
+ - analyze the screen data carefully to understand the user's work context and activities
+ - generate a clear, specific title that reflects the main activity
+ - write a concise but informative description focusing on what was accomplished
+ - add relevant tags based on detected applications, websites, and content types
+ - properly format media files as HTML video elements in table cell:
+ - video: <video src="file://PATH_TO_VIDEO.mp4" controls></video>
+ - include all relevant media file paths in the mediaLinks array
+ - maintain user privacy by excluding sensitive/personal information
+ - ensure description and content are properly escaped for markdown table cells (use <br> for newlines)
+
Return a JSON object with:
{
- "title": "Brief title of the activity",
- "description": "Concise description of what was done",
- "tags": ["#tag1", "#tag2", "#tag3"]
+ "title": "Brief, specific title describing the main activity",
+ "description": "Clear description of what was accomplished, focusing on concrete outcomes",
+ "tags": ["#relevant-tool", "#activity-type", "#project-context"],
+ "mediaLinks": ["<video src=\"file:///absolute/path/to/video.mp4\" controls></video>"]
}`;
- console.log("enrichedPrompt prompt:", enrichedPrompt);
-
const provider = ollama(model);
const response = await generateObject({
model: provider,
@@ -125,6 +70,7 @@ async function generateWorkLog(
schema: workLog,
});
+ console.log("response:", response.object);
const formatDate = (date: Date) => {
return date.toLocaleString("en-US", {
year: "numeric",
@@ -158,20 +104,59 @@ async function syncLogToObsidian(
const vaultName = path.basename(path.resolve(normalizedPath));
- const tableRow = `| ${logEntry.title} | ${
- logEntry.description
- } | ${logEntry.tags.join(", ")} | ${logEntry.startTime} | ${
+ const escapeTableCell = (content: string) => {
+ return content.replace(/\|/g, "\\|").replace(/\n/g, "<br>");
+ };
+
+ const timeRange = `${escapeTableCell(logEntry.startTime)} - ${escapeTableCell(
logEntry.endTime
+ )}`;
+
+ // Combine title with timestamp and description with tags
+ const titleWithTime = `${escapeTableCell(logEntry.title)}<br>${timeRange}`;
+ const descriptionWithTags = `${escapeTableCell(
+ logEntry.description
+ )}<br>${escapeTableCell(logEntry.tags.join("<br>"))}`;
+
+ const tableHeaders = `| Title | Description | Media |\n|-------|-------------|--------|\n`;
+ const tableRow = `| ${titleWithTime} | ${descriptionWithTags} | ${
+ logEntry.mediaLinks?.map((link) => escapeTableCell(link)).join("<br>") || ""
} |\n`;
try {
- await fs.access(filePath);
- await fs.appendFile(filePath, tableRow, "utf8");
- } catch {
- const content = `| Title | Description | Tags | Start Time | End Time |\n|-------|-------------|------|------------|------------|\n${tableRow}`;
- await fs.writeFile(filePath, content, "utf8");
+ let existingContent = "";
+ try {
+ existingContent = await fs.readFile(filePath, "utf8");
+ } catch {
+ // File doesn't exist yet, create new with headers
+ await fs.writeFile(filePath, tableHeaders + tableRow, "utf8");
+ return getObsidianUrl(vaultName, filename);
+ }
+
+ if (!existingContent.trim()) {
+ // Empty file - write headers and new row
+ await fs.writeFile(filePath, tableHeaders + tableRow, "utf8");
+ } else if (!existingContent.includes("| Title | Description |")) {
+ // No headers - prepend headers and add new row while keeping existing content
+ await fs.writeFile(
+ filePath,
+ tableHeaders + existingContent + tableRow,
+ "utf8"
+ );
+ } else {
+ // Headers exist - append new row while preserving existing content
+ await fs.appendFile(filePath, tableRow, "utf8");
+ }
+ } catch (error) {
+ console.error("Error writing to file:", error);
+ throw error;
}
+ return getObsidianUrl(vaultName, filename);
+}
+
+// Helper function to generate Obsidian URL
+function getObsidianUrl(vaultName: string, filename: string): string {
return `obsidian://open?vault=${encodeURIComponent(
vaultName
)}&file=${encodeURIComponent(filename)}`;
@@ -181,11 +166,12 @@ export async function GET() {
try {
const settings = await pipe.settings.getAll();
console.log("settings:", settings);
- const interval = settings.customSettings?.obsidian?.interval || 3600000;
+ const interval =
+ settings.customSettings?.obsidian?.logTimeWindow || 3600000;
const obsidianPath = settings.customSettings?.obsidian?.vaultPath;
const customPrompt = settings.customSettings?.obsidian?.prompt;
- const pageSize = settings.customSettings?.obsidian?.pageSize || 100;
- const model = settings.customSettings?.obsidian?.aiModel;
+ const pageSize = settings.customSettings?.obsidian?.logPageSize || 100;
+ const model = settings.customSettings?.obsidian?.logModel;
if (!obsidianPath) {
return NextResponse.json(
diff --git a/pipes/obsidian/src/components/markdown.tsx b/pipes/obsidian/src/components/markdown.tsx
new file mode 100644
index 000000000..d4491467a
--- /dev/null
+++ b/pipes/obsidian/src/components/markdown.tsx
@@ -0,0 +1,9 @@
+import { FC, memo } from 'react'
+import ReactMarkdown, { Options } from 'react-markdown'
+
+export const MemoizedReactMarkdown: FC<Options> = memo(
+ ReactMarkdown,
+ (prevProps, nextProps) =>
+ prevProps.children === nextProps.children &&
+ prevProps.className === nextProps.className
+)
diff --git a/pipes/obsidian/src/components/obsidian-settings.tsx b/pipes/obsidian/src/components/obsidian-settings.tsx
index 14dda90f7..4cafc68ec 100644
--- a/pipes/obsidian/src/components/obsidian-settings.tsx
+++ b/pipes/obsidian/src/components/obsidian-settings.tsx
@@ -8,16 +8,13 @@ import {
FolderOpen,
FileCheck,
Brain,
- Users,
LineChart,
Clock,
ExternalLink,
- LoaderIcon,
Loader2,
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { OllamaModelsList } from "./ollama-models-list";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import path from "path";
@@ -25,19 +22,19 @@ import { FileSuggestTextarea } from "./file-suggest-textarea";
import { Skeleton } from "@/components/ui/skeleton";
import { debounce } from "lodash";
import { updatePipeConfig } from "@/lib/actions/update-pipe-config";
-import { Settings } from "@/lib/types";
import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";
-
+import { MemoizedReactMarkdown } from "./markdown";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import { CodeBlock } from "./ui/codeblock";
+import { VideoComponent } from "./video";
export function ObsidianSettings() {
const { settings, updateSettings, loading } = usePipeSettings();
const [lastLog, setLastLog] = useState<any>(null);
const { toast } = useToast();
- const [intelligence, setIntelligence] = useState<any>(null);
+ const [intelligence, setIntelligence] = useState<string | null>(null);
const [intelligenceLoading, setIntelligenceLoading] = useState(false);
- const [logDeepLink, setLogDeepLink] = useState<string | null>(null);
- const [intelligenceDeepLink, setIntelligenceDeepLink] = useState<
- string | null
- >(null);
+
const [customPrompt, setCustomPrompt] = useState<string | null>(null);
const [testLogLoading, setTestLogLoading] = useState(false);
const [pathValidation, setPathValidation] = useState<{
@@ -75,6 +72,7 @@ export function ObsidianSettings() {
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
+
const formData = new FormData(e.target as HTMLFormElement);
const vaultPath = formData.get("vaultPath") as string;
@@ -99,20 +97,27 @@ export function ObsidianSettings() {
});
try {
- const interval = parseInt(formData.get("interval") as string) * 60000;
+ const vaultPath = formData.get("vaultPath") as string;
+ const logTimeWindow =
+ parseInt(formData.get("logTimeWindow") as string) * 60000;
+ const analysisTimeWindow =
+ parseInt(formData.get("analysisTimeWindow") as string) * 60 * 60 * 1000;
+
+ const logPageSize = parseInt(formData.get("logPageSize") as string);
+
const obsidianSettings = {
- vaultPath: formData.get("vaultPath") as string,
- interval,
- pageSize: parseInt(formData.get("pageSize") as string),
- aiModel: formData.get("aiModel") as string,
+ vaultPath,
+ logTimeWindow,
+ logPageSize,
prompt: customPrompt || "",
+ analysisTimeWindow,
};
await updateSettings({
...settings!,
...obsidianSettings,
});
- await updatePipeConfig(interval / 60000);
+ await updatePipeConfig(logTimeWindow / 60000);
loadingToast.update({
id: loadingToast.id,
@@ -120,6 +125,7 @@ export function ObsidianSettings() {
description: "your obsidian settings have been updated",
});
} catch (err) {
+ console.warn("error saving settings:", err);
loadingToast.update({
id: loadingToast.id,
title: "error",
@@ -131,29 +137,10 @@ export function ObsidianSettings() {
const testLog = async () => {
setTestLogLoading(true);
try {
- const formData = new FormData(
- document.querySelector("form") as HTMLFormElement,
- );
- const interval = parseInt(formData.get("interval") as string) * 60000;
- const obsidianSettings = {
- vaultPath: formData.get("vaultPath") as string,
- interval,
- pageSize: parseInt(formData.get("pageSize") as string),
- aiModel: formData.get("aiModel") as string,
- prompt: customPrompt || "",
- };
-
- await updateSettings({
- ...settings!,
- ...obsidianSettings,
- });
- await updatePipeConfig(interval / 60000);
-
// Then test log generation
const res = await fetch("/api/log");
const data = await res.json();
setLastLog(data);
- setLogDeepLink(data.deepLink);
} catch (err) {
console.error("error testing log:", err);
toast({
@@ -215,7 +202,6 @@ export function ObsidianSettings() {
const data = await res.json();
console.log("data", data);
setIntelligence(data.intelligence);
- setIntelligenceDeepLink(data.deepLink);
if (!data.summary.logsAnalyzed) {
toast({
@@ -227,15 +213,15 @@ export function ObsidianSettings() {
}
toast({
- title: "intelligence generated",
- description: `analyzed ${data.summary.logsAnalyzed} logs, found ${data.summary.contacts} contacts`,
+ title: "analysis complete",
+ description: `analyzed ${data.summary.logsAnalyzed} logs`,
});
} catch (err) {
- console.warn("error testing intelligence:", err);
+ console.warn("error testing analysis:", err);
toast({
variant: "destructive",
title: "error",
- description: "failed to generate intelligence",
+ description: "failed to generate analysis",
});
} finally {
setIntelligenceLoading(false);
@@ -284,7 +270,7 @@ export function ObsidianSettings() {
const searchQuery = `path:"${relativePath}"`;
const deepLink = `obsidian://search?vault=${encodeURIComponent(
- vaultName,
+ vaultName
)}&query=${encodeURIComponent(searchQuery)}`;
window.open(deepLink, "_blank");
@@ -380,7 +366,7 @@ export function ObsidianSettings() {
});
}
}, 500),
- [],
+ []
);
// Add this new useEffect for initial path validation
@@ -393,61 +379,57 @@ export function ObsidianSettings() {
if (loading) {
return (
<div className="w-full max-w-4xl mx-auto space-y-8">
- <Tabs defaultValue="logs">
- <TabsList className="grid w-full grid-cols-2">
- <TabsTrigger value="logs">logs</TabsTrigger>
- <TabsTrigger value="intelligence">intelligence (beta)</TabsTrigger>
- </TabsList>
-
- <TabsContent value="logs" className="space-y-4 w-full my-2">
- <div className="space-y-2">
- <Skeleton className="h-4 w-24" />
- <div className="flex gap-2">
- <Skeleton className="h-10 flex-1" />
- <Skeleton className="h-10 w-10" />
- <Skeleton className="h-10 w-10" />
- </div>
+ <form onSubmit={handleSave} className="space-y-4 w-full my-2">
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <div className="flex gap-2">
+ <Skeleton className="h-10 flex-1" />
+ <Skeleton className="h-10 w-10" />
+ <Skeleton className="h-10 w-10" />
</div>
+ </div>
- <div className="space-y-2">
- <Skeleton className="h-4 w-32" />
- <Skeleton className="h-10 w-full" />
- </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-10 w-full" />
+ </div>
- <div className="space-y-2">
- <Skeleton className="h-4 w-20" />
- <Skeleton className="h-10 w-full" />
- </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-20" />
+ <Skeleton className="h-10 w-full" />
+ </div>
- <div className="space-y-2">
- <Skeleton className="h-4 w-36" />
- <Skeleton className="h-10 w-full" />
- </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-36" />
+ <Skeleton className="h-10 w-full" />
+ </div>
- <div className="space-y-2">
- <Skeleton className="h-4 w-24" />
- <Skeleton className="h-32 w-full" />
- </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-32 w-full" />
+ </div>
- <Skeleton className="h-10 w-full" />
- </TabsContent>
- </Tabs>
+ <Skeleton className="h-10 w-full" />
+ </form>
</div>
);
}
-
+ const hasMP4File = (content: string) =>
+ content.trim().toLowerCase().includes(".mp4");
return (
<div className="w-full max-w-4xl mx-auto space-y-8">
- <Tabs defaultValue="logs">
- <TabsList className="grid w-full grid-cols-2">
- <TabsTrigger value="logs">logs</TabsTrigger>
- <TabsTrigger value="intelligence">intelligence (beta)</TabsTrigger>
- </TabsList>
-
- <TabsContent value="logs">
- <form onSubmit={handleSave} className="space-y-4 w-full my-2">
+ <form onSubmit={handleSave}>
+ <Card>
+ <CardHeader>
+ <CardTitle>obsidian settings</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-6">
<div className="space-y-2">
- <Label htmlFor="vaultPath">obsidian vault path</Label>
+ <Label htmlFor="vaultPath" className="flex items-center gap-2">
+ <FolderOpen className="h-4 w-4" />
+ obsidian vault path (this is the folder where we will save the
+ logs and insights)
+ </Label>
<div className="flex gap-2">
<div className="flex-1 relative">
<Input
@@ -459,8 +441,8 @@ export function ObsidianSettings() {
pathValidation.isValid
? "border-green-500"
: pathValidation.message
- ? "border-red-500"
- : ""
+ ? "border-red-500"
+ : ""
}`}
onChange={(e) => validatePath(e.target.value)}
/>
@@ -475,7 +457,7 @@ export function ObsidianSettings() {
className="cursor-pointer hover:bg-muted"
onClick={() => {
const input = document.getElementById(
- "vaultPath",
+ "vaultPath"
) as HTMLInputElement;
if (input) {
input.value = path;
@@ -503,12 +485,13 @@ export function ObsidianSettings() {
variant="outline"
onClick={openObsidianVault}
className="px-3"
- title="open in obsidian"
+ title="open in obsidian (only works in browser)"
disabled={!pathValidation.isValid}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
+
{pathValidation.message && (
<p
className={`text-sm ${
@@ -521,81 +504,183 @@ export function ObsidianSettings() {
</div>
<div className="space-y-2">
- <Label htmlFor="interval">sync interval (minutes)</Label>
- <Input
- disabled={!pathValidation.isValid}
- id="interval"
- name="interval"
- type="number"
- min="1"
- step="1"
- max="60"
- defaultValue={
- settings?.interval ? settings?.interval / 60000 : 5
- }
- />
- </div>
+ <Card>
+ <CardHeader>
+ <CardTitle>short-term activity logs</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-6">
+ <div className="space-y-2">
+ <Label
+ htmlFor="logTimeWindow"
+ className="flex items-center gap-2"
+ >
+ <Clock className="h-4 w-4" />
+ logging interval (minutes)
+ </Label>
+ <Input
+ disabled={!pathValidation.isValid}
+ id="logTimeWindow"
+ name="logTimeWindow"
+ type="number"
+ min="1"
+ step="1"
+ max="60"
+ defaultValue={
+ settings?.logTimeWindow
+ ? settings?.logTimeWindow / 60000
+ : 5
+ }
+ />
+ <p className="text-xs text-muted-foreground">
+ how often screenpipe will create a new log entry about
+ your activity
+ </p>
+ </div>
- <div className="space-y-2">
- <Label htmlFor="pageSize">page size</Label>
- <Input
- disabled={!pathValidation.isValid}
- id="pageSize"
- name="pageSize"
- type="number"
- defaultValue={settings?.pageSize || 100}
- />
- </div>
+ <div className="space-y-2">
+ <Label
+ htmlFor="logPageSize"
+ className="flex items-center gap-2"
+ >
+ <LineChart className="h-4 w-4" />
+ screenpipe page size
+ </Label>
+ <Input
+ disabled={!pathValidation.isValid}
+ id="logPageSize"
+ name="logPageSize"
+ type="number"
+ min="1"
+ step="1"
+ defaultValue={settings?.logPageSize || 100}
+ />
+ <p className="text-xs text-muted-foreground">
+ how many screenpipe results to include in the AI prompt
+ for log generation
+ </p>
+ </div>
- <div className="space-y-2">
- <Label htmlFor="aiModel">
- ollama/local openai-compatible model
- </Label>
- <OllamaModelsList
- disabled={!pathValidation.isValid}
- defaultValue={
- settings?.aiModel || "llama3.2:3b-instruct-q4_K_M"
- }
- onChange={(value) => {
- updateSettings({
- ...settings,
- aiModel: value,
- });
- }}
- />
- </div>
+ <div className="space-y-2">
+ <Label
+ htmlFor="logModel"
+ className="flex items-center gap-2"
+ >
+ <Brain className="h-4 w-4" />
+ log generation model
+ </Label>
+ <OllamaModelsList
+ disabled={!pathValidation.isValid}
+ defaultValue={
+ settings?.logModel || "llama3.2:3b-instruct-q4_K_M"
+ }
+ onChange={(value) => {
+ updateSettings({
+ ...settings,
+ logModel: value,
+ });
+ }}
+ />
+ <p className="text-xs text-muted-foreground">
+ local AI model used for generating individual activity
+ logs
+ </p>
+ </div>
+ </CardContent>
+ </Card>
- <div className="space-y-2">
- <Label htmlFor="prompt">custom prompt</Label>
- <FileSuggestTextarea
- value={customPrompt || ""}
- setValue={setCustomPrompt}
- disabled={!pathValidation.isValid}
- />
- <p className="text-xs text-muted-foreground">
- make sure to keep the prompt within llm context window size.
- <br />
- protip: use the @mention feature to link to files in your vault
- as context.
- </p>
- </div>
+ <Card>
+ <CardHeader>
+ <CardTitle>long-term analysis</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-6">
+ <div className="space-y-2">
+ <Label
+ htmlFor="analysisWindow"
+ className="flex items-center gap-2"
+ >
+ <Clock className="h-4 w-4" />
+ analysis window (hours)
+ </Label>
+ <Input
+ disabled={!pathValidation.isValid}
+ id="analysisWindow"
+ name="analysisTimeWindow"
+ type="number"
+ min="1"
+ step="1"
+ defaultValue={
+ settings?.analysisTimeWindow
+ ? settings.analysisTimeWindow / (60 * 60 * 1000)
+ : 1
+ }
+ />
+ <p className="text-xs text-muted-foreground">
+ timeframe of logs to analyze for generating insights
+ </p>
+ </div>
- <Button
- className="w-full"
- type="submit"
- disabled={!pathValidation.isValid}
- >
- <FileCheck className="mr-2 h-4 w-4" />
- save settings
- </Button>
- </form>
+ <div className="space-y-2">
+ <Label
+ htmlFor="analysisModel"
+ className="flex items-center gap-2"
+ >
+ <Brain className="h-4 w-4" />
+ analysis model
+ </Label>
+ <OllamaModelsList
+ disabled={!pathValidation.isValid}
+ defaultValue={
+ settings?.analysisModel ||
+ "deepseek-r1:7b-qwen-distill-q4_K_M"
+ }
+ onChange={(value) => {
+ updateSettings({
+ ...settings,
+ analysisModel: value,
+ });
+ }}
+ />
+ <p className="text-xs text-muted-foreground">
+ local AI model used for generating high-level insights
+ (typically larger model)
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>prompt customization</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ <Label htmlFor="prompt" className="flex items-center gap-2">
+ <FileCheck className="h-4 w-4" />
+ custom prompt
+ </Label>
+ <FileSuggestTextarea
+ value={customPrompt || ""}
+ setValue={setCustomPrompt}
+ disabled={!pathValidation.isValid}
+ />
+ <p className="text-xs text-muted-foreground">
+ customize how activity logs and insights are generated
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ </CardContent>
+ </Card>
- <div className="space-y-4 w-full flex flex-col">
+ <div className="space-y-4 w-full flex flex-col">
+ <div className="flex gap-2 mt-4">
<Button
+ type="button"
onClick={testLog}
variant="outline"
disabled={testLogLoading || !pathValidation.isValid}
- className="w-full"
+ className="flex-1"
>
{testLogLoading ? (
<>
@@ -603,166 +688,176 @@ export function ObsidianSettings() {
testing...
</>
) : (
- "test log generation"
+ <>
+ <FileCheck className="mr-2 h-4 w-4" />
+ test log generation
+ </>
)}
</Button>
- {lastLog && (
- <div className="p-4 border rounded-lg space-y-2 font-mono text-sm">
- <h4>last generated log:</h4>
- <pre className="bg-muted p-2 rounded overflow-auto">
- {JSON.stringify(lastLog, null, 2)}
- </pre>
- </div>
- )}
-
- {lastLog && logDeepLink && (
- <Button
- variant="outline"
- size="sm"
- onClick={() => window.open(logDeepLink, "_blank")}
- className="ml-2 my-2"
- >
- <ExternalLink className="h-4 w-4 mr-2" />
- open in obsidian
- </Button>
- )}
- </div>
- </TabsContent>
-
- <TabsContent value="intelligence" className="space-y-4">
- <div className="flex justify-between items-center">
- <h3 className="text-lg font-medium">relationship intelligence</h3>
<Button
+ type="button"
onClick={testIntelligence}
variant="outline"
disabled={intelligenceLoading || !pathValidation.isValid}
+ className="flex-1"
>
<Brain className="mr-2 h-4 w-4" />
- {intelligenceLoading ? "analyzing..." : "analyze relationships"}
+ {intelligenceLoading ? "analyzing..." : "test analyze activity"}
</Button>
- </div>
- {intelligence && (
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- {/* contacts summary */}
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Users className="h-4 w-4" />
- contacts
- </CardTitle>
- </CardHeader>
- <CardContent>
- <div className="space-y-4">
- {intelligence?.contacts?.length > 0 ? (
- intelligence.contacts.map((contact: any) => (
- <div key={contact.name} className="space-y-2">
- <div className="flex justify-between items-center">
- <span className="font-medium">{contact.name}</span>
- <Badge
- variant={
- contact.sentiment > 0 ? "default" : "secondary"
- }
- >
- {contact.company || "unknown"}
- </Badge>
- </div>
- <div className="text-sm text-muted-foreground">
- last: {contact.lastInteraction}
- </div>
- <div className="flex gap-1 flex-wrap">
- {contact.topics.map((topic: string) => (
- <Badge key={topic} variant="outline">
- {topic}
- </Badge>
- ))}
- </div>
- {contact.nextSteps.length > 0 && (
- <div className="text-sm text-muted-foreground">
- next steps: {contact.nextSteps.join(", ")}
- </div>
- )}
- </div>
- ))
- ) : (
- <div className="text-muted-foreground">
- no contacts found
- </div>
- )}
- </div>
- </CardContent>
- </Card>
+ <Button
+ type="submit"
+ disabled={!pathValidation.isValid}
+ className="flex-1"
+ >
+ <FileCheck className="mr-2 h-4 w-4" />
+ save settings
+ </Button>
+ </div>
- {/* insights */}
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <LineChart className="h-4 w-4" />
- insights
- </CardTitle>
- </CardHeader>
- <CardContent>
- <div className="space-y-4">
- <div>
- <h4 className="font-medium mb-2">follow-ups needed</h4>
- {intelligence.insights.followUps.map((item: string) => (
- <div
- key={item}
- className="text-sm text-muted-foreground"
+ {lastLog && (
+ <div className="p-4 border rounded-lg space-y-2">
+ <h4 className="font-mono text-sm">last log:</h4>
+ <div className="bg-muted p-2 rounded overflow-auto">
+ <MemoizedReactMarkdown
+ className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0"
+ remarkPlugins={[remarkGfm, remarkMath]}
+ components={{
+ p({ children }) {
+ return <p className="mb-2 last:mb-0">{children}</p>;
+ },
+ a({ node, href, children, ...props }) {
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ {...props}
>
- • {item}
- </div>
- ))}
- </div>
- <div>
- <h4 className="font-medium mb-2">opportunities</h4>
- {intelligence.insights.opportunities.map(
- (item: string) => (
- <div
- key={item}
- className="text-sm text-muted-foreground"
+ {children}
+ </a>
+ );
+ },
+ code({ node, className, children, ...props }) {
+ const content = String(children).replace(/\n$/, "");
+ const match = /language-(\w+)/.exec(className || "");
+
+ if (!match) {
+ return (
+ <code
+ className="px-1 py-0.5 rounded-sm font-mono text-sm"
+ {...props}
>
- • {item}
- </div>
- ),
- )}
- </div>
- </div>
- </CardContent>
- </Card>
+ {content}
+ </code>
+ );
+ }
+
+ return (
+ <CodeBlock
+ key={Math.random()}
+ language={(match && match[1]) || ""}
+ value={content}
+ {...props}
+ />
+ );
+ },
+ }}
+ >
+ {`\`\`\`json\n${JSON.stringify(lastLog, null, 2)}\n\`\`\``}
+ </MemoizedReactMarkdown>
+ </div>
</div>
)}
- {/* debug view */}
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Clock className="h-4 w-4" />
- raw data
- </CardTitle>
- </CardHeader>
- <CardContent>
- <pre className="text-xs overflow-auto max-h-96">
- {JSON.stringify(intelligence, null, 2)}
- </pre>
- </CardContent>
- </Card>
-
- {intelligence && intelligenceDeepLink && (
- <Button
- variant="outline"
- size="sm"
- onClick={() => window.open(intelligenceDeepLink, "_blank")}
- className="ml-2"
- >
- <ExternalLink className="h-4 w-4 mr-2" />
- open in obsidian
- </Button>
+ {intelligence && (
+ <div className="p-4 border rounded-lg space-y-2">
+ <h4 className="font-mono text-sm">analysis:</h4>
+ <div className="bg-muted p-2 rounded overflow-auto">
+ <MemoizedReactMarkdown
+ className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0"
+ remarkPlugins={[remarkGfm, remarkMath]}
+ components={{
+ video({ node, className, children, ...props }) {
+ const content = String(children).replace(/\n$/, "");
+ const match = /language-(\w+)/.exec(className || "");
+
+ const isMP4File = hasMP4File(content);
+
+ if (isMP4File || !match) {
+ return <VideoComponent filePath={content.trim()} />;
+ }
+
+ return (
+ <CodeBlock
+ key={Math.random()}
+ language={(match && match[1]) || ""}
+ value={content}
+ {...props}
+ />
+ );
+ },
+ p({ children }) {
+ return <p className="mb-2 last:mb-0">{children}</p>;
+ },
+ a({ node, href, children, ...props }) {
+ const isMP4Link = href?.toLowerCase().includes(".mp4");
+
+ if (isMP4Link && href) {
+ return <VideoComponent filePath={href} />;
+ }
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ {...props}
+ >
+ {children}
+ </a>
+ );
+ },
+ code({ node, className, children, ...props }) {
+ const content = String(children).replace(/\n$/, "");
+ const match = /language-(\w+)/.exec(className || "");
+
+ const isMP4File = hasMP4File(content);
+
+ if (isMP4File || !match) {
+ if (isMP4File) {
+ return <VideoComponent filePath={content.trim()} />;
+ }
+ return (
+ <code
+ className="px-1 py-0.5 rounded-sm font-mono text-sm"
+ {...props}
+ >
+ {content}
+ </code>
+ );
+ }
+
+ return (
+ <CodeBlock
+ key={Math.random()}
+ language={(match && match[1]) || ""}
+ value={content}
+ {...props}
+ />
+ );
+ },
+ }}
+ >
+ {`${intelligence}`}
+ </MemoizedReactMarkdown>
+ </div>
+ </div>
)}
- <div className="my-4 h-16" />
- </TabsContent>
- </Tabs>
+
+ <div className="h-10" />
+ </div>
+ </form>
</div>
);
}
diff --git a/pipes/obsidian/src/components/ui/textarea.tsx b/pipes/obsidian/src/components/ui/textarea.tsx
new file mode 100644
index 000000000..4d858bb6b
--- /dev/null
+++ b/pipes/obsidian/src/components/ui/textarea.tsx
@@ -0,0 +1,22 @@
+import * as React from "react"
+
+import { cn } from "@/lib/utils"
+
+const Textarea = React.forwardRef<
+ HTMLTextAreaElement,
+ React.ComponentProps<"textarea">
+>(({ className, ...props }, ref) => {
+ return (
+ <textarea
+ className={cn(
+ "flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
+ className
+ )}
+ ref={ref}
+ {...props}
+ />
+ )
+})
+Textarea.displayName = "Textarea"
+
+export { Textarea }
diff --git a/pipes/obsidian/src/components/video.tsx b/pipes/obsidian/src/components/video.tsx
new file mode 100644
index 000000000..20d40879f
--- /dev/null
+++ b/pipes/obsidian/src/components/video.tsx
@@ -0,0 +1,457 @@
+import { memo, useCallback, useEffect, useState, useRef, useMemo } from "react";
+import { getMediaFile } from "@/lib/actions/video-actions";
+import { cn } from "@/lib/utils";
+import { Speaker } from "@screenpipe/browser";
+import { motion } from "framer-motion";
+import { Slider } from "@/components/ui/slider";
+import { Button } from "@/components/ui/button";
+import { Pause, Play, Pencil, Save, X } from "lucide-react";
+import { Input } from "@/components/ui/input";
+
+export const VideoComponent = memo(function VideoComponent({
+ filePath,
+ customDescription,
+ className,
+ startTime,
+ endTime,
+ speaker,
+}: {
+ filePath: string;
+ customDescription?: string;
+ className?: string;
+ startTime?: number;
+ endTime?: number;
+ speaker?: Speaker;
+}) {
+ 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 = navigator.userAgent.includes("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 truncate px-2"
+ title={filePath}
+ >
+ {customDescription || filePath}
+ </div>
+ );
+
+ const validateMedia = async (path: string): Promise<string> => {
+ try {
+ const response = await fetch(
+ `http://localhost:3030/experimental/validate/media?file_path=${encodeURIComponent(
+ path
+ )}`
+ );
+ const result = await response.json();
+ return result.status;
+ } catch (error) {
+ console.error("Failed to validate media:", error);
+ return "Failed to validate media";
+ }
+ };
+
+ useEffect(() => {
+ async function loadMedia() {
+ try {
+ const sanitizedPath = sanitizeFilePath(filePath);
+ console.log("Sanitized path:", sanitizedPath);
+
+ if (!sanitizedPath) {
+ throw new Error("Invalid file path");
+ }
+
+ const validationStatus = await validateMedia(sanitizedPath);
+ console.log("Media file:", validationStatus);
+
+ if (validationStatus === "valid media file") {
+ setIsAudio(
+ sanitizedPath.toLowerCase().includes("input") ||
+ sanitizedPath.toLowerCase().includes("output")
+ );
+ const { data, mimeType } = await getMediaFile(sanitizedPath);
+ const binaryData = atob(data);
+ const bytes = new Uint8Array(binaryData.length);
+ for (let i = 0; i < binaryData.length; i++) {
+ bytes[i] = binaryData.charCodeAt(i);
+ }
+ const blob = new Blob([bytes], { type: mimeType });
+ setMediaSrc(URL.createObjectURL(blob));
+ } else if (validationStatus.startsWith("media file does not exist")) {
+ throw new Error(
+ `${
+ isAudio ? "audio" : "video"
+ } file not exists, it might get deleted`
+ );
+ } else if (validationStatus.startsWith("invalid media file")) {
+ throw new Error(
+ `the ${
+ isAudio ? "audio" : "video"
+ } file is not written completely, please try again later`
+ );
+ } else {
+ throw new Error("unknown media validation status");
+ }
+ } catch (error) {
+ console.warn("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}
+ speaker={speaker}
+ />
+ ) : (
+ <video controls className="w-full rounded-md">
+ <source src={mediaSrc} type='video/mp4; codecs="hvc1"' />
+ <source src={mediaSrc} type='video/mp4; codecs="hvec"' />
+ <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,
+ speaker,
+}: {
+ startTime?: number;
+ endTime?: number;
+ mediaSrc: string;
+ speaker?: Speaker;
+}) {
+ const [duration, setDuration] = useState<number>(0);
+ const [currentTime, setCurrentTime] = useState<number>(0);
+ const [isPlaying, setIsPlaying] = useState(false);
+ const [isEditing, setIsEditing] = useState(false);
+ const [speakerName, setSpeakerName] = useState(speaker?.name || "");
+ const [speakers, setSpeakers] = useState<Speaker[]>([]);
+ const [isSearching, setIsSearching] = useState(false);
+ const [showSpeakerNames, setShowSpeakerNames] = useState(false);
+ const audioRef = useRef<HTMLAudioElement>(null);
+
+ const handleUpdateSpeakerName = async () => {
+ try {
+ await fetch(`http://localhost:3030/speakers/update`, {
+ method: "POST",
+ body: JSON.stringify({
+ id: speaker?.id,
+ name: speakerName,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ setIsEditing(false);
+ } catch (error) {
+ console.error("error updating speaker name:", error);
+ }
+ };
+
+ const fetchSpeakers = async (searchTerm: string) => {
+ setIsSearching(true);
+ try {
+ const response = await fetch(
+ `http://localhost:3030/speakers/search?name=${searchTerm}`
+ );
+ const result = await response.json();
+ setSpeakers(result);
+ } catch (error) {
+ console.error("error fetching speakers:", error);
+ } finally {
+ setIsSearching(false);
+ }
+ };
+
+ 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 (value: number) => {
+ if (!audioRef.current) return;
+
+ const wasPlaying = isPlaying;
+ if (wasPlaying) {
+ audioRef.current.pause();
+ }
+
+ audioRef.current.currentTime = value;
+ setCurrentTime(value);
+
+ if (wasPlaying) {
+ try {
+ await audioRef.current.play();
+ } catch (error) {
+ console.error("Playback failed:", error);
+ setIsPlaying(false);
+ }
+ }
+ };
+
+ const formatTime = (seconds: number): string => {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
+ };
+
+ return (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ className="rounded-lg border bg-card p-4 space-y-4"
+ >
+ {speaker && (
+ <div className="mb-3 flex items-center gap-2">
+ <div className="w-8 h-8 rounded-full bg-black flex items-center justify-center text-white">
+ {speakerName?.[0]?.toUpperCase() || "S"}
+ </div>
+ <div className="text-sm flex-1">
+ {isEditing ? (
+ <div className="flex items-center gap-2">
+ <div className="relative flex-1">
+ <Input
+ value={speakerName}
+ onChange={(e) => {
+ setSpeakerName(e.target.value);
+ fetchSpeakers(e.target.value);
+ }}
+ onFocus={() => setShowSpeakerNames(true)}
+ onBlur={() =>
+ setTimeout(() => setShowSpeakerNames(false), 200)
+ }
+ className="h-8"
+ placeholder="Enter speaker name"
+ />
+ {showSpeakerNames && speakerName && (
+ <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>
+ ) : (
+ <ul className="py-1">
+ {speakers.map((s) => (
+ <li
+ key={s.id}
+ className="px-3 py-2 hover:bg-gray-100 cursor-pointer truncate"
+ onClick={() => {
+ setSpeakerName(s.name || "");
+ setShowSpeakerNames(false);
+ }}
+ >
+ {s.name}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </div>
+ <Button
+ size="sm"
+ onClick={handleUpdateSpeakerName}
+ disabled={!speakerName}
+ >
+ <Save className="h-4 w-4" />
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => {
+ setIsEditing(false);
+ setSpeakerName(speaker.name || "");
+ }}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ ) : (
+ <div className="flex items-center gap-2">
+ <div className="font-medium">
+ {speakerName || "Speaker " + speaker.id}
+ </div>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-6 w-6 p-0"
+ onClick={() => setIsEditing(true)}
+ >
+ <Pencil className="h-3 w-3" />
+ </Button>
+ </div>
+ )}
+ {speaker.metadata && !isEditing && (
+ <div className="text-xs text-gray-600">{speaker.metadata}</div>
+ )}
+ </div>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <div className="flex items-center gap-4">
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={togglePlay}
+ className="h-8 w-8 rounded-full"
+ >
+ {isPlaying ? (
+ <Pause className="h-4 w-4" />
+ ) : (
+ <Play className="h-4 w-4" />
+ )}
+ </Button>
+
+ <div className="relative flex-1">
+ {startTime !== undefined && endTime !== undefined && (
+ <div
+ className="absolute top-[60%] bg-primary/20 rounded-full"
+ style={{
+ left: `${(startTime / duration) * 100}%`,
+ width: `${((endTime - startTime) / duration) * 100}%`,
+ }}
+ />
+ )}
+
+ <Slider
+ value={[currentTime]}
+ max={duration}
+ step={0.1}
+ onValueChange={([value]) => handleTimeChange(value)}
+ className="cursor-pointer"
+ />
+
+ {startTime !== undefined && (
+ <div
+ className="absolute top-4 w-2 h-2 bg-primary rounded-full -translate-x-1/2"
+ title="start time where we found this audio transcript in the recorded file"
+ style={{
+ left: `${(startTime / duration) * 100}%`,
+ }}
+ >
+ <div className="absolute -bottom-5 left-1/2 -translate-x-1/2 text-[10px] text-muted-foreground">
+ {formatTime(startTime)}
+ </div>
+ </div>
+ )}
+
+ {endTime !== undefined && (
+ <div
+ className="absolute top-4 w-2 h-2 bg-primary rounded-full -translate-x-1/2"
+ title="end time where we found this audio transcript in the recorded file"
+ style={{
+ left: `${(endTime / duration) * 100}%`,
+ }}
+ >
+ <div className="absolute -bottom-5 left-1/2 -translate-x-1/2 text-[10px] text-muted-foreground">
+ {formatTime(endTime)}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div className="flex justify-between text-xs text-muted-foreground">
+ <span>{formatTime(currentTime)}</span>
+ <span>{formatTime(duration)}</span>
+ </div>
+ </div>
+ {audioElement}
+ </motion.div>
+ );
+});
diff --git a/pipes/obsidian/src/lib/actions/obsidian.ts b/pipes/obsidian/src/lib/actions/obsidian.ts
new file mode 100644
index 000000000..db2e63f08
--- /dev/null
+++ b/pipes/obsidian/src/lib/actions/obsidian.ts
@@ -0,0 +1,62 @@
+"use server";
+import * as fs from "fs/promises";
+import * as path from "path";
+
+export async function readObsidianFile(filePath: string): Promise<string> {
+ try {
+ const content = await fs.readFile(filePath, "utf8");
+ return content;
+ } catch (err) {
+ console.error(`failed to read file ${filePath}:`, err);
+ return "";
+ }
+}
+
+export async function findVaultRoot(startPath: string): Promise<string> {
+ let currentPath = startPath;
+
+ while (currentPath !== "/" && currentPath !== ".") {
+ try {
+ await fs.access(path.join(currentPath, ".obsidian"));
+ return currentPath;
+ } catch {
+ currentPath = path.dirname(currentPath);
+ }
+ }
+ throw new Error("could not find obsidian vault root (.obsidian folder)");
+}
+
+export async function extractLinkedContent(
+ prompt: string,
+ basePath: string
+): Promise<string> {
+ try {
+ const vaultRoot = await findVaultRoot(basePath);
+ const linkRegex = /@\[\[(.*?)\]\]/g;
+ const matches = [...prompt.matchAll(linkRegex)];
+ let enrichedPrompt = prompt;
+
+ for (const match of matches) {
+ const relativePath = match[1];
+ const fullPath = path.join(
+ vaultRoot,
+ relativePath.endsWith(".md") ? relativePath : `${relativePath}.md`
+ );
+
+ try {
+ const content = await readObsidianFile(fullPath);
+ enrichedPrompt = enrichedPrompt.replace(
+ match[0],
+ `\n--- Content of ${relativePath} ---\n${content}\n---\n`
+ );
+ } catch (err) {
+ console.error(`failed to process link ${relativePath}:`, err);
+ }
+ }
+
+ return enrichedPrompt;
+ } catch (err) {
+ console.error("failed to find vault root:", err);
+ return prompt;
+ }
+}
diff --git a/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx b/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx
index fe7ace9c9..2ad93f580 100644
--- a/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx
+++ b/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx
@@ -33,8 +33,6 @@ this data will be used later for analysis, it must contains valuable insights on
if you do your job well, i'll give you a 🍺 and $1m`,
};
-const STORAGE_KEY = "obsidian-settings";
-
export function usePipeSettings() {
const [settings, setSettings] = useState<Partial<Settings> | null>(null);
const [loading, setLoading] = useState(true);
@@ -50,16 +48,7 @@ export function usePipeSettings() {
console.log(screenpipeSettings);
- // Load notion settings from localStorage
- //const storedSettings = localStorage.getItem(STORAGE_KEY);
- //const notionSettings = storedSettings
- // ? JSON.parse(storedSettings)
- // : {
- // ...(screenpipeSettings.customSettings?.obsidian && {
- // ...screenpipeSettings.customSettings?.obsidian,
- // }),
- // };
- const notionSettings = {
+ const obsidianSettings = {
...(screenpipeSettings.customSettings?.obsidian && {
...screenpipeSettings.customSettings?.obsidian,
}),
@@ -68,7 +57,7 @@ export function usePipeSettings() {
// Merge everything together
setSettings({
...DEFAULT_SETTINGS,
- ...notionSettings,
+ ...obsidianSettings,
screenpipeAppSettings: screenpipeSettings,
});
} catch (error) {
@@ -97,9 +86,6 @@ export function usePipeSettings() {
},
});
- // Update notion settings in localStorage
- // localStorage.setItem(STORAGE_KEY, JSON.stringify(mergedObsidianSettings));
-
// Update state with everything
setSettings({
...mergedObsidianSettings,
diff --git a/pipes/obsidian/src/lib/types.ts b/pipes/obsidian/src/lib/types.ts
index e072860b1..ef675082a 100644
--- a/pipes/obsidian/src/lib/types.ts
+++ b/pipes/obsidian/src/lib/types.ts
@@ -26,10 +26,12 @@ export interface Intelligence {
}
export interface Settings {
- interval: number;
- pageSize: number;
- aiModel: string;
- vaultPath: string;
prompt: string;
+ vaultPath: string;
+ logTimeWindow: number;
+ logPageSize: number;
+ logModel: string;
+ analysisModel: string;
+ analysisTimeWindow: number;
screenpipeAppSettings: ScreenpipeAppSettings;
}
diff --git a/screenpipe-app-tauri/components/recording-settings.tsx b/screenpipe-app-tauri/components/recording-settings.tsx
index 46ffabd4a..96667d550 100644
--- a/screenpipe-app-tauri/components/recording-settings.tsx
+++ b/screenpipe-app-tauri/components/recording-settings.tsx
@@ -786,7 +786,7 @@ export function RecordingSettings() {
variant="default"
modalPopover={true}
animation={2}
- disabled={settings.useAllMonitors}
+ // disabled={settings.useAllMonitors}
/>
</div>