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.7: Idea jar shell: sidebar row, phone Jar tab, /idea composer, drop toast, Settings cap (Pixel) (#323)

Oleksandr Ivanchenko92f69c1c956e
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 68fe0b95..cf16ae8a 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -10,7 +10,7 @@ import { FirstRunWelcome } from './components/FirstRunWelcome';
import { SpaceTile } from './components/Spaces';
import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState, SendOptions } from './components/ChatView';
import { ReactResult, Reaction, optimisticReplyRef, reactionOf, saveReaction, senderLabel } from './reactReply';
-import { PhoneTabBar } from './components/PhoneTabBar';
+import { PhoneTabBar, type PhoneTabItem } from './components/PhoneTabBar';
import { ThreadBar, ThreadHeader, ThreadPicker, type ThreadBarProps } from './components/ThreadBar';
import { DelegationCard } from './components/DelegationCard';
import { ApprovalsOffBadge } from './components/ApprovalsSetting';
@@ -48,6 +48,11 @@ import { MISSION_BOARD_SETTING_EVENT, emitMission, parseMissionBoardSetting, sou
import { type ChatTarget, planOpenTarget } from './chatTarget';
import { ParallelPage } from './components/ParallelUniverseView';
import { ConnectionsPage } from './components/ConnectionsView';
+import { IdeaJarView, deleteIdea, dropIdea, emitIdeaUpdated, isIdeaCommand, onIdeaUpdated, useIdeaJarBadge } from './components/ideas';
+import { ideasApi, takeArrivedText } from './ideas';
+import { JarIcon } from './components/JarIcon';
+import { IdeaDropToast, type IdeaDropToastState } from './components/IdeaDropToast';
+import { JAR_DROPPED, JAR_SEND_FAILED, ideaSendOutcome, useJarWobble, wobbleJar } from './ideaShell';
import { Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings, Sparkles } from 'lucide-react';
import { ChatApproval, OpenChat, approvalFromEvent, lateAnswerText, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
import type { AgentFormData } from './components/NewAgentModal';
@@ -181,7 +186,7 @@ function useIsPhone(): boolean {
return phone;
}
-type PhoneTab = 'chats' | 'bots' | 'inbox' | 'space';
+type PhoneTab = 'chats' | 'bots' | 'jar' | 'inbox' | 'space';
/** One space: its bots, teams, channels and chats. Remounted for every space, so nothing carries over. */
export const SpaceApp: React.FC<SpaceAppProps> = ({
@@ -200,8 +205,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}) => {
const isPhone = useIsPhone();
// Phones: the list (one tab of it) or the open chat.
- const [phoneView, setPhoneView] = useState<'list' | 'chat'>(() => (initialTarget?.channelId || initialTarget?.botId ? 'chat' : 'list'));
- const [phoneTab, setPhoneTab] = useState<PhoneTab>('chats');
+ // The Idea jar is a tab of the list on phones, so a link to it opens on the list.
+ const [phoneView, setPhoneView] = useState<'list' | 'chat'>(() =>
+ initialView?.kind !== 'jar' && (initialTarget?.channelId || initialTarget?.botId) ? 'chat' : 'list',
+ );
+ const [phoneTab, setPhoneTab] = useState<PhoneTab>(() => (initialView?.kind === 'jar' ? 'jar' : 'chats'));
const [loaded, setLoaded] = useState(false);
const [kwants, setKwants] = useState<Kwant[]>([]);
// Whether the bot list is as new as the last bot change seen. Until then cards can't tell a
@@ -324,6 +332,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
useSettingsCover(!!spaceSettingsTab, contentRef);
const closeSpaceSettings = () => {
setSpaceSettingsTab(null);
+ setSettingsFocusRow(null);
setSettingsClosedCount((n) => n + 1);
// Accounts may have changed: the getting-started list counts the ready ones.
onSpacesChanged();
@@ -343,16 +352,66 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const switchLogRef = useRef(createOutageLog());
// What fills the main pane instead of a chat: the Inbox (New or Loose ends), the Mission board
// or Parallel Universe. The Inbox's unseen count is the sidebar badge.
- const [page, setPage] = useState<'chat' | 'inbox' | 'board' | 'parallel' | 'dev'>(() =>
- initialView?.kind === 'inbox' || initialView?.kind === 'board' || initialView?.kind === 'parallel' || initialView?.kind === 'dev' ? initialView.kind : 'chat',
+ const [page, setPage] = useState<'chat' | 'inbox' | 'board' | 'parallel' | 'dev' | 'jar'>(() =>
+ initialView?.kind === 'inbox' || initialView?.kind === 'board' || initialView?.kind === 'parallel' || initialView?.kind === 'dev' || initialView?.kind === 'jar'
+ ? initialView.kind
+ : 'chat',
);
const [inboxTab, setInboxTab] = useState<InboxTab>(() => (initialView?.kind === 'inbox' ? initialView.tab : 'new'));
- const showPage = (next: 'inbox' | 'board' | 'parallel' | 'dev', tab: InboxTab = 'new') => {
+ const showPage = (next: 'inbox' | 'board' | 'parallel' | 'dev' | 'jar', tab: InboxTab = 'new') => {
setPage(next);
if (next === 'inbox') setInboxTab(tab);
if (spaceSettingsTab) closeSpaceSettings();
- setPhoneView('chat');
- };
+ // Phones keep the tab bar under the jar (it's a tab, spec §2.2); every other page covers the list.
+ if (next === 'jar' && isPhoneRef.current) {
+ setPhoneTab('jar');
+ setPhoneView('list');
+ } else setPhoneView('chat');
+ };
+ const isPhoneRef = useRef(isPhone);
+ isPhoneRef.current = isPhone;
+ // Idea jar (0.7): the ready-takes badge, Open on board's mission, the drop toast and the
+ // app-wide live region (a take is announced on any screen; the open jar announces its own).
+ const ideaJarCount = useIdeaJarBadge(space.id);
+ const jarWobble = useJarWobble();
+ const [pendingMissionId, setPendingMissionId] = useState<string | null>(null);
+ const [ideaToast, setIdeaToast] = useState<{ id: string; state: IdeaDropToastState } | null>(null);
+ const [jarAnnouncement, setJarAnnouncement] = useState('');
+ const [settingsFocusRow, setSettingsFocusRow] = useState<string | null>(null);
+ const closeIdeaToast = useCallback(() => setIdeaToast(null), []);
+ // Open jar from the toast: land in the jar's own "Drop an idea…" field. The view may still be loading,
+ // so look for it for a couple of seconds; give up quietly if focus has moved elsewhere meanwhile.
+ const focusJarQuickAdd = useCallback(() => {
+ let tries = 0;
+ const tick = () => {
+ const field = document.querySelector<HTMLElement>('[data-quick-add="hero"] input, [data-quick-add="phone"] input');
+ const a = document.activeElement;
+ if (a && a !== document.body) return;
+ if (field) field.focus();
+ else if (++tries < 40) setTimeout(tick, 50);
+ };
+ requestAnimationFrame(tick);
+ }, []);
+ const announceJar = (text: string) => {
+ // Cleared first so the same words twice are read twice.
+ setJarAnnouncement('');
+ requestAnimationFrame(() => setJarAnnouncement(text));
+ };
+ useEffect(
+ () =>
+ onIdeaUpdated((e) => {
+ if (e.status !== 'ready' || e.idea || (e.space_id && e.space_id !== space.id) || pageRef.current === 'jar') return;
+ ideasApi.list(space.id).then(
+ (l) => {
+ const i = l.ideas.find((x) => x.id === e.id);
+ if (i?.take) announceJar(takeArrivedText(kwantName(i.kwant_id) ?? null, i.take, i.text));
+ },
+ () => undefined,
+ );
+ }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [space.id],
+ );
// Mission board: shown in the sidebar only when the server has it switched on.
const [missionBoard, setMissionBoard] = useState(false);
// Dev mode (0.7): the open space's state, read by the switch, the hats and the grid.
@@ -1026,6 +1085,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
case 'MemoryChanged':
emitContinuity({ type: 'memory_changed', data: event.data });
break;
+ case 'idea_updated':
+ case 'IdeaUpdated':
+ emitIdeaUpdated(event.data);
+ break;
case 'task_updated':
if (event.data?.task) emitMission({ type: 'task_updated', data: { task: event.data.task } });
break;
@@ -1403,13 +1466,46 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
});
};
- const handleSendMessage = async (text: string, attachments: AttachmentRef[] = [], opts: SendOptions = {}): Promise<boolean> => {
+ const handleSendMessage = async (text: string, attachments: AttachmentRef[] = [], opts: SendOptions = {}): Promise<boolean | string> => {
haptic('tap');
setHistoryWindow(null);
const targetId = openCtx;
const threadId = openThreadId;
const isTargetChannel = isChannel;
const targetTeam = selectedTeamId;
+ // `/idea …` (spec §2.3): the server files it and starts no turn, so no bubble and no "thinking".
+ // A string back is the composer's error line; the text goes back into the box.
+ if (isIdeaCommand(text) && !attachments.length) {
+ try {
+ const res = await fetch('/api/chat/send', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(
+ threadId
+ ? { thread_id: threadId, prompt: text, sender_id: 'PlayerHero', attachment_ids: [] }
+ : { channel_id: isTargetChannel ? targetId : null, kwant_id: !isTargetChannel ? targetId : null, team_id: targetTeam || null, prompt: text, sender_id: 'PlayerHero', attachment_ids: [] },
+ ),
+ });
+ const out = ideaSendOutcome(res.status, await res.json().catch(() => null));
+ if (out.kind === 'error') {
+ haptic('warning');
+ return out.line;
+ }
+ if (out.kind === 'dropped') {
+ emitIdeaUpdated({ id: out.idea.id, status: out.idea.status, space_id: out.idea.space_id || space.id, idea: out.idea });
+ setIdeaToast({ id: out.idea.id, state: 'dropped' });
+ wobbleJar();
+ haptic('success');
+ return true;
+ }
+ // An older server ran it as a chat message: show it the usual way.
+ refreshContext(targetId);
+ return true;
+ } catch {
+ haptic('warning');
+ return JAR_SEND_FAILED;
+ }
+ }
const speakerName = !isTargetChannel ? (currentKwant?.name || 'Bot') : chatTitle;
if (!threadId) {
@@ -3139,6 +3235,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
showPage('dev');
playSfx('click');
}}
+ ideaJarCount={ideaJarCount}
+ ideaJarActive={page === 'jar'}
+ onOpenIdeaJar={() => {
+ showPage('jar');
+ playSfx('click');
+ }}
+ onDropIdea={async (text) => {
+ await dropIdea(space.id, text);
+ wobbleJar();
+ announceJar(JAR_DROPPED);
+ }}
/>
);
@@ -3188,6 +3295,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}}
openTaskId={pendingTaskId}
onOpenedTaskId={() => setPendingTaskId(null)}
+ openMissionId={pendingMissionId}
+ onOpenedMissionId={() => setPendingMissionId(null)}
/>
);
const loose = <LooseEndsPage onOpenChat={openThread} />;
@@ -3339,16 +3448,45 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (viewRequest) applyViewRef.current(viewRequest.view);
}, [viewRequest?.seq]);
+ const jarBots = useMemo(() => kwants.map((k) => ({ id: k.id, name: k.name, role: k.title || null })), [kwants]);
+ const jarPage = (
+ <IdeaJarView
+ key={space.id}
+ spaceId={space.id}
+ spaceName={space.name}
+ bots={jarBots}
+ onOpenMission={(id) => {
+ setPendingMissionId(id);
+ showPage('board');
+ }}
+ onOpenSettings={() => {
+ setSettingsFocusRow('idea-jar');
+ openAppSettings();
+ }}
+ />
+ );
const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} />;
- const mainPane = needsSetup ? setupChecklist : page === 'parallel' ? parallel : page === 'board' && missionBoard ? missionsPage : page === 'dev' && devOn ? devDeskPage : page === 'inbox' ? inbox : !loaded ? (
+ const mainPane = needsSetup ? setupChecklist : page === 'parallel' ? parallel : page === 'board' && missionBoard ? missionsPage : page === 'dev' && devOn ? devDeskPage : page === 'jar' ? jarPage : page === 'inbox' ? inbox : !loaded ? (
<main className="flex-1 flex items-center justify-center text-xs text-zinc-500">
<Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…
</main>
) : chat;
- const phoneTabs: Array<{ id: PhoneTab; label: string; icon: React.ReactNode; badge?: number }> = [
+ const phoneTabs: Array<PhoneTabItem<PhoneTab>> = [
{ id: 'chats', label: 'Chats', icon: <MessageSquare size={20} aria-hidden="true" /> },
{ id: 'bots', label: 'Bots', icon: <Bot size={20} aria-hidden="true" /> },
+ {
+ id: 'jar',
+ label: 'Jar',
+ icon: (
+ <span key={jarWobble} className={`inline-flex ${jarWobble ? 'kw-jar-wobble' : ''}`}>
+ <JarIcon size={20} />
+ </span>
+ ),
+ badge: ideaJarCount,
+ badgeTone: 'violet',
+ badgeNoun: ideaJarCount === 1 ? 'take ready' : 'takes ready',
+ },
{ id: 'inbox', label: 'Inbox', icon: <Inbox size={20} aria-hidden="true" />, badge: awayCount },
{ id: 'space', label: 'Space', icon: <Settings size={20} aria-hidden="true" /> },
];
@@ -3368,6 +3506,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
{sidebar('chats')}
{setupChecklist}
</>
+ ) : phoneTab === 'jar' ? (
+ <div className="flex-1 min-h-0 flex" data-main-pane>{jarPage}</div>
) : (
sidebar(phoneTab === 'bots' ? 'bots' : 'chats')
)}
@@ -3391,6 +3531,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
openSpaceSettings(canRun === false ? 'accounts' : 'general');
return;
}
+ if (id === 'jar') {
+ showPage('jar');
+ return;
+ }
+ if (page === 'jar') setPage('chat');
setPhoneTab(id);
}}
/>
@@ -3532,7 +3677,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
</p>
}
>
- <SettingsModal embedded isOpen onClose={closeSpaceSettings} tokensUsed={tokensUsed} onOpenApiKeys={() => openSpaceSettings('accounts')} />
+ <SettingsModal
+ embedded
+ isOpen
+ onClose={closeSpaceSettings}
+ tokensUsed={tokensUsed}
+ onOpenApiKeys={() => openSpaceSettings('accounts')}
+ focusRow={settingsFocusRow}
+ />
</Suspense>
}
routineFocus={routineFocus}
@@ -3578,6 +3730,31 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
<StarAsk needsYou={Object.keys(needsYouByKwant).length > 0} waiting={awaitingTurns.size > 0 || pendingApprovals.length > 0} />
<Toasts toasts={toasts} onDismiss={dismissToast} />
+ {ideaToast && (
+ <IdeaDropToast
+ key={ideaToast.id}
+ state={ideaToast.state}
+ onClose={closeIdeaToast}
+ onReturnFocus={() => document.querySelector<HTMLElement>('[data-composer]')?.focus()}
+ onOpenJar={page === 'jar' ? undefined : () => {
+ setIdeaToast(null);
+ showPage('jar');
+ focusJarQuickAdd();
+ }}
+ onUndo={() => {
+ if (ideaToast.state !== 'dropped') return;
+ const id = ideaToast.id;
+ setIdeaToast({ id, state: 'undoing' });
+ deleteIdea(id, space.id).then(
+ () => setIdeaToast((t) => (t?.id === id ? { id, state: 'undone' } : t)),
+ () => setIdeaToast((t) => (t?.id === id ? { id, state: 'undo_failed' } : t)),
+ );
+ }}
+ />
+ )}
+ <p role="status" aria-live="polite" className="sr-only" data-jar-live>
+ {jarAnnouncement}
+ </p>
<NeedsYouPill items={pill.items} rev={pill.rev} spriteOf={spriteOf} onOpen={openPill} onDismiss={dismissPill} />
</div>
);
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 0aef2fb2..0e501086 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -52,6 +52,9 @@ import { routeChipLabel, routeReasonText } from '../routeReason';
import { BudgetPausedNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';
import { chainBudgetApi, parseBudgetPaused, parseHandoffCapped } from '../chainBudget';
import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';
+import { IDEA_MAX, isIdeaCommand } from '../ideas';
+import { ideaBlockedLine, ideaLength } from '../ideaShell';
+import { JarIcon } from './JarIcon';
import { consultedNames, hideStreamingDecisions, messageDecisions, parseWorkAhead } from '../decideFirst';
import { approvalScrollAction, fullyVisible, isNearBottom, nextFollowing } from '../approvalVisibility';
import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';
@@ -155,7 +158,8 @@ export interface ChatViewProps {
streamingSpeakerName?: string;
/** `attachments` are files already uploaded from the composer. */
/** Resolves to false when the message couldn't be sent. */
- onSendMessage: (text: string, attachments: AttachmentRef[], opts?: SendOptions) => void | Promise<boolean | void>;
+ /** A string back is a `/idea` that didn't go in: the composer gets the text back with that line. */
+ onSendMessage: (text: string, attachments: AttachmentRef[], opts?: SendOptions) => void | Promise<boolean | string | void>;
/** Saves the person's thumbs on a bot reply; absent hides the thumbs. */
onReact?: (msg: ChatMessage, reaction: Reaction | null) => Promise<ReactResult> | void;
onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
@@ -872,12 +876,57 @@ export const ChatView: React.FC<ChatViewProps> = ({
},
};
- const canSend = composerReady(inputVal, uploads);
+ // `/idea …` goes in the idea jar, not to a bot (spec §2.3): the field dresses violet and blocks a send it can't take.
+ const ideaMode = isIdeaCommand(inputVal);
+ const ideaBlocked = ideaMode ? ideaBlockedLine(inputVal, IDEA_MAX, uploads.length > 0) : null;
+ // A failed drop's reason, shown while the field still holds the words it gave back.
+ const [ideaError, setIdeaError] = useState<{ text: string; line: string } | null>(null);
+ const [ideaTried, setIdeaTried] = useState(false);
+ useEffect(() => {
+ if (!ideaMode) setIdeaTried(false);
+ }, [ideaMode]);
+ // The one-item "/" popover: shows while the field holds a start of "/idea" and nothing else.
+ const slashOpen = !ideaMode && inputVal.length > 0 && inputVal.length < 5 && '/idea'.startsWith(inputVal.toLowerCase()) && !uploads.length;
+ const completeIdea = () => {
+ setInputVal('/idea ');
+ requestAnimationFrame(() => {
+ const el = textareaRef.current;
+ if (el) {
+ el.focus();
+ el.setSelectionRange(6, 6);
+ }
+ });
+ };
+
+ const canSend = ideaMode ? !ideaBlocked : composerReady(inputVal, uploads);
+ // The line under the field: too long or a file shows at once; an empty idea only once Enter was tried.
+ const ideaLine = (ideaError && ideaError.text === inputVal ? ideaError.line : null) ?? (ideaBlocked && (ideaTried || ideaLength(inputVal) > 0 || uploads.length > 0) ? ideaBlocked : null);
const stillUploading = uploads.some((u) => u.state === 'uploading');
const handleSubmit = (e?: React.FormEvent) => {
if (e) e.preventDefault();
// A reply in progress doesn't block the next message (it waits its turn); a team discussion does.
+ if (ideaMode) {
+ // Ideas never wait on a reply or a discussion: the jar is not a bot.
+ if (ideaBlocked) {
+ setIdeaTried(true);
+ return;
+ }
+ const draft = inputVal;
+ playSfx('click');
+ const sent = onSendMessage(draft.trim(), [], undefined);
+ setInputVal('');
+ if (textareaRef.current) textareaRef.current.style.height = 'auto';
+ if (sent && typeof (sent as Promise<unknown>).then === 'function')
+ void (sent as Promise<boolean | string | void>).then((r) => {
+ if (typeof r === 'string') {
+ // A failed drop gives the words back, with the reason under the field.
+ setInputVal((now) => (now ? now : draft));
+ setIdeaError({ text: draft, line: r });
+ }
+ });
+ return;
+ }
if (!canSend || (isStreaming && discussionState?.inProgress)) return;
playSfx('click');
stickRef.current = true;
@@ -903,6 +952,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (slashOpen && (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey))) {
+ e.preventDefault();
+ completeIdea();
+ return;
+ }
if (isMentionOpen) {
if (e.key === 'ArrowDown') {
e.preventDefault();
@@ -1301,7 +1355,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
const toolPhone = 'w-11 h-11 text-[#a39dcc] hover:text-zinc-100 hover:bg-white/[0.06] active:bg-white/[0.06] focus-visible:outline-[#b8adff]';
// Phone hint row (spec A2): no "@ mention · attach files" on touch, and "Answers:" only where it isn't
// obvious (channels and team chats, or a direct chat with an @mention typed).
- const showAnswers = !phone || home?.kind !== 'bot' || target.kind === 'mention';
+ const showAnswers = !ideaMode && (!phone || home?.kind !== 'bot' || target.kind === 'mention');
const showHintText = !(phone && touch);
const placeholder = phone
? phonePlaceholder(title, fieldWidth, (t) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : ''))
@@ -1797,6 +1851,42 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
</div>
)}
+ {ideaMode && (
+ <p data-idea-hint className="basis-full min-w-0 px-1 pt-0.5 flex items-center gap-1.5 text-[12px] leading-4 text-violet-200">
+ <JarIcon size={13} className="shrink-0 text-violet-300" />
+ <span className="min-w-0 line-clamp-2">
+ Goes in the idea jar, not to{' '}
+ <span className="font-medium text-violet-100">
+ {home?.kind === 'bot' ? home.bot?.name ?? title : title.startsWith('#') || home?.kind === 'team' ? title : `#${title}`}
+ </span>
+ . No bot reads it now.
+ </span>
+ </p>
+ )}
+ {slashOpen && (
+ <div
+ role="listbox"
+ id="kw-slash-list"
+ aria-label="Commands"
+ data-slash-popover
+ className="kw-fade-in absolute bottom-full left-0 mb-2 bg-surface-overlay border border-hairline-strong rounded-xl shadow-raised p-1.5 min-w-[260px] z-50"
+ >
+ <button
+ type="button"
+ role="option"
+ id="kw-slash-idea"
+ aria-selected="true"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={completeIdea}
+ className="w-full flex items-center gap-2.5 px-2.5 min-h-11 sm:min-h-9 rounded-lg bg-white/[0.06] text-left text-sm text-zinc-100 hover:bg-white/[0.08]"
+ >
+ <JarIcon size={15} className="text-violet-300 shrink-0" />
+ <span className="font-semibold text-violet-300">/idea</span>
+ <span className="text-zinc-400">Drop an idea in the jar</span>
+ <kbd className="ml-auto font-sans text-[11px] text-zinc-500">Tab</kbd>
+ </button>
+ </div>
+ )}
{isMentionOpen && (
<MentionPopover
items={matchingItems}
@@ -1809,9 +1899,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
ref={textareaRef}
data-composer
role="combobox"
- aria-expanded={isMentionOpen}
- aria-controls={isMentionOpen ? 'kw-mention-list' : undefined}
- aria-activedescendant={isMentionOpen ? `kw-mention-${safeSelectedIndex}` : undefined}
+ aria-expanded={isMentionOpen || slashOpen}
+ aria-controls={isMentionOpen ? 'kw-mention-list' : slashOpen ? 'kw-slash-list' : undefined}
+ aria-activedescendant={isMentionOpen ? `kw-mention-${safeSelectedIndex}` : slashOpen ? 'kw-slash-idea' : undefined}
+ aria-invalid={ideaLine ? true : undefined}
+ aria-describedby={ideaLine ? 'kw-idea-line' : undefined}
aria-autocomplete="list"
rows={1}
value={inputVal}
@@ -1915,7 +2007,32 @@ export const ChatView: React.FC<ChatViewProps> = ({
<Square size={12} fill="currentColor" aria-hidden="true" />
</button>
)}
- {!(isStreaming && (discussionState?.inProgress || !canSend)) && (
+ {ideaMode && (
+ <span
+ data-idea-counter
+ aria-hidden="true"
+ className={`flex-shrink-0 px-1.5 text-[11px] tabular-nums ${ideaLength(inputVal) > IDEA_MAX ? 'text-rose-300' : 'text-zinc-500'}`}
+ >
+ {ideaLength(inputVal).toLocaleString('en-US')} / {IDEA_MAX.toLocaleString('en-US')}
+ </span>
+ )}
+ {ideaMode ? (
+ <button
+ type="submit"
+ aria-label="Drop in the jar"
+ title="Drop in the jar"
+ disabled={!canSend}
+ data-send-ready={canSend ? 'true' : 'false'}
+ data-idea-send
+ className={`w-11 h-11 ${phone ? '' : 'sm:w-9 sm:h-9'} rounded-xl flex items-center justify-center flex-shrink-0 transition-[transform,background-color] duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-violet-300 ${
+ canSend
+ ? 'bg-violet-500 text-white hover:bg-violet-400 active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'
+ : 'bg-violet-500/20 text-violet-300/60 cursor-not-allowed'
+ }`}
+ >
+ <JarIcon size={phone ? 18 : 17} />
+ </button>
+ ) : !(isStreaming && (discussionState?.inProgress || !canSend)) && (
<button
type="submit"
aria-label={stillUploading ? 'Send (waiting for uploads)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}
@@ -1937,6 +2054,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
</div>
</form>
+ {ideaLine && (
+ <p id="kw-idea-line" role="alert" data-idea-line className="max-w-4xl mx-auto mt-1.5 px-1 text-meta text-rose-300">
+ {ideaLine}
+ </p>
+ )}
{/* Under the field: who will answer, and what the field understands */}
<div
className={`max-w-4xl mx-auto mt-1.5 px-1 flex items-center justify-between gap-3 text-meta text-zinc-400${kbd || (!showAnswers && !showHintText) ? ' hidden' : ''}`}
diff --git a/frontend/src/components/IdeaDropToast.tsx b/frontend/src/components/IdeaDropToast.tsx
new file mode 100644
index 00000000..4d0cd66f
--- /dev/null
+++ b/frontend/src/components/IdeaDropToast.tsx
@@ -0,0 +1,95 @@
+import React, { useEffect, useRef } from 'react';
+import { X } from 'lucide-react';
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 focus-visible:outline-offset-2';
+
+export type IdeaDropToastState = 'dropped' | 'undoing' | 'undone' | 'undo_failed';
+
+/**
+ * "Dropped in the jar · Undo · Open jar" (spec §2.3), 6 s. The board's UndoToast shape, plus Open jar
+ * and the after-Undo line. The parent owns the timer so a hover or focus can't strand it.
+ */
+export const IdeaDropToast: React.FC<{
+ state: IdeaDropToastState;
+ onUndo: () => void;
+ onOpenJar?: () => void;
+ onClose: () => void;
+ /** ms before it closes itself; paused while the pointer or focus is inside. */
+ timeout?: number;
+ /** Where focus goes when the toast's own buttons go away under it (the composer the idea came from). */
+ onReturnFocus?: () => void;
+}> = ({ state, onUndo, onOpenJar, onClose, timeout = 6000, onReturnFocus }) => {
+ const box = useRef<HTMLDivElement>(null);
+ const held = useRef(false);
+ // Only take focus back if it was ours: on body (a button unmounted) or still inside the toast.
+ const ownsFocus = () => {
+ const a = document.activeElement;
+ return !a || a === document.body || !!box.current?.contains(a);
+ };
+ useEffect(() => {
+ if ((state === 'undone' || state === 'undo_failed') && ownsFocus()) {
+ held.current = false;
+ onReturnFocus?.();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [state]);
+ const close = () => {
+ const mine = ownsFocus();
+ onClose();
+ if (mine) onReturnFocus?.();
+ };
+ useEffect(() => {
+ if (state === 'undoing') return;
+ const ms = state === 'dropped' ? timeout : 3000;
+ let t = setTimeout(function tick() {
+ if (held.current) t = setTimeout(tick, 1000);
+ else onClose();
+ }, ms);
+ return () => clearTimeout(t);
+ }, [state, timeout, onClose]);
+ const text =
+ state === 'undone' ? 'Taken back out' : state === 'undo_failed' ? 'Couldn’t take it back out. It’s still in the jar.' : 'Dropped in the jar';
+ // Never over the chat box: under the header on phones (the composer grows there), above it from sm up.
+ return (
+ <div className="fixed inset-x-0 top-[calc(env(safe-area-inset-top)+4.25rem)] sm:top-auto sm:bottom-32 z-40 flex justify-center px-4 pointer-events-none" data-idea-toast={state}>
+ <div
+ ref={box}
+ role="status"
+ aria-live="polite"
+ onPointerEnter={() => (held.current = true)}
+ onPointerLeave={() => (held.current = false)}
+ onFocus={() => (held.current = true)}
+ onBlur={() => (held.current = false)}
+ className="pointer-events-auto flex items-center gap-2 max-w-md w-full sm:w-auto pl-4 pr-2 py-2 rounded-xl border border-[#2c2552] bg-[#1a1538] shadow-2xl shadow-black/50"
+ >
+ <span className={`min-w-0 flex-1 text-xs break-words ${state === 'undo_failed' ? 'text-rose-300' : 'text-[#ecebfa]'}`}>{text}</span>
+ {(state === 'dropped' || state === 'undoing') && (
+ <button
+ type="button"
+ onClick={() => {
+ if (state === 'dropped') onUndo();
+ }}
+ aria-disabled={state === 'undoing' || undefined}
+ className={`shrink-0 min-h-[44px] sm:min-h-[36px] px-3 rounded-lg text-xs font-semibold text-sky-300 hover:bg-sky-500/10 aria-disabled:opacity-60 aria-disabled:cursor-default ${focusRing}`}
+ data-idea-undo
+ >
+ Undo
+ </button>
+ )}
+ {onOpenJar && state !== 'undone' && (
+ <button
+ type="button"
+ onClick={onOpenJar}
+ className={`shrink-0 min-h-[44px] sm:min-h-[36px] px-3 rounded-lg text-xs font-semibold text-[#b8adff] hover:bg-violet-500/10 ${focusRing}`}
+ data-idea-open-jar
+ >
+ Open jar
+ </button>
+ )}
+ <button type="button" onClick={close} aria-label="Close" className={`shrink-0 grid place-items-center min-w-[44px] min-h-[44px] sm:min-w-0 sm:min-h-0 p-1.5 rounded-lg text-[#a39dcc] hover:text-white hover:bg-white/5 ${focusRing}`}>
+ <X size={14} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/IdeaJarRow.tsx b/frontend/src/components/IdeaJarRow.tsx
new file mode 100644
index 00000000..acc08e98
--- /dev/null
+++ b/frontend/src/components/IdeaJarRow.tsx
@@ -0,0 +1,132 @@
+import React, { useEffect, useId, useRef, useState } from 'react';
+import { Plus } from 'lucide-react';
+import { badgeText } from '../away';
+import { IDEA_MAX } from '../ideas';
+import { JarIcon } from './JarIcon';
+import { useJarWobble } from '../ideaShell';
+
+/**
+ * The sidebar's Idea jar row (spec §2.1): a nav row with the violet ready-takes badge, and a `+` that
+ * opens a one-line "Drop an idea…" field under it. Enter drops and keeps the field open for the next
+ * idea; Esc, or blur while empty, closes it.
+ */
+export const IdeaJarRow: React.FC<{
+ active: boolean;
+ count: number;
+ onOpen: () => void;
+ /** Drops one idea. Rejects with an Error whose message is shown under the field. */
+ onDrop: (text: string) => Promise<unknown>;
+ className: string;
+}> = ({ active, count, onOpen, onDrop, className }) => {
+ const [open, setOpen] = useState(false);
+ const [text, setText] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const input = useRef<HTMLInputElement>(null);
+ const plus = useRef<HTMLButtonElement>(null);
+ const wobble = useJarWobble();
+ const id = useId();
+ useEffect(() => {
+ if (open) input.current?.focus();
+ }, [open]);
+ const close = (refocus: boolean) => {
+ setOpen(false);
+ setText('');
+ setError(null);
+ if (refocus) plus.current?.focus();
+ };
+ const tooLong = text.trim().length > IDEA_MAX;
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ const t = text.trim();
+ if (!t || busy || tooLong) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await onDrop(t);
+ setText('');
+ } catch (err) {
+ setError(err instanceof Error && err.message ? err.message : 'Couldn’t drop it in the jar. Try again.');
+ } finally {
+ setBusy(false);
+ input.current?.focus();
+ }
+ };
+ // The + shows on hover and focus, and always on touch; the row makes room for it then.
+ const reveal = 'group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100';
+ const room = 'group-hover:pr-10 group-focus-within:pr-10 [@media(hover:none)]:pr-10';
+ return (
+ <div data-idea-jar-row>
+ <div className="group relative">
+ <button type="button" onClick={onOpen} aria-current={active ? 'page' : undefined} className={`${className} ${open ? 'pr-10' : room}`} data-nav="jar">
+ <span key={wobble} className={`inline-flex ${wobble ? 'kw-jar-wobble' : ''}`}>
+ <JarIcon size={15} className={active ? 'text-sky-400' : 'text-zinc-500'} />
+ </span>
+ <span className="truncate flex-1">Idea jar</span>
+ {count > 0 && (
+ <span className="shrink-0 min-w-[18px] px-1.5 py-px rounded-full bg-violet-500 text-white text-[10px] font-semibold text-center" data-jar-badge>
+ {badgeText(count)}
+ <span className="sr-only"> {count === 1 ? 'take' : 'takes'} ready</span>
+ </span>
+ )}
+ </button>
+ <button
+ ref={plus}
+ type="button"
+ aria-label="Drop an idea in the jar"
+ aria-expanded={open}
+ aria-controls={open ? `${id}-form` : undefined}
+ onClick={() => (open ? close(true) : setOpen(true))}
+ className={`absolute right-0 inset-y-0 w-9 flex items-center justify-center rounded-xl text-zinc-400 hover:text-zinc-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${open ? 'opacity-100' : `opacity-0 ${reveal}`}`}
+ data-jar-add
+ >
+ <span className="w-6 h-6 rounded-md flex items-center justify-center bg-white/[0.06] border border-white/10">
+ <Plus size={14} aria-hidden="true" />
+ </span>
+ </button>
+ </div>
+ {open && (
+ <form id={`${id}-form`} onSubmit={submit} className="mt-1 mb-1" data-jar-quick-add>
+ <label htmlFor={`${id}-in`} className="sr-only">
+ Drop an idea in the jar
+ </label>
+ <div className="flex items-center gap-2 h-9 px-2.5 rounded-xl border border-violet-400/60 bg-[#120e26] focus-within:border-violet-300">
+ <input
+ ref={input}
+ id={`${id}-in`}
+ value={text}
+ maxLength={IDEA_MAX + 200}
+ onChange={(e) => {
+ setText(e.target.value);
+ if (error) setError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ close(true);
+ }
+ }}
+ onBlur={(e) => {
+ const to = e.relatedTarget as Node | null;
+ if (!text.trim() && !busy && !(to && e.currentTarget.form?.contains(to)) && to !== plus.current) close(false);
+ }}
+ placeholder="Drop an idea…"
+ aria-invalid={!!error || tooLong || undefined}
+ aria-describedby={error || tooLong ? `${id}-err` : undefined}
+ className="min-w-0 flex-1 bg-transparent text-xs text-zinc-100 placeholder:text-[#8d87b8] outline-none"
+ data-jar-quick-input
+ />
+ <kbd aria-hidden="true" className="shrink-0 rounded border border-hairline-strong px-1 text-2xs font-sans text-zinc-400">
+ ↵
+ </kbd>
+ </div>
+ {(error || tooLong) && (
+ <p id={`${id}-err`} role="alert" className="mt-1 px-1 text-2xs text-rose-300">
+ {tooLong ? `${text.trim().length.toLocaleString('en-US')} / ${IDEA_MAX.toLocaleString('en-US')} · too long for the jar` : error}
+ </p>
+ )}
+ </form>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/JarIcon.tsx b/frontend/src/components/JarIcon.tsx
new file mode 100644
index 00000000..a617780d
--- /dev/null
+++ b/frontend/src/components/JarIcon.tsx
@@ -0,0 +1,23 @@
+import React from 'react';
+
+/** The Idea jar's line icon (spec §2.1): lucide-style, 24 units, 2 px round stroke. Not lucide's Amphora. */
+export const JarIcon: React.FC<{ size?: number; className?: string }> = ({ size = 15, className = '' }) => (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden="true"
+ focusable="false"
+ className={className}
+ data-jar-icon
+ >
+ <path d="M8 3h8M7 6h10" />
+ <path d="M8 6v1.5L5.5 10V19a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-9L16 7.5V6" />
+ <path d="M9 15h2M13 17h2M10 18.5h1" />
+ </svg>
+);
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 60377a43..713a5ada 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -3021,7 +3021,10 @@ export const MissionBoardPage: React.FC<{
/** 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 }) => {
+ /** A mission to select once the board has loaded (Open on board from an idea's take). */
+ openMissionId?: string | null;
+ onOpenedMissionId?: () => void;
+}> = ({ spaceId, names, avatars, onBack, onOpenChat, turns, teams = NO_TEAMS, rooms, threadTitles, onOpenPlace, openTaskId = null, onOpenedTaskId, openMissionId = null, onOpenedMissionId }) => {
const [tasks, setTasks] = useState<Task[] | null>(null);
const [missions, setMissions] = useState<Mission[]>([]);
const [insights, setInsights] = useState<Insights | null>(null);
@@ -3242,6 +3245,14 @@ export const MissionBoardPage: React.FC<{
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [openTaskId, tasks === null]);
+ // Open on board from the Idea jar: select that (draft) mission once the board has its list.
+ useEffect(() => {
+ if (!openMissionId || tasks === null) return;
+ setMissionId(openMissionId);
+ onOpenedMissionId?.();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [openMissionId, 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/PhoneTabBar.tsx b/frontend/src/components/PhoneTabBar.tsx
index 2d452caa..4bc5b54c 100644
--- a/frontend/src/components/PhoneTabBar.tsx
+++ b/frontend/src/components/PhoneTabBar.tsx
@@ -6,6 +6,10 @@ export interface PhoneTabItem<T extends string> {
label: string;
icon: React.ReactNode;
badge?: number;
+ /** amber = needs you (Inbox); violet = an offer, like the Idea jar's ready takes. */
+ badgeTone?: 'amber' | 'violet';
+ /** What the count means, for the aria-label: "Inbox, 2 waiting" / "Jar, 2 takes ready". */
+ badgeNoun?: string;
}
/** The phone's bottom tab bar (spec A6): 56px plus the home-indicator inset, the app's own violet
@@ -25,7 +29,7 @@ export function PhoneTabBar<T extends string>({
<nav
aria-label={label}
data-tab-bar
- className="shrink-0 grid grid-cols-4 border-t border-white/[0.07] bg-[#0e0a21] pb-[env(safe-area-inset-bottom)]"
+ className={`shrink-0 grid ${tabs.length >= 5 ? 'grid-cols-5' : 'grid-cols-4'} border-t border-white/[0.07] bg-[#0e0a21] pb-[env(safe-area-inset-bottom)]`}
>
{tabs.map((t) => {
const on = t.id === active;
@@ -34,7 +38,7 @@ export function PhoneTabBar<T extends string>({
key={t.id}
type="button"
aria-current={on ? 'page' : undefined}
- aria-label={t.badge ? `${t.label}, ${t.badge} waiting` : undefined}
+ aria-label={t.badge ? `${t.label}, ${t.badge} ${t.badgeNoun ?? 'waiting'}` : undefined}
data-tab={t.id}
onClick={() => onSelect(t.id)}
className={`relative h-14 flex flex-col items-center justify-center gap-0.5 text-xs leading-4 font-medium focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[#b8adff] ${
@@ -54,7 +58,12 @@ export function PhoneTabBar<T extends string>({
<span
aria-hidden="true"
data-tab-badge
- className="absolute top-[-4px] left-[10px] h-[18px] min-w-[18px] px-1 rounded-full bg-[#fcd34d] text-[#1b1033] text-[11px] leading-[18px] font-semibold text-center"
+ data-tone={t.badgeTone ?? 'amber'}
+ className={`absolute top-[-4px] left-[10px] h-[18px] min-w-[18px] px-1 rounded-full ${
+ t.badgeTone === 'violet'
+ ? 'bg-[#8b7bff] text-white text-[11px] leading-[18px] font-semibold text-center ring-2 ring-[#0e0a21]'
+ : 'bg-[#fcd34d] text-[#1b1033] text-[11px] leading-[18px] font-semibold text-center'
+ }`}
>
{badgeText(t.badge)}
</span>
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index c52867e4..bdc4b5f3 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -32,6 +32,7 @@ import { LayaStatusRow } from './LayaStatus';
import { AppUpdateAbout, useAppUpdate } from './AppUpdateBanner';
import { StarAskSettingsLink } from './StarAsk';
import { ProactiveSettings, WORK_AHEAD_CAP_MAX, WORK_AHEAD_CAP_MIN, parseProactiveSettings } from '../decideFirst';
+import { IDEA_CAP_DEFAULT, IDEA_CAP_MAX, IDEA_CAP_MIN, ideaCapForSwitch, lastIdeaCap, parseIdeaCap, rememberIdeaCap } from '../ideaShell';
import {
AUTOFIX_MODES,
AutofixSettings,
@@ -74,6 +75,7 @@ const SwitchRow: React.FC<{ id: string; label: string; hint: string; checked: bo
<button
type="button"
role="switch"
+ data-switch={id}
aria-checked={checked}
aria-labelledby={`${id}-label`}
aria-describedby={`${id}-hint`}
@@ -159,6 +161,8 @@ interface SettingsData {
decide_first?: boolean;
work_ahead?: boolean;
work_ahead_daily_cap?: number;
+ /** Idea jar (0.7): takes a day per space; 0 = off. Missing on older servers. */
+ idea_jar_daily_cap?: number;
}
/**
@@ -247,6 +251,8 @@ interface SettingsModalProps {
embedded?: boolean;
/** Opens Settings › This space › Accounts, where the API keys and Ollama address live. */
onOpenApiKeys?: () => void;
+ /** A switch to scroll to and focus once loaded, by its row id ("idea-jar" from the jar's Settings button). */
+ focusRow?: string | null;
}
/** App settings: shared by every space (keys, Laya, limits, notifications, sounds). Accounts,
@@ -293,7 +299,7 @@ const DiscoverySetting: React.FC<{ value: DiscoverySettings; onChange: (v: Disco
);
};
-export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tokensUsed = 0, embedded = false, onOpenApiKeys }) => {
+export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tokensUsed = 0, embedded = false, onOpenApiKeys, focusRow = null }) => {
const { authRequired, deviceLogin, signOut } = useAuth();
const computer = useComputerMode(isOpen);
const [sfxMuted, setSfxMuted] = useState(isSfxMuted);
@@ -311,6 +317,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const [agentTools, setAgentTools] = useState<boolean | null>(null);
// Deciding and working ahead on their own; null on a server without these settings
const [proactive, setProactive] = useState<ProactiveSettings | null>(null);
+ // Idea jar: takes a day per space, 0 = off; null on a server without it (hidden, left out of the save).
+ const [ideaCap, setIdeaCap] = useState<number | null>(null);
// 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);
@@ -386,6 +394,12 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
setTokenLimits(dl ? { task: String(dl.task), mission: String(dl.mission) } : null);
setAgentTools(typeof data.agent_tools === 'boolean' ? data.agent_tools : null);
setProactive(parseProactiveSettings(data));
+ if (data.idea_jar_daily_cap === undefined) setIdeaCap(null);
+ else {
+ const cap = parseIdeaCap(data.idea_jar_daily_cap);
+ if (cap > 0) rememberIdeaCap(cap);
+ setIdeaCap(cap);
+ }
setMissionBoard(parseMissionBoardSetting(data));
setAutofix(parseAutofixSettings(data));
setLessons(parseLessonsSetting(data));
@@ -443,6 +457,18 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const notifyHint = deviceNotifyHint({ support, permission, on: browserNotify, android: notifyEnv.android, standalone: notifyEnv.standalone });
const notifyBlocked = support === 'insecure' || support === 'ios-install' || support === 'unsupported';
+ // Opened from a page's Settings button (the Idea jar's): bring that switch into view and focus it.
+ useEffect(() => {
+ if (!isOpen || !focusRow || !settings) return;
+ const raf = requestAnimationFrame(() => {
+ const el = document.querySelector<HTMLElement>(`[data-switch="${focusRow}"]`);
+ if (!el) return;
+ el.scrollIntoView({ block: 'center', behavior: 'auto' });
+ el.focus({ preventScroll: true });
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [isOpen, focusRow, settings]);
+
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
if (webhookError || limitsInvalid || chainBudgetError || tokenLimitsInvalid) return;
@@ -468,6 +494,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
...(tokenLimitsValue ? defaultLimitsBody(tokenLimitsValue) : {}),
...(agentTools !== null ? { agent_tools: agentTools } : {}),
...(proactive ?? {}),
+ ...(ideaCap !== null ? { idea_jar_daily_cap: ideaCap } : {}),
...(missionBoard !== null ? { mission_board: missionBoard } : {}),
...(autofix !== null ? { autofix: autofix.autofix, recovery_budget_pct: autofix.recovery_budget_pct } : {}),
...(lessons !== null ? { lessons } : {}),
@@ -871,6 +898,47 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</span>
</div>
</SwitchRow>
+ {ideaCap !== null && (
+ <SwitchRow
+ id="idea-jar"
+ label="Free bots peek in the idea jar"
+ hint="A bot with nothing on takes the oldest idea and writes a take: worth it or not, how big, and a plan. It reads only. Nothing starts until you press Do it."
+ checked={ideaCap > 0}
+ onToggle={() =>
+ setIdeaCap((c) => {
+ const next = ideaCapForSwitch(!(c && c > 0), lastIdeaCap());
+ if (next > 0) rememberIdeaCap(next);
+ return next;
+ })
+ }
+ >
+ <div className="mt-2 flex items-center gap-2">
+ <label htmlFor="idea-jar-cap" className={`text-[11px] ${ideaCap > 0 ? 'text-zinc-300' : 'text-zinc-500'}`}>
+ At most
+ </label>
+ <select
+ id="idea-jar-cap"
+ value={ideaCap > 0 ? ideaCap : lastIdeaCap() ?? IDEA_CAP_DEFAULT}
+ disabled={ideaCap <= 0}
+ onChange={(e) => {
+ const n = Number(e.target.value);
+ rememberIdeaCap(n);
+ setIdeaCap(n);
+ }}
+ className="bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1.5 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none disabled:opacity-50"
+ >
+ {Array.from({ length: IDEA_CAP_MAX - IDEA_CAP_MIN + 1 }, (_, i) => i + IDEA_CAP_MIN).map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ <span className={`text-[11px] ${ideaCap > 0 ? 'text-zinc-300' : 'text-zinc-500'}`}>
+ {(ideaCap > 0 ? ideaCap : lastIdeaCap() ?? IDEA_CAP_DEFAULT) === 1 ? 'take' : 'takes'} a day in each space
+ </span>
+ </div>
+ </SwitchRow>
+ )}
</fieldset>
)}
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 9da78a0e..9172960a 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -19,6 +19,7 @@ import { trapFocusTarget } from '../imports';
import { type NeedsYouRow, workingIds, directIds } from '../chatsTab';
import { DevModeSwitch, DevOffNote, useDevMode } from './DevModeSwitch';
import { DevDeskRow } from './DevDesk';
+import { IdeaJarRow } from './IdeaJarRow';
export interface Kwant {
id: string;
@@ -124,6 +125,11 @@ export interface SidebarProps {
/** Dev mode (0.7): the Dev desk row's page is open, and how to open it. */
devDeskActive?: boolean;
onOpenDevDesk?: () => void;
+ /** Idea jar (0.7): ready takes for the violet badge, whether its page is open, how to open it, and the quick-add. Hidden on phone, which has the Jar tab. */
+ ideaJarCount?: number;
+ ideaJarActive?: boolean;
+ onOpenIdeaJar?: () => void;
+ onDropIdea?: (text: string) => Promise<unknown>;
/** Opens Space settings → Accounts from the footer. */
onOpenAccounts?: () => void;
/** Opens Accounts at "Sign in with Claude", when Claude being signed out is why nothing runs. */
@@ -282,6 +288,10 @@ export const Sidebar: React.FC<SidebarProps> = ({
devDeskActive = false,
onOpenDevDesk,
onOpenMissions,
+ ideaJarCount = 0,
+ ideaJarActive = false,
+ onOpenIdeaJar,
+ onDropIdea,
onOpenAccounts,
onSignInClaude,
enginesRefreshKey = 0,
@@ -799,6 +809,9 @@ export const Sidebar: React.FC<SidebarProps> = ({
<span className="truncate flex-1">Mission board</span>
</button>
)}
+ {onOpenIdeaJar && onDropIdea && !phone && (
+ <IdeaJarRow active={ideaJarActive} count={ideaJarCount} onOpen={onOpenIdeaJar} onDrop={onDropIdea} className={navRow(ideaJarActive)} />
+ )}
{onOpenParallel && (
<MoreMenu
className={navRow(parallelActive)}
diff --git a/frontend/src/ideaShell.ts b/frontend/src/ideaShell.ts
new file mode 100644
index 00000000..ce7c609e
--- /dev/null
+++ b/frontend/src/ideaShell.ts
@@ -0,0 +1,100 @@
+// Idea jar, the shell's side (0.7, Pixel): the wobble signal, the /idea send answer, the drop toast's
+// steps and the Settings switch. Pure where it can be, so tests reach it without a DOM.
+import { useEffect, useState } from 'react';
+import { parseIdea, type Idea } from './ideas';
+
+export const JAR_SEND_FAILED = 'Couldn’t drop it in the jar. Try again.';
+export const JAR_PERSON_ONLY = 'Only you can add ideas.';
+export const JAR_DROPPED = 'Dropped in the jar.';
+
+/** What POST /api/chat/send answered to a `/idea` line. */
+export type IdeaSendOutcome =
+ | { kind: 'dropped'; idea: Idea }
+ /** An older server ran it as a chat message: fall back to the normal path. */
+ | { kind: 'chat' }
+ | { kind: 'error'; line: string };
+
+/** Reads the send's answer (spec §2.3). `body` is the parsed JSON, or null. */
+export function ideaSendOutcome(status: number, body: unknown): IdeaSendOutcome {
+ const o = body && typeof body === 'object' ? (body as Record<string, unknown>) : null;
+ if (status === 403) return { kind: 'error', line: JAR_PERSON_ONLY };
+ if (status === 400) {
+ const m = typeof o?.message === 'string' && o.message.trim() ? o.message.trim() : null;
+ return { kind: 'error', line: m ? (/[.!?]$/.test(m) ? m : `${m}.`) : JAR_SEND_FAILED };
+ }
+ if (status < 200 || status >= 300) return { kind: 'error', line: JAR_SEND_FAILED };
+ if (o?.handled === 'idea') {
+ const idea = parseIdea(o.idea);
+ return idea ? { kind: 'dropped', idea } : { kind: 'error', line: JAR_SEND_FAILED };
+ }
+ return { kind: 'chat' };
+}
+
+/** The composer's blocked-send line for a `/idea` draft, or null when it may go (spec §2.3). */
+export function ideaBlockedLine(text: string, max: number, hasFiles = false): string | null {
+ const body = text.trimStart().replace(/^\/idea/i, '').trim();
+ if (!body) return 'Type your idea after /idea';
+ if (body.length > max) return `${body.length.toLocaleString('en-US')} / ${max.toLocaleString('en-US')} · too long for the jar`;
+ if (hasFiles) return 'Ideas are text only. Remove the file to drop it in.';
+ return null;
+}
+
+/** The length the counter shows: the idea itself, without `/idea `. */
+export const ideaLength = (text: string) => text.trimStart().replace(/^\/idea/i, '').trim().length;
+
+// ---- Settings › "Free bots peek in the idea jar" (spec §6). One number; 0 is off.
+
+export const IDEA_CAP_DEFAULT = 3;
+export const IDEA_CAP_MIN = 1;
+export const IDEA_CAP_MAX = 10;
+
+/** The cap to save when the switch flips: off writes 0, on brings back the last non-zero value or 3. */
+export function ideaCapForSwitch(on: boolean, last: number | null | undefined): number {
+ if (!on) return 0;
+ const n = typeof last === 'number' && Number.isFinite(last) ? Math.round(last) : 0;
+ return n >= IDEA_CAP_MIN ? Math.min(IDEA_CAP_MAX, n) : IDEA_CAP_DEFAULT;
+}
+
+/** The settings value, clamped 0–10 (0 allowed here, unlike work-ahead); 3 when missing. */
+export function parseIdeaCap(raw: unknown): number {
+ const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() ? Number(raw) : NaN;
+ if (!Number.isFinite(n)) return IDEA_CAP_DEFAULT;
+ return Math.max(0, Math.min(IDEA_CAP_MAX, Math.round(n)));
+}
+
+// ---- The wobble: one signal, so a drop anywhere (sidebar, /idea, the phone) wobbles the jar icon.
+
+let wobbleSeq = 0;
+const wobblers = new Set<(n: number) => void>();
+export function wobbleJar() {
+ wobbleSeq += 1;
+ wobblers.forEach((f) => f(wobbleSeq));
+}
+/** A key that changes on every drop; put it on the icon's wrapper so the animation restarts. 0 = never. */
+export function useJarWobble(): number {
+ const [n, setN] = useState(0);
+ useEffect(() => {
+ wobblers.add(setN);
+ return () => void wobblers.delete(setN);
+ }, []);
+ return n;
+}
+
+// The last non-zero cap, so turning the switch back on brings it back even after a reload.
+const LAST_CAP_KEY = 'kwant.ideaJarCap.last';
+export function lastIdeaCap(): number | null {
+ try {
+ const v = Number(globalThis.localStorage?.getItem(LAST_CAP_KEY));
+ return Number.isInteger(v) && v >= IDEA_CAP_MIN && v <= IDEA_CAP_MAX ? v : null;
+ } catch {
+ return null;
+ }
+}
+export function rememberIdeaCap(n: number) {
+ if (!(Number.isInteger(n) && n >= IDEA_CAP_MIN && n <= IDEA_CAP_MAX)) return;
+ try {
+ globalThis.localStorage?.setItem(LAST_CAP_KEY, String(n));
+ } catch {
+ // private mode: the switch falls back to 3
+ }
+}
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 282bc78e..f54aa1a7 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -9,6 +9,7 @@ import './styles/modern.css';
import './styles/stream.css';
import './styles/needsYou.css';
import './styles/ideas.css';
+import './styles/ideaShell.css';
registerServiceWorker();
captureInstallPrompt();
diff --git a/frontend/src/nav.ts b/frontend/src/nav.ts
index ec2949b0..b3b0961c 100644
--- a/frontend/src/nav.ts
+++ b/frontend/src/nav.ts
@@ -16,6 +16,7 @@ export type SpaceView =
| { kind: 'board' }
| { kind: 'parallel' }
| { kind: 'dev' }
+ | { kind: 'jar' }
| { kind: 'settings'; scope: 'space'; tab: SpaceSettingsTab }
| { kind: 'settings'; scope: 'app' };
@@ -30,6 +31,8 @@ export function viewSegment(v: SpaceView): string {
return 'parallel';
case 'dev':
return 'dev';
+ case 'jar':
+ return 'jar';
case 'settings':
return v.scope === 'app' ? 'settings/app' : `settings/${v.tab}`;
}
@@ -45,6 +48,8 @@ const LEGACY: Record<string, SpaceView> = {
'mission-board': { kind: 'board' },
missions: { kind: 'board' },
'parallel-universe': { kind: 'parallel' },
+ 'idea-jar': { kind: 'jar' },
+ ideas: { kind: 'jar' },
'app-settings': { kind: 'settings', scope: 'app' },
};
@@ -66,6 +71,7 @@ export function parseView(segment: string): { view: SpaceView; legacy: boolean }
if (head === 'board' && !sub) return { view: { kind: 'board' }, legacy: false };
if (head === 'parallel' && !sub) return { view: { kind: 'parallel' }, legacy: false };
if (head === 'dev' && !sub) return { view: { kind: 'dev' }, legacy: false };
+ if (head === 'jar' && !sub) return { view: { kind: 'jar' }, legacy: false };
if (head === 'settings') {
if (!sub) return { view: { kind: 'settings', scope: 'space', tab: 'general' }, legacy: true };
if (sub === 'app' || sub === 'all') return { view: { kind: 'settings', scope: 'app' }, legacy: sub !== 'app' };
diff --git a/frontend/src/styles/ideaShell.css b/frontend/src/styles/ideaShell.css
new file mode 100644
index 00000000..eaf98499
--- /dev/null
+++ b/frontend/src/styles/ideaShell.css
@@ -0,0 +1,23 @@
+/* Idea jar shell (0.7, Pixel): the jar icon's one wobble after a drop (spec §2.1, §3.4). 160 ms, once,
+ transform only; nothing under reduced motion. */
+@keyframes kwJarWobble {
+ 0%,
+ 100% {
+ transform: rotate(0);
+ }
+ 35% {
+ transform: rotate(-3deg);
+ }
+ 70% {
+ transform: rotate(2deg);
+ }
+}
+.kw-jar-wobble {
+ transform-origin: 50% 100%;
+ animation: kwJarWobble 160ms cubic-bezier(0.2, 0.7, 0.2, 1) 180ms both;
+}
+@media (prefers-reduced-motion: reduce) {
+ .kw-jar-wobble {
+ animation: none;
+ }
+}
diff --git a/frontend/tests/ideaShell.test.mjs b/frontend/tests/ideaShell.test.mjs
new file mode 100644
index 00000000..01c075b9
--- /dev/null
+++ b/frontend/tests/ideaShell.test.mjs
@@ -0,0 +1,213 @@
+// 0.7 Idea jar shell (Pixel): the /idea send answer and blocked lines, the Settings switch's numbers,
+// the jar route, the phone tab bar's violet Jar badge, the sidebar quick-add and the drop toast.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/s1/jar', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'FocusEvent', 'localStorage', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle']) {
+ if (k in dom.window) Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+globalThis.IS_REACT_ACT_ENVIRONMENT = false;
+if (!window.matchMedia) window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export * from './src/ideaShell';
+ export { parseView, viewSegment } from './src/nav';
+ export { PhoneTabBar } from './src/components/PhoneTabBar';
+ export { IdeaJarRow } from './src/components/IdeaJarRow';
+ export { IdeaDropToast } from './src/components/IdeaDropToast';
+`);
+const h = m.React.createElement;
+const settle = async () => { for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); };
+const mount = async (el) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(el);
+ await settle();
+ return { host, done: () => { root.unmount(); host.remove(); } };
+};
+const typeInto = (input, value) => {
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(input, value);
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+};
+const key = (el, k) => el.dispatchEvent(new window.KeyboardEvent('keydown', { key: k, bubbles: true }));
+
+const idea = { id: 'idea_1', space_id: 's1', text: 'A weekly summary of what the team did', status: 'new', created_at: '2026-11-05T10:00:00Z' };
+
+test('/idea send answer: 201 drops, an old server falls back to chat, errors give the spec lines', () => {
+ const ok = m.ideaSendOutcome(201, { handled: 'idea', idea });
+ assert.equal(ok.kind, 'dropped');
+ assert.equal(ok.idea.id, 'idea_1');
+ assert.deepEqual(m.ideaSendOutcome(200, { id: 'msg_1' }), { kind: 'chat' });
+ assert.deepEqual(m.ideaSendOutcome(403, { error: 'forbidden' }), { kind: 'error', line: 'Only you can add ideas.' });
+ assert.deepEqual(m.ideaSendOutcome(400, { error: 'too_long', message: 'Ideas are up to 2,000 characters' }), { kind: 'error', line: 'Ideas are up to 2,000 characters.' });
+ assert.deepEqual(m.ideaSendOutcome(400, { error: 'empty' }), { kind: 'error', line: m.JAR_SEND_FAILED });
+ assert.deepEqual(m.ideaSendOutcome(500, null), { kind: 'error', line: m.JAR_SEND_FAILED });
+ assert.deepEqual(m.ideaSendOutcome(201, { handled: 'idea', idea: null }), { kind: 'error', line: m.JAR_SEND_FAILED });
+ assert.equal(m.JAR_SEND_FAILED, 'Couldn’t drop it in the jar. Try again.');
+});
+
+test('/idea blocked lines: empty, too long, a file; the counter counts only the idea', () => {
+ assert.equal(m.ideaBlockedLine('/idea', 2000), 'Type your idea after /idea');
+ assert.equal(m.ideaBlockedLine('/idea ', 2000), 'Type your idea after /idea');
+ assert.equal(m.ideaBlockedLine(`/idea ${'x'.repeat(2140)}`, 2000), '2,140 / 2,000 · too long for the jar');
+ assert.equal(m.ideaBlockedLine('/idea a faster search', 2000, true), 'Ideas are text only. Remove the file to drop it in.');
+ assert.equal(m.ideaBlockedLine('/IDEA a faster search', 2000), null);
+ assert.equal(m.ideaLength('/idea hello'), 5);
+});
+
+test('Settings switch: off writes 0, on brings back the last value or 3; the read clamps to 0–10', () => {
+ assert.equal(m.ideaCapForSwitch(false, 5), 0);
+ assert.equal(m.ideaCapForSwitch(true, 5), 5);
+ assert.equal(m.ideaCapForSwitch(true, 0), 3);
+ assert.equal(m.ideaCapForSwitch(true, null), 3);
+ assert.equal(m.ideaCapForSwitch(true, 40), 10);
+ assert.equal(m.parseIdeaCap(0), 0);
+ assert.equal(m.parseIdeaCap(undefined), 3);
+ assert.equal(m.parseIdeaCap('7'), 7);
+ assert.equal(m.parseIdeaCap(99), 10);
+ assert.equal(m.parseIdeaCap(-2), 0);
+ m.rememberIdeaCap(6);
+ assert.equal(m.lastIdeaCap(), 6);
+});
+
+test('Route: /s/:id/jar parses and round-trips; older names land on the jar', () => {
+ assert.deepEqual(m.parseView('jar'), { view: { kind: 'jar' }, legacy: false });
+ assert.equal(m.viewSegment({ kind: 'jar' }), 'jar');
+ assert.deepEqual(m.parseView('ideas').view, { kind: 'jar' });
+ assert.equal(m.parseView('ideas').legacy, true);
+});
+
+test('Phone tab bar: five tabs make five columns, and the Jar badge is violet and says takes ready', () => {
+ const html = m.renderToStaticMarkup(h(m.PhoneTabBar, {
+ label: 'Demo sections', active: 'chats', onSelect: () => {},
+ tabs: [
+ { id: 'chats', label: 'Chats', icon: null },
+ { id: 'bots', label: 'Bots', icon: null },
+ { id: 'jar', label: 'Jar', icon: null, badge: 2, badgeTone: 'violet', badgeNoun: 'takes ready' },
+ { id: 'inbox', label: 'Inbox', icon: null, badge: 1 },
+ { id: 'space', label: 'Space', icon: null },
+ ],
+ }));
+ assert.match(html, /grid-cols-5/);
+ assert.match(html, /aria-label="Jar, 2 takes ready"/);
+ assert.match(html, /aria-label="Inbox, 1 waiting"/);
+ assert.match(html, /data-tone="violet"[^>]*class="[^"]*bg-\[#8b7bff\]/);
+});
+
+test('Sidebar quick-add: + opens the field, Enter drops and stays open, Esc closes and refocuses +', async () => {
+ const dropped = [];
+ const { host, done } = await mount(h(m.IdeaJarRow, { active: false, count: 2, onOpen: () => {}, onDrop: async (t) => { dropped.push(t); }, className: 'row' }));
+ assert.equal(host.querySelector('[data-jar-badge]').textContent.replace(/\s+/g, ' ').trim(), '2 takes ready');
+ const plus = host.querySelector('[data-jar-add]');
+ assert.equal(plus.getAttribute('aria-label'), 'Drop an idea in the jar');
+ plus.click();
+ await settle();
+ let input = host.querySelector('[data-jar-quick-input]');
+ assert.ok(input, 'the field opens');
+ assert.equal(plus.getAttribute('aria-expanded'), 'true');
+ typeInto(input, 'A faster way to find old chats');
+ await settle();
+ host.querySelector('[data-jar-quick-add]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.deepEqual(dropped, ['A faster way to find old chats']);
+ input = host.querySelector('[data-jar-quick-input]');
+ assert.ok(input, 'stays open for the next idea');
+ assert.equal(input.value, '');
+ key(input, 'Escape');
+ await settle();
+ assert.equal(host.querySelector('[data-jar-quick-input]'), null, 'Esc closes it');
+ assert.equal(document.activeElement, plus, 'and focus goes back to +');
+ done();
+});
+
+test('Drop toast: says Dropped in the jar, Undo calls back, then reads Taken back out', async () => {
+ let undone = 0;
+ const { host, done } = await mount(h(m.IdeaDropToast, { state: 'dropped', onUndo: () => { undone += 1; }, onOpenJar: () => {}, onClose: () => {} }));
+ const box = host.querySelector('[data-idea-toast] [role="status"]');
+ assert.equal(box.getAttribute('role'), 'status');
+ assert.match(box.textContent, /Dropped in the jar/);
+ host.querySelector('[data-idea-undo]').click();
+ assert.equal(undone, 1);
+ assert.ok(host.querySelector('[data-idea-open-jar]'));
+ done();
+ const after = await mount(h(m.IdeaDropToast, { state: 'undone', onUndo: () => {}, onClose: () => {} }));
+ assert.match(after.host.textContent, /Taken back out/);
+ after.done();
+});
+
+test('Drop toast keyboard (round 2): Undo stays focusable while undoing, focus returns to the composer, phone targets are 44 px', async () => {
+ const composer = document.createElement('textarea');
+ document.body.appendChild(composer);
+ let undone = 0;
+ let back = 0;
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ const props = { onUndo: () => { undone += 1; }, onOpenJar: () => {}, onClose: () => {}, onReturnFocus: () => { back += 1; composer.focus(); } };
+ root.render(h(m.IdeaDropToast, { ...props, state: 'dropped' }));
+ await settle();
+ const undo = host.querySelector('[data-idea-undo]');
+ assert.match(undo.className, /min-h-\[44px\] sm:min-h-\[36px\]/);
+ assert.match(host.querySelector('[data-idea-open-jar]').className, /min-h-\[44px\] sm:min-h-\[36px\]/);
+ assert.match(host.querySelector('[aria-label="Close"]').className, /min-w-\[44px\] min-h-\[44px\] sm:min-w-0 sm:min-h-0/);
+ undo.focus();
+ root.render(h(m.IdeaDropToast, { ...props, state: 'undoing' }));
+ await settle();
+ const busy = host.querySelector('[data-idea-undo]');
+ assert.equal(busy.disabled, false);
+ assert.equal(busy.getAttribute('aria-disabled'), 'true');
+ assert.equal(document.activeElement, busy);
+ busy.click();
+ assert.equal(undone, 0, 'a press while undoing is ignored');
+ root.render(h(m.IdeaDropToast, { ...props, state: 'undone' }));
+ await settle();
+ assert.equal(back, 1);
+ assert.equal(document.activeElement, composer);
+ // Focus elsewhere (the person moved on): the toast leaves it alone.
+ const other = document.createElement('input');
+ document.body.appendChild(other);
+ other.focus();
+ root.render(h(m.IdeaDropToast, { ...props, state: 'dropped', key: 'b' }));
+ await settle();
+ root.render(h(m.IdeaDropToast, { ...props, state: 'undo_failed', key: 'b' }));
+ await settle();
+ assert.equal(back, 1);
+ assert.equal(document.activeElement, other);
+ // Close from inside the toast hands focus back too.
+ host.querySelector('[aria-label="Close"]').focus();
+ host.querySelector('[aria-label="Close"]').click();
+ assert.equal(back, 2);
+ assert.equal(document.activeElement, composer);
+ root.unmount();
+ host.remove();
+ composer.remove();
+ other.remove();
+});
+
+test('Open jar (round 2): App focuses the jar quick-add after showPage, and ignores Undo unless dropped', () => {
+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(app, /showPage\('jar'\);\s*focusJarQuickAdd\(\);/);
+ assert.match(app, /\[data-quick-add="hero"\] input, \[data-quick-add="phone"\] input/);
+ assert.match(app, /if \(ideaToast\.state !== 'dropped'\) return;/);
+ assert.match(app, /onReturnFocus=\{\(\) => document\.querySelector<HTMLElement>\('\[data-composer\]'\)\?\.focus\(\)\}/);
+});
+
+test('Wiring: App catches idea_updated, skips the bubble for /idea; ChatView dresses the field', () => {
+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(app, /case 'idea_updated':[\s\S]{0,60}emitIdeaUpdated\(event\.data\)/);
+ assert.match(app, /isIdeaCommand\(text\) && !attachments\.length/);
+ const chat = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');
+ assert.match(chat, /aria-label="Drop in the jar"/);
+ assert.match(chat, /Goes in the idea jar, not to/);
+ assert.match(chat, /Drop an idea in the jar/);
+ const settings = readFileSync(new URL('../src/components/SettingsModal.tsx', import.meta.url), 'utf8');
+ assert.match(settings, /idea_jar_daily_cap/);
+});