From a9ac9516e03da40344763ce7887af2059ed8bfd9 Mon Sep 17 00:00:00 2001 From: Aaron Steven White Date: Sun, 22 Nov 2026 15:56:28 -0500 Subject: [PATCH 1/2] Adds offline jsPsych studies with named cloze responses and streamed results. --- .github/workflows/ci.yml | 22 +- .github/workflows/publish.yml | 24 +- CHANGELOG.md | 18 + bead/config/deployment.py | 11 +- bead/data_collection/__init__.py | 9 +- bead/data_collection/jatos.py | 121 +++--- bead/data_collection/records.py | 77 ++-- bead/data_collection/result_stream.py | 102 +++++ bead/deployment/jatos/api.py | 27 +- bead/deployment/jatos/exporter.py | 88 +++-- bead/deployment/jspsych/config.py | 3 + bead/deployment/jspsych/copy-runtime.mjs | 48 +++ bead/deployment/jspsych/generator.py | 112 +++++- bead/deployment/jspsych/licenses/jspsych.txt | 21 + bead/deployment/jspsych/package.json | 14 +- bead/deployment/jspsych/pnpm-lock.yaml | 152 +++++++- .../jspsych/src/plugins/cloze-dropdown.ts | 85 ++-- .../deployment/jspsych/src/types/jspsych.d.ts | 1 + .../jspsych/templates/experiment.js.template | 365 +++++++++++++++--- bead/deployment/jspsych/templates/index.html | 42 +- bead/deployment/jspsych/trials.py | 54 +++ bead/deployment/jspsych/tsup.config.ts | 2 - .../deployment/jspsych/tsup.gallery.config.ts | 22 +- bead/items/item_template.py | 17 + pyproject.toml | 6 + tests/data_collection/test_result_stream.py | 78 ++++ tests/deployment/jatos/test_api.py | 3 +- tests/deployment/jatos/test_exporter.py | 54 ++- tests/deployment/jspsych/test_plugins.py | 2 +- 29 files changed, 1266 insertions(+), 314 deletions(-) create mode 100644 bead/data_collection/result_stream.py create mode 100644 bead/deployment/jspsych/copy-runtime.mjs create mode 100644 bead/deployment/jspsych/licenses/jspsych.txt create mode 100644 tests/data_collection/test_result_stream.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98430f2..fb9a680 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v4 with: - version: 9 + package_json_file: bead/deployment/jspsych/package.json - name: Set up Node.js uses: actions/setup-node@v4 @@ -38,7 +38,7 @@ jobs: cache-dependency-path: bead/deployment/jspsych/pnpm-lock.yaml - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Run Biome check (lint + format) run: pnpm check @@ -55,7 +55,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v4 with: - version: 9 + package_json_file: bead/deployment/jspsych/package.json - name: Set up Node.js uses: actions/setup-node@v4 @@ -65,7 +65,7 @@ jobs: cache-dependency-path: bead/deployment/jspsych/pnpm-lock.yaml - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Run type check run: pnpm typecheck @@ -82,7 +82,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v4 with: - version: 9 + package_json_file: bead/deployment/jspsych/package.json - name: Set up Node.js uses: actions/setup-node@v4 @@ -92,7 +92,7 @@ jobs: cache-dependency-path: bead/deployment/jspsych/pnpm-lock.yaml - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Build TypeScript run: pnpm build @@ -109,7 +109,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v4 with: - version: 9 + package_json_file: bead/deployment/jspsych/package.json - name: Set up Node.js uses: actions/setup-node@v4 @@ -119,7 +119,7 @@ jobs: cache-dependency-path: bead/deployment/jspsych/pnpm-lock.yaml - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Run tests run: pnpm test @@ -188,7 +188,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v4 with: - version: 9 + package_json_file: bead/deployment/jspsych/package.json - name: Set up Node.js uses: actions/setup-node@v4 @@ -199,11 +199,11 @@ jobs: - name: Install TypeScript dependencies working-directory: bead/deployment/jspsych - run: pnpm install + run: pnpm install --frozen-lockfile - name: Build TypeScript working-directory: bead/deployment/jspsych - run: pnpm build && pnpm build:gallery + run: pnpm build - name: Set up Python uses: actions/setup-python@v5 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7205ab5..fc7b3e0 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -16,6 +16,24 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + package_json_file: bead/deployment/jspsych/package.json + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "22" + cache: "pnpm" + cache-dependency-path: bead/deployment/jspsych/pnpm-lock.yaml + + - name: Build pinned browser assets + working-directory: bead/deployment/jspsych + run: | + pnpm install --frozen-lockfile + pnpm build + - name: Set up Python uses: actions/setup-python@v5 with: @@ -25,7 +43,11 @@ jobs: run: pip install build - name: Build package - run: python -m build + run: | + python -m build + python -m venv /tmp/bead-wheel + /tmp/bead-wheel/bin/pip install --no-deps dist/*.whl + /tmp/bead-wheel/bin/python -c 'from importlib.metadata import distribution; import hashlib, json; runtime = distribution("bead").locate_file("bead/deployment/jspsych/dist/runtime"); manifest = json.loads((runtime / "manifest.json").read_text()); assert all(hashlib.sha256((runtime / name).read_bytes()).hexdigest() == entry["sha256"] for name, entry in manifest.items())' - name: Upload distribution artifacts uses: actions/upload-artifact@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index efb85bb..0130b37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Deploys named cloze fields with explicit choices and independent display labels. +- Appends consented JSONL session records to JATOS and reads complete or partial + streams into named annotation records while preserving the raw records. +- Allows a study-specific session adapter and a supplied slopit browser bundle + for consent-gated response-control telemetry. + +### Fixed + +- Ships pinned jsPsych runtime assets and standalone browser bundles in the + Python release. Generated studies load all required assets locally. +- Registers the slopit extension with jsPsych and supplies per-trial parameters + after consent. +- Exports native JATOS study archives with stable component and batch IDs when + the study ID is supplied. + + ## [0.13.0] - 2026-11-06 ### Added diff --git a/bead/config/deployment.py b/bead/config/deployment.py index 6c8ca23..fee7276 100644 --- a/bead/config/deployment.py +++ b/bead/config/deployment.py @@ -3,6 +3,7 @@ from __future__ import annotations from pathlib import Path +from typing import Literal import didactic.api as dx @@ -83,10 +84,11 @@ def _default_paste_config() -> SlopitPasteConfig: def _default_target_selectors() -> dict[str, str]: return { - "likert_rating": ".bead-rating-button", - "slider_rating": ".bead-slider", + "likert_rating": ".bead-rating-button, #bead-rating-continue", + "slider_rating": ".bead-slider-input, #bead-slider-continue", "forced_choice": ".bead-choice-button", - "cloze": ".bead-cloze-field", + "cloze": ".bead-cloze-field, #bead-cloze-continue", + "binary_choice": ".bead-binary-button", } @@ -108,6 +110,7 @@ class SlopitIntegrationConfig(dx.Model): """ enabled: bool = False + profile: Literal["legacy", "response_controls"] = "legacy" keystroke: dx.Embed[SlopitKeystrokeConfig] = dx.field( default_factory=_default_keystroke_config ) @@ -127,7 +130,7 @@ def validate_slopit_integration(config: SlopitIntegrationConfig) -> None: / "deployment" / "jspsych" / "dist" - / "slopit-bundle.js" + / "slopit-bundle.global.js" ) if not bundle_path.exists(): raise ValueError( diff --git a/bead/data_collection/__init__.py b/bead/data_collection/__init__.py index 31cbf7b..bcfebc7 100644 --- a/bead/data_collection/__init__.py +++ b/bead/data_collection/__init__.py @@ -1,13 +1,20 @@ """Data collection infrastructure for human experiments.""" -from bead.data_collection.jatos import JATOSDataCollector +from bead.data_collection.jatos import JATOSDataCollector, load_jatos_result_archive from bead.data_collection.merger import DataMerger from bead.data_collection.prolific import ProlificDataCollector from bead.data_collection.records import jatos_results_to_annotation_records +from bead.data_collection.result_stream import ( + JATOSResultStream, + parse_jatos_result_stream, +) __all__ = [ "DataMerger", "JATOSDataCollector", + "JATOSResultStream", "ProlificDataCollector", "jatos_results_to_annotation_records", + "load_jatos_result_archive", + "parse_jatos_result_stream", ] diff --git a/bead/data_collection/jatos.py b/bead/data_collection/jatos.py index 26691f2..279d3d7 100644 --- a/bead/data_collection/jatos.py +++ b/bead/data_collection/jatos.py @@ -12,13 +12,63 @@ from __future__ import annotations import json -from pathlib import Path +import zipfile +from io import BytesIO +from pathlib import Path, PurePosixPath from bead.data.base import JsonValue from bead.data.timestamps import now_iso8601 from bead.deployment.jatos.api import JATOSClient +def load_jatos_result_archive( + source: Path | BytesIO, +) -> list[dict[str, JsonValue]]: + """Load each component's raw data and metadata from a ZIP export. + + JSON arrays are decoded for legacy consumers. Appended JSONL remains text + for sequence-aware parsing, including the last line of interrupted runs. + Components without submitted data are included with a null payload. + """ + results: list[dict[str, JsonValue]] = [] + with zipfile.ZipFile(source) as archive: + files = set(archive.namelist()) + metadata = json.loads(archive.read("metadata.json")) + for study in metadata["data"]: + for result in study["studyResults"]: + for component in result["componentResults"]: + folder = component.get("path") or ( + f"study_result_{result['id']}/comp_result_{component['id']}" + ) + path = str(PurePosixPath(folder.lstrip("/")) / "data.txt") + data: JsonValue = None + if path in files: + text = archive.read(path).decode("utf-8") + try: + parsed: JsonValue = json.loads(text) + data = ( + text + if isinstance(parsed, dict) and "record_type" in parsed + else parsed + ) + except json.JSONDecodeError: + data = text + results.append( + { + "result_id": result["id"], + "component_result_id": component["id"], + "data": data, + "metadata": { + **result, + **component, + "studyId": study["studyId"], + "studyResultId": result["id"], + }, + } + ) + return results + + class JATOSDataCollector: """Collects experimental data from JATOS API. @@ -108,27 +158,17 @@ def download_results( worker_type="Prolific" ) """ - # Get result IDs from JATOS API - result_ids = self.client.get_results(self.study_id) - - results: list[dict[str, JsonValue]] = [] - - # Download each result with metadata - for result_id in result_ids: - result = self._download_single_result(result_id) - - # Apply filters - if component_id is not None: - result_component_id = result.get("metadata", {}).get("componentId") - if result_component_id != component_id: - continue - - if worker_type is not None: - result_worker_type = result.get("metadata", {}).get("workerType") - if result_worker_type != worker_type: - continue - - results.append(result) + archive = self.client.download_result_archive(self.study_id) + results = [] + for result in load_jatos_result_archive(BytesIO(archive)): + metadata = result["metadata"] + if not isinstance(metadata, dict): + continue + if component_id is not None and metadata.get("componentId") != component_id: + continue + if worker_type is not None and metadata.get("workerType") != worker_type: + continue + results.append({**result, "download_timestamp": now_iso8601().isoformat()}) # Save to JSONLines file (one result per line) output_path.parent.mkdir(parents=True, exist_ok=True) @@ -138,43 +178,6 @@ def download_results( return results - def _download_single_result(self, result_id: int) -> dict[str, JsonValue]: - """Download a single result with metadata. - - Parameters - ---------- - result_id : int - Result ID to download. - - Returns - ------- - dict[str, JsonValue] - Result data with metadata and download timestamp. - - Raises - ------ - requests.HTTPError - If the API request fails. - """ - # Get result data - data_url = f"{self.client.base_url}/api/v1/results/{result_id}/data" - data_response = self.client.session.get(data_url) - data_response.raise_for_status() - - # Get result metadata - meta_url = f"{self.client.base_url}/api/v1/results/{result_id}" - meta_response = self.client.session.get(meta_url) - meta_response.raise_for_status() - - metadata = meta_response.json() - - return { - "result_id": result_id, - "data": data_response.json(), - "metadata": metadata, - "download_timestamp": now_iso8601().isoformat(), - } - def get_study_info(self) -> dict[str, JsonValue]: """Get study information. diff --git a/bead/data_collection/records.py b/bead/data_collection/records.py index 49c28ee..33f2180 100644 --- a/bead/data_collection/records.py +++ b/bead/data_collection/records.py @@ -19,6 +19,7 @@ from typing import Any from bead.data.base import JsonValue +from bead.data_collection.result_stream import parse_jatos_result_stream from bead.evaluation.reliability import AnnotationRecord @@ -64,12 +65,19 @@ def _annotator_id( for the configured key (typically ``"PROLIFIC_PID"``), then falls back to the JATOS-assigned ``worker_id``. """ - url_params = result.get("urlQueryParameters") + url_params = result.get("urlQueryParameters") or result.get("url_params") if isinstance(url_params, Mapping) and annotator_id_key in url_params: candidate = url_params[annotator_id_key] if isinstance(candidate, str) and candidate: return candidate - worker_id = result.get("worker_id") + participant_id = result.get("prolific_pid") or result.get("participant_id") + if isinstance(participant_id, str) and participant_id: + return participant_id + worker_id = ( + result.get("worker_id") + or result.get("workerId") + or result.get("jatos_worker_id") + ) if isinstance(worker_id, str) and worker_id: return worker_id if isinstance(worker_id, int): @@ -94,7 +102,7 @@ def jatos_results_to_annotation_records( Parameters ---------- results : Iterable[Mapping[str, Any]] - JATOS result envelopes. + JATOS result envelopes with an aggregate array or appended JSONL. annotator_id_key : str, optional Query-parameter key carrying the annotator identifier. Defaults to ``"PROLIFIC_PID"``. @@ -102,36 +110,61 @@ def jatos_results_to_annotation_records( Returns ------- tuple[AnnotationRecord, ...] - One record per (item, template_name) trial. Records appear in - result-then-trial order. Trials missing required fields are - skipped. + One record per scalar response or answered named field. Named field + questions use template_name.field_name. Missing answers are skipped. """ records: list[AnnotationRecord] = [] for result in results: + payload = result.get("data") + stream = ( + parse_jatos_result_stream(payload) + if isinstance(payload, str | list | tuple) + else None + ) annotator_id = _annotator_id(result, annotator_id_key=annotator_id_key) + metadata = result.get("metadata") + if annotator_id is None and stream is not None and stream.session is not None: + annotator_id = _annotator_id( + stream.session, annotator_id_key=annotator_id_key + ) + if annotator_id is None and isinstance(metadata, Mapping): + annotator_id = _annotator_id(metadata, annotator_id_key=annotator_id_key) if annotator_id is None: continue - trials = result.get("data") - if not isinstance(trials, list): + trials = stream.trials if stream is not None else payload + if not isinstance(trials, list | tuple): continue for trial in trials: - if not isinstance(trial, Mapping): + if ( + not isinstance(trial, Mapping) + or trial.get("annotation_eligible") is False + ): continue item_id = trial.get("item_id") question_name = trial.get("template_name") - response = trial.get("response") - if ( - not isinstance(item_id, str) - or not isinstance(question_name, str) - or response is None - ): + if not isinstance(item_id, str) or not isinstance(question_name, str): continue - records.append( - AnnotationRecord( - annotator_id=annotator_id, - item_id=item_id, - question_name=question_name, - response_label=_coerce_response_label(response), + fields = trial.get("response_field_names") + responses = trial.get("responses") + if isinstance(fields, list | tuple) and isinstance(responses, Mapping): + named_responses = ( + (f"{question_name}.{name}", responses.get(name)) + for name in fields + if isinstance(name, str) and name + ) + else: + named_responses = ((question_name, trial.get("response")),) + for name, response in named_responses: + if response is None or ( + isinstance(responses, Mapping) and response == "" + ): + continue + records.append( + AnnotationRecord( + annotator_id=annotator_id, + item_id=item_id, + question_name=name, + response_label=_coerce_response_label(response), + ) ) - ) return tuple(records) diff --git a/bead/data_collection/result_stream.py b/bead/data_collection/result_stream.py new file mode 100644 index 0000000..bde46f3 --- /dev/null +++ b/bead/data_collection/result_stream.py @@ -0,0 +1,102 @@ +"""Normalization of append-only JATOS result records.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass + +from bead.data.base import JsonValue + +_RECORD_TYPES = ("session", "plan", "trial", "event", "end") + + +@dataclass(frozen=True) +class JATOSResultStream: + """Raw arrival order and a sequence-ordered view of a complete or partial run. + + Missing ranges include the first and last missing sequence numbers. A + terminal record indicates that the browser attempted to close the stream. + Its status and failed sequence numbers are recorded in the record itself. + """ + + records: tuple[dict[str, JsonValue], ...] + ordered_records: tuple[dict[str, JsonValue], ...] + missing_seq_ranges: tuple[tuple[int, int], ...] + malformed_line_numbers: tuple[int, ...] + session: dict[str, JsonValue] | None + terminal: dict[str, JsonValue] | None + + @property + def trials(self) -> tuple[dict[str, JsonValue], ...]: + """Return one trial per delivered sequence, in trial order.""" + return tuple(r for r in self.ordered_records if r.get("record_type") == "trial") + + +def parse_jatos_result_stream( + payload: str | list[JsonValue] | tuple[JsonValue, ...], +) -> JATOSResultStream | None: + """Parse JSONL text or a sequence of records emitted by a streaming study. + + Parameters + ---------- + payload + Raw JSONL text or a parsed sequence of result records. + + Returns + ------- + JATOSResultStream | None + The normalized stream, or None for an ordinary aggregate payload. + For repeated sequence numbers, the first arrival is used in the + sequence view and every delivered record is kept in the raw view. + """ + malformed_lines: list[int] = [] + parsed: list[JsonValue] + if isinstance(payload, str): + parsed = [] + for index, line in enumerate(payload.splitlines(), start=1): + if not line.strip(): + continue + try: + record: JsonValue = json.loads(line) + except json.JSONDecodeError: + malformed_lines.append(index) + else: + parsed.append(record) + else: + parsed = list(payload) + + records = tuple(record for record in parsed if isinstance(record, dict)) + if not any(r.get("record_type") in _RECORD_TYPES for r in records): + return None + + indexed: dict[int, dict[str, JsonValue]] = {} + for record in records: + seq = record.get("seq") + if type(seq) is int and seq >= 0: + indexed.setdefault(seq, record) + missing: list[tuple[int, int]] = [] + ordered: list[dict[str, JsonValue]] = [] + previous = -1 + for seq, record in sorted(indexed.items()): + if seq > previous + 1: + missing.append((previous + 1, seq - 1)) + previous = seq + ordered.append(record) + return JATOSResultStream( + records=records, + ordered_records=tuple(ordered), + missing_seq_ranges=tuple(missing), + malformed_line_numbers=tuple(malformed_lines), + session=next( + (record for record in ordered if record.get("record_type") == "session"), + None, + ), + terminal=next( + ( + record + for record in reversed(ordered) + if record.get("record_type") == "end" + ), + None, + ), + ) diff --git a/bead/deployment/jatos/api.py b/bead/deployment/jatos/api.py index 3599bf6..3799aab 100644 --- a/bead/deployment/jatos/api.py +++ b/bead/deployment/jatos/api.py @@ -47,10 +47,16 @@ def __init__(self, base_url: str, api_token: str) -> None: self.session = requests.Session() self.session.headers.update({"Authorization": f"Bearer {api_token}"}) + @property + def _api_url(self) -> str: + if self.base_url.endswith("/jatos"): + return f"{self.base_url}/api/v1" + return f"{self.base_url}/jatos/api/v1" + def upload_study(self, jzip_path: Path) -> dict[str, JsonValue]: """Upload study package to JATOS. - POST /api/v1/studies + POST /jatos/api/v1/study Parameters ---------- @@ -78,14 +84,27 @@ def upload_study(self, jzip_path: Path) -> dict[str, JsonValue]: if not jzip_path.exists(): raise FileNotFoundError(f".jzip file not found: {jzip_path}") - url = f"{self.base_url}/api/v1/studies" + url = f"{self._api_url}/study" with open(jzip_path, "rb") as f: - files = {"file": (jzip_path.name, f, "application/zip")} + files = {"study": (jzip_path.name, f, "application/zip")} response = self.session.post(url, files=files) response.raise_for_status() - return response.json() + payload: dict[str, JsonValue] = response.json() + data = payload.get("data") + return data if isinstance(data, dict) else payload + + def download_result_archive(self, study_id: int) -> bytes: + """Download the JATOS result archive for a study as ZIP bytes.""" + response = self.session.post( + f"{self._api_url}/results", + params={"studyId": study_id}, + headers={"Accept": "application/zip"}, + timeout=120, + ) + response.raise_for_status() + return response.content def list_studies(self) -> list[dict[str, JsonValue]]: """List all studies. diff --git a/bead/deployment/jatos/exporter.py b/bead/deployment/jatos/exporter.py index 721c85d..6eda85e 100644 --- a/bead/deployment/jatos/exporter.py +++ b/bead/deployment/jatos/exporter.py @@ -8,11 +8,8 @@ import json import re -import shutil -import tempfile import uuid import zipfile -from datetime import datetime from pathlib import Path from bead.data.base import BeadBaseModel, JsonValue @@ -22,8 +19,8 @@ class JATOSExporter(BeadBaseModel): """Exports jsPsych experiments as JATOS study packages (.jzip). A .jzip file is a ZIP archive containing: - - study.json: JATOS metadata - - experiment/: All experiment files (HTML, JS, CSS, data) + - A .jas file containing the JATOS study metadata + - The named assets directory containing all experiment files Attributes ---------- @@ -31,6 +28,8 @@ class JATOSExporter(BeadBaseModel): Title of the JATOS study. study_description : str Description of the study. + study_uuid : UUID | None + Stable study identity for reproducible exports and JATOS updates. Examples -------- @@ -41,6 +40,7 @@ class JATOSExporter(BeadBaseModel): study_title: str study_description: str = "" + study_uuid: uuid.UUID | None = None def export( self, @@ -91,33 +91,28 @@ def export( f"Required file not found: {experiment_dir / file}" ) - # create temporary directory for staging - with tempfile.TemporaryDirectory() as temp_dir: - temp_path = Path(temp_dir) - - # create study.json - study_json = self._create_study_json(component_title) - study_json_path = temp_path / "study.json" - study_json_path.write_text(json.dumps(study_json, indent=2)) - - # copy experiment files to temp/experiment/ - experiment_target = temp_path / "experiment" - shutil.copytree(experiment_dir, experiment_target) - - # create .jzip file - with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zipf: - # add study.json - zipf.write(study_json_path, "study.json") - - # add all experiment files - for file_path in experiment_target.rglob("*"): - if file_path.is_file(): - # archive name relative to temp_path - arcname = file_path.relative_to(temp_path) - zipf.write(file_path, arcname) + dir_name = self._sanitize_dirname(self.study_title) + study_json = self._create_study_json(component_title) + with zipfile.ZipFile(output_path, "w") as archive: + self._write_entry( + archive, f"{dir_name}.jas", json.dumps(study_json, indent=2).encode() + ) + for path in sorted(experiment_dir.rglob("*")): + if path.is_file() and path.resolve() != output_path.resolve(): + relative = path.relative_to(experiment_dir).as_posix() + self._write_entry( + archive, f"{dir_name}/{relative}", path.read_bytes() + ) + + @staticmethod + def _write_entry(archive: zipfile.ZipFile, name: str, data: bytes) -> None: + entry = zipfile.ZipInfo(name) + entry.create_system = 3 + entry.external_attr = (0o100644 & 0xFFFF) << 16 + archive.writestr(entry, data, compress_type=zipfile.ZIP_DEFLATED) def _create_study_json(self, component_title: str) -> dict[str, JsonValue]: - """Create JATOS study.json structure. + """Create the JATOS study descriptor. Parameters ---------- @@ -131,11 +126,11 @@ def _create_study_json(self, component_title: str) -> dict[str, JsonValue]: Notes ----- - The study.json follows JATOS v3 schema format. + The .jas file follows JATOS v3 schema format. """ - # generate UUIDs for study and component - study_uuid = str(uuid.uuid4()) - component_uuid = str(uuid.uuid4()) + study_uuid = self.study_uuid or uuid.uuid4() + component_uuid = uuid.uuid5(study_uuid, "component") + batch_uuid = uuid.uuid5(study_uuid, "batch") # sanitize title for directory name dir_name = self._sanitize_dirname(self.study_title) @@ -143,24 +138,37 @@ def _create_study_json(self, component_title: str) -> dict[str, JsonValue]: return { "version": "3", "data": { - "uuid": study_uuid, + "uuid": str(study_uuid), "title": self.study_title, "description": self.study_description, "dirName": dir_name, - "comments": f"Generated by bead {datetime.now().isoformat()}", + "comments": "Generated by bead", "jsonData": None, "componentList": ( { - "uuid": component_uuid, + "uuid": str(component_uuid), "title": component_title, - "htmlFilePath": "experiment/index.html", - "reloadable": True, + "htmlFilePath": "index.html", + "reloadable": False, "active": True, "comments": "", "jsonData": None, }, ), - "batchList": (), + "batchList": ( + { + "uuid": str(batch_uuid), + "title": "Default", + "active": True, + "allowedWorkerTypes": ( + "Jatos", + "PersonalSingle", + "PersonalMultiple", + "GeneralSingle", + "GeneralMultiple", + ), + }, + ), "groupStudy": False, "linearStudy": False, "allowPreview": True, diff --git a/bead/deployment/jspsych/config.py b/bead/deployment/jspsych/config.py index 0198e16..c29009d 100644 --- a/bead/deployment/jspsych/config.py +++ b/bead/deployment/jspsych/config.py @@ -16,6 +16,7 @@ "binary_choice", "forced_choice", "span_labeling", + "cloze", ] type UITheme = Literal["light", "dark", "auto"] @@ -243,6 +244,8 @@ class ExperimentConfig(dx.Model): show_click_target: bool = False minimum_duration_ms: int = 0 use_jatos: bool = True + consent_text: str | None = None + result_format: Literal["aggregate", "stream"] = "aggregate" prolific_completion_code: str | None = None slopit: dx.Embed[SlopitIntegrationConfig] = dx.field( default_factory=_default_slopit_integration diff --git a/bead/deployment/jspsych/copy-runtime.mjs b/bead/deployment/jspsych/copy-runtime.mjs new file mode 100644 index 0000000..7027956 --- /dev/null +++ b/bead/deployment/jspsych/copy-runtime.mjs @@ -0,0 +1,48 @@ +// Copy the scoped package manager dependencies into the deployable browser runtime. +import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; + +const require = createRequire(import.meta.url); +const entryPoints = { + jspsych: "jspsych.js", + "@jspsych/plugin-browser-check": "browser-check.js", + "@jspsych/plugin-fullscreen": "fullscreen.js", + "@jspsych/plugin-html-button-response": "html-button-response.js", + "@jspsych/plugin-html-keyboard-response": "html-keyboard-response.js", + "@jspsych/plugin-instructions": "instructions.js", + "@jspsych/plugin-survey-html-form": "survey-html-form.js", + "@jspsych/plugin-survey": "survey.js", +}; +const output = new URL("./dist/runtime/", import.meta.url); +await mkdir(output, { recursive: true }); +const manifest = {}; +async function copyAsset(name, source, packageName, version) { + // Published source maps are unnecessary at runtime and are not deployed. + let sourceText = (await readFile(source, "utf8")).replace(/(?:^\/\/#[ ]*sourceMappingURL=.*$|\/\*#[ ]*sourceMappingURL=.*?\*\/)/gm, ""); + if (name === "survey.css") { + // Use the browser's locally installed fonts. + sourceText = sourceText.replace(/@font-face\s*\{[^}]*https?:\/\/[^}]*\}/g, ""); + } + await writeFile(new URL(name, output), sourceText, "utf8"); + manifest[name] = { + package: packageName, + version, + sha256: createHash("sha256").update(sourceText).digest("hex"), + }; +} + +for (const [packageName, asset] of Object.entries(entryPoints)) { + const dist = dirname(require.resolve(packageName)); + const root = dirname(dist); + const { version } = JSON.parse(await readFile(join(root, "package.json"), "utf8")); + await copyAsset(asset, join(dist, "index.browser.min.js"), packageName, version); + if (packageName === "jspsych") { + await copyAsset("jspsych.css", join(root, "css", "jspsych.css"), packageName, version); + } else if (packageName === "@jspsych/plugin-survey") { + await copyAsset("survey.css", join(root, "css", "survey.css"), packageName, version); + } +} +await copyFile(new URL("./licenses/jspsych.txt", import.meta.url), new URL("jspsych.LICENSE", output)); +await writeFile(new URL("manifest.json", output), `${JSON.stringify(manifest, null, 2)}\n`); diff --git a/bead/deployment/jspsych/generator.py b/bead/deployment/jspsych/generator.py index 1cf3d1d..af41454 100644 --- a/bead/deployment/jspsych/generator.py +++ b/bead/deployment/jspsych/generator.py @@ -6,9 +6,10 @@ from __future__ import annotations +import hashlib import json import re -import warnings +import shutil from pathlib import Path from uuid import UUID @@ -83,8 +84,13 @@ def __init__( output_dir: Path, rating_config: RatingScaleConfig | None = None, choice_config: ChoiceConfig | None = None, + *, + slopit_browser_bundle: Path | None = None, + session_adapter: Path | None = None, ) -> None: self.config = config + self.slopit_browser_bundle = slopit_browser_bundle + self.session_adapter = session_adapter self.output_dir = Path(output_dir) self.rating_config = rating_config or RatingScaleConfig() self.choice_config = choice_config or ChoiceConfig() @@ -158,6 +164,17 @@ def generate( ... ) >>> # output_dir = generator.generate(lists, items, templates) """ + if self.config.slopit.enabled: + if not self.config.consent_text or not self.config.consent_text.strip(): + raise ValueError("Slopit capture requires consent_text") + if ( + self.config.slopit.profile == "response_controls" + and self.slopit_browser_bundle is None + ): + raise ValueError( + "The response-controls profile requires a slopit browser bundle" + ) + # validate inputs (no fallbacks) if not lists: raise ValueError( @@ -206,6 +223,11 @@ def generate( self._generate_config_file() self._copy_list_distributor_script() self._copy_gallery_bundle() + self._copy_runtime_assets() + if self.session_adapter is not None: + shutil.copyfile( + self.session_adapter, self.output_dir / "js" / "session-adapter.js" + ) # copy slopit bundle if enabled if self.config.slopit.enabled: @@ -215,6 +237,7 @@ def generate( if span_enabled: self._copy_span_plugin_scripts(span_wikidata) + self._write_build_hashes() return self.output_dir def _validate_item_references( @@ -356,7 +379,7 @@ def _write_trials_json( for exp_list in lists: list_trials: list[dict[str, JsonValue]] = [] - for trial_num, item_id in enumerate(exp_list.item_refs): + for trial_num, item_id in enumerate(exp_list.get_presentation_order()): item = items[item_id] template = templates[item.item_template_id] trial = create_trial( @@ -413,7 +436,7 @@ def _copy_list_distributor_script(self) -> None: OSError If copying fails. """ - dist_path = Path(__file__).parent / "dist" / "lib" / "list-distributor.js" + dist_path = Path(__file__).parent / "dist" / "list-distributor.global.js" output_path = self.output_dir / "js" / "list_distributor.js" if not dist_path.exists(): @@ -424,8 +447,7 @@ def _copy_list_distributor_script(self) -> None: ) try: - content = self._strip_esm_exports(dist_path.read_text()) - output_path.write_text(content) + shutil.copyfile(dist_path, output_path) except OSError as e: raise OSError( f"Failed to copy list_distributor.js to {output_path}: {e}. " @@ -438,13 +460,9 @@ def _copy_gallery_bundle(self) -> None: output_path = self.output_dir / "js" / "gallery-bundle.js" if not dist_path.exists(): - warnings.warn( - f"gallery-bundle.global.js not found at {dist_path}. " - f"Bead plugins will not be available in the experiment. " - f"Run 'npm run build:gallery' in the jspsych directory.", - stacklevel=2, + raise FileNotFoundError( + f"Browser plugin bundle missing at {dist_path}. Run pnpm build." ) - return try: output_path.write_text(dist_path.read_text()) @@ -482,6 +500,7 @@ def _generate_html( title=self.config.title, ui_theme=self.config.ui_theme, use_jatos=self.config.use_jatos, + session_adapter=self.session_adapter is not None, slopit_enabled=self.config.slopit.enabled, span_enabled=span_enabled, span_wikidata=span_wikidata, @@ -514,9 +533,23 @@ def _generate_experiment_script(self) -> None: slopit_config = None if self.config.slopit.enabled: slopit_config = { - "keystroke": self.config.slopit.keystroke.model_dump(), - "focus": self.config.slopit.focus.model_dump(), - "paste": self.config.slopit.paste.model_dump(), + "profile": self.config.slopit.profile, + "keystroke": { + "enabled": self.config.slopit.keystroke.enabled, + "captureKeyUp": self.config.slopit.keystroke.capture_key_up, + "includeModifiers": self.config.slopit.keystroke.include_modifiers, + }, + "focus": { + "enabled": self.config.slopit.focus.enabled, + "useVisibilityAPI": self.config.slopit.focus.use_visibility_api, + "useBlurFocus": self.config.slopit.focus.use_blur_focus, + }, + "paste": { + "enabled": self.config.slopit.paste.enabled, + "prevent": self.config.slopit.paste.prevent, + "capturePreview": self.config.slopit.paste.capture_preview, + "previewLength": self.config.slopit.paste.preview_length, + }, "target_selectors": self.config.slopit.target_selectors, } @@ -549,7 +582,7 @@ def _generate_experiment_script(self) -> None: # prepare instructions config for template instructions_is_multi_page = isinstance( self.config.instructions, InstructionsConfig - ) + ) and bool(self.config.instructions.pages) instructions_pages: list[dict[str, str | None]] = [] instructions_show_page_numbers = True instructions_allow_backwards = True @@ -587,6 +620,11 @@ def _generate_experiment_script(self) -> None: on_finish_url=on_finish_url, slopit_enabled=self.config.slopit.enabled, slopit_config=slopit_config, + consent_text=self.config.consent_text, + result_stream=self.config.result_format == "stream", + randomize_trial_order=self.config.randomize_trial_order, + debug_mode=self.config.distribution_strategy.debug_mode, + session_adapter=self.session_adapter is not None, # demographics variables demographics_enabled=demographics_enabled, demographics_title=demographics_title, @@ -625,7 +663,7 @@ def _copy_slopit_bundle(self) -> None: """ # look for slopit bundle in dist directory dist_dir = Path(__file__).parent / "dist" - bundle_path = dist_dir / "slopit-bundle.js" + bundle_path = self.slopit_browser_bundle or dist_dir / "slopit-bundle.global.js" if not bundle_path.exists(): raise FileNotFoundError( @@ -637,13 +675,53 @@ def _copy_slopit_bundle(self) -> None: output_path = self.output_dir / "js" / "slopit-bundle.js" try: - output_path.write_text(self._strip_esm_exports(bundle_path.read_text())) + shutil.copyfile(bundle_path, output_path) except OSError as e: raise OSError( f"Failed to copy slopit bundle to {output_path}: {e}. " f"Check write permissions." ) from e + def _copy_runtime_assets(self) -> None: + runtime = Path(__file__).parent / "dist" / "runtime" + if not (runtime / "manifest.json").is_file(): + raise FileNotFoundError( + "Pinned jsPsych assets are missing. Run pnpm build." + ) + shutil.copytree(runtime, self.output_dir / "runtime", dirs_exist_ok=True) + + def _write_build_hashes(self) -> None: + def digest(files: list[Path]) -> str: + checksum = hashlib.sha256() + for path in sorted(files): + relative_path = path.relative_to(self.output_dir).as_posix() + data = path.read_bytes() + checksum.update(f"{relative_path}\0{len(data)}\0".encode()) + checksum.update(data) + return checksum.hexdigest() + + data = self.output_dir / "data" + runtime = self.output_dir / "runtime" + scripts = self.output_dir / "js" + css = self.output_dir / "css" + hashes = { + "app_sha256": digest( + [ + self.output_dir / "index.html", + *scripts.rglob("*.js"), + *css.rglob("*.css"), + data / "config.json", + ] + ), + "items_sha256": digest( + [data / name for name in ("trials.json", "items.jsonl", "lists.jsonl")] + ), + "vendor_sha256": digest( + [path for path in runtime.rglob("*") if path.is_file()] + ), + } + (data / "build-hashes.json").write_text(json.dumps(hashes, indent=2)) + def _detect_span_usage( self, items: dict[UUID, Item], diff --git a/bead/deployment/jspsych/licenses/jspsych.txt b/bead/deployment/jspsych/licenses/jspsych.txt new file mode 100644 index 0000000..bb4e7ca --- /dev/null +++ b/bead/deployment/jspsych/licenses/jspsych.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2022 Joshua R. de Leeuw + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/bead/deployment/jspsych/package.json b/bead/deployment/jspsych/package.json index 9c8fc2c..a6a0495 100644 --- a/bead/deployment/jspsych/package.json +++ b/bead/deployment/jspsych/package.json @@ -3,6 +3,7 @@ "version": "0.3.0", "description": "TypeScript plugins and utilities for bead jsPsych experiment deployment", "private": true, + "packageManager": "pnpm@9.14.4", "type": "module", "exports": { "./plugins/*": { @@ -15,7 +16,7 @@ } }, "scripts": { - "build": "tsup", + "build": "tsup && tsup --config tsup.gallery.config.ts && node copy-runtime.mjs", "build:gallery": "tsup --config tsup.gallery.config.ts", "build:watch": "tsup --watch", "typecheck": "tsc --noEmit", @@ -30,7 +31,14 @@ "clean": "rm -rf dist" }, "dependencies": { - "@slopit/adapter-jspsych": "^0.1.0", + "@jspsych/plugin-browser-check": "2.1.0", + "@jspsych/plugin-fullscreen": "2.1.0", + "@jspsych/plugin-html-button-response": "2.1.0", + "@jspsych/plugin-html-keyboard-response": "2.1.0", + "@jspsych/plugin-instructions": "2.1.0", + "@jspsych/plugin-survey-html-form": "2.1.0", + "@jspsych/plugin-survey": "3.0.0", + "@slopit/adapter-jspsych": "0.1.0", "@slopit/behavioral": "^0.1.0", "@slopit/core": "^0.1.0" }, @@ -38,7 +46,7 @@ "@biomejs/biome": "^1.9.0", "@types/node": "^22.0.0", "jsdom": "^25.0.0", - "jspsych": "^8.0.0", + "jspsych": "8.4.0", "tsup": "^8.0.0", "typescript": "^5.7.0", "vitest": "^2.0.0" diff --git a/bead/deployment/jspsych/pnpm-lock.yaml b/bead/deployment/jspsych/pnpm-lock.yaml index 51008d3..2c9f76a 100644 --- a/bead/deployment/jspsych/pnpm-lock.yaml +++ b/bead/deployment/jspsych/pnpm-lock.yaml @@ -8,9 +8,30 @@ importers: .: dependencies: + '@jspsych/plugin-browser-check': + specifier: 2.1.0 + version: 2.1.0(jspsych@8.4.0) + '@jspsych/plugin-fullscreen': + specifier: 2.1.0 + version: 2.1.0(jspsych@8.4.0) + '@jspsych/plugin-html-button-response': + specifier: 2.1.0 + version: 2.1.0(jspsych@8.4.0) + '@jspsych/plugin-html-keyboard-response': + specifier: 2.1.0 + version: 2.1.0(jspsych@8.4.0) + '@jspsych/plugin-instructions': + specifier: 2.1.0 + version: 2.1.0(jspsych@8.4.0) + '@jspsych/plugin-survey': + specifier: 3.0.0 + version: 3.0.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(jspsych@8.4.0) + '@jspsych/plugin-survey-html-form': + specifier: 2.1.0 + version: 2.1.0(jspsych@8.4.0) '@slopit/adapter-jspsych': - specifier: ^0.1.0 - version: 0.1.0(jspsych@8.2.2) + specifier: 0.1.0 + version: 0.1.0(jspsych@8.4.0) '@slopit/behavioral': specifier: ^0.1.0 version: 0.1.0 @@ -28,8 +49,8 @@ importers: specifier: ^25.0.0 version: 25.0.1 jspsych: - specifier: ^8.0.0 - version: 8.2.2 + specifier: 8.4.0 + version: 8.4.0 tsup: specifier: ^8.0.0 version: 8.5.1(postcss@8.5.6)(typescript@5.9.3) @@ -433,6 +454,41 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jspsych/plugin-browser-check@2.1.0': + resolution: {integrity: sha512-jjqtiz/4u5keORwCE1BnG/GNLAx4SbT9KuFCtZcGqY5LHCC+aSWm7ivjezoQvzLD5UHrl6SGJ8uYa7Y+ZYYUWQ==} + peerDependencies: + jspsych: '>=7.1.0' + + '@jspsych/plugin-fullscreen@2.1.0': + resolution: {integrity: sha512-mPS3393R66Hm144LumXB2I8zHvXbUmF6e1+gZzdYm4nE5o5k0rLZZmuPRtEQl5+JFyEmk+tyH/CwL+KNGOD8cw==} + peerDependencies: + jspsych: '>=7.1.0' + + '@jspsych/plugin-html-button-response@2.1.0': + resolution: {integrity: sha512-AhJPePA8s/ount+QYtqfgMtEkz7g+j+bnhQ9XqxfsnK2f5MdnlakYtpjxW9YgFx9y0Gs7yb7OZk1+omcKlzaEQ==} + peerDependencies: + jspsych: '>=7.1.0' + + '@jspsych/plugin-html-keyboard-response@2.1.0': + resolution: {integrity: sha512-NmtYU9798mEJ6CLQREp6bNHo1e+Ca5zwAznBlREmpUMdOrqBhTLrF5T/Gg4t2MJHm4lFN/fwHJtt0g5vMAoYFg==} + peerDependencies: + jspsych: '>=7.1.0' + + '@jspsych/plugin-instructions@2.1.0': + resolution: {integrity: sha512-jg3bepI9axwenGMNGunmcnnsXn4V2xMhVrzfHUGkA7AP/TQLdS8aeNqwhq3SVy6EXPX8X+r/sr2GKHrXeViRFA==} + peerDependencies: + jspsych: '>=7.1.0' + + '@jspsych/plugin-survey-html-form@2.1.0': + resolution: {integrity: sha512-jM9xSaojD7+xqL7yVjn7FUmboH3QAFBAaNOLBSUNJNQpGaJmGRtjrmlPggLp24Bnjd/jkjnThFj+z88Mgr67gQ==} + peerDependencies: + jspsych: '>=7.1.0' + + '@jspsych/plugin-survey@3.0.0': + resolution: {integrity: sha512-2bvePlFEa9VAJK7AS6x2/B0SsswR8fmCbPPBzobzCvDz9wB5YIAX+ux5K12PEDQV2GaBekONat/WHuCv+noLJg==} + peerDependencies: + jspsych: '>=7.0.0' + '@rollup/rollup-android-arm-eabi@4.56.0': resolution: {integrity: sha512-LNKIPA5k8PF1+jAFomGe3qN3bbIgJe/IlpDBwuVjrDKrJhVWywgnJvflMt/zkbVNLFtF1+94SljYQS6e99klnw==} cpu: [arm] @@ -578,6 +634,14 @@ packages: '@types/node@22.19.7': resolution: {integrity: sha512-MciR4AKGHWl7xwxkBa6xUGxQJ4VBOmPTF7sL+iGzuahOFaO0jHCsuEfS80pan1ef4gWId1oWOweIhrDEYLuaOw==} + '@types/react-dom@19.3.0': + resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} + peerDependencies: + '@types/react': ^19.3.0 + + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + '@vitest/expect@2.1.9': resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==} @@ -675,6 +739,9 @@ packages: resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==} engines: {node: '>=18'} + csstype@3.2.4: + resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==} + data-urls@5.0.0: resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==} engines: {node: '>=18'} @@ -699,6 +766,9 @@ packages: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} + detect-browser@5.3.0: + resolution: {integrity: sha512-53rsFbGdwMwlF7qvCt0ypLM5V5/Mbl0szB7GPN8y9NCcbknYOeVVXdrXEq+90IwAfrrzt6Hd+u2E2ntakICU8w==} + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -823,8 +893,8 @@ packages: canvas: optional: true - jspsych@8.2.2: - resolution: {integrity: sha512-5Rs9WWXhSzrm/Nwtqjn/JmrKC4u7FpgDQLhDuqgl40eqYlmkxSkKXhoh07k3cYk6kyDonw0joGHNwRZUDPJ/KA==} + jspsych@8.4.0: + resolution: {integrity: sha512-wZfvw+mIgxDAmOGoJQSOQc4LEkJI/VmulGaHQoVQQapPUEHYZVCRcZzYTqPgK3o6IVfXlBx7pfa5ARQ+/TjI6g==} lilconfig@3.1.3: resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==} @@ -986,6 +1056,16 @@ packages: engines: {node: '>=16 || 14 >=14.17'} hasBin: true + survey-core@2.5.49: + resolution: {integrity: sha512-EAmi/xT4upI0G6OT5gcaR1gnFt++4OqQFsRjFqjIn2yeryJsXeylfdt+23sQchST17DIDu7SkOS+aEt9JrEQDQ==} + + survey-js-ui@2.5.49: + resolution: {integrity: sha512-OE2qCzPHRDfe4+Cp0FmaGpayVIzXH6Q0fTwhFo5FctlTH7tZl68ZJ9Wa2DclSnFXkdWw9+DmKfqHJXzeKJOUxQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + survey-core: 2.5.49 + symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} @@ -1409,6 +1489,40 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@jspsych/plugin-browser-check@2.1.0(jspsych@8.4.0)': + dependencies: + detect-browser: 5.3.0 + jspsych: 8.4.0 + + '@jspsych/plugin-fullscreen@2.1.0(jspsych@8.4.0)': + dependencies: + jspsych: 8.4.0 + + '@jspsych/plugin-html-button-response@2.1.0(jspsych@8.4.0)': + dependencies: + jspsych: 8.4.0 + + '@jspsych/plugin-html-keyboard-response@2.1.0(jspsych@8.4.0)': + dependencies: + jspsych: 8.4.0 + + '@jspsych/plugin-instructions@2.1.0(jspsych@8.4.0)': + dependencies: + jspsych: 8.4.0 + + '@jspsych/plugin-survey-html-form@2.1.0(jspsych@8.4.0)': + dependencies: + jspsych: 8.4.0 + + '@jspsych/plugin-survey@3.0.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(jspsych@8.4.0)': + dependencies: + jspsych: 8.4.0 + survey-core: 2.5.49 + survey-js-ui: 2.5.49(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(survey-core@2.5.49) + transitivePeerDependencies: + - '@types/react' + - '@types/react-dom' + '@rollup/rollup-android-arm-eabi@4.56.0': optional: true @@ -1484,12 +1598,12 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.56.0': optional: true - '@slopit/adapter-jspsych@0.1.0(jspsych@8.2.2)': + '@slopit/adapter-jspsych@0.1.0(jspsych@8.4.0)': dependencies: '@slopit/adapter-shared': 0.1.0 '@slopit/behavioral': 0.1.0 '@slopit/core': 0.1.0 - jspsych: 8.2.2 + jspsych: 8.4.0 '@slopit/adapter-shared@0.1.0': dependencies: @@ -1510,6 +1624,14 @@ snapshots: dependencies: undici-types: 6.21.0 + '@types/react-dom@19.3.0(@types/react@19.3.0)': + dependencies: + '@types/react': 19.3.0 + + '@types/react@19.3.0': + dependencies: + csstype: 3.2.4 + '@vitest/expect@2.1.9': dependencies: '@vitest/spy': 2.1.9 @@ -1603,6 +1725,8 @@ snapshots: '@asamuzakjp/css-color': 3.2.0 rrweb-cssom: 0.8.0 + csstype@3.2.4: {} + data-urls@5.0.0: dependencies: whatwg-mimetype: 4.0.0 @@ -1618,6 +1742,8 @@ snapshots: delayed-stream@1.0.0: {} + detect-browser@5.3.0: {} + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -1811,7 +1937,7 @@ snapshots: - supports-color - utf-8-validate - jspsych@8.2.2: + jspsych@8.4.0: dependencies: auto-bind: 4.0.0 random-words: 1.3.0 @@ -1968,6 +2094,14 @@ snapshots: tinyglobby: 0.2.15 ts-interface-checker: 0.1.13 + survey-core@2.5.49: {} + + survey-js-ui@2.5.49(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(survey-core@2.5.49): + dependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + survey-core: 2.5.49 + symbol-tree@3.2.4: {} thenify-all@1.6.0: diff --git a/bead/deployment/jspsych/src/plugins/cloze-dropdown.ts b/bead/deployment/jspsych/src/plugins/cloze-dropdown.ts index 3058f58..ad62738 100644 --- a/bead/deployment/jspsych/src/plugins/cloze-dropdown.ts +++ b/bead/deployment/jspsych/src/plugins/cloze-dropdown.ts @@ -33,7 +33,7 @@ export interface ClozeFieldConfig { slot_name?: string; position?: number; type: ClozeFieldType; - options?: string[]; + options?: (string | { value: string; label: string })[]; placeholder?: string; } @@ -47,6 +47,8 @@ interface BeadMetadata { export interface ClozeTrialParams { /** The text with gaps (use %% or {{slot_name}} for gaps) */ text: string | null; + prompt?: string; + canary?: string; /** Field configurations (auto-generated from unfilled_slots) */ fields: ClozeFieldConfig[]; /** Whether to require all fields to be filled */ @@ -74,6 +76,14 @@ const info: PluginInfo = { type: 8, // ParameterType.HTML_STRING default: null, }, + prompt: { + type: 8, // ParameterType.HTML_STRING + default: "", + }, + canary: { + type: 8, // ParameterType.HTML_STRING + default: "", + }, fields: { type: 13, // ParameterType.COMPLEX default: [], @@ -92,8 +102,18 @@ const info: PluginInfo = { default: {}, }, }, + data: {}, }; +function escapeHtml(value: string): string { + return value + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + /** * BeadClozeMultiPlugin - jsPsych plugin for fill-in-the-blank tasks */ @@ -107,41 +127,46 @@ class BeadClozeMultiPlugin implements JsPsychPlugin ({ - slot_name: slot.slot_name, - position: slot.position, - type: (slot.constraint_ids.length > 0 ? "dropdown" : "text") as ClozeFieldType, - options: [], // Would be populated from constraints in real implementation - placeholder: slot.slot_name, - })); - } + const fields = + trial.fields.length === 0 && trial.metadata.unfilled_slots + ? trial.metadata.unfilled_slots.map((slot) => ({ + slot_name: slot.slot_name, + position: slot.position, + type: "text" as const, + placeholder: slot.slot_name, + })) + : trial.fields; // Generate HTML let html = '
'; + if (trial.prompt) html += `
${trial.prompt}
`; if (trial.text) { // Replace gaps with input fields let processed_text = trial.text; - trial.fields.forEach((field, index) => { + fields.forEach((field, index) => { const field_id = `bead-cloze-field-${index}`; let field_html: string; - if (field.type === "dropdown" && field.options && field.options.length > 0) { + if (field.type === "dropdown") { + if (!field.options?.length) + throw new Error(`Cloze field ${field.slot_name ?? index} has no options`); // Dropdown field const optionsHtml = field.options - .map((opt) => ``) + .map((opt) => { + const { value, label } = typeof opt === "string" ? { value: opt, label: opt } : opt; + return ``; + }) .join(""); field_html = ` - + ${optionsHtml} `; @@ -149,21 +174,26 @@ class BeadClozeMultiPlugin implements JsPsychPlugin + placeholder="${escapeHtml(field.placeholder ?? "")}" /> `; } // Replace placeholder in text const placeholder = field.slot_name ? `{{${field.slot_name}}}` : "%%"; - processed_text = processed_text.replace(placeholder, field_html); + processed_text = processed_text.replace(placeholder, () => field_html); }); html += `
${processed_text}
`; } + if (trial.canary) { + html += ``; + } + // Continue button html += `
@@ -182,8 +212,9 @@ class BeadClozeMultiPlugin implements JsPsychPlugin { @@ -223,8 +254,8 @@ class BeadClozeMultiPlugin implements JsPsychPlugin { if (trial.require_all && continue_button) { // Check if all fields are filled - const all_filled = trial.fields.every((_field, index) => { - const response = responses[index.toString()]; + const all_filled = fields.every((field, index) => { + const response = responses[field.slot_name ?? index.toString()]; return response !== undefined && response.trim() !== ""; }); continue_button.disabled = !all_filled; @@ -233,11 +264,13 @@ class BeadClozeMultiPlugin implements JsPsychPlugin { // Gather all responses + const rt = performance.now() - start_time; const trial_data: Record = { ...trial.metadata, // Preserve all metadata responses: responses, response_times: response_times, - total_rt: performance.now() - start_time, + rt, + total_rt: rt, }; // Clear display diff --git a/bead/deployment/jspsych/src/types/jspsych.d.ts b/bead/deployment/jspsych/src/types/jspsych.d.ts index 8301ffc..2297788 100644 --- a/bead/deployment/jspsych/src/types/jspsych.d.ts +++ b/bead/deployment/jspsych/src/types/jspsych.d.ts @@ -41,6 +41,7 @@ export interface ParameterInfo { export interface PluginInfo { name: string; parameters: Record; + data?: Record; } /** Keyboard response info returned by getKeyboardResponse callback */ diff --git a/bead/deployment/jspsych/templates/experiment.js.template b/bead/deployment/jspsych/templates/experiment.js.template index 8432567..0462d27 100644 --- a/bead/deployment/jspsych/templates/experiment.js.template +++ b/bead/deployment/jspsych/templates/experiment.js.template @@ -8,8 +8,71 @@ // Global variables let distributor = null; -{% if slopit_enabled %} -let slopitExtension = null; +{% if result_stream %} +function createResultStream(append) { + const local = []; + const failed = []; + let sequence = 0; + let retries = 0; + let delivered = 0; + let pending = Promise.resolve(); + let closed = false; + function record(recordType, fields) { + if (closed) return; + const entry = { + ...fields, + schema_version: "1.0", + record_type: recordType, + seq: sequence++, + wall_ms: Date.now(), + perf_ms: performance.now(), + }; + if (!append) { + local.push(entry); + return; + } + const line = JSON.stringify(entry) + "\n"; + pending = pending.then(async () => { + for (const delay of [0, 250, 1000]) { + if (delay) { + retries++; + await new Promise(resolve => setTimeout(resolve, delay)); + } + try { + await append(line); + delivered++; + if (delay && entry.record_type !== "event") { + record("event", { event: "append_retry_succeeded", prior_seq: entry.seq }); + } + return; + } catch { + // Try to deliver the identical line and sequence number again. + } + } + failed.push(entry.seq); + }); + } + return { + record, + async finish(status) { + let flushing; + do { + flushing = pending; + await flushing; + } while (flushing !== pending); + record("end", { + status, failed_seqs: [...failed], + n_records_before_end: sequence, + n_acknowledged: append ? delivered : null, + n_retries: retries, + }); + closed = true; + await pending; + return failed.length === 0; + }, + records: () => structuredClone(local), + }; +} {% endif %} /** @@ -18,82 +81,139 @@ let slopitExtension = null; */ async function runExperiment() { try { + const params = new URLSearchParams( + {% if use_jatos %}jatos.urlQueryParameters ?? {% endif %}window.location.search + ); + const sessionAdapter = {% if session_adapter %}BeadSessionAdapter{% else %}{}{% endif %}; + {% if result_stream %} + const stream = createResultStream({% if use_jatos %}line => jatos.appendResultData(line){% else %}null{% endif %}); + {% if not use_jatos %} + window.beadResultRecords = stream.records; + {% endif %} + const hashes = await fetch("data/build-hashes.json").then(r => r.json()); + const sessionEvents = new AbortController(); + {% endif %} + const runtimeConfig = await fetch("data/config.json").then(r => r.json()); + let consented = {{ 'false' if consent_text else 'true' }}; + let withdrawn = false; + let sessionStarted = false; + let trialOnset = null; + {% if slopit_enabled %} + const captureLifetime = new AbortController(); + const captureConfig = {{ slopit_config | tojson }}; + if (captureConfig.profile === "response_controls" && + SlopitJsPsych.responseControlsSchemaVersion !== "1.0") { + throw new Error("The packaged slopit bundle lacks response-controls schema 1.0."); + } + window.addEventListener("pagehide", () => captureLifetime.abort(), { once: true }); + {% endif %} + // Load distribution config const distConfig = await fetch('data/distribution.json').then(r => r.json()); // Load lists from JSONL - const lists = await loadLists('data/lists.jsonl'); + const lists = await BeadLists.loadLists('data/lists.jsonl'); // Load items from JSONL - const items = await loadItems('data/items.jsonl'); - - {% if use_jatos %} - // Initialize list distributor (JATOS batch session) - distributor = new ListDistributor(distConfig, lists); - - // Assign list to this participant - const listIndex = await distributor.initialize(); - const assignedList = distributor.getAssignedList(); + const items = await BeadLists.loadItems('data/items.jsonl'); - console.log(`Assigned to list: ${assignedList.name} (index: ${listIndex})`); - {% else %} - // Local mode: use the first (only) list directly - const listIndex = 0; - const assignedList = lists[0]; - - console.log(`Local mode - using list: ${assignedList.name}`); - {% endif %} + const requestedSeed = {% if not use_jatos or debug_mode or session_adapter %}params.get("seed"){% else %}null{% endif %}; + const hasRequestedSeed = requestedSeed && /^\d{1,10}$/.test(requestedSeed) && Number(requestedSeed) <= 4294967295; + const seed = hasRequestedSeed ? Number(requestedSeed) : crypto.getRandomValues(new Uint32Array(1))[0]; + const seedSource = hasRequestedSeed ? "url" : "crypto"; - {% if slopit_enabled %} - // Initialize slopit extension - slopitExtension = new SlopitExtension({ - keystroke: {{ slopit_config.keystroke | tojson }}, - focus: {{ slopit_config.focus | tojson }}, - paste: {{ slopit_config.paste | tojson }}, - targetSelectors: {{ slopit_config.target_selectors | tojson }} - }); - {% endif %} + let listIndex; + let listSource; + if (sessionAdapter.assignList) { + ({ index: listIndex, source: listSource } = await sessionAdapter.assignList(lists, seed)); + } else { + {% if use_jatos %} + distributor = new BeadLists.ListDistributor(distConfig, lists); + listIndex = await distributor.initialize(); + listSource = "jatos"; + {% else %} + const replayList = params.get("list"); + listIndex = replayList === null ? 0 : lists.findIndex( + list => String(list.list_number) === replayList || list.id === replayList); + listSource = replayList === null ? "default" : "url"; + {% endif %} + } + const assignedList = lists[listIndex]; + if (!assignedList) throw new Error("Unknown assigned list."); + console.log("Assigned list:", assignedList.name, listIndex); // Initialize jsPsych const jsPsych = initJsPsych({ + display_element: "jspsych-target", {% if slopit_enabled %} extensions: [ - { type: slopitExtension } + { type: SlopitJsPsych.SlopitExtension } ], {% endif %} - {% if use_jatos %} - on_trial_start: jatos.addAbortButton, - {% endif %} - on_finish: async function() { - {% if use_jatos %} - // Mark as completed in batch session - if (distributor) { - await distributor.markCompleted(); + on_trial_start: function(trial) { + {% if result_stream %} + if (sessionStarted) { + trialOnset = { start_perf_ms: performance.now(), start_wall_ms: Date.now() }; + const onset = trialOnset; + queueMicrotask(() => { + const display = jsPsych.getDisplayElement(); + onset.onset_perf_ms = performance.now(); + onset.onset_wall_ms = Date.now(); + const canaries = [...display.querySelectorAll(".canary")]; + const originallyHidden = canaries.map(node => node.hidden); + canaries.forEach(node => { node.hidden = true; }); + onset.display_text = display.innerText; + canaries.forEach((node, index) => { node.hidden = originallyHidden[index]; }); + onset.canary_text = canaries.map(node => node.textContent.trim()).join(" ") || null; + requestAnimationFrame(time => { onset.onset_frame_perf_ms = time; }); + }); } {% endif %} - - {% if use_jatos %} - // Submit data and end study - const resultData = jsPsych.data.get().json(); - {% if on_finish_url %} - jatos.submitResultData(resultData) - .then(() => jatos.endStudyAndRedirect("{{ on_finish_url }}")) - .catch((error) => { - console.error("Failed to submit data:", error); - jatos.endStudyAndRedirect("{{ on_finish_url }}"); - }); - {% else %} - jatos.submitResultData(resultData) - .then(() => jatos.endStudy(true)) - .catch((error) => { - console.error("Failed to submit data:", error); - jatos.endStudy(false); - }); + }, + {% if result_stream %} + on_data_update: function(data) { + if (!sessionStarted || !trialOnset || !consented) return; + stream.record("trial", { + ...data, + ...trialOnset, + offset_perf_ms: performance.now(), + offset_wall_ms: Date.now(), + }); + trialOnset = null; + }, + {% endif %} + on_finish: async function() { + document.querySelector(".bead-withdraw")?.remove(); + {% if slopit_enabled %} + captureLifetime.abort(); {% endif %} - {% else %} - {% if on_finish_url %} - window.location.href = "{{ on_finish_url }}"; + {% if result_stream %} + sessionEvents.abort(); + const delivered = sessionStarted ? await stream.finish(withdrawn ? "withdrawn" : "completed") : true; {% endif %} + {% if use_jatos %} + if (!consented || withdrawn) { + await jatos.endStudy(false); + return; + } + try { + {% if result_stream %} + if (!delivered) throw new Error("Some result records could not be delivered."); + {% else %} + await jatos.submitResultData(jsPsych.data.get().json()); + {% endif %} + if (distributor) await distributor.markCompleted(); + {% if on_finish_url %} + await jatos.endStudyAndRedirect({{ on_finish_url | tojson }}); + {% else %} + await jatos.endStudy(true); + {% endif %} + } catch (error) { + console.error("Failed to submit data:", error); + await jatos.endStudy(false); + } + {% elif on_finish_url %} + if (consented && !withdrawn) window.location.href = {{ on_finish_url | tojson }}; {% endif %} }, show_progress_bar: {{ 'true' if show_progress_bar else 'false' }}, @@ -112,6 +232,7 @@ async function runExperiment() { jatos_study_result_id: jatos.studyResultId, jatos_component_result_id: jatos.componentResultId, assigned_list_index: listIndex, + list_source: listSource, assigned_list_name: assignedList.name, assigned_list_id: assignedList.id, experiment_start_time: new Date().toISOString(), @@ -120,14 +241,33 @@ async function runExperiment() { jsPsych.data.addProperties({ experiment_title: "{{ title }}", assigned_list_index: listIndex, + list_source: listSource, assigned_list_name: assignedList.name, assigned_list_id: assignedList.id, experiment_start_time: new Date().toISOString(), }); {% endif %} + jsPsych.randomization.setSeed(String(seed)); + jsPsych.data.addProperties({ seed, seed_source: seedSource }); + // Build timeline - const timeline = []; + const timeline = [...(sessionAdapter.beforeConsent?.() ?? [])]; + {% if consent_text %} + timeline.push({ + type: jsPsychHtmlButtonResponse, + stimulus: {{ consent_text | tojson }}, + choices: ["I consent", "I do not consent"], + on_finish(data) { + consented = data.response === 0; + if (!consented) { + jsPsych.abortExperiment("

You declined to participate.

"); + return; + } + startSession(); + }, + }); + {% endif %} // Demographics form (if enabled, appears before instructions) {% if demographics_enabled %} @@ -236,7 +376,11 @@ async function runExperiment() { // Load pre-generated trials for this list const trialsData = await fetch('data/trials.json').then(r => r.json()); - const listTrials = trialsData[assignedList.id]; + const trialDefinitions = trialsData[assignedList.id]; + const defaultOrder = trialDefinitions {% if randomize_trial_order %}&& jsPsych.randomization.shuffle(trialDefinitions){% endif %}; + const context = { seed, assignedList, listSource }; + const sessionPlan = sessionAdapter.plan?.(trialDefinitions, context) ?? { trials: defaultOrder }; + const listTrials = sessionPlan.trials; if (!listTrials || listTrials.length === 0) { throw new Error( @@ -259,8 +403,72 @@ async function runExperiment() { 'bead-multi-select': BeadMultiSelectPlugin, }; + function startSession() { + sessionStarted = true; + const contextData = sessionAdapter.sessionData?.(context) ?? {}; + if (contextData.trialProperties) jsPsych.data.addProperties(contextData.trialProperties); + {% if result_stream %} + stream.record("session", { + ...hashes, + session_id: {% if use_jatos %}String(jatos.componentResultId){% else %}crypto.randomUUID(){% endif %}, + jspsych_version: jsPsych.version(), + experiment: runtimeConfig.title, + ...contextData.sessionProperties, + ...sessionPlan.metadata, + list: assignedList.list_number, + list_id: assignedList.id, + list_source: listSource, + seed, + seed_source: seedSource, + {% if use_jatos %} + prolific_pid: jatos.urlQueryParameters.PROLIFIC_PID || null, + jatos_worker_id: jatos.workerId, + jatos_study_result_id: jatos.studyResultId, + jatos_component_result_id: jatos.componentResultId, + {% endif %} + }); + stream.record("plan", { n_trials: listTrials.length, trials: listTrials }); + {% endif %} + + {% if consent_text %} + const withdraw = document.createElement("button"); + withdraw.type = "button"; + withdraw.textContent = "Withdraw from study"; + withdraw.className = "bead-withdraw"; + withdraw.addEventListener("click", () => { + withdrawn = true; + consented = false; + {% if slopit_enabled %} + captureLifetime.abort(); + {% endif %} + withdraw.remove(); + {% if result_stream %} + stream.record("event", { event: "withdrawal" }); + {% endif %} + jsPsych.abortExperiment("

You withdrew from the study.

"); + }, { once: true }); + document.body.append(withdraw); + {% endif %} + {% if result_stream %} + const options = { signal: sessionEvents.signal }; + window.addEventListener("pagehide", (event) => stream.record("event", { + event: "pagehide", trusted: event.isTrusted, persisted: event.persisted, + }), { ...options, once: true }); + for (const type of ["blur", "focus"]) { + window.addEventListener(type, event => stream.record("event", { + event: type, trusted: event.isTrusted, + }), options); + } + document.addEventListener("visibilitychange", event => stream.record("event", { + event: "visibilitychange", + trusted: event.isTrusted, + visibility_state: document.visibilityState, + }), options); + {% endif %} + } + timeline.push(...(sessionAdapter.beforeTrials?.(context) ?? [])); // Add pre-generated trials to timeline, resolving plugin types - for (const trial of listTrials) { + for (const [planIndex, trial] of listTrials.entries()) { const pluginClass = pluginRegistry[trial.type]; if (!pluginClass) { throw new Error( @@ -268,8 +476,34 @@ async function runExperiment() { `Available: ${Object.keys(pluginRegistry).join(', ')}` ); } - timeline.push({ ...trial, type: pluginClass }); + const node = { + ...trial, + type: pluginClass, + data: { ...trial.data, plan_index: planIndex, list_number: assignedList.list_number }, + }; + sessionAdapter.configureTrial?.(node, context); + {% if slopit_enabled %} + const targetSelector = captureConfig.target_selectors[trial.data?.task_type] ?? + captureConfig.target_selectors[trial.type] ?? + captureConfig.target_selectors[runtimeConfig.experiment_type]; + if (targetSelector) { + node.extensions = [{ + type: SlopitJsPsych.SlopitExtension, + params: captureConfig.profile === "response_controls" ? + { responseControls: { targetSelector, hasConsent: () => consented, signal: captureLifetime.signal } } : + { + targetSelector, + keystroke: captureConfig.keystroke, + focus: captureConfig.focus, + paste: captureConfig.paste, + }, + }]; + } + {% endif %} + timeline.push(node); + timeline.push(...(sessionAdapter.afterTrial?.(node, context) ?? [])); } + timeline.push(...(sessionAdapter.afterTrials?.(context) ?? [])); // Completion timeline.push({ @@ -287,13 +521,16 @@ async function runExperiment() {
`, choices: "NO_KEYS", - trial_duration: {% if on_finish_url %}2000{% else %}null{% endif %}, + trial_duration: 800, data: { trial_type: 'completion' } }); // Run experiment + {% if not consent_text %} + startSession(); + {% endif %} await jsPsych.run(timeline); } catch (error) { diff --git a/bead/deployment/jspsych/templates/index.html b/bead/deployment/jspsych/templates/index.html index 8ddcac1..575cf90 100644 --- a/bead/deployment/jspsych/templates/index.html +++ b/bead/deployment/jspsych/templates/index.html @@ -5,29 +5,22 @@ {{ title }} - - - - - - - - + + - - - - - - - - - - - + + + + + {% if session_adapter %} + + + + {% endif %} + {% if use_jatos %} @@ -39,20 +32,15 @@ + {% if session_adapter %} + + {% endif %} {% if slopit_enabled %} {% endif %} - {% if span_enabled %} - - - - {% if span_wikidata %} - - {% endif %} - {% endif %}
diff --git a/bead/deployment/jspsych/trials.py b/bead/deployment/jspsych/trials.py index 631bc82..611aeb8 100644 --- a/bead/deployment/jspsych/trials.py +++ b/bead/deployment/jspsych/trials.py @@ -307,6 +307,9 @@ def create_trial( >>> trial["type"] 'bead-slider-rating' """ + if template.task_type == "cloze" or experiment_config.experiment_type == "cloze": + return _create_cloze_trial(item, template, trial_number) + # standalone span_labeling experiment type if experiment_config.experiment_type == "span_labeling": span_display = experiment_config.span_display or SpanDisplayConfig() @@ -370,6 +373,57 @@ def create_trial( ) +def _create_cloze_trial( + item: Item, template: ItemTemplate, trial_number: int +) -> dict[str, JsonValue]: + spec = template.task_spec + if spec is None or not spec.cloze_fields: + raise ValueError(f"Cloze template {template.name!r} requires explicit fields") + text = item.rendered_elements.get("sentence") + if not text: + raise ValueError(f"Cloze item {item.id} has no rendered sentence") + + fields: list[JsonValue] = [] + names: list[str] = [] + for field in spec.cloze_fields: + if not field.name or field.name in names: + raise ValueError(f"Missing or duplicate cloze field name: {field.name!r}") + if text.count("{{" + field.name + "}}") != 1: + raise ValueError(f"Cloze field {field.name!r} must occur exactly once") + values = [option.value for option in field.options] + if "" in values or len(set(values)) != len(values): + raise ValueError(f"Cloze field {field.name!r} has invalid option values") + names.append(field.name) + fields.append( + { + "slot_name": field.name, + "type": "dropdown" if field.options else "text", + "options": [ + {"value": option.value, "label": option.label or option.value} + for option in field.options + ], + "placeholder": field.placeholder or "", + } + ) + + return { + "type": "bead-cloze-multi", + "text": text, + "prompt": ( + spec.prompt + if template.presentation_spec.display_format.get("show_prompt", True) + else "" + ), + "fields": fields, + "require_all": spec.cloze_require_all, + "data": { + **_serialize_item_metadata(item, template), + "trial_number": trial_number, + "response_field_names": names, + }, + } + + def _create_likert_trial( item: Item, template: ItemTemplate, diff --git a/bead/deployment/jspsych/tsup.config.ts b/bead/deployment/jspsych/tsup.config.ts index 5b74f63..fe457d9 100644 --- a/bead/deployment/jspsych/tsup.config.ts +++ b/bead/deployment/jspsych/tsup.config.ts @@ -13,8 +13,6 @@ export default defineConfig({ "lib/randomizer": "src/lib/randomizer.ts", "lib/span-renderer": "src/lib/span-renderer.ts", "lib/wikidata-search": "src/lib/wikidata-search.ts", - // Slopit bundle (behavioral capture) - "slopit-bundle": "src/slopit/index.ts", }, format: ["esm"], dts: false, // browser code, no type exports needed diff --git a/bead/deployment/jspsych/tsup.gallery.config.ts b/bead/deployment/jspsych/tsup.gallery.config.ts index 9612b0b..d507daa 100644 --- a/bead/deployment/jspsych/tsup.gallery.config.ts +++ b/bead/deployment/jspsych/tsup.gallery.config.ts @@ -1,6 +1,6 @@ import { defineConfig } from "tsup"; -export default defineConfig({ +export default defineConfig([{ entry: { "gallery-bundle": "src/gallery/gallery-bundle.ts", }, @@ -13,7 +13,7 @@ export default defineConfig({ splitting: false, treeshake: true, minify: false, - // jspsych is loaded from CDN as a global; keep it external + // Bead plugins depend only on local jsPsych type declarations. external: ["jspsych"], outDir: "dist", esbuildOptions(options) { @@ -21,4 +21,20 @@ export default defineConfig({ js: "/* @bead/jspsych-gallery - Interactive demo bundle */", }; }, -}); +}, { + entry: { "slopit-bundle": "src/slopit/index.ts" }, + format: ["iife"], + globalName: "SlopitJsPsych", + dts: false, + target: "es2020", + outDir: "dist", + noExternal: [/^@slopit\//, /^jspsych$/], + minify: true, +}, { + entry: { "list-distributor": "src/lib/list-distributor.ts" }, + format: ["iife"], + globalName: "BeadLists", + dts: false, + target: "es2020", + outDir: "dist", +}]); diff --git a/bead/items/item_template.py b/bead/items/item_template.py index 2cc6a56..3fcf531 100644 --- a/bead/items/item_template.py +++ b/bead/items/item_template.py @@ -130,6 +130,21 @@ class ScalePointLabel(BeadBaseModel): label: str +class ClozeOption(BeadBaseModel): + """A cloze choice with a stored value and an optional display label.""" + + value: str + label: str | None = None + + +class ClozeFieldSpec(BeadBaseModel): + """A named gap and its choices. A gap without choices accepts text.""" + + name: str + options: tuple[dx.Embed[ClozeOption], ...] = () + placeholder: str | None = None + + class TaskSpec(BeadBaseModel): """Parameters for the response collection task. @@ -164,6 +179,8 @@ class TaskSpec(BeadBaseModel): text_validation_pattern: str | None = None max_length: int | None = None span_spec: dx.Embed[SpanSpec] | None = None + cloze_fields: tuple[dx.Embed[ClozeFieldSpec], ...] = () + cloze_require_all: bool = True @dx.validates("prompt") def _check_prompt(self, value: str) -> str: diff --git a/pyproject.toml b/pyproject.toml index 68a1616..42003a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -109,6 +109,12 @@ bead = "bead.cli.main:cli" [project.entry-points."lairs.codecs"] bead = "bead.interop.layers.codec:BeadCodec" +[tool.hatch.build] +artifacts = [ + "bead/deployment/jspsych/dist/**/*.js", + "bead/deployment/jspsych/dist/runtime/*", +] + [tool.pytest.ini_options] testpaths = ["tests", "docs/user-guide/cli"] norecursedirs = ["tests/fixtures", ".hypothesis"] diff --git a/tests/data_collection/test_result_stream.py b/tests/data_collection/test_result_stream.py new file mode 100644 index 0000000..2a2f728 --- /dev/null +++ b/tests/data_collection/test_result_stream.py @@ -0,0 +1,78 @@ +"""Tests for JATOS archive loading and partial trial normalization.""" + +import json +import zipfile + +from bead.data_collection import ( + jatos_results_to_annotation_records, + load_jatos_result_archive, + parse_jatos_result_stream, +) + + +def test_archived_partial_stream_keeps_duplicates_and_named_answers(tmp_path) -> None: + records = [ + {"record_type": "session", "seq": 0, "prolific_pid": "study-id"}, + { + "record_type": "trial", + "seq": 3, + "item_id": "stable-item", + "template_name": "duration", + "response_field_names": ["preposition", "numeral", "unit"], + "responses": {"preposition": "in", "numeral": None, "unit": "millenia"}, + }, + {"record_type": "plan", "seq": 1, "trials": []}, + {"record_type": "event", "seq": 4, "event": "pagehide"}, + ] + delivered = [*records, records[1]] + raw = "\n".join(json.dumps(record) for record in delivered) + '\n{"truncated"' + path = tmp_path / "results.zip" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr( + "metadata.json", + json.dumps( + { + "data": [ + { + "studyId": 2, + "studyResults": [ + { + "id": 6, + "workerId": 9, + "componentResults": [ + { + "id": 11, + "componentId": 1, + "componentState": "ABORTED", + }, + { + "id": 12, + "componentId": 1, + "componentState": "STARTED", + }, + ], + } + ], + } + ], + } + ), + ) + archive.writestr("study_result_6/comp_result_11/data.txt", raw) + results = load_jatos_result_archive(path) + assert results[0]["data"] == raw + assert results[1]["data"] is None + stream = parse_jatos_result_stream(raw) + assert stream is not None + assert stream.records == tuple(delivered) + assert stream.missing_seq_ranges == ((2, 2),) + assert stream.malformed_line_numbers == (6,) + assert stream.terminal is None + assert stream.trials == (records[1],) + assert [ + (a.annotator_id, a.item_id, a.question_name, a.response_label) + for a in jatos_results_to_annotation_records(results) + ] == [ + ("study-id", "stable-item", "duration.preposition", "in"), + ("study-id", "stable-item", "duration.unit", "millenia"), + ] diff --git a/tests/deployment/jatos/test_api.py b/tests/deployment/jatos/test_api.py index 6e7d367..ac5f318 100644 --- a/tests/deployment/jatos/test_api.py +++ b/tests/deployment/jatos/test_api.py @@ -45,7 +45,8 @@ def test_upload_study(tmp_path: Path) -> None: # Verify the request was made correctly mock_session.post.assert_called_once() call_args = mock_session.post.call_args - assert call_args[0][0] == "https://jatos.example.com/api/v1/studies" + assert call_args[0][0] == "https://jatos.example.com/jatos/api/v1/study" + assert set(call_args.kwargs["files"]) == {"study"} def test_upload_study_missing_file(tmp_path: Path) -> None: diff --git a/tests/deployment/jatos/test_exporter.py b/tests/deployment/jatos/test_exporter.py index 8743aa1..aa20f9d 100644 --- a/tests/deployment/jatos/test_exporter.py +++ b/tests/deployment/jatos/test_exporter.py @@ -44,26 +44,26 @@ def test_jzip_structure(sample_experiment_dir: Path, jzip_output_path: Path) -> with zipfile.ZipFile(jzip_output_path, "r") as zipf: namelist = zipf.namelist() - # Check for study.json - assert "study.json" in namelist + # Check for test_study.jas + assert "test_study.jas" in namelist # Check for experiment files - assert "experiment/index.html" in namelist - assert "experiment/css/experiment.css" in namelist - assert "experiment/js/experiment.js" in namelist - assert "experiment/data/config.json" in namelist - assert "experiment/data/timeline.json" in namelist + assert "test_study/index.html" in namelist + assert "test_study/css/experiment.css" in namelist + assert "test_study/js/experiment.js" in namelist + assert "test_study/data/config.json" in namelist + assert "test_study/data/timeline.json" in namelist def test_study_json_schema(sample_experiment_dir: Path, jzip_output_path: Path) -> None: - """Test study.json follows JATOS v3 schema.""" + """Test test_study.jas follows JATOS v3 schema.""" exporter = JATOSExporter( study_title="Test Study", study_description="Test Description" ) exporter.export(sample_experiment_dir, jzip_output_path) with zipfile.ZipFile(jzip_output_path, "r") as zipf: - study_json_content = zipf.read("study.json") + study_json_content = zipf.read("test_study.jas") study_json = json.loads(study_json_content) # Check top-level structure @@ -91,7 +91,7 @@ def test_study_json_schema(sample_experiment_dir: Path, jzip_output_path: Path) def test_study_json_component( sample_experiment_dir: Path, jzip_output_path: Path ) -> None: - """Test study.json has correct component configuration.""" + """Test test_study.jas has correct component configuration.""" exporter = JATOSExporter( study_title="Test Study", study_description="Test Description", @@ -103,7 +103,7 @@ def test_study_json_component( ) with zipfile.ZipFile(jzip_output_path, "r") as zipf: - study_json_content = zipf.read("study.json") + study_json_content = zipf.read("test_study.jas") study_json = json.loads(study_json_content) components = study_json["data"]["componentList"] @@ -116,7 +116,7 @@ def test_study_json_component( assert "active" in component assert component["title"] == "Main Experiment" - assert component["htmlFilePath"] == "experiment/index.html" + assert component["htmlFilePath"] == "index.html" assert component["active"] is True @@ -129,7 +129,7 @@ def test_sanitize_dirname(sample_experiment_dir: Path, jzip_output_path: Path) - exporter.export(sample_experiment_dir, jzip_output_path) with zipfile.ZipFile(jzip_output_path, "r") as zipf: - study_json_content = zipf.read("study.json") + study_json_content = zipf.read("my_study_2024.jas") study_json = json.loads(study_json_content) dirname = study_json["data"]["dirName"] @@ -181,19 +181,19 @@ def test_experiment_files_preserved( with zipfile.ZipFile(jzip_output_path, "r") as zipf: # Read HTML file - html_content = zipf.read("experiment/index.html").decode("utf-8") + html_content = zipf.read("test_study/index.html").decode("utf-8") assert "Test Experiment" in html_content # Read CSS file - css_content = zipf.read("experiment/css/experiment.css").decode("utf-8") + css_content = zipf.read("test_study/css/experiment.css").decode("utf-8") assert "body { margin: 0; }" in css_content # Read JS file - js_content = zipf.read("experiment/js/experiment.js").decode("utf-8") + js_content = zipf.read("test_study/js/experiment.js").decode("utf-8") assert "console.log('test');" in js_content # Read config.json - config_content = zipf.read("experiment/data/config.json").decode("utf-8") + config_content = zipf.read("test_study/data/config.json").decode("utf-8") config_json = json.loads(config_content) assert config_json["title"] == "Test" @@ -210,7 +210,7 @@ def test_custom_component_title( ) with zipfile.ZipFile(jzip_output_path, "r") as zipf: - study_json_content = zipf.read("study.json") + study_json_content = zipf.read("test_study.jas") study_json = json.loads(study_json_content) component = study_json["data"]["componentList"][0] @@ -227,6 +227,22 @@ def test_zip_file_compression( # Check that it's a valid ZIP file with compression with zipfile.ZipFile(jzip_output_path, "r") as zipf: # Get info about a file - info = zipf.getinfo("study.json") + info = zipf.getinfo("test_study.jas") # ZIP_DEFLATED = 8 assert info.compress_type == zipfile.ZIP_DEFLATED + + +def test_explicit_study_id_makes_jzip_repeatable( + sample_experiment_dir, tmp_path +) -> None: + exporter = JATOSExporter(study_title="Test Study", study_uuid=uuid.uuid4()) + first = tmp_path / "first.jzip" + second = tmp_path / "second.jzip" + exporter.export(sample_experiment_dir, first) + exporter.export(sample_experiment_dir, second) + assert first.read_bytes() == second.read_bytes() + with zipfile.ZipFile(first) as archive: + study = json.loads(archive.read("test_study.jas"))["data"] + assert study["uuid"] == str(exporter.study_uuid) + assert study["batchList"][0]["active"] is True + assert study["componentList"][0]["reloadable"] is False diff --git a/tests/deployment/jspsych/test_plugins.py b/tests/deployment/jspsych/test_plugins.py index 2a141b7..6d596bb 100644 --- a/tests/deployment/jspsych/test_plugins.py +++ b/tests/deployment/jspsych/test_plugins.py @@ -148,7 +148,7 @@ def test_slopit_source_exports() -> None: def test_slopit_bundle_exists() -> None: """Test that compiled slopit bundle exists in dist/.""" - bundle_path = Path("bead/deployment/jspsych/dist/slopit-bundle.js") + bundle_path = Path("bead/deployment/jspsych/dist/slopit-bundle.global.js") assert bundle_path.exists(), "slopit-bundle.js should exist after build" From 1d18a91721d6f61a009755162b6f85d3d8d801a9 Mon Sep 17 00:00:00 2001 From: Aaron Steven White Date: Sun, 22 Nov 2026 16:02:23 -0500 Subject: [PATCH 2/2] Documents offline deployment and response control capture. --- bead/config/deployment.py | 5 +++- bead/deployment/jspsych/config.py | 4 +++ docs/user-guide/api/deployment.md | 42 +++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/bead/config/deployment.py b/bead/config/deployment.py index fee7276..5748e86 100644 --- a/bead/config/deployment.py +++ b/bead/config/deployment.py @@ -89,6 +89,7 @@ def _default_target_selectors() -> dict[str, str]: "forced_choice": ".bead-choice-button", "cloze": ".bead-cloze-field, #bead-cloze-continue", "binary_choice": ".bead-binary-button", + "bead-slider-rating": ".bead-slider-input, #bead-slider-continue", } @@ -106,7 +107,9 @@ class SlopitIntegrationConfig(dx.Model): paste : SlopitPasteConfig Paste event capture settings. target_selectors : dict[str, str] - CSS selectors for capture targets by task type. + CSS selectors for capture targets by task type or plugin name. + profile : Literal["legacy", "response_controls"] + Capture profile applied after affirmative consent. """ enabled: bool = False diff --git a/bead/deployment/jspsych/config.py b/bead/deployment/jspsych/config.py index c29009d..f094167 100644 --- a/bead/deployment/jspsych/config.py +++ b/bead/deployment/jspsych/config.py @@ -220,6 +220,10 @@ class ExperimentConfig(dx.Model): Minimum trial duration in milliseconds (>= 0). use_jatos : bool Enable JATOS integration. + consent_text : str | None + Consent screen shown before collecting behavioral data. + result_format : Literal["aggregate", "stream"] + Store one result array or append records as a session progresses. prolific_completion_code : str | None Prolific completion code; when set, ``on_finish_url`` is auto-generated. diff --git a/docs/user-guide/api/deployment.md b/docs/user-guide/api/deployment.md index 105b2c0..10efb90 100644 --- a/docs/user-guide/api/deployment.md +++ b/docs/user-guide/api/deployment.md @@ -689,3 +689,45 @@ print("JATOS package created") - [Training module](training.md): Active learning with convergence detection - [CLI reference](../cli/deployment.md): Command-line equivalents - [Gallery example](https://github.com/FACTSlab/bead/blob/main/gallery/eng/argument_structure/generate_deployment.py): Full working script + +## Offline jsPsych studies and named cloze tasks + +Build the browser assets with `pnpm install --frozen-lockfile` and +`pnpm build` in `bead/deployment/jspsych` when working from a source +checkout. The Python release contains the built assets. The generated +`runtime/manifest.json` records the jsPsych package versions and content +hashes. JATOS supplies its own `jatos.js` at study launch. + +For a cloze item, use `task_type="cloze"` and define +`TaskSpec.cloze_fields` with one `ClozeFieldSpec` per named gap. The +item’s rendered sentence contains each gap once, for instance +`{{preposition}}`. A field with `ClozeOption` entries renders a dropdown. +The browser displays each option’s label and stores its value. A field +with no choices renders a text input. The plugin records values and +response times by field name. + +Set `ExperimentConfig(result_format="stream", ...)` to append a JATOS +record at session start, for the trial plan, after each completed trial, +and at completion. The default aggregate format still uses one submit at +the end. The stream parser exposes arrival order, one record per sequence, +missing sequence ranges, and the terminal record if one arrived. +`load_jatos_result_archive` accepts a JATOS ZIP result export. +`jatos_results_to_annotation_records` creates one record for every +answered named field, using `template_name.field_name` as the question. + +To add behavioral capture, set `consent_text` and enable +`SlopitIntegrationConfig`. Set `profile="response_controls"` and pass the +slopit `adapter-jspsych` browser artifact as `slopit_browser_bundle` for +the response-control schema. Set `target_selectors` to the CSS selectors +for the response controls in each task. The generated timeline starts +after affirmative consent and provides a withdrawal button. The +response-control profile records timing and event provenance without +including field values in the telemetry. The response plugin still +writes the answers the study collects. + +A study may supply a `session_adapter` script exposing a +`BeadSessionAdapter` object. Its optional hooks assign a list, set the +trial plan, add session and trial metadata, and configure timeline +nodes. The script is copied into the study assets and covered by the +application hash. The generic jsPsych generator remains responsible for +consent, telemetry, and result delivery.