From 801cb33041e26a9ac04b690e9795f32c36be8438 Mon Sep 17 00:00:00 2001 From: KazKozDev Date: Sun, 22 Nov 2026 11:11:32 +0100 Subject: [PATCH] refactor: remove dead functions and the never-written recovery hint read Fifteen functions with no reference anywhere in the code, scripts or tests: cdpPressAndHold, summarizeCall, snapshotSignature, downloadJson, downloadPdfViaPrint, sha256Hex, onSWEvent, anySubtasksPending, getCurrentSubtask, getSubtaskResult, skillPromptForSubtask, isInterrupted, retryPromptForStep, learnRecovery and clearMemory. learnRecovery was the only writer of recoveryMemory, so getRecoveryHint always came back empty while still querying IndexedDB on every retried step. The read and its call site go too. The Dexie table stays declared so existing databases keep a valid schema without a migration. Co-Authored-By: Claude Opus 5.5 --- core/src/background/agent-loop.ts | 8 +--- core/src/background/cdp-actions.ts | 36 ---------------- core/src/lib/action-cache.ts | 18 +------- core/src/lib/export.ts | 68 ------------------------------ core/src/lib/hash.ts | 9 ---- core/src/lib/messaging.ts | 10 ----- core/src/lib/orchestrator.ts | 32 +------------- core/src/lib/partial-work.ts | 5 --- core/src/lib/retry.ts | 28 ------------ core/src/lib/semantic-memory.ts | 43 +------------------ core/src/lib/storage.ts | 1 + 11 files changed, 5 insertions(+), 253 deletions(-) diff --git a/core/src/background/agent-loop.ts b/core/src/background/agent-loop.ts index 91b4df7..912932d 100644 --- a/core/src/background/agent-loop.ts +++ b/core/src/background/agent-loop.ts @@ -82,7 +82,7 @@ import { summarizeExtraction } from '@/lib/extraction'; import { ERROR_PAGE_DOM_HASH_PREFIX, assessPageHealth, describePageTransition, type RecoveryPage } from '@/lib/page-state'; import { parsePlanSteps, advancePlan, completePlan, planContext, markPlanStepFailed, shouldAdvancePlanAfterTool, isValidPlanStepCount, PLAN_MIN_STEPS, PLAN_MAX_STEPS } from '@/lib/planner'; import { decideRetry } from '@/lib/retry'; -import { learnFromSuccess, getCookieHint, getSearchHint, getRecoveryHint } from '@/lib/semantic-memory'; +import { learnFromSuccess, getCookieHint, getSearchHint } from '@/lib/semantic-memory'; import { learnFromTask, memoryContext } from '@/lib/memory'; import { loadConversation, renderConversationContext } from '@/lib/conversation'; import { classifyTaskNeural, skillPrompts } from '@/lib/skills'; @@ -1742,12 +1742,6 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise { await send(target, 'Runtime.evaluate', { expression: stealthScript }); } catch {} } - -/** - * Dispatches a trusted CDP Press and Hold sequence with humanized micro-tremor. - */ -export async function cdpPressAndHold(target: Debuggee, x: number, y: number, durationMs = 6500): Promise { - await send(target, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }); - await send(target, 'Input.dispatchMouseEvent', { - type: 'mousePressed', - x, - y, - button: 'left', - clickCount: 1, - }); - - const startTime = Date.now(); - while (Date.now() - startTime < durationMs) { - await sleep(75); - const jitterX = x + (Math.random() - 0.5) * 2; - const jitterY = y + (Math.random() - 0.5) * 2; - await send(target, 'Input.dispatchMouseEvent', { - type: 'mouseMoved', - x: jitterX, - y: jitterY, - button: 'left', - }).catch(() => {}); - } - - await send(target, 'Input.dispatchMouseEvent', { - type: 'mouseReleased', - x, - y, - button: 'left', - clickCount: 1, - }); - await sleep(100); -} diff --git a/core/src/lib/action-cache.ts b/core/src/lib/action-cache.ts index 400e0e5..5581a60 100644 --- a/core/src/lib/action-cache.ts +++ b/core/src/lib/action-cache.ts @@ -1,6 +1,6 @@ import { db } from './storage'; import { fastHash } from './hash'; -import type { A11ySnapshot, ToolCall } from './types'; +import type { ToolCall } from './types'; export interface CachedAction { key: string; @@ -66,19 +66,3 @@ export async function clearCache(): Promise { export async function invalidate(key: string): Promise { await db.actionCache.delete(key); } - -export function summarizeCall(call: ToolCall): string { - const parts: string[] = [call.name]; - const a = call.arguments; - if (a.ref) parts.push(`ref=${a.ref}`); - if (a.text) parts.push(`text="${String(a.text).slice(0, 24)}"`); - if (a.url) parts.push(`url=${a.url}`); - if (a.value) parts.push(`value=${a.value}`); - if (a.key) parts.push(`key=${a.key}`); - if (a.modifiers) parts.push(`modifiers=${a.modifiers}`); - return parts.join(' '); -} - -export function snapshotSignature(s: A11ySnapshot): string { - return s.domHash; -} diff --git a/core/src/lib/export.ts b/core/src/lib/export.ts index c33f38d..122dd73 100644 --- a/core/src/lib/export.ts +++ b/core/src/lib/export.ts @@ -12,18 +12,6 @@ export function buildTrace(task: AgentTask): TraceFile { return { version: 1, exportedAt: Date.now(), task: maskTaskForLog(task) }; } -export function downloadJson(name: string, data: unknown): void { - const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = name; - document.body.appendChild(a); - a.click(); - a.remove(); - setTimeout(() => URL.revokeObjectURL(url), 1000); -} - // ── PDF Export ── function escapeHtml(text: string): string { @@ -275,62 +263,6 @@ export function buildPdfHtml(task: AgentTask): string { `; } -export function downloadPdfViaPrint(task: AgentTask): void { - const html = buildPdfHtml(task); - - const iframe = document.createElement('iframe'); - iframe.style.cssText = 'position:fixed;top:-9999px;left:-9999px;width:794px;height:1123px;border:none;'; - document.body.appendChild(iframe); - - const doc = iframe.contentDocument ?? iframe.contentWindow?.document; - if (!doc) { - iframe.remove(); - // Fallback: download as HTML - const blob = new Blob([html], { type: 'text/html' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `report-${task.id.slice(0, 8)}.html`; - document.body.appendChild(a); - a.click(); - a.remove(); - setTimeout(() => URL.revokeObjectURL(url), 1000); - return; - } - - doc.open(); - doc.write(html); - doc.close(); - - // Keep print synchronous with the button click. Chrome only permits print dialogs - // initiated during a user gesture; scheduling this even one tick later causes the - // dialog to be silently blocked from the extension side panel. - const cleanup = () => iframe.remove(); - iframe.contentWindow?.addEventListener('afterprint', cleanup, { once: true }); - - try { - iframe.contentWindow?.focus(); - iframe.contentWindow?.print(); - } catch { - // If printing is unavailable, provide the rendered report as a usable fallback. - cleanup(); - const blob = new Blob([html], { type: 'text/html' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `report-${task.id.slice(0, 8)}.html`; - document.body.appendChild(a); - a.click(); - a.remove(); - setTimeout(() => URL.revokeObjectURL(url), 1000); - return; - } - - // Some browsers do not dispatch afterprint for an iframe. Keep it alive long - // enough for the print preview, then remove it without leaving hidden frames. - setTimeout(cleanup, 30_000); -} - function printableValue(value: unknown): string { if (typeof value === 'string') return value; try { diff --git a/core/src/lib/hash.ts b/core/src/lib/hash.ts index 616fe26..df8b423 100644 --- a/core/src/lib/hash.ts +++ b/core/src/lib/hash.ts @@ -1,12 +1,3 @@ -export async function sha256Hex(input: string): Promise { - const buf = new TextEncoder().encode(input); - const digest = await crypto.subtle.digest('SHA-256', buf); - const bytes = new Uint8Array(digest); - let out = ''; - for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, '0'); - return out; -} - export function fastHash(input: string): string { let h1 = 0xdeadbeef ^ 0; let h2 = 0x41c6ce57 ^ 0; diff --git a/core/src/lib/messaging.ts b/core/src/lib/messaging.ts index 85ef68f..90a4e4a 100644 --- a/core/src/lib/messaging.ts +++ b/core/src/lib/messaging.ts @@ -60,16 +60,6 @@ function withReplyTimeout(pending: Promise, msg: CSMessage): Promise }); } -export function onSWEvent(cb: (evt: SWEvent) => void): () => void { - const handler = (msg: unknown) => { - if (msg && typeof msg === 'object' && 'kind' in (msg as Record)) { - cb(msg as SWEvent); - } - }; - chrome.runtime.onMessage.addListener(handler); - return () => chrome.runtime.onMessage.removeListener(handler); -} - export function broadcastEvent(evt: SWEvent): void { for (const listener of localEventListeners) { try { listener(evt); } catch {} diff --git a/core/src/lib/orchestrator.ts b/core/src/lib/orchestrator.ts index 07c960a..d507555 100644 --- a/core/src/lib/orchestrator.ts +++ b/core/src/lib/orchestrator.ts @@ -7,7 +7,7 @@ import type { TabContext, } from './orchestrator-types'; import type { AgentPlan, SkillId } from './types'; -import { classifyTask, getSkill } from './skills'; +import { classifyTask } from './skills'; // ── Tab Manager ─────────────────────────────────────────────────────── @@ -303,10 +303,6 @@ export function allSubtasksComplete(plan: OrchestrationPlan): boolean { ); } -export function anySubtasksPending(plan: OrchestrationPlan): boolean { - return plan.subtasks.some((s) => s.status === 'pending'); -} - export function nextPendingSubtask(plan: OrchestrationPlan): Subtask | undefined { return plan.subtasks.find((s) => s.status === 'pending'); } @@ -365,10 +361,6 @@ export function advanceOrchPlan(plan: OrchestrationPlan, toolName: string): void plan.updatedAt = Date.now(); } -export function getCurrentSubtask(plan: OrchestrationPlan): Subtask | undefined { - return plan.subtasks.find((s) => s.status === 'running'); -} - export function markSubtaskDone(plan: OrchestrationPlan, subtaskId: string): void { const st = findSubtask(plan, subtaskId); if (st) { @@ -388,30 +380,8 @@ export function markSubtaskFailed(plan: OrchestrationPlan, subtaskId: string, er } } -export function getSubtaskResult(plan: OrchestrationPlan, index: number): string | undefined { - const st = plan.subtasks.find((s) => s.index === index); - return st?.result; -} - // ── Sub-task skill injection ────────────────────────────────────────── -export function skillPromptForSubtask(subtask: Subtask): string { - const prompts: string[] = []; - - // Get the skill's own prompt - if (subtask.skillId) { - const skill = getSkill(subtask.skillId); - if (skill) { - prompts.push(skill.prompt); - } - } - - // Inject context from completed dependent subtasks - prompts.push(`SUBTASK: ${subtask.description}`); - - return prompts.join('\n\n'); -} - // ── Utils ───────────────────────────────────────────────────────────── function sleep(ms: number): Promise { diff --git a/core/src/lib/partial-work.ts b/core/src/lib/partial-work.ts index 626fbf3..32d5724 100644 --- a/core/src/lib/partial-work.ts +++ b/core/src/lib/partial-work.ts @@ -183,11 +183,6 @@ export function buildTraceQuestionPrompt(goal: string, work: CollectedWork, ques ].join('\n'); } -/** Steps whose results were summarized, for marking the synthetic step. */ -export function isInterrupted(status: AgentTask['status']): boolean { - return status === 'stopped'; -} - export type { AgentStep }; /** Evidence below this is too thin for the question to be worth asking. */ diff --git a/core/src/lib/retry.ts b/core/src/lib/retry.ts index fc0514e..25b4593 100644 --- a/core/src/lib/retry.ts +++ b/core/src/lib/retry.ts @@ -93,31 +93,3 @@ export function decideRetry( }; } } - -export function retryPromptForStep( - retryCount: number, - maxRetries: number, - strategy: RetryStrategy, - originalError: string, -): string { - const header = `[RETRY ${retryCount}/${maxRetries}] Previous action failed: ${originalError}`; - - switch (strategy) { - case 'close_popup': - return `${header}\nA popup/dialog was detected on the page. Find the close button and click it.`; - case 'different_selector': - return `${header}\nElement changed or not found. Find a similar element by name/text.`; - case 'wait_and_retry': - return `${header}\nPage is loading. Wait longer and take a new snapshot.`; - case 'scroll_to_element': - return `${header}\nScroll the page — the element may be outside the visible area.`; - case 'coordinates_click': - return `${header}\nSystem will perform a coordinate click via CDP.`; - case 'refresh_page': - return `${header}\nRefresh the page and retry the step.`; - case 'try_alternative': - return `${header}\nFind an alternative way to complete the task.`; - default: - return `${header}\nWait for the page to settle, then retry. If it fails again, try a different element.`; - } -} diff --git a/core/src/lib/semantic-memory.ts b/core/src/lib/semantic-memory.ts index adc3585..06eaae0 100644 --- a/core/src/lib/semantic-memory.ts +++ b/core/src/lib/semantic-memory.ts @@ -1,6 +1,6 @@ import { db } from './storage'; import { urlPattern } from './action-cache'; -import type { A11ySnapshot, RecoveryMemory, SitePattern, ToolCall } from './types'; +import type { A11ySnapshot, SitePattern, ToolCall } from './types'; import { parseBatchActions } from './batch-actions'; export async function getSitePattern(snapshot: A11ySnapshot): Promise { @@ -58,39 +58,6 @@ export async function learnFromSuccess( await db.sitePatterns.put(sitePattern); } -export async function learnRecovery( - snapshot: A11ySnapshot, - failedAction: string, - successAction: string, - recoveryHint: string, -): Promise { - const pat = urlPattern(snapshot.url); - const existing = await db.recoveryMemory.where({ urlPattern: pat, failedAction }).first(); - - const record: RecoveryMemory = { - urlPattern: pat, - failedAction, - successAction, - recoveryHint, - hitCount: (existing?.hitCount ?? 0) + 1, - }; - - await db.recoveryMemory.put(record); -} - -export async function getRecoveryHint( - snapshot: A11ySnapshot, - failedAction: string, -): Promise { - const pat = urlPattern(snapshot.url); - const record = await db.recoveryMemory.where({ urlPattern: pat, failedAction }).first(); - if (!record) return undefined; - - record.hitCount += 1; - await db.recoveryMemory.put(record); - return record.recoveryHint; -} - export async function getCookieHint(snapshot: A11ySnapshot): Promise { const pattern = await getSitePattern(snapshot); if (pattern?.cookieAcceptSelector) { @@ -107,14 +74,6 @@ export async function getSearchHint(snapshot: A11ySnapshot): Promise { - const s = await db.sitePatterns.count(); - const r = await db.recoveryMemory.count(); - await db.sitePatterns.clear(); - await db.recoveryMemory.clear(); - return s + r; -} - function isSearchInput(name: string, role: string): boolean { const s = name; return (role === 'textbox' || role === 'searchbox' || role === 'combobox') && ( diff --git a/core/src/lib/storage.ts b/core/src/lib/storage.ts index 9fbe369..b585208 100644 --- a/core/src/lib/storage.ts +++ b/core/src/lib/storage.ts @@ -9,6 +9,7 @@ export class AgentDB extends Dexie { steps!: Table; actionCache!: Table; sitePatterns!: Table; + /** Never written; kept so existing databases keep a valid schema without a migration. */ recoveryMemory!: Table; constructor() {