diff --git a/DOCS-web-control-api.md b/DOCS-web-control-api.md index 7cec01f..f884b9b 100644 --- a/DOCS-web-control-api.md +++ b/DOCS-web-control-api.md @@ -60,7 +60,7 @@ mirror is `web/src/api/contract.ts`; change both together or neither. | GET | `/api/jobs/{id}` | – | `Job` | | GET | `/api/jobs/{id}/events` | `?token=&after=` | SSE stream of `JobEvent` | | POST | `/api/jobs/{id}/answer` | `PromptAnswer` | `204` | -| POST | `/api/jobs/{id}/cancel` | – | `204` (only if `CommandSpec.cancellable`) | +| POST | `/api/jobs/{id}/cancel` | – | `204` (only if `CommandSpec.cancellable`, or while the job's `cancel_window` is open) | | POST | `/api/pending/{id}/heartbeat` | – | `PendingAction` | | POST | `/api/pending/{id}/commit` | `{confirm_phrase}` | `Job` | | DELETE | `/api/pending/{id}` | – | `204` | @@ -134,7 +134,14 @@ with explicit params, a `Progress` reporter and a `Prompter`. `result.json`. The server only tails files, so jobs survive both page reloads and server restarts (including `_serve_stale` retirement). - At most **one mutating job** at a time (`busy` otherwise). Read-only jobs - (`check`, `stats`, `list`, …) may run alongside. + (`stats`, `list`) may run alongside. `check` is mutating, like `done`: a + new achievement releases the game and assigns the next one. +- `done`, `check`, `pick`, `pick-manual` and `hide` cannot be cancelled, + except while they hide games in the Steam library (the `cancel_window` + event below; `check` has the flag but no hide step today, so it never + opens a window). That phase can wait on a Steam launch, and the job holds + the mutating lock throughout. Cancelling there skips the hide; the job then carries on and ends normally, so the + lock drops. - History: last 50 job dirs kept, older ones pruned at job start. Job ids are `Z-<6 hex>`, so sorting by id is creation order even within one second. @@ -157,6 +164,14 @@ with explicit params, a `Progress` reporter and a `Prompter`. - `progress` — `{step, total, label, item?, eta_seconds?}`; `total` may be `null` for indeterminate phases. Any operation over 2 s must emit determinate progress. +- `cancel_window` — `{open}`, only from commands flagged `cancel_window` in + `jobs/_specs.py` (`done`, `check`, `pick`, `pick-manual`, `hide`): + `open: true` when the job starts hiding games in the Steam library, + `open: false` when it stops (also after a cancel). The job installs its SIGTERM handler before it + writes `open: true` and restores the previous one before `open: false`. + `POST /api/jobs/{id}/cancel` is accepted exactly while the latest + `cancel_window` event says `open`, else `not_cancellable`; the UI shows + its Cancel button on the same condition. Declared in `jobContract.ts`. - `prompt` — `{prompt_id, kind, message, options?, phrase?, default?, app_ids?}`; `kind` is `choice` (pick one of `options`), `confirm` (yes/no), `phrase` (type `phrase` exactly), `text` or `game`. The job diff --git a/steam_backlog_enforcer/_cancel_window.py b/steam_backlog_enforcer/_cancel_window.py new file mode 100644 index 0000000..fbafe2c --- /dev/null +++ b/steam_backlog_enforcer/_cancel_window.py @@ -0,0 +1,39 @@ +"""A stretch of a command during which a web job may be cancelled. + +Most commands cannot be stopped midway, but the library-hiding phase of +``done`` and ``check`` can: it only drives Steam, and a hide that is aborted is +already a skip. The command code marks that phase with :func:`cancel_window`; +*who* acts on the mark is decided by the caller, exactly like +:mod:`steam_backlog_enforcer._progress`. The CLI and the root daemon install +nothing, so for them the window is a no-op; a web job installs one that +announces it to the server and turns SIGTERM into a skipped hide. +""" + +from __future__ import annotations + +from contextlib import AbstractContextManager, contextmanager, nullcontext +from contextvars import ContextVar +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + WindowFactory = Callable[[], AbstractContextManager[None]] + +_ACTIVE: ContextVar[WindowFactory | None] = ContextVar("cancel_window", default=None) + + +def cancel_window() -> AbstractContextManager[None]: + """Return the context manager that brackets a cancellable phase.""" + factory = _ACTIVE.get() + return nullcontext() if factory is None else factory() + + +@contextmanager +def use_cancel_window(factory: WindowFactory) -> Iterator[None]: + """Make *factory* build the cancel windows for the duration of the context.""" + token = _ACTIVE.set(factory) + try: + yield + finally: + _ACTIVE.reset(token) diff --git a/steam_backlog_enforcer/_steam_errors.py b/steam_backlog_enforcer/_steam_errors.py index 1d0ad29..9c65288 100644 --- a/steam_backlog_enforcer/_steam_errors.py +++ b/steam_backlog_enforcer/_steam_errors.py @@ -60,3 +60,13 @@ class FastInstallInProgressError(SteamUnavailableError): underneath it discards the manifest the installer is about to write and resumes the slow client download - so every launch path defers instead. """ + + +class HidingCancelledError(SteamUnavailableError): + """Raised inside a job's library-hiding phase when the user cancels it. + + Subclasses :class:`SteamUnavailableError` so ``try_hide_other_games`` + already turns it into a skipped hide: the job carries on and ends + normally, releasing the one-mutating-job lock, instead of waiting out a + Steam launch that may never finish. + """ diff --git a/steam_backlog_enforcer/_web_jobs.py b/steam_backlog_enforcer/_web_jobs.py index 208a65c..8f5d4a3 100644 --- a/steam_backlog_enforcer/_web_jobs.py +++ b/steam_backlog_enforcer/_web_jobs.py @@ -119,7 +119,7 @@ def answer_view(request: Request) -> Reply: def cancel_view(request: Request) -> Reply: - """``POST /api/jobs/{id}/cancel`` — only for cancellable commands.""" + """``POST /api/jobs/{id}/cancel`` — cancellable, or inside a cancel window.""" try: cancel(request.args[0]) except JobError as exc: diff --git a/steam_backlog_enforcer/jobs/_cancel_window.py b/steam_backlog_enforcer/jobs/_cancel_window.py new file mode 100644 index 0000000..e320e4d --- /dev/null +++ b/steam_backlog_enforcer/jobs/_cancel_window.py @@ -0,0 +1,61 @@ +"""The job side of a cancel window: announce it, and turn SIGTERM into a skip. + +``done`` and ``check`` cannot be stopped midway, except while they hide games +in the Steam library (see :mod:`steam_backlog_enforcer._cancel_window`). While +a window is open the job writes ``cancel_window`` events (``open: true`` then +``open: false``), which the server reads to accept a cancel and the UI reads +to show its button, and a SIGTERM raises :class:`HidingCancelledError`. The hide +turns that into a skip, so the job finishes normally and drops the lock. +""" + +from __future__ import annotations + +from contextlib import contextmanager +import signal +from typing import TYPE_CHECKING + +from steam_backlog_enforcer._steam_errors import HidingCancelledError + +if TYPE_CHECKING: + from collections.abc import Iterator + from types import FrameType + + from steam_backlog_enforcer.jobs._events import EventWriter + +CANCEL_WINDOW_EVENT = "cancel_window" + + +def _raise_cancelled(_signum: int, _frame: FrameType | None) -> None: + """SIGTERM inside the window: abort the hide, once. No I/O, as in the runner. + + Ignoring further SIGTERMs first means a second cancel cannot interrupt the + cleanup that restores the previous handler and closes the window. + """ + signal.signal(signal.SIGTERM, signal.SIG_IGN) + msg = "Cancelled" + raise HidingCancelledError(msg) + + +class JobCancelWindow: + """Builds the context manager that brackets one cancellable phase.""" + + def __init__(self, writer: EventWriter) -> None: + """Bind to the job's event writer.""" + self._writer = writer + + @contextmanager + def __call__(self) -> Iterator[None]: + """Open the window for the body, then close it, however it ends. + + The handler goes in before ``open`` is written and the previous one + comes back before ``close``, so the server only ever sees a window + the job can act on. The previous handler is restored rather than + assumed to be "ignore": a cancellable command already had its own. + """ + previous = signal.signal(signal.SIGTERM, _raise_cancelled) + try: + self._writer.emit(CANCEL_WINDOW_EVENT, open=True) + yield + finally: + signal.signal(signal.SIGTERM, previous) + self._writer.emit(CANCEL_WINDOW_EVENT, open=False) diff --git a/steam_backlog_enforcer/jobs/_control.py b/steam_backlog_enforcer/jobs/_control.py index e8a9015..fb50c8b 100644 --- a/steam_backlog_enforcer/jobs/_control.py +++ b/steam_backlog_enforcer/jobs/_control.py @@ -35,6 +35,13 @@ def _open_prompt_id(job_id: str) -> str | None: return None if latest in answered else latest +def _cancel_window_open(job_id: str) -> bool: + """Whether the job's latest ``cancel_window`` event says it is open.""" + path = _store.job_dir(job_id) + windows = [e for e in read_events(path) if e.get("type") == "cancel_window"] + return bool(windows) and bool(windows[-1].get("open")) + + def write_answer(job_id: str, prompt_id: str, value: str) -> None: """Deliver the user's answer to the prompt the job is waiting on. @@ -60,7 +67,11 @@ def write_answer(job_id: str, prompt_id: str, value: str) -> None: def cancel(job_id: str) -> None: """Ask a job to stop: any job waiting on a prompt, else cancellable ones. - A cancellable job gets SIGTERM, to its own process only. + A cancellable job gets SIGTERM, to its own process only. So does a + cancel-window job (``done``, ``check``, ``pick``, ``pick-manual``, + ``hide``), but only while its ``cancel_window`` is open (it is hiding + games in the Steam library); the runner turns that SIGTERM into a skipped + hide and the job finishes normally. Only the job's pid is signalled, never its process group: a job may have started Steam, and cancelling a scan must not take Steam down. @@ -77,7 +88,9 @@ def cancel(job_id: str) -> None: (_store.job_dir(job_id) / CANCEL_NAME).touch() return flags = JOB_FLAGS.get(job["command"]) - if flags is None or not flags.cancellable: + if flags is None or not ( + flags.cancellable or (flags.cancel_window and _cancel_window_open(job_id)) + ): msg = f"{job['command']} cannot be cancelled once started." raise JobError(msg, code="not_cancellable") if job["state"] in TERMINAL_STATES: diff --git a/steam_backlog_enforcer/jobs/_runner.py b/steam_backlog_enforcer/jobs/_runner.py index 40c4537..861410f 100644 --- a/steam_backlog_enforcer/jobs/_runner.py +++ b/steam_backlog_enforcer/jobs/_runner.py @@ -18,6 +18,7 @@ import os import signal from typing import TYPE_CHECKING, Any, Final +from steam_backlog_enforcer._cancel_window import use_cancel_window from steam_backlog_enforcer._command_gate import lock_reason from steam_backlog_enforcer._echo import routed_echo from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS @@ -25,6 +26,7 @@ from steam_backlog_enforcer._progress import use_progress from steam_backlog_enforcer._prompter import PromptAbortedError, use_prompter from steam_backlog_enforcer.config import Config, State, _atomic_write from steam_backlog_enforcer.jobs import _spawn, _store +from steam_backlog_enforcer.jobs._cancel_window import JobCancelWindow from steam_backlog_enforcer.jobs._errors import ( JobCancelledError, JobError, @@ -156,6 +158,8 @@ def _run_command( stack.callback(logging.getLogger().removeHandler, handler) _on_sigterm(cancellable=flags.cancellable) stack.callback(signal.signal, signal.SIGTERM, signal.SIG_IGN) + if flags.cancel_window: + stack.enter_context(use_cancel_window(JobCancelWindow(writer))) config = Config.load() try: diff --git a/steam_backlog_enforcer/jobs/_specs.py b/steam_backlog_enforcer/jobs/_specs.py index 9a1d7e3..ea339c3 100644 --- a/steam_backlog_enforcer/jobs/_specs.py +++ b/steam_backlog_enforcer/jobs/_specs.py @@ -24,27 +24,34 @@ class JobFlags: mutating: Takes the one-mutating-job lock. cancellable: SIGTERM cancels it (only where stopping midway is safe). privileged: Runs in the root daemon; never spawned as a job. + cancel_window: Cancellable only while the job reports an open + ``cancel_window`` (hiding games in the Steam library); the work + before it cannot be stopped midway. """ mutating: bool = True cancellable: bool = False privileged: bool = False + cancel_window: bool = False _PRIVILEGED = JobFlags(privileged=True) JOB_FLAGS: Final[dict[str, JobFlags]] = { # check is mutating: a new achievement releases the game and assigns - # the next one, exactly like done. - "check": JobFlags(), + # the next one, exactly like done. Every command that hides games in the + # Steam library (try_hide_other_games, which may wait on a Steam launch) + # can be stopped only during that step. do_check never hides today, so + # check's window is inert until it gains one. + "check": JobFlags(cancel_window=True), "scan": JobFlags(cancellable=True), - "done": JobFlags(), - "pick": JobFlags(), - "pick-manual": JobFlags(), + "done": JobFlags(cancel_window=True), + "pick": JobFlags(cancel_window=True), + "pick-manual": JobFlags(cancel_window=True), "abandon-pick": JobFlags(), "install": JobFlags(), "uninstall": JobFlags(), - "hide": JobFlags(), + "hide": JobFlags(cancel_window=True), "unhide": JobFlags(), "add-exception": JobFlags(), "reset": JobFlags(), diff --git a/steam_backlog_enforcer/library_hider.py b/steam_backlog_enforcer/library_hider.py index 5d1955e..a24fd0b 100644 --- a/steam_backlog_enforcer/library_hider.py +++ b/steam_backlog_enforcer/library_hider.py @@ -22,6 +22,7 @@ from typing import TYPE_CHECKING from steam_backlog_enforcer._achievement_skip import zero_achievement_ids from steam_backlog_enforcer._actions import allowed_app_ids as _allowed_ids_of +from steam_backlog_enforcer._cancel_window import cancel_window from steam_backlog_enforcer._cdp import _cdp_result_value, _evaluate_js from steam_backlog_enforcer._echo import _echo from steam_backlog_enforcer._owned_apps_cache import get_all_owned_app_ids @@ -186,7 +187,10 @@ def try_hide_other_games( progress = current_progress() progress.phase("Hiding games in the Steam library", 1) try: - return hide_other_games(owned_app_ids, allowed_app_ids), None + # A web job may be cancelled here (the Steam launch can wait a while); + # the cancel raises a SteamUnavailableError, handled just below. + with cancel_window(): + return hide_other_games(owned_app_ids, allowed_app_ids), None except SteamUnavailableError as exc: return 0, str(exc) finally: diff --git a/steam_backlog_enforcer/tests/test_jobs_cancel_window.py b/steam_backlog_enforcer/tests/test_jobs_cancel_window.py new file mode 100644 index 0000000..53e0fe1 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_jobs_cancel_window.py @@ -0,0 +1,250 @@ +"""Tests for the cancel window: hiding jobs stop only while hiding games. + +A ``done`` job once sat 90+ s in the Steam launch wait holding the one +mutating-job lock, and could not be cancelled. Cancelling is now accepted +only inside the library-hiding phase: the job announces the phase with +``cancel_window`` events, the server signals it only while open, and the +runner turns the SIGTERM into a skipped hide so the job ends normally. +""" + +from __future__ import annotations + +from contextlib import contextmanager, suppress +import signal +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +from steam_backlog_enforcer._cancel_window import cancel_window, use_cancel_window +from steam_backlog_enforcer._steam_errors import ( + HidingCancelledError, + SteamUnavailableError, +) +from steam_backlog_enforcer.jobs import _control, _runner +from steam_backlog_enforcer.jobs._cancel_window import JobCancelWindow +from steam_backlog_enforcer.jobs._errors import JobError +from steam_backlog_enforcer.jobs._events import EventWriter, read_events +from steam_backlog_enforcer.jobs._job_io import JobLogSink +from steam_backlog_enforcer.jobs._registry import HANDLERS +from steam_backlog_enforcer.jobs._runner import _run_command +from steam_backlog_enforcer.jobs._specs import JOB_FLAGS +from steam_backlog_enforcer.library_hider import try_hide_other_games +from steam_backlog_enforcer.tests._jobs_helpers import JOB_ID, make_job + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + from contextlib import AbstractContextManager + from pathlib import Path + +_PID_ALIVE = "steam_backlog_enforcer.jobs._view._pid_alive" +_ALIVE = "steam_backlog_enforcer.jobs._control.pid_of" +_KILL = "steam_backlog_enforcer.jobs._control.os.kill" +_WINDOW_SIGNAL = "steam_backlog_enforcer.jobs._cancel_window.signal" +_GATE = "steam_backlog_enforcer.jobs._runner.enforce_gate" +_HIDE = "steam_backlog_enforcer.library_hider.hide_other_games" + + +def _window_events(path: Path) -> list[bool]: + """The ``open`` flag of every cancel_window event, in order.""" + return [bool(e["open"]) for e in read_events(path) if e["type"] == "cancel_window"] + + +# Every command whose job reaches try_hide_other_games, which opens the window. +_WINDOWED = ("done", "check", "pick", "pick-manual", "hide") + + +class TestFlags: + """Which commands have a cancel window.""" + + @pytest.mark.parametrize("command", _WINDOWED) + def test_hiding_commands_have_a_window(self, command: str) -> None: + """Each is mutating, not generally cancellable, but has the window.""" + flags = JOB_FLAGS[command] + assert flags.mutating + assert not flags.cancellable + assert flags.cancel_window + + def test_nothing_else_has_one(self) -> None: + """Every other command keeps its old cancel rules.""" + others = {k for k, f in JOB_FLAGS.items() if f.cancel_window} + assert others == set(_WINDOWED) + + +class TestControlCancel: + """_control.cancel honours the window for the commands that have one.""" + + @pytest.fixture(autouse=True) + def _alive(self) -> Iterator[None]: + with patch(_PID_ALIVE, return_value=True): + yield + + def test_accepted_while_the_window_is_open(self) -> None: + """Inside the window, ``done`` gets SIGTERM on its own pid.""" + path = make_job("done", pid="5\n") + EventWriter(path).emit("cancel_window", open=True) + with patch(_ALIVE, return_value=5), patch(_KILL) as kill: + _control.cancel(JOB_ID) + kill.assert_called_once_with(5, signal.SIGTERM) + + def test_refused_before_the_window_opens(self) -> None: + """A windowed job stays uncancellable until its window opens.""" + make_job("done", pid="5\n") + with patch(_KILL) as kill, pytest.raises(JobError) as info: + _control.cancel(JOB_ID) + assert info.value.code == "not_cancellable" + kill.assert_not_called() + + def test_refused_after_the_window_closes(self) -> None: + """Once hiding is over the job can no longer be stopped.""" + path = make_job("check", pid="5\n") + writer = EventWriter(path) + writer.emit("cancel_window", open=True) + writer.emit("cancel_window", open=False) + with patch(_KILL) as kill, pytest.raises(JobError) as info: + _control.cancel(JOB_ID) + assert info.value.code == "not_cancellable" + kill.assert_not_called() + + def test_window_event_does_not_open_other_commands(self) -> None: + """A command without the flag ignores any window event.""" + path = make_job("abandon-pick", pid="5\n") + EventWriter(path).emit("cancel_window", open=True) + with patch(_KILL) as kill, pytest.raises(JobError) as info: + _control.cancel(JOB_ID) + assert info.value.code == "not_cancellable" + kill.assert_not_called() + + +class TestJobCancelWindow: + """JobCancelWindow: the SIGTERM handler and the events, in order.""" + + @staticmethod + def _body(*, fail: bool) -> None: + """The hide inside the window: fine, or aborted by a cancel.""" + if fail: + raise HidingCancelledError + + def _enter(self, *, fail: bool = False) -> MagicMock: + """Run one window against mocks; return the recorded calls.""" + path = make_job("done") + writer = MagicMock(wraps=EventWriter(path)) + calls = MagicMock() + calls.attach_mock(writer.emit, "emit") + fake_signal = MagicMock() + fake_signal.SIGTERM = signal.SIGTERM + fake_signal.signal.return_value = "previous" + calls.attach_mock(fake_signal.signal, "signal") + with ( + patch(_WINDOW_SIGNAL, fake_signal), + suppress(HidingCancelledError), + JobCancelWindow(writer)(), + ): + self._body(fail=fail) + return calls + + def test_handler_is_installed_before_open_and_restored_before_close( + self, + ) -> None: + """The marker is only visible while a handler can act on it.""" + calls = self._enter() + names = [c[0] for c in calls.mock_calls] + assert names == ["signal", "emit", "signal", "emit"] + assert calls.mock_calls[1].kwargs == {"open": True} + assert calls.mock_calls[2].args == (signal.SIGTERM, "previous") + assert calls.mock_calls[3].kwargs == {"open": False} + + def test_window_closes_when_the_body_raises(self) -> None: + """An aborted hide still restores the handler and closes the window.""" + names = [c[0] for c in self._enter(fail=True).mock_calls] + assert names == ["signal", "emit", "signal", "emit"] + + def test_sigterm_handler_raises_a_hide_skip_once(self) -> None: + """SIGTERM inside the window raises an error ``try_hide`` turns to a skip. + + The handler also ignores any later SIGTERM, so a second cancel cannot + interrupt the cleanup. Called under a mocked ``signal``: a real call + would change the test process's own SIGTERM disposition. + """ + handler = self._enter().mock_calls[0].args[1] + fake_signal = MagicMock() + with patch(_WINDOW_SIGNAL, fake_signal), pytest.raises(HidingCancelledError): + handler(signal.SIGTERM, None) + fake_signal.signal.assert_called_once_with( + fake_signal.SIGTERM, fake_signal.SIG_IGN + ) + assert issubclass(HidingCancelledError, SteamUnavailableError) + + +class TestHideUsesTheWindow: + """try_hide_other_games runs the hide inside whatever window is installed.""" + + @staticmethod + def _recorder(seen: list[str]) -> Callable[[], AbstractContextManager[None]]: + @contextmanager + def window() -> Iterator[None]: + seen.append("open") + try: + yield + finally: + seen.append("close") + + return window + + def test_no_window_installed_is_a_noop(self) -> None: + """The CLI and the daemon have no window; hiding is unchanged.""" + with cancel_window(): + pass + with patch(_HIDE, return_value=2): + assert try_hide_other_games([1], {2}) == (2, None) + + def test_hide_runs_between_open_and_close(self) -> None: + """The window brackets exactly the hide.""" + seen: list[str] = [] + + def hide(*_args: object) -> int: + seen.append("hide") + return 3 + + with use_cancel_window(self._recorder(seen)), patch(_HIDE, side_effect=hide): + assert try_hide_other_games([1], {2}) == (3, None) + assert seen == ["open", "hide", "close"] + + def test_cancel_during_hide_is_a_skip_not_a_failure(self) -> None: + """A cancel mid-hide is reported as a skipped hide; the window closes.""" + seen: list[str] = [] + with ( + use_cancel_window(self._recorder(seen)), + patch(_HIDE, side_effect=HidingCancelledError("Cancelled")), + ): + assert try_hide_other_games([1], {2}) == (0, "Cancelled") + assert seen == ["open", "close"] + + +class TestRunnerWiring: + """The runner installs the window only for commands that have one.""" + + def _run(self, command: str) -> list[bool]: + path = make_job(command) + writer = EventWriter(path) + + def handler(*_args: object) -> None: + with cancel_window(): + pass + + with ( + patch.object(signal, "signal"), + patch.object(_runner, "_hold_lock", return_value=None), + patch.dict(HANDLERS, {command: handler}), + patch(_GATE), + ): + _run_command(path, writer, JobLogSink(writer), {"command": command}) + return _window_events(path) + + def test_done_opens_and_closes_a_window(self) -> None: + """A ``done`` job reports the window open, then closed.""" + assert self._run("done") == [True, False] + + def test_abandon_pick_has_no_window(self) -> None: + """A command without the flag never reports one.""" + assert self._run("abandon-pick") == [] diff --git a/web/src/api/jobContract.ts b/web/src/api/jobContract.ts index b10ff18..1058187 100644 --- a/web/src/api/jobContract.ts +++ b/web/src/api/jobContract.ts @@ -61,6 +61,13 @@ export type JobEvent = | (JobEventBase & { type: 'state'; state: JobState }) | (JobEventBase & { type: 'log'; level: 'info' | 'warning' | 'error'; message: string }) | (JobEventBase & { type: 'progress' } & JobProgress) + /** + * Sent only by commands with a cancel window (`done`, `pick`, `pick-manual`, + * `hide`; `check` has the flag but no hide step yet). The job is cancellable only while `open` is true + * (it is hiding games in the Steam library); `POST …/cancel` is refused + * outside it. + */ + | (JobEventBase & { type: 'cancel_window'; open: boolean }) | (JobEventBase & { type: 'prompt' prompt_id: string diff --git a/web/src/jobs/hub.ts b/web/src/jobs/hub.ts index ad8e354..0082392 100644 --- a/web/src/jobs/hub.ts +++ b/web/src/jobs/hub.ts @@ -24,14 +24,16 @@ export interface LiveJob { connected: boolean /** Seconds since epoch of the first progress event, for rate display. */ startedProgressAt: number | null + /** A job that is not cancellable as a command can be, right now. */ + cancelWindowOpen: boolean } const EMPTY: LiveJob = { lastSeq: 0, state: null, progress: null, logs: [], prompt: null, result: null, - connected: false, startedProgressAt: null, + connected: false, startedProgressAt: null, cancelWindowOpen: false, } const TERMINAL = new Set(['succeeded', 'failed', 'cancelled']) -const EVENT_TYPES = ['state', 'log', 'progress', 'prompt', 'result'] as const +const EVENT_TYPES = ['state', 'log', 'progress', 'cancel_window', 'prompt', 'result'] as const const MAX_LOGS = 500 function reduce(live: LiveJob, e: JobEvent): LiveJob { @@ -50,6 +52,9 @@ function reduce(live: LiveJob, e: JobEvent): LiveJob { next.startedProgressAt ??= Date.now() / 1000 break } + case 'cancel_window': + next.cancelWindowOpen = e.open + break case 'prompt': next.prompt = e break diff --git a/web/src/jobs/jobProgress.cancelWindow.test.ts b/web/src/jobs/jobProgress.cancelWindow.test.ts new file mode 100644 index 0000000..7a4ede4 --- /dev/null +++ b/web/src/jobs/jobProgress.cancelWindow.test.ts @@ -0,0 +1,44 @@ +// A done/check job is not cancellable as a command, but it announces a cancel +// window while it hides games in the Steam library: Cancel shows only then. + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { bodiesOf, installEventSource } from '../test/harness' +import { button } from '../test/events' +import { mountJob } from '../test/jobHelpers' + +beforeEach(installEventSource) + +const cancelButton = (el: Element) => el.querySelector('[aria-label="Cancel job"]') + +describe(' cancel window', () => { + it('shows Cancel only while the job reports the window open', async () => { + const { el, send } = mountJob({ cancellable: false }) + await vi.waitFor(() => { expect(el.querySelector('section')).not.toBeNull() }) + send('state', { state: 'running' }) + expect(cancelButton(el)).toBeNull() + + send('cancel_window', { open: true }) + expect(cancelButton(el)).not.toBeNull() + + send('cancel_window', { open: false }) + expect(cancelButton(el)).toBeNull() + }) + + it('cancels through the API from inside the window', async () => { + const { el, send, routes, id, mock } = mountJob({ cancellable: false }) + routes[`POST /api/jobs/${id}/cancel`] = undefined + send('state', { state: 'running' }) + send('cancel_window', { open: true }) + button(el, 'Cancel job').click() + await vi.waitFor(() => { + expect(bodiesOf(mock, `POST /api/jobs/${id}/cancel`)).toHaveLength(1) + }) + }) + + it('drops the button once the job has finished, window or not', () => { + const { el, send } = mountJob({ cancellable: false }) + send('cancel_window', { open: true }) + send('state', { state: 'succeeded' }) + expect(cancelButton(el)).toBeNull() + }) +}) diff --git a/web/src/jobs/jobProgress.ts b/web/src/jobs/jobProgress.ts index bdb7c90..a72c465 100644 --- a/web/src/jobs/jobProgress.ts +++ b/web/src/jobs/jobProgress.ts @@ -180,7 +180,7 @@ export class JobProgressElement extends LiveElement { ) f.actions.replaceChildren( ...(this.cancel.error ? [errorNotice(this.cancel.error)] : []), - ...((spec?.cancellable || waiting) && !finished + ...((spec?.cancellable || waiting || live.cancelWindowOpen) && !finished ? [ h( 'div',