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

Linkedin 6 (#1170)

Matthew Diakonoveaeaa7b3af81
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 396d91510..fe30f89cd 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
@@ -1,5 +1,5 @@
import { NextResponse } from 'next/server';
-import { loadConnections, saveConnection, saveRefreshStats, setShouldStopRefresh, getShouldStopRefresh, saveHarvestingState, saveNextHarvestTime } from '@/lib/storage/storage';
+import { loadConnections, saveConnection, saveRefreshStats, setShouldStopRefresh, getShouldStopRefresh, saveHarvestingState, saveNextHarvestTime, saveRestrictionInfo } from '@/lib/storage/storage';
import { setupBrowser, getActiveBrowser } from '@/lib/browser-setup';
import { ChromeSession } from '@/lib/chrome-session';
import { clickCancelConnectionRequest } from '@/lib/simple-actions/click-cancel-connection-request';
@@ -56,8 +56,16 @@ async function checkConnectionStatus(page: Page, profileUrl: string, connection:
if (restrictionStatus.restrictionEndDate) {
await saveHarvestingState('cooldown');
await saveNextHarvestTime(restrictionStatus.restrictionEndDate);
+ await saveRestrictionInfo({
+ isRestricted: true,
+ endDate: restrictionStatus.restrictionEndDate,
+ reason: 'linkedin has detected automated activity on your account'
+ });
} else {
await saveHarvestingState('stopped');
+ await saveRestrictionInfo({
+ isRestricted: false
+ });
}
throw new Error(`account restricted until ${restrictionStatus.restrictionEndDate}`);
}
@@ -212,11 +220,7 @@ export async function GET(request: Request) {
refreshError: null,
rateLimitedUntil: null,
nextProfileTime: nextDelay ? Date.now() + nextDelay : null,
- restrictionInfo: {
- isRestricted: connectionsStore.harvestingStatus === 'cooldown',
- endDate: connectionsStore.nextHarvestTime,
- reason: 'linkedin has detected automated activity on your account'
- }
+ restrictionInfo: connectionsStore.restrictionInfo || null
});
} catch (error) {
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 364bea3cf..c68f1f259 100644
--- a/pipes/linkedin-ai-assistant/app/api/harvest/stats/route.ts
+++ b/pipes/linkedin-ai-assistant/app/api/harvest/stats/route.ts
@@ -24,7 +24,10 @@ export async function GET() {
cooldown: stats?.cooldown || 0,
total: Object.keys(connectionsStore.connections).length,
lastRefreshDuration: connectionsStore.lastRefreshDuration,
- averageProfileCheckDuration: connectionsStore.averageProfileCheckDuration
+ averageProfileCheckDuration: connectionsStore.averageProfileCheckDuration,
+ withdrawStatus: connectionsStore.withdrawStatus || {
+ isWithdrawing: false
+ }
}
});
} catch (error) {
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.ts
new file mode 100644
index 000000000..4b64bb993
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/app/api/harvest/withdraw-connections/route.ts
@@ -0,0 +1,59 @@
+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';
+
+export const dynamic = 'force-dynamic'
+export const fetchCache = 'force-no-store'
+
+// Track withdrawal process state
+let isWithdrawing = false;
+
+export async function POST() {
+ console.log('stop withdraw requested');
+ isWithdrawing = false;
+ return NextResponse.json({ message: 'withdraw stop requested' });
+}
+
+export async function GET(request: Request) {
+ try {
+ const url = new URL(request.url);
+ const shouldStart = url.searchParams.get('start') === 'true';
+
+ if (shouldStart && !isWithdrawing) {
+ isWithdrawing = true;
+
+ // First check if we have an active page in the session
+ let page = ChromeSession.getInstance().getActivePage();
+
+ // If no page in session, try to set up browser
+ if (!page) {
+ const { page: newPage } = await setupBrowser();
+ page = newPage;
+ }
+
+ if (!page) {
+ throw new Error('no active browser page available');
+ }
+
+ // Start withdrawal process in background
+ startWithdrawing().catch(error => {
+ console.error('withdrawal process failed:', error);
+ isWithdrawing = false;
+ });
+ }
+
+ return NextResponse.json({
+ status: isWithdrawing ? 'running' : 'stopped',
+ message: isWithdrawing ? 'withdrawal process running' : 'withdrawal process not running'
+ });
+
+ } catch (error) {
+ console.error('withdrawal process failed:', error);
+ isWithdrawing = false;
+ return NextResponse.json({
+ status: 'error',
+ error: (error as Error).message
+ }, { status: 200 });
+ }
+}
diff --git a/pipes/linkedin-ai-assistant/components/harvest.tsx b/pipes/linkedin-ai-assistant/components/harvest.tsx
index 37483802f..db1ebf9e2 100644
--- a/pipes/linkedin-ai-assistant/components/harvest.tsx
+++ b/pipes/linkedin-ai-assistant/components/harvest.tsx
@@ -17,6 +17,11 @@ interface ConnectionStats {
cooldown: number;
total: number;
averageProfileCheckDuration?: number;
+ withdrawStatus?: {
+ isWithdrawing: boolean;
+ reason?: string;
+ timestamp?: string;
+ };
}
// Add type for harvesting status
@@ -89,6 +94,7 @@ export function HarvestClosestConnections() {
endDate?: string;
reason?: string;
} | null>(null);
+ const [isWithdrawing, setIsWithdrawing] = useState(false);
useEffect(() => {
// Load initial state with status only
@@ -98,11 +104,20 @@ export function HarvestClosestConnections() {
if (!res.ok) return;
const data = await res.json();
+ console.log('initial state data:', data);
+
setHarvestingStatus(data.harvestingStatus || 'stopped');
setConnectionsSent(data.connectionsSent || 0);
setDailyLimitReached(data.dailyLimitReached || false);
setWeeklyLimitReached(data.weeklyLimitReached || false);
- setRestrictionInfo(data.restrictionInfo || null);
+
+ // Fix: Only set restriction if it exists and is actually restricted
+ if (data.restrictionInfo && data.restrictionInfo.isRestricted === true) {
+ console.log('setting restriction info:', data.restrictionInfo);
+ setRestrictionInfo(data.restrictionInfo);
+ } else {
+ setRestrictionInfo(null); // Explicitly set to null if no restriction
+ }
if (data.nextHarvestTime) {
setNextHarvestTime(data.nextHarvestTime);
@@ -166,33 +181,39 @@ export function HarvestClosestConnections() {
};
}, [isRefreshing]); // Only re-run when isRefreshing changes
+ // Add effect to sync withdrawal status
+ useEffect(() => {
+ if (stats.withdrawStatus) {
+ setIsWithdrawing(stats.withdrawStatus.isWithdrawing);
+ }
+ }, [stats.withdrawStatus?.isWithdrawing]);
+
// Simplify the updateConnectionsStatus function
const updateConnectionsStatus = async () => {
try {
- if (isRefreshing) {
- await fetch("/api/harvest/connection-status-update/stop", { method: "POST" });
- setIsRefreshing(false);
- setRefreshProgress(null);
+ 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);
+ }
return;
}
- setIsRefreshing(true);
- // Trigger the update
- const statusRes = await fetch("/api/harvest/connection-status-update?refresh=true");
- if (statusRes.ok) {
- const data = await statusRes.json();
- setHarvestingStatus(data.harvestingStatus || 'stopped');
- setConnectionsSent(data.connectionsSent || 0);
- setDailyLimitReached(data.dailyLimitReached || false);
- setWeeklyLimitReached(data.weeklyLimitReached || false);
- setRestrictionInfo(data.restrictionInfo || null);
-
- if (data.nextHarvestTime) {
- setNextHarvestTime(data.nextHarvestTime);
- }
+ // Start 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);
}
} catch (error) {
- console.error("failed to update connections status:", error);
+ console.error("failed to update/withdraw connections:", error);
+ setIsWithdrawing(false);
}
};
@@ -330,23 +351,35 @@ export function HarvestClosestConnections() {
? 'bg-gray-100 cursor-not-allowed'
: 'hover:bg-gray-100'
}`}
- aria-label="update connections status"
+ aria-label={stats.withdrawStatus?.isWithdrawing ? "stop withdrawing old invitations" : "withdraw old invitations"}
>
<RefreshCw
className={`h-5 w-5 transition-all ${
- isRefreshing ? 'animate-spin text-gray-400' : 'text-gray-500 hover:text-gray-700'
+ isRefreshing || stats.withdrawStatus?.isWithdrawing ? 'animate-spin text-gray-400' : 'text-gray-500 hover:text-gray-700'
}`}
/>
</button>
- {isRefreshing && (
+ {isWithdrawing && (
<button
onClick={() => updateConnectionsStatus()}
className="ml-2 p-2 rounded-md bg-red-100 hover:bg-red-200 transition-all"
- aria-label="stop refreshing"
+ aria-label="stop withdrawing"
>
<span className="text-red-600 text-sm">stop</span>
</button>
)}
+ {(isWithdrawing ||
+ stats.withdrawStatus?.reason?.includes('failed') ||
+ stats.withdrawStatus?.reason?.includes('detected') ||
+ stats.withdrawStatus?.reason?.includes('completed') ||
+ (stats.withdrawStatus?.reason?.includes('finished') &&
+ stats.withdrawStatus?.timestamp &&
+ new Date().getTime() - new Date(stats.withdrawStatus.timestamp).getTime() < 12 * 60 * 60 * 1000)) &&
+ stats.withdrawStatus?.reason && (
+ <span className="ml-2 text-sm text-gray-500">
+ {stats.withdrawStatus.reason}
+ </span>
+ )}
{nextProfileTime && nextProfileTime > Date.now() && (
<div className="ml-2">
<CountdownTimer targetTime={nextProfileTime} />
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
new file mode 100644
index 000000000..ac38175cd
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/check-accepted-connections.ts
@@ -0,0 +1,98 @@
+import { Page } from 'puppeteer-core';
+import { setupBrowser } from '../browser-setup';
+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';
+
+const port = process.env.PORT!;
+const BASE_URL = `http://127.0.0.1:${port}`;
+
+let isCurrentlyChecking = false;
+
+export async function startCheckingAcceptedConnections(): Promise<void> {
+ if (isCurrentlyChecking) {
+ console.log('check accepted connections process already in progress');
+ return;
+ }
+
+ isCurrentlyChecking = true;
+ console.log('starting check accepted 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 all connections and filter for those pending > 14 days
+ const connectionsStore = await loadConnections();
+ const twoWeeksAgo = new Date();
+ twoWeeksAgo.setDate(twoWeeksAgo.getDate() - 14);
+
+ const pendingConnections = Object.values(connectionsStore.connections)
+ .filter(conn => {
+ if (conn.status !== 'pending') return false;
+ const connectionDate = new Date(conn.timestamp);
+ return connectionDate < twoWeeksAgo;
+ });
+
+ console.log(`found ${pendingConnections.length} pending connections older than 14 days to check`);
+
+ for (const connection of pendingConnections) {
+ try {
+ console.log(`checking connection status for ${connection.profileUrl}`);
+
+ // Visit profile
+ await page.goto(connection.profileUrl, {
+ waitUntil: 'networkidle0',
+ timeout: 30000
+ });
+
+ // Check if connected
+ const connectButton = await page.$('button.artdeco-button--connect');
+ const isConnected = !connectButton;
+
+ if (isConnected) {
+ console.log(`connection accepted for ${connection.profileUrl}`);
+
+ // Extract and save profile details
+ const profileDetails = await extractProfileText(page);
+ const cleanUrl = cleanProfileUrl(connection.profileUrl);
+ console.log('extracted profile details:', JSON.stringify(profileDetails).slice(0, 100) + '...');
+
+ await saveProfile(cleanUrl, profileDetails);
+
+ // Update connection status
+ await saveConnection({
+ ...connection,
+ status: 'accepted',
+ timestamp: new Date().toISOString()
+ });
+ }
+
+ // Random delay between profile checks
+ await new Promise(resolve => setTimeout(resolve, 2000 + Math.random() * 3000));
+
+ } catch (error) {
+ console.error(`error checking connection ${connection.profileUrl}:`, error);
+ continue;
+ }
+ }
+
+ console.log('completed checking all pending connections');
+
+ } catch (error) {
+ console.error('check accepted connections process failed:', error);
+ throw error;
+ } finally {
+ isCurrentlyChecking = false;
+ }
+}
\ 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
new file mode 100644
index 000000000..ace4e9e76
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/withdraw-connections.ts
@@ -0,0 +1,211 @@
+import { Page } from 'puppeteer-core';
+import { setupBrowser } from '../browser-setup';
+import { updateWorkflowStep } from '../../app/api/workflow/status/state';
+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';
+
+const port = process.env.PORT!;
+const BASE_URL = `http://127.0.0.1:${port}`;
+
+let isCurrentlyWithdrawing = false;
+
+export async function startWithdrawing(): Promise<void> {
+ if (isCurrentlyWithdrawing) {
+ console.log('withdraw process already in progress');
+ return;
+ }
+
+ isCurrentlyWithdrawing = true;
+ await setWithdrawingStatus(true);
+ console.log('starting withdraw 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');
+
+ // Navigate to sent invitations page
+ updateWorkflowStep('navigation', 'running', 'navigating to sent invitations');
+ await navigateToSentInvitations(page);
+
+ while (true) {
+ const foundProfilesToWithdraw = await withdrawOldInvitations(page);
+ if (!foundProfilesToWithdraw) {
+ const hasNextPage = await goToNextPage(page);
+ if (!hasNextPage) {
+ console.log('goToNextPagefunction stopped');
+ break;
+ }
+ }
+ }
+
+ } catch (error) {
+ console.error('withdraw process failed:', error);
+ await setWithdrawingStatus(false, {
+ reason: `withdraw process failed: ${error}`,
+ timestamp: new Date().toISOString()
+ });
+ throw error;
+ } finally {
+ isCurrentlyWithdrawing = false;
+ }
+}
+
+async function navigateToSentInvitations(page: Page) {
+ console.log('navigating to sent invitations page');
+ await page.goto('https://www.linkedin.com/mynetwork/invitation-manager/sent/', {
+ waitUntil: 'domcontentloaded',
+ timeout: 60000,
+ });
+}
+
+async function randomDelay(baseMs: number = 1000, variationMs: number = 500): Promise<void> {
+ const delay = baseMs + Math.random() * variationMs;
+// console.log(`waiting for ${Math.round(delay)}ms`);
+ await new Promise(resolve => setTimeout(resolve, delay));
+}
+
+async function withdrawOldInvitations(page: Page): Promise<boolean> {
+ console.log('checking for old invitations');
+
+ // Wait for cards to be present after any page update
+ await page.waitForSelector('.invitation-card__container', { timeout: 10000 });
+ await randomDelay(); // Add small delay after content load
+
+ // Re-query cards after ensuring page is loaded
+ const cards = await page.$$('.invitation-card__container');
+ let foundOldInvitation = false;
+
+ for (const card of cards) {
+ try {
+ // Re-query elements within each card to ensure fresh references
+ const profileLink = await card.$('a[href*="/in/"]');
+ const profileUrl = await profileLink?.evaluate(el => el.getAttribute('href'));
+
+ if (!profileUrl) {
+ console.log('no profile url found, skipping');
+ continue;
+ }
+
+ const timeBadge = await card.$('.time-badge');
+ const timeText = await timeBadge?.evaluate(el => el.textContent?.trim());
+
+ if (!timeText) continue;
+
+ const isOldEnough = timeText.includes('month') ||
+ (timeText.includes('week') && parseInt(timeText) >= 2);
+
+ if (isOldEnough) {
+ console.log(`found old invitation for ${profileUrl}: ${timeText}`);
+ foundOldInvitation = true;
+
+ // Re-query the withdraw button
+ const withdrawBtn = await card.$('button[aria-label^="Withdraw invitation"]');
+ if (!withdrawBtn) {
+ console.log('withdraw button not found, skipping');
+ continue;
+ }
+
+ await showClickAnimation(page, withdrawBtn);
+ await withdrawBtn.click();
+ await randomDelay();
+ console.log('clicked withdraw button');
+
+ // Wait for and handle confirmation modal
+ const confirmBtn = await page.waitForSelector('button.artdeco-modal__confirm-dialog-btn[data-test-dialog-primary-btn]', {
+ timeout: 5000
+ });
+
+ if (confirmBtn) {
+ await showClickAnimation(page, confirmBtn);
+ await confirmBtn.click();
+ await randomDelay();
+ console.log('confirmed withdrawal');
+
+ await saveConnection({
+ status: 'declined',
+ timestamp: new Date().toISOString(),
+ profileUrl
+ });
+
+ console.log(`updated status to declined for ${profileUrl}`);
+ await randomDelay(2000); // Longer delay after confirmation
+ }
+ }
+ } catch (error) {
+ console.error('error processing invitation card:', error);
+ continue;
+ }
+ }
+
+ return foundOldInvitation;
+}
+
+async function goToNextPage(page: Page): Promise<boolean> {
+ try {
+ console.log('checking for next page');
+
+ const nextButton = await page.$('button.artdeco-pagination__button--next:not([disabled])');
+ if (!nextButton) {
+ console.log('no next page available - reached last page');
+ await setWithdrawingStatus(false, {
+ reason: 'completed: reached last page of invitations',
+ timestamp: new Date().toISOString()
+ });
+
+ // Start checking accepted connections after withdrawal completes
+ console.log('starting accepted connections check flow');
+ await startCheckingAcceptedConnections();
+
+ return false;
+ }
+
+ const currentUrl = page.url();
+ await showClickAnimation(page, nextButton);
+ await nextButton.click();
+ console.log('navigating to next page');
+
+ // Wait for URL to change
+ await page.waitForFunction(
+ (oldUrl) => window.location.href !== oldUrl,
+ { timeout: 15000 },
+ currentUrl
+ );
+
+ // Check if we got redirected to the base page (LinkedIn's protection mechanism)
+ const newUrl = page.url();
+ if (newUrl.includes('invitationType=CONNECTION')) {
+ console.log('detected linkedin protection redirect');
+ await setWithdrawingStatus(false, {
+ reason: 'paused: linkedin daily withdrawal limit reached',
+ timestamp: new Date().toISOString()
+ });
+ return false;
+ }
+
+ // Wait for content
+ await page.waitForSelector('.invitation-card__container', {
+ timeout: 10000
+ });
+
+ console.log('successfully navigated to next page:', newUrl);
+ return true;
+ } catch (error) {
+ console.error('error during page navigation:', error);
+ await setWithdrawingStatus(false, {
+ reason: `error: page navigation failed - ${error}`,
+ timestamp: new Date().toISOString()
+ });
+ return false;
+ }
+}
diff --git a/pipes/linkedin-ai-assistant/lib/storage/storage.ts b/pipes/linkedin-ai-assistant/lib/storage/storage.ts
index 2f91d9040..e593c1be3 100644
--- a/pipes/linkedin-ai-assistant/lib/storage/storage.ts
+++ b/pipes/linkedin-ai-assistant/lib/storage/storage.ts
@@ -252,6 +252,14 @@ interface ConnectionsStore {
endDate?: string;
reason?: string;
};
+ isWithdrawing: boolean;
+ withdrawStatus?: WithdrawStatus;
+}
+
+interface WithdrawStatus {
+ isWithdrawing: boolean;
+ reason?: string;
+ timestamp?: string;
}
// Define default values
@@ -262,7 +270,8 @@ const DEFAULT_CONNECTION_STORE: ConnectionsStore = {
stopRequested: false,
nextHarvestTime: '',
lastRefreshDuration: 0,
- averageProfileCheckDuration: 0
+ averageProfileCheckDuration: 0,
+ isWithdrawing: false
};
export async function loadConnections(): Promise<ConnectionsStore> {
@@ -469,4 +478,32 @@ export async function loadFromChrome(key: string) {
console.log('failed to load from chrome storage:', err);
return null;
}
+}
+
+export async function setWithdrawingStatus(isWithdrawing: boolean, details?: { reason: string; timestamp: string }) {
+ const store = await loadConnections();
+ store.withdrawStatus = {
+ isWithdrawing,
+ ...(details || {})
+ };
+ await fs.writeFile(
+ path.join(STORAGE_DIR, 'connections.json'),
+ JSON.stringify(store, null, 2)
+ );
+ console.log('saved withdrawal status:', { isWithdrawing, ...details });
+}
+
+export async function saveRestrictionInfo(info: {
+ isRestricted: boolean;
+ endDate?: string;
+ reason?: string;
+}) {
+ const store = await loadConnections();
+ store.restrictionInfo = info;
+ await fs.writeFile(
+ path.join(STORAGE_DIR, 'connections.json'),
+ JSON.stringify(store, null, 2)
+ );
+ await saveToChrome('linkedin_assistant_connections', store);
+ console.log('saved restriction info:', info);
}
\ No newline at end of file