Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

0.9.0 P5: tool notes UI (Notes from bots, chat line, row chips) (#512)

Oleksandr Ivanchenko2c312f9942cd
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index bdff416e..46c13078 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -364,6 +364,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
openAppSettings();
};
const openConnections = () => openSpaceSettings('connections');
+ // 0.9.0 P5: "See the note" in a chat opens Connections on that one note.
+ const [toolNoteFocus, setToolNoteFocus] = useState<string | null>(null);
+ const openToolNote = (noteId: string) => {
+ setToolNoteFocus(noteId);
+ openConnections();
+ };
const openClaudeSignIn = () => {
setClaudeSignInFocus(Date.now());
setSettingsScope('space');
@@ -407,6 +413,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const contentRef = useRef<HTMLDivElement>(null);
useSettingsCover(!!spaceSettingsTab, contentRef);
const closeSpaceSettings = () => {
+ setToolNoteFocus(null);
setSpaceSettingsTab(null);
setSettingsFocusRow(null);
setSettingsClosedCount((n) => n + 1);
@@ -3818,6 +3825,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onAddTool={() => { setMcpStartAdding(true); setIsMcpOpen(true); }}
onOpenAccounts={openSettings}
onOpenLooseEnds={() => showPage('inbox', 'loose')}
+ focusNote={toolNoteFocus}
+ onClearFocusNote={() => setToolNoteFocus(null)}
+ onOpenNoteWhere={(w) => {
+ if (spaceSettingsTab) closeSpaceSettings();
+ openPlace({ channel_id: w.channel_id, kwant_id: w.direct_kwant_id, thread_id: w.thread_id, card_id: w.message_id });
+ }}
/>
);
const missionNames = Object.fromEntries(kwants.map((k) => [k.id, k.name]));
@@ -4004,6 +4017,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
renderMcpSuggestion={renderMcpSuggestion}
renderConnectionSuggestion={renderConnectionSuggestion}
renderBotAction={renderBotAction}
+ onOpenToolNote={openToolNote}
renderHire={renderHire}
renderRouteChoice={renderRouteChoice}
rerouteTargets={openThreadId ? [] : rerouteTargetsFor(currentChannel, kwants)}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index cb92af30..9219b3c1 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -61,6 +61,8 @@ import { DropRecipient, FOLDER_NOTE, dragHasFiles, dropAnnouncement, dropCard, l
import { DropBot, DropLayer, DropPhase } from './DropLayer';
import { EarlierCopies, FileTiles, PointChip, UploadChip } from './Attachments';
import { arrangeSharedFiles, botDisplayName, botOf, shareInfo } from '../sharedFiles';
+import { parseToolNoteMeta } from '../toolNotes';
+import { ToolNoteLine } from './ToolNoteLine';
import { ranOnLabel } from '../engines';
import { replyTokens } from '../modelUsage';
import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';
@@ -290,6 +292,8 @@ export interface ChatViewProps {
renderConnectionSuggestion?: (msg: ChatMessage, meta: ConnectionSuggestionMeta, flash: boolean) => React.ReactNode;
/** A change a bot made in the app (message meta kind "bot_action"). */
renderBotAction?: (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => React.ReactNode;
+ /** 0.9.0 P5: a bot's tool-note line (meta kind "tool_note"); "See the note" opens it on Connections. */
+ onOpenToolNote?: (noteId: string) => void;
/** A bot's proposal to hire a new bot (message meta kind "hire_proposal"). */
renderHire?: (msg: ChatMessage, meta: HireMeta, flash: boolean) => React.ReactNode;
/** Laya's "Who should answer this?" card (message meta kind "route_choice"); `question` is the
@@ -509,6 +513,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
renderMcpSuggestion,
renderConnectionSuggestion,
renderBotAction,
+ onOpenToolNote,
renderHire,
renderRouteChoice,
rerouteTargets = [],
@@ -1287,6 +1292,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
return <React.Fragment key={msg.id}>{renderConnectionSuggestion(msg, connection, flashId === msg.id)}</React.Fragment>;
const botAction = msg.meta && renderBotAction ? parseBotActionMeta(msg.meta) : null;
if (botAction && renderBotAction) return <React.Fragment key={msg.id}>{renderBotAction(msg, botAction, flashId === msg.id)}</React.Fragment>;
+ const toolNote = msg.meta ? parseToolNoteMeta(msg.meta) : null;
+ if (toolNote)
+ return (
+ <ToolNoteLine
+ key={msg.id}
+ meta={toolNote}
+ messageId={msg.id}
+ botName={botDisplayName(toolNote.kwant_id ?? msg.sender_id, knownBots)}
+ flash={flashId === msg.id}
+ onOpen={onOpenToolNote}
+ />
+ );
const hire = msg.meta && renderHire ? parseHireMeta(msg.meta) : null;
if (hire && renderHire) return <React.Fragment key={msg.id}>{renderHire(msg, hire, flashId === msg.id)}</React.Fragment>;
const routeChoice = msg.meta && renderRouteChoice ? parseRouteChoiceMeta(msg.meta) : null;
diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsx
index 4949b690..9e656f51 100644
--- a/frontend/src/components/ConnectionsView.tsx
+++ b/frontend/src/components/ConnectionsView.tsx
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
-import { AlertTriangle, Bot, ChevronLeft, ChevronRight, ExternalLink, Github, KeyRound, Loader2, Lock, Mail, Plug, Plus, RefreshCw, Search, Server, UserRound } from 'lucide-react';
+import { AlertTriangle, Bot, ChevronLeft, ChevronRight, ExternalLink, Github, KeyRound, Loader2, Lock, Mail, Plug, Plus, RefreshCw, Search, Server, StickyNote, UserRound } from 'lucide-react';
import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { relativeTime } from '../away';
import { quotaLine } from '../clock';
@@ -28,6 +28,9 @@ import {
import { inDesktopApp } from '../externalLinks';
import { editorProps } from '../escape';
import { TelegramConnection } from './TelegramCard';
+import { ToolNotesSection, ToolNotesSectionProps } from './ToolNotesSection';
+import { notesChipText } from '../toolNotes';
+import { usePhoneLayout } from '../usePhoneLayout';
const TONES: Record<Tone, string> = {
amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',
@@ -75,9 +78,11 @@ export interface ConnectionRowProps {
/** Dev mode is on in this space: MCP servers and Composio apps get a Production mark (D10). */
onProduction?: (c: Connection, production: boolean) => void;
markingProduction?: boolean;
+ /** 0.9.0 P5: the "2 notes" chip filters Notes from bots to this connection. */
+ onNotes?: (name: string) => void;
}
-export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(), checking = false, links = {}, onCheck, onProduction, markingProduction = false }) => {
+export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(), checking = false, links = {}, onCheck, onProduction, markingProduction = false, onNotes }) => {
const id = useId();
const badge = statusBadge(c.status);
const manage = manageFor(c.kind, links);
@@ -101,6 +106,21 @@ export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(
Production
</span>
)}
+ {c.kind === 'mcp' && c.notes && c.notes.open > 0 && (
+ <button
+ type="button"
+ onClick={() => onNotes?.(c.name)}
+ disabled={!onNotes}
+ aria-label={`${notesChipText(c.notes.open)} about ${c.name}${c.notes.broke ? `, ${c.notes.broke} didn’t work` : ''}: show them`}
+ className={`inline-flex items-center gap-1 px-1.5 py-px rounded-md border text-[11px] font-medium hover:bg-zinc-800 disabled:hover:bg-transparent focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
+ c.notes.broke > 0 ? 'border-rose-300/40 text-rose-200' : 'border-zinc-700 text-zinc-300'
+ }`}
+ data-notes-chip={c.notes.broke > 0 ? 'broke' : 'open'}
+ >
+ <StickyNote size={11} aria-hidden="true" />
+ {notesChipText(c.notes.open)}
+ </button>
+ )}
</div>
{c.detail &&
(isRawCommand(c) ? (
@@ -562,6 +582,15 @@ export interface ConnectionsViewProps extends ManageLinks {
composioOpen?: boolean;
/** Tests and screenshots open the "+ Add connection" list. */
addMenuOpen?: boolean;
+ /** 0.9.0 P5: "See the note" from a chat shows just that note. */
+ focusNote?: string | null;
+ onClearFocusNote?: () => void;
+ /** Refetches the connections so each row's note chip recounts. */
+ onNotesChanged?: () => void;
+ onOpenNoteWhere?: ToolNotesSectionProps['onOpenWhere'];
+ /** Tests and screenshots: the Notes from bots section's api and starting state. */
+ notes?: Partial<ToolNotesSectionProps>;
+ phone?: boolean;
}
export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
@@ -582,8 +611,24 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
marking = null,
composioOpen = false,
addMenuOpen = false,
+ focusNote = null,
+ onClearFocusNote,
+ onNotesChanged,
+ onOpenNoteWhere,
+ notes: notesProps = {},
+ phone,
...links
}) => {
+ const phoneLayout = usePhoneLayout();
+ const [noteConnection, setNoteConnection] = useState<string | null>(notesProps.connection ?? null);
+ const [noteScroll, setNoteScroll] = useState(0);
+ const filterNotes = (name: string | null) => {
+ setNoteConnection(name);
+ if (name) {
+ onClearFocusNote?.();
+ setNoteScroll((n) => n + 1);
+ }
+ };
const groups = data ? groupConnections(data.connections) : [];
const vault = data?.vault;
const [composioRequest, setComposioRequest] = useState(0);
@@ -679,6 +724,22 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
</div>
)}
+ {data && !needsToken && (
+ <ToolNotesSection
+ connections={data.connections.filter((c) => c.kind === 'mcp').map((c) => c.name)}
+ now={now}
+ phone={phone ?? phoneLayout}
+ onChanged={onNotesChanged}
+ onOpenWhere={onOpenNoteWhere}
+ focusNote={focusNote}
+ onClearFocus={onClearFocusNote}
+ scrollRequest={noteScroll}
+ {...notesProps}
+ connection={noteConnection}
+ onConnection={filterNotes}
+ />
+ )}
+
{data &&
groups.map((g) => {
const lockedLogins = g.key === 'browser_login' && vault && vault.status !== 'ok';
@@ -690,7 +751,7 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
{g.items.length > 0 ? (
<ul className="rounded-xl border border-zinc-800 bg-zinc-900/60 divide-y divide-zinc-800">
{g.items.map((c) => (
- <ConnectionRow key={c.id} c={c} now={now} checking={checking === c.id} links={links} onCheck={onCheck} onProduction={onProduction} markingProduction={marking === c.id} />
+ <ConnectionRow key={c.id} c={c} now={now} checking={checking === c.id} links={links} onCheck={onCheck} onProduction={onProduction} markingProduction={marking === c.id} onNotes={filterNotes} />
))}
</ul>
) : (
@@ -741,7 +802,16 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
};
/** The page: loads the list, checks MCP servers, unlocks the vault and adds Composio. */
-export const ConnectionsPage: React.FC<ManageLinks & { onBack?: () => void; embedded?: boolean }> = ({ onBack, embedded, ...links }) => {
+export interface ConnectionsPageProps extends ManageLinks {
+ onBack?: () => void;
+ embedded?: boolean;
+ /** 0.9.0 P5: open on one note ("See the note" in a chat). */
+ focusNote?: string | null;
+ onClearFocusNote?: () => void;
+ onOpenNoteWhere?: ToolNotesSectionProps['onOpenWhere'];
+}
+
+export const ConnectionsPage: React.FC<ConnectionsPageProps> = ({ onBack, embedded, focusNote, onClearFocusNote, onOpenNoteWhere, ...links }) => {
const [data, setData] = useState<ConnectionsList | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -779,6 +849,11 @@ export const ConnectionsPage: React.FC<ManageLinks & { onBack?: () => void; embe
};
}, [load]);
+ // A note changed: recount the row chips without the page's loading state.
+ const quietLoad = useCallback(() => {
+ connectionsApi.list().then((r) => alive.current && setData(r), () => undefined);
+ }, []);
+
const check = async (c: Connection) => {
const sid = mcpServerId(c);
if (!sid || checking) return;
@@ -841,6 +916,10 @@ export const ConnectionsPage: React.FC<ManageLinks & { onBack?: () => void; embe
embedded={embedded}
onProduction={devOn ? markProduction : undefined}
marking={marking}
+ focusNote={focusNote}
+ onClearFocusNote={onClearFocusNote}
+ onOpenNoteWhere={onOpenNoteWhere}
+ onNotesChanged={quietLoad}
{...links}
/>
{unlocking && (
diff --git a/frontend/src/components/ToolNoteLine.tsx b/frontend/src/components/ToolNoteLine.tsx
new file mode 100644
index 00000000..ed4eee0b
--- /dev/null
+++ b/frontend/src/components/ToolNoteLine.tsx
@@ -0,0 +1,31 @@
+// 0.9.0 P5: the grey line a bot's chat shows when it files or repeats a tool note (meta kind
+// "tool_note"). Quiet like a tool step: no card, no badge. "See the note" opens Connections on it.
+import React from 'react';
+import { StickyNote } from 'lucide-react';
+import { ToolNoteMeta, chatLineParts } from '../toolNotes';
+
+export const ToolNoteLine: React.FC<{ meta: ToolNoteMeta; botName: string; messageId?: string; flash?: boolean; onOpen?: (noteId: string) => void }> = ({ meta, botName, messageId, flash = false, onOpen }) => {
+ const [before, after] = chatLineParts(botName, meta);
+ return (
+ <div data-message-id={messageId} className={`flex items-start gap-2 pl-11 pr-4 py-1 rounded-lg text-[12.5px] leading-snug text-zinc-400 ${flash ? 'bg-sky-500/10' : ''}`} data-tool-note-line={meta.note_id}>
+ <StickyNote size={13} className="mt-[3px] shrink-0 text-zinc-500" aria-hidden="true" />
+ <p className="min-w-0 break-words">
+ {before}
+ <code className="font-mono text-zinc-300">{meta.tool}</code>
+ {after}
+ {onOpen && (
+ <>
+ {' '}
+ <button
+ type="button"
+ onClick={() => onOpen(meta.note_id)}
+ className="font-medium text-zinc-200 underline-offset-2 hover:underline rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ See the note
+ </button>
+ </>
+ )}
+ </p>
+ </div>
+ );
+};
diff --git a/frontend/src/components/ToolNotesSection.tsx b/frontend/src/components/ToolNotesSection.tsx
new file mode 100644
index 00000000..9a6d7f82
--- /dev/null
+++ b/frontend/src/components/ToolNotesSection.tsx
@@ -0,0 +1,822 @@
+// 0.9.0 P5: "Notes from bots" at the top of Connections. Bots file notes about their tools; the
+// person edits, marks fixed, reopens or deletes them. Design: release-090/designs/p5-tool-notes.md.
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { Check, CircleX, Ellipsis, Pencil, Plus, StickyNote, Trash2, Undo2, X, Zap, CirclePlus } from 'lucide-react';
+import { relativeTime } from '../away';
+import { useEscapeLayer } from '../escape';
+import { ConnectionsError } from '../connections';
+import {
+ FILTER_LABEL,
+ KIND_LABEL,
+ NOTE_FILTERS,
+ NOTE_KINDS,
+ NOTE_TEXT_MAX,
+ NOTE_TOOL_MAX,
+ NoteFilter,
+ ToolNote,
+ ToolNoteKind,
+ ToolNotesList,
+ ToolNoteWhere,
+ cleanNoteText,
+ notesQuery,
+ toolLabel,
+ toolNotesApi,
+} from '../toolNotes';
+
+export type ToolNotesApi = Pick<typeof toolNotesApi, 'list' | 'add' | 'update' | 'remove'>;
+
+const SHOWN = 5;
+
+/**
+ * What a failed save or delete says (D11): the server's own sentence for a refusal (409 "already
+ * open", 400 "280 characters at most", 403 "Only you…"), the offline sentence when the server
+ * couldn't be reached, and the generic line only otherwise.
+ */
+export function noteProblem(e: unknown, fallback: string): string {
+ if (e instanceof ConnectionsError && e.message.trim() && (e.status === 0 || (e.status >= 400 && e.status < 500))) return e.message;
+ return fallback;
+}
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const btn = `inline-flex items-center justify-center gap-1.5 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 ${focusRing}`;
+const quietBtn = `${btn} min-h-[30px] px-2.5 border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;
+const ghostBtn = `${btn} min-h-[30px] px-2.5 text-zinc-300 hover:bg-zinc-800 hover:text-zinc-100`;
+const iconBtn = `${btn} h-[30px] w-[30px] text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100`;
+const primaryBtn = `${btn} min-h-[30px] px-3 bg-sky-500 text-zinc-950 hover:bg-sky-400`;
+
+const KIND_TAG: Record<ToolNoteKind | 'fixed', string> = {
+ broke: 'text-rose-300 border-rose-300/35 bg-rose-300/[0.08]',
+ tip: 'text-teal-200 border-teal-400/30 bg-teal-400/[0.08]',
+ missing: 'text-violet-300 border-[#9d8fff]/35 bg-[#9d8fff]/[0.08]',
+ fixed: 'text-zinc-400 border-zinc-700 bg-transparent',
+};
+const KIND_ICON: Record<ToolNoteKind | 'fixed', React.ReactNode> = {
+ broke: <CircleX size={11} aria-hidden="true" />,
+ tip: <Zap size={11} aria-hidden="true" />,
+ missing: <CirclePlus size={11} aria-hidden="true" />,
+ fixed: <Check size={11} aria-hidden="true" />,
+};
+
+const KindTag: React.FC<{ kind: ToolNoteKind | 'fixed' }> = ({ kind }) => (
+ <span className={`inline-flex items-center gap-1 h-5 px-1.5 rounded-md border text-[11px] font-semibold ${KIND_TAG[kind]}`} data-note-kind={kind}>
+ {KIND_ICON[kind]}
+ {kind === 'fixed' ? 'Fixed' : KIND_LABEL[kind]}
+ </span>
+);
+
+const ToolChip: React.FC<{ n: ToolNote }> = ({ n }) => (
+ <code className={`inline-flex items-center px-1.5 h-5 rounded-md border border-zinc-800 bg-zinc-900 font-mono text-xs break-all ${n.removed ? 'text-zinc-500' : 'text-zinc-200'}`}>
+ {toolLabel(n)}
+ {n.removed && <span className="ml-1 font-sans">(removed)</span>}
+ </code>
+);
+
+/** The bots' small initial discs (14 px) and names; the person's own notes say so instead. */
+const WhoLine: React.FC<{ n: ToolNote }> = ({ n }) =>
+ n.written_by_person ? (
+ <span>Written by you</span>
+ ) : (
+ <span className="inline-flex flex-wrap items-center gap-x-2 gap-y-0.5">
+ {n.bots.map((b) => (
+ <span key={b.id} className="inline-flex items-center gap-1 font-medium text-zinc-300">
+ <span aria-hidden="true" className="inline-grid place-items-center h-3.5 w-3.5 rounded-full bg-[#9d8fff]/25 text-[9px] font-bold text-violet-200">
+ {b.name.charAt(0).toUpperCase()}
+ </span>
+ {b.name}
+ </span>
+ ))}
+ </span>
+ );
+
+/** "14:02" today, otherwise relative ("yesterday", "3 days ago"). */
+const shortWhen = (ts: string | null, now: number): string => {
+ if (!ts) return '';
+ const t = Date.parse(ts);
+ if (Number.isNaN(t)) return '';
+ const d = new Date(t);
+ const today = new Date(now);
+ if (d.toDateString() === today.toDateString()) return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', hour12: false });
+ return relativeTime(ts, now);
+};
+
+// ---------------------------------------------------------------------------
+// The editor: edit a note's text and kind, or add one (with a tool picker first)
+
+const KindSwitch: React.FC<{ value: ToolNoteKind; onChange: (k: ToolNoteKind) => void; phone: boolean }> = ({ value, onChange, phone }) => {
+ const refs = useRef<Array<HTMLButtonElement | null>>([]);
+ const move = (e: React.KeyboardEvent, i: number) => {
+ const d = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;
+ if (!d) return;
+ e.preventDefault();
+ const next = (i + d + NOTE_KINDS.length) % NOTE_KINDS.length;
+ onChange(NOTE_KINDS[next]);
+ refs.current[next]?.focus();
+ };
+ return (
+ <div role="radiogroup" aria-label="Kind of note" className="inline-flex rounded-lg border border-zinc-700 overflow-hidden">
+ {NOTE_KINDS.map((k, i) => (
+ <button
+ key={k}
+ ref={(el) => { refs.current[i] = el; }}
+ type="button"
+ role="radio"
+ aria-checked={value === k}
+ tabIndex={value === k ? 0 : -1}
+ onClick={() => onChange(k)}
+ onKeyDown={(e) => move(e, i)}
+ data-kind-option={k}
+ className={`${phone ? 'min-h-[44px]' : 'min-h-[30px]'} px-2.5 text-xs ${i ? 'border-l border-zinc-700' : ''} ${
+ value === k ? 'bg-surface-overlay text-zinc-50' : 'text-zinc-300 hover:bg-zinc-800'
+ } focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500`}
+ >
+ {KIND_LABEL[k]}
+ </button>
+ ))}
+ </div>
+ );
+};
+
+export interface NoteEditorProps {
+ /** Editing this note; none adds a new one. */
+ note?: ToolNote;
+ /** For adding: the MCP servers a note can be about. */
+ connections?: string[];
+ phone?: boolean;
+ onSave: (body: { tool?: string; kind: ToolNoteKind; text: string }) => Promise<string | null>;
+ onCancel: () => void;
+ /** Tests: a save error already showing. */
+ initialError?: string | null;
+}
+
+const BUILTIN = '__builtin__';
+
+export const NoteEditor: React.FC<NoteEditorProps> = ({ note, connections = [], phone = false, onSave, onCancel, initialError = null }) => {
+ const id = useId();
+ const [text, setText] = useState(note?.text ?? '');
+ const [kind, setKind] = useState<ToolNoteKind>(note?.kind ?? 'tip');
+ const [server, setServer] = useState(connections[0] ?? BUILTIN);
+ const [toolName, setToolName] = useState('');
+ const [error, setError] = useState<string | null>(initialError);
+ const [saving, setSaving] = useState(false);
+ const area = useRef<HTMLTextAreaElement>(null);
+ const length = [...text].length;
+ const dirty = note ? text !== note.text || kind !== note.kind : !!text.trim() || !!toolName.trim();
+
+ useEffect(() => {
+ if (note) {
+ const el = area.current;
+ el?.focus();
+ el?.setSelectionRange(el.value.length, el.value.length);
+ }
+ }, [note]);
+
+ const save = async () => {
+ if (saving) return;
+ const cleaned = cleanNoteText(text);
+ if ('error' in cleaned) return setError(cleaned.error);
+ let tool: string | undefined;
+ if (!note) {
+ const t = toolName.trim();
+ if (server === BUILTIN && !t) return setError('Name the built-in tool, like bash or browser.');
+ tool = server === BUILTIN ? t : t ? `${server} · ${t}` : server;
+ if ([...tool].length > NOTE_TOOL_MAX) return setError(`A tool name is ${NOTE_TOOL_MAX} characters at most.`);
+ }
+ setSaving(true);
+ setError(null);
+ const problem = await onSave({ tool, kind, text: cleaned.text });
+ setSaving(false);
+ if (problem) setError(problem);
+ };
+
+ const onKey = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape' && !e.defaultPrevented) {
+ e.preventDefault();
+ e.stopPropagation();
+ onCancel();
+ }
+ };
+ const tall = phone ? 'min-h-[44px]' : '';
+
+ return (
+ <div className="space-y-2" onKeyDown={onKey} data-note-editor={note ? note.id : 'new'}>
+ {!note && (
+ <div className="flex flex-wrap gap-2">
+ <div className="min-w-0 basis-40 flex-1 space-y-1">
+ <label htmlFor={`${id}-srv`} className="block text-[11px] font-medium text-zinc-300">
+ Tool
+ </label>
+ <select
+ id={`${id}-srv`}
+ autoFocus
+ value={server}
+ onChange={(e) => setServer(e.target.value)}
+ className={`w-full min-h-[36px] px-2 bg-zinc-950 border border-zinc-800 rounded-lg text-xs text-zinc-100 focus:outline-none focus:border-sky-500 ${tall}`}
+ >
+ {connections.map((c) => (
+ <option key={c} value={c}>
+ {c}
+ </option>
+ ))}
+ <option value={BUILTIN}>Built-in…</option>
+ </select>
+ </div>
+ <div className="min-w-0 basis-40 flex-[2] space-y-1">
+ <label htmlFor={`${id}-tool`} className="block text-[11px] font-medium text-zinc-300">
+ Tool name {server !== BUILTIN && <span className="font-normal text-zinc-400">(optional)</span>}
+ </label>
+ <input
+ id={`${id}-tool`}
+ value={toolName}
+ onChange={(e) => setToolName(e.target.value)}
+ maxLength={NOTE_TOOL_MAX}
+ autoComplete="off"
+ spellCheck={false}
+ placeholder={server === BUILTIN ? 'bash' : 'create_pull_request'}
+ className={`w-full min-h-[36px] px-2.5 bg-zinc-950 border border-zinc-800 rounded-lg font-mono text-xs text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:border-sky-500 ${tall}`}
+ />
+ </div>
+ </div>
+ )}
+ <div className="relative">
+ <label htmlFor={`${id}-t`} className="sr-only">
+ Note text
+ </label>
+ <textarea
+ id={`${id}-t`}
+ ref={area}
+ value={text}
+ rows={2}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void save();
+ }
+ }}
+ placeholder="What should the next bot know about this tool?"
+ aria-describedby={`${id}-c ${id}-e`}
+ aria-invalid={error ? true : undefined}
+ className="block w-full resize-y min-h-[64px] px-3 pt-2.5 pb-6 bg-zinc-950 border border-zinc-700 rounded-lg text-[13.5px] leading-normal text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:border-sky-500"
+ />
+ <span id={`${id}-c`} className={`absolute right-2.5 bottom-1.5 text-[11px] tabular-nums ${length > NOTE_TEXT_MAX ? 'text-rose-300' : 'text-zinc-400'}`} aria-live="off">
+ {length} / {NOTE_TEXT_MAX}
+ </span>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <KindSwitch value={kind} onChange={setKind} phone={phone} />
+ <div className={`flex gap-2 ${phone ? 'w-full' : 'ml-auto'}`}>
+ <button type="button" className={`${quietBtn} ${phone ? 'flex-1 min-h-[44px]' : ''}`} onClick={onCancel} data-dirty={dirty ? '' : undefined}>
+ Cancel
+ </button>
+ <button type="button" className={`${primaryBtn} ${phone ? 'flex-1 min-h-[44px]' : ''}`} onClick={save} disabled={saving}>
+ Save
+ </button>
+ </div>
+ </div>
+ <p id={`${id}-e`} role="alert" className="text-xs text-rose-300 empty:hidden">
+ {error}
+ </p>
+ </div>
+ );
+};
+
+// ---------------------------------------------------------------------------
+// One note
+
+export type RowMode = 'view' | 'edit' | 'confirm';
+
+export interface NoteRowProps {
+ n: ToolNote;
+ now: number;
+ phone: boolean;
+ readOnly: boolean;
+ mode: RowMode;
+ leaving?: boolean;
+ menuOpen?: boolean;
+ onMode: (m: RowMode) => void;
+ onMenu: (open: boolean) => void;
+ onFix: (n: ToolNote, fixed: boolean) => void;
+ onSave: (n: ToolNote, body: { kind: ToolNoteKind; text: string }) => Promise<string | null>;
+ onDelete: (n: ToolNote) => void;
+ onCopy: (n: ToolNote) => void;
+ onOpenWhere?: (where: ToolNoteWhere) => void;
+ /** Tests: a save error under the open editor. */
+ editError?: string | null;
+}
+
+/** The desktop ⋯ menu (Open where it happened · Copy text · Delete). */
+const RowMenu: React.FC<{ n: ToolNote; onClose: () => void; onWhere?: () => void; onCopy: () => void; onDelete: () => void }> = ({ n, onClose, onWhere, onCopy, onDelete }) => {
+ const ref = useRef<HTMLDivElement>(null);
+ useEscapeLayer(ref, true, onClose);
+ useEffect(() => {
+ ref.current?.querySelector<HTMLElement>('button')?.focus();
+ const down = (e: PointerEvent) => !ref.current?.parentElement?.contains(e.target as Node) && onClose();
+ window.addEventListener('pointerdown', down);
+ return () => window.removeEventListener('pointerdown', down);
+ }, [onClose]);
+ const item = `w-full flex items-center gap-2 px-2.5 py-2 rounded-lg text-left text-xs hover:bg-zinc-800 focus-visible:bg-zinc-800 ${focusRing}`;
+ return (
+ <div ref={ref} role="menu" aria-label={`Actions for ${toolLabel(n)}`} className="absolute right-0 top-full mt-1 z-30 w-56 rounded-xl border border-zinc-700 bg-zinc-900 p-1.5 shadow-xl shadow-black/40">
+ {onWhere && (
+ <button type="button" role="menuitem" className={`${item} text-zinc-100`} onClick={() => (onClose(), onWhere())}>
+ Open where it happened
+ </button>
+ )}
+ <button type="button" role="menuitem" className={`${item} text-zinc-100`} onClick={() => (onClose(), onCopy())}>
+ Copy text
+ </button>
+ <button type="button" role="menuitem" className={`${item} text-rose-300`} onClick={() => (onClose(), onDelete())}>
+ Delete
+ </button>
+ </div>
+ );
+};
+
+/** The phone ⋯ sheet: the tool and kind as the title, then 52 px rows. */
+export const NoteSheet: React.FC<{
+ n: ToolNote;
+ onClose: () => void;
+ onFix: () => void;
+ onEdit: () => void;
+ onWhere?: () => void;
+ onDelete: () => void;
+}> = ({ n, onClose, onFix, onEdit, onWhere, onDelete }) => {
+ const id = useId();
+ const ref = useRef<HTMLDivElement>(null);
+ useEscapeLayer(ref, true, onClose, { modal: true });
+ const fixed = n.state === 'fixed';
+ const row = `w-full flex items-center gap-3 h-[52px] px-4 text-left text-sm border-t border-zinc-800 hover:bg-zinc-800/60 ${focusRing}`;
+ const run = (f?: () => void) => () => (onClose(), f?.());
+ return (
+ <div className="fixed inset-0 z-50 flex items-end" data-note-sheet={n.id}>
+ <button type="button" aria-label="Close" tabIndex={-1} className="absolute inset-0 bg-black/60" onClick={onClose} />
+ <div ref={ref} role="dialog" aria-modal="true" aria-labelledby={`${id}-t`} className="relative w-full rounded-t-2xl border-t border-zinc-700 bg-zinc-900 pb-[env(safe-area-inset-bottom)]">
+ <div className="px-4 pt-3 pb-3 space-y-1.5">
+ <div aria-hidden="true" className="mx-auto mb-2 h-1 w-9 rounded-full bg-zinc-700" />
+ <h4 id={`${id}-t`} className="flex flex-wrap items-center gap-1.5 text-sm text-zinc-100">
+ <KindTag kind={fixed ? 'fixed' : n.kind} />
+ <ToolChip n={n} />
+ </h4>
+ </div>
+ <button type="button" className={`${row} text-zinc-100`} onClick={run(onFix)}>
+ {fixed ? <Undo2 size={16} aria-hidden="true" /> : <Check size={16} aria-hidden="true" />}
+ {fixed ? 'Reopen' : 'Mark fixed'}
+ </button>
+ {!fixed && (
+ <button type="button" className={`${row} text-zinc-100`} onClick={run(onEdit)}>
+ <Pencil size={16} aria-hidden="true" /> Edit
+ </button>
+ )}
+ {onWhere && (
+ <button type="button" className={`${row} text-zinc-100`} onClick={run(onWhere)}>
+ <StickyNote size={16} aria-hidden="true" /> Open where it happened
+ </button>
+ )}
+ <button type="button" className={`${row} text-rose-300`} onClick={run(onDelete)}>
+ <Trash2 size={16} aria-hidden="true" /> Delete
+ </button>
+ </div>
+ </div>
+ );
+};
+
+export const NoteRow: React.FC<NoteRowProps> = ({ n, now, phone, readOnly, mode, leaving = false, menuOpen = false, onMode, onMenu, onFix, onSave, onDelete, onCopy, onOpenWhere, editError = null }) => {
+ const fixed = n.state === 'fixed';
+ const where = n.where && onOpenWhere ? () => onOpenWhere(n.where!) : undefined;
+ const label = `${fixed ? 'Fixed' : KIND_LABEL[n.kind]}: ${toolLabel(n)}`;
+ const editing = mode === 'edit' && !readOnly;
+ // S1: when the editor closes (Esc, Cancel or Save), keyboard focus goes back to this note's
+ // "Edit note" button (⋯ on the phone) instead of falling to <body>.
+ const rowRef = useRef<HTMLLIElement>(null);
+ const editBtn = useRef<HTMLButtonElement>(null);
+ const moreBtn = useRef<HTMLButtonElement>(null);
+ const wasEditing = useRef(editing);
+ useEffect(() => {
+ const closed = wasEditing.current && !editing;
+ wasEditing.current = editing;
+ if (!closed || mode !== 'view') return;
+ const active = document.activeElement;
+ if (active && active !== document.body && !rowRef.current?.contains(active)) return;
+ (editBtn.current ?? moreBtn.current)?.focus();
+ }, [editing, mode]);
+ return (
+ <li
+ ref={rowRef}
+ aria-label={label}
+ data-note={n.id}
+ data-note-state={n.state}
+ className={`relative px-3.5 py-3 transition-opacity duration-[160ms] motion-reduce:transition-none ${leaving ? 'opacity-0' : ''} ${editing ? 'bg-[#9d8fff]/5' : ''}`}
+ >
+ <div className="flex items-start gap-3">
+ <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <KindTag kind={fixed ? 'fixed' : n.kind} />
+ <ToolChip n={n} />
+ {n.count > 1 && (
+ <span className="inline-flex items-center px-1 h-[18px] rounded bg-zinc-800 font-mono text-[11px] text-zinc-300" aria-label={`noted ${n.count} times`}>
+ ×{n.count}
+ </span>
+ )}
+ {n.edited_by_person && !n.written_by_person && (
+ <span className="inline-flex items-center gap-1 h-5 px-1.5 rounded-md border border-zinc-700 text-[11px] text-zinc-300">
+ <Pencil size={10} aria-hidden="true" /> Edited by you
+ </span>
+ )}
+ </div>
+ {editing ? (
+ <NoteEditor note={n} phone={phone} initialError={editError} onCancel={() => onMode('view')} onSave={(b) => onSave(n, b)} />
+ ) : (
+ <p className={`text-[13.5px] leading-normal whitespace-pre-line break-words ${fixed ? 'text-zinc-400' : 'text-zinc-100'}`}>{n.text}</p>
+ )}
+ {!editing && (
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11.5px] text-zinc-400">
+ <WhoLine n={n} />
+ {n.last_at && <span>last {shortWhen(n.last_at, now)}</span>}
+ {fixed && <span>Fixed by you{n.fixed_at ? ` · ${shortWhen(n.fixed_at, now)}` : ''} · bots no longer see it</span>}
+ </p>
+ )}
+ {mode === 'confirm' && !readOnly && (
+ <div className="mt-2 rounded-lg border border-zinc-700 bg-zinc-900 p-3 space-y-2.5" role="group" aria-label="Delete this note?">
+ <p className="text-[13px] text-zinc-100">Delete this note? Bots stop seeing it, and it isn’t kept under Fixed.</p>
+ <div className="flex gap-2">
+ <button type="button" className={`${quietBtn} ${phone ? 'flex-1 min-h-[44px]' : ''}`} onClick={() => onMode('view')} autoFocus>
+ Cancel
+ </button>
+ <button type="button" className={`${btn} min-h-[30px] px-3 bg-rose-700 text-white hover:bg-rose-600 ${phone ? 'flex-1 min-h-[44px]' : ''}`} onClick={() => onDelete(n)} data-confirm-delete>
+ Delete
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ {!readOnly && !editing && mode !== 'confirm' && (
+ <div className="relative flex shrink-0 items-center gap-1">
+ {phone ? (
+ <button ref={moreBtn} type="button" className={`${btn} h-11 w-11 -my-2 -mr-2 text-zinc-300 hover:bg-zinc-800`} aria-label="More actions for this note" aria-haspopup="dialog" onClick={() => onMenu(true)}>
+ <Ellipsis size={18} aria-hidden="true" />
+ </button>
+ ) : fixed ? (
+ <>
+ <button type="button" className={ghostBtn} onClick={() => onFix(n, false)}>
+ <Undo2 size={13} aria-hidden="true" /> Reopen
+ </button>
+ <button type="button" className={iconBtn} aria-label="Delete note" onClick={() => onMode('confirm')}>
+ <Trash2 size={14} aria-hidden="true" />
+ </button>
+ </>
+ ) : (
+ <>
+ <button type="button" className={quietBtn} onClick={() => onFix(n, true)}>
+ <Check size={13} aria-hidden="true" /> Mark fixed
+ </button>
+ <button ref={editBtn} type="button" className={iconBtn} aria-label="Edit note" onClick={() => onMode('edit')}>
+ <Pencil size={14} aria-hidden="true" />
+ </button>
+ <button type="button" className={iconBtn} aria-label="More actions for this note" aria-haspopup="menu" aria-expanded={menuOpen} onClick={() => onMenu(!menuOpen)}>
+ <Ellipsis size={16} aria-hidden="true" />
+ </button>
+ {menuOpen && <RowMenu n={n} onClose={() => onMenu(false)} onWhere={where} onCopy={() => onCopy(n)} onDelete={() => onMode('confirm')} />}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ {phone && menuOpen && (
+ <NoteSheet
+ n={n}
+ onClose={() => onMenu(false)}
+ onFix={() => onFix(n, !fixed)}
+ onEdit={() => onMode('edit')}
+ onWhere={where}
+ onDelete={() => onMode('confirm')}
+ />
+ )}
+ </li>
+ );
+};
+
+// ---------------------------------------------------------------------------
+// The section
+
+export interface ToolNotesSectionProps {
+ api?: ToolNotesApi;
+ /** MCP servers in this space, for the "Add a note" tool picker. */
+ connections?: string[];
+ /** Filter to one connection (from a row's chip); null for all. */
+ connection?: string | null;
+ onConnection?: (name: string | null) => void;
+ /** "See the note" from a chat: show just this note. */
+ focusNote?: string | null;
+ onClearFocus?: () => void;
+ /** Tells the page a note changed, so the row chips recount. */
+ onChanged?: () => void;
+ onOpenWhere?: (where: ToolNoteWhere) => void;
+ phone?: boolean;
+ readOnly?: boolean;
+ now?: number;
+ /** Goes up by one when a row's chip is clicked: scroll the section into view. */
+ scrollRequest?: number;
+ /** Tests and screenshots: a list already loaded, and rows in a given state. */
+ initialList?: ToolNotesList | null;
+ initialError?: string | null;
+ initialFilter?: NoteFilter;
+ initialMode?: Record<string, RowMode>;
+ initialMenu?: string | null;
+ initialAdding?: boolean;
+ initialEditError?: string | null;
+}
+
+export const ToolNotesSection: React.FC<ToolNotesSectionProps> = ({
+ api = toolNotesApi,
+ connections = [],
+ connection = null,
+ onConnection,
+ focusNote = null,
+ onClearFocus,
+ onChanged,
+ onOpenWhere,
+ phone = false,
+ readOnly = false,
+ now = Date.now(),
+ scrollRequest = 0,
+ initialList = null,
+ initialError = null,
+ initialFilter = 'all',
+ initialMode = {},
+ initialMenu = null,
+ initialAdding = false,
+ initialEditError = null,
+}) => {
+ const hid = useId();
+ const [filter, setFilter] = useState<NoteFilter>(initialFilter);
+ const [list, setList] = useState<ToolNotesList | null>(initialList);
+ const [error, setError] = useState<string | null>(initialError);
+ const [modes, setModes] = useState<Record<string, RowMode>>(initialMode);
+ const [menu, setMenu] = useState<string | null>(initialMenu);
+ const [adding, setAdding] = useState(initialAdding);
+ const [leaving, setLeaving] = useState<string | null>(null);
+ const [showAll, setShowAll] = useState(false);
+ const [said, setSaid] = useState('');
+ const [rowError, setRowError] = useState<string | null>(null);
+ const sectionRef = useRef<HTMLElement>(null);
+ const chipRefs = useRef<Array<HTMLButtonElement | null>>([]);
+ const seq = useRef(0);
+ const query = notesQuery(filter, connection, focusNote);
+
+ const load = useCallback(async () => {
+ const mine = ++seq.current;
+ try {
+ const r = await api.list(query);
+ if (mine !== seq.current) return;
+ setList(r);
+ setError(null);
+ } catch {
+ if (mine === seq.current) setError('Couldn’t load notes.');
+ }
+ }, [api, query]);
+
+ // A preloaded list (tests, screenshots) is shown as given.
+ const preloaded = useRef(initialList !== null || initialError !== null);
+ useEffect(() => {
+ if (preloaded.current) {
+ preloaded.current = false;
+ return;
+ }
+ void load();
+ }, [load]);
+
+ useEffect(() => {
+ if (!scrollRequest && !focusNote) return;
+ sectionRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'start' });
+ }, [scrollRequest, focusNote]);
+
+ useEffect(() => setShowAll(false), [query]);
+
+ const setMode = (id: string, m: RowMode) => {
+ setRowError(null);
+ setModes((x) => ({ ...x, [id]: m }));
+ };
+
+ const changed = () => {
+ onChanged?.();
+ return load();
+ };
+
+ const fix = async (n: ToolNote, fixed: boolean) => {
+ setRowError(null);
+ try {
+ await api.update(n.id, { state: fixed ? 'fixed' : 'open' });
+ // The row fades out of the list it no longer belongs to (static under reduced motion).
+ if (!focusNote) {
+ setLeaving(n.id);
+ await new Promise((r) => setTimeout(r, 160));
+ }
+ setSaid(fixed ? 'Marked fixed. Bots no longer see it.' : 'Note reopened.');
+ await changed();
+ } catch (e) {
+ setRowError(noteProblem(e, 'Couldn’t save the note. Try again.'));
+ } finally {
+ setLeaving(null);
+ }
+ };
+
+ const saveEdit = async (n: ToolNote, body: { kind: ToolNoteKind; text: string }): Promise<string | null> => {
+ const patch: { kind?: ToolNoteKind; text?: string } = {};
+ if (body.text !== n.text) patch.text = body.text;
+ if (body.kind !== n.kind) patch.kind = body.kind;
+ if (!patch.text && !patch.kind) return setMode(n.id, 'view'), null;
+ try {
+ const saved = await api.update(n.id, patch);
+ setList((l) => (l ? { ...l, notes: l.notes.map((x) => (x.id === n.id ? saved : x)) } : l));
+ setMode(n.id, 'view');
+ setSaid('Note saved.');
+ void changed();
+ return null;
+ } catch (e) {
+ return noteProblem(e, 'Couldn’t save the note. Try again.');
+ }
+ };
+
+ const add = async (body: { tool?: string; kind: ToolNoteKind; text: string }): Promise<string | null> => {
+ try {
+ await api.add({ tool: body.tool ?? '', kind: body.kind, text: body.text });
+ setAdding(false);
+ setSaid('Note saved.');
+ // Show it: the new note is open, so leave Fixed.
+ if (filter === 'fixed' || (filter !== 'all' && filter !== body.kind)) setFilter('all');
+ void changed();
+ return null;
+ } catch (e) {
+ return noteProblem(e, 'Couldn’t save the note. Try again.');
+ }
+ };
+
+ const remove = async (n: ToolNote) => {
+ try {
+ await api.remove(n.id);
+ setSaid('Note deleted.');
+ if (focusNote === n.id) onClearFocus?.();
+ await changed();
+ } catch (e) {
+ setRowError(noteProblem(e, 'Couldn’t delete the note. Try again.'));
+ }
+ };
+
+ const copy = async (n: ToolNote) => {
+ try {
+ await navigator.clipboard.writeText(n.text);
+ setSaid('Copied.');
+ } catch {
+ setSaid('Couldn’t copy. Select the text instead.');
+ }
+ };
+
+ const chooseFilter = (f: NoteFilter) => {
+ setFilter(f);
+ if (focusNote) onClearFocus?.();
+ };
+ const chipKey = (e: React.KeyboardEvent, i: number) => {
+ const d = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;
+ const to = e.key === 'Home' ? 0 : e.key === 'End' ? NOTE_FILTERS.length - 1 : d ? (i + d + NOTE_FILTERS.length) % NOTE_FILTERS.length : -1;
+ if (to < 0) return;
+ e.preventDefault();
+ chooseFilter(NOTE_FILTERS[to]);
+ chipRefs.current[to]?.focus();
+ };
+
+ const counts = list?.counts;
+ const notes = list?.notes ?? [];
+ const shown = showAll ? notes : notes.slice(0, SHOWN);
+ const nothingEver = !!counts && counts.all === 0 && counts.fixed === 0 && !focusNote;
+ const chip = (active: boolean) =>
+ `inline-flex items-center gap-1.5 ${phone ? 'h-9' : 'h-7'} px-3 rounded-full border text-xs whitespace-nowrap shrink-0 ${focusRing} ${
+ active ? 'bg-surface-overlay text-zinc-50 border-[#9d8fff]/45' : 'border-zinc-800 text-zinc-300 hover:bg-zinc-800/70'
+ }`;
+ const activeFilter = focusNote ? null : filter;
+
+ return (
+ <section ref={sectionRef} aria-labelledby={`${hid}-h`} className="space-y-2 scroll-mt-4" data-tool-notes>
+ <div className="flex items-center gap-3">
+ <h3 id={`${hid}-h`} className="flex items-center gap-2 text-xs font-semibold text-zinc-300 uppercase tracking-wider">
+ <StickyNote size={14} aria-hidden="true" className="text-zinc-400" />
+ Notes from bots
+ {counts && <span className="normal-case tracking-normal font-normal text-zinc-400 tabular-nums">{counts.all} open</span>}
+ </h3>
+ {!readOnly && !adding && (
+ <button type="button" className={`${ghostBtn} ml-auto ${phone ? 'min-h-[44px]' : ''}`} onClick={() => (setAdding(true), setRowError(null))}>
+ <Plus size={13} aria-hidden="true" /> Add a note
+ </button>
+ )}
+ </div>
+ <p className="text-xs text-zinc-400">
+ What bots found out about their tools. Open notes are shown to every bot that has the tool, so it doesn’t trip twice. Mark a note fixed when it no longer holds.
+ </p>
+
+ <div role="status" aria-live="polite" className="sr-only" data-notes-said>
+ {said}
+ </div>
+
+ {error && (
+ <p className="flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 text-xs text-rose-300" data-notes-error>
+ {error}
+ <button type="button" onClick={() => void load()} className={`ml-auto px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10 ${focusRing}`}>
+ Retry
+ </button>
+ </p>
+ )}
+
+ {counts && !nothingEver && (
+ <div className={`flex items-center gap-2 ${phone ? 'overflow-x-auto -mx-4 px-4 pb-1 [scrollbar-width:none]' : 'flex-wrap'}`}>
+ <div role="radiogroup" aria-label="Filter notes" className="flex items-center gap-2">
+ {NOTE_FILTERS.map((f, i) => {
+ const on = activeFilter === f;
+ const tab = activeFilter === null ? i === 0 : on;
+ return (
+ <button
+ key={f}
+ ref={(el) => (chipRefs.current[i] = el)}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ tabIndex={tab ? 0 : -1}
+ onClick={() => chooseFilter(f)}
+ onKeyDown={(e) => chipKey(e, i)}
+ className={chip(on)}
+ data-note-filter={f}
+ >
+ {FILTER_LABEL[f]}
+ <span className="tabular-nums text-zinc-400">{counts[f]}</span>
+ </button>
+ );
+ })}
+ </div>
+ {connection && !focusNote && (
+ <button type="button" className={chip(true)} onClick={() => onConnection?.(null)} aria-label={`Show notes for every tool, not only ${connection}`} data-note-connection={connection}>
+ {connection}
+ <X size={12} aria-hidden="true" />
+ </button>
+ )}
+ {focusNote && (
+ <button type="button" className={chip(true)} onClick={onClearFocus} aria-label="Show every note, not only the one from the chat" data-note-focus={focusNote}>
+ Note from the chat
+ <X size={12} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ )}
+
+ {rowError && (
+ <p role="alert" className="text-xs text-rose-300">
+ {rowError}
+ </p>
+ )}
+
+ {list && (adding || notes.length > 0) && (
+ <ul className="rounded-xl border border-zinc-800 bg-zinc-900/60 divide-y divide-zinc-800" aria-label="Notes">
+ {adding && (
+ <li className="px-3.5 py-3 bg-[#9d8fff]/5" aria-label="New note">
+ <NoteEditor connections={connections} phone={phone} onCancel={() => setAdding(false)} onSave={add} initialError={initialEditError} />
+ </li>
+ )}
+ {shown.map((n) => (
+ <NoteRow
+ key={n.id}
+ n={n}
+ now={now}
+ phone={phone}
+ readOnly={readOnly}
+ mode={modes[n.id] ?? 'view'}
+ leaving={leaving === n.id}
+ menuOpen={menu === n.id}
+ onMode={(m) => (setMenu(null), setMode(n.id, m))}
+ onMenu={(o) => setMenu(o ? n.id : null)}
+ onFix={fix}
+ onSave={saveEdit}
+ onDelete={remove}
+ onCopy={copy}
+ onOpenWhere={onOpenWhere}
+ editError={modes[n.id] === 'edit' ? initialEditError : null}
+ />
+ ))}
+ </ul>
+ )}
+
+ {list && notes.length > SHOWN && !showAll && (
+ <button type="button" className={ghostBtn} onClick={() => setShowAll(true)}>
+ Show {notes.length - SHOWN} more
+ </button>
+ )}
+
+ {list && notes.length === 0 && !adding && (
+ <p className="px-3 py-3 rounded-xl border border-dashed border-zinc-800 text-xs text-zinc-400" data-notes-empty={nothingEver ? 'never' : filter === 'all' ? 'none-open' : 'filter'}>
+ {nothingEver
+ ? 'No notes yet. When a tool fails, surprises a bot or is missing, the bot writes it down here.'
+ : focusNote
+ ? 'That note is gone.'
+ : filter === 'all'
+ ? 'No open notes.'
+ : 'No notes of this kind.'}
+ </p>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/connections.ts b/frontend/src/connections.ts
index 7ad3f025..0addaab4 100644
--- a/frontend/src/connections.ts
+++ b/frontend/src/connections.ts
@@ -31,6 +31,8 @@ export interface Connection {
manage: string;
/** Dev mode D10: marked as a production connection in this space (0.7 servers). */
production?: boolean;
+ /** 0.9.0 P5: open bot notes about this MCP server's tools; `broke` of them are "Didn't work". MCP rows only. */
+ notes?: { open: number; broke: number };
}
export interface CatalogEntry {
@@ -91,7 +93,7 @@ const sentence = (s: string) => {
return /[.!?]$/.test(up) ? up : `${up}.`;
};
-async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
+async function call<T>(url: string, method = 'GET', body?: unknown, missing = 'This server doesn’t list connections yet. Update the app and try again.'): Promise<T> {
let res: Response;
try {
res = await personFetch(url, {
@@ -108,13 +110,15 @@ async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T>
if (res.ok) return answer as T;
const err = answer && typeof answer === 'object' ? (answer as Record<string, unknown>).error : null;
if (res.status === 403) throw new ConnectionsError('Only you can see and change connections.', 403);
- if (res.status === 404 && !err) throw new ConnectionsError('This server doesn’t list connections yet. Update the app and try again.', 404);
+ if (res.status === 404 && !err) throw new ConnectionsError(missing, 404);
throw new ConnectionsError(typeof err === 'string' && err.trim() ? sentence(err) : `Something went wrong (HTTP ${res.status}).`, res.status);
}
const enc = encodeURIComponent;
export const connectionsApi = {
+ /** The same person-only call, for other Connections sections (0.9.0 P5 tool notes). */
+ raw: <T>(url: string, method = 'GET', body?: unknown, missing?: string) => call<T>(url, method, body, missing),
list: () => call<ConnectionsList>('/api/connections'),
addComposio: (body: ComposioBody) => call<{ connection_id: string; warning: string }>('/api/connections/composio', 'POST', body),
/** Searches Composio's apps with the person's own Composio key (only once Composio is added). */
diff --git a/frontend/src/toolNotes.ts b/frontend/src/toolNotes.ts
new file mode 100644
index 00000000..93a20505
--- /dev/null
+++ b/frontend/src/toolNotes.ts
@@ -0,0 +1,200 @@
+// 0.9.0 P5: bots' notes about their tools. A bot files a note (didn't work, tip, missing); the
+// person checks, edits, marks fixed or deletes it on Connections. Contract:
+// release-090/p5-contract.md (Lin), design release-090/designs/p5-tool-notes.md (Mira).
+
+import { ConnectionsError, connectionsApi } from './connections';
+import { parseMetaObject } from './questions';
+
+export type ToolNoteKind = 'broke' | 'tip' | 'missing';
+export type ToolNoteState = 'open' | 'fixed';
+export const NOTE_KINDS: ToolNoteKind[] = ['broke', 'tip', 'missing'];
+export const NOTE_TEXT_MAX = 280;
+export const NOTE_TOOL_MAX = 80;
+
+export interface ToolNoteWhere {
+ channel_id: string | null;
+ direct_kwant_id: string | null;
+ thread_id: string | null;
+ message_id: string | null;
+}
+
+/** One note, as GET/POST/PATCH /api/tool-notes give it (contract §1). */
+export interface ToolNote {
+ id: string;
+ tool: string;
+ connection: string | null;
+ builtin: boolean;
+ removed: boolean;
+ kind: ToolNoteKind;
+ state: ToolNoteState;
+ text: string;
+ bot_text: string | null;
+ edited_by_person: boolean;
+ written_by_person: boolean;
+ count: number;
+ bots: Array<{ id: string; name: string }>;
+ created_at: string;
+ last_at: string;
+ updated_at: string | null;
+ fixed_at: string | null;
+ purge_at: string | null;
+ where: ToolNoteWhere | null;
+}
+
+export interface ToolNoteCounts {
+ all: number;
+ broke: number;
+ tip: number;
+ missing: number;
+ fixed: number;
+}
+
+export interface ToolNotesList {
+ notes: ToolNote[];
+ counts: ToolNoteCounts;
+}
+
+/** The filter chips: open notes of every kind, one kind, or the fixed ones. */
+export type NoteFilter = 'all' | ToolNoteKind | 'fixed';
+export const NOTE_FILTERS: NoteFilter[] = ['all', 'broke', 'tip', 'missing', 'fixed'];
+
+export const KIND_LABEL: Record<ToolNoteKind, string> = { broke: 'Didn’t work', tip: 'Tip', missing: 'Missing' };
+export const FILTER_LABEL: Record<NoteFilter, string> = { all: 'All', ...KIND_LABEL, fixed: 'Fixed' };
+
+const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
+const num = (v: unknown, d = 0): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);
+const isKind = (v: unknown): v is ToolNoteKind => NOTE_KINDS.includes(v as ToolNoteKind);
+
+/** Reads one note, defensively; null when it has no id or tool. Unknown kinds read as "tip" (the quietest). */
+export function parseToolNote(raw: unknown): ToolNote | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ const id = str(r.id);
+ const tool = str(r.tool);
+ if (!id || !tool) return null;
+ const connection = str(r.connection);
+ const w = r.where && typeof r.where === 'object' ? (r.where as Record<string, unknown>) : null;
+ const where: ToolNoteWhere | null = w
+ ? { channel_id: str(w.channel_id), direct_kwant_id: str(w.direct_kwant_id), thread_id: str(w.thread_id), message_id: str(w.message_id) }
+ : null;
+ const bots = Array.isArray(r.bots)
+ ? r.bots.flatMap((b) => {
+ const o = b && typeof b === 'object' ? (b as Record<string, unknown>) : {};
+ const bid = str(o.id);
+ return bid ? [{ id: bid, name: str(o.name) ?? 'A bot' }] : [];
+ })
+ : [];
+ return {
+ id,
+ tool,
+ connection,
+ builtin: r.builtin === true || !connection,
+ removed: r.removed === true,
+ kind: isKind(r.kind) ? r.kind : 'tip',
+ state: r.state === 'fixed' ? 'fixed' : 'open',
+ text: typeof r.text === 'string' ? r.text : '',
+ bot_text: str(r.bot_text),
+ edited_by_person: r.edited_by_person === true,
+ written_by_person: r.written_by_person === true,
+ count: Math.max(1, Math.round(num(r.count, 1))),
+ bots,
+ created_at: str(r.created_at) ?? '',
+ last_at: str(r.last_at) ?? str(r.created_at) ?? '',
+ updated_at: str(r.updated_at),
+ fixed_at: str(r.fixed_at),
+ purge_at: str(r.purge_at),
+ where: where && (where.channel_id || where.direct_kwant_id) ? where : null,
+ };
+}
+
+export function parseToolNotesList(raw: unknown): ToolNotesList {
+ const r = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
+ const notes = Array.isArray(r.notes) ? r.notes.map(parseToolNote).filter((n): n is ToolNote => !!n) : [];
+ const c = r.counts && typeof r.counts === 'object' ? (r.counts as Record<string, unknown>) : {};
+ return { notes, counts: { all: num(c.all), broke: num(c.broke), tip: num(c.tip), missing: num(c.missing), fixed: num(c.fixed) } };
+}
+
+/** How the tool reads in a row: built-in tools say so (contract §1 `builtin`). */
+export const toolLabel = (n: Pick<ToolNote, 'tool' | 'builtin'>): string => (n.builtin && !/^built-in · /i.test(n.tool) ? `Built-in · ${n.tool}` : n.tool);
+
+/** The chip on a connection row: "1 note" · "{n} notes". */
+export const notesChipText = (open: number): string => (open === 1 ? '1 note' : `${open} notes`);
+
+/** The query for one list, from the filter and an optional connection. */
+export function notesQuery(filter: NoteFilter, connection: string | null, note: string | null = null): string {
+ const p = new URLSearchParams();
+ if (note) p.set('note', note);
+ else {
+ p.set('state', filter === 'fixed' ? 'fixed' : 'open');
+ if (filter !== 'all' && filter !== 'fixed') p.set('kind', filter);
+ if (connection) p.set('connection', connection);
+ }
+ return p.toString();
+}
+
+/** A text the person typed: trimmed, at most 4 lines and 280 characters; null when empty. */
+export function cleanNoteText(raw: string): { text: string } | { error: string } {
+ const lines = raw.replace(/\r\n?/g, '\n').trim().split('\n');
+ const text = lines.slice(0, 4).join('\n').trim();
+ if (!text) return { error: 'Write what the bots should know.' };
+ if ([...text].length > NOTE_TEXT_MAX) return { error: `A note is ${NOTE_TEXT_MAX} characters at most.` };
+ return { text };
+}
+
+/** The chat line a bot posts when it files or repeats a note (meta kind "tool_note", contract §2.3). */
+export interface ToolNoteMeta {
+ kind: 'tool_note';
+ note_id: string;
+ kwant_id: string | null;
+ tool: string;
+ note_kind: ToolNoteKind;
+ repeat: boolean;
+ count: number;
+}
+
+export function parseToolNoteMeta(raw: unknown): ToolNoteMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'tool_note') return null;
+ const id = str(m.note_id);
+ const tool = str(m.tool);
+ if (!id || !tool) return null;
+ return {
+ kind: 'tool_note',
+ note_id: id,
+ kwant_id: str(m.kwant_id),
+ tool,
+ note_kind: isKind(m.note_kind) ? m.note_kind : 'tip',
+ repeat: m.repeat === true,
+ count: Math.max(1, Math.round(num(m.count, 1))),
+ };
+}
+
+/** The words around the tool in the chat line (design copy table); the tool itself is drawn in mono. */
+export function chatLineParts(bot: string, meta: Pick<ToolNoteMeta, 'note_kind' | 'repeat'>): [string, string] {
+ const again = meta.repeat ? ' again' : '';
+ if (meta.note_kind === 'broke') return [`${bot} noted${again} that `, ' didn’t work.'];
+ if (meta.note_kind === 'missing') return [`${bot} noted${again} that it was missing `, '.'];
+ return [`${bot} noted${again} a tip for `, '.'];
+}
+
+const enc = encodeURIComponent;
+
+async function req<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
+ // The same person-only fetch and error words as Connections; `?space=` is added by the fetch wrapper.
+ return connectionsApi.raw<T>(url, method, body, 'This server doesn’t keep tool notes yet. Update the app and try again.');
+}
+
+export const toolNotesApi = {
+ list: async (query: string): Promise<ToolNotesList> => parseToolNotesList(await req<unknown>(`/api/tool-notes?${query}`)),
+ add: async (body: { tool: string; kind: ToolNoteKind; text: string }): Promise<ToolNote> => {
+ const n = parseToolNote(await req<unknown>('/api/tool-notes', 'POST', body));
+ if (!n) throw new ConnectionsError('The server answered with something that isn’t a note.', 500);
+ return n;
+ },
+ update: async (id: string, body: Partial<{ text: string; kind: ToolNoteKind; state: ToolNoteState }>): Promise<ToolNote> => {
+ const n = parseToolNote(await req<unknown>(`/api/tool-notes/${enc(id)}`, 'PATCH', body));
+ if (!n) throw new ConnectionsError('The server answered with something that isn’t a note.', 500);
+ return n;
+ },
+ remove: (id: string): Promise<unknown> => req<unknown>(`/api/tool-notes/${enc(id)}`, 'DELETE'),
+};
diff --git a/frontend/tests/toolNotes.test.mjs b/frontend/tests/toolNotes.test.mjs
new file mode 100644
index 00000000..4a750039
--- /dev/null
+++ b/frontend/tests/toolNotes.test.mjs
@@ -0,0 +1,216 @@
+// 0.9.0 P5: bots' notes about their tools. Contract: release-090/p5-contract.md (Lin);
+// design: release-090/designs/p5-tool-notes.md (Mira).
+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/toolNotes';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ToolNotesSection, NoteSheet } from './src/components/ToolNotesSection';
+ import { ToolNoteLine } from './src/components/ToolNoteLine';
+ import { ConnectionsView, ConnectionRow } from './src/components/ConnectionsView';
+ export const section = (props) => renderToStaticMarkup(React.createElement(ToolNotesSection, props));
+ export const sheet = (props) => renderToStaticMarkup(React.createElement(NoteSheet, props));
+ export const line = (props) => renderToStaticMarkup(React.createElement(ToolNoteLine, props));
+ export const view = (props) => renderToStaticMarkup(React.createElement(ConnectionsView, props));
+ export const row = (props) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(ConnectionRow, props)));
+`);
+
+const NOW = Date.parse('2026-11-10T15:00:00Z');
+// Shaped like the note in p5-contract.md §1.
+const note = (over = {}) => ({
+ id: 'tn_1', tool: 'github · create_pull_request', connection: 'github', builtin: false, removed: false, kind: 'broke', state: 'open',
+ text: 'Fails with "head branch not found" right after a push. Waiting ~10 s and trying again works.', bot_text: 'Fails…',
+ edited_by_person: false, written_by_person: false, count: 3, bots: [{ id: 'k1', name: 'Pixel' }, { id: 'k2', name: 'Iris' }],
+ created_at: '2026-11-08T10:00:00Z', last_at: '2026-11-10T14:02:00Z', updated_at: null, fixed_at: null, purge_at: null,
+ where: { channel_id: null, direct_kwant_id: 'k1', thread_id: null, message_id: 'm9' }, ...over,
+});
+const counts = (over = {}) => ({ all: 4, broke: 2, tip: 1, missing: 1, fixed: 3, ...over });
+const list = (notes, c = {}) => ({ notes, counts: counts(c) });
+const never = () => new Promise(() => {});
+const api = { list: never, add: never, update: never, remove: never };
+const props = (over = {}) => ({ api, now: NOW, initialList: list([note()]), ...over });
+
+test('a note is read defensively: built-in when no connection, unknown kind as tip, no where without a chat', () => {
+ const n = m.parseToolNote({ id: 'a', tool: 'bash', connection: null, kind: 'weird', count: 0, where: { channel_id: null, direct_kwant_id: null } });
+ assert.equal(n.builtin, true);
+ assert.equal(n.kind, 'tip');
+ assert.equal(n.count, 1);
+ assert.equal(n.where, null);
+ assert.equal(m.toolLabel(n), 'Built-in · bash');
+ assert.equal(m.toolLabel(m.parseToolNote(note())), 'github · create_pull_request');
+ assert.equal(m.parseToolNote({ id: 'a' }), null);
+ const l = m.parseToolNotesList({ notes: [note(), { nope: 1 }], counts: { all: 2 } });
+ assert.equal(l.notes.length, 1);
+ assert.deepEqual(l.counts, { all: 2, broke: 0, tip: 0, missing: 0, fixed: 0 });
+});
+
+test('the list query follows the filter and connection, and note=<id> asks for just that note', () => {
+ assert.equal(m.notesQuery('all', null), 'state=open');
+ assert.equal(m.notesQuery('broke', 'github'), 'state=open&kind=broke&connection=github');
+ assert.equal(m.notesQuery('fixed', null), 'state=fixed');
+ assert.equal(m.notesQuery('tip', 'github', 'tn_9'), 'note=tn_9');
+});
+
+test('the person’s text is trimmed, kept to 4 lines, and refused past 280 characters', () => {
+ assert.deepEqual(m.cleanNoteText(' a\nb\nc\nd\ne '), { text: 'a\nb\nc\nd' });
+ assert.ok('error' in m.cleanNoteText(' '));
+ assert.ok('error' in m.cleanNoteText('x'.repeat(281)));
+ assert.deepEqual(m.cleanNoteText('x'.repeat(280)), { text: 'x'.repeat(280) });
+});
+
+test('the chat line has the design’s words for each kind and for a repeat', () => {
+ assert.deepEqual(m.chatLineParts('Pixel', { note_kind: 'broke', repeat: false }), ['Pixel noted that ', ' didn’t work.']);
+ assert.deepEqual(m.chatLineParts('Pixel', { note_kind: 'broke', repeat: true }), ['Pixel noted again that ', ' didn’t work.']);
+ assert.deepEqual(m.chatLineParts('Lin', { note_kind: 'tip', repeat: false }), ['Lin noted a tip for ', '.']);
+ assert.deepEqual(m.chatLineParts('Rigel', { note_kind: 'missing', repeat: false }), ['Rigel noted that it was missing ', '.']);
+ const meta = m.parseToolNoteMeta({ kind: 'tool_note', note_id: 'tn_1', kwant_id: 'k1', tool: 'github · create_pull_request', note_kind: 'broke', repeat: false, count: 1 });
+ assert.equal(meta.note_id, 'tn_1');
+ assert.equal(m.parseToolNoteMeta({ kind: 'bot_action', note_id: 'x', tool: 't' }), null);
+ const html = ui.line({ meta, botName: 'Pixel', messageId: 'm9', onOpen: () => {} });
+ assert.match(html, /Pixel noted that <code[^>]*>github · create_pull_request<\/code> didn’t work\./);
+ assert.match(html, /See the note/);
+ assert.match(html, /data-message-id="m9"/);
+});
+
+test('an open note: kind tag with icon and word, mono tool, ×3, bots and last time, and the three actions', () => {
+ const html = ui.section(props());
+ assert.match(html, /Notes from bots/);
+ assert.match(html, /4 open/);
+ assert.match(html, /data-note-kind="broke"[^>]*><svg[\s\S]*?Didn’t work/);
+ assert.match(html, /github · create_pull_request/);
+ assert.match(html, /×3/);
+ assert.match(html, /Pixel/);
+ assert.match(html, /Iris/);
+ assert.match(html, /last \d\d:\d\d/);
+ assert.match(html, /Mark fixed/);
+ assert.match(html, /aria-label="Edit note"/);
+ assert.match(html, /aria-label="More actions for this note"/);
+ assert.match(html, /aria-label="Didn’t work: github · create_pull_request"/);
+ // The filters are a radio group with counts.
+ assert.match(html, /role="radiogroup" aria-label="Filter notes"/);
+ for (const [f, n] of [['all', 4], ['broke', 2], ['tip', 1], ['missing', 1], ['fixed', 3]])
+ assert.match(html, new RegExp(`aria-checked="${f === 'all'}"[^>]*data-note-filter="${f}"[\\s\\S]*?>${n}<`));
+ // The meta line is zinc-400, not zinc-500 (AA at 11.5 px).
+ assert.match(html, /text-\[11\.5px\] text-zinc-400/);
+});
+
+test('edited and person-written notes say so; a removed connection’s tool is greyed', () => {
+ const html = ui.section(props({ initialList: list([note({ id: 'a', kind: 'tip', edited_by_person: true }), note({ id: 'b', written_by_person: true, bots: [], edited_by_person: true }), note({ id: 'c', removed: true })]) }));
+ assert.equal((html.match(/Edited by you/g) ?? []).length, 1);
+ assert.match(html, /Written by you/);
+ assert.match(html, /text-zinc-500[^>]*>github · create_pull_request<span[^>]*>\(removed\)/);
+});
+
+test('a fixed note: Fixed tag, grey text, when it was fixed, Reopen and a delete icon', () => {
+ const html = ui.section(props({ initialFilter: 'fixed', initialList: list([note({ state: 'fixed', fixed_at: '2026-11-10T14:20:00Z' })]) }));
+ assert.match(html, /data-note-kind="fixed"/);
+ assert.match(html, /Fixed by you · \d\d:\d\d · bots no longer see it/);
+ assert.match(html, /Reopen/);
+ assert.match(html, /aria-label="Delete note"/);
+ assert.doesNotMatch(html, /Mark fixed/);
+});
+
+test('editing: textarea with the counter, the three-way kind switch, Cancel and Save; a save error keeps the text', () => {
+ const html = ui.section(props({ initialMode: { tn_1: 'edit' }, initialEditError: 'Couldn’t save the note. Try again.' }));
+ assert.match(html, /<textarea/);
+ assert.match(html, /92 \/ 280/);
+ assert.match(html, /role="radiogroup" aria-label="Kind of note"/);
+ assert.match(html, /aria-checked="true"[^>]*data-kind-option="broke"/);
+ assert.match(html, /Cancel/);
+ assert.match(html, />Save</);
+ assert.match(html, /Couldn’t save the note\. Try again\./);
+ assert.match(html, /head branch not found/);
+ assert.doesNotMatch(html, /Mark fixed/);
+});
+
+test('delete asks inline, with the design’s words', () => {
+ const html = ui.section(props({ initialMode: { tn_1: 'confirm' } }));
+ assert.match(html, /Delete this note\? Bots stop seeing it, and it isn’t kept under Fixed\./);
+ assert.match(html, /bg-rose-700 text-white/);
+});
+
+test('add a note: a tool picker of the connections plus Built-in…', () => {
+ const html = ui.section(props({ initialAdding: true, connections: ['github', 'cloudflare'] }));
+ assert.match(html, /<option value="github"/);
+ assert.match(html, /<option value="cloudflare"/);
+ assert.match(html, /Built-in…/);
+ assert.match(html, />Tool</);
+ assert.doesNotMatch(html, /Add a note/);
+});
+
+test('states: no notes ever, only fixed, a filter with no matches, and a load error', () => {
+ assert.match(ui.section(props({ initialList: list([], { all: 0, broke: 0, tip: 0, missing: 0, fixed: 0 }) })), /No notes yet\. When a tool fails, surprises a bot or is missing, the bot writes it down here\./);
+ const onlyFixed = ui.section(props({ initialList: list([], { all: 0, broke: 0, tip: 0, missing: 0, fixed: 2 }) }));
+ assert.match(onlyFixed, /No open notes\./);
+ assert.match(onlyFixed, /data-note-filter="fixed"[\s\S]*?>2</);
+ assert.match(ui.section(props({ initialFilter: 'tip', initialList: list([], { tip: 0 }) })), /No notes of this kind\./);
+ const err = ui.section(props({ initialList: null, initialError: 'Couldn’t load notes.' }));
+ assert.match(err, /Couldn’t load notes\./);
+ assert.match(err, /Retry/);
+ // Add a note stays in every state.
+ assert.match(err, /Add a note/);
+});
+
+test('more than five notes fold behind "Show {n} more"', () => {
+ const html = ui.section(props({ initialList: list(Array.from({ length: 8 }, (_, i) => note({ id: `n${i}` }))) }));
+ assert.equal((html.match(/data-note="/g) ?? []).length, 5);
+ assert.match(html, /Show 3 more/);
+});
+
+test('a connection filter adds a removable chip; a note from the chat shows its own chip', () => {
+ assert.match(ui.section(props({ connection: 'github' })), /data-note-connection="github"/);
+ const focus = ui.section(props({ focusNote: 'tn_1' }));
+ assert.match(focus, /Note from the chat/);
+ assert.match(focus, /aria-checked="false"[^>]*data-note-filter="all"/);
+});
+
+test('read-only: the list without actions', () => {
+ const html = ui.section(props({ readOnly: true }));
+ assert.doesNotMatch(html, /Mark fixed|Edit note|Add a note|More actions/);
+ assert.match(html, /github · create_pull_request/);
+});
+
+test('phone: one 44 px ⋯ button per row, and a sheet with the four actions', () => {
+ const html = ui.section(props({ phone: true }));
+ assert.match(html, /h-11 w-11[^"]*" aria-label="More actions for this note"/);
+ assert.doesNotMatch(html, /aria-label="Edit note"/);
+ assert.match(html, /h-9 /);
+ const s = ui.sheet({ n: m.parseToolNote(note()), onClose() {}, onFix() {}, onEdit() {}, onWhere() {}, onDelete() {} });
+ assert.match(s, /role="dialog"/);
+ for (const w of ['Mark fixed', 'Edit', 'Open where it happened', 'Delete']) assert.match(s, new RegExp(w));
+ assert.equal((s.match(/h-\[52px\]/g) ?? []).length, 4);
+ const fixed = ui.sheet({ n: m.parseToolNote(note({ state: 'fixed' })), onClose() {}, onFix() {}, onEdit() {}, onDelete() {} });
+ assert.match(fixed, /Reopen/);
+ assert.doesNotMatch(fixed, /Open where it happened|>Edit/);
+});
+
+const conn = (over = {}) => ({
+ id: 'mcp:s1', kind: 'mcp', name: 'github', detail: 'api.githubcopilot.com', status: 'connected', status_detail: null,
+ last_check: '2026-11-10T14:55:00Z', used_by: [], logins_stored: 'kwnt', manage: '/api/mcp/servers/s1', ...over,
+});
+
+test('connection rows: "{n} notes", rose when any didn’t work, none without open notes or on other kinds', () => {
+ const rose = ui.row({ c: conn({ notes: { open: 2, broke: 1 } }), now: NOW, onNotes: () => {} });
+ assert.match(rose, /data-notes-chip="broke"/);
+ assert.match(rose, /2 notes/);
+ assert.match(rose, /aria-label="2 notes about github, 1 didn’t work: show them"/);
+ const plain = ui.row({ c: conn({ notes: { open: 1, broke: 0 } }), now: NOW, onNotes: () => {} });
+ assert.match(plain, /data-notes-chip="open"/);
+ assert.match(plain, />1 note</);
+ assert.doesNotMatch(ui.row({ c: conn({ notes: { open: 0, broke: 0 } }), now: NOW }), /data-notes-chip/);
+ assert.doesNotMatch(ui.row({ c: conn({ kind: 'account', notes: { open: 2, broke: 0 } }), now: NOW }), /data-notes-chip/);
+});
+
+test('Connections: the section sits above the groups, and hides behind "Confirm it’s you"', () => {
+ const data = { connections: [conn()], counts: {}, vault: { status: 'ok' }, catalog: [] };
+ const base = { data, loading: false, error: null, now: NOW, onRefresh() {}, onAddComposio: async () => null, notes: { api, initialList: list([note()]) } };
+ const html = ui.view(base);
+ assert.ok(html.indexOf('data-tool-notes') > -1 && html.indexOf('data-tool-notes') < html.indexOf('Tool servers (MCP)'));
+ assert.doesNotMatch(ui.view({ ...base, needsToken: true }), /data-tool-notes/);
+ assert.doesNotMatch(ui.view({ ...base, data: null, loading: true }), /data-tool-notes/);
+});
diff --git a/frontend/tests/toolNotesFix.test.mjs b/frontend/tests/toolNotesFix.test.mjs
new file mode 100644
index 00000000..c4305769
--- /dev/null
+++ b/frontend/tests/toolNotesFix.test.mjs
@@ -0,0 +1,137 @@
+// 0.9.0 P5 QA fixes (Rigel, qa-p5-ui.md): M1 the server's own sentence on a refused save (D11 409,
+// 400, 403), S1 keyboard focus back on "Edit note" after Esc, Cancel or Save.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+
+const m = await loadBundled(`
+ export { ToolNotesSection, noteProblem } from './src/components/ToolNotesSection';
+ export { ConnectionsError } from './src/connections';
+ export { createRoot } from 'react-dom/client';
+ export { createElement } from 'react';
+`);
+
+const NOW = Date.parse('2026-11-10T15:00:00Z');
+const note = (over = {}) => ({
+ id: 'tn_1', tool: 'github · create_pull_request', connection: 'github', builtin: false, removed: false, kind: 'broke', state: 'open',
+ text: 'Fails right after a push.', bot_text: 'Fails…', edited_by_person: false, written_by_person: false, count: 1,
+ bots: [{ id: 'k1', name: 'Pixel' }], created_at: '2026-11-08T10:00:00Z', last_at: '2026-11-10T14:02:00Z', updated_at: null,
+ fixed_at: null, purge_at: null, where: null, ...over,
+});
+const list = (notes) => ({ notes, counts: { all: notes.length, broke: notes.length, tip: 0, missing: 0, fixed: 0 } });
+const act = async (fn) => {
+ await fn();
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const ALREADY = 'There is already an open “Tip” note for github · create_pull_request.';
+
+async function mount(api, notes = [note()]) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ await act(async () => root.render(m.createElement(m.ToolNotesSection, { api, now: NOW, initialList: list(notes) })));
+ const q = (sel) => host.querySelector(sel);
+ const byText = (t) => [...host.querySelectorAll('button')].find((b) => b.textContent.trim() === t);
+ const click = (el) => act(async () => el.dispatchEvent(new MouseEvent('click', { bubbles: true })));
+ const done = async () => {
+ await act(async () => root.unmount());
+ host.remove();
+ };
+ return { host, q, byText, click, done };
+}
+const tick = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+
+test('noteProblem: server refusals and offline say their own sentence, anything else the generic line', () => {
+ const E = m.ConnectionsError;
+ const generic = 'Couldn’t save the note. Try again.';
+ assert.equal(m.noteProblem(new E(ALREADY, 409), generic), ALREADY);
+ assert.equal(m.noteProblem(new E('Text is 280 characters at most.', 400), generic), 'Text is 280 characters at most.');
+ assert.equal(m.noteProblem(new E('Only you can see and change connections.', 403), generic), 'Only you can see and change connections.');
+ assert.equal(m.noteProblem(new E('Couldn’t reach the server. Check your connection and try again.', 0), generic), 'Couldn’t reach the server. Check your connection and try again.');
+ assert.equal(m.noteProblem(new E('Something went wrong (HTTP 500).', 500), generic), generic);
+ assert.equal(m.noteProblem(new Error('boom'), generic), generic);
+ assert.equal(m.noteProblem(new E(' ', 409), generic), generic);
+});
+
+test('a kind change the server refuses (409) shows its sentence; the editor stays open with the text', async () => {
+ let updates = 0;
+ const api = {
+ list: async () => list([note()]),
+ add: async () => { throw new Error('unused'); },
+ update: async () => { updates++; throw new m.ConnectionsError(ALREADY, 409); },
+ remove: async () => {},
+ };
+ const v = await mount(api);
+ await v.click(v.q('button[aria-label="Edit note"]'));
+ const area = v.q('textarea');
+ assert.ok(area, 'editor open');
+ await v.click(v.byText('Tip'));
+ await v.click(v.byText('Save'));
+ await tick();
+ assert.equal(updates, 1);
+ assert.equal(v.q('[role="alert"]').textContent, ALREADY);
+ assert.ok(!v.host.textContent.includes('Couldn’t save the note'));
+ assert.ok(v.q('textarea'), 'editor still open');
+ assert.equal(v.q('textarea').value, 'Fails right after a push.');
+ assert.equal(v.q('li[data-note="tn_1"]').querySelector('[data-note-editor]') !== null, true);
+ await v.done();
+});
+
+test('Reopen refused with 409 shows the server sentence in the row error', async () => {
+ const api = {
+ list: async () => list([note({ state: 'fixed' })]),
+ add: async () => {},
+ update: async () => { throw new m.ConnectionsError(ALREADY, 409); },
+ remove: async () => {},
+ };
+ const v = await mount(api, [note({ state: 'fixed', fixed_at: '2026-11-10T14:00:00Z' })]);
+ await v.click(v.byText('Reopen'));
+ await tick();
+ assert.ok(v.host.textContent.includes(ALREADY));
+ assert.ok(!v.host.textContent.includes('Couldn’t save the note'));
+ await v.done();
+});
+
+for (const how of ['Esc', 'Cancel', 'Save']) {
+ test(`after ${how} closes the editor, focus is back on that note’s "Edit note"`, async () => {
+ const api = {
+ list: async () => list([note({ text: 'Changed.' })]),
+ add: async () => {},
+ update: async (_id, patch) => note({ ...patch }),
+ remove: async () => {},
+ };
+ const v = await mount(api);
+ await v.click(v.q('button[aria-label="Edit note"]'));
+ const area = v.q('textarea');
+ assert.ok(document.activeElement === area, `focus starts in the textarea, not ${document.activeElement?.tagName}`);
+ if (how === 'Esc') {
+ await act(async () => area.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })));
+ } else if (how === 'Cancel') {
+ await v.click(v.byText('Cancel'));
+ } else {
+ await act(async () => {
+ const set = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set;
+ set.call(area, 'Changed.');
+ area.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await v.click(v.byText('Save'));
+ await tick();
+ }
+ assert.ok(v.q('textarea') === null, 'editor closed');
+ const edit = v.q('li[data-note="tn_1"] button[aria-label="Edit note"]');
+ assert.ok(edit);
+ assert.ok(document.activeElement === edit, `focus is on ${document.activeElement?.tagName} ${document.activeElement?.getAttribute?.('aria-label') ?? ''}`);
+ await v.done();
+ });
+}