chore(cleanup): remove basic-only utility skills

Removes the system-action skills that were only ever available in the now
-retired Basic/Assistant modes (play_music, open/close_app, open_notepad,
create_document, create_powerpoint, control_volume, control_media_playback,
take_screenshot, clipboard, search_file, set_reminder, lock_screen,
empty_recycle_bin, show_notification, print_file, create_folder,
create_file, delete_file, fill_browser_field) along with their
windows/lib helpers (appRegistry, fileSearch, locations, sendVirtualKey)
and the fillField browser-window helper. Keeps the read-only, side-effect
-free transversal skills (search_web, navigate_browser and friends,
check_system_memory/storage/battery/internet). Drops the now-unused
docx/pptxgenjs dependencies and the stale coachStore/meetingStore entries
from the coverage exclude list.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-10-31 19:33:04 +01:00
parent 83043b5819
commit b8aec9ed6b
45 changed files with 7 additions and 1891 deletions
-111
View File
@@ -12,13 +12,11 @@
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
"cheerio": "^1.2.0",
"docx": "^9.13.0",
"dotenv": "^18.0.8",
"electron-updater": "^6.8.11",
"mammoth": "^1.13.0",
"pdf-lib": "^1.17.1",
"pdf-parse": "^1.1.1",
"pptxgenjs": "^4.0.1",
"three": "^0.186.1"
},
"devDependencies": {
@@ -3977,54 +3975,6 @@
"node": ">=0.10.0"
}
},
"node_modules/docx": {
"version": "9.13.0",
"resolved": "https://registry.npmjs.org/docx/-/docx-9.13.0.tgz",
"integrity": "sha512-MofrvX7rzwCe1xUFXnwneQHzv2p1lIUIDPD01DueOnKGw+TSKxAAcK5Beo69bTyqKUYsX8d49Co03Bcntc60WQ==",
"license": "MIT",
"dependencies": {
"@types/node": "^26.6.2",
"hash.js": "^1.1.7",
"jszip": "^3.10.1",
"nanoid": "^6.0.1"
},
"engines": {
"node": ">=10"
}
},
"node_modules/docx/node_modules/@types/node": {
"version": "26.6.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/docx/node_modules/nanoid": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.2.tgz",
"integrity": "sha512-hIvVOb9Qr1p/9CNNLOe0OlWvgx/ziTsVwKN/GDSsuArN2K0wDiafP3s0SWmsm7o2BdnyS8Z9Z64NFBUbn6ziBg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.js"
},
"engines": {
"node": "^22 || ^24 || >=26"
}
},
"node_modules/docx/node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"license": "MIT"
},
"node_modules/dom-accessibility-api": {
"version": "0.5.16",
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
@@ -5885,16 +5835,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hash.js": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz",
"integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"minimalistic-assert": "^1.0.1"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
@@ -6037,12 +5977,6 @@
"node": ">=10.19.0"
}
},
"node_modules/https": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/https/-/https-1.0.0.tgz",
"integrity": "sha512-4EC57ddXrkaF0x83Oj8sM6SLQHAWXw90Skqu2M4AEWENZ3F02dFJE/GARA8igO79tcgYqGrD7ae4f5L3um2lgg==",
"license": "ISC"
},
"node_modules/https-proxy-agent": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
@@ -6095,18 +6029,6 @@
"node": ">= 4"
}
},
"node_modules/image-size": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.4.tgz",
"integrity": "sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw==",
"license": "MIT",
"bin": {
"image-size": "bin/image-size.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
@@ -7490,12 +7412,6 @@
"node": ">=4"
}
},
"node_modules/minimalistic-assert": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz",
"integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==",
"license": "ISC"
},
"node_modules/minimatch": {
"version": "10.2.6",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
@@ -8364,33 +8280,6 @@
"node": "^12.20.0 || >=14"
}
},
"node_modules/pptxgenjs": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/pptxgenjs/-/pptxgenjs-4.0.1.tgz",
"integrity": "sha512-TeJISr8wouAuXw4C1F/mC33xbZs/FuEG6nH9FG1Zj+nuPcGMP5YRHl6X+j3HSUnS1f3at6k75ZZXPMZlA5Lj9A==",
"license": "MIT",
"dependencies": {
"@types/node": "^22.8.1",
"https": "^1.0.0",
"image-size": "^1.2.1",
"jszip": "^3.10.1"
}
},
"node_modules/pptxgenjs/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/pptxgenjs/node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"license": "MIT"
},
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
-2
View File
@@ -45,13 +45,11 @@
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
"cheerio": "^1.2.0",
"docx": "^9.13.0",
"dotenv": "^18.0.8",
"electron-updater": "^6.8.11",
"mammoth": "^1.13.0",
"pdf-lib": "^1.17.1",
"pdf-parse": "^1.1.1",
"pptxgenjs": "^4.0.1",
"three": "^0.186.1"
},
"devDependencies": {
@@ -147,47 +147,6 @@ export function clickByTextInPage(target: string): boolean {
return true
}
export async function fillField(field: string, value: string, submit: boolean): Promise<boolean> {
const window = requireWindow()
return (await window.webContents.executeJavaScript(
`(${fillFieldInPage.toString()})(${JSON.stringify(field)}, ${JSON.stringify(value)}, ${JSON.stringify(submit)})`
)) as boolean
}
export function fillFieldInPage(field: string, value: string, submit: boolean): boolean {
const needle = field.trim().toLowerCase()
const inputs = Array.from(
document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>('input, textarea')
)
const score = (el: HTMLInputElement | HTMLTextAreaElement): string => {
const label = el.labels?.[0]?.innerText ?? ''
return [el.name, el.id, el.placeholder, label, el.getAttribute('aria-label') ?? '']
.join(' ')
.toLowerCase()
}
const match = inputs.find((el) => score(el).includes(needle))
if (!match) return false
const descriptor = Object.getOwnPropertyDescriptor(
match instanceof HTMLTextAreaElement
? HTMLTextAreaElement.prototype
: HTMLInputElement.prototype,
'value'
)
descriptor?.set?.call(match, value)
match.dispatchEvent(new Event('input', { bubbles: true }))
match.dispatchEvent(new Event('change', { bubbles: true }))
if (submit) {
const form = match.closest('form')
if (form) form.requestSubmit ? form.requestSubmit() : form.submit()
else match.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
}
return true
}
interface TaggedElement {
id: string
text: string
@@ -1,34 +0,0 @@
import { fillField } from '../../browser/browserWindow'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const fillBrowserField: SkillDefinition = {
name: 'fill_browser_field',
description:
"Remplit un champ de formulaire (texte, recherche...) dans le navigateur integre, identifie par son nom/placeholder/label approximatif, et peut le valider. Le matching n'est pas garanti a 100% sur tous les sites.",
parameters: {
type: 'object',
properties: {
field: {
type: 'string',
description: 'Description du champ (ex: "recherche", "email", "nom")'
},
value: { type: 'string', description: 'Valeur a saisir' },
submit: {
type: 'boolean',
description: 'Valider le formulaire apres saisie (defaut : false)'
}
},
required: ['field', 'value']
},
execute: async (args) => {
const field = asString(args.field).trim()
const value = asString(args.value)
const submit = args.submit === true
if (!field) throw new Error('field manquant')
const filled = await fillField(field, value, submit)
return filled
? `Champ "${field}" rempli${submit ? ' et formulaire valide' : ''}.`
: `Echec : aucun champ correspondant a "${field}" trouve sur la page.`
}
}
@@ -3,7 +3,6 @@ import { navigateBrowser } from './navigateBrowser'
import { readBrowserPage } from './readBrowserPage'
import { clickBrowserElement } from './clickBrowserElement'
import { goBackBrowser } from './goBackBrowser'
import { fillBrowserField } from './fillBrowserField'
import { translateBrowserPage } from './translateBrowserPage'
import { highlightBrowserText } from './highlightBrowserText'
@@ -13,7 +12,6 @@ export const browserSkills: SkillDefinition[] = [
readBrowserPage,
clickBrowserElement,
goBackBrowser,
fillBrowserField,
translateBrowserPage,
highlightBrowserText
]
@@ -1,35 +0,0 @@
import { clipboard } from 'electron'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const clipboardSkill: SkillDefinition = {
name: 'clipboard',
description: 'Lit le contenu texte du presse-papier, ou y copie un texte donne.',
parameters: {
type: 'object',
properties: {
action: { type: 'string', enum: ['lire', 'copier'], description: 'Action a effectuer' },
text: { type: 'string', description: 'Texte a copier (requis si action = copier)' }
},
required: ['action']
},
execute: async (args) => {
const action = asString(args.action)
if (action === 'lire') {
const text = await clipboard.readText()
return text
? `Contenu du presse-papier : ${text}`
: 'Le presse-papier est vide ou ne contient pas de texte.'
}
if (action === 'copier') {
const text = asString(args.text)
if (!text) throw new Error('texte manquant')
await clipboard.writeText(text)
return 'Texte copie dans le presse-papier.'
}
throw new Error('action invalide')
}
}
@@ -1,70 +0,0 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { APP_REGISTRY } from './lib/appRegistry'
import { TASKKILL_EXE } from './lib/systemPaths'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
const execFileAsync = promisify(execFile)
// Certaines applications se lancent via un executable/raccourci mais tournent sous un autre nom
// de process une fois ouvertes (ex: la Calculatrice modernisee de Windows 11, les Parametres).
// On essaie chaque candidat jusqu'a ce qu'un taskkill reussisse.
const CLOSE_OVERRIDES: Record<string, string[]> = {
calculatrice: ['CalculatorApp.exe', 'calc.exe', 'Calculator.exe'],
calculator: ['CalculatorApp.exe', 'calc.exe', 'Calculator.exe'],
parametres: ['SystemSettings.exe']
}
// explorer.exe n'est pas une "application" mais le shell Windows (bureau + barre des taches) :
// le tuer fait disparaitre tout l'affichage. Jamais fermable via cette competence.
const PROTECTED_PROCESSES = new Set(['explorer.exe'])
function lookupAppRegistry(key: string): string | undefined {
return Object.hasOwn(APP_REGISTRY, key) ? Reflect.get(APP_REGISTRY, key) : undefined
}
function lookupCloseOverride(key: string): string[] | undefined {
return Object.hasOwn(CLOSE_OVERRIDES, key) ? Reflect.get(CLOSE_OVERRIDES, key) : undefined
}
const CLOSABLE_APPS = Array.from(
new Set([...Object.keys(APP_REGISTRY), ...Object.keys(CLOSE_OVERRIDES)])
).filter((key) => !PROTECTED_PROCESSES.has(lookupAppRegistry(key)?.toLowerCase() ?? ''))
export const closeApp: SkillDefinition = {
name: 'close_app',
description: `Ferme une application en cours d'execution par son nom. Applications reconnues : ${CLOSABLE_APPS.join(', ')}.`,
parameters: {
type: 'object',
properties: {
application: { type: 'string', description: "Nom de l'application a fermer" }
},
required: ['application']
},
execute: async (args) => {
const application = asString(args.application)
const key = application.toLowerCase().trim()
const target = lookupAppRegistry(key)
const rawCandidates = lookupCloseOverride(key) ?? (target ? [target] : null)
if (!rawCandidates) {
return `Application "${application}" non reconnue.`
}
const candidates = rawCandidates.filter((name) => !PROTECTED_PROCESSES.has(name.toLowerCase()))
if (candidates.length === 0) {
return "L'explorateur de fichiers est le bureau Windows lui-meme : le fermer couperait tout l'affichage, ce n'est pas autorise."
}
for (const processName of candidates) {
try {
await execFileAsync(TASKKILL_EXE, ['/IM', processName, '/F'])
return `${application} ferme(e).`
} catch {
// on essaie le candidat suivant
}
}
return `${application} ne semble pas etre ouvert(e).`
}
}
@@ -1,41 +0,0 @@
import { shell } from 'electron'
import { writeFileSync } from 'fs'
import { join } from 'path'
import { LOCATION_NAMES, resolveLocation } from './lib/locations'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const createFile: SkillDefinition = {
name: 'create_file',
description: `Cree un fichier texte (.txt) avec un contenu donne dans un emplacement courant (${LOCATION_NAMES.join(', ')}) et l'ouvre.`,
parameters: {
type: 'object',
properties: {
name: {
type: 'string',
description: "Nom du fichier (l'extension .txt est ajoutee si absente)"
},
content: { type: 'string', description: 'Contenu texte du fichier' },
location: {
type: 'string',
enum: [...LOCATION_NAMES],
description: 'Ou creer le fichier (defaut : bureau)'
}
},
required: ['name']
},
execute: async (args) => {
const name = asString(args.name)
.trim()
.replace(/[\\/:*?"<>|]/g, '_')
if (!name) throw new Error('nom manquant')
const content = typeof args.content === 'string' ? args.content : ''
const base = resolveLocation(args.location)
const filePath = join(base, name.toLowerCase().endsWith('.txt') ? name : `${name}.txt`)
writeFileSync(filePath, content, 'utf-8')
await shell.openPath(filePath)
return `Fichier cree et ouvert : ${filePath}.`
}
}
@@ -1,37 +0,0 @@
import { shell } from 'electron'
import { existsSync, mkdirSync } from 'fs'
import { join } from 'path'
import { LOCATION_NAMES, resolveLocation } from './lib/locations'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const createFolder: SkillDefinition = {
name: 'create_folder',
description: `Cree un nouveau dossier dans un emplacement courant (${LOCATION_NAMES.join(', ')}) et l'ouvre.`,
parameters: {
type: 'object',
properties: {
name: { type: 'string', description: 'Nom du dossier a creer' },
location: {
type: 'string',
enum: [...LOCATION_NAMES],
description: 'Ou creer le dossier (defaut : bureau)'
}
},
required: ['name']
},
execute: async (args) => {
const name = asString(args.name)
.trim()
.replace(/[\\/:*?"<>|]/g, '_')
if (!name) throw new Error('nom manquant')
const base = resolveLocation(args.location)
const dirPath = join(base, name)
if (existsSync(dirPath)) return `Le dossier "${name}" existe deja dans ${base}.`
mkdirSync(dirPath, { recursive: true })
await shell.openPath(dirPath)
return `Dossier cree et ouvert : ${dirPath}.`
}
}
@@ -1,56 +0,0 @@
import { app, shell } from 'electron'
import PptxGenJS from 'pptxgenjs'
import { join } from 'path'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
interface SlideInput {
title: string
content?: string
}
export const createPowerpoint: SkillDefinition = {
name: 'create_powerpoint',
description:
"Cree une presentation a partir d'une liste de diapositives (titre + contenu chacune) et l'enregistre en .pptx dans le dossier Documents.",
parameters: {
type: 'object',
properties: {
title: { type: 'string', description: 'Titre de la presentation (sert de nom de fichier)' },
slides: {
type: 'array',
description: 'Liste des diapositives a creer',
items: {
type: 'object',
properties: {
title: { type: 'string', description: 'Titre de la diapositive' },
content: { type: 'string', description: 'Texte du corps de la diapositive' }
},
required: ['title']
}
}
},
required: ['title', 'slides']
},
execute: async (args) => {
const title = asString(args.title, 'Presentation')
const slides = Array.isArray(args.slides) ? (args.slides as SlideInput[]) : []
if (slides.length === 0) throw new Error('diapositives manquantes')
const pptx = new PptxGenJS()
for (const slide of slides) {
const s = pptx.addSlide()
s.addText(slide.title, { x: 0.5, y: 0.4, w: 9, h: 1, fontSize: 28, bold: true })
if (slide.content) {
s.addText(slide.content, { x: 0.5, y: 1.6, w: 9, h: 4.5, fontSize: 18 })
}
}
const safeName = title.replace(/[\\/:*?"<>|]/g, '_').slice(0, 80) || 'Presentation'
const pptxPath = join(app.getPath('documents'), `${safeName}.pptx`)
await pptx.writeFile({ fileName: pptxPath })
await shell.openPath(pptxPath)
return `Presentation creee, enregistree et ouverte : ${pptxPath}.`
}
}
@@ -1,66 +0,0 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { statSync } from 'fs'
import { app } from 'electron'
import { findFileByName } from './lib/fileSearch'
import { POWERSHELL_EXE } from './lib/systemPaths'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
const execFileAsync = promisify(execFile)
const psQuote = (value: string): string => value.replace(/'/g, "''")
// Jamais question de supprimer un de ces dossiers eux-memes (seulement leur contenu trouve par
// recherche), ni une racine de disque.
const PROTECTED_PATHS = new Set(
(['desktop', 'documents', 'downloads', 'pictures', 'videos', 'music', 'home'] as const).map(
(name) => app.getPath(name).toLowerCase()
)
)
function stripTrailingSlashes(value: string): string {
let end = value.length
while (end > 0 && (value[end - 1] === '\\' || value[end - 1] === '/')) end--
return value.slice(0, end)
}
function isProtected(path: string): boolean {
const normalized = stripTrailingSlashes(path.toLowerCase())
if (PROTECTED_PATHS.has(normalized)) return true
// Racine de disque (ex: "C:" ou "C:\\")
if (/^[a-z]:\\?$/i.test(path)) return true
return false
}
export const deleteFileOrFolder: SkillDefinition = {
name: 'delete_file',
description:
"Recherche un fichier ou dossier par son nom et le supprime en l'envoyant a la corbeille (recuperable, jamais de suppression definitive).",
parameters: {
type: 'object',
properties: {
name: { type: 'string', description: 'Nom (ou partie du nom) du fichier/dossier a supprimer' }
},
required: ['name']
},
execute: async (args) => {
const name = asString(args.name).trim()
if (!name) throw new Error('nom manquant')
const foundPath = await findFileByName(name)
if (!foundPath) return `Aucun fichier ou dossier correspondant a "${name}" trouve.`
if (isProtected(foundPath)) {
return `"${foundPath}" est un dossier protege, suppression refusee.`
}
const isDirectory = statSync(foundPath).isDirectory()
const method = isDirectory ? 'DeleteDirectory' : 'DeleteFile'
const script = `
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::${method}('${psQuote(foundPath)}', 'OnlyErrorDialogs', 'SendToRecycleBin')
`
await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', script])
return `Envoye a la corbeille : ${foundPath}.`
}
}
@@ -1,20 +0,0 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { POWERSHELL_EXE } from './lib/systemPaths'
import type { SkillDefinition } from '../types'
const execFileAsync = promisify(execFile)
export const emptyRecycleBin: SkillDefinition = {
name: 'empty_recycle_bin',
description: "Vide la corbeille Windows pour liberer de l'espace disque.",
parameters: { type: 'object', properties: {} },
execute: async () => {
try {
await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', 'Clear-RecycleBin -Force'])
} catch {
// Clear-RecycleBin renvoie parfois un code d'erreur si la corbeille est deja vide.
}
return 'Corbeille videe.'
}
}
+1 -39
View File
@@ -1,50 +1,12 @@
import type { SkillDefinition } from '../types'
import { playMusic } from './playMusic'
import { openApp } from './openApp'
import { closeApp } from './closeApp'
import { openNotepad } from './openNotepad'
import { writeWordDocument } from './writeWordDocument'
import { createPowerpoint } from './createPowerpoint'
import { systemMemory } from './systemMemory'
import { systemStorage } from './systemStorage'
import { systemVolume } from './systemVolume'
import { mediaControl } from './mediaControl'
import { takeScreenshot } from './takeScreenshot'
import { clipboardSkill } from './clipboard'
import { systemStatus } from './systemStatus'
import { searchFile } from './searchFile'
import { reminder } from './reminder'
import { lockScreen } from './lockScreen'
import { emptyRecycleBin } from './emptyRecycleBin'
import { showNotification } from './showNotification'
import { checkInternet } from './checkInternet'
import { printFile } from './printFile'
import { createFolder } from './createFolder'
import { createFile } from './createFile'
import { deleteFileOrFolder } from './deleteFileOrFolder'
export const windowsSkills: SkillDefinition[] = [
playMusic,
openApp,
closeApp,
openNotepad,
writeWordDocument,
createPowerpoint,
systemMemory,
systemStorage,
systemVolume,
mediaControl,
takeScreenshot,
clipboardSkill,
systemStatus,
searchFile,
reminder,
lockScreen,
emptyRecycleBin,
showNotification,
checkInternet,
printFile,
createFolder,
createFile,
deleteFileOrFolder
checkInternet
]
@@ -1,25 +0,0 @@
// Cible fixe et connue a l'avance : la requete utilisateur ne sert qu'a choisir une cle,
// jamais a construire une commande, pour eviter toute injection.
export const APP_REGISTRY: Record<string, string> = {
'bloc-notes': 'notepad.exe',
notepad: 'notepad.exe',
calculatrice: 'calc.exe',
calculator: 'calc.exe',
paint: 'mspaint.exe',
explorateur: 'explorer.exe',
'explorateur de fichiers': 'explorer.exe',
word: 'winword.exe',
excel: 'excel.exe',
powerpoint: 'powerpnt.exe',
outlook: 'outlook.exe',
'panneau de configuration': 'control.exe',
'gestionnaire des taches': 'taskmgr.exe',
'invite de commandes': 'cmd.exe',
terminal: 'wt.exe',
chrome: 'chrome.exe',
firefox: 'firefox.exe',
edge: 'msedge.exe',
spotify: 'spotify.exe',
claude: 'claude.exe',
discord: 'discord.exe'
}
@@ -1,91 +0,0 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { app } from 'electron'
import { POWERSHELL_EXE } from './systemPaths'
const execFileAsync = promisify(execFile)
const QUICK_FOLDERS = Array.from(
new Set(
(['desktop', 'documents', 'downloads', 'pictures', 'videos', 'music'] as const).map((name) =>
app.getPath(name)
)
)
)
// Dossiers systeme exclus du scan complet : enormes, lents, et quasiment jamais ce que
// l'utilisateur cherche.
const EXCLUDED_TOP_LEVEL = [
'Windows',
'Program Files',
'Program Files (x86)',
'ProgramData',
'$Recycle.Bin',
'System Volume Information'
]
const STOPWORDS = new Set(['le', 'la', 'les', 'un', 'une', 'des', 'de', 'du', 'et', 'a', 'au'])
const psQuote = (value: string): string => value.replace(/'/g, "''")
const psArray = (values: string[]): string => values.map((v) => `'${psQuote(v)}'`).join(',')
/** Decoupe en mots significatifs : "bug d'affichage" -> ["bug", "affichage"] (ignore "d", apostrophes...). */
function toSignificantWords(nom: string): string[] {
return nom
.replace(/[`"$;|&]/g, '')
.split(/[^\p{L}\p{N}]+/u)
.filter((word) => word.length > 1 && !STOPWORDS.has(word.toLowerCase()))
}
/**
* Cherche un fichier/dossier par nom, de maniere approximative (mots dans n'importe quel ordre,
* insensible aux apostrophes/casse). Dossiers utilisateur d'abord, puis tout le stockage si besoin.
* Renvoie le chemin complet du premier resultat, ou null si rien n'est trouve.
*/
export async function findFileByName(nom: string): Promise<string | null> {
const words = toSignificantWords(nom)
const firstWord = words[0]
if (!firstWord) return null
const primaryWord = [...words].sort((a, b) => b.length - a.length)[0] ?? firstWord
const script = `
$ErrorActionPreference = 'SilentlyContinue'
$words = @(${psArray(words)})
function Test-NameMatch($name) {
foreach ($w in $words) { if ($name -notlike "*$w*") { return $false } }
return $true
}
$found = $null
foreach ($dir in @(${psArray(QUICK_FOLDERS)})) {
$match = Get-ChildItem -Path $dir -Recurse -Filter '*${psQuote(primaryWord)}*' -Force -ErrorAction SilentlyContinue |
Where-Object { Test-NameMatch $_.Name } | Select-Object -First 1
if ($match) { $found = $match.FullName; break }
}
if (-not $found) {
$exclude = @(${psArray(EXCLUDED_TOP_LEVEL)})
$drives = [System.IO.DriveInfo]::GetDrives() | Where-Object { ($_.DriveType -eq 'Fixed' -or $_.DriveType -eq 'Removable') -and $_.IsReady } | ForEach-Object { $_.RootDirectory.FullName }
:scan foreach ($drive in $drives) {
$topFile = Get-ChildItem -Path $drive -File -Force -Filter '*${psQuote(primaryWord)}*' -ErrorAction SilentlyContinue |
Where-Object { Test-NameMatch $_.Name } | Select-Object -First 1
if ($topFile) { $found = $topFile.FullName; break scan }
$topDirs = Get-ChildItem -Path $drive -Directory -Force -ErrorAction SilentlyContinue | Where-Object { $exclude -notcontains $_.Name }
foreach ($dir in $topDirs) {
$match = Get-ChildItem -Path $dir.FullName -Recurse -Filter '*${psQuote(primaryWord)}*' -Force -ErrorAction SilentlyContinue |
Where-Object { Test-NameMatch $_.Name } | Select-Object -First 1
if ($match) { $found = $match.FullName; break scan }
}
}
}
if ($found) { Write-Output $found }
`
const { stdout } = await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', script], {
timeout: 120000,
maxBuffer: 10 * 1024 * 1024
})
const foundPath = stdout.trim()
return foundPath || null
}
@@ -1,29 +0,0 @@
import { app } from 'electron'
export const LOCATION_NAMES = [
'bureau',
'documents',
'telechargements',
'images',
'videos',
'musique'
] as const
export type LocationName = (typeof LOCATION_NAMES)[number]
const PATH_NAME_BY_LOCATION: Record<LocationName, Parameters<typeof app.getPath>[0]> = {
bureau: 'desktop',
documents: 'documents',
telechargements: 'downloads',
images: 'pictures',
videos: 'videos',
musique: 'music'
}
export function resolveLocation(location: unknown): string {
const key =
typeof location === 'string' && location in PATH_NAME_BY_LOCATION
? (location as LocationName)
: 'bureau'
return app.getPath(Reflect.get(PATH_NAME_BY_LOCATION, key))
}
@@ -1,26 +0,0 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { POWERSHELL_EXE } from './systemPaths'
const execFileAsync = promisify(execFile)
const script = (keyCode: number, times: number): string => `
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class ForgeAvatarInput {
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
}
"@
for ($i = 0; $i -lt ${times}; $i++) {
[ForgeAvatarInput]::keybd_event(${keyCode}, 0, 0, [UIntPtr]::Zero)
[ForgeAvatarInput]::keybd_event(${keyCode}, 0, 2, [UIntPtr]::Zero)
Start-Sleep -Milliseconds 50
}
`
/** Simule l'appui d'une touche virtuelle Windows (volume, media...) via user32.dll. */
export async function pressVirtualKey(keyCode: number, times = 1): Promise<void> {
await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', script(keyCode, times)])
}
@@ -7,6 +7,3 @@ const systemRoot = process.env.SystemRoot || process.env.windir || 'C:\\Windows'
const system32 = join(systemRoot, 'System32')
export const POWERSHELL_EXE = join(system32, 'WindowsPowerShell', 'v1.0', 'powershell.exe')
export const TASKKILL_EXE = join(system32, 'taskkill.exe')
export const NOTEPAD_EXE = join(system32, 'notepad.exe')
export const RUNDLL32_EXE = join(system32, 'rundll32.exe')
@@ -1,13 +0,0 @@
import { execFile } from 'child_process'
import { RUNDLL32_EXE } from './lib/systemPaths'
import type { SkillDefinition } from '../types'
export const lockScreen: SkillDefinition = {
name: 'lock_screen',
description: "Verrouille la session Windows (affiche l'ecran de verrouillage).",
parameters: { type: 'object', properties: {} },
execute: async () => {
execFile(RUNDLL32_EXE, ['user32.dll,LockWorkStation'])
return 'Ecran verrouille.'
}
}
@@ -1,39 +0,0 @@
import { pressVirtualKey } from './lib/sendVirtualKey'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
const VK_MEDIA_NEXT_TRACK = 0xb0
const VK_MEDIA_PREV_TRACK = 0xb1
const VK_MEDIA_STOP = 0xb2
const VK_MEDIA_PLAY_PAUSE = 0xb3
const KEY_BY_ACTION = new Map<string, number>([
['lecture_pause', VK_MEDIA_PLAY_PAUSE],
['suivant', VK_MEDIA_NEXT_TRACK],
['precedent', VK_MEDIA_PREV_TRACK],
['stop', VK_MEDIA_STOP]
])
export const mediaControl: SkillDefinition = {
name: 'control_media_playback',
description:
'Met en pause/relance, passe au morceau suivant/precedent ou arrete la lecture multimedia en cours (musique ou video).',
parameters: {
type: 'object',
properties: {
action: {
type: 'string',
enum: ['lecture_pause', 'suivant', 'precedent', 'stop'],
description: 'Action a effectuer'
}
},
required: ['action']
},
execute: async (args) => {
const action = asString(args.action)
const keyCode = KEY_BY_ACTION.get(action)
if (!keyCode) throw new Error('action invalide')
await pressVirtualKey(keyCode, 1)
return `Commande media envoyee : ${action}.`
}
}
@@ -1,31 +0,0 @@
import { exec } from 'child_process'
import { promisify } from 'util'
import { APP_REGISTRY } from './lib/appRegistry'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
const execAsync = promisify(exec)
const APPS: Record<string, string> = { ...APP_REGISTRY, parametres: 'ms-settings:' }
export const openApp: SkillDefinition = {
name: 'open_app',
description: `Ouvre une application installee sur Windows par son nom. Applications disponibles : ${Object.keys(APPS).join(', ')}.`,
parameters: {
type: 'object',
properties: {
application: { type: 'string', description: "Nom de l'application a ouvrir" }
},
required: ['application']
},
execute: async (args) => {
const application = asString(args.application)
const key = application.toLowerCase().trim()
const target = Object.hasOwn(APPS, key) ? Reflect.get(APPS, key) : undefined
if (!target) {
return `Application "${application}" non reconnue. Applications disponibles : ${Object.keys(APPS).join(', ')}.`
}
await execAsync(`start "" "${target}"`)
return `${application} ouvert(e).`
}
}
@@ -1,31 +0,0 @@
import { execFile } from 'child_process'
import { mkdtempSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { NOTEPAD_EXE } from './lib/systemPaths'
import type { SkillDefinition } from '../types'
export const openNotepad: SkillDefinition = {
name: 'open_notepad',
description: 'Ouvre le Bloc-notes Windows, avec un texte pre-rempli si fourni.',
parameters: {
type: 'object',
properties: {
text: { type: 'string', description: 'Texte a pre-remplir dans le Bloc-notes (optionnel)' }
}
},
execute: async (args) => {
const text = typeof args.text === 'string' ? args.text : undefined
const child = text
? (() => {
const filePath = join(mkdtempSync(join(tmpdir(), 'forge-avatar-')), 'note.txt')
writeFileSync(filePath, text, 'utf-8')
return execFile(NOTEPAD_EXE, [filePath])
})()
: execFile(NOTEPAD_EXE)
child.on('error', (error) => console.error('[skill:open_notepad]', error))
return text ? 'Bloc-notes ouvert avec le texte demande.' : 'Bloc-notes ouvert.'
}
}
@@ -1,28 +0,0 @@
import { shell } from 'electron'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const playMusic: SkillDefinition = {
name: 'play_music',
description:
"Ouvre l'application de musique (Spotify si installe, sinon le lecteur web) et lance une recherche pour un titre, artiste ou album.",
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Titre, artiste ou album a jouer' }
},
required: ['query']
},
execute: async (args) => {
const query = asString(args.query).trim()
if (!query) throw new Error('requete manquante')
const encoded = encodeURIComponent(query)
try {
await shell.openExternal(`spotify:search:${encoded}`)
return `Spotify ouvert, recherche lancee pour : ${query}.`
} catch {
await shell.openExternal(`https://open.spotify.com/search/${encoded}`)
return `Lecteur Spotify web ouvert, recherche lancee pour : ${query}.`
}
}
}
@@ -1,35 +0,0 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { findFileByName } from './lib/fileSearch'
import { POWERSHELL_EXE } from './lib/systemPaths'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
const execFileAsync = promisify(execFile)
const psQuote = (value: string): string => value.replace(/'/g, "''")
export const printFile: SkillDefinition = {
name: 'print_file',
description: "Recherche un fichier par son nom et l'envoie a l'imprimante par defaut.",
parameters: {
type: 'object',
properties: {
name: { type: 'string', description: 'Nom (ou partie du nom) du fichier a imprimer' }
},
required: ['name']
},
execute: async (args) => {
const name = asString(args.name).trim()
if (!name) throw new Error('nom manquant')
const foundPath = await findFileByName(name)
if (!foundPath) return `Aucun fichier correspondant a "${name}" trouve.`
await execFileAsync(POWERSHELL_EXE, [
'-NoProfile',
'-Command',
`Start-Process -FilePath '${psQuote(foundPath)}' -Verb Print`
])
return `Impression lancee pour : ${foundPath}.`
}
}
@@ -1,38 +0,0 @@
import { synthesizeSpeech } from '../../ai/elevenlabs'
import { sendToRenderer } from '../../windowBridge'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const reminder: SkillDefinition = {
name: 'set_reminder',
description:
"Programme un rappel vocal : l'avatar prononcera le message a voix haute une fois le delai ecoule.",
parameters: {
type: 'object',
properties: {
minutes: { type: 'number', description: 'Delai en minutes avant le rappel' },
message: { type: 'string', description: 'Message a dire a voix haute lors du rappel' }
},
required: ['minutes', 'message']
},
execute: async (args) => {
const minutes = Number(args.minutes)
const message = asString(args.message).trim()
if (!minutes || minutes <= 0) throw new Error('minutes invalide')
if (!message) throw new Error('message manquant')
setTimeout(
() => {
synthesizeSpeech(message)
.then((audio) => {
const buffer = audio.buffer.slice(audio.byteOffset, audio.byteOffset + audio.byteLength)
sendToRenderer('proactive-speech', buffer)
})
.catch((error) => console.error('[rappel]', error))
},
minutes * 60 * 1000
)
return `Rappel programme dans ${minutes} minute(s) : "${message}".`
}
}
@@ -1,29 +0,0 @@
import { shell } from 'electron'
import { findFileByName } from './lib/fileSearch'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const searchFile: SkillDefinition = {
name: 'search_file',
description:
"Cherche un fichier ou dossier LOCAL (sur l'ordinateur, pas sur internet/YouTube) par son nom, de maniere approximative (ignore l'ordre des mots, les apostrophes, la casse). Commence par les dossiers utilisateur courants, puis scanne tout le stockage en profondeur si besoin (peut prendre un peu de temps). Ouvre le resultat trouve. Pour une video en ligne, utiliser navigate_browser (avec search_web pour trouver l'URL) a la place.",
parameters: {
type: 'object',
properties: {
name: { type: 'string', description: 'Nom (ou partie du nom) du fichier/dossier a chercher' }
},
required: ['name']
},
execute: async (args) => {
const name = asString(args.name).trim()
if (!name) throw new Error('nom manquant')
const foundPath = await findFileByName(name)
if (!foundPath) {
return `Aucun fichier ou dossier correspondant a "${name}" trouve, meme apres un scan complet du stockage.`
}
await shell.openPath(foundPath)
return `Trouve et ouvert : ${foundPath}.`
}
}
@@ -1,24 +0,0 @@
import { Notification } from 'electron'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
export const showNotification: SkillDefinition = {
name: 'show_notification',
description: 'Affiche une notification Windows avec un titre et un message.',
parameters: {
type: 'object',
properties: {
title: { type: 'string', description: 'Titre de la notification (defaut : Max)' },
message: { type: 'string', description: 'Contenu du message' }
},
required: ['message']
},
execute: async (args) => {
const title = asString(args.title, 'Max')
const message = asString(args.message).trim()
if (!message) throw new Error('message manquant')
new Notification({ title, body: message }).show()
return 'Notification affichee.'
}
}
@@ -1,45 +0,0 @@
import { pressVirtualKey } from './lib/sendVirtualKey'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
const VK_VOLUME_MUTE = 0xad
const VK_VOLUME_DOWN = 0xae
const VK_VOLUME_UP = 0xaf
export const systemVolume: SkillDefinition = {
name: 'control_volume',
description: "Augmente, baisse ou coupe le son de l'ordinateur.",
parameters: {
type: 'object',
properties: {
action: {
type: 'string',
enum: ['augmenter', 'baisser', 'couper'],
description: 'Action a effectuer'
},
steps: {
type: 'number',
description: 'Nombre de crans de volume (environ 2% chacun), defaut 5'
}
},
required: ['action']
},
execute: async (args) => {
const action = asString(args.action)
const steps = typeof args.steps === 'number' && args.steps > 0 ? Math.min(args.steps, 25) : 5
if (action === 'couper') {
await pressVirtualKey(VK_VOLUME_MUTE, 1)
return 'Son coupe (ou reactive si deja coupe).'
}
if (action === 'augmenter') {
await pressVirtualKey(VK_VOLUME_UP, steps)
return 'Volume augmente.'
}
if (action === 'baisser') {
await pressVirtualKey(VK_VOLUME_DOWN, steps)
return 'Volume baisse.'
}
throw new Error('action invalide')
}
}
@@ -1,24 +0,0 @@
import { app, desktopCapturer, screen } from 'electron'
import { writeFileSync } from 'fs'
import { join } from 'path'
import type { SkillDefinition } from '../types'
export const takeScreenshot: SkillDefinition = {
name: 'take_screenshot',
description: "Prend une capture de l'ecran et l'enregistre dans le dossier Images.",
parameters: { type: 'object', properties: {} },
execute: async () => {
const display = screen.getPrimaryDisplay()
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: display.size
})
const source = sources[0]
if (!source) throw new Error('Aucun ecran detecte')
const fileName = `capture-${new Date().toISOString().replace(/[:.]/g, '-')}.png`
const filePath = join(app.getPath('pictures'), fileName)
writeFileSync(filePath, source.thumbnail.toPNG())
return `Capture d'ecran enregistree : ${filePath}.`
}
}
@@ -1,115 +0,0 @@
import { app, shell } from 'electron'
import { Document, Packer, Paragraph, TextRun } from 'docx'
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'
import { writeFileSync } from 'fs'
import { join } from 'path'
import type { SkillDefinition } from '../types'
import { asString } from '../argUtils'
function safeFileName(titre: string): string {
return titre.replace(/[\\/:*?"<>|]/g, '_').slice(0, 80) || 'Document'
}
async function writeDocx(path: string, titre: string, contenu: string): Promise<void> {
const doc = new Document({
sections: [
{
children: [
new Paragraph({ children: [new TextRun({ text: titre, bold: true, size: 32 })] }),
...contenu
.split('\n')
.map((line) => new Paragraph({ children: [new TextRun({ text: line, size: 22 })] }))
]
}
]
})
writeFileSync(path, await Packer.toBuffer(doc))
}
async function writePdf(path: string, titre: string, contenu: string): Promise<void> {
const pdf = await PDFDocument.create()
const font = await pdf.embedFont(StandardFonts.Helvetica)
const bold = await pdf.embedFont(StandardFonts.HelveticaBold)
const pageWidth = 595
const pageHeight = 842
const margin = 50
const maxWidth = pageWidth - margin * 2
const fontSize = 12
const lineHeight = 16
const wrapLine = (line: string): string[] => {
if (!line) return ['']
const words = line.split(' ')
const wrapped: string[] = []
let current = ''
for (const word of words) {
const candidate = current ? `${current} ${word}` : word
if (font.widthOfTextAtSize(candidate, fontSize) > maxWidth && current) {
wrapped.push(current)
current = word
} else {
current = candidate
}
}
wrapped.push(current)
return wrapped
}
const lines = contenu.split('\n').flatMap(wrapLine)
let page = pdf.addPage([pageWidth, pageHeight])
let y = pageHeight - margin
page.drawText(titre, { x: margin, y, size: 20, font: bold, color: rgb(0, 0, 0) })
y -= 32
for (const line of lines) {
if (y < margin) {
page = pdf.addPage([pageWidth, pageHeight])
y = pageHeight - margin
}
page.drawText(line, { x: margin, y, size: fontSize, font })
y -= lineHeight
}
writeFileSync(path, await pdf.save())
}
export const writeWordDocument: SkillDefinition = {
name: 'create_document',
description:
"Cree un document texte avec un titre et un contenu, et l'enregistre dans le dossier Documents (.docx et/ou .pdf).",
parameters: {
type: 'object',
properties: {
title: { type: 'string', description: 'Titre du document (sert aussi de nom de fichier)' },
content: { type: 'string', description: 'Texte a ecrire dans le document' },
format: {
type: 'string',
enum: ['docx', 'pdf', 'both'],
description: "Format d'enregistrement (defaut : both)"
}
},
required: ['title', 'content']
},
execute: async (args) => {
const title = asString(args.title, 'Document')
const content = asString(args.content)
const format = typeof args.format === 'string' ? args.format : 'both'
if (!content) throw new Error('contenu manquant')
const safeName = safeFileName(title)
const documentsDir = app.getPath('documents')
const docxPath = join(documentsDir, `${safeName}.docx`)
const pdfPath = join(documentsDir, `${safeName}.pdf`)
if (format !== 'pdf') await writeDocx(docxPath, title, content)
if (format !== 'docx') await writePdf(pdfPath, title, content)
const openedPath = format === 'docx' ? docxPath : pdfPath
await shell.openPath(openedPath)
const saved =
format === 'both' ? `${docxPath} et ${pdfPath}` : format === 'pdf' ? pdfPath : docxPath
return `Document cree, enregistre et ouvert : ${saved}.`
}
}
@@ -73,13 +73,11 @@ const {
goBack,
readPageText,
clickElementByText,
fillField,
collectTranslatableElements,
applyTranslations,
highlightText,
dismissCookieBannerInPage,
clickByTextInPage,
fillFieldInPage,
collectInPage,
applyInPage,
highlightInPage
@@ -216,47 +214,6 @@ describe('page interaction functions (require an open window)', () => {
expect(await clickElementByText('Envoyer')).toBe(true)
})
it('fillField() should fill a matching input by its name/placeholder/label', async () => {
document.body.innerHTML = '<input name="email" placeholder="Votre email" />'
const result = await fillField('email', 'test@example.com', false)
expect(result).toBe(true)
expect((document.querySelector('input') as HTMLInputElement).value).toBe('test@example.com')
})
it('fillField() should return false when no matching field is found', async () => {
document.body.innerHTML = '<input name="phone" />'
expect(await fillField('adresse', 'x', false)).toBe(false)
})
it('fillField() should match a field by its associated <label>', async () => {
document.body.innerHTML = '<label for="champ1">Numero de telephone</label><input id="champ1" />'
expect(await fillField('telephone', '0600000000', false)).toBe(true)
})
it('fillField() should fill a textarea too', async () => {
document.body.innerHTML = '<textarea name="message"></textarea>'
expect(await fillField('message', 'Bonjour', false)).toBe(true)
expect((document.querySelector('textarea') as HTMLTextAreaElement).value).toBe('Bonjour')
})
it('fillField() should submit the enclosing form when submit is requested', async () => {
document.body.innerHTML = '<form><input name="q" /></form>'
const form = document.querySelector('form') as HTMLFormElement
const requestSubmit = vi.fn()
form.requestSubmit = requestSubmit
await fillField('q', 'recherche', true)
expect(requestSubmit).toHaveBeenCalled()
})
it('fillField() should dispatch an Enter keydown when submitting a field with no form', async () => {
document.body.innerHTML = '<input name="q" />'
const input = document.querySelector('input')!
const keydown = vi.fn()
input.addEventListener('keydown', keydown)
await fillField('q', 'recherche', true)
expect(keydown).toHaveBeenCalled()
})
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()
@@ -344,36 +301,6 @@ describe('clickByTextInPage()', () => {
})
})
describe('fillFieldInPage()', () => {
beforeEach(() => {
document.body.innerHTML = ''
})
it('should return false when there are no input/textarea elements at all', () => {
expect(fillFieldInPage('email', 'x', false)).toBe(false)
})
it('should match by aria-label', () => {
document.body.innerHTML = '<input aria-label="Code postal" />'
expect(fillFieldInPage('code postal', '75000', false)).toBe(true)
})
it('should match by id', () => {
document.body.innerHTML = '<input id="search-box" />'
expect(fillFieldInPage('search', 'chaussures', false)).toBe(true)
})
it('should fall back to form.submit() when requestSubmit is unavailable', () => {
document.body.innerHTML = '<form><input name="q" /></form>'
const form = document.querySelector('form') as HTMLFormElement
;(form as unknown as { requestSubmit: unknown }).requestSubmit = undefined
const submit = vi.fn()
form.submit = submit
fillFieldInPage('q', 'recherche', true)
expect(submit).toHaveBeenCalled()
})
})
describe('collectInPage()', () => {
beforeEach(() => {
document.body.innerHTML = ''
@@ -1,64 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('electron', () => ({ app: { getPath: (name: string) => `C:\\Users\\test\\${name}` } }))
const execFileMock = vi.fn(
(
_cmd: string,
_args: string[],
_opts: unknown,
cb?: (err: Error | null, result: { stdout: string; stderr: string }) => void
) => {
const callback = typeof _opts === 'function' ? (_opts as typeof cb) : cb
callback?.(null, { stdout: '', stderr: '' })
}
)
vi.mock('child_process', () => ({ execFile: execFileMock }))
const { findFileByName } = await import('../../src/main/skills/windows/lib/fileSearch')
function mockStdout(stdout: string): void {
execFileMock.mockImplementation(
(
_cmd: string,
_args: string[],
optsOrCb: unknown,
cb?: (err: Error | null, result: { stdout: string; stderr: string }) => void
) => {
const callback = typeof optsOrCb === 'function' ? (optsOrCb as typeof cb) : cb
callback?.(null, { stdout, stderr: '' })
}
)
}
describe('findFileByName()', () => {
beforeEach(() => vi.clearAllMocks())
it('should return null when the name has no significant word', async () => {
expect(await findFileByName(' ')).toBeNull()
expect(execFileMock).not.toHaveBeenCalled()
})
it('should return null when nothing is found', async () => {
mockStdout('')
expect(await findFileByName('fichier introuvable')).toBeNull()
})
it('should return the found path, trimmed', async () => {
mockStdout('C:\\Users\\test\\desktop\\rapport.docx\r\n')
expect(await findFileByName('rapport')).toBe('C:\\Users\\test\\desktop\\rapport.docx')
})
it('should pick the longest word as the primary search term', async () => {
mockStdout('C:\\found.txt')
await findFileByName("le rapport d'activite")
const script = execFileMock.mock.calls[0]?.[1]?.[2] as string
expect(script).toContain("'*activite*'")
})
it('should ignore French stopwords when building significant words', async () => {
mockStdout('')
await findFileByName('le')
expect(execFileMock).not.toHaveBeenCalled()
})
})
@@ -1,29 +1,4 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const execFileMock = vi.fn((_cmd: string, _args: string[], cb: (err: Error | null) => void) =>
cb(null)
)
vi.mock('child_process', () => ({ execFile: execFileMock }))
const { pressVirtualKey } = await import('../../src/main/skills/windows/lib/sendVirtualKey')
describe('pressVirtualKey()', () => {
beforeEach(() => vi.clearAllMocks())
it('should invoke the PowerShell script once by default', async () => {
await pressVirtualKey(0xaf)
expect(execFileMock).toHaveBeenCalledTimes(1)
const script = execFileMock.mock.calls[0]?.[1]?.[2] as string
expect(script).toContain('175')
expect(script).toContain('$i -lt 1')
})
it('should bake the requested repeat count into the script', async () => {
await pressVirtualKey(0xae, 5)
const script = execFileMock.mock.calls[0]?.[1]?.[2] as string
expect(script).toContain('$i -lt 5')
})
})
import { describe, it, expect, vi, afterEach } from 'vitest'
describe('systemPaths', () => {
const originalSystemRoot = process.env.SystemRoot
@@ -1,7 +1,6 @@
import { describe, it, expect, vi } from 'vitest'
const clickElementByText = vi.fn(async (text: string) => text !== 'introuvable')
const fillField = vi.fn(async (field: string) => field !== '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')
@@ -9,7 +8,6 @@ const readPageText = vi.fn(async () => 'Contenu de la page')
vi.mock('../../src/main/browser/browserWindow', () => ({
clickElementByText,
fillField,
goBack,
highlightText,
navigateTo,
@@ -17,7 +15,6 @@ vi.mock('../../src/main/browser/browserWindow', () => ({
}))
const { clickBrowserElement } = await import('../../src/main/skills/browser/clickBrowserElement')
const { fillBrowserField } = await import('../../src/main/skills/browser/fillBrowserField')
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')
@@ -39,28 +36,6 @@ describe('click_browser_element', () => {
})
})
describe('fill_browser_field', () => {
it('should refuse an empty field name', async () => {
await expect(fillBrowserField.execute({ field: '', value: 'x' })).rejects.toThrow(
/field manquant/
)
})
it('should report success and mention submission when requested', async () => {
const result = await fillBrowserField.execute({
field: 'email',
value: 'a@b.com',
submit: true
})
expect(result).toMatch(/rempli et formulaire valide/)
})
it('should report failure when no matching field is found', async () => {
const result = await fillBrowserField.execute({ field: 'introuvable', value: 'x' })
expect(result).toMatch(/Echec/)
})
})
describe('go_back_browser', () => {
it('should report success when going back worked', async () => {
const result = await goBackBrowser.execute({})
@@ -1,33 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
const execFileMock = vi.fn((_cmd: string, _args: string[], cb: (err: Error | null) => void) =>
cb(null)
)
vi.mock('child_process', () => ({ execFile: execFileMock }))
const { closeApp } = await import('../../src/main/skills/windows/closeApp')
describe('close_app', () => {
it('should refuse to close an unrecognized application', async () => {
const result = await closeApp.execute({ application: 'application-inexistante-xyz' })
expect(result).toMatch(/non reconnue/)
})
it('should refuse to close the Windows shell (explorer)', async () => {
const result = await closeApp.execute({ application: 'explorateur de fichiers' })
expect(result).toMatch(/pas autorise/)
})
it('should close a recognized application by killing its process', async () => {
const result = await closeApp.execute({ application: 'bloc-notes' })
expect(result).toMatch(/ferme/)
expect(execFileMock).toHaveBeenCalled()
})
it('should try each override candidate for an app with multiple possible process names', async () => {
execFileMock.mockClear()
const result = await closeApp.execute({ application: 'calculatrice' })
expect(result).toMatch(/ferme/)
expect(execFileMock.mock.calls[0]?.[1]).toContain('CalculatorApp.exe')
})
})
@@ -1,65 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-documents-test-'))
const openPath = vi.fn(async () => '')
vi.mock('electron', () => ({
app: { getPath: () => tempDir },
shell: { openPath }
}))
const { writeWordDocument } = await import('../../src/main/skills/windows/writeWordDocument')
const { createPowerpoint } = await import('../../src/main/skills/windows/createPowerpoint')
describe('create_document', () => {
it('should refuse empty content', async () => {
await expect(writeWordDocument.execute({ title: 'Rapport', content: '' })).rejects.toThrow(
/contenu manquant/
)
})
it('should write both a real .docx and .pdf file by default and open one of them', async () => {
openPath.mockClear()
const result = await writeWordDocument.execute({
title: 'Rapport de test',
content: 'Premiere ligne.\nDeuxieme ligne.'
})
expect(result).toMatch(/cree, enregistre et ouvert/)
expect(existsSync(join(tempDir, 'Rapport de test.docx'))).toBe(true)
expect(existsSync(join(tempDir, 'Rapport de test.pdf'))).toBe(true)
expect(openPath).toHaveBeenCalled()
})
it('should only write the requested format', async () => {
const result = await writeWordDocument.execute({
title: 'Uniquement PDF',
content: 'Contenu',
format: 'pdf'
})
expect(result).toMatch(/\.pdf/)
expect(existsSync(join(tempDir, 'Uniquement PDF.docx'))).toBe(false)
expect(existsSync(join(tempDir, 'Uniquement PDF.pdf'))).toBe(true)
})
})
describe('create_powerpoint', () => {
it('should refuse an empty slide list', async () => {
await expect(createPowerpoint.execute({ title: 'Presentation', slides: [] })).rejects.toThrow(
/diapositives manquantes/
)
})
it('should generate a real .pptx file from the given slides', async () => {
openPath.mockClear()
const result = await createPowerpoint.execute({
title: 'Ma presentation',
slides: [{ title: 'Introduction', content: 'Bienvenue' }, { title: 'Conclusion' }]
})
expect(result).toMatch(/creee, enregistree et ouverte/)
expect(existsSync(join(tempDir, 'Ma presentation.pptx'))).toBe(true)
expect(openPath).toHaveBeenCalled()
})
})
+1 -1
View File
@@ -44,7 +44,7 @@ const { loadSkills, findSkill } = await import('../../src/main/skills')
describe('loadSkills()', () => {
it('should load a non-empty list of skills without throwing', () => {
const skills = loadSkills()
expect(skills.length).toBeGreaterThan(20)
expect(skills.length).toBeGreaterThan(5)
})
it('should not register the same skill name twice', () => {
@@ -1,25 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
const pressVirtualKey = vi.fn(async () => {})
vi.mock('../../src/main/skills/windows/lib/sendVirtualKey', () => ({ pressVirtualKey }))
const { mediaControl } = await import('../../src/main/skills/windows/mediaControl')
describe('control_media_playback', () => {
it('should send the play/pause media key', async () => {
pressVirtualKey.mockClear()
const result = await mediaControl.execute({ action: 'lecture_pause' })
expect(result).toMatch(/lecture_pause/)
expect(pressVirtualKey).toHaveBeenCalledWith(0xb3, 1)
})
it('should send the next-track media key', async () => {
pressVirtualKey.mockClear()
await mediaControl.execute({ action: 'suivant' })
expect(pressVirtualKey).toHaveBeenCalledWith(0xb0, 1)
})
it('should throw on an invalid action', async () => {
await expect(mediaControl.execute({ action: 'inconnue' })).rejects.toThrow(/action invalide/)
})
})
@@ -1,29 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
const execMock = vi.fn((_cmd: string, cb: (err: Error | null) => void) => cb(null))
vi.mock('child_process', () => ({ exec: execMock }))
const { openApp } = await import('../../src/main/skills/windows/openApp')
describe('open_app', () => {
it('should report an unrecognized application without running any command', async () => {
execMock.mockClear()
const result = await openApp.execute({ application: 'application-inexistante-xyz' })
expect(result).toMatch(/non reconnue/)
expect(execMock).not.toHaveBeenCalled()
})
it('should open a recognized application by its registered executable', async () => {
execMock.mockClear()
const result = await openApp.execute({ application: 'bloc-notes' })
expect(result).toMatch(/ouvert/)
expect(execMock.mock.calls[0]?.[0]).toContain('notepad.exe')
})
it('should be case- and whitespace-insensitive when matching the application name', async () => {
execMock.mockClear()
const result = await openApp.execute({ application: ' CALCULATRICE ' })
expect(result).toMatch(/ouvert/)
expect(execMock.mock.calls[0]?.[0]).toContain('calc.exe')
})
})
@@ -1,31 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
const pressVirtualKey = vi.fn(async () => {})
vi.mock('../../src/main/skills/windows/lib/sendVirtualKey', () => ({ pressVirtualKey }))
const { systemVolume } = await import('../../src/main/skills/windows/systemVolume')
describe('control_volume', () => {
it('should mute with a single key press regardless of steps', async () => {
pressVirtualKey.mockClear()
const result = await systemVolume.execute({ action: 'couper', steps: 10 })
expect(result).toMatch(/coupe/)
expect(pressVirtualKey).toHaveBeenCalledWith(0xad, 1)
})
it('should increase volume using the default 5 steps when none is given', async () => {
pressVirtualKey.mockClear()
await systemVolume.execute({ action: 'augmenter' })
expect(pressVirtualKey).toHaveBeenCalledWith(0xaf, 5)
})
it('should decrease volume using the given number of steps, capped at 25', async () => {
pressVirtualKey.mockClear()
await systemVolume.execute({ action: 'baisser', steps: 999 })
expect(pressVirtualKey).toHaveBeenCalledWith(0xae, 25)
})
it('should throw on an invalid action', async () => {
await expect(systemVolume.execute({ action: 'danser' })).rejects.toThrow(/action invalide/)
})
})
@@ -1,30 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-screenshot-test-'))
const getSources = vi.fn(async () => [{ thumbnail: { toPNG: () => Buffer.from([1, 2, 3]) } }])
vi.mock('electron', () => ({
app: { getPath: () => tempDir },
desktopCapturer: { getSources },
screen: { getPrimaryDisplay: () => ({ size: { width: 1920, height: 1080 } }) }
}))
const { takeScreenshot } = await import('../../src/main/skills/windows/takeScreenshot')
describe('take_screenshot', () => {
it('should capture the primary screen and save it as a real PNG file', async () => {
const result = await takeScreenshot.execute({})
expect(result).toMatch(/Capture d'ecran enregistree/)
expect(result).toMatch(/\.png/)
const match = /: (.+\.png)\./.exec(result)
expect(match?.[1] ? existsSync(match[1]) : false).toBe(true)
})
it('should throw when no screen source is detected', async () => {
getSources.mockResolvedValueOnce([])
await expect(takeScreenshot.execute({})).rejects.toThrow(/Aucun ecran detecte/)
})
})
@@ -1,140 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const openPath = vi.fn(async () => '')
vi.mock('electron', () => ({
shell: { openPath },
app: { getPath: (name: string) => `C:\\Users\\test\\${name}` }
}))
const writeFileSyncMock = vi.fn()
const existsSyncMock = vi.fn(() => false)
const mkdirSyncMock = vi.fn()
const statSyncMock = vi.fn(() => ({ isDirectory: () => false }))
vi.mock('fs', () => ({
writeFileSync: writeFileSyncMock,
existsSync: existsSyncMock,
mkdirSync: mkdirSyncMock,
statSync: statSyncMock
}))
const execFileMock = vi.fn((_cmd: string, _args: string[], cb: (err: Error | null) => void) =>
cb(null)
)
vi.mock('child_process', () => ({ execFile: execFileMock }))
const findFileByName = vi.fn(async (name: string) =>
name.includes('introuvable') ? null : `C:\\Users\\test\\desktop\\${name}.txt`
)
vi.mock('../../src/main/skills/windows/lib/fileSearch', () => ({ findFileByName }))
const { createFile } = await import('../../src/main/skills/windows/createFile')
const { createFolder } = await import('../../src/main/skills/windows/createFolder')
const { deleteFileOrFolder } = await import('../../src/main/skills/windows/deleteFileOrFolder')
const { printFile } = await import('../../src/main/skills/windows/printFile')
const { searchFile } = await import('../../src/main/skills/windows/searchFile')
beforeEach(() => {
vi.clearAllMocks()
existsSyncMock.mockReturnValue(false)
statSyncMock.mockReturnValue({ isDirectory: () => false })
findFileByName.mockImplementation(async (name: string) =>
name.includes('introuvable') ? null : `C:\\Users\\test\\desktop\\${name}.txt`
)
})
describe('create_file', () => {
it('should refuse an empty name', async () => {
await expect(createFile.execute({ name: ' ' })).rejects.toThrow(/nom manquant/)
})
it('should sanitize illegal characters, write the file and open it', async () => {
const result = await createFile.execute({ name: 'note<test>', content: 'hello' })
expect(result).toMatch(/Fichier cree et ouvert/)
expect(writeFileSyncMock).toHaveBeenCalled()
expect(openPath).toHaveBeenCalled()
expect(String(writeFileSyncMock.mock.calls[0]?.[0])).not.toMatch(/[<>]/)
})
it('should append .txt when the name has no extension', async () => {
await createFile.execute({ name: 'sansextension' })
expect(String(writeFileSyncMock.mock.calls[0]?.[0])).toMatch(/sansextension\.txt$/)
})
})
describe('create_folder', () => {
it('should refuse an empty name', async () => {
await expect(createFolder.execute({ name: '' })).rejects.toThrow(/nom manquant/)
})
it('should report when the folder already exists without creating it again', async () => {
existsSyncMock.mockReturnValue(true)
const result = await createFolder.execute({ name: 'existant' })
expect(result).toMatch(/existe deja/)
expect(mkdirSyncMock).not.toHaveBeenCalled()
})
it('should create and open a new folder', async () => {
const result = await createFolder.execute({ name: 'nouveau' })
expect(result).toMatch(/Dossier cree et ouvert/)
expect(mkdirSyncMock).toHaveBeenCalled()
expect(openPath).toHaveBeenCalled()
})
})
describe('delete_file', () => {
it('should refuse an empty name', async () => {
await expect(deleteFileOrFolder.execute({ name: '' })).rejects.toThrow(/nom manquant/)
})
it('should report when nothing is found', async () => {
const result = await deleteFileOrFolder.execute({ name: 'introuvable' })
expect(result).toMatch(/Aucun fichier ou dossier/)
})
it('should refuse to delete a protected location (drive root)', async () => {
findFileByName.mockResolvedValue('C:\\')
const result = await deleteFileOrFolder.execute({ name: 'quelquechose' })
expect(result).toMatch(/protege/)
expect(execFileMock).not.toHaveBeenCalled()
})
it('should send a found file to the recycle bin', async () => {
const result = await deleteFileOrFolder.execute({ name: 'document' })
expect(result).toMatch(/corbeille/)
expect(execFileMock).toHaveBeenCalled()
})
})
describe('print_file', () => {
it('should refuse an empty name', async () => {
await expect(printFile.execute({ name: '' })).rejects.toThrow(/nom manquant/)
})
it('should report when no file is found', async () => {
const result = await printFile.execute({ name: 'introuvable' })
expect(result).toMatch(/Aucun fichier/)
})
it('should launch printing for a found file', async () => {
const result = await printFile.execute({ name: 'rapport' })
expect(result).toMatch(/Impression lancee/)
expect(execFileMock).toHaveBeenCalled()
})
})
describe('search_file', () => {
it('should refuse an empty name', async () => {
await expect(searchFile.execute({ name: '' })).rejects.toThrow(/nom manquant/)
})
it('should report when nothing is found', async () => {
const result = await searchFile.execute({ name: 'introuvable' })
expect(result).toMatch(/Aucun fichier ou dossier/)
})
it('should find and open a matching file', async () => {
const result = await searchFile.execute({ name: 'photo' })
expect(result).toMatch(/Trouve et ouvert/)
expect(openPath).toHaveBeenCalled()
})
})
@@ -1,129 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { EventEmitter } from 'node:events'
const readText = vi.fn(async () => '')
const writeText = vi.fn(async () => {})
const openExternal = vi.fn(async () => {})
const NotificationShow = vi.fn()
class NotificationMock {
show = NotificationShow
}
vi.mock('electron', () => ({
clipboard: { readText, writeText },
shell: { openExternal },
Notification: NotificationMock
}))
const writeFileSyncMock = vi.fn()
const mkdtempSyncMock = vi.fn(() => 'C:\\temp\\forge-avatar-xyz')
vi.mock('fs', () => ({ writeFileSync: writeFileSyncMock, mkdtempSync: mkdtempSyncMock }))
const execFileMock = vi.fn(() => new EventEmitter())
vi.mock('child_process', () => ({ execFile: execFileMock }))
const synthesizeSpeech = vi.fn(async () => new Uint8Array([1, 2, 3]).buffer as unknown as Buffer)
vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
const sendToRenderer = vi.fn()
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
const { clipboardSkill } = await import('../../src/main/skills/windows/clipboard')
const { showNotification } = await import('../../src/main/skills/windows/showNotification')
const { playMusic } = await import('../../src/main/skills/windows/playMusic')
const { reminder } = await import('../../src/main/skills/windows/reminder')
const { openNotepad } = await import('../../src/main/skills/windows/openNotepad')
beforeEach(() => {
vi.clearAllMocks()
})
describe('clipboard', () => {
it('should refuse an invalid action', async () => {
await expect(clipboardSkill.execute({ action: 'danser' })).rejects.toThrow(/action invalide/)
})
it('should report an empty clipboard', async () => {
readText.mockResolvedValue('')
const result = await clipboardSkill.execute({ action: 'lire' })
expect(result).toMatch(/vide/)
})
it('should read non-empty clipboard content', async () => {
readText.mockResolvedValue('Bonjour')
const result = await clipboardSkill.execute({ action: 'lire' })
expect(result).toMatch(/Bonjour/)
})
it('should refuse to copy an empty text', async () => {
await expect(clipboardSkill.execute({ action: 'copier', text: '' })).rejects.toThrow(
/texte manquant/
)
})
it('should copy a given text to the clipboard', async () => {
const result = await clipboardSkill.execute({ action: 'copier', text: 'Salut' })
expect(result).toMatch(/copie/)
expect(writeText).toHaveBeenCalledWith('Salut')
})
})
describe('show_notification', () => {
it('should refuse an empty message', async () => {
await expect(showNotification.execute({ message: '' })).rejects.toThrow(/message manquant/)
})
it('should show a notification with the given title and message', async () => {
const result = await showNotification.execute({ title: 'Alerte', message: 'Ca a marche' })
expect(result).toMatch(/affichee/)
expect(NotificationShow).toHaveBeenCalled()
})
})
describe('play_music', () => {
it('should refuse an empty query', async () => {
await expect(playMusic.execute({ query: '' })).rejects.toThrow(/requete manquante/)
})
it('should open Spotify with the encoded search query', async () => {
const result = await playMusic.execute({ query: 'Daft Punk' })
expect(result).toMatch(/Spotify ouvert/)
expect(openExternal).toHaveBeenCalledWith('spotify:search:Daft%20Punk')
})
it('should fall back to the web player when the Spotify URI fails', async () => {
openExternal.mockRejectedValueOnce(new Error('no spotify'))
const result = await playMusic.execute({ query: 'Daft Punk' })
expect(result).toMatch(/web ouvert/)
})
})
describe('set_reminder', () => {
it('should refuse an invalid delay', async () => {
await expect(reminder.execute({ minutes: 0, message: 'test' })).rejects.toThrow(
/minutes invalide/
)
})
it('should refuse an empty message', async () => {
await expect(reminder.execute({ minutes: 5, message: '' })).rejects.toThrow(/message manquant/)
})
it('should confirm the reminder is scheduled', async () => {
const result = await reminder.execute({ minutes: 10, message: 'Pause cafe' })
expect(result).toMatch(/Rappel programme dans 10 minute/)
expect(result).toMatch(/Pause cafe/)
})
})
describe('open_notepad', () => {
it('should open an empty notepad when no text is given', async () => {
const result = await openNotepad.execute({})
expect(result).toBe('Bloc-notes ouvert.')
expect(writeFileSyncMock).not.toHaveBeenCalled()
})
it('should pre-fill a temp file and open it when text is given', async () => {
const result = await openNotepad.execute({ text: 'Mon brouillon' })
expect(result).toMatch(/texte demande/)
expect(writeFileSyncMock).toHaveBeenCalledWith(expect.any(String), 'Mon brouillon', 'utf-8')
})
})
@@ -16,8 +16,6 @@ vi.mock('child_process', () => ({ execFile: execFileMock }))
const { systemStatus } = await import('../../src/main/skills/windows/systemStatus')
const { systemStorage } = await import('../../src/main/skills/windows/systemStorage')
const { checkInternet } = await import('../../src/main/skills/windows/checkInternet')
const { lockScreen } = await import('../../src/main/skills/windows/lockScreen')
const { emptyRecycleBin } = await import('../../src/main/skills/windows/emptyRecycleBin')
function mockStdout(json: unknown): void {
execFileMock.mockImplementation(
@@ -85,34 +83,3 @@ describe('check_internet_connection', () => {
expect(result).toMatch(/Pas de connexion internet/)
})
})
describe('lock_screen', () => {
it('should invoke the lock command and confirm immediately', async () => {
const result = await lockScreen.execute({})
expect(result).toBe('Ecran verrouille.')
})
})
describe('empty_recycle_bin', () => {
it('should confirm the recycle bin was emptied', async () => {
mockStdout({})
const result = await emptyRecycleBin.execute({})
expect(result).toBe('Corbeille videe.')
})
it('should still confirm even if the underlying command fails (bin already empty)', async () => {
execFileMock.mockImplementation(
(
_cmd: string,
_args: string[],
optsOrCb: unknown,
cb?: (err: Error | null, result: unknown) => void
) => {
const callback = typeof optsOrCb === 'function' ? (optsOrCb as typeof cb) : cb
callback?.(new Error('already empty'), null)
}
)
const result = await emptyRecycleBin.execute({})
expect(result).toBe('Corbeille videe.')
})
})
+4 -7
View File
@@ -29,13 +29,10 @@ export default defineConfig({
'**/*.d.ts',
// node:sqlite (built-in Node >= 22.5) ne peut pas etre transforme par Rolldown pour le
// calcul de couverture des fichiers non importes (environnement "client", qui ne bundle
// pas les built-ins Node) : echoue sur Linux (CI) bien que fonctionnel sous Windows. Les
// trois fichiers restent neanmoins testes reellement (tests/unit/coachStore.test.ts,
// tests/unit/skills.memory.test.ts, tests/unit/skills.visionWebMeetingDocuments.test.ts) ;
// seul leur pourcentage de couverture global n'est plus comptabilise.
'src/main/coach/coachStore.ts',
'src/main/memory/store.ts',
'src/main/meeting/meetingStore.ts'
// pas les built-ins Node) : echoue sur Linux (CI) bien que fonctionnel sous Windows. Le
// fichier reste neanmoins teste reellement (tests/unit/skills.memory.test.ts) ; seul son
// pourcentage de couverture global n'est plus comptabilise.
'src/main/memory/store.ts'
]
}
}