From 631e9b2ce32100539054f29873814c46fe62616d Mon Sep 17 00:00:00 2001 From: Heros Date: Thu, 12 Nov 2026 17:50:59 -0300 Subject: [PATCH 1/7] =?UTF-8?q?fix:=20torna=20a=20atualiza=C3=A7=C3=A3o=20?= =?UTF-8?q?do=20Windows=20verific=C3=A1vel=20e=20resiliente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adiciona retentativas quando a consulta de atualização falha no início, um wrapper no Windows que registra o código de saída do Setup e reabre a versão atual em caso de falha, e o comando --apply-update para forçar/diagnosticar a atualização. Inclui um teste A -> B no CI do Windows e a opção de gerar manifesto com um único asset. --- .github/workflows/package.yml | 54 +++++- README.md | 33 +++- packaging/make_update_manifest.py | 26 ++- packaging/windows/test-update.ps1 | 248 +++++++++++++++++++++++++ src/learning_helper/app.py | 52 ++++++ src/learning_helper/updates/install.py | 135 +++++++++++++- src/learning_helper/updates/service.py | 51 +++-- tests/test_cli.py | 80 ++++++++ tests/test_update_manifest.py | 64 +++++++ tests/test_updates.py | 68 ++++++- 10 files changed, 782 insertions(+), 29 deletions(-) create mode 100644 packaging/windows/test-update.ps1 create mode 100644 tests/test_update_manifest.py diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 270c173..e5e091b 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -88,6 +88,58 @@ jobs: path: dist/installer/*.exe if-no-files-found: error + windows-update: + needs: windows + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + enable-cache: true + - name: Instalar Inno Setup + run: choco install innosetup --no-progress -y + - name: Baixar instalador da versão atual + uses: actions/download-artifact@v4 + with: + name: windows-installer + path: dist/installer + - name: Gerar instalador da versão seguinte + shell: pwsh + run: | + $versionA = (uv run python -c "from learning_helper import __version__; print(__version__)").Trim() + $parts = $versionA.Split(".") + $versionB = "{0}.{1}.{2}" -f $parts[0], $parts[1], ([int]$parts[2] + 1) + $init = "src/learning_helper/__init__.py" + $content = Get-Content $init -Raw + $content = [regex]::Replace($content, '__version__ = "[^"]+"', "__version__ = `"$versionB`"") + Set-Content -Path $init -Value $content -NoNewline + powershell -NoProfile -ExecutionPolicy Bypass -File packaging/windows/build.ps1 + if ($LASTEXITCODE -ne 0) { throw "build da versão $versionB falhou" } + "VERSION_A=$versionA" >> $env:GITHUB_ENV + "VERSION_B=$versionB" >> $env:GITHUB_ENV + - name: Testar atualização A -> B + shell: pwsh + run: | + $installerA = (Get-ChildItem dist/installer/*.exe | + Where-Object { $_.Name -notlike "*$env:VERSION_B*" } | + Select-Object -First 1).FullName + $installerB = (Get-ChildItem "dist/installer/LearningHelper-$env:VERSION_B-Setup.exe").FullName + powershell -NoProfile -ExecutionPolicy Bypass -File packaging/windows/test-update.ps1 ` + -InstallerA $installerA ` + -VersionA $env:VERSION_A ` + -InstallerB $installerB ` + -VersionB $env:VERSION_B ` + -Force + - name: Guardar diagnóstico da atualização + if: failure() + uses: actions/upload-artifact@v4 + with: + name: windows-update-diagnostics + path: | + ${{ runner.temp }}/learning-helper-update-e2e/** + dist/installer/latest*.json + if-no-files-found: ignore + linux: runs-on: ubuntu-22.04 steps: @@ -156,7 +208,7 @@ jobs: release: if: startsWith(github.ref, 'refs/tags/v') - needs: [windows, linux] + needs: [windows, windows-update, linux] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/README.md b/README.md index a1403e0..10c248d 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ A seção **Dados** mostra o caminho do banco e abre a pasta onde ficam o banco A atualização automática está disponível **a partir da v0.5.0**. Quem ainda está na v0.4.0 ou anterior precisa instalar a v0.5.0 uma vez; depois disso, as próximas versões instalam sozinhas. -Builds instalados consultam o `latest.json` da release mais recente **uma vez ao iniciar** (se a opção estiver ligada) e também pelo botão **Verificar atualizações agora** em Configurações. Não há verificação periódica enquanto o app está aberto. O repositório e as releases são públicos, então a atualização funciona sem token. +Builds instalados consultam o `latest.json` da release mais recente **uma vez ao iniciar** (se a opção estiver ligada) e também pelo botão **Verificar atualizações agora** em Configurações. Se a primeira consulta falhar (por exemplo, o Windows iniciou o app antes da rede ficar disponível), o app tenta de novo após 5, 15 e 30 minutos, sem exigir reiniciar. Não há verificação periódica depois de uma consulta bem-sucedida. O repositório e as releases são públicos, então a atualização funciona sem token. Quando há uma versão nova: @@ -206,7 +206,15 @@ A instalação padrão por usuário não pede senha. Se o Windows foi instalado Para desligar a verificação automática, use a opção em **Configurações** ou defina `LEARNING_HELPER_NO_UPDATE=1` no ambiente. O botão manual continua disponível. Em execução a partir do código-fonte, o app apenas informa se há versão nova; ele não se auto-instala. -Se uma instalação falhar três vezes, o app espera 7 dias antes de tentar a mesma versão de novo. **Verificar atualizações agora** ignora esse bloqueio e tenta novamente. O andamento fica em `updates/apply.log` e em `app.log` (veja [Dados locais](#dados-locais)). +Se uma instalação falhar três vezes, o app espera 7 dias antes de tentar a mesma versão de novo. **Verificar atualizações agora** ignora esse bloqueio e tenta novamente. O andamento fica em `updates/apply.log` e em `app.log` (veja [Dados locais](#dados-locais)). No Windows, o `apply.log` registra o código de saída do instalador e, se o Setup falhar, o app é reaberto na versão atual em vez de ficar fechado; o log detalhado do Inno Setup fica em `updates/setup-.log`. + +Também é possível forçar o download e a aplicação pelo terminal, sem abrir a interface: + +```powershell +& "$env:LOCALAPPDATA\Programs\LearningHelper\learning-helper.exe" --apply-update +``` + +O comando só funciona em builds instalados. Ele baixa o pacote, confere o SHA-256 e dispara a instalação; o app reabre na versão nova. ### Repositório público, token e espelhos @@ -294,6 +302,7 @@ A subpasta `updates/` guarda o que o atualizador precisa: - `state.json`: última versão pendente, tentativas e bloqueio temporário; - `manual.request`: aviso das Configurações para o overlay aplicar um download manual; - `apply.log`: saída do instalador ou do script de atualização; +- `setup-.log`: log detalhado do Inno Setup no Windows; - `/`: pacote baixado e conferido por SHA-256. Ela pode ser apagada a qualquer momento; o app baixa de novo na próxima verificação. @@ -370,6 +379,23 @@ As capturas precisam de uma sessão gráfica; o painel de estatísticas usa Fire Os alvos de empacotamento (`make build`, `make appimage`, `make tarball`, `make packages`) usam a versão de `src/learning_helper/__init__.py` e podem ser sobrescritos com `make packages VERSION=0.8.1`. +### Teste de atualização no Windows + +O workflow `package` tem um job `windows-update` que instala a versão atual, gera a versão seguinte, serve um `latest.json` local e valida a atualização completa (download, SHA-256, Setup silencioso, reinício e preservação do banco). Ele também testa a rejeição de um pacote com SHA-256 inválido. + +Para repetir o teste manualmente em uma VM ou usuário de teste do Windows, instale o Inno Setup 6 e rode: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File packaging/windows/test-update.ps1 ` + -InstallerA "dist\installer\LearningHelper-0.8.1-Setup.exe" ` + -VersionA "0.8.1" ` + -InstallerB "dist\installer\LearningHelper-0.8.2-Setup.exe" ` + -VersionB "0.8.2" ` + -Force +``` + +O script usa uma pasta de dados temporária, exige `-Force` se já existir uma instalação em `%LOCALAPPDATA%\Programs\LearningHelper` e desinstala o app ao final. Os logs ficam na pasta temporária e em `updates/apply.log`. + No Windows, o `make` não vem instalado por padrão: use o Git Bash/MSYS2 (ou instale com `choco install make`). Os comandos com `uv` mostrados acima continuam funcionando normalmente. ### Branches e pull requests @@ -409,6 +435,7 @@ O merge deve ser feito pela interface do GitHub ou por `gh pr merge`. O bloqueio --settings abre a tela de configuração e sai --stats abre as estatísticas no navegador --check-updates consulta o manifesto de atualização e informa se há versão nova +--apply-update baixa e aplica a atualização disponível (somente build instalado) --quit encerra app, configurações e servidor de estatísticas em execução --debug intervalo curto e botão de fechar no overlay --db CAMINHO usa outro arquivo SQLite @@ -420,7 +447,7 @@ O merge deve ser feito pela interface do GitHub ou por `gh pr merge`. O bloqueio No Windows o autostart é gerenciado pelo instalador; as duas opções de autostart apenas avisam isso e não alteram nada. As opções do lembrete de banheiro valem em qualquer plataforma e gravam a preferência no banco. -`--check-updates` não baixa nem instala nada: só consulta o `latest.json`. Ele sai com código 0 quando a consulta funciona (mesmo que haja versão nova) e 1 em caso de erro de rede/manifesto. +`--check-updates` não baixa nem instala nada: só consulta o `latest.json`. Ele sai com código 0 quando a consulta funciona (mesmo que haja versão nova) e 1 em caso de erro de rede/manifesto. `--apply-update` baixa e aplica a versão nova; sai com 0 quando não há nada a fazer ou quando a instalação foi iniciada, 1 em caso de erro de download/SHA-256 e 2 quando não está em um build instalado. ### Testes diff --git a/packaging/make_update_manifest.py b/packaging/make_update_manifest.py index e45f035..327c54e 100644 --- a/packaging/make_update_manifest.py +++ b/packaging/make_update_manifest.py @@ -30,14 +30,21 @@ def build_manifest( *, tag: str | None = None, base_url: str | None = None, + asset_keys: list[str] | None = None, ) -> dict: release_tag = tag or f"v{version}" release_url = base_url or ( f"https://github.com/{REPOSITORY}/releases/download/{release_tag}" ) + selected = ( + list(ASSET_PATTERNS) + if asset_keys is None + else [key for key in asset_keys if key in ASSET_PATTERNS] + ) assets = {} missing = [] - for key, pattern in ASSET_PATTERNS.items(): + for key in selected: + pattern = ASSET_PATTERNS[key] name = pattern.format(version=version) path = dist_dir / name if not path.is_file(): @@ -50,6 +57,8 @@ def build_manifest( } if missing: raise SystemExit("Arquivos ausentes para o manifesto: " + ", ".join(missing)) + if not assets: + raise SystemExit("Nenhum asset selecionado para o manifesto.") return {"version": version, "assets": assets} @@ -59,15 +68,30 @@ def main() -> int: parser.add_argument("--dist", type=Path, required=True) parser.add_argument("--tag") parser.add_argument("--base-url") + parser.add_argument( + "--assets", + help=( + "Chaves separadas por vírgula a incluir no manifesto " + "(padrão: todas). Ex.: windows_setup" + ), + ) parser.add_argument("--output", type=Path) args = parser.parse_args() + asset_keys = None + if args.assets: + asset_keys = [item.strip() for item in args.assets.split(",") if item.strip()] + unknown = [item for item in asset_keys if item not in ASSET_PATTERNS] + if unknown: + parser.error("assets desconhecidos: " + ", ".join(unknown)) + version = args.version.lstrip("vV") manifest = build_manifest( version, args.dist, tag=args.tag, base_url=args.base_url, + asset_keys=asset_keys, ) output = args.output or (args.dist / "latest.json") output.write_text( diff --git a/packaging/windows/test-update.ps1 b/packaging/windows/test-update.ps1 new file mode 100644 index 0000000..677a4a9 --- /dev/null +++ b/packaging/windows/test-update.ps1 @@ -0,0 +1,248 @@ +param( + [Parameter(Mandatory = $true)][string]$InstallerA, + [Parameter(Mandatory = $true)][string]$VersionA, + [Parameter(Mandatory = $true)][string]$InstallerB, + [Parameter(Mandatory = $true)][string]$VersionB, + [string]$Port = "8765", + [switch]$Force +) + +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +$tempRoot = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } else { $env:TEMP } +$uv = (Get-Command uv -ErrorAction Stop).Source +Set-Location $root + +function Write-Step { + param([string]$Message) + Write-Host "==> $Message" +} + +function Get-InstalledApp { + return Join-Path $env:LOCALAPPDATA "Programs\LearningHelper\learning-helper.exe" +} + +function Get-InstalledVersion { + param([string]$App) + try { + return (Get-Item -LiteralPath $App -ErrorAction Stop).VersionInfo.ProductVersion.Trim() + } catch { + return $null + } +} + +function Wait-InstalledVersion { + param([string]$App, [string]$Expected, [int]$Seconds = 180) + for ($i = 0; $i -lt $Seconds; $i++) { + $version = Get-InstalledVersion -App $App + if ($version -eq $Expected) { + return $true + } + Start-Sleep -Seconds 1 + } + return $false +} + +function Stop-LearningHelper { + Get-Process -Name "learning-helper" -ErrorAction SilentlyContinue | + Stop-Process -Force -ErrorAction SilentlyContinue +} + +function Write-SeedScript { + param([string]$Path) + Set-Content -LiteralPath $Path -Encoding UTF8 -Value @' +import sys +from learning_helper.persistence.db import Store, data_dir +from learning_helper.settings import Settings + +store = Store() +settings = store.get_settings().to_dict() +settings["daily_usage_limit_seconds"] = 3600 +store.save_settings(Settings(**settings)) +store.insert_attempt( + module_id="colors", + level=1, + prompt="teste", + choices=["a", "b"], + correct_answer="a", + given_answer="a", + is_correct=True, +) +store.complete_onboarding() +store.close() +print(data_dir()) +'@ +} + +function Write-CheckScript { + param([string]$Path) + Set-Content -LiteralPath $Path -Encoding UTF8 -Value @' +import sys +from learning_helper.persistence.db import Store + +store = Store() +settings = store.get_settings() +attempts = store.count_attempts() +store.close() +if settings.daily_usage_limit_seconds != 3600: + raise SystemExit(f"limite diario inesperado: {settings.daily_usage_limit_seconds}") +if attempts < 1: + raise SystemExit("tentativa de teste nao encontrada") +print(f"dados preservados: limite={settings.daily_usage_limit_seconds}, tentativas={attempts}") +'@ +} + +$installerA = (Resolve-Path -LiteralPath $InstallerA).Path +$installerB = (Resolve-Path -LiteralPath $InstallerB).Path +$distDir = Split-Path -Parent $installerB +$app = Get-InstalledApp +$appDir = Split-Path -Parent $app +if ((Test-Path -LiteralPath $appDir) -and !$Force) { + throw "Ja existe uma instalacao em $appDir. Use -Force em uma maquina/VM de teste." +} +$testLocal = Join-Path $tempRoot "learning-helper-update-e2e" +$server = $null +$oldLocal = $env:LOCALAPPDATA +$oldUrl = $env:LEARNING_HELPER_UPDATE_URL +$oldNoUpdate = $env:LEARNING_HELPER_NO_UPDATE +$oldPythonPath = $env:PYTHONPATH + +Write-Step "Versao A: $VersionA; versao B: $VersionB" + +try { + Write-Step "Instalando A" + $install = Start-Process -FilePath $installerA -Wait -PassThru -ArgumentList @( + "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/CURRENTUSER", "/SP-" + ) + if ($install.ExitCode -ne 0) { + throw "Falha ao instalar A (exit $($install.ExitCode))" + } + if (!(Test-Path -LiteralPath $app)) { + throw "Aplicativo A nao encontrado em $app" + } + if ((Get-InstalledVersion -App $app) -ne $VersionA) { + throw "Versao instalada de A nao confere" + } + + Remove-Item -LiteralPath $testLocal -Recurse -Force -ErrorAction SilentlyContinue + New-Item -ItemType Directory -Force -Path $testLocal | Out-Null + $env:LOCALAPPDATA = $testLocal + $env:PYTHONPATH = Join-Path $root "src" + + $seed = Join-Path $tempRoot "learning-helper-update-seed.py" + $check = Join-Path $tempRoot "learning-helper-update-check.py" + Write-SeedScript -Path $seed + Write-CheckScript -Path $check + uv run python $seed + if ($LASTEXITCODE -ne 0) { + throw "Falha ao preparar o banco de teste" + } + + Write-Step "Gerando manifesto local para B" + uv run python packaging/make_update_manifest.py ` + --version $VersionB ` + --dist $distDir ` + --base-url "http://127.0.0.1:$Port" ` + --assets windows_setup + if ($LASTEXITCODE -ne 0) { + throw "Falha ao gerar latest.json" + } + + Write-Step "Servindo $distDir em http://127.0.0.1:$Port" + $server = Start-Process -FilePath $uv -WindowStyle Hidden -PassThru -ArgumentList @( + "run", "python", "-m", "http.server", $Port, "--directory", $distDir + ) + $ready = $false + for ($i = 0; $i -lt 40; $i++) { + try { + $response = Invoke-WebRequest -UseBasicParsing ` + -Uri "http://127.0.0.1:$Port/latest.json" -TimeoutSec 1 + if ($response.StatusCode -eq 200) { + $ready = $true + break + } + } catch { + Start-Sleep -Milliseconds 250 + } + } + if (!$ready) { + throw "Servidor de atualizacao nao respondeu" + } + + Write-Step "Aplicando atualizacao A -> B" + $env:LEARNING_HELPER_UPDATE_URL = "http://127.0.0.1:$Port/latest.json" + Remove-Item Env:LEARNING_HELPER_NO_UPDATE -ErrorAction SilentlyContinue + $apply = Start-Process -FilePath $app -Wait -PassThru -ArgumentList "--apply-update" + if ($apply.ExitCode -ne 0) { + throw "Falha ao iniciar a atualizacao (exit $($apply.ExitCode))" + } + + if (!(Wait-InstalledVersion -App $app -Expected $VersionB)) { + throw "O aplicativo nao chegou a versao $VersionB" + } + Stop-LearningHelper + Start-Sleep -Seconds 1 + + Write-Step "Conferindo banco preservado" + uv run python $check + if ($LASTEXITCODE -ne 0) { + throw "Os dados de teste nao foram preservados" + } + + $log = Join-Path $testLocal "learning_helper\updates\apply.log" + if (!(Test-Path -LiteralPath $log)) { + throw "apply.log nao foi criado" + } + $logContent = Get-Content -LiteralPath $log -Raw + Write-Host $logContent + if ($logContent -notmatch "Installer exit code: 0") { + throw "O instalador nao terminou com sucesso" + } + + Write-Step "Testando rejeicao de SHA-256 invalido" + $badManifest = @{ + version = "99.0.0" + assets = @{ + windows_setup = @{ + name = (Split-Path -Leaf $installerB) + url = "http://127.0.0.1:$Port/$(Split-Path -Leaf $installerB)" + sha256 = ("0" * 64) + } + } + } + $badPath = Join-Path $distDir "latest-bad.json" + $badManifest | ConvertTo-Json -Depth 6 | + Set-Content -LiteralPath $badPath -Encoding UTF8 + + $env:LEARNING_HELPER_UPDATE_URL = "http://127.0.0.1:$Port/latest-bad.json" + $bad = Start-Process -FilePath $app -Wait -PassThru -ArgumentList "--apply-update" + if ($bad.ExitCode -eq 0) { + throw "Atualizacao com SHA-256 invalido foi aceita" + } + if ((Get-InstalledVersion -App $app) -ne $VersionB) { + throw "O aplicativo mudou de versao depois de uma falha de SHA-256" + } + Write-Step "Falha de SHA-256 rejeitada corretamente" +} finally { + Stop-LearningHelper + if ($server -and !$server.HasExited) { + Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue + } + if ($oldLocal) { $env:LOCALAPPDATA = $oldLocal } + if ($null -eq $oldUrl) { Remove-Item Env:LEARNING_HELPER_UPDATE_URL -ErrorAction SilentlyContinue } + else { $env:LEARNING_HELPER_UPDATE_URL = $oldUrl } + if ($null -eq $oldNoUpdate) { Remove-Item Env:LEARNING_HELPER_NO_UPDATE -ErrorAction SilentlyContinue } + else { $env:LEARNING_HELPER_NO_UPDATE = $oldNoUpdate } + if ($oldPythonPath) { $env:PYTHONPATH = $oldPythonPath } + else { Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue } + + if (Test-Path -LiteralPath $appDir) { + $uninstaller = Get-ChildItem -LiteralPath $appDir -Filter "unins*.exe" -ErrorAction SilentlyContinue | + Select-Object -First 1 + if ($uninstaller) { + Start-Process -FilePath $uninstaller.FullName -Wait -ArgumentList @( + "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART" + ) | Out-Null + } + } +} diff --git a/src/learning_helper/app.py b/src/learning_helper/app.py index ff9b86d..e3de817 100644 --- a/src/learning_helper/app.py +++ b/src/learning_helper/app.py @@ -67,6 +67,11 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: action="store_true", help="Verifica se há uma versão nova e sai.", ) + parser.add_argument( + "--apply-update", + action="store_true", + help="Baixa e aplica a atualização disponível, se houver, e sai.", + ) parser.add_argument( "--quit", action="store_true", @@ -214,6 +219,51 @@ def _check_updates() -> int: return 0 +def _apply_update() -> int: + """Baixa e dispara a atualização sem abrir a interface. + + Serve para diagnóstico e para o teste de fumaça do Windows. Em builds + instalados o instalador assume o controle e reabre o app; em execução a + partir do código-fonte não há pacote aplicável. + """ + from learning_helper.updates.install import apply_pending, asset_key + from learning_helper.updates.manifest import UpdateError + from learning_helper.updates.service import check_and_download + from learning_helper.updates.state import load_state, record_attempt, save_state + + if asset_key() is None: + print( + "Atualização automática não disponível nesta execução " + "(execute o build instalado).", + file=sys.stderr, + ) + return 2 + + base = data_dir() + try: + pending = check_and_download(__version__, base, force=True) + except UpdateError as exc: + print(f"Não foi possível baixar a atualização: {exc}", file=sys.stderr) + return 1 + if pending is None: + print(f"Nenhuma atualização disponível para {__version__}.") + return 0 + + state = load_state(base) + record_attempt(state, pending.version, pending.path) + save_state(base, state) + try: + apply_pending(pending, base) + except Exception as exc: + print(f"Falha ao aplicar a atualização: {exc}", file=sys.stderr) + return 1 + print( + f"Atualização {pending.version} iniciada. " + "O app deve reabrir na versão nova." + ) + return 0 + + def _handle_autostart(args: argparse.Namespace) -> int | None: from learning_helper import autostart @@ -306,6 +356,8 @@ def main(argv: list[str] | None = None) -> int: if args.check_updates: return _check_updates() + if args.apply_update: + return _apply_update() if args.quit: path = lifecycle.request_quit() print(f"Solicitação de encerramento enviada ({path}).") diff --git a/src/learning_helper/updates/install.py b/src/learning_helper/updates/install.py index ac2f04f..8a4a4f2 100644 --- a/src/learning_helper/updates/install.py +++ b/src/learning_helper/updates/install.py @@ -17,6 +17,79 @@ LINUX_APPIMAGE = "linux_appimage" LINUX_TARBALL = "linux_tarball" +WINDOWS_APPLY_SCRIPT = "apply-update.ps1" +WINDOWS_APPLY_SCRIPT_CONTENT = r"""param( + [Parameter(Mandatory = $true)][int]$ParentPid, + [Parameter(Mandatory = $true)][string]$Setup, + [Parameter(Mandatory = $true)][string]$App, + [Parameter(Mandatory = $true)][string]$InstallDir, + [Parameter(Mandatory = $true)][string]$Scope, + [Parameter(Mandatory = $true)][string]$Log, + [Parameter(Mandatory = $true)][string]$SetupLog +) +$ErrorActionPreference = "Stop" + +function Write-UpdateLog { + param([string]$Message) + $line = "[{0}] {1}" -f (Get-Date).ToString("o"), $Message + Add-Content -LiteralPath $Log -Value $line -Encoding UTF8 +} + +function Start-LearningHelper { + try { + Start-Process -FilePath $App -WorkingDirectory (Split-Path -Parent $App) | Out-Null + } catch { + Write-UpdateLog ("Could not restart the app: " + $_.Exception.Message) + } +} + +try { + Write-UpdateLog ("Waiting for process " + $ParentPid + " to exit.") + try { + Wait-Process -Id $ParentPid -Timeout 60 -ErrorAction Stop + } catch { + # O processo já saiu ou não existe mais. + } + Start-Sleep -Milliseconds 500 + + Write-UpdateLog ("Running installer: " + $Setup) + $arguments = @( + "/VERYSILENT", + "/SUPPRESSMSGBOXES", + "/NORESTART", + "/CLOSEAPPLICATIONS", + "/UPDATERESTART=1", + $Scope, + ('/DIR="{0}"' -f $InstallDir), + ('/LOG="{0}"' -f $SetupLog) + ) + $process = Start-Process -FilePath $Setup -ArgumentList $arguments -Wait -PassThru + Write-UpdateLog ("Installer exit code: " + $process.ExitCode) + + if ($process.ExitCode -ne 0) { + Write-UpdateLog "Update failed; restarting the current version." + Start-LearningHelper + exit $process.ExitCode + } + + # O instalador usa /UPDATERESTART=1, mas garantir que exista uma instância + # evita deixar o usuário sem app se o [Run] do Inno Setup falhar. + Start-Sleep -Seconds 1 + $running = Get-Process -Name "learning-helper" -ErrorAction SilentlyContinue + if (-not $running) { + Write-UpdateLog "Update applied; starting the app." + Start-LearningHelper + } else { + Write-UpdateLog "Update applied; the app is already running." + } +} catch { + Write-UpdateLog ("Update failed: " + $_.Exception.Message) + Start-LearningHelper + exit 1 +} +""" + + @dataclass(frozen=True) class PendingUpdate: @@ -69,6 +142,27 @@ def _write_script(path: Path, content: str) -> None: path.chmod(0o755) +def _write_powershell_script(path: Path) -> None: + # O PowerShell 5.1 no Windows lê arquivos UTF-8 sem BOM como ANSI; o BOM + # mantém o script intacto mesmo se ele ganhar acentos no futuro. + path.write_text(WINDOWS_APPLY_SCRIPT_CONTENT, encoding="utf-8-sig") + + +def _powershell_executable() -> str: + root = os.environ.get("SystemRoot") + if root: + candidate = ( + Path(root) + / "System32" + / "WindowsPowerShell" + / "v1.0" + / "powershell.exe" + ) + if candidate.is_file(): + return str(candidate) + return "powershell.exe" + + def _spawn_detached(command: list[str], *, log_path: Path) -> None: with log_path.open("a", encoding="utf-8") as log: subprocess.Popen( @@ -95,23 +189,48 @@ def _windows_all_users() -> bool: def _apply_windows(pending: PendingUpdate, base: Path) -> None: + """Agenda um script que espera o app sair, instala e reabre em caso de falha. + + Disparar o Setup direto e encerrar o app deixa o usuário sem aplicação se o + instalador falhar (UAC, antivírus, arquivo em uso). O script mantém o + resultado no log e reabre a versão atual quando o Setup retorna erro. + """ log_path = _log_file(base) + setup_log = Path(base) / "updates" / f"setup-{pending.version}.log" + setup_log.parent.mkdir(parents=True, exist_ok=True) + script = Path(base) / "updates" / WINDOWS_APPLY_SCRIPT + _write_powershell_script(script) + flags = 0 flags |= getattr(subprocess, "DETACHED_PROCESS", 0) flags |= getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) scope = "/ALLUSERS" if _windows_all_users() else "/CURRENTUSER" - install_dir = Path(sys.executable).resolve().parent + executable = Path(sys.executable).resolve() subprocess.Popen( [ + _powershell_executable(), + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-WindowStyle", + "Hidden", + "-File", + str(script), + "-ParentPid", + str(os.getpid()), + "-Setup", str(pending.path), - "/VERYSILENT", - "/SUPPRESSMSGBOXES", - "/NORESTART", - "/CLOSEAPPLICATIONS", - "/UPDATERESTART=1", + "-App", + str(executable), + "-InstallDir", + str(executable.parent), + "-Scope", scope, - f'/DIR="{install_dir}"', - f'/LOG="{log_path}"', + "-Log", + str(log_path), + "-SetupLog", + str(setup_log), ], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, diff --git a/src/learning_helper/updates/service.py b/src/learning_helper/updates/service.py index df229f6..7d41bf0 100644 --- a/src/learning_helper/updates/service.py +++ b/src/learning_helper/updates/service.py @@ -28,6 +28,9 @@ LOGGER = logging.getLogger(__name__) MANUAL_REQUEST_NAME = "manual.request" +# Se a primeira consulta falhar (por exemplo, o Windows iniciou o app antes +# da rede ficar disponível), tenta de novo sem exigir reiniciar o aplicativo. +RETRY_DELAYS_SECONDS = (5 * 60.0, 15 * 60.0, 30 * 60.0) def manual_request_path(base: Path) -> Path: @@ -138,11 +141,14 @@ def __init__( base: Path, *, manifest_url: str | None = None, + retry_delays: tuple[float, ...] = RETRY_DELAYS_SECONDS, ) -> None: self.current_version = current_version self.base = Path(base) self.manifest_url = manifest_url + self._retry_delays = retry_delays self._lock = threading.Lock() + self._stop_event = threading.Event() self._thread: threading.Thread | None = None self._pending: PendingUpdate | None = None self._error: str | None = None @@ -160,20 +166,43 @@ def start(self) -> None: ) self._thread.start() + def stop(self) -> None: + """Interrompe novas tentativas em segundo plano.""" + self._stop_event.set() + thread = self._thread + if thread is not None and thread is not threading.current_thread(): + thread.join(timeout=1.0) + + def _retry_delay(self, attempt: int) -> float | None: + if not self._retry_delays: + return None + return self._retry_delays[min(attempt, len(self._retry_delays) - 1)] + def _worker(self) -> None: - try: - pending = check_and_download( - self.current_version, - self.base, - manifest_url=self.manifest_url, - ) - except Exception as exc: - LOGGER.warning("Não foi possível verificar atualizações: %s", exc) + attempt = 0 + while not self._stop_event.is_set(): + try: + pending = check_and_download( + self.current_version, + self.base, + manifest_url=self.manifest_url, + ) + except Exception as exc: + LOGGER.warning("Não foi possível verificar atualizações: %s", exc) + with self._lock: + self._error = str(exc) + delay = self._retry_delay(attempt) + attempt += 1 + if delay is None or self._stop_event.wait(delay): + return + LOGGER.info( + "Nova tentativa de atualização em %.0f segundos.", delay + ) + continue with self._lock: - self._error = str(exc) + self._pending = pending + self._error = None return - with self._lock: - self._pending = pending def wait(self, timeout: float | None = None) -> None: thread = self._thread diff --git a/tests/test_cli.py b/tests/test_cli.py index 893e4ac..83d1284 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -64,6 +64,11 @@ def test_parse_args_accepts_update_and_quit_flags() -> None: assert args.quit is True +def test_parse_args_accepts_apply_update() -> None: + args = parse_args(["--apply-update"]) + assert args.apply_update is True + + def test_quit_writes_request_in_data_dir(tmp_path: Path) -> None: result = _run( "--quit", @@ -137,6 +142,81 @@ def fail(): assert "sem rede" in capsys.readouterr().err +def test_apply_update_unavailable_outside_build(monkeypatch, capsys) -> None: + from learning_helper import app + from learning_helper.updates import install + + monkeypatch.setattr(install, "asset_key", lambda: None) + + assert app._apply_update() == 2 + assert "não disponível" in capsys.readouterr().err + + +def test_apply_update_downloads_and_starts( + tmp_path: Path, monkeypatch, capsys +) -> None: + from learning_helper import app + from learning_helper.updates import install, service + from learning_helper.updates.install import PendingUpdate + from learning_helper.updates.state import load_state + + pending = PendingUpdate( + "99.0.0", "linux_tarball", tmp_path / "pkg" + ) + applied = [] + monkeypatch.setattr(install, "asset_key", lambda: "linux_tarball") + monkeypatch.setattr( + service, "check_and_download", lambda *_args, **_kwargs: pending + ) + monkeypatch.setattr(app, "data_dir", lambda: tmp_path / "data") + monkeypatch.setattr( + install, + "apply_pending", + lambda item, base: applied.append((item, base)), + ) + + assert app._apply_update() == 0 + assert applied == [(pending, tmp_path / "data")] + assert "Atualização 99.0.0 iniciada" in capsys.readouterr().out + state = load_state(tmp_path / "data") + assert state.pending_version == "99.0.0" + assert state.attempts == 1 + + +def test_apply_update_reports_when_up_to_date( + tmp_path: Path, monkeypatch, capsys +) -> None: + from learning_helper import app + from learning_helper.updates import install, service + + monkeypatch.setattr(install, "asset_key", lambda: "linux_tarball") + monkeypatch.setattr( + service, "check_and_download", lambda *_args, **_kwargs: None + ) + monkeypatch.setattr(app, "data_dir", lambda: tmp_path / "data") + + assert app._apply_update() == 0 + assert "Nenhuma atualização disponível" in capsys.readouterr().out + + +def test_apply_update_returns_error_on_download_failure( + tmp_path: Path, monkeypatch, capsys +) -> None: + from learning_helper import app + from learning_helper.updates import install, service + from learning_helper.updates.manifest import UpdateError + + def fail(*_args, **_kwargs): + raise UpdateError("sem rede") + + monkeypatch.setattr(install, "asset_key", lambda: "linux_tarball") + monkeypatch.setattr(service, "check_and_download", fail) + monkeypatch.setattr(app, "data_dir", lambda: tmp_path / "data") + + assert app._apply_update() == 1 + assert "sem rede" in capsys.readouterr().err + + def test_bathroom_flags_persist_preference(tmp_path: Path) -> None: db_path = tmp_path / "learning_helper.db" env = {"XDG_DATA_HOME": str(tmp_path), "LOCALAPPDATA": str(tmp_path)} diff --git a/tests/test_update_manifest.py b/tests/test_update_manifest.py new file mode 100644 index 0000000..88ef915 --- /dev/null +++ b/tests/test_update_manifest.py @@ -0,0 +1,64 @@ +import hashlib +import importlib.util +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "packaging" / "make_update_manifest.py" + + +def _module(): + spec = importlib.util.spec_from_file_location("make_update_manifest", SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _write(path: Path, content: bytes) -> None: + path.write_bytes(content) + + +def test_build_manifest_can_select_windows_only(tmp_path: Path) -> None: + module = _module() + setup = tmp_path / "LearningHelper-0.9.0-Setup.exe" + _write(setup, b"setup") + + manifest = module.build_manifest( + "0.9.0", + tmp_path, + base_url="http://127.0.0.1:8765", + asset_keys=["windows_setup"], + ) + + assert manifest["version"] == "0.9.0" + assert list(manifest["assets"]) == ["windows_setup"] + asset = manifest["assets"]["windows_setup"] + assert asset["name"] == setup.name + assert asset["url"] == f"http://127.0.0.1:8765/{setup.name}" + assert asset["sha256"] == hashlib.sha256(b"setup").hexdigest() + + +def test_build_manifest_reports_missing_selected_asset(tmp_path: Path) -> None: + module = _module() + + with pytest.raises(SystemExit, match="Arquivos ausentes"): + module.build_manifest( + "0.9.0", + tmp_path, + base_url="http://127.0.0.1:8765", + asset_keys=["windows_setup"], + ) + + +def test_build_manifest_rejects_empty_selection(tmp_path: Path) -> None: + module = _module() + + with pytest.raises(SystemExit, match="Nenhum asset"): + module.build_manifest( + "0.9.0", + tmp_path, + base_url="http://127.0.0.1:8765", + asset_keys=[], + ) diff --git a/tests/test_updates.py b/tests/test_updates.py index 92f108d..a6e6fb0 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -260,7 +260,7 @@ def test_apply_appimage_replaces_file_from_script(tmp_path, monkeypatch) -> None assert spawned and spawned[0][0] == ["/bin/sh", str(script)] -def test_apply_windows_builds_silent_arguments(tmp_path, monkeypatch) -> None: +def test_apply_windows_writes_wrapper_script(tmp_path, monkeypatch) -> None: pending = install.PendingUpdate( "0.5.0", "windows_setup", tmp_path / "Setup.exe" ) @@ -269,6 +269,7 @@ def test_apply_windows_builds_silent_arguments(tmp_path, monkeypatch) -> None: calls = [] monkeypatch.setattr(sys, "executable", str(executable)) monkeypatch.setattr(install, "_windows_all_users", lambda: False) + monkeypatch.setattr(install, "_powershell_executable", lambda: "powershell.exe") monkeypatch.setattr( install.subprocess, "Popen", @@ -277,12 +278,23 @@ def test_apply_windows_builds_silent_arguments(tmp_path, monkeypatch) -> None: install._apply_windows(pending, base) + script = base / "updates" / install.WINDOWS_APPLY_SCRIPT + content = script.read_text(encoding="utf-8-sig") + assert "Wait-Process" in content + assert "Start-Process" in content + assert "UPDATERESTART=1" in content + assert "Installer exit code" in content + command, kwargs = calls[0] - assert "/VERYSILENT" in command - assert "/UPDATERESTART=1" in command + assert command[0] == "powershell.exe" + assert "-File" in command + assert str(script) in command + assert str(pending.path) in command + assert "-ParentPid" in command assert "/CURRENTUSER" in command - assert f'/DIR="{executable.parent}"' in command - assert f'/LOG="{base / "updates" / "apply.log"}"' in command + assert str(executable.parent) in command + assert str(base / "updates" / "apply.log") in command + assert str(base / "updates" / "setup-0.5.0.log") in command assert kwargs["stdin"] == install.subprocess.DEVNULL calls.clear() @@ -515,6 +527,52 @@ def fake_download(asset: Asset, destination): assert pending.version == "0.5.0" +def test_update_service_retries_after_transient_failure(tmp_path, monkeypatch) -> None: + pending = install.PendingUpdate( + "0.5.0", "linux_tarball", tmp_path / "pkg" + ) + calls = [] + + def flaky(*_args, **_kwargs): + calls.append(1) + if len(calls) == 1: + raise UpdateError("rede indisponível") + return pending + + monkeypatch.setattr(service, "check_and_download", flaky) + update_service = service.UpdateService( + "0.4.0", tmp_path, retry_delays=(0.01,) + ) + update_service.start() + update_service.wait(timeout=2) + + assert len(calls) == 2 + assert update_service.pending is pending + assert update_service.error is None + + +def test_update_service_stops_before_retry(tmp_path, monkeypatch) -> None: + calls = [] + started = threading.Event() + + def unavailable(*_args, **_kwargs): + calls.append(1) + started.set() + raise UpdateError("rede indisponível") + + monkeypatch.setattr(service, "check_and_download", unavailable) + update_service = service.UpdateService( + "0.4.0", tmp_path, retry_delays=(30.0,) + ) + update_service.start() + assert started.wait(1) + update_service.stop() + + assert len(calls) == 1 + assert update_service.pending is None + assert update_service.error == "rede indisponível" + + class _ApiHandler(BaseHTTPRequestHandler): payload = b"authenticated-package" From 5c8d2dbfd0f4e84c659d164302d60dd796cc741e Mon Sep 17 00:00:00 2001 From: Heros Date: Thu, 12 Nov 2026 17:53:18 -0300 Subject: [PATCH 2/7] =?UTF-8?q?fix:=20evita=20falhas=20do=20CLI=20gr=C3=A1?= =?UTF-8?q?fico=20e=20fecha=20o=20app=20antes=20de=20atualizar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O build do Windows não tem stdout/stderr; o comando --apply-update e o --version agora terminam com código correto. --apply-update também exige que o app principal esteja fechado para não haver dois instaladores. O teste E2E usa o Python do .venv, sem depender do cache do uv. --- README.md | 2 +- packaging/windows/test-update.ps1 | 15 ++++--- src/learning_helper/app.py | 67 ++++++++++++++++++++++--------- tests/test_cli.py | 33 +++++++++++++++ 4 files changed, 90 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 10c248d..170349f 100644 --- a/README.md +++ b/README.md @@ -383,7 +383,7 @@ Os alvos de empacotamento (`make build`, `make appimage`, `make tarball`, `make O workflow `package` tem um job `windows-update` que instala a versão atual, gera a versão seguinte, serve um `latest.json` local e valida a atualização completa (download, SHA-256, Setup silencioso, reinício e preservação do banco). Ele também testa a rejeição de um pacote com SHA-256 inválido. -Para repetir o teste manualmente em uma VM ou usuário de teste do Windows, instale o Inno Setup 6 e rode: +Para repetir o teste manualmente em uma VM ou usuário de teste do Windows, instale o Inno Setup 6, rode `uv sync --group dev` e execute: ```powershell powershell -NoProfile -ExecutionPolicy Bypass -File packaging/windows/test-update.ps1 ` diff --git a/packaging/windows/test-update.ps1 b/packaging/windows/test-update.ps1 index 677a4a9..a6c71ec 100644 --- a/packaging/windows/test-update.ps1 +++ b/packaging/windows/test-update.ps1 @@ -10,7 +10,10 @@ param( $ErrorActionPreference = "Stop" $root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) $tempRoot = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } else { $env:TEMP } -$uv = (Get-Command uv -ErrorAction Stop).Source +$python = Join-Path $root ".venv\Scripts\python.exe" +if (!(Test-Path -LiteralPath $python)) { + throw "Ambiente .venv nao encontrado. Rode 'uv sync --group dev' antes do teste." +} Set-Location $root function Write-Step { @@ -133,13 +136,13 @@ try { $check = Join-Path $tempRoot "learning-helper-update-check.py" Write-SeedScript -Path $seed Write-CheckScript -Path $check - uv run python $seed + & $python $seed if ($LASTEXITCODE -ne 0) { throw "Falha ao preparar o banco de teste" } Write-Step "Gerando manifesto local para B" - uv run python packaging/make_update_manifest.py ` + & $python packaging/make_update_manifest.py ` --version $VersionB ` --dist $distDir ` --base-url "http://127.0.0.1:$Port" ` @@ -149,8 +152,8 @@ try { } Write-Step "Servindo $distDir em http://127.0.0.1:$Port" - $server = Start-Process -FilePath $uv -WindowStyle Hidden -PassThru -ArgumentList @( - "run", "python", "-m", "http.server", $Port, "--directory", $distDir + $server = Start-Process -FilePath $python -WindowStyle Hidden -PassThru -ArgumentList @( + "-m", "http.server", $Port, "--directory", $distDir ) $ready = $false for ($i = 0; $i -lt 40; $i++) { @@ -184,7 +187,7 @@ try { Start-Sleep -Seconds 1 Write-Step "Conferindo banco preservado" - uv run python $check + & $python $check if ($LASTEXITCODE -ne 0) { throw "Os dados de teste nao foram preservados" } diff --git a/src/learning_helper/app.py b/src/learning_helper/app.py index e3de817..a34e114 100644 --- a/src/learning_helper/app.py +++ b/src/learning_helper/app.py @@ -26,6 +26,19 @@ LOG_BACKUPS = 2 +def _ensure_std_streams() -> None: + """Evita erro de `print` em builds gráficos do Windows. + + O PyInstaller com ``console=False`` deixa ``sys.stdout``/``sys.stderr`` + como ``None``. As opções de linha de comando ainda precisam terminar com o + código de saída correto, mesmo sem um console visível. + """ + if sys.stdout is None: + sys.stdout = open(os.devnull, "w", encoding="utf-8") + if sys.stderr is None: + sys.stderr = open(os.devnull, "w", encoding="utf-8") + + def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description="Learning helper") parser.add_argument( @@ -240,28 +253,41 @@ def _apply_update() -> int: return 2 base = data_dir() - try: - pending = check_and_download(__version__, base, force=True) - except UpdateError as exc: - print(f"Não foi possível baixar a atualização: {exc}", file=sys.stderr) + lock = SingleInstance(base / "app.lock") + if not lock.acquire(): + print( + "O app principal está em execução; feche-o antes de usar " + "--apply-update.", + file=sys.stderr, + ) return 1 - if pending is None: - print(f"Nenhuma atualização disponível para {__version__}.") - return 0 - - state = load_state(base) - record_attempt(state, pending.version, pending.path) - save_state(base, state) try: - apply_pending(pending, base) - except Exception as exc: - print(f"Falha ao aplicar a atualização: {exc}", file=sys.stderr) - return 1 - print( - f"Atualização {pending.version} iniciada. " - "O app deve reabrir na versão nova." - ) - return 0 + try: + pending = check_and_download(__version__, base, force=True) + except UpdateError as exc: + print( + f"Não foi possível baixar a atualização: {exc}", file=sys.stderr + ) + return 1 + if pending is None: + print(f"Nenhuma atualização disponível para {__version__}.") + return 0 + + state = load_state(base) + record_attempt(state, pending.version, pending.path) + save_state(base, state) + try: + apply_pending(pending, base) + except Exception as exc: + print(f"Falha ao aplicar a atualização: {exc}", file=sys.stderr) + return 1 + print( + f"Atualização {pending.version} iniciada. " + "O app deve reabrir na versão nova." + ) + return 0 + finally: + lock.release() def _handle_autostart(args: argparse.Namespace) -> int | None: @@ -348,6 +374,7 @@ def _run_first_run_settings(store: Store) -> None: def main(argv: list[str] | None = None) -> int: + _ensure_std_streams() args = parse_args(argv if argv is not None else sys.argv[1:]) if args.self_check: return self_check() diff --git a/tests/test_cli.py b/tests/test_cli.py index 83d1284..5a1af13 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -29,6 +29,18 @@ def test_version_flag() -> None: assert __version__ in result.stdout +def test_ensure_std_streams_handles_windowed_build(monkeypatch) -> None: + from learning_helper import app + + monkeypatch.setattr(sys, "stdout", None) + monkeypatch.setattr(sys, "stderr", None) + + app._ensure_std_streams() + + assert sys.stdout is not None + assert sys.stderr is not None + + def test_self_check_passes_without_touching_user_data(tmp_path: Path) -> None: result = _run( "--self-check", @@ -217,6 +229,27 @@ def fail(*_args, **_kwargs): assert "sem rede" in capsys.readouterr().err +def test_apply_update_requires_app_closed( + tmp_path: Path, monkeypatch, capsys +) -> None: + from learning_helper import app + from learning_helper.updates import install + + class BusyLock: + def acquire(self) -> bool: + return False + + def release(self) -> None: + return None + + monkeypatch.setattr(install, "asset_key", lambda: "linux_tarball") + monkeypatch.setattr(app, "data_dir", lambda: tmp_path / "data") + monkeypatch.setattr(app, "SingleInstance", lambda _path: BusyLock()) + + assert app._apply_update() == 1 + assert "em execução" in capsys.readouterr().err + + def test_bathroom_flags_persist_preference(tmp_path: Path) -> None: db_path = tmp_path / "learning_helper.db" env = {"XDG_DATA_HOME": str(tmp_path), "LOCALAPPDATA": str(tmp_path)} From ee581215332e35887c792378c624ee704bb9166f Mon Sep 17 00:00:00 2001 From: Heros Date: Thu, 12 Nov 2026 17:57:53 -0300 Subject: [PATCH 3/7] =?UTF-8?q?fix:=20melhora=20o=20diagn=C3=B3stico=20da?= =?UTF-8?q?=20atualiza=C3=A7=C3=A3o=20no=20Windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Anexa ao console do processo pai para que --version/--check-updates mostrem saída em builds gráficos, informa o diretório de dados na checagem e espera o wrapper terminar antes de ler o apply.log no teste E2E. --- README.md | 2 +- packaging/windows/test-update.ps1 | 24 ++++++++++++++++++------ src/learning_helper/app.py | 20 ++++++++++++++++++-- src/learning_helper/updates/install.py | 1 - 4 files changed, 37 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 170349f..c79524d 100644 --- a/README.md +++ b/README.md @@ -214,7 +214,7 @@ Também é possível forçar o download e a aplicação pelo terminal, sem abrir & "$env:LOCALAPPDATA\Programs\LearningHelper\learning-helper.exe" --apply-update ``` -O comando só funciona em builds instalados. Ele baixa o pacote, confere o SHA-256 e dispara a instalação; o app reabre na versão nova. +O comando só funciona em builds instalados e exige que o app principal esteja fechado, para não haver dois instaladores ao mesmo tempo. Ele baixa o pacote, confere o SHA-256 e dispara a instalação; o app reabre na versão nova. ### Repositório público, token e espelhos diff --git a/packaging/windows/test-update.ps1 b/packaging/windows/test-update.ps1 index a6c71ec..7f3f807 100644 --- a/packaging/windows/test-update.ps1 +++ b/packaging/windows/test-update.ps1 @@ -183,6 +183,23 @@ try { if (!(Wait-InstalledVersion -App $app -Expected $VersionB)) { throw "O aplicativo nao chegou a versao $VersionB" } + + $log = Join-Path $testLocal "learning_helper\updates\apply.log" + $logReady = $false + for ($i = 0; $i -lt 60; $i++) { + if (Test-Path -LiteralPath $log) { + $logContent = Get-Content -LiteralPath $log -Raw + if ($logContent -match "Update applied|Update failed") { + $logReady = $true + break + } + } + Start-Sleep -Seconds 1 + } + if (!$logReady) { + throw "O wrapper da atualizacao nao terminou a tempo" + } + Stop-LearningHelper Start-Sleep -Seconds 1 @@ -192,11 +209,6 @@ try { throw "Os dados de teste nao foram preservados" } - $log = Join-Path $testLocal "learning_helper\updates\apply.log" - if (!(Test-Path -LiteralPath $log)) { - throw "apply.log nao foi criado" - } - $logContent = Get-Content -LiteralPath $log -Raw Write-Host $logContent if ($logContent -notmatch "Installer exit code: 0") { throw "O instalador nao terminou com sucesso" @@ -215,7 +227,7 @@ try { } $badPath = Join-Path $distDir "latest-bad.json" $badManifest | ConvertTo-Json -Depth 6 | - Set-Content -LiteralPath $badPath -Encoding UTF8 + Set-Content -LiteralPath $badPath -Encoding ASCII $env:LEARNING_HELPER_UPDATE_URL = "http://127.0.0.1:$Port/latest-bad.json" $bad = Start-Process -FilePath $app -Wait -PassThru -ArgumentList "--apply-update" diff --git a/src/learning_helper/app.py b/src/learning_helper/app.py index a34e114..dd27e57 100644 --- a/src/learning_helper/app.py +++ b/src/learning_helper/app.py @@ -30,9 +30,24 @@ def _ensure_std_streams() -> None: """Evita erro de `print` em builds gráficos do Windows. O PyInstaller com ``console=False`` deixa ``sys.stdout``/``sys.stderr`` - como ``None``. As opções de linha de comando ainda precisam terminar com o - código de saída correto, mesmo sem um console visível. + como ``None``. Se o comando foi chamado a partir de um terminal, tenta + anexar ao console do processo pai para que ``--version`` e + ``--check-updates`` continuem visíveis. Sem console, descarta a saída mas + preserva o código de saída. """ + if sys.stdout is not None and sys.stderr is not None: + return + if sys.platform == "win32": + try: + import ctypes + + if ctypes.windll.kernel32.AttachConsole(-1): + if sys.stdout is None: + sys.stdout = open("CONOUT$", "w", buffering=1, errors="replace") + if sys.stderr is None: + sys.stderr = open("CONOUT$", "w", buffering=1, errors="replace") + except Exception: + pass if sys.stdout is None: sys.stdout = open(os.devnull, "w", encoding="utf-8") if sys.stderr is None: @@ -214,6 +229,7 @@ def _check_updates() -> int: from learning_helper.updates.install import select_asset from learning_helper.updates.manifest import UpdateError, is_newer + print(f"Versão atual: {__version__}; dados: {data_dir()}") try: release = fetch_manifest() except UpdateError as exc: diff --git a/src/learning_helper/updates/install.py b/src/learning_helper/updates/install.py index 8a4a4f2..4dcd0c8 100644 --- a/src/learning_helper/updates/install.py +++ b/src/learning_helper/updates/install.py @@ -90,7 +90,6 @@ """ - @dataclass(frozen=True) class PendingUpdate: version: str From c8d1c97ca9620aa6660c0a58a2675afe08fa8b22 Mon Sep 17 00:00:00 2001 From: Heros Date: Thu, 12 Nov 2026 18:04:28 -0300 Subject: [PATCH 4/7] =?UTF-8?q?fix:=20registra=20falhas=20do=20wrapper=20P?= =?UTF-8?q?owerShell=20da=20atualiza=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Usa CREATE_NO_WINDOW para dar um console oculto ao PowerShell e grava stdout/stderr em updates/spawn.log. O teste A -> B falhou sem apply.log; o novo log mostra se o processo não iniciou, se o script foi bloqueado ou se o Setup falhou. --- src/learning_helper/updates/install.py | 72 ++++++++++++++------------ tests/test_updates.py | 3 ++ 2 files changed, 42 insertions(+), 33 deletions(-) diff --git a/src/learning_helper/updates/install.py b/src/learning_helper/updates/install.py index 4dcd0c8..6c3ce3e 100644 --- a/src/learning_helper/updates/install.py +++ b/src/learning_helper/updates/install.py @@ -200,43 +200,49 @@ def _apply_windows(pending: PendingUpdate, base: Path) -> None: script = Path(base) / "updates" / WINDOWS_APPLY_SCRIPT _write_powershell_script(script) + # CREATE_NO_WINDOW dá um console oculto ao PowerShell. DETACHED_PROCESS + # deixava alguns runners sem console e o wrapper morria antes de gravar o + # primeiro log, sem deixar rastro. flags = 0 - flags |= getattr(subprocess, "DETACHED_PROCESS", 0) + flags |= getattr(subprocess, "CREATE_NO_WINDOW", 0) flags |= getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) scope = "/ALLUSERS" if _windows_all_users() else "/CURRENTUSER" executable = Path(sys.executable).resolve() - subprocess.Popen( - [ - _powershell_executable(), - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Bypass", - "-WindowStyle", - "Hidden", - "-File", - str(script), - "-ParentPid", - str(os.getpid()), - "-Setup", - str(pending.path), - "-App", - str(executable), - "-InstallDir", - str(executable.parent), - "-Scope", - scope, - "-Log", - str(log_path), - "-SetupLog", - str(setup_log), - ], - stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - close_fds=True, - creationflags=flags, - ) + command = [ + _powershell_executable(), + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + str(script), + "-ParentPid", + str(os.getpid()), + "-Setup", + str(pending.path), + "-App", + str(executable), + "-InstallDir", + str(executable.parent), + "-Scope", + scope, + "-Log", + str(log_path), + "-SetupLog", + str(setup_log), + ] + spawn_log = Path(base) / "updates" / "spawn.log" + with spawn_log.open("a", encoding="utf-8") as output: + output.write(f"Starting update wrapper: {command!r}\n") + output.flush() + subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=output, + stderr=subprocess.STDOUT, + close_fds=True, + creationflags=flags, + ) def _safe_extract(archive: Path, destination: Path) -> None: diff --git a/tests/test_updates.py b/tests/test_updates.py index a6e6fb0..3ebd344 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -296,6 +296,9 @@ def test_apply_windows_writes_wrapper_script(tmp_path, monkeypatch) -> None: assert str(base / "updates" / "apply.log") in command assert str(base / "updates" / "setup-0.5.0.log") in command assert kwargs["stdin"] == install.subprocess.DEVNULL + spawn_log = base / "updates" / "spawn.log" + assert "Starting update wrapper" in spawn_log.read_text(encoding="utf-8") + assert str(pending.path) in spawn_log.read_text(encoding="utf-8") calls.clear() monkeypatch.setattr(install, "_windows_all_users", lambda: True) From 20811e7ae7d8b1fa6b65d5335022377096f866c1 Mon Sep 17 00:00:00 2001 From: Heros Date: Thu, 12 Nov 2026 18:19:44 -0300 Subject: [PATCH 5/7] test: limita espera do --apply-update no teste Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Start-Process -Wait pode esperar processos reabertos pelo instalador e travar o job. Usa WaitForExit com timeout, imprime spawn.log/apply.log no finally e falha rápido se o comando não terminar. --- packaging/windows/test-update.ps1 | 41 +++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/packaging/windows/test-update.ps1 b/packaging/windows/test-update.ps1 index 7f3f807..c662bb4 100644 --- a/packaging/windows/test-update.ps1 +++ b/packaging/windows/test-update.ps1 @@ -46,6 +46,23 @@ function Wait-InstalledVersion { return $false } +function Invoke-AppCommand { + param( + [Parameter(Mandatory = $true)][string]$App, + [Parameter(Mandatory = $true)][string]$Arguments, + [int]$TimeoutSeconds = 60 + ) + # Nao use Start-Process -Wait aqui: em alguns runners ele espera tambem + # pelo processo reaberto pelo instalador, que fica rodando para sempre. + $process = Start-Process -FilePath $App -ArgumentList $Arguments -PassThru + if (!$process.WaitForExit($TimeoutSeconds * 1000)) { + Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue + throw "O comando '$Arguments' nao terminou em $TimeoutSeconds s" + } + $process.Refresh() + return $process.ExitCode +} + function Stop-LearningHelper { Get-Process -Name "learning-helper" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue @@ -175,9 +192,9 @@ try { Write-Step "Aplicando atualizacao A -> B" $env:LEARNING_HELPER_UPDATE_URL = "http://127.0.0.1:$Port/latest.json" Remove-Item Env:LEARNING_HELPER_NO_UPDATE -ErrorAction SilentlyContinue - $apply = Start-Process -FilePath $app -Wait -PassThru -ArgumentList "--apply-update" - if ($apply.ExitCode -ne 0) { - throw "Falha ao iniciar a atualizacao (exit $($apply.ExitCode))" + $applyExit = Invoke-AppCommand -App $app -Arguments "--apply-update" -TimeoutSeconds 60 + if ($applyExit -ne 0) { + throw "Falha ao iniciar a atualizacao (exit $applyExit)" } if (!(Wait-InstalledVersion -App $app -Expected $VersionB)) { @@ -230,8 +247,8 @@ try { Set-Content -LiteralPath $badPath -Encoding ASCII $env:LEARNING_HELPER_UPDATE_URL = "http://127.0.0.1:$Port/latest-bad.json" - $bad = Start-Process -FilePath $app -Wait -PassThru -ArgumentList "--apply-update" - if ($bad.ExitCode -eq 0) { + $badExit = Invoke-AppCommand -App $app -Arguments "--apply-update" -TimeoutSeconds 60 + if ($badExit -eq 0) { throw "Atualizacao com SHA-256 invalido foi aceita" } if ((Get-InstalledVersion -App $app) -ne $VersionB) { @@ -240,6 +257,20 @@ try { Write-Step "Falha de SHA-256 rejeitada corretamente" } finally { Stop-LearningHelper + $updatesDir = Join-Path $testLocal "learning_helper\updates" + if (Test-Path -LiteralPath $updatesDir) { + Write-Step "Diagnostico da atualizacao" + Get-ChildItem -LiteralPath $updatesDir -Force | + Format-Table Name, Length, LastWriteTime | + Out-String | Write-Host + foreach ($name in @("spawn.log", "apply.log")) { + $path = Join-Path $updatesDir $name + if (Test-Path -LiteralPath $path) { + Write-Host "--- $name" + Get-Content -LiteralPath $path | Write-Host + } + } + } if ($server -and !$server.HasExited) { Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue } From 5180a488480fd444dd563752e906d9be00719ffc Mon Sep 17 00:00:00 2001 From: Heros Date: Thu, 12 Nov 2026 18:28:24 -0300 Subject: [PATCH 6/7] =?UTF-8?q?fix:=20n=C3=A3o=20espera=20o=20app=20reaber?= =?UTF-8?q?to=20ao=20aplicar=20a=20atualiza=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit O Start-Process -Wait do wrapper esperava o app iniciado pelo [Run] do Inno Setup, atrasando o apply.log. Usa WaitForExit no processo do Setup, com timeout de 5 minutos; o teste Windows agora valida essa regressão. --- src/learning_helper/updates/install.py | 17 +++++++++++++---- tests/test_updates.py | 2 ++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/learning_helper/updates/install.py b/src/learning_helper/updates/install.py index 6c3ce3e..0c93ee8 100644 --- a/src/learning_helper/updates/install.py +++ b/src/learning_helper/updates/install.py @@ -63,13 +63,22 @@ ('/DIR="{0}"' -f $InstallDir), ('/LOG="{0}"' -f $SetupLog) ) - $process = Start-Process -FilePath $Setup -ArgumentList $arguments -Wait -PassThru - Write-UpdateLog ("Installer exit code: " + $process.ExitCode) + $process = Start-Process -FilePath $Setup -ArgumentList $arguments -PassThru + # Não use -Wait: o Setup inicia o app novo em [Run], e o -Wait do + # PowerShell pode esperar esse app (que fica aberto) em vez de retornar + # quando o instalador termina. WaitForExit espera só o processo do Setup. + if (-not $process.WaitForExit(300000)) { + Write-UpdateLog "Installer timed out; restarting the current version." + Start-LearningHelper + exit 1 + } + $exitCode = $process.ExitCode + Write-UpdateLog ("Installer exit code: " + $exitCode) - if ($process.ExitCode -ne 0) { + if ($exitCode -ne 0) { Write-UpdateLog "Update failed; restarting the current version." Start-LearningHelper - exit $process.ExitCode + exit $exitCode } # O instalador usa /UPDATERESTART=1, mas garantir que exista uma instância diff --git a/tests/test_updates.py b/tests/test_updates.py index 3ebd344..17cbe54 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -284,6 +284,8 @@ def test_apply_windows_writes_wrapper_script(tmp_path, monkeypatch) -> None: assert "Start-Process" in content assert "UPDATERESTART=1" in content assert "Installer exit code" in content + assert "WaitForExit(300000)" in content + assert "-Wait -PassThru" not in content command, kwargs = calls[0] assert command[0] == "powershell.exe" From 0e830c5acd2db5f10cc87e090972660dbcd234c0 Mon Sep 17 00:00:00 2001 From: Heros Date: Thu, 12 Nov 2026 18:37:13 -0300 Subject: [PATCH 7/7] test: compara caminho escapado no spawn.log do Windows No Windows, repr() da lista de argumentos escapa as barras invertidas; o teste falhava apenas por comparar o caminho sem escape. --- tests/test_updates.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test_updates.py b/tests/test_updates.py index 17cbe54..5c677e0 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -299,8 +299,11 @@ def test_apply_windows_writes_wrapper_script(tmp_path, monkeypatch) -> None: assert str(base / "updates" / "setup-0.5.0.log") in command assert kwargs["stdin"] == install.subprocess.DEVNULL spawn_log = base / "updates" / "spawn.log" - assert "Starting update wrapper" in spawn_log.read_text(encoding="utf-8") - assert str(pending.path) in spawn_log.read_text(encoding="utf-8") + spawn_text = spawn_log.read_text(encoding="utf-8") + assert "Starting update wrapper" in spawn_text + # O log grava a lista com repr(), que escapa as barras invertidas do + # caminho no Windows; por isso a comparação precisa usar o mesmo formato. + assert repr(str(pending.path)) in spawn_text calls.clear() monkeypatch.setattr(install, "_windows_all_users", lambda: True)