Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f3e01cd8a | ||
|
|
e146a4ea39 |
142
augmentation.py
Normal file
142
augmentation.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""Local-only counselor augmentation helpers for the-door."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
import re
|
||||
|
||||
from crisis.detect import detect_crisis
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SignalGuide:
|
||||
label: str
|
||||
patterns: List[str]
|
||||
talking_point: str
|
||||
deescalation: str
|
||||
follow_up: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class CounselorAugmentation:
|
||||
risk_level: str
|
||||
risk_score: int
|
||||
signals: List[str]
|
||||
suggested_talking_points: List[str]
|
||||
deescalation_techniques: List[str]
|
||||
follow_up_prompt: str
|
||||
operator_notice: str
|
||||
local_only: bool = True
|
||||
advisory_only: bool = True
|
||||
|
||||
|
||||
SIGNAL_GUIDES: List[SignalGuide] = [
|
||||
SignalGuide(
|
||||
label="Explicit self-harm intent",
|
||||
patterns=[
|
||||
r"\bkill\s*(my)?self\b",
|
||||
r"\bend\s*my\s*life\b",
|
||||
r"\bwrote\s+a\s+suicide\s*(?:note|letter)\b",
|
||||
r"\bgoing\s+to\s+(?:kill\s+myself|die)\b",
|
||||
],
|
||||
talking_point="Ask directly whether they are safe right now and keep the next question concrete.",
|
||||
deescalation="Move to immediate safety: ask about means, people nearby, and whether they can call or text 988 now.",
|
||||
follow_up="You said you're ready to die. Are you alone right now, and can you tell me what is within reach?",
|
||||
),
|
||||
SignalGuide(
|
||||
label="Hopelessness / collapse",
|
||||
patterns=[
|
||||
r"\bhopeless\b",
|
||||
r"\bcan'?t\s+go\s+on\b",
|
||||
r"\bno\s+future\b",
|
||||
r"\bnothing\s+left\b",
|
||||
],
|
||||
talking_point="Reflect the hopelessness plainly before offering options. Avoid arguing with the feeling.",
|
||||
deescalation="Narrow the time horizon: focus on the next ten minutes, one breath, one call, one person.",
|
||||
follow_up="You said things feel hopeless. What feels most dangerous about the next hour?",
|
||||
),
|
||||
SignalGuide(
|
||||
label="Isolation / burden",
|
||||
patterns=[
|
||||
r"\bnobody\s+cares\b",
|
||||
r"\bbetter\s+off\s+without\s+me\b",
|
||||
r"\balone\b",
|
||||
r"\bburden\b",
|
||||
],
|
||||
talking_point="Counter isolation with immediacy: name one real person or service they can contact now.",
|
||||
deescalation="Invite a tiny reconnection step: text one safe person, unlock the door, move closer to others, or stay in the chat.",
|
||||
follow_up="You said you feel alone. Who is the safest real person we could bring into this moment with you?",
|
||||
),
|
||||
SignalGuide(
|
||||
label="Overwhelm / panic",
|
||||
patterns=[
|
||||
r"\bdesperate\b",
|
||||
r"\boverwhelm(?:ed|ing)\b",
|
||||
r"\btrapped\b",
|
||||
r"\bpanic\b",
|
||||
],
|
||||
talking_point="Offer one regulating action at a time instead of a list. Slow the pace of the chat.",
|
||||
deescalation="Ground in the room: feet on the floor, name five visible objects, one sip of water, one slow exhale.",
|
||||
follow_up="You said this feels overwhelming. What is the smallest thing in the room you can touch right now?",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class CounselorAugmentationEngine:
|
||||
BASE_SCORES = {
|
||||
"NONE": 5,
|
||||
"LOW": 25,
|
||||
"MEDIUM": 55,
|
||||
"HIGH": 75,
|
||||
"CRITICAL": 95,
|
||||
}
|
||||
|
||||
def _matched_guides(self, text: str) -> List[SignalGuide]:
|
||||
lowered = text.lower()
|
||||
matched: List[SignalGuide] = []
|
||||
for guide in SIGNAL_GUIDES:
|
||||
if any(re.search(pattern, lowered) for pattern in guide.patterns):
|
||||
matched.append(guide)
|
||||
return matched
|
||||
|
||||
def build_augmented_guidance(self, text: str, assistant_text: str = "") -> CounselorAugmentation:
|
||||
detection = detect_crisis(text)
|
||||
guides = self._matched_guides(text)
|
||||
|
||||
risk_level = detection.level
|
||||
signals = [guide.label for guide in guides]
|
||||
if risk_level == "CRITICAL" and "Explicit self-harm intent" not in signals:
|
||||
signals.insert(0, "Explicit self-harm intent")
|
||||
|
||||
risk_score = self.BASE_SCORES.get(risk_level, 5) + min(len(signals) * 5, 10)
|
||||
if risk_level == "CRITICAL":
|
||||
risk_score = max(risk_score, 95)
|
||||
|
||||
talking_points = [guide.talking_point for guide in guides] or [
|
||||
"Keep the response advisory and grounded in immediate safety, not abstract reassurance."
|
||||
]
|
||||
deescalation = [guide.deescalation for guide in guides] or [
|
||||
"Use short sentences, slow the conversation, and invite one concrete grounding step."
|
||||
]
|
||||
|
||||
quote = text.strip().replace("\n", " ")[:120]
|
||||
follow_up = (guides[0].follow_up if guides else "What feels most dangerous or heavy for you right now?")
|
||||
follow_up_prompt = f'You said "{quote}". Consider following up with: {follow_up}'
|
||||
|
||||
if assistant_text and "988" not in assistant_text and risk_level in {"HIGH", "CRITICAL"}:
|
||||
talking_points.append("Surface 988 or Crisis Text Line explicitly if the assistant has not already done so.")
|
||||
|
||||
return CounselorAugmentation(
|
||||
risk_level=risk_level,
|
||||
risk_score=min(risk_score, 100),
|
||||
signals=signals,
|
||||
suggested_talking_points=talking_points,
|
||||
deescalation_techniques=deescalation,
|
||||
follow_up_prompt=follow_up_prompt,
|
||||
operator_notice="Local-only advisory. This never replaces human judgment.",
|
||||
)
|
||||
|
||||
|
||||
def build_augmented_guidance(text: str, assistant_text: str = "") -> CounselorAugmentation:
|
||||
return CounselorAugmentationEngine().build_augmented_guidance(text, assistant_text=assistant_text)
|
||||
887
index.html
887
index.html
@@ -241,6 +241,105 @@ html, body {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* ===== OPERATOR AUGMENTATION SIDEBAR ===== */
|
||||
#augmentation-toggle {
|
||||
margin: 10px 16px 0;
|
||||
padding: 8px 12px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid #5b6b7a;
|
||||
background: #11161d;
|
||||
color: #b9c7d5;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#augmentation-toggle.active {
|
||||
border-color: #b388ff;
|
||||
color: #e2d4ff;
|
||||
background: #1a1324;
|
||||
}
|
||||
|
||||
#augmentation-sidebar {
|
||||
position: fixed;
|
||||
top: 90px;
|
||||
right: 16px;
|
||||
width: 320px;
|
||||
max-height: calc(100vh - 120px);
|
||||
overflow-y: auto;
|
||||
background: #11161d;
|
||||
border: 1px solid #30363d;
|
||||
border-left: 3px solid #b388ff;
|
||||
border-radius: 8px;
|
||||
padding: 14px;
|
||||
box-shadow: 0 12px 32px rgba(0,0,0,0.35);
|
||||
display: none;
|
||||
z-index: 70;
|
||||
}
|
||||
|
||||
#augmentation-sidebar.visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#augmentation-sidebar .augmentation-heading {
|
||||
color: #d2b8ff;
|
||||
font-size: 0.78rem;
|
||||
letter-spacing: 0.08em;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
#augmentation-risk-score {
|
||||
color: #fff;
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
#augmentation-sidebar .augmentation-section {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
#augmentation-sidebar .augmentation-section h3 {
|
||||
color: #c9d1d9;
|
||||
font-size: 0.78rem;
|
||||
margin: 0 0 6px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
#augmentation-sidebar ul {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
color: #b9c7d5;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
#augmentation-follow-up,
|
||||
#augmentation-notice {
|
||||
color: #b9c7d5;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.45;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#augmentation-notice {
|
||||
color: #8b949e;
|
||||
margin-top: 12px;
|
||||
border-top: 1px solid #21262d;
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 980px) {
|
||||
#augmentation-sidebar {
|
||||
left: 16px;
|
||||
right: 16px;
|
||||
width: auto;
|
||||
top: auto;
|
||||
bottom: 82px;
|
||||
max-height: 40vh;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== CHAT AREA ===== */
|
||||
#chat-area {
|
||||
flex: 1;
|
||||
@@ -500,184 +599,6 @@ html, body {
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
.safety-plan-status {
|
||||
min-height: 20px;
|
||||
margin: 4px 0 18px;
|
||||
font-size: 0.85rem;
|
||||
color: #8b949e;
|
||||
}
|
||||
|
||||
.safety-plan-status.success {
|
||||
color: #3fb950;
|
||||
}
|
||||
|
||||
.safety-plan-status.error {
|
||||
color: #ff7b72;
|
||||
}
|
||||
|
||||
.safety-plan-versioning {
|
||||
margin-top: 24px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #30363d;
|
||||
}
|
||||
|
||||
.safety-plan-versioning-grid {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.safety-plan-history-panel,
|
||||
.safety-plan-diff-panel {
|
||||
background: #0d1117;
|
||||
border: 1px solid #30363d;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.safety-plan-section-header h3 {
|
||||
font-size: 0.95rem;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.safety-plan-section-header p {
|
||||
font-size: 0.8rem;
|
||||
color: #8b949e;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.safety-plan-history {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.safety-plan-history-item {
|
||||
border: 1px solid #30363d;
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
background: #161b22;
|
||||
}
|
||||
|
||||
.safety-plan-history-item.active {
|
||||
border-color: #58a6ff;
|
||||
box-shadow: 0 0 0 1px rgba(88, 166, 255, 0.35);
|
||||
}
|
||||
|
||||
.safety-plan-history-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
align-items: baseline;
|
||||
margin-bottom: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.safety-plan-history-title {
|
||||
font-size: 0.88rem;
|
||||
font-weight: 600;
|
||||
color: #e6edf3;
|
||||
}
|
||||
|
||||
.safety-plan-history-note {
|
||||
font-size: 0.78rem;
|
||||
color: #8b949e;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.safety-plan-history-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.safety-plan-history-button,
|
||||
.safety-plan-restore-button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid #30363d;
|
||||
background: transparent;
|
||||
color: #e6edf3;
|
||||
padding: 8px 12px;
|
||||
font-size: 0.82rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.safety-plan-history-button:hover,
|
||||
.safety-plan-restore-button:hover,
|
||||
.safety-plan-history-button:focus,
|
||||
.safety-plan-restore-button:focus {
|
||||
border-color: #58a6ff;
|
||||
color: #58a6ff;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.safety-plan-restore-button {
|
||||
background: rgba(35, 134, 54, 0.14);
|
||||
}
|
||||
|
||||
.safety-plan-diff {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.safety-plan-diff-meta {
|
||||
font-size: 0.78rem;
|
||||
color: #8b949e;
|
||||
}
|
||||
|
||||
.safety-plan-diff-field {
|
||||
border-top: 1px solid #21262d;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.safety-plan-diff-field:first-child {
|
||||
border-top: none;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.safety-plan-diff-field h4 {
|
||||
font-size: 0.84rem;
|
||||
margin-bottom: 8px;
|
||||
color: #c9d1d9;
|
||||
}
|
||||
|
||||
.safety-plan-diff-block {
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.5;
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
font-size: 0.88rem;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.diff-unchanged {
|
||||
background: #161b22;
|
||||
color: #c9d1d9;
|
||||
}
|
||||
|
||||
.diff-added {
|
||||
background: rgba(46, 160, 67, 0.16);
|
||||
border-left: 3px solid #2ea043;
|
||||
color: #d2f4d3;
|
||||
}
|
||||
|
||||
.diff-removed {
|
||||
background: rgba(248, 81, 73, 0.16);
|
||||
border-left: 3px solid #f85149;
|
||||
color: #ffd8d3;
|
||||
}
|
||||
|
||||
.safety-plan-empty {
|
||||
color: #8b949e;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
@media (min-width: 840px) {
|
||||
.safety-plan-versioning-grid {
|
||||
grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
@@ -827,6 +748,29 @@ html, body {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button id="augmentation-toggle" type="button" aria-pressed="false" aria-controls="augmentation-sidebar">Operator assist: off</button>
|
||||
<aside id="augmentation-sidebar" aria-live="polite" aria-label="Local operator augmentation sidebar">
|
||||
<div class="augmentation-heading">LOCAL OPERATOR AUGMENTATION</div>
|
||||
<div id="augmentation-risk-score">Risk score: —</div>
|
||||
<div class="augmentation-section">
|
||||
<h3>Signals</h3>
|
||||
<ul id="augmentation-signals"><li>No signals yet.</li></ul>
|
||||
</div>
|
||||
<div class="augmentation-section">
|
||||
<h3>Talking points</h3>
|
||||
<ul id="augmentation-talking-points"><li>Enable operator assist to surface local advisory guidance.</li></ul>
|
||||
</div>
|
||||
<div class="augmentation-section">
|
||||
<h3>De-escalation</h3>
|
||||
<ul id="augmentation-techniques"><li>Suggestions stay local and never replace human judgment.</li></ul>
|
||||
</div>
|
||||
<div class="augmentation-section">
|
||||
<h3>Follow-up</h3>
|
||||
<p id="augmentation-follow-up">No follow-up prompt yet.</p>
|
||||
</div>
|
||||
<p id="augmentation-notice">Local-only advisory. Never replaces human judgment.</p>
|
||||
</aside>
|
||||
|
||||
<!-- Chat messages -->
|
||||
<div id="chat-area" role="log" aria-label="Chat messages" aria-live="polite" tabindex="0">
|
||||
<!-- Messages inserted here -->
|
||||
@@ -914,28 +858,6 @@ html, body {
|
||||
<label for="sp-environment">5. Making my environment safe</label>
|
||||
<textarea id="sp-environment" placeholder="e.g., Giving my car keys to a friend, locking away meds..."></textarea>
|
||||
</div>
|
||||
|
||||
<div id="safety-plan-status" class="safety-plan-status" role="status" aria-live="polite"></div>
|
||||
|
||||
<section class="safety-plan-versioning" aria-labelledby="safety-plan-history-title">
|
||||
<div class="safety-plan-versioning-grid">
|
||||
<div class="safety-plan-history-panel">
|
||||
<div class="safety-plan-section-header">
|
||||
<h3 id="safety-plan-history-title">Version History</h3>
|
||||
<p>Each save stays on this device so you can review changes and restore an earlier plan.</p>
|
||||
</div>
|
||||
<div id="safety-plan-history" class="safety-plan-history"></div>
|
||||
</div>
|
||||
|
||||
<div class="safety-plan-diff-panel">
|
||||
<div class="safety-plan-section-header">
|
||||
<h3>Diff View</h3>
|
||||
<p>Compare the selected version against the version immediately before it.</p>
|
||||
</div>
|
||||
<div id="safety-plan-diff" class="safety-plan-diff"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="cancel-safety-plan">Cancel</button>
|
||||
@@ -1006,6 +928,14 @@ Sovereignty and service always.`;
|
||||
var sendBtn = document.getElementById('send-btn');
|
||||
var typingIndicator = document.getElementById('typing-indicator');
|
||||
var crisisPanel = document.getElementById('crisis-panel');
|
||||
var augmentationToggle = document.getElementById('augmentation-toggle');
|
||||
var augmentationSidebar = document.getElementById('augmentation-sidebar');
|
||||
var augmentationRiskScore = document.getElementById('augmentation-risk-score');
|
||||
var augmentationSignals = document.getElementById('augmentation-signals');
|
||||
var augmentationTalkingPoints = document.getElementById('augmentation-talking-points');
|
||||
var augmentationTechniques = document.getElementById('augmentation-techniques');
|
||||
var augmentationFollowUp = document.getElementById('augmentation-follow-up');
|
||||
var augmentationNotice = document.getElementById('augmentation-notice');
|
||||
var crisisOverlay = document.getElementById('crisis-overlay');
|
||||
var overlayDismissBtn = document.getElementById('overlay-dismiss-btn');
|
||||
var overlayCallLink = document.querySelector('.overlay-call');
|
||||
@@ -1020,26 +950,14 @@ Sovereignty and service always.`;
|
||||
var cancelSafetyPlan = document.getElementById('cancel-safety-plan');
|
||||
var saveSafetyPlan = document.getElementById('save-safety-plan');
|
||||
var clearChatBtn = document.getElementById('clear-chat-btn');
|
||||
var safetyPlanHistory = document.getElementById('safety-plan-history');
|
||||
var safetyPlanDiff = document.getElementById('safety-plan-diff');
|
||||
var safetyPlanStatus = document.getElementById('safety-plan-status');
|
||||
var safetyPlanFields = {
|
||||
warningSigns: document.getElementById('sp-warning-signs'),
|
||||
coping: document.getElementById('sp-coping'),
|
||||
distraction: document.getElementById('sp-distraction'),
|
||||
help: document.getElementById('sp-help'),
|
||||
environment: document.getElementById('sp-environment')
|
||||
};
|
||||
var SAFETY_PLAN_STORAGE_KEY = 'timmy_safety_plan';
|
||||
var SAFETY_PLAN_VERSIONS_KEY = 'timmy_safety_plan_versions';
|
||||
var MAX_SAFETY_PLAN_VERSIONS = 20;
|
||||
|
||||
// ===== STATE =====
|
||||
var messages = [];
|
||||
var isStreaming = false;
|
||||
var overlayTimer = null;
|
||||
var crisisPanelShown = false;
|
||||
var selectedSafetyPlanVersionId = null;
|
||||
var lastUserMessage = '';
|
||||
var augmentationEnabled = false;
|
||||
|
||||
// ===== SERVICE WORKER =====
|
||||
if ('serviceWorker' in navigator) {
|
||||
@@ -1197,6 +1115,142 @@ Sovereignty and service always.`;
|
||||
}
|
||||
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
var AUGMENTATION_SIGNAL_GUIDES = [
|
||||
{
|
||||
label: 'Explicit self-harm intent',
|
||||
patterns: [/kill\s*(my)?self/i, /end\s*my\s*life/i, /suicide\s*(note|letter)/i, /going\s+to\s+(kill\s+myself|die)/i],
|
||||
talkingPoint: 'Ask directly whether they are safe right now and keep the next question concrete.',
|
||||
technique: 'Move to immediate safety: ask about means, people nearby, and whether 988 can be called or texted now.',
|
||||
followUp: 'You said you might die tonight. Are you alone right now, and what is within reach?'
|
||||
},
|
||||
{
|
||||
label: 'Hopelessness / collapse',
|
||||
patterns: [/hopeless/i, /can'?t\s+go\s+on/i, /no\s+future/i, /nothing\s+left/i],
|
||||
talkingPoint: 'Reflect the hopelessness plainly before offering options. Avoid arguing with the feeling.',
|
||||
technique: 'Narrow the time horizon to the next ten minutes and one immediate action.',
|
||||
followUp: 'You said things feel hopeless. What feels most dangerous about the next hour?'
|
||||
},
|
||||
{
|
||||
label: 'Isolation / burden',
|
||||
patterns: [/nobody\s+cares/i, /better\s+off\s+without\s+me/i, /\balone\b/i, /\bburden\b/i],
|
||||
talkingPoint: 'Counter isolation with one real contact point: a person, 988, or Crisis Text Line.',
|
||||
technique: 'Invite a tiny reconnection step: text one safe person, unlock the door, or stay in the chat.',
|
||||
followUp: 'You said you feel alone. Who is the safest real person we could bring into this moment with you?'
|
||||
},
|
||||
{
|
||||
label: 'Overwhelm / panic',
|
||||
patterns: [/desperate/i, /overwhelm(?:ed|ing)/i, /trapped/i, /panic/i],
|
||||
talkingPoint: 'Offer one regulating step at a time instead of a long list.',
|
||||
technique: 'Ground in the room: feet on the floor, name five visible objects, one sip of water, one slow exhale.',
|
||||
followUp: 'You said this feels overwhelming. What is the smallest thing in the room you can touch right now?'
|
||||
}
|
||||
];
|
||||
|
||||
function deriveAugmentationSignals(userText) {
|
||||
var text = (userText || '').toLowerCase();
|
||||
return AUGMENTATION_SIGNAL_GUIDES.filter(function(guide) {
|
||||
return guide.patterns.some(function(pattern) { return pattern.test(text); });
|
||||
});
|
||||
}
|
||||
|
||||
function buildAugmentationState(userText, assistantText) {
|
||||
var text = userText || '';
|
||||
var guides = deriveAugmentationSignals(text);
|
||||
var level = getCrisisLevel(userText);
|
||||
var signals = guides.map(function(guide) { return guide.label; });
|
||||
var explicitIntent = signals.indexOf('Explicit self-harm intent') !== -1;
|
||||
var riskLevel = explicitIntent ? 'CRITICAL' : (level === 2 ? 'CRITICAL' : level === 1 ? 'HIGH' : (guides.length ? 'LOW' : 'NONE'));
|
||||
var riskScore = riskLevel === 'CRITICAL' ? 95 : riskLevel === 'HIGH' ? 75 : riskLevel === 'LOW' ? 25 : 5;
|
||||
riskScore = Math.min(100, riskScore + Math.min(guides.length * 5, 10));
|
||||
|
||||
if (riskLevel === 'CRITICAL' && signals.indexOf('Explicit self-harm intent') === -1) {
|
||||
signals.unshift('Explicit self-harm intent');
|
||||
riskScore = Math.max(riskScore, 95);
|
||||
}
|
||||
|
||||
var talkingPoints = guides.map(function(guide) { return guide.talkingPoint; });
|
||||
var techniques = guides.map(function(guide) { return guide.technique; });
|
||||
if (!talkingPoints.length) {
|
||||
talkingPoints = ['Keep the response advisory, local-only, and focused on immediate safety rather than abstract reassurance.'];
|
||||
}
|
||||
if (!techniques.length) {
|
||||
techniques = ['Slow the pace. Use short sentences. Invite one concrete grounding step.'];
|
||||
}
|
||||
if ((assistantText || '').indexOf('988') === -1 && (riskLevel === 'HIGH' || riskLevel === 'CRITICAL')) {
|
||||
talkingPoints.push('Surface 988 or Crisis Text Line explicitly if the assistant has not already done so.');
|
||||
}
|
||||
|
||||
var quoted = (text || '').replace(/\s+/g, ' ').slice(0, 120);
|
||||
var followUp = guides.length ? guides[0].followUp : 'What feels heaviest or most dangerous for you right now?';
|
||||
|
||||
return {
|
||||
riskLevel: riskLevel,
|
||||
riskScore: riskScore,
|
||||
signals: signals,
|
||||
talkingPoints: talkingPoints,
|
||||
techniques: techniques,
|
||||
followUpPrompt: 'You said "' + quoted + '". Consider following up with: ' + followUp,
|
||||
operatorNotice: 'Local-only advisory. Never replaces human judgment.',
|
||||
localOnly: true,
|
||||
advisoryOnly: true
|
||||
};
|
||||
}
|
||||
|
||||
function renderAugmentationSidebar(state) {
|
||||
if (!augmentationSidebar) return;
|
||||
augmentationRiskScore.textContent = 'Risk score: ' + state.riskScore + ' / 100 (' + state.riskLevel + ')';
|
||||
augmentationSignals.innerHTML = state.signals.length
|
||||
? state.signals.map(function(signal) { return '<li>' + escapeHtml(signal) + '</li>'; }).join('')
|
||||
: '<li>No crisis signals detected.</li>';
|
||||
augmentationTalkingPoints.innerHTML = state.talkingPoints.map(function(item) { return '<li>' + escapeHtml(item) + '</li>'; }).join('');
|
||||
augmentationTechniques.innerHTML = state.techniques.map(function(item) { return '<li>' + escapeHtml(item) + '</li>'; }).join('');
|
||||
augmentationFollowUp.textContent = state.followUpPrompt;
|
||||
augmentationNotice.textContent = state.operatorNotice;
|
||||
augmentationSidebar.classList.add('visible');
|
||||
}
|
||||
|
||||
function updateAugmentationState(userText, assistantText) {
|
||||
if (!augmentationEnabled) return;
|
||||
renderAugmentationSidebar(buildAugmentationState(userText, assistantText));
|
||||
}
|
||||
|
||||
function setOperatorAugmentationEnabled(enabled) {
|
||||
augmentationEnabled = !!enabled;
|
||||
try { localStorage.setItem('door_operator_augmentation_enabled', augmentationEnabled ? '1' : '0'); } catch (e) {}
|
||||
if (!augmentationToggle) return;
|
||||
augmentationToggle.setAttribute('aria-pressed', augmentationEnabled ? 'true' : 'false');
|
||||
augmentationToggle.classList.toggle('active', augmentationEnabled);
|
||||
augmentationToggle.textContent = augmentationEnabled ? 'Operator assist: on' : 'Operator assist: off';
|
||||
if (!augmentationEnabled && augmentationSidebar) {
|
||||
augmentationSidebar.classList.remove('visible');
|
||||
return;
|
||||
}
|
||||
if (augmentationEnabled && lastUserMessage) {
|
||||
var lastAssistant = '';
|
||||
for (var i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].role === 'assistant') { lastAssistant = messages[i].content; break; }
|
||||
}
|
||||
updateAugmentationState(lastUserMessage, lastAssistant);
|
||||
}
|
||||
}
|
||||
|
||||
function loadOperatorAugmentationPreference() {
|
||||
try {
|
||||
return localStorage.getItem('door_operator_augmentation_enabled') === '1';
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ===== OVERLAY =====
|
||||
|
||||
// Focus trap: cycle through focusable elements within the crisis overlay
|
||||
@@ -1385,347 +1439,18 @@ Sovereignty and service always.`;
|
||||
});
|
||||
|
||||
// ===== SAFETY PLAN LOGIC =====
|
||||
function emptySafetyPlan() {
|
||||
return {
|
||||
warningSigns: '',
|
||||
coping: '',
|
||||
distraction: '',
|
||||
help: '',
|
||||
environment: ''
|
||||
};
|
||||
}
|
||||
|
||||
function cloneSafetyPlan(plan) {
|
||||
var normalized = emptySafetyPlan();
|
||||
var source = plan || {};
|
||||
Object.keys(normalized).forEach(function(key) {
|
||||
normalized[key] = typeof source[key] === 'string' ? source[key] : '';
|
||||
});
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function applySafetyPlan(plan) {
|
||||
var nextPlan = cloneSafetyPlan(plan);
|
||||
Object.keys(safetyPlanFields).forEach(function(key) {
|
||||
safetyPlanFields[key].value = nextPlan[key];
|
||||
});
|
||||
}
|
||||
|
||||
function getSafetyPlanFormData() {
|
||||
return {
|
||||
warningSigns: safetyPlanFields.warningSigns.value,
|
||||
coping: safetyPlanFields.coping.value,
|
||||
distraction: safetyPlanFields.distraction.value,
|
||||
help: safetyPlanFields.help.value,
|
||||
environment: safetyPlanFields.environment.value
|
||||
};
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function setSafetyPlanStatus(message, tone) {
|
||||
if (!safetyPlanStatus) return;
|
||||
safetyPlanStatus.textContent = message || '';
|
||||
safetyPlanStatus.className = 'safety-plan-status' + (tone ? ' ' + tone : '');
|
||||
}
|
||||
|
||||
function getSafetyPlanVersions() {
|
||||
try {
|
||||
var saved = localStorage.getItem(SAFETY_PLAN_VERSIONS_KEY);
|
||||
if (!saved) return [];
|
||||
var parsed = JSON.parse(saved);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter(function(version) {
|
||||
return version && version.id && version.plan;
|
||||
});
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function setSafetyPlanVersions(versions) {
|
||||
localStorage.setItem(
|
||||
SAFETY_PLAN_VERSIONS_KEY,
|
||||
JSON.stringify((versions || []).slice(0, MAX_SAFETY_PLAN_VERSIONS))
|
||||
);
|
||||
}
|
||||
|
||||
function buildSafetyPlanVersion(plan, meta) {
|
||||
return {
|
||||
id: 'spv_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8),
|
||||
savedAt: new Date().toISOString(),
|
||||
source: (meta && meta.source) || 'save',
|
||||
restoredFrom: meta && meta.restoredFrom ? meta.restoredFrom : null,
|
||||
plan: cloneSafetyPlan(plan)
|
||||
};
|
||||
}
|
||||
|
||||
function ensureSafetyPlanVersionHistory() {
|
||||
var versions = getSafetyPlanVersions();
|
||||
if (versions.length) {
|
||||
return versions;
|
||||
}
|
||||
|
||||
try {
|
||||
var saved = localStorage.getItem(SAFETY_PLAN_STORAGE_KEY);
|
||||
if (!saved) {
|
||||
return [];
|
||||
}
|
||||
var parsed = JSON.parse(saved);
|
||||
var migrated = [buildSafetyPlanVersion(parsed, { source: 'legacy' })];
|
||||
setSafetyPlanVersions(migrated);
|
||||
return migrated;
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function formatSafetyPlanTimestamp(iso) {
|
||||
var date = new Date(iso || '');
|
||||
if (isNaN(date.getTime())) {
|
||||
return 'Saved just now';
|
||||
}
|
||||
return date.toLocaleString([], {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
function getSafetyPlanVersionById(versionId) {
|
||||
var versions = getSafetyPlanVersions();
|
||||
for (var i = 0; i < versions.length; i++) {
|
||||
if (versions[i].id === versionId) {
|
||||
return { version: versions[i], index: i, versions: versions };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function calculateSafetyPlanDiff(previousText, currentText) {
|
||||
var previous = String(previousText || '');
|
||||
var current = String(currentText || '');
|
||||
var start = 0;
|
||||
while (start < previous.length && start < current.length && previous.charAt(start) === current.charAt(start)) {
|
||||
start += 1;
|
||||
}
|
||||
|
||||
var previousEnd = previous.length - 1;
|
||||
var currentEnd = current.length - 1;
|
||||
while (previousEnd >= start && currentEnd >= start && previous.charAt(previousEnd) === current.charAt(currentEnd)) {
|
||||
previousEnd -= 1;
|
||||
currentEnd -= 1;
|
||||
}
|
||||
|
||||
return {
|
||||
before: current.slice(0, start),
|
||||
removed: previous.slice(start, previousEnd + 1),
|
||||
added: current.slice(start, currentEnd + 1),
|
||||
after: current.slice(currentEnd + 1)
|
||||
};
|
||||
}
|
||||
|
||||
function renderDiffSegmentHtml(previousText, currentText) {
|
||||
var previous = String(previousText || '');
|
||||
var current = String(currentText || '');
|
||||
|
||||
if (!previous && !current) {
|
||||
return '<p class="safety-plan-empty">No content saved for this section yet.</p>';
|
||||
}
|
||||
|
||||
if (previous === current) {
|
||||
return '<div class="safety-plan-diff-block diff-unchanged">' + escapeHtml(current || 'No changes in this version.') + '</div>';
|
||||
}
|
||||
|
||||
var diff = calculateSafetyPlanDiff(previous, current);
|
||||
var blocks = [];
|
||||
if (diff.before) {
|
||||
blocks.push('<div class="safety-plan-diff-block diff-unchanged">' + escapeHtml(diff.before) + '</div>');
|
||||
}
|
||||
if (diff.removed) {
|
||||
blocks.push('<div class="safety-plan-diff-block diff-removed">Removed<br>' + escapeHtml(diff.removed) + '</div>');
|
||||
}
|
||||
if (diff.added) {
|
||||
blocks.push('<div class="safety-plan-diff-block diff-added">Added<br>' + escapeHtml(diff.added) + '</div>');
|
||||
}
|
||||
if (diff.after) {
|
||||
blocks.push('<div class="safety-plan-diff-block diff-unchanged">' + escapeHtml(diff.after) + '</div>');
|
||||
}
|
||||
return blocks.join('');
|
||||
}
|
||||
|
||||
function renderSafetyPlanDiff(versionId) {
|
||||
if (!safetyPlanDiff) return;
|
||||
|
||||
var versions = getSafetyPlanVersions();
|
||||
if (!versions.length) {
|
||||
safetyPlanDiff.innerHTML = '<p class="safety-plan-empty">Save your plan to start tracking changes.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
var selected = getSafetyPlanVersionById(versionId || selectedSafetyPlanVersionId || versions[0].id);
|
||||
if (!selected) {
|
||||
selected = { version: versions[0], index: 0, versions: versions };
|
||||
selectedSafetyPlanVersionId = versions[0].id;
|
||||
}
|
||||
|
||||
var baseline = selected.versions[selected.index + 1]
|
||||
? cloneSafetyPlan(selected.versions[selected.index + 1].plan)
|
||||
: emptySafetyPlan();
|
||||
var currentPlan = cloneSafetyPlan(selected.version.plan);
|
||||
var baselineLabel = selected.versions[selected.index + 1]
|
||||
? formatSafetyPlanTimestamp(selected.versions[selected.index + 1].savedAt)
|
||||
: 'an empty plan';
|
||||
|
||||
var fields = [
|
||||
['Warning signs', 'warningSigns'],
|
||||
['Internal coping strategies', 'coping'],
|
||||
['People/Places for distraction', 'distraction'],
|
||||
['People I can ask for help', 'help'],
|
||||
['Making my environment safe', 'environment']
|
||||
];
|
||||
|
||||
var html = [
|
||||
'<div class="safety-plan-diff-meta">Comparing ' +
|
||||
escapeHtml(formatSafetyPlanTimestamp(selected.version.savedAt)) +
|
||||
' against ' + escapeHtml(baselineLabel) + '.</div>'
|
||||
];
|
||||
|
||||
fields.forEach(function(field) {
|
||||
html.push(
|
||||
'<div class="safety-plan-diff-field">' +
|
||||
'<h4>' + escapeHtml(field[0]) + '</h4>' +
|
||||
renderDiffSegmentHtml(baseline[field[1]], currentPlan[field[1]]) +
|
||||
'</div>'
|
||||
);
|
||||
});
|
||||
|
||||
safetyPlanDiff.innerHTML = html.join('');
|
||||
}
|
||||
|
||||
function renderSafetyPlanVersionHistory() {
|
||||
if (!safetyPlanHistory) return;
|
||||
|
||||
var versions = getSafetyPlanVersions();
|
||||
if (!versions.length) {
|
||||
safetyPlanHistory.innerHTML = '<p class="safety-plan-empty">No saved versions yet. Each save creates a new local version.</p>';
|
||||
renderSafetyPlanDiff(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedSafetyPlanVersionId || !getSafetyPlanVersionById(selectedSafetyPlanVersionId)) {
|
||||
selectedSafetyPlanVersionId = versions[0].id;
|
||||
}
|
||||
|
||||
var html = [];
|
||||
versions.forEach(function(version, index) {
|
||||
var note = 'Saved locally';
|
||||
if (version.source === 'restore') {
|
||||
note = 'Restored from an earlier version';
|
||||
} else if (version.source === 'legacy') {
|
||||
note = 'Imported from your previous saved plan';
|
||||
}
|
||||
|
||||
html.push(
|
||||
'<div class="safety-plan-history-item' + (selectedSafetyPlanVersionId === version.id ? ' active' : '') + '">' +
|
||||
'<div class="safety-plan-history-meta">' +
|
||||
'<span class="safety-plan-history-title">' + escapeHtml(index === 0 ? 'Current version' : 'Version ' + (versions.length - index)) + '</span>' +
|
||||
'<span class="safety-plan-empty">' + escapeHtml(formatSafetyPlanTimestamp(version.savedAt)) + '</span>' +
|
||||
'</div>' +
|
||||
'<div class="safety-plan-history-note">' + escapeHtml(note) + '</div>' +
|
||||
'<div class="safety-plan-history-actions">' +
|
||||
'<button type="button" class="safety-plan-history-button" data-version-id="' + escapeHtml(version.id) + '">View diff</button>' +
|
||||
'<button type="button" class="safety-plan-restore-button" data-restore-version-id="' + escapeHtml(version.id) + '">Restore this version</button>' +
|
||||
'</div>' +
|
||||
'</div>'
|
||||
);
|
||||
});
|
||||
|
||||
safetyPlanHistory.innerHTML = html.join('');
|
||||
renderSafetyPlanDiff(selectedSafetyPlanVersionId);
|
||||
}
|
||||
|
||||
function saveSafetyPlanVersion(plan, meta) {
|
||||
var snapshot = buildSafetyPlanVersion(plan, meta);
|
||||
var versions = getSafetyPlanVersions();
|
||||
versions.unshift(snapshot);
|
||||
setSafetyPlanVersions(versions);
|
||||
localStorage.setItem(SAFETY_PLAN_STORAGE_KEY, JSON.stringify(snapshot.plan));
|
||||
selectedSafetyPlanVersionId = snapshot.id;
|
||||
renderSafetyPlanVersionHistory();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
function restoreSafetyPlanVersion(versionId) {
|
||||
var selected = getSafetyPlanVersionById(versionId);
|
||||
if (!selected) {
|
||||
setSafetyPlanStatus('That version could not be restored.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
applySafetyPlan(selected.version.plan);
|
||||
var restored = saveSafetyPlanVersion(selected.version.plan, {
|
||||
source: 'restore',
|
||||
restoredFrom: selected.version.id
|
||||
});
|
||||
setSafetyPlanStatus(
|
||||
'Restored version from ' + formatSafetyPlanTimestamp(selected.version.savedAt) + ' as the current plan.',
|
||||
'success'
|
||||
);
|
||||
return restored;
|
||||
}
|
||||
|
||||
function loadSafetyPlan() {
|
||||
var versions = ensureSafetyPlanVersionHistory();
|
||||
var latestPlan = versions.length ? versions[0].plan : null;
|
||||
|
||||
if (!latestPlan) {
|
||||
try {
|
||||
var saved = localStorage.getItem(SAFETY_PLAN_STORAGE_KEY);
|
||||
latestPlan = saved ? JSON.parse(saved) : null;
|
||||
} catch (e) {
|
||||
latestPlan = null;
|
||||
try {
|
||||
var saved = localStorage.getItem('timmy_safety_plan');
|
||||
if (saved) {
|
||||
var plan = JSON.parse(saved);
|
||||
document.getElementById('sp-warning-signs').value = plan.warningSigns || '';
|
||||
document.getElementById('sp-coping').value = plan.coping || '';
|
||||
document.getElementById('sp-distraction').value = plan.distraction || '';
|
||||
document.getElementById('sp-help').value = plan.help || '';
|
||||
document.getElementById('sp-environment').value = plan.environment || '';
|
||||
}
|
||||
}
|
||||
|
||||
applySafetyPlan(latestPlan || emptySafetyPlan());
|
||||
renderSafetyPlanVersionHistory();
|
||||
if (versions.length) {
|
||||
setSafetyPlanStatus('Version history stays on this device only.', '');
|
||||
} else {
|
||||
setSafetyPlanStatus('Every save creates a local version you can diff and restore.', '');
|
||||
}
|
||||
}
|
||||
|
||||
function openSafetyPlanModal(triggerEl) {
|
||||
loadSafetyPlan();
|
||||
safetyPlanModal.classList.add('active');
|
||||
_activateSafetyPlanFocusTrap(triggerEl);
|
||||
}
|
||||
|
||||
if (safetyPlanHistory) {
|
||||
safetyPlanHistory.addEventListener('click', function(event) {
|
||||
var restoreButton = event.target.closest('[data-restore-version-id]');
|
||||
if (restoreButton) {
|
||||
restoreSafetyPlanVersion(restoreButton.getAttribute('data-restore-version-id'));
|
||||
return;
|
||||
}
|
||||
|
||||
var diffButton = event.target.closest('[data-version-id]');
|
||||
if (diffButton) {
|
||||
selectedSafetyPlanVersionId = diffButton.getAttribute('data-version-id');
|
||||
renderSafetyPlanVersionHistory();
|
||||
}
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
closeSafetyPlan.addEventListener('click', function() {
|
||||
@@ -1739,23 +1464,41 @@ Sovereignty and service always.`;
|
||||
});
|
||||
|
||||
saveSafetyPlan.addEventListener('click', function() {
|
||||
var plan = {
|
||||
warningSigns: document.getElementById('sp-warning-signs').value,
|
||||
coping: document.getElementById('sp-coping').value,
|
||||
distraction: document.getElementById('sp-distraction').value,
|
||||
help: document.getElementById('sp-help').value,
|
||||
environment: document.getElementById('sp-environment').value
|
||||
};
|
||||
try {
|
||||
var snapshot = saveSafetyPlanVersion(getSafetyPlanFormData(), { source: 'save' });
|
||||
setSafetyPlanStatus('Saved locally as a new version at ' + formatSafetyPlanTimestamp(snapshot.savedAt) + '.', 'success');
|
||||
localStorage.setItem('timmy_safety_plan', JSON.stringify(plan));
|
||||
safetyPlanModal.classList.remove('active');
|
||||
_restoreSafetyPlanFocus();
|
||||
alert('Safety plan saved locally.');
|
||||
} catch (e) {
|
||||
setSafetyPlanStatus('Error saving plan.', 'error');
|
||||
alert('Error saving plan.');
|
||||
}
|
||||
});
|
||||
|
||||
// ===== SAFETY PLAN FOCUS TRAP (fix #65) =====
|
||||
// Focusable elements inside the modal, in tab order
|
||||
var _spFocusableIds = [
|
||||
'close-safety-plan',
|
||||
'sp-warning-signs',
|
||||
'sp-coping',
|
||||
'sp-distraction',
|
||||
'sp-help',
|
||||
'sp-environment',
|
||||
'cancel-safety-plan',
|
||||
'save-safety-plan'
|
||||
];
|
||||
var _spTriggerEl = null; // element that opened the modal
|
||||
|
||||
function _getSpFocusableEls() {
|
||||
return Array.prototype.slice.call(
|
||||
safetyPlanModal.querySelectorAll('button:not([disabled]), textarea:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')
|
||||
).filter(function(el) {
|
||||
return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
|
||||
});
|
||||
return _spFocusableIds
|
||||
.map(function(id) { return document.getElementById(id); })
|
||||
.filter(function(el) { return el && !el.disabled; });
|
||||
}
|
||||
|
||||
function _trapSafetyPlanFocus(e) {
|
||||
@@ -1812,13 +1555,17 @@ Sovereignty and service always.`;
|
||||
|
||||
// Wire open buttons to activate focus trap
|
||||
safetyPlanBtn.addEventListener('click', function() {
|
||||
openSafetyPlanModal(safetyPlanBtn);
|
||||
loadSafetyPlan();
|
||||
safetyPlanModal.classList.add('active');
|
||||
_activateSafetyPlanFocusTrap(safetyPlanBtn);
|
||||
});
|
||||
|
||||
// Crisis panel safety plan button (if crisis panel is visible)
|
||||
if (crisisSafetyPlanBtn) {
|
||||
crisisSafetyPlanBtn.addEventListener('click', function() {
|
||||
openSafetyPlanModal(crisisSafetyPlanBtn);
|
||||
loadSafetyPlan();
|
||||
safetyPlanModal.classList.add('active');
|
||||
_activateSafetyPlanFocusTrap(crisisSafetyPlanBtn);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1836,9 +1583,10 @@ Sovereignty and service always.`;
|
||||
|
||||
addMessage('user', text);
|
||||
messages.push({ role: 'user', content: text });
|
||||
var lastUserMessage = text;
|
||||
lastUserMessage = text;
|
||||
|
||||
checkCrisis(text);
|
||||
updateAugmentationState(text, '');
|
||||
|
||||
msgInput.value = '';
|
||||
msgInput.style.height = 'auto';
|
||||
@@ -1927,6 +1675,7 @@ Sovereignty and service always.`;
|
||||
messages.push({ role: 'assistant', content: fullText });
|
||||
saveMessages();
|
||||
checkCrisis(fullText);
|
||||
updateAugmentationState(lastUserMessage || '', fullText);
|
||||
}
|
||||
isStreaming = false;
|
||||
sendBtn.disabled = msgInput.value.trim().length === 0;
|
||||
@@ -1953,6 +1702,11 @@ Sovereignty and service always.`;
|
||||
});
|
||||
|
||||
sendBtn.addEventListener('click', sendMessage);
|
||||
if (augmentationToggle) {
|
||||
augmentationToggle.addEventListener('click', function() {
|
||||
setOperatorAugmentationEnabled(!augmentationEnabled);
|
||||
});
|
||||
}
|
||||
|
||||
// ===== WELCOME MESSAGE =====
|
||||
function init() {
|
||||
@@ -1965,11 +1719,14 @@ Sovereignty and service always.`;
|
||||
// Check for URL params (e.g., ?safetyplan=true for PWA shortcut)
|
||||
var urlParams = new URLSearchParams(window.location.search);
|
||||
if (urlParams.get('safetyplan') === 'true') {
|
||||
openSafetyPlanModal(safetyPlanBtn);
|
||||
loadSafetyPlan();
|
||||
safetyPlanModal.classList.add('active');
|
||||
_activateSafetyPlanFocusTrap(safetyPlanBtn);
|
||||
// Clean up URL
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
}
|
||||
|
||||
setOperatorAugmentationEnabled(loadOperatorAugmentationPreference());
|
||||
msgInput.focus();
|
||||
}
|
||||
|
||||
|
||||
33
tests/test_operator_augmentation.py
Normal file
33
tests/test_operator_augmentation.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from augmentation import CounselorAugmentationEngine
|
||||
|
||||
|
||||
def test_explicit_intent_forces_critical_sidebar_guidance():
|
||||
engine = CounselorAugmentationEngine()
|
||||
result = engine.build_augmented_guidance(
|
||||
"I want to kill myself tonight. I already wrote a note.",
|
||||
assistant_text="I'm here with you."
|
||||
)
|
||||
|
||||
assert result.risk_level == "CRITICAL"
|
||||
assert result.risk_score >= 90
|
||||
assert result.local_only is True
|
||||
assert result.advisory_only is True
|
||||
assert "Explicit self-harm intent" in result.signals
|
||||
assert result.suggested_talking_points
|
||||
assert result.deescalation_techniques
|
||||
assert "You said" in result.follow_up_prompt
|
||||
assert "never replaces human judgment" in result.operator_notice.lower()
|
||||
|
||||
|
||||
def test_hopelessness_signal_produces_follow_up_and_talking_points():
|
||||
engine = CounselorAugmentationEngine()
|
||||
result = engine.build_augmented_guidance(
|
||||
"I feel so hopeless about my life and I can't go on.",
|
||||
assistant_text=""
|
||||
)
|
||||
|
||||
assert result.risk_level in {"HIGH", "CRITICAL"}
|
||||
assert result.signals
|
||||
assert result.suggested_talking_points
|
||||
assert result.deescalation_techniques
|
||||
assert result.follow_up_prompt
|
||||
20
tests/test_operator_augmentation_ui.py
Normal file
20
tests/test_operator_augmentation_ui.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_operator_augmentation_ui_hooks_exist():
|
||||
html = Path('index.html').read_text()
|
||||
|
||||
assert 'id="augmentation-toggle"' in html
|
||||
assert 'id="augmentation-sidebar"' in html
|
||||
assert 'id="augmentation-risk-score"' in html
|
||||
assert 'id="augmentation-signals"' in html
|
||||
assert 'id="augmentation-follow-up"' in html
|
||||
assert 'door_operator_augmentation_enabled' in html
|
||||
assert 'function buildAugmentationState(' in html
|
||||
assert 'function renderAugmentationSidebar(' in html
|
||||
assert 'function updateAugmentationState(' in html
|
||||
assert 'function setOperatorAugmentationEnabled(' in html
|
||||
assert 'function loadOperatorAugmentationPreference(' in html
|
||||
assert 'getCrisisLevel(userText)' in html
|
||||
assert "updateAugmentationState(text, '')" in html
|
||||
assert "updateAugmentationState(lastUserMessage || '', fullText)" in html
|
||||
26
tests/test_operator_augmentation_walkthrough.py
Normal file
26
tests/test_operator_augmentation_walkthrough.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
|
||||
def test_operator_augmentation_walkthrough_marks_explicit_intent_critical():
|
||||
url = Path('index.html').resolve().as_uri()
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page()
|
||||
page.goto(url, wait_until='load')
|
||||
page.click('#augmentation-toggle')
|
||||
page.fill('#msg-input', 'I want to kill myself tonight. I already wrote a note.')
|
||||
page.click('#send-btn')
|
||||
page.wait_for_timeout(300)
|
||||
|
||||
risk = page.locator('#augmentation-risk-score').inner_text()
|
||||
signals = page.locator('#augmentation-signals').inner_text()
|
||||
follow_up = page.locator('#augmentation-follow-up').inner_text()
|
||||
|
||||
browser.close()
|
||||
|
||||
assert 'CRITICAL' in risk
|
||||
assert 'Explicit self-harm intent' in signals
|
||||
assert 'You said "I want to kill myself tonight. I already wrote a note."' in follow_up
|
||||
@@ -1,21 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_safety_plan_version_history_contract_present() -> None:
|
||||
html = Path("index.html").read_text(encoding="utf-8")
|
||||
|
||||
required_snippets = [
|
||||
'id="safety-plan-history"',
|
||||
'id="safety-plan-diff"',
|
||||
'id="safety-plan-status"',
|
||||
'Version History',
|
||||
'timmy_safety_plan_versions',
|
||||
'function renderSafetyPlanVersionHistory()',
|
||||
'function renderSafetyPlanDiff(',
|
||||
'function restoreSafetyPlanVersion(',
|
||||
'diff-added',
|
||||
'diff-removed',
|
||||
]
|
||||
|
||||
for snippet in required_snippets:
|
||||
assert snippet in html, f"missing safety plan versioning contract: {snippet}"
|
||||
Reference in New Issue
Block a user