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

cron job for harvesting and additional check for frame detachment (#1182)

Matthew Diakonov086c53fa3dc7
diff --git a/pipes/linkedin-ai-assistant/app/api/harvest/check/route.ts b/pipes/linkedin-ai-assistant/app/api/harvest/check/route.ts
new file mode 100644
index 000000000..53e20679c
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/app/api/harvest/check/route.ts
@@ -0,0 +1,75 @@
+import { NextResponse } from "next/server";
+import { loadConnections, saveCronLog } from "../../../../lib/storage/storage";
+
+export async function GET() {
+ try {
+ const connections = await loadConnections();
+ const now = new Date();
+ const nextHarvestTime = connections.nextHarvestTime ? new Date(connections.nextHarvestTime) : null;
+
+ console.log('checking harvest conditions:', {
+ nextHarvestTime: nextHarvestTime?.toISOString(),
+ currentStatus: connections.harvestingStatus,
+ });
+
+ // If it's time to harvest
+ if (nextHarvestTime && now >= nextHarvestTime) {
+ // Don't start if already running
+ if (connections.harvestingStatus === 'running') {
+ await saveCronLog({
+ timestamp: now.toISOString(),
+ action: 'check',
+ result: 'already running',
+ nextHarvestTime: nextHarvestTime.toISOString()
+ });
+ return NextResponse.json({ message: 'harvest already running' });
+ }
+
+ console.log('starting harvest: next harvest time reached');
+
+ const startResponse = await fetch('http://localhost:3000/api/harvest/start', {
+ method: 'POST',
+ });
+
+ if (!startResponse.ok) {
+ await saveCronLog({
+ timestamp: now.toISOString(),
+ action: 'check',
+ result: 'failed to start',
+ nextHarvestTime: nextHarvestTime.toISOString()
+ });
+ throw new Error('failed to start harvest');
+ }
+
+ await saveCronLog({
+ timestamp: now.toISOString(),
+ action: 'check',
+ result: 'started harvest',
+ nextHarvestTime: nextHarvestTime.toISOString()
+ });
+
+ return NextResponse.json({ message: 'harvest started' });
+ }
+
+ await saveCronLog({
+ timestamp: now.toISOString(),
+ action: 'check',
+ result: 'not time yet',
+ nextHarvestTime: nextHarvestTime?.toISOString()
+ });
+
+ return NextResponse.json({
+ message: 'harvest check completed, not time yet',
+ nextHarvestTime: nextHarvestTime?.toISOString()
+ });
+
+ } catch (error) {
+ console.error('error in harvest check:', error);
+ await saveCronLog({
+ timestamp: new Date().toISOString(),
+ action: 'check',
+ result: `error: ${error}`
+ });
+ return NextResponse.json({ error: 'failed to check harvest status' }, { status: 500 });
+ }
+}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/components/harvest.tsx b/pipes/linkedin-ai-assistant/components/harvest.tsx
index f422110fa..71c948af5 100644
--- a/pipes/linkedin-ai-assistant/components/harvest.tsx
+++ b/pipes/linkedin-ai-assistant/components/harvest.tsx
@@ -149,12 +149,12 @@ export function HarvestClosestConnections() {
const message = data.connectionsSent >= 35
? <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>daily limit reached, next harvest at</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>next harvest scheduled for</span>
<span className="font-medium">{formattedTime}</span>
</span>;
setStatus(message);
@@ -170,25 +170,31 @@ export function HarvestClosestConnections() {
loadInitialState();
}, []);
- // Stats polling without condition
+ // Stats polling stats, load connections
useEffect(() => {
const interval = setInterval(async () => {
try {
- const res = await fetch("/api/harvest/stats");
+ const res = await fetch("/api/harvest/stats"); // Changed from /api/harvest/stats
if (!res.ok) return;
const data = await res.json();
- // update stats
+ // Update both stats and status
if (data.stats) {
setStats(data.stats);
}
+ if (data.harvestingStatus) {
+ setHarvestingStatus(data.harvestingStatus);
+ }
+ if (data.nextHarvestTime) {
+ setNextHarvestTime(data.nextHarvestTime);
+ }
} catch (error) {
- console.error("failed to fetch stats:", error);
+ console.error("failed to fetch status:", error);
}
}, 2000);
-
+
return () => clearInterval(interval);
- }, []); // Empty dependency array since we want it to run always
+ }, []);
// Add this useEffect near your other effects
useEffect(() => {
@@ -220,22 +226,6 @@ 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 function
const updateConnectionsStatus = async () => {
try {
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 03e17eb17..04de38ca1 100644
--- a/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.ts
+++ b/pipes/linkedin-ai-assistant/lib/logic-sequence/harvest-connections.ts
@@ -364,14 +364,18 @@ async function clickNextConnectButton(
stopRequested: boolean
): Promise<ConnectionResult> {
try {
- // Load existing connections first
- const { connections } = await loadConnections();
+ // Simple check if page is still valid
+ if (page.isClosed()) {
+ console.log('page is closed, cannot proceed');
+ return { success: false };
+ }
- const connectButtonSelector =
- 'button[aria-label^="Invite"][aria-label$="to connect"]';
+ const { connections } = await loadConnections();
+
+ const connectButtonSelector = 'button[aria-label^="Invite"][aria-label$="to connect"]';
+
+ // Use evaluateHandle for more stable element selection
const connectButtons = await page.$$(connectButtonSelector);
-
- // Add logging for found buttons
console.log(`found ${connectButtons.length} connect buttons`);
// Log page structure
diff --git a/pipes/linkedin-ai-assistant/lib/storage/storage.ts b/pipes/linkedin-ai-assistant/lib/storage/storage.ts
index 8ed8d9124..b5eee0102 100644
--- a/pipes/linkedin-ai-assistant/lib/storage/storage.ts
+++ b/pipes/linkedin-ai-assistant/lib/storage/storage.ts
@@ -503,4 +503,42 @@ export async function saveRestrictionInfo(info: {
);
await saveToChrome('linkedin_assistant_connections', store);
console.log('saved restriction info:', info);
+}
+
+// Add this interface
+interface CronLog {
+ timestamp: string;
+ action: string;
+ result: string;
+ nextHarvestTime?: string;
+}
+
+// Add these functions
+export async function saveCronLog(log: CronLog) {
+ const logPath = path.join(STORAGE_DIR, 'cron-logs.json');
+ let logs: CronLog[] = [];
+
+ try {
+ const data = await fs.readFile(logPath, 'utf-8');
+ logs = JSON.parse(data);
+ } catch {
+ // File doesn't exist yet, start with empty array
+ }
+
+ // Add new log and keep last 100 entries
+ logs.unshift(log);
+ logs = logs.slice(0, 100);
+
+ await fs.writeFile(logPath, JSON.stringify(logs, null, 2));
+ console.log('saved cron log:', log);
+}
+
+export async function loadCronLogs(): Promise<CronLog[]> {
+ const logPath = path.join(STORAGE_DIR, 'cron-logs.json');
+ try {
+ const data = await fs.readFile(logPath, 'utf-8');
+ return JSON.parse(data);
+ } catch {
+ return [];
+ }
}
\ No newline at end of file
diff --git a/pipes/linkedin-ai-assistant/pipe.json b/pipes/linkedin-ai-assistant/pipe.json
new file mode 100644
index 000000000..b0c555dc1
--- /dev/null
+++ b/pipes/linkedin-ai-assistant/pipe.json
@@ -0,0 +1,8 @@
+{
+ "crons": [
+ {
+ "path": "/api/harvest/check",
+ "schedule": "0 */5 * * * *"
+ }
+ ]
+}