Skip to content

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

merge: linkedin latest (#1211)

Matthew Diakonov3ece6940b301
diff --git a/pipes/linkedin-ai-assistant/.gitignore b/pipes/linkedin-ai-assistant/.gitignore
index b0cf6a1c5..aaf394d1c 100644
--- a/pipes/linkedin-ai-assistant/.gitignore
+++ b/pipes/linkedin-ai-assistant/.gitignore
@@ -63,3 +63,6 @@ History*
# storage files
lib/storage/*.json
!lib/storage/templates.json
+
+# Sentry Config File
+.env.sentry-build-plugin
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.ts
index 5088d1631..275a336c9 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,27 +1,24 @@
import { NextResponse } from 'next/server';
import { setupBrowser, getActiveBrowser } from '@/lib/browser-setup';
+import { RouteLogger } from '@/lib/route-logger';
-const logs: string[] = [];
-const addLog = (msg: string) => {
- console.log(msg);
- logs.push(`${new Date().toISOString()} - ${msg}`);
-};
+const logger = new RouteLogger('chrome-check-login');
export async function POST(request: Request) {
try {
await request.json(); // keep reading the request to avoid hanging
- addLog('checking linkedin login status');
+ logger.log('checking linkedin login status');
- addLog('setting up browser...');
- await setupBrowser(logs);
+ logger.log('setting up browser...');
+ await setupBrowser(logger);
const { page } = getActiveBrowser();
if (!page) {
- addLog('no active browser session found');
+ logger.log('no active browser session found');
throw new Error('no active browser session');
}
- addLog('evaluating login state...');
+ logger.log('evaluating login state...');
// Check for elements that indicate logged-in state
const isLoggedIn = await page.evaluate(() => {
// Check for feed-specific elements that only appear when logged in
@@ -32,18 +29,18 @@ export async function POST(request: Request) {
return !!(feedElements || navElements)
});
- addLog(`login status: ${isLoggedIn ? 'logged in' : 'logged out'}`);
+ logger.log(`login status: ${isLoggedIn ? 'logged in' : 'logged out'}`);
return NextResponse.json({
success: true,
isLoggedIn: Boolean(isLoggedIn),
- logs
+ logs: logger.getLogs()
});
} catch (error) {
- addLog(`failed to check login status: ${error}`);
+ logger.error(`failed to check login status: ${error}`);
return NextResponse.json(
- { success: false, error: String(error), logs },
+ { success: false, error: String(error), logs: logger.getLogs() },
{ status: 500 }
);
}
diff --git a/pipes/linkedin-ai-assistant/app/api/chrome/navigate/route.ts b/pipes/linkedin-ai-assistant/app/api/chrome/navigate/route.ts
index 6110594bd..4d205ebf8 100644
--- a/pipes/linkedin-ai-assistant/app/api/chrome/navigate/route.ts
+++ b/pipes/linkedin-ai-assistant/app/api/chrome/navigate/route.ts
@@ -2,38 +2,35 @@ import { NextResponse } from 'next/server';
import { setupBrowser } from '@/lib/browser-setup';
import { ChromeSession } from '@/lib/chrome-session';
import type { Page } from 'puppeteer-core';
+import { RouteLogger } from '@/lib/route-logger';
-const logs: string[] = [];
-const addLog = (msg: string) => {
- console.log(msg);
- logs.push(`${new Date().toISOString()} - ${msg}`);
-};
+const logger = new RouteLogger('chrome-navigate');
async function navigateToPage(page: Page, url: string) {
try {
- addLog('starting navigation');
- addLog(`target url: ${url}`);
+ logger.log('starting navigation');
+ logger.log(`target url: ${url}`);
// Set longer timeout but keep navigation simple
await page.setDefaultNavigationTimeout(60000);
- addLog('navigation timeout set to 60s');
+ logger.log('navigation timeout set to 60s');
// Navigate to the target URL with same settings as search navigation
- addLog('navigating to page...');
+ logger.log('navigating to page...');
const response = await page.goto(url, {
waitUntil: 'domcontentloaded',
timeout: 60000
});
- addLog(`navigation response status: ${response?.status() || 0}`);
+ logger.log(`navigation response status: ${response?.status() || 0}`);
// Wait for the main content to load
- addLog('waiting for body element...');
+ logger.log('waiting for body element...');
await page.waitForSelector('body', { timeout: 30000 });
- addLog('body element found');
+ logger.log('body element found');
// Store the page in ChromeSession after successful navigation
ChromeSession.getInstance().setActivePage(page);
- addLog('page stored in chrome session');
+ logger.log('page stored in chrome session');
return {
status: response?.status() || 0,
@@ -41,7 +38,7 @@ async function navigateToPage(page: Page, url: string) {
};
} catch (error) {
- addLog(`navigation error: ${error}`);
+ logger.log(`navigation error: ${error}`);
throw error;
}
}
@@ -49,32 +46,32 @@ async function navigateToPage(page: Page, url: string) {
export async function POST(request: Request) {
try {
const { url } = await request.json();
- addLog(`attempting to navigate to: ${url}`);
+ logger.log(`attempting to navigate to: ${url}`);
// Setup the browser connection
- addLog('setting up browser...');
- const { page } = await setupBrowser(logs);
+ logger.log('setting up browser...');
+ const { page } = await setupBrowser(logger);
// Perform the navigation
const result = await navigateToPage(page, url);
- addLog(`navigation complete. final url: ${result.finalUrl}`);
+ logger.log(`navigation complete. final url: ${result.finalUrl}`);
// Return a successful response with navigation details
return NextResponse.json({
success: true,
status: result.status,
finalUrl: result.finalUrl,
- logs
+ logs: logger.getLogs()
});
} catch (error) {
- addLog(`failed to navigate: ${error}`);
+ logger.log(`failed to navigate: ${error}`);
// Return an error response with details
return NextResponse.json({
success: false,
error: 'failed to navigate',
details: error instanceof Error ? error.message : String(error),
- logs
+ logs: logger.getLogs()
}, { status: 500 });
}
}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/app/api/chrome/route.ts b/pipes/linkedin-ai-assistant/app/api/chrome/route.ts
index f0825a1e9..46df6d6ed 100644
--- a/pipes/linkedin-ai-assistant/app/api/chrome/route.ts
+++ b/pipes/linkedin-ai-assistant/app/api/chrome/route.ts
@@ -4,13 +4,10 @@ import { promisify } from 'util';
import { quitBrowser } from '@/lib/browser-setup';
import os from 'os';
import { ChromeSession } from '@/lib/chrome-session';
+import { RouteLogger } from '@/lib/route-logger';
// import { pipe } from "@screenpipe/js";
-const logs: string[] = [];
-const addLog = (msg: string) => {
- console.log(msg);
- logs.push(`${new Date().toISOString()} - ${msg}`);
-};
+const logger = new RouteLogger('chrome-route');
export const runtime = 'nodejs'; // specify node runtime
@@ -21,7 +18,7 @@ function getChromePath() {
switch (os.platform()) {
case "darwin": {
const isArm = os.arch() === 'arm64';
- addLog(`mac architecture: ${os.arch()}`);
+ logger.log(`mac architecture: ${os.arch()}`);
return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
}
case "linux":
@@ -42,18 +39,18 @@ function getScreenDimensions(requestDims?: ScreenDimensions) {
const defaultDims = { width: 2560, height: 1440 };
if (requestDims) {
- addLog(`using client screen dimensions: ${requestDims.width}x${requestDims.height}`);
+ logger.log(`using client screen dimensions: ${requestDims.width}x${requestDims.height}`);
return requestDims;
}
- addLog(`no dimensions provided, using defaults: ${defaultDims.width}x${defaultDims.height}`);
+ logger.log(`no dimensions provided, using defaults: ${defaultDims.width}x${defaultDims.height}`);
return defaultDims;
}
export async function POST(request: Request) {
try {
- addLog('chrome route: starting POST request');
-
+ logger.log('starting POST request');
+
// Get dimensions from request first
const body = await request.json();
const screenDims = getScreenDimensions(body.screenDims);
@@ -77,96 +74,120 @@ export async function POST(request: Request) {
'--disable-site-isolation-trials',
].flat();
// Log environment info
- addLog(`environment: ${process.env.NODE_ENV}`);
- addLog(`current platform: ${os.platform()}`);
- addLog(`system architecture: ${os.arch()}`);
- addLog(`cpu info: ${JSON.stringify(os.cpus()[0], null, 2)}`);
-
- addLog("attempting to launch chrome");
- addLog("killing existing chrome instances...");
- await quitChrome();
- await quitBrowser(logs);
-
- const chromePath = getChromePath();
- addLog(`using chrome path: ${chromePath}`);
- addLog(`checking if chrome exists: ${require('fs').existsSync(chromePath)}`);
-
- addLog("spawning chrome with debugging port 9222...");
- const isArmMac = os.platform() === 'darwin' && os.arch() === 'arm64';
- const spawnCommand = isArmMac ? 'arch' : chromePath;
- const spawnArgs = isArmMac ? [
- '-arm64',
- chromePath,
- ...additionalFlags
- ] : [
- ...additionalFlags
- ];
-
- const chromeProcess = spawn(spawnCommand, spawnArgs, {
- detached: true,
- stdio: 'ignore'
- });
+ logger.log(`environment: ${process.env.NODE_ENV}`);
+ logger.log(`current platform: ${os.platform()}`);
+ logger.log(`system architecture: ${os.arch()}`);
+ logger.log(`cpu info: ${JSON.stringify(os.cpus()[0], null, 2)}`);
+
+ logger.log("checking for existing chrome instance...");
+ let wsUrl: string | null = null;
+ try {
+ const response = await fetch('http://127.0.0.1:9222/json/version');
+ if (response.ok) {
+ const data = await response.json() as { webSocketDebuggerUrl: string };
+ wsUrl = data.webSocketDebuggerUrl.replace('ws://localhost:', 'ws://127.0.0.1:');
+ logger.log(`found existing chrome instance at ${wsUrl}`);
+ } else {
+ logger.log('no existing chrome instance found, launching a new one');
+ }
+ } catch (error) {
+ logger.error(`error checking for existing chrome instance: ${error}`);
+ logger.log('launching a new chrome instance');
+ }
- chromeProcess.unref();
- addLog("chrome process spawned and detached");
-
- addLog("waiting for chrome to initialize...");
- await new Promise(resolve => setTimeout(resolve, 3000));
-
- let attempts = 0;
- const maxAttempts = 5;
- addLog(`attempting to connect to debug port (max ${maxAttempts} attempts)`);
-
- while (attempts < maxAttempts) {
- try {
- addLog(`connection attempt ${attempts + 1}/${maxAttempts}`);
- const response = await fetch('http://127.0.0.1:9222/json/version');
- const data = await response.json();
-
- if (response.ok && data.webSocketDebuggerUrl) {
- addLog('chrome debug port responding');
- const wsUrl = data.webSocketDebuggerUrl.replace('ws://localhost:', 'ws://127.0.0.1:');
- addLog(`websocket url: ${wsUrl}`);
- ChromeSession.getInstance().setWsUrl(wsUrl);
-
- return NextResponse.json({
- success: true,
- wsUrl,
- logs
- });
+ if (!wsUrl) {
+ logger.log("attempting to launch chrome");
+ logger.log("killing existing chrome instances...");
+ await quitChrome(); // only kill if we are about to launch a new one
+ await quitBrowser(logger);
+
+ const chromePath = getChromePath();
+ logger.log(`using chrome path: ${chromePath}`);
+ logger.log(`checking if chrome exists: ${require('fs').existsSync(chromePath)}`);
+
+ logger.log("spawning chrome with debugging port 9222...");
+ const isArmMac = os.platform() === 'darwin' && os.arch() === 'arm64';
+ const spawnCommand = isArmMac ? 'arch' : chromePath;
+ const spawnArgs = isArmMac ? [
+ '-arm64',
+ chromePath,
+ ...additionalFlags
+ ] : [
+ ...additionalFlags
+ ];
+
+ const chromeProcess = spawn(spawnCommand, spawnArgs, {
+ detached: true,
+ stdio: 'ignore'
+ });
+
+ chromeProcess.unref();
+ logger.log("chrome process spawned and detached");
+
+ logger.log("waiting for chrome to initialize...");
+ await new Promise(resolve => setTimeout(resolve, 3000));
+
+ let attempts = 0;
+ const maxAttempts = 5;
+ logger.log(`attempting to connect to debug port (max ${maxAttempts} attempts)`);
+
+ while (attempts < maxAttempts) {
+ try {
+ logger.log(`connection attempt ${attempts + 1}/${maxAttempts}`);
+ const response = await fetch('http://127.0.0.1:9222/json/version');
+ const data = await response.json();
+
+ if (response.ok && data.webSocketDebuggerUrl) {
+ logger.log('chrome debug port responding');
+ wsUrl = data.webSocketDebuggerUrl.replace('ws://localhost:', 'ws://127.0.0.1:');
+ logger.log(`websocket url: ${wsUrl}`);
+ if (wsUrl) {
+ ChromeSession.getInstance().setWsUrl(wsUrl);
+ }
+ break; // exit retry loop on success
+ }
+ } catch (err) {
+ logger.error(`attempt ${attempts + 1} failed: ${err}`);
}
- } catch (err) {
- addLog(`attempt ${attempts + 1} failed: ${err}`);
+ attempts++;
+ logger.log(`waiting 1s before retry ${attempts}/${maxAttempts}`);
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+
+ if (!wsUrl) {
+ throw new Error('failed to connect to chrome debug port after all attempts');
}
- attempts++;
- addLog(`waiting 1s before retry ${attempts}/${maxAttempts}`);
- await new Promise(resolve => setTimeout(resolve, 1000));
}
-
- throw new Error('failed to connect to chrome debug port after all attempts');
+
+
+ return NextResponse.json({
+ success: true,
+ wsUrl,
+ logs: logger.getLogs()
+ });
} catch (err) {
- addLog(`chrome launch failed with error: ${err}`);
- return NextResponse.json({
- success: false,
+ logger.error(`chrome launch failed with error: ${err}`);
+ return NextResponse.json({
+ success: false,
error: String(err),
- logs
+ logs: logger.getLogs()
}, { status: 500 });
}
}
export async function DELETE() {
try {
- addLog('chrome route: starting DELETE request');
+ logger.log('starting DELETE request');
await quitChrome();
- await quitBrowser(logs);
- addLog('chrome processes terminated');
+ await quitBrowser(logger);
+ logger.log('chrome processes terminated');
ChromeSession.getInstance().clear();
- addLog('chrome session cleared');
- return NextResponse.json({ success: true, logs });
+ logger.log('chrome session cleared');
+ return NextResponse.json({ success: true, logs: logger.getLogs() });
} catch (error) {
- addLog(`failed to kill chrome: ${error}`);
+ logger.error(`failed to kill chrome: ${error}`);
return NextResponse.json(
- { success: false, error: String(error), logs },
+ { success: false, error: String(error), logs: logger.getLogs() },
{ status: 500 }
);
}
@@ -174,18 +195,18 @@ export async function DELETE() {
async function quitChrome() {
const platform = os.platform();
- console.log('quitting chrome on platform:', platform);
+ logger.log(`quitting chrome on platform: ${platform}`);
const killCommand =
platform === "win32"
? `taskkill /F /IM chrome.exe`
: `pkill -f -- "Google Chrome"`;
try {
- console.log('executing kill command:', killCommand);
+ logger.log('executing kill command:', killCommand);
await execPromise(killCommand);
- console.log("chrome killed successfully");
+ logger.log("chrome killed successfully");
} catch (error) {
- console.log("no chrome process found to kill", error);
+ logger.log("no chrome process found to kill", error);
}
}
diff --git a/pipes/linkedin-ai-assistant/app/api/chrome/status/route.ts b/pipes/linkedin-ai-assistant/app/api/chrome/status/route.ts
index 5c3b65508..dc824b3f2 100644
--- a/pipes/linkedin-ai-assistant/app/api/chrome/status/route.ts
+++ b/pipes/linkedin-ai-assistant/app/api/chrome/status/route.ts
@@ -1,43 +1,40 @@
import { NextResponse } from 'next/server';
+import { RouteLogger } from '@/lib/route-logger';
export const runtime = 'nodejs';
-const logs: string[] = [];
-const addLog = (msg: string) => {
- console.log(msg);
- logs.push(`${new Date().toISOString()} - ${msg}`);
-};
+const logger = new RouteLogger('chrome-status');
export async function GET() {
try {
- addLog('checking chrome connection status...');
+ logger.log('checking chrome connection status...');
const response = await fetch('http://127.0.0.1:9222/json/version');
if (!response.ok) {
- addLog('chrome not connected');
+ logger.log('chrome not connected');
return NextResponse.json({
status: 'not_connected',
- logs
+ logs: logger.getLogs()
}, { status: 200 });
}
const data = await response.json() as { webSocketDebuggerUrl: string };
- addLog('chrome connected, getting websocket url');
+ logger.log('chrome connected, getting websocket url');
const wsUrl = data.webSocketDebuggerUrl.replace('ws://localhost:', 'ws://127.0.0.1:');
- addLog(`websocket url: ${wsUrl}`);
+ logger.log(`websocket url: ${wsUrl}`);
return NextResponse.json({
wsUrl,
status: 'connected',
- logs
+ logs: logger.getLogs()
});
} catch (error) {
- addLog(`error checking status: ${error}`);
+ logger.error(`error checking status: ${error}`);
return NextResponse.json({
status: 'not_connected',
error: String(error),
- logs
+ logs: logger.getLogs()
}, { status: 200 });
}
}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/app/api/harvest/connection-status-update/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/connection-status-update/route.ts
index fe30f89cd..24d7339da 100644
--- a/pipes/linkedin-ai-assistant/app/api/harvest/connection-status-update/route.ts
+++ b/pipes/linkedin-ai-assistant/app/api/harvest/connection-status-update/route.ts
@@ -10,14 +10,14 @@ export const dynamic = 'force-dynamic'
export const fetchCache = 'force-no-store'
// Add types for page and connection
-type ConnectionStatus = 'cooldown' | 'declined' | 'accepted' | 'pending' | 'email_required';
+type ConnectionStatus = 'declined' | 'accepted' | 'pending' | 'email_required' | 'invalid';
type Connection = {
status: ConnectionStatus;
timestamp?: string;
};
-async function checkConnectionStatus(page: Page, profileUrl: string, connection: Connection) {
+async function checkConnectionStatus(page: Page, profileUrl: string, connection: Connection): Promise<Exclude<ConnectionStatus, 'cooldown'>> {
try {
const maxRetries = 3;
const baseDelay = 60000; // base delay of 1 minute
diff --git a/pipes/linkedin-ai-assistant/app/api/harvest/start/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/start/route.ts
index 1bdbe34ae..90066f92d 100644
--- a/pipes/linkedin-ai-assistant/app/api/harvest/start/route.ts
+++ b/pipes/linkedin-ai-assistant/app/api/harvest/start/route.ts
@@ -1,26 +1,67 @@
import { NextResponse } from 'next/server';
import { startHarvesting } from '@/lib/logic-sequence/harvest-connections';
-import { loadConnections, saveHarvestingState } from '@/lib/storage/storage';
+import {
+ loadConnections,
+ saveHarvestingState,
+ updateConnectionsSent,
+ isHarvestingAlive,
+ updateHeartbeat
+} from '@/lib/storage/storage';
+import { ChromeSession } from '@/lib/chrome-session';
+import crypto from 'crypto';
export async function POST() {
try {
console.log('farming start endpoint called');
const connections = await loadConnections();
- console.log('current harvesting status:', connections.harvestingStatus);
- // Check if already running first
+ // Check if process is actually running via heartbeat
if (connections.harvestingStatus === 'running') {
- console.log('farming already in progress');
- return NextResponse.json(
- {
- message: 'farming already in progress',
- harvestingStatus: 'running',
- weeklyLimitReached: false,
- dailyLimitReached: false,
- connectionsSent: connections.connectionsSent || 0
- },
- { status: 200 }
- );
+ const isAlive = await isHarvestingAlive();
+
+ if (!isAlive) {
+ console.log('detected dead harvest process, resetting state');
+ await saveHarvestingState('stopped');
+ } else {
+ console.log('farming already in progress');
+ return NextResponse.json(
+ {
+ message: 'farming already in progress',
+ harvestingStatus: 'running',
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ connectionsSent: connections.connectionsSent || 0
+ },
+ { status: 200 }
+ );
+ }
+ }
+
+ // Generate unique process ID for this harvest run
+ const processId = crypto.randomUUID();
+ await updateHeartbeat(processId);
+
+ // Add browser validation
+ if (connections.harvestingStatus === 'running') {
+ const session = ChromeSession.getInstance();
+ const isValid = await session.validateConnection();
+
+ if (!isValid) {
+ console.log('browser connection lost, resetting state');
+ await saveHarvestingState('stopped');
+ } else {
+ console.log('farming already in progress');
+ return NextResponse.json(
+ {
+ message: 'farming already in progress',
+ harvestingStatus: 'running',
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ connectionsSent: connections.connectionsSent || 0
+ },
+ { status: 200 }
+ );
+ }
}
// Check cooldown before starting
@@ -42,6 +83,7 @@ export async function POST() {
// Set state to running and start harvest
console.log('setting farming state to running');
await saveHarvestingState('running');
+ await updateConnectionsSent(0); // Reset connections counter
console.log('starting farming process');
const result = await startHarvesting(35);
diff --git a/pipes/linkedin-ai-assistant/app/api/harvest/stats/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/stats/route.ts
index c68f1f259..522ba8b7b 100644
--- a/pipes/linkedin-ai-assistant/app/api/harvest/stats/route.ts
+++ b/pipes/linkedin-ai-assistant/app/api/harvest/stats/route.ts
@@ -1,5 +1,5 @@
import { NextResponse } from 'next/server';
-import { loadConnections } from '@/lib/storage/storage';
+import { loadConnections, isHarvestingAlive, saveHarvestingState } from '@/lib/storage/storage';
export const dynamic = 'force-dynamic'
export const fetchCache = 'force-no-store'
@@ -7,7 +7,15 @@ export const fetchCache = 'force-no-store'
export async function GET() {
try {
const connectionsStore = await loadConnections();
+ const isAlive = await isHarvestingAlive();
+ // Reset state if process is dead but status is running
+ if (connectionsStore.harvestingStatus === 'running' && !isAlive) {
+ console.log('detected dead harvest process, resetting state to stopped');
+ await saveHarvestingState('stopped');
+ connectionsStore.harvestingStatus = 'stopped';
+ }
+
// Calculate stats using reduce
const stats = Object.values(connectionsStore.connections).reduce((acc, connection) => {
const status = connection.status || 'pending';
@@ -28,7 +36,12 @@ export async function GET() {
withdrawStatus: connectionsStore.withdrawStatus || {
isWithdrawing: false
}
- }
+ },
+ isAlive,
+ harvestingStatus: connectionsStore.harvestingStatus,
+ nextHarvestTime: connectionsStore.nextHarvestTime,
+ connectionsSent: connectionsStore.connectionsSent,
+ statusMessage: connectionsStore.statusMessage
});
} catch (error) {
console.error('stats check failed:', error);
diff --git a/pipes/linkedin-ai-assistant/app/api/sentry-example-api/route.ts b/pipes/linkedin-ai-assistant/app/api/sentry-example-api/route.ts
new file mode 100644
index 000000000..f486f3d1d
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/app/api/sentry-example-api/route.ts
@@ -0,0 +1,9 @@
+import { NextResponse } from "next/server";
+
+export const dynamic = "force-dynamic";
+
+// A faulty API route to test Sentry's error monitoring
+export function GET() {
+ throw new Error("Sentry Example API Route Error");
+ return NextResponse.json({ data: "Testing Sentry Error..." });
+}
diff --git a/pipes/linkedin-ai-assistant/app/global-error.tsx b/pipes/linkedin-ai-assistant/app/global-error.tsx
new file mode 100644
index 000000000..9bda5feef
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/app/global-error.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import * as Sentry from "@sentry/nextjs";
+import NextError from "next/error";
+import { useEffect } from "react";
+
+export default function GlobalError({ error }: { error: Error & { digest?: string } }) {
+ useEffect(() => {
+ Sentry.captureException(error);
+ }, [error]);
+
+ return (
+ <html>
+ <body>
+ {/* `NextError` is the default Next.js error page component. Its type
+ definition requires a `statusCode` prop. However, since the App Router
+ does not expose status codes for errors, we simply pass 0 to render a
+ generic error message. */}
+ <NextError statusCode={0} />
+ </body>
+ </html>
+ );
+}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/app/sentry-example-page/page.tsx b/pipes/linkedin-ai-assistant/app/sentry-example-page/page.tsx
new file mode 100644
index 000000000..f24637280
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/app/sentry-example-page/page.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import Head from "next/head";
+import * as Sentry from "@sentry/nextjs";
+
+export default function Page() {
+ return (
+ <div>
+ <Head>
+ <title>Sentry Onboarding</title>
+ <meta name="description" content="Test Sentry for your Next.js app!" />
+ </Head>
+
+ <main
+ style={{
+ minHeight: "100vh",
+ display: "flex",
+ flexDirection: "column",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
+ <h1 style={{ fontSize: "4rem", margin: "14px 0" }}>
+ <svg
+ style={{
+ height: "1em",
+ }}
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 200 44"
+ >
+ <path
+ fill="currentColor"
+ d="M124.32,28.28,109.56,9.22h-3.68V34.77h3.73V15.19l15.18,19.58h3.26V9.22h-3.73ZM87.15,23.54h13.23V20.22H87.14V12.53h14.93V9.21H83.34V34.77h18.92V31.45H87.14ZM71.59,20.3h0C66.44,19.06,65,18.08,65,15.7c0-2.14,1.89-3.59,4.71-3.59a12.06,12.06,0,0,1,7.07,2.55l2-2.83a14.1,14.1,0,0,0-9-3c-5.06,0-8.59,3-8.59,7.27,0,4.6,3,6.19,8.46,7.52C74.51,24.74,76,25.78,76,28.11s-2,3.77-5.09,3.77a12.34,12.34,0,0,1-8.3-3.26l-2.25,2.69a15.94,15.94,0,0,0,10.42,3.85c5.48,0,9-2.95,9-7.51C79.75,23.79,77.47,21.72,71.59,20.3ZM195.7,9.22l-7.69,12-7.64-12h-4.46L186,24.67V34.78h3.84V24.55L200,9.22Zm-64.63,3.46h8.37v22.1h3.84V12.68h8.37V9.22H131.08ZM169.41,24.8c3.86-1.07,6-3.77,6-7.63,0-4.91-3.59-8-9.38-8H154.67V34.76h3.8V25.58h6.45l6.48,9.2h4.44l-7-9.82Zm-10.95-2.5V12.6h7.17c3.74,0,5.88,1.77,5.88,4.84s-2.29,4.86-5.84,4.86Z M29,2.26a4.67,4.67,0,0,0-8,0L14.42,13.53A32.21,32.21,0,0,1,32.17,40.19H27.55A27.68,27.68,0,0,0,12.09,17.47L6,28a15.92,15.92,0,0,1,9.23,12.17H4.62A.76.76,0,0,1,4,39.06l2.94-5a10.74,10.74,0,0,0-3.36-1.9l-2.91,5a4.54,4.54,0,0,0,1.69,6.24A4.66,4.66,0,0,0,4.62,44H19.15a19.4,19.4,0,0,0-8-17.31l2.31-4A23.87,23.87,0,0,1,23.76,44H36.07a35.88,35.88,0,0,0-16.41-31.8l4.67-8a.77.77,0,0,1,1.05-.27c.53.29,20.29,34.77,20.66,35.17a.76.76,0,0,1-.68,1.13H40.6q.09,1.91,0,3.81h4.78A4.59,4.59,0,0,0,50,39.43a4.49,4.49,0,0,0-.62-2.28Z"
+ ></path>
+ </svg>
+ </h1>
+
+ <p>Get started by sending us a sample error:</p>
+ <button
+ type="button"
+ style={{
+ padding: "12px",
+ cursor: "pointer",
+ backgroundColor: "#AD6CAA",
+ borderRadius: "4px",
+ border: "none",
+ color: "white",
+ fontSize: "14px",
+ margin: "18px",
+ }}
+ onClick={async () => {
+ await Sentry.startSpan({
+ name: 'Example Frontend Span',
+ op: 'test'
+ }, async () => {
+ const res = await fetch("/api/sentry-example-api");
+ if (!res.ok) {
+ throw new Error("Sentry Example Frontend Error");
+ }
+ });
+ }}
+ >
+ Throw error!
+ </button>
+
+ <p>
+ Next, look for the error on the{" "}
+ <a href="https://mediar-n5.sentry.io/issues/?project=4508694799712256">Issues Page</a>.
+ </p>
+ <p style={{ marginTop: "24px" }}>
+ For more information, see{" "}
+ <a href="https://docs.sentry.io/platforms/javascript/guides/nextjs/">
+ https://docs.sentry.io/platforms/javascript/guides/nextjs/
+ </a>
+ </p>
+ </main>
+ </div>
+ );
+}
diff --git a/pipes/linkedin-ai-assistant/components/harvest.tsx b/pipes/linkedin-ai-assistant/components/harvest.tsx
index 71c948af5..29d882087 100644
--- a/pipes/linkedin-ai-assistant/components/harvest.tsx
+++ b/pipes/linkedin-ai-assistant/components/harvest.tsx
@@ -92,6 +92,13 @@ function getStatusStyle(status: HarvestingStatus): string {
}
}
+// Add this helper function
+function formatDuration(milliseconds: number): string {
+ const minutes = Math.floor(milliseconds / 60000);
+ const seconds = Math.floor((milliseconds % 60000) / 1000);
+ return `${minutes}m ${seconds}s`;
+}
+
export function HarvestClosestConnections() {
const [harvestingStatus, setHarvestingStatus] = useState<HarvestingStatus>('stopped');
const [status, setStatus] = useState<string | JSX.Element>("");
@@ -118,6 +125,10 @@ export function HarvestClosestConnections() {
reason?: string;
} | null>(null);
const [isWithdrawing, setIsWithdrawing] = useState(false);
+ // Add new state for cycle duration
+ const [cycleStartTime, setCycleStartTime] = useState<number | null>(null);
+ const [cycleDuration, setCycleDuration] = useState<string>('');
+ const [statusMessage, setStatusMessage] = useState<string | null>(null);
useEffect(() => {
// Load initial state with status only
@@ -127,9 +138,17 @@ export function HarvestClosestConnections() {
if (!res.ok) return;
const data = await res.json();
- console.log('initial state data:', data);
+ console.log('initial state loaded:', {
+ harvestingStatus: data.harvestingStatus,
+ nextHarvestTime: data.nextHarvestTime,
+ now: new Date().toISOString(),
+ timeUntil: data.nextHarvestTime ?
+ Math.floor((new Date(data.nextHarvestTime).getTime() - Date.now()) / 1000 / 60) + 'm'
+ : 'none'
+ });
setHarvestingStatus(data.harvestingStatus || 'stopped');
+ setNextHarvestTime(data.nextHarvestTime);
setConnectionsSent(data.connectionsSent || 0);
setDailyLimitReached(data.dailyLimitReached || false);
setWeeklyLimitReached(data.weeklyLimitReached || false);
@@ -170,14 +189,67 @@ export function HarvestClosestConnections() {
loadInitialState();
}, []);
+ // Auto-restart effect
+ useEffect(() => {
+ console.log('auto-restart effect triggered:', {
+ harvestingStatus,
+ nextHarvestTime,
+ now: new Date().toISOString()
+ });
+
+ if (!nextHarvestTime) {
+ console.log('no next harvest time set');
+ return;
+ }
+
+ if (harvestingStatus !== 'cooldown') {
+ console.log('status is not cooldown:', harvestingStatus);
+ return;
+ }
+
+ const timeUntilNextHarvest = new Date(nextHarvestTime).getTime() - Date.now();
+ console.log('time until next harvest:', {
+ nextHarvestTime,
+ timeUntilNextHarvest: Math.floor(timeUntilNextHarvest / 1000 / 60) + 'm',
+ status: harvestingStatus
+ });
+
+ if (timeUntilNextHarvest <= 0) {
+ console.log('harvest time already passed, starting now');
+ startHarvesting();
+ return;
+ }
+
+ console.log('scheduling ui auto-restart after cooldown');
+ const timer = setTimeout(() => {
+ console.log('cooldown finished, auto-restarting harvest from ui');
+ startHarvesting();
+ }, timeUntilNextHarvest);
+
+ return () => clearTimeout(timer);
+ }, [nextHarvestTime, harvestingStatus]);
+
// Stats polling stats, load connections
useEffect(() => {
const interval = setInterval(async () => {
try {
- const res = await fetch("/api/harvest/stats"); // Changed from /api/harvest/stats
+ const res = await fetch("/api/harvest/stats");
if (!res.ok) return;
const data = await res.json();
+ console.log('polling received data:', {
+ statusMessage: data.statusMessage,
+ harvestingStatus: data.harvestingStatus,
+ isAlive: data.isAlive
+ });
+
+ // Check if process is alive via heartbeat
+ if (data.harvestingStatus === 'running' && !data.isAlive) {
+ console.log('detected dead harvest process');
+ setHarvestingStatus('stopped');
+ return;
+ }
+
// Update both stats and status
if (data.stats) {
setStats(data.stats);
@@ -188,6 +260,14 @@ export function HarvestClosestConnections() {
if (data.nextHarvestTime) {
setNextHarvestTime(data.nextHarvestTime);
}
+ if (typeof data.connectionsSent === 'number') {
+ setConnectionsSent(data.connectionsSent);
+ }
+ // Add debug before setting status message
+ if (data.statusMessage) {
+ console.log('setting status message:', data.statusMessage);
+ setStatusMessage(data.statusMessage);
+ }
} catch (error) {
console.error("failed to fetch status:", error);
}
@@ -226,11 +306,35 @@ export function HarvestClosestConnections() {
}
}, [stats.withdrawStatus?.isWithdrawing]);
+ // Add effect to track running time
+ useEffect(() => {
+ let interval: NodeJS.Timeout;
+
+ if (harvestingStatus === 'running') {
+ if (!cycleStartTime) {
+ setCycleStartTime(Date.now());
+ }
+
+ interval = setInterval(() => {
+ if (cycleStartTime) {
+ setCycleDuration(formatDuration(Date.now() - cycleStartTime));
+ }
+ }, 1000);
+ } else {
+ setCycleStartTime(null);
+ setCycleDuration('');
+ }
+
+ return () => {
+ if (interval) clearInterval(interval);
+ };
+ }, [harvestingStatus, cycleStartTime]);
+
// Simplify the updateConnectionsStatus function
const updateConnectionsStatus = async () => {
try {
if (isWithdrawing) {
- // Stop withdrawal process
+ setIsRefreshing(true); // Start spinner immediately
const response = await fetch("/api/harvest/withdraw-connections", {
method: "POST"
});
@@ -239,20 +343,22 @@ export function HarvestClosestConnections() {
}
console.log('withdrawal stopped successfully');
setIsWithdrawing(false);
- return;
- }
-
- // Start withdrawal process
- console.log('starting withdrawal process');
- setIsWithdrawing(true);
- const withdrawRes = await fetch("/api/harvest/withdraw-connections?start=true");
- if (!withdrawRes.ok) {
- console.error('failed to start withdrawal');
- setIsWithdrawing(false);
+ } else {
+ // Start withdrawal process
+ console.log('starting withdrawal process');
+ setIsRefreshing(true); // Start spinner immediately
+ setIsWithdrawing(true);
+ const withdrawRes = await fetch("/api/harvest/withdraw-connections?start=true");
+ if (!withdrawRes.ok) {
+ console.error('failed to start withdrawal');
+ setIsWithdrawing(false);
+ }
}
} catch (error) {
console.error("failed to update/withdraw connections:", error);
setIsWithdrawing(false);
+ } finally {
+ setIsRefreshing(false); // Always stop spinner when done
}
};
@@ -272,7 +378,7 @@ export function HarvestClosestConnections() {
if (response.ok) {
setStatus(data.message?.toLowerCase() || 'unknown status');
- setConnectionsSent(data.connectionsSent || 0);
+ setConnectionsSent(data.connectionsSent || 0); // Update from response
setDailyLimitReached(data.dailyLimitReached || false);
setWeeklyLimitReached(data.weeklyLimitReached || false);
setHarvestingStatus(data.harvestingStatus);
@@ -376,11 +482,16 @@ export function HarvestClosestConnections() {
<span>weekly limit reached, next harvest at</span>
<span className="font-medium">{formatDateTime(nextHarvestTime)}</span>
</span>
- : harvestingStatus === 'running'
- ? connectionsSent > 0
- ? `sent ${connectionsSent} connections`
- : ''
- : status}
+ : statusMessage
+ ? <span className="flex items-center gap-2">
+ <Info className="h-4 w-4 text-gray-500" />
+ <span>{statusMessage.toLowerCase()}</span>
+ </span>
+ : harvestingStatus === 'running'
+ ? connectionsSent > 0
+ ? `sent ${connectionsSent} connections in ${cycleDuration}`
+ : cycleDuration ? `running for ${cycleDuration}` : ''
+ : ''}
</span>
)}
{restrictionInfo?.isRestricted && restrictionInfo?.reason && (
diff --git a/pipes/linkedin-ai-assistant/components/launch-linkedin-chrome-session.tsx b/pipes/linkedin-ai-assistant/components/launch-linkedin-chrome-session.tsx
index 025211172..242eb86b8 100644
--- a/pipes/linkedin-ai-assistant/components/launch-linkedin-chrome-session.tsx
+++ b/pipes/linkedin-ai-assistant/components/launch-linkedin-chrome-session.tsx
@@ -13,6 +13,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
+import * as Sentry from "@sentry/nextjs";
// import { pipe } from "@screenpipe/js";
interface Props {
@@ -38,48 +39,58 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro
};
}, [loginCheckInterval]);
- const addLog = (message: string) => {
- const now = new Date();
- const time = now.toLocaleTimeString('en-US', {
- hour12: false,
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit'
- });
-
- // Clean up embedded timestamps in the message
- const cleanMessage = message.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z - /, '');
- setLogs(prev => [...prev, `${time} - ${cleanMessage}`]);
+ const logger = {
+ log: (message: string) => {
+ const now = new Date();
+ const time = now.toLocaleTimeString('en-US', {
+ hour12: false,
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ });
+ setLogs(prev => [...prev, `${time} - ${message}`]);
+ },
+ error: (message: string) => {
+ const now = new Date();
+ const time = now.toLocaleTimeString('en-US', {
+ hour12: false,
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ });
+ console.error(message);
+ setLogs(prev => [...prev, `${time} - error: ${message}`]);
+ }
};
const killChrome = async () => {
try {
- addLog('killing chrome...');
+ logger.log('killing chrome...');
const response = await fetch('/api/chrome', { method: 'DELETE' });
const data = await response.json();
if (data.logs) {
- data.logs.forEach((log: string) => addLog(log));
+ data.logs.forEach((log: string) => logger.log(log));
}
setStatus('idle');
- addLog('chrome killed');
+ logger.log('chrome killed');
} catch (error) {
- addLog(`error killing chrome: ${error}`);
- console.error('failed to kill chrome:', error);
+ logger.error(`failed to kill chrome: ${error}`);
}
};
const launchChrome = async () => {
try {
- await killChrome();
setStatus('connecting');
setError(null);
- // Get screen dimensions from browser
+ await killChrome();
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
const screenDims = {
width: window.screen.availWidth,
height: window.screen.availHeight
};
- addLog(`screen dimensions: ${screenDims.width}x${screenDims.height}`);
+ logger.log(`screen dimensions: ${screenDims.width}x${screenDims.height}`);
const response = await fetch('/api/chrome', {
method: 'POST',
@@ -88,16 +99,16 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro
});
const data = await response.json();
if (data.logs) {
- data.logs.forEach((log: string) => addLog(log));
+ data.logs.forEach((log: string) => logger.log(log));
}
if (!response.ok) {
throw new Error(data.error || 'Failed to launch chrome');
}
- // Start polling the server-side API for debugger URL
+ await new Promise(resolve => setTimeout(resolve, 2000));
pollDebuggerStatus();
} catch (error) {
- console.error('failed to launch chrome:', error);
+ logger.error(`failed to launch chrome: ${error}`);
setStatus('error');
setError(error instanceof Error ? error.message : String(error));
}
@@ -109,32 +120,30 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro
while (attempts < maxAttempts) {
try {
- addLog('polling debugger status...');
+ logger.log('polling debugger status...');
const response = await fetch('/api/chrome/status');
const data = await response.json();
- // Add logs from the status endpoint
if (data.logs) {
- data.logs.forEach((log: string) => addLog(log));
+ data.logs.forEach((log: string) => logger.log(log));
}
- addLog(`poll response: ${JSON.stringify(data)}`);
+ logger.log(`poll response: ${JSON.stringify(data)}`);
if (data.status === 'connected') {
- addLog('debugger connected, proceeding to linkedin');
+ logger.log('debugger connected, proceeding to linkedin');
setStatus('connected');
await navigateToLinkedIn();
return;
}
- addLog(`not connected yet, attempt ${attempts + 1}/${maxAttempts}`);
+ logger.log(`not connected yet, attempt ${attempts + 1}/${maxAttempts}`);
} catch (error) {
- addLog(`poll error: ${error}`);
- console.error('error checking debugger status:', error);
+ logger.error(`poll error: ${error}`);
}
await new Promise(resolve => setTimeout(resolve, 1000));
attempts++;
}
- addLog('max polling attempts reached, setting error state');
+ logger.log('max polling attempts reached, setting error state');
setStatus('error');
};
@@ -149,9 +158,8 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro
if (!response.ok) throw new Error('Failed to check login status');
const data = await response.json();
- // Add log handling
if (data.logs) {
- data.logs.forEach((log: string) => addLog(log));
+ data.logs.forEach((log: string) => logger.log(log));
}
const isLoggedIn = data.isLoggedIn;
@@ -166,7 +174,7 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro
setLoginCheckInterval(interval);
}
} catch (error) {
- console.error('failed to check login status:', error);
+ logger.error('failed to check login status:');
if (loginCheckInterval) {
clearInterval(loginCheckInterval);
setLoginCheckInterval(null);
@@ -176,7 +184,6 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro
const navigateToLinkedIn = async () => {
try {
- // First get the wsUrl from status endpoint
const statusResponse = await fetch('/api/chrome/status');
const statusData = await statusResponse.json();
@@ -198,17 +205,15 @@ export function LaunchLinkedInChromeSession({ loginStatus, setLoginStatus }: Pro
throw new Error(error.details || 'Failed to navigate');
}
- // Missing: We need to handle the response data and logs here
const data = await response.json();
if (data.logs) {
- data.logs.forEach((log: string) => addLog(log));
+ data.logs.forEach((log: string) => logger.log(log));
}
- // Add login status check after navigation
setLoginStatus('checking');
await checkLoginStatus(statusData.wsUrl);
} catch (error) {
- console.error('failed to navigate:', error);
+ logger.error('failed to navigate:');
}
};
diff --git a/pipes/linkedin-ai-assistant/instrumentation.ts b/pipes/linkedin-ai-assistant/instrumentation.ts
new file mode 100644
index 000000000..964f937c4
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/instrumentation.ts
@@ -0,0 +1,13 @@
+import * as Sentry from '@sentry/nextjs';
+
+export async function register() {
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
+ await import('./sentry.server.config');
+ }
+
+ if (process.env.NEXT_RUNTIME === 'edge') {
+ await import('./sentry.edge.config');
+ }
+}
+
+export const onRequestError = Sentry.captureRequestError;
diff --git a/pipes/linkedin-ai-assistant/lib/browser-setup.ts b/pipes/linkedin-ai-assistant/lib/browser-setup.ts
index 93bd40f69..5415680b8 100644
--- a/pipes/linkedin-ai-assistant/lib/browser-setup.ts
+++ b/pipes/linkedin-ai-assistant/lib/browser-setup.ts
@@ -1,87 +1,84 @@
import puppeteer, { Browser, Page } from 'puppeteer-core';
import { ChromeSession } from './chrome-session';
+import { RouteLogger } from './route-logger';
let activeBrowser: Browser | null = null;
let activePage: Page | null = null;
+const defaultLogger = new RouteLogger('browser-setup');
// Export this function so it can be used elsewhere if needed
-export async function getDebuggerUrl(logs: string[] = []): Promise<string> {
- const addLog = (msg: string) => {
- console.log(msg);
- logs.push(`${new Date().toISOString()} - ${msg}`);
- };
-
- addLog('attempting to get debugger url...');
+export async function getDebuggerUrl(logger: RouteLogger = defaultLogger): Promise<string> {
+ logger.log('attempting to get debugger url...');
const response = await fetch('http://127.0.0.1:9222/json/version');
if (!response.ok) {
- addLog(`failed to get debugger url: ${response.status} ${response.statusText}`);
+ logger.error(`failed to get debugger url: ${response.status} ${response.statusText}`);
throw new Error('failed to get fresh websocket url');
}
const data = await response.json() as { webSocketDebuggerUrl: string };
- addLog('got debugger url: ' + data.webSocketDebuggerUrl);
+ logger.log('got debugger url: ' + data.webSocketDebuggerUrl);
return data.webSocketDebuggerUrl.replace('ws://localhost:', 'ws://127.0.0.1:');
}
// we rely on an existing or newly launched chrome instance
-export async function setupBrowser(logs: string[] = []): Promise<{ browser: Browser; page: Page }> {
- const addLog = (msg: string) => {
- console.log(msg); // keep console logging
- logs.push(`${new Date().toISOString()} - ${msg}`);
- };
-
- addLog('setting up browser...');
+export async function setupBrowser(logger: RouteLogger = defaultLogger): Promise<{ browser: Browser; page: Page }> {
+ logger.log('checking for existing browser...');
if (!activeBrowser) {
const session = ChromeSession.getInstance();
- addLog('getting ws url...');
- const wsUrl = session.getWsUrl() || await getDebuggerUrl(logs);
- addLog('using ws url: ' + wsUrl);
-
+ const wsUrl = session.getWsUrl() || await getDebuggerUrl(logger);
+
let retries = 5;
let lastError;
-
+
while (retries > 0) {
try {
- addLog(`connection attempt ${6 - retries}...`);
+ logger.log(`connection attempt ${6 - retries}...`);
await new Promise(resolve => setTimeout(resolve, 1000));
-
+
activeBrowser = await puppeteer.connect({
browserWSEndpoint: wsUrl,
defaultViewport: null,
});
- addLog('browser connected successfully');
-
+ session.setActiveBrowser(activeBrowser);
+ logger.log('browser connected successfully');
+
await new Promise(resolve => setTimeout(resolve, 1000));
- const pages = await activeBrowser.pages();
- addLog(`found ${pages.length} pages`);
-
- if (!pages.length) {
- throw new Error('no pages available');
+ let pages = await activeBrowser.pages();
+ logger.log(`found ${pages.length} pages`);
+
+ let linkedinPage = pages.find(page => page.url().startsWith('https://www.linkedin.com'));
+
+ if (linkedinPage) {
+ logger.log('found existing linkedin page, reusing it');
+ activePage = linkedinPage;
+ } else {
+ logger.log('no existing linkedin page found, opening a new tab');
+ activePage = await activeBrowser.newPage();
+ logger.log('new tab opened');
}
- activePage = pages[0];
session.setActivePage(activePage);
- addLog('browser setup complete');
+ logger.log('browser setup complete');
break;
} catch (error) {
lastError = error;
- addLog(`connection attempt ${6 - retries} failed: ${error}`);
+ logger.error(`connection attempt ${6 - retries} failed: ${error}`);
retries--;
if (retries > 0) {
- addLog(`retrying in 2s... (${retries} attempts left)`);
+ logger.log(`retrying in 2s... (${retries} attempts left)`);
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
}
if (!activeBrowser) {
- addLog(`all connection attempts failed: ${lastError}`);
+ logger.error(`all connection attempts failed: ${lastError}`);
throw new Error(`failed to connect to browser after 5 attempts: ${lastError}`);
}
} else {
- addLog('using existing browser connection');
+ logger.log('using existing browser connection');
}
if (!activeBrowser || !activePage) {
- addLog('browser or page not properly initialized');
+ logger.error('browser or page not properly initialized');
throw new Error('browser or page not initialized');
}
@@ -92,28 +89,23 @@ export async function setupBrowser(logs: string[] = []): Promise<{ browser: Brow
export function getActiveBrowser() {
const session = ChromeSession.getInstance();
return {
- browser: activeBrowser,
- page: session.getActivePage() || activePage
+ browser: session.getActiveBrowser(),
+ page: session.getActivePage()
};
}
// used to disconnect puppeteer if desired
-export async function quitBrowser(logs: string[] = []) {
- const addLog = (msg: string) => {
- console.log(msg);
- logs.push(`${new Date().toISOString()} - ${msg}`);
- };
-
+export async function quitBrowser(logger: RouteLogger = defaultLogger) {
ChromeSession.getInstance().clear();
if (activeBrowser) {
try {
await activeBrowser.disconnect();
- addLog('browser disconnected');
+ logger.log('browser disconnected');
} catch (error) {
- addLog(`error disconnecting browser: ${error}`);
+ logger.error(`error disconnecting browser: ${error}`);
}
activeBrowser = null;
activePage = null;
- addLog('browser session cleared');
+ logger.log('browser session cleared');
}
}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/lib/chrome-session.ts b/pipes/linkedin-ai-assistant/lib/chrome-session.ts
index 936e68922..41d0b1ffe 100644
--- a/pipes/linkedin-ai-assistant/lib/chrome-session.ts
+++ b/pipes/linkedin-ai-assistant/lib/chrome-session.ts
@@ -1,6 +1,6 @@
import fs from 'fs/promises';
import path from 'path';
-import { Page } from 'puppeteer-core';
+import { Page, Browser } from 'puppeteer-core';
const SESSION_FILE = path.join(process.cwd(), 'lib', 'storage', 'chrome-session.json');
@@ -9,6 +9,8 @@ export class ChromeSession {
private wsUrl: string | null = null;
private isConnected: boolean = false;
private activePage: Page | null = null;
+ private activePageId: string | null = null;
+ private activeBrowser: Browser | null = null;
private constructor() {
// Load saved state on instantiation
@@ -28,7 +30,7 @@ export class ChromeSession {
const state = {
wsUrl: this.wsUrl,
isConnected: this.isConnected,
- hasActivePage: !!this.activePage
+ activePageId: this.activePageId
};
try {
@@ -44,6 +46,7 @@ export class ChromeSession {
const state = JSON.parse(data);
this.wsUrl = state.wsUrl;
this.isConnected = state.isConnected;
+ this.activePageId = state.activePageId;
} catch (err) {
console.log('no saved chrome session state found');
}
@@ -61,13 +64,20 @@ export class ChromeSession {
setActivePage(page: Page) {
this.activePage = page;
+ // @ts-ignore - different puppeteer versions have different Target APIs
+ this.activePageId = page.target()._targetId || page.target().id() || page.target().targetId();
this.saveState();
}
getActivePage(): Page | null {
+ this.validateConnection().catch(() => this.clear());
return this.activePage;
}
+ getActivePageId(): string | null {
+ return this.activePageId;
+ }
+
isActive(): boolean {
return this.isConnected;
}
@@ -76,7 +86,39 @@ export class ChromeSession {
this.wsUrl = null;
this.isConnected = false;
this.activePage = null;
+ this.activePageId = null;
this.saveState();
console.log('chrome session cleared');
}
+
+ setActiveBrowser(browser: Browser) {
+ this.activeBrowser = browser;
+ this.isConnected = true;
+ this.saveState();
+ }
+
+ getActiveBrowser(): Browser | null {
+ this.validateConnection().catch(() => this.clear());
+ return this.activeBrowser;
+ }
+
+ async validateConnection(): Promise<boolean> {
+ if (!this.activeBrowser || !this.activePage) {
+ return false;
+ }
+
+ try {
+ // Test if browser is still connected
+ const pages = await this.activeBrowser.pages();
+ if (!pages.length || this.activePage.isClosed()) {
+ this.clear();
+ return false;
+ }
+ return true;
+ } catch (error) {
+ console.log('browser connection validation failed:', error);
+ this.clear();
+ return false;
+ }
+ }
}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/lib/logic-sequence/check-accepted-connections.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-accepted-connections.ts
index daae83493..bdaec75be 100644
--- a/pipes/linkedin-ai-assistant/lib/logic-sequence/check-accepted-connections.ts
+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-accepted-connections.ts
@@ -54,17 +54,60 @@ export async function startCheckingAcceptedConnections(): Promise<void> {
}
try {
- console.log(`checking connection status for ${connection.profileUrl}`);
+ console.log(`navigating to profile: ${connection.profileUrl}`);
- // Visit profile
await page.goto(connection.profileUrl, {
- waitUntil: 'networkidle0',
- timeout: 30000
+ waitUntil: 'domcontentloaded',
+ timeout: 15000
});
- // Check if connected
+ // Check for 404 page
+ const is404 = await Promise.race([
+ page.$eval('.not-found__header', () => true).catch(() => false),
+ page.$eval('[data-test-not-found-error-container]', () => true).catch(() => false)
+ ]);
+
+ if (is404) {
+ console.log(`profile not found (404) for ${connection.profileUrl}`);
+ await saveConnection({
+ ...connection,
+ status: 'invalid',
+ timestamp: new Date().toISOString()
+ });
+ continue;
+ }
+
+ console.log('waiting for profile content to load...');
+
+ // Wait for either connect button or pending/message buttons to appear
+ const selectors = [
+ 'button.artdeco-button--connect',
+ 'button[aria-label*="Pending"]',
+ 'button[aria-label*="Message"]'
+ ];
+
+ const button = await Promise.race([
+ ...selectors.map(selector =>
+ page.waitForSelector(selector, { timeout: 45000 })
+ .catch(() => null)
+ )
+ ]);
+
+ console.log('button detection result:', !!button);
+
+ // Check connection status
+ const pendingButton = await page.$('button[aria-label*="Pending"]');
+ const messageButton = await page.$('button[aria-label*="Message"]');
const connectButton = await page.$('button.artdeco-button--connect');
- const isConnected = !connectButton;
+
+ console.log('found buttons:', {
+ pending: !!pendingButton,
+ message: !!messageButton,
+ connect: !!connectButton
+ });
+
+ // If we have a message button or pending button but no connect button, they're connected
+ const isConnected = messageButton && !connectButton;
if (isConnected) {
console.log(`connection accepted for ${connection.profileUrl}`);
@@ -82,13 +125,38 @@ export async function startCheckingAcceptedConnections(): Promise<void> {
status: 'accepted',
timestamp: new Date().toISOString()
});
+ } else if (pendingButton) {
+ console.log(`connection still pending for ${connection.profileUrl}`);
+ } else {
+ console.log(`unclear connection status for ${connection.profileUrl}`);
+ }
+
+ // Check for any potential blocks or captchas
+ const possibleCaptcha = await page.$('iframe[title*="recaptcha"]');
+ if (possibleCaptcha) {
+ console.error('detected possible captcha, may need manual intervention');
+ throw new Error('captcha detected');
}
// Random delay between profile checks
- await new Promise(resolve => setTimeout(resolve, 2000 + Math.random() * 3000));
+ const delay = 2000 + Math.random() * 3000;
+ console.log(`waiting ${Math.round(delay)}ms before next profile...`);
+ await new Promise(resolve => setTimeout(resolve, delay));
} catch (error) {
console.error(`error checking connection ${connection.profileUrl}:`, error);
+
+ // Take screenshot on error for debugging
+ try {
+ await page.screenshot({
+ path: `error-${Date.now()}.png`,
+ fullPage: true
+ });
+ console.log('saved error screenshot');
+ } catch (e) {
+ console.error('failed to save error screenshot:', e);
+ }
+
continue;
}
}
diff --git a/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.ts
index 04de38ca1..131e43340 100644
--- a/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.ts
+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.ts
@@ -9,8 +9,10 @@ import {
updateConnectionsSent,
setStopRequested,
isStopRequested,
+ updateHeartbeat,
+ isHarvestingAlive,
} from '../storage/storage';
-import { setupBrowser } from '../browser-setup';
+import { setupBrowser, getActiveBrowser } from '../browser-setup';
import { updateWorkflowStep } from '../../app/api/workflow/status/state';
import { closeAllMessageDialogues } from '../simple-actions/close-dialogues';
import { cleanProfileUrl } from '../simple-actions/extract-profiles-from-search-results';
@@ -47,6 +49,7 @@ export interface HarvestStatus {
nextHarvestTime?: string;
stopped?: boolean;
harvestingStatus: 'stopped' | 'running' | 'cooldown';
+ statusMessage?: string;
}
export async function emitProgress(connectionsSent: number) {
@@ -61,289 +64,318 @@ export async function isHarvesting(): Promise<boolean> {
export async function startHarvesting(
maxDailyConnections: number = 35
): Promise<HarvestStatus> {
- // Reset stop flag at start
- await setStopRequested(false);
-
- // Prevent multiple harvesting processes
- if (isCurrentlyHarvesting) {
- console.log('harvest already in progress, skipping start');
- const connections = await loadConnections();
- return {
- connectionsSent: connections.connectionsSent || 0,
- weeklyLimitReached: false,
- dailyLimitReached: false,
- harvestingStatus: 'running'
- };
- }
-
- // Set flag before any async operations
- isCurrentlyHarvesting = true;
- console.log('starting new harvest process');
+ const processId = crypto.randomUUID(); // Unique ID for this run
+
+ // Set up heartbeat interval
+ const heartbeatInterval = setInterval(() => {
+ updateHeartbeat(processId).catch(console.error);
+ }, 10_000); // Update every 10 seconds
try {
- const store = await loadConnections();
-
- // Check cooldown period first
- if (store.nextHarvestTime && new Date(store.nextHarvestTime) > new Date()) {
- console.log('in cooldown period, cannot start');
- return {
- connectionsSent: store.connectionsSent || 0,
- weeklyLimitReached: false,
- dailyLimitReached: true,
- nextHarvestTime: store.nextHarvestTime,
- harvestingStatus: 'cooldown'
- };
- }
-
- // Initialize counters
- let connectionsSent = 0;
- let weeklyLimitReached = false;
- const dailyLimitReached = false;
+ // Reset stop flag at start
+ await setStopRequested(false);
- // Rest of harvesting logic...
+ // Prevent multiple harvesting processes
+ if (isCurrentlyHarvesting) {
+ console.log('harvest already in progress, checking browser state...');
+
+ // Add validation of browser state
+ const { browser, page } = getActiveBrowser();
+ if (!browser || !page || page.isClosed()) {
+ console.log('browser connection lost, resetting state');
+ await saveHarvestingState('stopped');
+ isCurrentlyHarvesting = false;
+ // Continue to start new harvest
+ } else {
+ const connections = await loadConnections();
+ return {
+ connectionsSent: connections.connectionsSent || 0,
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ harvestingStatus: 'running'
+ };
+ }
+ }
- // Set harvesting state to running immediately
- await saveHarvestingState('running');
- await updateConnectionsSent(0);
+ // Set flag before any async operations
+ isCurrentlyHarvesting = true;
+ console.log('starting new harvest process');
try {
- // Reset the stop request flag
- await setStopRequested(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,
- harvestingStatus: 'cooldown'
- };
- }
+ const store = await loadConnections();
+
+ // Check cooldown period first
+ if (store.nextHarvestTime && new Date(store.nextHarvestTime) > new Date()) {
+ console.log('in cooldown period, cannot start');
+ await saveHarvestingState('cooldown', 'waiting for cooldown period to end');
+ return {
+ connectionsSent: store.connectionsSent || 0,
+ weeklyLimitReached: false,
+ dailyLimitReached: true,
+ nextHarvestTime: store.nextHarvestTime,
+ harvestingStatus: 'cooldown',
+ statusMessage: 'waiting for cooldown period to end'
+ };
}
- console.log('starting farming process with max daily connections:', maxDailyConnections);
-
- await saveNextHarvestTime('');
+ // Initialize counters
+ let connectionsSent = 0;
+ let weeklyLimitReached = false;
+ const dailyLimitReached = false;
- // Load existing connections
- updateWorkflowStep('setup', 'done', 'connections loaded');
+ // Rest of harvesting logic...
- // Browser setup
- updateWorkflowStep('browser', 'running', 'connecting to chrome');
- const statusResponse = await fetch(`${BASE_URL}/api/chrome/status`);
- const statusData = await statusResponse.json();
+ // Set harvesting state to running immediately
+ await saveHarvestingState('running');
+ await updateConnectionsSent(0);
- if (statusData.status !== 'connected' || !statusData.wsUrl) {
- throw new Error('chrome not connected');
- }
+ try {
+ // Reset the stop request flag
+ await setStopRequested(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,
+ harvestingStatus: 'cooldown'
+ };
+ }
+ }
- const { page } = await setupBrowser();
- updateWorkflowStep('browser', 'done', 'browser connected');
+ console.log('starting farming process with max daily connections:', maxDailyConnections);
+
+ await saveNextHarvestTime('');
- // Navigate to LinkedIn search results
- updateWorkflowStep('navigation', 'running', 'navigating to linkedin search');
- const searchUrl =
- 'https://www.linkedin.com/search/results/people/?network=%5B%22S%22%5D';
- await navigateToSearch(page, searchUrl, { allowTruncate: true });
+ // Load existing connections
+ updateWorkflowStep('setup', 'done', 'connections loaded');
- // Close any open message dialogues before starting
- updateWorkflowStep('navigation', 'running', 'closing message dialogues');
- await closeAllMessageDialogues(page);
+ // Browser setup
+ updateWorkflowStep('browser', 'running', 'connecting to chrome');
+ const statusResponse = await fetch(`${BASE_URL}/api/chrome/status`);
+ const statusData = await statusResponse.json();
- // Wait for the search results to load
- console.log('waiting for search results container...');
- try {
- await page.waitForSelector(
- [
- 'div[data-view-name="search-entity-result-universal-template"]',
- 'ul.reusable-search__entity-result-list',
- ].join(','),
- {
- visible: true,
- timeout: 15000,
- }
- );
- console.log('search results loaded successfully');
- } catch (error) {
- console.error('failed to find search results:', error);
- throw new Error('no search results found on page');
- }
+ if (statusData.status !== 'connected' || !statusData.wsUrl) {
+ throw new Error('chrome not connected');
+ }
- console.log('search results loaded');
- updateWorkflowStep('navigation', 'done');
+ const { page } = await setupBrowser();
+ updateWorkflowStep('browser', 'done', 'browser connected');
- // Add stop handler
- if (await isStopRequested()) {
- await saveHarvestingState('stopped');
- return {
- connectionsSent,
- weeklyLimitReached,
- dailyLimitReached: false,
- stopped: true,
- harvestingStatus: 'stopped'
- };
- }
+ // Navigate to LinkedIn search results
+ updateWorkflowStep('navigation', 'running', 'navigating to linkedin search');
+ const searchUrl =
+ 'https://www.linkedin.com/search/results/people/?network=%5B%22S%22%5D';
+ await navigateToSearch(page, searchUrl, { allowTruncate: true });
- while (
- connectionsSent < maxDailyConnections &&
- !weeklyLimitReached &&
- !await isStopRequested()
- ) {
- // Check if stop was requested
+ // Close any open message dialogues before starting
+ updateWorkflowStep('navigation', 'running', 'closing message dialogues');
+ await closeAllMessageDialogues(page);
+
+ // Wait for the search results to load
+ console.log('waiting for search results container...');
+ try {
+ await page.waitForSelector(
+ [
+ 'div[data-view-name="search-entity-result-universal-template"]',
+ 'ul.reusable-search__entity-result-list',
+ ].join(','),
+ {
+ visible: true,
+ timeout: 15000,
+ }
+ );
+ console.log('search results loaded successfully');
+ } catch (error) {
+ console.error('failed to find search results:', error);
+ throw new Error('no search results found on page');
+ }
+
+ console.log('search results loaded');
+ updateWorkflowStep('navigation', 'done');
+
+ // Add stop handler
if (await isStopRequested()) {
- console.log('harvest process stopped by user');
- await saveHarvestingState('stopped');
+ const store = await loadConnections(); // Get current store to preserve message
+ await saveHarvestingState('stopped', store.statusMessage); // Keep existing message
return {
connectionsSent,
weeklyLimitReached,
dailyLimitReached: false,
stopped: true,
- harvestingStatus: 'stopped'
+ harvestingStatus: 'stopped',
+ statusMessage: store.statusMessage // Include message in return
};
}
- updateWorkflowStep('processing', 'running', `processing connections`);
-
- try {
- const result = await clickNextConnectButton(page, await isStopRequested());
-
+ while (
+ connectionsSent < maxDailyConnections &&
+ !weeklyLimitReached &&
+ !await isStopRequested()
+ ) {
+ // Check if stop was requested
if (await isStopRequested()) {
- break;
+ console.log('harvest process stopped by user');
+ const store = await loadConnections(); // Get current store to preserve message
+ await saveHarvestingState('stopped', store.statusMessage); // Keep existing message
+ return {
+ connectionsSent,
+ weeklyLimitReached,
+ dailyLimitReached: false,
+ stopped: true,
+ harvestingStatus: 'stopped',
+ statusMessage: store.statusMessage // Include message in return
+ };
}
- if (result.success) {
- connectionsSent++;
- await updateConnectionsSent(connectionsSent);
+ updateWorkflowStep('processing', 'running', `processing connections`);
- const cleanUrl = result.profileUrl
- ? cleanProfileUrl(result.profileUrl)
- : '';
- console.log(
- `Connection sent to ${cleanUrl}, total: ${connectionsSent}`
- );
+ try {
+ const result = await clickNextConnectButton(page, await isStopRequested());
- await saveConnection({
- profileUrl: cleanUrl,
- status: 'pending',
- timestamp: new Date().toISOString(),
- });
+ if (await isStopRequested()) {
+ break;
+ }
- // Update connectionsSent in the store
- await updateConnectionsSent(connectionsSent);
+ if (result.success) {
+ connectionsSent++;
+ await updateConnectionsSent(connectionsSent);
- // Add random delay between connections
- const delay = 3000 + Math.floor(Math.random() * 1000);
- await new Promise((resolve) => setTimeout(resolve, delay));
-
- continue; // Continue the loop instead of returning
- } else if (result.weeklyLimitReached) {
- console.log('Weekly limit reached, stopping');
- weeklyLimitReached = true;
- break;
- } else if (result.cooldown) {
- console.log('profile in cooldown period:', result.profileUrl);
- // Try next button on the page instead of continuing
- continue;
- } else if (result.emailRequired && result.profileUrl) {
- console.log(
- 'email verification required for profile:',
- result.profileUrl
- );
- await saveConnection({
- profileUrl: result.profileUrl,
- status: 'email_required',
- timestamp: new Date().toISOString(),
- });
- // Continue to next profile without incrementing connectionsSent
- continue;
- } else {
- // No valid connect buttons found, attempt to go to next page
- const hasNextPage = await goToNextPage(page, await isStopRequested());
- if (await isStopRequested() || !hasNextPage) {
- console.log('no more pages available or stopped, ending harvest');
+ const cleanUrl = result.profileUrl
+ ? cleanProfileUrl(result.profileUrl)
+ : '';
+ console.log(
+ `Connection sent to ${cleanUrl}, total: ${connectionsSent}`
+ );
+
+ await saveConnection({
+ profileUrl: cleanUrl,
+ status: 'pending',
+ timestamp: new Date().toISOString(),
+ });
+
+ // Update connectionsSent in the store
+ await updateConnectionsSent(connectionsSent);
+
+ // Add random delay between connections
+ const delay = 3000 + Math.floor(Math.random() * 1000);
+ await new Promise((resolve) => setTimeout(resolve, delay));
+
+ continue; // Continue the loop instead of returning
+ } else if (result.weeklyLimitReached) {
+ console.log('Weekly limit reached, stopping');
+ weeklyLimitReached = true;
break;
+ } else if (result.cooldown) {
+ console.log('profile in cooldown period:', result.profileUrl);
+ // Try next button on the page instead of continuing
+ continue;
+ } else if (result.emailRequired && result.profileUrl) {
+ console.log(
+ 'email verification required for profile:',
+ result.profileUrl
+ );
+ await saveConnection({
+ profileUrl: result.profileUrl,
+ status: 'email_required',
+ timestamp: new Date().toISOString(),
+ });
+ // Continue to next profile without incrementing connectionsSent
+ continue;
+ } else {
+ // No valid connect buttons found, attempt to go to next page
+ const hasNextPage = await goToNextPage(page, await isStopRequested());
+ if (await isStopRequested() || !hasNextPage) {
+ console.log('no more pages available or stopped, ending harvest');
+ break;
+ }
+ // Small delay after page navigation
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ if (await isStopRequested()) {
+ break;
+ }
}
- // Small delay after page navigation
- await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ // Add small delay between attempts
+ await new Promise((resolve) => setTimeout(resolve, 1000));
if (await isStopRequested()) {
break;
}
+ } catch (error) {
+ console.error('error processing connection:', error);
+ continue;
}
+ }
- // Add small delay between attempts
- await new Promise((resolve) => setTimeout(resolve, 1000));
+ console.log(`Finished sending ${connectionsSent} connections`);
+ } catch (error) {
+ await saveHarvestingState('stopped');
+ console.error('harvesting failed:', error);
+ throw error;
+ }
- if (await isStopRequested()) {
- break;
- }
- } catch (error) {
- console.error('error processing connection:', error);
- continue;
- }
+ if (await isStopRequested()) {
+ const store = await loadConnections(); // Get current store to preserve message
+ await saveHarvestingState('stopped', store.statusMessage); // Keep existing message
+ return {
+ connectionsSent,
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ stopped: true,
+ harvestingStatus: 'stopped',
+ statusMessage: store.statusMessage // Include message in return
+ };
}
- console.log(`Finished sending ${connectionsSent} connections`);
- } catch (error) {
- await saveHarvestingState('stopped');
- console.error('harvesting failed:', error);
- throw error;
- }
+ if (weeklyLimitReached) {
+ // Weekly limit reached, set next time and keep harvesting state
+ const nextTime = new Date(
+ Date.now() + 24 * 60 * 60 * 1000
+ ).toISOString();
+ await saveNextHarvestTime(nextTime);
+ return {
+ connectionsSent,
+ weeklyLimitReached: true,
+ dailyLimitReached: false,
+ nextHarvestTime: nextTime,
+ harvestingStatus: 'running'
+ };
+ }
- if (await isStopRequested()) {
- await saveHarvestingState('stopped');
- return {
- connectionsSent,
- weeklyLimitReached: false,
- dailyLimitReached: false,
- stopped: true,
- harvestingStatus: 'stopped'
- };
- }
+ if (connectionsSent >= maxDailyConnections) {
+ // Daily limit reached, set next time but keep harvesting true
+ const nextTime = new Date(
+ Date.now() + 24 * 60 * 60 * 1000
+ ).toISOString();
+ await saveNextHarvestTime(nextTime);
+ await saveHarvestingState('cooldown');
+ return {
+ connectionsSent,
+ weeklyLimitReached: false,
+ dailyLimitReached: true,
+ nextHarvestTime: nextTime,
+ harvestingStatus: 'cooldown'
+ };
+ }
- if (weeklyLimitReached) {
- // Weekly limit reached, set next time and keep harvesting state
- const nextTime = new Date(
- Date.now() + 24 * 60 * 60 * 1000
- ).toISOString();
- await saveNextHarvestTime(nextTime);
return {
connectionsSent,
- weeklyLimitReached: true,
+ weeklyLimitReached: false,
dailyLimitReached: false,
- nextHarvestTime: nextTime,
harvestingStatus: 'running'
};
+ } finally {
+ isCurrentlyHarvesting = false;
}
-
- if (connectionsSent >= maxDailyConnections) {
- // Daily limit reached, set next time but keep harvesting true
- const nextTime = new Date(
- Date.now() + 24 * 60 * 60 * 1000
- ).toISOString();
- await saveNextHarvestTime(nextTime);
- await saveHarvestingState('cooldown');
- return {
- connectionsSent,
- weeklyLimitReached: false,
- dailyLimitReached: true,
- nextHarvestTime: nextTime,
- harvestingStatus: 'cooldown'
- };
- }
-
- return {
- connectionsSent,
- weeklyLimitReached: false,
- dailyLimitReached: false,
- harvestingStatus: 'running'
- };
} finally {
- isCurrentlyHarvesting = false;
+ clearInterval(heartbeatInterval);
}
}
@@ -769,10 +801,14 @@ async function goToNextPage(
}
}
- console.log('no valid next button found');
+ console.log('no valid next button found - ending harvest process');
+ await setStopRequested(true); // Request stop when no more pages
+ await saveHarvestingState('stopped', 'last farming cycle: no more pages available');
return false;
} catch (error) {
console.error('error in goToNextPage:', error);
+ await setStopRequested(true);
+ await saveHarvestingState('stopped', 'last farming cycle: error navigating to next page');
return false;
}
}
@@ -812,4 +848,29 @@ export async function navigateToSearch(
}
throw error;
}
+}
+
+export async function getHarvestingStatus(): Promise<HarvestStatus> {
+ const store = await loadConnections();
+ const isAlive = await isHarvestingAlive();
+
+ if (store.harvestingStatus === 'running' && !isAlive) {
+ console.log('detected dead harvest process, resetting state');
+ await saveHarvestingState('stopped');
+ return {
+ harvestingStatus: 'stopped',
+ connectionsSent: store.connectionsSent || 0,
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ nextHarvestTime: store.nextHarvestTime,
+ };
+ }
+
+ return {
+ harvestingStatus: store.harvestingStatus,
+ connectionsSent: store.connectionsSent || 0,
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ nextHarvestTime: store.nextHarvestTime,
+ };
}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts
index b7dab8852..4af72e3df 100644
--- a/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts
+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts
@@ -141,10 +141,12 @@ async function withdrawOldInvitations(page: Page): Promise<boolean> {
if (!timeText) continue;
const isOldEnough = timeText.includes('month') ||
- (timeText.includes('week') && parseInt(timeText) >= 2);
+ (timeText.toLowerCase().includes('sent') &&
+ timeText.includes('week') &&
+ parseInt(timeText.match(/\d+/)?.[0] || '0') >= 2);
if (isOldEnough) {
- console.log(`found old invitation for ${profileUrl}: ${timeText}`);
+ console.log(`found old invitation to withdraw - age: ${timeText}`);
foundOldInvitation = true;
// Re-query the withdraw button
diff --git a/pipes/linkedin-ai-assistant/lib/route-logger.ts b/pipes/linkedin-ai-assistant/lib/route-logger.ts
new file mode 100644
index 000000000..4b1ebb6b8
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/lib/route-logger.ts
@@ -0,0 +1,45 @@
+import * as Sentry from "@sentry/nextjs";
+
+export class RouteLogger {
+ private logs: string[] = [];
+ private component: string;
+
+ constructor(component: string) {
+ this.component = component;
+ }
+
+ log(...messages: any[]) {
+ const message = messages.join(' ');
+ const timestamp = new Date().toISOString();
+ const formattedMessage = `${timestamp} - ${message}`;
+
+ console.log(`[${this.component}] ${message}`);
+ this.logs.push(formattedMessage);
+
+ if (message.toLowerCase().includes('error') || message.toLowerCase().includes('failed')) {
+ Sentry.captureMessage(`${this.component}: ${message}`, {
+ level: 'error',
+ tags: { component: this.component },
+ extra: { logs: this.logs }
+ });
+ }
+ }
+
+ error(message: string) {
+ const timestamp = new Date().toISOString();
+ const formattedMessage = `${timestamp} - ERROR: ${message}`;
+
+ console.error(`[${this.component}] ${message}`);
+ this.logs.push(formattedMessage);
+
+ Sentry.captureMessage(`${this.component}: ${message}`, {
+ level: 'error',
+ tags: { component: this.component },
+ extra: { logs: this.logs }
+ });
+ }
+
+ getLogs() {
+ return this.logs;
+ }
+}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/lib/storage/storage.ts b/pipes/linkedin-ai-assistant/lib/storage/storage.ts
index b5eee0102..59bb6e9f6 100644
--- a/pipes/linkedin-ai-assistant/lib/storage/storage.ts
+++ b/pipes/linkedin-ai-assistant/lib/storage/storage.ts
@@ -1,7 +1,7 @@
import fs from 'fs/promises';
import path from 'path';
import { ProfileVisit, State, Message, ProfileStore, ProfileDetails, MessageStore } from './types';
-import { getActiveBrowser } from '../browser-setup';
+import { getActiveBrowser, setupBrowser } from '../browser-setup';
import { ChromeSession } from '../chrome-session';
const STORAGE_DIR = path.join(process.cwd(), 'lib', 'storage');
@@ -233,15 +233,15 @@ export async function updateMultipleProfileVisits(state: State, newVisits: Profi
export interface Connection {
profileUrl: string;
- status: 'pending' | 'accepted' | 'declined' | 'email_required' | 'cooldown';
+ status: 'pending' | 'accepted' | 'declined' | 'email_required' | 'invalid';
timestamp: string;
- cooldownUntil?: string;
}
interface ConnectionsStore {
nextHarvestTime?: string;
connections: Record<string, Connection>;
harvestingStatus: 'stopped' | 'running' | 'cooldown';
+ statusMessage?: string;
connectionsSent: number;
lastRefreshDuration?: number; // in milliseconds
averageProfileCheckDuration?: number; // in milliseconds
@@ -254,6 +254,10 @@ interface ConnectionsStore {
};
isWithdrawing: boolean;
withdrawStatus?: WithdrawStatus;
+ heartbeat?: {
+ lastBeat: string; // ISO timestamp
+ processId: string; // unique ID for each harvest run
+ }
}
interface WithdrawStatus {
@@ -351,9 +355,13 @@ export async function saveNextHarvestTime(timestamp: string) {
}
}
-export async function saveHarvestingState(status: 'stopped' | 'running' | 'cooldown') {
+export async function saveHarvestingState(
+ status: 'stopped' | 'running' | 'cooldown',
+ statusMessage?: string
+) {
const connectionsStore = await loadConnections();
connectionsStore.harvestingStatus = status;
+ connectionsStore.statusMessage = statusMessage; // Save the status message
try {
await fs.writeFile(
@@ -361,7 +369,7 @@ export async function saveHarvestingState(status: 'stopped' | 'running' | 'coold
JSON.stringify(connectionsStore, null, 2)
);
await saveToChrome('linkedin_assistant_connections', connectionsStore);
- console.log(`saved harvesting status to both locations: ${status}`);
+ console.log(`saved harvesting status to both locations: ${status} (${statusMessage || 'no message'})`);
} catch (err) {
console.error('error saving harvesting state:', err);
}
@@ -426,29 +434,47 @@ export async function isStopRequested(): Promise<boolean> {
}
export async function saveToChrome(key: string, data: unknown) {
- const session = ChromeSession.getInstance();
- const page = session.getActivePage();
- if (!page) {
- console.log('cannot save to chrome: no active page in session');
- return;
- }
-
try {
- const currentUrl = await page.url();
- // console.log('current page url:', currentUrl);
+ // First try to get existing browser
+ let pages;
+ const { browser } = getActiveBrowser();
+ if (!browser) {
+ console.log('no browser found, attempting to set up...');
+ const { browser: newBrowser } = await setupBrowser();
+ if (!newBrowser) {
+ console.log('cannot save to chrome: failed to set up browser');
+ return;
+ }
+ pages = await newBrowser.pages();
+ } else {
+ pages = await browser.pages();
+ }
+ // console.log('found pages:', pages.length);
- // Only save if we're already on LinkedIn
- if (!currentUrl.includes('linkedin.com')) {
- console.log('skipping chrome storage: not on linkedin.com');
- return;
+ // Find LinkedIn tab
+ let linkedInPage = null;
+ for (const page of pages) {
+ const url = await page.url();
+ // console.log('checking page url:', url);
+ if (url.includes('linkedin.com')) {
+ linkedInPage = page;
+ break;
+ }
}
- await page.evaluate((key: string, data: unknown) => {
+ if (!linkedInPage) {
+ console.log('cannot save to chrome: no linkedin page found');
+ return;
+ }
+
+ await linkedInPage.evaluate((key: string, data: unknown) => {
localStorage.setItem(key, JSON.stringify(data));
- console.log('saved to chrome storage:', key);
+ return true;
}, key, data);
+
+ // console.log('successfully saved to chrome storage:', key);
} catch (err) {
- console.log('failed to save to chrome storage:', err);
+ console.log('failed to save to chrome storage:', {error: err, key});
}
}
@@ -541,4 +567,79 @@ export async function loadCronLogs(): Promise<CronLog[]> {
} catch {
return [];
}
+}
+
+export async function updateHeartbeat(processId: string) {
+ const store = await loadConnections();
+ store.heartbeat = {
+ lastBeat: new Date().toISOString(),
+ processId
+ };
+ console.log('updating heartbeat:', {
+ processId,
+ timestamp: store.heartbeat.lastBeat
+ });
+ await fs.writeFile(
+ path.join(STORAGE_DIR, 'connections.json'),
+ JSON.stringify(store, null, 2)
+ );
+}
+
+export async function isHarvestingAlive(): Promise<boolean> {
+ const store = await loadConnections();
+ if (!store.heartbeat) {
+ // console.log('no heartbeat found');
+ return false;
+ }
+
+ const lastBeat = new Date(store.heartbeat.lastBeat);
+ const now = new Date();
+
+ // If no heartbeat in last 30 seconds, consider process dead
+ const isAlive = now.getTime() - lastBeat.getTime() < 30_000;
+// console.log('harvest heartbeat check:', {
+// lastBeat: store.heartbeat.lastBeat,
+// processId: store.heartbeat.processId,
+// isAlive,
+// timeSinceLastBeat: `${Math.floor((now.getTime() - lastBeat.getTime()) / 1000)}s`
+// });
+
+ return isAlive;
+}
+
+export interface HarvestStatus {
+ connectionsSent: number;
+ weeklyLimitReached: boolean;
+ dailyLimitReached: boolean;
+ nextHarvestTime?: string;
+ stopped?: boolean;
+ harvestingStatus: 'stopped' | 'running' | 'cooldown';
+ statusMessage?: string; // Add this field
+}
+
+export async function getHarvestingStatus(): Promise<HarvestStatus> {
+ const store = await loadConnections();
+ const isAlive = await isHarvestingAlive();
+
+ if (store.harvestingStatus === 'running' && !isAlive) {
+ console.log('detected dead harvest process, resetting state');
+ await saveHarvestingState('stopped', 'harvest process died unexpectedly');
+ return {
+ harvestingStatus: 'stopped',
+ connectionsSent: store.connectionsSent || 0,
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ nextHarvestTime: store.nextHarvestTime,
+ statusMessage: 'harvest process died unexpectedly'
+ };
+ }
+
+ return {
+ harvestingStatus: store.harvestingStatus,
+ connectionsSent: store.connectionsSent || 0,
+ weeklyLimitReached: false,
+ dailyLimitReached: false,
+ nextHarvestTime: store.nextHarvestTime,
+ statusMessage: store.statusMessage
+ };
}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/next.config.mjs b/pipes/linkedin-ai-assistant/next.config.mjs
index 33e81b663..2065da661 100644
--- a/pipes/linkedin-ai-assistant/next.config.mjs
+++ b/pipes/linkedin-ai-assistant/next.config.mjs
@@ -1,3 +1,4 @@
+import {withSentryConfig} from '@sentry/nextjs';
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
@@ -16,5 +17,42 @@ const nextConfig = {
},
};
-export default nextConfig;
+export default withSentryConfig(nextConfig, {
+// For all available options, see:
+// https://github.com/getsentry/sentry-webpack-plugin#options
+org: "mediar-n5",
+project: "linkedin-pipe",
+
+// Only print logs for uploading source maps in CI
+silent: !process.env.CI,
+
+// For all available options, see:
+// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
+
+// Upload a larger set of source maps for prettier stack traces (increases build time)
+widenClientFileUpload: true,
+
+// Automatically annotate React components to show their full name in breadcrumbs and session replay
+reactComponentAnnotation: {
+enabled: true,
+},
+
+// Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers.
+// This can increase your server load as well as your hosting bill.
+// Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-
+// side errors will fail.
+tunnelRoute: "/monitoring",
+
+// Hides source maps from generated client bundles
+hideSourceMaps: true,
+
+// Automatically tree-shake Sentry logger statements to reduce bundle size
+disableLogger: true,
+
+// Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.)
+// See the following for more information:
+// https://docs.sentry.io/product/crons/
+// https://vercel.com/docs/cron-jobs
+automaticVercelMonitors: true,
+});
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/package.json b/pipes/linkedin-ai-assistant/package.json
index 9fb22cb34..11e9d7da2 100644
--- a/pipes/linkedin-ai-assistant/package.json
+++ b/pipes/linkedin-ai-assistant/package.json
@@ -16,9 +16,9 @@
"@radix-ui/react-switch": "^1.1.1",
"@radix-ui/react-toast": "^1.2.4",
"@radix-ui/react-tooltip": "^1.1.6",
- "@screenpipe/browser": "0.1.24",
- "@screenpipe/js": "^1.0.7",
- "@sentry/nextjs": "^8.42.0",
+ "@screenpipe/browser": "0.1.22",
+ "@screenpipe/js": "^1.0.6",
+ "@sentry/nextjs": "^8",
"@tauri-apps/api": "^2.1.1",
"chrome-launcher": "^1.1.2",
"class-variance-authority": "^0.7.1",
diff --git a/pipes/linkedin-ai-assistant/sentry.client.config.ts b/pipes/linkedin-ai-assistant/sentry.client.config.ts
new file mode 100644
index 000000000..e1ef4d362
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/sentry.client.config.ts
@@ -0,0 +1,28 @@
+// This file configures the initialization of Sentry on the client.
+// The config you add here will be used whenever a users loads a page in their browser.
+// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+
+import * as Sentry from "@sentry/nextjs";
+
+Sentry.init({
+ dsn: "https://abd242086d6057ca6c19d16d5d57eccb@o4507617161314304.ingest.us.sentry.io/4508694799712256",
+
+ // Add optional integrations for additional features
+ integrations: [
+ Sentry.replayIntegration(),
+ ],
+
+ // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
+ tracesSampleRate: 1,
+
+ // Define how likely Replay events are sampled.
+ // This sets the sample rate to be 10%. You may want this to be 100% while
+ // in development and sample at a lower rate in production
+ replaysSessionSampleRate: 0.1,
+
+ // Define how likely Replay events are sampled when an error occurs.
+ replaysOnErrorSampleRate: 1.0,
+
+ // Setting this option to true will print useful information to the console while you're setting up Sentry.
+ debug: false,
+});
diff --git a/pipes/linkedin-ai-assistant/sentry.edge.config.ts b/pipes/linkedin-ai-assistant/sentry.edge.config.ts
new file mode 100644
index 000000000..649d2897f
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/sentry.edge.config.ts
@@ -0,0 +1,16 @@
+// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
+// The config you add here will be used whenever one of the edge features is loaded.
+// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
+// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+
+import * as Sentry from "@sentry/nextjs";
+
+Sentry.init({
+ dsn: "https://abd242086d6057ca6c19d16d5d57eccb@o4507617161314304.ingest.us.sentry.io/4508694799712256",
+
+ // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
+ tracesSampleRate: 1,
+
+ // Setting this option to true will print useful information to the console while you're setting up Sentry.
+ debug: false,
+});
diff --git a/pipes/linkedin-ai-assistant/sentry.server.config.ts b/pipes/linkedin-ai-assistant/sentry.server.config.ts
new file mode 100644
index 000000000..ac67207d3
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/sentry.server.config.ts
@@ -0,0 +1,15 @@
+// This file configures the initialization of Sentry on the server.
+// The config you add here will be used whenever the server handles a request.
+// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+
+import * as Sentry from "@sentry/nextjs";
+
+Sentry.init({
+ dsn: "https://abd242086d6057ca6c19d16d5d57eccb@o4507617161314304.ingest.us.sentry.io/4508694799712256",
+
+ // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
+ tracesSampleRate: 1,
+
+ // Setting this option to true will print useful information to the console while you're setting up Sentry.
+ debug: false,
+});