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
Linkedin 6 (#1176)
Matthew Diakonov0a50f8e91d46
diff --git a/pipes/linkedin-ai-assistant/app/api/harvest/withdraw-connections/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/withdraw-connections/route.tsindex 4b64bb993..6dc3d0fa2 100644--- a/pipes/linkedin-ai-assistant/app/api/harvest/withdraw-connections/route.ts+++ b/pipes/linkedin-ai-assistant/app/api/harvest/withdraw-connections/route.ts@@ -1,7 +1,7 @@import { NextResponse } from 'next/server';import { setupBrowser, getActiveBrowser } from '@/lib/browser-setup';import { ChromeSession } from '@/lib/chrome-session';-import { startWithdrawing } from '@/lib/logic-sequence/withdraw-connections';+import { setShouldStop, startWithdrawing } from '@/lib/logic-sequence/withdraw-connections';export const dynamic = 'force-dynamic'export const fetchCache = 'force-no-store'@@ -12,7 +12,12 @@ let isWithdrawing = false;export async function POST() {console.log('stop withdraw requested');isWithdrawing = false;- return NextResponse.json({ message: 'withdraw stop requested' });+ setShouldStop(true);+ return NextResponse.json({+ success: true,+ message: 'withdrawal process stopped',+ isWithdrawing: false+ });}export async function GET(request: Request) {@@ -22,6 +27,7 @@ export async function GET(request: Request) {if (shouldStart && !isWithdrawing) {isWithdrawing = true;+ setShouldStop(false);// First check if we have an active page in the sessionlet page = ChromeSession.getInstance().getActivePage();diff --git a/pipes/linkedin-ai-assistant/components/harvest.tsx b/pipes/linkedin-ai-assistant/components/harvest.tsxindex db1ebf9e2..336c45026 100644--- a/pipes/linkedin-ai-assistant/components/harvest.tsx+++ b/pipes/linkedin-ai-assistant/components/harvest.tsx@@ -1,7 +1,7 @@"use client";import { useState, useEffect } from "react";-import { RefreshCw, Info, Loader2 } from "lucide-react";+import { RefreshCw, Info, Loader2, Clock, Timer } from "lucide-react";import {Tooltip,TooltipContent,@@ -14,7 +14,6 @@ interface ConnectionStats {accepted: number;declined: number;email_required: number;- cooldown: number;total: number;averageProfileCheckDuration?: number;withdrawStatus?: {@@ -35,6 +34,17 @@ function formatTimeRemaining(milliseconds: number): string {return `${minutes}m ${remainingSeconds}s`;}+// Add this helper function near your other utility functions+function formatDateTime(dateStr: string): string {+ const date = new Date(dateStr);+ return date.toLocaleString(undefined, {+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ });+}+// Add error typetype ApiError = {message?: string;@@ -68,9 +78,23 @@ function CountdownTimer({ targetTime, prefix = "next profile in:" }: { targetTim);}+// Add this helper function for status styling+function getStatusStyle(status: HarvestingStatus): string {+ switch (status) {+ case 'running':+ return 'bg-green-100 text-green-800';+ case 'cooldown':+ return 'bg-yellow-100 text-yellow-800';+ case 'stopped':+ return 'bg-gray-100 text-gray-800';+ default:+ return 'bg-gray-100 text-gray-800';+ }+}+export function HarvestClosestConnections() {const [harvestingStatus, setHarvestingStatus] = useState<HarvestingStatus>('stopped');- const [status, setStatus] = useState("");+ const [status, setStatus] = useState<string | JSX.Element>("");const [nextHarvestTime, setNextHarvestTime] = useState<string | null>(null);const [connectionsSent, setConnectionsSent] = useState(0);const [dailyLimitReached, setDailyLimitReached] = useState(false);@@ -80,7 +104,6 @@ export function HarvestClosestConnections() {accepted: 0,declined: 0,email_required: 0,- cooldown: 0,total: 0});const [isRefreshing, setIsRefreshing] = useState(false);@@ -122,9 +145,18 @@ export function HarvestClosestConnections() {if (data.nextHarvestTime) {setNextHarvestTime(data.nextHarvestTime);if (new Date(data.nextHarvestTime) > new Date()) {+ const formattedTime = formatDateTime(data.nextHarvestTime);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()}`;+ ? <span className="flex items-center gap-2">+ <Clock className="h-4 w-4 text-gray-500" />+ <span>daily limit of {data.connectionsSent} connections reached</span>+ <span className="font-medium">{formattedTime}</span>+ </span>+ : <span className="flex items-center gap-2">+ <Timer className="h-4 w-4 text-gray-500" />+ <span>harvesting cooldown until</span>+ <span className="font-medium">{formattedTime}</span>+ </span>;setStatus(message);}}@@ -188,23 +220,40 @@ export function HarvestClosestConnections() {}}, [stats.withdrawStatus?.isWithdrawing]);+ // Add effect to auto-restart after cooldown+ useEffect(() => {+ if (!nextHarvestTime || harvestingStatus !== 'cooldown') return;++ const timeUntilNextHarvest = new Date(nextHarvestTime).getTime() - Date.now();+ if (timeUntilNextHarvest <= 0) return;++ console.log('scheduling auto-restart after cooldown');+ const timer = setTimeout(() => {+ console.log('cooldown finished, auto-restarting harvest');+ startHarvesting();+ }, timeUntilNextHarvest);++ return () => clearTimeout(timer);+ }, [nextHarvestTime, harvestingStatus]);+// Simplify the updateConnectionsStatus functionconst updateConnectionsStatus = async () => {try {- if (isRefreshing || isWithdrawing) {- // Stop the current process- if (isWithdrawing) {- await fetch("/api/harvest/withdraw-connections", { method: "POST" });- setIsWithdrawing(false);- } else {- await fetch("/api/harvest/connection-status-update/stop", { method: "POST" });- setIsRefreshing(false);- setRefreshProgress(null);+ if (isWithdrawing) {+ // Stop withdrawal process+ const response = await fetch("/api/harvest/withdraw-connections", {+ method: "POST"+ });+ if (!response.ok) {+ throw new Error('failed to stop withdrawal');}+ 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) {@@ -292,6 +341,9 @@ export function HarvestClosestConnections() {<span className="text-lg font-medium">farming connections</span>+ <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${getStatusStyle(harvestingStatus)}`}>+ {harvestingStatus}+ </span><div className="flex items-center gap-2">{harvestingStatus === 'stopped' ? (<button@@ -305,7 +357,9 @@ export function HarvestClosestConnections() {</button>) : (<div className="flex items-center gap-2">- <Loader2 className="h-4 w-4 animate-spin text-gray-500" />+ {harvestingStatus === 'running' && (+ <Loader2 className="h-4 w-4 animate-spin text-gray-500" />+ )}<buttononClick={stopHarvesting}className="bg-red-600 text-white px-4 py-2 rounded-md text-base hover:bg-red-700"@@ -321,9 +375,17 @@ export function HarvestClosestConnections() {{restrictionInfo?.isRestricted? `account restricted until ${new Date(restrictionInfo.endDate!).toLocaleString()}`: dailyLimitReached && nextHarvestTime- ? `daily limit reached, next harvest at ${new Date(nextHarvestTime).toLocaleString()}`+ ? <span className="flex items-center gap-2">+ <Clock className="h-4 w-4 text-gray-500" />+ <span>daily limit reached, next harvest at</span>+ <span className="font-medium">{formatDateTime(nextHarvestTime)}</span>+ </span>: weeklyLimitReached && nextHarvestTime- ? `weekly limit reached, next harvest at ${new Date(nextHarvestTime).toLocaleString()}`+ ? <span className="flex items-center gap-2">+ <Clock className="h-4 w-4 text-gray-500" />+ <span>weekly limit reached, next harvest at</span>+ <span className="font-medium">{formatDateTime(nextHarvestTime)}</span>+ </span>: harvestingStatus === 'running'? connectionsSent > 0? `sent ${connectionsSent} connections`@@ -364,6 +426,7 @@ export function HarvestClosestConnections() {onClick={() => updateConnectionsStatus()}className="ml-2 p-2 rounded-md bg-red-100 hover:bg-red-200 transition-all"aria-label="stop withdrawing"+ aria-label="stop withdrawing"><span className="text-red-600 text-sm">stop</span></button>@@ -403,7 +466,7 @@ export function HarvestClosestConnections() {)}</div>- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-4">+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 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>@@ -434,10 +497,6 @@ export function HarvestClosestConnections() {<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>{restrictionInfo?.isRestricted && (diff --git a/pipes/linkedin-ai-assistant/components/reload-button.tsx b/pipes/linkedin-ai-assistant/components/reload-button.tsxindex f60a983ad..eeca09fa4 100644--- a/pipes/linkedin-ai-assistant/components/reload-button.tsx+++ b/pipes/linkedin-ai-assistant/components/reload-button.tsx@@ -10,15 +10,15 @@ export function ReloadButton() {return (<div className="flex items-center gap-1">- <Button+ {/* <Buttonvariant="ghost"size="icon"onClick={handleReload}className="hover:bg-gray-100 dark:hover:bg-gray-800"><RotateCw className="h-4 w-4" />- </Button>- <span className="text-sm text-muted-foreground">sometimes you need to refresh page</span>+ </Button> */}+ <span className="text-sm text-muted-foreground">if button does not work, right click to Reload</span></div>);}\ No newline at end of filediff --git a/pipes/linkedin-ai-assistant/lib/logic-sequence/check-accepted-connections.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-accepted-connections.tsindex ac38175cd..daae83493 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@@ -4,6 +4,7 @@ import { updateWorkflowStep } from '../../app/api/workflow/status/state';import { loadConnections, saveConnection, saveProfile } from '../storage/storage';import { extractProfileText } from '../simple-actions/extract-profile-details-from-page';import { cleanProfileUrl } from '../simple-actions/extract-profiles-from-search-results';+import { shouldStop } from './withdraw-connections';const port = process.env.PORT!;const BASE_URL = `http://127.0.0.1:${port}`;@@ -47,6 +48,11 @@ export async function startCheckingAcceptedConnections(): Promise<void> {console.log(`found ${pendingConnections.length} pending connections older than 14 days to check`);for (const connection of pendingConnections) {+ if (shouldStop) {+ console.log('check accepted connections stopped by user');+ return;+ }+try {console.log(`checking connection status for ${connection.profileUrl}`);diff --git a/pipes/linkedin-ai-assistant/lib/logic-sequence/check-recently-added-connections.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-recently-added-connections.tsnew file mode 100644index 000000000..9b529e9ea--- /dev/null+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-recently-added-connections.ts@@ -0,0 +1,151 @@+import { Page } from 'puppeteer-core';+import { setupBrowser } from '../browser-setup';+import { updateWorkflowStep } from '../../app/api/workflow/status/state';+import { loadConnections } from '../storage/storage';+import { saveConnection } from '../storage/storage';+import { shouldStop } from './withdraw-connections';++const port = process.env.PORT!;+const BASE_URL = `http://127.0.0.1:${port}`;++let isCurrentlyChecking = false;++export async function startCheckingRecentlyAddedConnections(): Promise<void> {+ if (isCurrentlyChecking) {+ console.log('check recently added connections process already in progress');+ return;+ }++ isCurrentlyChecking = true;+ console.log('starting check recently added connections process');++ try {+ // Browser setup+ updateWorkflowStep('browser', 'running', 'connecting to chrome');+ const statusResponse = await fetch(`${BASE_URL}/api/chrome/status`);+ const statusData = await statusResponse.json();++ if (statusData.status !== 'connected' || !statusData.wsUrl) {+ throw new Error('chrome not connected');+ }++ const { page } = await setupBrowser();+ updateWorkflowStep('browser', 'done', 'browser connected');++ // Load connections store to get pending connections+ const connectionsStore = await loadConnections();+ const pendingConnections = Object.values(connectionsStore.connections)+ .filter(conn => conn.status === 'pending')+ .map(conn => conn.profileUrl);++ console.log(`found ${pendingConnections.length} pending connections to check against recently added`);++ // Visit connections page+ await page.goto('https://www.linkedin.com/mynetwork/invite-connect/connections/', {+ waitUntil: 'domcontentloaded',+ timeout: 30000+ });++ // Wait for the sort button to be visible+ await page.waitForFunction(`document.querySelector('button[aria-label*="Sort by"]') !== null`, {+ timeout: 10000+ });++ // Verify sort is set to "Recently Added"+ console.log('checking sort button status');+ const sortButton = await page.$('button[aria-label*="Sort by"]');+ const sortText = await sortButton?.evaluate(el => el.textContent);+ console.log('current sort:', sortText);++ if (!sortText?.toLowerCase().includes('recently added')) {+ console.log('changing sort to recently added');+ await sortButton?.click();+ await page.waitForFunction(`new Promise(r => setTimeout(r, 1000))`);+ const recentlyAddedOption = await page.$('button:has-text("Recently added")');+ if (!recentlyAddedOption) {+ console.log('could not find recently added option');+ throw new Error('recently added sort option not found');+ }+ await recentlyAddedOption.click();+ await page.waitForFunction(`new Promise(r => setTimeout(r, 2000))`);+ }++ // Extract recently added connections+ console.log('starting to extract connections');+ const recentlyAddedProfiles = new Set<{url: string, name: string, time: string}>();+ let scrollTries = 0;+ const maxScrollTries = 5;+ let initialCardCount = await page.$$eval('.mn-connection-card', cards => cards.length);+ const maxConnections = 100;++ while (scrollTries < maxScrollTries) {+ if (shouldStop) {+ console.log('check recently added connections stopped by user during scrolling');+ return;+ }++ console.log(`scroll attempt ${scrollTries + 1}/${maxScrollTries}`);+ await page.keyboard.press('PageDown');+ await page.keyboard.press('PageDown');+ await new Promise(resolve => setTimeout(resolve, 2000));++ const currentCardCount = await page.$$eval('.mn-connection-card', cards => {+ console.log('after scroll: found', cards.length, 'cards');+ return cards.length;+ });++ if (currentCardCount >= maxConnections) {+ console.log(`reached max connections limit (${maxConnections})`);+ break;+ }++ // Check for "Show more" button at bottom+ if (scrollTries === maxScrollTries - 1) {+ const showMoreButton = await page.$('button.scaffold-finite-scroll__load-button');+ if (showMoreButton) {+ console.log('found show more button, clicking...');+ await showMoreButton.click();+ await new Promise(resolve => setTimeout(resolve, 1000));+ scrollTries = 0;+ initialCardCount = currentCardCount;+ continue;+ }+ }++ if (currentCardCount > initialCardCount) {+ console.log(`found ${currentCardCount - initialCardCount} new cards`);+ initialCardCount = currentCardCount;+ } else {+ console.log('no new cards, trying again...');+ scrollTries++;+ }+ }++ // Compare with pending connections+ const recentlyAddedPending = pendingConnections.filter(pendingUrl => {+ const cleanPendingUrl = pendingUrl.replace(/\/$/, '').toLowerCase();+ return Array.from(recentlyAddedProfiles).some(profile =>+ profile.url.replace(/\/$/, '').toLowerCase() === cleanPendingUrl+ );+ });++ console.log(`found ${recentlyAddedPending.length} pending connections that were recently added`);+ console.log('recently added pending connections:', recentlyAddedPending);++ // Update their status to accepted+ for (const profileUrl of recentlyAddedPending) {+ await saveConnection({+ profileUrl,+ status: 'accepted',+ timestamp: new Date().toISOString()+ });+ }+ console.log(`updated ${recentlyAddedPending.length} connections to accepted status`);++ } catch (error) {+ console.error('check recently added connections process failed:', error);+ throw error;+ } finally {+ isCurrentlyChecking = false;+ }+}diff --git a/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts b/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.tsindex ace4e9e76..b7dab8852 100644--- a/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts@@ -5,11 +5,17 @@ import { showClickAnimation } from '../simple-actions/click-animation';import { checkIfRestricted } from '../simple-actions/check-if-restricted';import { saveConnection, setWithdrawingStatus } from '../storage/storage';import { startCheckingAcceptedConnections } from './check-accepted-connections';+import { startCheckingRecentlyAddedConnections } from './check-recently-added-connections';const port = process.env.PORT!;const BASE_URL = `http://127.0.0.1:${port}`;let isCurrentlyWithdrawing = false;+export let shouldStop = false;++export function setShouldStop(value: boolean) {+ shouldStop = value;+}export async function startWithdrawing(): Promise<void> {if (isCurrentlyWithdrawing) {@@ -22,6 +28,24 @@ export async function startWithdrawing(): Promise<void> {console.log('starting withdraw process');try {+ // Reset the flag at start+ await setWithdrawingStatus(true);++ // Check if we should stop frequently during the process+ if (shouldStop) {+ console.log('withdraw process stopped by user');+ await setWithdrawingStatus(false, {+ reason: 'stopped by user',+ timestamp: new Date().toISOString()+ });+ return;+ }++ // First check recently added connections+ console.log('checking recently added connections first');+ if (shouldStop) return;+ await startCheckingRecentlyAddedConnections();+// Browser setupupdateWorkflowStep('browser', 'running', 'connecting to chrome');const statusResponse = await fetch(`${BASE_URL}/api/chrome/status`);@@ -39,6 +63,15 @@ export async function startWithdrawing(): Promise<void> {await navigateToSentInvitations(page);while (true) {+ if (shouldStop) {+ console.log('withdraw process stopped by user during main loop');+ await setWithdrawingStatus(false, {+ reason: 'stopped by user',+ timestamp: new Date().toISOString()+ });+ return;+ }+const foundProfilesToWithdraw = await withdrawOldInvitations(page);if (!foundProfilesToWithdraw) {const hasNextPage = await goToNextPage(page);@@ -87,6 +120,11 @@ async function withdrawOldInvitations(page: Page): Promise<boolean> {let foundOldInvitation = false;for (const card of cards) {+ if (shouldStop) {+ console.log('withdraw process stopped by user during card processing');+ return false;+ }+try {// Re-query elements within each card to ensure fresh referencesconst profileLink = await card.$('a[href*="/in/"]');diff --git a/pipes/linkedin-ai-assistant/lib/storage/storage.ts b/pipes/linkedin-ai-assistant/lib/storage/storage.tsindex e593c1be3..8ed8d9124 100644--- a/pipes/linkedin-ai-assistant/lib/storage/storage.ts+++ b/pipes/linkedin-ai-assistant/lib/storage/storage.ts@@ -434,22 +434,19 @@ export async function saveToChrome(key: string, data: unknown) {}try {- console.log('current page url:', await page.url());+ const currentUrl = await page.url();+ // console.log('current page url:', currentUrl);- // Navigate to LinkedIn if we're not already there- if (!page.url().includes('linkedin.com')) {- console.log('navigating to linkedin.com...');- await page.goto('https://www.linkedin.com');- console.log('navigation complete, new url:', await page.url());+ // Only save if we're already on LinkedIn+ if (!currentUrl.includes('linkedin.com')) {+ console.log('skipping chrome storage: not on linkedin.com');+ return;}- // console.log(`attempting to save ${key} to chrome storage...`);await page.evaluate((key: string, data: unknown) => {- console.log('in page context, saving:', key, data);localStorage.setItem(key, JSON.stringify(data));- console.log('storage after save:', localStorage.getItem(key));+ console.log('saved to chrome storage:', key);}, key, data);- // console.log('chrome storage save complete');} catch (err) {console.log('failed to save to chrome storage:', err);}