Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,15 @@ releases and the AppStream metadata.
focus is removed, so ZapZap no longer writes to the clipboard when it gains
focus (#498, #523, #969). Its tests are replaced with tests for the new
selection rules and for the paste script in a real WebEngine page.
- Stop a second instance from opening the profile while an earlier ZapZap
process still holds it but no longer answers on the single-instance socket
(#1038). The second instance showed the QR login page and reset the quota
database. Each instance now takes a lock file in the data directory before
it creates any WebEngine profile, and exits with a message naming the other
process when the lock stays taken. A successor started by "Restart
application" waits up to 10 seconds for the old process to exit, and the
lock of a crashed or killed process is taken over. Add regression tests
that run real separate instances.

## [7.5.1] - 2026-10-15

Expand Down
6 changes: 5 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,11 @@ ao `QApplication`, portanto sobrevivem a uma reconstrução apenas da interface
sem repetir a consulta.

`SingleApplication` também coordena mensagens entre instâncias, reinício apenas
da interface e reinício completo do processo. Configurações lidas antes da
da interface e reinício completo do processo. Quando o socket local não responde,
a instância toma `instance.lock` (`QLockFile`) no diretório de dados antes de
criar qualquer perfil WebEngine; se outro processo vivo ainda o mantém, sai com
uma mensagem em vez de abrir o mesmo perfil. A espera de até 10 segundos cobre o
reinício completo, cujo sucessor inicia antes de o processo antigo terminar. Configurações lidas antes da
criação do QtWebEngine, como escala, plataforma gráfica e flags Chromium,
normalmente exigem reinício completo.

Expand Down
2 changes: 2 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ documente o que ele protege.
| `test_settings_card.py` | divisores e grupos do card compartilhado em `ui.components` |
| `test_settings_lazy_loading.py` | subprocessos de importação, registro e instanciação lazy, singleton por painel, diagnóstico, empacotamento, APIs públicas e fechamento de Configurações |
| `test_settings_radio_group.py` | divisores do grupo de rádio em `ui.components` |
| `test_single_instance_lock.py` | trava de instância em subprocessos reais: processo vivo sem socket, trava de processo morto e reinício completo |
| `test_software_video_decoding.py` | presets, flags Chromium de renderização/strict proxy, persistência e ordem do bootstrap |
| `test_spellcheck_language_picker.py` | migração, seleção múltipla transacional, pesquisa, limite, recentes, menu e perfis WebEngine |
| `test_taskbar_badge.py` | contador nativo, zero, preferência, bandeja oculta, ativação primária/contexto por backend, integração StatusNotifier/AppIndicator, reabertura do painel e reconexão após reinício da interface, compatibilidade com Qt anterior |
Expand Down Expand Up @@ -234,6 +235,7 @@ documente o que ele protege.
- `test_settings_card.py`
- `test_settings_lazy_loading.py`
- `test_settings_radio_group.py`
- `test_single_instance_lock.py`
- `test_software_video_decoding.py`
- `test_spellcheck_language_picker.py`
- `test_system_startup_settings_ui.py`
Expand Down
123 changes: 123 additions & 0 deletions tests/test_single_instance_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""Regression tests for the single-instance profile lock (#1038).

Each instance runs in its own process, because a process can create only one
QApplication. The processes share a throwaway data directory and socket
directory, so they never touch a real profile.
"""

import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
import unittest


REPOSITORY_ROOT = Path(__file__).resolve().parents[1]

# argv: <lock timeout ms> <seconds to run> <remove socket: 0|1>
CHILD = """
import os, sys
from PyQt6.QtCore import QCoreApplication, QDir, QTimer
QCoreApplication.setApplicationName("ZapZap")
from zapzap.app.single_application import SingleApplication
SingleApplication.INSTANCE_LOCK_TIMEOUT_MS = int(sys.argv[1])
app = SingleApplication("zapzap-lock-test", ["zapzap"])
if sys.argv[3] == "1":
os.remove(os.path.join(QDir.tempPath(), "zapzap-lock-test"))
print("STARTED", flush=True)
QTimer.singleShot(int(float(sys.argv[2]) * 1000), app.quit)
app.exec()
"""


@unittest.skipUnless(
sys.platform.startswith("linux"),
"uses XDG_DATA_HOME and a socket file in TMPDIR",
)
class SingleInstanceLockTests(unittest.TestCase):
def setUp(self):
self._dir = tempfile.TemporaryDirectory(prefix="zapzap-lock-")
root = Path(self._dir.name)
for name in ("data", "tmp"):
(root / name).mkdir()
self.env = dict(
os.environ,
XDG_DATA_HOME=str(root / "data"),
TMPDIR=str(root / "tmp"),
QT_QPA_PLATFORM="offscreen",
PYTHONPATH=str(REPOSITORY_ROOT),
)
self.lock_path = root / "data" / "ZapZap" / "instance.lock"
self.socket_path = root / "tmp" / "zapzap-lock-test"
self.processes = []

def tearDown(self):
for process in self.processes:
if process.poll() is None:
process.kill()
process.communicate()
self._dir.cleanup()

def start(self, timeout_ms=1000, seconds=60, remove_socket=False):
process = subprocess.Popen(
[sys.executable, "-c", CHILD,
str(timeout_ms), str(seconds), "1" if remove_socket else "0"],
env=self.env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
self.processes.append(process)
return process

def wait_started(self, process):
self.assertEqual(process.stdout.readline().strip(), "STARTED")

def test_live_instance_without_socket_blocks_second_instance(self):
first = self.start(remove_socket=True)
self.wait_started(first)
# A long-running instance holds an old lock file; its age must not
# make the lock look stale.
old = time.time() - 3600
os.utime(self.lock_path, (old, old))

second = self.start(seconds=1)
stdout, stderr = second.communicate(timeout=30)

self.assertEqual(second.returncode, 1, stderr)
self.assertNotIn("STARTED", stdout)
self.assertIn(f"already running (PID {first.pid})", stderr)
self.assertIsNone(first.poll())

def test_lock_left_by_killed_instance_is_taken_over(self):
first = self.start()
self.wait_started(first)
os.kill(first.pid, signal.SIGKILL)
first.wait()
self.assertTrue(self.lock_path.exists())

second = self.start(seconds=1)
stdout, stderr = second.communicate(timeout=30)

self.assertEqual(second.returncode, 0, stderr)
self.assertIn("STARTED", stdout)

def test_successor_waits_for_exiting_instance(self):
# Like a restart: the old instance has closed its socket and exits
# a moment after the new one starts.
first = self.start(seconds=2, remove_socket=True)
self.wait_started(first)

second = self.start(timeout_ms=15000, seconds=1)
stdout, stderr = second.communicate(timeout=30)

self.assertEqual(first.wait(timeout=10), 0)
self.assertEqual(second.returncode, 0, stderr)
self.assertIn("STARTED", stdout)


if __name__ == "__main__":
unittest.main(verbosity=2)
41 changes: 40 additions & 1 deletion zapzap/app/single_application.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
"""Single-instance QApplication implementation."""

import os
import subprocess
import sys

from PyQt6.QtCore import Qt, QTextStream, QTimer, pyqtSignal, pyqtSlot
from PyQt6.QtCore import (
QLockFile,
QStandardPaths,
Qt,
QTextStream,
QTimer,
pyqtSignal,
pyqtSlot,
)
from PyQt6.QtNetwork import QLocalServer, QLocalSocket
from PyQt6.QtWidgets import QApplication


class SingleApplication(QApplication):
RESTART_MESSAGE = "zapzap://restart"
INSTANCE_LOCK_NAME = "instance.lock"
# A restarting instance starts its successor before it finishes exiting.
INSTANCE_LOCK_TIMEOUT_MS = 10000

messageReceived = pyqtSignal(str)

Expand All @@ -28,6 +40,7 @@ def __init__(self, appid, *argv):
self.window = None
self._window_factory = None
self._interface_restarting = False
self._instanceLock = None

if self._isRunning:
self._outStream = QTextStream(self._outSocket)
Expand All @@ -37,6 +50,7 @@ def __init__(self, appid, *argv):
break
sys.exit(0)
else:
self._acquireInstanceLock()
error = self._outSocket.error()
if error == QLocalSocket.LocalSocketError.ConnectionRefusedError:
self.close()
Expand All @@ -46,6 +60,31 @@ def __init__(self, appid, *argv):
self._server.listen(self._appid)
self._server.newConnection.connect(self._onNewConnection)

def _acquireInstanceLock(self):
"""Exit when another live process still holds the profile data.

The local socket alone cannot tell, because a process can stay alive
without it. QLockFile frees the lock of a dead process by itself.
"""
data_dir = QStandardPaths.writableLocation(
QStandardPaths.StandardLocation.AppDataLocation)
os.makedirs(data_dir, exist_ok=True)
lock = QLockFile(os.path.join(data_dir, self.INSTANCE_LOCK_NAME))
if lock.tryLock(self.INSTANCE_LOCK_TIMEOUT_MS):
self._instanceLock = lock
return
# An unwritable data directory is not proof of another instance.
if lock.error() != QLockFile.LockError.LockFailedError:
return

_found, pid, _host, _app = lock.getLockInfo()
print(
f"ZapZap is already running (PID {pid}) but does not answer. "
"Close that process and start ZapZap again.",
file=sys.stderr,
)
sys.exit(1)

def close(self):
if self._inSocket:
self._inSocket.disconnectFromServer()
Expand Down