chore(cleanup): remove browser control skills and direct OpenRouter translate call
Remove navigate_browser, read_browser_page, click_browser_element, go_back_browser, translate_browser_page and highlight_browser_text, plus the Electron BrowserWindow infrastructure (src/main/browser/browserWindow.ts) that only backed them, and src/main/ai/translate.ts, which called OpenRouter directly from the main process (bypassing Max API and requireLoggedIn, a CLAUDE.md violation) solely to back translate_browser_page. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
a55323a3fa
commit
c99b01a902
@@ -1,38 +0,0 @@
|
|||||||
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'
|
|
||||||
|
|
||||||
/** Traduit une liste de textes courts, en conservant l'ordre. Appel independant de la conversation. */
|
|
||||||
export async function translateTexts(texts: string[], targetLanguage: string): Promise<string[]> {
|
|
||||||
const apiKey = process.env.OPENROUTER_API_KEY
|
|
||||||
if (!apiKey) throw new Error('OPENROUTER_API_KEY manquante dans .env')
|
|
||||||
const model = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-chat'
|
|
||||||
|
|
||||||
const prompt = `Traduis chaque element de ce tableau JSON en ${targetLanguage}. Renvoie
|
|
||||||
UNIQUEMENT un tableau JSON de la meme longueur et dans le meme ordre, sans aucun texte autour, sans
|
|
||||||
markdown. Tableau source :\n${JSON.stringify(texts)}`
|
|
||||||
|
|
||||||
const response = await fetch(OPENROUTER_URL, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${apiKey}`,
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ model, messages: [{ role: 'user', content: prompt }] })
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Traduction echouee (${response.status}): ${await response.text()}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = (await response.json()) as {
|
|
||||||
choices?: { message: { content?: string } }[]
|
|
||||||
}
|
|
||||||
const content: string = data.choices?.[0]?.message.content ?? '[]'
|
|
||||||
// Extrait le tableau JSON borne par le premier "[" et le dernier "]" sans regex gourmande
|
|
||||||
// (evite tout risque de backtracking superlineaire sur une reponse LLM de taille arbitraire).
|
|
||||||
const start = content.indexOf('[')
|
|
||||||
const end = content.lastIndexOf(']')
|
|
||||||
const jsonSlice = start !== -1 && end > start ? content.slice(start, end + 1) : content
|
|
||||||
const parsed: unknown = JSON.parse(jsonSlice)
|
|
||||||
if (!Array.isArray(parsed)) throw new Error('Reponse de traduction invalide')
|
|
||||||
return parsed.map((item) => String(item))
|
|
||||||
}
|
|
||||||
@@ -1,263 +0,0 @@
|
|||||||
import { BrowserWindow } from 'electron'
|
|
||||||
import { SECURE_WEB_PREFERENCES } from '../utils/windowSecurity'
|
|
||||||
|
|
||||||
const MAX_PAGE_TEXT = 12000
|
|
||||||
const MAX_TRANSLATABLE_ELEMENTS = 150
|
|
||||||
|
|
||||||
let win: BrowserWindow | null = null
|
|
||||||
|
|
||||||
function ensureWindow(): BrowserWindow {
|
|
||||||
if (win && !win.isDestroyed()) return win
|
|
||||||
|
|
||||||
win = new BrowserWindow({
|
|
||||||
width: 1200,
|
|
||||||
height: 800,
|
|
||||||
title: 'Max — navigateur',
|
|
||||||
// Pas de preload ici (fenetre de navigation generale, destination choisie par l'utilisateur) :
|
|
||||||
// aucune API privilegiee exposee a la page, contrairement aux autres fenetres de l'app. Sans
|
|
||||||
// preload, le souci sandbox/contextBridge des autres fenetres ne s'applique pas : sandbox peut
|
|
||||||
// rester actif ici pour une isolation maximale (defense en profondeur sur du contenu externe).
|
|
||||||
webPreferences: { ...SECURE_WEB_PREFERENCES, sandbox: true }
|
|
||||||
})
|
|
||||||
win.maximize()
|
|
||||||
win.on('closed', () => {
|
|
||||||
win = null
|
|
||||||
})
|
|
||||||
return win
|
|
||||||
}
|
|
||||||
|
|
||||||
function waitForLoad(window: BrowserWindow): Promise<void> {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const onFinish = (): void => {
|
|
||||||
cleanup()
|
|
||||||
resolve()
|
|
||||||
}
|
|
||||||
const onFail = (_event: unknown, errorCode: number, errorDescription: string): void => {
|
|
||||||
cleanup()
|
|
||||||
reject(new Error(`Echec de chargement (${errorCode}): ${errorDescription}`))
|
|
||||||
}
|
|
||||||
const cleanup = (): void => {
|
|
||||||
window.webContents.removeListener('did-finish-load', onFinish)
|
|
||||||
window.webContents.removeListener('did-fail-load', onFail)
|
|
||||||
}
|
|
||||||
window.webContents.once('did-finish-load', onFinish)
|
|
||||||
window.webContents.once('did-fail-load', onFail)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Phrases courantes des bandeaux de consentement cookies (FR/EN) : sans ca, document.body.innerText
|
|
||||||
// peut renvoyer le texte du bandeau plutot que le contenu reel de la page.
|
|
||||||
const COOKIE_ACCEPT_PHRASES = [
|
|
||||||
'tout accepter',
|
|
||||||
'accepter tout',
|
|
||||||
"j'accepte",
|
|
||||||
'accepter et fermer',
|
|
||||||
'accepter',
|
|
||||||
"d'accord",
|
|
||||||
'accept all',
|
|
||||||
'i accept',
|
|
||||||
'accept'
|
|
||||||
]
|
|
||||||
|
|
||||||
export function dismissCookieBannerInPage(phrases: string[]): string | null {
|
|
||||||
const candidates = Array.from(
|
|
||||||
document.querySelectorAll<HTMLElement>('button, [role="button"], a')
|
|
||||||
)
|
|
||||||
for (const phrase of phrases) {
|
|
||||||
const match = candidates.find((el) => (el.innerText || '').trim().toLowerCase() === phrase)
|
|
||||||
if (match) {
|
|
||||||
match.click()
|
|
||||||
return phrase
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
async function dismissCookieBanner(window: BrowserWindow): Promise<void> {
|
|
||||||
try {
|
|
||||||
await window.webContents.executeJavaScript(
|
|
||||||
`(${dismissCookieBannerInPage.toString()})(${JSON.stringify(COOKIE_ACCEPT_PHRASES)})`
|
|
||||||
)
|
|
||||||
} catch {
|
|
||||||
// best-effort : une page qui bloque l'injection ne doit pas faire echouer la navigation
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function navigateTo(url: string): Promise<string> {
|
|
||||||
const window = ensureWindow()
|
|
||||||
window.show()
|
|
||||||
const loadPromise = waitForLoad(window)
|
|
||||||
await window.loadURL(url)
|
|
||||||
await loadPromise
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 600))
|
|
||||||
await dismissCookieBanner(window)
|
|
||||||
return window.webContents.getTitle()
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function goBack(): Promise<boolean> {
|
|
||||||
if (!win || win.isDestroyed()) throw new Error('Aucun navigateur ouvert')
|
|
||||||
if (!win.webContents.navigationHistory.canGoBack()) return false
|
|
||||||
const loadPromise = waitForLoad(win)
|
|
||||||
win.webContents.navigationHistory.goBack()
|
|
||||||
await loadPromise
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 600))
|
|
||||||
await dismissCookieBanner(win)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
function requireWindow(): BrowserWindow {
|
|
||||||
if (!win || win.isDestroyed())
|
|
||||||
throw new Error("Aucun navigateur ouvert : appelle navigate_browser d'abord")
|
|
||||||
return win
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function readPageText(): Promise<string> {
|
|
||||||
const window = requireWindow()
|
|
||||||
const text = (await window.webContents.executeJavaScript(
|
|
||||||
'(() => document.body ? document.body.innerText : "")()'
|
|
||||||
)) as string
|
|
||||||
const trimmed = text.trim().replace(/\n{3,}/g, '\n\n')
|
|
||||||
return trimmed.length > MAX_PAGE_TEXT ? trimmed.slice(0, MAX_PAGE_TEXT) : trimmed
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function clickElementByText(text: string): Promise<boolean> {
|
|
||||||
const window = requireWindow()
|
|
||||||
return (await window.webContents.executeJavaScript(
|
|
||||||
`(${clickByTextInPage.toString()})(${JSON.stringify(text)})`
|
|
||||||
)) as boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export function clickByTextInPage(target: string): boolean {
|
|
||||||
const needle = target.trim().toLowerCase()
|
|
||||||
const candidates = Array.from(
|
|
||||||
document.querySelectorAll<HTMLElement>(
|
|
||||||
'a, button, [role="button"], input[type="submit"], input[type="button"]'
|
|
||||||
)
|
|
||||||
)
|
|
||||||
const match =
|
|
||||||
candidates.find(
|
|
||||||
(el) => (el.innerText || el.getAttribute('value') || '').trim().toLowerCase() === needle
|
|
||||||
) ??
|
|
||||||
candidates.find((el) =>
|
|
||||||
(el.innerText || el.getAttribute('value') || '').trim().toLowerCase().includes(needle)
|
|
||||||
)
|
|
||||||
if (!match) return false
|
|
||||||
match.scrollIntoView({ block: 'center' })
|
|
||||||
match.click()
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TaggedElement {
|
|
||||||
id: string
|
|
||||||
text: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function collectTranslatableElements(): Promise<TaggedElement[]> {
|
|
||||||
const window = requireWindow()
|
|
||||||
return (await window.webContents.executeJavaScript(
|
|
||||||
`(${collectInPage.toString()})(${MAX_TRANSLATABLE_ELEMENTS})`
|
|
||||||
)) as TaggedElement[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function collectInPage(limit: number): TaggedElement[] {
|
|
||||||
const ATTR = 'data-forge-tid'
|
|
||||||
const isLeaf = (el: Element): boolean =>
|
|
||||||
Array.from(el.children).every((child) =>
|
|
||||||
['BR', 'B', 'I', 'EM', 'STRONG', 'SPAN', 'A'].includes(child.tagName)
|
|
||||||
)
|
|
||||||
const nodes = Array.from(
|
|
||||||
document.querySelectorAll(
|
|
||||||
'p, h1, h2, h3, h4, h5, h6, li, span, a, button, td, th, label, figcaption'
|
|
||||||
)
|
|
||||||
).filter((el) => isLeaf(el) && (el.textContent ?? '').trim().length > 1)
|
|
||||||
|
|
||||||
const results: TaggedElement[] = []
|
|
||||||
for (const el of nodes) {
|
|
||||||
if (results.length >= limit) break
|
|
||||||
const text = (el.textContent ?? '').trim()
|
|
||||||
if (!text) continue
|
|
||||||
const id = `t${results.length}`
|
|
||||||
el.setAttribute(ATTR, id)
|
|
||||||
results.push({ id, text })
|
|
||||||
}
|
|
||||||
return results
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function applyTranslations(translations: TaggedElement[]): Promise<void> {
|
|
||||||
const window = requireWindow()
|
|
||||||
await window.webContents.executeJavaScript(
|
|
||||||
`(${applyInPage.toString()})(${JSON.stringify(translations)})`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function applyInPage(translations: TaggedElement[]): void {
|
|
||||||
for (const { id, text } of translations) {
|
|
||||||
const el = document.querySelector(`[data-forge-tid="${id}"]`)
|
|
||||||
if (el) el.textContent = text
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function highlightText(text: string): Promise<boolean> {
|
|
||||||
const window = requireWindow()
|
|
||||||
return (await window.webContents.executeJavaScript(
|
|
||||||
`(${highlightInPage.toString()})(${JSON.stringify(text)})`
|
|
||||||
)) as boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export function highlightInPage(target: string): boolean {
|
|
||||||
const needle = target.trim()
|
|
||||||
if (!needle) return false
|
|
||||||
// window.find() recherche dans le texte rendu (gere nativement un passage coupe sur plusieurs
|
|
||||||
// balises, ex: un prix en plusieurs <span>), contrairement a une recherche manuelle noeud par
|
|
||||||
// noeud. caseSensitive=false, backwards=false, wrapAround=true, wholeWord=false.
|
|
||||||
type LegacyWindow = Window & {
|
|
||||||
find?: (
|
|
||||||
text: string,
|
|
||||||
caseSensitive?: boolean,
|
|
||||||
backwards?: boolean,
|
|
||||||
wrapAround?: boolean,
|
|
||||||
wholeWord?: boolean,
|
|
||||||
searchInFrames?: boolean,
|
|
||||||
showDialog?: boolean
|
|
||||||
) => boolean
|
|
||||||
}
|
|
||||||
const legacyWindow = window as LegacyWindow
|
|
||||||
const found = legacyWindow.find?.(needle, false, false, true, false, true, false) ?? false
|
|
||||||
if (!found) return false
|
|
||||||
|
|
||||||
const selection = window.getSelection()
|
|
||||||
if (!selection || selection.rangeCount === 0) return false
|
|
||||||
const range = selection.getRangeAt(0)
|
|
||||||
|
|
||||||
// document.execCommand('hiliteColor', ...) ne produit aucun effet visible dans ce contexte
|
|
||||||
// (verifie par capture d'ecran) : on surligne donc manuellement en entourant chaque noeud
|
|
||||||
// texte touche par la selection d'un <mark>, ce qui gere aussi un passage coupe sur
|
|
||||||
// plusieurs balises.
|
|
||||||
const rootNode = range.commonAncestorContainer
|
|
||||||
const root = rootNode.nodeType === Node.TEXT_NODE ? rootNode.parentNode : rootNode
|
|
||||||
if (!root) return false
|
|
||||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
|
||||||
acceptNode: (node) =>
|
|
||||||
range.intersectsNode(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
|
|
||||||
})
|
|
||||||
const textNodes: Text[] = []
|
|
||||||
let node: Node | null
|
|
||||||
while ((node = walker.nextNode())) textNodes.push(node as Text)
|
|
||||||
|
|
||||||
for (const textNode of textNodes) {
|
|
||||||
const start = textNode === range.startContainer ? range.startOffset : 0
|
|
||||||
const end = textNode === range.endContainer ? range.endOffset : textNode.length
|
|
||||||
if (start >= end) continue
|
|
||||||
const nodeRange = document.createRange()
|
|
||||||
nodeRange.setStart(textNode, start)
|
|
||||||
nodeRange.setEnd(textNode, end)
|
|
||||||
const mark = document.createElement('mark')
|
|
||||||
mark.style.backgroundColor = '#ffe066'
|
|
||||||
mark.style.color = 'inherit'
|
|
||||||
nodeRange.surroundContents(mark)
|
|
||||||
}
|
|
||||||
|
|
||||||
textNodes[0]?.parentElement?.scrollIntoView({ block: 'center' })
|
|
||||||
selection.removeAllRanges()
|
|
||||||
return textNodes.length > 0
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { clickElementByText } from '../../browser/browserWindow'
|
|
||||||
import type { SkillDefinition } from '../types'
|
|
||||||
import { asString } from '../argUtils'
|
|
||||||
|
|
||||||
export const clickBrowserElement: SkillDefinition = {
|
|
||||||
name: 'click_browser_element',
|
|
||||||
description:
|
|
||||||
'Clique sur un lien ou un bouton du navigateur integre dont le texte visible correspond (ou contient) le texte donne. Ne fonctionne que sur des elements avec du texte visible.',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
text: {
|
|
||||||
type: 'string',
|
|
||||||
description: 'Texte visible du lien/bouton a cliquer, le plus exact possible'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
required: ['text']
|
|
||||||
},
|
|
||||||
execute: async (args) => {
|
|
||||||
const text = asString(args.text).trim()
|
|
||||||
if (!text) throw new Error('text manquant')
|
|
||||||
const clicked = await clickElementByText(text)
|
|
||||||
return clicked
|
|
||||||
? `Clic effectue sur l'element correspondant a "${text}".`
|
|
||||||
: `Echec : aucun lien ou bouton visible ne correspond a "${text}".`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { goBack } from '../../browser/browserWindow'
|
|
||||||
import type { SkillDefinition } from '../types'
|
|
||||||
|
|
||||||
export const goBackBrowser: SkillDefinition = {
|
|
||||||
name: 'go_back_browser',
|
|
||||||
description: 'Revient a la page precedente dans le navigateur integre.',
|
|
||||||
parameters: { type: 'object', properties: {} },
|
|
||||||
execute: async () => {
|
|
||||||
const didGoBack = await goBack()
|
|
||||||
return didGoBack ? 'Retour a la page precedente effectue.' : 'Echec : pas de page precedente.'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { highlightText } from '../../browser/browserWindow'
|
|
||||||
import type { SkillDefinition } from '../types'
|
|
||||||
import { asString } from '../argUtils'
|
|
||||||
|
|
||||||
export const highlightBrowserText: SkillDefinition = {
|
|
||||||
name: 'highlight_browser_text',
|
|
||||||
description:
|
|
||||||
'Surligne en jaune (et fait defiler jusqu a) un passage de texte exact dans la page actuellement affichee dans le navigateur integre.',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
text: {
|
|
||||||
type: 'string',
|
|
||||||
description: 'Texte exact a surligner (doit correspondre mot pour mot au texte de la page)'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
required: ['text']
|
|
||||||
},
|
|
||||||
execute: async (args) => {
|
|
||||||
const text = asString(args.text).trim()
|
|
||||||
if (!text) throw new Error('text manquant')
|
|
||||||
const found = await highlightText(text)
|
|
||||||
return found
|
|
||||||
? `Passage surligne : "${text}".`
|
|
||||||
: `Echec : le texte "${text}" n'a pas ete trouve exactement sur la page.`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import type { SkillDefinition } from '../types'
|
|
||||||
import { navigateBrowser } from './navigateBrowser'
|
|
||||||
import { readBrowserPage } from './readBrowserPage'
|
|
||||||
import { clickBrowserElement } from './clickBrowserElement'
|
|
||||||
import { goBackBrowser } from './goBackBrowser'
|
|
||||||
import { translateBrowserPage } from './translateBrowserPage'
|
|
||||||
import { highlightBrowserText } from './highlightBrowserText'
|
|
||||||
|
|
||||||
// Navigateur integre, independant de l'OS, commun a toutes les plateformes.
|
|
||||||
export const browserSkills: SkillDefinition[] = [
|
|
||||||
navigateBrowser,
|
|
||||||
readBrowserPage,
|
|
||||||
clickBrowserElement,
|
|
||||||
goBackBrowser,
|
|
||||||
translateBrowserPage,
|
|
||||||
highlightBrowserText
|
|
||||||
]
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { navigateTo } from '../../browser/browserWindow'
|
|
||||||
import type { SkillDefinition } from '../types'
|
|
||||||
import { asString } from '../argUtils'
|
|
||||||
|
|
||||||
export const navigateBrowser: SkillDefinition = {
|
|
||||||
name: 'navigate_browser',
|
|
||||||
description:
|
|
||||||
"Ouvre une URL dans le navigateur integre que tu controles toi-meme (fenetre separee, visible par l'utilisateur). C'est le seul moyen d'ouvrir un site : utilise systematiquement cette fonction pour toute demande de consultation d'un site, que tu doives ensuite lire la page, cliquer, remplir un formulaire, traduire ou surligner du texte, ou simplement montrer le site a l'utilisateur. Ne jamais deviner l'URL d'un site inconnu : utiliser search_web d'abord.",
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
url: { type: 'string', description: 'URL exacte a ouvrir' }
|
|
||||||
},
|
|
||||||
required: ['url']
|
|
||||||
},
|
|
||||||
execute: async (args) => {
|
|
||||||
const url = asString(args.url).trim()
|
|
||||||
if (!url) throw new Error('url manquante')
|
|
||||||
const title = await navigateTo(url)
|
|
||||||
return `Page ouverte : "${title}" (${url}).`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { readPageText } from '../../browser/browserWindow'
|
|
||||||
import type { SkillDefinition } from '../types'
|
|
||||||
|
|
||||||
export const readBrowserPage: SkillDefinition = {
|
|
||||||
name: 'read_browser_page',
|
|
||||||
description:
|
|
||||||
"Lit le texte reel actuellement affiche dans le navigateur integre (apres navigate_browser). Utilise ceci pour repondre a une question sur le contenu de la page, plutot que d'inventer.",
|
|
||||||
parameters: { type: 'object', properties: {} },
|
|
||||||
execute: async () => {
|
|
||||||
const text = await readPageText()
|
|
||||||
return text || "La page est vide ou n'a pas pu etre lue."
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import { applyTranslations, collectTranslatableElements } from '../../browser/browserWindow'
|
|
||||||
import { translateTexts } from '../../ai/translate'
|
|
||||||
import type { SkillDefinition } from '../types'
|
|
||||||
import { asString } from '../argUtils'
|
|
||||||
|
|
||||||
export const translateBrowserPage: SkillDefinition = {
|
|
||||||
name: 'translate_browser_page',
|
|
||||||
description:
|
|
||||||
'Traduit et remplace le texte visible de la page actuellement affichee dans le navigateur integre, dans la langue demandee (comme la traduction automatique dun navigateur).',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
language: { type: 'string', description: 'Langue cible (ex: "anglais", "espagnol")' }
|
|
||||||
},
|
|
||||||
required: ['language']
|
|
||||||
},
|
|
||||||
execute: async (args) => {
|
|
||||||
const language = asString(args.language).trim()
|
|
||||||
if (!language) throw new Error('language manquante')
|
|
||||||
|
|
||||||
const elements = await collectTranslatableElements()
|
|
||||||
if (elements.length === 0) return 'Aucun texte traduisible trouve sur cette page.'
|
|
||||||
|
|
||||||
const translated = await translateTexts(
|
|
||||||
elements.map((el) => el.text),
|
|
||||||
language
|
|
||||||
)
|
|
||||||
await applyTranslations(
|
|
||||||
elements.map((el, i) => ({ id: el.id, text: translated.at(i) ?? el.text }))
|
|
||||||
)
|
|
||||||
|
|
||||||
return `Page traduite en ${language} (${elements.length} elements remplaces).`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
import type { SkillDefinition } from './types'
|
import type { SkillDefinition } from './types'
|
||||||
import { memorySkills } from './memory'
|
import { memorySkills } from './memory'
|
||||||
import { webSkills } from './web'
|
import { webSkills } from './web'
|
||||||
import { browserSkills } from './browser'
|
|
||||||
|
|
||||||
export type { SkillDefinition } from './types'
|
export type { SkillDefinition } from './types'
|
||||||
|
|
||||||
export function loadSkills(): SkillDefinition[] {
|
export function loadSkills(): SkillDefinition[] {
|
||||||
return [...memorySkills, ...webSkills, ...browserSkills]
|
return [...memorySkills, ...webSkills]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function findSkill(name: string): SkillDefinition | undefined {
|
export function findSkill(name: string): SkillDefinition | undefined {
|
||||||
|
|||||||
@@ -1,360 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
||||||
import { EventEmitter } from 'node:events'
|
|
||||||
|
|
||||||
// jsdom n'implemente pas innerText (pas de mise en page reelle) : le code de production (destine a
|
|
||||||
// un vrai Chromium via executeJavaScript) s'appuie dessus. On le fait correspondre a textContent
|
|
||||||
// pour ce test, suffisant pour du texte simple sans mise en forme complexe.
|
|
||||||
Object.defineProperty(HTMLElement.prototype, 'innerText', {
|
|
||||||
get(): string {
|
|
||||||
return (this as HTMLElement).textContent ?? ''
|
|
||||||
},
|
|
||||||
set(value: string) {
|
|
||||||
;(this as HTMLElement).textContent = value
|
|
||||||
},
|
|
||||||
configurable: true
|
|
||||||
})
|
|
||||||
|
|
||||||
// jsdom n'implemente pas scrollIntoView (pas de mise en page reelle) non plus.
|
|
||||||
Element.prototype.scrollIntoView = vi.fn()
|
|
||||||
|
|
||||||
// jsdom n'implemente pas non plus l'API legacy window.find() (recherche de texte dans la page) :
|
|
||||||
// implementation minimaliste suffisante pour le test (recherche globale, premiere occurrence,
|
|
||||||
// selectionne le noeud texte correspondant).
|
|
||||||
;(window as unknown as { find: (text: string) => boolean }).find = (text: string): boolean => {
|
|
||||||
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT)
|
|
||||||
let node: Node | null
|
|
||||||
while ((node = walker.nextNode())) {
|
|
||||||
const index = (node.textContent ?? '').indexOf(text)
|
|
||||||
if (index >= 0) {
|
|
||||||
const range = document.createRange()
|
|
||||||
range.setStart(node, index)
|
|
||||||
range.setEnd(node, index + text.length)
|
|
||||||
const selection = window.getSelection()
|
|
||||||
selection?.removeAllRanges()
|
|
||||||
selection?.addRange(range)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// executeJavaScript recoit le code sous forme de chaine ( `(${fn.toString()})(args)` ) : l'evaluer
|
|
||||||
// reellement ici (environnement jsdom) execute le vrai code de manipulation DOM contre le vrai
|
|
||||||
// `document` de jsdom, ce qui donne a la fois une vraie couverture ET un vrai test de comportement,
|
|
||||||
// plutot que de mocker la valeur de retour a la main pour chaque fonction.
|
|
||||||
class FakeWebContents extends EventEmitter {
|
|
||||||
executeJavaScript = vi.fn(async (code: string): Promise<unknown> => eval(code) as unknown)
|
|
||||||
getTitle = vi.fn(() => 'Titre de la page')
|
|
||||||
navigationHistory = { canGoBack: vi.fn(() => true), goBack: vi.fn() }
|
|
||||||
}
|
|
||||||
|
|
||||||
class FakeBrowserWindow extends EventEmitter {
|
|
||||||
webContents = new FakeWebContents()
|
|
||||||
show = vi.fn()
|
|
||||||
maximize = vi.fn()
|
|
||||||
loadURL = vi.fn()
|
|
||||||
destroyed = false
|
|
||||||
isDestroyed(): boolean {
|
|
||||||
return this.destroyed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let lastWindow: FakeBrowserWindow | null = null
|
|
||||||
function createBrowserWindow(): FakeBrowserWindow {
|
|
||||||
const window = new FakeBrowserWindow()
|
|
||||||
lastWindow = window
|
|
||||||
return window
|
|
||||||
}
|
|
||||||
|
|
||||||
vi.mock('electron', () => ({ BrowserWindow: vi.fn(createBrowserWindow) }))
|
|
||||||
|
|
||||||
const {
|
|
||||||
navigateTo,
|
|
||||||
goBack,
|
|
||||||
readPageText,
|
|
||||||
clickElementByText,
|
|
||||||
collectTranslatableElements,
|
|
||||||
applyTranslations,
|
|
||||||
highlightText,
|
|
||||||
dismissCookieBannerInPage,
|
|
||||||
clickByTextInPage,
|
|
||||||
collectInPage,
|
|
||||||
applyInPage,
|
|
||||||
highlightInPage
|
|
||||||
} = await import('../../src/main/browser/browserWindow')
|
|
||||||
|
|
||||||
function finishLoad(): void {
|
|
||||||
lastWindow?.webContents.emit('did-finish-load')
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('navigateTo()', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
lastWindow?.emit('closed')
|
|
||||||
vi.clearAllMocks()
|
|
||||||
lastWindow = null
|
|
||||||
document.body.innerHTML = ''
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should create the window, load the URL and return the page title', async () => {
|
|
||||||
const promise = navigateTo('https://example.com')
|
|
||||||
finishLoad()
|
|
||||||
const title = await promise
|
|
||||||
expect(title).toBe('Titre de la page')
|
|
||||||
expect(lastWindow?.show).toHaveBeenCalled()
|
|
||||||
expect(lastWindow?.loadURL).toHaveBeenCalledWith('https://example.com')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should reject when the page fails to load', async () => {
|
|
||||||
const promise = navigateTo('https://example.com')
|
|
||||||
lastWindow?.webContents.emit('did-fail-load', {}, 404, 'Not Found')
|
|
||||||
await expect(promise).rejects.toThrow(/Echec de chargement/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should dismiss a cookie banner by clicking the matching button', async () => {
|
|
||||||
document.body.innerHTML = '<button>Tout accepter</button><p>Contenu reel</p>'
|
|
||||||
const promise = navigateTo('https://example.com')
|
|
||||||
finishLoad()
|
|
||||||
await promise
|
|
||||||
expect(document.querySelector('button')?.textContent).toBe('Tout accepter')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not click anything when no cookie banner phrase matches', async () => {
|
|
||||||
document.body.innerHTML = '<button>Parametres avances</button>'
|
|
||||||
const clicked = vi.fn()
|
|
||||||
document.querySelector('button')?.addEventListener('click', clicked)
|
|
||||||
const promise = navigateTo('https://example.com')
|
|
||||||
finishLoad()
|
|
||||||
await promise
|
|
||||||
expect(clicked).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not fail navigation when the cookie-dismiss script injection itself fails', async () => {
|
|
||||||
const promise = navigateTo('https://example.com')
|
|
||||||
lastWindow!.webContents.executeJavaScript = vi.fn(async () => {
|
|
||||||
throw new Error('injection blocked')
|
|
||||||
})
|
|
||||||
finishLoad()
|
|
||||||
await expect(promise).resolves.toBe('Titre de la page')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('goBack()', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
lastWindow?.emit('closed')
|
|
||||||
vi.clearAllMocks()
|
|
||||||
lastWindow = null
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should throw when no browser window is open', async () => {
|
|
||||||
await expect(goBack()).rejects.toThrow(/Aucun navigateur ouvert/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return false when there is no previous page', async () => {
|
|
||||||
const navPromise = navigateTo('https://example.com')
|
|
||||||
finishLoad()
|
|
||||||
await navPromise
|
|
||||||
lastWindow!.webContents.navigationHistory.canGoBack.mockReturnValue(false)
|
|
||||||
expect(await goBack()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should go back and wait for the page to finish loading', async () => {
|
|
||||||
const navPromise = navigateTo('https://example.com')
|
|
||||||
finishLoad()
|
|
||||||
await navPromise
|
|
||||||
const backPromise = goBack()
|
|
||||||
finishLoad()
|
|
||||||
expect(await backPromise).toBe(true)
|
|
||||||
expect(lastWindow?.webContents.navigationHistory.goBack).toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('page interaction functions (require an open window)', () => {
|
|
||||||
beforeEach(async () => {
|
|
||||||
lastWindow?.emit('closed')
|
|
||||||
vi.clearAllMocks()
|
|
||||||
lastWindow = null
|
|
||||||
document.body.innerHTML = ''
|
|
||||||
const navPromise = navigateTo('https://example.com')
|
|
||||||
finishLoad()
|
|
||||||
await navPromise
|
|
||||||
})
|
|
||||||
|
|
||||||
it('readPageText() should throw when no browser window is open', async () => {
|
|
||||||
lastWindow?.emit('closed')
|
|
||||||
await expect(readPageText()).rejects.toThrow(/Aucun navigateur ouvert/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('readPageText() should return the trimmed body text', async () => {
|
|
||||||
document.body.innerHTML = '<p>Bonjour le monde</p>'
|
|
||||||
const text = await readPageText()
|
|
||||||
expect(text).toContain('Bonjour le monde')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clickElementByText() should click a visible button matching the text and return true', async () => {
|
|
||||||
document.body.innerHTML = '<button>Connexion</button>'
|
|
||||||
const clicked = vi.fn()
|
|
||||||
document.querySelector('button')?.addEventListener('click', clicked)
|
|
||||||
const result = await clickElementByText('Connexion')
|
|
||||||
expect(result).toBe(true)
|
|
||||||
expect(clicked).toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clickElementByText() should return false when nothing matches', async () => {
|
|
||||||
document.body.innerHTML = '<button>Autre chose</button>'
|
|
||||||
expect(await clickElementByText('Introuvable')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clickElementByText() should fall back to a partial (includes) match', async () => {
|
|
||||||
document.body.innerHTML = '<a href="#">Voir tous les articles</a>'
|
|
||||||
expect(await clickElementByText('articles')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clickElementByText() should match a submit input by its value attribute', async () => {
|
|
||||||
document.body.innerHTML = '<input type="submit" value="Envoyer" />'
|
|
||||||
expect(await clickElementByText('Envoyer')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('collectTranslatableElements() should collect visible leaf text nodes', async () => {
|
|
||||||
document.body.innerHTML = '<p>Un paragraphe</p><div><span>Imbrique</span></div>'
|
|
||||||
const elements = await collectTranslatableElements()
|
|
||||||
expect(elements.length).toBeGreaterThan(0)
|
|
||||||
expect(elements.some((e) => e.text === 'Un paragraphe')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('applyTranslations() should replace the text of tagged elements', async () => {
|
|
||||||
document.body.innerHTML = '<p>Original</p>'
|
|
||||||
const [element] = await collectTranslatableElements()
|
|
||||||
await applyTranslations([{ id: element!.id, text: 'Traduit' }])
|
|
||||||
expect(document.querySelector('p')?.textContent).toBe('Traduit')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('highlightText() should return false when the text is not found on the page', async () => {
|
|
||||||
document.body.innerHTML = '<p>Contenu quelconque</p>'
|
|
||||||
expect(await highlightText('texte introuvable')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('highlightText() should return false for an empty search string', async () => {
|
|
||||||
expect(await highlightText(' ')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('highlightText() should wrap the matching text in a <mark> element', async () => {
|
|
||||||
document.body.innerHTML = '<p>Le prix est de 42 euros aujourd-hui</p>'
|
|
||||||
const found = await highlightText('42 euros')
|
|
||||||
expect(found).toBe(true)
|
|
||||||
expect(document.querySelector('mark')?.textContent).toBe('42 euros')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('collectTranslatableElements() should skip elements with empty text', async () => {
|
|
||||||
document.body.innerHTML = '<p> </p><p>Texte reel</p>'
|
|
||||||
const elements = await collectTranslatableElements()
|
|
||||||
expect(elements.map((e) => e.text)).toEqual(['Texte reel'])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
// Appels directs des fonctions injectees dans la page (exportees pour etre testables) : memes
|
|
||||||
// fonctions que celles envoyees a executeJavaScript via .toString(), executees ici directement
|
|
||||||
// contre le vrai `document` de jsdom pour une couverture de branches complete.
|
|
||||||
describe('dismissCookieBannerInPage()', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
document.body.innerHTML = ''
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should click the first matching phrase and return it', () => {
|
|
||||||
document.body.innerHTML = '<button>Tout accepter</button>'
|
|
||||||
expect(dismissCookieBannerInPage(['tout accepter'])).toBe('tout accepter')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return null when no phrase matches any element', () => {
|
|
||||||
document.body.innerHTML = '<button>Parametres</button>'
|
|
||||||
expect(dismissCookieBannerInPage(['tout accepter', 'accepter'])).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should match a [role="button"] or an anchor, not only <button>', () => {
|
|
||||||
document.body.innerHTML = '<a role="button">J\'accepte</a>'
|
|
||||||
expect(dismissCookieBannerInPage(["j'accepte"])).toBe("j'accepte")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('clickByTextInPage()', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
document.body.innerHTML = ''
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return false when there are no candidate elements at all', () => {
|
|
||||||
expect(clickByTextInPage('rien')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return false when candidates exist but none match', () => {
|
|
||||||
document.body.innerHTML = '<button>Autre chose</button>'
|
|
||||||
expect(clickByTextInPage('Introuvable')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should prefer an exact match over a partial one when both exist', () => {
|
|
||||||
document.body.innerHTML = '<button>Suivant</button><button>Suivant encore</button>'
|
|
||||||
expect(clickByTextInPage('Suivant')).toBe(true)
|
|
||||||
expect((document.querySelectorAll('button')[0] as HTMLElement).onclick).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should match an input[type="button"] by its value attribute', () => {
|
|
||||||
document.body.innerHTML = '<input type="button" value="Annuler" />'
|
|
||||||
expect(clickByTextInPage('Annuler')).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('collectInPage()', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
document.body.innerHTML = ''
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should respect the given limit', () => {
|
|
||||||
document.body.innerHTML = '<p>Un</p><p>Deux</p><p>Trois</p>'
|
|
||||||
expect(collectInPage(2)).toHaveLength(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should skip a non-leaf element containing nested block content', () => {
|
|
||||||
document.body.innerHTML = '<div><p>Paragraphe interne</p></div>'
|
|
||||||
const results = collectInPage(150)
|
|
||||||
expect(results.some((r) => r.text === 'Paragraphe interne')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return an empty array when the page has no matching elements', () => {
|
|
||||||
document.body.innerHTML = '<svg></svg>'
|
|
||||||
expect(collectInPage(150)).toEqual([])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('applyInPage()', () => {
|
|
||||||
it('should do nothing for an id that does not exist on the page', () => {
|
|
||||||
document.body.innerHTML = '<p>Original</p>'
|
|
||||||
expect(() => applyInPage([{ id: 'inexistant', text: 'Nouveau' }])).not.toThrow()
|
|
||||||
expect(document.querySelector('p')?.textContent).toBe('Original')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('highlightInPage()', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
document.body.innerHTML = ''
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return false for an empty target string', () => {
|
|
||||||
expect(highlightInPage('')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return false when window.find reports no match', () => {
|
|
||||||
document.body.innerHTML = '<p>Rien ici</p>'
|
|
||||||
expect(highlightInPage('absent')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should wrap the matching text node in a <mark> and scroll it into view', () => {
|
|
||||||
document.body.innerHTML = '<p>Le prix est de 42 euros aujourd-hui</p>'
|
|
||||||
expect(highlightInPage('42 euros')).toBe(true)
|
|
||||||
expect(document.querySelector('mark')?.textContent).toBe('42 euros')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return false when a match is found but the selection has no range', () => {
|
|
||||||
const getSelectionSpy = vi.spyOn(window, 'getSelection').mockReturnValue(null)
|
|
||||||
document.body.innerHTML = '<p>Un texte a trouver ici</p>'
|
|
||||||
expect(highlightInPage('trouver')).toBe(false)
|
|
||||||
getSelectionSpy.mockRestore()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
import { describe, it, expect, vi } from 'vitest'
|
|
||||||
|
|
||||||
const clickElementByText = vi.fn(async (text: string) => text !== 'introuvable')
|
|
||||||
const goBack = vi.fn(async () => true)
|
|
||||||
const highlightText = vi.fn(async (text: string) => text !== 'introuvable')
|
|
||||||
const navigateTo = vi.fn(async () => 'Titre de la page')
|
|
||||||
const readPageText = vi.fn(async () => 'Contenu de la page')
|
|
||||||
|
|
||||||
vi.mock('../../src/main/browser/browserWindow', () => ({
|
|
||||||
clickElementByText,
|
|
||||||
goBack,
|
|
||||||
highlightText,
|
|
||||||
navigateTo,
|
|
||||||
readPageText
|
|
||||||
}))
|
|
||||||
|
|
||||||
const { clickBrowserElement } = await import('../../src/main/skills/browser/clickBrowserElement')
|
|
||||||
const { goBackBrowser } = await import('../../src/main/skills/browser/goBackBrowser')
|
|
||||||
const { highlightBrowserText } = await import('../../src/main/skills/browser/highlightBrowserText')
|
|
||||||
const { navigateBrowser } = await import('../../src/main/skills/browser/navigateBrowser')
|
|
||||||
const { readBrowserPage } = await import('../../src/main/skills/browser/readBrowserPage')
|
|
||||||
|
|
||||||
describe('click_browser_element', () => {
|
|
||||||
it('should refuse an empty text', async () => {
|
|
||||||
await expect(clickBrowserElement.execute({ text: '' })).rejects.toThrow(/text manquant/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report success when the element is found and clicked', async () => {
|
|
||||||
const result = await clickBrowserElement.execute({ text: 'Connexion' })
|
|
||||||
expect(result).toMatch(/Clic effectue/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report failure when no matching element is found', async () => {
|
|
||||||
const result = await clickBrowserElement.execute({ text: 'introuvable' })
|
|
||||||
expect(result).toMatch(/Echec/)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('go_back_browser', () => {
|
|
||||||
it('should report success when going back worked', async () => {
|
|
||||||
const result = await goBackBrowser.execute({})
|
|
||||||
expect(result).toMatch(/Retour/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report failure when there is no previous page', async () => {
|
|
||||||
goBack.mockResolvedValueOnce(false)
|
|
||||||
const result = await goBackBrowser.execute({})
|
|
||||||
expect(result).toMatch(/Echec/)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('highlight_browser_text', () => {
|
|
||||||
it('should refuse an empty text', async () => {
|
|
||||||
await expect(highlightBrowserText.execute({ text: '' })).rejects.toThrow(/text manquant/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report success when the text is found', async () => {
|
|
||||||
const result = await highlightBrowserText.execute({ text: 'un passage' })
|
|
||||||
expect(result).toMatch(/surligne/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report failure when the text is not found', async () => {
|
|
||||||
const result = await highlightBrowserText.execute({ text: 'introuvable' })
|
|
||||||
expect(result).toMatch(/Echec/)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('navigate_browser', () => {
|
|
||||||
it('should refuse an empty URL', async () => {
|
|
||||||
await expect(navigateBrowser.execute({ url: '' })).rejects.toThrow(/url manquante/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should navigate and report the page title', async () => {
|
|
||||||
const result = await navigateBrowser.execute({ url: 'https://example.com' })
|
|
||||||
expect(result).toMatch(/Titre de la page/)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('read_browser_page', () => {
|
|
||||||
it('should return the page text', async () => {
|
|
||||||
const result = await readBrowserPage.execute({})
|
|
||||||
expect(result).toBe('Contenu de la page')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report an empty/unreadable page', async () => {
|
|
||||||
readPageText.mockResolvedValueOnce('')
|
|
||||||
const result = await readBrowserPage.execute({})
|
|
||||||
expect(result).toMatch(/vide ou n'a pas pu/)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import { describe, it, expect, vi } from 'vitest'
|
|
||||||
|
|
||||||
const collectTranslatableElements = vi.fn(async () => [{ id: 't0', text: 'Hello' }])
|
|
||||||
const applyTranslations = vi.fn(async () => {})
|
|
||||||
vi.mock('../../src/main/browser/browserWindow', () => ({
|
|
||||||
collectTranslatableElements,
|
|
||||||
applyTranslations
|
|
||||||
}))
|
|
||||||
|
|
||||||
const translateTexts = vi.fn(async () => ['Bonjour'])
|
|
||||||
vi.mock('../../src/main/ai/translate', () => ({ translateTexts }))
|
|
||||||
|
|
||||||
const { translateBrowserPage } = await import('../../src/main/skills/browser/translateBrowserPage')
|
|
||||||
|
|
||||||
describe('translate_browser_page', () => {
|
|
||||||
it('should refuse an empty language', async () => {
|
|
||||||
await expect(translateBrowserPage.execute({ language: '' })).rejects.toThrow(
|
|
||||||
/language manquante/
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should report no translatable text when the page is empty', async () => {
|
|
||||||
collectTranslatableElements.mockResolvedValueOnce([])
|
|
||||||
const result = await translateBrowserPage.execute({ language: 'anglais' })
|
|
||||||
expect(result).toMatch(/Aucun texte traduisible/)
|
|
||||||
expect(translateTexts).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should translate and apply the translated text to the page', async () => {
|
|
||||||
const result = await translateBrowserPage.execute({ language: 'francais' })
|
|
||||||
expect(translateTexts).toHaveBeenCalledWith(['Hello'], 'francais')
|
|
||||||
expect(applyTranslations).toHaveBeenCalledWith([{ id: 't0', text: 'Bonjour' }])
|
|
||||||
expect(result).toMatch(/Page traduite en francais \(1 elements remplaces\)/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should fall back to the original text when a translation is missing', async () => {
|
|
||||||
translateTexts.mockResolvedValueOnce([])
|
|
||||||
await translateBrowserPage.execute({ language: 'francais' })
|
|
||||||
expect(applyTranslations).toHaveBeenCalledWith([{ id: 't0', text: 'Hello' }])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
||||||
import { translateTexts } from '../../src/main/ai/translate'
|
|
||||||
|
|
||||||
describe('translateTexts()', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.stubGlobal('fetch', vi.fn())
|
|
||||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should return the translated array when the API call succeeds', async () => {
|
|
||||||
vi.mocked(fetch).mockResolvedValue({
|
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
choices: [{ message: { content: '["Bonjour", "Au revoir"]' } }]
|
|
||||||
})
|
|
||||||
} as Response)
|
|
||||||
|
|
||||||
const result = await translateTexts(['Hello', 'Goodbye'], 'francais')
|
|
||||||
expect(result).toEqual(['Bonjour', 'Au revoir'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should extract a JSON array even when the model wraps it in extra text', async () => {
|
|
||||||
vi.mocked(fetch).mockResolvedValue({
|
|
||||||
ok: true,
|
|
||||||
json: () =>
|
|
||||||
Promise.resolve({
|
|
||||||
choices: [{ message: { content: 'Voici le resultat:\n["Salut"]\nVoila.' } }]
|
|
||||||
})
|
|
||||||
} as Response)
|
|
||||||
|
|
||||||
const result = await translateTexts(['Hi'], 'francais')
|
|
||||||
expect(result).toEqual(['Salut'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should throw when the API call fails', async () => {
|
|
||||||
vi.mocked(fetch).mockResolvedValue({
|
|
||||||
ok: false,
|
|
||||||
status: 500,
|
|
||||||
text: () => Promise.resolve('Internal error')
|
|
||||||
} as Response)
|
|
||||||
|
|
||||||
await expect(translateTexts(['Hello'], 'francais')).rejects.toThrow(/Traduction echouee/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should throw when the API key is missing', async () => {
|
|
||||||
delete process.env.OPENROUTER_API_KEY
|
|
||||||
await expect(translateTexts(['Hello'], 'francais')).rejects.toThrow(/OPENROUTER_API_KEY/)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
Reference in New Issue
Block a user