Spaces:
Running
One belief page about every partner, and a points screen per block
Browse filesFrom our user's second review of the run.
The belief question is asked once, at the end of the study, about every
partner, one Yes/No each, in words that fit what could happen to that person.
Split across the two batteries it was asked twice and still missed a partner
each time, because the other task's partner belongs to neither battery. A
liking slider per partner sits with it, since both are about the people rather
than about either task. Both defer to whichever task finishes second, the way
the TriPM and demographics already do, so the handoff's partner rows now carry
a fourth field saying what kind of partner each one was. Three fields still
decode, so the two deploys can straddle.
Each block has its own points screen before its own questions, naming only
that block's two people: the day pair kept theirs, the night harvest had none
at all and its result appeared only on the very last screen of the study.
Every screen that says what somebody got now shows that person's picture, the
avatar they were introduced with. The other task's partners go without: their
explorers are drawn by art this app does not have, and redrawing them as
farmers would show a different-looking person from the one they met.
The rest phase no longer quotes its own pay. It read "+2 credits for YOU" for
ten seconds while the work phase showed nothing, so the two options were
described differently while they were being played.
The quiz's revisit screen states the question above each answer. The answer
alone reads as a statement out of nowhere when more than one item was missed.
TriPM and demographics items each sit in their own full-width left-aligned
column with the question above the scale. The page centred everything, so a
short item sat beside its own options and a long one above them.
And the matched screen says which partner in the study this one is, when the
handoff said how many came before.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Files changed (10)
- analysis/pe_analysis/loader.py+8-6
- docs/SESSION_STRUCTURE.md+19-8
- effort_stages.py+186-41
- order_link.py+28-10
- questionnaires.py+132-85
- static/cornfield.js+7-8
- test_handoff_night_block.py+14-5
- test_night_watch_onboarding.py+67-28
- test_quiz_option_order.py+40
- web_app.py+28-22
46 unmodified lines47484950515253545556575859606146 unmodified lines# The night harvest and the battery that asks about it. Both sit after# the day task's questions, because each block is asked about once it has# been played rather than both at the end."NightWatchPractice", "NightWatch","Fatigue_night", "Night_NASA_TLX", "Night_Effort_impact","Night_PostTask_Motivation", "Night_PostTask_Effort2","Night_PostTask_TaskRating", "Night_PostTask_Strategy",# Both belief checks go last, after every other question. Asking whether# the other person was real, in the middle of a battery, tells the# participant there is something to doubt, and everything after it is# answered by someone who has just been invited to suspect the study."TriPM", "Demographics", "PostTask_Belief", "Night_PostTask_Belief",]46 unmodified lines474849505152535455565758596061626346 unmodified lines# The night harvest and the battery that asks about it. Both sit after# the day task's questions, because each block is asked about once it has# been played rather than both at the end."NightWatchPractice", "NightWatch", "NightQuestionnaireTransition","Fatigue_night", "Night_NASA_TLX", "Night_Effort_impact","Night_PostTask_Motivation", "Night_PostTask_Effort2","Night_PostTask_TaskRating", "Night_PostTask_Strategy",# The questions about the PEOPLE, then the ones about the participant. One# belief page covering every partner, including the other task's, because# split across the two batteries it was asked twice and still missed a# partner each time. After everything that asks about the tasks, because# asking whether the other person was real tells the participant there is# something to doubt."PostTask_Belief", "PostTask_Liking", "TriPM", "Demographics",]
110 unmodified lines111112113114115116117118119120121122123124125126110 unmodified lines| Screen | What it asks ||---|---|| TriPM | 58 items, in a per-participant order. The individual-difference measure H3 and H5 are tested against. || Demographics | After the TriPM. || Belief (day) | Did they believe the day partner would really receive the credits. || Belief (night) | Did they believe the night partner would really lose the credits shown. || Completed | Final screen with all purses and the payment reference code. |Both belief checks go last, after every other question. Asking whether theother person was real, mid-battery, tells the participant there is somethingto doubt, and everything after it is then answered by someone who has justbeen invited to suspect the study.Every questionnaire page can be left blank. It asks "are you sure" andrecords which items were untouched, because the consent says participants110 unmodified lines111112113114115116117118119120121122123124125126127128129130131132133134135136137110 unmodified lines| Screen | What it asks ||---|---|| Belief | One Yes/No per partner, every partner the participant has met. || Liking | One 0-100 slider per partner. || TriPM | 58 items, in a per-participant order. The individual-difference measure H3 and H5 are tested against. || Demographics | After the TriPM. || Completed | Final screen: YOU and every partner, each named, pictured, and settled, plus the payment reference code. |The belief check comes after everything that asks about either task. Askingwhether the other person was real tells the participant there is something todoubt, and anything after it is answered by someone who has just been invitedto suspect the study. Only the TriPM and the demographics follow it, neitherof which is about the tasks.All four of those are asked once per STUDY, not once per task: in the combinedSONA session they are deferred to whichever task the participant finishessecond, so the belief and liking questions can name every partner from bothtasks. The partners of the other task reach this one on the handoff, signed.Each block has its own points screen before its own questions, naming onlythat block's two people: the day pair after the evening harvest, the nightpair after the night harvest, and the treasure hunt's pair in that task. Thescreen that accounts for everybody is the last one of the study.Every questionnaire page can be left blank. It asks "are you sure" andrecords which items were untouched, because the consent says participants
65 unmodified lines6667686970717273747576777874 unmodified lines15315415515615715820 unmodified lines1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082099 unmodified lines219220221222223224222 unmodified lines4474484494504514521 unmodified line454455456457458459460461462463464465878 unmodified lines1344134513461347134813491350281 unmodified lines1632163316341635163616371 unmodified line163916401641164216431644164516461647164816491650165116521653165416551656165716581659166065 unmodified lines{switch}"""def howtoplay_1_text():return f"""## You've been matched!We have randomly picked an **anonymous stranger{_partner_age_phrase()} from ourcommunity database**. This person will be YOUR PARTNER.On some rounds you'll play for YOURSELF, and on others you'll play for YOUR PARTNER.YOU make all the choices. YOUR PARTNER doesn't play.74 unmodified lines"""async def credits_bridge_display(stage, container):"""Shown once, right before the post-game questionnaire starts: credit totals + moneyconversion for the game that just finished (with the finish-splash picture), plus a20 unmodified lines'style="width:100%;max-width:620px;border-radius:12px;display:block;''margin:0 auto;background:#ffd58a;"></canvas>')ui.markdown("## 🌽 Harvest complete!")ui.markdown(f"### You earned **{self_pts} credits** for yourself → "f"**${to_money(self_pts):.2f}**")# Phrased as what the participant did, not as something the partner did.# They made every choice; the partner never played.ui.markdown(f"### You earned **{partner_pts} credits** for {partner_label_plain()} → "f"**${to_money(partner_pts):.2f}**")# The night partner is NOT earned for: nothing the participant did# could raise their total, only hold down what they lost. "You earned# 0 credits for them" describes a game that was never played._e = earnings_summary()if _e.get("night_partner_points") is not None:_lost = D.WATCH_ENDOWMENT - _e["night_partner_points"]ui.markdown(f"### {partner_label_plain('night').capitalize()} lost "f"**{_lost} of their {D.WATCH_ENDOWMENT} credits** during the "f"Night Harvest, and keeps "f"**${_e['night_partner_bonus']:.2f}**")ui.markdown(f"*Settled from the {_e['nights_paid']} of "f"{_e['nights_total']} nights drawn at random.*")ui.markdown("Next, a few questions about the game you just played.")ui.button("Continue", on_click=lambda: ev.set()).props("color=primary size=lg")try:9 unmodified lineseasiest_success_rate=(round(eas, 4) if eas is not None else None))def fmt(md):"""Fill in the partner id placeholder."""return md.format(random_id=app.storage.user.get("random_id", "Player 2"))222 unmodified lines# would put a number on screen that no trial produced.ids.append(app.storage.user["random_id_2"])rows = [{"id": ", ".join(ids), "where": "the daytime harvest","earned": float(e["partner_bonus"]), "lost": 0.0,"kept": float(e["partner_bonus"])}]if e.get("night_partner_points") is not None:1 unmodified linerows.append({"id": (app.storage.user.get("random_id_night")or night_partner_id()),"where": "the Night Harvest","earned": 0.0,"lost": max(0.0, D.WATCH_ENDOWMENT / 25.0 - kept),"kept": kept})return rowsdef easiest_level_success():"""Success rate at the easiest effort level, or None if never attempted."""n = int(app.storage.user.get("easiest_attempts", 0))878 unmodified linesNIGHT_WATCH_PRACTICE_STAGE = "NightWatchPractice"#: The battery that asks about the night harvest. Skipped with the block#: itself: a day-only session must not be asked about a task it never saw.NIGHT_QUESTION_STAGES = frozenset(['Fatigue_night', 'Night_NASA_TLX', 'Night_Effort_impact', 'Night_PostTask_Motivation', 'Night_PostTask_Effort2', 'Night_PostTask_TaskRating', 'Night_PostTask_Belief', 'Night_PostTask_Strategy'])def night_watch_on():281 unmodified lines# participant had not reached._night_watch_practice_stage(),_night_watch_stage(),Q.fatigue_stage("night"),Q.nasa_tlx_stage("night"),Q.effort_impact_stage("night"),1 unmodified lineQ.effort_exerted_stage("night"),Q.task_rating_stage("night"),Q.strategy_stage("night"),# Demographics and the TriPM go LAST. Everything above asks about the# task the participant just did, and the belief check in particular is# worth asking while it is fresh; the trait measure is the longest# block here, so putting it earlier would spend their attention before# the task-relevant questions rather than after them.Q.tripm_stage(),Q.demographics_stage(),# The belief checks go LAST, after everything else has been answered.# They ask whether the participant believed the other person was real# and would really be paid, or really lose, and asking that in the# middle of a battery tells them there is something to doubt. Whatever# follows is then answered by someone who has just been invited to# suspect the study. Nothing comes after these, so there is nothing# left to contaminate. Both are asked here, each about its own block.Q.belief_stage("day"),Q.belief_stage("night"),]return SimpleExperiment(stages=stages, name="HarvestForTwo")65 unmodified lines66676869707172737475767778798081828384858687888990919293949596979874 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922020 unmodified lines2412422432442452462472482492502512522532542552562572582592609 unmodified lines270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323222 unmodified lines5465475485495505515521 unmodified line554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607878 unmodified lines1486148714881489149014911492281 unmodified lines17741775177617771778177917801 unmodified line17821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180565 unmodified lines{switch}"""def _partner_ordinal_phrase():""""your second partner in this study", when we can say which.A participant arriving from the other task has already met somebody, andthis screen said "we have randomly picked an anonymous stranger" as thoughit were the first time. Counted from the partners the other task actuallyhanded over, so an arrival that carried none says nothing rather thanguessing a number."""n = len(app.storage.user.get("other_task_partner_rows") or [])if not n:return ""word = {1: "second", 2: "third", 3: "fourth"}.get(n + 1)if not word:return ""return (f"\nThis is your **{word} partner** in the study, and a "f"**different person** from the one you played with in the other "f"task.\n")def howtoplay_1_text():return f"""## You've been matched!We have randomly picked an **anonymous stranger{_partner_age_phrase()} from ourcommunity database**. This person will be YOUR PARTNER.{_partner_ordinal_phrase()}On some rounds you'll play for YOURSELF, and on others you'll play for YOUR PARTNER.YOU make all the choices. YOUR PARTNER doesn't play.74 unmodified lines"""async def _people_lines(rows):"""One line per person, with that person's picture beside it.Every screen that tells the participant what somebody got shows who thatsomebody is. The ids alone (P2-63540) are not people; the avatar is theone the participant was shown when they were introduced.`rows` are {"md", "avatar", "self"}. A row with avatar None gets the sameindent and no picture, which is what the other task's partners get: theirexplorers are drawn by art this app does not have, and redrawing them asfarmers would show a different-looking person from the one they met."""faces = []for i, r in enumerate(rows):cid = f"pe_face_{i}"with ui.row().style("align-items:center; gap:14px; width:100%; ""max-width:620px; margin-bottom:4px;"):if r.get("avatar") is None:ui.html('<div style="width:64px;height:76px;"></div>')else:ui.html(f'<canvas id="{cid}" width="84" height="100" 'f'style="width:64px;height:76px;border-radius:8px;'f'background:#dff4d6;display:block;flex:0 0 auto;">'f'</canvas>')faces.append({"id": cid, "idx": int(r["avatar"]),"self": bool(r.get("self"))})ui.markdown(r["md"]).style("text-align:left;")if not faces:return# One round trip for every face. Each await is a round trip the# participant is looking at, and a screen that paints its pictures one by# one down the page is the same flash the canvas mount had.try:await ui.run_javascript("(function(a){if(!window.Cornfield)return;a.forEach(function(x){""(x.self?window.Cornfield.preview:window.Cornfield.""partnerAvatarPreview)(x.id,x.idx);});})(" + json.dumps(faces) + ")",timeout=10)except Exception:passasync def credits_bridge_display(stage, container):"""Shown once, right before the post-game questionnaire starts: credit totals + moneyconversion for the game that just finished (with the finish-splash picture), plus a20 unmodified lines'style="width:100%;max-width:620px;border-radius:12px;display:block;''margin:0 auto;background:#ffd58a;"></canvas>')ui.markdown("## 🌽 Harvest complete!")# This block's two people and nobody else. The night harvest has its# own screen after its own block, and the one screen that accounts for# everybody comes at the very end: a participant reading about a# partner here has not met the others yet.await _people_lines([{"md": f"### YOU earned **{self_pts} credits** → "f"**${to_money(self_pts):.2f}**","avatar": int(app.storage.user.get("avatar", 0)), "self": True},# Phrased as what the participant did, not as something the partner# did. They made every choice; the partner never played.{"md": f"### You earned **{partner_pts} credits** for "f"{partner_label_plain()} → **${to_money(partner_pts):.2f}**","avatar": _partner_avatar_idx()},])ui.markdown("Next, a few questions about the game you just played.")ui.button("Continue", on_click=lambda: ev.set()).props("color=primary size=lg")try:9 unmodified lineseasiest_success_rate=(round(eas, 4) if eas is not None else None))async def night_credits_bridge_display(stage, container):"""The night harvest's own points screen, before its own questions.The day task had one and the night block had none, so its result appearedonly on the very last screen of the study, after twenty minutes ofquestionnaires and, when this task ran first, after a handoff that used toforward by itself. This block's two people and nobody else: the day pairhad their screen after the day blocks, and the screen that accounts foreverybody is the last one of the study."""w = watch_settlement() or {}nicewebrl.clear_element(container)ev = asyncio.Event()to_money = lambda p: max(0.0, min(6.0, int(p) / 25.0))with container.style("align-items:center; max-width:720px;"):ui.markdown("## \U0001F319 The night is over")if not w:ui.markdown("Nothing was settled from this block.")else:await _people_lines([{"md": f"### YOU collected **{w['self_credits']} credits** "f"in the Night Harvest → "f"**${to_money(w['self_credits']):.2f}**","avatar": int(app.storage.user.get("avatar", 0)),"self": True},# Never "you earned N for them": nothing the participant did# could raise this person's total, only hold down what they# lost.{"md": f"### {partner_label_plain('night').capitalize()} lost "f"**{w['partner_lost']} of their "f"{D.WATCH_ENDOWMENT} credits**, and keeps "f"**${to_money(w['partner_credits']):.2f}**","avatar": (app.storage.user.get("partner_avatar_idx_night")if app.storage.user.get("partner_avatar_idx_night")is not None else night_partner_avatar_idx())},])ui.markdown(f"*Settled from the {w['nights_paid']} of "f"{w['nights_total']} nights drawn at random.*")ui.markdown("Next, a few questions about the night harvest.")ui.button("Continue", on_click=lambda: ev.set()).props("color=primary size=lg")await ev.wait()return dict(instructions="NightQuestionnaireTransition",night_self_credits=w.get("self_credits"),night_partner_lost=w.get("partner_lost"),nights_paid=w.get("nights_paid"),nights_total=w.get("nights_total"))def fmt(md):"""Fill in the partner id placeholder."""return md.format(random_id=app.storage.user.get("random_id", "Player 2"))222 unmodified lines# would put a number on screen that no trial produced.ids.append(app.storage.user["random_id_2"])rows = [{"id": ", ".join(ids), "where": "the daytime harvest","kind": "day", "avatar": _partner_avatar_idx(),"earned": float(e["partner_bonus"]), "lost": 0.0,"kept": float(e["partner_bonus"])}]if e.get("night_partner_points") is not None:1 unmodified linerows.append({"id": (app.storage.user.get("random_id_night")or night_partner_id()),"where": "the Night Harvest","kind": "night","avatar": (app.storage.user.get("partner_avatar_idx_night")if app.storage.user.get("partner_avatar_idx_night")is not None else night_partner_avatar_idx()),"earned": 0.0,"lost": max(0.0, D.WATCH_ENDOWMENT / 25.0 - kept),"kept": kept})return rows#: How the belief question is worded for each kind of partner. A partner you#: earned for is asked whether they would really receive it; the night#: harvest's partner could only ever lose, so "receive the credits you earned#: for them" describes a game that was never played with them.def _belief_question(row, where):if row.get("kind") == "night":return (f"During {where}, did you believe that **{row['id']}** would "f"really lose the credits shown on screen?")return (f"During {where}, did you believe that **{row['id']}** would "f"really receive the credits you earned for them?")def partner_roster():"""Every partner this participant has met, in the order they met them.This task's own, plus the other task's when its handoff carried them. Thebelief and liking questions are asked once, at the end of the study, aboutall of them, so they need one list rather than each block's own."""import order_linkmine = partner_rows()theirs = []for r in (app.storage.user.get("other_task_partner_rows") or []):theirs.append(dict(r, where="the treasure hunt",kept=max(0.0, 6.0 - float(r.get("lost", 0.0)))))first = app.storage.user.get("task_first")rows = theirs + mine if first != order_link.THIS_TASK else mine + theirsfor i, r in enumerate(rows, start=1):r["position"] = ir["question"] = _belief_question(r, r.get("where", "the study"))# Only this task can draw its own partners: the other app's people are# explorers, drawn by art this app does not have, and redrawing them as# farmers would show the participant a different-looking person from# the one they met.r["drawable"] = r.get("where") != "the treasure hunt"return rowsdef easiest_level_success():"""Success rate at the easiest effort level, or None if never attempted."""n = int(app.storage.user.get("easiest_attempts", 0))878 unmodified linesNIGHT_WATCH_PRACTICE_STAGE = "NightWatchPractice"#: The battery that asks about the night harvest. Skipped with the block#: itself: a day-only session must not be asked about a task it never saw.NIGHT_QUESTION_STAGES = frozenset(['NightQuestionnaireTransition', 'Fatigue_night', 'Night_NASA_TLX', 'Night_Effort_impact', 'Night_PostTask_Motivation', 'Night_PostTask_Effort2', 'Night_PostTask_TaskRating', 'Night_PostTask_Strategy'])def night_watch_on():281 unmodified lines# participant had not reached._night_watch_practice_stage(),_night_watch_stage(),_fb("NightQuestionnaireTransition", night_credits_bridge_display),Q.fatigue_stage("night"),Q.nasa_tlx_stage("night"),Q.effort_impact_stage("night"),1 unmodified lineQ.effort_exerted_stage("night"),Q.task_rating_stage("night"),Q.strategy_stage("night"),# --- the questions that are about the PEOPLE rather than about either# task, and then the ones about the participant. All four are deferred# to whichever task the participant finishes SECOND, so each is asked# once and the two partner ones can name every partner, this task's# and the other task's. A single-task session asks them here about its# own partners.## The belief check comes after everything that asks about the tasks:# asking whether the other person was real tells the participant there# is something to doubt, and anything after it is answered by someone# who has just been invited to suspect the study. Only the TriPM and# the demographics follow it, neither of which is about the tasks.Q.partner_belief_stage(),Q.partner_liking_stage(),# The trait measure is the longest block here, so it sits after the# task-relevant questions rather than spending their attention first.Q.tripm_stage(),Q.demographics_stage(),]return SimpleExperiment(stages=stages, name="HarvestForTwo")
118 unmodified lines1191201211221231241251261271281291301311321331341351362 unmodified lines1391401411421431441451461471482 unmodified lines151152153154155156157158159160161162118 unmodified lines"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_, ")def encode_partner_rows(rows):""""<id>:<earned>:<lost>|..." for the handoff.One entry per PERSON, not one total, so the task that finishes second canname each partner across both tasks and say what that person walked awaywith. Order is the order the participant met them."""out = []for r in rows or []:rid = "".join(c for c in str(r.get("id", ""))[:40] if c in _ROW_ID_OK)out.append(f"{rid}:{float(r.get('earned', 0)):.2f}"f":{float(r.get('lost', 0)):.2f}")return "|".join(out)2 unmodified linesdef verify_partner_rows(survey_code, rows_str, signature):"""[{"id", "earned", "lost"}] for a genuine encode_partner_rows string,else []. Never raises: a missing, unsigned or malformed list means theother task said nothing about its partners, and the screen then names onlythe ones this task knows about."""if not rows_str or not signature:return []expected = partner_list_signature(survey_code, rows_str)2 unmodified linesout = []for part in str(rows_str).split("|"):bits = part.split(":")if len(bits) != 3:return []rid = "".join(c for c in bits[0][:40] if c in _ROW_ID_OK)try:out.append({"id": rid, "earned": float(bits[1]),"lost": float(bits[2])})except ValueError:return []return out118 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471482 unmodified lines1511521531541551561571581591601611621631642 unmodified lines167168169170171172173174175176177178179180118 unmodified lines"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_, ")#: What kind of partner a row describes, which decides how the belief question#: about that person is worded. "hunt" and "day" are people the participant#: earned for; "night" is the one who could only lose. A row with no kind is#: read as earned-for, which is what the three-field version of this format#: carried before the belief questions moved to the end of the study._ROW_KIND_OK = set("abcdefghijklmnopqrstuvwxyz")DEFAULT_ROW_KIND = "earned"def encode_partner_rows(rows):""""<id>:<earned>:<lost>:<kind>|..." for the handoff.One entry per PERSON, not one total, so the task that finishes second canname each partner across both tasks, say what that person walked awaywith, and ask the belief question about them in the right words. Order isthe order the participant met them."""out = []for r in rows or []:rid = "".join(c for c in str(r.get("id", ""))[:40] if c in _ROW_ID_OK)kind = "".join(c for c in str(r.get("kind", DEFAULT_ROW_KIND))[:12]if c in _ROW_KIND_OK) or DEFAULT_ROW_KINDout.append(f"{rid}:{float(r.get('earned', 0)):.2f}"f":{float(r.get('lost', 0)):.2f}:{kind}")return "|".join(out)2 unmodified linesdef verify_partner_rows(survey_code, rows_str, signature):"""[{"id", "earned", "lost", "kind"}] for a genuine encode_partner_rowsstring, else []. Never raises: a missing, unsigned or malformed list meansthe other task said nothing about its partners, and the screen then namesonly the ones this task knows about.Three fields are accepted as well as four. That is the version deployedbefore the belief questions moved to the end of the study, and a run thatstraddles the two deploys should lose the wording, not the partner."""if not rows_str or not signature:return []expected = partner_list_signature(survey_code, rows_str)2 unmodified linesout = []for part in str(rows_str).split("|"):bits = part.split(":")if len(bits) not in (3, 4):return []rid = "".join(c for c in bits[0][:40] if c in _ROW_ID_OK)kind = (("".join(c for c in bits[3][:12] if c in _ROW_KIND_OK)or DEFAULT_ROW_KIND) if len(bits) == 4 else DEFAULT_ROW_KIND)try:out.append({"id": rid, "earned": float(bits[1]),"lost": float(bits[2]), "kind": kind})except ValueError:return []return out
349 unmodified lines350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422236 unmodified lines659660661662663664131 unmodified lines79679779879980080180231 unmodified lines83483583683783883984084160 unmodified lines9029039049059069079 unmodified lines91791891992092192292392492592692792892993093193293393493593693793893994094194294394455 unmodified lines100010011002100310041005100610071008349 unmodified linesreturn _fb(BLOCK_SUFFIX[block] + "PostTask_TaskRating", _display)def _belief_key(block):"""Distinct column names: the two answers mean different things, and oneoverwriting the other in the export would be silent."""return ("believed_night_partner_lost" if block == "night"else "believed_partner_paid")def belief_stage(block="day"):"""Manipulation check: did they believe the partner's payout was real?"""async def _display(stage, container):nicewebrl.clear_element(container)chosen = {"v": None}result = {"went_back": False}done = asyncio.Event()import effort_stages as Enight = (block == "night")with container.style("align-items:center; max-width:640px;"):# Heading dropped: the question is the instruction.# Each battery asks about its own block's partner. Asking both# on one page meant asking about a block the participant had not# reached yet, once the batteries were split.if night:nid = (app.storage.user.get("random_id_night")or E.night_partner_id())prompt = (f"During the Night Harvest, did you believe that "f"the other person (**{nid}**) would really lose "f"the credits shown on screen?")else:rid = app.storage.user.get("random_id", "Player 2")prompt = (f"During the daytime harvest, did you believe that "f"the other person (**{rid}**) would really receive "f"the credits you earned for them?")ui.markdown(prompt)radio = ui.radio({"Yes": "Yes", "No": "No"}).props("color=primary")with ui.row():ui.button("Back", on_click=lambda: (result.update(went_back=True), done.set())).props("outline")submit = ui.button("Submit")cont = ui.button("Continue", on_click=lambda: done.set())cont.set_visibility(False)async def go():if chosen["v"] is not None:return# Requested, not forced. The consent says participants are# free to refrain from answering any question, and every# other page in the battery already asks before letting an# unanswered one through. This one silently did nothing when# Submit was pressed with a blank, which reads as a broken# button rather than as a requirement.if radio.value is None and not await _confirm_skip():returnchosen["v"] = radio.valueradio.disable(); submit.disable(); cont.set_visibility(True)submit.on_click(go)await done.wait()if result["went_back"]:_go_back_one_stage()# chosen["v"] is only set once Submit is clicked; include it so an# already-submitted answer isn't discarded if this record happens# to be the last one written for this stage (same reasoning as the# slider-battery stages above).return dict(measure="belief_check", block=block, went_back=True,**{_belief_key(block): chosen["v"]})return dict(measure="belief_check", block=block,**{_belief_key(block): chosen["v"]})return _fb(BLOCK_SUFFIX[block] + "PostTask_Belief", _display)# ----------------------------------------------------------------------------236 unmodified lineschosen["idx"] = radio.valueok = (radio.value == correct_idx)lead = "✅ **Correct!** " if ok else "❌ **Not quite.** "fb.set_content(lead + item.get("explain", ""))radio.disable() # lock the optionssubmit.disable() # grey out submit after one choice131 unmodified lineswith container.style("align-items:center; max-width:680px;"):ui.markdown("### Not quite. Let's go through that again.")for it in wrong:ui.markdown(f"- {it['explain']}")ui.button("Try again", on_click=lambda: ev.set())await ev.wait()attempts += 131 unmodified linesev2 = asyncio.Event()with container.style("align-items:center; max-width:680px;"):ui.markdown("### Let's revisit the ones you got wrong!")for it in wrong:ui.markdown(f"- {it['explain']}")ui.button("OK", on_click=lambda: ev2.set())await ev2.wait()attempts += 160 unmodified linesreturn out["agreed"]def demographics_stage():"""Demographics, from content/demographics.txt."""async def _display(stage, container):9 unmodified linesui.markdown("Please answer the following questions about ""yourself.")ui.markdown("_You may leave any question blank._")for it in items:ui.markdown(f"**{it['question']}**")t = it["type"]if t == "number":w = ui.number().props("outlined").style("width:100%;")elif t == "choice":w = ui.radio(it["options"]).props("color=primary")elif t == "dropdown":# A radio grid of 20-odd income bands is a wall; a select is# the same question without the wall.w = ui.select(it["options"]).props("outlined").style("width:100%;")elif t == "multi":# Select all that apply -- race/ethnicity is not a single# choice, and forcing it into one loses people who are more# than one thing.w = ui.select(it["options"], multiple=True).props("outlined use-chips").style("width:100%;")elif t == "scale":w = ui.slider(min=0, max=100, value=50).props("label-always")else:w = ui.input().props("outlined").style("width:100%;")widgets[it["key"]] = (w, t)ui.button("Continue", on_click=done.set).props("color=primary size=lg")await done.wait()55 unmodified lineswith container.style("align-items:center; max-width:720px;"):ui.markdown("Please indicate how true each statement is of you.")warn = ui.markdown("")for key, text in items:ui.markdown(f"**{text}**")widgets[key] = ui.radio(TRIPM_SCALE).props("inline color=primary")async def submit():missing = [k for k, w in widgets.items() if w.value not in TRIPM_SCALE]349 unmodified lines350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441236 unmodified lines678679680681682683684685131 unmodified lines81781881982082182282382431 unmodified lines85685785885986086186286386486586686786860 unmodified lines9299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599 unmodified lines96997097197297397497597697797897998098198255 unmodified lines103810391040104110421043104410451046104710481049105010511052105310541055349 unmodified linesreturn _fb(BLOCK_SUFFIX[block] + "PostTask_TaskRating", _display)#: Legacy column names, kept so the export and the analysis keep reading what#: they always read. The three questions now sit on one page about every#: partner, but the day one and the night one still mean what they meant._LEGACY_BELIEF_KEY = {"day": "believed_partner_paid","night": "believed_night_partner_lost"}def partner_belief_stage():"""Did they believe each partner was real, asked once about all of them.Asked at the very end of the study, after every other question. Asking itmid-battery tells the participant there is something to doubt, andeverything after it is then answered by someone who has just been invitedto suspect the study. Asked about ALL the partners, including the othertask's, because the question is the same question and splitting it acrosstwo tasks asked it twice and still missed a partner each time."""async def _display(stage, container):import effort_stages as Erows = E.partner_roster()if not rows:return dict(measure="belief_check", skipped="no partners")nicewebrl.clear_element(container)done = asyncio.Event()radios = {}with container.style("align-items:center; max-width:680px;"):ui.markdown("Please answer for each of the people you played with.")warn = ui.markdown("")for r in rows:with ui.column().style("width:100%; max-width:600px; ""align-items:flex-start; margin-bottom:14px;"):ui.markdown(r["question"]).style("text-align:left;")radios[r["position"]] = (ui.radio({"Yes": "Yes", "No": "No"}).props("inline color=primary"))async def go():blank = [p for p, w in radios.items() if w.value is None]if blank:warn.set_content(f"\u26a0\ufe0f **{len(blank)} of "f"{len(rows)} still blank.**")if not await _confirm_skip():returndone.set()ui.button("Continue", on_click=go).props("color=primary size=lg")await done.wait()out = {"measure": "belief_check", "partners": []}for r in rows:answer = radios[r["position"]].valueout[f"believed_p{r['position']}"] = answerlegacy = _LEGACY_BELIEF_KEY.get(r.get("kind"))if legacy:out[legacy] = answerout["partners"].append({"position": r["position"], "id": r["id"],"kind": r.get("kind"),"where": r.get("where")})return outreturn _fb("PostTask_Belief", _display)def partner_liking_stage():"""How much they liked each partner, one slider per person.Next to the belief questions because both are about the people rather thanabout either task, and both have to come after everything that asks aboutthe tasks themselves."""async def _display(stage, container):import effort_stages as Erows = E.partner_roster()if not rows:return dict(measure="partner_liking", skipped="no partners")items = [(f"liking_p{r['position']}",f"How much did you like **{r['id']}**, the person you "f"played with in {r.get('where', 'this study')}?")for r in rows]res, _went_back = await _slider_battery(container, "","Please indicate how much you liked each of the people you ""played with.",items, "Not at all", "Very much", allow_back=False)return dict(measure="partner_liking",partners=[{"position": r["position"], "id": r["id"],"where": r.get("where")} for r in rows],**res)return _fb("PostTask_Liking", _display)# ----------------------------------------------------------------------------236 unmodified lineschosen["idx"] = radio.valueok = (radio.value == correct_idx)lead = "✅ **Correct!** " if ok else "❌ **Not quite.** "# The question is still on screen above this, so the feedback does# not repeat it; the revisit screen, where it is not, does.fb.set_content(lead + item.get("explain", ""))radio.disable() # lock the optionssubmit.disable() # grey out submit after one choice131 unmodified lineswith container.style("align-items:center; max-width:680px;"):ui.markdown("### Not quite. Let's go through that again.")for it in wrong:ui.markdown(f"**{it['prompt']}**")ui.markdown(f"{it['explain']}")ui.button("Try again", on_click=lambda: ev.set())await ev.wait()attempts += 131 unmodified linesev2 = asyncio.Event()with container.style("align-items:center; max-width:680px;"):ui.markdown("### Let's revisit the ones you got wrong!")# The question with its answer. The answer alone reads as a# statement out of nowhere when more than one item was missed,# and the participant has to work out which question it is# about before they can learn anything from it.for it in wrong:ui.markdown(f"**{it['prompt']}**")ui.markdown(f"{it['explain']}")ui.button("OK", on_click=lambda: ev2.set())await ev2.wait()attempts += 160 unmodified linesreturn out["agreed"]def _demographic_widget(it):"""The input for one demographics item.Out of the page loop so each item can sit in its own left-aligned columnwith its question above it, the way the TriPM reads."""t = it["type"]if t == "number":return ui.number().props("outlined").style("width:100%;")if t == "choice":return ui.radio(it["options"]).props("color=primary")if t == "dropdown":# A radio grid of 20-odd income bands is a wall; a select is the same# question without the wall.return ui.select(it["options"]).props("outlined").style("width:100%;")if t == "multi":# Select all that apply -- race/ethnicity is not a single choice, and# forcing it into one loses people who are more than one thing.return ui.select(it["options"], multiple=True).props("outlined use-chips").style("width:100%;")if t == "scale":return ui.slider(min=0, max=100, value=50).props("label-always")return ui.input().props("outlined").style("width:100%;")def demographics_stage():"""Demographics, from content/demographics.txt."""async def _display(stage, container):9 unmodified linesui.markdown("Please answer the following questions about ""yourself.")ui.markdown("_You may leave any question blank._")# Same layout as the TriPM: question above, left aligned, the# control under it at full width.for it in items:with ui.column().style("width:100%; max-width:560px; ""align-items:flex-start; ""margin-bottom:14px;"):ui.markdown(f"**{it['question']}**").style("text-align:left;")widgets[it["key"]] = (_demographic_widget(it), it["type"])ui.button("Continue", on_click=done.set).props("color=primary size=lg")await done.wait()55 unmodified lineswith container.style("align-items:center; max-width:720px;"):ui.markdown("Please indicate how true each statement is of you.")warn = ui.markdown("")# Each statement in its own full-width, left-aligned column with# the scale under it. The page centred everything, so a short# statement sat beside its own options and a long one above them,# and the list read as two different layouts interleaved.for key, text in items:with ui.column().style("width:100%; max-width:600px; ""align-items:flex-start; ""margin-bottom:16px;"):ui.markdown(f"**{text}**").style("text-align:left;")widgets[key] = (ui.radio(TRIPM_SCALE).props("inline color=primary").style("margin-left:0; padding-left:0;"))async def submit():missing = [k for k, w in widgets.items() if w.value not in TRIPM_SCALE]
1587 unmodified lines158815891590159115921593159415951596159715981599160016011587 unmodified linesctx.fillStyle = accentFor(t); ctx.fillRect(0, 0, W, 6);ctx.textAlign = "center"; ctx.fillStyle = C.white; ctx.font = "bold 22px system-ui, sans-serif";ctx.fillText("Rest", W / 2, 38);ctx.fillStyle = "#bfe3c8"; ctx.font = "13px system-ui, sans-serif";// The last field pays the PARTICIPANT for resting while the partner// loses; beneficiary is "other" on all of its trials because that is// whose field it is, so the day task's rule credited exactly the wrong// person on the one screen that states who gets the money.ctx.fillText("+" + t.restCredit + " " + creditsWord(t.restCredit) + " for " +((t.nightWatch || t.beneficiary !== "other") ? "YOU" : "your PARTNER"),W / 2, 60);// The same countdown the work phase shows. Rest had only the bar, so one// of the two options told you how long it had left in numbers and the// other did not, on phases of identical length.1587 unmodified lines15881589159015911592159315941595159615971598159916001587 unmodified linesctx.fillStyle = accentFor(t); ctx.fillRect(0, 0, W, 6);ctx.textAlign = "center"; ctx.fillStyle = C.white; ctx.font = "bold 22px system-ui, sans-serif";ctx.fillText("Rest", W / 2, 38);// No credit line here. The work phase shows no running total and no// promise of one, and this showed "+2 credits for YOU" throughout the// rest phase, so the two options were described differently while they// were being played. Both cards already state what each pays, which is// when it bears on the choice; after the choice it is one option// repeating its own payoff and the other staying silent. The outcome// screen pays both the same way.// The same countdown the work phase shows. Rest had only the bar, so one// of the two options told you how long it had left in numbers and the// other did not, on phases of identical length.
193 unmodified lines19419519619719819920020120220320420520620720820921019 unmodified lines230231232233234235236237238239193 unmodified lineswhat the participant decided. One entry per partner, signed."""monkeypatch.setenv("OTHER_TASK_BASE_URL", "https://other.test/")monkeypatch.setenv("SONA_PID_HASH_KEY", KEY)rows = [{"id": "P2-11111", "earned": 2.5, "lost": 0.0},{"id": "P2-22222", "earned": 0.0, "lost": 4.25}]url = order_link.other_task_url("SMOKE_rows", first_value="pe",partner_rows=rows)assert "&pparts1=" in url and "&ppsig=" in urls = order_link.encode_partner_rows(rows)assert s == "P2-11111:2.50:0.00|P2-22222:0.00:4.25"sig = order_link.partner_list_signature("SMOKE_rows", s)back = order_link.verify_partner_rows("SMOKE_rows", s, sig)assert [r["id"] for r in back] == ["P2-11111", "P2-22222"]assert back[1]["lost"] == 4.25# Tampering, junk and an unsigned list are all simply nothing to report.assert order_link.verify_partner_rows("SMOKE_rows", "P2-11111:6.00:0.00", sig) == []19 unmodified linescode = "SMOKE_rows_b"from urllib.parse import quotes = order_link.encode_partner_rows([{"id": "SL-9001", "earned": 1.5, "lost": 0.0}])sig = order_link.partner_list_signature(code, s)await user.open(_handoff_url(code, extra=f"&pparts1={quote(s, safe='')}&ppsig={sig}"))with user.client:got = app.storage.user["other_task_partner_rows"]assert got == [{"id": "SL-9001", "earned": 1.5, "lost": 0.0}]193 unmodified lines19419519619719819920020120220320420520620720820921021121221321421521621721819 unmodified lines238239240241242243244245246247248193 unmodified lineswhat the participant decided. One entry per partner, signed."""monkeypatch.setenv("OTHER_TASK_BASE_URL", "https://other.test/")monkeypatch.setenv("SONA_PID_HASH_KEY", KEY)rows = [{"id": "P2-11111", "earned": 2.5, "lost": 0.0, "kind": "day"},{"id": "P2-22222", "earned": 0.0, "lost": 4.25, "kind": "night"}]url = order_link.other_task_url("SMOKE_rows", first_value="pe",partner_rows=rows)assert "&pparts1=" in url and "&ppsig=" in urls = order_link.encode_partner_rows(rows)assert s == "P2-11111:2.50:0.00:day|P2-22222:0.00:4.25:night"sig = order_link.partner_list_signature("SMOKE_rows", s)back = order_link.verify_partner_rows("SMOKE_rows", s, sig)assert [r["id"] for r in back] == ["P2-11111", "P2-22222"]assert back[1]["lost"] == 4.25assert [r["kind"] for r in back] == ["day", "night"]# The three-field version, which is what is deployed on the other side# until it picks this up: the wording defaults, the partner survives.old = "P2-11111:2.50:0.00"back3 = order_link.verify_partner_rows("SMOKE_rows", old, order_link.partner_list_signature("SMOKE_rows", old))assert back3 == [{"id": "P2-11111", "earned": 2.5, "lost": 0.0,"kind": order_link.DEFAULT_ROW_KIND}]# Tampering, junk and an unsigned list are all simply nothing to report.assert order_link.verify_partner_rows("SMOKE_rows", "P2-11111:6.00:0.00", sig) == []19 unmodified linescode = "SMOKE_rows_b"from urllib.parse import quotes = order_link.encode_partner_rows([{"id": "SL-9001", "earned": 1.5, "lost": 0.0, "kind": "hunt"}])sig = order_link.partner_list_signature(code, s)await user.open(_handoff_url(code, extra=f"&pparts1={quote(s, safe='')}&ppsig={sig}"))with user.client:got = app.storage.user["other_task_partner_rows"]assert got == [{"id": "SL-9001", "earned": 1.5, "lost": 0.0,"kind": "hunt"}]
116 unmodified lines117118119120121122123124125126127128129130131132286 unmodified lines4194204214224234244254264274284294304314324334346 unmodified lines44144244344444544625 unmodified lines47247347447547647747847948044 unmodified lines5255265275285295305315325335345355365375385395406 unmodified lines547548549550551552553554555116 unmodified linesassert E.night_watch_on() is Truedef test_the_rest_banner_credits_the_participant_not_the_partner():"""Every night-harvest trial has beneficiary "other", because that is whosefield it is, and the day task's rule reads that as "the partner is paid".So the one screen that states who gets the money named the wrong person,contradicting the quiz the participant had just passed."""with open("static/cornfield.js") as f:js = f.read()i = js.index('ctx.fillText("Rest", W / 2, 38);')body = js[i:i + 900]assert "t.nightWatch ||" in bodydef test_the_work_banner_quotes_the_pay_this_block_actually_gives():286 unmodified linesdef _belief_source():"""The belief stage's source with adjacent string literals joined.Its prompts are built from f-string fragments across several lines, so aplain substring search for a sentence fails on the line break rather thanon the wording."""with open("questionnaires.py") as f:src = f.read()i = src.index("def belief_stage")body = src[i:src.index("\ndef ", i + 10)]return re.sub(r'"\s*\n\s*f?"', "", body)6 unmodified linesbody = _belief_source()assert "_confirm_skip()" in bodyassert "if radio.value is None or chosen" not in bodydef test_the_all_or_nothing_rule_is_stated_before_they_play(storage):25 unmodified linesbody = _belief_source()assert "the credits you took" not in bodyassert "lose the credits shown on screen" in body# and the two items are parallel, both naming the block they ask aboutassert "During the daytime harvest" in bodyassert "During the Night Harvest" in bodydef test_the_night_block_has_a_break_like_the_day_task():44 unmodified linesassert "P2-11111" not in textdef test_each_battery_asks_its_own_belief_question():"""Both questions on one page meant asking about a block the participanthad not reached. They are different columns too, so one cannot silentlyoverwrite the other."""body = _belief_source()assert "During the daytime harvest" in bodyassert "During the Night Harvest" in bodyassert "lose the credits shown on screen" in bodyassert Q._belief_key("day") == "believed_partner_paid"assert Q._belief_key("night") == "believed_night_partner_lost"def test_the_night_battery_is_skipped_with_the_block():6 unmodified linesassert n in names, n# the day battery keeps its original, registered namesfor n in ("NASA_TLX", "Effort_impact", "PostTask_Motivation","PostTask_Effort2", "PostTask_TaskRating", "PostTask_Belief","PostTask_Strategy", "Fatigue_post"):assert n in names, ndef test_the_night_partner_is_named_even_before_storage_is_written(storage):116 unmodified lines117118119120121122123124125126127128129130131132133134135136137138139140141142143144286 unmodified lines4314324334344354364374384394404414424434444454464474484494504514526 unmodified lines45946046146246346446546625 unmodified lines49249349449549649749849950044 unmodified lines5455465475485495505515525535545555565575585595605615625635645655665675685695705715725736 unmodified lines580581582583584585586587588589590591592593594116 unmodified linesassert E.night_watch_on() is Truedef test_the_rest_phase_no_longer_quotes_its_own_pay():"""It read "+2 credits for YOU" for the whole rest phase while the workphase showed nothing, so the two options were described differently whilethey were being played.This replaces a test that checked WHO that line credited. Everynight-harvest trial has beneficiary "other", because that is whose fieldit is, and the day task's rule read that as "the partner is paid", so theone screen stating who got the money named the wrong person. The line isgone, which settles that question as well: both cards state what eachoption pays before the choice, and the outcome screen pays both the sameway afterwards."""with open("static/cornfield.js") as f:js = f.read()i = js.index('ctx.fillText("Rest", W / 2, 38);')body = js[i:i + 1500]assert "creditsWord" not in bodyassert "+\" + t.restCredit" not in body# the countdown and the bar stay: both phases are the same length and# both say how long is leftassert "rSecs" in body and "timerBar(rEl, t.restMs" in bodydef test_the_work_banner_quotes_the_pay_this_block_actually_gives():286 unmodified linesdef _belief_source():"""The belief wording with adjacent string literals joined.It is built from f-string fragments across several lines, so a plainsubstring search for a sentence fails on the line break rather than on thewording. Both the question builder in effort_stages and the page inquestionnaires, since the words live in the first and the page in thesecond."""with open("questionnaires.py") as f:qsrc = f.read()i = qsrc.index("def partner_belief_stage")body = qsrc[i:qsrc.index("\ndef ", i + 10)]with open("effort_stages.py") as f:esrc = f.read()j = esrc.index("def _belief_question")body += esrc[j:esrc.index("\ndef ", j + 10)]return re.sub(r'"\s*\n\s*f?"', "", body)6 unmodified linesbody = _belief_source()assert "_confirm_skip()" in bodyassert "if radio.value is None or chosen" not in body# and it says how many are blank rather than refusing silentlyassert "still blank" in bodydef test_the_all_or_nothing_rule_is_stated_before_they_play(storage):25 unmodified linesbody = _belief_source()assert "the credits you took" not in bodyassert "lose the credits shown on screen" in body# and the two wordings are parallel, each naming where it asks aboutassert "During {where}" in bodyassert "receive the credits you earned for them" in bodydef test_the_night_block_has_a_break_like_the_day_task():44 unmodified linesassert "P2-11111" not in textdef test_one_page_asks_about_every_partner_in_its_own_words(storage):"""One question per person, on one page, at the end of the study.Split across the two batteries it was asked twice and still missed apartner each time, because the other task's partner belongs to neitherbattery. The wording follows the kind of partner: one you earned for isasked whether they would receive it, and the night harvest's partner couldonly ever lose."""import effort_stages as Eassert Q._LEGACY_BELIEF_KEY["day"] == "believed_partner_paid"assert Q._LEGACY_BELIEF_KEY["night"] == "believed_night_partner_lost"day = E._belief_question({"id": "P2-1", "kind": "day"},"the daytime harvest")night = E._belief_question({"id": "P2-2", "kind": "night"},"the Night Harvest")hunt = E._belief_question({"id": "SL-3", "kind": "hunt"},"the treasure hunt")assert "receive the credits you earned for them" in dayassert "lose the credits shown on screen" in nightassert "receive the credits you earned for them" in huntfor q, who in ((day, "P2-1"), (night, "P2-2"), (hunt, "SL-3")):assert who in qdef test_the_night_battery_is_skipped_with_the_block():6 unmodified linesassert n in names, n# the day battery keeps its original, registered namesfor n in ("NASA_TLX", "Effort_impact", "PostTask_Motivation","PostTask_Effort2", "PostTask_TaskRating","PostTask_Strategy", "Fatigue_post"):assert n in names, n# The belief check is no longer one of the night battery's stages: it is# asked once, about every partner, after both batteries. So it must NOT be# skipped with the night block, or a day-only session is never asked it.assert "PostTask_Belief" in names and "PostTask_Liking" in namesassert "Night_PostTask_Belief" not in namesassert not {"PostTask_Belief", "PostTask_Liking"} & E.NIGHT_QUESTION_STAGESdef test_the_night_partner_is_named_even_before_storage_is_written(storage):
82 unmodified lines83848582 unmodified linesassert a == CI.tripm_items(order_seed="P0001"), "not stable for one pid"# No seed means file order, which is what the scoring key is written in.assert [k for k, _ in CI.tripm_items()] == [f"tripm_{i}" for i in range(1, 59)]82 unmodified lines838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412582 unmodified linesassert a == CI.tripm_items(order_seed="P0001"), "not stable for one pid"# No seed means file order, which is what the scoring key is written in.assert [k for k, _ in CI.tripm_items()] == [f"tripm_{i}" for i in range(1, 59)]def test_the_roster_lists_every_partner_in_the_order_they_were_met(monkeypatch):"""The belief and liking questions, and the final screen, all walk onelist: this task's partners plus the other task's, ordered by which taskran first. Split per block they asked twice and still missed a partner."""import effort_stages as Estore = {"theme": "harvest", "pid": "P0001", "self_points": 50,"partner_points": 100, "random_id": "P2-1","random_id_night": "P2-2","watch_log": [{"pay": 2, "loss": 8}, {"pay": 1, "loss": 2}],"other_task_partner_rows": [{"id": "SL-9", "earned": 3.0, "lost": 0.0, "kind": "hunt"}],"task_first": "sl"}monkeypatch.setattr(E.app, "storage", type("S", (), {"user": store})())monkeypatch.setattr(E.TH.app, "storage", type("S", (), {"user": store})())rows = E.partner_roster()assert [r["id"] for r in rows] == ["SL-9", "P2-1", "P2-2"]assert [r["position"] for r in rows] == [1, 2, 3]# The other task's explorer cannot be drawn by this app's art.assert [r["drawable"] for r in rows] == [False, True, True]# Each one's belief question is worded for what could happen to them.assert "receive the credits" in rows[0]["question"]assert "receive the credits" in rows[1]["question"]assert "lose the credits shown" in rows[2]["question"]# And when this task ran first, its own partners lead.store["task_first"] = "pe"assert [r["id"] for r in E.partner_roster()] == ["P2-1", "P2-2", "SL-9"]def test_the_roster_is_just_this_task_without_a_handoff(monkeypatch):import effort_stages as Estore = {"theme": "harvest", "pid": "P0002", "partner_points": 25,"random_id": "P2-7"}monkeypatch.setattr(E.app, "storage", type("S", (), {"user": store})())monkeypatch.setattr(E.TH.app, "storage", type("S", (), {"user": store})())rows = E.partner_roster()assert [r["id"] for r in rows] == ["P2-7"]# No night block ran, so nobody is asked about a night partner.assert all(r["kind"] != "night" for r in rows)
238 unmodified lines239240241242243244245246247422 unmodified lines670671672673674675676677678679680681682683684685686687688689690691692693694695259 unmodified lines9559569579589599609615 unmodified lines967968969970971972973238 unmodified lines#: The battery that asks about the day task. Named so a dev link can jump#: PAST it to the night block, which otherwise means clicking through ten#: questionnaire pages to reach the screens being checked.DAY_QUESTION_SKIP = frozenset(['QuestionnaireTransition', 'Fatigue_post', 'NASA_TLX', 'Effort_impact', 'PostTask_Motivation', 'PostTask_Effort2', 'PostTask_TaskRating', 'PostTask_Belief', 'PostTask_Hypothetical', 'PostTask_Strategy'])NIGHT_QUESTION_SKIP = frozenset(['Fatigue_night', 'Night_NASA_TLX', 'Night_Effort_impact', 'Night_PostTask_Motivation', 'Night_PostTask_Effort2', 'Night_PostTask_TaskRating', 'Night_PostTask_Belief', 'Night_PostTask_Strategy'])DEV_SKIP = {# The whole session, front matter included: the consent form, the device422 unmodified lines# last screen of the study accounts for everybody.try:e = E.earnings_summary()ui.markdown(f"### YOU earned **{e['self_points']} credits** "f"→ **${e['self_bonus']:.2f}**")mine = [dict(r, where=r["where"]) for r in E.partner_rows()]theirs = [dict(r, where="the treasure hunt",kept=max(0.0, 6.0 - float(r.get("lost", 0.0))))for r in (app.storage.user.get("other_task_partner_rows") or [])]# Whoever they met first comes first. The order this session resolved,# not a guess: task_first says which task ran before this one.rows = (theirs + mineif app.storage.user.get("task_first") != order_link.THIS_TASKelse mine + theirs)for i, r in enumerate(rows, start=1):who = f"YOUR PARTNER {i}" + (f" ({r['id']})" if r.get("id") else "")if r.get("lost"):ui.markdown(f"### {who} lost **${r['lost']:.2f}** of their "f"**$6.00** in {r['where']}, and keeps "f"**${r.get('kept', 0.0):.2f}**")else:ui.markdown(f"### {who} earned **${r.get('earned', 0.0):.2f}** "f"in {r['where']}")if e.get("night_partner_points") is not None:ui.markdown(f"*The Night Harvest was settled from the {e['nights_paid']} of "259 unmodified linesdef _general_measures_to_skip():"""{"TriPM", "Demographics"} when this task runs FIRST in the combined study.They belong to the participant rather than to either task, so the task thatfinishes second collects them. Empty unless ?study=sona and the handoff to5 unmodified linesreturn set()# The position this session resolved once, not a fresh derivation: a second# answer here could disagree with the one already recorded and handed on.return {"TriPM", "Demographics"} if app.storage.user.get("task_position") == 1 else set()async def _refuse_unpseudonymised(key_env):238 unmodified lines239240241242243244245246247422 unmodified lines670671672673674675676677678679680681682683684685686687688689690691692693694695696259 unmodified lines9569579589599609619625 unmodified lines968969970971972973974975976977978979238 unmodified lines#: The battery that asks about the day task. Named so a dev link can jump#: PAST it to the night block, which otherwise means clicking through ten#: questionnaire pages to reach the screens being checked.DAY_QUESTION_SKIP = frozenset(['QuestionnaireTransition', 'Fatigue_post', 'NASA_TLX', 'Effort_impact', 'PostTask_Motivation', 'PostTask_Effort2', 'PostTask_TaskRating', 'PostTask_Hypothetical', 'PostTask_Strategy'])NIGHT_QUESTION_SKIP = frozenset(['NightQuestionnaireTransition', 'Fatigue_night', 'Night_NASA_TLX', 'Night_Effort_impact', 'Night_PostTask_Motivation', 'Night_PostTask_Effort2', 'Night_PostTask_TaskRating', 'Night_PostTask_Strategy'])DEV_SKIP = {# The whole session, front matter included: the consent form, the device422 unmodified lines# last screen of the study accounts for everybody.try:e = E.earnings_summary()# partner_roster() orders them by when they were met and carries the# avatar each one was introduced with, so the ids are people here.rows = E.partner_roster()lines = [{"md": f"### YOU earned **{e['self_points']} credits** "f"→ **${e['self_bonus']:.2f}**","avatar": int(app.storage.user.get("avatar", 0)),"self": True}]for r in rows:who = (f"YOUR PARTNER {r['position']}"+ (f" ({r['id']})" if r.get("id") else ""))if r.get("lost"):md = (f"### {who} lost **${r['lost']:.2f}** of their **$6.00** in "f"{r['where']}, and keeps **${r.get('kept', 0.0):.2f}**")else:md = (f"### {who} earned **${r.get('earned', 0.0):.2f}** in "f"{r['where']}")lines.append({"md": md,"avatar": (r.get("avatar") if r.get("drawable")else None)})await E._people_lines(lines)theirs = [r for r in rows if not r.get("drawable")]if e.get("night_partner_points") is not None:ui.markdown(f"*The Night Harvest was settled from the {e['nights_paid']} of "259 unmodified linesdef _general_measures_to_skip():"""The measures the SECOND task collects, when this task runs FIRST.They belong to the participant rather than to either task, so the task thatfinishes second collects them. Empty unless ?study=sona and the handoff to5 unmodified linesreturn set()# The position this session resolved once, not a fresh derivation: a second# answer here could disagree with the one already recorded and handed on.# The two partner questions defer too: they ask about every partner across# both tasks, so the task that finishes second is the only one that can ask# them once and name all three. Asked in the first task they would name two# people and then be asked again about the third.return ({"TriPM", "Demographics", "PostTask_Belief", "PostTask_Liking"}if app.storage.user.get("task_position") == 1 else set())async def _refuse_unpseudonymised(key_env):