From 8dfab281aabb86bf1f52a800ca41d03243ab7ef0 Mon Sep 17 00:00:00 2001 From: jack Date: Mon, 30 Nov 2026 06:26:47 -0600 Subject: [PATCH] feat: Patchy mood and waiting indicators, plus named-facts memory Co-authored-by: Sonic Assistant --- app.py | 2 +- backend/components/sonic_changelog.py | 14 + backend/tests/test_named_facts.py | 141 +++++++++ backend/utils/memory_utils.py | 18 +- backend/utils/named_facts.py | 94 ++++++ backend/utils/self_counters.py | 2 +- local/src/components/ChangeCard.tsx | 2 + local/src/components/ChoiceCard.tsx | 4 +- local/src/components/MiniPatchy.tsx | 25 +- local/src/components/PatchyParts.tsx | 30 +- local/src/components/RunnerCheckCard.tsx | 7 + .../src/components/__styles__/MiniPatchy.css | 26 ++ local/src/components/patchyLook.ts | 12 +- local/src/components/patchyWatch.test.mjs | 267 ++++++++++++++++++ local/src/components/patchyWatch.ts | 65 +++++ local/src/components/turnWaiting.ts | 49 ++++ local/src/hooks/usePatchyMood.ts | 8 +- local/src/hooks/useTurnWaiting.ts | 7 + local/src/hooks/useWatchCheck.ts | 17 ++ local/src/pages/Chat.tsx | 17 +- local/src/patchy-preview-main.tsx | 19 +- 21 files changed, 802 insertions(+), 24 deletions(-) create mode 100644 backend/tests/test_named_facts.py create mode 100644 backend/utils/named_facts.py create mode 100644 local/src/components/patchyWatch.test.mjs create mode 100644 local/src/components/patchyWatch.ts create mode 100644 local/src/components/turnWaiting.ts create mode 100644 local/src/hooks/useTurnWaiting.ts create mode 100644 local/src/hooks/useWatchCheck.ts diff --git a/app.py b/app.py index 13175801..2befac48 100644 --- a/app.py +++ b/app.py @@ -1657,7 +1657,7 @@ def _read_progress_notes(): await asyncio.to_thread(load_user_facts, username) guardrail_context = await asyncio.to_thread(fetch_relevant_corrections, username, question) # question_embedding (computed above, before the relatable line) is threaded through both fact + semantic memory recall — they embed the identical question string this turn. - memory_context = await asyncio.to_thread(lambda: fetch_relevant_user_facts(username, question, precomputed_embedding=question_embedding, messages=chat_sessions[history_key])) + memory_context = await asyncio.to_thread(lambda: fetch_relevant_user_facts(username, question, precomputed_embedding=question_embedding, messages=chat_sessions[history_key], counts=turn_counts)) goal_nudge_context = "" if (risk_level != RISK_NONE or open_loop_entry) else await asyncio.to_thread(fetch_goal_nudge_context, username) if guardrail_context: diff --git a/backend/components/sonic_changelog.py b/backend/components/sonic_changelog.py index cec1aa3c..b73d77a1 100644 --- a/backend/components/sonic_changelog.py +++ b/backend/components/sonic_changelog.py @@ -1711,6 +1711,20 @@ "keywords": ["several places", "read faster", "too many steps", "reads too much", "multiple files at once", "ranges"], "volunteer": [], }, + { + "id": "named_things_recalled", + "requires": [ + "backend/utils/named_facts.py::def pick", + "backend/utils/memory_utils.py::named_facts.pick", + ], + "month": "2026-11", + "title": "When you name something, I bring what I know about it", + "line": ( + "When you mention something by name that I have notes about (a place, an employer, a person), I now bring those notes into my reply even if the rest of your message is about something else." + ), + "keywords": ["forgot", "didn't remember", "nothing saved", "you should know", "remember", "my notes about"], + "volunteer": [], + }, { "id": "voice_examples", "requires": [ diff --git a/backend/tests/test_named_facts.py b/backend/tests/test_named_facts.py new file mode 100644 index 00000000..67cd6597 --- /dev/null +++ b/backend/tests/test_named_facts.py @@ -0,0 +1,141 @@ +"""Saved facts that name what the message names get a place in the reply, whatever their rank (backend/utils/named_facts.py, memory_utils.fetch_relevant_user_facts). +The real case (2026-11-30): a message mostly about a run named Casey's in passing; the best of sixteen Casey's facts ranked 19th and the reply said it had nothing saved about it. +No database and no model: facts are stored in a temporary folder and the embedding is faked.""" +from types import SimpleNamespace + +import pytest + +from backend.utils import memory_utils +from backend.utils import named_facts as nf + +QUESTION = "going out for the run anyway even though i dont want to. still nothing from caseys, no idea when theyll get back to me" +RUN = "Jack runs most mornings and finds the first mile hard when he is tired." +SLEEP = "Jack has been sleeping badly before early runs." +SHOES = "Jack bought new running shoes in October." +MORNING = "Jack prefers to run before work in the cold." +GOAL = "Jack wants to run a half marathon next spring." +CASEY_ROLE = "Jack interviewed for a software engineer role in the AI Center of Excellence at Casey's." +CASEY_ONSITE = "Jack finished the four-round onsite at Casey's on Monday, November 16." +CASEY_OLD = "Jack missed an earlier interview at Casey's and tried to reschedule it." +VECTORS = { + QUESTION: [1.0, 0.0], + "going out for the run anyway": [1.0, 0.0], + RUN: [0.99, 0.1], SLEEP: [0.98, 0.15], SHOES: [0.97, 0.2], MORNING: [0.96, 0.25], GOAL: [0.95, 0.3], + CASEY_ROLE: [0.3, 0.95], CASEY_ONSITE: [0.25, 0.97], CASEY_OLD: [0.2, 0.98], # far from the run-shaped message: they lose every one of the five slots +} + + +@pytest.fixture(autouse=True) +def isolated(tmp_path, monkeypatch): + monkeypatch.setattr(memory_utils, "DATA_DIR", str(tmp_path)) + monkeypatch.setattr(memory_utils, "get_db", lambda: None) + monkeypatch.setattr(memory_utils, "embed_text", lambda text: VECTORS.get(text.strip(), [0.0, 0.1])) + yield + + +def _store(*texts, category="goal"): + for text in texts: + memory_utils.save_user_fact("jack", text, category=category) + + +def _all(): + _store(RUN, SLEEP, SHOES, MORNING, GOAL) + _store(CASEY_ROLE, CASEY_ONSITE, CASEY_OLD, category="career") + + +def _fact(text, active=True): + return SimpleNamespace(fact=text, active=active) + + +# ---- the real case through the lookup ---------------------------------------------------------------------------------------------------------- + +def test_a_name_mentioned_in_passing_brings_its_facts_although_they_rank_last(): + _all() + counts = {} + block = memory_utils.fetch_relevant_user_facts("jack", QUESTION, limit=5, counts=counts) + assert RUN in block # the ranking itself is unchanged + assert CASEY_ROLE in block and CASEY_ONSITE in block # the two best facts that name it + assert CASEY_OLD not in block # at most FACTS_PER_NAME + assert "THEY NAMED Casey: " in block and "never say you have nothing saved about it" in block + assert counts == {"memory_named_facts": 1} + + +def test_without_the_name_nothing_is_added_and_nothing_is_counted(): + _all() + counts = {} + block = memory_utils.fetch_relevant_user_facts("jack", "going out for the run anyway", limit=5, counts=counts) + assert "Casey" not in block and "THEY NAMED" not in block and counts == {} + + +def test_a_named_fact_already_in_the_five_is_not_counted_as_added(): + _all() + counts = {} + block = memory_utils.fetch_relevant_user_facts("jack", QUESTION, limit=20, counts=counts) + assert CASEY_ROLE in block and "THEY NAMED Casey" in block and counts == {} + + +# ---- which words are names ----------------------------------------------------------------------------------------------------------------------- + +def test_names_come_from_the_middle_of_a_sentence_and_skip_days_months_and_the_assistant(): + facts = [_fact("Jack met Priya at Casey's on Monday in November."), _fact("Jack asked Sonic about it."), _fact("Priya works nights.")] + names = nf.vocabulary(facts) + assert "casey" in names and "priya" in names + assert "monday" not in names and "november" not in names and "sonic" not in names + assert names["casey"] == "Casey" + + +def test_a_name_in_a_large_share_of_facts_says_too_little(): + facts = [_fact(f"Every day Jack works on thing {i} with Robin.") for i in range(10)] + [_fact(f"Once Jack saw Quinn at the park {i}.") for i in range(1)] + [_fact(f"Plain fact {i}.") for i in range(30)] + names = nf.vocabulary(facts) # 10 of 41 facts name Robin: more than COMMON_SHARE + assert "robin" not in names and "quinn" in names + + +def test_inactive_facts_neither_name_nor_count(): + assert nf.vocabulary([_fact("Jack met Priya once.", active=False)]) == {} + facts = [_fact("Jack met Priya once.", active=False), _fact("Jack likes Priya's cooking.")] + chosen, _ = nf.pick("priya called", facts) + assert chosen == [facts[1]] + + +def test_the_message_may_be_lowercase_possessive_or_typographic(): + names = {"casey": "Casey", "priya": "Priya"} + assert nf.named_in("still nothing from caseys", names) == ["casey"] # people drop the apostrophe + assert nf.named_in("still nothing from casey's", names) == ["casey"] + assert nf.named_in("still nothing from Casey’s", names) == ["casey"] + assert nf.named_in("priya and casey both called", names) == ["priya", "casey"] # in the order the message uses them + + +def test_an_everyday_word_counts_only_with_a_capital(): + names = {"will": "Will", "hope": "Hope"} + assert nf.named_in("i will go and i hope so", names) == [] + assert nf.named_in("Will said Hope is coming", names) == ["will", "hope"] + assert nf.named_in("Will's car broke", names) == ["will"] + + +def test_at_most_three_names_and_two_facts_each_best_first(): + names = {k: k.title() for k in ("ann", "bea", "cal", "dee")} + assert nf.named_in("ann bea cal dee", names) == ["ann", "bea", "cal"] + ranked = [_fact(f"Jack saw Ann at place {i}.") for i in range(4)] + [_fact(f"Plain fact {i}.") for i in range(80)] # filler, so Ann is not in too large a share + chosen, shown = nf.pick("ann again", ranked) + assert chosen == ranked[:nf.FACTS_PER_NAME] and shown == ["Ann"] + + +def test_one_fact_naming_two_things_is_given_once(): + both = _fact("Jack met Priya at Casey's.") + chosen, shown = nf.pick("priya and casey's", [both, _fact("Jack and Priya cook.")]) + assert chosen.count(both) == 1 and shown == ["Priya", "Casey"] + + +def test_nothing_named_gives_nothing(): + assert nf.pick("just tired today", [_fact("Jack met Priya at Casey's.")]) == ([], []) + assert nf.note([]) == "" + + +def test_the_reply_passes_its_turn_counters_and_the_counter_is_known(): + from pathlib import Path + + from backend.utils import self_counters + + app_source = (Path(__file__).resolve().parents[2] / "app.py").read_text(encoding="utf-8") + assert "messages=chat_sessions[history_key], counts=turn_counts))" in app_source + assert "memory_named_facts" in self_counters._PLAIN_KEYS diff --git a/backend/utils/memory_utils.py b/backend/utils/memory_utils.py index 90ea2301..c7e589b0 100644 --- a/backend/utils/memory_utils.py +++ b/backend/utils/memory_utils.py @@ -5,7 +5,7 @@ import uuid import logging from datetime import datetime, timezone -from typing import List, Optional +from typing import Dict, List, Optional import numpy as np from pydantic import BaseModel, Field @@ -14,7 +14,7 @@ from backend.utils.embedding_utils import embed_text, cosine_similarity from backend.components.constraints import FACT_CONFLICT_PROMPT, GOAL_STATUS_PROMPT from backend.models.models import lite_llm -from backend.utils import conversation_people, fact_links, name_aliases +from backend.utils import conversation_people, fact_links, name_aliases, named_facts from backend.services.memory_search import flag_stale_chunks_for_superseded_fact logger = logging.getLogger("SASS Logger") @@ -789,7 +789,7 @@ def fetch_goal_nudge_context(username: str) -> str: def fetch_relevant_user_facts( - username: str, question: str, limit: int = 5, precomputed_embedding: Optional[List[float]] = None, messages=None, + username: str, question: str, limit: int = 5, precomputed_embedding: Optional[List[float]] = None, messages=None, counts: Optional[Dict[str, int]] = None, ) -> str: """ Builds a short "known about this user" context block for passive injection into every @@ -808,6 +808,10 @@ def fetch_relevant_user_facts( messages: the conversation so far (backend/utils/conversation_people.py). A message with no name in it ("I'm afraid I won't see her again") used to be matched on its words alone and picked facts about people who had not come up in weeks; now facts about the people the conversation has been about rank higher, and a reply to a message that names nobody is told who they are. + + A name the message uses that their facts also use ("Casey's") brings the best facts that mention it, whatever their rank (backend/utils/named_facts.py): on 2026-11-30 a message mostly about + a run named Casey's in passing, the best of sixteen Casey's facts ranked 19th, and the reply said it had nothing saved about it. `counts` (the turn's counters) gets memory_named_facts + when that added a fact the ranking left out. """ try: facts = load_user_facts(username) @@ -854,15 +858,19 @@ def fetch_relevant_user_facts( ) matched = ranked_other[:remaining_slots] + named, names = named_facts.pick(question, ranked_other) + added = [f for f in named if f not in matched] + if added and counts is not None: + counts["memory_named_facts"] = counts.get("memory_named_facts", 0) + 1 # A fact chosen because it matches the question brings along the facts bound to it (the project, and where it is done), so the context the # person already gave about the same thing is not lost. Identity facts are always shown anyway and do not bring anything extra. - top_facts = identity_facts + domain_anchors(other_facts) + matched + fact_links.linked_extras(matched, facts) + top_facts = identity_facts + domain_anchors(other_facts) + matched + added + fact_links.linked_extras(matched, facts) seen_ids: set = set() top_facts = [f for f in top_facts if not (f.id in seen_ids or seen_ids.add(f.id))] if not top_facts: return "" - return format_facts_block(top_facts) + conversation_people.people_note(people, question) + return format_facts_block(top_facts) + named_facts.note(names) + conversation_people.people_note(people, question) except Exception: logger.exception("[MEMORY WARNING] Could not fetch user facts for %s", username) return "" diff --git a/backend/utils/named_facts.py b/backend/utils/named_facts.py new file mode 100644 index 00000000..6a90d930 --- /dev/null +++ b/backend/utils/named_facts.py @@ -0,0 +1,94 @@ +"""Saved facts that name what the message names get a place in the reply, whatever their rank. + +THE FAILURE (2026-11-30): "...going for a run... and still waiting to hear from Casey's" got "I don't have anything saved about it. Is Casey's a job?" Sixteen of the person's 911 facts mention Casey's. +The facts block is the five facts closest in MEANING to the message (memory_utils.fetch_relevant_user_facts), and a message mostly about a run sits closest to run and morning facts: the best +Casey's fact ranked 19th. The next message used the role's own words and only just made the five. + +THE RULE: a name in the message (a capitalised word from the middle of a sentence in one of their facts: a place, an employer, a person, a product) that also appears in their facts brings the +best FACTS_PER_NAME facts that mention it, for up to NAMES_PER_MESSAGE names. Pure code, no model call, no name in any log line. A word in a large share of their facts (their own name, +the assistant's) is not a name worth matching, nor are days and months, and a word that is also an everyday word ("will", "may") counts only when the message capitalises it. +""" +import re +from typing import Any, Dict, List, Sequence, Tuple + +from backend.utils.conversation_people import _mid_sentence_capitals + +NAMES_PER_MESSAGE = 3 +FACTS_PER_NAME = 2 +COMMON_SHARE = 0.05 # a name in more than this share of all their facts says too little to pick facts by +MIN_COMMON_AT = 3 + +_SKIP = frozenset({ + "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", + "november", "december", "sonic", "saapp", "patchy", "the", "this", "that", "they", "their", "she", "her", "his", "him", "and", "but", +}) +# Names that are also everyday words: matched only when the message writes them with a capital. +_EVERYDAY = frozenset({ + "will", "mark", "bill", "grace", "hope", "rose", "faith", "joy", "art", "max", "sky", "summer", "dawn", "rich", "frank", "pat", "sue", "chase", "page", "case", "cash", "jack", "jade", + "amber", "ruby", "pearl", "iris", "lily", "ivy", "holly", "angel", "bob", "drew", "gene", "guy", "harry", "jean", "ken", "lee", "nick", "penny", "ray", "rob", "sandy", "tom", "wade", "west", + "young", "king", "price", "cook", "baker", "hunter", "carter", "porter", "turner", "parker", "mason", "miles", "ford", "may", "august", "june", "april", "home", "work", "target", +}) + + +def _words(text: str) -> set: + """The words of a text, casefolded, with a possessive 's taken off ("Casey's" -> "casey").""" + return {w[:-2] if w.endswith("'s") else w for w in re.findall(r"[a-z0-9]+(?:'s)?", text.casefold())} + + +def vocabulary(facts: Sequence[Any]) -> Dict[str, str]: + """casefolded name -> the name as written, for the names in their active facts that are specific enough to pick facts by.""" + active = [f for f in facts if getattr(f, "active", True)] + counts: Dict[str, int] = {} + shown: Dict[str, str] = {} + for fact in active: + for word in {w for w in _mid_sentence_capitals(getattr(fact, "fact", "") or "")}: + key = word.casefold() + if key in _SKIP: + continue + shown.setdefault(key, word) + for fact in active: + for key in _words(getattr(fact, "fact", "") or "") & shown.keys(): + counts[key] = counts.get(key, 0) + 1 + common_at = max(COMMON_SHARE * len(active), MIN_COMMON_AT) + return {key: word for key, word in shown.items() if counts.get(key, 0) <= common_at} + + +def named_in(question: str, names: Dict[str, str]) -> List[str]: + """The names from `names` that the message uses, in the order it uses them, at most NAMES_PER_MESSAGE. Case does not matter (people type "caseys"), except for everyday words.""" + text = question or "" + words = _words(text) + words |= {w[:-1] for w in words if w.endswith("s") and len(w) > 3} # "caseys": people drop the apostrophe + lowered = text.casefold() + found = [] + for key, word in names.items(): + if key in _EVERYDAY: + match = re.search(r"\b" + re.escape(word) + r"(?:'s)?\b", text) # case kept: "Will" is a name, "will" is not + if match: + found.append((match.start(), key)) + elif key in words: + found.append((lowered.find(key), key)) + return [key for _, key in sorted(found)][:NAMES_PER_MESSAGE] + + +def pick(question: str, ranked_facts: Sequence[Any]) -> Tuple[List[Any], List[str]]: + """(facts, names): for each name the message uses that their facts know, the first FACTS_PER_NAME of `ranked_facts` (best first) that mention it, and the names as written in the facts. + ([], []) when it names nothing they have saved.""" + names = vocabulary(ranked_facts) + used = named_in(question, names) + chosen: List[Any] = [] + for key in used: + taken = 0 + for fact in ranked_facts: + if taken >= FACTS_PER_NAME: + break + if getattr(fact, "active", True) and key in _words(getattr(fact, "fact", "") or "") and fact not in chosen: + chosen.append(fact) + taken += 1 + return chosen, [names[key] for key in used] + + +def note(names: Sequence[str]) -> str: + """The line under the facts block when the message named something they have facts about.""" + if not names: + return "" + return (f"THEY NAMED {', '.join(names)}: the saved facts above that mention it are about what they mean. Use them, and never say you have nothing saved about it.\n") diff --git a/backend/utils/self_counters.py b/backend/utils/self_counters.py index 5d01b03a..57c447da 100644 --- a/backend/utils/self_counters.py +++ b/backend/utils/self_counters.py @@ -101,7 +101,7 @@ # How much each turn mattered, whatever model wrote it (backend/utils/reply_tier.py STAKES, plus "none" for a plain turn): sizes the turns a stronger reply voice would be spent on. Counts only. "reply_stakes": ("safety", "emotional", "checkin", "companion", "identity", "frustration", "none"), } -_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "code_thinking_turns", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "code_after_edit_check_held", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "support_card_none", "support_card_moved_on", "support_card_stopped","encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") +_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "memory_named_facts", "code_thinking_turns", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "code_after_edit_check_held", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "support_card_none", "support_card_moved_on", "support_card_stopped","encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") # The rhythm of a coding turn (backend/utils/loop_rhythm.py): turns it was followed on, turns that acted at all, reads before the first act (summed), edits applied, applied edits checked in the next # step, and reading-streak notices shown. Counts only. RHYTHM_KEYS = ("code_rhythm_turns", "code_rhythm_acted_turns", "code_rhythm_reads_before_first_act", "code_rhythm_applies", "code_rhythm_applies_checked", "code_rhythm_streak_notices") diff --git a/local/src/components/ChangeCard.tsx b/local/src/components/ChangeCard.tsx index ddff18b0..65e08f10 100644 --- a/local/src/components/ChangeCard.tsx +++ b/local/src/components/ChangeCard.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react'; import { api } from '../api'; +import { theyAnswered } from './turnWaiting'; import { outcomeLine, type ChangeCardData, type ChangeStatus } from './changeCardLogic'; import './__styles__/ChangeCard.css'; @@ -29,6 +30,7 @@ export default function ChangeCard({ card }: ChangeCardProps) { setState({ kind: 'sending' }); try { const reply = await api.decideChange(card.proposal_id, decision); + theyAnswered(card.proposal_id, reply.status === 'applied' ? 'approved' : reply.status === 'declined' ? 'noted' : null); if (!alive.current) return; setState({ kind: 'done', status: reply.status, message: reply.message || '' }); } catch (problem) { diff --git a/local/src/components/ChoiceCard.tsx b/local/src/components/ChoiceCard.tsx index 411e561a..26d838b9 100644 --- a/local/src/components/ChoiceCard.tsx +++ b/local/src/components/ChoiceCard.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react'; import { api } from '../api'; +import { theyAnswered } from './turnWaiting'; import { MAX_OTHER_CHARS, afterAnswer, answerText, cleanOther, goesAsMessage, messageFor, type ChoiceAnswer, type ChoiceCardData } from './choiceCardLogic'; import './__styles__/ChoiceCard.css'; @@ -47,8 +48,9 @@ export default function ChoiceCard({ card, onSendMessage }: ChoiceCardProps) { setState({ kind: 'sending' }); try { const reply = await api.answerChoice(card.choice_id, 'index' in answer ? { index: answer.index } : { other: answer.other }); - if (!alive.current) return; const next = afterAnswer(card, reply.status); + theyAnswered(card.choice_id, next === 'answered' ? 'noted' : null); // the turn has its answer, or is not there to have it: it waits on this card no longer + if (!alive.current) return; if (next === 'send') sendAsMessage(answer); else setState(next === 'answered' ? { kind: 'answered', answer } : { kind: 'expired' }); } catch (problem) { diff --git a/local/src/components/MiniPatchy.tsx b/local/src/components/MiniPatchy.tsx index 286dd88e..e11b4d5b 100644 --- a/local/src/components/MiniPatchy.tsx +++ b/local/src/components/MiniPatchy.tsx @@ -2,6 +2,8 @@ import { useEffect, useRef, useState, type CSSProperties } from 'react'; import { usePatchyMood, type PatchySignals } from '../hooks/usePatchyMood'; import { useStretchRig } from '../hooks/useStretchRig'; import { useYawn } from '../hooks/useYawn'; +import { useWatchCheck } from '../hooks/useWatchCheck'; +import { APPROVED_MS } from './patchyWatch'; import { PatchyHead, PatchyRightArm } from './PatchyParts'; import { loopVictory, motionAllowed, patchyRootClass, patchyTitle, type ArmPose } from './patchyLook'; import { STRETCH_STAGES, STRETCH_START_DELAY_MS, stretchFlags } from './patchyStretch'; @@ -20,6 +22,8 @@ import './__styles__/MiniPatchy.css'; // over his eye), PUZZLED (a shrug, one brow up, a sweat drop, a question mark when a query is rewritten or an answer reconsidered) and // WRITING (both hands on the keyboard, code building line by line); // - when a turn ends he celebrates (a check pops off the laptop and he hops), or, if it failed, his face turns sorry and red instead; +// - while a turn waits for you to answer a card (Apply, Run, a choice) he stops working and looks at you, and after a while checks his wristwatch, then looks up with a brow raised; in a long wait he holds it to his ear +// (patchyWatch.ts). Say yes and he hops back to work; say anything else and he nods "got it"; // - he watches the box while you type, nods "got it" when you steer a running turn, and gets drowsy after a long quiet; // - the usage budget shows too: a sweat drop at the notice level, heavy lids when chat is throttled, asleep when it is paused; // - poke him and he giggles (pink), idle he waves now and then. @@ -115,6 +119,21 @@ export function MiniPatchy(props: PatchySignals) { rightHandRef.current?.setAttribute('cx', String(rig.right[4])); rightHandRef.current?.setAttribute('cy', String(rig.right[5])); }); + // Waiting on the person, he checks his watch now and then (patchyWatch.ts). + const beat = useWatchCheck(mood === 'waiting', energy); + // They said yes to the card (the page bumps `approved`): a little hop on the way back to work. A low person is not hopped at. + const [seenApproved, setSeenApproved] = useState(props.approved ?? 0); + const [hopping, setHopping] = useState(false); + if ((props.approved ?? 0) !== seenApproved) { + setSeenApproved(props.approved ?? 0); + if (motionAllowed() && energy !== 'subdued') setHopping(true); + } + useEffect(() => { + if (!hopping) return undefined; + const timer = window.setTimeout(() => setHopping(false), APPROVED_MS); + return () => window.clearTimeout(timer); + }, [hopping, seenApproved]); + const approving = hopping && mood === 'active'; // Drowsy, he yawns every so often (patchyYawn.ts); in the tool loop, the gears turn. const yawning = useYawn(mood === 'drowsy'); const looping = props.loop === true && mood === 'active'; @@ -125,6 +144,8 @@ export function MiniPatchy(props: PatchySignals) { : stretch.stretching ? (stretch.reach ? 'cheer' : 'hang') : yawning ? 'yawn' : victory ? 'cheer' + : approving ? 'cheer' + : mood === 'waiting' ? (beat === 'listen' ? 'listen' : beat === 'none' ? 'hang' : 'watch') // between checks the arm just hangs; no wave, he is not saying hello : mood === 'active' ? (look === 'thinking' ? 'think' : look === 'searching' ? 'search' : look === 'puzzled' ? 'puzzle' : 'type') : mood === 'idle' ? 'hang' : mood === 'praise' ? 'fistpump' // praise: right arm snaps up into the fist pump @@ -137,7 +158,7 @@ export function MiniPatchy(props: PatchySignals) { return (