Integrazione 0.1.1: Febe per Windows si collega, VS Code, prove su Windows, storico e vista remota #4
No files matched your search
+2
-11
@@ -379,17 +379,6 @@ MigrationBackup/
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
|
||||
# VS Code files for those working on multiple tools
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Windows Installer files from build outputs
|
||||
*.cab
|
||||
*.msi
|
||||
@@ -401,12 +390,14 @@ FodyWeavers.xsd
|
||||
*.sln.iml
|
||||
|
||||
# ---> VisualStudioCode
|
||||
# Della cartella .vscode entra nel repository solo la configurazione condivisa (guida: Sviluppo, «Da VS Code»).
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["ms-dotnettools.csdevkit", "ms-dotnettools.csharp"]
|
||||
}
|
||||
Vendored
+182
@@ -0,0 +1,182 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Febe per Windows · sito di prova",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila e avvia il sito di prova",
|
||||
"postDebugTask": "ferma il sito di prova",
|
||||
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
|
||||
"args": [
|
||||
"--dati",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati",
|
||||
"--libreria",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria",
|
||||
"--sito-di-prova",
|
||||
"http://127.0.0.1:8481",
|
||||
"--accesso-di-prova",
|
||||
"--prima-sessione",
|
||||
"30",
|
||||
"--sviluppo"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"linux": { "preLaunchTask": "solo su Windows" },
|
||||
"osx": { "preLaunchTask": "solo su Windows" },
|
||||
"presentation": { "group": "1-windows", "order": 1 }
|
||||
},
|
||||
{
|
||||
"name": "Sito di prova + Febe per Windows",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll",
|
||||
"args": ["--porta", "8481", "--porta-cdn", "8482"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"serverReadyAction": {
|
||||
"action": "startDebugging",
|
||||
"pattern": "Sito di prova: http://",
|
||||
"name": "Febe per Windows · contro il sito già avviato",
|
||||
"killOnServerStop": true
|
||||
},
|
||||
"checkForDevCert": false,
|
||||
"logging": { "moduleLoad": false },
|
||||
"linux": { "preLaunchTask": "solo su Windows" },
|
||||
"osx": { "preLaunchTask": "solo su Windows" },
|
||||
"presentation": { "group": "1-windows", "order": 2 }
|
||||
},
|
||||
{
|
||||
"name": "Febe per Windows · contro il sito già avviato",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
|
||||
"args": [
|
||||
"--dati",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati",
|
||||
"--libreria",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria",
|
||||
"--sito-di-prova",
|
||||
"http://127.0.0.1:8481",
|
||||
"--accesso-di-prova",
|
||||
"--prima-sessione",
|
||||
"30",
|
||||
"--sviluppo"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "hidden": true }
|
||||
},
|
||||
{
|
||||
"name": "Febe Server · dimostrazione (--demo)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
|
||||
"args": ["--demo"],
|
||||
"env": { "FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot" },
|
||||
"windows": {
|
||||
"env": {
|
||||
"FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot",
|
||||
"TEMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei",
|
||||
"TMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei"
|
||||
}
|
||||
},
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"serverReadyAction": { "action": "openExternally", "pattern": "Apri (https?://\\S+)" },
|
||||
"checkForDevCert": false,
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "group": "2-strumenti", "order": 1 }
|
||||
},
|
||||
{
|
||||
"name": "Sito di prova",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll",
|
||||
"args": ["--porta", "8481", "--porta-cdn", "8482"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "group": "2-strumenti", "order": 2 }
|
||||
},
|
||||
{
|
||||
"name": "Simulazione 30 giorni (prudente)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
|
||||
"args": ["--simula", "30g", "--profilo", "prudente"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "group": "2-strumenti", "order": 3 }
|
||||
},
|
||||
{
|
||||
"name": "Febe Server · sito di prova (solo Linux)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila e avvia il sito di prova",
|
||||
"postDebugTask": "ferma il sito di prova",
|
||||
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
|
||||
"args": [
|
||||
"--dati",
|
||||
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/dati",
|
||||
"--libreria",
|
||||
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/libreria",
|
||||
"--importa",
|
||||
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/importa",
|
||||
"--ascolta",
|
||||
"127.0.0.1",
|
||||
"--sito-di-prova",
|
||||
"http://127.0.0.1:8481",
|
||||
"--accesso-di-prova",
|
||||
"--prima-sessione",
|
||||
"30"
|
||||
],
|
||||
"env": {
|
||||
"FEBE_PASSWORD": "prova",
|
||||
"FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot"
|
||||
},
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"terminateChildProcesses": true,
|
||||
"serverReadyAction": {
|
||||
"action": "openExternally",
|
||||
"pattern": "Interfaccia sulla porta (\\d+)",
|
||||
"uriFormat": "http://127.0.0.1:%s/"
|
||||
},
|
||||
"checkForDevCert": false,
|
||||
"logging": { "moduleLoad": false },
|
||||
"windows": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] },
|
||||
"osx": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] },
|
||||
"presentation": { "group": "3-linux", "order": 1 }
|
||||
},
|
||||
{
|
||||
"name": "⚠ Febe per Windows · Instagram vero (dati veri)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "${input:confermaInstagramVero}",
|
||||
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"linux": { "preLaunchTask": "solo su Windows" },
|
||||
"osx": { "preLaunchTask": "solo su Windows" },
|
||||
"presentation": { "group": "9-instagram-vero", "order": 1 }
|
||||
}
|
||||
],
|
||||
"inputs": [
|
||||
{
|
||||
"id": "confermaInstagramVero",
|
||||
"type": "pickString",
|
||||
"description": "INSTAGRAM VERO con l'account e i dati veri di Alberto. Invio avvia, Esc annulla.",
|
||||
"options": [{ "label": "Sì, avvia Febe con Instagram vero", "value": "compila" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"dotnet.defaultSolution": "Febe.slnx"
|
||||
}
|
||||
Vendored
+202
@@ -0,0 +1,202 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "compila",
|
||||
"detail": "dotnet build Febe.slnx -warnaserror: tutta la soluzione, gli avvisi sono errori; con -tl:off -clp:ForceNoAlign ogni errore sta su una riga e finisce nel pannello Problemi",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"build",
|
||||
"${workspaceFolder}/Febe.slnx",
|
||||
"-warnaserror",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": { "kind": "build", "isDefault": true },
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "prove",
|
||||
"detail": "dotnet test tests/Febe.Tests: tutte le prove (senza Chromium e Xvfb quelle con il browser vero risultano saltate)",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"test",
|
||||
"${workspaceFolder}/tests/Febe.Tests",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": { "kind": "test", "isDefault": true },
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "prove Windows",
|
||||
"detail": "dotnet test tests/Febe.Tests.Windows: le prove con WebView2 vero e un Dispatcher di WPF, solo su Windows (aprono per qualche istante la finestra «Browser di Febe»)",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"test",
|
||||
"${workspaceFolder}/tests/Febe.Tests.Windows",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": "test",
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "prove con filtro",
|
||||
"detail": "dotnet test tests/Febe.Tests --filter …: una prova o un gruppo, per nome",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"test",
|
||||
"${workspaceFolder}/tests/Febe.Tests",
|
||||
"--filter",
|
||||
"${input:filtroDelleProve}",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": "test",
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "sito di prova",
|
||||
"detail": "dotnet run --project tools/Febe.SitoDiProva: http://127.0.0.1:8481, CDN su 127.0.0.2:8482 (dove Febe lo cerca), dati sintetici del seme 13; in sfondo, pronto alla riga «Sito di prova: http://…»",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"run",
|
||||
"--project",
|
||||
"${workspaceFolder}/tools/Febe.SitoDiProva",
|
||||
"--",
|
||||
"--porta",
|
||||
"8481",
|
||||
"--porta-cdn",
|
||||
"8482"
|
||||
],
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"base": "$msCompile",
|
||||
"owner": "sito-di-prova",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": "(?!)",
|
||||
"endsPattern": "^Sito di prova: http://"
|
||||
}
|
||||
},
|
||||
"presentation": { "panel": "dedicated", "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "pubblica Febe.exe",
|
||||
"detail": "dotnet publish di Febe.Desktop in un file solo, come installer/costruisci.sh: out/pubblicazione/Febe.exe (Release, win-x64)",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/src/Febe.Desktop/Febe.Desktop.csproj",
|
||||
"-c",
|
||||
"Release",
|
||||
"-r",
|
||||
"win-x64",
|
||||
"--self-contained",
|
||||
"true",
|
||||
"-p:PublishSingleFile=true",
|
||||
"-p:IncludeNativeLibrariesForSelfExtract=true",
|
||||
"-p:EnableCompressionInSingleFile=true",
|
||||
"-nologo",
|
||||
"-o",
|
||||
"${workspaceFolder}/out/pubblicazione",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": "build",
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "immagine Docker (serve Docker Desktop)",
|
||||
"detail": "docker build -f docker/Dockerfile -t febe .: compilazione e prove dentro l'immagine; serve un demone Docker avviato",
|
||||
"type": "process",
|
||||
"command": "docker",
|
||||
"args": ["build", "-f", "docker/Dockerfile", "-t", "febe", "."],
|
||||
"group": "build",
|
||||
"problemMatcher": [],
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "compila e avvia il sito di prova",
|
||||
"detail": "Prima del debug contro il sito di prova: compila, poi avvia il sito (se è già aperto, lo usa così com'è)",
|
||||
"dependsOrder": "sequence",
|
||||
"dependsOn": ["compila", "sito di prova"],
|
||||
"hide": true,
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "ferma il sito di prova",
|
||||
"detail": "A fine debug: chiude l'attività «sito di prova» con l'input fermaIlSitoDiProva (comando workbench.action.tasks.terminate); echo stampa solo il suo argomento",
|
||||
"type": "process",
|
||||
"command": "echo",
|
||||
"args": ["${input:fermaIlSitoDiProva}"],
|
||||
"windows": { "command": "cmd.exe", "args": ["/d", "/c", "echo", "${input:fermaIlSitoDiProva}"] },
|
||||
"hide": true,
|
||||
"problemMatcher": [],
|
||||
"presentation": { "reveal": "never", "echo": false, "close": true }
|
||||
},
|
||||
{
|
||||
"label": "solo su Linux",
|
||||
"detail": "Ferma una configurazione che gira solo su Linux",
|
||||
"type": "process",
|
||||
"command": "sh",
|
||||
"args": [
|
||||
"-c",
|
||||
"echo 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb.' >&2; exit 1"
|
||||
],
|
||||
"windows": {
|
||||
"command": "powershell.exe",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"Write-Host 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb. Su Windows usa «Febe per Windows · sito di prova».'; exit 1"
|
||||
]
|
||||
},
|
||||
"hide": true,
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "solo su Windows",
|
||||
"detail": "Ferma una configurazione che gira solo su Windows",
|
||||
"type": "process",
|
||||
"command": "sh",
|
||||
"args": [
|
||||
"-c",
|
||||
"echo 'Questa configurazione gira solo su Windows: Febe per Windows è WPF e WebView2. Su Linux usa «Febe Server · sito di prova (solo Linux)».' >&2; exit 1"
|
||||
],
|
||||
"hide": true,
|
||||
"problemMatcher": []
|
||||
}
|
||||
],
|
||||
"inputs": [
|
||||
{
|
||||
"id": "filtroDelleProve",
|
||||
"type": "promptString",
|
||||
"description": "Filtro di dotnet test, per esempio FullyQualifiedName~Febe.Tests.Docs (oppure solo una parte del nome: IconTests)",
|
||||
"default": "FullyQualifiedName~Febe.Tests.Docs"
|
||||
},
|
||||
{
|
||||
"id": "fermaIlSitoDiProva",
|
||||
"type": "command",
|
||||
"command": "workbench.action.tasks.terminate",
|
||||
"args": "sito di prova"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,38 @@
|
||||
# Novità
|
||||
|
||||
## 0.1.1 (in preparazione)
|
||||
|
||||
Versione correttiva: **Febe per Windows si collega**. Con la 0.1.0 il browser di Febe non diventava mai pronto e
|
||||
l'accesso a Instagram non poteva cominciare.
|
||||
|
||||
Correzioni:
|
||||
|
||||
- **Febe per Windows**: il browser di Febe parte al primo tentativo. Prima WebView2 partiva, ma subito dopo veniva
|
||||
toccato fuori dal suo thread; l'errore era scambiato per un avvio fallito, e il browser veniva chiuso e riavviato
|
||||
per sempre.
|
||||
- Febe per Windows: un «Scollega» premuto durante un nuovo tentativo di avvio poteva lasciare due browser nella finestra
|
||||
e la sessione sul disco. «Esci» non resta più fermo dietro un avvio di WebView2.
|
||||
- Collegamento: prima del primo giro il pannello dice «Collegato» e «Nome non ancora noto», non più «Collegato come @».
|
||||
- Storico: la fine dello storico di un account dà una sola riga negli Avvisi, con il testo intero. Lo storico si chiude
|
||||
anche se subito dopo l'ultima pagina arrivano un segnale, un'interruzione o il controllo del profilo: prima l'account
|
||||
restava «Storico in corso» per sempre.
|
||||
- Vista remota (Docker): aprirne una mentre un'altra la sostituisce, o mentre la pagina sta cambiando, non dà più «Il
|
||||
browser di Febe non risponde».
|
||||
|
||||
Sviluppo e qualità:
|
||||
|
||||
- **CI a ogni push e a ogni unione** (`docs/processo.md`):
|
||||
- controlli e gitleaks;
|
||||
- tutte le prove con Chromium vero e dati sintetici, con un seme diverso a ogni esecuzione;
|
||||
- installatore per Windows;
|
||||
- immagine Docker provata senza rete e scansionata con Trivy.
|
||||
|
||||
Dopo ogni unione in `main` l'immagine esce come `:main` e `:sha-<commit>`. Ogni esecuzione toglie ciò che ha creato,
|
||||
e c'è una pulizia settimanale.
|
||||
- **Sviluppo da VS Code**: attività e configurazioni di debug in `.vscode/` (guida, «Sviluppo» ▸ «Da VS Code»).
|
||||
- Prove: `tests/Febe.Tests` verdi anche su Windows, e prove nuove con WebView2 vero in `tests/Febe.Tests.Windows`.
|
||||
- Sito di prova: `/benvenuto`, la pagina di accesso che Febe apre in sviluppo.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
Prima versione, **anteprima**: il programma è completo e provato contro il sito di prova locale, ma non ha mai
|
||||
|
||||
@@ -10,6 +10,7 @@ All'inizio di ogni sessione leggi docs/stato.md.
|
||||
- Avviare in modalità dimostrativa: `dotnet run --project src/Febe.Server -- --demo`
|
||||
- Simulare il motore: `dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente`
|
||||
- Immagine Docker: `docker build -f docker/Dockerfile -t febe .`
|
||||
- Da VS Code: attività e configurazioni di debug in `.vscode/` (guida: `docs/guida/Sviluppo.md`, «Da VS Code»); Febe per Windows di sviluppo tiene i dati in `%USERPROFILE%\FebeSviluppo\<cartella del checkout>`, mai in `%LOCALAPPDATA%\Febe`.
|
||||
|
||||
## Regole che non si discutono (specifica §2)
|
||||
1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto.
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/Febe.Tests/Febe.Tests.csproj" />
|
||||
<Project Path="tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tools/">
|
||||
<Project Path="tools/Febe.Sonda/Febe.Sonda.csproj" />
|
||||
|
||||
@@ -244,3 +244,35 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-20 | Processo in `docs/processo.md`: rami `<tipo>/<argomento>` da `main`, commit piccoli in italiano, una richiesta di unione per ramo con il modello di `.gitea/` (comprese le 14 regole di §2), unione con commit di unione e ramo cancellato; `main` protetto con i quattro lavori di `verifica` come controlli richiesti e «blocca se indietro»; tag `v*` protetti; Alberto proprietario di tutto (`CODEOWNERS`) | Decisione di Alberto del 20 ottobre (processo da grande azienda); con il ramo aggiornato il commit di unione ha lo stesso contenuto del commit verificato, quindi in `main` entra solo codice provato. Le approvazioni richieste dipendono da chi apre le richieste (Gitea non conta quella dell'autore): domanda aperta per Alberto |
|
||||
| 2026-10-20 | Nella verifica il lavoro «immagine» viene dopo «prove» e «installatore» (`needs: [prove, installatore]`) | `:main` e `:sha-` devono uscire solo da un commit con tutta la verifica verde, come dice `docs/docker.md`; sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia. Su un ramo, se l'installatore fallisce l'immagine si salta: la richiesta di unione è già bloccata dall'installatore |
|
||||
| 2026-10-20 | Anche nel rilascio il lavoro «immagine» viene dopo «prove» e «windows» (`needs: [prove, windows]`) | Come nella verifica: `:X.Y.Z` e `:latest` si pubblicano solo se anche la release potrà uscire; prima, con l'installatore rosso, l'immagine usciva senza release |
|
||||
| 2026-10-20 | Nuovo progetto di prove `tests/Febe.Tests.Windows` (`net10.0-windows`, WPF, solo MSTest e riferimenti ai progetti, nella soluzione): WebView2 vero su un thread STA con un `Dispatcher` di WPF vero, il sito di prova in processo; si compila anche da Linux (`EnableWindowsTargeting`), gira solo su Windows, senza runtime WebView2 è inconcludente | L'errore che bloccava Febe per Windows (14 e 19 ottobre) si vedeva solo con WebView2 vero e un thread dell'interfaccia vero: le prove su Linux con il finto `IWebView2DevTools` non potevano coglierlo |
|
||||
| 2026-10-20 | `WebView2Host` legge sul thread dell'interfaccia, durante l'avvio, i valori che servono altrove (versione di WebView2, numero del processo del browser) e li espone come valori semplici; nessun membro di un oggetto di WebView2 si legge fuori da quel thread | Causa dell'errore: `Version` leggeva `BrowserVersionString` dell'ambiente da un thread del pool, dopo `ConfigureAwait(false)`, e WebView2 lanciava `InvalidOperationException` |
|
||||
| 2026-10-20 | Nel ciclo di avvio di `WebView2Browser` si riprova solo l'eccezione dell'avvio stesso: stato e riga «Browser di Febe pronto» stanno fuori dal blocco dei tentativi | La riga del registro, dentro il `try`, trasformava ogni avvio riuscito in un avvio fallito: chiusura del WebView buono e nuovi tentativi per sempre |
|
||||
| 2026-10-20 | Avvio, ripartenza e arresto di `WebView2Host` uno alla volta (un `SemaphoreSlim` preso sul thread dell'interfaccia); l'arresto aspetta al più 30 s chi è in corso, poi chiude quello che c'è | Ognuno aspetta WebView2 sul thread dell'interfaccia e fra un'attesa e l'altra potevano intrecciarsi (per esempio una ripartenza dopo un arresto del processo e «Scollega»); l'uscita da Febe non deve restare appesa a un avvio che WebView2 non completa |
|
||||
| 2026-10-20 | Arresto del processo del browser: annunciato solo dopo che il gestore di `ProcessFailed` è tornato e solo per il WebView in uso (numero di generazione); se capita durante un avvio fa fallire quell'avvio; la ripartenza (e quella dopo un «Scollega» la cui ripartenza fallisce) usa gli stessi tentativi del primo avvio, un solo ciclo alla volta sul pool | Modello dei thread di WebView2: niente chiusure né ricreazioni dentro i suoi gestori. Prima: un solo tentativo, poi browser morto fino al riavvio di Febe; dopo «Scollega» restava fermo anche il motore, perché l'errore non era di cartella e `DisconnectAsync` non lo gestiva |
|
||||
| 2026-10-20 | `WebView2CdpSession.Attach` chiama i gestori di `Reconnected` uno per uno: l'errore di uno va nel registro e non esce da `Attach` (l'avviso resta sincrono) | `Attach` è dentro l'avvio del nuovo WebView: un'eccezione di chi ascolta avrebbe disfatto un avvio riuscito, ancora e ancora |
|
||||
| 2026-10-20 | La finestra dell'interfaccia apre gli indirizzi esterni nel browser predefinito dopo che il gestore di WebView2 è tornato (in coda sul dispatcher) | La shell di Windows può far girare un ciclo di messaggi suo e WebView2 non regge di essere richiamato dentro i propri gestori |
|
||||
| 2026-10-20 | Le prove per Windows hanno un `CompressedClock` e un fuso «mezzogiorno» propri, copie di quelli della suite per Linux; `Febe.Desktop` concede gli `internal` a `Febe.Tests.Windows` e `WebView2Host` espone la sua finestra come `internal` (da leggere sul thread dell'interfaccia) | Un progetto di prove non può dipendere dall'altro; la finestra serve alle prove del primo piano e del fuori vista |
|
||||
| 2026-10-20 | Un solo WebView alla volta in `WebView2Host`: l'avvio, dentro la sezione esclusiva, non fa nulla se un WebView è già collegato, chiude prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato (il ciclo dei tentativi non chiude più niente da fuori); la ripartenza dopo un arresto del processo usa lo stesso avvio; chiudere un WebView ne cambia la generazione, così i suoi eventi tardivi non contano | Revisione del ramo: un «Scollega» durante i tentativi del primo avvio faceva partire il browser, poi il tentativo in attesa ne apriva un secondo nella stessa finestra senza chiudere il primo. Il processo orfano teneva il profilo: il «Scollega» dopo aspettava 20 s e non cancellava la sessione di Instagram, l'uscita aspettava 15 s a vuoto |
|
||||
| 2026-10-20 | All'uscita il primo avvio e il ciclo di ripartenza di `WebView2Browser` smettono subito di aspettare WebView2: `WebView2Host.StartAsync` onora il suo token (un avvio non ancora cominciato non comincia, uno in corso finisce da sé e l'arresto chiude ciò che lascia, anche se arriva dopo i 30 s); `WebView2Browser.DisposeAsync` aspetta il ciclo al più 30 s. «Scollega», una volta cominciato, va fino in fondo e resta coperto dai 30 s dell'arresto | Revisione del ramo: il limite di 30 s copriva solo un «Scollega» in corso. `FebeApp` aspetta `RunAsync` prima di chiudere il browser, e `RunAsync` e il ciclo aspettavano WebView2 senza limite; interrompere «Scollega» a metà lascerebbe invece fermo il motore |
|
||||
| 2026-10-20 | Collegamento, pannello «collegato» senza nome dell'account (subito dopo «Ho finito», prima del primo giro): titolo «Collegato» e sotto «Nome non ancora noto», come il riquadro di stato | Provando a mano su Windows la pagina diceva «Collegato come @»; il mockup 10 mostra solo il caso con il nome |
|
||||
| 2026-10-20 | Prove portabili fra Linux e Windows: i percorsi attesi si calcolano come li calcola il sistema (`Path.GetFullPath` per il profilo del browser e per `/importa`, `LibraryLayout.ToStored` per il percorso mostrato in Docker) invece di essere scritti alla Linux | Febe per Windows gira su Windows e le prove devono passare dove gira il prodotto; su Linux il testo atteso è identico a prima, quindi lì non cambia nulla |
|
||||
| 2026-10-20 | Prova della cartella dei dati su una condivisione: su Linux il montaggio cifs iniettato come prima, su Windows un percorso UNC verso `febe-prova.invalid`, riconosciuto dalla sola forma; il controllo «niente scritto nella cartella dei dati» resta solo su Linux | Stesso comportamento sui due sistemi, ognuno con il suo modo di riconoscere la rete (su Windows non c'è tabella dei montaggi); guardare dentro un UNC vorrebbe dire interrogare la rete, e un nome `.invalid` (RFC 6761) non risponde mai |
|
||||
| 2026-10-20 | `TestLibrary.LoseDatabaseAsync`: su Windows un'eliminazione che trova il file in uso da un altro programma (`0x80070020`) si ripete ogni 50 ms, per al più 5 s | Su Windows un file aperto da un altro programma non si elimina. Su questo PC, con Defender attivo, succedeva circa 3 volte su 40 esecuzioni di `Febe.Tests.Library`: il file era libero dopo 6–17 ms e il Restart Manager non vedeva nessun processo che lo tenesse, quindi non è un collegamento di Febe rimasto aperto. Su Linux eliminare un file aperto riesce sempre e non si ripete nulla |
|
||||
| 2026-10-20 | Prova di `costruisci.sh`: su Windows prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), altrimenti un bash sul PATH che non sia il lanciatore di WSL (`System32\bash.exe`, alias in `WindowsApps`); senza bash la prova è inconcludente invece di passare in silenzio | Dal PATH di PowerShell il primo bash è il lanciatore di WSL, che senza distribuzione fallisce («execvpe(/bin/bash) failed») e non vede lo script col percorso di Windows; su Linux si usa come prima il primo bash sul PATH |
|
||||
| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre |
|
||||
| 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso |
|
||||
| 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano |
|
||||
| 2026-10-20 | Vista remota: `Page.startScreencast` si manda di nuovo solo se Chromium risponde -32000 «Not attached to an active page», con pause da 100 a 500 ms e per al più 5 s di orologio vero (`ScreencastSession.InactivePageBudget`); collegamento chiuso, nessuna risposta o qualunque altro rifiuto danno subito «Il browser di Febe non risponde». Nessun comando CDP nuovo | Issue #3. Dal `ReadyToCommitNavigation` di una navigazione con un nuovo RenderFrameHost fino al suo commit, DevTools punta già al documento nuovo non ancora attivo e i comandi di pagina gestiti dal browser falliscono così (`page_handler.cc`, `AssureTopLevelActiveFrame`); con RenderDocument, attivo in Chromium, vale per ogni navigazione, anche verso la pagina di riposo. Ci cadevano la vista aperta insieme alla pagina di accesso, dopo un riposo del motore o durante una sessione |
|
||||
| 2026-10-20 | Sostituzione di una vista remota: `BrowserRemoteViewHost.OpenAsync` tiene un permesso «Alberto usa il browser» di passaggio dalla fine della vista vecchia all'avvio della nuova; l'ospite della vista usa `IFebeBrowser` invece di `ChromiumBrowser` | Fra le due viste i permessi scendevano a zero: il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto cominciare una sessione. L'interfaccia permette di provarlo senza browser |
|
||||
| 2026-10-20 | Prova con Chromium vero del ritentativo della vista remota (`RemoteViewDuringNavigationTests`): una pagina del sito locale delle prove (`/occupata`) tiene occupato il renderer per 2 s, così la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit e `Page.startScreencast` ci cade apposta; se in nessun giro Chromium rifiuta il primo avvio, la prova risulta inconcludente e non superata | Revisione dell'issue #3: TwoViews… prova solo il permesso di passaggio, e una vista aperta dall'ospite dopo l'inizio di una navigazione non incontra il rifiuto (`Page.getFrameTree` risponde solo dopo il commit). Con Chrome 155 sulla macchina di sviluppo, in un esperimento a parte con lo stesso codice di Febe, il rifiuto è arrivato in 18 giri su 18 e la vista si è aperta al sesto tentativo; con il testo atteso cambiato la stessa sequenza fallisce. Verso about:blank da una pagina del sito il commit avviene in un altro renderer: quel caso non serve allo scopo |
|
||||
| 2026-10-20 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, che non legge `launchSettings.json` (lo cerca in `{cwd}/Properties`, e `cwd` è la radice del repository) | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo |
|
||||
| 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\<checkout>\dati` e `--libreria %USERPROFILE%\FebeSviluppo\<checkout>\libreria` (`${workspaceFolderBasename}`: una cartella per checkout); il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Una per checkout perché il blocco contro le istanze doppie dipende dalla cartella dei dati (F5 in un secondo worktree mostrava il Febe del primo e finiva subito) e un database migrato da un ramo più nuovo non si apre con una versione più vecchia. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) |
|
||||
| 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) |
|
||||
| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask`. Limite noto: se il sito non è più in corso, il comando apre l'elenco delle attività da terminare (la guida dice di premere Esc) |
|
||||
| 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse |
|
||||
| 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio |
|
||||
| 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri |
|
||||
| 2026-10-20 | Tutte le configurazioni di debug usano la Console di debug (`internalConsole`), mai il terminale integrato (Febe per Windows non ha una console: il suo registro resta nella cartella dei dati, `registro`); le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code |
|
||||
| 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\<checkout>\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` |
|
||||
| 2026-10-20 | I file di `.vscode/` sono JSON rigido, senza commenti: le spiegazioni stanno nella guida (pagina «Sviluppo», «Da VS Code»), nei campi `detail` delle attività e in queste righe | Il controllo «File JSON» della CI legge ogni `*.json` tracciato con `JSON.parse`, e con i commenti `//` il lavoro «controlli» falliva a ogni push dopo l'unione. VS Code legge anche il JSON rigido, così il ramo non dipende da come la CI tratta i commenti |
|
||||
| 2026-10-20 | `src/Febe.Desktop/Properties/launchSettings.json` con un solo profilo, «Sito di prova»: `--dati` e `--libreria` in `%USERPROFILE%\FebeSviluppo\comune`, `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo` | `dotnet run --project src/Febe.Desktop` e i comandi del C# Dev Kit (▷ «Debug project associated with this file», «Start New Instance», «C#: …») avviavano Febe senza opzioni: Instagram vero e dati veri, senza la conferma della configurazione ⚠. `dotnet run` e il Dev Kit leggono quel profilo ed espandono `%USERPROFILE%` (provato); se un altro strumento non lo facesse, Febe rifiuta il percorso non completo e non parte. Una cartella comune perché il file non conosce il checkout. Instagram vero dal terminale: `dotnet run --project src/Febe.Desktop --no-launch-profile` |
|
||||
@@ -46,6 +46,61 @@ dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Alerts"
|
||||
- La prova `Febe.Tests.Docs` controlla che questa guida dica tutto ciò che la specifica chiede (§15) e che ogni
|
||||
collegamento fra le pagine porti a una pagina che esiste.
|
||||
|
||||
## Da VS Code
|
||||
|
||||
La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev Kit e C#), soluzione predefinita
|
||||
`Febe.slnx`, attività e configurazioni di debug. Ogni configurazione compila prima con l'attività `compila`
|
||||
(`dotnet build Febe.slnx -warnaserror`); gli errori del compilatore finiscono nel pannello Problemi.
|
||||
|
||||
| Configurazione (Esegui e debug, F5) | Che cosa fa |
|
||||
|---|---|
|
||||
| Febe per Windows · sito di prova | Avvia il sito di prova come attività di sfondo (porte 8481 e 8482), poi Febe per Windows con `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo`; a fine debug ferma il sito |
|
||||
| Sito di prova + Febe per Windows | Il sito di prova nel debugger; quando è pronto parte anche Febe per Windows, che si ferma insieme al sito |
|
||||
| Febe Server · dimostrazione (--demo) | La dimostrazione su `http://127.0.0.1:8480`, che si apre da sola nel browser; l'interfaccia viene da `src/Febe.Web/wwwroot` (`FEBE_INTERFACCIA`): modifichi un file e ricarichi la pagina |
|
||||
| Sito di prova | Solo il sito di prova, nel debugger |
|
||||
| Simulazione 30 giorni (prudente) | `--simula 30g --profilo prudente`, con il resoconto nella Console di debug |
|
||||
| Febe Server · sito di prova (solo Linux) | Il server vero, con Chromium su Xvfb, contro il sito di prova: interfaccia su `127.0.0.1:8480`, password `prova` (come root serve anche `--senza-sandbox`, e `FEBE_CHROMIUM` se Chromium non è nel `PATH`). Su Windows e macOS si ferma con un messaggio; anche con «Esegui comunque il debug» stampa solo l'aiuto |
|
||||
| ⚠ Febe per Windows · Instagram vero (dati veri) | Febe senza opzioni: Instagram vero, `%LOCALAPPDATA%\Febe` e `Immagini\Febe`. Solo per le prove dal vivo di Alberto: chiede conferma, e una versione di sviluppo può aggiornare il database vero. Se Febe installato è aperto, prima esci da lui (menu dell'icona ▸ Esci): un solo Febe per cartella dei dati |
|
||||
|
||||
- **Dati di sviluppo.** Febe per Windows di sviluppo tiene dati e libreria in
|
||||
`%USERPROFILE%\FebeSviluppo\<checkout>\dati` e `%USERPROFILE%\FebeSviluppo\<checkout>\libreria`, dove `<checkout>` è
|
||||
il nome della cartella aperta in VS Code (per esempio `Febe`; il server su Linux in `~/FebeSviluppo/<checkout>`):
|
||||
fuori dal repository e mai nella cartella vera. Una cartella per checkout perché su una cartella dei dati gira un
|
||||
Febe solo (un secondo avvio mostra il primo ed esce) e un database scritto da un ramo più nuovo non si apre con una
|
||||
versione più vecchia. Con Febe chiuso si possono cancellare quando vuoi.
|
||||
- Chiudendo la finestra Febe resta nell'area di notifica e il debug continua: per finire, menu dell'icona ▸ Esci oppure
|
||||
Maiusc+F5. Finché Febe gira, `compila` non può sovrascrivere `Febe.exe`.
|
||||
- Il sito di prova usa sempre le porte 8481 e 8482, come attività e come configurazione: uno alla volta.
|
||||
- Se il sito di prova si ferma prima di Febe (terminale chiuso a mano, un guasto, oppure porta occupata e «Esegui
|
||||
comunque il debug»), a fine debug VS Code apre l'elenco delle attività da terminare, con «Termina tutte»: premi Esc.
|
||||
Con «Sito di prova + Febe per Windows» non succede, perché lì il sito sta nel debugger e non c'è un'attività da
|
||||
chiudere.
|
||||
- **Registro.** Nella Console di debug compaiono le righe del sito di prova, della dimostrazione, della simulazione e
|
||||
del server. Febe per Windows non ha una console: lì mostra solo i messaggi del debugger, e il suo registro sta nella
|
||||
cartella dei dati, `%USERPROFILE%\FebeSviluppo\<checkout>\dati\registro\febe-AAAA-MM-GG.log` (con il profilo di
|
||||
`launchSettings.json`, in `FebeSviluppo\comune\dati\registro`). Lì si leggono «Interfaccia sulla porta N», lo stato
|
||||
del browser di Febe e gli errori.
|
||||
- Le configurazioni usano la Console di debug e le attività partono senza shell: il terminale integrato carica il
|
||||
profilo di PowerShell, che può mettere davanti un altro .NET (per esempio quello di un ambiente conda), e allora
|
||||
`dotnet` non trova l'SDK 10 o Febe non parte («You must install or update .NET»). Se nel terminale
|
||||
`dotnet --list-sdks` non mostra il 10, usa le attività, Git Bash oppure `conda deactivate`.
|
||||
- Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea (`febe-dimostrazione-…`, una trentina
|
||||
di MB): da VS Code su Windows finisce in `%USERPROFILE%\FebeSviluppo\<checkout>\temporanei`, che si svuota quando
|
||||
vuoi. Con `dotnet run --project src/Febe.Server -- --demo` in un terminale, Ctrl+C la chiude in ordine e la cancella.
|
||||
- Fuori da queste configurazioni (`dotnet run --project src/Febe.Desktop`, il pulsante ▷ «Debug project associated
|
||||
with this file» e «Start New Instance» del C# Dev Kit, le sue configurazioni automatiche «C#: …») Febe per Windows
|
||||
prende l'unico profilo di `src/Febe.Desktop/Properties/launchSettings.json`: sito di prova su `http://127.0.0.1:8481`
|
||||
(da avviare a parte, per esempio con l'attività `sito di prova`) e dati in `%USERPROFILE%\FebeSviluppo\comune`, la
|
||||
stessa cartella per tutti i checkout. Instagram vero da un terminale solo con
|
||||
`dotnet run --project src/Febe.Desktop --no-launch-profile`: come la configurazione ⚠, è per le prove dal vivo di
|
||||
Alberto.
|
||||
- Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove Windows`
|
||||
(`dotnet test tests/Febe.Tests.Windows`, WebView2 vero: solo su Windows), `prove con filtro`
|
||||
(chiede il filtro, per esempio `FullyQualifiedName~Febe.Tests.Docs`), `sito di prova`, `pubblica Febe.exe` (un file
|
||||
solo in `out/pubblicazione/`, come `installer/costruisci.sh`) e `immagine Docker (serve Docker Desktop)`.
|
||||
- I file di `.vscode/` sono JSON senza commenti, così li legge anche un lettore rigido come quello dei controlli della
|
||||
CI: le spiegazioni stanno in questa sezione, nei campi `detail` delle attività e in `docs/decisioni.md`.
|
||||
|
||||
## Dimostrazione
|
||||
|
||||
```sh
|
||||
|
||||
+48
-6
@@ -1,10 +1,24 @@
|
||||
# Stato
|
||||
|
||||
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
||||
Aggiornato il 13 ottobre 2026, versione 0.1.0 (anteprima).
|
||||
Aggiornato il 20 ottobre 2026: versione 0.1.0 (anteprima), 0.1.1 in preparazione.
|
||||
|
||||
## In breve
|
||||
|
||||
**20 ottobre 2026.** Febe per Windows non riusciva a collegarsi: il browser di Febe non diventava mai pronto (registro di
|
||||
Alberto del 14 e del 19/10). Era un errore di thread, corretto. Febe per Windows ha girato per la prima volta su un
|
||||
Windows vero: collegamento, account e sessioni contro il sito di prova, dall'interfaccia. Lo stesso giorno sono arrivati:
|
||||
|
||||
- la CI da grande azienda (`docs/processo.md`), con prove con Chromium vero, installatore e immagine a ogni push,
|
||||
gitleaks, Trivy e pulizia;
|
||||
- lo sviluppo da VS Code;
|
||||
- le prove verdi anche su Windows;
|
||||
- altre tre correzioni trovate provando: lo storico completato doppio o bloccato, la vista remota durante un cambio di
|
||||
pagina, il pannello «Collegato come @».
|
||||
|
||||
Il lavoro è su sei rami, ciascuno con la sua revisione avversaria, unito in `main` con la PR #2 (CI) e la PR
|
||||
d'integrazione della 0.1.1.
|
||||
|
||||
Tutte le tappe M0–M8 sono state realizzate in una volta, su richiesta di Alberto del 13 ottobre 2026, sul ramo
|
||||
`febe-v1`. Il programma è completo e provato **contro il sito di prova locale** (§14.2) con un Chromium vero su Xvfb.
|
||||
**Non ha mai contattato Instagram** (regola 9): per questo le ricette, per costruzione, **si rifiutano di girare su
|
||||
@@ -21,14 +35,22 @@ Instagram** finché la sonda di M0 non ha prodotto i campioni da cui compilare `
|
||||
| M3 | Governatore, interruttore, fascia, sessioni, composizione, avvio graduale, cruscotto, simulazione | Prove del motore verdi; `--simula 30g` per i tre profili: **zero superamenti**, nessuna azione fuori fascia, nessuna pausa sotto il pavimento. **Arresto di M3**: Alberto legge i numeri (`docs/decisioni.md` e il resoconto della simulazione) |
|
||||
| M4 | API, eventi, ossatura, tutte le schermate, tema scuro, finestra stretta, modalità dimostrativa | Schermate confrontate con i mockup (`docs/schermate/`, differenze in `docs/schermate/differenze.md`); gli originali di 02, 04–07, 09, 11–14 non sono stati forniti: confronto sui ritagli della panoramica |
|
||||
| M5 | Composizione reale, vista remota, password, pagina di errore, `/salute`, Dockerfile, compose, modello Unraid | Prova d'insieme del server reale contro il sito di prova; immagine costruita dalla CI sul runner; **non provata su Unraid** |
|
||||
| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux; **mai eseguiti su Windows**: S1–S3 da provare (`docs/prove-dal-vivo.md`, parte C) |
|
||||
| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux. **20/10, su Windows 11 (WebView2 155)**: «Browser di Febe pronto» al primo tentativo; S1 e una sessione di raccolta nelle 11 prove di `tests/Febe.Tests.Windows`. Dall'interfaccia, contro il sito di prova: collegamento, due account, «Controlla ora», 47 file in libreria, sessioni con il browser fuori vista (S2, primo caso), sessione ritrovata dopo un riavvio (S3, primo caso). **Da provare**: S2 con la finestra ridotta a icona e con lo schermo bloccato, S3 con Instagram (parte C5), l'installatore su un Windows pulito (C2) |
|
||||
| M7 | Importazione in quattro passi, riconoscitori, doppioni, copia verificata | Prove di importazione verdi; riconoscitore 4K Stogram solo come ipotesi (domanda 4 di §16) |
|
||||
| M8 | Avvisi (interfaccia, notifiche di Windows, Telegram), esportazione CSV, guida | Un arresto simulato produce striscia, notifica e messaggio (prova automatica con canali finti); guida in `docs/guida/`, pubblicata nel wiki |
|
||||
|
||||
Revisione avversaria completata il 14 ottobre (54 rilievi confermati e corretti, vedi `docs/decisioni.md`).
|
||||
|
||||
Prove automatiche: `dotnet test tests/Febe.Tests` — 750 prove, tutte verdi (le prove con il browser vero si
|
||||
saltano da sole dove mancano Chromium e Xvfb, come sul runner della CI).
|
||||
Prove automatiche:
|
||||
|
||||
- `dotnet test tests/Febe.Tests`, nella CI dal 20/10 dentro un contenitore Debian con Chromium, Xvfb, ffmpeg e NSIS:
|
||||
tutte girano, **nessuna saltata** (prima, sul runner, se ne saltavano 66). Le prove del sito di prova girano una
|
||||
seconda volta con il seme `1000 + numero dell'esecuzione`.
|
||||
- Su Windows le prove con Chromium e Xvfb si saltano, e nessuna fallisce.
|
||||
- `dotnet test tests/Febe.Tests.Windows` (solo Windows): 11 prove con WebView2 vero.
|
||||
|
||||
CI: ogni push su ogni ramo passa da quattro controlli (controlli, prove, installatore, immagine). Il processo e la
|
||||
protezione di `main` sono in `docs/processo.md`.
|
||||
|
||||
## Da fare (di Alberto)
|
||||
|
||||
@@ -36,9 +58,29 @@ saltano da sole dove mancano Chromium e Xvfb, come sul runner della CI).
|
||||
campioni **ripuliti** e le righe di `interazioni.jsonl` dei comandi dell'interfaccia: con quelli si compilano
|
||||
`bersagli.instagram.json` e `lettori.instagram.json` e si portano le ipotesi H1–H11 a un esito.
|
||||
2. **Prima sessione dal vivo** dopo la sonda, con il profilo Prudente su un profilo pubblico (parte B).
|
||||
3. **Windows**: S1–S3 (parte C). **Docker su Unraid**: S3–S6 nel contenitore vero.
|
||||
3. **Windows**: C5 (accesso con l'account di prova, Esci e riapri, riavvio di Windows), S2 con la finestra ridotta a
|
||||
icona e con lo schermo bloccato, C2 (installatore su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
vero.
|
||||
4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`).
|
||||
5. Il segreto `REGISTRY_TOKEN` nel repository, perché il rilascio pubblichi l'immagine sul registro di Gitea.
|
||||
5. Il segreto `REGISTRY_TOKEN` nel repository: senza, la CI e il rilascio costruiscono, provano e scansionano
|
||||
l'immagine, ma non la pubblicano (lo dicono con un avviso). Il 20/10 mancava ancora.
|
||||
6. Sicurezza dell'istanza Gitea: la registrazione è aperta, senza CAPTCHA, con quattro account creati da programmi fra
|
||||
agosto e settembre. Il runner `fa94b0298b8d` è registrato per tutta l'istanza e i suoi lavori parlano con il Docker
|
||||
dell'host, quindi un utente registrato potrebbe farci girare un suo flusso. Si consiglia di chiudere la registrazione
|
||||
(`[service] DISABLE_REGISTRATION = true`) o di registrare il runner per il solo utente o repository.
|
||||
|
||||
## Rilievi aperti (20 ottobre)
|
||||
|
||||
- Il motore e le ricette scrivono due righe per lo stesso fatto anche per «formato-non-riconosciuto», e solo nella
|
||||
cronologia per «bersaglio-non-trovato» e «ricetta-fallita». La notifica è una sola. Visto leggendo il codice, da
|
||||
correggere in un cambio a parte, come «storico-completato».
|
||||
- Su Windows il controllo «cartella dei dati in rete» non segue un collegamento simbolico verso una condivisione. Visto
|
||||
leggendo il codice, non provato.
|
||||
- Trivy, nell'immagine del 20/10: una CRITICAL (`libxml2`, CVE-2026-6653) e 246 HIGH, nessuna con una correzione di
|
||||
Debian. La CI si fermerà da sola quando la correzione esisterà e non sarà ancora applicata.
|
||||
- La prima sessione dopo il collegamento: se il primo giro programmato trova Febe senza account, conta come sessione
|
||||
(vuota) e quella vera arriva dopo la pausa minima, circa 20 minuti. È il comportamento della specifica, ma chi ha
|
||||
appena collegato Febe aspetta.
|
||||
|
||||
## Rimandato, e perché
|
||||
|
||||
|
||||
+58
-5
@@ -8,10 +8,23 @@ un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; i
|
||||
> rischio per l'account (ritmo umano, tetti, fermo al primo segnale), ma non può azzerarlo. Le storie che Febe apre
|
||||
> risultano viste da te.
|
||||
|
||||
> **Stato.** Questa versione è stata costruita e provata su Linux: tutto ciò che non dipende da Windows ha le sue prove
|
||||
> automatiche, ma **nessuna parte che richiede Windows è ancora stata eseguita su un Windows vero** (finestre, WebView2,
|
||||
> area di notifica, registro, programma di installazione). Le prove da fare sono in fondo a questa pagina e in
|
||||
> `docs/prove-dal-vivo.md`, parte C.
|
||||
> **Stato (20 ottobre 2026).** Con la 0.1.0 il browser di Febe per Windows non diventava mai disponibile, e l'accesso a
|
||||
> Instagram non poteva nemmeno cominciare: WebView2 partiva, ma subito dopo Febe ne leggeva la versione da un thread
|
||||
> diverso da quello dell'interfaccia, WebView2 lo rifiutava e Febe, credendo fallito l'avvio, chiudeva il browser e
|
||||
> riprovava per sempre (nel registro, a ogni tentativo: «WebView2 non parte (InvalidOperationException:
|
||||
> CoreWebView2Environment members can only be accessed from the UI thread.)»). **È corretto**: su un Windows vero
|
||||
> (Windows 11 Pro, runtime WebView2 155.0.4283.62) il browser di Febe parte al primo tentativo, in un paio di secondi.
|
||||
>
|
||||
> Ora ci sono anche **prove automatiche che girano su Windows**, con WebView2 vero e il sito di prova (mai Instagram):
|
||||
> S1 con la finestra fuori vista (navigazione, corpi delle risposte, lettura della pagina, scorrimento con la rotella,
|
||||
> fotogrammi, scaricamenti dal CDN, comandi vietati rifiutati), la finestra che viene in primo piano e torna fuori vista
|
||||
> con il motore fermo nel frattempo, «Scollega», la ripartenza da sola dopo l'arresto del processo del browser, la
|
||||
> «composizione» di S2 e una sessione di raccolta intera, con i file che arrivano nella libreria. Vedi «Prove
|
||||
> automatiche su Windows», più sotto.
|
||||
>
|
||||
> **Restano da provare a mano** (parte C di `docs/prove-dal-vivo.md`): l'installazione su un Windows pulito, S2 con la
|
||||
> finestra di Febe ridotta a icona e con lo schermo bloccato, S3 (il collegamento che sopravvive a «Esci» e al riavvio di
|
||||
> Windows), area di notifica, notifiche, avvio con il computer, e l'accesso vero a Instagram.
|
||||
|
||||
## Che cosa serve
|
||||
|
||||
@@ -173,9 +186,18 @@ della specifica (§6.6); si sceglie con `--browser` e la scelta resta:
|
||||
che lo chiude insieme a Febe.exe, anche se Febe si chiude all'improvviso o da Gestione attività: un Edge rimasto
|
||||
aperto terrebbe la porta 9222 e il browser di Febe non ripartirebbe più.
|
||||
|
||||
Come tutti gli oggetti di WebView2, ambiente, controllo, pagina e ricevitori degli eventi DevTools vivono sul thread
|
||||
dell'interfaccia: Febe li tocca solo da lì (i comandi del motore arrivano da altri thread e ci passano attraverso il
|
||||
dispatcher di WPF), e il resto del programma legge solo valori semplici presi durante l'avvio, come la versione per il
|
||||
registro. Se il processo del browser si chiude da solo, Febe lo fa ripartire con lo stesso profilo e con gli stessi
|
||||
tentativi del primo avvio (5, 15, 30, 60 secondi, poi ogni 5 minuti), e lo stesso se dopo «Scollega» non ripartisse.
|
||||
Nella finestra c'è sempre un solo browser: se «Scollega» lo fa ripartire mentre il primo avvio aspetta il prossimo
|
||||
tentativo, quel tentativo lo trova già in funzione e non ne apre un secondo.
|
||||
|
||||
Le prove da fare su un Windows vero, con la procedura esatta, sono in `docs/prove-dal-vivo.md`, **parte C**. In breve:
|
||||
|
||||
- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di Attività.
|
||||
- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di
|
||||
Attività. La parte che non dipende dall'installazione è già una prova automatica su Windows (sotto).
|
||||
- **S2** — la stessa sessione con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato;
|
||||
poi, se serve, `composizione` e `edge`.
|
||||
- **S3** — accesso a mano, «Esci», riapertura, riavvio di Windows: il collegamento deve restare.
|
||||
@@ -207,11 +229,42 @@ L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è dis
|
||||
SkiaSharp e scritta a mano: per rigenerarla dopo un cambio del marchio,
|
||||
`FEBE_RIGENERA_ICONA=1 dotnet test tests/Febe.Tests --filter IconTests`.
|
||||
|
||||
## Prove automatiche su Windows
|
||||
|
||||
`tests/Febe.Tests.Windows` contiene le prove che hanno bisogno di Windows e di WebView2 vero. Si compila anche da Linux
|
||||
(la CI compila tutta la soluzione), ma gira solo su Windows, con il .NET SDK 10 e il runtime WebView2; dove il runtime
|
||||
manca le prove risultano inconcludenti, non rosse:
|
||||
|
||||
```sh
|
||||
dotnet test tests/Febe.Tests.Windows
|
||||
dotnet test tests/Febe.Tests.Windows --filter "FullyQualifiedName~WebView2CdpTests" # una classe sola
|
||||
```
|
||||
|
||||
Ogni prova crea un thread dell'interfaccia di WPF vero (come quello di `Febe.exe`), il proprio sito di prova su porte
|
||||
libere di 127.0.0.1 (il suo «CDN» su 127.0.0.2) e cartelle temporanee in `%TEMP%`: niente tocca la cartella dei dati né
|
||||
la libreria vere. La finestra «Browser di Febe» resta fuori dallo schermo, tranne in due prove che la portano in primo
|
||||
piano per un attimo: una prova il primo piano da solo, l'altra il percorso intero di «Accedi a Instagram» e «Ho finito».
|
||||
Una prova chiude, con il suo numero di processo, il processo del browser che lei stessa ha avviato, per vedere Febe
|
||||
farlo ripartire. Tutte insieme durano due o tre minuti, quasi tutti della sessione di raccolta.
|
||||
|
||||
| Classe | Che cosa prova |
|
||||
|---|---|
|
||||
| `WebView2BrowserStartTests` | Avviato da un thread del pool, come fa la composizione, il browser è pronto al primo tentativo e il registro dice «Browser di Febe pronto: WebView2 …» (l'errore del 14 ottobre) |
|
||||
| `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; «Scollega» mentre il primo avvio aspetta di riprovare (un solo browser nella finestra, il «Scollega» dopo riesce subito); «Esci» mentre l'avvio non si completa (non lo aspetta); ripartenza dopo l'arresto del processo; «composizione» di S2 |
|
||||
| `WebView2CdpTests` | S1: i comandi dell'elenco su WebView2 contro il sito di prova, con la finestra fuori vista, e i comandi vietati rifiutati |
|
||||
| `WebView2CollectionTests` | Una sessione vera della composizione (`FebeApp` con `DesktopPlatform`) su WebView2: i file arrivano nella libreria |
|
||||
| `WebView2ConnectionTests` | Il collegamento dal servizio vero della composizione: «Accedi a Instagram» porta in primo piano la finestra con la pagina di accesso (del sito di prova), «Ho finito» trova la sessione e la rimette fuori vista, «Scollega» cancella il profilo e il motore riparte |
|
||||
|
||||
Quello che di `WebView2CdpSession` non chiede Windows (per esempio: un errore di chi ascolta la ripartenza non disfa
|
||||
l'avvio) si prova invece in `tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs`, con un finto WebView2: gira anche
|
||||
sulla CI per Linux.
|
||||
|
||||
## Problemi comuni
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| All'avvio: «Manca il runtime WebView2 di Microsoft» | Installa il runtime dalla pagina ufficiale (il messaggio offre di aprirla), poi riapri Febe |
|
||||
| Nel registro, a ogni tentativo: «WebView2 non parte (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)»; «Accedi a Instagram» risponde che il browser di Febe non è in funzione | È l'errore della 0.1.0: il browser di Febe non diventava mai disponibile. Installa una versione successiva alla 0.1.0 |
|
||||
| «La cartella dei dati è su un disco di rete» o «non può scrivere» | Riapri Febe con una cartella dei dati su un disco locale (`--dati`), oppure libera la cartella |
|
||||
| Aprendo Febe si porta solo in primo piano la finestra già aperta | È voluto: un solo Febe per cartella dei dati. Per fermarlo: menu dell'icona ▸ Esci |
|
||||
| Il collegamento risulta perso dopo un riavvio | È l'ipotesi S3: riferiscilo (parte C di `docs/prove-dal-vivo.md`) con l'ora e il registro di quel giorno |
|
||||
|
||||
@@ -92,11 +92,31 @@ public sealed class CdpCommandNotAllowedException(string method, string message)
|
||||
public sealed class CdpCommandException(string method, int code, string browserMessage)
|
||||
: Exception($"Il comando CDP «{method}» è fallito: {browserMessage} (codice {code}).")
|
||||
{
|
||||
/// <summary>Chromium's generic «server error» code.</summary>
|
||||
public const int ServerErrorCode = -32000;
|
||||
|
||||
/// <summary>
|
||||
/// What Chromium answers to a browser-side page command (<c>Page.startScreencast</c>, <c>Page.captureScreenshot</c>)
|
||||
/// while the page's current document is not «active»: from <c>ReadyToCommitNavigation</c> of a navigation that uses
|
||||
/// a new RenderFrameHost until that navigation commits, DevTools already points at the new, still uncommitted frame
|
||||
/// (content/browser/devtools/protocol/page_handler.cc, <c>AssureTopLevelActiveFrame</c>;
|
||||
/// render_frame_devtools_agent_host.cc, <c>ReadyToCommitNavigation</c>). A new RenderFrameHost comes with a process
|
||||
/// swap, a cross-site or back-forward-cache swap and, with RenderDocument (on by default in current Chromium), with
|
||||
/// every navigation of the page to a new document — the rest page included.
|
||||
/// </summary>
|
||||
public const string InactivePageMessage = "Not attached to an active page";
|
||||
|
||||
public string Method { get; } = method;
|
||||
|
||||
public int Code { get; } = code;
|
||||
|
||||
public string BrowserMessage { get; } = browserMessage;
|
||||
|
||||
/// <summary>
|
||||
/// The page is between two documents (see <see cref="InactivePageMessage"/>): the same command a moment later finds
|
||||
/// the new document committed. A browser that is gone answers differently (closed connection, no answer).
|
||||
/// </summary>
|
||||
public bool IsInactivePage => Code == ServerErrorCode && string.Equals(BrowserMessage, InactivePageMessage, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>The connection to the browser is closed (browser exited, crashed or is restarting).</summary>
|
||||
|
||||
@@ -64,12 +64,16 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
private IDisposable? _lease;
|
||||
private int _buttons;
|
||||
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null)
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
|
||||
/// <param name="log">Where opening and closing are noted (never keys).</param>
|
||||
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
||||
_gate = gate ?? throw new ArgumentNullException(nameof(gate));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
Screencast = new ScreencastSession(cdp, _log);
|
||||
Screencast = new ScreencastSession(cdp, _log, clock);
|
||||
}
|
||||
|
||||
public ScreencastSession Screencast { get; }
|
||||
|
||||
@@ -39,10 +39,22 @@ public sealed record ScreencastFrame(
|
||||
/// <c>Page.screencastFrameAck</c>, stopped with <c>Page.stopScreencast</c>. Frames are delivered through
|
||||
/// <see cref="ReadFramesAsync"/> (only the latest ones are kept when the reader is slow) and <see cref="FrameReceived"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A view opened while the page changes document (the rest page after a session, the login page opened together with
|
||||
/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start
|
||||
/// is sent again, a few times, for at most <see cref="InactivePageBudget"/>. Any other failure is reported at once.
|
||||
/// </remarks>
|
||||
public sealed class ScreencastSession : IAsyncDisposable
|
||||
{
|
||||
/// <summary>How long a start refused because the page is between two documents is tried again.</summary>
|
||||
public static readonly TimeSpan InactivePageBudget = TimeSpan.FromSeconds(5);
|
||||
|
||||
private static readonly TimeSpan FirstPause = TimeSpan.FromMilliseconds(100);
|
||||
private static readonly TimeSpan LongestPause = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
private readonly ICdpSession _cdp;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly IClock _clock;
|
||||
private readonly Channel<ScreencastFrame> _frames = Channel.CreateBounded<ScreencastFrame>(
|
||||
new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
|
||||
|
||||
@@ -54,10 +66,14 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
private int _stopped;
|
||||
private long _framesReceived;
|
||||
|
||||
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null)
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="log">Where the start and stop are noted (never parameters or frames).</param>
|
||||
/// <param name="clock">Wall-clock time for the pauses between start attempts; null: the system clock.</param>
|
||||
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
_clock = clock ?? new SystemClock();
|
||||
}
|
||||
|
||||
/// <summary>Raised on the browser event thread for every frame: handlers must be quick.</summary>
|
||||
@@ -144,20 +160,47 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
|
||||
private Task SendStartAsync(CancellationToken ct)
|
||||
private async Task SendStartAsync(CancellationToken ct)
|
||||
{
|
||||
var o = _options ?? new ScreencastOptions();
|
||||
return _cdp.SendAsync(
|
||||
"Page.startScreencast",
|
||||
new JsonObject
|
||||
var deadline = _clock.Now + InactivePageBudget;
|
||||
var pause = FirstPause;
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
["format"] = "jpeg",
|
||||
["quality"] = Math.Clamp(o.Quality, 0, 100),
|
||||
["maxWidth"] = o.MaxWidth,
|
||||
["maxHeight"] = o.MaxHeight,
|
||||
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
|
||||
},
|
||||
ct);
|
||||
await _cdp.SendAsync(
|
||||
"Page.startScreencast",
|
||||
new JsonObject
|
||||
{
|
||||
["format"] = "jpeg",
|
||||
["quality"] = Math.Clamp(o.Quality, 0, 100),
|
||||
["maxWidth"] = o.MaxWidth,
|
||||
["maxHeight"] = o.MaxHeight,
|
||||
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
if (attempt > 1)
|
||||
{
|
||||
_log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
catch (CdpCommandException ex) when (ex.IsInactivePage && _clock.Now + pause <= deadline)
|
||||
{
|
||||
// A navigation is committing in a new frame of the page: nothing is started on the browser side, the
|
||||
// same start a moment later finds the new document. Past the budget the error goes up as it is.
|
||||
}
|
||||
|
||||
await _clock.Delay(pause, ct).ConfigureAwait(false);
|
||||
if (Volatile.Read(ref _stopped) == 1)
|
||||
{
|
||||
return; // stopped meanwhile (a restart's start in the background): nothing left to start
|
||||
}
|
||||
|
||||
pause = pause * 2 < LongestPause ? pause * 2 : LongestPause;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReconnected(object? sender, EventArgs e) =>
|
||||
|
||||
@@ -113,7 +113,7 @@ public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsy
|
||||
_log.Write(BrowserLogLevel.Debug, "CDP: WebView2 collegato.");
|
||||
if (reconnect)
|
||||
{
|
||||
Reconnected?.Invoke(this, EventArgs.Empty);
|
||||
RaiseReconnected();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,6 +275,31 @@ public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsy
|
||||
return JsonElement.ParseValue(ref reader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Reconnected"/>, on the thread of <see cref="Attach"/> (WebView2's UI thread), one handler at a time: an
|
||||
/// error of a handler is logged and never reaches <see cref="Attach"/>, so it cannot undo the start of the new
|
||||
/// WebView that called it. Handlers only queue their work (re-enabling a domain is a command, never sent from here).
|
||||
/// </summary>
|
||||
private void RaiseReconnected()
|
||||
{
|
||||
if (Reconnected is not { } handlers)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var handler in handlers.GetInvocationList().Cast<EventHandler>())
|
||||
{
|
||||
try
|
||||
{
|
||||
handler(this, EventArgs.Empty);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Write(BrowserLogLevel.Warning, "CDP: errore in chi ascolta il nuovo collegamento con WebView2.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IDisposable SubscribeNative(IWebView2DevTools devTools, string eventName) =>
|
||||
devTools.Subscribe(eventName, json => _events.Writer.TryWrite(new QueuedEvent(eventName, json ?? string.Empty, null)));
|
||||
|
||||
|
||||
@@ -184,7 +184,11 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
else if (page?.HasMore == false)
|
||||
{
|
||||
// The whole profile is on the first page, saved just now. For an account «Storico in corso» its history
|
||||
// is complete: the engine closes it, with its line (RecipeOutcome.BackfillFinished). An account that
|
||||
// keeps only the new posts had no history to announce.
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
|
||||
run.Finished = account.State == AccountState.Backfilling;
|
||||
}
|
||||
}
|
||||
else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null))
|
||||
@@ -394,9 +398,10 @@ public sealed partial class RecipeRunner
|
||||
run.Finished = true;
|
||||
if (walk.IsGrid)
|
||||
{
|
||||
// «Storico completato» in Attività, and the new state of the account, are the engine's: one line per
|
||||
// history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished).
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
|
||||
await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false);
|
||||
await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -89,7 +89,10 @@ public sealed record RecipeOutcome(
|
||||
/// <summary>Accounts where the sweep saw new posts (FollowingSweep).</summary>
|
||||
public IReadOnlyList<long> AccountsWithNewPosts { get; init; } = [];
|
||||
|
||||
/// <summary>For Backfill: true when the beginning of the profile has been reached.</summary>
|
||||
/// <summary>
|
||||
/// Backfill: true when the beginning of the profile has been reached. ProfileCheck: true when the check found the
|
||||
/// whole profile of an account «Storico in corso» on its first page (its history is complete as well).
|
||||
/// </summary>
|
||||
public bool BackfillFinished { get; init; }
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ internal sealed class SessionComposer
|
||||
public async Task<SessionSummary> RunAsync(SessionContext context, EngineTask? outsideWindowTask, CancellationToken ct)
|
||||
{
|
||||
var state = new SessionState(context);
|
||||
await CloseCompletedHistoriesAsync(state, ct).ConfigureAwait(false);
|
||||
var accounts = await SyncQueueAsync(ct).ConfigureAwait(false);
|
||||
|
||||
if (outsideWindowTask is not null)
|
||||
@@ -145,12 +146,41 @@ internal sealed class SessionComposer
|
||||
// 5. A few pages of history on one account.
|
||||
if (!light && !Over(state, ct))
|
||||
{
|
||||
await RunBackfillAsync(accounts, state, ct).ConfigureAwait(false);
|
||||
await RunBackfillAsync(state, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return state.Summary();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accounts still «Storico in corso» whose history is complete: a run closed it but its outcome was never recorded
|
||||
/// (Febe stopped in between), or an earlier version left them so. Closed before the session plans anything, with
|
||||
/// their line (<see cref="FinishBackfillAsync"/>); nothing towards the site.
|
||||
/// </summary>
|
||||
private async Task CloseCompletedHistoriesAsync(SessionState state, CancellationToken ct)
|
||||
{
|
||||
var complete = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
|
||||
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is not null)
|
||||
.ToList();
|
||||
if (complete.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
foreach (var account in complete)
|
||||
{
|
||||
await FinishBackfillAsync(account, state, Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
|
||||
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
|
||||
@@ -568,14 +598,16 @@ internal sealed class SessionComposer
|
||||
/// History advances on one account per session, alternating among the accounts «Storico in corso», each up to its
|
||||
/// daily maximum; suspended while the account has too many files waiting or the data budget is reached (§6.3).
|
||||
/// </summary>
|
||||
private async Task RunBackfillAsync(Dictionary<long, Account> accounts, SessionState state, CancellationToken ct)
|
||||
private async Task RunBackfillAsync(SessionState state, CancellationToken ct)
|
||||
{
|
||||
if (_health.IsSuspended(RecipeKind.Backfill) || state.Exhausted.Contains(ActionKind.BackfillPage))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var candidates = accounts.Values
|
||||
// Read again, not taken from the start of the session: a profile check of this session may have completed a
|
||||
// history already (its line is written), and that account is not walked again.
|
||||
var candidates = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
|
||||
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a))
|
||||
.ToList();
|
||||
if (candidates.Count == 0)
|
||||
@@ -771,6 +803,15 @@ internal sealed class SessionComposer
|
||||
var now = Clock.Now;
|
||||
var kind = request.Kind;
|
||||
var writes = new List<Task>();
|
||||
|
||||
// The history reached the beginning of the profile: the walk of the Storico, however the run ended (a signal or
|
||||
// a cancellation can come right after the last page was stored, and that account would not be walked again),
|
||||
// or a profile check that found the whole profile on its first page. What follows sees the account as it is now.
|
||||
if (kind is RecipeKind.Backfill or RecipeKind.ProfileCheck && outcome.BackfillFinished && account is not null)
|
||||
{
|
||||
account = await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
switch (outcome.Status)
|
||||
{
|
||||
case RecipeStatus.Completed:
|
||||
@@ -798,7 +839,12 @@ internal sealed class SessionComposer
|
||||
|
||||
case RecipeStatus.StoppedBySignal:
|
||||
case RecipeStatus.Cancelled:
|
||||
if (task is not null)
|
||||
if (task is not null && kind == RecipeKind.Backfill && outcome.BackfillFinished)
|
||||
{
|
||||
// The walk got to the end before the run stopped: nothing to take up again (closed above).
|
||||
writes.Add(Store.Tasks.CompleteAsync(task.Id, now, ct));
|
||||
}
|
||||
else if (task is not null)
|
||||
{
|
||||
await RequeueAsync(task, outcome.Status == RecipeStatus.Cancelled ? "Interrotta" : "Fermata da un segnale", now).ConfigureAwait(false);
|
||||
}
|
||||
@@ -947,27 +993,8 @@ internal sealed class SessionComposer
|
||||
break;
|
||||
}
|
||||
|
||||
case RecipeKind.Backfill when outcome.BackfillFinished:
|
||||
{
|
||||
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
|
||||
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
|
||||
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
|
||||
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
|
||||
var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
|
||||
var tail = fresh.KeepUpdated
|
||||
? " Da ora lo tengo aggiornato."
|
||||
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Success,
|
||||
EngineEventCodes.BackfillCompleted,
|
||||
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
|
||||
account.Id,
|
||||
state.Context.SessionId,
|
||||
ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
|
||||
case RecipeKind.Backfill:
|
||||
// A history completed: FinishBackfillAsync, from ApplyOutcomeAsync.
|
||||
case RecipeKind.Backfill when !outcome.BackfillFinished:
|
||||
if (contactable)
|
||||
{
|
||||
// Behind the other accounts «Storico in corso»: they alternate.
|
||||
@@ -980,6 +1007,43 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one
|
||||
/// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their
|
||||
/// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account
|
||||
/// as it is now.
|
||||
/// </summary>
|
||||
private async Task<Account> FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct)
|
||||
{
|
||||
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
|
||||
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
|
||||
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
|
||||
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
|
||||
|
||||
// The Coda follows at once, not at the next session: no «Storico» left for the account, and nothing planned
|
||||
// for an account that stays paused. Commands of Alberto stay; the task in flight is settled by its outcome.
|
||||
foreach (var task in await Store.Tasks.ListPendingAsync(10_000, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (task.AccountId == account.Id && !task.IsManual && (newState == AccountState.Paused || task.Kind == EngineTaskKind.Backfill))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var total =await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
|
||||
var tail = fresh.KeepUpdated
|
||||
? " Da ora lo tengo aggiornato."
|
||||
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Success,
|
||||
EngineEventCodes.BackfillCompleted,
|
||||
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
|
||||
account.Id,
|
||||
state.Context.SessionId,
|
||||
ct).ConfigureAwait(false);
|
||||
return await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? fresh;
|
||||
}
|
||||
|
||||
private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct)
|
||||
{
|
||||
await Store.Accounts.SetStateAsync(account.Id, AccountState.Paused, now, null, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -12,16 +12,31 @@ namespace Febe.Desktop.Browser;
|
||||
/// <summary>
|
||||
/// The browser of Instagram on Windows as the shared composition sees it (<see cref="IFebeBrowser"/>): a
|
||||
/// <see cref="WebView2Host"/> started with retries like <see cref="ChromiumBrowser"/> starts Chromium, started again
|
||||
/// when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has closed.
|
||||
/// (with the same retries) when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has
|
||||
/// closed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only a failed start is retried: what follows a start that worked (the log line, the state) is outside the retries,
|
||||
/// and reads only plain values of the host, never WebView2 objects — this class runs on the threads of the composition,
|
||||
/// while every WebView2 object lives on the UI thread (the error of 14 October 2026: the version of WebView2 read here,
|
||||
/// on a thread-pool thread, threw after every successful start, and the start was undone and retried for ever).
|
||||
/// </remarks>
|
||||
internal sealed class WebView2Browser : IFebeBrowser
|
||||
{
|
||||
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
|
||||
|
||||
/// <summary>How long stopping waits for the restart loop to end before closing WebView2 anyway.</summary>
|
||||
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly WebView2BrowserSettings _settings;
|
||||
private readonly FebePlatformContext _context;
|
||||
private readonly IClock _wallClock;
|
||||
private readonly BrowserOptions _options;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly Lock _gate = new();
|
||||
private Task? _restartLoop;
|
||||
private bool _restartWanted;
|
||||
private Exception? _restartFailure;
|
||||
private volatile bool _started;
|
||||
private volatile string? _lastError;
|
||||
|
||||
@@ -39,7 +54,7 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
ui,
|
||||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
|
||||
context.Log);
|
||||
Host.BrowserProcessFailed += (_, _) => _ = RecoverAsync();
|
||||
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
|
||||
}
|
||||
|
||||
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
|
||||
@@ -63,35 +78,10 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
|
||||
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await Host.StartAsync(_options, ct).ConfigureAwait(false);
|
||||
_started = true;
|
||||
_lastError = null;
|
||||
_context.Log.Info("browser", $"Browser di Febe pronto: WebView2 {Host.Version}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.");
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_lastError = $"WebView2 non parte ({ex.GetType().Name}: {FirstLine(ex.Message)}).";
|
||||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||||
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||||
await Host.ResetAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,56 +91,218 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
|
||||
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
|
||||
|
||||
/// <summary>«Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty.</summary>
|
||||
/// <summary>
|
||||
/// «Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty. When
|
||||
/// the profile cannot be deleted completely an <see cref="IOException"/> says so (the browser starts again anyway);
|
||||
/// when WebView2 does not start again, the same retries as at start-up bring it back in the background, and
|
||||
/// «Scollega» has still done its part (the connection service starts the engine again either way).
|
||||
/// </summary>
|
||||
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
|
||||
{
|
||||
Exception? deletion = null;
|
||||
async Task DeleteProfileQuietlyAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await DeleteProfileAsync().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
deletion = ex;
|
||||
}
|
||||
}
|
||||
|
||||
var restarted = false;
|
||||
try
|
||||
{
|
||||
await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false);
|
||||
await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false);
|
||||
MarkStarted();
|
||||
restarted = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException))
|
||||
{
|
||||
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", ex);
|
||||
// The start that follows the deletion failed: never a dead browser after «Scollega».
|
||||
RequestRestart(ex);
|
||||
}
|
||||
|
||||
_context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
|
||||
if (deletion is not null)
|
||||
{
|
||||
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", deletion);
|
||||
}
|
||||
|
||||
_context.Log.Info("browser", restarted
|
||||
? "Profilo del browser cancellato; il browser è ripartito vuoto."
|
||||
: "Profilo del browser cancellato; il browser ripartirà vuoto.");
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => Host.DisposeAsync();
|
||||
|
||||
/// <summary>The browser process of WebView2 went away by itself: it starts again with the same profile.</summary>
|
||||
private async Task RecoverAsync()
|
||||
/// <summary>
|
||||
/// Stops the retries, waits for the restart loop to notice (it stops waiting for WebView2 as soon as
|
||||
/// <c>_lifetime</c> is cancelled; at most <see cref="StopWait"/> in any case), then closes WebView2 and its window.
|
||||
/// <c>_lifetime</c> stays undisposed on purpose: a late caller may still read its (cancelled) token.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
Task? restarting;
|
||||
lock (_gate)
|
||||
{
|
||||
restarting = _restartLoop;
|
||||
}
|
||||
|
||||
if (restarting is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await restarting.WaitAsync(StopWait).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
_context.Log.Warn("browser", "WebView2: la ripartenza del browser non si è fermata in tempo; Febe si chiude lo stesso.");
|
||||
}
|
||||
}
|
||||
|
||||
await Host.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="start"/> until it works (true) or <paramref name="ct"/> is cancelled (false), waiting
|
||||
/// <see cref="Retry"/> between attempts. With <paramref name="failedFirst"/> the first attempt already failed with it.
|
||||
/// Only an exception of the start itself is a failed start; this method never throws.
|
||||
/// </summary>
|
||||
private async Task<bool> StartWithRetriesAsync(Func<CancellationToken, Task> start, CancellationToken ct, Exception? failedFirst = null)
|
||||
{
|
||||
var attempt = 0;
|
||||
if (failedFirst is not null && !await AfterFailedStartAsync(failedFirst, attempt++, ct).ConfigureAwait(false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await start(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ct.IsCancellationRequested && ex is (OperationCanceledException or ObjectDisposedException))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (!await AfterFailedStartAsync(ex, attempt++, ct).ConfigureAwait(false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
MarkStarted();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A start failed: it is said, and the next attempt waits. False when cancelled. What the failed start created it
|
||||
/// closed itself, inside the host: a close from here could catch a browser that «Scollega» started meanwhile.
|
||||
/// </summary>
|
||||
private async Task<bool> AfterFailedStartAsync(Exception error, int attempt, CancellationToken ct)
|
||||
{
|
||||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||||
_lastError = $"WebView2 non parte ({error.GetType().Name}: {FirstLine(error.Message)}).";
|
||||
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||||
try
|
||||
{
|
||||
await Host.RestartAsync(null, CancellationToken.None).ConfigureAwait(false);
|
||||
_context.Log.Info("browser", "Browser di Febe ripartito dopo l'arresto del suo processo.");
|
||||
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_started = false;
|
||||
_lastError = $"WebView2 non riparte ({ex.GetType().Name}).";
|
||||
_context.Log.Error("browser", _lastError);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deletes the profile; a process of WebView2 may still hold a file for a moment.</summary>
|
||||
private void MarkStarted()
|
||||
{
|
||||
_started = true;
|
||||
_lastError = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The browser must start again (its process went away by itself, or the start after «Scollega» failed with
|
||||
/// <paramref name="failure"/>): one loop at a time starts it, with the retries of the first start, on the thread
|
||||
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round
|
||||
/// again. The loop only starts what is not running: when another way in (the first start, «Scollega») brought the
|
||||
/// browser back first, its attempt finds it running and is done.
|
||||
/// </summary>
|
||||
private void RequestRestart(Exception? failure)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_restartWanted = true;
|
||||
_restartFailure ??= failure;
|
||||
_restartLoop ??= Task.Run(RestartLoopAsync);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RestartLoopAsync()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Exception? failure;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_restartWanted || _lifetime.IsCancellationRequested)
|
||||
{
|
||||
_restartLoop = null;
|
||||
return;
|
||||
}
|
||||
|
||||
_restartWanted = false;
|
||||
failure = _restartFailure;
|
||||
_restartFailure = null;
|
||||
}
|
||||
|
||||
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false))
|
||||
{
|
||||
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plain values only (the version was read on the UI thread during the start).</summary>
|
||||
private string ReadyMessage(string what) =>
|
||||
$"{what}: WebView2 {Host.Version ?? "di versione sconosciuta"}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.";
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a
|
||||
/// file for a moment.
|
||||
/// </summary>
|
||||
private async Task DeleteProfileAsync()
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(ProfileDirectory))
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Directory.Delete(ProfileDirectory, recursive: true);
|
||||
}
|
||||
|
||||
if (Directory.Exists(ProfileDirectory))
|
||||
{
|
||||
Directory.Delete(ProfileDirectory, recursive: true);
|
||||
}
|
||||
}).ConfigureAwait(true);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10)
|
||||
{
|
||||
await Task.Delay(500).ConfigureAwait(true);
|
||||
await _wallClock.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None).ConfigureAwait(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
@@ -35,27 +36,49 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
|
||||
/// «Ho finito»; using and closing it marks the browser as used for «Riprendi».</item>
|
||||
/// <item>Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3);
|
||||
/// <see cref="RestartAsync"/> («Scollega») does the same before deleting the profile.</item>
|
||||
/// <item>Every WebView2 call runs on the UI thread through its dispatcher.</item>
|
||||
/// <item>Threads: every WebView2 object (environment, controller, <c>CoreWebView2</c>, its settings and DevTools
|
||||
/// receivers) and the window are touched only on the UI thread, through its dispatcher; WebView2 throws on any other
|
||||
/// thread. Callers on other threads (the composition, the engine) get only plain values captured on the UI thread
|
||||
/// during the start (<see cref="Version"/>, <see cref="BrowserProcessId"/>), the CDP session, and tasks. Start,
|
||||
/// restart and stop run one at a time.</item>
|
||||
/// <item>One WebView at a time, whoever starts it (the first start and its retries, «Scollega», the start after a
|
||||
/// crash): a start finds the WebView running and does nothing, closes what a dead one left before creating a new one,
|
||||
/// and when it fails it closes what it created itself. Events of a closed WebView never count.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
internal sealed class WebView2Host : IBrowserHost
|
||||
{
|
||||
private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>How long stopping waits for a start or restart in progress before closing what there is.</summary>
|
||||
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly Dispatcher _ui;
|
||||
private readonly WebView2HostOptions _settings;
|
||||
private readonly FebeLog _log;
|
||||
private readonly WebView2CdpSession _session;
|
||||
|
||||
// Start, restart and dispose each await WebView2 on the UI thread: without this they could interleave there.
|
||||
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
||||
|
||||
// The fields below are touched on the UI thread only.
|
||||
private BrowserOptions? _options;
|
||||
private BrowserWindow? _window;
|
||||
private CoreWebView2Environment? _environment;
|
||||
private CoreWebView2Controller? _controller;
|
||||
private CoreWebView2? _core;
|
||||
private CompositionHost? _composition;
|
||||
private CoreWebView2DevTools? _devTools;
|
||||
private TaskCompletionSource? _exited;
|
||||
private IDisposable? _lease;
|
||||
private int _generation;
|
||||
private bool _starting;
|
||||
private bool _crashedWhileStarting;
|
||||
private bool _closing;
|
||||
private bool _restarting;
|
||||
|
||||
// Plain values read on the UI thread during the start: any thread may read them.
|
||||
private volatile string? _version;
|
||||
private int _browserProcessId;
|
||||
|
||||
public WebView2Host(Dispatcher ui, WebView2HostOptions settings, FebeLog log)
|
||||
{
|
||||
@@ -79,18 +102,41 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
/// <summary>True while a WebView is attached (commands can be sent).</summary>
|
||||
public bool IsAttached => _session.IsAttached;
|
||||
|
||||
/// <summary>The version of the WebView2 runtime in use (for the log).</summary>
|
||||
public string? Version => _environment?.BrowserVersionString;
|
||||
/// <summary>
|
||||
/// The version of the WebView2 runtime of the browser in use (for the log), read on the UI thread when it started;
|
||||
/// null before the first start. Any thread: it is a plain value, never a member of a WebView2 object.
|
||||
/// </summary>
|
||||
public string? Version => _version;
|
||||
|
||||
/// <summary>Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts).</summary>
|
||||
/// <summary>The browser process of WebView2 when it last started (0 before the first start). Any thread.</summary>
|
||||
public int BrowserProcessId => Volatile.Read(ref _browserProcessId);
|
||||
|
||||
/// <summary>The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object.</summary>
|
||||
internal BrowserWindow? Window => _window;
|
||||
|
||||
/// <summary>
|
||||
/// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts), after the
|
||||
/// handler of WebView2's own event has returned: WebView2 does not support closing and recreating inside it.
|
||||
/// </summary>
|
||||
public event EventHandler? BrowserProcessFailed;
|
||||
|
||||
/// <summary>Creates the window (once), the environment and the controller, and attaches the CDP session.</summary>
|
||||
/// <summary>
|
||||
/// Creates the window (once), the environment and the controller, and attaches the CDP session — unless a WebView
|
||||
/// is already running, because another way in started it («Scollega», the start after a crash): then it does nothing
|
||||
/// and the start counts as done. A failed start leaves nothing open. When <paramref name="ct"/> is cancelled (Febe
|
||||
/// is exiting) the caller stops waiting at once, even while WebView2 has not answered: a start not yet begun does not
|
||||
/// begin, one under way on the UI thread ends by itself, and stopping closes what it leaves.
|
||||
/// </summary>
|
||||
public Task StartAsync(BrowserOptions options, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
_options = options;
|
||||
return OnUiAsync(StartCoreAsync);
|
||||
var start = OnUiAsync(() => ExclusiveAsync(() =>
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return StartCoreAsync();
|
||||
}));
|
||||
return UntilCancelledAsync(start, ct);
|
||||
}
|
||||
|
||||
public Task ShowToUserAsync() => OnUiAsync(() =>
|
||||
@@ -104,8 +150,18 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
window.Activate();
|
||||
window.Topmost = true;
|
||||
window.Topmost = false;
|
||||
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
|
||||
|
||||
// The lease first: once the window is on screen the engine must be still, whatever happens to the focus.
|
||||
TakeLease();
|
||||
try
|
||||
{
|
||||
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone (it is starting again): the window is on screen anyway.
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
@@ -119,55 +175,50 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
/// <summary>
|
||||
/// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs
|
||||
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
|
||||
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails; its error is
|
||||
/// thrown afterwards.
|
||||
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails with an
|
||||
/// <see cref="IOException"/> or <see cref="UnauthorizedAccessException"/>; that error is thrown afterwards. A failed
|
||||
/// start throws its own error and, like a failed <see cref="StartAsync"/>, leaves nothing open. Once begun it goes
|
||||
/// to the end whatever <paramref name="ct"/> says (the profile with the Instagram session must go, and the engine
|
||||
/// starts again after it); stopping waits for it at most <see cref="StopWait"/>.
|
||||
/// </summary>
|
||||
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(async () =>
|
||||
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () =>
|
||||
{
|
||||
_restarting = true;
|
||||
try
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
Exception? failure = null;
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
if (whileStopped is not null)
|
||||
{
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
if (whileStopped is not null)
|
||||
{
|
||||
await whileStopped().ConfigureAwait(true);
|
||||
}
|
||||
await whileStopped().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
failure = ex;
|
||||
}
|
||||
|
||||
await StartCoreAsync().ConfigureAwait(true);
|
||||
if (failure is not null)
|
||||
{
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
finally
|
||||
|
||||
await StartCoreAsync().ConfigureAwait(true);
|
||||
if (failure is not null)
|
||||
{
|
||||
_restarting = false;
|
||||
ExceptionDispatchInfo.Throw(failure);
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
|
||||
public Task ResetAsync() => OnUiAsync(CloseWebViewAsync);
|
||||
}));
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await OnUiAsync(async () =>
|
||||
{
|
||||
_closing = true;
|
||||
ReleaseLease();
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
_window?.CloseForGood();
|
||||
_window = null;
|
||||
}).ConfigureAwait(false);
|
||||
await OnUiAsync(() => ExclusiveAsync(
|
||||
async () =>
|
||||
{
|
||||
_closing = true;
|
||||
ReleaseLease();
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
_window?.CloseForGood();
|
||||
_window = null;
|
||||
},
|
||||
StopWait)).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or TaskCanceledException)
|
||||
{
|
||||
@@ -177,9 +228,71 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
await _session.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>True while a WebView is in the window and attached to the session (its browser process did not die).</summary>
|
||||
private bool IsRunning => _controller is not null && _session.IsAttached;
|
||||
|
||||
/// <summary>
|
||||
/// UI thread, one at a time (<see cref="ExclusiveAsync"/>): the only place a WebView is created, so the window never
|
||||
/// holds two. A WebView already running stays (the start is done); what a dead one left is closed first; a failed
|
||||
/// start closes what it created.
|
||||
/// </summary>
|
||||
private async Task StartCoreAsync()
|
||||
{
|
||||
_ui.VerifyAccess();
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti.");
|
||||
|
||||
// Started already, by «Scollega» or by the start after a crash, while this start waited for its turn or for its
|
||||
// next attempt: a second WebView would orphan the first, whose browser process then holds the profile.
|
||||
if (IsRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A WebView whose browser process died (the session is detached) is closed before the new one exists.
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
_starting = true;
|
||||
_crashedWhileStarting = false;
|
||||
try
|
||||
{
|
||||
await CreateWebViewAsync(options).ConfigureAwait(true);
|
||||
|
||||
// The browser process went away while the start awaited WebView2: this start failed, the caller retries.
|
||||
if (_crashedWhileStarting)
|
||||
{
|
||||
throw new InvalidOperationException("Il processo del browser WebView2 si è chiuso durante l'avvio.");
|
||||
}
|
||||
|
||||
// Stopping gave up waiting for this start (WebView2 took longer than StopWait) and closed what there was:
|
||||
// what this start created goes too.
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Nothing stays open after a failed start, whoever retries it and whenever: here, inside the same step.
|
||||
await CloseAfterFailedStartAsync().ConfigureAwait(true);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_starting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CloseAfterFailedStartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CreateWebViewAsync(BrowserOptions options)
|
||||
{
|
||||
if (_window is null)
|
||||
{
|
||||
var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon);
|
||||
@@ -196,24 +309,31 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
var profile = Path.GetFullPath(options.ProfileDirectory);
|
||||
Directory.CreateDirectory(profile);
|
||||
var environmentOptions = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = _settings.AdditionalBrowserArguments };
|
||||
_environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
|
||||
var environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
|
||||
_environment = environment;
|
||||
_exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_environment.BrowserProcessExited += OnBrowserProcessExited;
|
||||
environment.BrowserProcessExited += OnBrowserProcessExited;
|
||||
|
||||
// Read here, on the UI thread, for the log line the composition writes from another thread: a member of the
|
||||
// environment read there throws «CoreWebView2Environment members can only be accessed from the UI thread».
|
||||
_version = environment.BrowserVersionString;
|
||||
|
||||
var hwnd = _window.Handle;
|
||||
CoreWebView2Controller controller;
|
||||
if (_settings.Hosting == BrowserHosting.Composition)
|
||||
{
|
||||
var composition = await _environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
|
||||
var composition = await environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
|
||||
controller = composition;
|
||||
_controller = controller;
|
||||
_composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default);
|
||||
_composition.Attach(composition);
|
||||
_controller = composition;
|
||||
}
|
||||
else
|
||||
{
|
||||
_controller = await _environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
|
||||
controller = await environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
|
||||
_controller = controller;
|
||||
}
|
||||
|
||||
var controller = _controller;
|
||||
controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels;
|
||||
controller.Bounds = _window.PageBounds;
|
||||
|
||||
@@ -221,6 +341,8 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
controller.IsVisible = true;
|
||||
|
||||
var core = controller.CoreWebView2;
|
||||
_core = core;
|
||||
Volatile.Write(ref _browserProcessId, unchecked((int)core.BrowserProcessId));
|
||||
var s = core.Settings;
|
||||
s.IsPasswordAutosaveEnabled = false;
|
||||
s.IsGeneralAutofillEnabled = false;
|
||||
@@ -228,11 +350,14 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
s.IsZoomControlEnabled = false;
|
||||
s.IsPinchZoomEnabled = false;
|
||||
s.IsSwipeNavigationEnabled = false;
|
||||
|
||||
// Events of an earlier WebView (closed, or crashed) must not act on this one.
|
||||
var generation = ++_generation;
|
||||
core.NewWindowRequested += OnNewWindowRequested;
|
||||
core.DownloadStarting += (_, e) => e.Cancel = true;
|
||||
core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny;
|
||||
core.SourceChanged += (_, _) => _window?.ShowAddress(Addresses.WithoutQuery(core.Source));
|
||||
core.ProcessFailed += OnProcessFailed;
|
||||
core.ProcessFailed += (sender, e) => OnProcessFailed(generation, sender, e);
|
||||
core.Navigate(CdpPageExtensions.RestUrl);
|
||||
|
||||
_devTools = new CoreWebView2DevTools(_ui, core);
|
||||
@@ -240,19 +365,37 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
|
||||
/// <summary>
|
||||
/// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. From here on
|
||||
/// the events of the WebView being closed belong to an old generation: they change nothing.
|
||||
/// </summary>
|
||||
private async Task CloseWebViewAsync()
|
||||
{
|
||||
_ui.VerifyAccess();
|
||||
_generation++;
|
||||
_session.Detach();
|
||||
_devTools?.Close();
|
||||
_devTools = null;
|
||||
_core = null;
|
||||
var exited = _exited;
|
||||
if (_composition is { } composition)
|
||||
{
|
||||
_composition = null;
|
||||
try
|
||||
{
|
||||
composition.Dispose();
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The visual tree goes with the window.
|
||||
}
|
||||
}
|
||||
|
||||
if (_controller is { } controller)
|
||||
{
|
||||
_controller = null;
|
||||
try
|
||||
{
|
||||
_composition?.Dispose();
|
||||
controller.Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
@@ -260,7 +403,6 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
// The browser process is already gone (it crashed): nothing left to close.
|
||||
}
|
||||
|
||||
_composition = null;
|
||||
if (exited is not null)
|
||||
{
|
||||
await Task.WhenAny(exited.Task, Task.Delay(ExitWait)).ConfigureAwait(true);
|
||||
@@ -276,24 +418,42 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
|
||||
private void OnBrowserProcessExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs e) => _exited?.TrySetResult();
|
||||
|
||||
private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e)
|
||||
private void OnProcessFailed(int generation, object? sender, CoreWebView2ProcessFailedEventArgs e)
|
||||
{
|
||||
_log.Warn("browser", $"WebView2: processo terminato ({e.ProcessFailedKind}).");
|
||||
if (_closing || _restarting)
|
||||
var kind = e.ProcessFailedKind;
|
||||
_log.Warn("browser", $"WebView2: processo terminato ({kind}).");
|
||||
|
||||
// A WebView that is closing, closed or replaced is not ours any more (a restart, «Scollega», a failed start).
|
||||
if (_closing || generation != _generation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
|
||||
// During a start the failure is the start's own error: the start closes what it created and the caller retries.
|
||||
if (_starting)
|
||||
{
|
||||
// The whole browser is gone: the owner starts it again (same profile), as the supervisor does with Chromium.
|
||||
_session.Detach();
|
||||
BrowserProcessFailed?.Invoke(this, EventArgs.Empty);
|
||||
_crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited;
|
||||
return;
|
||||
}
|
||||
else if (e.ProcessFailedKind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
|
||||
|
||||
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
|
||||
{
|
||||
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
|
||||
// the supervisor does with Chromium — once this handler has returned (threading model of WebView2).
|
||||
_session.Detach();
|
||||
_ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background);
|
||||
}
|
||||
else if (kind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
|
||||
{
|
||||
// The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors.
|
||||
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
|
||||
try
|
||||
{
|
||||
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser went with the page: its own ProcessFailed follows.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,19 +491,40 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
|
||||
{
|
||||
// «Indietro» and «Ricarica» of the bar are Alberto's own navigation (rule 7): never an engine action.
|
||||
if (_controller?.CoreWebView2 is { } core && allowed(core))
|
||||
if (_core is not { } core)
|
||||
{
|
||||
TakeLease();
|
||||
action(core);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (allowed(core))
|
||||
{
|
||||
TakeLease();
|
||||
action(core);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone (it is starting again): the button does nothing.
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateBounds()
|
||||
{
|
||||
if (_controller is { } controller && _window is { } window)
|
||||
if (_controller is not { } controller || _window is not { } window)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
controller.Bounds = window.PageBounds;
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone: the next start sizes the new WebView.
|
||||
}
|
||||
}
|
||||
|
||||
private void TakeLease()
|
||||
@@ -368,5 +549,75 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
private Task OnUiAsync(Func<Task> action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap();
|
||||
/// <summary>
|
||||
/// Runs one step of the life of the WebView (start, restart, stop) after the others. UI thread. With
|
||||
/// <paramref name="wait"/> the step runs anyway once that time has passed (stopping must not hang behind a start
|
||||
/// that WebView2 never completes).
|
||||
/// </summary>
|
||||
private async Task ExclusiveAsync(Func<Task> step, TimeSpan? wait = null)
|
||||
{
|
||||
var entered = true;
|
||||
if (wait is { } limit)
|
||||
{
|
||||
entered = await _lifecycle.WaitAsync(limit).ConfigureAwait(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _lifecycle.WaitAsync().ConfigureAwait(true);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await step().ConfigureAwait(true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (entered)
|
||||
{
|
||||
_lifecycle.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for <paramref name="work"/> until <paramref name="ct"/> is cancelled. Then the caller goes on and the work
|
||||
/// is left to end by itself; its outcome is observed here, so a late error is never an unobserved task.
|
||||
/// </summary>
|
||||
private static async Task UntilCancelledAsync(Task work, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await work.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
_ = work.ContinueWith(
|
||||
static done => _ = done.Exception,
|
||||
CancellationToken.None,
|
||||
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="action"/> on the UI thread — at once when already there — and returns its task: an exception
|
||||
/// is always in the task, never thrown to the caller.
|
||||
/// </summary>
|
||||
private Task OnUiAsync(Func<Task> action)
|
||||
{
|
||||
if (!_ui.CheckAccess())
|
||||
{
|
||||
return _ui.InvokeAsync(action).Task.Unwrap();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return action();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
return Task.FromException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,10 @@
|
||||
<ProjectReference Include="..\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||
<PackageReference Include="Microsoft.Web.WebView2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Le prove che girano solo su Windows (WebView2 vero sul thread dell'interfaccia). -->
|
||||
<InternalsVisibleTo Include="Febe.Tests.Windows" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- L'icona del marchio (appendice C), generata da BrandMark e IcoWriter: finestre e area di notifica la leggono da qui. -->
|
||||
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compila anche da Linux
|
||||
(`EnableWindowsTargeting`), ma gira solo su Windows: tutto ciò che si può provare altrove sta in
|
||||
`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`). Guida per l'uso: `docs/windows.md`.
|
||||
`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`); il resto si prova su Windows, con WebView2
|
||||
vero, in `tests/Febe.Tests.Windows` (`dotnet test tests/Febe.Tests.Windows`). Guida per l'uso: `docs/windows.md`.
|
||||
|
||||
## Come è fatto
|
||||
|
||||
@@ -23,9 +24,22 @@ L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compi
|
||||
| `Native/Win32.cs` | Le poche chiamate Win32 e le interfacce di DirectComposition |
|
||||
| `Febe.ico` | Il marchio (appendice C) a 16–256 pixel, generato da `BrandMark`/`IcoWriter` (`FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests`) |
|
||||
|
||||
Regole che valgono anche qui: le chiamate a WebView2 solo sul thread dell'interfaccia; il browser di Febe non si nasconde
|
||||
e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie o tasti; nessun pacchetto oltre a
|
||||
`Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
|
||||
Regole che valgono anche qui:
|
||||
|
||||
- Ogni oggetto di WebView2 (ambiente, controllo, `CoreWebView2`, impostazioni, ricevitori DevTools) e ogni finestra si
|
||||
tocca solo sul thread dell'interfaccia, anche solo per leggere una proprietà: WebView2 lancia
|
||||
`InvalidOperationException` su ogni altro thread. Chi sta su un altro thread (composizione, motore) passa dal
|
||||
dispatcher o legge valori semplici presi durante l'avvio (`WebView2Host.Version`, `BrowserProcessId`). Attenzione a
|
||||
`ConfigureAwait(false)`: dopo, si è su un thread del pool. È l'errore del 14 ottobre 2026 (il browser non partiva mai).
|
||||
- Dentro un gestore di un evento di WebView2 niente chiusure, ricreazioni, cicli di messaggi o shell: si mette in coda
|
||||
sul dispatcher e si fa dopo (modello dei thread di WebView2).
|
||||
- Si riprova solo un avvio fallito: ciò che segue un avvio riuscito (registro, stato) non lo disfa mai.
|
||||
- Un solo WebView alla volta, chiunque lo avvii (primo avvio e suoi tentativi, «Scollega», ripartenza dopo un arresto
|
||||
del processo): l'avvio, dentro la sezione esclusiva di `WebView2Host`, trova quello in funzione e non fa nulla, chiude
|
||||
prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato. Un WebView orfano terrebbe vivo il processo
|
||||
del browser sul profilo, e «Scollega» non potrebbe più cancellarlo.
|
||||
- Il browser di Febe non si nasconde e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie
|
||||
o tasti; nessun pacchetto oltre a `Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
|
||||
|
||||
## Pubblicazione
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.Wpf;
|
||||
|
||||
@@ -120,7 +121,7 @@ internal sealed class MainWindow : Window
|
||||
e.Cancel = true;
|
||||
if (uri.Scheme is "http" or "https")
|
||||
{
|
||||
_ = _openOutside(uri);
|
||||
OpenOutsideLater(uri);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +139,13 @@ internal sealed class MainWindow : Window
|
||||
}
|
||||
else if (uri.Scheme is "http" or "https")
|
||||
{
|
||||
_ = _openOutside(uri);
|
||||
OpenOutsideLater(uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens <paramref name="uri"/> in Alberto's browser once the handler of WebView2's event has returned: the shell
|
||||
/// may run a message loop of its own, and WebView2 does not support re-entering its handlers (threading model).
|
||||
/// </summary>
|
||||
private void OpenOutsideLater(Uri uri) => Dispatcher.InvokeAsync(() => _openOutside(uri), DispatcherPriority.Background);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Sito di prova": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "--dati \"%USERPROFILE%\\FebeSviluppo\\comune\\dati\" --libreria \"%USERPROFILE%\\FebeSviluppo\\comune\\libreria\" --sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,40 @@ namespace Febe.Server;
|
||||
/// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser
|
||||
/// and nowhere else.
|
||||
/// </summary>
|
||||
internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost
|
||||
internal sealed class BrowserRemoteViewHost : IRemoteViewHost
|
||||
{
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly IClock _browserClock;
|
||||
private readonly FebeLog _log;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SemaphoreSlim _opening = new(1, 1);
|
||||
private BrowserRemoteViewConnection? _current;
|
||||
private bool _shuttingDown;
|
||||
|
||||
/// <param name="browser">The browser shown.</param>
|
||||
/// <param name="tracker">Notes when Alberto last used the browser.</param>
|
||||
/// <param name="clock">The composition's clock (the time of that note).</param>
|
||||
/// <param name="log">Febe's log.</param>
|
||||
/// <param name="browserClock">
|
||||
/// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real
|
||||
/// time whatever clock the engine runs on (the tests compress it).
|
||||
/// </param>
|
||||
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null)
|
||||
{
|
||||
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
||||
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
|
||||
}
|
||||
|
||||
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
if (!browser.IsAvailable)
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
throw new RemoteViewUnavailableException(browser.LastError is { } error
|
||||
throw new RemoteViewUnavailableException(_browser.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
@@ -37,6 +59,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
// would both start and the later assignment would orphan the other (still holding its lease, and stopping the
|
||||
// shared screencast when it closes).
|
||||
await _opening.WaitAsync(ct).ConfigureAwait(false);
|
||||
IDisposable? handover = null;
|
||||
try
|
||||
{
|
||||
BrowserRemoteViewConnection? previous;
|
||||
@@ -53,13 +76,17 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
|
||||
if (previous is not null)
|
||||
{
|
||||
// Alberto is still at the browser while one view takes the place of the other: without this lease the
|
||||
// engine would see nobody driving for a moment and put the page back to rest (a navigation under the new
|
||||
// view's start) or even begin a session.
|
||||
handover = _browser.UserDriving.Begin();
|
||||
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
|
||||
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock);
|
||||
try
|
||||
{
|
||||
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
|
||||
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -90,11 +117,13 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
_log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
return connection;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The new view holds its own lease by now; if it did not start, nobody is at the browser any more.
|
||||
handover?.Dispose();
|
||||
_opening.Release();
|
||||
}
|
||||
}
|
||||
@@ -126,7 +155,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota chiusa.");
|
||||
_log.Info("vista", "Vista remota chiusa.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +163,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
{
|
||||
private readonly BrowserRemoteViewHost _owner;
|
||||
private readonly ChromiumBrowser _browser;
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly RemoteViewSession _session;
|
||||
@@ -155,18 +184,18 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
private int _disposed;
|
||||
private bool _used;
|
||||
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock)
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock)
|
||||
{
|
||||
_owner = owner;
|
||||
_browser = browser;
|
||||
_tracker = tracker;
|
||||
_clock = clock;
|
||||
_session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving);
|
||||
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock);
|
||||
}
|
||||
|
||||
public RemoteViewEnd? Ended { get; private set; }
|
||||
|
||||
private ICdpSession Cdp => _browser.Host.Cdp;
|
||||
private ICdpSession Cdp => _browser.Cdp;
|
||||
|
||||
public async Task StartAsync(int width, int height, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log);
|
||||
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log);
|
||||
services.AddSingleton<IRemoteViewHost>(RemoteView);
|
||||
}
|
||||
|
||||
|
||||
@@ -220,9 +220,12 @@ export async function mountConnection(page) {
|
||||
function drawConnected() {
|
||||
waitingResume = false;
|
||||
closeView();
|
||||
// Before the first round the name of the account is not known yet: «Collegato» and «Nome non ancora noto», never «@».
|
||||
const nome = status.username || '';
|
||||
const sotto = nome ? status.displayName : t('stato.accountDaLeggere');
|
||||
fill(left, h('div.pannello.collegato',
|
||||
h('div.chi-collegato', avatar(status.username || '', 'g'),
|
||||
h('div', h('h2', t('impostazioni.collegamento.collegatoCome', { nome: status.username || '' })), status.displayName ? h('span.muto', status.displayName) : null)),
|
||||
h('div.chi-collegato', avatar(nome, 'g'),
|
||||
h('div', h('h2', nome ? t('impostazioni.collegamento.collegatoCome', { nome }) : t('stato.collegato')), sotto ? h('span.muto', sotto) : null)),
|
||||
h('p', t('impostazioni.collegamento.collegatoTesto')),
|
||||
h('div.azioni-collegato',
|
||||
h('button.btn', { type: 'button', onclick: useBrowser }, icon('app-window', 's'), t('impostazioni.collegamento.usaBrowser')),
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Prove che girano solo su Windows, con il WebView2 vero: il thread dell'interfaccia di WPF, il browser di Febe,
|
||||
il protocollo DevTools sul sito di prova locale e una sessione di raccolta della composizione condivisa.
|
||||
Si compila anche da Linux (EnableWindowsTargeting, come Febe.Desktop: la CI compila tutta la soluzione), ma si
|
||||
esegue solo su Windows (dotnet test tests/Febe.Tests.Windows); dove manca il runtime WebView2 le prove risultano
|
||||
inconcludenti. Mai Instagram: il browser vede solo 127.0.0.1. -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- Con WPF l'SDK toglie System.IO dagli using impliciti (Path di System.Windows.Shapes): qui serve. -->
|
||||
<Using Include="System.IO" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Febe.Core\Febe.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Data\Febe.Data.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Browser\Febe.Browser.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Web\Febe.Web.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.App\Febe.App.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Desktop\Febe.Desktop.csproj" />
|
||||
<ProjectReference Include="..\..\tools\Febe.SitoDiProva\Febe.SitoDiProva.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,2 @@
|
||||
// One WebView2 at a time: every test starts its own browser process, window and UI thread.
|
||||
[assembly: DoNotParallelize]
|
||||
@@ -0,0 +1,127 @@
|
||||
using Febe.App;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Data;
|
||||
using Febe.Desktop.Browser;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The browser of Febe for Windows on its own, as the composition builds it (<see cref="DesktopPlatform"/> through
|
||||
/// <c>DesktopShell</c>): a <see cref="WebView2Browser"/> with its window «Browser di Febe» and WebView2 on a real UI
|
||||
/// thread, a profile in a temporary Data folder, the switches of S2 and the log of Febe captured.
|
||||
/// </summary>
|
||||
internal sealed class BrowserBed : IAsyncDisposable
|
||||
{
|
||||
private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, BrowserUseTracker tracker, WebView2Browser browser)
|
||||
{
|
||||
Folder = folder;
|
||||
Ui = ui;
|
||||
Lines = lines;
|
||||
Log = log;
|
||||
Database = database;
|
||||
Tracker = tracker;
|
||||
Browser = browser;
|
||||
}
|
||||
|
||||
public TestFolder Folder { get; }
|
||||
|
||||
public UiThread Ui { get; }
|
||||
|
||||
/// <summary>What Febe wrote in its log.</summary>
|
||||
public LogLines Lines { get; }
|
||||
|
||||
public FebeLog Log { get; }
|
||||
|
||||
public FebeDatabase Database { get; }
|
||||
|
||||
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
|
||||
public BrowserUseTracker Tracker { get; }
|
||||
|
||||
public WebView2Browser Browser { get; }
|
||||
|
||||
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window)
|
||||
{
|
||||
var folder = new TestFolder(name);
|
||||
var ui = await UiThread.StartAsync();
|
||||
var lines = new LogLines();
|
||||
var clock = new SystemClock();
|
||||
var log = new FebeLog(null, lines, clock);
|
||||
var data = new DataFolderLayout(folder.Combine("dati"));
|
||||
var database = await FebeDatabase.OpenAsync(data.Root);
|
||||
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
|
||||
var tracker = new BrowserUseTracker();
|
||||
var context = new FebePlatformContext(options, data, database, clock, log, tracker);
|
||||
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
|
||||
|
||||
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
|
||||
var browser = new WebView2Browser(ui.Dispatcher, settings, context, icon: null);
|
||||
return new BrowserBed(folder, ui, lines, log, database, tracker, browser);
|
||||
}
|
||||
|
||||
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
|
||||
public async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.\n{Lines.Text}");
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a value of the UI thread (the window, its position) through the dispatcher.</summary>
|
||||
public Task<T> OnUiAsync<T>(Func<T> read) => Ui.InvokeAsync(read);
|
||||
|
||||
/// <summary>The class names of the child windows of «Browser di Febe»: one per WebView hosted in it.</summary>
|
||||
public Task<IReadOnlyList<string>> ChildWindowsAsync() =>
|
||||
OnUiAsync(() => Browser.Host.Window is { } window ? ChildWindows.Of(window.Handle) : (IReadOnlyList<string>)[]);
|
||||
|
||||
/// <summary>
|
||||
/// Starts the browser from a thread-pool thread, like <c>FebeApp.BringUpBrowserAsync</c>, and waits until
|
||||
/// <see cref="WebView2Browser.RunAsync"/> returns. Fails at once when the log reports a failed start: the loop of
|
||||
/// retries would otherwise go on for ever.
|
||||
/// </summary>
|
||||
public async Task StartAsync(CancellationToken ct, TimeSpan? timeout = null)
|
||||
{
|
||||
var run = Task.Run(() => Browser.RunAsync(ct), ct);
|
||||
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(60));
|
||||
while (!run.IsCompleted)
|
||||
{
|
||||
if (Lines.Any("non parte"))
|
||||
{
|
||||
Assert.Fail("Il browser di Febe non è partito al primo tentativo:\n" + Lines.Text);
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail("Il browser di Febe non è diventato disponibile in tempo:\n" + Lines.Text);
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
|
||||
await run;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Browser.DisposeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Ui.DisposeAsync();
|
||||
await Database.DisposeAsync();
|
||||
Log.Dispose();
|
||||
Folder.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The direct child windows of a window, by class name. WebView2 hosted in a window («finestra») puts one child window
|
||||
/// per controller into its parent: two of them in «Browser di Febe» mean two WebViews, one of them orphaned.
|
||||
/// </summary>
|
||||
internal static class ChildWindows
|
||||
{
|
||||
/// <summary>The class names of the direct children of <paramref name="parent"/>, in Z order.</summary>
|
||||
public static IReadOnlyList<string> Of(IntPtr parent)
|
||||
{
|
||||
var names = new List<string>();
|
||||
var buffer = new char[256];
|
||||
var child = IntPtr.Zero;
|
||||
while ((child = FindWindowEx(parent, child, null, null)) != IntPtr.Zero)
|
||||
{
|
||||
var length = GetClassName(child, buffer, buffer.Length);
|
||||
names.Add(new string(buffer, 0, Math.Max(length, 0)));
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "FindWindowExW", CharSet = CharSet.Unicode)]
|
||||
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childAfter, string? className, string? windowName);
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetClassName(IntPtr window, [Out] char[] className, int maxCount);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A clock that compresses time, like the one of the Linux suite: <see cref="Delay"/> waits for real only a fraction
|
||||
/// of the requested time and <see cref="Now"/> moves on by the whole of it, so the engine keeps its order of events
|
||||
/// while a session lasts minutes instead of hours.
|
||||
/// </summary>
|
||||
internal sealed class CompressedClock(double factor, TimeZoneInfo zone) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private TimeSpan _offset;
|
||||
|
||||
public TimeZoneInfo LocalZone { get; } = zone;
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return DateTimeOffset.UtcNow + _offset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
if (time <= TimeSpan.Zero)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return;
|
||||
}
|
||||
|
||||
var real = TimeSpan.FromTicks((long)(time.Ticks / factor));
|
||||
if (real >= TimeSpan.FromMilliseconds(1))
|
||||
{
|
||||
await Task.Delay(real, ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await Task.Yield();
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_offset += time - real;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class TestZones
|
||||
{
|
||||
/// <summary>
|
||||
/// A fixed-offset zone where it is between 12:00 and 13:00 now: inside the active window of every caution profile,
|
||||
/// whatever the hour of the test.
|
||||
/// </summary>
|
||||
public static TimeZoneInfo Noon()
|
||||
{
|
||||
var offset = 12 - DateTimeOffset.UtcNow.Hour;
|
||||
return TimeZoneInfo.CreateCustomTimeZone("Febe/Mezzogiorno", TimeSpan.FromHours(offset), "Mezzogiorno di prova", "Mezzogiorno di prova");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The registry values «CartellaDati» and «NuovaCartellaDati», in memory.</summary>
|
||||
internal sealed class MemoryLocations : IDataFolderLocationStore
|
||||
{
|
||||
public string? Current { get; private set; }
|
||||
|
||||
public string? Pending { get; private set; }
|
||||
|
||||
public void SetCurrent(string? folder) => Current = folder;
|
||||
|
||||
public void SetPending(string? folder) => Pending = folder;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.App;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop;
|
||||
using Febe.Desktop.Browser;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Web.Native;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The shared composition (<see cref="FebeApp"/>) as Febe.exe composes it — <see cref="DesktopPlatform"/>,
|
||||
/// <c>DesktopShell</c>, the window «Browser di Febe» on a WPF UI thread — against its own test site, in temporary
|
||||
/// folders, on a clock ten times faster and in a zone where it is noon. The interface is asked like the main window asks
|
||||
/// it: with the token of this start and the Origin of the interface.
|
||||
/// </summary>
|
||||
internal sealed class DesktopBed : IAsyncDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
private DesktopBed(TestSite site, TestFolder folder, UiThread ui, LogLines lines, CompressedClock clock, DesktopPlatform platform, FebeApp app)
|
||||
{
|
||||
Site = site;
|
||||
Folder = folder;
|
||||
Ui = ui;
|
||||
Lines = lines;
|
||||
Clock = clock;
|
||||
Platform = platform;
|
||||
App = app;
|
||||
_client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false })
|
||||
{
|
||||
BaseAddress = app.Address,
|
||||
Timeout = TimeSpan.FromSeconds(30),
|
||||
};
|
||||
}
|
||||
|
||||
public TestSite Site { get; }
|
||||
|
||||
public TestFolder Folder { get; }
|
||||
|
||||
public UiThread Ui { get; }
|
||||
|
||||
/// <summary>What Febe wrote in its log.</summary>
|
||||
public LogLines Lines { get; }
|
||||
|
||||
public CompressedClock Clock { get; }
|
||||
|
||||
public DesktopPlatform Platform { get; }
|
||||
|
||||
public FebeApp App { get; }
|
||||
|
||||
/// <summary>The browser of Febe: WebView2 (Febe.exe never uses another one unless asked with <c>--browser edge</c>).</summary>
|
||||
public WebView2Browser Browser => App.Browser as WebView2Browser ?? throw new AssertFailedException("Il browser della composizione non è WebView2.");
|
||||
|
||||
/// <param name="name">Prefix of the temporary folder.</param>
|
||||
/// <param name="autoLogin"><c>--accesso-di-prova</c>: the composition opens the test site once at start-up.</param>
|
||||
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct)
|
||||
{
|
||||
var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
var folder = new TestFolder(name);
|
||||
var ui = await UiThread.StartAsync();
|
||||
try
|
||||
{
|
||||
var lines = new LogLines();
|
||||
var data = folder.Combine("dati");
|
||||
List<string> arguments =
|
||||
[
|
||||
"--dati", data, "--libreria", folder.Combine("libreria"),
|
||||
"--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--prima-sessione", "1",
|
||||
];
|
||||
if (autoLogin)
|
||||
{
|
||||
arguments.Add("--accesso-di-prova");
|
||||
}
|
||||
|
||||
if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem))
|
||||
{
|
||||
throw new ArgumentException(problem);
|
||||
}
|
||||
|
||||
var zone = TestZones.Noon();
|
||||
var clock = new CompressedClock(10, zone);
|
||||
var shell = new DesktopShell(ui.Dispatcher, null, BrowserShell.Instance);
|
||||
var platform = new DesktopPlatform(options, shell, new MemoryLocations(), dataFolderFixed: true);
|
||||
var appOptions = options.AppOptions(data, new DesktopFolders(folder.Combine("AppData"), folder.Combine("Immagini"))) with { Zone = zone, ZoneId = zone.Id };
|
||||
var hooks = new FebeAppHooks { Clock = clock, Random = new SeededRandom(20261020), Console = lines, ShutdownTimeout = TimeSpan.FromSeconds(1) };
|
||||
var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct);
|
||||
return new DesktopBed(site, folder, ui, lines, clock, platform, app);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await ui.DisposeAsync();
|
||||
folder.Dispose();
|
||||
await site.DisposeAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A request as the main window sends it; the answer must be 200 with JSON.</summary>
|
||||
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json, CancellationToken ct)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, Platform.AccessToken);
|
||||
request.Headers.TryAddWithoutValidation("Origin", $"{App.Address.Scheme}://{App.Address.Authority}");
|
||||
if (json is not null)
|
||||
{
|
||||
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
}
|
||||
|
||||
using var response = await _client.SendAsync(request, ct);
|
||||
var text = await response.Content.ReadAsStringAsync(ct);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
||||
return JsonDocument.Parse(text).RootElement.Clone();
|
||||
}
|
||||
|
||||
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
|
||||
public async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout, string what, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!await condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.\n{Lines.Text}");
|
||||
}
|
||||
|
||||
await Task.Delay(250, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops the composition (the browser of Febe closes on its UI thread), then the UI thread, folders, site.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_client.Dispose();
|
||||
try
|
||||
{
|
||||
await App.DisposeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Ui.DisposeAsync();
|
||||
Folder.Dispose();
|
||||
await Site.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>The «console» of <see cref="Febe.App.FebeLog"/> in a test: the lines Alberto would find in his log.</summary>
|
||||
internal sealed class LogLines : TextWriter
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<string> _lines = [];
|
||||
private readonly StringBuilder _current = new();
|
||||
|
||||
public override Encoding Encoding => Encoding.UTF8;
|
||||
|
||||
public IReadOnlyList<string> Lines
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _lines];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string Text => string.Join('\n', Lines);
|
||||
|
||||
public bool Any(string fragment) => Lines.Any(l => l.Contains(fragment, StringComparison.Ordinal));
|
||||
|
||||
public override void Write(char value)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (value == '\n')
|
||||
{
|
||||
_lines.Add(_current.ToString().TrimEnd('\r'));
|
||||
_current.Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
_current.Append(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void WriteLine(string? value)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_current.Append(value);
|
||||
_lines.Add(_current.ToString());
|
||||
_current.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A temporary folder under <see cref="Path.GetTempPath"/> (TEMP: on Alberto's PC a work folder outside drive C:),
|
||||
/// removed at the end of the test. WebView2 may hold a file of its profile for a moment after it closed: removal is
|
||||
/// retried and a leftover folder is not an error.
|
||||
/// </summary>
|
||||
internal sealed class TestFolder : IDisposable
|
||||
{
|
||||
public TestFolder(string prefix)
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove-windows", prefix + "-" + Guid.NewGuid().ToString("N")[..10]);
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
for (var attempt = 0; attempt < 10; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(Path))
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Thread.Sleep(300);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A UI thread like the one of Febe.exe: an STA thread running a WPF <see cref="System.Windows.Threading.Dispatcher"/>
|
||||
/// (its message pump and its <see cref="DispatcherSynchronizationContext"/>). The browser of Febe is created on it,
|
||||
/// while the test itself — like the engine of Febe — runs on thread-pool threads.
|
||||
/// </summary>
|
||||
internal sealed class UiThread : IAsyncDisposable
|
||||
{
|
||||
private readonly Thread _thread;
|
||||
|
||||
private UiThread(Thread thread, Dispatcher dispatcher)
|
||||
{
|
||||
_thread = thread;
|
||||
Dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
public Dispatcher Dispatcher { get; }
|
||||
|
||||
/// <summary>The managed id of the UI thread (to tell where code ran).</summary>
|
||||
public int ThreadId => _thread.ManagedThreadId;
|
||||
|
||||
public static async Task<UiThread> StartAsync()
|
||||
{
|
||||
var ready = new TaskCompletionSource<Dispatcher>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
ready.SetResult(Dispatcher.CurrentDispatcher);
|
||||
Dispatcher.Run();
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "Febe: thread dell'interfaccia (prove)",
|
||||
};
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
var dispatcher = await ready.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
||||
return new UiThread(thread, dispatcher);
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="action"/> on the UI thread and waits for it.</summary>
|
||||
public Task<T> InvokeAsync<T>(Func<T> action) => Dispatcher.InvokeAsync(action).Task;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (!Dispatcher.HasShutdownStarted)
|
||||
{
|
||||
Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
|
||||
}
|
||||
|
||||
await Task.Run(() => _thread.Join(TimeSpan.FromSeconds(15))).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>Whether these tests can run here: Windows with the WebView2 runtime (the tests are inconclusive otherwise).</summary>
|
||||
internal static class WebView2Runtime
|
||||
{
|
||||
/// <summary>Null when WebView2 can run; otherwise why not, in Italian (the text of the inconclusive result).</summary>
|
||||
public static string? UnavailableReason()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return "Prova solo per Windows: qui non c'è WebView2.";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return InstalledVersion() is null ? "Runtime WebView2 non installato su questo Windows." : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is WebView2RuntimeNotFoundException or DllNotFoundException or BadImageFormatException)
|
||||
{
|
||||
return $"Runtime WebView2 non disponibile ({ex.GetType().Name}).";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The version of the installed WebView2 runtime, e.g. «141.0.3537.71».</summary>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static string? InstalledVersion() => CoreWebView2Environment.GetAvailableBrowserVersionString();
|
||||
|
||||
/// <summary>Marks the test inconclusive where WebView2 cannot run.</summary>
|
||||
public static void Require()
|
||||
{
|
||||
if (UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The start of the browser of Febe on a real Windows (regression of 14 and 19 October 2026: «WebView2 non parte
|
||||
/// (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)» at every
|
||||
/// attempt, for ever). The composition starts the browser from a thread-pool thread; every WebView2 object lives on the
|
||||
/// UI thread of WPF.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class WebView2BrowserStartTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task StartedFromAThreadPoolThreadTheBrowserIsReadyAtTheFirstAttempt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("avvio");
|
||||
|
||||
await bed.StartAsync(ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, "the browser is available once RunAsync returned");
|
||||
Assert.IsNull(bed.Browser.LastError);
|
||||
var ready = bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(1, ready, "one «ready» line: " + bed.Lines.Text);
|
||||
Assert.MatchesRegex(ReadyLine(), ready[0]);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), "no failed attempt: " + bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), "no error at all: " + bed.Lines.Text);
|
||||
|
||||
// The version is a plain value now: it can be read from any thread.
|
||||
var version = await Task.Run(() => bed.Browser.Host.Version, ct);
|
||||
Assert.IsNotNull(version);
|
||||
StringAssert.Contains(ready[0], version);
|
||||
|
||||
// The engine's threads use the page through the session: the command hops to the UI thread and back.
|
||||
Assert.AreEqual("about:blank", await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\[browser\] Browser di Febe pronto: WebView2 \d+\.\d+\.\d+\.\d+, pagina 1280×900, finestra, fuori vista\.$")]
|
||||
private static partial Regex ReadyLine();
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Browser.Capture;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Download;
|
||||
using Febe.Browser.Gestures;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Browser.WebView2;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// S1 on a real Windows (docs/prove-dal-vivo.md, C3): the DevTools protocol of WebView2 through the real
|
||||
/// <see cref="WebView2CdpSession"/> and its allowlist, against the local test site (never Instagram), from thread-pool
|
||||
/// threads as the engine sends it, with the window «Browser di Febe» out of view as it always is.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebView2CdpTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task S1TheProtocolWorksOnTheTestSiteWithTheWindowOutOfView()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("s1");
|
||||
await bed.StartAsync(ct);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
Assert.IsInstanceOfType<WebView2CdpSession>(cdp, "the real session of WebView2, with its allowlist");
|
||||
var clock = new SystemClock();
|
||||
var testSite = CollectionSite.TestSite(site.SiteHost, site.CdnHost);
|
||||
|
||||
await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
// Response bodies: Network.enable and the events are subscribed from this thread, the bodies come
|
||||
// through Network.getResponseBody.
|
||||
var bodies = new BodyCollector();
|
||||
await using var tap = new ResponseTap(cdp, testSite.Hosts, clock);
|
||||
tap.AddConsumer(bodies);
|
||||
await tap.StartAsync(ct);
|
||||
|
||||
// Navigation.
|
||||
var navigation = await cdp.NavigateAsync(site.Url("/profilo/luca.prova/"), ct);
|
||||
Assert.IsTrue(navigation.Succeeded, navigation.ErrorText);
|
||||
Assert.IsTrue(await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(20), ct), "the profile page loaded");
|
||||
await WaitUntilAsync(() => bodies.Paths.Contains("/dati/profilo/luca.prova"), TimeSpan.FromSeconds(20), "il corpo JSON del profilo", ct);
|
||||
var profile = bodies.Json("/dati/profilo/luca.prova");
|
||||
Assert.AreEqual("luca.prova", profile.GetProperty("profilo").GetProperty("nome").GetString());
|
||||
Assert.IsTrue(tap.Stats.JsonBodies >= 1);
|
||||
|
||||
// Read-only Runtime.evaluate: what the page sees, out of view (S2: visible, never «hidden»).
|
||||
var seen = await cdp.EvaluateAsync(
|
||||
"({ visibility: document.visibilityState, hidden: document.hidden, webdriver: navigator.webdriver, width: innerWidth, height: innerHeight, path: location.pathname, tiles: document.querySelectorAll('#griglia a').length })",
|
||||
ct);
|
||||
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
|
||||
Assert.AreEqual("/profilo/luca.prova/", seen.GetProperty("path").GetString());
|
||||
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString(), "out of view the page stays visible (S2)");
|
||||
Assert.IsFalse(seen.GetProperty("hidden").GetBoolean());
|
||||
Assert.IsFalse(seen.GetProperty("webdriver").GetBoolean(), "an ordinary browser: navigator.webdriver is false");
|
||||
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32(), "the page has its fixed width");
|
||||
Assert.IsGreaterThan(0, seen.GetProperty("tiles").GetInt32(), "the page drew the grid from the JSON");
|
||||
|
||||
// The session cookie of the site exists (only its name is looked at).
|
||||
Assert.IsTrue(await SessionCookieProbe.HasSessionCookieAsync(cdp, testSite.SessionCookie, ct));
|
||||
|
||||
// Scrolling with Input.dispatchMouseEvent (mouseWheel), as the recipes do.
|
||||
var height = (await cdp.EvaluateAsync("document.documentElement.scrollHeight", ct)).GetDouble();
|
||||
Assert.IsGreaterThan(seen.GetProperty("height").GetInt32() + 400.0, height, "a page long enough to scroll");
|
||||
Assert.AreEqual(0, (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble());
|
||||
var gestures = new HumanGestures(cdp, clock, new SeededRandom(20261020));
|
||||
await gestures.MoveToAsync(new PagePoint(640, 450), ct);
|
||||
var requested = await gestures.ScrollBurstAsync(ct: ct);
|
||||
await Task.Delay(800, ct);
|
||||
var scrolled = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
|
||||
TestContext.WriteLine($"Scorrimento: chiesti {requested} pixel, pagina scesa di {scrolled}.");
|
||||
Assert.IsGreaterThan(100.0, scrolled, "the wheel really scrolled the page out of view");
|
||||
|
||||
// Page.captureScreenshot: a JPEG of the page, out of view (the preview of Attività).
|
||||
var jpeg = await PagePreview.CaptureAsync(cdp, 60, ct);
|
||||
TestContext.WriteLine($"Fotogramma: {jpeg.Length} byte.");
|
||||
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame, not an empty one");
|
||||
Assert.AreEqual(0xFF, jpeg[0]);
|
||||
Assert.AreEqual(0xD8, jpeg[1]);
|
||||
|
||||
// A file of the CDN through the browser (Network.loadNetworkResource, IO.read, IO.close).
|
||||
var media = FirstCdnAddress(profile, site.CdnUrl) ?? throw new AssertFailedException("nessun indirizzo del CDN nel JSON del profilo");
|
||||
var fetcher = new BrowserFileFetcher(cdp, testSite.Hosts);
|
||||
using var file = new MemoryStream();
|
||||
var fetched = await fetcher.FetchAsync(new Uri(media), file, null, ct);
|
||||
Assert.AreEqual(FetchOutcome.Completed, fetched.Outcome, fetched.Error);
|
||||
Assert.IsGreaterThan(1_000L, fetched.Bytes);
|
||||
Assert.AreEqual(0xFF, file.GetBuffer()[0], "a JPEG of the CDN");
|
||||
var refused = await fetcher.FetchAsync(new Uri(site.Url("/dati/inizio")), Stream.Null, null, ct);
|
||||
Assert.AreEqual(FetchOutcome.HostNotAllowed, refused.Outcome, "only the CDN is downloaded");
|
||||
|
||||
// Forbidden commands are refused before WebView2, and change nothing.
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Emulation.setTimezoneOverride", new JsonObject { ["timezoneId"] = "America/New_York" }, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Network.setUserAgentOverride", new JsonObject { ["userAgent"] = "Febe" }, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = "1" }, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Fetch.enable", null, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Target.createTarget", new JsonObject { ["url"] = "about:blank" }, ct));
|
||||
var before = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.EvaluateAsync("window.scrollBy(0, 500)", ct));
|
||||
await Task.Delay(300, ct);
|
||||
var after = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
|
||||
Assert.IsLessThan(100.0, Math.Abs(after - before), "the refused script did not run (it would have scrolled 500 px)");
|
||||
var zone = (await cdp.EvaluateAsync("Intl.DateTimeFormat().resolvedOptions().timeZone", ct)).GetString();
|
||||
Assert.AreNotEqual("America/New_York", zone);
|
||||
|
||||
// Back to the rest page.
|
||||
await bed.Browser.RestAsync(ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(10), ct);
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await cdp.GetMainFrameUrlAsync(ct));
|
||||
},
|
||||
ct);
|
||||
|
||||
// The log has actions and outcomes only: no signed address of the CDN, no error.
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
private static string? FirstCdnAddress(JsonElement element, string cdnUrl)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (property.Name == "indirizzo" && property.Value.ValueKind == JsonValueKind.String
|
||||
&& property.Value.GetString() is { } address && address.StartsWith(cdnUrl, StringComparison.Ordinal) && address.Contains(".jpg", StringComparison.Ordinal))
|
||||
{
|
||||
return address;
|
||||
}
|
||||
|
||||
if (FirstCdnAddress(property.Value, cdnUrl) is { } found)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (FirstCdnAddress(item, cdnUrl) is { } found)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.");
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The JSON bodies the page received, by path.</summary>
|
||||
private sealed class BodyCollector : IResponseConsumer
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, string> _bodies = new(StringComparer.Ordinal);
|
||||
|
||||
public ICollection<string> Paths => _bodies.Keys;
|
||||
|
||||
public JsonElement Json(string path) => JsonDocument.Parse(_bodies[path]).RootElement.Clone();
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
_bodies.TryAdd(response.Path, body.RootElement.GetRawText());
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Net.Http;
|
||||
using Febe.App;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Desktop.Browser;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// One real collection session of the shared composition (<see cref="FebeApp"/>) running on WebView2, as Febe.exe
|
||||
/// composes it, against the local test site, with files arriving in a temporary library. The Linux suite has the
|
||||
/// equivalent with Chromium (ServerEndToEndTests). Never Instagram: the browser only sees 127.0.0.1.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebView2CollectionTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(420_000, CooperativeCancellation = true)]
|
||||
public async Task ARealSessionOfTheCompositionRunsOnWebView2AndTheFilesArriveInTheLibrary()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopBed.StartAsync("raccolta", autoLogin: true, ct);
|
||||
var app = bed.App;
|
||||
Assert.IsEmpty(app.Problems, string.Join("; ", app.Problems.Select(p => p.Title)));
|
||||
|
||||
// The browser starts from a thread of the composition (the path that failed on Alberto's PC), the pipeline and
|
||||
// the engine follow.
|
||||
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
|
||||
Assert.IsInstanceOfType<WebView2Browser>(app.Browser);
|
||||
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
|
||||
Assert.AreEqual(Febe.Web.Connection.ConnectionState.Connected, (await app.Connection!.GetStatusAsync(ct)).State, "the test site's automatic login");
|
||||
|
||||
// Accounts and «Controlla ora» through the interface, as from the main window.
|
||||
var added = await bed.JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}""", ct);
|
||||
Assert.AreEqual(2, added.GetProperty("added").GetInt32());
|
||||
var marta = await app.Database.Accounts.FindByUsernameAsync("marta.prova", ct) ?? throw new AssertFailedException("marta.prova manca");
|
||||
var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", null, ct);
|
||||
if (check.GetProperty("status").GetString() == "needsConfirmation")
|
||||
{
|
||||
check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""", ct);
|
||||
}
|
||||
|
||||
Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString());
|
||||
|
||||
// A session of the engine acts on the site through WebView2: every action has its Governor's permit.
|
||||
await bed.WaitUntilAsync(
|
||||
async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id),
|
||||
TimeSpan.FromSeconds(120),
|
||||
"un'azione del motore su marta.prova nel registro delle azioni",
|
||||
ct);
|
||||
|
||||
// Files arrive in the library, complete, downloaded through the browser from the test site's CDN.
|
||||
var library = app.Library ?? throw new AssertFailedException("nessuna libreria");
|
||||
List<Media> stored = [];
|
||||
await bed.WaitUntilAsync(
|
||||
async () =>
|
||||
{
|
||||
stored = await StoredAsync(app, marta.Id, ct);
|
||||
return stored.Count >= 3;
|
||||
},
|
||||
TimeSpan.FromSeconds(180),
|
||||
"tre file di marta.prova nella libreria",
|
||||
ct);
|
||||
foreach (var media in stored)
|
||||
{
|
||||
var path = library.FullPath(marta, media.RelativePath!);
|
||||
Assert.IsTrue(File.Exists(path), path);
|
||||
Assert.AreEqual(media.Bytes, new FileInfo(path).Length, path);
|
||||
StringAssert.StartsWith(path, bed.Folder.Path, "inside the temporary library");
|
||||
}
|
||||
|
||||
var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct);
|
||||
Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session");
|
||||
TestContext.WriteLine($"File di marta.prova: {stored.Count}; azioni: {actions.Count}; CDN: {bed.Site.Control.CdnFilesServed} file serviti.");
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), "the browser never failed to start");
|
||||
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
|
||||
}
|
||||
|
||||
private static async Task<List<Media>> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
|
||||
{
|
||||
var list = new List<Media>();
|
||||
foreach (var entry in await app.Database.Entries.ListByAccountAsync(accountId, null, ct))
|
||||
{
|
||||
foreach (var media in await app.Database.Media.ListByEntryAsync(entry.Id, ct))
|
||||
{
|
||||
if (media.State == MediaState.Downloaded && media.RelativePath is not null && media.Sha256 is not null && entry.Kind != EntryKind.ProfilePicture)
|
||||
{
|
||||
list.Add(media);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Windows.Support;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The login on Windows through the real connection service of the composition (spec §4.1, docs/windows.md «Il primo
|
||||
/// collegamento a Instagram»), on WebView2 and the test site: «Accedi a Instagram» opens the login page in the window
|
||||
/// «Browser di Febe», which comes on screen while the engine is still; «Ho finito» checks the session (the cookie's name
|
||||
/// only) and puts the window back out of view; «Scollega» deletes the profile with the session and the browser comes
|
||||
/// back empty. The window comes on screen for a moment, as for Alberto.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebView2ConnectionTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(240_000, CooperativeCancellation = true)]
|
||||
public async Task TheLoginBringsTheWindowAndScollegaEmptiesTheProfile()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopBed.StartAsync("collegamento", autoLogin: false, ct);
|
||||
var app = bed.App;
|
||||
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
|
||||
var connection = app.Connection!;
|
||||
var browser = bed.Browser;
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State, "a new profile is not connected");
|
||||
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
|
||||
|
||||
// «Accedi a Instagram» (here the test site's welcome page, whose first visit starts its session).
|
||||
await connection.BeginUserDrivingAsync(openLogin: true, ct);
|
||||
var driving = await connection.GetStatusAsync(ct);
|
||||
Assert.IsTrue(driving.UserIsDriving);
|
||||
Assert.IsTrue(browser.UserIsDriving, "the engine is still while Alberto is at the browser");
|
||||
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "the window «Browser di Febe» came on screen");
|
||||
StringAssert.StartsWith(driving.CurrentUrl, bed.Site.SiteUrl, "the login page of the configured site, never Instagram in tests");
|
||||
|
||||
// «Ho finito».
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsTrue(finish.Connected, finish.Message);
|
||||
Assert.IsFalse(browser.UserIsDriving, "«Ho finito» ends the driving");
|
||||
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "and puts the window back out of view");
|
||||
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
|
||||
Assert.IsNotNull(await app.Database.Settings.GetInt64Async(Febe.App.BrowserConnectionService.FirstConnectionKey, ct), "first connection recorded");
|
||||
|
||||
// «Scollega»: engine stopped, WebView2 closed, profile deleted, browser started again empty, engine started again.
|
||||
var marker = Path.Combine(browser.ProfileDirectory, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
await connection.DisconnectAsync(ct);
|
||||
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
|
||||
Assert.IsTrue(browser.IsAvailable, "the browser runs again, with an empty profile");
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State);
|
||||
Assert.IsFalse(browser.UserIsDriving);
|
||||
await bed.WaitUntilAsync(() => Task.FromResult(app.Engine!.Services.Runtime.IsRunning), TimeSpan.FromSeconds(10), "il motore di nuovo in funzione", ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Lines.Any("«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto."), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The life of the browser of Febe on a real Windows, driven from thread-pool threads as the composition and the
|
||||
/// connection service drive it: a start that really fails is retried (and only that), the window comes on screen and
|
||||
/// goes away with the «driving» lease (the login), «Scollega» empties the profile and the browser comes back, a browser
|
||||
/// process that dies is started again, and the second hosting of S2 (composition) starts and draws.
|
||||
/// </summary>
|
||||
/// <remarks>Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does.</remarks>
|
||||
[TestClass]
|
||||
public sealed class WebView2LifecycleTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task AStartThatReallyFailsIsRetriedAndThenTheBrowserIsReady()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("tentativi");
|
||||
|
||||
// A file where the profile folder must go: WebView2 cannot start.
|
||||
var profile = bed.Browser.ProfileDirectory;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
|
||||
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
|
||||
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("non parte"), TimeSpan.FromSeconds(30), "il primo avvio non riuscito", ct);
|
||||
Assert.IsFalse(bed.Browser.IsAvailable);
|
||||
StringAssert.StartsWith(bed.Browser.LastError, "WebView2 non parte (IOException:");
|
||||
StringAssert.EndsWith(bed.Lines.Lines.Single(l => l.Contains("non parte", StringComparison.Ordinal)), "Nuovo tentativo fra 5 s.");
|
||||
|
||||
// The obstacle goes away: the next attempt, 5 s later, works.
|
||||
File.Delete(profile);
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
Assert.IsNull(bed.Browser.LastError);
|
||||
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("non parte", StringComparison.Ordinal)), "one failed attempt only");
|
||||
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)));
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheWindowComesOnScreenWithTheLeaseAndGoesAwayWithIt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("finestra");
|
||||
await bed.StartAsync(ct);
|
||||
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "the window is open");
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen), "after the start it is parked out of view");
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
|
||||
// «Accedi a Instagram» / «Portalo in primo piano», from the connection service's thread.
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen), "the window came on screen");
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving, "while it is in front the engine is still");
|
||||
Assert.IsNotNull(bed.Tracker.LastUsedAt, "using it counts for «Riprendi»");
|
||||
|
||||
// «Ho finito».
|
||||
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
|
||||
// Closing the window is «ho finito» too: out of view, still open, still painting.
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving);
|
||||
await bed.OnUiAsync(() =>
|
||||
{
|
||||
window.Close();
|
||||
return true;
|
||||
});
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "closing it never closes it");
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(bed.Browser.Cdp, 50, ct), ct);
|
||||
Assert.AreEqual(0xFF, jpeg[0], "the page still draws out of view");
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task ScollegaDeletesTheProfileWithTheSessionAndTheBrowserComesBackEmpty()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("scollega");
|
||||
await bed.StartAsync(ct);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
var cookie = CollectionSite.TestSite(site.SiteHost, site.CdnHost).SessionCookie;
|
||||
var clock = new SystemClock();
|
||||
|
||||
// «Collegato»: the site's session cookie is in the profile.
|
||||
await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await cdp.NavigateAsync(site.Url("/"), ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
|
||||
},
|
||||
ct);
|
||||
Assert.IsTrue(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "connected to the test site");
|
||||
var marker = Path.Combine(bed.Browser.ProfileDirectory, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
var before = bed.Browser.Host.BrowserProcessId;
|
||||
|
||||
// «Scollega», from the connection service's thread.
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, "the browser runs again");
|
||||
Assert.AreNotEqual(before, bed.Browser.Host.BrowserProcessId, "with a new browser process");
|
||||
Assert.IsFalse(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "the session went with the profile");
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
Assert.IsTrue(bed.Lines.Any("Profilo del browser cancellato; il browser è ripartito vuoto."));
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Regression (review of 20 October 2026): «Scollega» while the first start waits for its next attempt started the
|
||||
/// browser, then the waiting attempt started a second WebView in the same window without closing the first. The
|
||||
/// orphan kept its browser process alive on the profile: the next «Scollega» waited 15 s for nothing and could not
|
||||
/// delete the profile (the Instagram session stayed on disk), and exiting waited 15 s more.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task ScollegaWhileTheFirstStartWaitsToRetryLeavesOneWebViewAndTheNextScollegaWorks()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("scollega-nei-tentativi");
|
||||
|
||||
// A file where the profile folder must go: the first start fails, and fails again 5 s later.
|
||||
var profile = bed.Browser.ProfileDirectory;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
|
||||
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("Nuovo tentativo fra 15 s."), TimeSpan.FromSeconds(40), "il secondo avvio non riuscito", ct);
|
||||
File.Delete(profile);
|
||||
|
||||
// «Scollega» while RunAsync waits 15 s for its third attempt: the browser starts with it.
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, bed.Lines.Text);
|
||||
var pid = bed.Browser.Host.BrowserProcessId;
|
||||
|
||||
// The waiting attempt finds the browser running: no second WebView, the one of «Scollega» untouched.
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(40), ct);
|
||||
var children = await bed.ChildWindowsAsync();
|
||||
Assert.HasCount(1, children, "one WebView in the window: " + string.Join(", ", children));
|
||||
Assert.AreEqual(pid, bed.Browser.Host.BrowserProcessId, "the browser process of «Scollega» is still the one in use");
|
||||
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
|
||||
// The next «Scollega»: the only browser process exits at once, the profile goes, the browser comes back.
|
||||
var marker = Path.Combine(profile, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
var watch = Stopwatch.StartNew();
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
TestContext.WriteLine($"Secondo «Scollega»: {watch.Elapsed.TotalSeconds:0.0} s.");
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "no wait for a browser process that never exits");
|
||||
Assert.IsFalse(File.Exists(marker), "the profile with the session was deleted");
|
||||
Assert.HasCount(1, await bed.ChildWindowsAsync());
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
|
||||
// Exiting closes the only WebView and its process exits: no wait in vain.
|
||||
watch.Restart();
|
||||
await bed.Browser.DisposeAsync();
|
||||
TestContext.WriteLine($"Arresto: {watch.Elapsed.TotalSeconds:0.0} s.");
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "exiting waits for nothing");
|
||||
Assert.HasCount(2, bed.Lines.Lines.Where(l => l.Contains("ERRORE", StringComparison.Ordinal)), "only the two failed starts: " + bed.Lines.Text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Esci» while the start does not complete (review of 20 October 2026): the composition awaits
|
||||
/// <see cref="Febe.Desktop.Browser.WebView2Browser.RunAsync"/> before it closes the browser, so RunAsync must stop
|
||||
/// waiting as soon as it is cancelled. Here the UI thread is kept busy, as when WebView2 does not answer.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task OnExitTheStartStopsWaitingForAUiThreadThatDoesNotAnswer()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("uscita");
|
||||
var released = false;
|
||||
var busy = bed.Ui.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
// Thread.Sleep does not pump: nothing else runs on the UI thread meanwhile.
|
||||
var until = DateTime.UtcNow.AddSeconds(60);
|
||||
while (!Volatile.Read(ref released) && DateTime.UtcNow < until)
|
||||
{
|
||||
Thread.Sleep(20);
|
||||
}
|
||||
});
|
||||
|
||||
using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(lifetime.Token), ct);
|
||||
await Task.Delay(500, ct);
|
||||
Assert.IsFalse(run.IsCompleted, "the start waits for the UI thread");
|
||||
|
||||
// «Esci»: FebeApp cancels its lifetime, then waits for RunAsync.
|
||||
var watch = Stopwatch.StartNew();
|
||||
await lifetime.CancelAsync();
|
||||
try
|
||||
{
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref released, true);
|
||||
await busy.Task;
|
||||
}
|
||||
|
||||
TestContext.WriteLine($"RunAsync è tornato {watch.Elapsed.TotalSeconds:0.0} s dopo la cancellazione.");
|
||||
Assert.IsLessThan(3, watch.Elapsed.TotalSeconds, "RunAsync stops waiting at once");
|
||||
Assert.IsFalse(bed.Browser.IsAvailable);
|
||||
|
||||
// The start that was waiting for the UI thread does not begin after the exit, and stopping is quick.
|
||||
watch.Restart();
|
||||
await bed.Browser.DisposeAsync();
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds);
|
||||
Assert.IsNull(await bed.OnUiAsync(() => bed.Browser.Host.Window), "no window was created after the exit");
|
||||
Assert.AreEqual(0, bed.Browser.Host.BrowserProcessId, "no browser process was started after the exit");
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("Browser di Febe pronto"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task WhenItsBrowserProcessDiesTheBrowserStartsAgainByItself()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("arresto");
|
||||
await bed.StartAsync(ct);
|
||||
var reconnected = 0;
|
||||
bed.Browser.Host.Connection.Reconnected += (_, _) => Interlocked.Increment(ref reconnected);
|
||||
|
||||
// The browser process this test started — by its id, never by name.
|
||||
var pid = bed.Browser.Host.BrowserProcessId;
|
||||
Assert.AreNotEqual(0, pid);
|
||||
using (var process = Process.GetProcessById(pid))
|
||||
{
|
||||
Assert.AreEqual("msedgewebview2", process.ProcessName, "the browser process of WebView2");
|
||||
process.Kill();
|
||||
}
|
||||
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("Browser di Febe ripartito: WebView2 "), TimeSpan.FromSeconds(90), "la ripartenza del browser", ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Lines.Any("WebView2: processo terminato (BrowserProcessExited)."));
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
Assert.AreNotEqual(pid, bed.Browser.Host.BrowserProcessId, "a new browser process");
|
||||
Assert.AreEqual(1, Volatile.Read(ref reconnected), "the subscriptions of the session moved to the new WebView once");
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), "the new start worked at once");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheCompositionHostingOfS2StartsAndDrawsThePage()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("composizione", BrowserHosting.Composition);
|
||||
await bed.StartAsync(ct);
|
||||
Assert.IsTrue(bed.Lines.Any(", composizione, fuori vista."), bed.Lines.Text);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
var clock = new SystemClock();
|
||||
|
||||
var seen = await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await cdp.NavigateAsync(site.Url("/profilo/marta.prova/"), ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
|
||||
return await cdp.EvaluateAsync("({ visibility: document.visibilityState, width: innerWidth, height: innerHeight })", ct);
|
||||
},
|
||||
ct);
|
||||
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
|
||||
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString());
|
||||
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32());
|
||||
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(cdp, 60, ct), ct);
|
||||
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame");
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,9 @@ public sealed class HostingTests
|
||||
var args = ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions());
|
||||
|
||||
CollectionAssert.Contains(args.ToList(), "--remote-debugging-port=9333");
|
||||
CollectionAssert.Contains(args.ToList(), "--user-data-dir=/tmp/febe-profilo");
|
||||
|
||||
// The profile reaches Chromium as a full path: «/tmp/febe-profilo» on Linux, rooted on the current drive on Windows.
|
||||
CollectionAssert.Contains(args.ToList(), $"--user-data-dir={Path.GetFullPath(Options.ProfileDirectory)}");
|
||||
CollectionAssert.Contains(args.ToList(), "--no-first-run");
|
||||
CollectionAssert.Contains(args.ToList(), "--no-default-browser-check");
|
||||
CollectionAssert.Contains(args.ToList(), "--window-size=1280,900");
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The remote view started while the page is between two documents (Gitea issue #3), on a real Chromium on Xvfb and the
|
||||
/// local test site. From <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until its commit,
|
||||
/// DevTools points at the new, not yet active document and Chromium refuses <c>Page.startScreencast</c> with -32000
|
||||
/// «Not attached to an active page». That moment lasts milliseconds in real use; here a page keeps its renderer busy, so
|
||||
/// a navigation away from it to a page of the same site waits to commit for over a second and the start lands in it on
|
||||
/// purpose. The view must open once the new document has committed and show its frames. If Chromium ever answers that
|
||||
/// moment with another text or code, the start fails here, on the CI, and not in Alberto's hands.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Seen with Chrome 155 on the development machine (a standalone CDP experiment, same pages): the start was refused in
|
||||
/// every round to a page of the same site and went through once the new document had committed. A navigation to
|
||||
/// about:blank from a site page commits in another renderer, which is not busy, so it is not used here. And a view opened
|
||||
/// through the host after a navigation has begun does not meet the refusal at all: its <c>Page.getFrameTree</c> is answered
|
||||
/// only once that navigation has committed (see ServerEndToEndTests.AViewOpenedWhileThePageIsNavigating…).
|
||||
/// </remarks>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public sealed class RemoteViewDuringNavigationTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireBrowser()
|
||||
{
|
||||
if (RealBrowser.UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task AViewStartedBeforeTheNewDocumentCommitsOpensOnceItHasCommitted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var browser = await RealBrowser.StartAsync();
|
||||
var cdp = browser.Cdp;
|
||||
|
||||
const int rounds = 6;
|
||||
var refusedRounds = 0;
|
||||
for (var round = 0; round < rounds; round++)
|
||||
{
|
||||
// Page.navigate answers once the new document is ready to commit; the busy page commits a moment later and its
|
||||
// script holds the renderer from 0.1 s after that, for 2 s.
|
||||
var busy = await cdp.NavigateAsync(browser.Site.Url("/occupata"), ct);
|
||||
Assert.IsTrue(busy.Succeeded, busy.ErrorText);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(500), ct);
|
||||
|
||||
// The login page of the site, as «Accedi a Instagram» opens it: ready to commit at once, committed only when
|
||||
// the busy script lets go.
|
||||
var navigation = cdp.NavigateAsync(browser.Site.Url($"/accesso?giro={round}"), ct);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
|
||||
|
||||
var notes = new ConcurrentQueue<string>();
|
||||
var log = new DelegateBrowserLog((level, message, _) =>
|
||||
{
|
||||
if (level == BrowserLogLevel.Debug)
|
||||
{
|
||||
notes.Enqueue(message);
|
||||
}
|
||||
});
|
||||
var view = new RemoteViewSession(cdp, browser.Host.UserDriving, log);
|
||||
try
|
||||
{
|
||||
var watch = Stopwatch.StartNew();
|
||||
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900), ct);
|
||||
watch.Stop();
|
||||
var navigated = await navigation;
|
||||
Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}");
|
||||
Assert.IsTrue(browser.Host.UserIsDriving, $"Round {round}: the open view holds the browser.");
|
||||
|
||||
// Only the attempt number is in the note (ScreencastSession): «… al tentativo N, dopo un cambio di pagina.»
|
||||
var retry = notes.FirstOrDefault(n => n.Contains("tentativo", StringComparison.Ordinal));
|
||||
if (retry is not null)
|
||||
{
|
||||
refusedRounds++;
|
||||
}
|
||||
|
||||
TestContext.WriteLine($"Giro {round}: vista aperta in {watch.ElapsedMilliseconds} ms; {retry ?? "fotogrammi avviati al primo tentativo."}");
|
||||
|
||||
// The frames of the new document: an animated page repaints all the time.
|
||||
var animated = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct);
|
||||
Assert.IsTrue(animated.Succeeded, animated.ErrorText);
|
||||
Assert.IsTrue(await JpegArrivesAsync(view.Screencast, ct), $"Round {round}: frames after the view opened.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
Assert.IsFalse(browser.Host.UserIsDriving, $"Round {round}: the closed view released the browser.");
|
||||
}
|
||||
|
||||
TestContext.WriteLine($"Giri in cui Chromium ha rifiutato il primo avvio con «{CdpCommandException.InactivePageMessage}»: {refusedRounds} su {rounds}.");
|
||||
if (refusedRounds == 0)
|
||||
{
|
||||
// Every view opened: the product is fine, but the start never met the refusal, so the retry was not exercised.
|
||||
Assert.Inconclusive("La vista si è aperta in ogni giro, ma Chromium non ha mai rifiutato il primo avvio: la prova non ha raggiunto il momento fra «ready to commit» e il commit (pagina /occupata, versione di Chromium) e il ritentativo non è stato messo alla prova.");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> JpegArrivesAsync(ScreencastSession screencast, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
try
|
||||
{
|
||||
await foreach (var frame in screencast.ReadFramesAsync(timeout.Token))
|
||||
{
|
||||
return frame.Jpeg is [0xFF, 0xD8, ..];
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -202,6 +202,10 @@ public sealed class LocalTestSite : IDisposable
|
||||
"/spa" => "<p>Applicazione</p><script>addEventListener('load', () => setTimeout(() => history.pushState({}, '', '/verifica/interna?x=1'), 300));</script>",
|
||||
"/verifica" => "<h1>Verifica</h1>",
|
||||
"/accesso" => "<h1>Accesso</h1>",
|
||||
|
||||
// Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the
|
||||
// same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go.
|
||||
"/occupata" => "<p>Occupata</p><script>setTimeout(() => { const end = performance.now() + 2000; while (performance.now() < end) { } }, 100);</script>",
|
||||
_ => "<p>Pagina di prova</p>",
|
||||
};
|
||||
|
||||
|
||||
@@ -112,10 +112,10 @@ public sealed partial class InstallerTests
|
||||
StringAssert.Contains(text, "100 * 1024 * 1024");
|
||||
Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR");
|
||||
|
||||
var bash = FindOnPath("bash");
|
||||
var bash = FindBash();
|
||||
if (bash is null)
|
||||
{
|
||||
return;
|
||||
Assert.Inconclusive("Manca bash (su Windows: Git Bash): la prova della sintassi di costruisci.sh si salta.");
|
||||
}
|
||||
|
||||
using var process = Process.Start(new ProcessStartInfo(bash, ["-n", script]) { RedirectStandardError = true })!;
|
||||
@@ -124,21 +124,69 @@ public sealed partial class InstallerTests
|
||||
Assert.AreEqual(0, process.ExitCode, errors);
|
||||
}
|
||||
|
||||
private static string? FindOnPath(string name)
|
||||
private static string? FindOnPath(string name) => OnPath(name).FirstOrDefault();
|
||||
|
||||
/// <summary>
|
||||
/// A bash that checks the script on this system. Elsewhere than Windows, the first on PATH. On Windows Git Bash
|
||||
/// first (next to git on PATH, then where its installer puts it), else any bash on PATH except the WSL launcher:
|
||||
/// <c>System32\bash.exe</c> and the <c>WindowsApps</c> alias start a Linux distribution, which may be missing
|
||||
/// («execvpe(/bin/bash) failed») and does not see the script by its Windows path.
|
||||
/// </summary>
|
||||
private static string? FindBash()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return FindOnPath("bash");
|
||||
}
|
||||
|
||||
var roots = new List<string>();
|
||||
if (FindOnPath("git") is { } git)
|
||||
{
|
||||
// git.exe sits in <Git>\cmd, <Git>\bin or <Git>\mingw64\bin.
|
||||
for (var folder = Path.GetDirectoryName(git); folder is not null && roots.Count < 3; folder = Path.GetDirectoryName(folder))
|
||||
{
|
||||
roots.Add(folder);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var variable in new[] { "ProgramW6432", "ProgramFiles", "ProgramFiles(x86)" })
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable(variable) is { Length: > 0 } programs)
|
||||
{
|
||||
roots.Add(Path.Combine(programs, "Git"));
|
||||
}
|
||||
}
|
||||
|
||||
roots.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Git"));
|
||||
var gitBash = roots
|
||||
.SelectMany(root => new[] { Path.Combine(root, "bin", "bash.exe"), Path.Combine(root, "usr", "bin", "bash.exe") })
|
||||
.FirstOrDefault(path => File.Exists(path) && !IsWslLauncher(path));
|
||||
return gitBash ?? OnPath("bash").FirstOrDefault(path => !IsWslLauncher(path));
|
||||
}
|
||||
|
||||
private static bool IsWslLauncher(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
var windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
|
||||
return (windows.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(windows) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
|| full.Contains(@"\Microsoft\WindowsApps\", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>Every file called <paramref name="name"/> on PATH, in order (on Windows only <c>.exe</c>: the others do not start).</summary>
|
||||
private static IEnumerable<string> OnPath(string name)
|
||||
{
|
||||
var candidates = OperatingSystem.IsWindows() ? new[] { name + ".exe" } : new[] { name, name + ".exe" };
|
||||
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
foreach (var candidate in new[] { name, name + ".exe" })
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
var path = Path.Combine(folder, candidate);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return path;
|
||||
yield return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?<target>[^""]+)""", RegexOptions.Multiline)]
|
||||
|
||||
@@ -286,6 +286,26 @@ public sealed class WebView2CdpSessionTests
|
||||
CollectionAssert.AreEqual(new[] { "uno", "due" }, received.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFailingReconnectionHandlerDoesNotUndoTheAttach()
|
||||
{
|
||||
// Attach runs inside the start of the new WebView: an error of whoever listens must not turn a start that worked
|
||||
// into a failed one, retried with the same outcome for ever.
|
||||
var log = new RecordingBrowserLog();
|
||||
await using var session = new WebView2CdpSession(log);
|
||||
var later = 0;
|
||||
session.Reconnected += (_, _) => throw new InvalidOperationException("guasto di chi ascolta");
|
||||
session.Reconnected += (_, _) => later++;
|
||||
|
||||
session.Attach(new FakeDevTools());
|
||||
session.Attach(new FakeDevTools());
|
||||
|
||||
Assert.IsTrue(session.IsAttached, "the new WebView stays attached");
|
||||
Assert.AreEqual(1, later, "the other handlers still hear of it");
|
||||
Assert.IsTrue(log.Lines.Any(l => l.StartsWith("Warning ", StringComparison.Ordinal) && l.Contains("InvalidOperationException", StringComparison.Ordinal)), log.All);
|
||||
Assert.AreEqual("{}", (await session.SendAsync("Page.enable", ct: TestContext.CancellationToken)).GetRawText());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ProtocolErrorsAreReadFromTheMessageOfWebView2()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Alerts.Support;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Web.Api;
|
||||
|
||||
namespace Febe.Tests.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers:
|
||||
/// the real recipes on the scripted site (no browser) under the real engine, and the runs that end otherwise right
|
||||
/// after the last page.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class BackfillCompletedTests
|
||||
{
|
||||
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
|
||||
/// <summary>Found testing Febe for Windows on the test site: two lines in «Avvisi» for one history, at 14:31.</summary>
|
||||
[TestMethod]
|
||||
public async Task AHistoryCompletedByTheRecipesIsOneLineOfAvvisiWithItsNumbersAndOneNotification()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(start: Morning);
|
||||
var engine = bed.Engine;
|
||||
var (runner, site) = RealRecipes(engine);
|
||||
var marta = site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false });
|
||||
marta.Posts.AddRange(ScriptedBed.Posts(0, 18, Morning.AddDays(-30)));
|
||||
var account = await AddBackfillingAsync(engine, marta, postCount: 18);
|
||||
|
||||
engine.Start(runner);
|
||||
await engine.RunUntilAsync(Morning.AddDays(2));
|
||||
await engine.StopAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
|
||||
const string Expected = "Storico di @marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato.";
|
||||
var done = await engine.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.IsNotNull(done!.BackfillCompletedAt, "The history reached the beginning of the profile.");
|
||||
Assert.AreEqual(AccountState.UpToDate, done.State);
|
||||
Assert.HasCount(18, await engine.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 }));
|
||||
|
||||
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
|
||||
Assert.HasCount(1, lines, "One line for one history: " + string.Join(" | ", lines.Select(e => e.Message)));
|
||||
Assert.AreEqual(Expected, lines[0].Message);
|
||||
Assert.AreEqual(EventSeverity.Success, lines[0].Severity);
|
||||
Assert.AreEqual(account.Id, lines[0].AccountId);
|
||||
Assert.IsNotNull(lines[0].SessionId);
|
||||
|
||||
// The «Avvisi» list of Attività.
|
||||
var alerts = (await ActivityApi.AlertsAsync(engine.Db, engine.Clock, CancellationToken.None)).Items.Where(i => i.Kind == "backfillDone").ToList();
|
||||
Assert.HasCount(1, alerts);
|
||||
Assert.AreEqual(Expected, alerts[0].Message);
|
||||
|
||||
// One Windows notification and one Telegram message, with the same full text.
|
||||
var notification = bed.Shell.Notifications.Single(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone));
|
||||
Assert.AreEqual(Expected, notification.Message);
|
||||
var telegram = bed.Telegram.Requests.Where(r => r.Text.StartsWith("Febe · Storico completato\n", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(1, telegram);
|
||||
Assert.AreEqual("Febe · Storico completato\n" + Expected, telegram[0].Text);
|
||||
Assert.HasCount(1, bed.Outcomes.Where(o => o.Alert.Kind == AlertKind.BackfillDone), "Nothing held back as a repeat either.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A run that completes the history: the walk reached the beginning of the profile and stored it, then a signal or
|
||||
/// a cancellation changed how the run ended; or a profile check found the whole profile on its first page. The
|
||||
/// history is closed with its line (it would never be walked again), and right after that run the Coda shows
|
||||
/// nothing planned for the account, now paused: no «Storico» put back in the queue (review F3).
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[DataRow(RecipeKind.Backfill, RecipeStatus.StoppedBySignal)]
|
||||
[DataRow(RecipeKind.Backfill, RecipeStatus.Cancelled)]
|
||||
[DataRow(RecipeKind.ProfileCheck, RecipeStatus.Completed)]
|
||||
public async Task AHistoryCompletedByARunIsClosedWithItsLineAndLeavesNothingInTheQueue(RecipeKind kind, RecipeStatus status)
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(start: Morning);
|
||||
var engine = bed.Engine;
|
||||
var account = await engine.AddAccountAsync("luca.prova", followed: true, state: AccountState.Backfilling, postCount: 30);
|
||||
await engine.Db.Accounts.UpdateAsync((await engine.Db.Accounts.GetAsync(account.Id))! with { KeepUpdated = false });
|
||||
var runner = new ScriptedRunner(engine.Governor, engine.Clock);
|
||||
RecipeRequest? closing = null;
|
||||
var walksAfter = 0;
|
||||
runner.Before = async r =>
|
||||
{
|
||||
if (r.AccountId != account.Id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (closing is not null)
|
||||
{
|
||||
walksAfter += r.Kind == RecipeKind.Backfill ? 1 : 0;
|
||||
}
|
||||
else if (r.Kind == kind)
|
||||
{
|
||||
// What the recipe stores: the walk met the end of the list, or the whole profile is on its first page.
|
||||
await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now);
|
||||
closing = r;
|
||||
}
|
||||
};
|
||||
runner.Script = r => ReferenceEquals(r, closing) ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } : null;
|
||||
engine.Start(runner);
|
||||
var end = Morning.AddDays(2);
|
||||
while (closing is null && engine.Clock.Now < end)
|
||||
{
|
||||
await engine.RunForAsync(TimeSpan.FromMinutes(1));
|
||||
}
|
||||
|
||||
// Right after that run, before the next session tidies the queue.
|
||||
Assert.IsNotNull(closing);
|
||||
var queued = (await engine.Db.Tasks.ListPendingAsync(1000)).Where(t => t.AccountId == account.Id).ToList();
|
||||
Assert.HasCount(0, queued, "Planned for a paused account: " + string.Join(", ", queued.Select(t => $"{t.Kind} «{t.LastError}»")));
|
||||
|
||||
await engine.RunUntilAsync(end);
|
||||
await engine.StopAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
|
||||
Assert.AreEqual(0, walksAfter, "Never walked again.");
|
||||
var finished = await engine.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused.");
|
||||
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
|
||||
Assert.HasCount(1, lines);
|
||||
Assert.AreEqual("Storico di @luca.prova completato: 0 post in libreria. «Tieni aggiornato» è spento: l'account resta in pausa.", lines[0].Message);
|
||||
Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A profile that fits on its first page: the profile check completes its history. When the walk of the session
|
||||
/// went to another account «Storico in corso», the small one stayed so for ever, with no line and no alert (review
|
||||
/// F1). Added first, the small one is the walk's next pick in that very session: it must not get a second line.
|
||||
/// An account that keeps only the new posts has no history to announce.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task AHistoryCompletedByTheProfileCheckIsClosedAtOnceWithOneLine(bool smallFirst)
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(start: Morning);
|
||||
var engine = bed.Engine;
|
||||
var (runner, site) = RealRecipes(engine);
|
||||
var big = site.Add(new ScriptedAccount("3003", "grande.prova") { Followed = false });
|
||||
big.Posts.AddRange(ScriptedBed.Posts(0, 400, Morning.AddDays(-30), prefix: "g"));
|
||||
var small = site.Add(new ScriptedAccount("4004", "piccolo.prova") { Followed = false });
|
||||
small.Posts.AddRange(ScriptedBed.Posts(0, 5, Morning.AddDays(-30), prefix: "s"));
|
||||
var news = site.Add(new ScriptedAccount("5005", "nuovi.prova") { Followed = false });
|
||||
news.Posts.AddRange(ScriptedBed.Posts(0, 3, Morning.AddDays(-30), prefix: "n"));
|
||||
|
||||
// Among the accounts «Storico in corso» the walk takes the lowest id first.
|
||||
Account smallAccount;
|
||||
if (smallFirst)
|
||||
{
|
||||
smallAccount = await AddBackfillingAsync(engine, small, postCount: 5);
|
||||
await AddBackfillingAsync(engine, big, postCount: 400);
|
||||
}
|
||||
else
|
||||
{
|
||||
await AddBackfillingAsync(engine, big, postCount: 400);
|
||||
smallAccount = await AddBackfillingAsync(engine, small, postCount: 5);
|
||||
}
|
||||
|
||||
var newsAccount = await engine.Db.Accounts.AddAsync(Account.Create(news.Username, StartingPoint.OnlyNewFromToday, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with
|
||||
{
|
||||
InstagramId = news.Id,
|
||||
IsFollowed = news.Followed,
|
||||
ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos,
|
||||
PostCount = 3,
|
||||
});
|
||||
Assert.AreEqual(AccountState.UpToDate, newsAccount.State);
|
||||
|
||||
engine.Start(runner);
|
||||
await engine.RunUntilAsync(Morning.AddDays(4));
|
||||
await engine.StopAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
|
||||
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
|
||||
var all = string.Join(" | ", lines.Select(e => e.Message));
|
||||
var done = await engine.Db.Accounts.GetAsync(smallAccount.Id);
|
||||
Assert.IsNotNull(done!.BackfillCompletedAt, "The whole profile is on its first page.");
|
||||
Assert.AreEqual(AccountState.UpToDate, done.State, all);
|
||||
const string Expected = "Storico di @piccolo.prova completato: 5 post in libreria. Da ora lo tengo aggiornato.";
|
||||
Assert.HasCount(1, lines.Where(e => e.AccountId == smallAccount.Id).ToList(), all);
|
||||
Assert.AreEqual(Expected, lines.Single(e => e.AccountId == smallAccount.Id).Message);
|
||||
Assert.AreEqual(1, bed.Shell.Notifications.Count(n => n.Message == Expected));
|
||||
|
||||
Assert.IsFalse(lines.Any(e => e.AccountId == newsAccount.Id), "«Solo i nuovi»: no history. " + all);
|
||||
Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(newsAccount.Id))!.State);
|
||||
Assert.IsTrue(lines.GroupBy(e => e.AccountId).All(g => g.Count() == 1), "One line per history: " + all);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An account «Storico in corso» whose history is already complete (a profile check closed it and Febe stopped
|
||||
/// before recording the outcome, or a version that left it so): closed when the next session starts, with its
|
||||
/// line, without walking anything.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AnAccountLeftStoricoInCorsoWithItsHistoryCompleteIsClosedWhenASessionStarts()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(start: Morning);
|
||||
var engine = bed.Engine;
|
||||
var account = await engine.AddAccountAsync("anna.prova", followed: true, state: AccountState.Backfilling, postCount: 7);
|
||||
await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now);
|
||||
var runner = new ScriptedRunner(engine.Governor, engine.Clock);
|
||||
engine.Start(runner);
|
||||
await engine.RunUntilAsync(Morning.AddDays(1));
|
||||
await engine.StopAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
|
||||
Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(account.Id))!.State);
|
||||
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
|
||||
Assert.HasCount(1, lines);
|
||||
Assert.AreEqual("Storico di @anna.prova completato: 0 post in libreria. Da ora lo tengo aggiornato.", lines[0].Message);
|
||||
Assert.IsNotNull(lines[0].SessionId);
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill), "Nothing left to walk.");
|
||||
Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)));
|
||||
}
|
||||
|
||||
/// <summary>The real recipes over the scripted site, on the engine's database, clock, Governor and breaker.</summary>
|
||||
private static (RecipeRunner Runner, ScriptedSite Site) RealRecipes(EngineTestBed engine)
|
||||
{
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), engine.Clock);
|
||||
var site = new ScriptedSite(capture, engine.Clock);
|
||||
var runner = new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = site,
|
||||
Capture = capture,
|
||||
Governor = engine.Governor,
|
||||
Budget = engine.Governor,
|
||||
DataBudget = engine.Governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadTestSite(), engine.Breaker, engine.Clock),
|
||||
Storage = engine.Db,
|
||||
SiteMap = SiteMap.LoadTestSite(),
|
||||
Clock = engine.Clock,
|
||||
Random = new SeededRandom(7),
|
||||
Breaker = engine.Breaker,
|
||||
});
|
||||
return (runner, site);
|
||||
}
|
||||
|
||||
/// <summary>An account «Storico in corso» for a scripted account: posts only, so that a visit is the profile check.</summary>
|
||||
private static Task<Account> AddBackfillingAsync(EngineTestBed engine, ScriptedAccount scripted, int postCount) =>
|
||||
engine.Db.Accounts.AddAsync(Account.Create(scripted.Username, StartingPoint.EverythingAndKeepUpdated, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with
|
||||
{
|
||||
InstagramId = scripted.Id,
|
||||
IsFollowed = scripted.Followed,
|
||||
State = AccountState.Backfilling,
|
||||
ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos,
|
||||
PostCount = postCount,
|
||||
});
|
||||
}
|
||||
@@ -27,7 +27,8 @@ public sealed class ImportSourcesTests
|
||||
Assert.AreEqual(Path.Combine(root, "4K Stogram"), info.FullPath);
|
||||
Assert.IsTrue(info.ReadOnly, "Il volume /importa è in sola lettura.");
|
||||
Assert.IsFalse(info.CanMove);
|
||||
Assert.AreEqual(root + "/4K Stogram", info.DisplayPath);
|
||||
// Shown as in the container, with «/»: the same text as the root on Linux; on Windows the separators change too.
|
||||
Assert.AreEqual(LibraryLayout.ToStored(root) + "/4K Stogram", info.DisplayPath);
|
||||
|
||||
var outside = Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(temp.Combine("fuori")));
|
||||
StringAssert.Contains(outside.Message, "sottocartella");
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Opening the remote view while the page changes document (Gitea issue #3), without a browser. From
|
||||
/// <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until it commits, Chromium answers
|
||||
/// <c>Page.startScreencast</c> with -32000 «Not attached to an active page»: the view must open once the new document is
|
||||
/// there, a page that never gets there must still end in «non risponde» within a few seconds, and a browser that is gone
|
||||
/// must say so at once.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RemoteViewStartTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task AViewOpenedWhileThePageChangesDocumentOpensOnceTheNewDocumentIsThere()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(attempt => attempt == 1 ? InactivePage() : null);
|
||||
|
||||
var view = await bed.Host.OpenAsync(ct);
|
||||
|
||||
Assert.IsNull(view.Ended, "the view is open");
|
||||
Assert.AreEqual(2, bed.Starts, "the start refused while the page changed document was sent again");
|
||||
Assert.AreEqual(1, bed.Browser.UserDriving.Leases, "the open view holds the browser");
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds(1), bed.Elapsed, "a short pause, not the whole budget");
|
||||
|
||||
// Frames flow to the view: meta first, then the JPEG.
|
||||
bed.Cdp.Raise("Page.screencastFrame", Frame());
|
||||
var outputs = await ReadUntilFrameAsync(view, ct);
|
||||
Assert.IsInstanceOfType<RemoteViewMeta>(outputs[0]);
|
||||
Assert.IsInstanceOfType<RemoteViewFrame>(outputs[^1]);
|
||||
|
||||
await view.DisposeAsync();
|
||||
Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "no view, no lease");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task APageThatStaysBetweenTwoDocumentsStillEndsInNonRispondeWithinTheBudget()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => InactivePage());
|
||||
var watch = Stopwatch.StartNew();
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
||||
|
||||
StringAssert.Contains(error.Message, "non risponde");
|
||||
Assert.IsTrue(error.InnerException is CdpCommandException { IsInactivePage: true }, "the browser's answer stays the cause");
|
||||
Assert.IsLessThanOrEqualTo(ScreencastSession.InactivePageBudget, bed.Elapsed, "never longer than the budget");
|
||||
Assert.IsGreaterThan(TimeSpan.FromSeconds(4), bed.Elapsed, "tried for the whole budget");
|
||||
Assert.IsInRange(5, 15, bed.Starts, "a few attempts, spaced out");
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the pauses are the clock's, not a hang");
|
||||
Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "nothing of the view stays behind");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ABrowserThatIsGoneIsNotTriedAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => new CdpDisconnectedException("Il collegamento con il browser si è chiuso."));
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
||||
|
||||
StringAssert.Contains(error.Message, "non risponde");
|
||||
Assert.AreEqual(1, bed.Starts);
|
||||
Assert.AreEqual(TimeSpan.Zero, bed.Elapsed, "no pause at all");
|
||||
Assert.AreEqual(0, bed.Browser.UserDriving.Leases);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task AnotherRefusalOfTheBrowserIsNotTriedAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => new CdpCommandException("Page.startScreencast", CdpCommandException.ServerErrorCode, "Not attached to a page"));
|
||||
|
||||
await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
||||
|
||||
Assert.AreEqual(1, bed.Starts, "only «Not attached to an active page» is the moment of a navigation");
|
||||
Assert.AreEqual(TimeSpan.Zero, bed.Elapsed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ReplacingAViewKeepsAlbertoAtTheBrowserThroughout()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => null);
|
||||
var gate = bed.Browser.UserDriving;
|
||||
var older = await bed.Host.OpenAsync(ct);
|
||||
var released = 0;
|
||||
void OnChanged(object? sender, bool driving)
|
||||
{
|
||||
if (!driving)
|
||||
{
|
||||
Interlocked.Increment(ref released);
|
||||
}
|
||||
}
|
||||
|
||||
gate.Changed += OnChanged;
|
||||
try
|
||||
{
|
||||
var newer = await bed.Host.OpenAsync(ct);
|
||||
|
||||
Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended);
|
||||
Assert.IsNull(newer.Ended);
|
||||
Assert.AreEqual(0, released, "the engine never sees nobody at the browser between the two views (it would rest the page under the new one)");
|
||||
Assert.AreEqual(1, gate.Leases);
|
||||
|
||||
await newer.DisposeAsync();
|
||||
Assert.AreEqual(1, released, "closing the last view lets the engine go on");
|
||||
Assert.AreEqual(0, gate.Leases);
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Changed -= OnChanged;
|
||||
}
|
||||
}
|
||||
|
||||
private static CdpCommandException InactivePage() =>
|
||||
new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage);
|
||||
|
||||
private static JsonObject Frame() => new()
|
||||
{
|
||||
["sessionId"] = 1,
|
||||
["data"] = Convert.ToBase64String([0xFF, 0xD8, 0xFF, 0xD9]),
|
||||
["metadata"] = new JsonObject { ["deviceWidth"] = Bed.Width, ["deviceHeight"] = Bed.Height, ["pageScaleFactor"] = 1 },
|
||||
};
|
||||
|
||||
private static async Task<List<RemoteViewOutput>> ReadUntilFrameAsync(IRemoteViewConnection view, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
var outputs = new List<RemoteViewOutput>();
|
||||
await foreach (var output in view.ReadAsync(timeout.Token))
|
||||
{
|
||||
outputs.Add(output);
|
||||
if (output is RemoteViewFrame)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return outputs;
|
||||
}
|
||||
|
||||
/// <summary>The host over a fake page whose answer to each <c>Page.startScreencast</c> is chosen by the test.</summary>
|
||||
private sealed class Bed : IAsyncDisposable
|
||||
{
|
||||
public const int Width = 1280;
|
||||
public const int Height = 900;
|
||||
|
||||
private readonly FebeLog _log;
|
||||
private readonly DateTimeOffset _start;
|
||||
private int _starts;
|
||||
|
||||
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
|
||||
public Bed(Func<int, Exception?> startFailure)
|
||||
{
|
||||
Clock = new VirtualClock();
|
||||
_start = Clock.Now;
|
||||
Cdp = new FakeCdpSession(Clock)
|
||||
{
|
||||
Responder = (method, _) =>
|
||||
{
|
||||
switch (method)
|
||||
{
|
||||
case "Page.getFrameTree":
|
||||
return new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } };
|
||||
case "Page.startScreencast":
|
||||
if (startFailure(Interlocked.Increment(ref _starts)) is { } failure)
|
||||
{
|
||||
throw failure;
|
||||
}
|
||||
|
||||
return null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
Browser = new PageBrowser(Cdp);
|
||||
_log = new FebeLog(null, null, Clock);
|
||||
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock);
|
||||
}
|
||||
|
||||
public VirtualClock Clock { get; }
|
||||
|
||||
public FakeCdpSession Cdp { get; }
|
||||
|
||||
public PageBrowser Browser { get; }
|
||||
|
||||
public BrowserRemoteViewHost Host { get; }
|
||||
|
||||
public int Starts => Volatile.Read(ref _starts);
|
||||
|
||||
/// <summary>Time spent in the host's pauses (the virtual clock moves only there).</summary>
|
||||
public TimeSpan Elapsed => Clock.Now - _start;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Host.ShutdownAsync();
|
||||
_log.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A running browser on one page, as the remote view host sees it.</summary>
|
||||
private sealed class PageBrowser(ICdpSession cdp) : IFebeBrowser
|
||||
{
|
||||
public ICdpSession Cdp { get; } = cdp;
|
||||
|
||||
public UserDrivingGate UserDriving { get; } = new();
|
||||
|
||||
public bool UserIsDriving => UserDriving.IsDriving;
|
||||
|
||||
public bool IsAvailable => true;
|
||||
|
||||
public string? LastError => null;
|
||||
|
||||
public string ProfileDirectory => "browser";
|
||||
|
||||
public int WindowWidth => Bed.Width;
|
||||
|
||||
public int WindowHeight => Bed.Height;
|
||||
|
||||
public Task RunAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task<NavigationResult> RestAsync(CancellationToken ct) => Cdp.RestAsync(ct);
|
||||
|
||||
public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task RestartWithEmptyProfileAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -252,20 +252,44 @@ public sealed partial class ServerEndToEndTests
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var host = server.RemoteView!;
|
||||
var gate = server.Browser!.UserDriving;
|
||||
var released = 0;
|
||||
void OnChanged(object? sender, bool driving)
|
||||
{
|
||||
if (!driving)
|
||||
{
|
||||
Interlocked.Increment(ref released);
|
||||
}
|
||||
}
|
||||
|
||||
for (var round = 0; round < 5; round++)
|
||||
{
|
||||
// From the rest page: where the browser starts, and where the engine puts it once nobody is at the browser.
|
||||
// Page.getFrameTree is answered by the page itself, which DevTools holds back while a navigation is pending:
|
||||
// «about:blank» here means the engine's rest has committed.
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(server.Browser.Cdp, ct) == "about:blank",
|
||||
TimeSpan.FromSeconds(20),
|
||||
"la pagina di riposo");
|
||||
|
||||
// Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended.
|
||||
var views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct));
|
||||
// Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended — and the
|
||||
// engine never sees nobody at the browser in between (it would put the page to rest under the newer view).
|
||||
Volatile.Write(ref released, 0);
|
||||
gate.Changed += OnChanged;
|
||||
IRemoteViewConnection[] views;
|
||||
try
|
||||
{
|
||||
views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct));
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Changed -= OnChanged;
|
||||
}
|
||||
|
||||
var open = views.Where(v => v.Ended is null).ToList();
|
||||
Assert.HasCount(1, open, $"Round {round}: one view stays open.");
|
||||
Assert.AreEqual(RemoteViewEnd.Replaced, views.Single(v => v.Ended is not null).Ended);
|
||||
Assert.AreEqual(1, gate.Leases, $"Round {round}: only the open view holds the browser.");
|
||||
Assert.AreEqual(0, Volatile.Read(ref released), $"Round {round}: the browser was never left without a driver while one view replaced the other.");
|
||||
|
||||
// The page of the replaced view closes its socket: the open view still gets its frames.
|
||||
await views.Single(v => v.Ended is not null).DisposeAsync();
|
||||
@@ -277,6 +301,55 @@ public sealed partial class ServerEndToEndTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task AViewOpenedWhileThePageIsNavigatingOpensAndShowsItsFrames()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ServerTestBed.StartAsync();
|
||||
var server = bed.Server;
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var host = server.RemoteView!;
|
||||
var browser = server.Browser!;
|
||||
|
||||
for (var round = 0; round < 6; round++)
|
||||
{
|
||||
// From the rest page, as in TwoViews…: the previous round ends on a site page, so «about:blank» here means the
|
||||
// engine's rest after the last view has committed and nothing else navigates.
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(browser.Cdp, ct) == "about:blank",
|
||||
TimeSpan.FromSeconds(20),
|
||||
"la pagina di riposo");
|
||||
|
||||
// Even rounds: «Accedi a Instagram» on the Collegamento page navigates to the login page while the same page
|
||||
// opens the view. Odd rounds: the rest page, as the engine puts it after a session or after the last view.
|
||||
// A guard of these pairs, not of the retry: with the navigation already sent, the view's first look at the
|
||||
// page (Page.getFrameTree) is answered only once it has committed, so the start comes after the commit (seen
|
||||
// with Chrome 155). RemoteViewDuringNavigationTests makes the start meet the refusal on purpose.
|
||||
var navigation = round % 2 == 0
|
||||
? Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?vista={round}", ct)
|
||||
: browser.RestAsync(ct);
|
||||
var view = await host.OpenAsync(ct);
|
||||
try
|
||||
{
|
||||
var navigated = await navigation;
|
||||
Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}");
|
||||
Assert.IsNull(view.Ended, $"Round {round}: the view is open.");
|
||||
Assert.AreEqual(1, browser.UserDriving.Leases, $"Round {round}: only the view holds the browser.");
|
||||
|
||||
// A new page paints: its frames reach the view.
|
||||
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?giro={round}", ct);
|
||||
Assert.IsTrue(await FrameArrivesAsync(view, ct), $"Round {round}: frames of the page.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, browser.UserDriving.Leases, $"Round {round}: no view, no lease.");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> FrameArrivesAsync(IRemoteViewConnection view, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
|
||||
@@ -99,14 +99,23 @@ public sealed class StartupProblemTests
|
||||
[TestMethod]
|
||||
public async Task ADataFolderOnANetworkShareIsRefused()
|
||||
{
|
||||
// A share shows itself differently on the two systems: on Linux as a cifs mount in the mount table (injected
|
||||
// here), on Windows as a UNC path, recognised from its form before anything touches it. The Windows server name
|
||||
// ends in .invalid (RFC 6761): no machine answers to it, and nothing here looks it up.
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
var data = temp.Combine("dati");
|
||||
var windows = OperatingSystem.IsWindows();
|
||||
var data = windows ? @"\\febe-prova.invalid\condivisa\dati" : temp.Combine("dati");
|
||||
var mounts = $"/dev/sda1 / ext4 rw 0 0\n//nas/condivisa {temp.Path} cifs rw 0 0\n";
|
||||
await using var server = await FebeServer.StartAsync(Options(temp), Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) });
|
||||
await using var server = await FebeServer.StartAsync(Options(temp) with { DataFolder = data }, Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) });
|
||||
var problem = server.Problems.Single();
|
||||
Assert.AreEqual(StartupChecks.DataOnNetwork, problem.Code);
|
||||
StringAssert.Contains(problem.Message, "cifs");
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro")));
|
||||
StringAssert.Contains(problem.Message, windows ? "condivisione di rete" : "cifs");
|
||||
if (!windows)
|
||||
{
|
||||
// Nothing written in the Data folder (on Windows the share does not exist: looking would mean asking the network).
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro")));
|
||||
}
|
||||
|
||||
using var client = Client(server);
|
||||
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
|
||||
}
|
||||
|
||||
@@ -63,13 +63,36 @@ internal sealed class TestLibrary : IAsyncDisposable
|
||||
await Db.DisposeAsync();
|
||||
foreach (var suffix in new[] { string.Empty, "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(Data.Database + suffix);
|
||||
await DeleteClosedFileAsync(Data.Database + suffix);
|
||||
}
|
||||
|
||||
Db = await FebeDatabase.OpenAsync(Data.Root);
|
||||
Ingest = new LibraryIngest(Db, Layout, LibraryNaming.Default, Journal, Clock, Thumbnails, Index);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a file Febe has already closed. On Windows a file still held open elsewhere cannot be deleted, and on one PC a
|
||||
/// database just closed was now and then held for a few milliseconds by something outside Febe (Restart Manager listed
|
||||
/// no process; probably the real-time antivirus, which was active, but the cause was never shown): that sharing
|
||||
/// violation is waited out (at most 5 s). On Linux a delete never meets one, so the first attempt is the only one.
|
||||
/// </summary>
|
||||
private static async Task DeleteClosedFileAsync(string path)
|
||||
{
|
||||
const int SharingViolation = unchecked((int)0x80070020);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
return;
|
||||
}
|
||||
catch (IOException ex) when (OperatingSystem.IsWindows() && ex.HResult == SharingViolation && attempt < 100)
|
||||
{
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => Db.DisposeAsync();
|
||||
}
|
||||
|
||||
|
||||
@@ -163,10 +163,12 @@ public sealed class ImportApiTests
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, sources, "desktop: the native picker, no listing");
|
||||
}
|
||||
|
||||
// Docker: the sources live under /importa (absent on this machine: the listing says so).
|
||||
// Docker: the sources live under /importa (absent on this machine: the listing says so). The root is reported as
|
||||
// a full path: «/importa» in the container, rooted on the current drive where the edition runs for development
|
||||
// on Windows.
|
||||
await using var docker = await Part2.StartAsync();
|
||||
var overview = await docker.GetJsonAsync("/api/import");
|
||||
Assert.AreEqual("/importa", overview.Str("sourceRoot"));
|
||||
Assert.AreEqual(Path.GetFullPath("/importa"), overview.Str("sourceRoot"));
|
||||
Assert.IsFalse(overview.Bool("pickFolder"));
|
||||
var (pick, _) = await docker.SendJsonAsync(HttpMethod.Post, "/api/import/pick-folder");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, pick);
|
||||
|
||||
@@ -112,6 +112,21 @@ public sealed class InterfaceTests
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "«Ho finito» already gave the browser back");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ConnectedBeforeTheFirstRoundSaysTheNameIsNotKnownYet()
|
||||
{
|
||||
// Right after «Ho finito» the session exists but no round has read the name of the account yet.
|
||||
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null) };
|
||||
await using var server = await DockerAsync(connection, new FakeRemoteViewHost());
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
|
||||
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
|
||||
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato");
|
||||
Assert.AreEqual("Collegato", (await ui.EvalAsync("document.querySelector('.chi-collegato h2').textContent")).GetString());
|
||||
Assert.AreEqual("Nome non ancora noto", (await ui.EvalAsync("document.querySelector('.chi-collegato .muto').textContent")).GetString());
|
||||
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.chi-collegato').textContent.includes('@')")).GetBoolean(), "no «@» without a name");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task HoFinitoOnCollegamentoClosesTheRemoteView()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user