Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e132fc134b | ||
|
|
8b658e76f3 |
@@ -104,9 +104,13 @@ MEDIUM_INDICATORS = [
|
||||
r"\blost\s+all\s+hope\b",
|
||||
r"\bno\s+tomorrow\b",
|
||||
# Contextual versions (from crisis_detector.py legacy)
|
||||
# Keep only medium-only patterns here; stronger overlaps live in HIGH_INDICATORS.
|
||||
r"\bfeel(?:s|ing)?\s+(?:so\s+)?worthless\b",
|
||||
r"\bfeel(?:s|ing)?\s+(?:so\s+)?hopeless\b",
|
||||
r"\bfeel(?:s|ing)?\s+trapped\b",
|
||||
r"\bfeel(?:s|ing)?\s+desperate\b",
|
||||
r"\bno\s+future\s+(?:for\s+me|ahead|left)\b",
|
||||
r"\bnothing\s+left\s+(?:to\s+(?:live|hope)\s+for|inside)\b",
|
||||
r"\bgive(?:n)?\s*up\s+on\s+myself\b",
|
||||
]
|
||||
|
||||
LOW_INDICATORS = [
|
||||
|
||||
62
index.html
62
index.html
@@ -681,6 +681,7 @@ html, body {
|
||||
<!-- Footer -->
|
||||
<footer id="footer">
|
||||
<a href="/about.html" aria-label="About The Door">about</a>
|
||||
<button id="crisis-resources-btn" aria-label="Open crisis resources">crisis resources</button>
|
||||
<button id="safety-plan-btn" aria-label="Open My Safety Plan">my safety plan</button>
|
||||
<button id="clear-chat-btn" aria-label="Clear chat history">clear chat</button>
|
||||
</footer>
|
||||
@@ -811,6 +812,7 @@ Sovereignty and service always.`;
|
||||
var overlayCallLink = document.querySelector('.overlay-call');
|
||||
var statusDot = document.querySelector('.status-dot');
|
||||
var statusText = document.getElementById('status-text');
|
||||
var crisisResourcesBtn = document.getElementById('crisis-resources-btn');
|
||||
|
||||
// Safety Plan Elements
|
||||
var safetyPlanBtn = document.getElementById('safety-plan-btn');
|
||||
@@ -826,6 +828,9 @@ Sovereignty and service always.`;
|
||||
var isStreaming = false;
|
||||
var overlayTimer = null;
|
||||
var crisisPanelShown = false;
|
||||
var CRISIS_OVERLAY_COOLDOWN_MS = 10 * 60 * 1000;
|
||||
var CRISIS_OVERLAY_LAST_SHOWN_KEY = 'timmy_crisis_overlay_last_shown_at';
|
||||
var CRISIS_OVERLAY_EVENT_LOG_KEY = 'timmy_crisis_overlay_event_log';
|
||||
|
||||
// ===== SERVICE WORKER =====
|
||||
if ('serviceWorker' in navigator) {
|
||||
@@ -853,6 +858,43 @@ Sovereignty and service always.`;
|
||||
window.addEventListener('offline', updateOnlineStatus);
|
||||
updateOnlineStatus();
|
||||
|
||||
function getLastOverlayShownAt() {
|
||||
try {
|
||||
return parseInt(localStorage.getItem(CRISIS_OVERLAY_LAST_SHOWN_KEY) || '0', 10) || 0;
|
||||
} catch (e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function setLastOverlayShownAt(timestamp) {
|
||||
try {
|
||||
localStorage.setItem(CRISIS_OVERLAY_LAST_SHOWN_KEY, String(timestamp));
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function logCrisisOverlayEvent(type, level) {
|
||||
try {
|
||||
var raw = localStorage.getItem(CRISIS_OVERLAY_EVENT_LOG_KEY);
|
||||
var events = raw ? JSON.parse(raw) : [];
|
||||
if (!Array.isArray(events)) events = [];
|
||||
events.push({ type: type, level: level, at: Date.now() });
|
||||
if (events.length > 20) events = events.slice(events.length - 20);
|
||||
localStorage.setItem(CRISIS_OVERLAY_EVENT_LOG_KEY, JSON.stringify(events));
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function openCrisisResources() {
|
||||
crisisPanelShown = true;
|
||||
crisisPanel.classList.add('visible');
|
||||
if (typeof crisisPanel.scrollIntoView === 'function') {
|
||||
crisisPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
var firstAction = crisisPanel.querySelector('.crisis-btn, a[href]');
|
||||
if (firstAction && typeof firstAction.focus === 'function') {
|
||||
firstAction.focus();
|
||||
}
|
||||
}
|
||||
|
||||
// ===== CRISIS KEYWORDS =====
|
||||
// Tier 1: General crisis indicators - triggers enhanced 988 panel
|
||||
var crisisKeywords = [
|
||||
@@ -1021,6 +1063,19 @@ Sovereignty and service always.`;
|
||||
var _preOverlayFocusElement = null;
|
||||
|
||||
function showOverlay() {
|
||||
return showOverlayWithRateLimit(false, 2);
|
||||
}
|
||||
|
||||
function showOverlayWithRateLimit(forceOpen, level) {
|
||||
var lastShownAt = getLastOverlayShownAt();
|
||||
if (!forceOpen && Date.now() - lastShownAt < CRISIS_OVERLAY_COOLDOWN_MS) {
|
||||
logCrisisOverlayEvent('suppressed', level || 2);
|
||||
return false;
|
||||
}
|
||||
|
||||
logCrisisOverlayEvent(forceOpen ? 'manual-open' : 'shown', level || 2);
|
||||
setLastOverlayShownAt(Date.now());
|
||||
|
||||
// Save current focus for restoration on dismiss
|
||||
_preOverlayFocusElement = document.activeElement;
|
||||
|
||||
@@ -1053,6 +1108,7 @@ Sovereignty and service always.`;
|
||||
|
||||
// Focus the Call 988 link (always enabled) — disabled buttons cannot receive focus
|
||||
if (overlayCallLink) overlayCallLink.focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Register focus trap on document (always listening, gated by class check)
|
||||
@@ -1301,6 +1357,12 @@ Sovereignty and service always.`;
|
||||
});
|
||||
}
|
||||
|
||||
if (crisisResourcesBtn) {
|
||||
crisisResourcesBtn.addEventListener('click', function() {
|
||||
openCrisisResources();
|
||||
});
|
||||
}
|
||||
|
||||
// ===== TEXTAREA AUTO-RESIZE =====
|
||||
msgInput.addEventListener('input', function() {
|
||||
this.style.height = 'auto';
|
||||
|
||||
53
tests/test_crisis_overlay_rate_limit.py
Normal file
53
tests/test_crisis_overlay_rate_limit.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import pathlib
|
||||
import re
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
INDEX_HTML = ROOT / 'index.html'
|
||||
|
||||
|
||||
class TestCrisisOverlayRateLimit(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.html = INDEX_HTML.read_text()
|
||||
|
||||
def test_overlay_has_ten_minute_cooldown_constant(self):
|
||||
self.assertRegex(
|
||||
self.html,
|
||||
r"CRISIS_OVERLAY_COOLDOWN_MS\s*=\s*10\s*\*\s*60\s*\*\s*1000",
|
||||
'Expected a 10-minute crisis overlay cooldown constant.',
|
||||
)
|
||||
|
||||
def test_show_overlay_suppresses_repeat_with_logging(self):
|
||||
self.assertRegex(
|
||||
self.html,
|
||||
r"function\s+logCrisisOverlayEvent\s*\(",
|
||||
'Expected a crisis overlay event logger.',
|
||||
)
|
||||
self.assertRegex(
|
||||
self.html,
|
||||
r"if\s*\(!forceOpen\s*&&\s*Date\.now\(\)\s*-\s*lastShownAt\s*<\s*CRISIS_OVERLAY_COOLDOWN_MS\)",
|
||||
'Expected showOverlay to suppress repeated auto-displays inside the cooldown window.',
|
||||
)
|
||||
self.assertRegex(
|
||||
self.html,
|
||||
r"logCrisisOverlayEvent\('suppressed'",
|
||||
'Expected suppressed overlay attempts to be logged.',
|
||||
)
|
||||
|
||||
def test_manual_crisis_resources_button_exists_and_bypasses_cooldown(self):
|
||||
self.assertIn('id="crisis-resources-btn"', self.html)
|
||||
self.assertRegex(
|
||||
self.html,
|
||||
r"function\s+openCrisisResources\s*\(",
|
||||
'Expected a manual crisis resources opener.',
|
||||
)
|
||||
self.assertRegex(
|
||||
self.html,
|
||||
r"crisisResourcesBtn\.addEventListener\('click',\s*function\(\)\s*\{\s*openCrisisResources\(\);",
|
||||
'Expected the footer button to wire into openCrisisResources().',
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,50 +0,0 @@
|
||||
"""Regression tests for duplicate crisis indicators cleanup (#123)."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from crisis.detect import detect_crisis
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DETECT_FILE = ROOT / "crisis" / "detect.py"
|
||||
|
||||
|
||||
class TestCrisisIndicatorDedup(unittest.TestCase):
|
||||
def _extract_indicator_list(self, name: str) -> set[str]:
|
||||
text = DETECT_FILE.read_text(encoding="utf-8")
|
||||
match = re.search(rf"{name}\s*=\s*\[(.*?)\n\]", text, re.S)
|
||||
self.assertIsNotNone(match, f"{name} list missing")
|
||||
return {
|
||||
line.strip().rstrip(",")
|
||||
for line in match.group(1).splitlines()
|
||||
if line.strip().startswith('r"')
|
||||
}
|
||||
|
||||
def test_high_and_medium_indicator_lists_do_not_overlap(self):
|
||||
high = self._extract_indicator_list("HIGH_INDICATORS")
|
||||
medium = self._extract_indicator_list("MEDIUM_INDICATORS")
|
||||
overlap = high & medium
|
||||
self.assertEqual(set(), overlap, f"duplicate cross-tier patterns found: {sorted(overlap)}")
|
||||
|
||||
def test_removed_duplicates_still_classify_at_high_tier(self):
|
||||
cases = {
|
||||
"I feel hopeless": "HIGH",
|
||||
"I feel trapped": "HIGH",
|
||||
"I feel desperate": "HIGH",
|
||||
"I have no future ahead": "HIGH",
|
||||
"I have given up on myself": "HIGH",
|
||||
}
|
||||
for text, expected in cases.items():
|
||||
with self.subTest(text=text):
|
||||
result = detect_crisis(text)
|
||||
self.assertEqual(expected, result.level)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user