From 494f98d1d4f2e40ca63548edfc4742f4a28d438a Mon Sep 17 00:00:00 2001 From: riponcm <86886711+riponcm@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:51:23 -0700 Subject: [PATCH 1/2] Session details: a drawer for any event, with speakers and similar sessions - GET /api/sessions/{id}: full session, speakers (bio, links, other sessions), on agenda, clashes, going and people you know, why it matches (interests, projects, track, profile similarity), similar sessions by kNN on the session vector (same track later as fallback), catch-up availability - Session drawer mounted in the shell, opened by clicking a title in Schedule, search, Compare, Now, Dashboard and My brief; in-drawer history for similar sessions; ?session= deep link; Agenda toggle inside - 20 new tests --- backend/app/data/people.py | 10 + backend/app/indices.py | 2 + backend/app/routers/sessions.py | 342 +++++++++++++++ backend/tests/test_sessions.py | 222 ++++++++++ docs/architecture.md | 26 ++ frontend/src/components/SessionCard.tsx | 6 +- frontend/src/components/Shell.tsx | 9 +- frontend/src/components/brief/DayTimeline.tsx | 7 +- frontend/src/components/dashboard/NextUp.tsx | 5 +- .../src/components/schedule/CompareDialog.tsx | 5 +- .../src/components/schedule/ScheduleRow.tsx | 5 +- .../src/components/session/SessionDrawer.tsx | 393 ++++++++++++++++++ .../session/SessionDrawerProvider.tsx | 59 +++ .../src/components/session/SessionLink.tsx | 20 + frontend/src/components/session/context.ts | 21 + frontend/src/components/session/types.ts | 62 +++ frontend/src/pages/Brief.tsx | 5 +- frontend/src/pages/Now.tsx | 26 +- frontend/src/pages/Schedule.tsx | 7 +- frontend/src/styles/session.css | 175 ++++++++ 20 files changed, 1389 insertions(+), 18 deletions(-) create mode 100644 backend/app/routers/sessions.py create mode 100644 backend/tests/test_sessions.py create mode 100644 frontend/src/components/session/SessionDrawer.tsx create mode 100644 frontend/src/components/session/SessionDrawerProvider.tsx create mode 100644 frontend/src/components/session/SessionLink.tsx create mode 100644 frontend/src/components/session/context.ts create mode 100644 frontend/src/components/session/types.ts create mode 100644 frontend/src/styles/session.css diff --git a/backend/app/data/people.py b/backend/app/data/people.py index c56d24d..3584c51 100644 --- a/backend/app/data/people.py +++ b/backend/app/data/people.py @@ -122,6 +122,15 @@ def sample_attendees(n: int = 80) -> list[dict]: return head + rest +def speaker_links(speaker: dict) -> list[dict]: + """The speaker's published links (LinkedIn, blog, ...) as {title, url}; only http(s) URLs are kept.""" + return [ + {"title": (link.get("title") or link.get("linkType") or "Link").strip(), "url": link["url"]} + for link in speaker.get("links") or [] + if str(link.get("url") or "").startswith(("https://", "http://")) + ] + + def speakers(raw: dict) -> list[dict]: """Public speaker profiles as published on the schedule. Not sample data.""" questions = {q["id"]: q["question"] for q in raw["questions"]} @@ -145,6 +154,7 @@ def speakers(raw: dict) -> list[dict]: "interests_text": ", ".join(tracks), "session_ids": [str(x) for x in s.get("sessions") or []], "picture": s.get("profilePicture"), + "links": speaker_links(s), } ) return out diff --git a/backend/app/indices.py b/backend/app/indices.py index 82bea84..673a4d0 100644 --- a/backend/app/indices.py +++ b/backend/app/indices.py @@ -55,6 +55,8 @@ "country": {"type": "keyword"}, "session_ids": {"type": "keyword"}, "picture": {"type": "keyword", "index": False}, + # Speakers' published links, shown in session details; stored, never searched. + "links": {"type": "object", "enabled": False}, "embedding": EMBEDDING, } }, diff --git a/backend/app/routers/sessions.py b/backend/app/routers/sessions.py new file mode 100644 index 0000000..ccb2a37 --- /dev/null +++ b/backend/app/routers/sessions.py @@ -0,0 +1,342 @@ +"""Session details: everything about one session for the drawer that opens when a title is clicked. + +GET /api/sessions/{session_id}?user_id=emma + +The session itself (full description, its vector read with `source_exclude_vectors=False`), the user's profile, +agenda and people are read first; then one `msearch` fetches the speakers, the speakers' other sessions, the kNN +neighbours of the session's own vector, later sessions in the same track, whether a transcript exists and who is +going. A failing part of the msearch is logged and recorded on the span and left empty, so the drawer still opens. +The shaping rules are pure functions, tested without Elasticsearch in tests/test_sessions.py. +""" + +import logging +import math +import re + +from elasticsearch import ApiError, NotFoundError +from fastapi import APIRouter, HTTPException, Query +from opentelemetry import trace + +from .. import agenda_store as store +from ..config import settings +from ..es import es +from .schedule import ( + _all_agenda, + _profile, + _top_matches, + blocking_items, + friends, + going_body, + interest_matches, + overlap_labels, + parse_going, +) + +router = APIRouter(prefix="/api/sessions", tags=["sessions"]) +tracer = trace.get_tracer("confox.sessions") +log = logging.getLogger(__name__) + +SIMILAR = 5 +TRACK_LATER = 5 +OTHER_SESSIONS = 3 # per speaker +GOING_NAMES = 8 +BIO_CHARS = 600 +NOT_ADDABLE = {"break", "registration"} +# Cosine between the profile vector and the session vector (text-embedding-3-small). On the demo data Emma's +# scores run from 0.12 to 0.55, median 0.39, top quarter above 0.43: the buckets follow that spread. +SIMILARITY_BUCKETS = ( + (0.48, "very_close", "Very close to your profile"), + (0.43, "close", "Close to your profile"), + (0.38, "related", "Somewhat related to your profile"), +) +DISTANT = ("distant", "Not close to your profile") +LIST_FIELDS = ["title", "starts_at", "ends_at", "day", "kind", "is_food", "track", "level", "room", "speaker_ids"] +SPEAKER_FIELDS = ["name", "title", "company", "bio", "picture", "links", "session_ids"] +NOT_LISTED = [{"terms": {"kind": ["registration", "break"]}}, {"term": {"is_food": True}}] + + +# ---------- pure rules ---------- + + +def cosine(a: list[float] | None, b: list[float] | None) -> float | None: + """Cosine similarity of two vectors, or None when either is missing, empty or zero, or the sizes differ.""" + if not a or not b or len(a) != len(b): + return None + dot = sum(x * y for x, y in zip(a, b, strict=True)) + norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)) + return dot / norm if norm else None + + +def similarity_bucket(score: float | None) -> dict | None: + """{"score", "bucket", "label"} for a profile-to-session cosine; None without vectors.""" + if score is None: + return None + bucket, label = next(((b, lbl) for floor, b, lbl in SIMILARITY_BUCKETS if score >= floor), DISTANT) + return {"score": round(score, 3), "bucket": bucket, "label": label} + + +def title_has_words(title: str, phrase: str) -> bool: + """Every word of the phrase is a whole word of the title, in any order: "AI inference" is in "Cloud Native AI + + Inference Day" even though the phrase itself is not.""" + words = re.findall(r"[A-Za-z0-9]{2,}", phrase) + return bool(words) and all(re.search(rf"\b{re.escape(w)}\b", title, re.I) for w in words) + + +def why_matches(session: dict, profile: dict, similarity: dict | None) -> list[dict]: + """Why the session fits the user, as chips: profile interests found in the session (a phrase found only in the + track counts as a track match), profile projects, then how close the vectors are when that is close or better. + Each is {"kind": "interest" | "project" | "track" | "similar", "label", "where"?}.""" + interests = [i for i in profile.get("interests") or [] if i and i.strip()] + projects = [p for p in profile.get("projects") or [] if p and p.strip() and p not in interests] + out: list[dict] = [] + for value, where in interest_matches(session, interests): + kind = "track" if where == "track" else "interest" + label = f"Track: {session.get('track')}" if kind == "track" else f"Matches {value}" + out.append({"kind": kind, "label": label, "value": value, "where": where}) + found = {w["value"] for w in out} + title = session.get("title") or "" + for value in interests: + if value not in found and title_has_words(title, value): + out.append({"kind": "interest", "label": f"Related to {value}", "value": value, "where": "title"}) + for value, where in interest_matches(session, projects): + out.append({"kind": "project", "label": f"Uses {value}", "value": value, "where": where}) + if similarity and similarity["bucket"] in ("very_close", "close"): + out.append({"kind": "similar", "label": similarity["label"]}) + # A track can match more than one interest phrase; show it once. + unique: dict[str, dict] = {} + for w in out: + unique.setdefault(w["label"], w) + return list(unique.values()) + + +def list_item(hit: dict, agenda_ids: set[str]) -> dict: + """A short session for the drawer's lists (similar, same track later, a speaker's other sessions).""" + s = hit["_source"] + item = {k: s.get(k) for k in LIST_FIELDS if k != "speaker_ids"} | {"id": hit["_id"]} + item["on_agenda"] = hit["_id"] in agenda_ids + return item + + +def pick_similar(knn_hits: list[dict], track_hits: list[dict], agenda_ids: set[str], limit: int = SIMILAR) -> dict: + """The kNN neighbours when there are any (`basis: "semantic"`), else later sessions in the same track + (`basis: "track"`), else nothing. kNN scores are kept so the list can say how close each one is.""" + if knn_hits: + items = [] + for h in knn_hits[:limit]: + item = list_item(h, agenda_ids) + if h.get("_score") is not None: + item["score"] = round(float(h["_score"]), 3) + items.append(item) + return {"basis": "semantic", "items": items} + if track_hits: + return {"basis": "track", "items": [list_item(h, agenda_ids) for h in track_hits[:limit]]} + return {"basis": "none", "items": []} + + +def speakers_out(session: dict, people: list[dict], others: list[dict], agenda_ids: set[str]) -> list[dict]: + """Speakers in the session's own order. `people` are confox-people hits, `others` session hits of the same + speakers (this session already left out). A speaker without a profile keeps their published name.""" + by_id = {p["_id"]: p["_source"] for p in people} + names = session.get("speaker_names") or [] + out = [] + for i, sid in enumerate(session.get("speaker_ids") or []): + p = by_id.get(sid, {}) + bio = (p.get("bio") or "").strip() + theirs = [h for h in others if sid in (h["_source"].get("speaker_ids") or [])] + out.append( + { + "id": sid, + "name": p.get("name") or (names[i] if i < len(names) else "Speaker"), + "title": p.get("title") or "", + "company": p.get("company") or "", + "bio": bio if len(bio) <= BIO_CHARS else bio[: BIO_CHARS - 1].rstrip() + "…", + "picture": p.get("picture"), + "links": [ + {"title": link.get("title") or "Link", "url": link["url"]} + for link in p.get("links") or [] + if isinstance(link, dict) and str(link.get("url") or "").startswith(("https://", "http://")) + ], + "other_sessions": [list_item(h, agenda_ids) for h in theirs[:OTHER_SESSIONS]], + } + ) + return out + + +def agenda_session_ids(agenda: list[dict]) -> set[str]: + """Sessions the user has confirmed on the agenda.""" + return { + i["session_id"] + for i in agenda + if i.get("kind") == "session" and i.get("status") == "confirmed" and i.get("session_id") + } + + +def similar_body(session_id: str, vector: list[float], k: int = SIMILAR) -> dict: + """kNN on the session's own vector; itself, breaks, food and registration left out by pre-filter.""" + flt = {"bool": {"must_not": [{"ids": {"values": [session_id]}}, *NOT_LISTED]}} + return { + "knn": {"field": "embedding", "query_vector": vector, "k": k, "num_candidates": 100, "filter": flt}, + "size": k, + "_source": LIST_FIELDS, + } + + +def track_later_body(session: dict, limit: int = TRACK_LATER) -> dict | None: + """Sessions in the same track that start at or after this one, earliest first. None without a track.""" + if not session.get("track"): + return None + return { + "query": { + "bool": { + "filter": [ + {"term": {"track": session["track"]}}, + {"range": {"starts_at": {"gte": session["starts_at"]}}}, + ], + "must_not": [{"ids": {"values": [session["id"]]}}, *NOT_LISTED], + } + }, + "sort": [{"starts_at": "asc"}], + "size": limit, + "_source": LIST_FIELDS, + } + + +def speakers_body(speaker_ids: list[str]) -> dict: + return {"query": {"ids": {"values": speaker_ids}}, "size": len(speaker_ids), "_source": SPEAKER_FIELDS} + + +def others_body(session_id: str, speaker_ids: list[str]) -> dict: + return { + "query": { + "bool": { + "filter": [{"terms": {"speaker_ids": speaker_ids}}], + "must_not": [{"ids": {"values": [session_id]}}], + } + }, + "sort": [{"starts_at": "asc"}], + "size": 50, + "_source": LIST_FIELDS, + } + + +def transcript_body(session_id: str) -> dict: + return { + "query": {"bool": {"filter": [{"term": {"doc_type": "chunk"}}, {"term": {"session_id": session_id}}]}}, + "size": 0, + "track_total_hits": True, + } + + +def detail( + session: dict, + profile: dict, + profile_vector: list[float] | None, + session_vector: list[float] | None, + agenda: list[dict], + agenda_kinds: dict[str, str], + parts: dict[str, dict | None], + people: dict[str, str], +) -> dict: + """The response from the session (with `id`) and the msearch parts (None where a part failed or was not + asked). `agenda_kinds` maps agenda session ids to their kind, for leaving co-located days out of clashes.""" + hits = {name: (r or {}).get("hits", {}).get("hits", []) for name, r in parts.items()} + on_ids = agenda_session_ids(agenda) + blockers = blocking_items(agenda, agenda_kinds | {session["id"]: session.get("kind", "")}) + similarity = similarity_bucket(cosine(profile_vector, session_vector)) + going = parse_going((parts.get("going") or {}).get("aggregations", {}), people, GOING_NAMES).get(session["id"], {}) + transcript = parts.get("transcript") or {} + chunks = transcript.get("hits", {}).get("total", {}).get("value", 0) + track_later = [list_item(h, on_ids) for h in hits.get("track_later", [])] + kind = session.get("kind") or "" + return { + "session": session, + "speakers": speakers_out(session, hits.get("speakers", []), hits.get("others", []), on_ids), + "on_agenda": session["id"] in on_ids, + "can_add": kind not in NOT_ADDABLE and not session.get("is_food"), + "clashes": overlap_labels(session, blockers), + "going": going.get("going", 0), + "going_names": going.get("going_names", []), + "why": why_matches(session, profile, similarity), + "similarity": similarity, + "similar": pick_similar(hits.get("similar", []), hits.get("track_later", []), on_ids), + "same_track_later": track_later, + "catch_up": {"available": chunks > 0, "chunks": chunks}, + "slides_url": session.get("slides_url") or None, + } + + +# ---------- Elasticsearch ---------- + + +def _session(session_id: str) -> tuple[dict, list[float] | None]: + try: + doc = es.get(index=settings.idx_sessions, id=session_id, source_exclude_vectors=False) + except NotFoundError as exc: + raise HTTPException(status_code=404, detail=f"unknown session {session_id}") from exc + source = dict(doc["_source"]) + vector = source.pop("embedding", None) + return source | {"id": session_id}, vector if isinstance(vector, list) and vector else None + + +def _msearch(searches: dict[str, tuple[str, dict]]) -> dict[str, dict | None]: + """Run named bodies as one msearch; a failed body comes back as None (logged and recorded on the span).""" + names = list(searches) + lines: list[dict] = [] + for name in names: + index, body = searches[name] + lines += [{"index": index, "ignore_unavailable": True}, body] + span = trace.get_current_span() + try: + responses = es.msearch(searches=lines)["responses"] + except ApiError as exc: + log.warning("session detail: msearch failed: %s", exc) + span.record_exception(exc) + return dict.fromkeys(names) + out: dict[str, dict | None] = {} + for name, r in zip(names, responses, strict=True): + if "error" in r: + log.warning("session detail: %s unavailable: %s", name, r["error"]) + span.add_event("confox.session.part_failed", {"part": name, "error": str(r["error"])[:500]}) + out[name] = None + else: + out[name] = r + return out + + +@router.get("/{session_id}") +def session_detail(session_id: str, user_id: str = Query(default_factory=lambda: settings.demo_user)) -> dict: + span = trace.get_current_span() + span.set_attribute("confox.session.id", session_id) + with tracer.start_as_current_span("session.read"): + session, vector = _session(session_id) + with tracer.start_as_current_span("session.user"): + profile, profile_vector = _profile(user_id) + agenda = _all_agenda(user_id) + people = friends(agenda, _top_matches(user_id, profile, profile_vector)) + kinds = store.session_kinds([i.get("session_id") or "" for i in agenda]) + + speaker_ids = list(session.get("speaker_ids") or []) + searches: dict[str, tuple[str, dict]] = { + "transcript": (settings.idx_transcripts, transcript_body(session_id)), + "going": (settings.idx_agenda, going_body([session_id], user_id, list(people))), + } + if speaker_ids: + searches["speakers"] = (settings.idx_people, speakers_body(speaker_ids)) + searches["others"] = (settings.idx_sessions, others_body(session_id, speaker_ids)) + if vector: + searches["similar"] = (settings.idx_sessions, similar_body(session_id, vector)) + later = track_later_body(session) + if later: + searches["track_later"] = (settings.idx_sessions, later) + with tracer.start_as_current_span("session.related") as related: + related.set_attribute("confox.session.parts", ",".join(searches)) + parts = _msearch(searches) + + out = detail(session, profile, profile_vector, vector, agenda, kinds, parts, people) + span.set_attribute("confox.session.kind", session.get("kind") or "") + span.set_attribute("confox.session.speakers", len(out["speakers"])) + span.set_attribute("confox.session.similar", len(out["similar"]["items"])) + span.set_attribute("confox.session.similar_basis", out["similar"]["basis"]) + span.set_attribute("confox.session.going", out["going"]) + span.set_attribute("confox.session.catch_up", out["catch_up"]["available"]) + return out diff --git a/backend/tests/test_sessions.py b/backend/tests/test_sessions.py new file mode 100644 index 0000000..3b5e681 --- /dev/null +++ b/backend/tests/test_sessions.py @@ -0,0 +1,222 @@ +"""Session details: the pure shaping rules of GET /api/sessions/{id}; no Elasticsearch.""" + +import pytest + +from app.data.people import speaker_links +from app.routers.sessions import ( + agenda_session_ids, + cosine, + detail, + pick_similar, + similar_body, + similarity_bucket, + speakers_out, + title_has_words, + track_later_body, + why_matches, +) + +DAY = "2026-11-09" +AI_DAY = { + "id": "1289760", + "title": "Cloud Native AI + Inference Day Hosted by CNCF - Full Day Event", + "description": "A day on serving models.", + "kind": "colocated", + "track": "CNCF-hosted Co-located Events", + "projects": [], + "starts_at": f"{DAY}T09:00:00", + "ends_at": f"{DAY}T17:30:00", + "speaker_ids": [], +} +TALK = { + "id": "t1", + "title": "Who Ran Up the Inference Bill? AI Traffic Control with KServe", + "description": "GPU scheduling for AI inference at scale.", + "kind": "talk", + "track": "AI + ML", + "projects": ["KServe"], + "starts_at": f"{DAY}T10:40:00", + "ends_at": f"{DAY}T11:10:00", + "speaker_ids": ["sp-1", "sp-2"], + "speaker_names": ["Ada Lovelace", "Grace Hopper"], +} +EMMA = {"interests": ["AI inference", "GPU scheduling", "Platform engineering"], "projects": ["KServe"]} +AGENDA = [ + { + "kind": "session", + "status": "confirmed", + "session_id": "1289760", + **{k: AI_DAY[k] for k in ("starts_at", "ends_at")}, + }, + { + "kind": "meeting", + "status": "confirmed", + "with_id": "alice", + "with_name": "Alice Moreno", + "title": "Coffee", + "starts_at": f"{DAY}T10:48:00", + "ends_at": f"{DAY}T11:03:00", + }, + {"kind": "meeting", "status": "pending", "with_id": "liam", "starts_at": f"{DAY}T12:46:00", "ends_at": "x"}, +] + + +def hit(_id: str, score: float | None = None, **source) -> dict: + return {"_id": _id, "_score": score, "_source": source} + + +def test_cosine_handles_missing_and_mismatched_vectors(): + assert cosine([1.0, 0.0], [1.0, 0.0]) == pytest.approx(1.0) + assert cosine([1.0, 0.0], [0.0, 1.0]) == pytest.approx(0.0) + assert cosine(None, [1.0]) is None + assert cosine([1.0, 2.0], [1.0]) is None + assert cosine([0.0, 0.0], [0.0, 0.0]) is None + + +@pytest.mark.parametrize( + ("score", "bucket"), + [(0.55, "very_close"), (0.48, "very_close"), (0.446, "close"), (0.40, "related"), (0.2, "distant")], +) +def test_similarity_buckets(score, bucket): + assert similarity_bucket(score)["bucket"] == bucket + + +def test_no_vectors_no_bucket(): + assert similarity_bucket(None) is None + + +def test_title_has_words_in_any_order(): + assert title_has_words(AI_DAY["title"], "AI inference") + assert not title_has_words(AI_DAY["title"], "GPU scheduling") + assert not title_has_words("Detailed talk", "AI") # whole words only + + +def test_why_lists_interests_projects_and_closeness(): + why = why_matches(TALK, EMMA, similarity_bucket(0.5)) + kinds = [w["kind"] for w in why] + labels = [w["label"] for w in why] + assert "Matches AI inference" in labels and "Matches GPU scheduling" in labels + assert "Uses KServe" in labels + assert kinds[-1] == "similar" + assert len(labels) == len(set(labels)) + + +def test_why_for_the_ai_day_uses_title_words_and_skips_distant_vectors(): + why = why_matches(AI_DAY, EMMA, similarity_bucket(0.3)) + assert [w["label"] for w in why] == ["Related to AI inference"] + + +def test_why_track_match_reads_as_track(): + session = TALK | {"title": "Untitled", "description": "", "projects": [], "track": "Platform Engineering"} + why = why_matches(session, {"interests": ["Platform engineering"]}, None) + assert why == [ + {"kind": "track", "label": "Track: Platform Engineering", "value": "Platform engineering", "where": "track"} + ] + + +def test_agenda_session_ids_are_confirmed_sessions_only(): + items = AGENDA + [{"kind": "session", "status": "declined", "session_id": "gone"}] + assert agenda_session_ids(items) == {"1289760"} + + +def test_similar_prefers_knn_then_track_then_nothing(): + knn = [hit("a", 0.91234, title="A", starts_at="x"), hit("b", 0.8, title="B")] + track = [hit("c", None, title="C")] + got = pick_similar(knn, track, {"b"}) + assert got["basis"] == "semantic" + assert [(i["id"], i.get("score"), i["on_agenda"]) for i in got["items"]] == [("a", 0.912, False), ("b", 0.8, True)] + fallback = pick_similar([], track, set()) + assert fallback["basis"] == "track" and [i["id"] for i in fallback["items"]] == ["c"] + assert pick_similar([], [], set()) == {"basis": "none", "items": []} + + +def test_similar_body_excludes_itself_and_breaks(): + body = similar_body("t1", [0.1, 0.2]) + flt = body["knn"]["filter"]["bool"]["must_not"] + assert {"ids": {"values": ["t1"]}} in flt + assert {"term": {"is_food": True}} in flt + assert body["knn"]["k"] == 5 and body["size"] == 5 + + +def test_track_later_needs_a_track_and_starts_here(): + assert track_later_body(TALK | {"track": None}) is None + body = track_later_body(TALK) + assert {"range": {"starts_at": {"gte": TALK["starts_at"]}}} in body["query"]["bool"]["filter"] + assert body["sort"] == [{"starts_at": "asc"}] + + +def test_speakers_keep_session_order_and_fall_back_to_published_names(): + people = [ + hit( + "sp-1", + bio="x" * 900, + name="Ada Lovelace", + title="Engineer", + company="Analytical", + links=[{"title": "Blog", "url": "https://ada.dev"}, {"title": "Bad", "url": "javascript:alert(1)"}], + ) + ] + others = [ + hit("o1", title="Other one", starts_at="a", speaker_ids=["sp-1"]), + hit("o2", title="Grace solo", starts_at="b", speaker_ids=["sp-2"]), + ] + out = speakers_out(TALK, people, others, {"o1"}) + assert [s["name"] for s in out] == ["Ada Lovelace", "Grace Hopper"] + assert len(out[0]["bio"]) == 600 and out[0]["bio"].endswith("…") + assert out[0]["links"] == [{"title": "Blog", "url": "https://ada.dev"}] + assert [(o["id"], o["on_agenda"]) for o in out[0]["other_sessions"]] == [("o1", True)] + assert out[1]["title"] == "" and [o["id"] for o in out[1]["other_sessions"]] == ["o2"] + + +def test_detail_puts_it_together(): + going = { + "aggregations": { + "sessions": { + "buckets": [ + { + "key": "t1", + "doc_count": 4, + "people": {"value": 4}, + "friends": {"who": {"buckets": [{"key": "alice"}]}}, + } + ] + } + } + } + parts = { + "going": going, + "transcript": {"hits": {"total": {"value": 8}, "hits": []}}, + "speakers": None, # a failed part leaves its list empty + "similar": {"hits": {"hits": [hit("s1", 0.9, title="Close one")]}}, + "track_later": {"hits": {"hits": [hit("l1", None, title="Later")]}}, + } + out = detail(TALK, EMMA, [1.0, 0.0], [1.0, 0.0], AGENDA, {"1289760": "colocated"}, parts, {"alice": "Alice Moreno"}) + assert out["on_agenda"] is False and out["can_add"] is True + assert out["clashes"] == ["Coffee with Alice Moreno"] # the co-located day on the agenda does not clash + assert (out["going"], out["going_names"]) == (4, ["Alice Moreno"]) + assert out["catch_up"] == {"available": True, "chunks": 8} + assert out["similar"]["basis"] == "semantic" and out["same_track_later"][0]["id"] == "l1" + assert [s["name"] for s in out["speakers"]] == ["Ada Lovelace", "Grace Hopper"] + assert out["similarity"]["bucket"] == "very_close" + assert out["slides_url"] is None + + +def test_detail_of_the_agenda_day_itself(): + parts = {"going": None, "transcript": None} + out = detail(AI_DAY, EMMA, None, None, AGENDA, {"1289760": "colocated"}, parts, {}) + assert out["on_agenda"] is True + assert out["clashes"] == ["Coffee with Alice Moreno"] # a co-located day shows what it overlaps + assert out["going"] == 0 and out["catch_up"]["available"] is False + assert out["similar"] == {"basis": "none", "items": []} + assert out["similarity"] is None + + +def test_breaks_cannot_be_added(): + out = detail(TALK | {"kind": "break", "is_food": True}, {}, None, None, [], {}, {}, {}) + assert out["can_add"] is False + + +def test_speaker_links_keep_web_urls(): + raw = {"links": [{"title": "LinkedIn", "url": "https://linkedin.com/in/x"}, {"linkType": "Blog", "url": "ftp://x"}]} + assert speaker_links(raw) == [{"title": "LinkedIn", "url": "https://linkedin.com/in/x"}] + assert speaker_links({}) == [] diff --git a/docs/architecture.md b/docs/architecture.md index ef499cb..d89a425 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -251,6 +251,32 @@ One calm page for the signed-in attendee's day. `GET /api/brief?user_id=emma` (d The page shows the date and summary, "People today" (confirmed meetings, incoming requests with Accept and Decline, suggested people linking to `/people?q=`), the "Your day" timeline (dashed free rows link to `/schedule`) and "Suggested for you" as `SessionCard`s. Accept and Decline call `POST /api/connect/{id}/accept|decline` from the connect pull request and refresh; on a 404 the card says "Not available yet". The request span carries `confox.brief.timeline`, `confox.brief.requests_incoming`, `confox.brief.people` and `confox.brief.suggested`. Agenda items and people are labelled as generated sample data. +## Session details + +Clicking a session title anywhere opens one drawer with everything about it. `GET /api/sessions/{id}?user_id=emma` lives in `backend/app/routers/sessions.py`; the drawer is `src/components/session/` with `src/styles/session.css`. Nothing new is stored: it reads `confox-sessions`, `confox-people`, `confox-agenda` and `confox-transcripts`, and reuses the Schedule helpers (`_profile`, `_all_agenda`, `_top_matches`, `friends`, `going_body`, `parse_going`, `blocking_items`, `overlap_labels`, `interest_matches`). + +| Field | Meaning | +|---|---| +| `session` | The whole session document (full description, kind, track, level, projects, room, venue, times, `minutes`), without its vector | +| `speakers[]` | `confox-people` speaker profiles in the session's order: `name`, `title`, `company`, `bio` (600 characters), `picture`, `links` (http(s) only), `other_sessions` (up to 3). A speaker without a profile keeps the published name | +| `on_agenda`, `can_add` | The session is a confirmed agenda item of the user; breaks, food and registration cannot be added | +| `clashes` | Confirmed agenda items overlapping it, as in the day view (`overlap_labels`: a co-located day lists what it overlaps, co-located days on the agenda never block) | +| `going`, `going_names` | Other attendees who saved it, and up to 8 of the user's people among them (meeting partners, then the top 10 Match results) | +| `why[]` | Chips `{kind, label}`: profile interests found in the title, projects, track or description (`interest`, or `track` when only the track has it), an interest whose words all appear in the title ("Related to AI inference" for "Cloud Native AI + Inference Day"), profile projects (`project`), and `similar` when the vectors are close | +| `similarity` | Cosine of profile and session vectors (computed in the API, both are read anyway) and a bucket: `very_close` 0.48+, `close` 0.43+, `related` 0.38+, else `distant`; null without vectors. The cut-offs follow Emma's spread on the demo data (0.12 to 0.55, median 0.39) | +| `similar` | `{basis, items}`: kNN on the session's own `embedding` (read with `source_exclude_vectors=False`), itself, breaks, food and registration pre-filtered out, top 5 with scores (`semantic`); without a vector, later sessions in the same track (`track`) | +| `same_track_later` | Up to 5 sessions in the same track starting at or after this one | +| `catch_up` | `{available, chunks}`: a transcript exists in `confox-transcripts` | +| `slides_url` | From the schedule when published | + +Cost: four reads (session with vector, profile with vector, the user's agenda, the Match query for names; plus an `mget` of agenda session kinds), then one `msearch` with up to six bodies (speakers, their other sessions, kNN, same track later, transcript count, going aggregation). Each body names its index and uses `ignore_unavailable`; a failing body is logged, added to the span as a `confox.session.part_failed` event and left empty, so the drawer still opens. Unknown ids are 404. Spans: `session.read`, `session.user`, `session.related` (attribute `confox.session.parts`) under the request span, which carries `confox.session.id`, `.kind`, `.speakers`, `.similar`, `.similar_basis`, `.going` and `.catch_up`. Pure helpers (`cosine`, `similarity_bucket`, `why_matches`, `title_has_words`, `pick_similar`, `speakers_out`, the body builders and `detail`) are tested in `tests/test_sessions.py`. + +Speaker links come from the schedule snapshot; the people loader now indexes them (`links`, an unindexed object). They appear after the next `uv run python -m app.load --only people`; until then the list is empty. + +**Drawer.** `SessionDrawerProvider` is mounted once in the Shell. `useSessionDrawer().open(id)` opens it; `SessionLink` is the title button every list uses (Schedule rows in the day view and ranked views, search results and Brief suggestions through `SessionCard`, Compare dialog titles, Now cards and tiles, Dashboard "Starting soon", the My brief timeline). The open session is the URL parameter `?session=` (replace, so a reload or a shared link opens the same drawer on any page); the in-drawer history is kept in the provider, so a similar session or a speaker's other talk opens inside the drawer and Back returns. A URL naming another session starts a fresh history. + +It is a native modal `` on the right, full width under 768 px (sized in percent, since `100vw` includes the page scrollbar): focus is trapped, Escape closes it (only the drawer when it is opened from the Compare dialog), focus returns to the title that opened it, and after Back or a similar session focus moves to the new title. Content: kind, title, day and time range with length, room and venue, track, level and project chips, the Schedule's `AgendaButton`, "Catch up on this talk" (to `/catch-up?talk=`, the Catch up page's own parameter; `?session=` would reopen the drawer there) and Slides when present, the clash warning, "Why it matches you", Going (labelled sample data), the description (Show more past 360 characters), speakers (initials avatar, name, title and company, bio, links, Also speaking) and Similar sessions (or "Later in this track"). Adding or removing in the drawer bumps `agendaVersion` in the provider; Schedule and My brief reload on it, so rows, For you and the brief agree. + ## Key decisions | Decision | Why | diff --git a/frontend/src/components/SessionCard.tsx b/frontend/src/components/SessionCard.tsx index 3dfc129..02ad991 100644 --- a/frontend/src/components/SessionCard.tsx +++ b/frontend/src/components/SessionCard.tsx @@ -2,6 +2,7 @@ import type { ReactNode } from 'react' import { Clock, MapPin, Users } from 'lucide-react' import type { Session, SessionKind } from '../types.ts' +import SessionLink from './session/SessionLink.tsx' type Props = { session: Session @@ -52,7 +53,10 @@ export default function SessionCard({ session, onSelect, aside }: Props) { {session.minutes >= 60 && · {session.minutes / 60 >= 2 ? `${Math.floor(session.minutes / 60)} h ${session.minutes % 60} min` : `${session.minutes} min`}} -

{session.title}

+

+ {/* A whole-card button cannot hold another button; otherwise the title opens the session drawer. */} + {onSelect ? session.title : {session.title}} +

{label}

- -
+ +
+ +
+
setProfileOpen(false)} /> ) diff --git a/frontend/src/components/brief/DayTimeline.tsx b/frontend/src/components/brief/DayTimeline.tsx index 95bfa5a..7a1d692 100644 --- a/frontend/src/components/brief/DayTimeline.tsx +++ b/frontend/src/components/brief/DayTimeline.tsx @@ -1,6 +1,7 @@ import { Link } from 'react-router' import { CalendarRange, Coffee, MapPin, UtensilsCrossed } from 'lucide-react' import { hhmm, minutes, roomLabel, timeRange } from '../schedule/time.ts' +import SessionLink from '../session/SessionLink.tsx' import { initials, mealWord } from './types.ts' import type { Gap, TimelineItem } from './types.ts' @@ -58,7 +59,7 @@ function ItemCard({ item }: { item: TimelineItem }) {

@@ -73,7 +74,9 @@ function ItemCard({ item }: { item: TimelineItem }) { return (

-

{item.title}

+

+ {item.session_id ? {item.title} : item.title} +

{next}

diff --git a/frontend/src/components/dashboard/NextUp.tsx b/frontend/src/components/dashboard/NextUp.tsx index 64a333f..df61227 100644 --- a/frontend/src/components/dashboard/NextUp.tsx +++ b/frontend/src/components/dashboard/NextUp.tsx @@ -1,4 +1,5 @@ import { MapPin } from 'lucide-react' +import SessionLink from '../session/SessionLink.tsx' import { type DashboardData, groupOf, hhmm, hhmmFromMinutes, minutesOf } from './types.ts' const WINDOW_MINUTES = 90 @@ -24,7 +25,9 @@ export default function NextUp({ data }: { data: DashboardData }) { {hhmm(s.starts_at)}

-

{s.title}

+

+ {s.title} +

  • - {s.title} + + {s.title} +

    {s.on_agenda && ( diff --git a/frontend/src/components/schedule/ScheduleRow.tsx b/frontend/src/components/schedule/ScheduleRow.tsx index 8caec7b..fe16f1b 100644 --- a/frontend/src/components/schedule/ScheduleRow.tsx +++ b/frontend/src/components/schedule/ScheduleRow.tsx @@ -1,6 +1,7 @@ import { Clock, TriangleAlert, Users, UsersRound } from 'lucide-react' import AgendaButton from './AgendaButton.tsx' import KindIcon from './KindIcon.tsx' +import SessionLink from '../session/SessionLink.tsx' import { canAdd, type ToggleAgenda } from './agenda.ts' import { goingLabel, goingTitle } from './filters.ts' import { durationMin, hhmm, roomLabel } from './time.ts' @@ -65,7 +66,9 @@ export function ScheduleRow({ session: s, muted = false, showTime, onToggleAgend

    - {s.title} + + {s.title} +

    {showTime && ( diff --git a/frontend/src/components/session/SessionDrawer.tsx b/frontend/src/components/session/SessionDrawer.tsx new file mode 100644 index 0000000..d8a652e --- /dev/null +++ b/frontend/src/components/session/SessionDrawer.tsx @@ -0,0 +1,393 @@ +import { useEffect, useRef, useState } from 'react' +import { Link } from 'react-router' +import { + ArrowLeft, + BookOpenText, + CalendarDays, + CircleCheck, + ExternalLink, + FileText, + MapPin, + Sparkles, + TriangleAlert, + UsersRound, + X, +} from 'lucide-react' +import { ApiError, DEMO_USER, deleteJSON, getJSON, postJSON } from '../../api.ts' +import AgendaButton from '../schedule/AgendaButton.tsx' +import KindIcon from '../schedule/KindIcon.tsx' +import { durationMin, kindLabel, longDate, roomLabel, shortDate, timeRange } from '../schedule/time.ts' +import type { SessionDetail, SessionListItem, Speaker } from './types.ts' +import '../../styles/schedule.css' +import '../../styles/session.css' + +type Props = { + /** The session shown; null when the drawer is closed. */ + sessionId: string | null + canGoBack: boolean + onNavigate: (sessionId: string) => void + onBack: () => void + onClose: () => void + onAgendaChanged: () => void +} + +type Answer = { key: string; data?: SessionDetail; failed?: boolean } + +const DESCRIPTION_PREVIEW = 360 + +function initials(name: string): string { + const parts = name.trim().split(/\s+/).filter(Boolean) + return ((parts[0]?.[0] ?? '') + (parts.length > 1 ? parts[parts.length - 1][0] : '')).toUpperCase() || '?' +} + +function goingText(going: number, names: string[]): string { + if (!going) return 'Nobody has saved it yet' + if (!names.length) return `${going} going` + const others = going - names.length + return others > 0 ? `${names.join(', ')} and ${others} more going` : `${names.join(', ')} going` +} + +/** One session in a drawer list; the title opens it inside the drawer (Back returns). */ +function ListRow({ item, onOpen }: { item: SessionListItem; onOpen: (id: string) => void }) { + const room = roomLabel(item.room) + return ( +

  • + +
  • + ) +} + +function SpeakerCard({ speaker, onOpen }: { speaker: Speaker; onOpen: (id: string) => void }) { + // Public titles often end with the company already ("Product, AWS"); do not say it twice. + const role = + speaker.company && speaker.title.includes(speaker.company) + ? speaker.title + : [speaker.title, speaker.company].filter(Boolean).join(' · ') + return ( +
  • + +
    +

    {speaker.name}

    + {role &&

    {role}

    } + {speaker.bio &&

    {speaker.bio}

    } + {speaker.links.length > 0 && ( + + )} + {speaker.other_sessions.length > 0 && ( +
    +

    Also speaking

    +
      + {speaker.other_sessions.map((s) => ( + + ))} +
    +
    + )} +
    +
  • + ) +} + +function Body({ + data, + onOpen, + onToggle, +}: { + data: SessionDetail + onOpen: (id: string) => void + onToggle: () => Promise +}) { + const s = data.session + const [expanded, setExpanded] = useState(false) + const description = (s.description ?? '').trim() + const long = description.length > DESCRIPTION_PREVIEW + const shown = long && !expanded ? `${description.slice(0, DESCRIPTION_PREVIEW).trimEnd()}…` : description + const room = roomLabel(s.room) + const similarTitle = data.similar.basis === 'track' ? 'Later in this track' : 'Similar sessions' + const chips = [s.track, s.level, ...(s.projects ?? [])].filter((c): c is string => !!c) + + return ( + <> +
    +

    + + {kindLabel(s.kind, s.is_food)} +

    +

    + {s.title} +

    +

    +

    + {(room || s.venue) && ( +

    +

    + )} + {chips.length > 0 && ( +
      + {chips.map((c) => ( +
    • + {c} +
    • + ))} +
    + )} +
    + +
    + {data.can_add && ( + + )} + {data.catch_up.available && ( + +
    + + {data.clashes.length > 0 && ( +

    +

    + )} + +
    +

    + Why it matches you +

    + {data.why.length ? ( +
      + {data.why.map((w) => ( +
    • +
    • + ))} +
    + ) : ( +

    Nothing in your profile points here.

    + )} + {data.similarity && !data.why.some((w) => w.kind === 'similar') && ( +

    {data.similarity.label}.

    + )} +
    + +
    +

    + Going +

    +

    +

    +

    From generated sample attendees.

    +
    + + {description && ( +
    +

    + About +

    +

    + {shown} +

    + {long && ( + + )} +
    + )} + + {data.speakers.length > 0 && ( +
    +

    + {data.speakers.length === 1 ? 'Speaker' : `Speakers (${data.speakers.length})`} +

    +
      + {data.speakers.map((sp) => ( + + ))} +
    +
    + )} + + {data.similar.items.length > 0 && ( +
    +

    + {similarTitle} +

    +
      + {data.similar.items.map((item) => ( + + ))} +
    +
    + )} + + ) +} + +/** + * The session details drawer: a native modal dialog on the right (full screen on a phone), so focus is trapped, + * Escape closes it and focus returns to the title that opened it. + */ +export default function SessionDrawer({ sessionId, canGoBack, onNavigate, onBack, onClose, onAgendaChanged }: Props) { + const ref = useRef(null) + const bodyRef = useRef(null) + const [answer, setAnswer] = useState(null) + const [reload, setReload] = useState(0) + const [agendaFailed, setAgendaFailed] = useState(null) + const open = sessionId !== null + const key = `${sessionId}#${reload}` + // Keep the last session on screen (dimmed) while the next loads, so Back and Similar do not flash. + const loading = open && answer?.key !== key + const data = answer?.data && answer.data.session.id === sessionId ? answer.data : null + const shown = data ?? (loading ? answer?.data : undefined) + + useEffect(() => { + const dialog = ref.current + if (!dialog) return + if (open && !dialog.open) dialog.showModal() + if (!open && dialog.open) dialog.close() + }, [open]) + + useEffect(() => { + if (!sessionId) return + const ctrl = new AbortController() + getJSON(`sessions/${encodeURIComponent(sessionId)}`, { user_id: DEMO_USER }, { signal: ctrl.signal }) + .then((d) => setAnswer({ key, data: d })) + .catch(() => !ctrl.signal.aborted && setAnswer({ key, failed: true })) + return () => ctrl.abort() + }, [sessionId, key]) + + // A new session in the drawer starts at the top, with focus on its title for screen readers. + const shownId = data?.session.id + useEffect(() => { + if (!shownId) return + bodyRef.current?.scrollTo({ top: 0 }) + // Back disappears on the first session, so focus would otherwise fall to the page. + if (ref.current?.open) document.getElementById('session-drawer-title')?.focus() + }, [shownId]) + + const toggle = async () => { + if (!data) return + const id = data.session.id + try { + if (data.on_agenda) await deleteJSON(`agenda/${encodeURIComponent(id)}`, { user_id: DEMO_USER }) + else await postJSON('agenda', { user_id: DEMO_USER, session_id: id }) + setAgendaFailed(null) + } catch (err) { + if (!(err instanceof ApiError && err.status === 404)) setAgendaFailed(id) + } + setReload((r) => r + 1) + onAgendaChanged() + } + + const failed = open && !loading && answer?.failed + return ( + { + if (e.target === e.currentTarget) ref.current?.close() + }} + > +
    +
    + {canGoBack ? ( + + ) : ( +

    Session

    + )} + +
    + {failed && ( +

    + Could not load this session. Is the API running? +

    + )} + {!shown && loading && ( +

    + Loading the session… +

    + )} + {agendaFailed && agendaFailed === shown?.session.id && ( +

    + Could not change your agenda. Try again. +

    + )} + {shown && ( +
    + +
    + )} +
    +
    + ) +} diff --git a/frontend/src/components/session/SessionDrawerProvider.tsx b/frontend/src/components/session/SessionDrawerProvider.tsx new file mode 100644 index 0000000..12dc35a --- /dev/null +++ b/frontend/src/components/session/SessionDrawerProvider.tsx @@ -0,0 +1,59 @@ +import { useCallback, useMemo, useState, type ReactNode } from 'react' +import { useSearchParams } from 'react-router' +import SessionDrawer from './SessionDrawer.tsx' +import { SessionDrawerContext, type SessionDrawerApi } from './context.ts' + +export const SESSION_PARAM = 'session' + +/** + * Holds the session drawer for the whole app. The open session lives in the URL (`?session=`), so a link or + * a reload opens the same drawer; the in-drawer history (Similar sessions, a speaker's other talks) is kept here + * so Back returns to the previous session. A URL that names a session the history does not end with (a deep + * link, or a page changing it) starts a fresh history. + */ +export default function SessionDrawerProvider({ children }: { children: ReactNode }) { + const [params, setParams] = useSearchParams() + const [history, setHistory] = useState([]) + const [agendaVersion, setAgendaVersion] = useState(0) + const current = params.get(SESSION_PARAM) + const stack = useMemo( + () => (!current ? [] : history[history.length - 1] === current ? history : [current]), + [current, history], + ) + + const show = useCallback( + (next: string[]) => { + setHistory(next) + const id = next[next.length - 1] + setParams( + (prev) => { + const p = new URLSearchParams(prev) + if (id) p.set(SESSION_PARAM, id) + else p.delete(SESSION_PARAM) + return p + }, + { replace: true }, + ) + }, + [setParams], + ) + + const api: SessionDrawerApi = useMemo( + () => ({ open: (id: string) => show([id]), agendaVersion }), + [show, agendaVersion], + ) + + return ( + + {children} + 1} + onNavigate={(id) => show([...stack, id])} + onBack={() => show(stack.slice(0, -1))} + onClose={() => show([])} + onAgendaChanged={() => setAgendaVersion((v) => v + 1)} + /> + + ) +} diff --git a/frontend/src/components/session/SessionLink.tsx b/frontend/src/components/session/SessionLink.tsx new file mode 100644 index 0000000..fc311bd --- /dev/null +++ b/frontend/src/components/session/SessionLink.tsx @@ -0,0 +1,20 @@ +import type { ReactNode } from 'react' +import { useSessionDrawer } from './context.ts' + +type Props = { id: string; children: ReactNode; className?: string } + +/** A session title that opens the session drawer. Outside the Shell it is plain text. */ +export default function SessionLink({ id, children, className }: Props) { + const drawer = useSessionDrawer() + if (!drawer || !id) return {children} + return ( + + ) +} diff --git a/frontend/src/components/session/context.ts b/frontend/src/components/session/context.ts new file mode 100644 index 0000000..85c8826 --- /dev/null +++ b/frontend/src/components/session/context.ts @@ -0,0 +1,21 @@ +import { createContext, useContext } from 'react' + +/** What the session drawer offers to every page (mounted once in the Shell). */ +export type SessionDrawerApi = { + /** Open the drawer on a session, starting a fresh in-drawer history. */ + open: (sessionId: string) => void + /** Bumped whenever the drawer changes the agenda, so pages showing agenda state can reload. */ + agendaVersion: number +} + +export const SessionDrawerContext = createContext(null) + +/** The drawer, or null when rendered outside the Shell (titles then stay plain text). */ +export function useSessionDrawer(): SessionDrawerApi | null { + return useContext(SessionDrawerContext) +} + +/** 0 outside the Shell; use as an effect dependency to reload after an agenda change in the drawer. */ +export function useAgendaVersion(): number { + return useContext(SessionDrawerContext)?.agendaVersion ?? 0 +} diff --git a/frontend/src/components/session/types.ts b/frontend/src/components/session/types.ts new file mode 100644 index 0000000..11e9f6a --- /dev/null +++ b/frontend/src/components/session/types.ts @@ -0,0 +1,62 @@ +// Shape of GET /api/sessions/{id}. Kept local to the session details feature. + +export type SessionListItem = { + id: string + title: string + starts_at: string + ends_at: string + day: string + kind: string + is_food?: boolean + track?: string | null + level?: string | null + room?: string + on_agenda: boolean + /** kNN similarity to the opened session (semantic list only). */ + score?: number +} + +export type Speaker = { + id: string + name: string + title: string + company: string + bio: string + picture?: string | null + links: { title: string; url: string }[] + other_sessions: SessionListItem[] +} + +export type WhyChip = { kind: 'interest' | 'project' | 'track' | 'similar'; label: string; value?: string; where?: string } + +export type SessionDetail = { + session: { + id: string + title: string + description?: string + starts_at: string + ends_at: string + day: string + minutes?: number + kind: string + is_food?: boolean + track?: string | null + level?: string | null + projects?: string[] + room?: string + venue?: string + speaker_names?: string[] + } + speakers: Speaker[] + on_agenda: boolean + can_add: boolean + clashes: string[] + going: number + going_names: string[] + why: WhyChip[] + similarity: { score: number; bucket: string; label: string } | null + similar: { basis: 'semantic' | 'track' | 'none'; items: SessionListItem[] } + same_track_later: SessionListItem[] + catch_up: { available: boolean; chunks: number } + slides_url: string | null +} diff --git a/frontend/src/pages/Brief.tsx b/frontend/src/pages/Brief.tsx index d2abfcb..4d5b484 100644 --- a/frontend/src/pages/Brief.tsx +++ b/frontend/src/pages/Brief.tsx @@ -3,6 +3,7 @@ import { CalendarDays, RefreshCw, Sparkles, Users } from 'lucide-react' import { DEMO_USER, getJSON } from '../api.ts' import SessionCard from '../components/SessionCard.tsx' import DayTimeline from '../components/brief/DayTimeline.tsx' +import { useAgendaVersion } from '../components/session/context.ts' import PeopleToday from '../components/brief/PeopleToday.tsx' import { longDay } from '../components/brief/types.ts' import type { BriefResponse } from '../components/brief/types.ts' @@ -11,6 +12,8 @@ import '../styles/brief.css' export default function Brief() { const [data, setData] = useState(null) const [failed, setFailed] = useState(false) + // Reload when the session drawer adds or removes something, so the timeline and suggestions agree. + const agendaVersion = useAgendaVersion() const fetchBrief = useCallback(() => { getJSON('brief', { user_id: DEMO_USER }) @@ -21,7 +24,7 @@ export default function Brief() { .catch(() => setFailed(true)) }, []) - useEffect(fetchBrief, [fetchBrief]) + useEffect(fetchBrief, [fetchBrief, agendaVersion]) const load = () => { setFailed(false) diff --git a/frontend/src/pages/Now.tsx b/frontend/src/pages/Now.tsx index 633e359..97bd083 100644 --- a/frontend/src/pages/Now.tsx +++ b/frontend/src/pages/Now.tsx @@ -2,12 +2,21 @@ import { useEffect, useState } from 'react' import { CalendarCheck, Coffee, Radio, Timer } from 'lucide-react' import { DEMO_USER, getJSON } from '../api.ts' import SessionCard from '../components/SessionCard.tsx' +import SessionLink from '../components/session/SessionLink.tsx' import { dayLabel, hhmm, roomLabel } from '../components/schedule/time.ts' import type { Session } from '../types.ts' import '../styles/now.css' type Food = { session: Session; status: 'now' | 'next'; minutes: number } -type AgendaItem = { title: string; kind: string; with_name?: string; starts_at: string; ends_at: string; room?: string } +type AgendaItem = { + title: string + kind: string + with_name?: string + session_id?: string + starts_at: string + ends_at: string + room?: string +} type NowResponse = { now: string on_now: Session[] @@ -54,9 +63,10 @@ export default function Now() { {data.food ? ( <>

    + {data.food.session.title} {data.food.status === 'now' - ? `${data.food.session.title} now, ${inMinutes(data.food.minutes)} left` - : `${data.food.session.title} in ${inMinutes(data.food.minutes)}`} + ? ` now, ${inMinutes(data.food.minutes)} left` + : ` in ${inMinutes(data.food.minutes)}`}

    {hhmm(data.food.session.starts_at)}–{hhmm(data.food.session.ends_at)} ·{' '} @@ -75,9 +85,13 @@ export default function Now() { {data.my_next ? ( <>

    - {data.my_next.kind === 'meeting' && data.my_next.with_name - ? `${data.my_next.title} with ${data.my_next.with_name}` - : data.my_next.title} + {data.my_next.kind === 'meeting' && data.my_next.with_name ? ( + `${data.my_next.title} with ${data.my_next.with_name}` + ) : data.my_next.session_id ? ( + {data.my_next.title} + ) : ( + data.my_next.title + )}

    {hhmm(data.my_next.starts_at)}–{hhmm(data.my_next.ends_at)} diff --git a/frontend/src/pages/Schedule.tsx b/frontend/src/pages/Schedule.tsx index 81a6f82..2128e30 100644 --- a/frontend/src/pages/Schedule.tsx +++ b/frontend/src/pages/Schedule.tsx @@ -3,6 +3,7 @@ import { LoaderCircle } from 'lucide-react' import { useSearchParams } from 'react-router' import { ApiError, deleteJSON, getJSON, postJSON } from '../api.ts' import { useOpenProfile } from '../components/shellContext.ts' +import { useAgendaVersion } from '../components/session/context.ts' import DayView from '../components/schedule/DayView.tsx' import FilterPanel from '../components/schedule/FilterPanel.tsx' import InterestChips from '../components/schedule/InterestChips.tsx' @@ -51,6 +52,8 @@ export default function Schedule() { setParams((prev) => toParams({ ...parseState(prev), ...change }), { replace: true }) const setFilters = (filters: Filters) => update({ filters }) const openProfile = useOpenProfile() + // Bumped when the session drawer changes the agenda: reload the day and the agenda ids. + const agendaVersion = useAgendaVersion() const [meta, setMeta] = useState(null) const [days, setDays] = useState([]) @@ -95,7 +98,7 @@ export default function Schedule() { .then((data) => setDayAnswer({ key: day, data })) .catch(() => !ctrl.signal.aborted && setDayAnswer({ key: day, failed: true })) return () => ctrl.abort() - }, [day, meta]) + }, [day, meta, agendaVersion]) useEffect(() => { if (!meta) return @@ -104,7 +107,7 @@ export default function Schedule() { .then(setAgendaIds) .catch(() => !ctrl.signal.aborted && setAgendaIds(new Set())) return () => ctrl.abort() - }, [meta]) + }, [meta, agendaVersion]) // Add or remove, then reload the day and the agenda ids so For you, clashes and the buttons agree. const toggleAgenda: ToggleAgenda = async (sessionId, on) => { diff --git a/frontend/src/styles/session.css b/frontend/src/styles/session.css new file mode 100644 index 0000000..0d8cf72 --- /dev/null +++ b/frontend/src/styles/session.css @@ -0,0 +1,175 @@ +/* Session details: the drawer and the clickable titles that open it. Colours from index.css tokens only. + The drawer reuses the Schedule's kind icon, chips and Agenda button, so it loads schedule.css too. */ + +/* A title that opens the drawer: reads as text, shows it is clickable on hover and focus. */ +.session-link { + display: inline; + padding: 0; + border: 0; + background: none; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; + overflow-wrap: anywhere; +} +.session-link:hover { color: var(--accent-ink); text-decoration: underline; text-underline-offset: 3px; } + +/* The drawer: wider than the profile drawer, full screen on a phone. Percentages, not vw: 100vw includes the + page scrollbar, which would push the drawer's left edge off screen. */ +.session-drawer { width: min(520px, 100%); max-width: 100%; } +.session-drawer[open] { display: flex; } +.sd-body { flex: 1; display: flex; flex-direction: column; gap: 16px; min-width: 0; padding: 0 20px 28px; overflow-y: auto; } +.sd-head { + position: sticky; + top: 0; + z-index: 1; + margin: 0 -20px; + padding: 12px 12px 10px 20px; + background: var(--bg-2); + border-bottom: 1px solid var(--line); +} +.sd-back { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 10px 6px 6px; + border: 0; + border-radius: 9px; + background: transparent; + color: var(--accent-ink); + font-weight: 600; + cursor: pointer; +} +.sd-back:hover { background: var(--panel); } +.sd-content { display: flex; flex-direction: column; gap: 18px; min-width: 0; transition: opacity 120ms; } +.sd-content.is-loading { opacity: 0.55; } +.sd-note { margin: 0; color: var(--muted); } +.sd-warn { color: var(--warn); } +.sd-muted { color: var(--muted); } +.sd-small { margin: 0; font-size: 12.5px; } +.sd-sr-only { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +.sd-hero { display: flex; flex-direction: column; gap: 8px; min-width: 0; } +.sd-kind { display: flex; align-items: center; gap: 6px; margin: 0; color: var(--accent-ink); font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; } +.sd-kind .sch-kind { margin-top: 0; } +.sd-title { margin: 0; font-size: 20px; line-height: 1.3; font-weight: 700; overflow-wrap: anywhere; } +.sd-title:focus { outline: none; } +.sd-title:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +.sd-fact { display: flex; align-items: flex-start; gap: 8px; margin: 0; color: var(--text-2); min-width: 0; } +.sd-fact svg { flex: none; margin-top: 3px; color: var(--muted); } +.sd-fact > span { min-width: 0; overflow-wrap: anywhere; } +.sd-chips { gap: 6px; } +.sd-chips .chip { max-width: 100%; overflow-wrap: anywhere; } +.chip.chip-similar { background: var(--ok-soft); color: var(--ok); } + +.sd-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } +.sd-action-link { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 12px; + border-radius: 999px; + background: var(--panel); + box-shadow: inset 0 0 0 1px var(--line-strong); + color: var(--accent-ink); + font-size: 13px; + font-weight: 600; + text-decoration: none; +} +.sd-action-link:hover { background: var(--panel-2); } +.sd-clash { + display: flex; + align-items: flex-start; + gap: 8px; + margin: 0; + padding: 8px 12px; + border-radius: 10px; + background: var(--warn-soft); + color: var(--warn); + font-weight: 500; +} +.sd-clash svg { flex: none; margin-top: 3px; } + +.sd-section { display: flex; flex-direction: column; gap: 8px; min-width: 0; } +.sd-section .section-label { margin: 0; } +.sd-going { display: flex; align-items: flex-start; gap: 8px; margin: 0; color: var(--text-2); } +.sd-going svg { flex: none; margin-top: 3px; color: var(--muted); } +.sd-section .sample-note { margin: 0; } +.sd-description { margin: 0; color: var(--text-2); line-height: 1.65; white-space: pre-line; overflow-wrap: anywhere; } +.sd-more { + align-self: flex-start; + padding: 0; + border: 0; + background: none; + color: var(--accent-ink); + font-weight: 600; + cursor: pointer; +} +.sd-more:hover { text-decoration: underline; } + +.sd-speakers { display: flex; flex-direction: column; gap: 10px; margin: 0; padding: 0; list-style: none; } +.sd-speaker { + display: flex; + gap: 12px; + padding: 12px; + border: 1px solid var(--line); + border-radius: 12px; + background: var(--panel); + min-width: 0; +} +.sd-avatar { width: 38px; height: 38px; font-size: 14px; } +.sd-speaker-body { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; } +.sd-speaker-name { margin: 0; font-weight: 600; } +.sd-speaker-role { margin: 0; color: var(--text-2); font-size: 13px; overflow-wrap: anywhere; } +.sd-speaker-bio { + margin: 2px 0 0; + color: var(--muted); + font-size: 13px; + line-height: 1.55; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 4; + line-clamp: 4; + overflow: hidden; +} +.sd-links { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 2px 0 0; padding: 0; list-style: none; font-size: 13px; } +.sd-links a { display: inline-flex; align-items: center; gap: 4px; } +.sd-also { margin-top: 6px; } +.sd-also-label { margin: 0 0 4px; color: var(--muted); font-size: 12px; } + +.sd-list { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; } +.sd-list-btn { + display: flex; + align-items: flex-start; + gap: 8px; + width: 100%; + padding: 9px 10px; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--panel); + text-align: left; + cursor: pointer; +} +.sd-list-btn:hover { background: var(--panel-2); } +.sd-list-btn .sch-kind { margin-top: 3px; } +.sd-list-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; } +.sd-list-title { font-weight: 600; line-height: 1.35; overflow-wrap: anywhere; } +.sd-list-meta { display: flex; flex-wrap: wrap; gap: 0 8px; color: var(--muted); font-size: 12px; } +.sd-list-meta > span + span::before { content: "\00b7"; margin-right: 8px; } +.sd-list-added { flex: none; padding: 1px 8px; font-size: 11.5px; gap: 4px; } + +@media (max-width: 767px) { + .session-drawer { width: 100%; } + .sd-body { padding: 0 16px calc(24px + env(safe-area-inset-bottom)); } + .sd-head { margin: 0 -16px; padding-left: 16px; } + .sd-title { font-size: 18px; } +} From 28dba58cfc6ab1de3e116c71292f03b1d0546fc9 Mon Sep 17 00:00:00 2001 From: riponcm <86886711+riponcm@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:08:03 -0700 Subject: [PATCH 2/2] Session drawer: keep ?session on Schedule URL updates; Now and Dashboard tiles refetch on agenda changes --- frontend/src/components/dashboard/DashTiles.tsx | 5 ++++- frontend/src/pages/Now.tsx | 5 ++++- frontend/src/pages/Schedule.tsx | 10 ++++++++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/frontend/src/components/dashboard/DashTiles.tsx b/frontend/src/components/dashboard/DashTiles.tsx index 10390ed..a14e242 100644 --- a/frontend/src/components/dashboard/DashTiles.tsx +++ b/frontend/src/components/dashboard/DashTiles.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from 'react' +import { useAgendaVersion } from '../session/context.ts' import { CalendarCheck, CalendarDays, Coffee, Radio, Users } from 'lucide-react' import { DEMO_USER, getJSON } from '../../api.ts' import { roomLabel } from '../schedule/time.ts' @@ -42,11 +43,13 @@ export default function DashTiles({ data }: { data: DashboardData }) { const [now, setNow] = useState(null) const [failed, setFailed] = useState(false) + const agendaVersion = useAgendaVersion() + useEffect(() => { getJSON('now', { user_id: DEMO_USER }) .then(setNow) .catch(() => setFailed(true)) - }, []) + }, [agendaVersion]) // refetch when the session drawer changes the agenda const people = data.people const peopleTile = ( diff --git a/frontend/src/pages/Now.tsx b/frontend/src/pages/Now.tsx index e84717e..19938b5 100644 --- a/frontend/src/pages/Now.tsx +++ b/frontend/src/pages/Now.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from 'react' +import { useAgendaVersion } from '../components/session/context.ts' import { Link } from 'react-router' import { CalendarDays, ChevronDown, Coffee, FileText, Radio, Users } from 'lucide-react' import { DEMO_USER, getJSON } from '../api.ts' @@ -232,11 +233,13 @@ export default function Now() { const [data, setData] = useState(null) const [failed, setFailed] = useState(false) + const agendaVersion = useAgendaVersion() + useEffect(() => { getJSON('now', { user_id: DEMO_USER }) .then(setData) .catch(() => setFailed(true)) - }, []) + }, [agendaVersion]) // refetch when the session drawer changes the agenda return (

    diff --git a/frontend/src/pages/Schedule.tsx b/frontend/src/pages/Schedule.tsx index 13b17c0..765ec46 100644 --- a/frontend/src/pages/Schedule.tsx +++ b/frontend/src/pages/Schedule.tsx @@ -48,8 +48,14 @@ async function loadAgendaIds(userId: string, signal?: AbortSignal): Promise { + const session = prev.get('session') + if (session) next.set('session', session) + return next + } const update = (change: Partial) => - setParams((prev) => toParams({ ...parseState(prev), ...change }), { replace: true }) + setParams((prev) => withSession(prev, toParams({ ...parseState(prev), ...change })), { replace: true }) const setFilters = (filters: Filters) => update({ filters }) const openProfile = useOpenProfile() // Bumped when the session drawer changes the agenda: reload the day and the agenda ids. @@ -139,7 +145,7 @@ export default function Schedule() { const q = query.trim() if (q === debounced) return const t = setTimeout( - () => setParams((prev) => toParams({ ...parseState(prev), q }), { replace: true }), + () => setParams((prev) => withSession(prev, toParams({ ...parseState(prev), q })), { replace: true }), DEBOUNCE_MS, ) return () => clearTimeout(t)