C / app.py
linxinhua's picture
Fix auto-restart watchdog (strptime parsing log filenames with new _<sessioncode> suffix), SyntaxWarning (\s in JS-inside-Python string), and pin python_version to 3.11 (avoids Python 3.14 asyncio cleanup noise with Gradio 6.x).
c875c14 verified
Raw
History Blame Contribute Delete
108 kB
"""Gradio for the HOT No-AI Control condition.
Same UI shape as socratic / explanatory (chatbot panel left, argument
textbox right, end-session button) so the visual confound across the three
conditions is minimised. The difference is delivery: this condition has
no chat. After the participant submits their initial argument, the host
code calls the same `core.perfect_answer.generate_session_artifacts`
generator the bot conditions use, then renders the resulting essay as a
single piece of reading material in the chatbot panel.
Phases (implicit, driven by button clicks):
Phase 1 (entry): chatbot shows the case; arg_input writes initial argument.
Phase 2 (after Submit Initial confirm): host code runs the per-session
generator (around 15-30s blocking call, status message
shown). On success, two assistant messages appear: a
short intro line and the ~600-word perfect-answer essay.
arg_input becomes a notepad.
Phase 3 (after End Session): notepad locked, done panel shown.
The discussion plan is generated as a side-output of the same generator
call and is logged at the top level of the session JSON for analyst use.
The participant never sees it; there is no bot agenda in this condition.
Schema 1.0 envelope is identical to socratic / explanatory: `condition`,
`run_mode`, `case_id`, `perfect_answer`, `discussion_plan`, `feedback`,
`essays`, `turns`. `turns` is always empty for this condition.
"""
import time
import gradio as gr
from core import SessionLogger, now_aest, get_next_client
from core.config_loader import BASE_DIR, CONFIG
# ============================================================
# Lockdown config (revise-check gate)
# ============================================================
_LOCKDOWN_CFG = (CONFIG.get("lockdown") if isinstance(CONFIG, dict) else None) or {}
LOCKDOWN_REVISE_CHECK = bool(_LOCKDOWN_CFG.get("revise_check", False))
print(f"[lockdown] revise_check={LOCKDOWN_REVISE_CHECK}", flush=True)
# Revise-check gate: word-level similarity ratio between initial argument
# and current argument. > REVISE_SIMILARITY_THRESHOLD means the participant
# has not revised enough (changed less than 10% of words) — block End
# Session with a modal asking them to revise more.
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>'
# ============================================================
# 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 + 'Start walkthrough'),
(2) a mixed walkthrough carousel that interleaves image slides and
a Msg2 text slide; footer has Back + Next buttons, with 'Start'
replacing Next on the last slide.
Slides in order (no_ai condition):
1-3: tutorial images 01..03
4: Msg2 text panel (reference-version explanation)
5-6: tutorial images 04..05
All advance buttons share the orange Gradio primary-button color.
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.
try {
var raw = localStorage.getItem('non_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 HTML — kept here as a constant for easy edit. no_ai variant
// describes the reference-version flow (no chatbot discussion).
var MSG2_HTML =
'The system will generate a reference version based on your ' +
'initial argument. This reference is meant to help you reflect ' +
'on and improve your reasoning.<br><br>' +
'Read the reference at your own pace.<br>' +
'Take from it what is useful, and <b>revise your argument</b> ' +
'on the right.<br>' +
'When you are ready, submit your final revised version.';
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;
// no_ai slide deck: image, image, image, text(Msg2), 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: '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() {
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 (`non_ca_session_v1` / `non_ca_tab_id`) so other A_Ethic
# Spaces opened in the same browser do not collide. Since non-ca has no chat
# (the participant reads the AI-generated essay and revises their argument),
# the touch-observer watches for clicks anywhere on the chatbot (covers
# aha/ugh reactions) and arg_input edits to keep `last_touched` fresh.
# ============================================================
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 = 'non_ca_session_v1';
const TAB_KEY = 'non_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() {
// no_ai has no chat input — touch on any chatbot click (reactions)
// and on arg_input keystrokes (which are the dominant activity in
// this condition).
document.addEventListener('click', function(e) {
const cb = e.target.closest('#chatbot-main, #chatbot-main *');
if (cb) touchSession();
}, true);
document.addEventListener('input', function(e) {
const ta = e.target.closest('#right-essay textarea, #right-essay input');
if (ta) 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>
"""
# ============================================================
# Revise-check gate: modal styling + JS watcher + a flags block so the
# watcher can early-return when revise_check is OFF in config.
# ============================================================
_LOCKDOWN_FLAGS_JS = f"""<script>
window.__LOCKDOWN = {{
reviseCheck: {str(LOCKDOWN_REVISE_CHECK).lower()}
}};
</script>"""
REVISE_GATE_HEAD = """
<style>
/* Revise-check gate modal — shown when the participant tries End Session
with an argument too similar to their initial submission. */
#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;
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: var(--button-primary-background-fill, #f59e0b);
color: var(--button-primary-text-color, #fff);
border: none;
border-radius: 8px;
padding: 12px 28px;
font-size: 1.05em;
cursor: pointer;
transition: filter 0.15s ease;
}
#revise-gate-overlay .revise-gate-btn:hover {
background: var(--button-primary-background-fill-hover, #d97706);
filter: brightness(0.95);
}
</style>
<script>
// --- Revise-check gate modal watcher ---
// Server emits <div id="revise-gate-trigger-NONCE"> in the done_panel when
// the participant clicks End Session but their current argument is still
// > 90% similar to the initial submission. Watcher creates a full-screen
// modal; the "Go back and revise" button dismisses it so they can edit.
(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();
}
})();
</script>
"""
from core.content_sync import sync_chapters_from_ssot
from core.perfect_answer import generate_session_artifacts
# 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()
# ============================================================
# 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 if any future flow needs it.
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)
INTRO_MESSAGE = (
"**Thanks for submitting your initial argument.**\n\n"
"Below is a more developed and refined version based on your argument. "
"Read it carefully, and decide how, or whether, you want to use it "
"when revising your argument on the right.\n\n"
"When you are happy with your revised version, click "
"**'End session & finalize'** on the right to lock your submission "
"and end the session."
)
# ============================================================
# 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
# ============================================================
# 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 = """
/* 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. */
#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. */
#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. */
/* Extend Gradio container to full browser width. */
.gradio-container, .main, .wrap {
max-width: 100% !important;
}
.gradio-container {
padding-left: 12px !important;
padding-right: 12px !important;
}
/* Right column: keep it inside the row's equal_height stretch. */
#right-col {
gap: 4px !important;
}
/* Argument textbox: outer block has explicit 65vh height so the inner
absolute-positioned textarea has a real container to fill. */
#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;
}
#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;
}
/* Custom label row: strip Gradio block padding + clamp with max-height
so the row is exactly one line tall. */
#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;
}
/* 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 uses flex-end so Send stays at the bottom
of the (possibly grown) input; action col stays centred. */
#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;
}
#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;
}
/* Old .discussion-intro-title/body/feedback removed — replaced by compact
2-line .discussion-intro-line layout above. */
/* Force the like/dislike buttons (which we repurpose as ✨/😳) to always
be visible — Gradio's default is hover-only. Larger hit area too. */
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;
}
/* Highlight the currently-selected ✨/😳 button on a message. The
data-emoji-active attribute is toggled by the click handler in
EMOJI_SWAP_HEAD; same-emoji second click clears it (cancel). */
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 = """
<script>
(function() {
// Find the controls container that scopes a single message's aha!/ugh. pair.
// Gradio renders both buttons as siblings; we clear the sibling when one
// is activated so the pair is mutually exclusive per message.
const findGroup = (btn) => btn.parentElement || btn;
const onEmojiClick = (e) => {
const btn = e.currentTarget;
const wasActive = btn.dataset.emojiActive === '1';
// Clear active state on all swapped buttons in the same group.
findGroup(btn).querySelectorAll('button[data-emoji-swapped="1"]').forEach(b => {
b.removeAttribute('data-emoji-active');
});
// Same-emoji second click = cancel; otherwise activate this one.
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 = [
'dislike', 'thumbs down', 'thumb down',
'unhelpful', 'not helpful', 'mark as dislike', 'rate down',
'gefällt mir nicht', 'nicht gefällt', 'daumen runter', 'daumen nach unten',
"je n'aime pas", "n'aime pas", 'pouce vers le bas', 'pouce en bas',
'no me gusta', 'no gusta', 'pulgar abajo', 'pulgar hacia abajo',
'não gostei', 'descurtir', 'não gosto', 'polegar para baixo',
'non mi piace', 'pollice giù',
'踩', '不喜欢', '不赞', '点踩',
'不讚', '不喜歡', '倒讚',
'नापसंद', 'napasand', 'na pasand',
'よくない', '良くない', '싫어', 'не нравится',
];
const LIKE_TOKENS = [
'like', 'thumbs up', 'thumb up',
'helpful', 'mark as like', 'rate up',
'gefällt mir', 'daumen hoch', 'daumen nach oben',
"j'aime", 'aime', 'pouce vers le haut', 'pouce en haut',
'me gusta', 'pulgar arriba', 'pulgar hacia arriba',
'gostei', 'curtir', 'gosto', 'polegar para cima',
'mi piace', 'pollice su',
'赞', '喜欢', '点赞',
'讚', '喜歡',
'पसंद', 'pasand',
'いいね', '좋아', 'нравится',
];
const matchTokens = (s, tokens) => {
for (const k of tokens) {
if (s.indexOf(k) !== -1) return true;
}
return false;
};
const detectKind = (btn) => {
if (btn.querySelector('svg[class*="thumbs-up"]')) return 'like';
if (btn.querySelector('svg[class*="thumbs-down"]')) return 'dislike';
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';
}
const al = (btn.getAttribute('aria-label') || '').trim().toLowerCase();
if (al) {
if (matchTokens(al, DISLIKE_TOKENS)) return 'dislike';
if (matchTokens(al, LIKE_TOKENS)) return 'like';
}
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);
}
};
// aha (like) must sit on the LEFT, ugh (dislike) on the RIGHT. Gradio's
// default sibling order is not guaranteed, so enforce it; only move when
// out of order to avoid per-tick DOM churn.
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();
};
// Run every 400ms — cheap, and catches buttons no matter when Gradio renders them.
setInterval(sweep, 400);
// Also run on DOM ready in case the interval hasn't ticked yet.
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() {
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');
}
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';
}
update();
}
setInterval(attach, 500);
if (document.readyState !== 'loading') attach();
else document.addEventListener('DOMContentLoaded', attach);
})();
</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>
/* Broad CSS targeting HF Spaces injected chrome. Class names are unstable
so we shotgun common patterns, and also nuke any anchor that links back
to huggingface.co at the top level. */
.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"],
[class*="HfSpace"],
[class*="SpaceHeader"],
[class*="SpaceTag"],
[id*="space-header"],
[id*="hf-spaces"],
[data-testid*="space-header"],
[data-testid*="space-info"] {
display: none !important;
visibility: hidden !important;
pointer-events: none !important;
height: 0 !important;
width: 0 !important;
overflow: hidden !important;
}
/* Body-direct anchors to HF (the floating "powered by" badge usually links there) */
body > a[href*="huggingface.co"],
body > a[href*="hf.co"] {
display: none !important;
}
</style>
<script>
(function() {
// HF injects a floating widget on .hf.space direct URLs. Class names
// change, so we use 3 detection strategies:
// (1) text signatures (repo path, "Built with", "Hugging Face"),
// (2) link signature (contains a link to huggingface.co / hf.co),
// (3) position heuristic (small fixed/absolute element in a corner,
// not inside our gradio container, not our own toast).
const SIGNATURES = [
'AE-Talk-bot/',
'huggingface.co/',
'hf.co/',
'Hugging Face',
'Built with',
];
const SAFE_IDS = new Set([
'root', 'gradio-app',
'__arg_lockdown_toast__'
]);
function isSafe(el) {
if (!el) return true;
if (SAFE_IDS.has(el.id)) return true;
if (el.classList && el.classList.contains('gradio-container')) return true;
if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' ||
el.tagName === 'LINK' || el.tagName === 'META' ||
el.tagName === 'NOSCRIPT' || el.tagName === 'IFRAME') return true;
// If the element CONTAINS our gradio root, it must not be hidden
if (el.querySelector && el.querySelector('.gradio-container, #root, #gradio-app, gradio-app')) return true;
return false;
}
function looksLikeHfWidget(el) {
if (!el || el.nodeType !== 1) return false;
if (isSafe(el)) return false;
const txt = (el.textContent || '').trim();
// Strategy 1: text signatures (small badge text only)
if (txt.length > 0 && txt.length < 400) {
for (const sig of SIGNATURES) {
if (txt.includes(sig)) return true;
}
}
// Strategy 2: contains a link to HF
if (el.querySelector && el.querySelector('a[href*="huggingface.co"], a[href*="hf.co"]')) {
return true;
}
// Strategy 3: HF-shaped class / id names
const cls = (el.className && el.className.toString) ? el.className.toString() : '';
if (/(^|[^a-z])(hf|huggingface)[-_]/i.test(cls)) return true;
if (/space[s-]?(header|tag|banner|card|info|badge|widget|overlay)/i.test(cls)) return true;
const idAttr = el.id || '';
if (/(^|[^a-z])(hf|huggingface)[-_]/i.test(idAttr)) return true;
// Strategy 4: position heuristic for small floating badges
try {
const style = window.getComputedStyle(el);
if ((style.position === 'fixed' || style.position === 'absolute') &&
txt.length > 0 && txt.length < 200) {
const rect = el.getBoundingClientRect();
if (rect.width > 0 && rect.width < 400 &&
rect.height > 0 && rect.height < 120) {
const inCorner =
(rect.top < 120 || rect.bottom > window.innerHeight - 120) &&
(rect.left < 120 || rect.right > window.innerWidth - 120);
if (inCorner) return true;
}
}
} catch (e) { /* ignore */ }
return false;
}
function nuke(el) {
try {
el.style.setProperty('display', 'none', 'important');
el.style.setProperty('visibility', 'hidden', 'important');
el.setAttribute('hidden', '');
console.log('[hf-widget-hide] removed', el.tagName, el.id || '', el.className || '');
} catch (e) { /* ignore */ }
}
function sweep() {
if (!document.body) return;
// Direct body children first
Array.from(document.body.children).forEach(el => {
if (looksLikeHfWidget(el)) nuke(el);
});
// Also check direct html children (some injection patterns put nodes there)
Array.from(document.documentElement.children).forEach(el => {
if (el.tagName === 'BODY' || el.tagName === 'HEAD') return;
if (looksLikeHfWidget(el)) nuke(el);
});
// Sweep any body-level <a> pointing to HF
document.querySelectorAll('body > a[href*="huggingface.co"], body > a[href*="hf.co"]').forEach(nuke);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', sweep);
} else {
sweep();
}
function attachObserver() {
if (!document.body) return;
const obs = new MutationObserver(sweep);
obs.observe(document.body, { childList: true, subtree: false });
obs.observe(document.documentElement, { childList: true, subtree: false });
}
if (document.body) {
attachObserver();
} else {
document.addEventListener('DOMContentLoaded', attachObserver);
}
// Fallback: re-sweep every 1.5s for the first 30s, in case HF injects late
let ticks = 0;
const iv = setInterval(() => {
sweep();
if (++ticks >= 20) clearInterval(iv);
}, 1500);
})();
</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>'
FEEDBACK_HINT_HTML = (
'<div class="discussion-intro">'
'<div class="discussion-intro-title">How to use this reading</div>'
'<div class="discussion-intro-line">'
'<b>1.</b> The AI will provide you with a discussion of the case, '
'generated based on your argument. Read it carefully. While reading, '
'<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> Read it <b><i><u>at your own pace</u></i></b>; take from '
'it what\'s useful to you.'
'</div>'
'<div class="discussion-intro-line">'
'<b>3.</b> The reading takes a moment to generate. Please wait, '
'it\'s being written specifically for your argument.'
'</div>'
'<div class="discussion-intro-line">'
'<b>4.</b> While reading, you can tag passages:'
'<ul class="discussion-intro-bullets">'
'<li>Click ' + _AHA_INLINE_SVG + ' if a passage <b><i><u>helped'
'</u></i></b> you notice or rethink something new.</li>'
'<li>Click ' + _UGH_INLINE_SVG + ' if a passage 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>'
)
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,
)
# See socratic/app.py for full commentary. JS that takes over scroll behavior
# from Gradio's built-in autoscroll (we set autoscroll=False on the Chatbot):
# initial load → top; new content → bottom (via MutationObserver).
_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;
}
inner.scrollTop = 0;
setTimeout(() => { inner.scrollTop = 0; }, 200);
setTimeout(() => { inner.scrollTop = 0; }, 600);
setTimeout(() => { inner.scrollTop = 0; }, 1200);
setTimeout(() => {
const obs = new MutationObserver(() => {
inner.scrollTop = inner.scrollHeight;
});
obs.observe(inner, {
childList: true, subtree: true, characterData: true
});
}, 1600);
};
setup();
}
"""
with gr.Blocks(title="C", fill_height=True) as demo:
# ====== TOP ROW: reading | argument/essay textbox ======
# guide-col (yellow feedback hint) is visible=False — collapsed by
# Gradio so the chatbot panel expands to the left edge.
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 receive a more developed "
"version of your argument.\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: action buttons (right column only) ======
# Top guide-col is visible=False (collapses), so top row is 3:2. Bottom
# row drops the scale=1 mirror and keeps scale=3 empty + scale=2 action
# col so action buttons stay under the right-col argument textbox.
with gr.Row(equal_height=True):
with gr.Column(scale=3):
pass # left column intentionally empty (mirrors chatbot above)
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 states
arm_state = gr.State(0.0)
revert_timer = gr.Timer(value=2.5, active=False)
submit_initial_arm_state = gr.State(0.0)
submit_initial_revert_timer = gr.Timer(value=2.5, active=False)
# Periodic notepad snapshot timer (no_ai only). Fires every 60s while
# active. Activated when submit_initial confirms, deactivated when
# end_session confirms. Captures argument-revision trajectory in the
# reading-only condition where there are no per-event triggers like
# chat_send. Server-side; doesn't fire when browser tab is closed.
snapshot_timer = gr.Timer(value=60.0, active=False)
# Per-session SessionLogger. Lazy-init guard for gradio_client (which
# bypasses demo.load); pin via the State output every handler call.
logger_state = gr.State()
# Hidden Textbox carrying walkthrough-finished timestamp from JS to
# the on_submit_initial handler via the submit button's js= wrapper.
walkthrough_ts_input = gr.Textbox(
value="",
visible=False,
elem_id="walkthrough-ts-input",
)
done_panel = gr.HTML(value="", visible=False)
# ============================================================
# Handlers
# ============================================================
def on_submit_initial(arg_text, history, arm_at, logger, walkthrough_ts):
"""Phase 1 → Phase 2 with 2-click confirmation.
`walkthrough_ts` is the unix-seconds string captured client-side
at the walkthrough's "Start" click; injected via the submit
button's js= wrapper.
Outputs (10): chatbot, arg_input, submit_initial_btn, end_session_btn,
submit_initial_arm_state, submit_initial_revert_timer,
logger_state, snapshot_timer, arg_label_row,
recovery_payload
"""
if logger is None:
logger = SessionLogger()
now = time.time()
if arm_at and (now - arm_at) <= ARM_TTL:
logger.start_session()
# Round-robin assign one OpenAI key from the pool for the
# essay generation. Stored on the logger so the assignment
# is preserved across recovery and persisted in the JSON log.
try:
_key_idx, _session_client = get_next_client()
logger.set_assigned_key(_key_idx)
logger._session_oai_client = _session_client
print(f"[key_pool] session {logger.session_id} -> key_idx={_key_idx}",
flush=True)
except Exception as _e:
logger._session_oai_client = None
print(f"[key_pool] failed to assign key: {_e}", flush=True)
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.set_essay("argument", arg_text)
logger.add_argument_snapshot(
trigger="submit_initial_confirm",
text=arg_text,
)
# Yield 1: append participant arg + status; flip phase-2 layout;
# disable both action buttons during generation. Snapshot timer
# stays inactive during the 15-30s generator wait.
# 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": "user", "content": arg_text},
{"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),
0.0,
gr.update(active=False),
logger,
gr.update(active=False),
gr.update(value=ARG_LABEL_PHASE2),
gr.update(value=save_payload),
)
# Generate the per-session essay + plan.
try:
arts = generate_session_artifacts(
arg_text,
client=getattr(logger, "_session_oai_client", None),
)
if arts.get("perfect_answer"):
logger.set_perfect_answer(arts["perfect_answer"])
if arts.get("discussion_plan"):
logger.set_discussion_plan(arts["discussion_plan"])
if arts.get("dominant_framework"):
logger.set_dominant_framework(arts["dominant_framework"])
print(f"[framework] {arts['dominant_framework']}", flush=True)
essay = arts.get("perfect_answer") or ""
except Exception as e:
print(f"[session_artifacts] generation failed: {e}", flush=True)
essay = ""
# Yield 2: clear status, show two assistant messages (intro + essay),
# enable end-session button, START the 60s notepad-snapshot timer.
if essay:
history_final = history + [
{"role": "user", "content": arg_text},
{"role": "assistant", "content": INTRO_MESSAGE},
{"role": "assistant", "content": essay},
]
else:
# Fallback if generation failed: show a graceful note.
history_final = history + [
{"role": "user", "content": arg_text},
{"role": "assistant",
"content": "*Discussion content could not be prepared. "
"Please end the session.*"},
]
yield (
history_final,
gr.update(),
gr.update(),
gr.update(interactive=True),
gr.update(),
gr.update(),
logger,
gr.update(active=True),
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(),
arm_at, gr.update(),
logger,
gr.update(),
gr.update(),
gr.update(),
)
return
# ARM
yield (
gr.update(),
gr.update(),
gr.update(value=SUBMIT_INITIAL_CONFIRM_LABEL, variant="stop"),
gr.update(),
now,
gr.update(active=True),
logger,
gr.update(),
gr.update(),
gr.update(),
)
def on_submit_initial_tick(arm_at):
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_end_session(arm_at, arg_text, logger):
"""2-click end-session/finalize. Generator: yields a 'saving…' state
first, then a final status reflecting whether the upload succeeded.
CONFIRM also stops the 60s periodic snapshot timer.
The 8th 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 (8): arg_input, end_session_btn, done_panel,
arm_state, revert_timer, snapshot_timer, arg_label_row,
recovery_payload
"""
now = time.time()
is_first_click = not (arm_at and (now - arm_at) <= ARM_TTL)
# Revise-check gate. Run only on first click and only when the
# `lockdown.revise_check` config flag is on. Compare current arg_text
# against the initial argument; if word-level similarity is > 0.9
# (i.e. the participant changed less than ~10%), show a modal asking
# them to revise more before finalising.
if LOCKDOWN_REVISE_CHECK and is_first_click and logger is not None:
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:
yield (
gr.update(),
gr.update(),
gr.update(value=_revise_gate_trigger_html(), visible=True),
arm_at,
gr.update(),
gr.update(),
gr.update(),
gr.update(), # recovery_payload (no event)
)
return
if arm_at and (now - arm_at) <= ARM_TTL:
yield (
gr.update(interactive=False),
gr.update(visible=False, value=END_SESSION_LABEL,
variant="secondary"),
gr.update(value=SAVING_PANEL_HTML, visible=True),
0.0,
gr.update(active=False),
gr.update(active=False),
gr.update(value=ARG_LABEL_LOCKED),
gr.update(), # recovery_payload (clear happens in next yield)
)
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()
modal_html = _completion_modal_html(flush_result)
import json as _json_local
yield (
gr.update(),
gr.update(),
gr.update(value=modal_html, visible=True),
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(value=_json_local.dumps({"event": "ended"})),
)
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(),
now,
gr.update(active=True),
gr.update(),
gr.update(),
gr.update(), # recovery_payload (no event)
)
def on_timer_tick(arm_at):
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_snapshot_tick(arg_text, logger):
"""Fires every 60s while snapshot_timer is active (between
submit_initial_confirm and end_session_confirm). Records the current
notepad state with trigger='periodic_1min'. Pure local + HF persistence;
no LLM involvement. Intended for the no_ai control where the
participant is reading the perfect-answer essay and may revise their
argument over many minutes without producing chat / feedback events
that would otherwise trigger snapshots."""
if logger is None or not logger.session_id:
return
logger.add_argument_snapshot(
trigger="periodic_1min",
text=arg_text,
)
def on_feedback(arg_text, logger, data: gr.LikeData):
"""Every click is recorded as a timestamped event in the feedback list;
clicking the already-active emoji cancels the reaction (logged as
kind='none'). Logger derives feedback_current at upload time. Also
snapshots the notepad textbox at click time for revision tracking."""
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.
no_ai has no chat turns — sessions consist of the reference essay
(perfect_answer) plus the participant's argument-revision history.
Recovery rebuilds the chatbot as
[case, user_arg, INTRO_MESSAGE, perfect_answer], restores the
argument textbox to the latest snapshot, re-enables End Session,
and re-starts the 60s notepad-snapshot timer.
Outputs (10): same shape as on_submit_initial — chatbot, arg_input,
submit_initial_btn, end_session_btn,
submit_initial_arm_state, submit_initial_revert_timer,
logger_state, snapshot_timer, arg_label_row,
recovery_payload
"""
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(9))
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")
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)")
# Restore the per-session OpenAI client by looking up the assigned
# key index in the current pool. If we can't find a match, get a
# fresh round-robin assignment.
from core.config_loader import KEY_POOL as _KP
_restored_client = None
for _idx, _c in _KP:
if _idx == new_logger.assigned_key_idx:
_restored_client = _c
break
if _restored_client is None:
try:
_new_idx, _restored_client = get_next_client()
new_logger.set_assigned_key(_new_idx)
print(f"[recover] re-assigned key_idx={_new_idx}", flush=True)
except Exception as _e:
print(f"[recover] could not assign client: {_e}", flush=True)
new_logger._session_oai_client = _restored_client
initial_arg = (data.get("essays") or {}).get("argument", {}).get("text", "")
pa = data.get("perfect_answer") or {}
essay = pa.get("text", "")
# Rebuild the chatbot: case display + user argument + intro + essay
# (mirroring on_submit_initial yield 2). If essay generation had
# failed in the original session, fall back to the same note shown
# at that time.
history = list(INITIAL_CHATBOT_VALUE) + [
{"role": "user", "content": initial_arg},
]
if essay:
history.append({"role": "assistant", "content": INTRO_MESSAGE})
history.append({"role": "assistant", "content": essay})
else:
history.append({
"role": "assistant",
"content": "*Discussion content could not be prepared. "
"Please end the session.*",
})
snapshots = data.get("argument_snapshots") or []
arg_text = snapshots[-1].get("text") if snapshots else initial_arg
print(f"[recover] OK: sid={sid}, "
f"essay={'yes' if essay else 'no'}, "
f"{len(data.get('feedback') or [])} feedback events, "
f"{len(snapshots)} snapshots", flush=True)
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),
0.0,
gr.update(active=False),
new_logger,
gr.update(active=True), # restart snapshot_timer
gr.update(value=ARG_LABEL_PHASE2),
gr.update(value=save_payload),
)
# ============================================================
# Wire events
# ============================================================
initial_outputs = [
chatbot,
arg_input,
submit_initial_btn,
end_session_btn,
]
_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, submit_initial_arm_state, logger_state, walkthrough_ts_input],
outputs=initial_outputs + [submit_initial_arm_state,
submit_initial_revert_timer, logger_state,
snapshot_timer, arg_label_row,
recovery_payload],
js="""(arg_text, history, arm_at, logger, ts_in) => {
var ts = window.__walkthroughStartedAt;
return [arg_text, history, 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,
snapshot_timer, 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],
)
end_session_btn.click(
on_end_session,
inputs=[arm_state, arg_input, logger_state],
outputs=[arg_input, end_session_btn, done_panel, arm_state, revert_timer,
snapshot_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],
)
# 60s periodic notepad snapshot — only the no_ai condition needs this
# because the reading flow has no chat_send / few feedback events to drive
# event-based snapshots. Active between submit_initial_confirm (yield 2)
# and end_session_confirm.
snapshot_timer.tick(
on_snapshot_tick,
inputs=[arg_input, logger_state],
outputs=None,
)
# ✨ aha / 😳 stress reactions on the perfect-answer essay (and the
# intro message; participants may click on either, both are logged).
# arg_input passed so notepad gets snapshotted at click time.
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,
)
def _start_auto_restart():
"""Background thread: poll the HF dataset for the latest session log;
if the latest is older than `idle_threshold_hours`, restart the Space.
Same machinery as socratic / explanatory."""
import os
import threading
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)
# Thread-uptime fallback: if the dataset has no logs yet (fresh Space, no
# participants) we still want to restart once the Space itself has been
# running ≥ idle_hours, otherwise zero-log Spaces never auto-recover.
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 + HIDE_HF_WIDGET_HEAD + RECOVERY_HEAD + TUTORIAL_HEAD + REVISE_GATE_HEAD,
)