Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Lessons UI: Settings switch, Memory list and task activity lines (#257)
Oleksandr Ivanchenko42a197e41386
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 269d474f..c87c1bf0 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -343,6 +343,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({};// Mission board: shown in the sidebar only when the server has it switched on.const [missionBoard, setMissionBoard] = useState(false);+ // A task to open on the board once it shows (from a lesson on a bot's Memory tab).+ const [pendingTaskId, setPendingTaskId] = useState<string | null>(null);const [awayCount, setAwayCount] = useState(0);const awaySinceRef = useRef<string | null>(null);const awayTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);@@ -2952,6 +2954,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (c.kwantId && c.threadId) return openThread(c.kwantId, c.threadId);if (!openTarget({ channel_id: c.channelId, kwant_id: c.kwantId })) pushToast('That chat no longer exists.');}}+ openTaskId={pendingTaskId}+ onOpenedTaskId={() => setPendingTaskId(null)}/>);const loose = <LooseEndsPage onOpenChat={openThread} />;@@ -3217,6 +3221,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({initialTab={editingTab}pendingSkills={editingKwant ? pendingSkillCounts[editingKwant.id] ?? 0 : 0}onClose={() => setEditingKwant(null)}+ onOpenTask={+ missionBoard+ ? (id) => {+ setEditingKwant(null);+ setPendingTaskId(id);+ showPage('board');+ }+ : undefined+ }onSubmit={(data) => (editingKwant ? handleUpdateAgent(editingKwant, data) : undefined)}onRequestDelete={editingKwant ? () => setDeletingKwant(editingKwant) : undefined}onApprovalsChanged={refreshRoster}diff --git a/frontend/src/components/MemoryPanel.tsx b/frontend/src/components/MemoryPanel.tsxindex 4795d903..5a1f2f44 100644--- a/frontend/src/components/MemoryPanel.tsx+++ b/frontend/src/components/MemoryPanel.tsx@@ -5,6 +5,7 @@ import { Bot, Check, Loader2, Pencil, Pin, PinOff, Plus, RefreshCw, Trash2, Userimport { MAX_MEMORIES, MAX_MEMORY, MAX_PINNED, Memory, continuityApi, formatWhen, memoriesForDisplay, onContinuity } from '../continuity';import { playSfx } from '../audio/chiptune';import { editorProps } from '../escape';+import { LessonLine, missionsApi } from '../missions';const smallBtn ='inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';@@ -166,13 +167,65 @@ export const MemoryRow: React.FC<{);};+/**+ * "Lessons from earlier work": the short lines a bot sees before similar work, from its last+ * 30 days. Read-only: no buttons, nothing to decide. Shows nothing when there are no lines.+ * `onOpenTask` makes the "View task" link; without it (the Mission board is off) the line is text only.+ */+export const LessonsGroup: React.FC<{ kwantName: string; lines: LessonLine[] | null; onOpenTask?: (taskId: string) => void }> = ({+ kwantName,+ lines,+ onOpenTask,+}) => {+ if (!lines || lines.length === 0) return null;+ return (+ <section aria-labelledby="lessons-h" className="space-y-1.5 pt-1" data-testid="lessons-group">+ <h3 id="lessons-h" className="text-xs font-medium text-zinc-400">+ Lessons from earlier work+ </h3>+ <p className="text-[10px] text-zinc-500 leading-relaxed">+ {kwantName} sees these before similar work. They come from the last 30 days and update on their own.+ </p>+ <ul className="space-y-1.5" aria-labelledby="lessons-h">+ {lines.map((l) => (+ <li key={l.key} className="p-2.5 rounded-lg border border-zinc-800 bg-zinc-950/60 space-y-1">+ <p className="text-xs text-zinc-300 break-words">{l.text}</p>+ {(l.count > 1 || (l.task_id && onOpenTask)) && (+ <div className="flex items-center gap-2 text-[11px]">+ {l.count > 1 && (+ <span className="px-1.5 py-0.5 rounded bg-zinc-800 text-zinc-300 tabular-nums" title={`Happened ${l.count} times`}>+ <span aria-hidden="true">×{l.count}</span>+ <span className="sr-only">{l.count} times</span>+ </span>+ )}+ {l.task_id && onOpenTask && (+ <button+ type="button"+ onClick={() => onOpenTask(l.task_id as string)}+ aria-label={`View task for this lesson: ${l.text.length > 70 ? `${l.text.slice(0, 70)}…` : l.text}`}+ className="rounded px-0.5 py-1.5 -my-1.5 text-sky-300 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ View task+ </button>+ )}+ </div>+ )}+ </li>+ ))}+ </ul>+ </section>+ );+};+/** A kwant's memory: what it keeps between chats. Refreshes live when the kwant changes it. */-export const MemoryPanel: React.FC<{ kwantId: string; kwantName: string }> = ({ kwantId, kwantName }) => {+export const MemoryPanel: React.FC<{ kwantId: string; kwantName: string; onOpenTask?: (taskId: string) => void }> = ({ kwantId, kwantName, onOpenTask }) => {const [memories, setMemories] = useState<Memory[] | null>(null);const [loadError, setLoadError] = useState<string | null>(null);const [draft, setDraft] = useState('');const [adding, setAdding] = useState(false);const [addError, setAddError] = useState<string | null>(null);+ // Read-only extra: stays null (and hidden) while loading, when off, on an older server or on any error.+ const [lessons, setLessons] = useState<LessonLine[] | null>(null);const reload = useCallback(async () => {try {@@ -183,6 +236,15 @@ export const MemoryPanel: React.FC<{ kwantId: string; kwantName: string }> = ({}}, [kwantId]);+ useEffect(() => {+ let live = true;+ setLessons(null);+ missionsApi.lessons(kwantId).then((l) => live && setLessons(l));+ return () => {+ live = false;+ };+ }, [kwantId]);+useEffect(() => {setMemories(null);reload();@@ -298,6 +360,7 @@ export const MemoryPanel: React.FC<{ kwantId: string; kwantName: string }> = ({</ul></>)}+ <LessonsGroup kwantName={kwantName} lines={lessons} onOpenTask={onOpenTask} /></div>);};diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsxindex dad7ebb5..fbd24ed2 100644--- a/frontend/src/components/MissionBoardView.tsx+++ b/frontend/src/components/MissionBoardView.tsx@@ -139,6 +139,7 @@ import {parseLimit,durationText,eventText,+ isQuietEvent,formatBytes,formatTokens,measuresView,@@ -2015,7 +2016,8 @@ export const TaskDetailBody: React.FC<{const actions = actionsFor(t).filter((a) => !(limitHit && a === 'unblock'));const chat = sourceChat(t);const [showAll, setShowAll] = useState(false);- const events = showAll ? detail.events : detail.events.slice(-12);+ const shownEvents = detail.events.filter((e) => !isQuietEvent(e));+ const events = showAll ? shownEvents : shownEvents.slice(-12);useEffect(() => {setAsking(null);@@ -2350,7 +2352,7 @@ export const TaskDetailBody: React.FC<{<RestoreSection task={t} api={restoreApi} titleOf={(id) => tasksById[id]?.title} now={now} onRestored={onRestored} onError={onRestoreError} />- {detail.events.length > 0 && (+ {shownEvents.length > 0 && (<section aria-labelledby="ev-h" className="space-y-1.5"><h4 id="ev-h" className="text-xs font-semibold text-zinc-200">Activity@@ -2362,9 +2364,9 @@ export const TaskDetailBody: React.FC<{</li>))}</ol>- {!showAll && detail.events.length > events.length && (+ {!showAll && shownEvents.length > events.length && (<button type="button" onClick={() => setShowAll(true)} className={`text-[11px] text-sky-300 hover:underline rounded ${focusRing}`}>- Show all {detail.events.length}+ Show all {shownEvents.length}</button>)}</section>@@ -2922,7 +2924,10 @@ export const MissionBoardPage: React.FC<{threadTitles?: Record<string, string>;/** Opens a Live bot's conversation. */onOpenPlace?: (place: ChatPlace) => void;-}> = ({ spaceId, names, avatars, onBack, onOpenChat, turns, teams = NO_TEAMS, rooms, threadTitles, onOpenPlace }) => {+ /** A task to open as soon as the board has loaded (a link from a bot's Memory tab). `onOpenedTaskId` tells the parent it was used. */+ openTaskId?: string | null;+ onOpenedTaskId?: () => void;+}> = ({ spaceId, names, avatars, onBack, onOpenChat, turns, teams = NO_TEAMS, rooms, threadTitles, onOpenPlace, openTaskId = null, onOpenedTaskId }) => {const [tasks, setTasks] = useState<Task[] | null>(null);const [missions, setMissions] = useState<Mission[]>([]);const [insights, setInsights] = useState<Insights | null>(null);@@ -3125,6 +3130,17 @@ export const MissionBoardPage: React.FC<{setOpenId(null);setDetail(null);};+ // A link from elsewhere (a lesson on a bot's Memory tab): open that task once the board has its list.+ useEffect(() => {+ if (!openTaskId || tasks === null) return;+ const t = tasks.find((x) => x.id === openTaskId);+ const c = t ? columnOfTask(t) : null;+ if (c) setColumn(c);+ openTask(openTaskId);+ onOpenedTaskId?.();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [openTaskId, tasks === null]);+// "Open goal" from a task's "Keep this true": the goal drawer takes the task panel's place.useEffect(() => {const onGoal = () => {diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex 92e1c1f8..d7a14405 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -87,6 +87,8 @@ interface NewAgentModalProps {onApprovalsChanged?: () => void;/** Whether this bot runs tools without asking: the bot's effective value, or the space's for a new bot. */approvalsOff?: boolean;+ /** Opens a task on the Mission board (from a lesson on the Memory tab). Absent when the board is off. */+ onOpenTask?: (taskId: string) => void;}type ProfileFields = { name: string; title: string; roleStyle: string; model: string; prompt: string; soul: string; profileId: string | null; failover: boolean; covers: string; avoids: string; sites: string };@@ -111,6 +113,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({pendingSkills = 0,onRequestDelete,onApprovalsChanged,+ onOpenTask,approvalsOff = false,}) => {const [tab, setTab] = useState<EditTab>('profile');@@ -359,7 +362,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({{isEdit && kwantId && tab === 'memory' && (<div role="tabpanel" id="agent-panel-memory" aria-labelledby="agent-tab-memory">- <MemoryPanel kwantId={kwantId} kwantName={initial?.name ?? 'This bot'} />+ <MemoryPanel kwantId={kwantId} kwantName={initial?.name ?? 'This bot'} onOpenTask={onOpenTask} /></div>)}{isEdit && kwantId && tab === 'skills' && (diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex e78d4342..11bdf712 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -43,6 +43,7 @@ import {formatTokens,limitError as tokenLimitError,parseAutofixSettings,+ parseLessonsSetting,parseDefaultLimits,parseLimit,parseMissionBoardSetting,@@ -311,6 +312,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t// null: this server has no Mission board, so the switch stays hidden.const [missionBoard, setMissionBoard] = useState<boolean | null>(null);const [autofix, setAutofix] = useState<AutofixSettings | null>(null);+ // Bots see what went wrong in their last 30 days before similar work. Null on a server without it.+ const [lessons, setLessons] = useState<'on' | 'off' | null>(null);// null on a server without the Swarm Auditor: the switch stays hidden and out of the saveconst [auditor, setAuditor] = useState<AuditorSettings | null>(null);// null on a server without Flight School: the switch stays hidden and out of the save@@ -383,6 +386,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tsetProactive(parseProactiveSettings(data));setMissionBoard(parseMissionBoardSetting(data));setAutofix(parseAutofixSettings(data));+ setLessons(parseLessonsSetting(data));setAuditor(parseAuditorSettings(data));setFlightSchool(parseFlightSchoolSettings(data));setDiscovery(parseDiscoverySettings(data));@@ -464,6 +468,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t...(proactive ?? {}),...(missionBoard !== null ? { mission_board: missionBoard } : {}),...(autofix !== null ? { autofix: autofix.autofix, recovery_budget_pct: autofix.recovery_budget_pct } : {}),+ ...(lessons !== null ? { lessons } : {}),...(flightSchool ?? {}),...(auditor ?? {}),...(discovery ?? {}),@@ -907,6 +912,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t)}</SwitchRow>)}+ {lessons !== null && (+ <SwitchRow+ id="lessons"+ label="Learn from earlier work"+ hint="Before similar work, each bot sees what went wrong in its last 30 days: failed checks, stalled turns, your send-backs and goals that stopped holding."+ checked={lessons === 'on'}+ onToggle={() => setLessons((v) => (v === 'on' ? 'off' : 'on'))}+ />+ )}{flightSchool !== null && <FlightSchoolSetting value={flightSchool} onChange={setFlightSchool} />}{auditor !== null && (<SwitchRowdiff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex 5973b171..438b9948 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -1459,6 +1459,9 @@ export const safeHttps = (url: string | null | undefined): string | null => {// ---------------------------------------------------------------------------// Activity+/** Events the Activity list leaves out: they have no text for the person. */+export const isQuietEvent = (e: Pick<TaskEvent, 'kind'>): boolean => e.kind === 'lessons_held_out';+/** One plain line per event for the activity list. */export function eventText(e: TaskEvent, names: Record<string, string> = {}): string {const who = actorName(e.actor, e.actor_name, names);@@ -1541,6 +1544,15 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): strreturn `No audit: ${str(d.reason) === 'daily_cap' ? 'today’s limit was reached' : str(d.reason) === 'no_challenger' ? 'no other bot could challenge it' : str(d.reason) === 'task_moved' ? 'the task moved on' : 'skipped'}`;case 'risk_resolved':return `${Who} ${str(d.resolution) === 'dismissed' ? 'dismissed' : 'resolved'} a risk`;+ case 'self_checked':+ return 'It ran its checks before hand-in';+ case 'lessons_shown': {+ const n = Array.isArray(d.keys) ? d.keys.length : null;+ return n ? `It started with ${n === 1 ? '1 lesson' : `${n} lessons`} from earlier work` : 'It started with lessons from earlier work';+ }+ case 'lessons_held_out':+ // A measurement holdout. It says nothing the person can use, so the Activity list leaves it out.+ return '';case 'class_changed':return `${Who} changed its kind of work${str(d.to) ? ` to ${str(d.to)}` : ''}`;default:@@ -1644,6 +1656,55 @@ export function parseMissionBoardSetting(data: unknown): boolean | null {return typeof v === 'boolean' ? v : null;}+/** `lessons` from GET /api/settings: whether bots see what went wrong in their last 30 days. Null on a server without it. */+export function parseLessonsSetting(data: unknown): 'on' | 'off' | null {+ if (!data || typeof data !== 'object') return null;+ const v = (data as Record<string, unknown>).lessons;+ return v === 'on' || v === 'off' ? v : null;+}++export type LessonSource = 'check' | 'stall' | 'denied' | 'error' | 'review' | 'goal';++/** One line of "Lessons from earlier work": what the bot is shown before similar work. Read-only. */+export interface LessonLine {+ key: string;+ source: LessonSource | null;+ text: string;+ count: number;+ last_at: number | null;+ task_id: string | null;+}++const LESSON_SOURCES: readonly string[] = ['check', 'stall', 'denied', 'error', 'review', 'goal'];++/**+ * The lines from GET /api/kwants/:id/lessons, in the server's order. Null means show nothing: the+ * answer isn't the expected shape, or `enabled` is false (the setting is off). Lines without text+ * are dropped; a missing count is 1.+ */+export function parseLessons(data: unknown): LessonLine[] | null {+ if (!data || typeof data !== 'object') return null;+ const d = data as Record<string, unknown>;+ if (d.enabled === false || !Array.isArray(d.lines)) return null;+ const lines: LessonLine[] = [];+ for (const raw of d.lines) {+ if (!raw || typeof raw !== 'object') continue;+ const l = raw as Record<string, unknown>;+ const text = typeof l.text === 'string' ? l.text.trim() : '';+ if (!text) continue;+ const taskId = typeof l.task_id === 'string' && l.task_id ? l.task_id : null;+ lines.push({+ key: typeof l.key === 'string' && l.key ? l.key : `${lines.length}:${text.slice(0, 24)}`,+ source: typeof l.source === 'string' && LESSON_SOURCES.includes(l.source) ? (l.source as LessonSource) : null,+ text,+ count: typeof l.count === 'number' && Number.isFinite(l.count) ? Math.max(1, Math.round(l.count)) : 1,+ last_at: typeof l.last_at === 'number' && Number.isFinite(l.last_at) ? l.last_at : null,+ task_id: taskId,+ });+ }+ return lines;+}+// ---------------------------------------------------------------------------// API@@ -1714,6 +1775,13 @@ export const missionsApi = {await call<Task>(`/api/tasks/${enc(id)}`, 'PATCH', { budget_tokens });return call<Task>(`/api/tasks/${enc(id)}/unblock`, 'POST', {});},+ /**+ * What a bot is shown from its last 30 days. Resolves to the lines, or null when there is nothing to+ * show: the setting is off, the server is older than the route (404), or the call failed. It is an+ * extra, so it never raises an error on screen.+ */+ lessons: (kwantId: string): Promise<LessonLine[] | null> =>+ call<unknown>(`/api/kwants/${enc(kwantId)}/lessons`).then(parseLessons, () => null),tasks: () => call<{ tasks: Task[] }>('/api/tasks?limit=500').then((r) => r.tasks),task: (id: string) => call<TaskDetail>(`/api/tasks/${enc(id)}`),approveCheck: (id: string) => call<Check>(`/api/checks/${enc(id)}/approve`, 'POST', {}),diff --git a/frontend/tests/goals.test.mjs b/frontend/tests/goals.test.mjsindex 4cb402a7..5ef346e3 100644--- a/frontend/tests/goals.test.mjs+++ b/frontend/tests/goals.test.mjs@@ -545,7 +545,8 @@ test('the board shows Goals on All work only, and there is no setting', () => {const board = readFileSync(new URL('../src/components/MissionBoardView.tsx', import.meta.url), 'utf8');assert.match(board, /<GoalsStrip[^>]*hidden=\{!!missionId\}/s, 'hidden (drawer only) inside a mission');const settings = readFileSync(new URL('../src/components/SettingsModal.tsx', import.meta.url), 'utf8');- assert.doesNotMatch(settings, /goals/i, 'Settings has no Goals switch');+ // The "Learn from earlier work" hint names goals as one thing bots learn from; that is not a Goals switch.+ assert.doesNotMatch(settings.replace(/goals that stopped holding/g, ''), /goals/i, 'Settings has no Goals switch');assert.equal(typeof b.parseGoalsSetting, 'undefined');assert.equal(typeof b.GOALS_SETTING_EVENT, 'undefined');});diff --git a/frontend/tests/lessons.test.mjs b/frontend/tests/lessons.test.mjsnew file mode 100644index 00000000..76f63832--- /dev/null+++ b/frontend/tests/lessons.test.mjs@@ -0,0 +1,118 @@+// Self-improving bots, round 1: the Settings switch, the read-only "Lessons from earlier work" group on a+// bot's Memory tab, and the three Activity lines. Built to the contract in self-improve/plan.md.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++const m = await loadBundled(`export * from './src/missions';`);+const ui = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { LessonsGroup } from './src/components/MemoryPanel';+ export const group = (p) => renderToStaticMarkup(React.createElement(LessonsGroup, p));+`);++const LINE = {+ key: 'check_failed:3fa2c1',+ source: 'check',+ text: '3 days ago, task "Draft the 1.4 release notes": the command check `cargo test --doc` failed after hand-in; fixed by AutoFix, then verified.',+ count: 3,+ last_at: 1762180000000,+ task_id: 't_ab12',+};++test('parseLessons: the contract answer gives its lines in order', () => {+ const second = { ...LINE, key: 'stall:9', source: 'stall', text: 'A turn stalled.', count: 1, task_id: 't_cd34' };+ const got = m.parseLessons({ enabled: true, window_days: 30, lines: [LINE, second] });+ assert.equal(got.length, 2);+ assert.deepEqual(got[0], { key: LINE.key, source: 'check', text: LINE.text, count: 3, last_at: 1762180000000, task_id: 't_ab12' });+ assert.equal(got[1].key, 'stall:9');+});++test('parseLessons: no lines is an empty list; the setting off or a wrong shape hides it', () => {+ assert.deepEqual(m.parseLessons({ enabled: true, window_days: 30, lines: [] }), []);+ assert.equal(m.parseLessons({ enabled: false, window_days: 30, lines: [LINE] }), null, 'off: show nothing');+ assert.equal(m.parseLessons(null), null);+ assert.equal(m.parseLessons({ error: 'not found' }), null);+ assert.equal(m.parseLessons({ enabled: true }), null);+});++test('parseLessons: drops lines without text, defaults count to 1, keeps unknown sources as null', () => {+ const got = m.parseLessons({ lines: [{ key: 'a', text: ' ' }, { key: 'b', text: 'Hello', source: 'weird', count: 'x' }, 7, null, { text: 'No task', count: 0 }] });+ assert.equal(got.length, 2);+ assert.deepEqual(got[0], { key: 'b', source: null, text: 'Hello', count: 1, last_at: null, task_id: null });+ assert.equal(got[1].count, 1);+ assert.equal(got[1].task_id, null);+});++test('missionsApi.lessons: a 404 from an older server hides the group, so does a network error', async () => {+ const real = globalThis.fetch;+ try {+ globalThis.fetch = async () => new Response(JSON.stringify({ error: 'not found' }), { status: 404 });+ assert.equal(await m.missionsApi.lessons('k1'), null);+ globalThis.fetch = async () => {+ throw new TypeError('network');+ };+ assert.equal(await m.missionsApi.lessons('k1'), null);+ let url = '';+ globalThis.fetch = async (u) => {+ url = String(u);+ return new Response(JSON.stringify({ enabled: true, window_days: 30, lines: [LINE] }), { status: 200 });+ };+ const lines = await m.missionsApi.lessons('k 1');+ assert.equal(lines.length, 1);+ assert.equal(url, '/api/kwants/k%201/lessons');+ } finally {+ globalThis.fetch = real;+ }+});++test('parseLessonsSetting: on and off are read; an older server with no field gives null (switch hidden)', () => {+ assert.equal(m.parseLessonsSetting({ lessons: 'on' }), 'on');+ assert.equal(m.parseLessonsSetting({ lessons: 'off' }), 'off');+ assert.equal(m.parseLessonsSetting({}), null);+ assert.equal(m.parseLessonsSetting({ mission_board: true }), null);+ assert.equal(m.parseLessonsSetting({ lessons: 'measure' }), null);+ assert.equal(m.parseLessonsSetting({ lessons: true }), null);+ assert.equal(m.parseLessonsSetting(null), null);+});++const ev = (kind, detail = {}) => ({ id: 1, task_id: 't', kind, actor: 'kwant', actor_name: null, from_state: null, to_state: null, detail, created_at: 0 });++test('eventText: self_checked, lessons_shown and lessons_held_out', () => {+ assert.equal(m.eventText(ev('self_checked', { checks: 2 })), 'It ran its checks before hand-in');+ assert.equal(m.eventText(ev('lessons_shown', { keys: ['a', 'b', 'c'], bytes: 400 })), 'It started with 3 lessons from earlier work');+ assert.equal(m.eventText(ev('lessons_shown', { keys: ['a'], bytes: 90 })), 'It started with 1 lesson from earlier work');+ assert.equal(m.eventText(ev('lessons_shown', {})), 'It started with lessons from earlier work', 'no keys: no made-up number');+ assert.equal(m.eventText(ev('lessons_held_out', { keys: ['a'] })), '');+});++test('isQuietEvent: only the holdout is left out of Activity', () => {+ assert.equal(m.isQuietEvent(ev('lessons_held_out')), true);+ assert.equal(m.isQuietEvent(ev('lessons_shown')), false);+ assert.equal(m.isQuietEvent(ev('self_checked')), false);+});++test('LessonsGroup: text, ×N only above 1, a task link, the caption, and no action buttons beyond the links', () => {+ const html = ui.group({ kwantName: 'Ada', lines: [LINE, { ...LINE, key: 'b', count: 1, text: 'One-off.', task_id: 't_x' }], onOpenTask: () => {} });+ assert.match(html, /Lessons from earlier work/);+ assert.match(html, /Ada sees these before similar work\. They come from the last 30 days and update on their own\./);+ assert.match(html, /×3/);+ assert.equal((html.match(/×/g) ?? []).length, 1, 'count 1 shows no ×N');+ assert.equal((html.match(/>View task</g) ?? []).length, 2);+ assert.equal((html.match(/<button/g) ?? []).length, 2, 'only the task links are buttons');+ assert.doesNotMatch(html, /Delete|Edit|Pin|Dismiss/);+ assert.match(html, /cargo test --doc/);+});++test('LessonsGroup: hidden with no lines, while loading or when off/404 (null); no link without a task or without the board', () => {+ assert.equal(ui.group({ kwantName: 'Ada', lines: [] }), '');+ assert.equal(ui.group({ kwantName: 'Ada', lines: null }), '');+ const noBoard = ui.group({ kwantName: 'Ada', lines: [LINE] });+ assert.doesNotMatch(noBoard, /View task/);+ assert.match(noBoard, /×3/);+ const noTask = ui.group({ kwantName: 'Ada', lines: [{ ...LINE, task_id: null }], onOpenTask: () => {} });+ assert.doesNotMatch(noTask, /View task/);+});