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.

Frontend: a team from your own words (#545)

Oleksandr Ivanchenkoaac29623699a
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index e50557eb..a2403d2f 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -64,12 +64,13 @@ 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 } from 'lucide-react';
+import { Bot, HelpCircle, Inbox, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
import { TG_EVENT, TelegramEventDetail, forThisSpace } from './telegram';
import { ChatApproval, OpenChat, addSettled, settledFromRecords, withdrawApproval, approvalFromEvent, lateAnswerText, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
import type { AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
import { ReadyTeamsProvider, TeamNeedsTop, type ReadyTeam } from './components/ReadyTeams';
+import { SpaceReadyCard } from './components/SpaceReadyCard';
import { NewChannelModal } from './components/NewChannelModal';
import type { NewChannelBody } from './channels';
import { ManageTeamModal } from './components/ManageTeamModal';
@@ -3770,81 +3771,18 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
/>
) : null;
const setupChecklist = (
- <main className="flex-1 min-w-0 overflow-y-auto flex items-start sm:items-center justify-center p-4 sm:p-8" data-space-checklist>
- <div className="w-full max-w-md rounded-2xl border border-zinc-800 bg-zinc-900/60 p-5 sm:p-6 space-y-4">
- <div className="flex items-center gap-3">
- <SpaceTile space={space} size={40} />
- <div className="min-w-0">
- <h1 className="text-base font-semibold text-zinc-100 truncate">Get {space.name} ready</h1>
- <p className="text-xs text-zinc-400">Bots, teams and accounts here stay in {space.name}.</p>
- </div>
- </div>
- <ol className="space-y-2">
- {[
- readyAccounts > 0
- ? {
- done: true,
- // Still offered once This machine is ready: more accounts and API keys go here too.
- keepAction: true,
- title: readyAccounts === 1 ? '1 account ready' : `${readyAccounts} accounts ready`,
- detail: 'Add another Claude, Codex or Grok sign-in, or an API key.',
- action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: () => openSpaceSettings('apps', 'accounts') },
- }
- : {
- done: false,
- title: 'Add an account',
- detail: 'Sign in with Claude, Codex or Grok, add an API key, or use this machine.',
- action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: () => openSpaceSettings('apps', 'accounts') },
- },
- {
- done: kwants.length > 0,
- title: 'Add your first bot',
- detail: `${space.name}'s #general opens with it.`,
- action: {
- label: 'New bot',
- icon: <Bot size={13} />,
- onClick: () => {
- setNewAgentTeam(null);
- setIsNewAgentOpen(true);
- playSfx('click');
- },
- },
- },
- { done: false, title: 'Message #general', detail: `Laya picks who answers, only from ${space.name}'s bots.` },
- ].map((step: { done: boolean; keepAction?: boolean; title: string; detail: string; action?: { label: string; icon: React.ReactNode; onClick: () => void } }, i) => (
- <li key={step.title} className="flex items-start gap-3 rounded-xl border border-zinc-800 bg-zinc-950/50 p-3">
- <span
- className={`mt-0.5 w-5 h-5 shrink-0 rounded-full flex items-center justify-center text-[11px] font-semibold ${
- step.done ? 'bg-emerald-500 text-zinc-950' : 'bg-zinc-800 text-zinc-300'
- }`}
- aria-hidden="true"
- >
- {step.done ? <Check size={12} /> : i + 1}
- </span>
- <span className="flex-1 min-w-0">
- <span className={`block text-xs font-medium ${step.done ? (step.keepAction ? 'text-zinc-300' : 'text-zinc-400 line-through') : 'text-zinc-100'}`}>
- {step.title}
- {step.done && <span className="sr-only"> (done)</span>}
- </span>
- <span className="block text-[11px] text-zinc-500">{step.detail}</span>
- </span>
- {step.action && (!step.done || step.keepAction) && (
- <button
- type="button"
- onClick={step.action.onClick}
- className={`shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] font-medium focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-300 ${
- step.done ? 'text-zinc-200 border border-zinc-700 hover:border-sky-500/50 hover:text-sky-200' : 'text-white bg-sky-600 hover:bg-sky-500'
- }`}
- >
- {step.action.icon}
- {step.action.label}
- </button>
- )}
- </li>
- ))}
- </ol>
- </div>
- </main>
+ <SpaceReadyCard
+ spaceName={space.name}
+ tile={<SpaceTile space={space} size={40} />}
+ readyAccounts={readyAccounts}
+ botCount={kwants.length}
+ onAddAccount={() => openSpaceSettings('apps', 'accounts')}
+ onNewBot={() => {
+ setNewAgentTeam(null);
+ setIsNewAgentOpen(true);
+ playSfx('click');
+ }}
+ />
);
// H5: every bot in the one attention order. Not computed until the Inbox's first fetch lands, so the
@@ -4351,6 +4289,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onChanged={refreshRoster}
onOpenTeam={(t, channelId) => void openNewTeamChat(t, channelId)}
onUndone={handleTeamUndone}
+ readyAccounts={readyAccounts}
+ onOpenAccounts={() => openSpaceSettings('apps', 'accounts')}
>
{/* overflow: clip, not just hidden: a hidden box can still be scrolled from script (scrollIntoView), which
once slid the whole chat under its header (P1-7). Browsers without clip keep hidden. */}
diff --git a/frontend/src/components/NewTeamModal.tsx b/frontend/src/components/NewTeamModal.tsx
index cd6c102a..63caf2d2 100644
--- a/frontend/src/components/NewTeamModal.tsx
+++ b/frontend/src/components/NewTeamModal.tsx
@@ -6,6 +6,7 @@ import { Kwant, Team } from './Sidebar';
import { FolderBrowserModal } from './FolderBrowserModal';
import { playSfx } from '../audio/chiptune';
import { ReadyTeamsTiles, SuggestMembersButton } from './ReadyTeamsEntry';
+import { TeamNeedBox } from './TeamNeedBox';
export interface NewTeamModalProps {
isOpen: boolean;
@@ -220,6 +221,17 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({
</div>
)}
+ <TeamNeedBox
+ label="Describe what this team should do"
+ onHide={() => setHidden(true)}
+ onShow={() => setHidden(false)}
+ onDone={() => {
+ setHidden(false);
+ onClose();
+ }}
+ onLeave={onClose}
+ />
+
<ReadyTeamsTiles
source={{
workspace_path: workspaceType === 'local' ? workspacePath.trim() || undefined : undefined,
diff --git a/frontend/src/components/ReadyTeams.tsx b/frontend/src/components/ReadyTeams.tsx
index c70c74a5..1e993ab8 100644
--- a/frontend/src/components/ReadyTeams.tsx
+++ b/frontend/src/components/ReadyTeams.tsx
@@ -2,8 +2,13 @@
// preview sheet from any entry point (welcome, New team, sidebar, Manage team), shows the Created toast
// and runs Undo. `TeamNeedsTop` is the Needs card at the top of a template team's chat (Q-T5: a client
// overlay built from live state, not a message). Design: next-077/design/design.md §T, §D. API: api.md.
-import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
+import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { Sparkles, X } from 'lucide-react';
import { TeamPreviewSheet, type SheetMode } from './TeamPreviewSheet';
+import { TeamNeedBox } from './TeamNeedBox';
+import { useEscapeLayer } from '../escape';
+import { useMedia } from '../useMedia';
+import { PHONE_QUERY } from '../layout';
import { TeamCreatedLine, TeamCreatedToast, TeamNeedsCard, UndoTeamConfirm } from './TeamNeedsCard';
import { openForgeConnect, openGitHubConnect } from './GitHubConnect';
import { FolderBrowserModal } from './FolderBrowserModal';
@@ -119,6 +124,16 @@ interface ReadyTeamsValue {
open: (mode: SheetMode, opts?: OpenOpts) => void;
made: (teamId: string) => MadeTeam | null;
undo: (team: ReadyTeam) => void;
+ /** Accounts in this space that can run now (`space.counts.ready_accounts`); 0 turns Suggest a team into "Add an AI account first". */
+ readyAccounts: number;
+ openAccounts?: () => void;
+ /** The words typed into any "Describe your own" box, kept across entry points, cancels and errors. */
+ needDraft: string;
+ setNeedDraft: (v: string) => void;
+ /** "Describe your own": focus the Get ready card's box, or open the box in a small sheet. */
+ describe: () => void;
+ /** The Get ready card's box registers its focus; returns the unregister. */
+ registerNeedBox: (focus: () => void) => () => void;
}
const Ctx = createContext<ReadyTeamsValue | null>(null);
@@ -136,11 +151,15 @@ export interface ReadyTeamsProviderProps {
onOpenTeam: (team: CreatedTeam['team'], channelId: string) => void;
/** Undo answered 200: the team and its chat are gone on the server; drop them from the lists now. */
onUndone?: (team: ReadyTeam) => void;
+ /** Accounts that can run now; undefined is read as "some" (an older caller). */
+ readyAccounts?: number;
+ /** Opens Space settings › Accounts. */
+ onOpenAccounts?: () => void;
/** Message count of a team's chat, for the Undo confirm; the server's count wins when it answers. */
children: React.ReactNode;
}
-export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, bots, teams, onChanged, onOpenTeam, onUndone, children }) => {
+export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, bots, teams, onChanged, onOpenTeam, onUndone, readyAccounts, onOpenAccounts, children }) => {
const [templates, setTemplates] = useState<TeamTemplate[] | null>(() => cache.get(space) ?? null);
const [templatesError, setTemplatesError] = useState(false);
const [available, setAvailable] = useState(true);
@@ -280,7 +299,7 @@ export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, b
[made, runUndo, templates, space],
);
- const onCreated = (r: CreatedTeam, _t: TeamTemplate, handle: string) => {
+ const onCreated = (r: CreatedTeam, _t: TeamTemplate | null, handle: string) => {
const m: MadeTeam = { templateId: r.template_id, handle, createdAt: Date.now(), actionId: r.action_id, undoUntil: Date.parse(r.undo_until) || Date.now() + 86_400_000 };
remember(r.team.id, m);
setMade((x) => ({ ...x, [r.team.id]: m }));
@@ -297,7 +316,27 @@ export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, b
setToast((x) => ({ text, team: { id: r.team.id, name: handle }, n: (x?.n ?? 0) + 1 }));
};
- const value = useMemo<ReadyTeamsValue>(() => ({ space, templates, available, open, made: madeOf, undo }), [space, templates, available, open, madeOf, undo]);
+ // ---- a team from your own words
+ const [needDraft, setNeedDraft] = useState('');
+ const [needSheet, setNeedSheet] = useState(false);
+ const needBox = useRef<(() => void) | null>(null);
+ useEffect(() => setNeedDraft(''), [space]);
+ const registerNeedBox = useCallback((focus: () => void) => {
+ needBox.current = focus;
+ return () => {
+ if (needBox.current === focus) needBox.current = null;
+ };
+ }, []);
+ const describe = useCallback(() => {
+ if (needBox.current) needBox.current();
+ else setNeedSheet(true);
+ }, []);
+ const ready = readyAccounts ?? 1;
+
+ const value = useMemo<ReadyTeamsValue>(
+ () => ({ space, templates, available, open, made: madeOf, undo, readyAccounts: ready, openAccounts: onOpenAccounts, needDraft, setNeedDraft, describe, registerNeedBox }),
+ [space, templates, available, open, madeOf, undo, ready, onOpenAccounts, needDraft, describe, registerNeedBox],
+ );
return (
<Ctx.Provider value={value}>
@@ -320,6 +359,13 @@ export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, b
cb?.();
}}
onCreated={onCreated}
+ onOpenAccounts={
+ onOpenAccounts &&
+ (() => {
+ setSheet(null);
+ onOpenAccounts();
+ })
+ }
onPickFolder={() => void pickFolder()}
onUseCoding={() => setSheet((s) => s && { mode: { kind: 'template', templateId: 'coding' }, opts: s.opts, n: s.n + 1 })}
onConnectForge={(url, forge) => {
@@ -328,6 +374,13 @@ export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, b
}}
/>
)}
+ {needSheet && (
+ <NeedSheet
+ onClose={() => setNeedSheet(false)}
+ onHide={() => setNeedSheet(false)}
+ onShow={() => setNeedSheet(true)}
+ />
+ )}
{/* Above the sheet (z-70): FolderBrowserModal is z-50 on its own. */}
<div className="relative z-[80]">
<FolderBrowserModal isOpen={browsing} initialPath="" onClose={() => setBrowsing(false)} onSelectPath={(p) => { setBrowsing(false); readFolder(p); }} />
@@ -366,6 +419,53 @@ export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, b
);
};
+// ---------------------------------------------------------------------------------------------------
+// "Describe your own" when the Get ready card isn't on screen: the same box in a small dialog
+// (desktop) or bottom sheet (phone). It hides while the preview is open and comes back on Cancel.
+
+const NeedSheet: React.FC<{ onClose: () => void; onHide: () => void; onShow: () => void }> = ({ onClose, onHide, onShow }) => {
+ const phone = useMedia(PHONE_QUERY);
+ const root = useRef<HTMLDivElement>(null);
+ const titleId = React.useId();
+ useEscapeLayer(root, true, onClose, { modal: true });
+ return (
+ <div className={`fixed inset-0 z-[70] ${phone ? '' : 'grid place-items-center p-6'} bg-[rgb(6_3_20/.62)]`} onClick={onClose} data-need-sheet-scrim>
+ <div
+ ref={root}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ tabIndex={-1}
+ data-need-sheet
+ onClick={(e) => e.stopPropagation()}
+ className={
+ phone
+ ? 'absolute inset-x-0 bottom-0 max-h-[92%] overflow-y-auto rounded-t-2xl bg-zinc-900 border-t border-zinc-800 px-4 pt-3 pb-[max(16px,env(safe-area-inset-bottom))] outline-none animate-[t-sheet_200ms_ease-out] motion-reduce:animate-none'
+ : 'w-[480px] max-w-[calc(100vw-32px)] rounded-2xl bg-zinc-900 border border-zinc-800 p-5 shadow-[0_25px_50px_-12px_rgb(0_0_0/.6)] outline-none animate-[t-rise_180ms_ease-out] motion-reduce:animate-none'
+ }
+ >
+ <div className="flex items-center gap-3 mb-3">
+ <span aria-hidden="true" className="w-8 h-8 rounded-[9px] shrink-0 grid place-items-center bg-sky-400/15 text-sky-400 ring-1 ring-inset ring-sky-300/20">
+ <Sparkles size={16} />
+ </span>
+ <h3 id={titleId} className="flex-1 min-w-0 text-[15px] font-semibold text-zinc-50">
+ Describe your own team
+ </h3>
+ <button
+ type="button"
+ aria-label="Close"
+ onClick={onClose}
+ className={`${phone ? 'w-11 h-11' : 'w-8 h-8'} shrink-0 grid place-items-center rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-white/5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400`}
+ >
+ <X size={16} aria-hidden="true" />
+ </button>
+ </div>
+ <TeamNeedBox label="What should your bots do?" autoFocus onHide={onHide} onShow={onShow} onLeave={onClose} />
+ </div>
+ </div>
+ );
+};
+
// ---------------------------------------------------------------------------------------------------
// The Needs card's live state (Q-T5): no polling and no model call. It reads once, then again when the
// window gets focus back or `refreshKey` changes (Settings closed, a connection or source changed).
diff --git a/frontend/src/components/ReadyTeamsEntry.tsx b/frontend/src/components/ReadyTeamsEntry.tsx
index c4d3462c..c27798ab 100644
--- a/frontend/src/components/ReadyTeamsEntry.tsx
+++ b/frontend/src/components/ReadyTeamsEntry.tsx
@@ -56,6 +56,7 @@ export const ReadyTeamsSidebarBox: React.FC<{ teamCount: number }> = ({ teamCoun
<TemplateSidebarBox
templates={rt.templates}
onPick={(id) => rt.open({ kind: 'template', templateId: id })}
+ onDescribe={rt.describe}
onHide={() => {
hideReadyTeams(rt.space);
setHidden(true);
diff --git a/frontend/src/components/SpaceReadyCard.tsx b/frontend/src/components/SpaceReadyCard.tsx
new file mode 100644
index 00000000..81c35b4f
--- /dev/null
+++ b/frontend/src/components/SpaceReadyCard.tsx
@@ -0,0 +1,136 @@
+// "Get {space} ready": the card on an empty space (no bots yet). Step 2 is "Add your bots": say what
+// they should do and get a team suggested (team-from-words brief, "Entry points"), or start from a
+// ready-made team, or add one bot. On a server without the team routes, step 2 is the plain New bot.
+import React from 'react';
+import { Bot, Check, KeyRound } from 'lucide-react';
+import { useReadyTeams } from './ReadyTeams';
+import { TeamNeedBox } from './TeamNeedBox';
+
+const FOCUS = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-300';
+
+export interface SpaceReadyCardProps {
+ spaceName: string;
+ /** The space's tile, drawn by the caller. */
+ tile: React.ReactNode;
+ readyAccounts: number;
+ botCount: number;
+ onAddAccount: () => void;
+ onNewBot: () => void;
+}
+
+interface Step {
+ done: boolean;
+ keepAction?: boolean;
+ title: string;
+ detail?: string;
+ action?: { label: string; icon: React.ReactNode; onClick: () => void };
+ body?: React.ReactNode;
+}
+
+export const SpaceReadyCard: React.FC<SpaceReadyCardProps> = ({ spaceName, tile, readyAccounts, botCount, onAddAccount, onNewBot }) => {
+ const rt = useReadyTeams();
+ const words = !!rt?.available;
+ const picks = rt?.templates ?? [];
+ const quiet = `inline rounded text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline ${FOCUS}`;
+
+ const botsStep: Step = words
+ ? {
+ done: botCount > 0,
+ title: 'Add your bots',
+ body: (
+ <div className="mt-2 space-y-2.5">
+ <TeamNeedBox label="What should your bots do?" register />
+ {/* flex-wrap: on a touch phone each link is a 44 px target, so wrapped rows stay even. */}
+ <p className="flex flex-wrap items-center gap-x-1 text-[11.5px] leading-[18px] text-zinc-400" data-ready-made-line>
+ <span className="basis-full">Or start from a ready-made team:</span>
+ {picks.map((t) => (
+ <React.Fragment key={t.id}>
+ <button type="button" data-template={t.id} onClick={() => rt!.open({ kind: 'template', templateId: t.id })} className={quiet}>
+ {t.label}
+ </button>
+ <span aria-hidden="true"> · </span>
+ </React.Fragment>
+ ))}
+ <span>or </span>
+ <button type="button" data-new-bot onClick={onNewBot} className={quiet}>
+ add one bot
+ </button>
+ </p>
+ </div>
+ ),
+ }
+ : {
+ done: botCount > 0,
+ title: 'Add your first bot',
+ detail: `${spaceName}'s #general opens with it.`,
+ action: { label: 'New bot', icon: <Bot size={13} />, onClick: onNewBot },
+ };
+
+ const steps: Step[] = [
+ readyAccounts > 0
+ ? {
+ done: true,
+ // Still offered once This machine is ready: more accounts and API keys go here too.
+ keepAction: true,
+ title: readyAccounts === 1 ? '1 account ready' : `${readyAccounts} accounts ready`,
+ detail: 'Add another Claude, Codex or Grok sign-in, or an API key.',
+ action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: onAddAccount },
+ }
+ : {
+ done: false,
+ title: 'Add an account',
+ detail: 'Sign in with Claude, Codex or Grok, add an API key, or use this machine.',
+ action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: onAddAccount },
+ },
+ botsStep,
+ { done: false, title: 'Message #general', detail: `Laya picks who answers, only from ${spaceName}'s bots.` },
+ ];
+
+ return (
+ <main className="flex-1 min-w-0 overflow-y-auto flex items-start sm:items-center justify-center p-4 sm:p-8" data-space-checklist>
+ <div className="w-full max-w-md rounded-2xl border border-zinc-800 bg-zinc-900/60 p-5 sm:p-6 space-y-4">
+ <div className="flex items-center gap-3">
+ {tile}
+ <div className="min-w-0">
+ <h1 className="text-base font-semibold text-zinc-100 truncate">Get {spaceName} ready</h1>
+ <p className="text-xs text-zinc-400">Bots, teams and accounts here stay in {spaceName}.</p>
+ </div>
+ </div>
+ <ol className="space-y-2">
+ {steps.map((step, i) => (
+ <li key={step.title} className="flex items-start gap-3 rounded-xl border border-zinc-800 bg-zinc-950/50 p-3" data-step={i + 1}>
+ <span
+ className={`mt-0.5 w-5 h-5 shrink-0 rounded-full flex items-center justify-center text-[11px] font-semibold ${
+ step.done ? 'bg-emerald-500 text-zinc-950' : 'bg-zinc-800 text-zinc-300'
+ }`}
+ aria-hidden="true"
+ >
+ {step.done ? <Check size={12} /> : i + 1}
+ </span>
+ <span className="flex-1 min-w-0">
+ <span className={`block text-xs font-medium ${step.done ? (step.keepAction ? 'text-zinc-300' : 'text-zinc-400 line-through') : 'text-zinc-100'}`}>
+ {step.title}
+ {step.done && <span className="sr-only"> (done)</span>}
+ </span>
+ {step.detail && <span className="block text-[11px] text-zinc-500">{step.detail}</span>}
+ {step.body}
+ </span>
+ {step.action && (!step.done || step.keepAction) && (
+ <button
+ type="button"
+ onClick={step.action.onClick}
+ className={`shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] font-medium ${FOCUS} ${
+ step.done ? 'text-zinc-200 border border-zinc-700 hover:border-sky-500/50 hover:text-sky-200' : 'text-white bg-sky-600 hover:bg-sky-500'
+ }`}
+ >
+ {step.action.icon}
+ {step.action.label}
+ </button>
+ )}
+ </li>
+ ))}
+ </ol>
+ </div>
+ </main>
+ );
+};
diff --git a/frontend/src/components/TeamNeedBox.tsx b/frontend/src/components/TeamNeedBox.tsx
new file mode 100644
index 00000000..9871743a
--- /dev/null
+++ b/frontend/src/components/TeamNeedBox.tsx
@@ -0,0 +1,233 @@
+// A team from your own words (team-from-words brief, "Entry points" and "Flow"). The person says what
+// their bots should do; Suggest a team asks the server (`POST /api/teams/suggest` with `{ need }`) and
+// opens the preview sheet on the answer. Nothing is created before Create in the sheet. The same box
+// sits in the Get ready card, the sidebar's "Describe your own" sheet and New team; the typed words are
+// shared through the ReadyTeams provider, so they survive a cancel, an error or a switch of entry point.
+import React, { useEffect, useId, useRef, useState } from 'react';
+import { Loader2, Sparkles } from 'lucide-react';
+import { useReadyTeams } from './ReadyTeams';
+import { useMedia } from '../useMedia';
+import { PHONE_QUERY } from '../layout';
+import { NEED_PLACEHOLDER, needError, needProblem, teamsApi } from '../teams/teamTemplates';
+
+const FOCUS = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+
+export interface TeamNeedBoxProps {
+ label: string;
+ /** The Get ready card's box: the sidebar's "Describe your own" focuses it instead of opening a sheet. */
+ register?: boolean;
+ autoFocus?: boolean;
+ /** New team and the small sheet hide themselves while the preview is open… */
+ onHide?: () => void;
+ /** …come back when it's cancelled… */
+ onShow?: () => void;
+ /** …and close after a create. */
+ onDone?: () => void;
+ /** Called before "Add an AI account first" opens Accounts (the small sheet closes itself). */
+ onLeave?: () => void;
+ className?: string;
+}
+
+type Phase = 'idle' | 'suggesting';
+
+export const TeamNeedBox: React.FC<TeamNeedBoxProps> = ({ label, register, autoFocus, onHide, onShow, onDone, onLeave, className = '' }) => {
+ const rt = useReadyTeams();
+ const phone = useMedia(PHONE_QUERY);
+ const id = useId();
+ const ta = useRef<HTMLTextAreaElement>(null);
+ const [phase, setPhase] = useState<Phase>('idle');
+ const [slow, setSlow] = useState(false);
+ const [problem, setProblem] = useState<string | null>(null);
+ const [err, setErr] = useState<ReturnType<typeof needError> | null>(null);
+ const [live, setLive] = useState('');
+ /** Each ask gets a number; Cancel moves it on, so a late answer is dropped. */
+ const seq = useRef(0);
+ const local = useState('');
+ const value = rt ? rt.needDraft : local[0];
+ const setValue = rt ? rt.setNeedDraft : local[1];
+
+ const focusBox = () => {
+ const el = ta.current;
+ if (!el) return;
+ el.scrollIntoView?.({ block: 'center', behavior: 'auto' });
+ el.focus({ preventScroll: true });
+ };
+ useEffect(() => {
+ if (!register || !rt) return;
+ return rt.registerNeedBox(focusBox);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [register, rt?.registerNeedBox]);
+ useEffect(() => {
+ if (autoFocus) requestAnimationFrame(() => ta.current?.focus({ preventScroll: true }));
+ }, [autoFocus]);
+ useEffect(() => {
+ if (phase !== 'suggesting') return;
+ const t = window.setTimeout(() => setSlow(true), 8000);
+ return () => window.clearTimeout(t);
+ }, [phase]);
+ useEffect(() => () => void (seq.current += 1), []);
+
+ if (!rt?.available) return null;
+ const busy = phase === 'suggesting';
+ const noAccount = rt.readyAccounts === 0 || !!err?.noAccount;
+
+ const cancel = () => {
+ seq.current += 1;
+ // Decisions 11-12 §2: stop the server's ask too, not only stop listening for it.
+ teamsApi.cancelSuggest(rt.space);
+ setPhase('idle');
+ setSlow(false);
+ setLive('Stopped. Your words are kept.');
+ focusBox();
+ };
+
+ const submit = async () => {
+ if (busy) return;
+ if (noAccount) {
+ onLeave?.();
+ return rt.openAccounts?.();
+ }
+ const p = needProblem(value);
+ setProblem(p);
+ if (p) {
+ setLive(p);
+ return focusBox();
+ }
+ const need = value.trim();
+ const n = ++seq.current;
+ setErr(null);
+ setSlow(false);
+ setPhase('suggesting');
+ setLive('Suggesting a team');
+ try {
+ const s = await teamsApi.suggest({ space: rt.space, need }, 'need');
+ if (seq.current !== n) return;
+ setPhase('idle');
+ setLive('');
+ onHide?.();
+ rt.open(
+ { kind: 'suggest', need, initial: s },
+ {
+ onCancel: () => {
+ onShow?.();
+ requestAnimationFrame(focusBox);
+ },
+ onDone: () => {
+ setValue('');
+ onDone?.();
+ },
+ },
+ );
+ } catch (e) {
+ if (seq.current !== n) return;
+ const ne = needError(e);
+ setErr(ne);
+ setPhase('idle');
+ // The alert below reads it out; the polite line stays quiet so it isn't said twice.
+ setLive('');
+ focusBox();
+ }
+ };
+
+ const hintId = `${id}-hint`;
+ const errId = `${id}-err`;
+ const hint = busy
+ ? slow
+ ? 'Usually under a minute.'
+ : 'Drafting a team from your words.'
+ : noAccount
+ ? 'Suggest a team needs an AI account that can run. Your words are kept.'
+ : phone
+ ? 'Nothing is made until you create it.'
+ : 'Enter to suggest · Shift+Enter for a new line. Nothing is made until you create it.';
+ const btnH = phone ? 'h-11' : 'h-9';
+
+ return (
+ <div
+ data-need-box
+ className={`min-w-0 ${className}`}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape' && busy) {
+ // Escape stops the ask; the dialog around stays (escape.ts layers respect preventDefault).
+ e.preventDefault();
+ e.stopPropagation();
+ cancel();
+ }
+ }}
+ >
+ <label htmlFor={`${id}-ta`} className="block text-[13px] font-medium text-zinc-200 mb-1.5">
+ {label}
+ </label>
+ <textarea
+ ref={ta}
+ id={`${id}-ta`}
+ rows={3}
+ value={value}
+ placeholder={NEED_PLACEHOLDER}
+ readOnly={busy}
+ aria-busy={busy || undefined}
+ aria-invalid={!!problem || undefined}
+ aria-describedby={`${hintId}${problem || err ? ` ${errId}` : ''}`}
+ onChange={(e) => {
+ setValue(e.target.value);
+ if (problem) setProblem(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key !== 'Enter' || e.shiftKey || e.nativeEvent.isComposing) return;
+ e.preventDefault();
+ if (!noAccount) void submit();
+ }}
+ className={`block w-full min-h-[84px] max-md:min-h-[104px] max-h-[220px] resize-y rounded-lg border bg-zinc-950/60 px-3 py-2 text-sm leading-5 text-zinc-50 placeholder:text-zinc-500 outline-none ${
+ problem ? 'border-amber-300/70' : 'border-zinc-700 focus:border-sky-400'
+ } ${busy ? 'opacity-70' : ''}`}
+ />
+ <div className={`mt-2 flex ${phone ? 'flex-col items-stretch' : 'flex-wrap items-center'} gap-2`}>
+ <button
+ type="button"
+ onClick={() => void submit()}
+ aria-disabled={busy || undefined}
+ data-need-submit
+ className={`${btnH} inline-flex items-center justify-center gap-1.5 px-4 rounded-lg text-sm font-medium ${
+ noAccount && !busy ? 'border border-sky-300/40 text-sky-200 hover:bg-sky-300/10' : 'bg-sky-600 hover:bg-sky-500 text-white'
+ } aria-disabled:opacity-70 aria-disabled:cursor-progress ${FOCUS}`}
+ >
+ {busy ? (
+ <>
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ Suggesting…
+ </>
+ ) : noAccount ? (
+ 'Add an AI account first'
+ ) : (
+ <>
+ <Sparkles size={14} aria-hidden="true" />
+ Suggest a team
+ </>
+ )}
+ </button>
+ {busy && (
+ <button type="button" onClick={cancel} className={`${btnH} px-3.5 rounded-lg text-sm text-zinc-200 hover:bg-white/5 ${FOCUS}`}>
+ Cancel
+ </button>
+ )}
+ <span id={hintId} className="min-w-0 text-xs text-zinc-400">
+ {hint}
+ </span>
+ </div>
+ {problem && (
+ <p id={errId} className="mt-1.5 text-xs text-amber-200">
+ {problem}
+ </p>
+ )}
+ {err && !problem && (
+ <div id={errId} role="alert" className="mt-2 rounded-lg border border-rose-400/30 bg-rose-500/10 px-3 py-2 text-[12.5px] leading-[18px] text-rose-100" data-need-error>
+ <p className="font-semibold">{err.head}</p>
+ {err.reason && <p className="mt-0.5 text-rose-100/85">{err.reason}</p>}
+ </div>
+ )}
+ <p className="sr-only" aria-live="polite">
+ {live}
+ </p>
+ </div>
+ );
+};
diff --git a/frontend/src/components/TeamPreviewSheet.tsx b/frontend/src/components/TeamPreviewSheet.tsx
index ff55bd3d..b602b974 100644
--- a/frontend/src/components/TeamPreviewSheet.tsx
+++ b/frontend/src/components/TeamPreviewSheet.tsx
@@ -23,6 +23,7 @@ import {
RefreshCw,
ScanSearch,
ShieldCheck,
+ Sparkles,
Undo2,
WifiOff,
CircleAlert,
@@ -43,6 +44,7 @@ import {
fieldKey,
connectForgeFor,
serverErrorText,
+ needError,
initialEdits,
nameError,
newBotCount,
@@ -121,6 +123,9 @@ const Banner: React.FC<{ tone: 'bad' | 'warn' | 'info'; head: string; children?:
);
};
+/** "a", "a and b", "a, b and c": the server's own phrases, joined, never rewritten. */
+export const listWords = (xs: string[]) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);
+
const Note: React.FC<{ children: React.ReactNode; id?: string }> = ({ children, id }) => (
<p id={id} className="mt-1 flex items-start gap-1.5 text-xs text-zinc-300">
<Info size={12} className="mt-0.5 shrink-0 text-sky-300" aria-hidden="true" />
@@ -163,7 +168,18 @@ export const Reason: React.FC<{ parts: SuggestedBot['reason'] }> = ({ parts }) =
export type SheetMode =
| { kind: 'template'; templateId: string }
/** D: from New team (no team), Manage team (team), or the Coding template with a folder or repo. */
- | { kind: 'suggest'; workspace_path?: string | null; repo_url?: string | null; handleSeed?: string; team?: { id: string; name: string }; viaCoding?: boolean };
+ | {
+ kind: 'suggest';
+ workspace_path?: string | null;
+ repo_url?: string | null;
+ handleSeed?: string;
+ team?: { id: string; name: string };
+ viaCoding?: boolean;
+ /** A team from your own words: the person's words, sent as `{ need }`. Try again sends them again. */
+ need?: string;
+ /** The answer the need box already has, so the sheet opens on it without asking twice. */
+ initial?: Suggestion;
+ };
export interface TeamPreviewSheetProps {
open: boolean;
@@ -178,7 +194,10 @@ export interface TeamPreviewSheetProps {
/** Bots in this space, for D6's "Add Frontend (already in this space)" avatar. */
spaceBots?: { id: string; name: string; role?: string }[];
onClose: () => void;
- onCreated: (r: CreatedTeam, t: TeamTemplate, handle: string) => void;
+ /** `t` is null for a team from your own words, which has no template. */
+ onCreated: (r: CreatedTeam, t: TeamTemplate | null, handle: string) => void;
+ /** No ready account: "Add an AI account" opens Accounts. */
+ onOpenAccounts?: () => void;
/** D7: "Use the Coding roster" switches the sheet to the plain Coding template. */
onUseCoding?: () => void;
onPickFolder?: () => void;
@@ -206,6 +225,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
onUseCoding,
onPickFolder,
onConnectForge,
+ onOpenAccounts,
}) => {
const phone = useMedia(PHONE_QUERY);
const rootRef = useRef<HTMLDivElement>(null);
@@ -215,6 +235,9 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
const subId = useId();
const isD = mode.kind === 'suggest';
const manage = isD && !!mode.team;
+ /** A team from your own words (brief "Flow"): no facts, read line, partial or stack line. */
+ const isN = mode.kind === 'suggest' && !!mode.need && !mode.team;
+ const need = mode.kind === 'suggest' ? mode.need ?? '' : '';
const templateId = mode.kind === 'template' ? mode.templateId : 'coding';
const t = templates?.find((x) => x.id === templateId) ?? null;
@@ -267,12 +290,27 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
editsRef.current = edits;
const sugRef = useRef(sug);
sugRef.current = sug;
+ /** Need mode: why the last ask failed, in the person's words. */
+ const [needErr, setNeedErr] = useState<ReturnType<typeof needError> | null>(null);
+ /** Need mode: the answer the box handed over is used once, for the first read. */
+ const usedInitial = useRef(false);
+ /** Need mode: Try again keeps the last team here, so Cancel or Escape while asking goes back to it. */
+ const [again, setAgain] = useState(false);
+ const [openInstr, setOpenInstr] = useState<Set<string>>(new Set());
const close = useCallback(() => {
if (phase === 'creating') return;
+ if (dPhase === 'reading' && readAbort.current && !readAbort.current.signal.aborted) teamsApi.cancelSuggest(space);
readAbort.current?.abort();
+ if (isN && again && dPhase === 'reading' && sugRef.current) {
+ // Stop the second ask and keep the team that was here.
+ setAgain(false);
+ setDPhase('ready');
+ setLive('Stopped. The last suggestion is still here.');
+ return;
+ }
onClose();
- }, [phase, onClose]);
+ }, [phase, onClose, isN, again, dPhase, space]);
useEscapeLayer(rootRef, true, close, { modal: true });
// Seed names and handle once the template is here (T9 clash rules).
@@ -323,20 +361,26 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
setDPhase('reading');
setInUse(false);
setElapsed(0);
- setLive('Reading the project');
- if (!navigator.onLine) {
+ setNeedErr(null);
+ setLive(isN ? 'Suggesting a team' : 'Reading the project');
+ const first = isN && !usedInitial.current && mode.initial ? mode.initial : null;
+ usedInitial.current = true;
+ if (!first && !navigator.onLine) {
setDPhase('offline');
- setLive('You’re offline. Nothing was read.');
+ setLive(isN ? 'You’re offline. Your words are kept.' : 'You’re offline. Nothing was read.');
return;
}
try {
- // api.md §4: exactly one source. Manage team reads the team's own folder or repo.
- const req: SuggestRequest = mode.team
- ? { space, team_id: mode.team.id }
- : mode.workspace_path
- ? { space, workspace_path: mode.workspace_path }
- : { space, repo_url: mode.repo_url ?? '' };
- const s = await teamsApi.suggest(req, mode.workspace_path || mode.repo_url || (mode.team ? `@${mode.team.name}` : ''));
+ // api.md §4: exactly one source. Manage team reads the team's own folder or repo. A team from
+ // your own words sends only `{ need }` (brief "Server contract").
+ const req: SuggestRequest = isN
+ ? { space, need: need.trim() }
+ : mode.team
+ ? { space, team_id: mode.team.id }
+ : mode.workspace_path
+ ? { space, workspace_path: mode.workspace_path }
+ : { space, repo_url: mode.repo_url ?? '' };
+ const s = first ?? (await teamsApi.suggest(req, isN ? 'need' : mode.workspace_path || mode.repo_url || (mode.team ? `@${mode.team.name}` : '')));
if (ac.signal.aborted) return;
const fresh = initialEdits(s, takenNames);
const old = sugRef.current;
@@ -349,13 +393,24 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
setHandleNote(c.handleNote);
}
setDPhase('ready');
+ setAgain(false);
setLive(
- s.bots.length + s.also_possible.length === 0
+ isN
+ ? `Suggested ${plural(s.bots.length, 'bot')}. Nothing is made until you create it.`
+ : s.bots.length + s.also_possible.length === 0
? 'Nothing new to add.'
: `Suggested ${plural(s.bots.length, 'bot')}${s.also_possible.length ? `, ${s.also_possible.length} also possible` : ''}`,
);
} catch (e) {
if (ac.signal.aborted) return;
+ if (isN) {
+ const ne = needError(e);
+ setNeedErr(ne);
+ setAgain(false);
+ setDPhase(e instanceof TeamsError && e.status === 0 ? 'offline' : 'error');
+ setLive(`${ne.head}${ne.reason ? ` ${ne.reason}` : ''}`);
+ return;
+ }
// The live region still says "Reading the project" otherwise.
if (cantRead(e)) {
setCantForge(e instanceof TeamsError ? e.extra?.forge ?? null : null);
@@ -385,7 +440,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
- [space, mode.kind === 'suggest' ? mode.workspace_path : null, mode.kind === 'suggest' ? mode.repo_url : null],
+ [space, mode.kind === 'suggest' ? mode.workspace_path : null, mode.kind === 'suggest' ? mode.repo_url : null, need],
);
useEffect(() => {
if (isD) void read();
@@ -423,12 +478,15 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
};
const ticked = isD ? tickedCount(edits) : tBots.length;
const anyNameBad = isD ? dRows.some((b) => edits[b.key]?.ticked && nameErr(b.key)) : tBots.some((b) => nameErr(b.key));
- const handleBad = !manage && !cleanHandle(handle);
+ // Decisions 11-12 §4: a team from the person's words has no handle field; the server picks a free one
+ // (free_team_handle), which can be changed later in the team's settings.
+ const askHandle = !manage && !isN;
+ const handleBad = askHandle && !cleanHandle(handle);
const minBots = manage ? 1 : MIN_BOTS;
const dSizeBad = isD && (ticked < minBots || ticked > MAX_BOTS);
const creating = phase === 'creating';
const canCreate = ready && online && !creating && !anyNameBad && !handleBad && !dSizeBad && renaming === null;
- const label = t?.label ?? 'Coding';
+ const label = isN ? 'suggested' : t?.label ?? 'Coding';
const busy = (!isD && !t && !templatesError) || (isD && dPhase === 'reading');
// ---- rename
@@ -469,7 +527,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
// ---- create
const create = async () => {
- if (!canCreate || !t) return;
+ if (!canCreate || (!t && !isD)) return;
setPhase('creating');
setLive(manage ? `Adding ${plural(newBotCount(edits), 'bot')} to @${mode.kind === 'suggest' ? mode.team?.name : ''}` : `Creating the ${label} team`);
const h = cleanHandle(handle);
@@ -494,17 +552,19 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
space,
suggestion_id: sug.suggestion_id,
rows,
- ...(manage && mode.kind === 'suggest' && mode.team ? { team_id: mode.team.id } : { handle: h }),
+ ...(manage && mode.kind === 'suggest' && mode.team ? { team_id: mode.team.id } : askHandle ? { handle: h } : {}),
};
} else {
const ns: Record<string, string> = {};
for (const b of tBots) if (names[b.key] && names[b.key] !== b.name) ns[b.key] = names[b.key];
+ if (!t) return;
body = { kind: 'template', space, template_id: t.id, handle: h, names: ns };
}
try {
const r = await teamsApi.create(body, idemKey.current);
- setLive(`Created @${h}. Undo is available.`);
- onCreated(r, t, h);
+ const made = askHandle ? h : r.team.name;
+ setLive(`Created @${made}. Undo is available.`);
+ onCreated(r, t, made);
} catch (e) {
if (e instanceof TeamsError && e.status === 410 && isD) {
// A17: read again, keep the edits on rows that come back.
@@ -549,7 +609,11 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
let title = `${label} team`;
let sub: React.ReactNode = t ? summaryLine(t) : '';
let glyph = t?.icon ?? 'code-xml';
- if (isD && mode.kind === 'suggest') {
+ if (isN) {
+ title = 'Suggested team';
+ sub = 'Drafted from your words. Nothing is made until you create it.';
+ glyph = 'sparkles';
+ } else if (isD && mode.kind === 'suggest') {
if (manage) {
title = `Suggested for @${mode.team!.name}`;
sub = (
@@ -651,7 +715,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
</section>
);
- const handleSec = !manage && (
+ const handleSec = askHandle && (
<section className={SEC} aria-labelledby={`${titleId}-handle`}>
<h4 className={H} id={`${titleId}-handle`}>
Team handle
@@ -795,7 +859,10 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
const off = !e.ticked;
const existing = b.existing_kwant_id ? spaceBots.find((x) => x.id === b.existing_kwant_id) : null;
const existingName = existing?.name ?? b.existing_name ?? b.name;
- const owns = b.owns.filter(safeFolder);
+ // Code suggestions own folders, so only safe folder names show. A team from words owns plain jobs.
+ const owns = isN ? b.owns.filter((o) => o.trim()) : b.owns.filter(safeFolder);
+ const instrOpen = openInstr.has(b.key);
+ const instrId = `${titleId}-in-${b.key}`;
const disabledTick = !b.lead && off && atMax;
const choiceBlock = (
<>
@@ -855,7 +922,32 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
<Reason parts={b.reason} />
</p>
{notes[b.key] && renaming !== b.key && <Note>{notes[b.key]}</Note>}
- {owns.length > 0 && (
+ {isN && owns.length > 0 && (
+ <p className="mt-1 text-xs text-zinc-300" data-takes-care>
+ Takes care of {listWords(owns)}
+ </p>
+ )}
+ {isN && b.instructions && (
+ <div className="mt-1.5">
+ <button
+ type="button"
+ aria-expanded={instrOpen}
+ aria-controls={instrId}
+ onClick={() => setOpenInstr((r) => (r.has(b.key) ? new Set([...r].filter((x) => x !== b.key)) : new Set([...r, b.key])))}
+ className={`inline-flex items-center gap-1 ${phone ? 'min-h-11' : 'min-h-7'} -ml-1 px-1 rounded-md text-[12.5px] font-medium text-sky-300 hover:bg-white/5 ${FOCUS}`}
+ >
+ <ChevronDown size={12} aria-hidden="true" className={`transition-transform motion-reduce:transition-none ${instrOpen ? 'rotate-180' : ''}`} />
+ Instructions<span className="sr-only"> for {e.name}</span>
+ </button>
+ {instrOpen && (
+ <div id={instrId} className="mt-1">
+ <pre className="max-h-[180px] overflow-auto whitespace-pre-wrap break-words p-3 rounded-lg bg-black/30 border border-white/5 text-xs leading-[18px] text-zinc-300 font-sans">{b.instructions}</pre>
+ <p className="mt-1 text-[11.5px] text-zinc-400">You can change these in the bot’s settings after you create it.</p>
+ </div>
+ )}
+ </div>
+ )}
+ {!isN && owns.length > 0 && (
<p className="mt-1 text-xs text-zinc-400">
Owns{' '}
{owns.map((o) => (
@@ -870,7 +962,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
</div>
{!also && renaming !== b.key && (
<span className={`flex items-center gap-1 ${phone ? 'flex-col' : ''}`}>
- {!b.lead && (
+ {!b.lead && !isN && (
<RoleSelect
phone={phone}
name={e.name}
@@ -901,7 +993,60 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
};
const reasonUnknown = sug?.fallback === true;
+ const asked = isN && (
+ <section className={SEC} aria-labelledby={`${titleId}-asked`}>
+ <h4 className={H} id={`${titleId}-asked`}>
+ You asked
+ </h4>
+ <p data-asked className="max-h-[96px] overflow-auto whitespace-pre-wrap break-words p-2.5 rounded-lg bg-black/30 border border-white/5 text-[13px] leading-[18px] text-zinc-200">
+ {need.trim()}
+ </p>
+ </section>
+ );
+ const nBody = () => {
+ if (dPhase === 'reading')
+ return (
+ <>
+ {asked}
+ <div role="status" aria-live="polite" className="flex flex-col items-center text-center pt-6 pb-6 px-3" data-suggesting>
+ <Loader2 size={22} className="text-sky-400 animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ <p className="mt-3 text-sm font-semibold text-zinc-50">Suggesting…</p>
+ {elapsed >= 8000 && <p className="mt-1 text-xs text-zinc-400">Usually under a minute.</p>}
+ </div>
+ <Skeleton rows={3} tick />
+ </>
+ );
+ if (dPhase === 'offline' || dPhase === 'error')
+ return (
+ <>
+ <Banner tone={dPhase === 'offline' ? 'warn' : 'bad'} icon={dPhase === 'offline' ? 'offline' : 'alert'} head={needErr?.head ?? 'Couldn’t suggest a team this time. Try again, or start from a ready-made team.'}>
+ {needErr?.reason ? `${needErr.reason} ` : ''}Nothing was created.
+ </Banner>
+ {asked}
+ </>
+ );
+ if (!sug) return null;
+ const lead = sug.bots.find((b) => b.lead);
+ return (
+ <>
+ {expiredNote && (
+ <p role="status" className="mt-3 text-xs text-zinc-300">
+ Suggested again, it had been an hour.
+ </p>
+ )}
+ {asked}
+ <section className={SEC} aria-labelledby={`${titleId}-who`}>
+ <h4 className={H} id={`${titleId}-who`}>
+ Who’s on it{lead && <span className={`${CNT} text-zinc-500`}>{edits[lead.key]?.name} leads</span>}
+ </h4>
+ <ul>{sug.bots.map((b) => sgRow(b, false))}</ul>
+ </section>
+ {handleSec}
+ </>
+ );
+ };
const dBody = () => {
+ if (isN) return nBody();
if (dPhase === 'reading') {
const near = elapsed >= 7000;
return (
@@ -1064,16 +1209,19 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
};
// ---- footer
+ const phoneN = phone && isN;
const nNew = isD ? newBotCount(edits) : tBots.length;
// Manage with nothing new to suggest: the body says so; no "Pick at least" nag.
const nothingNew = manage && dPhase === 'ready' && !!sug && sug.bots.length === 0 && sug.also_possible.length === 0;
const sNote = isD && dPhase === 'ready' && !nothingNew ? sizeNote(ticked, minBots) : null;
const fallbackFooter = isD && (dPhase === 'cantread' || dPhase === 'offline' || dPhase === 'error');
+ const noAccount = isN && dPhase === 'error' && !!needErr?.noAccount && !!onOpenAccounts;
// N-5: the same folder gets the same refusal, so offer another folder instead of "Try again".
const pickOther = inUse && !!onPickFolder && mode.kind === 'suggest' && !mode.team && (phase === 'failed' || dPhase === 'error');
const retry = !pickOther && ((!isD && templatesError && !t) || phase === 'failed' || (isD && (dPhase === 'error' || dPhase === 'offline')));
- const primaryLabel = creating ? 'Creating…' : pickOther ? 'Pick another folder' : retry ? 'Try again' : manage ? (nothingNew || ticked === 0 ? 'Add bots' : `Add ${plural(ticked, 'bot')}`) : isD && dPhase === 'reading' ? 'Create team' : `Create team · ${plural(ticked, 'bot')}`;
+ const primaryLabel = creating ? 'Creating…' : noAccount ? 'Add an AI account first' : pickOther ? 'Pick another folder' : retry ? 'Try again' : manage ? (nothingNew || ticked === 0 ? 'Add bots' : `Add ${plural(ticked, 'bot')}`) : isD && dPhase === 'reading' ? 'Create team' : `Create team · ${plural(ticked, 'bot')}`;
const onPrimary = () => {
+ if (noAccount) return onOpenAccounts?.();
if (pickOther) return onPickFolder?.();
if (retry) {
if (!isD && templatesError && !t) return onRetryTemplates?.();
@@ -1094,7 +1242,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
? 'Undo takes them out of the team again.'
: 'Undo removes the team. Your bots stay.'
: `Undo removes the ${plural(nNew, 'new bot')}.`
- : 'Undo removes all of it.');
+ : 'Undo removes it all.');
const btnH = phone ? 'h-11 flex-1' : 'h-9';
const panel = (
@@ -1121,7 +1269,11 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
</div>
)}
<header className={`flex items-center gap-3 ${phone ? 'px-4 pt-1 pb-3' : 'px-5 py-4'} border-b border-zinc-800`}>
- {glyph === 'scan' ? (
+ {glyph === 'sparkles' ? (
+ <span aria-hidden="true" className="w-10 h-10 rounded-[11px] shrink-0 grid place-items-center bg-sky-400/15 text-sky-400 ring-1 ring-inset ring-sky-300/20">
+ <Sparkles size={20} />
+ </span>
+ ) : glyph === 'scan' ? (
<span aria-hidden="true" className="w-10 h-10 rounded-[11px] shrink-0 grid place-items-center bg-sky-400/15 text-sky-400 ring-1 ring-inset ring-sky-300/20">
<ScanSearch size={20} />
</span>
@@ -1132,7 +1284,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
<h3 id={titleId} className="text-[17px] leading-6 font-semibold text-zinc-50 truncate">
{title}
</h3>
- <p id={subId} className="text-xs text-zinc-400 truncate">
+ <p id={subId} className={`text-xs text-zinc-400 ${phone ? 'line-clamp-2' : 'truncate'}`}>
{sub}
</p>
</div>
@@ -1157,15 +1309,32 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
)}
{isD ? dBody() : tBody()}
</div>
+ {/* Phone, team from words: Cancel and Try again share a row as equal halves (Cancel's transparent border matches
+ Try again's), and Create gets its own full-width row: basis-full, since flex-1's 0% basis never wraps.
+ Desktop note: text-balance, not nowrap, so the amber "6 bots at most..." wraps to 2 even lines beside the buttons. */}
<footer className={`flex ${phone ? 'flex-wrap' : 'items-center'} gap-2 ${phone ? 'px-4 pt-3 pb-[max(12px,env(safe-area-inset-bottom))]' : 'px-5 py-3.5'} border-t border-zinc-800 bg-zinc-900`}>
- <p className={`${phone ? 'w-full' : 'flex-1 min-w-0'} flex items-center gap-1.5 text-xs ${sNote ? 'text-amber-200' : 'text-zinc-400'}`} aria-live="polite">
+ <p className={`${phone ? 'w-full' : 'flex-1 min-w-0 text-balance'} flex items-center gap-1.5 text-xs ${sNote ? 'text-amber-200' : 'text-zinc-400'}`} aria-live="polite">
{!fallbackFooter && !sNote && footNote && <Undo2 size={13} aria-hidden="true" />}
{fallbackFooter ? null : footNote}
</p>
- <button type="button" onClick={close} disabled={creating} className={`${btnH} px-3.5 rounded-lg text-sm text-zinc-200 hover:bg-white/5 disabled:opacity-50 ${FOCUS}`}>
+ <button type="button" onClick={close} disabled={creating} className={`${btnH} ${phoneN ? 'flex-1 border border-transparent' : ''} px-3.5 rounded-lg text-sm text-zinc-200 hover:bg-white/5 disabled:opacity-50 ${FOCUS}`}>
Cancel
</button>
- {fallbackFooter && onUseCoding && (
+ {isN && dPhase === 'ready' && (
+ <button
+ type="button"
+ onClick={() => {
+ setAgain(true);
+ void read();
+ }}
+ disabled={creating || !online}
+ className={`${btnH} ${phoneN ? 'flex-1' : ''} whitespace-nowrap inline-flex items-center justify-center gap-1.5 px-3.5 rounded-lg border border-zinc-700 text-sm text-zinc-100 hover:bg-white/5 disabled:opacity-50 ${FOCUS}`}
+ >
+ <RefreshCw size={14} aria-hidden="true" />
+ Try again
+ </button>
+ )}
+ {fallbackFooter && onUseCoding && !isN && (
<button type="button" onClick={onUseCoding} className={`${btnH} px-3.5 rounded-lg border border-zinc-700 text-sm text-zinc-100 hover:bg-white/5 ${FOCUS}`}>
Use the Coding roster
</button>
@@ -1176,11 +1345,11 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
type="button"
onClick={onPrimary}
disabled={primaryDisabled}
- className={`${btnH} inline-flex items-center justify-center gap-2 px-4 rounded-lg bg-sky-600 hover:bg-sky-500 text-white text-sm font-medium disabled:opacity-50 disabled:hover:bg-sky-600 ${FOCUS}`}
+ className={`${btnH} ${phoneN ? 'basis-full' : ''} whitespace-nowrap inline-flex items-center justify-center gap-2 px-4 rounded-lg bg-sky-600 hover:bg-sky-500 text-white text-sm font-medium disabled:opacity-50 disabled:hover:bg-sky-600 ${FOCUS}`}
>
{creating && <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
{pickOther && !creating && <FolderOpen size={14} aria-hidden="true" />}
- {retry && !creating && <RefreshCw size={14} aria-hidden="true" />}
+ {retry && !creating && !noAccount && <RefreshCw size={14} aria-hidden="true" />}
{primaryLabel}
</button>
)}
diff --git a/frontend/src/components/TeamTemplatePicks.tsx b/frontend/src/components/TeamTemplatePicks.tsx
index 5b6384ef..7d1e0fbf 100644
--- a/frontend/src/components/TeamTemplatePicks.tsx
+++ b/frontend/src/components/TeamTemplatePicks.tsx
@@ -1,7 +1,7 @@
// 0.7.7 T7 entry points: the welcome cards (T7.1), the New team tiles (T7.2) and the sidebar box (T7.3).
// Each opens the same preview sheet. Design: next-077/design/design.md §T7.
import React from 'react';
-import { ChevronRight, X } from 'lucide-react';
+import { ChevronRight, Sparkles, X } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { TEMPLATE_ICONS, TemplateGlyph } from './TeamPreviewSheet';
import { useMedia } from '../useMedia';
@@ -112,7 +112,7 @@ export const TemplateTiles: React.FC<{ templates: TeamTemplate[]; onPick: (id: s
};
/** T7.3: a dashed box at the bottom of the Bots list while the space has no teams. */
-export const TemplateSidebarBox: React.FC<{ templates: TeamTemplate[]; onPick: (id: string) => void; onHide: () => void }> = ({ templates, onPick, onHide }) => {
+export const TemplateSidebarBox: React.FC<{ templates: TeamTemplate[]; onPick: (id: string) => void; onHide: () => void; onDescribe?: () => void }> = ({ templates, onPick, onHide, onDescribe }) => {
const phone = useMedia(PHONE_QUERY);
if (!templates.length) return null;
return (
@@ -122,6 +122,18 @@ export const TemplateSidebarBox: React.FC<{ templates: TeamTemplate[]; onPick: (
<p className="text-[11px] leading-4 text-zinc-400">Bots, instructions and skills in one step.</p>
</div>
<div className="mt-2 flex flex-wrap gap-1.5">
+ {onDescribe && (
+ <button
+ type="button"
+ data-describe-own
+ onClick={onDescribe}
+ aria-label="Describe your own team"
+ className={`inline-flex items-center gap-[5px] ${phone ? 'h-11 px-3.5' : 'h-[26px] px-[9px]'} rounded-full border border-sky-300/35 bg-sky-300/[.08] text-xs font-medium text-sky-200 hover:bg-sky-300/[.14] ${FOCUS}`}
+ >
+ <Sparkles size={12} className="text-sky-300" aria-hidden="true" />
+ Describe your own
+ </button>
+ )}
{templates.map((t) => {
const Icon = TEMPLATE_ICONS[t.icon];
return (
diff --git a/frontend/src/teams/suggestFixtures.ts b/frontend/src/teams/suggestFixtures.ts
index 76c89f40..f6a51211 100644
--- a/frontend/src/teams/suggestFixtures.ts
+++ b/frontend/src/teams/suggestFixtures.ts
@@ -90,6 +90,90 @@ export const MANAGE_WIRE: WireSuggestion = {
also_possible: [SHOP_WIRE.also_possible[1]],
};
+// Team from your own words: the server contract's answer to `{ need }` (brief.md, "Server contract").
+// `facts` empty, `read` zeros, `partial` and `stack_line` null, `fallback` false; rows carry `owns`
+// ("Takes care of…"), `reason` (tied to the words) and `instructions` (the drafted soul). Example data.
+export const BAKERY_NEED = 'I run a small bakery: answer customer emails, post on Instagram, keep track of orders';
+const needRow = (key: string, preset: string, name: string, title: string, sprite: string, reason: string, owns: string[], instructions: string, lead = false): Row => ({
+ key,
+ preset,
+ lead,
+ name,
+ title,
+ avatar_sprite: sprite,
+ reason,
+ owns,
+ instructions,
+ existing: null,
+});
+export const BAKERY_WIRE: WireSuggestion = {
+ suggestion_id: 'sug_demo_bakery',
+ handle: 'bakery',
+ need: BAKERY_NEED,
+ facts: [],
+ bots: [
+ needRow(
+ 'lead',
+ 'custom',
+ 'ShopLead',
+ 'Bakery Lead',
+ 'product',
+ 'You run the bakery day to day, so one bot keeps the others on track and asks you before anything goes out.',
+ ['the day’s plan', 'questions for you'],
+ 'You lead a small bakery’s team.\n\nEach morning, list what the team has to do today: emails waiting for an answer, posts to schedule and orders due.\nHand each job to the right teammate and check it is done.\nAsk the owner before anything is sent, posted or promised to a customer.\nKeep your notes short and plain.',
+ true,
+ ),
+ needRow(
+ 'inbox',
+ 'inbox',
+ 'CustomerMail',
+ 'Customer Email',
+ 'writer',
+ 'You asked for customer emails to be answered.',
+ ['customer emails', 'reply drafts'],
+ 'You answer the bakery’s customer emails.\n\nRead new emails and sort them: orders, questions, complaints, other.\nDraft a friendly, short reply for each. Never send without the owner’s OK.\nWhen an email is an order, pass it to OrderKeeper with the date, items and name.',
+ ),
+ needRow(
+ 'social',
+ 'custom',
+ 'InstaPoster',
+ 'Instagram Poster',
+ 'designer',
+ 'You asked for posts on Instagram.',
+ ['Instagram posts', 'captions'],
+ 'You plan the bakery’s Instagram posts.\n\nSuggest three posts a week: what is fresh, a behind-the-scenes moment, and a customer favourite.\nWrite the caption and say which photo to take.\nNever post without the owner’s OK.',
+ ),
+ needRow(
+ 'orders',
+ 'custom',
+ 'OrderKeeper',
+ 'Order Keeper',
+ 'data',
+ 'You asked to keep track of orders.',
+ ['the order list', 'pickup dates'],
+ 'You keep the bakery’s order list.\n\nAdd each order with the customer’s name, items, pickup date and whether it is paid.\nEach evening, list tomorrow’s pickups for the owner.\nFlag any order with a missing date or item.',
+ ),
+ ],
+ also_possible: [],
+ read: { files: 0, manifests: 0, ms: 0 },
+ partial: null,
+ stack_line: null,
+ fallback: false,
+};
+/** Try again: the same words, a second draft (fewer bots, other names). */
+export const BAKERY_AGAIN_WIRE: WireSuggestion = {
+ ...BAKERY_WIRE,
+ suggestion_id: 'sug_demo_bakery_2',
+ bots: [
+ { ...BAKERY_WIRE.bots[0], name: 'Baker', title: 'Head of the Bakery Team' },
+ { ...BAKERY_WIRE.bots[1], name: 'MailHelper' },
+ { ...BAKERY_WIRE.bots[3], name: 'Orders' },
+ ],
+};
+export const BAKERY_SUGGESTION: Suggestion = normSuggestion(BAKERY_WIRE, 'need');
+
+export type NeedScenario = 'bakery' | 'again' | 'slow' | 'draft_failed' | 'no_ready_account' | 'limit' | 'busy' | 'offline' | 'too_short';
+
export const SHOP_SUGGESTION: Suggestion = normSuggestion(SHOP_WIRE, '~/projects/shop');
export const PARTIAL_SUGGESTION: Suggestion = normSuggestion(PARTIAL_WIRE, '~/projects/shop');
export const UNKNOWN_SUGGESTION: Suggestion = normSuggestion(UNKNOWN_WIRE, '~/projects/notes');
@@ -100,10 +184,11 @@ export type Call = { url: string; method: string; body?: unknown; headers?: Reco
/** A transport answering the T and D routes from fixtures. `calls` collects every request. */
export function fixtureTransport(
- opts: { suggest?: SuggestScenario; create?: 'ok' | 'fail' | 'clash' | 'clash-handle' | 'clash-many' | 'expired-once'; preview?: TemplatePreview | 'error'; templates?: 'ok' | 'error' | 'slow' } = {},
+ opts: { suggest?: SuggestScenario; need?: NeedScenario; create?: 'ok' | 'fail' | 'clash' | 'clash-handle' | 'clash-many' | 'expired-once'; preview?: TemplatePreview | 'error'; templates?: 'ok' | 'error' | 'slow'; cancel?: 'ok' } = {},
calls: Call[] = [],
): TeamsTransport {
let expired = opts.create === 'expired-once';
+ let needCalls = 0;
return async (url, method, body, headers) => {
calls.push({ url, method, body, headers });
const path = url.split('?')[0];
@@ -118,6 +203,25 @@ export function fixtureTransport(
if (!opts.preview || opts.preview === 'error') return { status: 404, body: { error: 'not found' } };
return { status: 200, body: opts.preview };
}
+ if (path === '/api/teams/suggest' && method === 'DELETE') {
+ // decisions-1112 §2: 204 once Juno's route lands; by default a 404 like today's server, which the client ignores.
+ return opts.cancel === 'ok' ? { status: 204, body: null } : { status: 404, body: { error: 'not found' } };
+ }
+ if (path === '/api/teams/suggest' && body && typeof (body as { need?: unknown }).need === 'string') {
+ // `again`: the first ask gives the bakery team, every later one the second draft.
+ const sc = opts.need ?? 'bakery';
+ needCalls++;
+ if (sc === 'offline') throw new TeamsError('Couldn’t reach the server.', 0, 'offline');
+ // unref: a test that cancels the ask doesn't wait the minute out (no-op in a browser).
+ if (sc === 'slow') await new Promise((r) => (setTimeout(r, 60_000) as unknown as { unref?: () => void }).unref?.());
+ if (sc === 'draft_failed') return { status: 502, body: { error: 'The draft came back unusable twice.', code: 'draft_failed' } };
+ if (sc === 'no_ready_account') return { status: 409, body: { error: 'No account in this space can run right now.', code: 'no_ready_account' } };
+ if (sc === 'limit') return { status: 429, body: { error: 'Claude is out until 21:10.', code: 'limited', account: 'Claude', until: '2026-11-12T21:10:00Z' } };
+ if (sc === 'busy') return { status: 409, body: { error: 'Already drafting a team for this space.', code: 'busy' } };
+ if (sc === 'too_short') return { status: 422, body: { error: 'need is too short', code: 'need_too_short' } };
+ const need = (body as { need: string }).need;
+ return { status: 200, body: { ...(sc === 'again' && needCalls > 1 ? BAKERY_AGAIN_WIRE : BAKERY_WIRE), need } };
+ }
if (path === '/api/teams/suggest') {
const sc = opts.suggest ?? 'shop';
if (sc === 'offline') throw new TeamsError('Couldn’t reach the server.', 0, 'offline');
@@ -155,6 +259,26 @@ export function fixtureTransport(
const b = body as { template_id?: string; handle?: string; names?: Record<string, string>; edits?: { handle?: string } };
const handle = b.handle ?? b.edits?.handle ?? 'team';
const t = TEMPLATES_WIRE.find((x) => x.id === b.template_id);
+ const sid = (body as { suggestion_id?: string }).suggestion_id;
+ const needWire = [BAKERY_WIRE, BAKERY_AGAIN_WIRE].find((w) => w.suggestion_id === sid);
+ if (needWire) {
+ const rows = (b.edits as { rows?: Record<string, { on?: boolean; name?: string }> } | undefined)?.rows ?? {};
+ const on = needWire.bots.filter((x) => rows[x.key]?.on !== false);
+ return {
+ status: 201,
+ body: {
+ // No handle sent: the server picks a free one (free_team_handle), here the draft's own.
+ team: { id: 'team_new', name: b.handle ?? b.edits?.handle ?? needWire.handle ?? handle },
+ channel_id: 'ch_team_new',
+ action_id: 'act_demo',
+ template_id: null,
+ bots: on.map((x, i) => ({ slot: x.key, id: `kw_${i}`, name: rows[x.key]?.name ?? x.name, preset: x.preset, lead: x.lead, existing: false })),
+ skills: [],
+ routine: null,
+ undo_until: '2026-11-13T20:00:00Z',
+ },
+ };
+ }
return {
status: 201,
body: {
diff --git a/frontend/src/teams/teamTemplates.ts b/frontend/src/teams/teamTemplates.ts
index 172562e4..f2144265 100644
--- a/frontend/src/teams/teamTemplates.ts
+++ b/frontend/src/teams/teamTemplates.ts
@@ -85,6 +85,8 @@ export interface SuggestedBot {
existing_avatar?: string | null;
/** That bot already leads a team, so adding it here makes it a member, not this team's lead. */
existing_leads_team?: string | null;
+ /** A need suggestion (team-from-words): the drafted instructions (soul), shown read-only in the sheet. */
+ instructions?: string | null;
}
/** api.md §0.6: the wire's `existing` object; the client flattens it onto the row. */
@@ -110,6 +112,8 @@ export interface Suggestion {
fallback: boolean;
/** What was read, for the readline: the folder or the repo (client-side). */
source: string;
+ /** A need suggestion: the person's words, echoed by the server. */
+ need?: string | null;
}
type WireSuggested = Omit<SuggestedBot, 'reason' | 'owns'> & {
@@ -188,7 +192,52 @@ export type CreateRequest =
/** `team_id` set: A18, add the ticked bots to that existing team (Manage team). */
| { kind: 'suggestion'; space: string; suggestion_id: string; handle?: string; team_id?: string; rows: Record<string, RowSend> };
-export type SuggestRequest = { space: string } & ({ workspace_path: string } | { repo_url: string } | { team_id: string });
+export type SuggestRequest = { space: string } & ({ workspace_path: string } | { repo_url: string } | { team_id: string } | { need: string });
+
+// ---------------------------------------------------------------------------------------------------
+// Team from your own words (brief: autonomy/team-from-words/brief.md, "Server contract")
+
+/** 10–1000 characters after trimming (422 `need_too_short` / `need_too_long`). */
+export const NEED_MIN = 10;
+export const NEED_MAX = 1000;
+export const NEED_PLACEHOLDER = 'e.g. I run a small bakery: answer customer emails, post on Instagram, keep track of orders';
+
+/** The client's own length check, the same limits as the server. null when it can be sent. */
+export function needProblem(raw: string): string | null {
+ const n = raw.trim().length;
+ if (n < NEED_MIN) return n === 0 ? 'Say what your bots should do first.' : 'Add a few more words so the team fits.';
+ if (n > NEED_MAX) return `That’s ${n - NEED_MAX} characters over the 1,000 limit. Shorten it a little.`;
+ return null;
+}
+
+export const NEED_FAILED = 'Couldn’t suggest a team this time. Try again, or start from a ready-made team.';
+
+/** A time from the server (`until`, RFC 3339) as the person's clock time, or null. */
+const clock = (v: unknown): string | null => {
+ if (typeof v !== 'string') return null;
+ const d = new Date(v);
+ return Number.isFinite(d.getTime()) ? d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : null;
+};
+
+/**
+ * What a failed need suggestion says: { head, reason }. `head` is the brief's line; `reason` is the
+ * server's own words when it gave any, or a line built from a known code. Never invents numbers.
+ */
+export function needError(e: unknown): { head: string; reason: string | null; noAccount: boolean } {
+ if (!(e instanceof TeamsError)) return { head: NEED_FAILED, reason: null, noAccount: false };
+ if (e.status === 0) return { head: 'You’re offline.', reason: 'Suggest a team works when you’re back. Your words are kept.', noAccount: false };
+ const said = serverErrorText(e);
+ if (e.code === 'no_ready_account') return { head: 'Add an AI account first.', reason: said ?? 'No account in this space can run right now.', noAccount: true };
+ if (e.code === 'need_too_short') return { head: 'Add a few more words so the team fits.', reason: null, noAccount: false };
+ if (e.code === 'need_too_long') return { head: 'That’s over the 1,000-character limit. Shorten it a little.', reason: null, noAccount: false };
+ if (e.code === 'busy') return { head: 'Already suggesting a team here.', reason: said ?? 'Wait for that one to finish, then try again.', noAccount: false };
+ if (e.status === 429) {
+ const until = clock(e.extra?.until);
+ const account = typeof e.extra?.account === 'string' ? (e.extra.account as string) : null;
+ return { head: NEED_FAILED, reason: said ?? (until ? `${account ?? 'The account'} is out until ${until}.` : null), noAccount: false };
+ }
+ return { head: NEED_FAILED, reason: said, noAccount: false };
+}
export class TeamsError extends Error {
constructor(
@@ -323,6 +372,12 @@ export const teamsApi = {
call<TemplatePreview>(`/api/team-templates/${enc(templateId)}/preview?space=${enc(space)}`),
suggest: ({ space, ...src }: SuggestRequest, source: string) =>
call<WireSuggestion>(`/api/teams/suggest?space=${enc(space)}`, 'POST', src).then((s) => normSuggestion(s, source)),
+ /** Stops a running suggest (decisions-1112 §2: `DELETE /api/teams/suggest?space=`, 204 also when idle).
+ * Fire and forget: a 404 from a server without the route, or any other failure, is ignored; the
+ * 409 `busy` copy on the next ask stays the fallback. */
+ cancelSuggest: (space: string): void => {
+ call(`/api/teams/suggest?space=${enc(space)}`, 'DELETE').catch(() => {});
+ },
templateInfo: (teamId: string, space: string) =>
call<WireTemplateInfo>(`/api/teams/${enc(teamId)}/template?space=${enc(space)}`).then(normInfo),
};
diff --git a/frontend/tests/teamFromWords.test.mjs b/frontend/tests/teamFromWords.test.mjs
new file mode 100644
index 00000000..1f8fee7e
--- /dev/null
+++ b/frontend/tests/teamFromWords.test.mjs
@@ -0,0 +1,529 @@
+// A team from your own words (team-from-words brief, "Frontend (Iris)"): the box in the Get ready card,
+// the sidebar's "Describe your own" chip and New team; Add an AI account first; submit, loading and the
+// sheet; an error keeps the words; Try again sends the same need; Create sends suggestion_id + edits;
+// Escape cancels. Against the bakery fixture in src/teams/suggestFixtures.ts. Example data only.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_demo', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of [
+ 'window',
+ 'document',
+ 'navigator',
+ 'HTMLElement',
+ 'HTMLInputElement',
+ 'HTMLSelectElement',
+ 'HTMLTextAreaElement',
+ 'HTMLButtonElement',
+ 'Element',
+ 'Node',
+ 'Event',
+ 'MouseEvent',
+ 'KeyboardEvent',
+ 'FocusEvent',
+ 'CustomEvent',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'getComputedStyle',
+ 'localStorage',
+ 'sessionStorage',
+]) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.IS_REACT_ACT_ENVIRONMENT = false;
+let phone = false;
+window.matchMedia = (q) => ({ matches: q.includes('max-width: 767px') ? phone : false, media: q, addEventListener() {}, removeEventListener() {} });
+g.fetch = g.window.fetch = async () => new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export * from './src/teams/teamTemplates';
+ export * as fx from './src/teams/suggestFixtures';
+ export { TeamPreviewSheet, listWords } from './src/components/TeamPreviewSheet';
+ export { ReadyTeamsProvider } from './src/components/ReadyTeams';
+ export { ReadyTeamsSidebarBox } from './src/components/ReadyTeamsEntry';
+ export { TeamNeedBox } from './src/components/TeamNeedBox';
+ export { SpaceReadyCard } from './src/components/SpaceReadyCard';
+ export { NewTeamModal } from './src/components/NewTeamModal';
+`);
+const { React, createRoot, fx } = m;
+const h = React.createElement;
+const settle = async (n = 12) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const click = async (el) => {
+ assert.ok(el, 'element to click exists');
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const typeArea = async (el, value) => {
+ Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set.call(el, value);
+ el.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle(2);
+};
+const key = async (el, k, extra = {}) => {
+ el.dispatchEvent(new window.KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true, ...extra }));
+ await settle();
+};
+const mount = async (el) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(el);
+ await settle();
+ return { host, root, rerender: async (e) => (root.render(e), await settle()), unmount: () => (root.unmount(), host.remove()) };
+};
+const byText = (root, sel, re) => [...root.querySelectorAll(sel)].find((el) => re.test(el.textContent ?? ''));
+const use = (opts) => {
+ const calls = [];
+ m.setTeamsTransport(fx.fixtureTransport(opts, calls));
+ return calls;
+};
+const asks = (calls) => calls.filter((c) => c.url.startsWith('/api/teams/suggest') && c.method !== 'DELETE');
+const stops = (calls) => calls.filter((c) => c.url.startsWith('/api/teams/suggest') && c.method === 'DELETE');
+const creates = (calls) => calls.filter((c) => c.url.startsWith('/api/teams/from-template'));
+const NEED = fx.BAKERY_NEED;
+
+/** The Get ready card inside the provider, as App renders it on an empty space. */
+const card = (props = {}, provider = {}) => {
+ const out = { accounts: 0, newBot: 0, opened: [], undone: 0 };
+ const el = h(
+ m.ReadyTeamsProvider,
+ {
+ space: 'spc_demo',
+ bots: [],
+ teams: [],
+ onChanged() {},
+ onOpenTeam: (t, ch) => out.opened.push({ t, ch }),
+ onUndone: () => out.undone++,
+ readyAccounts: 1,
+ onOpenAccounts: () => out.accounts++,
+ ...provider,
+ },
+ h('div', { id: 'card' }, h(m.SpaceReadyCard, { spaceName: 'Bakery', tile: null, readyAccounts: provider.readyAccounts ?? 1, botCount: 0, onAddAccount() {}, onNewBot: () => out.newBot++, ...props })),
+ h('div', { id: 'side' }, h(m.ReadyTeamsSidebarBox, { teamCount: 0 })),
+ );
+ return { el, out };
+};
+const box = () => document.querySelector('#card [data-need-box] textarea');
+const submitBtn = () => document.querySelector('#card [data-need-submit]');
+const theSheet = () => document.querySelector('[data-team-sheet="suggest"]');
+
+// ---------------------------------------------------------------------------------------------------
+
+test('client rules: 10–1000 characters after trimming; the error copy per server code', () => {
+ assert.equal(m.needProblem(' '), 'Say what your bots should do first.');
+ assert.equal(m.needProblem(' bakery '), 'Add a few more words so the team fits.');
+ assert.equal(m.needProblem('a'.repeat(10)), null);
+ assert.equal(m.needProblem(` ${'a'.repeat(1000)} `), null);
+ assert.match(m.needProblem('a'.repeat(1003)), /3 characters over the 1,000 limit/);
+ const E = (status, body) => new m.TeamsError(body.error ?? 'x', status, body.code ?? null, null, null, null, body);
+ const failed = 'Couldn’t suggest a team this time. Try again, or start from a ready-made team.';
+ assert.equal(m.needError(E(502, { error: 'The draft came back unusable twice.', code: 'draft_failed' })).head, failed);
+ assert.equal(m.needError(E(502, { error: 'The draft came back unusable twice.', code: 'draft_failed' })).reason, 'The draft came back unusable twice.');
+ const na = m.needError(E(409, { error: 'No account in this space can run right now.', code: 'no_ready_account' }));
+ assert.equal(na.noAccount, true);
+ assert.equal(na.head, 'Add an AI account first.');
+ assert.equal(m.needError(E(409, { code: 'busy' })).head, 'Already suggesting a team here.');
+ const lim = m.needError(E(429, { code: 'limited', account: 'Claude', until: '2026-11-12T21:10:00Z' }));
+ assert.equal(lim.head, failed);
+ assert.match(lim.reason, /Claude/);
+ assert.equal(m.needError(new m.TeamsError('x', 0, 'offline')).head, 'You’re offline.');
+ assert.equal(m.needError(new Error('boom')).head, failed);
+ assert.equal(m.listWords(['customer emails', 'reply drafts']), 'customer emails and reply drafts');
+ assert.equal(m.listWords(['a', 'b', 'c']), 'a, b and c');
+});
+
+test('fixture: the bakery answer has the server contract’s shape (brief "Server contract")', () => {
+ const s = fx.BAKERY_SUGGESTION;
+ assert.equal(s.bots.length, 4);
+ assert.equal(s.bots.filter((b) => b.lead).length, 1);
+ assert.deepEqual(s.facts, []);
+ assert.deepEqual(s.read, { files: 0, manifests: 0, ms: 0 });
+ assert.equal(s.partial, null);
+ assert.equal(s.stack_line, null);
+ assert.equal(s.fallback, false);
+ assert.equal(s.need, NEED);
+ for (const b of s.bots) {
+ assert.ok(b.owns.length > 0, `${b.name} owns something`);
+ assert.ok(b.reason.length > 0, `${b.name} has a reason`);
+ assert.ok(b.instructions && b.instructions.length > 20, `${b.name} has instructions`);
+ }
+});
+
+test('Get ready card: step 2 is "Add your bots" with the box, the ready-made line and add one bot', async () => {
+ use({});
+ const { el, out } = card();
+ const v = await mount(el);
+ const c = document.querySelector('#card');
+ assert.match(c.textContent, /Add your bots/);
+ const ta = box();
+ assert.ok(ta, 'the box is there');
+ assert.equal(ta.labels[0].textContent, 'What should your bots do?');
+ assert.equal(ta.placeholder, 'e.g. I run a small bakery: answer customer emails, post on Instagram, keep track of orders');
+ assert.equal(submitBtn().textContent, 'Suggest a team');
+ const line = c.querySelector('[data-ready-made-line]');
+ assert.match(line.textContent, /^Or start from a ready-made team:Inbox · Sales · Coding · or add one bot$/);
+ assert.equal(byText(c, 'button', /^New bot$/), undefined, 'New bot moved into the line');
+ await click(byText(line, 'button', /^add one bot$/));
+ assert.equal(out.newBot, 1);
+ await click(line.querySelector('[data-template="inbox"]'));
+ assert.ok(document.querySelector('[data-team-sheet="inbox"]'), 'Inbox opens its preview');
+ await key(document.querySelector('[data-team-sheet="inbox"]'), 'Escape');
+ assert.match(c.textContent, /Message #general/, 'step 3 stays');
+ v.unmount();
+});
+
+test('submit: Suggesting… locks the box, then the sheet opens on the bakery team; nothing is created yet', async () => {
+ const calls = use({});
+ const { el } = card();
+ const v = await mount(el);
+ await typeArea(box(), ` ${NEED} `);
+ submitBtn().dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await new Promise((r) => setTimeout(r, 0));
+ const ask = asks(calls).at(-1);
+ assert.equal(ask.url, '/api/teams/suggest?space=spc_demo');
+ assert.deepEqual(ask.body, { need: NEED }, 'only { need }, trimmed');
+ await settle();
+ const s = theSheet();
+ assert.ok(s, 'the sheet opens');
+ assert.equal(s.querySelector('h3').textContent, 'Suggested team');
+ assert.match(s.querySelector('[data-asked]').textContent, /I run a small bakery/);
+ const rows = [...s.querySelectorAll('[data-row]')];
+ assert.equal(rows.length, 4);
+ assert.match(s.textContent, /ShopLead\s*Leads/);
+ assert.match(rows[1].querySelector('[data-takes-care]').textContent, /^Takes care of customer emails and reply drafts$/);
+ // Hidden for a team from words: the read line, partial notes, the stack line, and Coding's role picker.
+ assert.doesNotMatch(s.textContent, /What it found|In every persona|Use the Coding roster|Owns /);
+ assert.equal(s.querySelector('[aria-haspopup="listbox"]'), null);
+ assert.equal(creates(calls).length, 0, 'nothing is created before Create');
+ // Instructions: an expander per bot, closed at first, read-only text.
+ const exp = byText(rows[1], 'button', /^Instructions/);
+ assert.equal(exp.getAttribute('aria-expanded'), 'false');
+ await click(exp);
+ assert.equal(exp.getAttribute('aria-expanded'), 'true');
+ const pane = document.getElementById(exp.getAttribute('aria-controls'));
+ assert.match(pane.querySelector('pre').textContent, /Never send without the owner’s OK/);
+ assert.equal(pane.querySelector('textarea, input'), null, 'instructions are read-only');
+ v.unmount();
+});
+
+test('Enter submits, Shift+Enter is a new line; too few words stay in the box with a note', async () => {
+ const calls = use({});
+ const { el } = card();
+ const v = await mount(el);
+ await typeArea(box(), 'bakery');
+ await key(box(), 'Enter');
+ assert.equal(asks(calls).length, 0, 'too short is not sent');
+ assert.match(document.querySelector('#card').textContent, /Add a few more words so the team fits\./);
+ assert.equal(box().getAttribute('aria-invalid'), 'true');
+ await typeArea(box(), NEED);
+ await key(box(), 'Enter', { shiftKey: true });
+ assert.equal(asks(calls).length, 0, 'Shift+Enter does not submit');
+ await key(box(), 'Enter');
+ assert.equal(asks(calls).length, 1);
+ assert.ok(theSheet());
+ v.unmount();
+});
+
+test('no ready account: the box stays, the button reads "Add an AI account first" and opens Accounts', async () => {
+ const calls = use({});
+ const { el, out } = card({}, { readyAccounts: 0 });
+ const v = await mount(el);
+ assert.ok(box(), 'the box stays');
+ assert.equal(box().readOnly, false, 'you can still type');
+ assert.equal(submitBtn().textContent, 'Add an AI account first');
+ await typeArea(box(), NEED);
+ await key(box(), 'Enter');
+ assert.equal(asks(calls).length, 0, 'Enter sends nothing without an account');
+ await click(submitBtn());
+ assert.equal(out.accounts, 1);
+ assert.equal(asks(calls).length, 0);
+ v.unmount();
+
+ // The server says so (409 no_ready_account): same button, words kept.
+ use({ need: 'no_ready_account' });
+ const b = card();
+ const v2 = await mount(b.el);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ assert.match(document.querySelector('[data-need-error]').textContent, /Add an AI account first\./);
+ assert.equal(submitBtn().textContent, 'Add an AI account first');
+ assert.equal(box().value, NEED);
+ await click(submitBtn());
+ assert.equal(b.out.accounts, 1);
+ v2.unmount();
+});
+
+test('errors keep the words and show the server’s reason (502, 429, busy, offline)', async () => {
+ for (const [sc, re] of [
+ ['draft_failed', /Couldn’t suggest a team this time\. Try again, or start from a ready-made team\.The draft came back unusable twice\./],
+ ['limit', /Couldn’t suggest a team this time\..*Claude is out until 21:10\./],
+ ['busy', /Already suggesting a team here\./],
+ ['offline', /You’re offline\./],
+ ]) {
+ use({ need: sc });
+ const { el } = card();
+ const v = await mount(el);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ const err = document.querySelector('[data-need-error]');
+ assert.ok(err, `${sc}: an error shows`);
+ assert.equal(err.getAttribute('role'), 'alert');
+ assert.match(err.textContent, re, sc);
+ assert.equal(box().value, NEED, `${sc}: the words are kept`);
+ assert.equal(box().readOnly, false, `${sc}: the box unlocks`);
+ assert.equal(theSheet(), null, `${sc}: no sheet`);
+ assert.equal(submitBtn().textContent, 'Suggest a team');
+ v.unmount();
+ }
+});
+
+test('Escape or Cancel stops Suggesting…; the words stay; after 8 s it adds "Usually under a minute."', async () => {
+ const realST = window.setTimeout;
+ // The 8-second note: run that one timer at once.
+ window.setTimeout = (fn, ms, ...a) => realST(fn, ms === 8000 ? 0 : ms, ...a);
+ try {
+ const calls = use({ need: 'slow' });
+ const { el } = card();
+ const v = await mount(el);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ assert.equal(stops(calls).length, 0);
+ assert.equal(submitBtn().textContent, 'Suggesting…');
+ assert.equal(submitBtn().getAttribute('aria-disabled'), 'true');
+ assert.equal(box().readOnly, true, 'the box locks');
+ assert.match(document.querySelector('#card').textContent, /Usually under a minute\./);
+ await key(box(), 'Escape');
+ assert.deepEqual(stops(calls).map((c) => c.url), ['/api/teams/suggest?space=spc_demo'], 'Escape stops the server too; its 404 is ignored');
+ assert.equal(document.querySelector('#card [role="alert"]'), null, 'no error for the 404');
+ assert.equal(submitBtn().textContent, 'Suggest a team');
+ assert.equal(box().readOnly, false);
+ assert.equal(box().value, NEED);
+ assert.equal(theSheet(), null);
+ // Cancel does the same.
+ await click(submitBtn());
+ await click(byText(document.querySelector('#card'), 'button', /^Cancel$/));
+ assert.equal(stops(calls).length, 2, 'Cancel too');
+ assert.equal(submitBtn().textContent, 'Suggest a team');
+ assert.equal(box().value, NEED);
+ v.unmount();
+ } finally {
+ window.setTimeout = realST;
+ }
+});
+
+test('Try again sends the same words again and shows the new team; Escape while asking keeps the last one', async () => {
+ const calls = use({ need: 'again' });
+ const { el } = card();
+ const v = await mount(el);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ let s = theSheet();
+ assert.equal(s.querySelectorAll('[data-row]').length, 4);
+ await click(byText(s, 'button', /^Try again$/));
+ const sent = asks(calls).map((c) => c.body);
+ assert.equal(sent.length, 2);
+ assert.deepEqual(sent[1], sent[0], 'the same need');
+ s = theSheet();
+ assert.equal(s.querySelectorAll('[data-row]').length, 3, 'the second draft');
+ assert.match(s.textContent, /Baker/);
+ v.unmount();
+
+ // A slow second ask: Escape stops it and the first team stays.
+ const realST = window.setTimeout;
+ let calls2 = [];
+ let n = 0;
+ const base = fx.fixtureTransport({}, calls2);
+ m.setTeamsTransport(async (url, method, body, headers) => {
+ if (url.startsWith('/api/teams/suggest') && method !== 'DELETE' && ++n > 1) {
+ calls2.push({ url, method, body });
+ return new Promise(() => {});
+ }
+ return base(url, method, body, headers);
+ });
+ const b = card();
+ const v2 = await mount(b.el);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ await click(byText(theSheet(), 'button', /^Try again$/));
+ assert.match(theSheet().textContent, /Suggesting…/);
+ assert.equal(stops(calls2).length, 0);
+ await key(theSheet(), 'Escape');
+ assert.equal(stops(calls2).length, 1, 'Escape during Try again stops the server’s ask');
+ assert.ok(theSheet(), 'the sheet stays');
+ assert.equal(theSheet().querySelectorAll('[data-row]').length, 4, 'the last team is back');
+ await key(theSheet(), 'Escape');
+ assert.equal(stops(calls2).length, 1, 'closing a ready sheet sends no stop');
+ assert.equal(theSheet(), null, 'a second Escape closes it');
+ assert.equal(box().value, NEED, 'the words are still in the box');
+ window.setTimeout = realST;
+ v2.unmount();
+});
+
+test('Create sends suggestion_id + edits (untick, rename) to from-template; the toast offers Undo', async () => {
+ const calls = use({});
+ const realFetch = g.fetch;
+ const undos = [];
+ g.fetch = g.window.fetch = async (url, init) => {
+ if (String(url).includes('/api/bot-actions/')) {
+ undos.push(String(url));
+ return new Response(JSON.stringify({ id: 'act_demo', status: 'undone', can_undo: false }), { status: 200, headers: { 'Content-Type': 'application/json' } });
+ }
+ return new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } });
+ };
+ try {
+ const { el, out } = card();
+ const v = await mount(el);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ const s = theSheet();
+ // decisions-1112 §4: no Team handle field for a team from words; the project suggest flows keep it.
+ assert.equal(s.querySelector('[aria-label="Team handle"]'), null);
+ assert.equal(/Team handle/.test(s.textContent), false);
+ // Untick the Instagram bot, rename the order keeper.
+ await click(s.querySelector('[data-row="social"] [role="checkbox"]'));
+ await click(s.querySelector('[aria-label="Rename OrderKeeper"]'));
+ const input = s.querySelector('[aria-label^="Name for"]');
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(input, 'Orders');
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle(2);
+ await key(input, 'Enter');
+ const create = byText(s, 'button', /^Create team · 3 bots$/);
+ assert.ok(create, 'Create team · 3 bots');
+ await click(create);
+ const c = creates(calls);
+ assert.equal(c.length, 1);
+ assert.equal(c[0].url, '/api/teams/from-template?space=spc_demo');
+ assert.deepEqual(c[0].body, {
+ suggestion_id: 'sug_demo_bakery',
+ edits: {
+ rows: { lead: { on: true, name: 'ShopLead' }, inbox: { on: true, name: 'CustomerMail' }, social: { on: false }, orders: { on: true, name: 'Orders' } },
+ },
+ }, 'no handle: the server picks a free one (decisions-1112 §4)');
+ assert.ok(c[0].headers?.['Idempotency-Key'], 'one idempotency key per open');
+ assert.equal(theSheet(), null);
+ assert.equal(out.opened.length, 1);
+ const toast = byText(document.body, '[role="status"], div', /Created @bakery: 3 bots\./);
+ assert.ok(toast, 'Created toast');
+ await click(byText(document.body, 'button', /^\s*Undo$/));
+ assert.deepEqual(undos, ['/api/bot-actions/act_demo/undo']);
+ assert.ok(byText(document.body, 'div', /Removed @bakery\./));
+ assert.equal(out.undone, 1);
+ assert.equal(box().value, '', 'the words go after a create');
+ v.unmount();
+ } finally {
+ g.fetch = g.window.fetch = realFetch;
+ }
+});
+
+test('sidebar chip "Describe your own": focuses the card’s box; without the card it opens the box in a small sheet', async () => {
+ use({});
+ const { el } = card();
+ const v = await mount(el);
+ const chip = document.querySelector('#side [data-describe-own]');
+ assert.ok(chip, 'the first chip');
+ assert.equal(document.querySelector('#side [data-template-sidebar] button[data-describe-own]'), document.querySelector('#side [data-template-sidebar] .flex button'), 'it comes first');
+ assert.equal(chip.textContent, 'Describe your own');
+ await click(chip);
+ assert.equal(document.activeElement, box(), 'focuses the card’s box');
+ assert.equal(document.querySelector('[data-need-sheet]'), null);
+ v.unmount();
+
+ // No card on screen: a small sheet with the same box; Cancel in the preview brings it back.
+ const calls = use({});
+ const v2 = await mount(h(m.ReadyTeamsProvider, { space: 'spc_demo', bots: [], teams: [], onChanged() {}, onOpenTeam() {}, readyAccounts: 1 }, h('div', { id: 'side' }, h(m.ReadyTeamsSidebarBox, { teamCount: 0 }))));
+ await click(document.querySelector('#side [data-describe-own]'));
+ const ns = document.querySelector('[data-need-sheet]');
+ assert.ok(ns, 'the small sheet opens');
+ assert.equal(ns.getAttribute('role'), 'dialog');
+ assert.match(ns.textContent, /Describe your own team/);
+ const ta = ns.querySelector('textarea');
+ await typeArea(ta, NEED);
+ await key(ta, 'Enter');
+ assert.equal(asks(calls).length, 1);
+ assert.equal(document.querySelector('[data-need-sheet]'), null, 'it steps aside for the preview');
+ assert.ok(theSheet());
+ await key(theSheet(), 'Escape');
+ const back = document.querySelector('[data-need-sheet]');
+ assert.ok(back, 'Cancel brings it back');
+ assert.equal(back.querySelector('textarea').value, NEED, 'with the words');
+ await key(back, 'Escape');
+ assert.equal(document.querySelector('[data-need-sheet]'), null);
+ v2.unmount();
+});
+
+test('New team: "Describe what this team should do" above the form; Suggest members from the code stays', async () => {
+ const calls = use({});
+ let closed = 0;
+ const v = await mount(
+ h(m.ReadyTeamsProvider, { space: 'spc_demo', bots: [], teams: [], onChanged() {}, onOpenTeam() {}, readyAccounts: 1 }, h(m.NewTeamModal, { isOpen: true, onClose: () => closed++, kwants: [] })),
+ );
+ const ta = [...document.querySelectorAll('textarea')].find((t) => t.labels?.[0]?.textContent === 'Describe what this team should do');
+ assert.ok(ta, 'the box with its label');
+ const form = document.querySelector('form');
+ assert.ok(ta.compareDocumentPosition(form) & 4, 'above the manual form');
+ await typeArea(ta, NEED);
+ await key(ta, 'Enter');
+ assert.equal(asks(calls).length, 1);
+ const dlg = document.querySelector('.kw-dialog');
+ assert.equal(dlg.hidden, true, 'New team hides while the preview is open');
+ await key(theSheet(), 'Escape');
+ assert.equal(dlg.hidden, false, 'and comes back on Cancel');
+ assert.equal(ta.value, NEED);
+ await key(ta, 'Enter');
+ await click(byText(theSheet(), 'button', /^Create team · 4 bots$/));
+ assert.equal(creates(calls).length, 1);
+ assert.equal(closed, 1, 'New team closes after a create');
+ assert.match(readFileSync(new URL('../src/components/NewTeamModal.tsx', import.meta.url), 'utf8'), /<SuggestMembersButton/);
+ v.unmount();
+});
+
+test('phone (390 px): the preview is a bottom sheet; the box’s buttons are 44 px tall', async () => {
+ phone = true;
+ try {
+ use({});
+ const { el } = card();
+ const v = await mount(el);
+ assert.match(submitBtn().className, /\bh-11\b/);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ const s = theSheet();
+ assert.match(s.className, /bottom-0/);
+ assert.match(s.className, /rounded-t-2xl/);
+ v.unmount();
+ } finally {
+ phone = false;
+ }
+});
+
+test('never renders HTML from the server: instructions and owns are text', async () => {
+ const calls = [];
+ const base = fx.fixtureTransport({}, calls);
+ m.setTeamsTransport(async (url, method, body, headers) => {
+ const r = await base(url, method, body, headers);
+ if (url.startsWith('/api/teams/suggest')) {
+ const b = structuredClone(r.body);
+ b.bots[1].instructions = '<img src=x onerror="window.__pwned=1">Hi';
+ b.bots[1].owns = ['<b>emails</b>'];
+ return { ...r, body: b };
+ }
+ return r;
+ });
+ const { el } = card();
+ const v = await mount(el);
+ await typeArea(box(), NEED);
+ await click(submitBtn());
+ const row = theSheet().querySelector('[data-row="inbox"]');
+ await click(byText(row, 'button', /^Instructions/));
+ assert.equal(row.querySelector('img, b'), null);
+ assert.match(row.textContent, /<img src=x/);
+ assert.equal(window.__pwned, undefined);
+ v.unmount();
+});
diff --git a/frontend/tests/teamTemplates.test.mjs b/frontend/tests/teamTemplates.test.mjs
index 2be0dee0..dd80abf1 100644
--- a/frontend/tests/teamTemplates.test.mjs
+++ b/frontend/tests/teamTemplates.test.mjs
@@ -348,6 +348,7 @@ test('D: reads one source, shows the stack, the reasons with paths, the existing
assert.equal(s.url, '/api/teams/suggest?space=spc_demo');
assert.deepEqual(s.body, { workspace_path: '~/projects/shop' });
assert.match(root.textContent, /Suggested team for shop/);
+ assert.ok(root.querySelector('[aria-label="Team handle"]'), 'a project suggest keeps the handle field (decisions-1112 §4)');
assert.match(root.textContent, /Rust \(axum\)/);
assert.match(root.textContent, /server\/Cargo\.toml/);
assert.ok(root.querySelector('[data-row="frontend"]'));
@@ -385,7 +386,7 @@ test('D: a 410 reads the project again and keeps the edits on rows that come bac
await click(primary(root));
assert.equal(out.created, null);
assert.match(root.textContent, /Read the project again, it had been an hour\./);
- assert.equal(calls.filter((c) => c.url.startsWith('/api/teams/suggest')).length, 2);
+ assert.equal(calls.filter((c) => c.url.startsWith('/api/teams/suggest') && c.method !== 'DELETE').length, 2);
assert.match(primary(root).textContent, /Create team · 3 bots/);
await click(primary(root));
assert.deepEqual(creates(calls)[1].body.edits.rows.sre, { on: false });
@@ -853,10 +854,10 @@ test('N-5: after folder_in_use the main button picks another folder instead of "
let btn = primary(root);
assert.equal(btn.textContent, 'Pick another folder');
assert.equal(btn.disabled, false);
- const reads = calls.filter((c) => c.url.startsWith('/api/teams/suggest')).length;
+ const reads = calls.filter((c) => c.url.startsWith('/api/teams/suggest') && c.method !== 'DELETE').length;
await click(btn);
assert.equal(picked, 1);
- assert.equal(calls.filter((c) => c.url.startsWith('/api/teams/suggest')).length, reads, 'the same folder is not read again');
+ assert.equal(calls.filter((c) => c.url.startsWith('/api/teams/suggest') && c.method !== 'DELETE').length, reads, 'the same folder is not read again');
v.unmount();
// Create refused after a good read: the same.
calls = failing(400, { error: said, code: 'folder_in_use', field: 'workspace_path' });