A / app.py
linxinhua's picture
End Session gates: turn off end_session_gate (probe-count/20-min condition no longer blocks); demote revise_check to a one-shot warning (first click below the ~10% revision threshold shows the revision modal and blocks; every later click finalises regardless).
34ef029 verified
Raw
History Blame Contribute Delete
136 kB
"""Gradio app for the Socratic AI condition (v4 two-agent architecture).
Single-layout design (no visible stage labels):
- Left: chat area. The case is the first 'assistant' message.
- Right: a text input that doubles as initial-argument writing in Phase 1
and a participant notepad in Phase 2.
Phases (implicit, driven by button clicks):
Phase 1 (entry): chatbot shows the case; right input is for initial
argument; chat input DISABLED.
Phase 2 (after Submit Initial confirm): host code calls
`core.perfect_answer.generate_session_artifacts` (around
15-30s blocking) to produce the per-session essay +
discussion plan. The plan is parsed and pinned into the
session cache. Each subsequent chat turn runs a manager
agent + main bot agent (see core.orchestrator). Right
input becomes a notepad; chat ENABLED.
Phase 3 (after End Session): chat input + notepad locked, done panel shown.
Per-message aha!/ugh. reactions: same as v3. Gradio's like/dislike buttons
swapped via EMOJI_SWAP_HEAD; clicks land in `logger.add_feedback`.
Two-agent flow per chat turn (post-Phase 1):
1. Manager agent classifies the turn (~2-4s blocking).
2. Host builds PLAN CONTROL block from the verdict.
3. Main bot streams its reply.
4. Host logs the turn (user_message + verdict + plan_control + bot reply
+ scratch + latencies).
"""
import threading
import time
import gradio as gr
from core import client, get_next_client, MODEL, REASONING_EFFORT, VERBOSITY
from core import SessionLogger, now_aest
from core.config_loader import BASE_DIR, CONFIG
# Participant-side lockdown flags read from config.yaml. Defaults are FALSE
# (test mode). For an actual experiment run, set all three to true in the
# config (or via Space Variables) and redeploy.
_LOCKDOWN_CFG = (CONFIG.get("lockdown") if isinstance(CONFIG, dict) else None) or {}
LOCKDOWN_ARG_CLIPBOARD = bool(_LOCKDOWN_CFG.get("arg_clipboard", False))
LOCKDOWN_CHAT_COPY = bool(_LOCKDOWN_CFG.get("chat_copy", False))
ENFORCE_END_SESSION_GATE = bool(_LOCKDOWN_CFG.get("end_session_gate", False))
LOCKDOWN_REVISE_CHECK = bool(_LOCKDOWN_CFG.get("revise_check", False))
print(
f"[lockdown] arg_clipboard={LOCKDOWN_ARG_CLIPBOARD} "
f"chat_copy={LOCKDOWN_CHAT_COPY} "
f"end_session_gate={ENFORCE_END_SESSION_GATE} "
f"revise_check={LOCKDOWN_REVISE_CHECK}",
flush=True,
)
# ============================================================
# Tutorial image carousel — appears as a full-screen overlay on
# participant entry. Images live in `tutorial_images/` next to this app.py,
# named 01.png / 02.png / ... so they sort in display order. The folder
# scan is done once at startup; each image is base64-encoded and injected
# into the head as a JS array, so no runtime file serving is needed.
# ============================================================
import base64 as _b64
from pathlib import Path as _Path
_TUTORIAL_DIR = BASE_DIR / "tutorial_images"
def _load_tutorial_images_b64():
"""Scan tutorial_images/, sort by filename, return list of data URLs.
Returns [] if folder is missing or empty (carousel won't render)."""
if not _TUTORIAL_DIR.exists():
return []
out = []
# ONLY .png accepted — earlier deploys left stale .webp on remote that
# upload_folder won't auto-clean, so narrow the loader to ignore them.
exts = {".png": "image/png"}
for f in sorted(_TUTORIAL_DIR.iterdir()):
if not f.is_file():
continue
mime = exts.get(f.suffix.lower())
if not mime:
continue
try:
raw = f.read_bytes()
enc = _b64.b64encode(raw).decode("ascii")
out.append(f"data:{mime};base64,{enc}")
except Exception as e:
print(f"[tutorial] skipping {f.name}: {e}", flush=True)
return out
_TUTORIAL_IMAGES_B64 = _load_tutorial_images_b64()
print(f"[tutorial] loaded {len(_TUTORIAL_IMAGES_B64)} image(s)", flush=True)
def _build_tutorial_head():
"""Build the <style> + <script> block that injects:
(1) a Welcome overlay shown first (Msg1 text + 'Start walkthrough'),
(2) a mixed walkthrough carousel that interleaves image slides and
text slides (Msg2, Msg3); each step has a 'Next' button at the
footer, except the last which shows 'Start' to close the overlay.
Slides in order:
1-3: tutorial images 01..03
4: Msg2 text panel
5: Msg3 text panel
6-7: tutorial images 04..05
All advance buttons share the orange Gradio primary-button color so
they match the right-side 'Submit initial argument' button.
Returns empty string if there aren't enough images to fill the layout.
"""
if len(_TUTORIAL_IMAGES_B64) < 5:
return ""
arr = "[" + ",".join(f'"{u}"' for u in _TUTORIAL_IMAGES_B64) + "]"
return """
<style>
/* ----- Welcome overlay (shown first; Msg1) ----- */
#welcome-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.78);
z-index: 200001;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
#welcome-overlay .welcome-modal {
background: #ffffff;
border-radius: 16px;
padding: 64px 72px;
max-width: 760px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
display: flex;
flex-direction: column;
gap: 36px;
align-items: center;
text-align: center;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji", sans-serif;
}
#welcome-overlay .welcome-text {
font-size: 1.45em;
color: #1f2937;
line-height: 1.6;
}
#welcome-overlay .welcome-btn {
background: var(--button-primary-background-fill, #f59e0b);
color: var(--button-primary-text-color, #fff);
border: none;
border-radius: 8px;
padding: 14px 34px;
font-size: 1.15em;
font-weight: 600;
cursor: pointer;
font-family: inherit;
transition: filter 0.15s ease;
}
#welcome-overlay .welcome-btn:hover {
background: var(--button-primary-background-fill-hover, #d97706);
filter: brightness(0.95);
}
/* ----- Walkthrough overlay (mixed image + text carousel) ----- */
#walkthrough-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.92);
z-index: 200000;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
}
#walkthrough-overlay .walkthrough-img {
max-width: 100vw;
max-height: 100vh;
object-fit: contain;
display: none;
}
#walkthrough-overlay .walkthrough-text-modal {
background: #ffffff;
border-radius: 16px;
padding: 64px 72px;
max-width: 760px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
text-align: center;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 1.45em;
color: #1f2937;
line-height: 1.6;
display: none;
}
#walkthrough-overlay .walkthrough-text-modal b,
#walkthrough-overlay .walkthrough-text-modal strong {
color: #111827;
}
#walkthrough-overlay .walkthrough-footer {
position: fixed;
bottom: 28px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 18px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
#walkthrough-overlay .walkthrough-counter {
color: rgba(255, 255, 255, 0.92);
background: rgba(0, 0, 0, 0.55);
padding: 7px 14px;
border-radius: 16px;
font-size: 0.95em;
font-variant-numeric: tabular-nums;
}
#walkthrough-overlay .walkthrough-back {
background: transparent;
color: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 8px;
padding: 10px 24px;
font-size: 1em;
font-weight: 600;
cursor: pointer;
font-family: inherit;
transition: opacity 0.15s ease, background 0.15s ease;
}
#walkthrough-overlay .walkthrough-back:hover {
background: rgba(255, 255, 255, 0.12);
}
#walkthrough-overlay .walkthrough-back:disabled {
opacity: 0.3;
cursor: not-allowed;
}
#walkthrough-overlay .walkthrough-next,
#walkthrough-overlay .walkthrough-done {
background: var(--button-primary-background-fill, #f59e0b);
color: var(--button-primary-text-color, #fff);
border: none;
border-radius: 8px;
padding: 10px 28px;
font-size: 1em;
font-weight: 600;
cursor: pointer;
font-family: inherit;
transition: filter 0.15s ease;
}
#walkthrough-overlay .walkthrough-next:hover,
#walkthrough-overlay .walkthrough-done:hover {
background: var(--button-primary-background-fill-hover, #d97706);
filter: brightness(0.95);
}
#walkthrough-overlay .walkthrough-done { display: none; }
#walkthrough-overlay.last-slide .walkthrough-done { display: inline-block; }
#walkthrough-overlay.last-slide .walkthrough-next { display: none; }
</style>
<script>
window.__TUTORIAL_IMAGES = """ + arr + """;
(function() {
if (!Array.isArray(window.__TUTORIAL_IMAGES) || window.__TUTORIAL_IMAGES.length < 5) return;
var started = false;
// Recovery guard: if localStorage carries an unfinished session, the
// RECOVERY_HEAD layer takes over (modal + restore flow). Skip welcome
// and walkthrough entirely so the recovery modal can render cleanly
// without the welcome overlay sitting underneath.
try {
var raw = localStorage.getItem('socratic_ca_session_v1');
if (raw) {
var st = JSON.parse(raw);
if (st && st.session_id) {
console.log('[walkthrough] skipped — recovery in progress for', st.session_id);
return;
}
}
} catch (e) { /* fall through to normal flow */ }
// Msg2 / Msg3 HTML — kept here as constants for easy edit.
var MSG2_HTML =
'The AI assistant will discuss your argument with you and help you ' +
'reflect on and improve your reasoning.<br><br>' +
'As you go, <b>revise your argument</b> on the right. ' +
'When you are ready, submit your final revised version.';
var MSG3_HTML =
'During the discussion, you can <b>ask for clarification</b>, ' +
'<b>disagree</b> with the AI assistant, or <b>ask it to rephrase ' +
'anything that feels unclear</b>. The AI assistant may take a few ' +
'seconds to reply. Please wait — this is normal.';
function buildWelcome() {
var overlay = document.createElement('div');
overlay.id = 'welcome-overlay';
overlay.innerHTML =
'<div class="welcome-modal">' +
'<div class="welcome-text">' +
'Welcome to the study.<br><br>' +
'First, we will briefly show you how to use the interface.' +
'</div>' +
'<button type="button" class="welcome-btn">Start walkthrough</button>' +
'</div>';
document.body.appendChild(overlay);
overlay.querySelector('.welcome-btn').addEventListener('click', function() {
overlay.remove();
buildWalkthrough();
});
}
function buildWalkthrough() {
var imgs = window.__TUTORIAL_IMAGES;
// Mixed slide deck: image, image, image, text(Msg2), text(Msg3), image, image
var slides = [
{type: 'image', src: imgs[0]},
{type: 'image', src: imgs[1]},
{type: 'image', src: imgs[2]},
{type: 'text', html: MSG2_HTML},
{type: 'text', html: MSG3_HTML},
{type: 'image', src: imgs[3]},
{type: 'image', src: imgs[4]}
];
var N = slides.length;
var idx = 0;
var overlay = document.createElement('div');
overlay.id = 'walkthrough-overlay';
overlay.innerHTML =
'<img class="walkthrough-img" alt="Walkthrough slide">' +
'<div class="walkthrough-text-modal"></div>' +
'<div class="walkthrough-footer">' +
'<button type="button" class="walkthrough-back">Back</button>' +
'<span class="walkthrough-counter"></span>' +
'<button type="button" class="walkthrough-next">Next</button>' +
'<button type="button" class="walkthrough-done">Start</button>' +
'</div>';
document.body.appendChild(overlay);
var img = overlay.querySelector('.walkthrough-img');
var textModal = overlay.querySelector('.walkthrough-text-modal');
var counter = overlay.querySelector('.walkthrough-counter');
var backBtn = overlay.querySelector('.walkthrough-back');
var nextBtn = overlay.querySelector('.walkthrough-next');
var doneBtn = overlay.querySelector('.walkthrough-done');
function update() {
var s = slides[idx];
if (s.type === 'image') {
img.src = s.src;
img.style.display = 'block';
textModal.style.display = 'none';
} else {
textModal.innerHTML = s.html;
textModal.style.display = 'block';
img.style.display = 'none';
}
counter.textContent = (idx + 1) + ' / ' + N;
backBtn.disabled = (idx === 0);
overlay.classList.toggle('last-slide', idx === N - 1);
}
backBtn.addEventListener('click', function() {
if (idx > 0) { idx--; update(); }
});
nextBtn.addEventListener('click', function() {
if (idx < N - 1) { idx++; update(); }
});
doneBtn.addEventListener('click', function() {
// Record the walkthrough-finished timestamp client-side. This
// value is read at argument-submit time via the js= wrapper on
// submit_initial_btn.click and passed into the Python handler,
// which stores it on the SessionLogger.
window.__walkthroughStartedAt = Date.now() / 1000;
console.log('[walkthrough] recorded ts=' + window.__walkthroughStartedAt);
overlay.remove();
});
update();
}
function start() {
if (started) return;
started = true;
buildWelcome();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();
</script>
"""
TUTORIAL_HEAD = _build_tutorial_head()
# ============================================================
# Session-recovery layer (browser-side). localStorage keys are namespaced per
# condition (`socratic_ca_session_v1` / `socratic_ca_tab_id`) so other A_Ethic
# condition Spaces opened in the same browser do not collide. The global JS
# helper is exposed as `window.__RECOVERY` (same name across conditions for
# the .then(js=...) snippets, but each Space defines its own copy on load).
# ============================================================
RECOVERY_HEAD = """
<style>
.soc-hidden-helper,
#recover-session-id-input,
#recover-btn,
#recovery-payload {
display: none !important;
}
#recovery-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.78);
z-index: 200002;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
#recovery-overlay .recovery-modal {
background: #ffffff;
border-radius: 16px;
padding: 56px 64px;
max-width: 640px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
display: flex;
flex-direction: column;
gap: 28px;
align-items: center;
text-align: center;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
#recovery-overlay .recovery-title {
font-size: 1.35em;
font-weight: 600;
color: #111827;
line-height: 1.35;
}
#recovery-overlay .recovery-body {
font-size: 1.05em;
color: #374151;
line-height: 1.55;
}
#recovery-overlay .recovery-actions {
display: flex;
gap: 14px;
flex-wrap: wrap;
justify-content: center;
}
#recovery-overlay .recovery-fresh,
#recovery-overlay .recovery-continue {
border: none;
border-radius: 8px;
padding: 12px 28px;
font-size: 1.05em;
font-weight: 600;
cursor: pointer;
font-family: inherit;
transition: filter 0.15s ease, background 0.15s ease;
}
#recovery-overlay .recovery-fresh {
background: transparent;
color: #4b5563;
border: 1px solid #d1d5db;
}
#recovery-overlay .recovery-fresh:hover { background: #f3f4f6; }
#recovery-overlay .recovery-continue {
background: var(--button-primary-background-fill, #f59e0b);
color: var(--button-primary-text-color, #fff);
}
#recovery-overlay .recovery-continue:hover {
background: var(--button-primary-background-fill-hover, #d97706);
filter: brightness(0.95);
}
#recovery-overlay .recovery-loading {
color: #6b7280;
font-size: 0.95em;
display: none;
}
#recovery-overlay.loading .recovery-actions { display: none; }
#recovery-overlay.loading .recovery-loading { display: block; }
#recovery-overlay .recovery-error {
color: #b91c1c;
font-size: 0.95em;
display: none;
}
#recovery-overlay.error .recovery-error { display: block; }
#recovery-overlay.error .recovery-loading { display: none; }
#recovery-overlay.error .recovery-actions { display: flex; }
</style>
<script>
window.__RECOVERY = (function() {
const STORAGE_KEY = 'socratic_ca_session_v1';
const TAB_KEY = 'socratic_ca_tab_id';
function getOrCreateTabId() {
let tid = sessionStorage.getItem(TAB_KEY);
if (!tid) {
tid = 'tab_' + Date.now().toString(36) + '_' +
Math.random().toString(36).slice(2, 10);
sessionStorage.setItem(TAB_KEY, tid);
}
return tid;
}
function readState() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
return raw ? JSON.parse(raw) : null;
} catch (e) { return null; }
}
function writeState(state) {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); }
catch (e) { console.warn('[recovery] localStorage write failed', e); }
}
function clearState() {
try { localStorage.removeItem(STORAGE_KEY); } catch (e) {}
}
function saveSession(sid, code) {
writeState({
tab_id: getOrCreateTabId(),
session_id: sid,
completion_code: code || '',
last_touched: Date.now(),
});
console.log('[recovery] localStorage write — session_id =', sid);
}
function touchSession() {
const s = readState();
if (!s || !s.session_id) return;
s.last_touched = Date.now();
writeState(s);
}
function buildModal({title, body, freshLabel, continueLabel,
onFresh, onContinue}) {
let existing = document.getElementById('recovery-overlay');
if (existing) existing.remove();
const overlay = document.createElement('div');
overlay.id = 'recovery-overlay';
overlay.innerHTML =
'<div class="recovery-modal">' +
'<div class="recovery-title">' + title + '</div>' +
'<div class="recovery-body">' + body + '</div>' +
'<div class="recovery-actions">' +
'<button type="button" class="recovery-fresh">' + freshLabel + '</button>' +
'<button type="button" class="recovery-continue">' + continueLabel + '</button>' +
'</div>' +
'<div class="recovery-loading">Restoring your session, please wait…</div>' +
'<div class="recovery-error">Could not restore the session. Please start a new one.<br><span class="recovery-error-detail" style="display:block;margin-top:8px;font-size:0.85em;color:#6b7280;"></span></div>' +
'</div>';
document.body.appendChild(overlay);
overlay.querySelector('.recovery-fresh').addEventListener('click', () => {
overlay.remove();
onFresh();
});
overlay.querySelector('.recovery-continue').addEventListener('click', () => {
overlay.classList.add('loading');
overlay.classList.remove('error');
onContinue();
});
return overlay;
}
function triggerServerRecover(sid, attempt) {
attempt = attempt || 0;
const inputWrap = document.querySelector('#recover-session-id-input');
const btnWrap = document.querySelector('#recover-btn');
if (!inputWrap || !btnWrap) {
if (attempt < 30) {
if (attempt === 0) {
console.log('[recovery] hidden recover elements not yet in DOM, retrying');
}
setTimeout(() => triggerServerRecover(sid, attempt + 1), 200);
return;
}
console.error('[recovery] hidden recover elements not found after 6s');
const overlay = document.getElementById('recovery-overlay');
if (overlay) {
overlay.classList.remove('loading');
overlay.classList.add('error');
const detail = overlay.querySelector('.recovery-error-detail');
if (detail) detail.textContent = '(reason: recover button missing from DOM)';
}
return;
}
const ta = inputWrap.querySelector('textarea') || inputWrap.querySelector('input');
if (!ta) {
console.error('[recovery] no input element inside #recover-session-id-input');
return;
}
const setter = Object.getOwnPropertyDescriptor(
window.HTMLTextAreaElement.prototype, 'value'
)?.set || Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype, 'value'
)?.set;
if (setter) setter.call(ta, sid); else ta.value = sid;
ta.dispatchEvent(new Event('input', { bubbles: true }));
ta.dispatchEvent(new Event('change', { bubbles: true }));
setTimeout(() => {
const btn = btnWrap.querySelector('button') || btnWrap;
btn.click();
console.log('[recovery] recover-btn clicked, sid =', sid);
}, 100);
}
function startTouchObserver() {
document.addEventListener('click', function(e) {
const sendBtn = e.target.closest('#send-btn button, #send-btn');
if (sendBtn) touchSession();
}, true);
document.addEventListener('keydown', function(e) {
if (e.key !== 'Enter' || e.shiftKey) return;
const input = e.target.closest('#chat-input textarea, #chat-input input');
if (input) touchSession();
}, true);
}
function startRecoveryCheck() {
if (!document.body) { setTimeout(startRecoveryCheck, 100); return; }
startTouchObserver();
const state = readState();
if (!state || !state.session_id) {
console.log('[recovery] no saved session, normal flow');
return;
}
const myTabId = getOrCreateTabId();
const continueHandler = () => {
state.tab_id = myTabId;
state.last_touched = Date.now();
writeState(state);
triggerServerRecover(state.session_id);
};
const freshHandler = () => {
clearState();
console.log('[recovery] user chose Start fresh — localStorage cleared');
location.reload();
};
if (state.tab_id && state.tab_id !== myTabId) {
buildModal({
title: '<b>Session open in another tab</b>',
body: 'A previous session appears to be open in another browser tab. ' +
'You can take it over here (the other tab will go out of sync), ' +
'or start a new session.',
freshLabel: 'Start a new session',
continueLabel: 'Take over here',
onFresh: freshHandler,
onContinue: continueHandler,
});
} else {
buildModal({
title: '<b>Continue your previous session?</b>',
body: 'Your previous session was not completed. ' +
'Would you like to continue where you left off, or start a new session?',
freshLabel: 'Start a new session',
continueLabel: 'Continue',
onFresh: freshHandler,
onContinue: continueHandler,
});
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startRecoveryCheck);
} else {
startRecoveryCheck();
}
return {
saveSession: saveSession,
clearState: clearState,
dismissModalIfLoading: function() {
const overlay = document.getElementById('recovery-overlay');
if (overlay && overlay.classList.contains('loading')) {
overlay.remove();
}
},
markModalError: function(reason) {
const overlay = document.getElementById('recovery-overlay');
if (overlay) {
overlay.classList.remove('loading');
overlay.classList.add('error');
const detail = overlay.querySelector('.recovery-error-detail');
if (detail) {
detail.textContent = reason
? '(reason: ' + reason + ')'
: '';
}
}
},
};
})();
</script>
"""
from core.content_sync import sync_chapters_from_ssot
from core.perfect_answer import generate_session_artifacts
from core import plan_parsing
from core import orchestrator
from core import main_agent
from core.manager_agent import ManagerVerdict
from core.main_agent import BotResponse
# Mirror generator inputs (case_analysis.md, ethics-frameworks.md) from
# shared_content/ into local data/. Local-only, no-op on HF Space.
sync_chapters_from_ssot()
# ============================================================
# Session cache keys (held inside a Gradio State dict)
# ============================================================
PERFECT_ANSWER_KEY = "__perfect_answer__" # str, the essay (kept for log)
PLAN_TEXT_KEY = "__plan_text__" # str, raw markdown of plan
PLAN_SUBPROBES_KEY = "__plan_subprobes__" # list[dict] from plan_parsing
MANAGER_HISTORY_KEY = "__manager_history__" # list[dict], cumulative verdicts
SESSION_CLIENT_KEY = "__session_client__" # OpenAI client assigned to this
# session by get_next_client() —
# rotates across OPENAI_KEY_01..10
# so concurrent sessions hit
# different OpenAI keys / quotas.
INITIAL_ARG_KEY = "__initial_argument__" # str, the full essay the
# participant submitted at
# Phase 1 — passed to manager
# on every turn so its overall
# stance never falls out of
# the recent-turns window.
# ============================================================
# Content
# ============================================================
CONTENT_DIR = BASE_DIR / "content"
def _load(name):
p = CONTENT_DIR / name
if p.exists():
return p.read_text(encoding="utf-8")
return f"*[Missing: content/{name}]*"
CASE_TEXT = _load("case_1.md")
# Display version of the case strips the leading H1 ("# Case: ...") so the
# title is not shown in the chatbot panel. The LLM still receives the full
# CASE_TEXT (including the title) via stream_turn.
def _strip_leading_h1(md: str) -> str:
lines = md.lstrip("\n").split("\n")
if lines and lines[0].lstrip().startswith("# "):
return "\n".join(lines[1:]).lstrip("\n")
return md
CASE_TEXT_DISPLAY = _strip_leading_h1(CASE_TEXT)
# ============================================================
# Per-turn pipeline (manager then main bot, synchronous)
# ============================================================
THINKING_TEXT = "*Thinking…*"
# ============================================================
# Multi-message output for `opening` and `transition-due`.
#
# The main-agent prompt instructs the LLM to emit `<<<MSG-BREAK>>>` on its
# own line to split its reply into multiple chat messages, ONLY for these
# two turn types. The host (stream_turn below) splits on this marker after
# the LLM finishes streaming, and replaces the single assembled bot message
# in chatbot history with multiple discrete assistant messages.
#
# For `opening` specifically, the LLM is told NOT to write the greeting /
# "I'm here to help you think through your argument" framing — that text
# is HARDCODED below (OPENING_M1_HARDCODED) and prepended by the host as
# the first message. This guarantees the framing wording is exact and
# never drifts under prompt jitter.
#
# Wording in OPENING_M1_HARDCODED is locked by collaborator request — do
# NOT edit without explicit sign-off.
# ============================================================
MSG_BREAK_MARKER = "<<<MSG-BREAK>>>"
OPENING_M1_HARDCODED = (
"Thanks for sharing your argument. I've read it carefully.\n\n"
"I'm here to **help you think through your argument, rather than think "
"for you**. So, in the following discussion, **I'll ask you questions** to "
"**help you examine your reasoning** and decide how you want to revise "
"your argument."
)
def stream_turn(user_msg, history, case_text, cache, result):
"""Run one chat turn end-to-end. Synchronous: manager (blocking ~2-5s),
then main bot stream (yielding deltas).
`history` already contains the participant's message as its last entry.
`result` is a caller-supplied dict that this function populates with:
- "verdict": ManagerVerdict or None
- "plan_control_text": str
- "bot_response": BotResponse or None
- "manager_latency_ms": int
Yields successive history snapshots for the Gradio chatbot.
The caller iterates with a for loop and reads `result` after the loop
ends; logging happens in the caller (NOT in a post-yield block, which
is unreliable under Gradio's streaming framework).
"""
plan_subprobes = cache.get(PLAN_SUBPROBES_KEY, [])
plan_text = cache.get(PLAN_TEXT_KEY, "")
manager_history = cache.get(MANAGER_HISTORY_KEY, [])
initial_argument = cache.get(INITIAL_ARG_KEY, "")
# Bot-slot placeholder while the manager call is running.
history = history + [{"role": "assistant", "content": THINKING_TEXT}]
yield history
# Per-session OpenAI client (assigned at session start via get_next_client();
# may be None on legacy/recovered sessions, in which case downstream falls
# back to the module-level default client).
session_client = cache.get(SESSION_CLIENT_KEY)
# 1. Manager call (blocking).
verdict = None
manager_latency_ms = 0
if plan_subprobes:
t0 = time.perf_counter()
try:
verdict = orchestrator.run_manager(
discussion_plan_subprobes=plan_subprobes,
manager_history=manager_history,
history=history[:-1],
current_msg=user_msg,
initial_argument=initial_argument,
client=session_client,
)
except Exception as e:
print(f"[manager] failed: {e!r}", flush=True)
manager_latency_ms = int((time.perf_counter() - t0) * 1000)
result["verdict"] = verdict
result["manager_latency_ms"] = manager_latency_ms
# 2. PLAN CONTROL block.
if verdict is not None and plan_subprobes:
plan_control_text = main_agent.build_plan_control(verdict, plan_subprobes)
else:
plan_control_text = (
"=== PLAN CONTROL (host-managed) ===\n"
"(no discussion plan available for this session; respond using "
"your own judgement on the participant's argument)\n"
"=== END PLAN CONTROL ==="
)
result["plan_control_text"] = plan_control_text
# 3. Stream main bot.
messages = main_agent.build_messages(
history=history[:-1],
case_text=case_text,
discussion_plan_text=plan_text or "(no plan)",
plan_control_text=plan_control_text,
)
accumulated = ""
bot_response = None
streaming_started = False
try:
for ev in main_agent.stream(messages, client=session_client):
if ev[0] == "delta":
if not streaming_started:
streaming_started = True
accumulated = ev[1]
else:
accumulated += ev[1]
# While streaming, hide the raw MSG-BREAK marker so the
# participant doesn't see "<<<MSG-BREAK>>>" appearing as
# literal text. Replace with paragraph break for display
# only — the actual split into discrete bubbles happens
# at "done" below.
display = accumulated.replace(MSG_BREAK_MARKER, "\n\n")
history[-1] = {"role": "assistant", "content": display}
yield history
elif ev[0] == "done":
bot_response = ev[1]
history = _finalize_multi_message_history(
history,
bot_response.visible,
turn_type=getattr(verdict, "turn_type", None) if verdict else None,
)
yield history
break
except Exception as e:
history[-1] = {"role": "assistant", "content": f"*Error during bot reply: {e!r}*"}
yield history
print(f"[main_bot] failed: {e!r}", flush=True)
result["bot_response"] = bot_response
def _finalize_multi_message_history(history, raw_visible, turn_type):
"""Replace the single streaming bot message at history[-1] with one or
more discrete assistant messages.
Logic:
- Split raw_visible on `<<<MSG-BREAK>>>` into segments
- If turn_type == "opening", prepend OPENING_M1_HARDCODED as the
first segment (fixed wording, host-injected, not LLM-authored)
- Replace history[-1] (the assembled message) with one assistant
entry per segment
Logging note: the raw LLM output (with MSG_BREAK_MARKER intact) is
still preserved on bot_response.visible by the caller, so the session
log records the model's actual output — only the chat UI gets split.
"""
segments = [
s.strip()
for s in raw_visible.split(MSG_BREAK_MARKER)
if s.strip()
]
if turn_type == "opening":
segments = [OPENING_M1_HARDCODED] + segments
# If only one segment remains (no MSG-BREAK + not opening), keep the
# existing single-message behaviour to avoid disturbing other turn
# types like engaging-default / needs-clarification / plan-complete.
if len(segments) <= 1:
history[-1] = {"role": "assistant", "content": segments[0] if segments else raw_visible}
return history
# Multi-segment: drop the streaming placeholder, append discrete
# assistant messages.
history = history[:-1]
for seg in segments:
history.append({"role": "assistant", "content": seg})
return history
def _log_turn(user_msg, cache, logger, result, total_t0):
"""Apply per-turn state changes to cache + logger. Called by the
handler AFTER stream_turn's for loop finishes. This function is NOT a
generator: it runs to completion synchronously."""
verdict = result.get("verdict")
plan_control_text = result.get("plan_control_text", "")
bot_response = result.get("bot_response")
manager_latency_ms = result.get("manager_latency_ms", 0)
if verdict is not None:
mh = cache.get(MANAGER_HISTORY_KEY)
if mh is None:
mh = []
cache[MANAGER_HISTORY_KEY] = mh
mh.append(verdict.to_dict())
logger.add_manager_verdict(verdict.to_dict())
logger.add_turn(
user_message=user_msg,
manager_verdict=verdict.to_dict() if verdict else None,
plan_control=plan_control_text,
assistant_response=bot_response.visible if bot_response else "",
scratch=bot_response.scratch if bot_response else {},
latency_s={
"manager_ms": manager_latency_ms,
"ttft_ms": bot_response.ttft_ms if bot_response else None,
"main_ms": bot_response.latency_ms if bot_response else None,
"total_ms": int((time.perf_counter() - total_t0) * 1000),
},
)
print(f"[logger] add_turn done; turn count now = {len(logger.turns)}", flush=True)
# ============================================================
# UI constants
# ============================================================
INITIAL_CHATBOT_VALUE = [{"role": "assistant", "content": CASE_TEXT_DISPLAY}]
SUBMIT_INITIAL_LABEL = "Submit initial argument"
SUBMIT_INITIAL_CONFIRM_LABEL = "✓ Click again to confirm submission"
END_SESSION_LABEL = "End session & finalize · no return"
END_SESSION_CONFIRM_LABEL = "✓ Click again to confirm end session"
ARM_TTL = 10.0 # seconds before armed state auto-reverts
# End Session gate: participant cannot end the session until EITHER
# (a) the discussion has advanced past (n_active_probes - 2) probes
# (where n_active = non-well-addressed sub-probes in this session's
# plan, typically 5-6), OR
# (b) plan-complete has fired (manager closed the whole plan), OR
# (c) at least END_GATE_TIMEOUT_SECONDS have elapsed since the
# participant submitted the initial argument (safety escape hatch).
# Both Path-A (gap satisfied) and Path-B (stuck) transitions count
# toward (a) — manager already made the judgement, UI follows.
END_GATE_TIMEOUT_SECONDS = 15 * 60 # 15 minutes
def _count_non_well_addressed_probes(plan_obj):
"""plan_obj is the dict stored in logger.discussion_plan (has 'text' key,
plan body in the 7-component scaffold). Counts sub-probes whose `gap:`
line does NOT begin with 'well-addressed'. Returns 0 if no plan."""
if not plan_obj:
return 0
text = plan_obj.get("text", "") if isinstance(plan_obj, dict) else ""
if not text:
return 0
n = 0
for line in text.split("\n"):
s = line.strip()
if s.startswith("gap:"):
body = s[4:].strip().lower()
if not body.startswith("well-addressed"):
n += 1
return n
def _can_end_session(logger_obj):
"""Returns True if the End Session button should proceed; False to gate.
See END_GATE_TIMEOUT_SECONDS comment for the three release conditions."""
if logger_obj is None:
return True # no logger state, fall through (don't block)
mh = getattr(logger_obj, "manager_history", None) or []
# (b) plan-complete ever fired → unconditionally allow
for v in mh:
if v.get("turn_type") == "plan-complete":
return True
# (c) 20-minute timeout since argument submission → allow
arg_at = getattr(logger_obj, "argument_submitted_at", None)
if arg_at and (time.time() - arg_at) >= END_GATE_TIMEOUT_SECONDS:
return True
# (a) probe threshold
n_active = _count_non_well_addressed_probes(
getattr(logger_obj, "discussion_plan", None)
)
if n_active <= 2:
return True # too few non-well-addressed probes to gate meaningfully
n_transitions = sum(1 for v in mh if v.get("advanced_this_turn"))
return n_transitions >= (n_active - 2)
def _gate_toast_trigger_html():
"""Returns a tiny hidden element whose id contains a fresh nonce.
The JS watcher in INPUT_LOCKDOWN_HEAD spots the new id and fires
the toast. Nonce-per-click is what makes a repeated click re-toast."""
nonce = str(int(time.time() * 1000))
return f'<div id="session-gate-trigger-{nonce}" style="display:none"></div>'
# Revise-check gate: word-level similarity ratio between initial argument
# and current argument. > REVISE_SIMILARITY_THRESHOLD means the participant
# has not revised enough — block End Session with a modal.
REVISE_SIMILARITY_THRESHOLD = 0.9
import difflib as _difflib
def _arg_word_similarity(initial_text, current_text):
"""Word-level SequenceMatcher ratio. 1.0 = identical, 0.0 = no overlap.
Lowercased, whitespace-tokenised; punctuation kept on tokens."""
a = (initial_text or "").lower().split()
b = (current_text or "").lower().split()
if not a or not b:
return 0.0
return _difflib.SequenceMatcher(None, a, b).ratio()
def _revise_gate_trigger_html():
"""Hidden element whose id triggers the revise-gate modal in JS."""
nonce = str(int(time.time() * 1000))
return f'<div id="revise-gate-trigger-{nonce}" style="display:none"></div>'
# ============================================================
# End-of-session "completion code" modal — shown when the participant
# confirms End Session. The code (5-char alphanumeric, generated in
# SessionLogger.start_session) is what participants paste into the
# Qualtrics survey page so the researcher can join the dialogue log to
# the rest of the survey response. Same modal also appears on upload
# failure (with a warning tone) so the participant can still complete
# Qualtrics and so the researcher gets the code to recover manually.
# ============================================================
SAVING_PANEL_HTML = (
'<div class="saving-panel">'
'<h3>⏳ Submitting your session to our records.</h3>'
'<p>This can take up to a minute under heavy server load. '
"Please don't close the page.</p>"
'</div>'
)
def _completion_modal_html(flush_result):
"""Build the full-screen completion-code modal HTML.
The participant-facing display string is `BotThanksU` + the 5-digit
code (e.g. `BotThanksU23548`); the log filename and the
`completion_code` field stored in the log envelope contain ONLY the
5 digits. The decorative prefix is added here at display time so the
Qualtrics paste-back is recognisable as having come from the bot."""
status = (flush_result or {}).get("status", "no_logger")
code = (flush_result or {}).get("completion_code") or ""
display_code = f"BotThanksU{code}" if code else "UNKNOWN"
if status in ("uploaded_primary", "uploaded_recovery"):
title = "✅ Session complete"
message = (
"Your session has been saved. Copy the completion code below "
"and paste it into the Qualtrics survey page to continue."
)
warning_cls = ""
elif status == "all_failed":
title = "⚠ Session ended"
message = (
"Your session is finished, but the upload could not be confirmed. "
"Copy the completion code below — paste it into the Qualtrics "
"page <em>and</em> share it with the researcher so they can "
"recover your data."
)
warning_cls = " completion-warning"
else: # no_logger / unexpected
title = "Session ended"
message = (
"Copy the code below and paste it into the Qualtrics survey "
"page to continue."
)
warning_cls = ""
js_close = ("document.getElementById('completion-overlay-root')"
".style.display='none';")
# Inline copy-to-clipboard: replace the button label with 'Copied ✓'
# for 2 seconds, then restore.
js_copy = (
f"var b=this;navigator.clipboard.writeText('{display_code}').then("
"function(){b.textContent='Copied \\u2713';"
"setTimeout(function(){b.textContent='Copy';},2000);});"
)
return (
f'<div class="completion-overlay{warning_cls}" '
f'id="completion-overlay-root">'
f'<div class="completion-modal-box">'
f'<button class="completion-close" type="button" '
f'title="Close" onclick="{js_close}">×</button>'
f'<div class="completion-title">{title}</div>'
f'<div class="completion-instructions">{message}</div>'
f'<div class="completion-code-row">'
f'<div class="completion-code" id="completion-code-value">{display_code}</div>'
f'<button class="completion-copy" type="button" '
f'onclick="{js_copy}">Copy</button>'
f'</div>'
f'</div>'
f'</div>'
)
COMPLETION_MODAL_CSS = """
/* End-of-session completion-code modal overlay (full-screen). */
.completion-overlay {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0, 0, 0, 0.55);
z-index: 99999;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.completion-modal-box {
position: relative;
background: white;
border-radius: 12px;
padding: 36px 40px 28px;
max-width: 560px;
width: 100%;
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.35);
font-size: 1.05em;
line-height: 1.55;
}
.completion-overlay.completion-warning .completion-modal-box {
border-top: 4px solid #f59e0b;
}
.completion-close {
position: absolute;
top: 8px; right: 12px;
background: transparent;
border: none;
font-size: 1.5em;
color: #6b7280;
cursor: pointer;
line-height: 1;
padding: 4px 10px;
border-radius: 4px;
}
.completion-close:hover { color: #111827; background: #f3f4f6; }
.completion-title {
font-size: 1.4em;
font-weight: 600;
margin-bottom: 14px;
color: #16a34a;
}
.completion-overlay.completion-warning .completion-title { color: #b45309; }
.completion-instructions {
margin-bottom: 22px;
color: #1f2937;
}
.completion-code-row {
display: flex;
align-items: stretch;
gap: 10px;
margin-bottom: 14px;
}
.completion-code {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 1.7em;
font-weight: 700;
letter-spacing: 0.18em;
padding: 14px 18px;
background: #f3f4f6;
border-radius: 8px;
flex: 1;
user-select: all;
text-align: center;
color: #111827;
}
.completion-copy {
padding: 0 24px;
background: #2563eb;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 1em;
font-weight: 500;
white-space: nowrap;
}
.completion-copy:hover { background: #1d4ed8; }
.completion-note {
font-size: 0.9em;
color: #6b7280;
}
/* Inline saving panel (shown while flush is running, before the modal). */
.saving-panel {
padding: 16px 22px;
background: #fefce8;
border: 1px solid #fde68a;
border-radius: 8px;
margin-top: 12px;
}
.saving-panel h3 { margin: 0 0 6px 0; font-size: 1.05em; font-weight: 600; }
.saving-panel p { margin: 0; color: #57534e; }
"""
CUSTOM_CSS = """
/* Revise-check modal — shown when participant tries to end the session
with an argument too similar to their initial submission. Styled to
match the tutorial overlay. */
#revise-gate-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.78);
z-index: 200001;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
#revise-gate-overlay .revise-gate-modal {
background: #ffffff;
border-radius: 14px;
padding: 36px 44px;
max-width: 620px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
display: flex;
flex-direction: column;
gap: 18px;
align-items: center;
text-align: center;
/* Match the rest of the app's font (Gradio default sans-serif).
The modal is appended to document.body so it escapes Gradio's
font scope and would otherwise fall back to the browser's serif
default — pin a sans-serif stack here and let children inherit. */
font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji", sans-serif;
}
#revise-gate-overlay .revise-gate-title,
#revise-gate-overlay .revise-gate-body,
#revise-gate-overlay .revise-gate-btn {
font-family: inherit;
}
#revise-gate-overlay .revise-gate-title {
font-size: 1.35em;
color: #1f2937;
line-height: 1.35;
}
#revise-gate-overlay .revise-gate-body {
font-size: 1em;
color: #4b5563;
line-height: 1.5;
}
#revise-gate-overlay .revise-gate-btn {
background: #2563eb;
color: #fff;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-size: 1.05em;
cursor: pointer;
transition: background 0.15s ease;
}
#revise-gate-overlay .revise-gate-btn:hover { background: #1d4ed8; }
/* Hide Gradio's built-in copy button on chatbot messages. Aha/ugh buttons
live in custom HTML siblings so this selector only catches the
framework's copy icon (the small clipboard left of aha/ugh). */
#chatbot-main button[aria-label*="opy" i],
#chatbot-main button[title*="opy" i],
#chatbot-main .copy-button,
#chatbot-main .message-buttons-copy,
#chatbot-main [data-testid*="copy" i] {
display: none !important;
}
/* Hide Gradio Chatbot top-bar chrome: the "Chatbot" label badge in the
upper-left and the share / clear (trash) icons in the upper-right.
show_label=False on gr.Chatbot covers the label in theory, but Gradio
6.11 still renders a label badge plus share + clear buttons (and the
chatbot class has no show_share_button kwarg), so we suppress them
here. Aha/ugh and the rest of the message actions live inside
.message-buttons-* so they stay visible. */
#chatbot-main label,
#chatbot-main > .label-wrap,
#chatbot-main > div > .label-wrap,
#chatbot-main button[aria-label*="hare" i],
#chatbot-main button[aria-label*="lear" i],
#chatbot-main button[aria-label*="elete" i],
#chatbot-main button[aria-label*="rash" i],
#chatbot-main button[title*="hare" i],
#chatbot-main button[title*="lear" i],
#chatbot-main button[title*="elete" i],
#chatbot-main button[title*="rash" i] {
display: none !important;
}
/* NOTE: do NOT blanket-hide .icon-button-wrapper — the aha!/ugh.
buttons (repurposed Like/Dislike) live in the same wrapper class
as the share/clear/delete buttons. The aria-label / title matchers
above already target exactly the toolbar buttons we want gone. */
/* Extend the Gradio outer container to the full browser width (height is
handled by vh-based heights on the chatbot + textbox so the layout stays
responsive to browser zoom). */
.gradio-container, .main, .wrap {
max-width: 100% !important;
}
.gradio-container {
padding-left: 12px !important;
padding-right: 12px !important;
}
/* Bottom-row buttons stay one-row tall (msg input is allowed to grow — see next rule) */
#send-btn button,
#bottom-action-col button {
min-height: 42px !important;
max-height: 42px !important;
}
/* Chat input auto-grows from 1 line up to ~6 lines, then scrolls internally.
Pairs with lines=1, max_lines=6 on the gr.Textbox. */
#chat-input textarea {
min-height: 42px !important;
max-height: 160px !important;
}
/* Bottom-row symmetry — chat-row aligns to flex-end so Send button stays
with the bottom of the (possibly grown) input, not floating mid-row. */
#chat-row { align-items: flex-end !important; justify-content: center !important; gap: 8px !important; }
#bottom-action-col { align-items: center !important; justify-content: center !important; gap: 8px !important; }
#send-btn { align-self: flex-end !important; flex-grow: 0 !important; }
#chatbot-main .message,
#chatbot-main .message p,
#chatbot-main .message li,
#chatbot-main .prose p,
#chatbot-main .prose li,
#chatbot-main .markdown p,
#chatbot-main .markdown li {
font-size: 1.08em !important;
line-height: 1.55 !important;
}
/* Right column: keep it inside the row's equal_height stretch (so it
matches the left column = chatbot 65vh + feedback panel). Only tighten
the inter-row gap; let Gradio handle column display. */
#right-col {
gap: 4px !important;
}
/* Argument textbox: two nested rectangles. The OUTER rectangle is the
Gradio block (#right-essay) — explicit fixed height (65vh) so it
doesn't collapse. The INNER rectangle is the <textarea>, absolute-
positioned with 6px inset on all four sides so the gap between outer
and inner border is exactly equal everywhere. position:relative on the
block establishes the positioning context for the textarea's absolute. */
#right-essay {
height: 55vh !important;
position: relative !important;
padding: 0 !important;
margin: 0 !important;
border: 1px solid var(--border-color-primary, #d1d5db) !important;
border-radius: 8px !important;
background: var(--background-fill-primary, #ffffff) !important;
box-sizing: border-box !important;
overflow: hidden !important;
}
/* Ensure no intermediate Gradio wrapper establishes its own positioning
context — we want the textarea positioned relative to #right-essay. */
#right-essay > div,
#right-essay .container,
#right-essay .input-container {
position: static !important;
transform: none !important;
padding: 0 !important;
margin: 0 !important;
border: none !important;
background: transparent !important;
height: 100% !important;
width: 100% !important;
}
#right-essay textarea {
position: absolute !important;
top: 10px !important;
right: 10px !important;
bottom: 10px !important;
left: 10px !important;
width: auto !important;
height: auto !important;
max-height: none !important;
min-height: 0 !important;
margin: 0 !important;
padding: 12px 14px !important;
border: 1px solid var(--border-color-primary, #e5e7eb) !important;
border-radius: 6px !important;
background: var(--background-fill-secondary, #f9fafb) !important;
font-size: 1.25em !important;
line-height: 1.6 !important;
resize: none !important;
box-sizing: border-box !important;
}
#feedback-hint {
margin: 8px 4px 4px 4px !important;
padding: 0 !important;
}
#guide-col {
min-width: 0;
}
#feedback-hint {
margin: 0 !important;
padding: 0 !important;
}
.discussion-intro {
background: #fef9c3;
border-left: 4px solid #d97706;
border-radius: 6px;
padding: 10px 14px;
font-size: 1.08em;
line-height: 1.55;
color: #713f12;
}
.discussion-intro-title {
font-weight: 700;
font-size: 1.05em;
margin-bottom: 6px;
color: #422006;
}
.discussion-intro-line {
margin: 5px 0;
}
.discussion-intro-bullets {
margin: 4px 0 0 0;
padding-left: 18px;
}
.discussion-intro-bullets li {
margin: 2px 0;
}
.discussion-intro-line svg,
.discussion-intro-bullets svg {
vertical-align: -0.3em;
margin: 0 2px;
}
/* Custom label row: gr.HTML wraps its content in a Gradio block that
has its own padding + min-height of ~80px. We force the block + every
level of inner wrapper to be flush so the row is exactly one line tall,
and clamp with max-height as a hard ceiling. */
#arg-label-row {
margin: 0 4px 0 4px !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
min-height: 0 !important;
max-height: 40px !important;
height: auto !important;
overflow: visible !important;
}
#arg-label-row > *,
#arg-label-row > * > *,
#arg-label-row > * > * > * {
margin: 0 !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
min-height: 0 !important;
height: auto !important;
}
.arg-label-row {
display: flex !important;
justify-content: space-between !important;
align-items: baseline !important;
width: 100%;
line-height: 1.0 !important;
white-space: nowrap;
}
#arg-label-row .arg-label-text {
font-weight: 700 !important;
font-size: 1.7em !important;
color: var(--body-text-color, #111827) !important;
}
#arg-label-row #wc-display {
font-weight: 600 !important;
font-size: 1.5em !important;
color: #b91c1c !important;
transition: color 0.15s ease;
white-space: nowrap;
}
#arg-label-row #wc-display.sufficient {
color: #15803d !important;
}
/* Argument-side notice (the "Do not use external AI tools" reminder
placed between the Your argument label row and the textbox). Same
wrapper-flattening pattern as #arg-label-row so the gr.HTML block
doesn't add Gradio padding. */
#arg-notice {
margin: 6px 4px 8px 4px !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
min-height: 0 !important;
height: auto !important;
overflow: visible !important;
flex: none !important;
}
#arg-notice > *,
#arg-notice > * > *,
#arg-notice > * > * > * {
margin: 0 !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
min-height: 0 !important;
height: auto !important;
overflow: visible !important;
}
.arg-notice {
background: #fef9c3 !important;
border-left: 4px solid #d97706 !important;
border-radius: 6px !important;
padding: 8px 12px !important;
font-size: 1.08em !important;
line-height: 1.4 !important;
color: #422006 !important;
}
/* Old .discussion-intro-title/body/feedback removed — replaced by the
compact 2-line .discussion-intro-line layout above. */
/* Force the like/dislike buttons (repurposed as aha!/ugh.) to always be visible */
button[aria-label="Like" i],
button[aria-label="Dislike" i],
button[aria-label="like" i],
button[aria-label="dislike" i] {
opacity: 1 !important;
visibility: visible !important;
width: auto !important;
min-width: 28px !important;
}
button[data-emoji-active="1"] {
background-color: rgba(99, 102, 241, 0.18) !important;
border: 1px solid rgba(99, 102, 241, 0.7) !important;
border-radius: 6px !important;
box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.15) !important;
}
"""
# EMOJI_SWAP_HEAD: replace Gradio's Like/Dislike thumbs with the custom
# aha!/ugh. SVG glyphs. Same script as v3.
EMOJI_SWAP_HEAD = """
<script>
(function() {
const findGroup = (btn) => btn.parentElement || btn;
const onEmojiClick = (e) => {
const btn = e.currentTarget;
const wasActive = btn.dataset.emojiActive === '1';
findGroup(btn).querySelectorAll('button[data-emoji-swapped="1"]').forEach(b => {
b.removeAttribute('data-emoji-active');
});
if (!wasActive) btn.dataset.emojiActive = '1';
};
// detectKind: identify whether a button is the Gradio chatbot's
// "like" or "dislike" button, robust across browser locales (the
// target audience includes US users with English / Spanish (incl.
// Mexican + Latin American) / French / Chinese (simplified +
// traditional) / Hindi / Portuguese / German / etc. browsers).
//
// Layered detection in priority order:
// 1. SVG class hint (e.g. "lucide-thumbs-up" / "lucide-thumbs-down")
// 2. SVG path data (Lucide thumbs-up starts with "M7 10",
// thumbs-down starts with "M17 14")
// 3. aria-label substring match across locales
// 4. title attribute substring match across locales
// Returns 'like' | 'dislike' | null.
const DISLIKE_TOKENS = [
// English (and variants)
'dislike', 'thumbs down', 'thumb down',
'unhelpful', 'not helpful', 'mark as dislike', 'rate down',
// German
'gefällt mir nicht', 'nicht gefällt', 'daumen runter', 'daumen nach unten',
// French
"je n'aime pas", "n'aime pas", 'pouce vers le bas', 'pouce en bas',
// Spanish (Spain, Mexico, Latin American)
'no me gusta', 'no gusta', 'pulgar abajo', 'pulgar hacia abajo',
// Portuguese (Brazilian + EU)
'não gostei', 'descurtir', 'não gosto', 'polegar para baixo',
// Italian
'non mi piace', 'pollice giù',
// Chinese simplified
'踩', '不喜欢', '不赞', '点踩',
// Chinese traditional
'不讚', '不喜歡', '倒讚',
// Hindi (devanagari + romanized)
'नापसंद', 'napasand', 'na pasand',
// Japanese / Korean / Russian (covered for completeness)
'よくない', '良くない', '싫어', 'не нравится',
];
const LIKE_TOKENS = [
// English (and variants)
'like', 'thumbs up', 'thumb up',
'helpful', 'mark as like', 'rate up',
// German
'gefällt mir', 'daumen hoch', 'daumen nach oben',
// French
"j'aime", 'aime', 'pouce vers le haut', 'pouce en haut',
// Spanish (Spain, Mexico, Latin American)
'me gusta', 'pulgar arriba', 'pulgar hacia arriba',
// Portuguese (Brazilian + EU)
'gostei', 'curtir', 'gosto', 'polegar para cima',
// Italian
'mi piace', 'pollice su',
// Chinese simplified
'赞', '喜欢', '点赞',
// Chinese traditional
'讚', '喜歡',
// Hindi (devanagari + romanized)
'पसंद', 'pasand',
// Japanese / Korean / Russian (covered for completeness)
'いいね', '좋아', 'нравится',
];
const matchTokens = (s, tokens) => {
for (const k of tokens) {
if (s.indexOf(k) !== -1) return true;
}
return false;
};
const detectKind = (btn) => {
// Signal 1: SVG class hint
if (btn.querySelector('svg[class*="thumbs-up"]')) return 'like';
if (btn.querySelector('svg[class*="thumbs-down"]')) return 'dislike';
// Signal 2: SVG path d= (Lucide-style)
const paths = btn.querySelectorAll('svg path[d]');
for (const path of paths) {
const d = (path.getAttribute('d') || '').trim();
if (d.startsWith('M7 10')) return 'like';
if (d.startsWith('M17 14')) return 'dislike';
}
// Signal 3: aria-label substring (DISLIKE tokens FIRST, since many
// contain LIKE as substring, e.g. "dislike" or "no me gusta").
const al = (btn.getAttribute('aria-label') || '').trim().toLowerCase();
if (al) {
if (matchTokens(al, DISLIKE_TOKENS)) return 'dislike';
if (matchTokens(al, LIKE_TOKENS)) return 'like';
}
// Signal 4: title attribute substring (same logic).
const title = (btn.getAttribute('title') || '').trim().toLowerCase();
if (title) {
if (matchTokens(title, DISLIKE_TOKENS)) return 'dislike';
if (matchTokens(title, LIKE_TOKENS)) return 'like';
}
return null;
};
const apply = (btn) => {
if (btn.dataset.emojiSwapped === '1') return;
const kind = detectKind(btn);
if (kind === 'like') {
btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 116 54" aria-label="aha" style="height:20px;width:auto;display:block;overflow:visible"><g fill="#F59E0B" stroke="#D97706" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(-8 17 44) translate(8 50) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/><path transform="rotate(5 41 34) translate(29 43) scale(0.020020 -0.020020)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/><path transform="rotate(-6 62 45) translate(53 51) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/></g><g fill="#F59E0B" stroke="#D97706" stroke-width="1" stroke-linejoin="round"><rect x="82" y="17" width="4" height="23" rx="2" transform="rotate(13 84 28.5)"/><circle cx="82.5" cy="50" r="3.5"/><rect x="92" y="17" width="4" height="23" rx="2" transform="rotate(13 94 28.5)"/><circle cx="92.5" cy="50" r="3.5"/><rect x="102" y="17" width="4" height="23" rx="2" transform="rotate(13 104 28.5)"/><circle cx="102.5" cy="50" r="3.5"/></g></svg>`;
btn.title = 'Aha \\u2014 this clicked for me (click again to cancel)';
btn.dataset.emojiSwapped = '1';
btn.addEventListener('click', onEmojiClick);
} else if (kind === 'dislike') {
btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 115 64" aria-label="ugh." style="height:23px;width:auto;display:block;overflow:visible"><g fill="#8E7398" stroke="#5E4865" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(6 18 42) translate(8 46) scale(0.017090 -0.017090)" d="M978 578Q978 511 979.0 376.0Q980 241 980 174Q980 153 983.5 111.5Q987 70 987 49Q987 -7 946.5 -43.5Q906 -80 847 -80Q764 -80 726 -5Q598 -52 461 -52Q319 -52 222 8Q113 77 92 209Q53 459 53 656Q53 786 83 953Q103 1066 218 1066Q276 1066 317.0 1029.5Q358 993 358 937Q358 893 343.5 799.0Q329 705 329 656Q329 515 338.5 409.5Q348 304 367 235Q392 224 415.5 218.0Q439 212 461 212Q572 212 705 244Q705 321 704 419Q702 536 702 587Q702 792 721 941Q736 1060 857 1060Q916 1060 958.0 1023.0Q1000 986 997 930Q978 549 978 578Z"/><path transform="rotate(3 43 40) translate(31 49) scale(0.018066 -0.018066)" d="M1029 596Q987 361 979 100Q969 -223 871 -369Q740 -564 407 -564Q18 -564 18 -410Q18 -355 53.0 -321.0Q88 -287 145 -287Q190 -287 274.0 -304.0Q358 -321 423 -321Q572 -321 643 -230Q711 -141 723 53Q672 1 608.0 -25.0Q544 -51 468 -51Q269 -51 144.5 78.5Q20 208 20 410Q20 682 186 850Q358 1024 651 1024Q745 1024 813.0 1001.0Q881 978 923 931Q1050 916 1050 781Q1050 714 1029 596ZM641 796Q472 796 378 685Q294 584 294 423Q294 304 339.0 244.0Q384 184 474 184Q556 184 639 279Q717 369 728 457Q747 553 772 756Q738 776 705.0 786.0Q672 796 641 796Z"/><path transform="rotate(8 67 38) translate(55 45) scale(0.018066 -0.018066)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/></g><circle cx="84" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="96" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="108" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/></svg>`;
btn.title = 'Stress \\u2014 this made me uncomfortable (click again to cancel)';
btn.dataset.emojiSwapped = '1';
btn.addEventListener('click', onEmojiClick);
}
};
const reorder = () => {
// Locale-independent reorder: identify swapped buttons via the
// aria-label of our injected aha / ugh inner SVG (which we control),
// not via Gradio's button aria-label (which is localized).
document.querySelectorAll('button[data-emoji-swapped="1"] svg[aria-label="ugh."]').forEach(sv => {
const dis = sv.closest('button');
if (!dis) return;
const grp = dis.parentElement;
if (!grp) return;
const likeSvg = grp.querySelector('svg[aria-label="aha"]');
const like = likeSvg ? likeSvg.closest('button') : null;
if (like && (like.compareDocumentPosition(dis) & Node.DOCUMENT_POSITION_PRECEDING)) {
grp.insertBefore(like, dis);
}
});
};
const sweep = () => {
document.querySelectorAll('button[aria-label]').forEach(apply);
reorder();
};
setInterval(sweep, 400);
if (document.readyState !== 'loading') sweep();
else document.addEventListener('DOMContentLoaded', sweep);
})();
</script>
<script>
// Live word counter for the argument textbox + submit-button gate.
// Pure JS: listens to input event on the textarea, updates count display
// every keystroke with zero server round-trip. Threshold 100 words.
// When count < 100, the submit-initial-btn is disabled (visual + click).
(function() {
const THRESHOLD = 100;
function countWords(text) {
const t = (text || '').trim();
if (!t) return 0;
return t.split(/\\s+/).length;
}
function findSubmitBtn() {
// Gradio renders Button as <button> directly with the elem_id on it,
// or wraps in a div. Try both.
return document.querySelector('button#submit-initial-btn')
|| document.querySelector('#submit-initial-btn button')
|| document.querySelector('#submit-initial-btn');
}
function update() {
const ta = document.querySelector('#right-essay textarea');
const disp = document.querySelector('#wc-display');
if (!ta) return;
const n = countWords(ta.value);
const ok = n >= THRESHOLD;
const wordWord = n === 1 ? ' word' : ' words';
const text = ok
? n + wordWord + ' ✓'
: n + wordWord + ' (need at least ' + THRESHOLD + ')';
if (disp) {
disp.textContent = text;
if (ok) disp.classList.add('sufficient');
else disp.classList.remove('sufficient');
}
// Gate the submit button.
const btn = findSubmitBtn();
if (btn && btn.tagName === 'BUTTON') {
btn.disabled = !ok;
btn.style.opacity = ok ? '' : '0.5';
btn.style.cursor = ok ? '' : 'not-allowed';
btn.title = ok ? '' : 'Write at least ' + THRESHOLD + ' words to enable';
}
}
function attach() {
const ta = document.querySelector('#right-essay textarea');
if (ta && ta.dataset.wcAttached !== '1') {
ta.addEventListener('input', update);
ta.dataset.wcAttached = '1';
}
// Always re-run update; Gradio may re-render the button (e.g. on
// ARM/CONFIRM state changes) so the disabled state needs reapplying.
update();
}
setInterval(attach, 500);
if (document.readyState !== 'loading') attach();
else document.addEventListener('DOMContentLoaded', attach);
})();
</script>
"""
# ============================================================
# Participant-side lockdown:
# 1. Force light theme regardless of browser dark-mode preference or
# ?__theme query param being missing. Implemented by stripping the
# 'dark' class from <html>/<body> on load and re-stripping via a
# MutationObserver if Gradio / SSR re-adds it.
# 2. Block paste/copy/cut/drag on the participant's argument textbox
# (#right-essay) so they can't paste outside-AI text in nor copy the
# running argument out. Both Phase 1 (initial argument) and Phase 2
# (notepad) use the same textarea, so one guard covers both. JS
# re-attaches via MutationObserver in case Gradio re-mounts the
# textarea.
# ============================================================
# Injected at the very top of the head so the lockdown IIFEs below can
# check window.__LOCKDOWN.{argClipboard, chatCopy, endSessionGate} and
# bail out early when the corresponding feature is OFF in config.
_LOCKDOWN_FLAGS_JS = f"""<script>
window.__LOCKDOWN = {{
argClipboard: {str(LOCKDOWN_ARG_CLIPBOARD).lower()},
chatCopy: {str(LOCKDOWN_CHAT_COPY).lower()},
endSessionGate: {str(ENFORCE_END_SESSION_GATE).lower()},
reviseCheck: {str(LOCKDOWN_REVISE_CHECK).lower()}
}};
</script>"""
INPUT_LOCKDOWN_HEAD = """
<style>
.arg-lockdown-toast {
position: fixed;
top: 16px;
left: 50%;
transform: translateX(-50%) translateY(-12px);
background: rgba(31, 41, 55, 0.95);
color: #fff;
padding: 10px 18px;
border-radius: 8px;
font-size: 0.95em;
line-height: 1.4;
z-index: 100000;
opacity: 0;
pointer-events: none;
transition: opacity 0.18s ease, transform 0.18s ease;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.25);
max-width: 520px;
text-align: center;
}
.arg-lockdown-toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
</style>
<script>
// --- Force light theme ---
(function() {
function stripDark() {
document.documentElement.classList.remove('dark');
if (document.body) document.body.classList.remove('dark');
document.documentElement.setAttribute('data-theme', 'light');
}
stripDark();
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', stripDark);
}
// Observe and re-strip if Gradio / SSR re-adds .dark
const obs = new MutationObserver(stripDark);
obs.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme'] });
if (document.body) {
obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });
} else {
document.addEventListener('DOMContentLoaded', () => {
obs.observe(document.body, { attributes: true, attributeFilter: ['class'] });
});
}
})();
// --- Clipboard / drag lockdown on #right-essay textarea ---
(function() {
if (!window.__LOCKDOWN || !window.__LOCKDOWN.argClipboard) return;
const TOAST_ID = '__arg_lockdown_toast__';
const BLOCKED = ['paste', 'copy', 'cut', 'drop', 'dragstart'];
const MESSAGES = {
paste: 'Pasting is disabled for this study. Please type your text directly.',
copy: 'Copying out of this box is disabled for this study.',
cut: 'Cut is disabled for this study.',
drop: 'Dragging text into this box is disabled.',
dragstart: 'Dragging text out of this box is disabled.'
};
function ensureToast() {
let t = document.getElementById(TOAST_ID);
if (t) return t;
t = document.createElement('div');
t.id = TOAST_ID;
t.className = 'arg-lockdown-toast';
document.body.appendChild(t);
return t;
}
let hideTimer = null;
function showToast(msg) {
const t = ensureToast();
t.textContent = msg;
t.classList.add('show');
if (hideTimer) clearTimeout(hideTimer);
hideTimer = setTimeout(() => { t.classList.remove('show'); hideTimer = null; }, 2200);
}
const handler = (ev) => {
ev.preventDefault();
ev.stopPropagation();
const msg = MESSAGES[ev.type] || 'Action disabled for this study.';
showToast(msg);
return false;
};
const attached = new WeakSet();
function attachTo(el) {
if (!el || attached.has(el)) return;
BLOCKED.forEach(evt => el.addEventListener(evt, handler, { capture: true }));
attached.add(el);
console.log('[arg-lockdown] attached to', el.tagName, el);
}
function scan() {
const root = document.querySelector('#right-essay');
if (!root) return;
root.querySelectorAll('textarea, input[type="text"]').forEach(attachTo);
}
function setup(tries) {
tries = tries || 0;
if (tries > 60) return;
if (!document.querySelector('#right-essay')) {
setTimeout(() => setup(tries + 1), 200);
return;
}
scan();
const root = document.querySelector('#right-essay');
const obs = new MutationObserver(() => scan());
obs.observe(root, { childList: true, subtree: true });
console.log('[arg-lockdown] observer attached on #right-essay');
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => setup(0));
} else {
setup(0);
}
})();
// --- Revise-check gate modal watcher ---
// Server emits <div id="revise-gate-trigger-NONCE"> when the participant
// clicks End Session but their current argument is still > 90% similar
// to the initial submission. Watcher creates a full-screen modal styled
// like the tutorial overlay; the "Go back and revise" button dismisses it.
(function() {
if (!window.__LOCKDOWN || !window.__LOCKDOWN.reviseCheck) return;
const SEEN = new Set();
function buildOverlay() {
let existing = document.getElementById('revise-gate-overlay');
if (existing) existing.remove();
const overlay = document.createElement('div');
overlay.id = 'revise-gate-overlay';
overlay.innerHTML =
'<div class="revise-gate-modal">' +
'<div class="revise-gate-body">' +
'Please revise at least 10% of your argument before submitting your final version.' +
'</div>' +
'<button type="button" class="revise-gate-btn"><b>Go back to argument</b></button>' +
'</div>';
document.body.appendChild(overlay);
overlay.querySelector('.revise-gate-btn').addEventListener('click', function() {
overlay.remove();
});
}
function scan() {
document.querySelectorAll('[id^="revise-gate-trigger-"]').forEach(function(el) {
if (SEEN.has(el.id)) return;
SEEN.add(el.id);
buildOverlay();
});
}
function start() {
if (!document.body) { setTimeout(start, 100); return; }
scan();
const obs = new MutationObserver(scan);
obs.observe(document.body, { childList: true, subtree: true });
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();
// --- End-Session gate toast watcher ---
// When the server gates an End Session click (because the participant
// has not advanced through enough probes yet and the 20-minute timeout
// has not elapsed), it injects a hidden <div id="session-gate-trigger-NONCE">
// into the done_panel. This watcher spots the new id and shows a toast
// asking the participant to keep discussing. The nonce ensures repeated
// gated clicks each trigger the toast.
(function() {
if (!window.__LOCKDOWN || !window.__LOCKDOWN.endSessionGate) return;
const SEEN = new Set();
function showGateToast() {
let t = document.getElementById('__arg_lockdown_toast__');
if (!t) {
t = document.createElement('div');
t.id = '__arg_lockdown_toast__';
t.className = 'arg-lockdown-toast';
document.body.appendChild(t);
}
t.textContent = 'Your argument can still be refined. Please continue discussing with the AI before ending the session.';
t.classList.add('show');
setTimeout(function(){ t.classList.remove('show'); }, 3500);
}
function scan() {
document.querySelectorAll('[id^="session-gate-trigger-"]').forEach(function(el) {
if (SEEN.has(el.id)) return;
SEEN.add(el.id);
showGateToast();
});
}
function start() {
if (!document.body) { setTimeout(start, 100); return; }
scan();
const obs = new MutationObserver(scan);
obs.observe(document.body, { childList: true, subtree: true });
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();
// --- Copy lockdown on #chatbot-main (the chat history / bot replies) ---
// Participants can still select text (so they can re-read or visually trace),
// but copy / cut / drag-out events are blocked. Reuses the arg-lockdown toast.
(function() {
if (!window.__LOCKDOWN || !window.__LOCKDOWN.chatCopy) return;
const ROOT_SEL = '#chatbot-main';
const TOAST_ID = '__arg_lockdown_toast__';
const BLOCKED = ['copy', 'cut', 'dragstart'];
const MESSAGES = {
copy: 'Copying from the chat is disabled for this study.',
cut: 'Cut is disabled for this study.',
dragstart: 'Dragging text out of the chat is disabled.'
};
function ensureToast() {
let t = document.getElementById(TOAST_ID);
if (t) return t;
t = document.createElement('div');
t.id = TOAST_ID;
t.className = 'arg-lockdown-toast';
document.body.appendChild(t);
return t;
}
let hideTimer = null;
function showToast(msg) {
const t = ensureToast();
t.textContent = msg;
t.classList.add('show');
if (hideTimer) clearTimeout(hideTimer);
hideTimer = setTimeout(() => { t.classList.remove('show'); hideTimer = null; }, 2200);
}
const handler = (ev) => {
ev.preventDefault();
ev.stopPropagation();
const msg = MESSAGES[ev.type] || 'Action disabled for this study.';
showToast(msg);
return false;
};
function setup(tries) {
tries = tries || 0;
if (tries > 60) return;
const root = document.querySelector(ROOT_SEL);
if (!root) {
setTimeout(() => setup(tries + 1), 200);
return;
}
BLOCKED.forEach(evt => root.addEventListener(evt, handler, { capture: true }));
console.log('[chat-lockdown] attached on #chatbot-main', BLOCKED);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => setup(0));
} else {
setup(0);
}
})();
</script>
"""
# ============================================================
# Hide HuggingFace Spaces floating widget that appears on .hf.space
# direct URLs. The widget shows the repo name, a like button, and an
# X to dismiss. We want it to never appear for participants.
# CSS targets HF's common class patterns; JS sweeps top-level body
# children that match an HF Spaces signature and removes them.
# ============================================================
HIDE_HF_WIDGET_HEAD = """
<style>
/* CSS targeting common HF Spaces floating widget classes */
.space-header, .hf-spaces-header, .spaces-banner,
[class*="space-header"],
[class*="spaces-header"],
[class*="spaces-tag"],
[class*="spaces-card"],
[class*="spaces-banner"],
[class*="hf-spaces"],
[data-testid*="space-header"] {
display: none !important;
visibility: hidden !important;
pointer-events: none !important;
height: 0 !important;
width: 0 !important;
overflow: hidden !important;
}
</style>
<script>
(function() {
// HF Spaces floating widget signature: top-level element near top-right
// that mentions the Space repo path or an HF Spaces-style breadcrumb.
// We sweep on load and on every DOM mutation.
const SIGNATURES = [
'AE-Talk-bot/',
'huggingface.co/spaces/',
'Built with',
];
function looksLikeHfWidget(el) {
if (!el || el.nodeType !== 1) return false;
// Don't touch our own gradio app
if (el.id === 'root' || el.id === 'gradio-app' ||
el.classList && el.classList.contains('gradio-container')) return false;
if (el.querySelector && el.querySelector('.gradio-container, #root, #gradio-app')) return false;
const txt = (el.textContent || '').trim();
if (txt.length > 400) return false; // too big, not a small badge
// Must match at least one signature
for (const sig of SIGNATURES) {
if (txt.includes(sig)) return true;
}
// Also flag obviously-HF class names
const cls = (el.className && el.className.toString) ? el.className.toString() : '';
if (/space[s-]?(header|tag|banner|card)/i.test(cls)) return true;
return false;
}
function sweep() {
// Only check direct body children to keep this cheap
Array.from(document.body.children).forEach(el => {
if (looksLikeHfWidget(el)) {
el.style.display = 'none';
el.setAttribute('hidden', '');
console.log('[hf-widget-hide] removed', el.tagName, el.className || '(no class)');
}
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', sweep);
} else {
sweep();
}
// Re-sweep on every mutation in case HF injects later
const obs = new MutationObserver(sweep);
if (document.body) {
obs.observe(document.body, { childList: true });
} else {
document.addEventListener('DOMContentLoaded', () => {
obs.observe(document.body, { childList: true });
});
}
})();
</script>
"""
_AHA_INLINE_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 116 54" aria-label="aha" style="height:1.2em;width:auto;display:inline-block;overflow:visible"><g fill="#F59E0B" stroke="#D97706" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(-8 17 44) translate(8 50) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/><path transform="rotate(5 41 34) translate(29 43) scale(0.020020 -0.020020)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/><path transform="rotate(-6 62 45) translate(53 51) scale(0.016602 -0.016602)" d="M965 -66Q919 -66 819 34Q727 -10 657.0 -32.5Q587 -55 538 -55Q297 -55 176.5 74.0Q56 203 56 460Q56 701 234.0 872.5Q412 1044 660 1044Q755 1044 880 990Q1031 925 1031 839Q1031 803 1008 776Q998 736 992.5 675.5Q987 615 987 534Q987 343 1014 259Q1017 250 1060 155Q1099 69 1099 57Q1099 4 1058.5 -31.0Q1018 -66 965 -66ZM717 620Q717 652 721.5 693.5Q726 735 735 786Q715 796 699.5 800.5Q684 805 673 805Q537 805 435.0 698.5Q333 592 333 452Q333 318 381.0 250.5Q429 183 525 183Q587 183 642.5 203.5Q698 224 747 264Q717 502 717 620Z"/></g><g fill="#F59E0B" stroke="#D97706" stroke-width="1" stroke-linejoin="round"><rect x="82" y="17" width="4" height="23" rx="2" transform="rotate(13 84 28.5)"/><circle cx="82.5" cy="50" r="3.5"/><rect x="92" y="17" width="4" height="23" rx="2" transform="rotate(13 94 28.5)"/><circle cx="92.5" cy="50" r="3.5"/><rect x="102" y="17" width="4" height="23" rx="2" transform="rotate(13 104 28.5)"/><circle cx="102.5" cy="50" r="3.5"/></g></svg>'
_UGH_INLINE_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 6 115 64" aria-label="ugh." style="height:1.35em;width:auto;display:inline-block;overflow:visible"><g fill="#8E7398" stroke="#5E4865" stroke-width="1.3" stroke-linejoin="round" paint-order="stroke"><path transform="rotate(6 18 42) translate(8 46) scale(0.017090 -0.017090)" d="M978 578Q978 511 979.0 376.0Q980 241 980 174Q980 153 983.5 111.5Q987 70 987 49Q987 -7 946.5 -43.5Q906 -80 847 -80Q764 -80 726 -5Q598 -52 461 -52Q319 -52 222 8Q113 77 92 209Q53 459 53 656Q53 786 83 953Q103 1066 218 1066Q276 1066 317.0 1029.5Q358 993 358 937Q358 893 343.5 799.0Q329 705 329 656Q329 515 338.5 409.5Q348 304 367 235Q392 224 415.5 218.0Q439 212 461 212Q572 212 705 244Q705 321 704 419Q702 536 702 587Q702 792 721 941Q736 1060 857 1060Q916 1060 958.0 1023.0Q1000 986 997 930Q978 549 978 578Z"/><path transform="rotate(3 43 40) translate(31 49) scale(0.018066 -0.018066)" d="M1029 596Q987 361 979 100Q969 -223 871 -369Q740 -564 407 -564Q18 -564 18 -410Q18 -355 53.0 -321.0Q88 -287 145 -287Q190 -287 274.0 -304.0Q358 -321 423 -321Q572 -321 643 -230Q711 -141 723 53Q672 1 608.0 -25.0Q544 -51 468 -51Q269 -51 144.5 78.5Q20 208 20 410Q20 682 186 850Q358 1024 651 1024Q745 1024 813.0 1001.0Q881 978 923 931Q1050 916 1050 781Q1050 714 1029 596ZM641 796Q472 796 378 685Q294 584 294 423Q294 304 339.0 244.0Q384 184 474 184Q556 184 639 279Q717 369 728 457Q747 553 772 756Q738 776 705.0 786.0Q672 796 641 796Z"/><path transform="rotate(8 67 38) translate(55 45) scale(0.018066 -0.018066)" d="M399 915Q472 987 555.5 1022.5Q639 1058 734 1058Q905 1058 980 962Q1036 890 1048 741Q1053 618 1059 494Q1075 333 1079 298Q1093 187 1113 104Q1118 83 1118 67Q1118 11 1075.5 -25.5Q1033 -62 976 -62Q875 -62 845 38Q821 119 801 266Q783 407 783 498Q783 523 785.5 573.5Q788 624 788 649Q788 723 786 735Q777 790 734 790Q623 790 533 688Q487 637 407 494Q407 132 372 58Q333 -24 248 -24Q192 -24 148.5 13.5Q105 51 105 106Q105 125 116 159Q123 181 128 429Q123 630 130 1098L132 1131Q138 1249 138 1289Q138 1320 128.5 1380.5Q119 1441 119 1472Q119 1529 160.0 1565.5Q201 1602 259 1602Q358 1602 392 1496Q411 1436 411 1312Q411 1212 405 1109Q399 1011 399 915Z"/></g><circle cx="84" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="96" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/><circle cx="108" cy="51" r="3.5" fill="#8E7398" stroke="#5E4865" stroke-width="1" stroke-linejoin="round"/></svg>'
def _label_row_html(text, *, with_counter=True):
"""Build the HTML for the custom label row above the argument textbox.
The word-counter span has id='wc-display' so the JS in EMOJI_SWAP_HEAD
can write into it on every keystroke."""
counter = (
'<span id="wc-display" class="wc-status">'
'0 words (need at least 100)'
'</span>'
) if with_counter else ''
return (
'<div class="arg-label-row">'
f'<span class="arg-label-text">{text}</span>'
f'{counter}'
'</div>'
)
ARG_NOTICE_HTML = (
'<div class="arg-notice">'
'Please <b><i><u>Do not use external AI tools or other online writing '
'assistants.</u></i></b> You may use only the material provided in this '
'system.'
'</div>'
)
ARG_LABEL_PHASE1 = _label_row_html("Your argument", with_counter=True)
ARG_LABEL_PHASE2 = _label_row_html(
"Your argument and revision",
with_counter=False,
)
ARG_LABEL_LOCKED = _label_row_html(
"Your argument (locked — submitted)", with_counter=False,
)
FEEDBACK_HINT_HTML = (
'<div class="discussion-intro">'
'<div class="discussion-intro-title">How to use this discussion</div>'
'<div class="discussion-intro-line">'
'<b>1.</b> The chatbot will analyze your argument and discuss some '
'related questions with you. As you go, <b><i><u>revise your argument'
'</u></i></b> on the right and submit the final revised version when '
'you\'re ready.'
'</div>'
'<div class="discussion-intro-line">'
'<b>2.</b> During the <b><i><u>discussion</u></i></b>, you can '
'<b><i><u>ask for clarification, disagree, or explain what feels '
'unclear</u></i></b>.'
'</div>'
'<div class="discussion-intro-line">'
'<b>3.</b> The bot may take a few seconds to think before each reply. '
'Please be patient — that\'s normal.'
'</div>'
'<div class="discussion-intro-line">'
'<b>4.</b> After each bot reply, you can tag it:'
'<ul class="discussion-intro-bullets">'
'<li>Click ' + _AHA_INLINE_SVG + ' if it <b><i><u>helped</u></i></b>'
' you notice or rethink something new.</li>'
'<li>Click ' + _UGH_INLINE_SVG + ' if it felt <b><i><u>frustrating'
'</u></i></b> or off.</li>'
'<li>If you do not feel either reaction, you can also leave it '
'unclicked.</li>'
'</ul>'
'</div>'
'</div>'
)
# ============================================================
# Blocks
# ============================================================
# JS that takes over scroll behavior from Gradio's built-in autoscroll
# (we set autoscroll=False on the Chatbot):
# 1. On initial load: scroll to TOP of the chatbot so participants read the
# case from the start (Gradio's default lands at the bottom).
# 2. While the bot is thinking/streaming OR any new message arrives: scroll
# to BOTTOM via MutationObserver on the inner scroll container.
# The observer is armed only AFTER initial render is settled, so it doesn't
# fight the initial scroll-to-top.
_CHATBOT_SCROLL_JS = """
() => {
const setup = (tries) => {
tries = tries || 0;
if (tries > 40) return;
const cb = document.querySelector('#chatbot-main');
if (!cb) { setTimeout(() => setup(tries+1), 100); return; }
const inner = cb.querySelector('.bubble-wrap')
|| cb.querySelector('[class*="bubble-wrap"]')
|| cb.querySelector('.message-wrap')
|| cb.querySelector('[class*="message-wrap"]')
|| cb;
if (!inner || inner.scrollHeight <= inner.clientHeight + 4) {
setTimeout(() => setup(tries+1), 100);
return;
}
// Initial: scroll to top, and re-assert a few times in case any late
// layout pass tries to push us back down.
inner.scrollTop = 0;
setTimeout(() => { inner.scrollTop = 0; }, 200);
setTimeout(() => { inner.scrollTop = 0; }, 600);
setTimeout(() => { inner.scrollTop = 0; }, 1200);
// After initial render is settled, watch for ANY content change and
// pin scroll to bottom. This covers: user message added, bot reply
// streaming token-by-token, final reply settled.
setTimeout(() => {
const obs = new MutationObserver(() => {
inner.scrollTop = inner.scrollHeight;
});
obs.observe(inner, {
childList: true, subtree: true, characterData: true
});
}, 1600);
};
setup();
}
"""
with gr.Blocks(title="A", fill_height=True) as demo:
# Per-session cache dict. Holds parsed plan + manager_history.
cache_state = gr.State({})
# Per-session SessionLogger. Initialized in demo.load (Gradio 6.11
# doesn't call callable defaults of gr.State).
logger_state = gr.State()
# Hidden Textbox carrying the walkthrough-finished timestamp from JS
# (set by the walkthrough's "Start" button at the last slide) to the
# Python on_submit_initial handler. The submit button's js= wrapper
# reads window.__walkthroughStartedAt and overrides this value before
# the Python handler runs.
walkthrough_ts_input = gr.Textbox(
value="",
visible=False,
elem_id="walkthrough-ts-input",
)
# ====== TOP ROW (tall): guide | chatbot | argument textbox ======
with gr.Row(equal_height=True):
with gr.Column(scale=1, elem_id="guide-col", visible=False):
gr.HTML(
FEEDBACK_HINT_HTML,
elem_id="feedback-hint",
)
with gr.Column(scale=3):
chatbot = gr.Chatbot(
value=INITIAL_CHATBOT_VALUE,
height="65vh",
group_consecutive_messages=False,
autoscroll=False,
show_label=False,
elem_id="chatbot-main",
)
with gr.Column(scale=2, elem_id="right-col"):
arg_label_row = gr.HTML(
ARG_LABEL_PHASE1, elem_id="arg-label-row",
)
arg_notice = gr.HTML(
ARG_NOTICE_HTML, elem_id="arg-notice",
)
arg_input = gr.Textbox(
show_label=False,
placeholder=(
"Type your initial argument here.\n"
"You need at least 100 words to start the discussion with the AI assistant.\n"
"Start by saying whether you think the AI system is ethically "
"acceptable, ethically unacceptable, or acceptable only under "
"certain conditions. Then explain why."
),
lines=15,
max_lines=20,
interactive=True,
elem_id="right-essay",
)
# ====== BOTTOM ROW: chat input + send | action buttons ======
# The top row's guide column is visible=False (collapsed by Gradio),
# so the chatbot column expands left. The bottom row matches: no mirror
# column, just chat-row (scale=3) + action-col (scale=2) aligned under
# the chatbot (scale=3) and the argument textbox (scale=2) above.
with gr.Row(equal_height=True):
with gr.Column(scale=3):
with gr.Row(elem_id="chat-row"):
msg_input = gr.Textbox(
placeholder="Submit your initial argument first to enable chat",
show_label=False,
interactive=False,
scale=6,
lines=1,
max_lines=6,
elem_id="chat-input",
)
send_btn = gr.Button(
"Send", interactive=False, scale=1, variant="primary",
elem_id="send-btn",
)
with gr.Column(scale=2, elem_id="bottom-action-col"):
submit_initial_btn = gr.Button(
SUBMIT_INITIAL_LABEL, variant="primary", visible=True,
elem_id="submit-initial-btn",
)
end_session_btn = gr.Button(
END_SESSION_LABEL,
variant="secondary",
visible=False,
interactive=False,
)
# Hidden elements for session-recovery (see RECOVERY_HEAD comment).
# visible=True + CSS display:none keeps them in the DOM so the JS layer
# can write to the textbox and click the button.
recover_session_id_input = gr.Textbox(
value="", visible=True, elem_id="recover-session-id-input",
elem_classes=["soc-hidden-helper"],
)
recover_btn = gr.Button(
"recover", visible=True, elem_id="recover-btn",
elem_classes=["soc-hidden-helper"],
)
recovery_payload = gr.Textbox(
value="", visible=True, elem_id="recovery-payload",
elem_classes=["soc-hidden-helper"],
)
# 2-click confirmation state for end_session_btn (Phase 2 to 3):
arm_state = gr.State(0.0)
revert_timer = gr.Timer(value=2.5, active=False)
# 2-click confirmation state for submit_initial_btn (Phase 1 to 2):
submit_initial_arm_state = gr.State(0.0)
submit_initial_revert_timer = gr.Timer(value=2.5, active=False)
done_panel = gr.HTML(value="", visible=False)
# ============================================================
# Handlers
# ============================================================
def on_submit_initial(arg_text, history, cache, arm_at, logger, walkthrough_ts):
"""Phase 1 to Phase 2 with 2-click confirmation.
`walkthrough_ts` is a string carrying the unix-seconds timestamp
the participant clicked "Start" at the end of the walkthrough. It
is injected by the js= wrapper on submit_initial_btn.click, which
reads `window.__walkthroughStartedAt` (set client-side at the
moment of the walkthrough Start click).
Outputs (12): chatbot, arg_input, submit_initial_btn, end_session_btn,
msg_input, send_btn, cache_state,
submit_initial_arm_state, submit_initial_revert_timer,
logger_state, arg_label_row, recovery_payload
"""
if logger is None:
logger = SessionLogger()
now = time.time()
if arm_at and (now - arm_at) <= ARM_TTL:
# CONFIRMED
logger.start_session()
# Assign one OpenAI key from the pool for this whole session
# (round-robin across OPENAI_KEY_01..10). The same client is
# then threaded through to manager + main bot + essay
# generation for the rest of the session.
try:
_key_idx, _session_client = get_next_client()
logger.set_assigned_key(_key_idx)
print(f"[key_pool] session {logger.session_id} -> key_idx={_key_idx}",
flush=True)
except Exception as _e:
_key_idx, _session_client = None, None
print(f"[key_pool] failed to assign key: {_e}", flush=True)
# Persist the walkthrough-finished timestamp the JS handler
# captured at the walkthrough-end "Start" click. Robust to
# empty / malformed input.
try:
ts_float = float(walkthrough_ts) if walkthrough_ts else None
if ts_float and ts_float > 0:
logger.walkthrough_started_at = ts_float
except (ValueError, TypeError):
pass
logger.argument_submitted_at = now # gates End Session by time
logger.set_essay("argument", arg_text)
logger.add_argument_snapshot(
trigger="submit_initial_confirm",
text=arg_text,
)
# Trigger ③: persist initial argument + walkthrough timing to HF.
# Protects users who submit initial then close tab before any
# chat turn happens (otherwise the only push would be at first
# turn completion).
logger.checkpoint()
cache = {INITIAL_ARG_KEY: arg_text,
SESSION_CLIENT_KEY: _session_client}
history = history + [{"role": "user", "content": arg_text}]
# Yield 1: phase-2 layout with a "preparing" status, chat disabled
# while we generate the per-session essay + discussion plan.
# Also write a "submitted" JSON event into recovery_payload so the
# chained .then(js=...) writes session_id to localStorage.
import json as _json_local
history_with_status = history + [{
"role": "assistant",
"content": "*Reading your argument and preparing the discussion. This takes about 15-30 seconds... Please keep this page open and do not refresh it during this time.*",
}]
save_payload = _json_local.dumps({
"event": "submitted",
"sid": logger.session_id,
"code": logger.completion_code or "",
})
yield (
history_with_status,
gr.update(value=arg_text, placeholder=""),
gr.update(visible=False, value=SUBMIT_INITIAL_LABEL,
variant="primary"),
gr.update(visible=True, interactive=False),
gr.update(interactive=False,
placeholder="Preparing the discussion..."),
gr.update(interactive=False),
cache,
0.0,
gr.update(active=False),
logger,
gr.update(value=ARG_LABEL_PHASE2),
gr.update(value=save_payload),
)
# Generate the essay + plan. On any failure, fall back to no
# plan (the main bot will freestyle without PLAN CONTROL).
try:
arts = generate_session_artifacts(arg_text, client=_session_client)
if arts.get("perfect_answer"):
cache[PERFECT_ANSWER_KEY] = arts["perfect_answer"]
logger.set_perfect_answer(arts["perfect_answer"])
if arts.get("dominant_framework"):
logger.set_dominant_framework(arts["dominant_framework"])
print(f"[framework] {arts['dominant_framework']}",
flush=True)
if arts.get("discussion_plan"):
cache[PLAN_TEXT_KEY] = arts["discussion_plan"]
logger.set_discussion_plan(arts["discussion_plan"])
subprobes = plan_parsing.parse_plan(arts["discussion_plan"])
cache[PLAN_SUBPROBES_KEY] = subprobes
cache[MANAGER_HISTORY_KEY] = []
print(f"[plan_parsing] parsed {len(subprobes)} sub-probes",
flush=True)
except Exception as e:
print(f"[session_artifacts] generation failed: {e}", flush=True)
# Yield 2: enable chat input, clear the status, prepare to stream
# the bot's first reply.
yield (
history,
gr.update(), gr.update(), gr.update(),
gr.update(interactive=True,
placeholder="Type your response..."),
gr.update(interactive=True),
cache,
gr.update(), gr.update(),
logger,
gr.update(),
gr.update(),
)
# Stream the first bot reply. The participant's argument is the
# 'user message' for turn 1 from the bot's perspective.
t0 = time.perf_counter()
turn_result = {}
try:
for history in stream_turn(arg_text, history, CASE_TEXT, cache, turn_result):
yield (
history,
gr.update(), gr.update(), gr.update(),
gr.update(), gr.update(), cache,
gr.update(), gr.update(),
logger,
gr.update(),
gr.update(),
)
# After streaming finishes, persist this turn (manager_verdict +
# plan_control + assistant_response + scratch + latencies).
_log_turn(arg_text, cache, logger, turn_result, t0)
finally:
# Trigger ① on auto-first-turn: covers the manager-generated
# perfect_answer + discussion_plan + dominant_framework (set
# earlier in this handler) together with the first turn data.
# In try/finally so PA/plan/framework get persisted even when
# stream_turn raises (e.g. OpenAI mid-stream failure).
if logger:
logger.checkpoint()
# ENABLE end_session_btn.
yield (
gr.update(),
gr.update(), gr.update(),
gr.update(interactive=True),
gr.update(), gr.update(),
cache,
gr.update(), gr.update(),
logger,
gr.update(),
gr.update(),
)
return
if not arg_text.strip():
gr.Warning("Please write your argument before submitting.")
yield (
gr.update(), gr.update(), gr.update(), gr.update(),
gr.update(), gr.update(), cache,
arm_at, gr.update(),
logger,
gr.update(),
gr.update(),
)
return
# ARM
yield (
gr.update(),
gr.update(),
gr.update(value=SUBMIT_INITIAL_CONFIRM_LABEL, variant="stop"),
gr.update(),
gr.update(),
gr.update(),
cache,
now,
gr.update(active=True),
logger,
gr.update(),
gr.update(),
)
def on_submit_initial_tick(arm_at):
"""1Hz tick: auto-revert submit_initial_btn after ARM_TTL."""
if not arm_at:
return arm_at, gr.update(active=False), gr.update()
if (time.time() - arm_at) > ARM_TTL:
return (
0.0,
gr.update(active=False),
gr.update(value=SUBMIT_INITIAL_LABEL, variant="primary"),
)
return arm_at, gr.update(), gr.update()
def on_send(msg, history, cache, logger, arg_text):
"""Regular chat turn: snapshot notepad, show user message, then run
manager + main bot via the two-agent orchestrator. `arg_text` is the
current notepad value (snapshotted to logger, never sent to bot).
Trigger ① (per-turn push): exactly one HF upload at the end of this
handler, covering everything accumulated since last upload:
- chat_send snapshot
- any feedback events / textbox snapshots between turns
- this turn (user_message + manager_verdict + assistant_response)
Bot-failure path also gets one push (try/finally) so a failed turn
doesn't lose the user's message."""
if not msg.strip():
yield history, "", cache
return
logger.add_argument_snapshot(
trigger="chat_send",
text=arg_text,
context={
"next_turn_n": len(logger.turns) + 1,
"user_msg_excerpt": msg[:120],
},
)
history = history + [{"role": "user", "content": msg}]
yield history, "", cache
t0 = time.perf_counter()
turn_result = {}
try:
for history in stream_turn(msg, history, CASE_TEXT, cache, turn_result):
yield history, "", cache
_log_turn(msg, cache, logger, turn_result, t0)
finally:
# Trigger ①: persist this turn + interim events. Runs on both
# success and failure paths so we never lose the user's message
# even if stream_turn raises mid-stream.
if logger:
logger.checkpoint()
def on_end_session(arm_at, arg_text, logger):
"""2-click end-session/finalize. Generator so we can show an
intermediate 'Uploading your session…' state while flush runs (up
to ~165s of retries under HF rate-limit), then a final status
message reflecting whether the upload actually succeeded.
The 9th output (recovery_payload) carries an "ended" event JSON on
the CONFIRM second yield, which the chained .then(js=...) reads to
clear localStorage. Other yields leave it untouched.
Outputs (9): arg_input, end_session_btn, msg_input, send_btn,
done_panel, arm_state, revert_timer, arg_label_row,
recovery_payload
"""
now = time.time()
# Gate check on FIRST click only (when not yet armed / arm expired).
# If the participant has not advanced through enough probes and
# the 20-minute timeout hasn't elapsed, do not arm — instead emit
# a toast asking them to keep discussing. Plan-complete sessions
# always pass _can_end_session. Bypassed entirely if the
# `lockdown.end_session_gate` config flag is false (test mode).
is_first_click = not (arm_at and (now - arm_at) <= ARM_TTL)
if ENFORCE_END_SESSION_GATE and is_first_click and not _can_end_session(logger):
yield (
gr.update(), # arg_input
gr.update(), # end_session_btn (stays in normal state)
gr.update(), # msg_input
gr.update(), # send_btn
gr.update(value=_gate_toast_trigger_html(), visible=True),
arm_at,
gr.update(),
gr.update(),
gr.update(), # recovery_payload (no event)
)
return
# Gate 2: revise-check. Fires at most once per session: compare the
# current arg_text against the initial argument the participant
# submitted at Phase-1; if word-level similarity is too high, they
# have not revised — show the modal and block this click. Any later
# End Session click goes through regardless of similarity.
if (
LOCKDOWN_REVISE_CHECK
and is_first_click
and logger is not None
and not getattr(logger, "revise_warned", False)
):
initial_text = (
(logger.essays.get("argument") if logger.essays else None) or {}
).get("text", "")
sim = _arg_word_similarity(initial_text, arg_text)
print(
f"[revise-check] similarity={sim:.3f} "
f"threshold={REVISE_SIMILARITY_THRESHOLD}",
flush=True,
)
if initial_text and sim > REVISE_SIMILARITY_THRESHOLD:
logger.revise_warned = True
yield (
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(value=_revise_gate_trigger_html(), visible=True),
arm_at,
gr.update(),
gr.update(),
gr.update(), # recovery_payload (no event)
)
return
if arm_at and (now - arm_at) <= ARM_TTL:
# CONFIRMED. First yield: lock the UI + show 'uploading' state.
yield (
gr.update(interactive=False),
gr.update(visible=False, value=END_SESSION_LABEL,
variant="secondary"),
gr.update(interactive=False,
placeholder="Session ended. Saving your data…", value=""),
gr.update(interactive=False),
gr.update(value=SAVING_PANEL_HTML, visible=True),
0.0,
gr.update(active=False),
gr.update(value=ARG_LABEL_LOCKED),
gr.update(), # recovery_payload (clear happens in next yield)
)
# Now run the actual flush (blocks for up to ~165s of retries).
flush_result = {"status": "no_logger", "session_id": None,
"completion_code": None}
if logger is not None:
logger.add_argument_snapshot(
trigger="end_session_confirm", text=arg_text,
)
flush_result = logger.flush()
# Second yield: full-screen modal with the completion code.
# Also emit "ended" event so the chained .then(js=...) clears
# localStorage now that the session has been finalised.
import json as _json_local
yield (
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(value=_completion_modal_html(flush_result), visible=True),
gr.update(),
gr.update(),
gr.update(),
gr.update(value=_json_local.dumps({"event": "ended"})),
)
return
# ARM (single yield equivalent to the original return).
if logger is not None:
logger.add_argument_snapshot(
trigger="end_session_arm", text=arg_text,
)
yield (
gr.update(),
gr.update(value=END_SESSION_CONFIRM_LABEL, variant="stop"),
gr.update(),
gr.update(),
gr.update(),
now,
gr.update(active=True),
gr.update(),
gr.update(), # recovery_payload (no event)
)
def on_timer_tick(arm_at):
"""1Hz tick: revert end_session_btn if not confirmed within ARM_TTL."""
if not arm_at:
return arm_at, gr.update(active=False), gr.update()
if (time.time() - arm_at) > ARM_TTL:
return (
0.0,
gr.update(active=False),
gr.update(value=END_SESSION_LABEL, variant="secondary"),
)
return arm_at, gr.update(), gr.update()
def on_feedback(arg_text, logger, data: gr.LikeData):
"""Participant clicked aha! or ugh. on a bot message."""
if logger is None:
return
new_kind = "aha" if data.liked else "stress"
idx = data.index if isinstance(data.index, int) else (
data.index[0] if data.index else -1
)
current = logger.get_current_kind(idx)
kind = "none" if current == new_kind else new_kind
def _flatten(v):
if isinstance(v, str):
return v
if isinstance(v, dict):
return v.get("text") or v.get("content") or ""
if isinstance(v, list):
return " ".join(_flatten(x) for x in v if x)
return str(v or "")
excerpt = _flatten(data.value).strip()
logger.add_feedback(message_index=idx, kind=kind,
message_excerpt=excerpt[:200])
logger.add_argument_snapshot(
trigger="feedback_click",
text=arg_text,
context={"message_index": idx, "kind": kind},
)
def on_recover_session(session_id_str):
"""Session-recovery handler. Fired by the hidden recover_btn that JS
clicks programmatically when the participant chooses 'Continue' on
the recovery modal.
All three conditions (A/B/C) share the same HF dataset
(`AE-Talk-bot/log-Jun-17-2026`), so the file lookup is restricted to
this Space's mode prefix (LOG_PATH's parent) to prevent picking up a
session belonging to a different condition.
Outputs (12): same shape as on_submit_initial.
"""
import json as _json
sid = (session_id_str or "").strip()
def _err(reason):
print(f"[recover] FAIL ({reason}); sid={sid!r}", flush=True)
outs = list(gr.update() for _ in range(11))
outs.append(gr.update(value=_json.dumps({
"event": "error", "reason": reason
})))
return tuple(outs)
if not sid:
return _err("empty session_id")
try:
from core.config_loader import (
hf_api as _hf_api, HF_DATASET, HF_TOKEN, LOG_PATH,
)
if not _hf_api or not HF_DATASET:
return _err("HF api/dataset not configured")
files = _hf_api.list_repo_files(HF_DATASET, repo_type="dataset")
# Restrict to this Space's mode_prefix (e.g. "A-soc/" /
# "B-ans/" / "C-non/") so a session belonging to a different
# condition in the same shared dataset does not match.
mode_prefix = LOG_PATH.rsplit("/", 1)[0] + "/" if "/" in LOG_PATH else ""
target = next(
(f for f in files
if f.endswith(".json") and f"/{sid}_" in f
and (not mode_prefix or f.startswith(mode_prefix))),
None,
)
if not target:
print(f"[recover] sid={sid!r} not in {len(files)} files; "
f"LOG_PATH={LOG_PATH!r}", flush=True)
return _err(f"session file not found (looked for /{sid}_*.json)")
print(f"[recover] matched {target}", flush=True)
from huggingface_hub import hf_hub_download
local = hf_hub_download(
repo_id=HF_DATASET, filename=target, repo_type="dataset",
token=HF_TOKEN, force_download=True,
)
data = _json.loads(_Path(local).read_text(encoding="utf-8"))
except Exception as e:
return _err(f"{type(e).__name__}: {e}")
new_logger = SessionLogger.from_dict(data)
if new_logger is None:
return _err("from_dict returned None (malformed payload)")
initial_arg = (data.get("essays") or {}).get("argument", {}).get("text", "")
# Resolve the assigned OpenAI key back to its pool client. The index
# was preserved across the recovery boundary (from_dict restored it
# on the logger). If we can't find a matching pool entry, fall back
# to whatever get_next_client returns now.
from core.config_loader import KEY_POOL as _KP
_restored_client = None
_restored_idx = new_logger.assigned_key_idx
if _restored_idx is not None:
for _idx, _c in _KP:
if _idx == _restored_idx:
_restored_client = _c
break
if _restored_client is None:
try:
_restored_idx, _restored_client = get_next_client()
new_logger.set_assigned_key(_restored_idx)
print(f"[recover] no original key match; re-assigned key_idx={_restored_idx}",
flush=True)
except Exception as _e:
print(f"[recover] failed to assign client on recovery: {_e}", flush=True)
cache = {INITIAL_ARG_KEY: initial_arg,
SESSION_CLIENT_KEY: _restored_client}
pa = data.get("perfect_answer")
if pa and pa.get("text"):
cache[PERFECT_ANSWER_KEY] = pa["text"]
dp = data.get("discussion_plan")
if dp and dp.get("text"):
cache[PLAN_TEXT_KEY] = dp["text"]
try:
cache[PLAN_SUBPROBES_KEY] = plan_parsing.parse_plan(dp["text"])
except Exception as e:
print(f"[recover] plan re-parse failed: {e}", flush=True)
cache[MANAGER_HISTORY_KEY] = list(data.get("manager_history") or [])
history = []
for t in (data.get("turns") or []):
um = t.get("user_message")
ar = t.get("assistant_response")
if um:
history.append({"role": "user", "content": um})
if ar:
history.append({"role": "assistant", "content": ar})
snapshots = data.get("argument_snapshots") or []
arg_text = snapshots[-1].get("text") if snapshots else initial_arg
print(f"[recover] OK: sid={sid}, "
f"{len(history)//2} chat exchanges, "
f"{len(cache.get(MANAGER_HISTORY_KEY) or [])} verdicts, "
f"{len(snapshots)} snapshots", flush=True)
# Trigger ⑤: persist the 'session_resumed' snapshot that from_dict()
# appended in-memory. Without this, a second tab-close before the
# next chat turn would lose the resume marker.
new_logger.checkpoint()
save_payload = _json.dumps({
"event": "submitted",
"sid": new_logger.session_id,
"code": new_logger.completion_code or "",
})
return (
history,
gr.update(value=arg_text, placeholder=""),
gr.update(visible=False, value=SUBMIT_INITIAL_LABEL,
variant="primary"),
gr.update(visible=True, interactive=True,
variant="secondary",
value=END_SESSION_LABEL),
gr.update(interactive=True,
placeholder="Type your response..."),
gr.update(interactive=True),
cache,
0.0,
gr.update(active=False),
new_logger,
gr.update(value=ARG_LABEL_PHASE2),
gr.update(value=save_payload),
)
_initial_outputs = [
chatbot,
arg_input,
submit_initial_btn,
end_session_btn,
msg_input,
send_btn,
cache_state,
]
_RECOVERY_SAVE_JS = """(payload) => {
console.log('[recovery] .then(js) received payload:', payload);
if (!payload) return payload;
try {
const obj = JSON.parse(payload);
if (obj.event === 'submitted' && obj.sid &&
window.__RECOVERY) {
window.__RECOVERY.saveSession(obj.sid, obj.code || '');
window.__RECOVERY.dismissModalIfLoading();
} else if (obj.event === 'error' && window.__RECOVERY) {
console.error('[recovery] server returned error:', obj.reason);
window.__RECOVERY.markModalError(obj.reason || 'unknown');
}
} catch (e) {
console.warn('[recovery] save-js parse failed', e, 'payload:', payload);
}
return payload;
}"""
_RECOVERY_CLEAR_JS = """(payload) => {
if (!payload) return payload;
try {
const obj = JSON.parse(payload);
if (obj.event === 'ended' && window.__RECOVERY) {
window.__RECOVERY.clearState();
}
} catch (e) {}
return payload;
}"""
submit_initial_btn.click(
on_submit_initial,
inputs=[arg_input, chatbot, cache_state, submit_initial_arm_state, logger_state, walkthrough_ts_input],
outputs=_initial_outputs + [submit_initial_arm_state, submit_initial_revert_timer, logger_state, arg_label_row, recovery_payload],
js="""(arg_text, history, cache, arm_at, logger, ts_in) => {
// Override the hidden walkthrough-ts input with the value JS
// captured at the walkthrough-end Start click. Empty string
// if the participant somehow skipped the walkthrough.
var ts = window.__walkthroughStartedAt;
return [arg_text, history, cache, arm_at, logger, ts ? String(ts) : ''];
}""",
).then(
fn=None,
inputs=[recovery_payload],
outputs=[recovery_payload],
js=_RECOVERY_SAVE_JS,
)
recover_btn.click(
on_recover_session,
inputs=[recover_session_id_input],
outputs=_initial_outputs + [submit_initial_arm_state, submit_initial_revert_timer, logger_state, arg_label_row, recovery_payload],
).then(
fn=None,
inputs=[recovery_payload],
outputs=[recovery_payload],
js=_RECOVERY_SAVE_JS,
)
submit_initial_revert_timer.tick(
on_submit_initial_tick,
inputs=[submit_initial_arm_state],
outputs=[submit_initial_arm_state, submit_initial_revert_timer, submit_initial_btn],
)
send_btn.click(
on_send,
inputs=[msg_input, chatbot, cache_state, logger_state, arg_input],
outputs=[chatbot, msg_input, cache_state],
)
msg_input.submit(
on_send,
inputs=[msg_input, chatbot, cache_state, logger_state, arg_input],
outputs=[chatbot, msg_input, cache_state],
)
end_session_btn.click(
on_end_session,
inputs=[arm_state, arg_input, logger_state],
outputs=[arg_input, end_session_btn, msg_input, send_btn,
done_panel, arm_state, revert_timer, arg_label_row,
recovery_payload],
).then(
fn=None,
inputs=[recovery_payload],
outputs=[recovery_payload],
js=_RECOVERY_CLEAR_JS,
)
revert_timer.tick(
on_timer_tick,
inputs=[arm_state],
outputs=[arm_state, revert_timer, end_session_btn],
)
chatbot.like(on_feedback, inputs=[arg_input, logger_state], outputs=None)
demo.load(
fn=lambda: SessionLogger(),
inputs=None,
outputs=logger_state,
js=_CHATBOT_SCROLL_JS,
)
# ============================================================
# Auto-restart (unchanged from v3)
# ============================================================
def _start_auto_restart():
import os
from datetime import datetime
from core.config_loader import CONFIG, HF_TOKEN, HF_DATASET, LOG_PATH
from core import AEST
cfg = CONFIG.get("auto_restart") or {}
env_override = os.environ.get("AUTO_RESTART_ENABLED", "").strip().lower()
enabled = (env_override in {"1", "true", "yes"}) or (env_override == "" and cfg.get("enabled"))
if not enabled:
return
if not (HF_TOKEN and HF_DATASET):
print("[auto-restart] HF token / dataset missing — skipping.", flush=True)
return
space_id = cfg.get("space_id")
if not space_id:
return
check_hours = cfg.get("check_interval_hours", 12)
idle_hours = cfg.get("idle_threshold_hours", 24)
from huggingface_hub import HfApi
api = HfApi(token=HF_TOKEN)
started_at = now_aest()
def _check_and_restart():
while True:
time.sleep(check_hours * 3600)
now = now_aest()
print(f"[auto-restart] {now.strftime('%Y-%m-%d %H:%M:%S')} — idle check…", flush=True)
try:
files = api.list_repo_files(HF_DATASET, repo_type="dataset")
log_files = sorted(
f for f in files if f.startswith(LOG_PATH + "/") and f.endswith(".json")
)
if log_files:
latest = log_files[-1].rsplit("/", 1)[-1].removesuffix(".json")
# Filenames are "<YYYYMMDD>_<HHMMSS>_<session_code>" — strptime the timestamp only.
ts = "_".join(latest.split("_")[:2])
latest_dt = datetime.strptime(ts, "%Y%m%d_%H%M%S").replace(tzinfo=AEST)
idle_h = (now - latest_dt).total_seconds() / 3600
src = f"latest log {latest}"
else:
idle_h = (now - started_at).total_seconds() / 3600
src = "no logs yet — using thread uptime"
print(f"[auto-restart] Idle source: {src} ({idle_h:.1f}h ago)", flush=True)
if idle_h > idle_hours:
print(f"[auto-restart] Idle {idle_h:.1f}h > {idle_hours}h — restarting {space_id}.", flush=True)
api.restart_space(space_id)
else:
print(f"[auto-restart] Active within {idle_hours}h — no restart.", flush=True)
except Exception as e:
print(f"[auto-restart] Check failed: {e}", flush=True)
threading.Thread(target=_check_and_restart, daemon=True).start()
print(f"[auto-restart] Started — checking every {check_hours}h, "
f"restart if idle > {idle_hours}h, watching {LOG_PATH}/", flush=True)
if __name__ == "__main__":
_start_auto_restart()
demo.queue(default_concurrency_limit=None).launch(
css=CUSTOM_CSS + COMPLETION_MODAL_CSS, head=_LOCKDOWN_FLAGS_JS + EMOJI_SWAP_HEAD + INPUT_LOCKDOWN_HEAD + HIDE_HF_WIDGET_HEAD + RECOVERY_HEAD + TUTORIAL_HEAD,
show_error=True,
)