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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Linkedin5 (#1125)
Matthew Diakonovc0edb9930a19
diff --git a/pipes/linkedin_ai_assistant/.eslintrc.json b/pipes/linkedin-ai-assistant/.eslintrc.jsonsimilarity index 100%rename from pipes/linkedin_ai_assistant/.eslintrc.jsonrename to pipes/linkedin-ai-assistant/.eslintrc.jsondiff --git a/pipes/linkedin_ai_assistant/.gitignore b/pipes/linkedin-ai-assistant/.gitignoresimilarity index 96%rename from pipes/linkedin_ai_assistant/.gitignorerename to pipes/linkedin-ai-assistant/.gitignoreindex 7d0e6f5a8..b0cf6a1c5 100644--- a/pipes/linkedin_ai_assistant/.gitignore+++ b/pipes/linkedin-ai-assistant/.gitignore@@ -62,3 +62,4 @@ History*# storage fileslib/storage/*.json+!lib/storage/templates.jsondiff --git a/pipes/linkedin-ai-assistant/README.md b/pipes/linkedin-ai-assistant/README.mdnew file mode 100644index 000000000..02dfbdb62--- /dev/null+++ b/pipes/linkedin-ai-assistant/README.md@@ -0,0 +1,15 @@+Automate your LinkedIn outreach with an AI-powered desktop agent that runs locally on your computer. No password required, works in the background without interfering with your keyboard. Smart targeting finds relevant prospects based on industry and role, while AI generates personalized messages using profile context. Built with safety in mind - uses human-like behavior and rate limiting to protect your account.++<img width="1312" alt="LinkedIn Automation Demo" src="./public/li_harvester.gif">+++## Features++- 🛡️ Exceptional safety: Runs as a desktop app with human-like behavior+- 👥 Smart targeting: Finds prospects based on industry & mutual connections+- 🤖 AI messaging: Generates personalized outreach using profile context+- 💬 Drip campaigns: Automated sequences with reply detection+- ⚡ Multi-source targeting: Connect via search, groups, and profile visitors+- 📊 Data extraction: Safely logs profile data and messaging history++diff --git a/pipes/linkedin_ai_assistant/app/api/chrome/check-login/route.ts b/pipes/linkedin-ai-assistant/app/api/chrome/check-login/route.tssimilarity index 87%rename from pipes/linkedin_ai_assistant/app/api/chrome/check-login/route.tsrename to pipes/linkedin-ai-assistant/app/api/chrome/check-login/route.tsindex c7c8c2789..cdb055119 100644--- a/pipes/linkedin_ai_assistant/app/api/chrome/check-login/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/chrome/check-login/route.ts@@ -1,12 +1,12 @@import { NextResponse } from 'next/server';-import { setupBrowser, getActiveBrowser } from '@/lib/browser_setup';+import { setupBrowser, getActiveBrowser } from '@/lib/browser-setup';export async function POST(request: Request) {try {- const { wsUrl } = await request.json();+ await request.json(); // keep reading the request to avoid hangingconsole.log('checking linkedin login status');- await setupBrowser(wsUrl);+ await setupBrowser();const { page } = getActiveBrowser();if (!page) {diff --git a/pipes/linkedin_ai_assistant/app/api/chrome/navigate/route.ts b/pipes/linkedin-ai-assistant/app/api/chrome/navigate/route.tssimilarity index 88%rename from pipes/linkedin_ai_assistant/app/api/chrome/navigate/route.tsrename to pipes/linkedin-ai-assistant/app/api/chrome/navigate/route.tsindex f56b4a381..eb505ebcf 100644--- a/pipes/linkedin_ai_assistant/app/api/chrome/navigate/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/chrome/navigate/route.ts@@ -1,5 +1,5 @@import { NextResponse } from 'next/server';-import { getActiveBrowser, setupBrowser } from '@/lib/browser_setup';+import { getActiveBrowser, setupBrowser } from '@/lib/browser-setup';import type { Page } from 'puppeteer-core';async function navigateToPage(page: Page, url: string) {@@ -31,11 +31,11 @@ async function navigateToPage(page: Page, url: string) {export async function POST(request: Request) {try {- const { url, wsUrl } = await request.json();+ const { url } = await request.json();console.log('attempting to navigate to:', url);- // Setup the browser connection using the provided WebSocket URL- await setupBrowser(wsUrl);+ // Setup the browser connection+ await setupBrowser();const { page } = getActiveBrowser();if (!page) {diff --git a/pipes/linkedin-ai-assistant/app/api/chrome/route.ts b/pipes/linkedin-ai-assistant/app/api/chrome/route.tsnew file mode 100644index 000000000..bef71a264--- /dev/null+++ b/pipes/linkedin-ai-assistant/app/api/chrome/route.ts@@ -0,0 +1,106 @@+import { NextResponse } from 'next/server';+import { exec, spawn } from 'child_process';+import { promisify } from 'util';+import { quitBrowser } from '@/lib/browser-setup';+import os from 'os';++export const runtime = 'nodejs'; // specify node runtime++const execPromise = promisify(exec);++// helper to get chrome path based on platform+function getChromePath() {+ switch (os.platform()) {+ case 'darwin':+ return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';+ case 'linux':+ return '/usr/bin/google-chrome';+ case 'win32':+ return 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';+ default:+ throw new Error('unsupported platform');+ }+}++export async function POST() {+ try {+ console.log('attempting to launch chrome in', process.env.NODE_ENV);++ await quitChrome();+ await quitBrowser();++ const chromePath = getChromePath();+ console.log('using chrome path:', chromePath);++ const chromeProcess = spawn(chromePath, [+ '--remote-debugging-port=9222',+ '--restore-last-session',+ '--no-first-run',+ '--no-default-browser-check',+ '--no-sandbox',+ '--disable-setuid-sandbox',+ // Add these flags to help with stability+ '--disable-dev-shm-usage',+ '--disable-gpu'+ ], {+ detached: true,+ stdio: 'ignore'+ });++ chromeProcess.unref();++ // increase timeout and add retries+ let attempts = 0;+ const maxAttempts = 5;++ while (attempts < maxAttempts) {+ try {+ await new Promise(resolve => setTimeout(resolve, 2000));+ const response = await fetch('http://127.0.0.1:9222/json/version');+ if (response.ok) {+ console.log('chrome debug port responding');+ return NextResponse.json({ success: true });+ }+ } catch (err) {+ console.log(`attempt ${attempts + 1} failed:`, err);+ attempts++;+ if (attempts === maxAttempts) {+ throw new Error('failed to connect to chrome debug port after multiple attempts');+ }+ }+ }+ } catch (err) {+ console.error('failed to launch chrome:', err);+ return NextResponse.json({+ success: false,+ error: String(err),+ details: err instanceof Error ? err.stack : undefined+ }, { status: 500 });+ }+}++export async function DELETE() {+ try {+ await quitChrome();+ await quitBrowser();+ console.log('chrome process terminated');+ return NextResponse.json({ success: true });+ } catch (error) {+ console.error('failed to kill chrome:', error);+ return NextResponse.json({ success: false, error: String(error) }, { status: 500 });+ }+}++async function quitChrome() {+ const platform = os.platform();+ const killCommand = platform === 'win32'+ ? `taskkill /F /IM chrome.exe`+ : `pkill -f -- "Google Chrome"`;++ try {+ await execPromise(killCommand);+ console.log('chrome killed');+ } catch (error) {+ console.log('no chrome process found to kill', error);+ }+}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/app/api/chrome/status/route.ts b/pipes/linkedin-ai-assistant/app/api/chrome/status/route.tssimilarity index 65%rename from pipes/linkedin_ai_assistant/app/api/chrome/status/route.tsrename to pipes/linkedin-ai-assistant/app/api/chrome/status/route.tsindex b428c327c..52b2dc981 100644--- a/pipes/linkedin_ai_assistant/app/api/chrome/status/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/chrome/status/route.ts@@ -1,19 +1,21 @@import { NextResponse } from 'next/server';-import fetch from 'node-fetch';++export const runtime = 'nodejs';export async function GET() {try {const response = await fetch('http://127.0.0.1:9222/json/version');if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);+ return NextResponse.json({ status: 'not_connected' }, { status: 200 });}const data = await response.json() as { webSocketDebuggerUrl: string };+ const wsUrl = data.webSocketDebuggerUrl.replace('ws://localhost:', 'ws://127.0.0.1:');+return NextResponse.json({- wsUrl: data.webSocketDebuggerUrl,+ wsUrl,status: 'connected'});-} catch {return NextResponse.json({ status: 'not_connected' }, { status: 200 });}diff --git a/pipes/linkedin_ai_assistant/app/api/harvest/start/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/start/route.tssimilarity index 55%rename from pipes/linkedin_ai_assistant/app/api/harvest/start/route.tsrename to pipes/linkedin-ai-assistant/app/api/harvest/start/route.tsindex c3cf2ab54..08ab50cd7 100644--- a/pipes/linkedin_ai_assistant/app/api/harvest/start/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/harvest/start/route.ts@@ -1,19 +1,37 @@-import { NextRequest, NextResponse } from 'next/server';-import { startHarvesting } from '@/lib/logic_sequence/harvest_connections';+import { NextResponse } from 'next/server';+import { startHarvesting, isHarvesting } from '@/lib/logic-sequence/harvest-connections';+import { saveHarvestingState } from '@/lib/storage/storage';-export async function POST(req: NextRequest) {+export async function POST() {try {+ // Check if already harvesting+ if (await isHarvesting()) {+ return NextResponse.json(+ {+ message: 'harvesting already in progress',+ isHarvesting: true,+ weeklyLimitReached: false,+ dailyLimitReached: false,+ connectionsSent: 0+ },+ { status: 409 } // Conflict status code+ );+ }+const result = await startHarvesting(35);- // If nextHarvestTime exists but no connections were sent, it means we're in cooldown+ // If in cooldown, return 429 but include all status infoif (result.nextHarvestTime && result.connectionsSent === 0) {return NextResponse.json({message: `harvesting cooldown active until ${new Date(result.nextHarvestTime).toLocaleString()}`,nextHarvestTime: result.nextHarvestTime,- connectionsSent: 0+ connectionsSent: 0,+ weeklyLimitReached: result.weeklyLimitReached || false,+ dailyLimitReached: result.dailyLimitReached || false,+ isHarvesting: false},- { status: 429 } // Too Many Requests+ { status: 429 });}@@ -39,10 +57,17 @@ export async function POST(req: NextRequest) {},{ status: 200 });- } catch (error: any) {+ } catch (error: unknown) {console.error('error starting harvesting:', error);+ await saveHarvestingState(false);return NextResponse.json(- { message: error.message.toLowerCase() },+ {+ message: (error as Error).message.toLowerCase(),+ weeklyLimitReached: false,+ dailyLimitReached: false,+ connectionsSent: 0,+ isHarvesting: false+ },{ status: 500 });}diff --git a/pipes/linkedin-ai-assistant/app/api/harvest/status/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/status/route.tsnew file mode 100644index 000000000..c8284d37d--- /dev/null+++ b/pipes/linkedin-ai-assistant/app/api/harvest/status/route.ts@@ -0,0 +1,273 @@+import { NextResponse } from 'next/server';+import { loadConnections, saveConnection, saveNextHarvestTime, saveHarvestingState, saveRefreshStats } from '@/lib/storage/storage';+import { getActiveBrowser } from '@/lib/browser-setup';+import { clickCancelConnectionRequest } from '@/lib/simple-actions/click-cancel-connection-request';+import { startHarvesting } from '@/lib/logic-sequence/harvest-connections';+import { Page } from 'puppeteer-core';++export const dynamic = 'force-dynamic'+export const fetchCache = 'force-no-store'++// Add types for page and connection+type Connection = {+ status: string;+ timestamp?: string;+};++async function checkConnectionStatus(page: Page, profileUrl: string, connection: Connection) {+ try {+ const maxRetries = 3;+ const baseDelay = 60000; // base delay of 1 minute++ for (let attempt = 0; attempt < maxRetries; attempt++) {+ try {+ // Add delay only after first attempt+ if (attempt > 0 || (refreshProgress && refreshProgress.current > 1)) {+ const nextDelay = Math.floor(Math.random() * 1000) + 20000;+ await new Promise(resolve => setTimeout(resolve, nextDelay));+ }++ // check if page is still valid+ try {+ await page.evaluate(() => document.title);+ } catch {+ // page is detached, get a new one+ const browser = getActiveBrowser();+ if (!browser.page) throw new Error('failed to get new page');+ page = browser.page;+ }++ // Navigate once at the start+ await page.goto(profileUrl, { waitUntil: 'domcontentloaded' });++ // check for rate limit error (429)+ const is429 = await page.evaluate(() => {+ return document.body.textContent?.includes('HTTP ERROR 429') || false;+ });++ if (is429) {+ const retryDelay = baseDelay + Math.floor(Math.random() * baseDelay);+ console.log(`rate limited on ${profileUrl}, waiting ${retryDelay/1000}s before retry ${attempt + 1}/${maxRetries}`);+ await new Promise(resolve => setTimeout(resolve, retryDelay));+ continue;+ }++ // First check if we need to cancel old pending request+ if (connection.status === 'pending' && connection.timestamp) {+ const daysAsPending = (new Date().getTime() - new Date(connection.timestamp).getTime()) / (1000 * 60 * 60 * 24);++ if (daysAsPending > 14) {+ console.log(`connection request to ${profileUrl} has been pending for ${Math.floor(daysAsPending)} days, canceling...`);+ const result = await clickCancelConnectionRequest(page);+ if (result.success) {+ return 'declined';+ }+ }+ }++ // Then check current connection status+ await page.waitForSelector('body', { timeout: 30000 });+ const isAccepted = await page.evaluate(() => {+ const distanceBadge = document.querySelector('.distance-badge');+ return distanceBadge?.textContent?.trim().includes('1st') || false;+ });++ return isAccepted ? 'accepted' : 'pending';++ } catch (error) {+ console.error(`failed to check status for ${profileUrl} (attempt ${attempt + 1}/${maxRetries}):`, error);++ if (error instanceof Error && error.message.includes('detached Frame')) {+ const browser = getActiveBrowser();+ if (!browser.page) throw new Error('failed to get new page');+ page = browser.page;+ }++ if (attempt === maxRetries - 1) {+ return 'pending';+ }++ const retryDelay = baseDelay + Math.floor(Math.random() * baseDelay);+ await new Promise(resolve => setTimeout(resolve, retryDelay));+ }+ }++ return 'pending';+ } catch (error) {+ console.error(`failed to check status for ${profileUrl}:`, error);+ return 'pending';+ }+}++// Add type for status+interface HarvestStatus {+ nextHarvestTime: string;+ isHarvesting: string;+ connectionsSent: number;+}++// Initialize with empty strings instead of undefined+let lastStatus: HarvestStatus = {+ nextHarvestTime: '',+ isHarvesting: '',+ connectionsSent: 0+};++// Add cache for cooldown check+let lastCooldownCheck = {+ nextTime: '',+ shouldRestart: false+};++// Add type for progress updates+interface RefreshProgress {+ current: number;+ total: number;+}++// Add progress tracking at module level+let refreshProgress: RefreshProgress | null = null;++export async function GET(request: Request) {+ const nextDelay = 0;+ try {+ const url = new URL(request.url);+ const shouldRefresh = url.searchParams.get('refresh') === 'true';+ let connectionsStore = await loadConnections();++ // Only log if values changed+ const currentStatus = {+ nextHarvestTime: connectionsStore.nextHarvestTime || '',+ isHarvesting: String(connectionsStore.isHarvesting || ''),+ connectionsSent: connectionsStore.connectionsSent+ };++ if (JSON.stringify(lastStatus) !== JSON.stringify(currentStatus)) {+ console.log('harvest status changed:', currentStatus);+ lastStatus = currentStatus;+ }++ // If isHarvesting is true but no active harvesting is happening, restart it+ if (connectionsStore.isHarvesting && !connectionsStore.nextHarvestTime) {+ console.log('detected stale harvesting state, restarting process');++ // Start harvesting in the background+ startHarvesting().then(() => {+ // console.log('harvest restart result:', result);+ }).catch(error => {+ console.error('failed to restart harvesting:', error);+ // Reset harvesting state if start fails+ saveHarvestingState(false).catch(console.error);+ });+ }++ // Original cooldown check+ if (connectionsStore.nextHarvestTime) {+ const nextTime = new Date(connectionsStore.nextHarvestTime);+ const now = new Date();+ const shouldRestart = nextTime <= now;++ // Only track nextTime and shouldRestart state changes+ const currentCooldownCheck = {+ nextTime: nextTime.toISOString(),+ shouldRestart+ };++ if (JSON.stringify(lastCooldownCheck) !== JSON.stringify(currentCooldownCheck)) {+ console.log('cooldown check:', {+ ...currentCooldownCheck,+ now: now.toISOString() // Include now only in the log+ });+ lastCooldownCheck = currentCooldownCheck;+ }++ if (shouldRestart) {+ console.log('cooldown period ended, restarting harvest process');+ await saveNextHarvestTime('');+ await saveHarvestingState(true);+ connectionsStore = await loadConnections();++ startHarvesting().then(() => {+ // console.log('harvest restart result:', result);+ }).catch(error => {+ console.error('failed to restart harvesting:', error);+ saveHarvestingState(false).catch(console.error);+ });+ }+ }++ if (shouldRefresh) {+ const { page } = getActiveBrowser();+ if (page) {+ const startTime = Date.now();++ const pendingConnections = Object.entries(connectionsStore.connections)+ .filter(([, connection]) => connection.status === 'pending');++ refreshProgress = {+ current: 0,+ total: pendingConnections.length+ };++ // Check pending connections+ for (const [url, connection] of pendingConnections) {+ refreshProgress.current++;++ const newStatus = await checkConnectionStatus(page, url, connection);+ if (newStatus !== connection.status) {+ await saveConnection({+ ...connection,+ status: newStatus,+ timestamp: new Date().toISOString()+ });+ }+ }++ // Calculate and save duration stats+ const totalDuration = Date.now() - startTime;+ await saveRefreshStats(totalDuration, pendingConnections.length);++ // Reset progress after completion+ refreshProgress = null;+ }+ // Reload after updates+ connectionsStore = await loadConnections();+ }++ // Calculate stats from connections+ const stats = Object.values(connectionsStore.connections).reduce((acc, connection) => {+ const status = connection.status || 'pending';+ acc[status] = (acc[status] || 0) + 1;+ return acc;+ }, {} as Record<string, number>);++ return NextResponse.json({+ // Convert boolean isHarvesting to three-state status+ isHarvesting: connectionsStore.nextHarvestTime && new Date(connectionsStore.nextHarvestTime) > new Date()+ ? 'cooldown'+ : connectionsStore.isHarvesting+ ? 'running'+ : 'stopped',+ nextHarvestTime: connectionsStore.nextHarvestTime,+ connectionsSent: connectionsStore.connectionsSent || 0,+ dailyLimitReached: connectionsStore.connectionsSent >= 35,+ weeklyLimitReached: false,+ stats: {+ pending: stats.pending || 0,+ accepted: stats.accepted || 0,+ declined: stats.declined || 0,+ email_required: stats.email_required || 0,+ cooldown: stats.cooldown || 0,+ total: Object.keys(connectionsStore.connections).length,+ lastRefreshDuration: connectionsStore.lastRefreshDuration,+ averageProfileCheckDuration: connectionsStore.averageProfileCheckDuration+ },+ // Add refresh progress to response+ refreshProgress,+ rateLimitedUntil: null,+ nextProfileTime: nextDelay ? Date.now() + nextDelay : null,+ });+ } catch (error: unknown) {+ return NextResponse.json({ message: (error as Error).message?.toLowerCase() }, { status: 500 });+ }+}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/app/api/harvest/stop/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/stop/route.tssimilarity index 67%rename from pipes/linkedin_ai_assistant/app/api/harvest/stop/route.tsrename to pipes/linkedin-ai-assistant/app/api/harvest/stop/route.tsindex a9259b3cd..86564bff4 100644--- a/pipes/linkedin_ai_assistant/app/api/harvest/stop/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/harvest/stop/route.ts@@ -1,5 +1,5 @@import { NextResponse } from 'next/server';-import { stopHarvesting } from '@/lib/logic_sequence/harvest_connections';+import { stopHarvesting } from '@/lib/logic-sequence/harvest-connections';import { saveHarvestingState } from '@/lib/storage/storage';export async function POST() {@@ -13,7 +13,7 @@ export async function POST() {message: 'stopping harvest process',isHarvesting: false});- } catch (error: any) {- return NextResponse.json({ message: error.message.toLowerCase() }, { status: 500 });+ } catch (error: unknown) {+ return NextResponse.json({ message: (error as Error).message.toLowerCase() }, { status: 500 });}}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/app/api/messages/check/route.ts b/pipes/linkedin-ai-assistant/app/api/messages/check/route.tssimilarity index 84%rename from pipes/linkedin_ai_assistant/app/api/messages/check/route.tsrename to pipes/linkedin-ai-assistant/app/api/messages/check/route.tsindex 9554054f9..8e474f5a5 100644--- a/pipes/linkedin_ai_assistant/app/api/messages/check/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/messages/check/route.ts@@ -1,4 +1,4 @@-import { startMessageCheck } from '@/lib/logic_sequence/check_messages';+import { startMessageCheck } from '@/lib/logic-sequence/check-messages';import { NextResponse } from 'next/server';export async function POST() {diff --git a/pipes/linkedin_ai_assistant/app/api/messages/route.ts b/pipes/linkedin-ai-assistant/app/api/messages/route.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/app/api/messages/route.tsrename to pipes/linkedin-ai-assistant/app/api/messages/route.tsdiff --git a/pipes/linkedin_ai_assistant/app/api/profiles/route.ts b/pipes/linkedin-ai-assistant/app/api/profiles/route.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/app/api/profiles/route.tsrename to pipes/linkedin-ai-assistant/app/api/profiles/route.tsdiff --git a/pipes/linkedin_ai_assistant/app/api/save-template/route.ts b/pipes/linkedin-ai-assistant/app/api/save-template/route.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/app/api/save-template/route.tsrename to pipes/linkedin-ai-assistant/app/api/save-template/route.tsdiff --git a/pipes/linkedin_ai_assistant/app/api/state/route.ts b/pipes/linkedin-ai-assistant/app/api/state/route.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/app/api/state/route.tsrename to pipes/linkedin-ai-assistant/app/api/state/route.tsdiff --git a/pipes/linkedin_ai_assistant/app/api/validate-search/route.ts b/pipes/linkedin-ai-assistant/app/api/validate-search/route.tssimilarity index 82%rename from pipes/linkedin_ai_assistant/app/api/validate-search/route.tsrename to pipes/linkedin-ai-assistant/app/api/validate-search/route.tsindex 9f077f3e2..92bdc6da5 100644--- a/pipes/linkedin_ai_assistant/app/api/validate-search/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/validate-search/route.ts@@ -1,10 +1,10 @@import { NextResponse } from 'next/server';-import { navigateToSearch } from '@/lib/simple_actions/go_to_search_results';-import { setupBrowser, getActiveBrowser } from '@/lib/browser_setup';+import { navigateToSearch } from '@/lib/simple-actions/go-to-search-results';+import { setupBrowser, getActiveBrowser } from '@/lib/browser-setup';export async function POST(request: Request) {try {- const { url, wsUrl, allowTruncate } = await request.json();+ const { url, allowTruncate } = await request.json();if (!url || !url.includes('linkedin.com/search')) {return NextResponse.json(@@ -14,7 +14,7 @@ export async function POST(request: Request) {}// Setup browser with the provided WebSocket URL- await setupBrowser(wsUrl);+ await setupBrowser();const { page } = getActiveBrowser();if (!page) {diff --git a/pipes/linkedin_ai_assistant/app/api/workflow/start/route.ts b/pipes/linkedin-ai-assistant/app/api/workflow/start/route.tssimilarity index 90%rename from pipes/linkedin_ai_assistant/app/api/workflow/start/route.tsrename to pipes/linkedin-ai-assistant/app/api/workflow/start/route.tsindex 282451abb..d771c81d3 100644--- a/pipes/linkedin_ai_assistant/app/api/workflow/start/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/workflow/start/route.ts@@ -1,5 +1,5 @@import { NextResponse } from 'next/server';-import { startAutomation } from '@/lib/logic_sequence/intro_requester';+import { startAutomation } from '@/lib/logic-sequence/intro-requester';export async function POST(request: Request) {try {diff --git a/pipes/linkedin_ai_assistant/app/api/workflow/status/route.ts b/pipes/linkedin-ai-assistant/app/api/workflow/status/route.tssimilarity index 94%rename from pipes/linkedin_ai_assistant/app/api/workflow/status/route.tsrename to pipes/linkedin-ai-assistant/app/api/workflow/status/route.tsindex 4eb49f6d7..1fe54e67e 100644--- a/pipes/linkedin_ai_assistant/app/api/workflow/status/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/workflow/status/route.ts@@ -1,6 +1,6 @@import { setRunningState, currentSteps, queueStats } from './state';-let isRunning = false;+const isRunning = false;export async function GET() {return new Response(JSON.stringify({diff --git a/pipes/linkedin_ai_assistant/app/api/workflow/status/state.ts b/pipes/linkedin-ai-assistant/app/api/workflow/status/state.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/app/api/workflow/status/state.tsrename to pipes/linkedin-ai-assistant/app/api/workflow/status/state.tsdiff --git a/pipes/linkedin_ai_assistant/app/favicon.ico b/pipes/linkedin-ai-assistant/app/favicon.icosimilarity index 100%rename from pipes/linkedin_ai_assistant/app/favicon.icorename to pipes/linkedin-ai-assistant/app/favicon.icodiff --git a/pipes/linkedin_ai_assistant/app/fonts/GeistMonoVF.woff b/pipes/linkedin-ai-assistant/app/fonts/GeistMonoVF.woffsimilarity index 100%rename from pipes/linkedin_ai_assistant/app/fonts/GeistMonoVF.woffrename to pipes/linkedin-ai-assistant/app/fonts/GeistMonoVF.woffdiff --git a/pipes/linkedin_ai_assistant/app/fonts/GeistVF.woff b/pipes/linkedin-ai-assistant/app/fonts/GeistVF.woffsimilarity index 100%rename from pipes/linkedin_ai_assistant/app/fonts/GeistVF.woffrename to pipes/linkedin-ai-assistant/app/fonts/GeistVF.woffdiff --git a/pipes/linkedin_ai_assistant/app/globals.css b/pipes/linkedin-ai-assistant/app/globals.csssimilarity index 100%rename from pipes/linkedin_ai_assistant/app/globals.cssrename to pipes/linkedin-ai-assistant/app/globals.cssdiff --git a/pipes/linkedin_ai_assistant/app/layout.tsx b/pipes/linkedin-ai-assistant/app/layout.tsxsimilarity index 100%rename from pipes/linkedin_ai_assistant/app/layout.tsxrename to pipes/linkedin-ai-assistant/app/layout.tsxdiff --git a/pipes/linkedin-ai-assistant/app/page.tsx b/pipes/linkedin-ai-assistant/app/page.tsxnew file mode 100644index 000000000..aa9588498--- /dev/null+++ b/pipes/linkedin-ai-assistant/app/page.tsx@@ -0,0 +1,56 @@+"use client";++import { useState } from "react";+import { LaunchLinkedInChromeSession } from "@/components/launch-linkedin-chrome-session";+import { IntroRequester } from "@/components/intro-requester";+import { ReloadButton } from "@/components/reload-button";+import { HarvestClosestConnections } from "@/components/harvest";++export default function Home() {+ const [loginStatus, setLoginStatus] = useState<'checking' | 'logged_in' | 'logged_out' | null>(null);++ return (+ <div className="min-h-screen w-full p-4 pb-20 sm:p-8">+ <div className="space-y-1.5 mb-8">+ <h1 className="text-2xl font-semibold tracking-tight">linkedin ai assistant</h1>+ <p className="text-sm text-muted-foreground">automate your linkedin interactions with ai</p>+ <p className="text-sm text-muted-foreground mt-4">+ this tool helps you manage your linkedin network by automating common tasks. you can harvest connections+ from your network and request introductions using ai-powered workflows. make sure you're logged into+ linkedin before starting any automation.+ </p>+ </div>++ <div className="space-y-8">+ <section>+ <div className="flex items-center gap-4">+ <h2 className="text-xl font-semibold">getting started</h2>+ <LaunchLinkedInChromeSession+ loginStatus={loginStatus}+ setLoginStatus={setLoginStatus}+ />+ <ReloadButton />+ </div>+ </section>++ {loginStatus === 'logged_in' && (+ <section>+ <h2 className="text-xl font-semibold mb-4">available workflows</h2>+ <div className="grid gap-4">+ <div className="border rounded-lg p-4">+ <HarvestClosestConnections />+ </div>++ <div className="border rounded-lg p-4">+ <p className="text-sm text-muted-foreground mb-4">+ send introduction requests to your network based on your criteria+ </p>+ <IntroRequester />+ </div>+ </div>+ </section>+ )}+ </div>+ </div>+ );+}diff --git a/pipes/linkedin-ai-assistant/bun.lockb b/pipes/linkedin-ai-assistant/bun.lockbnew file mode 100755index 000000000..223b9b547Binary files /dev/null and b/pipes/linkedin-ai-assistant/bun.lockb differdiff --git a/pipes/linkedin_ai_assistant/components.json b/pipes/linkedin-ai-assistant/components.jsonsimilarity index 100%rename from pipes/linkedin_ai_assistant/components.jsonrename to pipes/linkedin-ai-assistant/components.jsondiff --git a/pipes/linkedin-ai-assistant/components/harvest.tsx b/pipes/linkedin-ai-assistant/components/harvest.tsxnew file mode 100644index 000000000..f852ffa49--- /dev/null+++ b/pipes/linkedin-ai-assistant/components/harvest.tsx@@ -0,0 +1,387 @@+"use client";++import { useState, useEffect } from "react";+import { RefreshCw, Info } from "lucide-react";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";++interface ConnectionStats {+ pending: number;+ accepted: number;+ declined: number;+ email_required: number;+ cooldown: number;+ total: number;+ averageProfileCheckDuration?: number;+}++// Add type for harvesting status+type HarvestingStatus = 'running' | 'stopped' | 'cooldown';++// Add helper function for formatting time+function formatTimeRemaining(milliseconds: number): string {+ const seconds = Math.ceil(milliseconds / 1000);+ const minutes = Math.floor(seconds / 60);+ const remainingSeconds = seconds % 60;+ return `${minutes}m ${remainingSeconds}s`;+}++// Add error type+type ApiError = {+ message?: string;+ toString: () => string;+};++// Add this new component+function CountdownTimer({ targetTime, prefix = "next profile in:" }: { targetTime: number, prefix?: string }) {+ const [timeLeft, setTimeLeft] = useState<string>('');++ useEffect(() => {+ const interval = setInterval(() => {+ const now = Date.now();+ if (now >= targetTime) {+ setTimeLeft('');+ clearInterval(interval);+ return;+ }+ setTimeLeft(formatTimeRemaining(targetTime - now));+ }, 1000);++ return () => clearInterval(interval);+ }, [targetTime]);++ if (!timeLeft) return null;++ return (+ <span className="text-sm text-gray-500">+ {prefix} {timeLeft}+ </span>+ );+}++export function HarvestClosestConnections() {+ const [harvestingStatus, setHarvestingStatus] = useState<HarvestingStatus>('stopped');+ const [status, setStatus] = useState("");+ const [nextHarvestTime, setNextHarvestTime] = useState<string | null>(null);+ const [connectionsSent, setConnectionsSent] = useState(0);+ const [dailyLimitReached, setDailyLimitReached] = useState(false);+ const [weeklyLimitReached, setWeeklyLimitReached] = useState(false);+ const [stats, setStats] = useState<ConnectionStats>({+ pending: 0,+ accepted: 0,+ declined: 0,+ email_required: 0,+ cooldown: 0,+ total: 0+ });+ const [isRefreshing, setIsRefreshing] = useState(false);+ const [refreshProgress, setRefreshProgress] = useState<{ current: number; total: number } | null>(null);+ const [nextProfileTime, setNextProfileTime] = useState<number | null>(null);+ const [rateLimitedUntil, setRateLimitedUntil] = useState<string | null>(null);++ useEffect(() => {+ // Update initial state+ fetch("/api/harvest/status")+ .then(res => res.json())+ .then(data => {+ setHarvestingStatus(data.isHarvesting);+ setConnectionsSent(data.connectionsSent || 0);+ setDailyLimitReached(data.dailyLimitReached || false);+ setWeeklyLimitReached(data.weeklyLimitReached || false);+ if (data.nextHarvestTime) {+ setNextHarvestTime(data.nextHarvestTime);+ if (new Date(data.nextHarvestTime) > new Date()) {+ setStatus(`harvesting cooldown active until ${new Date(data.nextHarvestTime).toLocaleString()}`);+ }+ }+ })+ .catch(console.error);+ }, []);++ // Combine both status polling effects into one+ useEffect(() => {+ if (harvestingStatus !== 'stopped') {+ const interval = setInterval(() => {+ fetch("/api/harvest/status")+ .then(res => res.json())+ .then(data => {+ setHarvestingStatus(data.isHarvesting);+ setConnectionsSent(data.connectionsSent || 0);+ setDailyLimitReached(data.connectionsSent >= 35);+ setWeeklyLimitReached(data.weeklyLimitReached || false);+ if (data.stats) {+ setStats(data.stats);+ }+ if (data.nextHarvestTime) {+ setNextHarvestTime(data.nextHarvestTime);+ if (new Date(data.nextHarvestTime) > new Date()) {+ const message = data.connectionsSent >= 35+ ? `daily limit of ${data.connectionsSent} connections reached, next harvest at ${new Date(data.nextHarvestTime).toLocaleString()}`+ : `harvesting cooldown active until ${new Date(data.nextHarvestTime).toLocaleString()}`;+ setStatus(message);+ }+ }++ // Check for cooldown restart if needed+ if (!data.isHarvesting && data.nextHarvestTime) {+ const now = new Date();+ const harvestTime = new Date(data.nextHarvestTime);++ if (now >= harvestTime) {+ console.log('cooldown period ended, initiating restart');+ setNextHarvestTime(null);+ setStatus('cooldown period ended, restarting...');++ // Force a status refresh to trigger the backend restart+ fetch('/api/harvest/status?refresh=true')+ .then(() => new Promise(resolve => setTimeout(resolve, 1000)))+ .then(() => setHarvestingStatus('running'))+ .catch(error => {+ console.error('failed to restart harvesting:', error);+ setStatus('failed to restart after cooldown');+ });+ }+ }++ if (data.nextProfileTime) {+ setNextProfileTime(data.nextProfileTime);+ } else {+ setNextProfileTime(null);+ }+ })+ .catch(error => {+ console.error('failed to fetch status:', error);+ });+ }, 1000);++ return () => clearInterval(interval);+ }+ }, [harvestingStatus]);++ const startHarvesting = async () => {+ try {+ setHarvestingStatus('running');+ setStatus("starting harvesting process...");++ const response = await fetch("/api/harvest/start", {+ method: "POST",+ });++ const data = await response.json();+ console.log('harvest start response:', data);++ if (response.ok) {+ setStatus(data.message?.toLowerCase() || 'unknown status');+ setConnectionsSent(data.connectionsSent || 0);+ setDailyLimitReached(data.dailyLimitReached || false);+ setWeeklyLimitReached(data.weeklyLimitReached || false);+ if (data.nextHarvestTime) {+ setNextHarvestTime(data.nextHarvestTime);+ }+ } else {+ // Handle 429 without stopping the workflow+ if (response.status === 429) {+ setNextHarvestTime(data.nextHarvestTime);+ setStatus(data.message?.toLowerCase() || 'rate limit reached');+ } else {+ setStatus(`error: ${data.message?.toLowerCase() || 'unknown error'}`);+ setHarvestingStatus('stopped');+ }+ }+ } catch (error: unknown) {+ console.error("failed to start harvesting:", error);+ const err = error as ApiError;+ setStatus(`error: ${err.message?.toLowerCase() || err.toString().toLowerCase()}`);+ setHarvestingStatus('stopped');+ }+ };++ const stopHarvesting = async () => {+ try {+ // Set status immediately to improve UI responsiveness+ setHarvestingStatus('stopped');+ setStatus("stopping harvest process...");++ const response = await fetch("/api/harvest/stop", {+ method: "POST",+ });++ if (!response.ok) {+ const data = await response.json();+ setStatus(`error stopping: ${data.message?.toLowerCase() || 'unknown error'}`);+ // Revert status if there was an error+ setHarvestingStatus('running');+ }+ } catch (error: unknown) {+ console.error("failed to stop harvesting:", error);+ const err = error as ApiError;+ setStatus(`${err.message?.toLowerCase() || err.toString().toLowerCase()}`);+ // Revert status if there was an error+ setHarvestingStatus('running');+ }+ };++ const refreshStats = async () => {+ try {+ setIsRefreshing(true);++ // Start polling for progress+ const pollInterval = setInterval(async () => {+ const response = await fetch("/api/harvest/status");+ const data = await response.json();+ if (data.refreshProgress) {+ setRefreshProgress(data.refreshProgress);+ }+ }, 1000);++ // Trigger the actual refresh+ const response = await fetch("/api/harvest/status?refresh=true");+ const data = await response.json();++ // Add rate limit handling+ if (data.rateLimitedUntil) {+ setRateLimitedUntil(data.rateLimitedUntil);+ } else {+ setRateLimitedUntil(null);+ }++ // Clear polling and progress+ clearInterval(pollInterval);+ setRefreshProgress(null);++ setConnectionsSent(data.connectionsSent || 0);+ setDailyLimitReached(data.dailyLimitReached || false);+ setWeeklyLimitReached(data.weeklyLimitReached || false);+ if (data.stats) {+ setStats(data.stats);+ }+ } catch (error) {+ console.error("failed to refresh stats:", error);+ } finally {+ setIsRefreshing(false);+ setRefreshProgress(null);+ }+ };++ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-row items-center gap-4">+ <div className="flex items-center gap-4">+ <span className="text-lg font-medium">+ farming connections {connectionsSent > 0 && `(${connectionsSent})`}+ </span>+ <div className="flex gap-2">+ {harvestingStatus === 'stopped' && (+ <button+ onClick={startHarvesting}+ className="bg-black text-white px-4 py-2 rounded-md text-base"+ >+ start+ </button>+ )}+ {(harvestingStatus === 'running' || harvestingStatus === 'cooldown') && (+ <button+ onClick={stopHarvesting}+ className="bg-red-600 text-white px-4 py-2 rounded-md text-base hover:bg-red-700"+ >+ stop+ </button>+ )}+ </div>+ </div>+ {harvestingStatus && (+ <span className="text-sm text-gray-500">+ {dailyLimitReached && nextHarvestTime+ ? `daily limit reached, next harvest at ${new Date(nextHarvestTime).toLocaleString()}`+ : weeklyLimitReached && nextHarvestTime+ ? `weekly limit reached, next harvest at ${new Date(nextHarvestTime).toLocaleString()}`+ : status}+ </span>+ )}+ </div>+ <p className="text-sm text-muted-foreground">+ automatically send connection requests to your closest linkedin connections+ </p>++ <div className="flex items-center mt-4 mb-2">+ <span className="text-sm font-medium">stats</span>+ <button+ onClick={refreshStats}+ disabled={isRefreshing || !!rateLimitedUntil}+ className={`p-2 rounded-md transition-all ${+ isRefreshing || rateLimitedUntil ? 'bg-gray-100 cursor-not-allowed' : 'hover:bg-gray-100'+ }`}+ aria-label="refresh stats"+ >+ <RefreshCw+ className={`h-5 w-5 transition-all ${+ isRefreshing ? 'animate-spin text-gray-400' : 'text-gray-500 hover:text-gray-700'+ }`}+ />+ </button>+ {nextProfileTime && nextProfileTime > Date.now() && (+ <div className="ml-2">+ <CountdownTimer targetTime={nextProfileTime} />+ </div>+ )}+ {rateLimitedUntil && (+ <span className="ml-2 text-sm text-red-500">+ rate limited ({formatTimeRemaining(new Date(rateLimitedUntil).getTime() - Date.now())})+ </span>+ )}+ {refreshProgress && !rateLimitedUntil && (+ <span className="ml-2 text-sm text-gray-500">+ checking {refreshProgress.current}/{refreshProgress.total} profiles+ {stats.averageProfileCheckDuration && nextProfileTime && (+ <CountdownTimer+ targetTime={nextProfileTime}+ prefix="~"+ />+ )}+ </span>+ )}+ </div>++ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-4">+ <div className="flex flex-col items-center p-3 bg-gray-50 rounded-lg">+ <span className="text-lg font-medium">{stats.total}</span>+ <span className="text-sm text-muted-foreground">total</span>+ </div>+ <div className="flex flex-col items-center p-3 bg-blue-50 rounded-lg">+ <span className="text-lg font-medium">{stats.pending}</span>+ <span className="text-sm text-muted-foreground">pending</span>+ </div>+ <div className="flex flex-col items-center p-3 bg-green-50 rounded-lg">+ <span className="text-lg font-medium">{stats.accepted}</span>+ <span className="text-sm text-muted-foreground">accepted</span>+ </div>+ <div className="flex flex-col items-center p-3 bg-red-50 rounded-lg">+ <span className="text-lg font-medium">{stats.declined}</span>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger className="flex items-center gap-1">+ <span className="text-sm text-muted-foreground">declined</span>+ <Info className="h-3 w-3 text-muted-foreground" />+ </TooltipTrigger>+ <TooltipContent>+ <p className="text-sm">profiles that didn't accept your connection request within 14 days are marked as declined and the request is withdrawn</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ <div className="flex flex-col items-center p-3 bg-yellow-50 rounded-lg">+ <span className="text-lg font-medium">{stats.email_required}</span>+ <span className="text-sm text-muted-foreground">email required</span>+ </div>+ <div className="flex flex-col items-center p-3 bg-orange-50 rounded-lg">+ <span className="text-lg font-medium">{stats.cooldown}</span>+ <span className="text-sm text-muted-foreground">cooldown</span>+ </div>+ </div>+ </div>+ );+}diff --git a/pipes/linkedin_ai_assistant/components/header.tsx b/pipes/linkedin-ai-assistant/components/header.tsxsimilarity index 74%rename from pipes/linkedin_ai_assistant/components/header.tsxrename to pipes/linkedin-ai-assistant/components/header.tsxindex e54b18bd1..a150e09e1 100644--- a/pipes/linkedin_ai_assistant/components/header.tsx+++ b/pipes/linkedin-ai-assistant/components/header.tsx@@ -1,12 +1,17 @@"use client"+import Image from 'next/image';+export default function Header() {return (<div className="flex flex-col justify-center items-center mt-6">- <img+ <ImageclassName="w-24 h-24"src="/128x128.png"alt="screenpipe-logo"+ width={96}+ height={96}+ priority/><h1 className="font-bold text-center text-2xl">screenpipe</h1></div>diff --git a/pipes/linkedin_ai_assistant/components/intro-requester.tsx b/pipes/linkedin-ai-assistant/components/intro-requester.tsxsimilarity index 95%rename from pipes/linkedin_ai_assistant/components/intro-requester.tsxrename to pipes/linkedin-ai-assistant/components/intro-requester.tsxindex 4ae45f40b..cbb65c4cf 100644--- a/pipes/linkedin_ai_assistant/components/intro-requester.tsx+++ b/pipes/linkedin-ai-assistant/components/intro-requester.tsx@@ -3,9 +3,9 @@import { Button } from "@/components/ui/button";import { useState, useEffect } from "react";import { Play, Loader2, Check } from "lucide-react";-import TemplateEditor from "@/components/settings_editor";-import StateViewer from "@/components/state_viewer";-import template from "@/lib/storage/templates.json";+import TemplateEditor from "@/components/template-editor";+import StateViewer from "@/components/state-viewer";+import template from '@/lib/storage/templates.json';type WorkflowStep = {step: string;@@ -28,7 +28,7 @@ export function IntroRequester() {const [steps, setSteps] = useState<WorkflowStep[]>([]);const [queueStats, setQueueStats] = useState<QueueStats | null>(null);const [showSettings, setShowSettings] = useState(false);- const [searchUrl, setSearchUrl] = useState(template.paste_here_url_from_linkedin_with_2nd_grade_connections);+ const [searchUrl, setSearchUrl] = useState(template['paste-here-url-from-linkedin-with-2nd-grade-connections']);useEffect(() => {const handleStorageChange = async () => {diff --git a/pipes/linkedin_ai_assistant/components/launch_linkedin_chrome_session.tsx b/pipes/linkedin-ai-assistant/components/launch-linkedin-chrome-session.tsxsimilarity index 83%rename from pipes/linkedin_ai_assistant/components/launch_linkedin_chrome_session.tsxrename to pipes/linkedin-ai-assistant/components/launch-linkedin-chrome-session.tsxindex 5f582f3e2..e5c5bdf7e 100644--- a/pipes/linkedin_ai_assistant/components/launch_linkedin_chrome_session.tsx+++ b/pipes/linkedin-ai-assistant/components/launch-linkedin-chrome-session.tsx@@ -2,7 +2,12 @@import { Button } from "@/components/ui/button";import { useState, useEffect } from "react";-import { Chrome, ArrowRight, CheckCircle, LogIn, Loader2 } from "lucide-react";+import { Chrome, CheckCircle, LogIn, Loader2, Info } from "lucide-react";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/components/ui/hover-card";interface Props {loginStatus: 'checking' | 'logged_in' | 'logged_out' | null;@@ -135,10 +140,10 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro};return (- <div className="flex flex-col gap-4">- <div className="flex flex-col gap-2">- <div className="flex gap-2">- {(status === 'idle' || status === 'connecting') && (+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-2">+ {(status === 'idle' || status === 'connecting') && (+ <div className="flex items-center gap-2"><ButtononClick={launchChrome}disabled={status === 'connecting'}@@ -147,20 +152,27 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro<Chrome className="w-4 h-4" />{status === 'connecting' ? 'launching chrome...' : 'launch'}</Button>- )}- {status === 'connected' && (- <Button- onClick={killChrome}- variant="destructive"- className="flex items-center gap-2"- >- exit chrome- </Button>- )}- </div>- <span className="text-xs text-gray-500">- it will close your chrome browser, but you can restore tabs- </span>+ <HoverCard>+ <HoverCardTrigger>+ <Info className="w-4 h-4 text-gray-500" />+ </HoverCardTrigger>+ <HoverCardContent className="w-80">+ <p className="text-sm text-gray-500">+ it will close your chrome browser, but you can restore tabs+ </p>+ </HoverCardContent>+ </HoverCard>+ </div>+ )}+ {status === 'connected' && (+ <Button+ onClick={killChrome}+ variant="destructive"+ className="flex items-center gap-2"+ >+ exit chrome+ </Button>+ )}</div>{status === 'connected' && (diff --git a/pipes/linkedin_ai_assistant/components/reload_button.tsx b/pipes/linkedin-ai-assistant/components/reload-button.tsxsimilarity index 100%rename from pipes/linkedin_ai_assistant/components/reload_button.tsxrename to pipes/linkedin-ai-assistant/components/reload-button.tsxdiff --git a/pipes/linkedin_ai_assistant/components/settings_editor.tsx b/pipes/linkedin-ai-assistant/components/settings-editor.tsxsimilarity index 96%rename from pipes/linkedin_ai_assistant/components/settings_editor.tsxrename to pipes/linkedin-ai-assistant/components/settings-editor.tsxindex eb72447b3..76c1bba9e 100644--- a/pipes/linkedin_ai_assistant/components/settings_editor.tsx+++ b/pipes/linkedin-ai-assistant/components/settings-editor.tsx@@ -8,6 +8,7 @@ import {} from "@/components/ui/collapsible";import { ChevronDown, Loader2 } from "lucide-react";import { debounce } from "lodash";+import Image from 'next/image';interface TemplateEditorProps {initialTemplate: unknown;@@ -154,7 +155,14 @@ export default function TemplateEditor({ initialTemplate, defaultOpen = true }:<li>When finished copy the url</li><li>Insert it in the field below</li></ol>- <img src="/guide_bigger.gif" alt="LinkedIn search guide" className="rounded-lg mt-4 w-full max-w-3xl" />+ <Image+ src="/guide_bigger.gif"+ alt="LinkedIn search guide"+ width={896}+ height={504}+ className="rounded-lg mt-4 w-full max-w-3xl"+ priority+ /></div>{Object.entries(template).map(([key, value]) => (<div key={key} className="flex flex-col gap-2">diff --git a/pipes/linkedin_ai_assistant/components/start_workflow.tsx b/pipes/linkedin-ai-assistant/components/start-workflow.tsxsimilarity index 100%rename from pipes/linkedin_ai_assistant/components/start_workflow.tsxrename to pipes/linkedin-ai-assistant/components/start-workflow.tsxdiff --git a/pipes/linkedin_ai_assistant/components/state_viewer.tsx b/pipes/linkedin-ai-assistant/components/state-viewer.tsxsimilarity index 89%rename from pipes/linkedin_ai_assistant/components/state_viewer.tsxrename to pipes/linkedin-ai-assistant/components/state-viewer.tsxindex 1b0b14887..3096b1436 100644--- a/pipes/linkedin_ai_assistant/components/state_viewer.tsx+++ b/pipes/linkedin-ai-assistant/components/state-viewer.tsx@@ -16,6 +16,19 @@ interface Profile {headline: string;}+interface ProfileData {+ profileUrl: string;+ timestamp: string;+ status: 'visited' | 'to visit';+ actions: Record<string, string>;+ originalIndex: number;+}++interface StateData {+ visitedProfiles: ProfileData[];+ toVisitProfiles: ProfileData[];+}+type SortField = 'index' | 'name' | 'timestamp' | 'status' | 'actions' | 'messages';type SortDirection = 'asc' | 'desc';@@ -23,13 +36,23 @@ interface StateViewerProps {defaultOpen?: boolean;}+interface Message {+ content: string;+ timestamp: string;+}++interface MessageData {+ messages: Message[];+ timestamp: string;+}+export default function StateViewer({ defaultOpen = true }: StateViewerProps) {- const [data, setData] = useState<any>(null);+ const [data, setData] = useState<StateData | null>(null);const [profiles, setProfiles] = useState<Record<string, Profile>>({});- const [messages, setMessages] = useState<Record<string, any>>({});+ const [messages, setMessages] = useState<Record<string, MessageData>>({});const [sortField, setSortField] = useState<SortField>('timestamp');const [sortDirection, setSortDirection] = useState<SortDirection>('asc');- const previousProfilesRef = useRef<any[]>([]);+ const previousProfilesRef = useRef<ProfileData[]>([]);const [isCheckingMessages, setIsCheckingMessages] = useState(false);const [isOpen, setIsOpen] = useState(defaultOpen);@@ -60,18 +83,18 @@ export default function StateViewer({ defaultOpen = true }: StateViewerProps) {if (data) {const currentProfiles = [- ...data.visitedProfiles.map((p: any, i: number) => ({ ...p, status: 'visited', originalIndex: i })),- ...data.toVisitProfiles.map((p: any, i: number) => ({ ...p, status: 'to visit', originalIndex: i + data.visitedProfiles.length }))+ ...data.visitedProfiles.map((p: ProfileData, i: number) => ({ ...p, status: 'visited' as const, originalIndex: i })),+ ...data.toVisitProfiles.map((p: ProfileData, i: number) => ({ ...p, status: 'to visit' as const, originalIndex: i + data.visitedProfiles.length }))];previousProfilesRef.current = currentProfiles;}- setData(newState);- setProfiles(newProfiles.profiles || {});- setMessages(newMessages.messages || {});- } catch (error) {- console.error('failed to fetch data:', error);- }+ setData(newState);+ setProfiles(newProfiles.profiles || {});+ setMessages(newMessages.messages || {});+ } catch (error) {+ console.error('failed to fetch data:', error);+ }};fetchData();@@ -79,10 +102,8 @@ export default function StateViewer({ defaultOpen = true }: StateViewerProps) {return () => {clearInterval(interval);};- }, [isOpen]);+ }, [isOpen, data]);- // Always render the dashboard, even if data is null- // The dashboard will update once data is loadedconst getUsername = (url: string) => {try {const cleanUrl = url.replace(/\/$/, '');@@ -96,7 +117,7 @@ export default function StateViewer({ defaultOpen = true }: StateViewerProps) {.replace(/^\s+|\s+$/g, '').replace(/\s*\([^)]*\)/g, '').replace(/\s+$/, '');- } catch (e) {+ } catch {return url;}};@@ -137,7 +158,7 @@ export default function StateViewer({ defaultOpen = true }: StateViewerProps) {});};- const sortProfiles = (profiles: any[]) => {+ const sortProfiles = (profiles: ProfileData[]) => {return [...profiles].sort((a, b) => {let comparison = 0;switch (sortField) {@@ -174,20 +195,9 @@ export default function StateViewer({ defaultOpen = true }: StateViewerProps) {});};- const hasUpdates = (profile: any) => {- return previousProfilesRef.current.find(p => {- if (p.profileUrl !== profile.profileUrl) return false;- return (- p.timestamp !== profile.timestamp ||- JSON.stringify(p.actions) !== JSON.stringify(profile.actions) ||- getMessageInfo(p.profileUrl)?.count !== getMessageInfo(profile.profileUrl)?.count- );- });- };-const allProfiles = data ? [- ...data.visitedProfiles.map((p: any, i: number) => ({ ...p, status: 'visited', originalIndex: i })),- ...data.toVisitProfiles.map((p: any, i: number) => ({ ...p, status: 'to visit', originalIndex: i + data.visitedProfiles.length }))+ ...data.visitedProfiles.map((p: ProfileData, i: number) => ({ ...p, status: 'visited' as const, originalIndex: i })),+ ...data.toVisitProfiles.map((p: ProfileData, i: number) => ({ ...p, status: 'to visit' as const, originalIndex: i + data.visitedProfiles.length }))] : [];const sortedProfiles = sortProfiles(allProfiles);@@ -205,7 +215,7 @@ export default function StateViewer({ defaultOpen = true }: StateViewerProps) {}};- const hasFieldUpdated = (profile: any, field: string) => {+ const hasFieldUpdated = (profile: ProfileData, field: string) => {const previous = previousProfilesRef.current.find(p => p.profileUrl === profile.profileUrl);if (!previous) return false;@@ -323,7 +333,7 @@ export default function StateViewer({ defaultOpen = true }: StateViewerProps) {</thead><tbody><AnimatePresence mode="popLayout">- {sortedProfiles.map((profile: any) => {+ {sortedProfiles.map((profile: ProfileData) => {const messageInfo = getMessageInfo(profile.profileUrl);const isNew = !previousProfilesRef.current.find(p => p.profileUrl === profile.profileUrl);diff --git a/pipes/linkedin-ai-assistant/components/template-editor.tsx b/pipes/linkedin-ai-assistant/components/template-editor.tsxnew file mode 100644index 000000000..bf03554e9--- /dev/null+++ b/pipes/linkedin-ai-assistant/components/template-editor.tsx@@ -0,0 +1,61 @@+"use client";++import { useState } from "react";++interface Template {+ 'paste-here-url-from-linkedin-with-2nd-grade-connections': string;+ 'request-for-intro-prompt-to-ai': string;+ 'llm-appraisal-prompt': string;+ 'llm-user-reply-needs-response-prompt': string;+}++interface TemplateEditorProps {+ initialTemplate: Template;+ defaultOpen?: boolean;+}++export default function TemplateEditor({ initialTemplate, defaultOpen = true }: TemplateEditorProps) {+ const [template, setTemplate] = useState(initialTemplate);++ const handleChange = (key: keyof Template, value: string) => {+ setTemplate(prev => ({+ ...prev,+ [key]: value+ }));+ };++ const handleSave = () => {+ try {+ console.log("Template saved:", template);+ // TODO: Implement save logic+ } catch (error) {+ console.error("error saving template:", error);+ }+ };++ return (+ <div className={`w-full max-w-7xl flex flex-col gap-6 ${defaultOpen ? '' : 'hidden'}`}>+ <h2 className="text-xl font-semibold">edit template</h2>+ <div className="flex flex-col gap-6">+ {Object.entries(template).map(([key, value]) => (+ <div key={key} className="flex flex-col gap-2">+ <label className="text-sm font-medium">{key.replace(/_/g, ' ')}</label>+ <textarea+ className="w-full min-h-[100px] p-4 border rounded-lg font-mono text-sm+ bg-white dark:bg-black text-black dark:text-white resize-vertical"+ value={value}+ onChange={(e) => handleChange(key as keyof Template, e.target.value)}+ placeholder={`Enter ${key}...`}+ />+ </div>+ ))}+ </div>+ <button+ className="px-4 py-2 bg-gray-800 text-white rounded hover:bg-gray-700 w-fit"+ onClick={handleSave}+ >+ save changes+ </button>+ </div>+ );+}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/components/ui/alert.tsx b/pipes/linkedin-ai-assistant/components/ui/alert.tsxsimilarity index 100%rename from pipes/linkedin_ai_assistant/components/ui/alert.tsxrename to pipes/linkedin-ai-assistant/components/ui/alert.tsxdiff --git a/pipes/linkedin_ai_assistant/components/ui/button.tsx b/pipes/linkedin-ai-assistant/components/ui/button.tsxsimilarity index 100%rename from pipes/linkedin_ai_assistant/components/ui/button.tsxrename to pipes/linkedin-ai-assistant/components/ui/button.tsxdiff --git a/pipes/linkedin_ai_assistant/components/ui/collapsible.tsx b/pipes/linkedin-ai-assistant/components/ui/collapsible.tsxsimilarity index 100%rename from pipes/linkedin_ai_assistant/components/ui/collapsible.tsxrename to pipes/linkedin-ai-assistant/components/ui/collapsible.tsxdiff --git a/pipes/linkedin-ai-assistant/components/ui/hover-card.tsx b/pipes/linkedin-ai-assistant/components/ui/hover-card.tsxnew file mode 100644index 000000000..e54d91cf8--- /dev/null+++ b/pipes/linkedin-ai-assistant/components/ui/hover-card.tsx@@ -0,0 +1,29 @@+"use client"++import * as React from "react"+import * as HoverCardPrimitive from "@radix-ui/react-hover-card"++import { cn } from "@/lib/utils"++const HoverCard = HoverCardPrimitive.Root++const HoverCardTrigger = HoverCardPrimitive.Trigger++const HoverCardContent = React.forwardRef<+ React.ElementRef<typeof HoverCardPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>+>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (+ <HoverCardPrimitive.Content+ ref={ref}+ align={align}+ sideOffset={sideOffset}+ className={cn(+ "z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className+ )}+ {...props}+ />+))+HoverCardContent.displayName = HoverCardPrimitive.Content.displayName++export { HoverCard, HoverCardTrigger, HoverCardContent }diff --git a/pipes/linkedin_ai_assistant/components/ui/switch.tsx b/pipes/linkedin-ai-assistant/components/ui/switch.tsxsimilarity index 100%rename from pipes/linkedin_ai_assistant/components/ui/switch.tsxrename to pipes/linkedin-ai-assistant/components/ui/switch.tsxdiff --git a/pipes/linkedin-ai-assistant/components/ui/tooltip.tsx b/pipes/linkedin-ai-assistant/components/ui/tooltip.tsxnew file mode 100644index 000000000..a66b3f220--- /dev/null+++ b/pipes/linkedin-ai-assistant/components/ui/tooltip.tsx@@ -0,0 +1,32 @@+"use client"++import * as React from "react"+import * as TooltipPrimitive from "@radix-ui/react-tooltip"++import { cn } from "@/lib/utils"++const TooltipProvider = TooltipPrimitive.Provider++const Tooltip = TooltipPrimitive.Root++const TooltipTrigger = TooltipPrimitive.Trigger++const TooltipContent = React.forwardRef<+ React.ElementRef<typeof TooltipPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>+>(({ className, sideOffset = 4, ...props }, ref) => (+ <TooltipPrimitive.Portal>+ <TooltipPrimitive.Content+ ref={ref}+ sideOffset={sideOffset}+ className={cn(+ "z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className+ )}+ {...props}+ />+ </TooltipPrimitive.Portal>+))+TooltipContent.displayName = TooltipPrimitive.Content.displayName++export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }diff --git a/pipes/linkedin-ai-assistant/lib/browser-setup.ts b/pipes/linkedin-ai-assistant/lib/browser-setup.tsnew file mode 100644index 000000000..b78ae69e8--- /dev/null+++ b/pipes/linkedin-ai-assistant/lib/browser-setup.ts@@ -0,0 +1,73 @@+import puppeteer, { Browser, Page } from 'puppeteer-core';++let activeBrowser: Browser | null = null;+let activePage: Page | null = null;++export async function setupBrowser(): Promise<{ browser: Browser; page: Page }> {+ if (!activeBrowser) {+ let retries = 5;+ let lastError;++ while (retries > 0) {+ try {+ const response = await fetch('http://127.0.0.1:9222/json/version');+ if (!response.ok) {+ throw new Error('failed to get fresh websocket url');+ }+ const data = await response.json() as { webSocketDebuggerUrl: string };+ const freshWsUrl = data.webSocketDebuggerUrl.replace('ws://localhost:', 'ws://127.0.0.1:');++ console.log('attempting connection with fresh ws url:', freshWsUrl);++ activeBrowser = await puppeteer.connect({+ browserWSEndpoint: freshWsUrl,+ defaultViewport: null,+ });++ console.log('browser connected to:', freshWsUrl);++ const pages = await activeBrowser.pages();+ if (!pages.length) {+ throw new Error('no pages available');+ }+ activePage = pages[0];+ console.log('got active page');+ break;+ } catch (error) {+ lastError = error;+ console.error(`connection attempt ${6 - retries} failed:`, error);+ retries--;+ if (retries > 0) {+ await new Promise(resolve => setTimeout(resolve, 2000));+ }+ }+ }++ if (!activeBrowser) {+ throw new Error(`failed to connect to browser after 5 attempts: ${lastError}`);+ }+ }++ if (!activeBrowser || !activePage) {+ throw new Error('browser or page not initialized');+ }++ return { browser: activeBrowser, page: activePage };+}++export function getActiveBrowser() {+ return { browser: activeBrowser, page: activePage };+}++export async function quitBrowser() {+ if (activeBrowser) {+ try {+ await activeBrowser.disconnect();+ } catch (error) {+ console.error('error disconnecting browser:', error);+ }+ activeBrowser = null;+ activePage = null;+ console.log('browser session cleared');+ }+}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/lib/logic_sequence/check_messages.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-messages.tssimilarity index 84%rename from pipes/linkedin_ai_assistant/lib/logic_sequence/check_messages.tsrename to pipes/linkedin-ai-assistant/lib/logic-sequence/check-messages.tsindex dcd09f661..b1f17930f 100644--- a/pipes/linkedin_ai_assistant/lib/logic_sequence/check_messages.ts+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-messages.ts@@ -1,18 +1,16 @@-import { setupBrowser } from '../browser_setup';-import { getMessages } from '../simple_actions/extract_messages';+import { setupBrowser } from '../browser-setup';+import { getMessages } from '../simple-actions/extract-messages';import { loadState, saveMessages } from '../storage/storage';-import { closeAllMessageDialogues } from '../simple_actions/close_dialogues';-import { clickFirstMessageButton } from '../simple_actions/click_message';-import { checkIfConnected } from '../simple_actions/check_if_connected';--const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';+import { closeAllMessageDialogues } from '../simple-actions/close-dialogues';+import { clickFirstMessageButton } from '../simple-actions/click-message';+import { checkIfConnected } from '../simple-actions/check-if-connected';export async function checkAllMessages() {console.log('starting message check automation...');const state = await loadState();// Check Chrome connection- const statusResponse = await fetch(`${BASE_URL}/api/chrome/status`);+ const statusResponse = await fetch('/api/chrome/status');const statusData = await statusResponse.json();if (statusData.status !== 'connected' || !statusData.wsUrl) {@@ -20,7 +18,7 @@ export async function checkAllMessages() {}// Setup browser- const { browser, page } = await setupBrowser(statusData.wsUrl);+ const { browser, page } = await setupBrowser();try {// Get all profiles (both visited and to visit)diff --git a/pipes/linkedin_ai_assistant/lib/logic_sequence/harvest_connections.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.tssimilarity index 73%rename from pipes/linkedin_ai_assistant/lib/logic_sequence/harvest_connections.tsrename to pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.tsindex b33e926c1..c043a2069 100644--- a/pipes/linkedin_ai_assistant/lib/logic_sequence/harvest_connections.ts+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.ts@@ -1,3 +1,5 @@+/* eslint-disable @typescript-eslint/no-unused-vars */+import { Page } from 'puppeteer-core';import {loadConnections,@@ -6,14 +8,15 @@ import {saveHarvestingState,updateConnectionsSent,} from '../storage/storage';-import { setupBrowser } from '../browser_setup';+import { setupBrowser } from '../browser-setup';import { updateWorkflowStep } from '../../app/api/workflow/status/state';import { EventEmitter } from 'events';-import { closeAllMessageDialogues } from '../simple_actions/close_dialogues';-import { cleanProfileUrl } from '../simple_actions/extract_profiles_from_search_results';-import { showClickAnimation } from '../simple_actions/click_animation';+import { closeAllMessageDialogues } from '../simple-actions/close-dialogues';+import { cleanProfileUrl } from '../simple-actions/extract-profiles-from-search-results';+import { showClickAnimation } from '../simple-actions/click-animation';-const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';+const port = process.env.PORT!;+const BASE_URL = `http://127.0.0.1:${port}`;// Global harvesting state using an EventEmitterconst harvestingState = new EventEmitter();@@ -29,8 +32,10 @@ const cooldownProfiles = new Set<string>();export function stopHarvesting() {stopRequested = true;harvestingState.emit('stop');- saveHarvestingState(false).catch(console.error);- updateConnectionsSent(0).catch(console.error);+ // Ensure we clean up state+ attemptedProfiles.clear();+ emailVerificationProfiles.clear();+ cooldownProfiles.clear();}export interface HarvestStatus {@@ -39,48 +44,91 @@ export interface HarvestStatus {dailyLimitReached: boolean;nextHarvestTime?: string;stopped?: boolean;+ isHarvesting?: boolean;}export function emitProgress(connectionsSent: number) {harvestingState.emit('progress', connectionsSent);}+export async function isHarvesting(): Promise<boolean> {+ const store = await loadConnections();+ return !!store.isHarvesting;+}+export async function startHarvesting(maxDailyConnections: number = 35): Promise<HarvestStatus> {- console.log(- 'starting harvest process with max daily connections:',- maxDailyConnections- );-- // Reset the stop request flag at the beginning of the process+ // Reset stop flag at startstopRequested = false;- const connections = await loadConnections();- console.log('initial connections state:', connections);-- // Set harvesting state to true immediately- await saveHarvestingState(true);+ // Add early check for existing harvesting state+ const isCurrentlyHarvesting = await isHarvesting();+ if (isCurrentlyHarvesting) {+ console.log('harvest already in progress');+ const connections = await loadConnections();+ return {+ connectionsSent: connections.connectionsSent || 0,+ weeklyLimitReached: false,+ dailyLimitReached: false,+ isHarvesting: true+ };+ }- if (connections.nextHarvestTime) {- const nextTime = new Date(connections.nextHarvestTime);- console.log('checking next harvest time:', nextTime);- if (nextTime > new Date()) {+ // Initialize status variables at the start+ let connectionsSent = 0;+ let weeklyLimitReached = false;+ const dailyLimitReached = false;++ // Add mutex-like check at the start+ if (await isHarvesting()) {+ const store = await loadConnections();+ if (store.connectionsSent >= maxDailyConnections) {+ const nextTime = new Date(Date.now() + 86400000).toISOString();+ await saveNextHarvestTime(nextTime);+ await saveHarvestingState(false);return {- connectionsSent: 0,+ connectionsSent: store.connectionsSent,weeklyLimitReached: false,- dailyLimitReached: false,- nextHarvestTime: connections.nextHarvestTime,+ dailyLimitReached: true,+ nextHarvestTime: nextTime,+ isHarvesting: false};}+ const connections = await loadConnections();+ return {+ connectionsSent: connections.connectionsSent || 0,+ weeklyLimitReached,+ dailyLimitReached,+ isHarvesting: true+ };}- let connectionsSent = 0;- await updateConnectionsSent(connectionsSent);- let weeklyLimitReached = false;+ // Set harvesting state to true immediately+ await saveHarvestingState(true);+ await updateConnectionsSent(0);try {- console.log('Starting harvesting process');+ // Reset the stop request flag+ stopRequested = false;+ const connections = await loadConnections();++ // Check cooldown period+ if (connections.nextHarvestTime) {+ const nextTime = new Date(connections.nextHarvestTime);+ if (nextTime > new Date()) {+ return {+ connectionsSent: 0,+ weeklyLimitReached,+ dailyLimitReached,+ nextHarvestTime: connections.nextHarvestTime,+ };+ }+ }++ console.log('starting harvest process with max daily connections:', maxDailyConnections);++ await saveNextHarvestTime('');// Load existing connectionsupdateWorkflowStep('setup', 'done', 'connections loaded');@@ -94,7 +142,7 @@ export async function startHarvesting(throw new Error('chrome not connected');}- const { page } = await setupBrowser(statusData.wsUrl);+ const { page } = await setupBrowser();updateWorkflowStep('browser', 'done', 'browser connected');// Navigate to LinkedIn search results@@ -184,10 +232,8 @@ export async function startHarvesting(// Add random delay between connectionsconst delay = 3000 + Math.floor(Math.random() * 1000);await new Promise((resolve) => setTimeout(resolve, delay));-- if (stopRequested) {- break;- }++ continue; // Continue the loop instead of returning} else if (result.weeklyLimitReached) {console.log('Weekly limit reached, stopping');weeklyLimitReached = true;@@ -267,16 +313,18 @@ export async function startHarvesting(}if (connectionsSent >= maxDailyConnections) {- // Daily limit reached, set next time and keep harvesting state+ // Daily limit reached, set next time but keep harvesting trueconst nextTime = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();await saveNextHarvestTime(nextTime);+ // Don't set harvesting to false herereturn {connectionsSent,weeklyLimitReached: false,dailyLimitReached: true,nextHarvestTime: nextTime,+ isHarvesting: true // Keep harvesting true during cooldown};}@@ -287,18 +335,22 @@ export async function startHarvesting(};}-// Function to click the next connect button-async function clickNextConnectButton(- page: Page,- stopRequested: boolean-): Promise<{+// Add this interface near the top with other interfaces+interface ConnectionResult {success: boolean;profileUrl?: string;+ nextProfileTime?: number;weeklyLimitReached?: boolean;emailRequired?: boolean;cooldown?: boolean;cooldownUntil?: string;-}> {+}++// Update the function signature+async function clickNextConnectButton(+ page: Page,+ stopRequested: boolean+): Promise<ConnectionResult> {try {// Load existing connections firstconst { connections } = await loadConnections();@@ -307,21 +359,95 @@ async function clickNextConnectButton('button[aria-label^="Invite"][aria-label$="to connect"]';const connectButtons = await page.$$(connectButtonSelector);+ // Add logging for found buttons+ console.log(`found ${connectButtons.length} connect buttons`);++ // Log page structure+ await page.evaluate(() => {+ const searchResults = document.querySelector('.reusable-search__entity-result-list');+ console.log('search results html:', searchResults?.outerHTML);++ // Log all connect buttons found+ const buttons = document.querySelectorAll('button[aria-label*="Invite"][aria-label*="connect"]');+ console.log('all connect buttons found:', Array.from(buttons).map(b => ({+ ariaLabel: b.getAttribute('aria-label'),+ text: b.textContent?.trim(),+ html: b.outerHTML,+ // Log parent structure+ parentStructure: {+ immediate: b.parentElement?.className,+ entityResult: b.closest('.entity-result__item')?.className,+ linkedArea: b.closest('.linked-area')?.className,+ // Get all parent classes up to 3 levels+ parents: Array.from({ length: 3 }).map((_, i) => {+ let parent = b;+ for (let j = 0; j <= i; j++) {+ parent = parent.parentElement as Element;+ }+ return parent?.className;+ })+ }+ })));++ // Log all profile links in the page+ const profileLinks = document.querySelectorAll('a[href*="/in/"]');+ console.log('all profile links found:', Array.from(profileLinks).map(a => ({+ href: a.getAttribute('href'),+ text: a.textContent?.trim(),+ parentClass: a.parentElement?.className,+ closestEntityResult: a.closest('.entity-result__item')?.className+ })));+ });+for (const connectButton of connectButtons) {if (stopRequested) {return { success: false };}- const profileUrl = await page.evaluate((button) => {- const container = button.closest('.linked-area');- if (!container) return null;- const profileLink = container.querySelector(- 'a.EvQUJBaxIRgFetdTQjAXvpGhCNvVbYEbE'- );- return profileLink?.getAttribute('href') || null;+ const profileUrl = await page.evaluate((button: HTMLElement) => {+ let current: HTMLElement = button;+ let container: HTMLElement | null = null;++ for (let i = 0; i < 5 && current.parentElement; i++) {+ current = current.parentElement as HTMLElement;+ if (current.querySelector('a[href*="/in/"]')) {+ container = current;+ break;+ }+ }++ if (!container) {+ console.log('no container with profile link found');+ return null;+ }++ const profileLinks = container.querySelectorAll('a[href*="/in/"]');+ return profileLinks[0]?.getAttribute('href') || null;}, connectButton);if (!profileUrl) {+ console.log('profile url extraction failed:', {+ buttonExists: !!connectButton,+ buttonHtml: await connectButton.evaluate(el => el.outerHTML),+ // Log the structure for debugging+ structure: await connectButton.evaluate(el => {+ let current = el as HTMLElement;+ const path = [];+ for (let i = 0; i < 5 && current.parentElement; i++) {+ current = current.parentElement as HTMLElement;+ path.push({+ tag: current.tagName,+ hasProfileLink: !!current.querySelector('a[href*="/in/"]'),+ linkCount: current.querySelectorAll('a[href*="/in/"]').length,+ allLinks: Array.from(current.querySelectorAll('a')).map(a => ({+ href: a.getAttribute('href'),+ text: a.textContent?.trim()+ }))+ });+ }+ return path;+ })+ });console.log('could not find profile url, trying next button');continue;}@@ -387,7 +513,7 @@ async function clickNextConnectButton(continue;}}- } catch (e) {+ } catch (_) {// No error toast appeared; proceed}@@ -419,7 +545,7 @@ async function clickNextConnectButton(emailRequired: true,};}- } catch (e) {+ } catch (_) {// No email verification modal appeared}@@ -473,7 +599,7 @@ async function clickNextConnectButton(continue;}}- } catch (e) {+ } catch (_) {// No error toast; connection was successful}@@ -498,7 +624,7 @@ async function clickNextConnectButton(console.log('clicked got it button');return { success: false, weeklyLimitReached: true };}- } catch {+ } catch (_) {// No weekly limit modal; proceed}@@ -648,8 +774,7 @@ export async function navigateToSearch();console.log('page loaded despite navigation abort');return;- } catch (waitError) {- // If we can't find the elements, then rethrow the original error+ } catch (_) {throw error;}}diff --git a/pipes/linkedin_ai_assistant/lib/logic_sequence/intro_requester.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/intro-requester.tssimilarity index 85%rename from pipes/linkedin_ai_assistant/lib/logic_sequence/intro_requester.tsrename to pipes/linkedin-ai-assistant/lib/logic-sequence/intro-requester.tsindex f852321a0..53eb3dc26 100644--- a/pipes/linkedin_ai_assistant/lib/logic_sequence/intro_requester.ts+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/intro-requester.ts@@ -1,14 +1,13 @@-import fs from 'fs/promises';-import { extractProfileElements } from '../simple_actions/extract_profiles_from_search_results';-import { navigateToSearch } from '../simple_actions/go_to_search_results';+import { extractProfileElements } from '../simple-actions/extract-profiles-from-search-results';+import { navigateToSearch } from '../simple-actions/go-to-search-results';import templates from '../storage/templates.json';-import { setupBrowser } from '../browser_setup';-import { ProfileDetails, ProfileVisit, State, ProfileElement } from '../storage/types';-import { extractProfileText } from '../simple_actions/extract_profile_details_from_page';-import { clickMutualConnections } from '../simple_actions/click_mutual_connection';-import { clickFirstMessageButton } from '../simple_actions/click_message';-import { clickFirstProfile } from '../simple_actions/click_first_profile_in_the_list';-import { getMessages } from '../simple_actions/extract_messages';+import { setupBrowser } from '../browser-setup';+import type { ProfileVisit, ProfileElement } from '../storage/types';+import { extractProfileText } from '../simple-actions/extract-profile-details-from-page';+import { clickMutualConnections } from '../simple-actions/click-mutual-connection';+import { clickFirstMessageButton } from '../simple-actions/click-message';+import { clickFirstProfile } from '../simple-actions/click-first-profile-in-the-list';+import { getMessages } from '../simple-actions/extract-messages';import {loadState,updateOrAddProfileVisit,@@ -18,16 +17,14 @@ import {saveState,saveProfile} from '../storage/storage';-import { callGPT4 } from '../simple_actions/llm_call';-import { writeMessage } from '../simple_actions/write_message';-import { clickSend } from '../simple_actions/click_send';-import { cleanProfileUrl } from '../simple_actions/extract_profiles_from_search_results';-import { closeAllMessageDialogues } from '../simple_actions/close_dialogues';-import { hasRecentMessages } from '../simple_actions/check_recent_messages';+import { callGPT4 } from '../simple-actions/llm-call';+import { writeMessage } from '../simple-actions/write-message';+import { clickSend } from '../simple-actions/click-send';+import { cleanProfileUrl } from '../simple-actions/extract-profiles-from-search-results';+import { closeAllMessageDialogues } from '../simple-actions/close-dialogues';+import { hasRecentMessages } from '../simple-actions/check-recent-messages';import { setRunningState, updateWorkflowStep, updateQueueStats } from '../../app/api/workflow/status/state';-const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';-export async function startAutomation(maxProfiles: number = Infinity) {try {setRunningState(true);@@ -38,7 +35,7 @@ export async function startAutomation(maxProfiles: number = Infinity) {// Chrome setupupdateWorkflowStep('browser', 'running', 'connecting to chrome');- const statusResponse = await fetch(`${BASE_URL}/api/chrome/status`);+ const statusResponse = await fetch(`/api/chrome/status`);const statusData = await statusResponse.json();if (statusData.status !== 'connected' || !statusData.wsUrl) {@@ -46,12 +43,12 @@ export async function startAutomation(maxProfiles: number = Infinity) {}// Use the shared browser setup- const { browser, page } = await setupBrowser(statusData.wsUrl);+ const { page } = await setupBrowser();updateWorkflowStep('browser', 'done', 'browser connected');// NavigationupdateWorkflowStep('navigation', 'running', 'navigating to linkedin search');- await navigateToSearch(page, templates.paste_here_url_from_linkedin_with_2nd_grade_connections, { allowTruncate: true });+ await navigateToSearch(page, templates['paste-here-url-from-linkedin-with-2nd-grade-connections'], { allowTruncate: true });updateWorkflowStep('navigation', 'done');// Close any open dialogues before proceeding@@ -162,7 +159,7 @@ export async function startAutomation(maxProfiles: number = Infinity) {// Call LLM even when recent messages existconst llmResponse = await callGPT4(`Profile details: ${JSON.stringify(newProfileDetails)}- ${templates.llm_appraisal_prompt}`+ ${templates['llm-appraisal-prompt']}`);console.log('llm response:', JSON.stringify(llmResponse.content).slice(0, 100) + '...');@@ -193,7 +190,7 @@ export async function startAutomation(maxProfiles: number = Infinity) {// Call LLMconst llmResponse = await callGPT4(`Profile details: ${JSON.stringify(newProfileDetails)}- ${templates.llm_appraisal_prompt}`+ ${templates['llm-appraisal-prompt']}`);console.log('llm response:', JSON.stringify(llmResponse.content).slice(0, 100) + '...');@@ -220,7 +217,7 @@ export async function startAutomation(maxProfiles: number = Infinity) {await scheduleMessage(state,newProfileUrl,- templates.request_for_intro_prompt_to_AI.replace('${fullName}', profileDetails.name || 'your connection'),+ templates['request-for-intro-prompt-to-ai'].replace('${fullName}', profileDetails.name || 'your connection'),'replied to previous message');diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/browser_setup.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/browser-setup.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/browser_setup.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/browser-setup.tsdiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/check_if_connected.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/check-if-connected.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/check_if_connected.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/check-if-connected.tsdiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/check_recent_messages.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/check-recent-messages.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/check_recent_messages.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/check-recent-messages.tsdiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/click_animation.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/click-animation.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/click_animation.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/click-animation.tsdiff --git a/pipes/linkedin-ai-assistant/lib/simple-actions/click-cancel-connection-request.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/click-cancel-connection-request.tsnew file mode 100644index 000000000..51feb5c18--- /dev/null+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/click-cancel-connection-request.ts@@ -0,0 +1,168 @@+/* eslint-disable @typescript-eslint/no-unused-vars */++import { Page, ElementHandle } from 'puppeteer-core';+import { showClickAnimation } from './click-animation';++const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));++// this function attempts to click the "pending" button to cancel a connection request+// then it checks for a "connect" button to verify that the request was indeed canceled+export async function clickCancelConnectionRequest(page: Page): Promise<{+ success: boolean;+ profileUrl?: string;+}> {+ try {+ // 1) We'll locate any "artdeco-button--muted.artdeco-button--secondary" button,+ // then filter by innerText === "Pending". This removes the need for :has() syntax.+ const selector = 'button.artdeco-button--muted.artdeco-button--secondary';++ // 2) Wait for at least one muted+secondary button to appear+ // (in case the page hasn't fully loaded).+ await page.waitForSelector(selector, { timeout: 5000 });++ // 3) Evaluate in the DOM to find the button whose text is exactly "Pending"+ const foundButton = await page.evaluateHandle((sel) => {+ const buttons = document.querySelectorAll<HTMLButtonElement>(sel);+ console.log(`found ${buttons.length} muted secondary buttons`); // debug+ for (const btn of buttons) {+ // Check both direct text and text within span+ const buttonText = btn.innerText.trim();+ const spanText = btn.querySelector('span.artdeco-button__text')?.textContent?.trim();+ console.log(`button text: "${buttonText}", span text: "${spanText}"`); // debug+ if (buttonText === 'Pending' || spanText === 'Pending') {+ return btn;+ }+ }+ return null;+ }, selector) as ElementHandle<HTMLButtonElement>;++ if (!foundButton) {+ console.log('no pending connection request found after filtering by text');+ return { success: false };+ }++ // Validate that the button exists before trying to interact+ const isButtonAttached = await foundButton.evaluate(btn => {+ return btn instanceof HTMLButtonElement;+ });++ if (!isButtonAttached) {+ console.log('pending button not found, checking for connect button...');++ // wait longer and retry multiple times+ for (let i = 0; i < 3; i++) {+ await delay(1000); // wait 1s between attempts++ // wait for any button to appear+ await page.waitForSelector('button.artdeco-button', { timeout: 5000 });++ const connectButton = await page.evaluateHandle((attempt) => {+ const buttons = document.querySelectorAll<HTMLButtonElement>('button.artdeco-button');+ console.log(`attempt ${attempt + 1}: found ${buttons.length} buttons`); // debug+ for (const btn of buttons) {+ const buttonText = btn.innerText.trim();+ const spanText = btn.querySelector('span.artdeco-button__text')?.textContent?.trim();+ console.log(`checking button: text="${buttonText}", span="${spanText}"`); // debug+ if (buttonText === 'Connect' || spanText === 'Connect') {+ return btn;+ }+ }+ return null;+ }, i); // pass i as an argument++ const connectExists = connectButton+ ? await (connectButton as ElementHandle<HTMLButtonElement>).evaluate(btn => btn instanceof HTMLButtonElement)+ : false;++ if (connectExists) {+ console.log('found connect button - request was already cancelled');+ return { success: true };+ }++ console.log(`attempt ${i + 1}: connect button not found, will retry...`);+ }++ console.log('no connect button found after 3 attempts');+ return { success: false };+ }++ // 4) Try to scroll and click, with error handling+ try {+ await foundButton.evaluate((btn) => {+ btn.scrollIntoView({ block: 'center', behavior: 'instant' });+ });+ } catch (_) {+ console.log('could not scroll to button, trying to click anyway');+ // Continue execution - the button might still be clickable+ }++ // Optional: get a profile URL+ const profileUrl = await page.evaluate(() => {+ const linkSelectors = [+ 'a[href*="/in/"]',+ 'a[data-control-name="profile"]',+ 'a[href*="linkedin.com/in/"]'+ ];+ for (const sel of linkSelectors) {+ const el = document.querySelector<HTMLAnchorElement>(sel);+ if (el) return el.href;+ }+ return null;+ });++ // 5) Show animation and click+ await showClickAnimation(page, selector);+ await foundButton.evaluate(btn => btn.click());+ console.log('clicked the "pending" button');++ // 6) Wait for modal+ await delay(1000);+ console.log('waiting for withdraw modal...');+ const modalSelector = '.artdeco-modal[role="alertdialog"], div[role="alertdialog"]';+ await page.waitForSelector(modalSelector, { visible: true, timeout: 5000 });+ console.log('withdraw modal appeared');++ // 7) Withdraw button check+ const withdrawSelector = [+ 'button[data-test-dialog-primary-btn]',+ 'button.artdeco-button--primary'+ ].join(', ');+ await page.waitForSelector(withdrawSelector, { visible: true, timeout: 5000 });+ await showClickAnimation(page, withdrawSelector);+ await page.evaluate((sel) => {+ const btn = document.querySelector<HTMLButtonElement>(sel);+ if (btn) btn.click();+ }, withdrawSelector);+ console.log('clicked withdraw button');++ // 8) Wait for modal to disappear+ await page.waitForFunction(+ (s) => !document.querySelector(s),+ { timeout: 5000 },+ modalSelector+ );+ console.log('withdraw modal disappeared, request canceled!');++ // double check if "connect" is now visible to confirm+ try {+ // wait up to 5s for connect+ await page.waitForFunction(() => {+ const cBtn = document.querySelector<HTMLButtonElement>('button.artdeco-button');+ if (!cBtn) return false;+ const text = cBtn.innerText.trim();+ const spanTxt = cBtn.querySelector('span.artdeco-button__text')?.textContent?.trim();+ return text === 'Connect' || spanTxt === 'Connect';+ }, { timeout: 5000 });++ console.log('confirmed "connect" button is present now');+ return { success: true, profileUrl: profileUrl || undefined };+ } catch {+ // no connect found, but we tried+ console.log('no connect button recognized, but request was canceled anyway');+ return { success: true, profileUrl: profileUrl || undefined };+ }+ } catch (e) {+ console.error('failed to cancel connection request:', e);+ return { success: false };+ }+}diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/click_first_profile_in_the_list.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/click-first-profile-in-the-list.tssimilarity index 93%rename from pipes/linkedin_ai_assistant/lib/simple_actions/click_first_profile_in_the_list.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/click-first-profile-in-the-list.tsindex d0fe9e49b..8650d5d14 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/click_first_profile_in_the_list.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/click-first-profile-in-the-list.ts@@ -1,5 +1,5 @@import { Page } from 'puppeteer-core';-import { showClickAnimation } from './click_animation';+import { showClickAnimation } from './click-animation';export async function clickFirstProfile(page: Page) {try {diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/click_message.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/click-message.tssimilarity index 96%rename from pipes/linkedin_ai_assistant/lib/simple_actions/click_message.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/click-message.tsindex 12eb6db65..7f0df7592 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/click_message.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/click-message.ts@@ -1,6 +1,5 @@import { Page } from 'puppeteer-core';-import { setupBrowser } from './browser_setup';-import { showClickAnimation } from './click_animation';+import { showClickAnimation } from './click-animation';export async function clickFirstMessageButton(page: Page) {try {diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/click_mutual_connection.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/click-mutual-connection.tssimilarity index 92%rename from pipes/linkedin_ai_assistant/lib/simple_actions/click_mutual_connection.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/click-mutual-connection.tsindex 37655ffd8..84f36cd20 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/click_mutual_connection.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/click-mutual-connection.ts@@ -1,5 +1,5 @@import { Page } from 'puppeteer-core';-import { showClickAnimation } from './click_animation';+import { showClickAnimation } from './click-animation';export async function clickMutualConnections(page: Page) {try {diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/click_profile_from_message.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/click-profile-from-message.tssimilarity index 92%rename from pipes/linkedin_ai_assistant/lib/simple_actions/click_profile_from_message.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/click-profile-from-message.tsindex f911dbd0f..1f41de298 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/click_profile_from_message.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/click-profile-from-message.ts@@ -1,5 +1,5 @@import { Page } from 'puppeteer-core';-import { showClickAnimation } from './click_animation';+import { showClickAnimation } from './click-animation';export async function clickProfileFromMessage(page: Page) {try {diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/click_send.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/click-send.tssimilarity index 91%rename from pipes/linkedin_ai_assistant/lib/simple_actions/click_send.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/click-send.tsindex f8ac1d134..3e83f7f24 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/click_send.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/click-send.ts@@ -1,5 +1,5 @@import { Page } from 'puppeteer-core';-import { showClickAnimation } from './click_animation';+import { showClickAnimation } from './click-animation';export async function clickSend(page: Page) {try {diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/close_dialogues.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/close-dialogues.tssimilarity index 97%rename from pipes/linkedin_ai_assistant/lib/simple_actions/close_dialogues.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/close-dialogues.tsindex c59a4005d..af73b19cc 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/close_dialogues.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/close-dialogues.ts@@ -1,5 +1,5 @@import { Page } from 'puppeteer-core';-import { showClickAnimation } from './click_animation';+import { showClickAnimation } from './click-animation';export async function closeAllMessageDialogues(page: Page) {try {diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/extract_messages.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/extract-messages.tssimilarity index 86%rename from pipes/linkedin_ai_assistant/lib/simple_actions/extract_messages.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/extract-messages.tsindex e9c5ce120..3c487e275 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/extract_messages.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/extract-messages.ts@@ -1,6 +1,6 @@import { Page } from 'puppeteer-core';import { Message } from '../storage/types';-import { standardizeTimestamps } from './standardize_timestamp_in_messages';+import { standardizeTimestamps } from './standardize-timestamp-in-messages';export async function getMessages(page: Page): Promise<Message[]> {try {@@ -83,19 +83,22 @@ export async function getMessages(page: Page): Promise<Message[]> {// test the functionsif (require.main === module) {- async function test() {+ const test = async () => {try {- const { setupBrowser } = require('./browser_setup');- const { browser, page } = await setupBrowser();+ const { setupBrowser, getActiveBrowser } = await import('../browser-setup');+ await setupBrowser();+ const { browser, page } = getActiveBrowser();+ if (!page) throw new Error('no active page');+ if (!browser) throw new Error('no active browser');console.log('connected to browser');- const messages = await getMessages(page);+ await getMessages(page);await browser.disconnect();- } catch (e) {- console.error('test failed:', e);+ } catch (error) {+ console.error('test failed:', error);}- }+ };test();}diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/extract_profile_details_from_page.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/extract-profile-details-from-page.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/extract_profile_details_from_page.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/extract-profile-details-from-page.tsdiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/extract_profiles_from_search_results.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/extract-profiles-from-search-results.tssimilarity index 98%rename from pipes/linkedin_ai_assistant/lib/simple_actions/extract_profiles_from_search_results.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/extract-profiles-from-search-results.tsindex f5cfde1d2..cefd90c6e 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/extract_profiles_from_search_results.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/extract-profiles-from-search-results.ts@@ -1,6 +1,6 @@import { Page } from 'puppeteer-core';import { ProfileElement } from '../storage/types';-import { highlightElement } from './highlight_element';+import { highlightElement } from './highlight-element';export function cleanProfileUrl(url: string): string {return url.split('?')[0];diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/go_to_search_results.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/go-to-search-results.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/go_to_search_results.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/go-to-search-results.tsdiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/highlight_element.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/highlight-element.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/highlight_element.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/highlight-element.tsdiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/llm_call.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/llm-call.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/llm_call.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/llm-call.tsdiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/standardize_timestamp_in_messages.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/standardize-timestamp-in-messages.tssimilarity index 98%rename from pipes/linkedin_ai_assistant/lib/simple_actions/standardize_timestamp_in_messages.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/standardize-timestamp-in-messages.tsindex 7399e6f56..2a1e49c76 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/standardize_timestamp_in_messages.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/standardize-timestamp-in-messages.ts@@ -1,5 +1,5 @@import { Message } from '../storage/types';-import { addDays, format, parse, startOfToday } from 'date-fns';+import { addDays, format, startOfToday } from 'date-fns';export function standardizeTimestamps(messages: Message[]): Message[] {const today = startOfToday();diff --git a/pipes/linkedin-ai-assistant/lib/simple-actions/test-click-cancel-request.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/test-click-cancel-request.tsnew file mode 100644index 000000000..b48f05f80--- /dev/null+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/test-click-cancel-request.ts@@ -0,0 +1,29 @@+import { setupBrowser } from '../browser-setup';+import { clickCancelConnectionRequest } from './click-cancel-connection-request';++async function testCancelRequest() {+ try {+ // Replace with your actual WebSocket URL+ // const wsUrl = 'ws://127.0.0.1:9222/devtools/browser/eb8cd29f-cf02-43c1-a4f7-6368bd6c25de';++ const { browser, page } = await setupBrowser();+ console.log('connected to browser');++ // Test the cancel request functionality+ const result = await clickCancelConnectionRequest(page);+ console.log('cancel request test result:', result);++ // Wait a bit to see the results visually+ await new Promise(r => setTimeout(r, 2000));++ await browser.disconnect();+ console.log('browser disconnected');+ } catch (e) {+ console.error('test failed:', e);+ }+}++testCancelRequest();+++// visit http://localhost:9222/json/version to get websocket url code\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/test_click_message.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/test-click-message.tssimilarity index 66%rename from pipes/linkedin_ai_assistant/lib/simple_actions/test_click_message.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/test-click-message.tsindex 5d889ec0e..b726eed4f 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/test_click_message.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/test-click-message.ts@@ -1,12 +1,12 @@-import { setupBrowser } from '../browser_setup';-import { clickFirstMessageButton } from './click_message';+import { setupBrowser } from '../browser-setup';+import { clickFirstMessageButton } from './click-message';async function testClickMessage() {try {// Replace with your actual WebSocket URL- const wsUrl = 'ws://127.0.0.1:9222/devtools/browser/1f237598-603c-4e61-8fc1-f8a91a3340a7';+ // const wsUrl = 'ws://127.0.0.1:9222/devtools/browser/1f237598-603c-4e61-8fc1-f8a91a3340a7';- const { browser, page } = await setupBrowser(wsUrl);+ const { browser, page } = await setupBrowser();console.log('connected to browser');// Test the click message functionalitydiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/test_extract_messages.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/test-extract-messages.tssimilarity index 63%rename from pipes/linkedin_ai_assistant/lib/simple_actions/test_extract_messages.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/test-extract-messages.tsindex ad36c7b87..62fb61071 100644--- a/pipes/linkedin_ai_assistant/lib/simple_actions/test_extract_messages.ts+++ b/pipes/linkedin-ai-assistant/lib/simple-actions/test-extract-messages.ts@@ -1,12 +1,12 @@-import { setupBrowser } from '../browser_setup';-import { getMessages } from './extract_messages';+import { setupBrowser } from '../browser-setup';+import { getMessages } from './extract-messages';async function testExtractMessages() {try {// Replace with your actual WebSocket URL- const wsUrl = 'ws://127.0.0.1:9222/devtools/browser/72af91ce-8c00-4035-81bc-aa5d86846084';+ // const wsUrl = 'ws://127.0.0.1:9222/devtools/browser/72af91ce-8c00-4035-81bc-aa5d86846084';- const { browser, page } = await setupBrowser(wsUrl);+ const { browser, page } = await setupBrowser();console.log('connected to browser');// Extract messages using your existing functiondiff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/write_message.ts b/pipes/linkedin-ai-assistant/lib/simple-actions/write-message.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/simple_actions/write_message.tsrename to pipes/linkedin-ai-assistant/lib/simple-actions/write-message.tsdiff --git a/pipes/linkedin_ai_assistant/lib/storage/remove_duplicates.js b/pipes/linkedin-ai-assistant/lib/storage/remove-duplicates.tssimilarity index 60%rename from pipes/linkedin_ai_assistant/lib/storage/remove_duplicates.jsrename to pipes/linkedin-ai-assistant/lib/storage/remove-duplicates.tsindex 95f8137cb..13a569424 100644--- a/pipes/linkedin_ai_assistant/lib/storage/remove_duplicates.js+++ b/pipes/linkedin-ai-assistant/lib/storage/remove-duplicates.ts@@ -1,19 +1,23 @@-// remove_duplicates.js-const fs = require('fs');+import { readFileSync, writeFileSync } from 'fs';// Read the JSON file-const data = fs.readFileSync('./state.json', 'utf8');+const data = readFileSync('./state.json', 'utf8');const state = JSON.parse(data);+interface Profile {+ profileUrl: string;+ timestamp?: string;+ status?: string;+ actions?: Record<string, string>;+}+// Function to remove duplicates from an array based on 'profileUrl'-function removeDuplicates(profiles) {+function removeDuplicates(profiles: Profile[]) {const seen = new Set();return profiles.filter(profile => {if (seen.has(profile.profileUrl)) {- // Duplicate found, don't include in the new arrayreturn false;} else {- // First occurrence, include in the new arrayseen.add(profile.profileUrl);return true;}@@ -25,6 +29,6 @@ state.visitedProfiles = removeDuplicates(state.visitedProfiles);state.toVisitProfiles = removeDuplicates(state.toVisitProfiles);// Write the cleaned data back to the JSON file-fs.writeFileSync('./state.json', JSON.stringify(state, null, 2));+writeFileSync('./state.json', JSON.stringify(state, null, 2));-console.log('duplicates removed successfully.');\ No newline at end of file+console.log('duplicates removed successfully.');\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/lib/storage/storage.ts b/pipes/linkedin-ai-assistant/lib/storage/storage.tssimilarity index 90%rename from pipes/linkedin_ai_assistant/lib/storage/storage.tsrename to pipes/linkedin-ai-assistant/lib/storage/storage.tsindex d637638f2..a8ee82d97 100644--- a/pipes/linkedin_ai_assistant/lib/storage/storage.ts+++ b/pipes/linkedin-ai-assistant/lib/storage/storage.ts@@ -211,26 +211,28 @@ interface ConnectionsStore {connections: Record<string, Connection>;isHarvesting?: boolean;connectionsSent: number;+ lastRefreshDuration?: number; // in milliseconds+ averageProfileCheckDuration?: number; // in milliseconds}+type FileError = Error & { code?: string };+export async function loadConnections(): Promise<ConnectionsStore> {await ensureStorageDir();try {const data = await fs.readFile(path.join(STORAGE_DIR, 'connections.json'), 'utf-8');return JSON.parse(data);- } catch (error: any) {- if (error.code === 'ENOENT') {- // File does not exist, safe to return default empty object+ } catch (error: unknown) {+ const err = error as FileError;+ if (err.code === 'ENOENT') {return {connections: {},connectionsSent: 0,isHarvesting: false,};- } else {- // Parsing error or other read error, do not overwrite existing data- console.error('Failed to read or parse connections.json:', error);- throw new Error('Could not load connections data.');}+ console.error('Failed to read or parse connections.json:', err);+ throw new Error('Could not load connections data.');}}@@ -283,4 +285,16 @@ export async function updateConnectionsSent(connectionsSent: number) {JSON.stringify(connectionsStore, null, 2));console.log(`Updated connections sent count to ${connectionsSent}`);+}++export async function saveRefreshStats(totalDuration: number, profileCount: number) {+ const connectionsStore = await loadConnections();+ connectionsStore.lastRefreshDuration = totalDuration;+ connectionsStore.averageProfileCheckDuration = profileCount > 0 ? totalDuration / profileCount : undefined;++ await fs.writeFile(+ path.join(STORAGE_DIR, 'connections.json'),+ JSON.stringify(connectionsStore, null, 2)+ );+ console.log(`saved refresh stats: ${totalDuration}ms for ${profileCount} profiles`);}\ No newline at end of filediff --git a/pipes/linkedin-ai-assistant/lib/storage/templates.d.ts b/pipes/linkedin-ai-assistant/lib/storage/templates.d.tsnew file mode 100644index 000000000..28a0bd0d9--- /dev/null+++ b/pipes/linkedin-ai-assistant/lib/storage/templates.d.ts@@ -0,0 +1,11 @@+export interface Templates {+ 'paste-here-url-from-linkedin-with-2nd-grade-connections': string;+ 'request-for-intro-prompt-to-ai': string;+ 'llm-appraisal-prompt': string;+ 'llm-user-reply-needs-response-prompt': string;+}++declare module '*.json' {+ const value: Templates;+ export default value;+}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/lib/storage/templates.json b/pipes/linkedin-ai-assistant/lib/storage/templates.jsonsimilarity index 71%rename from pipes/linkedin_ai_assistant/lib/storage/templates.jsonrename to pipes/linkedin-ai-assistant/lib/storage/templates.jsonindex a9d28a4b6..68225ed41 100644--- a/pipes/linkedin_ai_assistant/lib/storage/templates.json+++ b/pipes/linkedin-ai-assistant/lib/storage/templates.json@@ -1,6 +1,6 @@{- "paste_here_url_from_linkedin_with_2nd_grade_connections": "",- "request_for_intro_prompt_to_AI": "I noticed that you are connected with ${fullName}. I'm currently working on this cool software https://screenpi.pe/#business that capture knowledge from employee computers and processes it with on-premise LLMs. Can you make an intro?",- "llm_appraisal_prompt": "give a one sentence summary that i can send back to this person with appraisal, make it sound like a message to a friend, make it less grandiose and more factual, make it even shorter. E.g. it can start with personal greeting",- "llm_user_reply_needs_response_prompt": "I'm asking my connections introductions, right now I received some new messages, do these messages require response or I can proceed with request for introduction, answer yes, no with percentage of confidence:\nfor example\nyes [80%]\nno [20%]\n\nmessage:\n${message}"+ "paste-here-url-from-linkedin-with-2nd-grade-connections": "",+ "request-for-intro-prompt-to-ai": "I noticed that you are connected with ${fullName}. I'm currently working on this cool software https://screenpi.pe/#business that capture knowledge from employee computers and processes it with on-premise LLMs. Can you make an intro?",+ "llm-appraisal-prompt": "give a one sentence summary that i can send back to this person with appraisal, make it sound like a message to a friend, make it less grandiose and more factual, make it even shorter. E.g. it can start with personal greeting",+ "llm-user-reply-needs-response-prompt": "I'm asking my connections introductions, right now I received some new messages, do these messages require response or I can proceed with request for introduction, answer yes, no with percentage of confidence:\nfor example\nyes [80%]\nno [20%]\n\nmessage:\n${message}"}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/lib/storage/types.ts b/pipes/linkedin-ai-assistant/lib/storage/types.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/storage/types.tsrename to pipes/linkedin-ai-assistant/lib/storage/types.tsdiff --git a/pipes/linkedin_ai_assistant/lib/utils.ts b/pipes/linkedin-ai-assistant/lib/utils.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/lib/utils.tsrename to pipes/linkedin-ai-assistant/lib/utils.tsdiff --git a/pipes/linkedin-ai-assistant/next.config.mjs b/pipes/linkedin-ai-assistant/next.config.mjsnew file mode 100644index 000000000..701676123--- /dev/null+++ b/pipes/linkedin-ai-assistant/next.config.mjs@@ -0,0 +1,25 @@+/** @type {import('next').NextConfig} */+const nextConfig = {+ images: {+ domains: ['screenpi.pe'],+ },+ experimental: {},+ logging: {+ fetches: {+ fullUrl: true,+ },+ },+ output: 'standalone',+ webpack: (config, { isServer }) => {+ if (isServer) {+ config.externals.push('child_process', 'node-fetch')+ }+ return config+ },+ server: {+ port: 13000,+ host: '127.0.0.1',+ },+};++export default nextConfig;diff --git a/pipes/linkedin_ai_assistant/package-lock.json b/pipes/linkedin-ai-assistant/package-lock.jsonsimilarity index 100%rename from pipes/linkedin_ai_assistant/package-lock.jsonrename to pipes/linkedin-ai-assistant/package-lock.jsondiff --git a/pipes/linkedin_ai_assistant/package.json b/pipes/linkedin-ai-assistant/package.jsonsimilarity index 93%rename from pipes/linkedin_ai_assistant/package.jsonrename to pipes/linkedin-ai-assistant/package.jsonindex 7556740d6..0987a3fe0 100644--- a/pipes/linkedin_ai_assistant/package.json+++ b/pipes/linkedin-ai-assistant/package.json@@ -11,10 +11,12 @@},"dependencies": {"@radix-ui/react-collapsible": "^1.1.1",+ "@radix-ui/react-hover-card": "^1.1.4","@radix-ui/react-slot": "^1.1.0","@radix-ui/react-switch": "^1.1.1",- "@screenpipe/js": "1.0.0",+ "@radix-ui/react-tooltip": "^1.1.6","@screenpipe/browser": "0.1.12",+ "@screenpipe/js": "1.0.0","@sentry/nextjs": "^8.42.0","@tauri-apps/api": "^2.1.1","chrome-launcher": "^1.1.2",diff --git a/pipes/linkedin_ai_assistant/postcss.config.mjs b/pipes/linkedin-ai-assistant/postcss.config.mjssimilarity index 100%rename from pipes/linkedin_ai_assistant/postcss.config.mjsrename to pipes/linkedin-ai-assistant/postcss.config.mjsdiff --git a/pipes/linkedin_ai_assistant/public/guide_bigger.gif b/pipes/linkedin-ai-assistant/public/guide_bigger.gifsimilarity index 100%rename from pipes/linkedin_ai_assistant/public/guide_bigger.gifrename to pipes/linkedin-ai-assistant/public/guide_bigger.gifdiff --git a/pipes/linkedin-ai-assistant/public/li_harvester.gif b/pipes/linkedin-ai-assistant/public/li_harvester.gifnew file mode 100644index 000000000..b2c8039ceBinary files /dev/null and b/pipes/linkedin-ai-assistant/public/li_harvester.gif differdiff --git a/pipes/linkedin_ai_assistant/tailwind.config.ts b/pipes/linkedin-ai-assistant/tailwind.config.tssimilarity index 100%rename from pipes/linkedin_ai_assistant/tailwind.config.tsrename to pipes/linkedin-ai-assistant/tailwind.config.tsdiff --git a/pipes/linkedin_ai_assistant/tsconfig.json b/pipes/linkedin-ai-assistant/tsconfig.jsonsimilarity index 100%rename from pipes/linkedin_ai_assistant/tsconfig.jsonrename to pipes/linkedin-ai-assistant/tsconfig.jsondiff --git a/pipes/linkedin_ai_assistant/README.md b/pipes/linkedin_ai_assistant/README.mddeleted file mode 100644index 2b3c8aaf0..000000000--- a/pipes/linkedin_ai_assistant/README.md+++ /dev/null@@ -1,34 +0,0 @@-This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).--## Getting Started--First, run the development server:--```bash-bun i--bun dev-```--Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.--You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.--This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.--## Learn More--To learn more about Next.js, take a look at the following resources:--- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.-- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.--You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!--## Deploy on screenpipe--The easiest way to deploy your Next.js pipe is to use the [screenpipe Platform](https://screenpi.pe).--Check out our [pipe deployment documentation](https://docs.screenpi.pe/docs/plugins) for more details.--diff --git a/pipes/linkedin_ai_assistant/app/api/chrome/route.ts b/pipes/linkedin_ai_assistant/app/api/chrome/route.tsdeleted file mode 100644index 797e86b47..000000000--- a/pipes/linkedin_ai_assistant/app/api/chrome/route.ts+++ /dev/null@@ -1,52 +0,0 @@-import { NextResponse } from 'next/server';-import { exec, spawn } from 'child_process';-import { promisify } from 'util';-import { quitBrowser } from '@/lib/browser_setup';-const execPromise = promisify(exec);--export async function POST() {- try {- console.log('attempting to launch chrome');-- // Kill any existing Chrome instances first- await quitChrome();- await quitBrowser();-- const chromePath = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';- const chromeLaunchCommand = `"${chromePath}" --remote-debugging-port=9222 --restore-last-session`;- const chromeProcess = spawn(chromeLaunchCommand, { detached: true, stdio: 'ignore' });-- chromeProcess.unref();-- // Give Chrome a moment to start- await new Promise(resolve => setTimeout(resolve, 1000));-- console.log('chrome launch initiated');- return NextResponse.json({ success: true });- } catch (error) {- console.error('failed to launch chrome:', error);- return NextResponse.json({ success: false, error: String(error) }, { status: 500 });- }-}--export async function DELETE() {- try {- await quitChrome();- await quitBrowser();- console.log('chrome process terminated');- return NextResponse.json({ success: true });- } catch (error) {- console.error('failed to kill chrome:', error);- return NextResponse.json({ success: false, error: String(error) }, { status: 500 });- }-}--async function quitChrome() {- const killCommand = `pkill -f -- "Google Chrome"`;- try {- await execPromise(killCommand);- console.log('chrome killed');- } catch (error) {- console.log('no chrome process found to kill', error);- }-}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/app/api/harvest/status/route.ts b/pipes/linkedin_ai_assistant/app/api/harvest/status/route.tsdeleted file mode 100644index 740a1fc78..000000000--- a/pipes/linkedin_ai_assistant/app/api/harvest/status/route.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextResponse } from 'next/server';-import { loadConnections } from '@/lib/storage/storage';--export async function GET() {- try {- const connectionsStore = await loadConnections();- return NextResponse.json({- isHarvesting: connectionsStore.isHarvesting || false,- nextHarvestTime: connectionsStore.nextHarvestTime,- connectionsSent: connectionsStore.connectionsSent || 0- });- } catch (error: any) {- return NextResponse.json({ message: error.message?.toLowerCase() }, { status: 500 });- }-}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/app/page.tsx b/pipes/linkedin_ai_assistant/app/page.tsxdeleted file mode 100644index 8108a9c4a..000000000--- a/pipes/linkedin_ai_assistant/app/page.tsx+++ /dev/null@@ -1,38 +0,0 @@-"use client";--import { useState } from "react";-import { LaunchLinkedInChromeSession } from "@/components/launch_linkedin_chrome_session";-import { IntroRequester } from "@/components/intro-requester";-import { ReloadButton } from "@/components/reload_button";-import { HarvestClosestConnections } from "@/components/harvest";--export default function Home() {- const [loginStatus, setLoginStatus] = useState<'checking' | 'logged_in' | 'logged_out' | null>(null);-- return (- <div className="min-h-screen w-full p-4 pb-20 sm:p-8">- <div className="space-y-1.5 mb-8">- <h1 className="text-2xl font-semibold tracking-tight">linkedin ai assistant</h1>- <p className="text-sm text-muted-foreground">automate your linkedin interactions with ai</p>- </div>-- <div className="flex flex-col gap-2 mb-8">- <ReloadButton />- <LaunchLinkedInChromeSession- loginStatus={loginStatus}- setLoginStatus={setLoginStatus}- />- </div>-- {loginStatus === 'logged_in' && (- <div className="w-full space-y-6">- <h2 className="text-2xl font-semibold mb-6">workflows</h2>- <div className="space-y-6 text-lg">- <HarvestClosestConnections />- <IntroRequester />- </div>- </div>- )}- </div>- );-}diff --git a/pipes/linkedin_ai_assistant/components/harvest.tsx b/pipes/linkedin_ai_assistant/components/harvest.tsxdeleted file mode 100644index 6b6dad9b8..000000000--- a/pipes/linkedin_ai_assistant/components/harvest.tsx+++ /dev/null@@ -1,152 +0,0 @@-"use client";--import { useState, useEffect } from "react";--export function HarvestClosestConnections() {- const [isRunning, setIsRunning] = useState(false);- const [status, setStatus] = useState("");- const [nextHarvestTime, setNextHarvestTime] = useState<string | null>(null);- const [connectionsSent, setConnectionsSent] = useState(0);- const [dailyLimitReached, setDailyLimitReached] = useState(false);- const [weeklyLimitReached, setWeeklyLimitReached] = useState(false);-- useEffect(() => {- // Update initial state- fetch("/api/harvest/status")- .then(res => res.json())- .then(data => {- setConnectionsSent(data.connectionsSent || 0);- setDailyLimitReached(data.dailyLimitReached || false);- setWeeklyLimitReached(data.weeklyLimitReached || false);- if (data.nextHarvestTime) {- setNextHarvestTime(data.nextHarvestTime);- if (new Date(data.nextHarvestTime) > new Date()) {- setStatus(`harvesting cooldown active until ${new Date(data.nextHarvestTime).toLocaleString()}`);- }- }- setIsRunning(data.isHarvesting || false);- })- .catch(console.error);- }, []);-- useEffect(() => {- if (isRunning) {- const interval = setInterval(() => {- fetch("/api/harvest/status")- .then(res => res.json())- .then(data => {- setConnectionsSent(data.connectionsSent || 0);- setDailyLimitReached(data.dailyLimitReached || false);- setWeeklyLimitReached(data.weeklyLimitReached || false);- if (data.nextHarvestTime) {- setNextHarvestTime(data.nextHarvestTime);- if (new Date(data.nextHarvestTime) > new Date()) {- setStatus(`harvesting cooldown active until ${new Date(data.nextHarvestTime).toLocaleString()}`);- }- }- if (!data.isHarvesting && isRunning) {- setIsRunning(false);- setStatus("harvest process stopped");- }- })- .catch(console.error);- }, 2000);-- return () => clearInterval(interval);- }- }, [isRunning]);-- const startHarvesting = async () => {- try {- setIsRunning(true);- setStatus("starting harvesting process...");-- const response = await fetch("/api/harvest/start", {- method: "POST",- });-- const data = await response.json();- console.log('harvest start response:', data);-- if (response.ok) {- setStatus(data.message?.toLowerCase() || 'unknown status');- setConnectionsSent(data.connectionsSent || 0);- setDailyLimitReached(data.dailyLimitReached || false);- setWeeklyLimitReached(data.weeklyLimitReached || false);- if (data.nextHarvestTime) {- setNextHarvestTime(data.nextHarvestTime);- }- } else {- // Handle 429 without stopping the workflow- if (response.status === 429) {- setNextHarvestTime(data.nextHarvestTime);- setStatus(data.message?.toLowerCase() || 'rate limit reached');- } else {- setStatus(`error: ${data.message?.toLowerCase() || 'unknown error'}`);- setIsRunning(false);- }- }- } catch (error: any) {- console.error("failed to start harvesting:", error);- setStatus(`error: ${error.message?.toLowerCase() || error.toString().toLowerCase()}`);- setIsRunning(false);- }- };-- const stopHarvesting = async () => {- try {- const response = await fetch("/api/harvest/stop", {- method: "POST",- });-- if (response.ok) {- setStatus("stopping harvest process...");- } else {- const data = await response.json();- setStatus(`error stopping: ${data.message?.toLowerCase() || 'unknown error'}`);- }- } catch (error: any) {- console.error("failed to stop harvesting:", error);- setStatus(`${error.message?.toLowerCase() || error.toString().toLowerCase()}`);- }- };-- return (- <div className="flex flex-row items-center gap-4">- <div className="flex items-center gap-4">- <span className="text-lg font-medium">- harvest connections {connectionsSent > 0 && `(${connectionsSent})`}- </span>- <div className="flex gap-2">- {!isRunning && (- <button- onClick={startHarvesting}- className="bg-black text-white px-4 py-2 rounded-md text-base"- >- start- </button>- )}- {isRunning && (- <button- onClick={stopHarvesting}- className="bg-red-600 text-white px-4 py-2 rounded-md text-base hover:bg-red-700"- >- stop- </button>- )}- </div>- </div>- {isRunning && status && (- <span className="text-sm text-gray-500">- {status}- </span>- )}- {(dailyLimitReached || weeklyLimitReached) && nextHarvestTime && (- <span className="text-sm text-gray-500">- {dailyLimitReached && `daily limit reached, next harvest at ${new Date(nextHarvestTime).toLocaleString()}`}- {weeklyLimitReached && `weekly limit reached, next harvest at ${new Date(nextHarvestTime).toLocaleString()}`}- </span>- )}- </div>- );-}diff --git a/pipes/linkedin_ai_assistant/components/keyword-cloud.tsx b/pipes/linkedin_ai_assistant/components/keyword-cloud.tsxdeleted file mode 100644index 73cce8259..000000000--- a/pipes/linkedin_ai_assistant/components/keyword-cloud.tsx+++ /dev/null@@ -1,122 +0,0 @@-"use client";--import React, { useEffect, useState } from "react";--interface KeywordCount {- word: string;- count: number;-}--interface ScreenpipeQueryParams {- content_type?: string;- start_time?: string;- end_time?: string;- limit?: number;-}--interface ContentItem {- type: "OCR" | "Audio";- content: {- text?: string;- transcription?: string;- };-}--export const KeywordCloud: React.FC = () => {- const [keywords, setKeywords] = useState<KeywordCount[]>([]);- const [isLoading, setIsLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- const processContentStreaming = async () => {- console.log("fetching keyword stats...");- const url = new URL("http://localhost:3030/raw_sql");-- const query = `- WITH RECURSIVE- split(word, str) AS (- SELECT '', content || ' '- FROM (- -- Get OCR text and audio from last 12h- SELECT text as content- FROM ocr_text ot- JOIN frames f ON ot.frame_id = f.id- WHERE datetime(timestamp) >= datetime('now', '-12 hours')- UNION ALL- SELECT transcription as content- FROM audio_transcriptions- WHERE datetime(timestamp) >= datetime('now', '-12 hours')- )- UNION ALL- SELECT- LOWER(SUBSTR(str, 0, INSTR(str, ' '))),- SUBSTR(str, INSTR(str, ' ')+1)- FROM split WHERE str!=''- )- SELECT- word,- COUNT(*) as count- FROM split- WHERE length(word) > 3- AND word NOT IN ('this', 'that', 'with', 'from', 'have', 'what', 'your', 'which', 'their', 'about')- GROUP BY word- HAVING count > 5- ORDER BY count DESC- LIMIT 50;- `;-- try {- const response = await fetch(url, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({ query }),- });-- if (!response.ok) {- throw new Error(`http error! status: ${response.status}`);- }-- const result = await response.json();- console.log("received keyword stats:", result);-- setKeywords(result.map((row: any) => ({- word: row.word,- count: row.count- })));-- } catch (err) {- console.error("failed to fetch keyword stats:", err);- setError("error fetching keyword stats");- } finally {- setIsLoading(false);- }- };-- useEffect(() => {- processContentStreaming();- }, []);-- if (isLoading) return <div>loading...</div>;- if (error) return <div>error: {error}</div>;-- return (- <div className="p-4 bg-gray-100 rounded-lg">- <h2 className="text-xl font-bold mb-4">top keywords (last 24h)</h2>- <div className="flex flex-wrap gap-2">- {keywords.map((keyword) => (- <span- key={keyword.word}- className="px-2 py-1 bg-white rounded-full text-sm flex items-center"- style={{- fontSize: `${Math.max(0.8, Math.min(2, keyword.count / 10))}rem`,- }}- >- {keyword.word}- <span className="ml-1 text-xs text-gray-500">({keyword.count})</span>- </span>- ))}- </div>- </div>- );-};diff --git a/pipes/linkedin_ai_assistant/lib/browser_setup.ts b/pipes/linkedin_ai_assistant/lib/browser_setup.tsdeleted file mode 100644index bc0b21be2..000000000--- a/pipes/linkedin_ai_assistant/lib/browser_setup.ts+++ /dev/null@@ -1,37 +0,0 @@-import puppeteer, { Browser, Page } from 'puppeteer-core';--let activeBrowser: Browser | null = null;-let activePage: Page | null = null;--export async function setupBrowser(wsUrl: string): Promise<{ browser: Browser; page: Page }> {- if (!activeBrowser) {- activeBrowser = await puppeteer.connect({- browserWSEndpoint: wsUrl,- defaultViewport: null,- });- console.log('browser connected');-- const pages = await activeBrowser.pages();- activePage = pages[0];- console.log('got active page');- }-- if (!activeBrowser || !activePage) {- throw new Error('browser or page not initialized');- }-- return { browser: activeBrowser, page: activePage };-}--export function getActiveBrowser() {- return { browser: activeBrowser, page: activePage };-}--export async function quitBrowser() {- if (activeBrowser) {- await activeBrowser.disconnect();- activeBrowser = null;- activePage = null;- console.log('browser session cleared');- }-}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/click_first_connect_button.ts b/pipes/linkedin_ai_assistant/lib/simple_actions/click_first_connect_button.tsdeleted file mode 100644index 290df382a..000000000--- a/pipes/linkedin_ai_assistant/lib/simple_actions/click_first_connect_button.ts+++ /dev/null@@ -1,67 +0,0 @@-import { Page } from 'puppeteer-core';-import { showClickAnimation } from './click_animation';--export async function clickFirstConnectButton(page: Page): Promise<{- success: boolean;- profileUrl?: string;- weeklyLimitReached?: boolean;-}> {- try {- // Check if connect button exists with specific text and aria-label pattern- const connectButtonSelector = 'button[aria-label^="Invite"][aria-label$="to connect"]';- const connectButton = await page.$(connectButtonSelector);-- if (!connectButton) {- console.log('no connect button found on this page');- return { success: false };- }-- // Get profile URL before clicking connect- const profileUrl = await page.evaluate(() => {- const link = document.querySelector('a.EvQUJBaxIRgFetdTQjAXvpGhCNvVbYEbE');- return link?.getAttribute('href');- });-- console.log('found connect button');-- // Click the connect button with animation- await showClickAnimation(page, connectButtonSelector);- await page.click(connectButtonSelector);- console.log('clicked connect button');-- // Wait for the connect modal- await page.waitForSelector('.artdeco-modal[role="dialog"]', { timeout: 5000 });- console.log('connect modal appeared');-- // Click "Send without a note" button- const sendWithoutNoteSelector = 'button[aria-label="Send without a note"]';- await page.waitForSelector(sendWithoutNoteSelector, { timeout: 5000 });- await showClickAnimation(page, sendWithoutNoteSelector);- await page.click(sendWithoutNoteSelector);- console.log('clicked send without note');-- // Now check for weekly limit modal- try {- const weeklyLimitHeader = await page.waitForSelector('h2#ip-fuse-limit-alert__header', { timeout: 1000 });- if (weeklyLimitHeader) {- console.log('weekly invitation limit reached');-- // Click the "Got it" button- const gotItButtonSelector = 'button[aria-label="Got it"]';- await page.waitForSelector(gotItButtonSelector, { timeout: 5000 });- await showClickAnimation(page, gotItButtonSelector);- await page.click(gotItButtonSelector);- console.log('clicked got it button');- return { success: false, weeklyLimitReached: true };- }- } catch {- // No weekly limit modal appeared, connection was successful- return { success: true, profileUrl: profileUrl || undefined };- }-- return { success: true, profileUrl: profileUrl || undefined };- } catch (e) {- console.error('failed to click connect button:', e);- return { success: false };- }-}diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/conversation_review_with_llm.ts b/pipes/linkedin_ai_assistant/lib/simple_actions/conversation_review_with_llm.tsdeleted file mode 100644index e69de29bb..000000000diff --git a/pipes/linkedin_ai_assistant/lib/simple_actions/test_click_connect_button.ts b/pipes/linkedin_ai_assistant/lib/simple_actions/test_click_connect_button.tsdeleted file mode 100644index 7c53d1f00..000000000--- a/pipes/linkedin_ai_assistant/lib/simple_actions/test_click_connect_button.ts+++ /dev/null@@ -1,26 +0,0 @@-import { setupBrowser } from '../browser_setup';-import { clickFirstConnectButton } from './click_first_connect_button';--async function testClickConnect() {- try {- // Replace with your actual WebSocket URL- const wsUrl = 'ws://127.0.0.1:9222/devtools/browser/52a359b2-8d8f-401e-b2dd-ec00f1311a25';-- const { browser, page } = await setupBrowser(wsUrl);- console.log('connected to browser');-- // Test the click connect functionality- await clickFirstConnectButton(page);- console.log('connect button click test completed successfully');-- // Wait a bit to see the results visually- await new Promise(r => setTimeout(r, 2000));-- await browser.disconnect();- console.log('browser disconnected');- } catch (e) {- console.error('test failed:', e);- }-}--testClickConnect();\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/lib/storage/templates.d.ts b/pipes/linkedin_ai_assistant/lib/storage/templates.d.tsdeleted file mode 100644index 932b52053..000000000--- a/pipes/linkedin_ai_assistant/lib/storage/templates.d.ts+++ /dev/null@@ -1,9 +0,0 @@-declare module '*.json' {- export interface Templates {- request_for_intro: string;- llm_appraisal_prompt: string;- request_for_intro_prompt_to_AI: string;- }- const value: Templates;- export default value;-}\ No newline at end of filediff --git a/pipes/linkedin_ai_assistant/next.config.mjs b/pipes/linkedin_ai_assistant/next.config.mjsdeleted file mode 100644index 1322e0988..000000000--- a/pipes/linkedin_ai_assistant/next.config.mjs+++ /dev/null@@ -1,9 +0,0 @@-/** @type {import('next').NextConfig} */-const nextConfig = {- images: {- domains: ['screenpi.pe'],- },- experimental: {},-};--export default nextConfig;