Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

feat(ui): split Learning by category and forget several at once (#588)

Rufusd4c84bc6896c
diff --git a/packages/core/openexecutive/guide/prebuilt/pulse.json b/packages/core/openexecutive/guide/prebuilt/pulse.json
index d3401a54..18c5e224 100644
--- a/packages/core/openexecutive/guide/prebuilt/pulse.json
+++ b/packages/core/openexecutive/guide/prebuilt/pulse.json
@@ -1,7 +1,7 @@
{
"section_id": "pulse",
"title": "Pulse (Memory)",
- "markdown": "**What it is:** The Executive's running memory and heartbeat — the decisions it has made with you, the initiatives it's tracking, the advice it has gathered, and the rhythm of work it runs on its own.\n\n**What it does:**\n\n- Browse past **decisions** with their rationale and outcome.\n- Track **initiatives** as planned, active, paused, or completed.\n- Review **advice** collected from specialists, labelled by domain.\n- See your **corrections** — facts you corrected or asked the Executive to keep, where you said them, and what they replaced. They hold everywhere: every conversation, brief, scheduled run and alert review.\n- See the **heartbeat** — the recurring cadence of daily briefs, department check-ins, system scans, and pending scheduled follow-ups.\n- Keep **your notes**: what you said, in chat and in replies you approved. Each person sees only their own notes; the owner can't see anyone else's.\n- See **Done for you**: what the Executive did for you this month, counted from the record (only the owner sees the count), then the last few things it did on its own, each with a line on what came of it.\n- See how it is **learning**: after a chat goes quiet, the Executive checks its own answers from your words and your reactions (a correction, a 👎, a reply you stopped, a turn you asked again). The ones that fell short are listed with what you wanted instead and a link to the conversation. Each person sees their own. The owner also sees the ones from channels and group chats, never a teammate's own chat with the Executive, which stays theirs as it does everywhere else. Under the misses, **What it learned**: one line per lesson, in your own words, that the Executive keeps from a miss (a term you use, something you always want included, a thing to do rather than promise, which specialist to ask). It reads a lesson on later chats about the same thing and keeps count of how those went; one that doesn't help stops on its own and is listed under **Stopped saying it**. **Forget** stops one by hand. A lesson applies to the chats of the person it was learned from; one the owner taught it in a channel or group chat applies to everyone's, and is marked so. At the top, the proof: **of the things that went wrong in the last 30 days, how many would go right today**. Each night the Executive replays its misses with everything it has learned since, in a dry run nobody receives (it reads for real but sends, books and saves nothing), and a judge says whether each would now go right. A miss that now passes is marked so with the date; one that depends on what that day's calendar or inbox held is kept as evidence only. A lesson that doesn't fix its miss after two tries, or that twice breaks a chat you had given a thumbs up, stops on its own.\n- Edit or delete any item to keep the Executive's memory accurate.\n\n**How to use:**\n\n1. Just chat. Decisions, initiatives and advice are pulled out of your conversations automatically after each chat — there's nothing to add by hand.\n2. Click **Pulse** in the sidebar. The **Heartbeat** card shows the last 90 days beside three numbers: what it did today, how long until the next thing it does, and how many days in a row it has been active. **More detail** opens the rest. Below it, under **What it remembers**, a tile for **Decisions**, **Projects**, **Advice**, **Facts you taught it**, **Your notes** and **Learning** opens that list on its own screen; **Pulse** at the top takes you back. Then **Coming up** lists the next few briefs, check-ins and follow-ups (**Full schedule** shows them all, with background scans under **Show background scans**; choose **Cancel follow-up** in a follow-up's **⋯** to drop it), and **Done for you** opens with this month's count in one line (owner only; click it for every count by month or week, against the period before), then lists the last few things it did, each saying what came of it, with **Read it** where it wrote something up and **See changes** on a day it kept your contacts up to date (**All activity** shows the full feed).\n3. Choose **Edit** in any row's **⋯** menu to correct it — fix a decision's summary, rationale or outcome, change its domain or tags, change a project's title, summary or status (*planned*, *active*, *paused*, *completed*), or fix an advice item's question, advice or domain — then **Save**.\n4. Choose **Delete** in the same menu to remove something that's simply wrong. It asks first; this can't be undone.\n5. On **Your notes**, search with **Search your notes**, and use a note's **⋯**: **Correct**, **Pin** / **Unpin**, **Don't remember this** (forgets every note from that conversation and never notes it again) or **Forget** (deletes that one note). Both ask first and can't be undone.\n6. On **Learning**, a **How it learns** card at the top shows the four steps (you chat, it looks back 30 minutes later, it keeps a lesson, it checks itself each night) with your own numbers: answers checked this week, how many fell short, lessons kept, and how many of the last 30 days' misses would go right today. **Hide** folds it away. Below it, a bar counts the turns that fell short by week. Under **Something to learn** are misses a term, a fact or a preference would have fixed; under **Couldn't do it**, ones where a tool failed or it was asked for something it can't do yet. **See the conversation** opens the chat; **Forget** in a row's **⋯** drops it from the record.\n7. To correct a fact, just say it in chat — *\"Maple House is 48 units, not 52\"* or *\"we're 42 people now\"*. The Executive keeps it (a company-profile field such as headcount or burn updates the profile too), and it shows under **Facts you taught it** with your words. Choose **Retire (stop using it)** in a correction's **⋯** menu when it no longer holds (it asks first); a company-profile change is fixed on the Company profile instead. Older, retired and declined versions stay under **Show history (N)**. You can also email a correction from your own address: nothing changes until you reply CONFIRM to the confirmation email the Executive sends you. Teammates on your People list can correct facts too, from the web app or their own Slack or Discord. Theirs are marked with their name and wait for your approval at the top of that list with **Approve** and **Decline** (the tile says how many), and they appear in your morning brief. Under **Teammates' corrections**, untick **needs my approval** next to a teammate you trust to let theirs apply straight away; one that would replace yours still waits for you. Only you can retire someone else's correction.\n\n**Example:** tell the Executive *\"we've decided to push the EU launch to Q2 so we can finish SOC 2 first.\"* Afterwards, **Pulse → Decisions** shows that decision with its rationale. If it captured the wrong reason, edit it — future answers build on what's recorded here.\n\n**Just for yourself?** When you use Open Executive just for yourself, the heartbeat leaves out department check-ins and the \"Awaiting people\" list, and the count of active projects takes the department check-ins' place under **More detail**. The same projects appear on Home under **Your projects**.\n\n*Note: this memory is searchable across the system, so what's captured here informs future answers.*",
+ "markdown": "**What it is:** The Executive's running memory and heartbeat — the decisions it has made with you, the initiatives it's tracking, the advice it has gathered, and the rhythm of work it runs on its own.\n\n**What it does:**\n\n- Browse past **decisions** with their rationale and outcome.\n- Track **initiatives** as planned, active, paused, or completed.\n- Review **advice** collected from specialists, labelled by domain.\n- See your **corrections** — facts you corrected or asked the Executive to keep, where you said them, and what they replaced. They hold everywhere: every conversation, brief, scheduled run and alert review.\n- See the **heartbeat** — the recurring cadence of daily briefs, department check-ins, system scans, and pending scheduled follow-ups.\n- Keep **your notes**: what you said, in chat and in replies you approved. Each person sees only their own notes; the owner can't see anyone else's.\n- See **Done for you**: what the Executive did for you this month, counted from the record (only the owner sees the count), then the last few things it did on its own, each with a line on what came of it.\n- See how it is **learning**: after a chat goes quiet, the Executive checks its own answers from your words and your reactions (a correction, a 👎, a reply you stopped, a turn you asked again). The ones that fell short are listed with what you wanted instead and a link to the conversation. Each person sees their own. The owner also sees the ones from channels and group chats, never a teammate's own chat with the Executive, which stays theirs as it does everywhere else. Under the misses, **What it learned**: one line per lesson, in your own words, that the Executive keeps from a miss (a term you use, something you always want included, a thing to do rather than promise, which specialist to ask). It reads a lesson on later chats about the same thing and keeps count of how those went; one that doesn't help stops on its own and is listed under **Stopped saying it**. **Forget** stops one by hand. A lesson applies to the chats of the person it was learned from; one the owner taught it in a channel or group chat applies to everyone's, and is marked so. At the top, the proof: **of the things that went wrong in the last 30 days, how many would go right today**. Each night the Executive replays its misses with everything it has learned since, in a dry run nobody receives (it reads for real but sends, books and saves nothing), and a judge says whether each would now go right. A miss that now passes is marked so with the date; one that depends on what that day's calendar or inbox held is kept as evidence only. A lesson that doesn't fix its miss after two tries, or that twice breaks a chat you had given a thumbs up, stops on its own.\n- Edit or delete any item to keep the Executive's memory accurate.\n\n**How to use:**\n\n1. Just chat. Decisions, initiatives and advice are pulled out of your conversations automatically after each chat — there's nothing to add by hand.\n2. Click **Pulse** in the sidebar. The **Heartbeat** card shows the last 90 days beside three numbers: what it did today, how long until the next thing it does, and how many days in a row it has been active. **More detail** opens the rest. Below it, under **What it remembers**, a tile for **Decisions**, **Projects**, **Advice**, **Facts you taught it**, **Your notes** and **Learning** opens that list on its own screen; **Pulse** at the top takes you back. Then **Coming up** lists the next few briefs, check-ins and follow-ups (**Full schedule** shows them all, with background scans under **Show background scans**; choose **Cancel follow-up** in a follow-up's **⋯** to drop it), and **Done for you** opens with this month's count in one line (owner only; click it for every count by month or week, against the period before), then lists the last few things it did, each saying what came of it, with **Read it** where it wrote something up and **See changes** on a day it kept your contacts up to date (**All activity** shows the full feed).\n3. Choose **Edit** in any row's **⋯** menu to correct it — fix a decision's summary, rationale or outcome, change its domain or tags, change a project's title, summary or status (*planned*, *active*, *paused*, *completed*), or fix an advice item's question, advice or domain — then **Save**.\n4. Choose **Delete** in the same menu to remove something that's simply wrong. It asks first; this can't be undone.\n5. On **Your notes**, search with **Search your notes**, and use a note's **⋯**: **Correct**, **Pin** / **Unpin**, **Don't remember this** (forgets every note from that conversation and never notes it again) or **Forget** (deletes that one note). Both ask first and can't be undone.\n6. On **Learning**, a **This week** card shows your numbers: answers checked this week, how many fell short, lessons kept, and how many of the last 30 days' misses would go right today. **How it learns** opens the four steps (you chat, it looks back 30 minutes later, it keeps a lesson, it checks itself each night). Below it, **What fell short** and **What it learned** switch between the misses and the lessons. Misses are grouped under **Something to learn** (a term, a fact or a preference would have fixed it) and **Couldn't do it** (a tool failed, or it was asked for something it can't do yet); pick one of those chips to see only that kind. Click a row to see what it said, what you wanted and **See the conversation**. To clear several at once, tick their boxes (or **Select all**, or **Select the N that are fixed** for the ones that would go right today; on lessons, **Select the N not helping**) and choose **Forget** (**Stop saying** for lessons). **Undo** brings them back for a few seconds; after that a forgotten miss is gone. Retired lessons are under **Show N stopped**.\n7. To correct a fact, just say it in chat — *\"Maple House is 48 units, not 52\"* or *\"we're 42 people now\"*. The Executive keeps it (a company-profile field such as headcount or burn updates the profile too), and it shows under **Facts you taught it** with your words. Choose **Retire (stop using it)** in a correction's **⋯** menu when it no longer holds (it asks first); a company-profile change is fixed on the Company profile instead. Older, retired and declined versions stay under **Show history (N)**. You can also email a correction from your own address: nothing changes until you reply CONFIRM to the confirmation email the Executive sends you. Teammates on your People list can correct facts too, from the web app or their own Slack or Discord. Theirs are marked with their name and wait for your approval at the top of that list with **Approve** and **Decline** (the tile says how many), and they appear in your morning brief. Under **Teammates' corrections**, untick **needs my approval** next to a teammate you trust to let theirs apply straight away; one that would replace yours still waits for you. Only you can retire someone else's correction.\n\n**Example:** tell the Executive *\"we've decided to push the EU launch to Q2 so we can finish SOC 2 first.\"* Afterwards, **Pulse → Decisions** shows that decision with its rationale. If it captured the wrong reason, edit it — future answers build on what's recorded here.\n\n**Just for yourself?** When you use Open Executive just for yourself, the heartbeat leaves out department check-ins and the \"Awaiting people\" list, and the count of active projects takes the department check-ins' place under **More detail**. The same projects appear on Home under **Your projects**.\n\n*Note: this memory is searchable across the system, so what's captured here informs future answers.*",
"mermaid": null,
"generated_at": "2026-10-19T16:00:00Z"
}
diff --git a/packages/ui/scripts/learning.test.mjs b/packages/ui/scripts/learning.test.mjs
index c32ffb40..596bf759 100644
--- a/packages/ui/scripts/learning.test.mjs
+++ b/packages/ui/scripts/learning.test.mjs
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { isoWeek, learningStats } from "../src/lib/learning.ts";
+import { DeferredForget, fixedMissIds, groupByKind, isoWeek, learningStats, toggleAll, unhelpfulLessonIds } from "../src/lib/learning.ts";
test("isoWeek matches Python's isocalendar, across a year end", () => {
assert.equal(isoWeek(new Date("2026-10-19T09:00:00Z")), "2026-W43");
@@ -30,3 +30,101 @@ test("a quiet week and no misses read as zero and nothing to check", () => {
assert.equal(stats.fellShort, 0);
assert.equal(stats.wouldGoRight, null);
});
+
+test("misses group by kind in a fixed order, and an empty kind is left out", () => {
+ const misses = [
+ { id: 1, kind: "product" },
+ { id: 2, kind: "company" },
+ { id: 3, kind: "product" },
+ ];
+ assert.deepEqual(
+ groupByKind(misses).map((g) => [g.kind, g.items.map((m) => m.id)]),
+ [["company", [2]], ["product", [1, 3]]],
+ );
+ assert.deepEqual(groupByKind([{ id: 4, kind: "company" }]).map((g) => g.kind), ["company"]);
+ assert.deepEqual(groupByKind([]), []);
+});
+
+test("the quick picks: misses that would go right today, lessons that aren't helping", () => {
+ assert.deepEqual(
+ fixedMissIds([
+ { id: 1, replay_state: "closed" },
+ { id: 2, replay_state: "open" },
+ { id: 3, replay_state: "evidence" },
+ { id: 4, replay_state: "closed" },
+ ]),
+ [1, 4],
+ );
+ const lesson = (id, fine_after, miss_after, retired_at = null) => ({ id, fine_after, miss_after, retired_at });
+ assert.deepEqual(
+ unhelpfulLessonIds([lesson(1, 1, 2), lesson(2, 2, 2), lesson(3, 0, 0), lesson(4, 0, 3, "2026-10-01T00:00:00Z")]),
+ [1],
+ );
+});
+
+test("select all adds the rest, and takes them all off once all are on", () => {
+ const some = toggleAll(new Set([1]), [1, 2, 3]);
+ assert.deepEqual([...some].sort(), [1, 2, 3]);
+ const none = toggleAll(new Set([1, 2, 3, 9]), [1, 2, 3]);
+ assert.deepEqual([...none], [9]);
+ assert.deepEqual([...toggleAll(new Set(), [])], []);
+});
+
+function recorder(fail = () => false) {
+ const sent = [];
+ const reports = [];
+ const queue = new DeferredForget(
+ async (item, keepalive) => {
+ sent.push([item, keepalive]);
+ if (fail(item)) throw new Error("no");
+ },
+ 6000,
+ );
+ const onSent = (items, failed) => reports.push([items, failed]);
+ return { queue, onSent, sent, reports };
+}
+
+const settle = () => new Promise((r) => setImmediate(r));
+
+test("a forget waits for its window, then sends each item once", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const { queue, onSent, sent, reports } = recorder();
+ queue.hold([1, 2], onSent);
+ assert.deepEqual(queue.waiting, [1, 2]);
+ t.mock.timers.tick(5999);
+ assert.deepEqual(sent, []);
+ t.mock.timers.tick(1);
+ await settle();
+ assert.deepEqual(sent, [[1, false], [2, false]]);
+ assert.deepEqual(reports, [[[1, 2], 0]]);
+ t.mock.timers.tick(10000);
+ await settle();
+ assert.equal(sent.length, 2);
+});
+
+test("undo takes the batch back and nothing is sent", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const { queue, onSent, sent } = recorder();
+ queue.hold([7], onSent);
+ assert.deepEqual(queue.undo(), [7]);
+ assert.deepEqual(queue.undo(), []);
+ t.mock.timers.tick(10000);
+ await settle();
+ assert.deepEqual(sent, []);
+});
+
+test("a second forget sends the first at once; a flush sends with keepalive", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const { queue, onSent, sent, reports } = recorder((item) => item === 2);
+ queue.hold([1, 2], onSent);
+ queue.hold([3], onSent);
+ await settle();
+ assert.deepEqual(sent, [[1, false], [2, false]]);
+ assert.deepEqual(reports, [[[1, 2], 1]]);
+ assert.deepEqual(queue.waiting, [3]);
+ await queue.flush({ keepalive: true });
+ assert.deepEqual(sent.at(-1), [3, true]);
+ t.mock.timers.tick(10000);
+ await settle();
+ assert.equal(sent.length, 3);
+});
diff --git a/packages/ui/src/components/memories/MemorySection.tsx b/packages/ui/src/components/memories/MemorySection.tsx
index a1316fc1..3d3af0e5 100644
--- a/packages/ui/src/components/memories/MemorySection.tsx
+++ b/packages/ui/src/components/memories/MemorySection.tsx
@@ -38,13 +38,15 @@ export default function MemoryList({ view }: { view: MemoryView }) {
const [historyAvailable, setHistoryAvailable] = useState(true);
const onHistoryAvailable = useCallback((available: boolean) => setHistoryAvailable(available), []);
+ // Learning lays out its own cards: its numbers, then the list.
+ if (view === "reflection") return <ReflectionTab />;
+
return (
<div className="rounded-2xl border border-line bg-surface-elevated px-4 sm:px-5 py-1">
{view === "decisions" && <DecisionsTab onCount={ignoreCount} />}
{view === "initiatives" && <InitiativesTab onCount={ignoreCount} />}
{view === "advice" && <AdviceTab onCount={ignoreCount} />}
{view === "corrections" && <CorrectionsTab onCount={ignoreCount} />}
- {view === "reflection" && <ReflectionTab />}
{view === "history" &&
(historyAvailable ? (
<HistoryTab onCount={ignoreCount} onAvailable={onHistoryAvailable} />
diff --git a/packages/ui/src/components/memories/ReflectionTab.tsx b/packages/ui/src/components/memories/ReflectionTab.tsx
index 2d4e6744..7e0e73f2 100644
--- a/packages/ui/src/components/memories/ReflectionTab.tsx
+++ b/packages/ui/src/components/memories/ReflectionTab.tsx
@@ -1,9 +1,11 @@
"use client";
import Link from "next/link";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useId, useRef, useState } from "react";
-import OverflowMenu from "@/components/ui/OverflowMenu";
+import Icon from "@/components/Icon";
+import Button from "@/components/ui/Button";
+import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";
import {
forgetReflectionLesson,
forgetReflectionMiss,
@@ -14,48 +16,85 @@ import {
type ReflectionState,
type ReflectionWeek,
} from "@/lib/api";
-import { learningStats } from "@/lib/learning";
-
-import { EmptyState, formatDate, formatRunAt } from "./shared";
-
-// Learning (the Reflection screen). At the top, how it learns: four steps and
-// this person's own numbers. After a chat goes quiet, the conversation
-// review grades each turn from the person's own words, the reply and the
-// signals the product recorded (a 👎, a stopped reply, a turn taken back, a
-// claim no tool backed, a failed tool). The misses land here with what the
-// person wanted instead, so the owner can see where the Executive falls
-// short in this workspace. Each person sees their own; the owner also the ones
-// from channels and group chats (never a teammate's own chat).
-// Below the misses, what it learned from them: one-line lessons in the
+import {
+ DeferredForget,
+ fixedMissIds,
+ groupByKind,
+ learningStats,
+ toggleAll,
+ unhelpfulLessonIds,
+ type MissKind,
+} from "@/lib/learning";
+
+import { EmptyState, STAT_VALUE_TONE, formatDate, formatRunAt, type StatTone } from "./shared";
+
+// Learning (the Reflection screen). At the top, this week's numbers, with how
+// it learns one tap away. After a chat goes quiet, the conversation review
+// grades each turn from the person's own words, the reply and the signals the
+// product recorded (a 👎, a stopped reply, a turn taken back, a claim no tool
+// backed, a failed tool). The misses land here with what the person wanted
+// instead, so the owner can see where the Executive falls short in this
+// workspace. Each person sees their own; the owner also the ones from
+// channels and group chats (never a teammate's own chat).
+// Beside the misses, what it learned from them: one-line lessons in the
// person's own words that reach later turns, with how those turns went.
// A lesson that doesn't help retires on its own; Forget retires it by hand.
// At night the Executive replays the misses with today's lessons, in a dry
// run nobody receives, and a judge says whether each would now go right:
-// that is the "would go right today" number, and the pill on each miss.
+// that is the "would go right today" number, and the note on each miss.
+// The list is long, so it is split by category, a row opens for its detail,
+// and several can be forgotten at once. Forgetting waits a few seconds for
+// Undo before it is sent, since a forgotten miss is deleted.
// Nothing here notifies anyone: it is a record, opened on purpose.
+type View = "misses" | "lessons";
+type Category = "all" | MissKind;
+
const EMPTY =
"Nothing yet. After a chat goes quiet, the Executive grades its own answers; the ones that fell short show up here.";
-const KIND_LABEL: Record<ReflectionMiss["kind"], string> = {
+const KIND_LABEL: Record<MissKind, string> = {
company: "Something to learn",
product: "Couldn't do it",
};
-const KIND_PILL: Record<ReflectionMiss["kind"], string> = {
- company: "bg-amber-500/15 text-amber-500 border-amber-500/30",
- product: "bg-sky-500/15 text-sky-500 border-sky-500/30",
+const RETIRED_LABEL: Record<NonNullable<ReflectionLesson["retired_reason"]>, string> = {
+ unhelpful: "stopped: the chats it reached went worse",
+ forgotten: "stopped: forgotten",
+ room: "stopped: made room for newer ones",
+ replay: "stopped: replaying showed it didn't help",
};
-/** "W42" from "2026-W42". */
-function weekLabel(week: string): string {
- const i = week.indexOf("-W");
- return i >= 0 ? `W${week.slice(i + 2)}` : week;
+/** How long a forget waits for Undo before it is sent. */
+const UNDO_MS = 6000;
+
+/** One forgotten row, waiting for Undo. */
+interface Forget {
+ view: View;
+ id: number;
+}
+
+const keyOf = (f: Forget) => `${f.view === "misses" ? "m" : "l"}:${f.id}`;
+
+function sendForget(f: Forget, keepalive: boolean): Promise<void> {
+ return f.view === "misses" ? forgetReflectionMiss(f.id, { keepalive }) : forgetReflectionLesson(f.id, { keepalive });
}
export default function ReflectionTab() {
const [state, setState] = useState<ReflectionState | null | undefined>(undefined);
const [failed, setFailed] = useState(false);
+ const [view, setView] = useState<View>("misses");
+ const [category, setCategory] = useState<Category>("all");
+ const [selected, setSelected] = useState<Set<number>>(new Set());
+ const [open, setOpen] = useState<Set<number>>(new Set());
+ const [showRetired, setShowRetired] = useState(false);
+ // Forgotten here but not yet sent ("m:<id>" / "l:<id>"), and the toast.
+ const [hidden, setHidden] = useState<Set<string>>(new Set());
+ const [toast, setToast] = useState<string | null>(null);
+ const [queue] = useState(() => new DeferredForget<Forget>(sendForget, UNDO_MS));
+ // A forget sent after leaving the screen (unmount, page close) reports nothing.
+ const mounted = useRef(true);
+ const tabsId = useId();
const refresh = useCallback(async () => {
try {
@@ -70,117 +109,275 @@ export default function ReflectionTab() {
void refresh();
}, [refresh]);
- const handleForget = useCallback(
- async (miss: ReflectionMiss) => {
- if (!window.confirm(`Forget this one?\n\n${miss.message}`)) return;
- try {
- await forgetReflectionMiss(miss.id);
- } catch {
- window.alert("Failed to forget.");
- return;
- }
- void refresh();
- },
- [refresh],
- );
+ // Leaving the screen sends what is waiting rather than dropping it: on
+ // unmount, and when the tab closes or reloads (keepalive, since the page
+ // is going away and nothing will read the answer).
+ useEffect(() => {
+ mounted.current = true;
+ const onPageHide = () => void queue.flush({ keepalive: true });
+ window.addEventListener("pagehide", onPageHide);
+ return () => {
+ window.removeEventListener("pagehide", onPageHide);
+ mounted.current = false;
+ void queue.flush();
+ };
+ }, [queue]);
- const handleForgetLesson = useCallback(
- async (lesson: ReflectionLesson) => {
- if (!window.confirm(`Stop saying this?\n\n${lesson.text}`)) return;
- try {
- await forgetReflectionLesson(lesson.id);
- } catch {
- window.alert("Failed to forget.");
- return;
- }
- void refresh();
- },
- [refresh],
- );
+ const pick = useCallback((next: { view?: View; category?: Category }) => {
+ if (next.view !== undefined) setView(next.view);
+ if (next.category !== undefined) setCategory(next.category);
+ setSelected(new Set());
+ setOpen(new Set());
+ }, []);
- if (failed) return <EmptyState message="This is unavailable right now." />;
+ const forgetSelected = useCallback(() => {
+ if (selected.size === 0) return;
+ const items = [...selected].map((id) => ({ view, id }));
+ setHidden((h) => new Set([...h, ...items.map(keyOf)]));
+ setSelected(new Set());
+ const n = items.length;
+ setToast(view === "misses" ? `Forgot ${n}.` : `Stopped saying ${n === 1 ? "it" : n}.`);
+ queue.hold(items, (sent, failedSends) => {
+ if (!mounted.current) return;
+ // Drop the toast unless a newer forget is waiting, then reload.
+ setToast((t) => (queue.waiting.length ? t : null));
+ if (failedSends > 0) window.alert("Some of them couldn't be forgotten.");
+ void refresh().then(() => {
+ const done = new Set(sent.map(keyOf));
+ setHidden((h) => new Set([...h].filter((k) => !done.has(k))));
+ });
+ });
+ }, [queue, refresh, selected, view]);
+
+ const undo = useCallback(() => {
+ const back = new Set(queue.undo().map(keyOf));
+ setHidden((h) => new Set([...h].filter((k) => !back.has(k))));
+ setToast(null);
+ }, [queue]);
+
+ if (failed) return <Card><EmptyState message="This is unavailable right now." /></Card>;
if (state === undefined) return <div className="text-fg-muted text-[15px] py-4">Loading…</div>;
if (state === null) {
return (
- <EmptyState message="There is nothing for you here. It's kept for people on the People list, once they're signed in." />
+ <Card>
+ <EmptyState message="There is nothing for you here. It's kept for people on the People list, once they're signed in." />
+ </Card>
);
}
- const { misses, lessons, weeks, replay, sees_everyone: seesEveryone } = state;
- const company = misses.filter((m) => m.kind === "company");
- const product = misses.filter((m) => m.kind === "product");
+ const { weeks, replay, sees_everyone: seesEveryone } = state;
+ const misses = state.misses.filter((m) => !hidden.has(`m:${m.id}`));
+ const lessons = state.lessons.filter((l) => !hidden.has(`l:${l.id}`));
const live = lessons.filter((l) => l.retired_at === null);
const retired = lessons.filter((l) => l.retired_at !== null);
+ const kinds = groupByKind(misses);
+ // A chip whose misses are all gone (forgotten, or a refresh) falls back to
+ // All, so the other kind stays in reach.
+ const cat: Category = category !== "all" && !kinds.some((g) => g.kind === category) ? "all" : category;
+ const shownMisses = cat === "all" ? misses : misses.filter((m) => m.kind === cat);
+ const shownIds = view === "misses" ? shownMisses.map((m) => m.id) : live.map((l) => l.id);
+ const quick = view === "misses" ? fixedMissIds(shownMisses) : unhelpfulLessonIds(live);
+ const allSelected = shownIds.length > 0 && shownIds.every((id) => selected.has(id));
+ const toggle = (id: number) =>
+ setSelected((s) => {
+ const next = new Set(s);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ const toggleOpen = (id: number) =>
+ setOpen((s) => {
+ const next = new Set(s);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
return (
- <div className="space-y-4 py-3">
- <HowItLearns weeks={weeks} liveLessons={live.length} replay={replay} />
- <Trend weeks={weeks} />
- {misses.length === 0 ? (
- <EmptyState message={EMPTY} />
- ) : (
- <p className="text-sm text-fg-muted">
- {seesEveryone ? "Your chats and the shared ones, newest first." : "Your chats, newest first."} Each one links to the
- conversation. Forget one to drop it from this record.
- </p>
- )}
- {company.length > 0 && (
- <Group
- title="Something to learn"
- blurb="A term, a fact, a preference or the right specialist would have fixed these."
- misses={company}
- seesEveryone={seesEveryone}
- onForget={handleForget}
- />
- )}
- {product.length > 0 && (
- <Group
- title="Couldn't do it"
- blurb="A tool failed, or it was asked for something it can't do yet."
- misses={product}
- seesEveryone={seesEveryone}
- onForget={handleForget}
+ <div className="space-y-5">
+ <ThisWeek weeks={weeks} liveLessons={live.length} replay={replay} />
+
+ <div className="space-y-3">
+ <SectionTabs<View>
+ label="Show"
+ idBase={tabsId}
+ active={view}
+ onChange={(v) => pick({ view: v, category: "all" })}
+ tabs={[
+ { id: "misses", label: "What fell short", count: misses.length },
+ { id: "lessons", label: "What it learned", count: live.length },
+ ]}
/>
- )}
- {lessons.length > 0 && (
- <section>
- <div className="text-base font-semibold text-fg">What it learned</div>
- <p className="text-sm text-fg-muted mb-1">
- One line each, in your own words, from the misses above. It reads them on your later chats about
- the same thing, and keeps count of how those went. One that doesn&apos;t help stops on its own.
- {seesEveryone && " A lesson you taught it in a channel or group chat reaches everyone's chats."}
- </p>
- <div className="divide-y divide-line">
- {live.map((l) => (
- <LessonRow key={l.id} lesson={l} seesEveryone={seesEveryone} onForget={() => handleForgetLesson(l)} />
+ {view === "misses" && kinds.length > 1 && (
+ <div role="group" aria-label="Category" className="flex flex-wrap gap-2">
+ {(["all", ...kinds.map((g) => g.kind)] as Category[]).map((c) => (
+ <button
+ key={c}
+ type="button"
+ onClick={() => pick({ category: c })}
+ aria-pressed={cat === c}
+ className={`h-10 text-sm px-3.5 rounded-xl border transition-colors ${
+ cat === c
+ ? "bg-accent/10 text-accent border-accent/30"
+ : "bg-surface-overlay/40 text-fg-muted border-line hover:text-fg"
+ }`}
+ >
+ {c === "all" ? "All" : KIND_LABEL[c]}
+ </button>
))}
</div>
- {retired.length > 0 && (
- <details className="mt-2">
- <summary className="cursor-pointer text-sm text-fg-muted min-h-[40px] flex items-center">
- Stopped saying it ({retired.length})
- </summary>
- <div className="divide-y divide-line">
- {retired.map((l) => (
- <LessonRow key={l.id} lesson={l} seesEveryone={seesEveryone} />
+ )}
+ </div>
+
+ <Card {...sectionPanelProps(tabsId, view)}>
+ {shownIds.length === 0 && (view === "misses" || retired.length === 0) ? (
+ <EmptyState message={view === "misses" ? EMPTY : "No lessons yet. They come from the misses."} />
+ ) : (
+ <>
+ {shownIds.length > 0 && (
+ <div className="flex items-center justify-between gap-3 py-1.5 border-b border-line">
+ <label className="flex items-center gap-3 min-h-[44px] text-sm text-fg-muted cursor-pointer">
+ <input
+ type="checkbox"
+ checked={allSelected}
+ onChange={() => setSelected((s) => toggleAll(s, shownIds))}
+ className="h-[18px] w-[18px] accent-accent-strong"
+ />
+ Select all
+ </label>
+ {quick.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setSelected(new Set(quick))}
+ className="min-h-[40px] text-sm font-semibold text-accent hover:underline"
+ >
+ {view === "misses"
+ ? `Select the ${quick.length} that ${quick.length === 1 ? "is" : "are"} fixed`
+ : `Select the ${quick.length} not helping`}
+ </button>
+ )}
+ </div>
+ )}
+ {view === "misses" &&
+ (cat === "all" ? kinds : [{ kind: cat, items: shownMisses }]).map((g) => (
+ <div key={g.kind} className="pb-2">
+ {cat === "all" && <GroupHeading title={KIND_LABEL[g.kind]} count={g.items.length} />}
+ {g.items.map((m, i) => (
+ <MissRow
+ key={m.id}
+ miss={m}
+ first={i === 0}
+ seesEveryone={seesEveryone}
+ selected={selected.has(m.id)}
+ onToggle={() => toggle(m.id)}
+ expanded={open.has(m.id)}
+ onExpand={() => toggleOpen(m.id)}
+ />
+ ))}
+ </div>
+ ))}
+ {view === "lessons" && (
+ <div className="pb-2">
+ {live.length > 0 && seesEveryone && (
+ <p className="text-sm text-fg-muted pt-3">
+ A lesson you taught it in a channel or group chat reaches everyone&apos;s chats.
+ </p>
+ )}
+ {live.map((l, i) => (
+ <LessonRow
+ key={l.id}
+ lesson={l}
+ first={i === 0}
+ seesEveryone={seesEveryone}
+ selected={selected.has(l.id)}
+ onToggle={() => toggle(l.id)}
+ expanded={open.has(l.id)}
+ onExpand={() => toggleOpen(l.id)}
+ />
))}
+ {retired.length > 0 && (
+ <>
+ <button
+ type="button"
+ onClick={() => setShowRetired((v) => !v)}
+ aria-expanded={showRetired}
+ className="mt-1 min-h-[44px] text-sm text-fg-muted hover:text-fg"
+ >
+ {showRetired ? "Hide stopped lessons" : `Show ${retired.length} stopped`}
+ </button>
+ {showRetired && (
+ <div>
+ <GroupHeading title="Stopped saying it" count={retired.length} />
+ {retired.map((l, i) => (
+ <LessonRow
+ key={l.id}
+ lesson={l}
+ first={i === 0}
+ seesEveryone={seesEveryone}
+ expanded={open.has(l.id)}
+ onExpand={() => toggleOpen(l.id)}
+ />
+ ))}
+ </div>
+ )}
+ </>
+ )}
</div>
- </details>
+ )}
+ </>
+ )}
+ </Card>
+
+ {(selected.size > 0 || toast) && (
+ <div className="sticky bottom-4 z-10 flex flex-col items-start gap-2">
+ {toast && (
+ <div
+ role="status"
+ className="flex max-w-full items-center gap-2 rounded-2xl border border-line-strong bg-surface-overlay py-1.5 pl-5 pr-1.5 shadow-lg"
+ >
+ <span className="text-sm text-fg">{toast}</span>
+ <Button variant="ghost" size="sm" className="!text-accent" onClick={undo}>
+ Undo
+ </Button>
+ </div>
)}
- </section>
+ {selected.size > 0 && (
+ <div
+ role="region"
+ aria-label="Selection"
+ className="flex w-full items-center gap-2 rounded-2xl border border-line-strong bg-surface-overlay py-2 pl-5 pr-2 shadow-lg"
+ >
+ <span className="flex-1 text-[15px] font-semibold text-fg">{selected.size} selected</span>
+ <Button variant="ghost" size="sm" onClick={() => setSelected(new Set())}>
+ Cancel
+ </Button>
+ <Button variant="danger" size="sm" onClick={forgetSelected}>
+ {view === "misses" ? `Forget ${selected.size}` : `Stop saying ${selected.size}`}
+ </Button>
+ </div>
+ )}
+ </div>
)}
</div>
);
}
-const RETIRED_LABEL: Record<NonNullable<ReflectionLesson["retired_reason"]>, string> = {
- unhelpful: "stopped: the chats it reached went worse, not better",
- forgotten: "stopped: forgotten",
- room: "stopped: made room for newer ones",
- replay: "stopped: replaying the chats showed it didn't help",
-};
+function Card({ children, ...rest }: { children: React.ReactNode } & React.HTMLAttributes<HTMLDivElement>) {
+ return (
+ <div {...rest} className="rounded-2xl border border-line bg-surface-elevated px-4 sm:px-5 py-1">
+ {children}
+ </div>
+ );
+}
-const HIDE_KEY = "oe.learning.howItLearns.hidden";
+function GroupHeading({ title, count }: { title: string; count: number }) {
+ return (
+ <h3 className="flex items-baseline gap-2 pt-5 pb-1 text-base font-semibold text-fg">
+ {title}
+ <span className="text-sm font-normal text-fg-subtle tabular-nums">{count}</span>
+ </h3>
+ );
+}
const STEPS: { title: string; body: string; when?: string }[] = [
{
@@ -204,25 +401,8 @@ const STEPS: { title: string; body: string; when?: string }[] = [
},
];
-function readHidden(): boolean {
- try {
- return window.localStorage.getItem(HIDE_KEY) === "1";
- } catch {
- return false;
- }
-}
-
-function writeHidden(hidden: boolean): void {
- try {
- if (hidden) window.localStorage.setItem(HIDE_KEY, "1");
- else window.localStorage.removeItem(HIDE_KEY);
- } catch {
- // Not kept: the card shows again next time.
- }
-}
-
-/** The four steps of how it learns, with this person's own numbers under them. */
-function HowItLearns({
+/** This week's numbers, with the four steps of how it learns behind a link. */
+function ThisWeek({
weeks,
liveLessons,
replay,
@@ -231,99 +411,80 @@ function HowItLearns({
liveLessons: number;
replay: ReflectionReplay;
}) {
- // Mounted only once the screen's data has loaded in the browser, so the
- // stored choice can be read up front.
- const [hidden, setHidden] = useState(readHidden);
- const toggle = () => {
- writeHidden(!hidden);
- setHidden(!hidden);
- };
+ const [how, setHow] = useState(false);
const stats = learningStats(weeks, liveLessons, replay);
const lastRun = replay.last_run_at ? formatRunAt(replay.last_run_at).absolute : null;
-
- if (hidden) {
- return (
- <button
- type="button"
- onClick={toggle}
- className="min-h-[44px] text-sm font-semibold text-accent hover:underline"
- >
- How it learns
- </button>
- );
- }
+ const numbers: { value: string; label: string; tone: StatTone }[] = [
+ { value: String(stats.checked), label: "answers checked", tone: "default" },
+ { value: String(stats.fellShort), label: "fell short", tone: stats.fellShort > 0 ? "amber" : "default" },
+ { value: String(stats.lessons), label: stats.lessons === 1 ? "lesson kept" : "lessons kept", tone: "accent" },
+ {
+ value: stats.wouldGoRight ? `${stats.wouldGoRight.pass} of ${stats.wouldGoRight.of}` : "–",
+ label: stats.wouldGoRight ? "would go right today" : "nothing to recheck yet",
+ tone: stats.wouldGoRight && stats.wouldGoRight.pass > 0 ? "emerald" : "default",
+ },
+ ];
return (
- <section aria-labelledby="how-it-learns" className="rounded-2xl border border-line bg-surface-panel p-4 sm:p-5">
- <div className="flex items-baseline justify-between gap-3 mb-4">
- <h2 id="how-it-learns" className="text-lg font-semibold text-fg">
- How it learns
+ <section aria-labelledby="learning-this-week" className="rounded-2xl border border-line bg-surface-elevated p-4 sm:p-6">
+ <div className="flex items-center justify-between gap-3 mb-3">
+ <h2 id="learning-this-week" className="text-lg font-semibold text-fg">
+ This week
</h2>
<button
type="button"
- onClick={toggle}
- className="min-h-[44px] px-1 text-sm font-semibold text-accent hover:underline"
+ onClick={() => setHow((v) => !v)}
+ aria-expanded={how}
+ className="inline-flex h-10 items-center gap-1 rounded-xl px-2 -mr-2 text-sm font-semibold text-accent hover:bg-surface-overlay transition-colors"
>
- Hide
+ How it learns
+ <Icon name="chevron-right" size="w-4 h-4" className={how ? "rotate-90" : ""} />
</button>
</div>
- <ol className="grid grid-cols-1 lg:grid-cols-4 gap-3">
- {STEPS.map((step, i) => (
- <li
- key={step.title}
- className="rounded-xl border border-line bg-surface p-4 grid grid-cols-[2.25rem_1fr] lg:block gap-x-3"
- >
- <div className="h-8 w-8 rounded-full bg-accent/15 text-accent font-bold flex items-center justify-center lg:mb-3">
- {i + 1}
- </div>
- <div>
- <div className="text-base font-semibold text-fg">{step.title}</div>
- <p className="text-sm text-fg-muted mt-1">{step.body}</p>
- {step.when && (
- <span className="inline-block mt-2 rounded-full bg-accent/15 px-2.5 py-0.5 text-xs font-semibold text-accent">
- {step.when}
- </span>
- )}
- </div>
- </li>
+ <dl className="grid grid-cols-2 sm:grid-cols-4 gap-4 sm:gap-6">
+ {numbers.map((n) => (
+ <div key={n.label} className="min-w-0 flex flex-col-reverse">
+ <dt className="text-sm text-fg-muted mt-1">{n.label}</dt>
+ <dd className={`text-2xl sm:text-3xl font-bold tabular-nums leading-tight ${STAT_VALUE_TONE[n.tone]}`}>
+ {n.value}
+ </dd>
+ </div>
))}
- </ol>
- <dl className="grid grid-cols-2 lg:grid-cols-4 gap-4 mt-4 border-t border-line pt-4">
- <Stat value={String(stats.checked)} label="answers checked this week" />
- <Stat value={String(stats.fellShort)} label="fell short" tone={stats.fellShort > 0 ? "amber" : undefined} />
- <Stat value={String(stats.lessons)} label={stats.lessons === 1 ? "lesson kept" : "lessons kept"} />
- <Stat
- value={stats.wouldGoRight ? `${stats.wouldGoRight.pass} of ${stats.wouldGoRight.of}` : "–"}
- label={stats.wouldGoRight ? "would go right today" : "nothing to recheck yet"}
- tone={stats.wouldGoRight && stats.wouldGoRight.pass > 0 ? "green" : undefined}
- />
</dl>
- <p className="text-sm text-fg-muted mt-3">
- Chats that read your mail are looked at for you alone.
- {lastRun ? ` Last checked ${lastRun}.` : " The first nightly check runs once something has gone wrong."}
- {replay.evidence > 0 &&
- ` ${replay.evidence} ${replay.evidence === 1 ? "depends" : "depend"} on what that day's calendar or inbox held, so ${replay.evidence === 1 ? "it is" : "they are"} kept as evidence only.`}
- </p>
+ {how && (
+ <div className="mt-5 border-t border-line pt-5">
+ <ol className="grid grid-cols-1 lg:grid-cols-4 gap-3">
+ {STEPS.map((step, i) => (
+ <li
+ key={step.title}
+ className="rounded-xl border border-line bg-surface p-4 grid grid-cols-[2.25rem_1fr] lg:block gap-x-3"
+ >
+ <div className="h-8 w-8 rounded-full bg-accent/15 text-accent font-bold flex items-center justify-center lg:mb-3">
+ {i + 1}
+ </div>
+ <div>
+ <div className="text-base font-semibold text-fg">{step.title}</div>
+ <p className="text-sm text-fg-muted mt-1">{step.body}</p>
+ {step.when && (
+ <span className="inline-block mt-2 rounded-full bg-accent/15 px-2.5 py-0.5 text-xs font-semibold text-accent">
+ {step.when}
+ </span>
+ )}
+ </div>
+ </li>
+ ))}
+ </ol>
+ <p className="text-sm text-fg-muted mt-3">
+ Chats that read your mail are looked at for you alone.
+ {lastRun ? ` Last checked ${lastRun}.` : " The first nightly check runs once something has gone wrong."}
+ {replay.evidence > 0 &&
+ ` ${replay.evidence} ${replay.evidence === 1 ? "depends" : "depend"} on what that day's calendar or inbox held, so ${replay.evidence === 1 ? "it is" : "they are"} kept as evidence only.`}
+ </p>
+ </div>
+ )}
</section>
);
}
-function Stat({ value, label, tone }: { value: string; label: string; tone?: "amber" | "green" }) {
- const color = tone === "amber" ? "text-amber-500" : tone === "green" ? "text-emerald-500" : "text-fg";
- return (
- <div>
- <dt className="sr-only">{label}</dt>
- <dd className={`text-2xl font-bold tabular-nums leading-tight ${color}`}>{value}</dd>
- <dd className="text-sm text-fg-muted">{label}</dd>
- </div>
- );
-}
-
-const REPLAY_PILL: Record<ReflectionMiss["replay_state"], string> = {
- open: "bg-surface-input/60 text-fg-muted",
- closed: "bg-emerald-500/15 text-emerald-500",
- evidence: "bg-surface-input/60 text-fg-muted",
-};
-
/** The miss's last replay: still wrong, would go right now, or evidence only. */
function replayLabel(miss: ReflectionMiss): string | null {
if (miss.replay_state === "closed" && miss.closed_at) return `Would go right today (since ${formatDate(miss.closed_at)})`;
@@ -332,170 +493,162 @@ function replayLabel(miss: ReflectionMiss): string | null {
return null;
}
-function LessonRow({
- lesson,
- seesEveryone,
- onForget,
+/** One selectable row: a checkbox, then the line and its meta, which open the detail. */
+function Row({
+ first,
+ title,
+ meta,
+ selected,
+ onToggle,
+ expanded,
+ onExpand,
+ children,
}: {
- lesson: ReflectionLesson;
- seesEveryone: boolean;
- onForget?: () => void;
+ first: boolean;
+ title: string;
+ meta: React.ReactNode;
+ selected?: boolean;
+ onToggle?: () => void;
+ expanded: boolean;
+ onExpand: () => void;
+ children: React.ReactNode;
}) {
- const reached = lesson.shown;
- const went =
- reached === 0
- ? "Not reached a chat yet"
- : `Reached ${reached} ${reached === 1 ? "chat" : "chats"}: ${lesson.fine_after} went fine, ${lesson.miss_after} fell short`;
return (
- <div className="py-3 flex gap-3">
- <div className="flex-1 min-w-0 space-y-1">
- <div className="text-[15px] text-fg">{lesson.text}</div>
- <div className="flex flex-wrap items-center gap-2 text-xs text-fg-muted">
- <span>{formatDate(lesson.created_at)}</span>
- {seesEveryone && lesson.person_name && <span>· {lesson.person_name}</span>}
- <span>· {went}</span>
- {seesEveryone && lesson.shared && (
- <span className="rounded-full bg-surface-input/60 px-2 py-0.5">reaches everyone</span>
- )}
- {lesson.retired_reason && (
- <span className="rounded-full bg-surface-input/60 px-2 py-0.5">{RETIRED_LABEL[lesson.retired_reason]}</span>
- )}
- </div>
- <div className="text-sm text-fg-muted" title={lesson.quote}>
- <span className="font-medium">From: </span>&ldquo;{lesson.quote}&rdquo;
- </div>
+ <div className={first ? "" : "border-t border-line"}>
+ <div className="flex items-start gap-3">
+ {onToggle ? (
+ <label className="flex min-h-[44px] flex-none cursor-pointer items-start pt-[15px]">
+ <input
+ type="checkbox"
+ checked={!!selected}
+ onChange={onToggle}
+ aria-label={`Select: ${title}`}
+ className="h-[18px] w-[18px] accent-accent-strong"
+ />
+ </label>
+ ) : (
+ <span className="w-[18px] flex-none" />
+ )}
+ <button
+ type="button"
+ onClick={onExpand}
+ aria-expanded={expanded}
+ className="flex min-w-0 flex-1 flex-col gap-1 py-3.5 text-left"
+ >
+ <span className="text-[15px] font-medium leading-snug text-fg">{title}</span>
+ <span className="text-sm text-fg-muted">{meta}</span>
+ </button>
</div>
- {onForget && (
- <OverflowMenu label="Options for this lesson" items={[{ label: "Forget", onSelect: onForget, danger: true }]} />
- )}
+ {expanded && <div className="ml-[30px] -mt-1 pb-3.5 space-y-1 text-sm text-fg-muted">{children}</div>}
</div>
);
}
-/** Graded turns and misses by week, oldest left, with the share as a bar. */
-function Trend({ weeks }: { weeks: ReflectionWeek[] }) {
- if (weeks.length === 0) return null;
- const ordered = [...weeks].reverse().slice(-12);
- const graded = ordered.reduce((n, w) => n + w.graded, 0);
- const misses = ordered.reduce((n, w) => n + w.misses, 0);
- const share = graded ? Math.round((misses / graded) * 100) : 0;
- return (
- <section
- aria-label="Misses by week"
- className="rounded-xl border border-line bg-surface px-4 py-3 flex flex-col sm:flex-row sm:items-center gap-3"
- >
- <div className="min-w-0 sm:w-56">
- <div className="text-2xl font-bold tabular-nums text-fg leading-tight">
- {misses} <span className="text-base font-semibold text-fg-muted">of {graded}</span>
- </div>
- <div className="text-sm text-fg-muted">
- turns fell short over {ordered.length === 1 ? "the last week" : `the last ${ordered.length} weeks`} ({share}%)
- </div>
- </div>
- <ol className="flex items-end gap-1.5 h-14 flex-1" aria-hidden="true">
- {ordered.map((w) => {
- const pct = w.graded ? Math.round((w.misses / w.graded) * 100) : 0;
- return (
- <li
- key={w.week}
- title={`${weekLabel(w.week)}: ${w.misses} of ${w.graded}`}
- className="flex-1 flex flex-col items-center justify-end gap-1 min-w-0"
- >
- <div
- className="w-full max-w-6 rounded-t bg-amber-500/60"
- style={{ height: `${Math.max(4, pct)}%` }}
- />
- <span className="text-[10px] text-fg-muted tabular-nums truncate">{weekLabel(w.week)}</span>
- </li>
- );
- })}
- </ol>
- </section>
- );
-}
-
-function Group({
- title,
- blurb,
- misses,
+function MissRow({
+ miss,
+ first,
seesEveryone,
- onForget,
+ selected,
+ onToggle,
+ expanded,
+ onExpand,
}: {
- title: string;
- blurb: string;
- misses: ReflectionMiss[];
+ miss: ReflectionMiss;
+ first: boolean;
seesEveryone: boolean;
- onForget: (miss: ReflectionMiss) => void;
+ selected: boolean;
+ onToggle: () => void;
+ expanded: boolean;
+ onExpand: () => void;
}) {
+ const replay = replayLabel(miss);
return (
- <section>
- <div className="text-base font-semibold text-fg">{title}</div>
- <p className="text-sm text-fg-muted mb-1">{blurb}</p>
- <div className="divide-y divide-line">
- {misses.map((m) => (
- <MissRow key={m.id} miss={m} seesEveryone={seesEveryone} onForget={() => onForget(m)} />
- ))}
- </div>
- </section>
+ <Row
+ first={first}
+ title={miss.message}
+ selected={selected}
+ onToggle={onToggle}
+ expanded={expanded}
+ onExpand={onExpand}
+ meta={
+ <>
+ {formatDate(miss.created_at)}
+ {seesEveryone && miss.person_name && ` · ${miss.person_name}`}
+ {miss.replay_state === "closed" && <span className="text-emerald-500"> · would go right today</span>}
+ </>
+ }
+ >
+ <p>
+ <span className="font-medium">It said: </span>
+ {miss.reply}
+ </p>
+ {miss.wanted && (
+ <p className="text-fg">
+ <span className="font-medium text-fg-muted">They wanted: </span>
+ {miss.wanted}
+ </p>
+ )}
+ {(miss.signals.length > 0 || replay) && (
+ <p title={miss.replay_notes || undefined}>{[...miss.signals, ...(replay ? [replay] : [])].join(" · ")}</p>
+ )}
+ <Link
+ href={`/?session=${encodeURIComponent(miss.session_id)}`}
+ className="inline-flex min-h-[40px] items-center font-semibold text-accent hover:underline"
+ >
+ See the conversation
+ </Link>
+ </Row>
);
}
-function MissRow({
- miss,
+function LessonRow({
+ lesson,
+ first,
seesEveryone,
- onForget,
+ selected,
+ onToggle,
+ expanded,
+ onExpand,
}: {
- miss: ReflectionMiss;
+ lesson: ReflectionLesson;
+ first: boolean;
seesEveryone: boolean;
- onForget: () => void;
+ selected?: boolean;
+ onToggle?: () => void;
+ expanded: boolean;
+ onExpand: () => void;
}) {
+ const reached = lesson.shown;
+ const went =
+ reached === 0
+ ? "not reached a chat yet"
+ : `reached ${reached} ${reached === 1 ? "chat" : "chats"}: ${lesson.fine_after} went fine, ${lesson.miss_after} fell short`;
return (
- <div className="py-3 flex gap-3">
- <div className="flex-1 min-w-0 space-y-1.5">
- <div className="flex flex-wrap items-center gap-2 text-xs text-fg-muted">
- <span
- className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-semibold ${KIND_PILL[miss.kind]}`}
- >
- {KIND_LABEL[miss.kind]}
- </span>
- <span>{formatDate(miss.created_at)}</span>
- {seesEveryone && miss.person_name && <span>· {miss.person_name}</span>}
- {miss.signals.map((s) => (
- <span key={s} className="rounded-full bg-surface-input/60 px-2 py-0.5">
- {s}
- </span>
- ))}
- {replayLabel(miss) && (
- <span
- className={`rounded-full px-2 py-0.5 ${REPLAY_PILL[miss.replay_state]}`}
- title={miss.replay_notes || undefined}
- >
- {replayLabel(miss)}
- </span>
- )}
- </div>
- <div className="text-[15px] text-fg">
- <span className="text-fg-muted">They asked: </span>
- {miss.message}
- </div>
- <div className="text-sm text-fg-muted line-clamp-2" title={miss.reply}>
- <span className="font-medium">It said: </span>
- {miss.reply}
- </div>
- {miss.wanted && (
- <div className="text-[15px] text-fg">
- <span className="text-fg-muted">They wanted: </span>
- {miss.wanted}
- </div>
- )}
- <Link
- href={`/?session=${encodeURIComponent(miss.session_id)}`}
- className="inline-flex min-h-[40px] items-center text-sm font-medium text-accent hover:underline"
- >
- See the conversation
- </Link>
- </div>
- <OverflowMenu label="Options for this miss" items={[{ label: "Forget", onSelect: onForget, danger: true }]} />
- </div>
+ <Row
+ first={first}
+ title={lesson.text}
+ selected={selected}
+ onToggle={onToggle}
+ expanded={expanded}
+ onExpand={onExpand}
+ meta={
+ <>
+ {formatDate(lesson.created_at)}
+ {seesEveryone && lesson.person_name && ` · ${lesson.person_name}`}
+ {` · ${lesson.retired_reason ? RETIRED_LABEL[lesson.retired_reason] : went}`}
+ {seesEveryone && lesson.shared && " · reaches everyone"}
+ </>
+ }
+ >
+ <p title={lesson.quote}>
+ <span className="font-medium">From: </span>&ldquo;{lesson.quote}&rdquo;
+ </p>
+ <Link
+ href={`/?session=${encodeURIComponent(lesson.session_id)}`}
+ className="inline-flex min-h-[40px] items-center font-semibold text-accent hover:underline"
+ >
+ See the conversation
+ </Link>
+ </Row>
);
}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index eabe1d73..3dc1da51 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -2346,13 +2346,21 @@ export async function getReflection(signal?: AbortSignal): Promise<ReflectionSta
return res.json();
}
-export async function forgetReflectionMiss(id: number): Promise<void> {
- const res = await fetch(`${API_BASE}/memories/reflection/misses/${id}`, { method: "DELETE" });
+/** `keepalive` lets the request finish while the page is closing. */
+export async function forgetReflectionMiss(id: number, opts: { keepalive?: boolean } = {}): Promise<void> {
+ const res = await fetch(`${API_BASE}/memories/reflection/misses/${id}`, {
+ method: "DELETE",
+ keepalive: opts.keepalive,
+ });
if (!res.ok) throw await delegationError(res, "Couldn't forget it.");
}
-export async function forgetReflectionLesson(id: number): Promise<void> {
- const res = await fetch(`${API_BASE}/memories/reflection/lessons/${id}`, { method: "DELETE" });
+/** `keepalive` lets the request finish while the page is closing. */
+export async function forgetReflectionLesson(id: number, opts: { keepalive?: boolean } = {}): Promise<void> {
+ const res = await fetch(`${API_BASE}/memories/reflection/lessons/${id}`, {
+ method: "DELETE",
+ keepalive: opts.keepalive,
+ });
if (!res.ok) throw await delegationError(res, "Couldn't forget it.");
}
diff --git a/packages/ui/src/lib/learning.ts b/packages/ui/src/lib/learning.ts
index 2c2d1d54..60f028b3 100644
--- a/packages/ui/src/lib/learning.ts
+++ b/packages/ui/src/lib/learning.ts
@@ -43,3 +43,92 @@ export function learningStats(
wouldGoRight: replay.misses > 0 ? { pass: replay.would_pass, of: replay.misses } : null,
};
}
+
+// --- The Learning list: categories, quick picks ------------------------------
+
+/** What `memory/chat_review` says would have fixed a miss. */
+export type MissKind = "company" | "product";
+
+export const MISS_KINDS: MissKind[] = ["company", "product"];
+
+/** The two kinds in order, each with its misses, leaving out an empty one. */
+export function groupByKind<T extends { kind: MissKind }>(misses: T[]): { kind: MissKind; items: T[] }[] {
+ return MISS_KINDS.map((kind) => ({ kind, items: misses.filter((m) => m.kind === kind) })).filter(
+ (g) => g.items.length > 0,
+ );
+}
+
+/** The misses whose last nightly replay went right: safe to clear. */
+export function fixedMissIds(misses: { id: number; replay_state: string }[]): number[] {
+ return misses.filter((m) => m.replay_state === "closed").map((m) => m.id);
+}
+
+/** Live lessons whose chats so far went worse more often than fine. The
+ * review retires one on its own once it has reached enough chats; these are
+ * the ones heading that way. */
+export function unhelpfulLessonIds(
+ lessons: { id: number; retired_at: string | null; fine_after: number; miss_after: number }[],
+): number[] {
+ return lessons.filter((l) => l.retired_at === null && l.miss_after > l.fine_after).map((l) => l.id);
+}
+
+/** Every id in `ids` selected, or, when they all already are, none of them. */
+export function toggleAll(selected: ReadonlySet<number>, ids: number[]): Set<number> {
+ const next = new Set(selected);
+ const all = ids.length > 0 && ids.every((id) => next.has(id));
+ for (const id of ids) {
+ if (all) next.delete(id);
+ else next.add(id);
+ }
+ return next;
+}
+
+/**
+ * A forget that waits for Undo. `hold` keeps the items for `delayMs`, then
+ * sends each and tells `onSent` how many failed; a second `hold` sends the
+ * first batch straight away; `undo` takes the batch back unsent; `flush`
+ * sends it now (unmount, page close).
+ */
+export class DeferredForget<T> {
+ private batch: {
+ items: T[];
+ onSent: (items: T[], failed: number) => void;
+ timer: ReturnType<typeof setTimeout>;
+ } | null = null;
+ private readonly send: (item: T, keepalive: boolean) => Promise<unknown>;
+ private readonly delayMs: number;
+ constructor(send: (item: T, keepalive: boolean) => Promise<unknown>, delayMs: number) {
+ this.send = send;
+ this.delayMs = delayMs;
+ }
+
+ get waiting(): T[] {
+ return this.batch ? [...this.batch.items] : [];
+ }
+
+ hold(items: T[], onSent: (items: T[], failed: number) => void = () => {}): void {
+ void this.flush();
+ if (items.length === 0) return;
+ this.batch = { items, onSent, timer: setTimeout(() => void this.flush(), this.delayMs) };
+ }
+
+ /** The batch taken back, or [] when nothing was waiting. */
+ undo(): T[] {
+ const b = this.take();
+ return b ? b.items : [];
+ }
+
+ async flush({ keepalive = false }: { keepalive?: boolean } = {}): Promise<void> {
+ const b = this.take();
+ if (!b) return;
+ const results = await Promise.allSettled(b.items.map((item) => this.send(item, keepalive)));
+ b.onSent(b.items, results.filter((r) => r.status === "rejected").length);
+ }
+
+ private take() {
+ const b = this.batch;
+ if (b) clearTimeout(b.timer);
+ this.batch = null;
+ return b;
+ }
+}