/keys.toml` file can be used for separated secret management (which takes priority when present).
- **Broker Closing-Only & Banned Stock Filter**:
- Interactive topbar toggle pill (`[๐ซ Banned: ON / OFF]`) dynamically filters banned/closing-only symbols from both the Screener table and Running Tape stream without reloads.
diff --git a/docs/releases/v2.12.1.md b/docs/releases/v2.12.1.md
new file mode 100644
index 0000000..5d9d287
--- /dev/null
+++ b/docs/releases/v2.12.1.md
@@ -0,0 +1,64 @@
+# NewsAlerts v2.12.1 โ Release Notes
+
+**Release Date:** December 2026
+**Type:** Patch Release (`PATCH` โ Comprehensive Stability, Security, Cross-Platform & UI Remediation)
+**Single Source of Truth:** `VERSION` (`2.12.1`)
+
+---
+
+## ๐ Overview
+
+NewsAlerts **v2.12.1** delivers a targeted institutional hardening pass resolving **15 live-verified defects** across the HTTP API, frontend UI controls, hotkey engine, Alpaca & TradingView clients, Telegram worker, caching layers, cross-platform audio, and macOS packaging.
+
+---
+
+## ๐ ๏ธ Key Fixes & Hardening
+
+### 1. Critical UI & API Wiring Fixes
+- **Settings Navigation (`#67`)**: Fixed `TypeError` when clicking `#tv-status-badge` or `#watchlist-status-badge` by routing both to `Settings.open("general")` and adding a safe fallback in `Settings.open()`.
+- **App Data Folder & Factory Reset APIs (`#68`)**: Wired `POST /api/open_app_dir`, `POST /api/reset_config`, and `GET /api/version` in `app/server.py` and exposed `open_app_dir()` / `reset_config()` in `web/js/util.js`.
+- **BamSEC Backend Opt-Out Enforcement (`#69`)**: Fixed `Api.get_bamsec()` to read `self._app.cfg.get()` instead of non-existent `self._app.config`, ensuring disabled BamSEC truly suppresses backend requests.
+
+### 2. Frontend UX, Hotkeys & Backup Security
+- **BamSEC Full-View Search Input (`#70`)**: Scoped search re-rendering to `.bamsec-results-body` so typing in the filings filter box never destroys the `` or drops focus.
+- **Pop-Out Tape Watchlist Quick-Add (`#71`)**: Promoted `App.handleAddToWatchlist` into `web/js/util.js` so `+` buttons work identically in both the main window and detached `web/tape.html`, and aligned cache-buster query versions (`?v=8`).
+- **Hotkey Engine & Modifier Combos (`#75`)**: Added `toggle_telegram: "Ctrl+Shift+T"` to `DEFAULT_HOTKEYS` and Settings defaults, fixed `"undefined"` blur text, enabled full modifier-key recording & matching (`Ctrl`/`Alt`/`Shift`/`Meta`), and removed hardcoded `Space`/`Enter`/`Escape` bypasses so remapping works cleanly.
+- **Settings Save Sync & Safe Backup Export (`#76`)**: Synchronized topbar Mute, Telegram, and Volume widgets immediately on Settings Save, Backup Import, and Factory Reset. Full Backup JSON exports now strip sensitive API keys, Telegram tokens, and TradingView cookies by default (with explicit opt-in checkbox).
+
+### 3. Backend Concurrency, Feeds, Caching & Cross-Platform Parity
+- **Cross-Platform Audio (`#72`)**: Replaced Windows-only default sound path concatenation with OS-native `pathlib.Path` defaults (`.wav` on Windows, `.aiff` on macOS, freedesktop `.oga`/`.wav` on Linux), added `paplay --volume` scaling on Linux, and guarded `sys.stdout` fallback beeps in windowed frozen builds.
+- **Thread-Safe `TVClient` (`#73`)**: Migrated `TVClient` from a shared `requests.Session` to version-synchronized thread-local sessions (`threading.local()`), eliminating concurrent `CookieJar` mutation races.
+- **Alpaca Live & Paper API Support (`#74`)**: Added automatic paper (`PK...` -> `paper-api.alpaca.markets`) vs live (`AK...` -> `api.alpaca.markets`) endpoint selection with 401/403 fallback, cleared borrow caches on mode/credential updates, and respected strict `mode="alpaca"` without unintended heuristic fallback.
+- **Tape Seeding, Limits & Disk I/O (`#77`)**: Silently seeds the initial tape universe on startup/session change to prevent false squeeze bursts, respects user-configured `retention_days` (>= 1) and `max_events` (>= 100), and debounces `tape_history.json` disk writes.
+- **Telegram Reliability (`#78`)**: Logged non-200 / `ok=False` responses (with HTTP 429 `retry_after` backoff), re-checked `enabled`/`paused` under lock inside `_worker()` to drop queued alerts when disabled, and URL-encoded/HTML-escaped dynamic fields.
+- **Bounded Caches & Priority News Prefetch (`#79`)**: Stopped permanently caching empty stories and transient BamSEC 5xx/429 responses, bounded in-memory caches via LRU `OrderedDict`, and upgraded `NewsPrefetcher` to `queue.PriorityQueue`.
+- **macOS Packaging (`#80`)**: Read `VERSION` dynamically in `NewsAlerts.spec` for `CFBundleVersion`/`CFBundleShortVersionString` and updated `scripts/package_macos_dmg.sh` to package `dist/NewsAlerts.app` (and include `VERSION` + `.venv` detection in fallback mode).
+- **Security & Resource Cleanup (`#81`)**: Restricted `ast_to_html()` links and `open_url()` to `http://`/`https://`, added localhost `Origin`/`Referer` CSRF protection on mutating `/api/*` `POST` routes, eliminated redundant `POST /api/config` on volume changes, and cleaned up popover listeners and cancelled file inputs.
+
+---
+
+## ๐ฏ Closed Issues
+
+- Resolves #67: `fix(ui): Settings.open('tv') crashes on status pill and watchlist badge click`
+- Resolves #68: `fix(api): wire open_app_dir and reset_config HTTP routes and frontend API client`
+- Resolves #69: `fix(bamsec): backend opt-out check reads non-existent app.config instead of app.cfg`
+- Resolves #70: `fix(bamsec): Full-View filings search input destroys itself and loses focus per keystroke`
+- Resolves #71: `fix(tape): pop-out tape window watchlist '+' buttons are non-functional`
+- Resolves #72: `fix(audio): default sound paths hardcode Windows backslashes and filenames on macOS/Linux`
+- Resolves #73: `fix(tv): synchronize requests.Session and CookieJar access across concurrent threads`
+- Resolves #74: `fix(borrow): support Alpaca live API endpoints and clear borrow cache on mode/key changes`
+- Resolves #75: `fix(hotkeys): add toggle_telegram default, support modifier combos, and fix remapping`
+- Resolves #76: `fix(settings): sync topbar alert controls on save and sanitize secrets in backup export`
+- Resolves #77: `fix(tape): seed tape on startup to stop squeeze bursts, honor limits, debounce disk writes`
+- Resolves #78: `fix(telegram): log API errors, skip queued alerts when disabled, escape chart URLs`
+- Resolves #79: `fix(cache): bound in-memory caches, stop caching empty stories, use priority prefetch`
+- Resolves #80: `fix(build): read VERSION dynamically in NewsAlerts.spec and fix macOS DMG packaging`
+- Resolves #81: `fix(security): validate AST link schemes, guard local POST CSRF, fix volume & DOM leaks`
+
+---
+
+## ๐งช Verification & Test Suite
+
+- Added dedicated regression suite in `tests/test_audit_fixes.py` covering all backend, API, security, caching, tape seeding, thread-safety, Alpaca endpoint, and packaging fixes.
+- Re-verified all frontend fixes live in Chrome via Chrome DevTools Protocol (CDP) against the isolated worktree server.
+- Passed full Python syntax compilation, unit test suite, and secret leak audit.
diff --git a/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md b/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md
index bef7945..1fbc99a 100644
--- a/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md
+++ b/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md
@@ -9,7 +9,7 @@ NewsAlerts is built for rapid keyboard-driven workflow. Use these hotkeys to nav
| Shortcut | Action | Description |
| :---: | :--- | :--- |
| **`M`** | **Mute In-App Audio** | Instantly toggles local terminal audio alert chimes on or off. |
-| **Configurable** | **Toggle Telegram Alerts** | Toggles mobile & desktop Telegram push notifications on or off. |
+| **`Ctrl+Shift+T`** | **Toggle Telegram Alerts** | Toggles mobile & desktop Telegram push notifications on or off. |
| **`T`** | **Pop-Out Tape** | Opens the detached, floating running tape window. |
| **`Space`** | **Pause / Resume** | Pauses or resumes real-time tape and screener stream updates. |
| **`S`** | **Open Settings** | Launches the modal settings window for feeds, audio, and strategies. |
@@ -28,7 +28,7 @@ Starting in **v2.5.0**, hotkeys are fully customizable to user preference:
1. Open **Settings** (press `S` or click the gear icon in the topbar).
2. Click the **Hotkeys** tab.
3. Click any shortcut key badge. The badge will glow green with `Press key...`.
-4. Press the key you wish to assign (letters, numbers, `Space`, `Enter`, `Escape`, etc.).
+4. Press the key or modifier combination you wish to assign (letters, numbers, `Space`, `Enter`, `Escape`, or combos like `Ctrl+Shift+T`).
5. The shortcut is instantly bound and a confirmation toast appears.
6. Click **Save Settings** in the modal footer to persist your bindings to `config.json`.
7. Need to revert? Click **โบ Reset Defaults** at the top of the tab anytime.
diff --git a/docs/wiki/_Footer.md b/docs/wiki/_Footer.md
index d604bce..1219fa8 100644
--- a/docs/wiki/_Footer.md
+++ b/docs/wiki/_Footer.md
@@ -1,7 +1,7 @@
---
- NewsAlerts v2.12.0 ยท Institutional Trading Terminal ยท Maintained by @mlgitdev ยท GitHub Repository ยท Wiki Home
+ NewsAlerts v2.12.1 ยท Institutional Trading Terminal ยท Maintained by @mlgitdev ยท GitHub Repository ยท Wiki Home
diff --git a/scripts/package_macos_dmg.sh b/scripts/package_macos_dmg.sh
index 62444c2..a2aa2f9 100644
--- a/scripts/package_macos_dmg.sh
+++ b/scripts/package_macos_dmg.sh
@@ -18,17 +18,22 @@ STAGING_DIR="dmg-staging"
APP_DIR="${STAGING_DIR}/NewsAlerts.app"
rm -rf "$STAGING_DIR" NewsAlerts-macOS-arm64.dmg
-mkdir -p "${APP_DIR}/Contents/MacOS"
-mkdir -p "${APP_DIR}/Contents/Resources"
+# Prefer standalone PyInstaller bundle when available; otherwise stage runtime resources
+if [ -d "dist/NewsAlerts.app" ]; then
+ echo "[+] Packaging standalone PyInstaller bundle dist/NewsAlerts.app..."
+ cp -R "dist/NewsAlerts.app" "${APP_DIR}"
+else
+ mkdir -p "${APP_DIR}/Contents/MacOS"
+ mkdir -p "${APP_DIR}/Contents/Resources"
-# Copy assets and runtime dependencies
-if [ -f "assets/icon.icns" ]; then
- cp assets/icon.icns "${APP_DIR}/Contents/Resources/icon.icns"
-fi
-cp -r app web assets requirements.txt run_app.py "${APP_DIR}/Contents/Resources/"
+ # Copy assets, VERSION SSOT, and runtime dependencies
+ if [ -f "assets/icon.icns" ]; then
+ cp assets/icon.icns "${APP_DIR}/Contents/Resources/icon.icns"
+ fi
+ cp -r app web assets requirements.txt run_app.py VERSION "${APP_DIR}/Contents/Resources/"
-# Generate Info.plist
-cat << EOF > "${APP_DIR}/Contents/Info.plist"
+ # Generate Info.plist
+ cat << EOF > "${APP_DIR}/Contents/Info.plist"
@@ -55,14 +60,18 @@ cat << EOF > "${APP_DIR}/Contents/Info.plist"
EOF
-# Generate executable binary launcher script
-cat << 'EOF' > "${APP_DIR}/Contents/MacOS/NewsAlerts"
+ # Generate executable binary launcher script (prefer bundled venv if present)
+ cat << 'EOF' > "${APP_DIR}/Contents/MacOS/NewsAlerts"
#!/usr/bin/env bash
DIR="$(cd "$(dirname "$0")/../Resources" && pwd)"
cd "$DIR"
+if [ -x "$DIR/.venv/bin/python" ]; then
+ exec "$DIR/.venv/bin/python" "$DIR/run_app.py" "$@"
+fi
exec python3 "$DIR/run_app.py" "$@"
EOF
-chmod +x "${APP_DIR}/Contents/MacOS/NewsAlerts"
+ chmod +x "${APP_DIR}/Contents/MacOS/NewsAlerts"
+fi
# Symlink /Applications for drag-and-drop installer
ln -s /Applications "${STAGING_DIR}/Applications"
diff --git a/tests/test_audit_fixes.py b/tests/test_audit_fixes.py
new file mode 100644
index 0000000..da2a4ee
--- /dev/null
+++ b/tests/test_audit_fixes.py
@@ -0,0 +1,301 @@
+"""Regression tests covering verified audit fixes (Issues #67 - #81)."""
+from __future__ import annotations
+
+import io
+import json
+import threading
+import time
+import unittest
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+from app.api import Api
+from app.bamsec import BamSECService
+from app.borrow import ALPACA_LIVE_API, ALPACA_PAPER_API, BorrowService, alpaca_trading_base
+from app.config import DEFAULT_HOTKEYS, _default_sound_path
+from app.news import AlpacaNews, NewsProvider, NewsService, ast_to_html
+from app.screener import NewsPrefetcher
+from app.server import make_app
+from app.sounds import SoundPlayer
+from app.tape import TapeWorker
+from app.telegram import TelegramService
+from app.tv_client import TVClient
+
+
+def _wsgi_call(app, method: str, path: str, body: bytes = b"", headers: dict | None = None):
+ status_line = []
+ environ = {
+ "REQUEST_METHOD": method,
+ "PATH_INFO": path,
+ "QUERY_STRING": "",
+ "CONTENT_LENGTH": str(len(body)),
+ "CONTENT_TYPE": "application/json",
+ "wsgi.input": io.BytesIO(body),
+ "wsgi.errors": io.StringIO(),
+ "wsgi.version": (1, 0),
+ "wsgi.multithread": False,
+ "wsgi.multiprocess": False,
+ "wsgi.run_once": False,
+ "wsgi.url_scheme": "http",
+ "SERVER_NAME": "127.0.0.1",
+ "SERVER_PORT": "49281",
+ }
+ for k, v in (headers or {}).items():
+ environ["HTTP_" + k.upper().replace("-", "_")] = v
+
+ def start_response(status, _headers, exc_info=None):
+ status_line.append(status)
+
+ chunks = app(environ, start_response)
+ raw = b"".join(chunks).decode("utf-8", errors="replace")
+ return status_line[0] if status_line else "", raw
+
+
+class TestServerRoutesAndCsrf(unittest.TestCase):
+ def setUp(self):
+ self.web_dir = Path(__file__).resolve().parent.parent / "web"
+ self.api = MagicMock()
+ self.api.open_app_dir.return_value = {"ok": True, "path": "/tmp/na"}
+ self.api.reset_config.return_value = {"alerts": {"mute": False}}
+ self.api.get_version.return_value = {"version": "2.12.1"}
+ self.api.clear_tape.return_value = True
+ self.app = make_app(self.api, self.web_dir)
+
+ def test_open_app_dir_and_reset_config_routes_wired(self):
+ st1, body1 = _wsgi_call(self.app, "POST", "/api/open_app_dir", headers={"Origin": "http://127.0.0.1:49281"})
+ self.assertTrue(st1.startswith("200"))
+ self.assertTrue(json.loads(body1)["ok"])
+ self.api.open_app_dir.assert_called_once()
+
+ st2, body2 = _wsgi_call(self.app, "POST", "/api/reset_config", headers={"Origin": "http://localhost:49281"})
+ self.assertTrue(st2.startswith("200"))
+ self.assertEqual(json.loads(body2)["alerts"]["mute"], False)
+ self.api.reset_config.assert_called_once()
+
+ st3, body3 = _wsgi_call(self.app, "GET", "/api/version")
+ self.assertTrue(st3.startswith("200"))
+ self.assertEqual(json.loads(body3)["version"], "2.12.1")
+
+ def test_cross_origin_post_blocked_by_csrf_guard(self):
+ st, _ = _wsgi_call(self.app, "POST", "/api/clear_tape", headers={"Origin": "https://evil.example"})
+ self.assertTrue(st.startswith("403"))
+ self.api.clear_tape.assert_not_called()
+
+ st_ref, _ = _wsgi_call(self.app, "POST", "/api/clear_tape", headers={"Referer": "https://evil.example/page"})
+ self.assertTrue(st_ref.startswith("403"))
+ self.api.clear_tape.assert_not_called()
+
+
+class TestBamSECOptOutRealCfg(unittest.TestCase):
+ def test_get_bamsec_reads_app_cfg_not_app_config(self):
+ class RealCfgApp:
+ def __init__(self, enabled: bool):
+ self.cfg = MagicMock()
+ self.cfg.get.return_value = {"news": {"bamsec_enabled": enabled}}
+ self.bamsec = MagicMock()
+ self.bamsec.get_filings.return_value = {"ticker": "AAPL", "total": 10}
+
+ app_off = RealCfgApp(False)
+ res_off = Api(app_off).get_bamsec("AAPL")
+ self.assertTrue(res_off.get("disabled"))
+ app_off.bamsec.get_filings.assert_not_called()
+
+ app_on = RealCfgApp(True)
+ res_on = Api(app_on).get_bamsec("AAPL")
+ self.assertEqual(res_on["total"], 10)
+ app_on.bamsec.get_filings.assert_called_once_with("AAPL", force=False)
+
+
+class TestCrossPlatformAudioAndHotkeys(unittest.TestCase):
+ def test_default_hotkeys_includes_toggle_telegram(self):
+ self.assertIn("toggle_telegram", DEFAULT_HOTKEYS)
+ self.assertEqual(DEFAULT_HOTKEYS["toggle_telegram"], "Ctrl+Shift+T")
+
+ @patch("app.config.sys.platform", "darwin")
+ @patch("app.config.MEDIA", "/System/Library/Sounds")
+ def test_macos_sound_path_has_no_windows_backslash(self):
+ p = _default_sound_path("Windows Ding.wav", "Ping.aiff", ())
+ self.assertNotIn("\\", p)
+ self.assertTrue(p.endswith("Ping.aiff"))
+
+ def test_sound_fallback_handles_none_stdout(self):
+ sp = SoundPlayer(volume=80)
+ with patch("app.sounds.sys.platform", "linux"), \
+ patch("app.sounds.shutil.which", return_value=None), \
+ patch("app.sounds.sys.stdout", None):
+ self.assertFalse(sp.play("/nonexistent.wav", force=True))
+
+
+class TestTVClientThreadSafety(unittest.TestCase):
+ @patch.object(TVClient, "check_auth", return_value={})
+ def test_thread_local_sessions_isolated_and_cookie_synced(self, _mock_auth):
+ client = TVClient("sid_initial", "sig_initial")
+ main_sess = client._session()
+ other_sessions = []
+
+ def worker():
+ other_sessions.append(client._session())
+
+ t = threading.Thread(target=worker)
+ t.start()
+ t.join()
+
+ self.assertEqual(len(other_sessions), 1)
+ self.assertIsNot(main_sess, other_sessions[0])
+ self.assertEqual(other_sessions[0].cookies.get("sessionid"), "sid_initial")
+
+ # Updating cookies bumps version and refreshes thread-local session lazily
+ client.set_cookies("sid_updated", "sig_updated")
+ self.assertEqual(client._session().cookies.get("sessionid"), "sid_updated")
+
+
+class TestBorrowAlpacaRoutingAndCache(unittest.TestCase):
+ def test_alpaca_trading_base_selects_paper_vs_live(self):
+ self.assertEqual(alpaca_trading_base("PK123456"), ALPACA_PAPER_API)
+ self.assertEqual(alpaca_trading_base("AK987654"), ALPACA_LIVE_API)
+
+ def test_switching_to_heuristic_clears_alpaca_cache(self):
+ bs = BorrowService(key_id="", secret_key="", mode="auto")
+ bs._cache["AAPL"] = {"status": "easy", "label": "ETB", "source": "alpaca"}
+ bs.update_credentials("", "", mode="heuristic")
+ res = bs.get_status("AAPL", float_shares=1_000_000)
+ self.assertEqual(res["source"], "heuristic")
+ self.assertEqual(res["status"], "hard")
+
+
+class TestTapeSeedingAndLimits(unittest.TestCase):
+ @patch("app.tape.S.market_state", return_value="regular")
+ @patch("app.tape.S.current_session", return_value="regular")
+ def test_first_tick_seeds_silently_without_squeeze_storm(self, _sess, _mkt):
+ cfg = MagicMock()
+ cfg.get.return_value = {
+ "tape": {
+ "universe": {"price_min": 1, "price_max": 500, "chg_min": 1, "vol_min": 20e3, "limit": 400},
+ "cooldown_sec": 30,
+ "max_events": 250,
+ "retention_days": 1,
+ "enabled": ["Squeeze Alert - Up 10% in 5min"],
+ "strategies": [
+ {"name": "Squeeze Alert - Up 10% in 5min", "family": "squeeze", "trigger": "squeeze", "up_pct": 10, "window_min": 5}
+ ],
+ },
+ "alerts": {"mute": False, "tape_sound_enabled": False, "telegram_enabled": False, "telegram_tape_enabled": False},
+ }
+ client = MagicMock()
+ client.scan.return_value = [{
+ "ticker": "NASDAQ:GAPPED",
+ "name": "GAPPED",
+ "close": 11.2,
+ "change": 12.0,
+ "volume": 500_000,
+ "high": 11.25,
+ "low": 10.0,
+ "float_shares_outstanding": 5_000_000,
+ "relative_volume_10d_calc": 4.0,
+ "average_volume_10d_calc": 100_000,
+ "price_52_week_high": 20.0,
+ "price_52_week_low": 5.0,
+ "ATR": 1.0,
+ "change|5": 0.0,
+ "change|15": 0.0,
+ "gap": 12.0,
+ }]
+ emit = MagicMock()
+ tw = TapeWorker(cfg, client, MagicMock(), emit)
+ tw.events = []
+ tw.tick()
+ self.assertTrue(tw._seeded)
+ emit.assert_not_called()
+ self.assertEqual(len(tw.events), 0)
+
+
+class TestTelegramSecurityAndWorker(unittest.TestCase):
+ def test_send_new_symbol_alert_escapes_ticker_and_borrow(self):
+ tg = TelegramService(bot_token="tok", chat_id="123", enabled=True, paused=False)
+ tg._queue = MagicMock()
+ tg.send_new_symbol_alert(
+ "Test ",
+ "regular",
+ {"ticker": 'NASDAQ:A"B', "symbol": "A", "desc": "Co", "sp": 5.0, "sc": 10.0, "borrow": {"status": "custom", "label": "X"}},
+ )
+ tg._queue.put.assert_called_once()
+ sent = tg._queue.put.call_args[0][0]
+ self.assertIn("NASDAQ:A%22B", sent)
+ self.assertIn("<b>X</b>", sent)
+
+
+class TestCachesPriorityAndAstSecurity(unittest.TestCase):
+ def test_ast_to_html_rejects_javascript_urls(self):
+ out_bad = ast_to_html({"type": "url", "params": {"url": "javascript:alert(1)", "linkText": "Bad"}})
+ self.assertEqual(out_bad, "Bad")
+ self.assertNotIn("javascript:", out_bad)
+
+ out_good = ast_to_html({"type": "url", "params": {"url": "https://example.com/a", "linkText": "Good"}})
+ self.assertIn('href="https://example.com/a"', out_good)
+
+ def test_news_service_does_not_permanently_cache_empty_story_and_bounds_cache(self):
+ class Flaky(NewsProvider):
+ def __init__(self):
+ self.calls = 0
+
+ def headlines(self, ticker):
+ return [{"id": ticker, "title": ticker, "published": time.time(), "provider": "tv"}]
+
+ def story(self, story_id):
+ self.calls += 1
+ if self.calls == 1:
+ return {"html": "", "source_url": ""}
+ return {"html": "OK
", "source_url": "https://example.com"}
+
+ fp = Flaky()
+ ns = NewsService(fp, max_cache=2, max_stories=2)
+ s1 = ns.story("s1")
+ s2 = ns.story("s1")
+ self.assertEqual(s1["html"], "")
+ self.assertEqual(s2["html"], "OK
")
+ self.assertEqual(fp.calls, 2)
+
+ ns.get("T1")
+ ns.get("T2")
+ ns.get("T3")
+ self.assertEqual(len(ns._cache), 2)
+ self.assertNotIn("T1", ns._cache)
+
+ def test_bamsec_does_not_cache_503(self):
+ svc = BamSECService(ttl=120.0, max_cache=2)
+ with patch("app.bamsec.requests.get") as mget:
+ mget.return_value = MagicMock(status_code=503, url="https://www.bamsec.com/search?q=ERR")
+ svc.get_filings("ERR")
+ svc.get_filings("ERR")
+ self.assertEqual(mget.call_count, 2)
+
+ def test_news_prefetcher_prioritizes_urgent_tickers(self):
+ np = NewsPrefetcher(MagicMock())
+ np.want("A")
+ np.want("B")
+ np.want("URGENT", priority=True)
+ order = [np.q.get_nowait()[2], np.q.get_nowait()[2], np.q.get_nowait()[2]]
+ self.assertEqual(order, ["URGENT", "A", "B"])
+
+ def test_alpaca_news_bounds_story_cache(self):
+ an = AlpacaNews("k", "s", max_stories=2)
+ an._stories["1"] = {"html": "1"}
+ an._stories["2"] = {"html": "2"}
+ an._stories["3"] = {"html": "3"}
+ while len(an._stories) > an._max_stories:
+ an._stories.popitem(last=False)
+ self.assertEqual(list(an._stories.keys()), ["2", "3"])
+
+
+class TestPackagingVersionSync(unittest.TestCase):
+ def test_spec_reads_version_dynamically_and_dmg_copies_version(self):
+ root = Path(__file__).resolve().parent.parent
+ spec_txt = (root / "NewsAlerts.spec").read_text(encoding="utf-8")
+ dmg_txt = (root / "scripts" / "package_macos_dmg.sh").read_text(encoding="utf-8")
+ self.assertNotIn("'CFBundleVersion': '2.9.0'", spec_txt)
+ self.assertIn("'CFBundleVersion': app_version", spec_txt)
+ self.assertIn("VERSION", dmg_txt)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/web/index.html b/web/index.html
index e0eac9f..472c767 100644
--- a/web/index.html
+++ b/web/index.html
@@ -6,7 +6,7 @@
-
+
@@ -222,11 +222,11 @@
Settings & Data Sources
-
-
-
-
-
-
+
+
+
+
+
+