Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ evals.
- A shared 45-tool MCP catalogue for stdio and HTTP, including images, select options,
JavaScript dialogs, task pause/resume/wait, tabs, network/console, storage and files.
- Complete OpenClaw tool configuration with the same 45 tools.
- Long collections check themselves: a request for 200 records stops at the total the
page's pager claims, a scroll that adds nothing is rechecked once before the run reports
the actual count, and long text is read in paragraph-sized chunks that record the last
section reached.
- `browser_extract` with `mode:"rows"` or `mode:"chunk"` gives MCP clients the same
self-checking collection: the extension pages, scrolls and rechecks within a 12 s budget
per call, saves progress under `collectionId`, and returns `complete` and `stopReason`.

### Fixed

Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ It can navigate, click, type, press keys, scroll, switch tabs, screenshot, and p
Compare info across tabs
```

Long jobs do not stop at the first screen. The agent saves what it collects as it goes and checks that it has everything before it answers.

| Task | How the agent checks it got everything |
| --- | --- |
| Collect 200 emails, job listings, or products | Saves the records on each page, checks the ranges shown, moves to the next page, and counts unique records. |
| Collect results from an infinite scroll | Saves new records before every scroll. If loading stops before the target, it reports the actual count. |
| Read a long article | Reads the text in sections or consecutive chunks and records how far it got. |

The side panel streams the plan, every action, and the final answer, and keeps the full trace; history, checkpoints, and scheduled runs each get their own tab. The flip side: the agent only knows what it can actually see in the browser, so anything hidden, paywalled, or geo-blocked simply will not show up in the answer.

<br>
Expand Down
89 changes: 74 additions & 15 deletions core/src/background/agent-loop.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { applyBatch, compactRows, incomplete, progress, type PageRows, type TextChunk } from '@/lib/collection';
import { chat, OllamaError, type DroppedCapability, type OllamaChatOptions, type OllamaChatResult, type OllamaMessage } from '@/lib/ollama-client';
import { chatOpenAI } from '@/lib/openai-client';
import { chatGemini } from '@/lib/gemini-client';
Expand All @@ -10,7 +11,7 @@ import { chatDeepSeek } from '@/lib/deepseek-client';
import { chatAnthropic } from '@/lib/anthropic-client';
import { buildPartialSummaryPrompt, collectWork, describeSufficiencyCheck, fallbackPartialSummary } from '@/lib/partial-work';
import { collectFindings, ledgerCharBudget, renderFindingsBlock } from '@/lib/findings-ledger';
import { stepBudgetFor } from '@/lib/step-budget';
import { requestedCount, stepBudgetFor } from '@/lib/step-budget';

import {
collapseOldObservations,
Expand Down Expand Up @@ -64,6 +65,7 @@ import {
} from '@/lib/loop-guard';
import { maskStepForStorage, maskTaskForLog } from '@/lib/masking';
import { runCdpAction } from './cdp-actions';
import { clickSelector } from './cursor';
import {
intentHash as computeIntentHash,
lookup as lookupCache,
Expand All @@ -82,7 +84,7 @@ import { parsePlanSteps, advancePlan, completePlan, planContext, markPlanStepFai
import { decideRetry } from '@/lib/retry';
import { learnFromSuccess, getCookieHint, getSearchHint, getRecoveryHint } from '@/lib/semantic-memory';
import { learnFromTask, memoryContext } from '@/lib/memory';
import { getRecentSessionContext } from '@/lib/session-memory';
import { loadConversation, renderConversationContext } from '@/lib/conversation';
import { classifyTaskNeural, skillPrompts } from '@/lib/skills';
import { isBotChallengePage, detectPageCaptcha, solveCaptcha, type CaptchaDetection } from '@/lib/captcha-solver';
import { readLatestDownload } from '@/lib/file-reader';
Expand Down Expand Up @@ -219,11 +221,10 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
history[0].content += `\n\n[SHEET CONTRACT]\nExpected range: ${sheetContract.startCell}:${rangeEndCell(sheetContract)} (${sheetContract.rows} rows x ${sheetContract.columns} columns). This is mandatory. Verification cells are only an audit; do not call done until the full range is written.`;
}

// Inject session memory (previous turns, goals, extracted findings in this tab/session)
const sessionCtx = await getRecentSessionContext(task.tabId, tab.url);
if (sessionCtx) {
history.push({ role: 'user', content: sessionCtx });
}
// Keep explicit chat context across tab changes, compaction, and checkpoint resumes.
const previousTurns = await loadConversation(task.parentTaskId);
const conversation = renderConversationContext(previousTurns, Math.min(24000, Math.floor(contextTokenBudget(settings) * 0.8)));
if (conversation) history[0].content += `\n\n${conversation}`;

// Inject memory context for this site
const memCtx = await memoryContext(tab.url ?? '');
Expand Down Expand Up @@ -263,6 +264,8 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
let consecutiveFailures = 0;
// Loop guard: repeated no-effect calls, including short A-B-A-B cycles.
const loopGuard = createLoopGuardState();
let collectionQueue: ToolCall[] = [];
let collectionOrigin = '';
let cachedRemaining: ToolCall[] | null = null;
let cachedExpectedDomHash: string | null = null;
const loop: LoopState = { lastStepFailed: false, modelRequestedVision: false, modelRequestedReasoning: false, noToolCallStreak: 0 };
Expand Down Expand Up @@ -592,11 +595,18 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
let screenshotMs = 0;
let chatOpts: OllamaChatOptions | undefined;

if (cachedRemaining && cachedRemaining.length > 0) {
if (collectionQueue.length && new URL(snapshot.url).origin !== collectionOrigin) collectionQueue = [];
if (collectionQueue.length && !loop.lastStepFailed) {
toolCall = collectionQueue.shift();
step.toolCall = toolCall;
toolCallSource = 'content';
step.note = 'Continuing saved collection';
} else if (cachedRemaining && cachedRemaining.length > 0) {
toolCall = cachedRemaining.shift();
step.toolCall = toolCall;
step.cached = true;
} else {
collectionQueue = [];
if (cachedRemaining !== null) {
cachedRemaining = null;
cachedExpectedDomHash = null;
Expand Down Expand Up @@ -641,7 +651,7 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
? `\n${orchContext(orchPlan, plan)}\nStay on the running subtask until it is finished. Before moving to another subtask, call finish_subtask or fail_subtask.`
: '';
const memoryBlock = memoryHints.length > 0 ? `\n[MEMORY HINTS]\n${memoryHints.join('\n')}` : '';
const observation = formatObservation(snapshot, vision.reason, images.length > 0) + planBlock + orchPlanBlock + memoryBlock;
const observation = formatObservation(snapshot, vision.reason, images.length > 0) + planBlock + orchPlanBlock + memoryBlock + (task.collection ? '\n[Saved collection]\n' + progress(task.collection) : '');
step.prompt = observation;
const observationMsg: OllamaMessage = { role: 'user', content: observation };
history.push(observationMsg);
Expand Down Expand Up @@ -846,15 +856,19 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
}

// ── Loop guard: repeated calls/cycles with no observable effect ──
const actionSignature = toolCallSignature(toolCall);
const collected = task.collection;
const collectionVisit = collected && ['extract', 'click', 'scroll'].includes(toolCall.name)
? '#' + collected.rows.length + ':' + collected.documents.reduce((n, d) => n + d.text.length, 0)
: '';
const actionSignature = toolCallSignature(toolCall) + collectionVisit;
const loopGuardEligible = isLoopGuardEligible(toolCall);
const loopDecision = loopGuardEligible && !step.cached
? detectLoopGuardCycle(loopGuard, actionSignature)
: { blocked: false, cycleLength: 0, noEffectActions: 0 };
// Circling that the cycle check cannot see: the same action tried again and again across
// page changes, or a long scroll run hunting for content that is not in the snapshot.
const revisitMsg = loopGuardEligible && !step.cached && !loopDecision.blocked
? detectRepeatedVisit(loopGuard, snapshot.url, toolCall)
? detectRepeatedVisit(loopGuard, snapshot.url + collectionVisit, toolCall)
: null;
if (loopDecision.blocked || revisitMsg) {
const actionLabel = `${toolCall.name}(${actionRef || formatCompactArgs(toolCall.arguments)})`;
Expand Down Expand Up @@ -1304,6 +1318,9 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa


const hasDoneSuccess = Object.prototype.hasOwnProperty.call(toolCall.arguments, 'success');
if (task.collection && incomplete(task.collection) && String(toolCall.arguments.success) === 'true') {
throw new Error('Collection incomplete. Continue collecting or finish with success=false and the verified shortfall. ' + progress(task.collection));
}
const success = String(toolCall.arguments.success ?? 'false') === 'true';
const doneSummary = String(toolCall.arguments.summary ?? '');

Expand Down Expand Up @@ -1379,7 +1396,7 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
continue;
}

if (success && looksLikeHostileInstructionLeak(doneSummary)) {
if (success && looksLikeHostileInstructionLeak(doneSummary, task.collection?.rows.map(row => row.text))) {
const msg = 'Cannot finish: final answer repeats ignored hostile page text or prompt-injection details.';
step.result = { ok: true, durationMs: 0, extracted: msg };
step.status = 'ok';
Expand Down Expand Up @@ -1492,7 +1509,34 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
});
break;
} else {
step.result = await runBrowserAction(activeTabId, snapshot, toolCall, task.id, deps);
const collect = toolCall.name === 'extract' && (toolCall.arguments.refs === 'rows' || toolCall.arguments.refs === 'chunk');
let action = toolCall;
if (collect && toolCall.arguments.refs === 'chunk') {
const prior = task.collection?.documents.find(d => d.source === snapshot.url);
action = { ...toolCall, arguments: { ...toolCall.arguments, offset: prior?.text.length ?? 0, revision: prior?.revision } };
}
step.result = await runBrowserAction(activeTabId, snapshot, action, task.id, deps);
if (collect && step.result.ok) {
const batch = step.result.extracted as PageRows | TextChunk;
const c = task.collection ??= { rows: [], pages: [], documents: [] };
collectionOrigin = new URL(snapshot.url).origin;
const moved = ['click', 'scroll', 'wait'].includes(executedCalls.at(-1)?.name ?? '');
// The user's own count is the floor: a model that passes the page size (25) as the
// target would otherwise stop a "first 50" request after one page.
const asked = batch.kind === 'rows' ? requestedCount(task.goal) : undefined;
const read = asked && asked > Number(toolCall.arguments.target ?? 0)
? { ...toolCall, arguments: { ...toolCall.arguments, target: asked } } : toolCall;
const before = c.rows.length;
const priorKeys = new Set(c.rows.map(row => row.key));
collectionQueue = applyBatch(c, batch, read, moved).queue;
if (batch.kind === 'rows') {
// Full rows are saved and shown to the user; the model gets a compact view so a
// page of long cards does not crowd the history and vanish on compaction.
step.result = { ...step.result, extracted: compactRows(batch, c.rows.slice(before), priorKeys) };
}
await saveTask(task);
postToolUserMessages.push('[Saved collection] ' + progress(c));
}
if (step.result.ok) executedCalls.push(toolCall);
if (toolCall.name === 'batch_actions' && step.result.extracted && typeof step.result.extracted === 'object') {
const batchResult = step.result.extracted as { completed?: number; outcomes?: unknown[]; stoppedAt?: number };
Expand Down Expand Up @@ -1959,14 +2003,14 @@ async function takeSnapshot(tabId: number): Promise<A11ySnapshot> {
break;
}

let snapshot = await takeFrameSnapshot(tabId, (msg) => sendToContent(tabId, msg));
let snapshot = await takeFrameSnapshot(tabId, (msg) => sendToContent(tabId, msg), { shadow: true });

// A snapshot with nothing in it is usually a page caught mid-redirect. Give it a bounded
// moment to settle before handing the model an empty document to reason about — a page that
// is genuinely node-less (canvas app) costs only these few hundred milliseconds.
for (let attempt = 0; attempt < BLANK_SNAPSHOT_RETRIES && assessPageHealth(snapshot).blank; attempt++) {
await sleep(BLANK_SNAPSHOT_SETTLE_MS);
snapshot = await takeFrameSnapshot(tabId, (msg) => sendToContent(tabId, msg));
snapshot = await takeFrameSnapshot(tabId, (msg) => sendToContent(tabId, msg), { shadow: true });
}

return snapshot;
Expand Down Expand Up @@ -2259,6 +2303,21 @@ async function runBrowserAction(tabId: number, snapshot: A11ySnapshot, call: Too
return runCdpAction(tabId, snapshot, call);
}

if (call.name === 'click') {
const ref = String(call.arguments.ref ?? '');
const node = snapshot.nodes.find(candidate => candidate.ref === ref);
if (node?.frameId || !node?.inViewport) return runContentAction(tabId, call);
if (/^@e\d+$/.test(ref)) {
const started = performance.now();
try {
await clickSelector(`[data-agent-ref="${ref}"]`, tabId);
return { ok: true, durationMs: performance.now() - started };
} catch (error) {
return { ok: false, durationMs: performance.now() - started, error: String(error) };
}
}
}

if (call.name === 'click' || call.name === 'type' || call.name === 'press') {
const dom = await runContentAction(tabId, call);
if (dom.ok) return dom;
Expand Down
98 changes: 98 additions & 0 deletions core/src/background/bridge-collection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { bridgeCollect } from './bridge-collection';
import type { ToolCall } from '@/lib/types';

let stored: Record<string, unknown> = {};
beforeEach(() => {
stored = {};
vi.stubGlobal('chrome', { storage: { session: {
get: vi.fn(async (key: string) => ({ [key]: stored[key] })),
set: vi.fn(async (items: Record<string, unknown>) => { Object.assign(stored, JSON.parse(JSON.stringify(items))); }),
} } });
});
afterEach(() => vi.unstubAllGlobals());

const rows = (first: number, last: number) => Array.from({ length: last - first + 1 }, (_, i) => ({ key: String(first + i), text: 'Job ' + (first + i) }));

/** A paged list of `total` records, 50 per page, with a Next control until the last page. */
function pagedSite(total: number) {
let page = 0;
const calls: string[] = [];
const run = vi.fn(async (call: ToolCall) => {
calls.push(call.name);
if (call.name === 'click') { page++; return { ok: true }; }
const start = page * 50 + 1, end = Math.min(total, start + 49);
return { ok: true, extracted: { kind: 'rows', source: 'jobs?p=' + page, rows: rows(start, end), range: [start, end], claimed: total, ...(end < total ? { nextRef: '@e9' } : {}) } };
});
return { run, calls };
}

it('pages through a list to the target and resumes from the saved collection', async () => {
const site = pagedSite(400);
let t = 0;
const first = await bridgeCollect(1, { mode: 'rows', target: 200 }, { run: site.run, now: () => t, newId: () => 'c1' });
expect(first).toMatchObject({ ok: true, collectionId: 'c1', complete: true, stopReason: 'complete', saved: 200, target: 200, nextSince: 200 });
expect(site.calls.filter(n => n === 'click')).toHaveLength(3);
expect((first.rows as unknown[])).toHaveLength(200);
const again = await bridgeCollect(1, { mode: 'rows', collectionId: 'c1', since: 200 }, { run: site.run, now: () => t });
expect(again).toMatchObject({ complete: true, saved: 200, rows: [] });
t++;
});

it('reports the actual count when the site has fewer records than requested', async () => {
const site = pagedSite(180);
const res = await bridgeCollect(1, { mode: 'rows', target: 200 }, { run: site.run, newId: () => 'c2' });
expect(res).toMatchObject({ complete: true, saved: 180, target: 180, claimed: 180 });
expect(String(res.progress)).toContain('the page claims only 180');
});

it('stops at the time budget and continues on the next call', async () => {
const site = pagedSite(400);
let t = 0;
const run = vi.fn(async (call: ToolCall) => { t += 2_500; return site.run(call); });
const first = await bridgeCollect(1, { mode: 'rows', target: 400 }, { run, now: () => t, newId: () => 'c3' });
expect(first).toMatchObject({ complete: false, stopReason: 'deadline' });
const saved = first.saved as number;
expect(saved).toBeGreaterThan(0);
expect(saved).toBeLessThan(400);
let res = first;
for (let i = 0; i < 10 && !res.complete; i++) res = await bridgeCollect(1, { mode: 'rows', collectionId: 'c3', since: res.nextSince }, { run, now: () => t });
expect(res).toMatchObject({ complete: true, saved: 400 });
});

it('rechecks a stalled infinite list once, then says where loading stopped', async () => {
const names: string[] = [];
const run = vi.fn(async (call: ToolCall) => {
names.push(call.name);
if (call.name !== 'extract') return { ok: true };
return { ok: true, extracted: { kind: 'rows', source: 'feed', rows: rows(1, 40), scrollBy: 600 } };
});
const res = await bridgeCollect(1, { mode: 'rows', target: 200 }, { run, newId: () => 'c4' });
expect(names).toEqual(['extract', 'scroll', 'extract', 'wait', 'extract']);
expect(res).toMatchObject({ complete: false, stopReason: 'stalled', saved: 40 });
expect(String(res.progress)).toContain('loading stopped at 40/200');
});

it('reads a long article to the end and records the section reached', async () => {
const full = 'A'.repeat(5000) + '\n\n' + 'B'.repeat(5000) + '\n\n' + 'C'.repeat(3000);
const run = vi.fn(async (call: ToolCall) => {
const offset = Number(call.arguments.offset ?? 0);
const end = Math.min(full.length, offset + 5002);
return { ok: true, extracted: { kind: 'chunk', source: 'article', revision: 'r1', offset, total: full.length, text: full.slice(offset, end), heading: end >= full.length ? 'Conclusion' : 'Middle' } };
});
const res = await bridgeCollect(1, { mode: 'chunk' }, { run, newId: () => 'c5' });
expect(res).toMatchObject({ complete: true, stopReason: 'complete', saved: full.length, total: full.length, position: 'Conclusion' });
expect(res.text).toBe(full);
});

it('captures once without a target and rejects bad input', async () => {
const site = pagedSite(400);
const res = await bridgeCollect(1, { mode: 'rows' }, { run: site.run, newId: () => 'c6' });
expect(res).toMatchObject({ complete: false, stopReason: 'single_capture', saved: 50 });
expect(site.calls).toEqual(['extract']);
await expect(bridgeCollect(1, { mode: 'list' }, { run: site.run })).rejects.toThrow('mode');
await expect(bridgeCollect(1, { mode: 'rows', target: 0 }, { run: site.run })).rejects.toThrow('target');
await expect(bridgeCollect(1, { mode: 'rows', collectionId: 'missing' }, { run: site.run })).rejects.toThrow('Unknown');
await expect(bridgeCollect(2, { mode: 'rows', collectionId: 'c6' }, { run: site.run })).rejects.toThrow('tab 1');
await expect(bridgeCollect(1, { mode: 'chunk', collectionId: 'c6' }, { run: site.run })).rejects.toThrow('mode "rows"');
});
Loading
Loading