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.

Space controls: Dev mode explainer and switch v3 (0.7.2) (#360)

Oleksandr Ivanchenkod71744785ed0
diff --git a/frontend/src/approvalMode.ts b/frontend/src/approvalMode.ts
index 6bd9b498..a07b5938 100644
--- a/frontend/src/approvalMode.ts
+++ b/frontend/src/approvalMode.ts
@@ -103,6 +103,36 @@ export function spaceOffLine(space: SpaceApprovals | undefined, bots: Array<{ ap
return off ? `Approvals off for ${off} ${off === 1 ? 'bot' : 'bots'}` : null;
}
+/** Explainer spec §2, Approvals row: the chip, its tone and the one line under it (or null). */
+export interface ApprovalsRow {
+ value: SpaceApprovals;
+ chip: 'Ask' | 'When risky' | 'Off';
+ tone: 'neutral' | 'warn';
+ sub: string | null;
+ /** The value button's name: "Approvals: Off. Change in space settings". */
+ label: string;
+ /** Desktop tooltip, only when approvals are off. */
+ title: string | null;
+}
+
+const CHIP: Record<SpaceApprovals, ApprovalsRow['chip']> = { ask: 'Ask', smart: 'When risky', off: 'Off' };
+export const APPROVALS_OFF_TITLE = 'Bots here act without asking, including deletions, publishing and sign-ins. Payments still ask you. Change it in Settings › This space.';
+export const APPROVALS_OFF_TITLE_DEV = ' With Dev mode on, pushes to main, deploys and deleting data still ask.';
+
+/** null on an older server that doesn't say the space's approvals: the row isn't drawn rather than guessed. */
+export function approvalsRow(space: SpaceApprovals | undefined, bots: Array<{ approvals_effective?: string | null }>, devOn: boolean): ApprovalsRow | null {
+ if (space !== 'ask' && space !== 'smart' && space !== 'off') return null;
+ const chip = CHIP[space];
+ const label = `Approvals: ${chip}. Change in space settings`;
+ if (space === 'off') {
+ const asking = bots.filter((b) => b.approvals_effective === 'ask' || b.approvals_effective === 'smart').length;
+ const sub = asking ? (asking === 1 ? '1 bot still asks' : `${asking} bots still ask`) : devOn ? 'Main and deploys still ask' : 'Bots act without asking';
+ return { value: space, chip, tone: 'warn', sub, label, title: APPROVALS_OFF_TITLE + (devOn ? APPROVALS_OFF_TITLE_DEV : '') };
+ }
+ const off = bots.filter(approvalsOff).length;
+ return { value: space, chip, tone: 'neutral', sub: off ? `Off for ${off} ${off === 1 ? 'bot' : 'bots'}` : null, label, title: null };
+}
+
async function errorText(res: Response, fallback: string): Promise<string | NeedsBitwardenError> {
try {
const body = await res.json();
diff --git a/frontend/src/components/DevDesk.tsx b/frontend/src/components/DevDesk.tsx
index e5588116..665db8d1 100644
--- a/frontend/src/components/DevDesk.tsx
+++ b/frontend/src/components/DevDesk.tsx
@@ -4,7 +4,7 @@
import React, { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
import { ChevronLeft, Code, RefreshCw } from 'lucide-react';
-import { DEV_OFF, DevModeState, checkedLabel, DevTeamRef, cardRepoLabel, cardsOfRepo, devApi, devStore, deskStatus, firstRun, repoFilters, reposSummary, statusLine } from '../devMode';
+import { DEV_FEATURES, DEV_OFF, DevModeState, checkedLabel, DevTeamRef, cardRepoLabel, cardsOfRepo, devApi, devStore, deskStatus, firstRun, repoFilters, reposSummary, statusLine } from '../devMode';
import { FindingAction, LandedPage, ShellCard, asCard, parseCards, parseLandedPage } from '../dev/shellTypes';
import { LandedList, ReleaseNotesSheet, ReviewCard, Rollup } from './DevDeskSlots';
import { useDevMode } from './DevModeSwitch';
@@ -585,11 +585,8 @@ const TermEmpty: React.FC<{ cmd?: string; out: string; title: string; line: stri
// First run (flow copy §5): a terminal-style block above the cards on the first visit only. Got it hides
// it for good; it is the only control.
-export const DEV_FEATURES = [
- { key: 'landed', n: '01', title: 'What landed.', line: 'Every merge to main in plain words, and when main is ready to ship.' },
- { key: 'reviews', n: '02', title: 'Reviews.', line: 'A second bot reads each pull request before you merge it.' },
- { key: 'floor', n: '03', title: 'Production floor.', line: 'Deploys and live-database commands wait for your OK.' },
-] as const;
+/** Shared with the explainer card (spec §4); re-exported for callers. */
+export { DEV_FEATURES };
// cmd is the terminal line the intro types out (copy.md §5), not prose.
const DevIntro: React.FC<{ repo: string | null; onClose: () => void; cmd: string }> = ({ repo, onClose, cmd }) => (
diff --git a/frontend/src/components/DevModeSwitch.tsx b/frontend/src/components/DevModeSwitch.tsx
index 0d89d761..f59227a7 100644
--- a/frontend/src/components/DevModeSwitch.tsx
+++ b/frontend/src/components/DevModeSwitch.tsx
@@ -1,9 +1,9 @@
-// The Dev mode switch in the sidebar space header (style v2 §10, flow F1/F2/F9): the Branch switch.
-// Off has no cover: one press turns it on (F1). On is covered by a 1 px violet ring and a lock; turning
-// it off takes two presses (F2): press 1 arms (2 px amber ring, open lock, `off?`), press 2 within 5 s
-// turns it off. Armed drops back after 5 s, on Esc or when focus leaves. Presses are ignored while a
-// flip settles (450 ms), so a double-click on Off can't turn it on and arm it. 0.7.1 (any-git S5):
-// there is no setup sheet; the server finds the repo and the Dev desk says what it found.
+// The Dev mode switch in the space controls (explainer spec §3, flow F1/F2/F9): switch v3, a state word
+// (Off / On / Off?) next to a track and knob. One press turns it on (F1). Turning it off takes two presses
+// (F2): press 1 arms (amber track ring, open lock, "Off?"), press 2 within 5 s turns it off. Armed drops
+// back after 5 s, on Esc or when focus leaves. Presses are ignored while a flip settles (450 ms), so a
+// double-click on Off can't turn it on and arm it. The armed line itself is the Dev mode row's sub-line;
+// the polite live region here still announces it.
import React, { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
import { Lock, LockOpen, X } from 'lucide-react';
@@ -53,6 +53,13 @@ export interface DevModeSwitchProps {
onTurnedOff?: () => void;
/** The person turned it on here (flow F3): the sidebar shows the toast. Never for a space already on. */
onTurnedOn?: (s: DevModeState) => void;
+ /** In the space controls: the row's label and sub-line name and describe the switch (spec §5). */
+ labelledBy?: string;
+ describedBy?: string;
+ /** Armed (press 1 of 2) and not-the-owner, for the row's sub-line and the explainer. */
+ onLook?: (look: { armed: boolean; disabled: boolean; on: boolean; failed: boolean }) => void;
+ /** The button, so the explainer's "Turn on Dev mode" can press it and give it focus. */
+ buttonRef?: React.MutableRefObject<HTMLButtonElement | null>;
/** Test hooks: start in a given state, and a clock. */
initial?: Partial<SwitchState>;
now?: () => number;
@@ -79,7 +86,7 @@ export const lastOn = {
},
};
-export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = false, onTurnedOff, onTurnedOn, initial, now = Date.now }) => {
+export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = false, onTurnedOff, onTurnedOn, labelledBy, describedBy, onLook, buttonRef, initial, now = Date.now }) => {
const reduced = useReducedMotion();
const known = useDevMode(space.id);
// Until this space's state loads, start from the last value seen here, so a space that is on doesn't
@@ -90,10 +97,12 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
// Never seen here and not loaded yet: neither on nor off (no node on the graph, busy) until dev_mode
// answers, so an on space never reads "off" for a moment (QA F8-R3-1).
const [loading, setLoading] = useState(() => !known && !initial && lastOn.get(space.id) === null);
+ // The first load failed: the row's sub-line stops waiting for a repo list (addendum 3).
+ const [failed, setFailed] = useState(false);
// The reducer's truth lives in the ref, written only by dispatch. Copying `state` into it on render
// would let a render that started before a dispatch (a store update mid-save) put an older state back.
const ref = useRef(state);
- const btn = useRef<HTMLButtonElement>(null);
+ const btn = useRef<HTMLButtonElement | null>(null);
const dispatch = useCallback(
(a: SwitchAction): SwitchState => {
@@ -118,6 +127,7 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
(e: unknown) => {
if (!live) return;
setLoading(false);
+ setFailed(true);
dispatch({ type: 'server', state: null, disabled: e instanceof DevModeError && (e.status === 403 || e.status === 404) });
},
);
@@ -171,83 +181,69 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
const look = switchLook(state);
const descId = useId();
- const hint = look.hint && (
- <span
- role="presentation"
- className={
- phone
- ? 'kw-dv-hint fixed inset-x-4 mx-auto w-fit max-w-[calc(100vw-32px)] text-center leading-snug bottom-[calc(56px+env(safe-area-inset-bottom)+12px)] z-40 rounded-lg border border-white/14 bg-surface-overlay px-2.5 py-1.5 text-meta text-zinc-100 shadow-raised'
- : 'kw-dv-hint absolute -left-[52px] top-full mt-1.5 z-30 whitespace-nowrap rounded-lg border border-white/14 bg-surface-overlay px-2 py-1.5 text-meta text-zinc-100 shadow-raised'
- }
- aria-hidden="true"
- data-dv-hint
- >
- {look.hint}
- {!phone && <kbd className="dv-kbd ml-1.5">Esc</kbd>}
- </span>
- );
-
- const common = {
- ref: btn,
- type: 'button' as const,
- onClick: press,
- onKeyDown: (e: React.KeyboardEvent) => {
- if (e.key === 'Escape' && ref.current.phase === 'lifted') {
- e.stopPropagation();
- dispatch({ type: 'escape' });
- }
+ const armed = look.look === 'armed';
+ const disabled = state.disabled;
+ useEffect(() => onLook?.({ armed, disabled, on: state.on, failed }), [onLook, armed, disabled, state.on, failed]);
+ const setBtn = useCallback(
+ (el: HTMLButtonElement | null) => {
+ btn.current = el;
+ if (buttonRef) buttonRef.current = el;
},
- onBlur: () => dispatch({ type: 'blur' }),
- disabled: state.disabled || loading,
- 'aria-busy': loading || undefined,
- role: 'switch' as const,
- 'aria-checked': state.on,
- 'aria-label': look.label,
- 'aria-describedby': descId,
- title: look.tooltip,
- 'data-dev-switch': loading ? 'loading' : state.phase,
- 'data-look': look.look,
- 'data-on': state.on || undefined,
- 'data-ring': look.ring || undefined,
- 'data-knob': look.knobRight ? 'right' : 'left',
- 'data-cover': look.coverOpen ? 'open' : 'closed',
- style: { ['--kw-dv-fill' as string]: String(look.fill) } as React.CSSProperties,
- };
+ [buttonRef],
+ );
- // The Branch switch (style v2 §10): a mono label and a tiny git graph. The node sits on the line
- // when off and hops onto the fork when on; then the cover (a 1 px violet ring, ::after) closes and a
- // lock shows. Armed (only ever while on) lifts it: 2 px amber ring, open lock, the fork dashed amber
- // with a halo on the node, `off?`. Reduced motion keeps the same shapes, instantly (kw-dv-rm).
- const armed = look.look === 'armed';
- const word = armed ? 'off?' : 'dev';
+ // Switch v3 (spec §3): the state word, then a 40×22 track with a 16 px knob. Off: a hollow node at the
+ // left. On: the knob at the right with a pip, a small lock in the track. Armed: amber ring, open lock,
+ // "Off?". Not colour alone: the word, the knob's side and the lock all change.
+ const word = loading ? '' : armed ? 'Off?' : state.on ? 'On' : 'Off';
const button = (
<button
- {...common}
+ ref={setBtn}
+ type="button"
+ onClick={press}
+ onKeyDown={(e: React.KeyboardEvent) => {
+ if (e.key === 'Escape' && ref.current.phase === 'lifted') {
+ e.stopPropagation();
+ dispatch({ type: 'escape' });
+ }
+ }}
+ onBlur={() => dispatch({ type: 'blur' })}
+ // Not the owner: still focusable so the reason (title) can be read; presses do nothing (reducer).
+ disabled={loading}
+ aria-disabled={disabled || undefined}
+ aria-busy={loading || state.saving || undefined}
+ role="switch"
+ aria-checked={state.on}
+ {...(labelledBy ? { 'aria-labelledby': labelledBy } : { 'aria-label': look.label })}
+ aria-describedby={describedBy ?? descId}
+ title={look.tooltip}
+ data-dev-switch={loading ? 'loading' : state.phase}
+ data-look={look.look}
+ data-on={state.on || undefined}
+ data-ring={look.ring || undefined}
+ data-knob={look.knobRight ? 'right' : 'left'}
+ data-cover={look.coverOpen ? 'open' : 'closed'}
data-armed={armed || undefined}
+ // Answer 1 (0.7.2): the only "busy" sign is this spinner, and only while the PUT is in flight.
+ data-saving={state.saving || undefined}
data-covered={(look.ring && !armed) || undefined}
- className={`kw-dv${state.reduced ? ' kw-dv-rm' : ''}${phone ? ' h-11' : ''} focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400`}
+ className={`kw-dv${state.reduced ? ' kw-dv-rm' : ''}${phone ? ' h-11' : ''}`}
>
- {look.glyph === 'locked' && <Lock size={10} strokeWidth={2.5} className="kw-dv-lock" aria-hidden="true" data-dv-glyph="locked" />}
- {look.glyph === 'unlocked' && <LockOpen size={10} strokeWidth={2.5} className="kw-dv-lock" aria-hidden="true" data-dv-glyph="unlocked" />}
- <span className="kw-dv-lbl" aria-hidden="true" data-dv-word>
+ <span className="kw-dv-val" aria-hidden="true" data-dv-word>
{word}
</span>
- <svg className="kw-dv-graph" viewBox="0 0 44 24" aria-hidden="true" data-dv-graph>
- <path className="kw-dv-base" d="M2 17H42" />
- <path className="kw-dv-fork" d="M12 17C19 17 18 7 26 7H42" />
- <g className="kw-dv-node" visibility={loading ? 'hidden' : undefined}>
- <circle className="kw-dv-halo" cx="12" cy="17" r="5" />
- <circle className="kw-dv-dot" cx="12" cy="17" r="5" />
- <circle className="kw-dv-pip" cx="12" cy="17" r="1.6" />
- </g>
- </svg>
+ <span className="kw-dv-track" aria-hidden="true" data-dv-track>
+ {look.glyph === 'locked' && state.on && <Lock size={10} strokeWidth={2.5} className="kw-dv-lock" data-dv-glyph="locked" />}
+ {look.glyph === 'locked' && !state.on && <span className="sr-only" data-dv-glyph="locked" />}
+ {look.glyph === 'unlocked' && <LockOpen size={10} strokeWidth={2.5} className="kw-dv-lock" data-dv-glyph="unlocked" />}
+ <span className="kw-dv-knob" data-dv-knob style={loading ? { visibility: 'hidden' } : undefined} />
+ </span>
</button>
);
return (
<span className={`relative inline-flex shrink-0 items-center justify-center ${phone ? 'min-w-[44px] min-h-[44px]' : ''}`} data-dev-switch-wrap>
{button}
- {hint}
<span id={descId} className="sr-only" data-dv-describe>
{look.describe}
</span>
@@ -255,7 +251,7 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
{state.announce ? <span key={state.announce.seq}>{state.announce.text}</span> : null}
</span>
{state.error && !state.saving && state.phase === 'covered' && (
- <span role="alert" className="absolute right-0 top-full mt-1.5 z-30 w-56 rounded-lg border border-rose-300/30 bg-surface-overlay px-2.5 py-1.5 text-meta text-bad">
+ <span role="alert" className="absolute right-0 top-full mt-1.5 z-30 w-56 max-w-[calc(100vw-32px)] rounded-lg border border-rose-300/30 bg-surface-overlay px-2.5 py-1.5 text-meta text-bad">
{state.error}
</span>
)}
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 10cdf054..043ae4d3 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useState } from 'react';
-import { Hash, Plus, CheckCircle2, ShieldCheck, KeyRound, Loader2, Users, ChevronDown, Settings, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, ShieldOff, Split, Hand, MoreHorizontal, UserMinus, MessageSquare, KanbanSquare } from 'lucide-react';
+import { Hash, Plus, CheckCircle2, ShieldCheck, KeyRound, Loader2, Users, ChevronDown, Settings, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, Split, Hand, MoreHorizontal, UserMinus, MessageSquare, KanbanSquare } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { playSfx } from '../audio/chiptune';
import { badgeText } from '../away';
@@ -11,13 +11,14 @@ import { Space, spaceSummary, spaceSummaryTitle } from '../spaces';
import { SpaceSwitcher, SpaceTile } from './Spaces';
import { isMac } from './LayaStatus';
import { ApprovalsOffBadge } from './ApprovalsSetting';
-import { approvalsOff, spaceOffLine } from '../approvalMode';
+import { approvalsOff } from '../approvalMode';
import { teamChannelOf } from '../teamChannel';
import { layaRoutes } from '../channels';
import { InstallAppButton } from './InstallAppButton';
import { trapFocusTarget } from '../imports';
import { type NeedsYouRow, workingIds, directIds } from '../chatsTab';
-import { DevModeSwitch, DevFlipNote, useDevMode } from './DevModeSwitch';
+import { DevFlipNote, useDevMode } from './DevModeSwitch';
+import { SpaceControls } from './SpaceControls';
import { DevOnToast } from './DevOnToast';
import { type DevModeState, deskIntent, devConnect, turnDevMode } from '../devMode';
import { DevDeskRow } from './DevDesk';
@@ -377,8 +378,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
return selectedId === c.id;
};
- const offLine = spaceOffLine(space.approvals, kwants);
- // Dev mode: on phones the switch sits after the name; on desktop it has its own row under it; on, the meta line says the branch.
+ // Dev mode and Approvals live in the space controls block under the header (explainer spec §1).
const dev = useDevMode(space.id);
const devOn = !!dev?.on;
// The off note under the header (flow copy §7: HEAD → main, with Turn back on).
@@ -395,18 +395,6 @@ export const Sidebar: React.FC<SidebarProps> = ({
setDevOffNote(false);
setDevOnToast(s);
};
- const devSwitch = (
- <DevModeSwitch
- key={space.id}
- space={space}
- phone={phone}
- onTurnedOff={() => {
- setDevOnToast(null);
- setDevOffNote(true);
- }}
- onTurnedOn={showOn}
- />
- );
const focusDevSwitch = () => setTimeout(() => document.querySelector<HTMLElement>('[data-dev-switch]')?.focus(), 0);
const connectDev = onConnectDevGitHub
? () => {
@@ -418,24 +406,27 @@ export const Sidebar: React.FC<SidebarProps> = ({
deskIntent.set(space.id, 'type');
onOpenDevDesk?.();
};
- const devMeta = devOn ? (
- // The repo truncates; the branch never does (Mira S3)
- <span className="flex min-w-0 items-baseline gap-1 text-meta text-zinc-400" data-dev-meta>
- <span className="shrink-0">Dev ·{' '}</span>
- {dev?.repo ? (
- <>
- <span className="truncate min-w-0 font-mono text-zinc-200" title={dev.repo} data-dev-meta-repo>
- {dev.repo}
- </span>
- <span className="shrink-0">
- {' '}· <span className="font-mono text-sky-300">{dev.branch ?? 'main'}</span>
- </span>
- </>
- ) : (
- <span className="truncate min-w-0">no repo yet</span>
- )}
- </span>
- ) : null;
+ const seeDevRepos = () => {
+ deskIntent.set(space.id, 'repos');
+ onOpenDevDesk?.();
+ };
+ const spaceControls = (
+ <SpaceControls
+ space={{ id: space.id, name: space.name, approvals: space.approvals }}
+ phone={phone}
+ bots={kwants}
+ onTurnedOn={showOn}
+ onTurnedOff={() => {
+ setDevOnToast(null);
+ setDevOffNote(true);
+ }}
+ onOpenDevDesk={onOpenDevDesk}
+ onSeeRepos={onOpenDevDesk ? seeDevRepos : undefined}
+ onLinkRepo={onOpenDevDesk ? typeDevRepo : undefined}
+ onConnect={connectDev}
+ onOpenSettings={onOpenSpaceSettings}
+ />
+ );
// Phones: section titles stay pinned while their list scrolls, so they are never cut off
const sectionHead = `px-2 py-1 min-w-0 flex items-center justify-between gap-2 text-2xs font-semibold text-zinc-400 uppercase tracking-wider${
phone ? ' kw-sticky-head sticky top-0 z-10' : ''
@@ -770,21 +761,20 @@ export const Sidebar: React.FC<SidebarProps> = ({
aria-expanded={switcherOpen}
className="w-full flex items-center gap-2.5 px-1.5 py-1.5 rounded-lg text-left hover:bg-zinc-800/60 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
>
- <SpaceTile space={space} size={32} dev={devOn} devBehind="var(--kw-surface-side)" />
+ <SpaceTile space={space} size={32} dev={false} />
<span className="flex-1 min-w-0">
<span className="block text-body font-semibold text-zinc-50 truncate">{space.name}</span>
- {devMeta ?? <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>}
+ <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>
</span>
<ChevronDown size={14} className={`shrink-0 text-zinc-500 transition-transform ${switcherOpen ? 'rotate-180' : ''}`} aria-hidden="true" />
</button>
- {devSwitch}
</div>
) : (
<div className="flex items-center gap-2.5 px-1.5 py-1.5" data-space-header>
- <SpaceTile space={space} size={32} dev={devOn} devBehind="var(--kw-surface-side)" />
+ <SpaceTile space={space} size={32} dev={false} />
<span className="flex-1 min-w-0">
<h1 className="text-body font-semibold text-zinc-50 truncate">{space.name}</h1>
- {devMeta ?? <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>}
+ <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>
</span>
<button
type="button"
@@ -801,13 +791,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
</button>
</div>
)}
- {/* Desktop: the switch has its own 32 px row under the name, starting where the name text
- starts (6 px pad + 32 px tile + 10 px gap), so it never squeezes the name or subtitle. */}
- {!phone && (
- <div className="h-8 flex items-center pl-12" data-dev-switch-row>
- {devSwitch}
- </div>
- )}
+ {spaceControls}
{devOffNote && <DevFlipNote on={false} approvals={space.approvals} onDismiss={dismissDevOff} onTurnBackOn={() => turnDevMode(space.id, true).then(showOn)} />}
{devOnToast && devOn && (
<DevOnToast
@@ -825,17 +809,6 @@ export const Sidebar: React.FC<SidebarProps> = ({
onClose={closeDevOnToast}
/>
)}
- {offLine && (
- <button
- type="button"
- onClick={onOpenSpaceSettings}
- title="Bots here act without asking, including deletions, publishing and sign-ins. Payments still ask you. Change it in Settings › This space."
- className="mt-1.5 w-full flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl border border-amber-300/30 bg-amber-300/10 text-meta font-medium text-warn hover:bg-amber-300/15 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-300"
- >
- <ShieldOff size={12} aria-hidden="true" className="shrink-0" />
- <span className="truncate">{offLine}</span>
- </button>
- )}
{phone && switcherOpen && (
<SpaceSwitcher
spaces={spaces}
diff --git a/frontend/src/components/SpaceControls.tsx b/frontend/src/components/SpaceControls.tsx
new file mode 100644
index 00000000..05dd706f
--- /dev/null
+++ b/frontend/src/components/SpaceControls.tsx
@@ -0,0 +1,420 @@
+// The space controls under the space header (explainer spec §1–§5, kwant 0.7.2): one block with two
+// identical rows. Row 1 is Dev mode: a label, a "?" that opens the explainer, the switch, and one line
+// under it that says what Dev mode is doing (devSubLine). Row 2 is Approvals: the space's setting as a
+// chip that opens Settings › This space, and what still asks. The header subtitle never changes, and the
+// </> badge lives on the rail only.
+
+import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { ArrowUpRight, ChevronRight, CircleHelp, CodeXml, Lock, Shield, ShieldCheck, ShieldOff, X } from 'lucide-react';
+import { DEV_FEATURES, DEV_GUIDE_URL, EXPLAINER, SUB_ACTION_TEXT, type DevModeState, type DevSub, type DevSubAction, devSubLine } from '../devMode';
+import { approvalsRow, type SpaceApprovals } from '../approvalMode';
+import { DevModeSwitch, useDevMode } from './DevModeSwitch';
+import { backGestureEntry } from './BrowserControlOverlay';
+
+export interface SpaceControlsProps {
+ space: { id: string; name: string; approvals?: SpaceApprovals };
+ phone?: boolean;
+ /** The space's bots, for what still asks when approvals differ per bot. */
+ bots: Array<{ approvals_effective?: string | null }>;
+ onTurnedOn?: (s: DevModeState) => void;
+ onTurnedOff?: () => void;
+ /** The sub-line actions and the explainer's "Open Dev desk". Absent: the action isn't drawn. */
+ onOpenDevDesk?: () => void;
+ onSeeRepos?: () => void;
+ onLinkRepo?: () => void;
+ onConnect?: () => void;
+ /** The Approvals value: Settings › This space (turning approvals off stays there, behind its confirm). */
+ onOpenSettings: () => void;
+}
+
+/** How long the Approvals row waits for a space's approvals before taking it for an older server. */
+export const APPROVALS_WAIT_MS = 1500;
+
+export const SpaceControls: React.FC<SpaceControlsProps> = ({ space, phone = false, bots, onTurnedOn, onTurnedOff, onOpenDevDesk, onSeeRepos, onLinkRepo, onConnect, onOpenSettings }) => {
+ const dev = useDevMode(space.id);
+ const [look, setLook] = useState({ armed: false, disabled: false, on: false, failed: false });
+ const onLook = useCallback((l: { armed: boolean; disabled: boolean; on: boolean; failed: boolean }) => setLook(l), []);
+ const [open, setOpen] = useState(false);
+ const help = useRef<HTMLButtonElement>(null);
+ const switchBtn = useRef<HTMLButtonElement | null>(null);
+ useEffect(() => setOpen(false), [space.id]);
+
+ const sub = devSubLine(dev, { armed: look.armed, disabled: look.disabled, turningOn: look.on, loading: !dev && !look.failed });
+ const lbl = `dv-lbl-${space.id}`;
+ const subId = `dv-sub-${space.id}`;
+ const dlg = `dvx-${space.id}`;
+ const on = !!dev?.on;
+ const actions: Record<DevSubAction, (() => void) | undefined> = { repos: onSeeRepos, link: onLinkRepo, connect: onConnect };
+ const act = sub.action ? actions[sub.action] : undefined;
+ const appr = approvalsRow(space.approvals, bots, on);
+ // Answer 3: a skeleton while the space's approvals may still arrive. An older server never sends them,
+ // so after APPROVALS_WAIT_MS with none the row isn't drawn (as before). Never in a static render.
+ const [apprWaiting, setApprWaiting] = useState(false);
+ useEffect(() => {
+ if (space.approvals !== undefined) return undefined;
+ setApprWaiting(true);
+ const t = window.setTimeout(() => setApprWaiting(false), APPROVALS_WAIT_MS);
+ return () => window.clearTimeout(t);
+ }, [space.id, space.approvals]);
+
+ const close = useCallback((refocus: boolean) => {
+ setOpen(false);
+ if (refocus) setTimeout(() => help.current?.focus(), 0);
+ }, []);
+
+ return (
+ <div role="group" aria-label="Space controls" className={`kw-sc${phone ? ' kw-sc-phone' : ''}`} data-space-controls>
+ <div className="kw-sc-row" data-sc-row="dev">
+ <CodeXml size={16} strokeWidth={2} aria-hidden="true" className={`kw-sc-icon ${on || look.armed ? 'text-sky-300' : 'text-zinc-500'}`} />
+ <span className="kw-sc-label">
+ <span id={lbl}>Dev mode</span>
+ <button
+ ref={help}
+ type="button"
+ className="kw-sc-help"
+ aria-label="What is Dev mode?"
+ aria-haspopup="dialog"
+ aria-expanded={open}
+ aria-controls={dlg}
+ data-dv-help
+ data-open={open || undefined}
+ onClick={() => setOpen((v) => !v)}
+ >
+ <CircleHelp size={14} aria-hidden="true" />
+ </button>
+ </span>
+ <DevModeSwitch
+ key={space.id}
+ space={space}
+ phone={phone}
+ labelledBy={lbl}
+ describedBy={subId}
+ onLook={onLook}
+ buttonRef={switchBtn}
+ onTurnedOn={onTurnedOn}
+ onTurnedOff={onTurnedOff}
+ />
+ <DevSubLine id={subId} sub={sub} phone={phone} onAction={act} />
+ </div>
+ {/* Answer 3: while the space's approvals are still loading, a skeleton the row's height, no text. */}
+ {!appr && space.approvals === undefined && apprWaiting && (
+ <div className="kw-sc-row kw-sc-row-skeleton" data-sc-row="approvals" data-sc-skeleton aria-hidden="true">
+ <span className="kw-sc-skel kw-sc-skel-icon" />
+ <span className="kw-sc-skel kw-sc-skel-line" />
+ <span className="kw-sc-skel kw-sc-skel-chip" />
+ </div>
+ )}
+ {appr && (
+ <div className="kw-sc-row" data-sc-row="approvals">
+ {appr.value === 'ask' ? (
+ <ShieldCheck size={16} strokeWidth={2} aria-hidden="true" className="kw-sc-icon text-ok" />
+ ) : appr.value === 'off' ? (
+ <ShieldOff size={16} strokeWidth={2} aria-hidden="true" className="kw-sc-icon text-warn" />
+ ) : (
+ <Shield size={16} strokeWidth={2} aria-hidden="true" className="kw-sc-icon text-zinc-500" />
+ )}
+ <span className="kw-sc-label">Approvals</span>
+ <button type="button" className="kw-sc-value" aria-label={appr.label} title={phone ? undefined : appr.title ?? undefined} onClick={onOpenSettings} data-approvals-value={appr.value}>
+ <span className="kw-sc-chip" data-tone={appr.tone} aria-hidden="true">
+ {appr.chip}
+ </span>
+ <ChevronRight size={14} aria-hidden="true" className="text-zinc-500" />
+ </button>
+ {appr.sub && (
+ <p className="kw-sc-sub" data-tone={appr.value !== 'off' ? 'warn' : undefined} data-approvals-sub>
+ <span className="truncate">{appr.sub}</span>
+ </p>
+ )}
+ </div>
+ )}
+ {open && (
+ <DevExplainer
+ id={dlg}
+ space={space.name}
+ on={on}
+ disabled={look.disabled}
+ phone={phone}
+ anchor={help}
+ onClose={close}
+ onTurnOn={() => {
+ close(false);
+ const b = switchBtn.current;
+ b?.focus();
+ b?.click();
+ }}
+ onOpenDesk={
+ onOpenDevDesk &&
+ (() => {
+ close(false);
+ onOpenDevDesk();
+ })
+ }
+ />
+ )}
+ </div>
+ );
+};
+
+/** The Dev mode row's second line (spec §2): an LED, the text, and at most one action on the right. */
+const DevSubLine: React.FC<{ id: string; sub: DevSub; phone: boolean; onAction?: () => void }> = ({ id, sub, phone, onAction }) =>
+ sub.state === 'loading' ? (
+ // Addendum 3: the line's height, no text, until the first repo list arrives. The id stays so the switch's
+ // aria-describedby still resolves (to nothing to read).
+ <div className="kw-sc-sub" data-dev-sub="loading" data-sc-skeleton aria-hidden="true">
+ <span id={id} className="kw-sc-skel kw-sc-skel-sub" />
+ </div>
+ ) : (
+ <div className="kw-sc-sub" data-dev-sub={sub.state} data-tone={sub.tone ?? undefined}>
+ {sub.led && <span className="dv-led kw-sc-led" data-s={sub.led} aria-hidden="true" />}
+ <span id={id} className="kw-sc-sub-text" data-dev-sub-text>
+ {sub.parts.map((p, i) =>
+ p.repo ? (
+ <span key={i} className="kw-sc-repo" title={p.text}>
+ {p.text}
+ </span>
+ ) : p.branch ? (
+ <span key={i} className="kw-sc-branch">
+ {p.text}
+ </span>
+ ) : (
+ <span key={i} className="shrink-0 whitespace-pre">
+ {p.text}
+ </span>
+ ),
+ )}
+ </span>
+ {sub.state === 'armed' && !phone && (
+ <kbd className="dv-kbd ml-auto" aria-hidden="true">
+ Esc
+ </kbd>
+ )}
+ {sub.action && onAction && (
+ <button type="button" className="kw-sc-act" aria-label={SUB_ACTION_TEXT[sub.action].label} onClick={onAction} data-dev-sub-action={sub.action}>
+ {SUB_ACTION_TEXT[sub.action].text}
+ </button>
+ )}
+ </div>
+ );
+
+interface ExplainerProps {
+ id: string;
+ space: string;
+ on: boolean;
+ disabled: boolean;
+ phone: boolean;
+ anchor: React.RefObject<HTMLButtonElement>;
+ onClose: (refocus: boolean) => void;
+ onTurnOn: () => void;
+ onOpenDesk?: () => void;
+}
+
+const focusables = (root: HTMLElement | null): HTMLElement[] =>
+ root ? [...root.querySelectorAll<HTMLElement>('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])')] : [];
+
+/**
+ * What Dev mode is (spec §4): a non-modal popover beside the sidebar on desktop, a modal bottom sheet on
+ * phones. Esc, the X or a click outside closes it and focus goes back to the "?".
+ */
+/** The phone sheet's slide-down on close (answer 4): mirrors the 200 ms open, none under reduced motion. */
+export const SHEET_CLOSE_MS = 150;
+const reducedMotion = () => typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+
+export const DevExplainer: React.FC<ExplainerProps> = ({ id, space, on, disabled, phone, anchor, onClose: close, onTurnOn, onOpenDesk }) => {
+ const card = useRef<HTMLDivElement>(null);
+ // Phone: closing slides the sheet down first, then it unmounts. Desktop closes at once.
+ const [closing, setClosing] = useState(false);
+ const closingRef = useRef(false);
+ const closeRef = useRef(close);
+ closeRef.current = close;
+ const onClose = useCallback(
+ (refocus: boolean) => {
+ if (closingRef.current) return;
+ if (!phone || reducedMotion()) {
+ closingRef.current = true;
+ closeRef.current(refocus);
+ return;
+ }
+ closingRef.current = true;
+ setClosing(true);
+ window.setTimeout(() => closeRef.current(refocus), SHEET_CLOSE_MS);
+ },
+ [phone],
+ );
+ // Phone: the back gesture closes the sheet. Opening adds a history entry; closing any other way takes it off.
+ useEffect(() => (phone ? backGestureEntry(() => onClose(true)) : undefined), [phone, onClose]);
+ const primary = useRef<HTMLButtonElement>(null);
+ const [pos, setPos] = useState<{ left: number; top: number; arrow: number; width: number } | null>(null);
+
+ // Desktop: 10 px right of the sidebar, the arrow at the "?", clamped to the viewport with 12 px margins.
+ useLayoutEffect(() => {
+ if (phone) return undefined;
+ const place = () => {
+ const q = anchor.current?.getBoundingClientRect();
+ if (!q) return;
+ const side = anchor.current?.closest('[data-kw-sidebar]')?.getBoundingClientRect();
+ const left = Math.round((side?.right ?? q.right) + 10);
+ const width = Math.max(240, Math.min(368, window.innerWidth - left - 12));
+ const h = card.current?.offsetHeight ?? 0;
+ const mid = q.top + q.height / 2;
+ const top = Math.round(Math.max(12, Math.min(mid - 24, window.innerHeight - h - 12)));
+ setPos({ left, top, arrow: Math.round(h > 28 ? Math.max(14, Math.min(mid - top, h - 14)) : mid - top), width });
+ };
+ place();
+ window.addEventListener('resize', place);
+ return () => window.removeEventListener('resize', place);
+ }, [phone, anchor]);
+
+ // Focus the primary button when it opens (or the first control when there is none). The desktop popover
+ // is hidden until it is placed, and a hidden button can't take focus, so wait for its position.
+ const focused = useRef(false);
+ const ready = phone || pos !== null;
+ useEffect(() => {
+ if (!ready || focused.current) return;
+ focused.current = true;
+ (primary.current ?? focusables(card.current)[0])?.focus();
+ }, [ready]);
+
+ // Outside click closes the popover; focus returns to "?" only if it was inside the card.
+ useEffect(() => {
+ if (phone) return undefined;
+ const down = (e: PointerEvent) => {
+ const t = e.target as Node | null;
+ if (!t || card.current?.contains(t) || anchor.current?.contains(t)) return;
+ onClose(!!card.current?.contains(document.activeElement));
+ };
+ document.addEventListener('pointerdown', down);
+ return () => document.removeEventListener('pointerdown', down);
+ }, [phone, anchor, onClose]);
+
+ // Phone: the sheet is modal, so everything behind it is inert while it is open.
+ useEffect(() => {
+ if (!phone) return undefined;
+ const host = card.current?.closest('[data-dvx-portal]');
+ const others = [...document.body.children].filter((el) => el !== host && !el.hasAttribute('inert'));
+ others.forEach((el) => el.setAttribute('inert', ''));
+ return () => others.forEach((el) => el.removeAttribute('inert'));
+ }, [phone]);
+
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ onClose(true);
+ return;
+ }
+ if (e.key !== 'Tab') return;
+ const items = focusables(card.current);
+ if (!items.length) return;
+ const first = items[0];
+ const last = items[items.length - 1];
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ if (phone) last.focus();
+ else onClose(true); // not a trap on desktop: Shift+Tab out of the first item goes back to "?"
+ } else if (!e.shiftKey && document.activeElement === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+
+ const swipe = useRef<number | null>(null);
+ const titleId = 'dvx-title';
+ const body = (
+ <>
+ <p className="kw-dvx-kicker">{on ? EXPLAINER.kickerOn(space) : EXPLAINER.kickerOff}</p>
+ <h2 id={titleId} className="kw-dvx-title">
+ {EXPLAINER.title}
+ </h2>
+ <p className="kw-dvx-lead">{on ? EXPLAINER.leadOn : EXPLAINER.leadOff}</p>
+ <ol className="kw-dvx-list">
+ {DEV_FEATURES.map((f) => (
+ <li key={f.key} data-dev-feature={f.key}>
+ <span className="kw-dvx-n" aria-hidden="true">
+ {f.n}
+ </span>
+ <span>
+ <strong>{f.title}</strong> {f.line}
+ </span>
+ </li>
+ ))}
+ </ol>
+ <p className="kw-dvx-trust">
+ <Lock size={14} aria-hidden="true" className="shrink-0 text-ok mt-0.5" />
+ <span>
+ {EXPLAINER.trustLead}
+ <strong>{EXPLAINER.trustPost}</strong>.
+ </span>
+ </p>
+ <div className="kw-dvx-actions">
+ {on ? (
+ onOpenDesk && (
+ <button ref={primary} type="button" className="kw-dvx-primary" onClick={onOpenDesk} data-dvx-primary="desk">
+ {EXPLAINER.openDesk}
+ </button>
+ )
+ ) : disabled ? (
+ <p className="kw-dvx-owner" data-dvx-not-owner>
+ {EXPLAINER.notOwner}
+ </p>
+ ) : (
+ <button ref={primary} type="button" className="kw-dvx-primary" onClick={onTurnOn} data-dvx-primary="on">
+ {EXPLAINER.turnOn}
+ </button>
+ )}
+ <a className="kw-dvx-guide" href={DEV_GUIDE_URL} target="_blank" rel="noopener noreferrer" data-dvx-guide>
+ {EXPLAINER.guide}
+ <ArrowUpRight size={12} aria-hidden="true" />
+ <span className="sr-only"> (opens in a new tab)</span>
+ </a>
+ </div>
+ {on && <p className="kw-dvx-note">{EXPLAINER.noteOn}</p>}
+ <button type="button" className="kw-dvx-close" aria-label="Close" onClick={() => onClose(true)} data-dvx-close>
+ <X size={14} aria-hidden="true" />
+ </button>
+ </>
+ );
+
+ const content = phone ? (
+ <div className="kw-dvx-layer" data-dvx-portal>
+ <div className="kw-dvx-scrim" aria-hidden="true" onClick={() => onClose(true)} data-dvx-scrim data-closing={closing || undefined} />
+ <div
+ ref={card}
+ id={id}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ className="kw-dvx kw-dvx-sheet"
+ data-closing={closing || undefined}
+ onKeyDown={onKeyDown}
+ onTouchStart={(e) => (swipe.current = e.touches[0]?.clientY ?? null)}
+ onTouchEnd={(e) => {
+ const y0 = swipe.current;
+ swipe.current = null;
+ const y1 = e.changedTouches[0]?.clientY;
+ if (y0 !== null && y1 !== undefined && y1 - y0 > 64 && (card.current?.scrollTop ?? 0) <= 0) onClose(true);
+ }}
+ data-dev-explainer="sheet"
+ >
+ <span className="kw-dvx-grab" aria-hidden="true" />
+ {body}
+ </div>
+ </div>
+ ) : (
+ <div data-dvx-portal>
+ <div
+ ref={card}
+ id={id}
+ role="dialog"
+ aria-labelledby={titleId}
+ className="kw-dvx kw-dvx-pop"
+ style={pos ? { left: pos.left, top: pos.top, width: pos.width } : { visibility: 'hidden' }}
+ onKeyDown={onKeyDown}
+ data-dev-explainer="popover"
+ >
+ <span className="kw-dvx-arrow" aria-hidden="true" style={pos ? { top: pos.arrow - 5.5 } : undefined} />
+ {body}
+ </div>
+ </div>
+ );
+ return createPortal(content, document.body);
+};
diff --git a/frontend/src/devMode.ts b/frontend/src/devMode.ts
index ee3e9fd1..de98edce 100644
--- a/frontend/src/devMode.ts
+++ b/frontend/src/devMode.ts
@@ -707,8 +707,9 @@ export interface SwitchLook {
export const OFF_TOOLTIP = 'Dev mode: plain-words merges, code reviews, production floor';
export const ON_TOOLTIP = 'Dev mode is on. Press twice to turn it off.';
-export const OWNER_TOOLTIP = 'Only the space owner can change Dev mode.';
-export const OFF_DESCRIBE = 'Turns on reviews, the ship gate and the production floor.';
+export const OWNER_TOOLTIP = 'Only the space owner can turn Dev mode on or off.';
+/** Explainer spec §2: the off sub-line, also the switch's description when it stands alone. */
+export const OFF_DESCRIBE = 'For bots that write code';
export const ON_DESCRIBE = 'Press twice to turn off.';
export const ARMED_HINT = 'Press again to turn Dev mode off';
@@ -734,6 +735,105 @@ function switchParts(s: SwitchState): Omit<SwitchLook, 'look' | 'glyph'> {
}
}
+// ---------------------------------------------------------------------------
+// Space controls (explainer spec §2, §4): the Dev mode row's sub-line and the explainer's copy.
+
+/** What Dev mode does, in three lines: the explainer card and the Dev desk's first-run block share it. */
+export const DEV_FEATURES = [
+ { key: 'landed', n: '01', title: 'What landed.', line: 'Every merge to main in plain words, and when main is ready to ship.' },
+ { key: 'reviews', n: '02', title: 'Reviews.', line: 'A second bot reads each pull request before you merge it.' },
+ { key: 'floor', n: '03', title: 'Production floor.', line: 'Pushes to main, deploys and deleting data always wait for your OK, even with approvals off.' },
+] as const;
+
+export const DEV_GUIDE_URL = 'https://kwant.si/docs/dev-mode.html';
+
+/** Explainer spec §4, final copy. The kicker is upper-cased by CSS, so screen readers read words. */
+export const EXPLAINER = {
+ title: 'Dev mode: when your bots write code',
+ kickerOff: 'For spaces that build software',
+ kickerOn: (space: string) => `On in ${space}`,
+ leadOff: 'Turn it on in a space where your teams work on code. Dev mode watches each team’s repo. Everywhere else, leave it off.',
+ leadOn: 'It’s on in this space. Dev mode watches each team’s repo and shows what changed on the Dev desk.',
+ trustLead: 'Bots only read your repo. Nothing is posted to it unless you press ',
+ trustPost: 'Post',
+ turnOn: 'Turn on Dev mode',
+ openDesk: 'Open Dev desk',
+ guide: 'Read the guide',
+ noteOn: 'To turn it off, press the switch twice.',
+ notOwner: 'Only the space owner can turn on Dev mode.',
+} as const;
+
+export type DevSubState = 'loading' | 'off' | 'disabled' | 'watching' | 'several' | 'partial' | 'no_repo' | 'not_connected' | 'other_host' | 'error' | 'armed';
+export type DevSubAction = 'repos' | 'link' | 'connect';
+
+export interface DevSub {
+ state: DevSubState;
+ /** null: no LED (off, armed). 'off' is the hollow ring. */
+ led: 'ok' | 'warn' | 'bad' | 'off' | null;
+ /** The text in pieces: `repo` truncates first, `branch` never does. */
+ parts: Array<{ text: string; repo?: boolean; branch?: boolean }>;
+ /** warn: the armed line. */
+ tone: 'warn' | null;
+ action: DevSubAction | null;
+}
+
+export const SUB_ACTION_TEXT: Record<DevSubAction, { text: string; label: string }> = {
+ repos: { text: 'See repos', label: 'See repos on the Dev desk' },
+ link: { text: 'Link a repo', label: 'Link a repo on the Dev desk' },
+ connect: { text: 'Connect', label: 'Connect GitHub' },
+};
+
+export const ARMED_SUB = 'Press again to turn off';
+
+const sub = (state: DevSubState, led: DevSub['led'], text: string | DevSub['parts'], action: DevSubAction | null = null, tone: DevSub['tone'] = null): DevSub => ({
+ state,
+ led,
+ parts: typeof text === 'string' ? [{ text }] : text,
+ tone,
+ action,
+});
+
+/** The repo list hasn't come yet (addendum 3): no state, a press on still saving, or on with no status and no repos. */
+export const devListPending = (s: DevModeState | null, o: { loading?: boolean; turningOn?: boolean } = {}): boolean =>
+ s ? (!!o.turningOn && !s.on) || (s.on && !s.status && s.repos.length === 0) : !!o.loading;
+
+/**
+ * The Dev mode row's one line under the label (spec §2). Which state wins: armed, then if any
+ * repo is watched several / partial / watching, else error, not_connected, other_host, no_repo. Counts
+ * come straight from repos[]; nothing is added up beyond counting rows.
+ */
+export function devSubLine(s: DevModeState | null, o: { armed?: boolean; disabled?: boolean; turningOn?: boolean; loading?: boolean } = {}): DevSub {
+ if (o.armed) return sub('armed', null, ARMED_SUB, null, 'warn');
+ // Not the owner (403) never brings a state: say so rather than wait on a list.
+ if (o.disabled && !s?.on) return sub('disabled', null, OFF_DESCRIBE);
+ // Ada's addendum 3 (0.7.2): until the first repo list arrives the line is a skeleton, never "No repo
+ // yet" (or the off line) for a moment: the first load still in flight, the switch already flipped on,
+ // or an on state that carries neither a status nor a repo. A failed load falls back to the off line.
+ if (devListPending(s, o)) return sub('loading', null, []);
+ if (!s?.on) return sub(o.disabled ? 'disabled' : 'off', null, OFF_DESCRIBE);
+ // No "checking" line (Ada's answer 1, 0.7.2): the PUT reply already carries the repos, so there is no
+ // in-between state; only the switch shows a spinner, while its request is in flight.
+ const repos = s.repos;
+ const watching = repos.filter((r) => r.status === 'watching');
+ if (watching.length) {
+ if (repos.length === 1) {
+ const r = watching[0];
+ return sub('watching', 'ok', [{ text: 'Watching ' }, { text: r.repo, repo: true }, { text: ' · ' }, { text: r.branch ?? 'main', branch: true }]);
+ }
+ if (watching.length === repos.length) return sub('several', 'ok', `Watching ${watching.length} repos`, 'repos');
+ return sub('partial', 'warn', `${watching.length} of ${repos.length} watched`, 'repos');
+ }
+ const failed = repos.filter((r) => r.status === 'error').length;
+ if (failed) return sub('error', 'bad', failed === 1 ? 'Can’t read a repo' : `Can’t read ${failed} repos`, 'repos');
+ if (repos.some((r) => r.status === 'not_connected')) return sub('not_connected', 'warn', 'Needs GitHub', 'connect');
+ const other = repos.find((r) => r.status === 'other_host');
+ if (other) {
+ if (other.from === 'local' || !other.host) return sub('other_host', 'off', 'Local folder, no remote');
+ return sub('other_host', 'off', [{ text: other.host, repo: true }, { text: ' isn’t read yet' }]);
+ }
+ return sub('no_repo', 'off', 'No repo yet', 'link');
+}
+
// ---------------------------------------------------------------------------
// Setup sheet: the Repository field (design §3 table)
diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.css
index a9efafa7..c58ad90b 100644
--- a/frontend/src/styles/modern.css
+++ b/frontend/src/styles/modern.css
@@ -577,58 +577,164 @@ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow:
}
/* ---- Dev mode (0.7): the switch, the </> badge, the hard hat and the blueprint grid. design.md §1–§2.
Under reduced motion nothing animates. */
-/* The switch (style v2 §10, the Branch switch): a tiny git line. The knob is a commit node.
- Off: a hollow node on the line, no cover. One press: the node hops onto a solid violet fork, then
- a 1 px violet cover closes. Off takes two: armed is a dashed amber fork, a halo and `off?`. 32 px tall
- (44 on phones), mono label + a 44×24 graph. Not colour alone: node position, fork drawn/dashed/
- absent and the label word all change. */
+/* The switch v3 (explainer spec §3): the state word Off / On / Off? next to a 40×22 track and a 16 px
+ knob. Off: a hollow node at the left. On: the knob at the right with a violet pip, a small lock in the
+ track. Armed (press 1 of 2 to turn off): amber ring and open lock, no halo, no pulse. 32 px tall (44 on
+ phones). Not colour alone: the word, the knob's side and the lock all change. */
.kw-dv {
- position: relative; display: inline-flex; align-items: center; justify-content: center; gap: 4px;
- height: 32px; min-width: 44px; padding: 0 6px; border-radius: 10px; flex-shrink: 0; cursor: pointer;
- background: transparent; transition: background-color 120ms var(--kw-ease);
+ position: relative; display: inline-flex; align-items: center; justify-content: flex-end; gap: 6px;
+ height: 32px; min-width: 44px; padding: 0 2px; border-radius: 10px; flex-shrink: 0; cursor: pointer; background: transparent;
}
.kw-dv.h-11 { height: 44px; } /* phone: a 44 px target */
-.kw-dv:not(:disabled):hover { background: rgb(247 246 255 / 0.06); }
-.kw-dv:disabled { opacity: 0.4; cursor: not-allowed; }
-.kw-dv-lbl {
- font: 600 11px/1 'JetBrains Mono', ui-monospace, monospace; color: theme('colors.zinc.400');
- min-width: 4ch; text-align: right; transition: color 120ms var(--kw-ease);
-}
-.kw-dv[data-on] .kw-dv-lbl { color: theme('colors.sky.300'); }
-.kw-dv[data-armed] .kw-dv-lbl { color: var(--dv-armed); }
-.kw-dv-lock { color: theme('colors.zinc.400'); flex-shrink: 0; }
-.kw-dv[data-on]:not(:disabled) .kw-dv-lock { color: theme('colors.sky.300'); }
+.kw-dv:focus-visible { outline: 2px solid #9d8fff; outline-offset: 2px; }
+.kw-dv[aria-disabled='true'], .kw-dv:disabled { opacity: 0.4; cursor: not-allowed; }
+.kw-dv-hint, .kw-dv-lbl { display: none; } /* 0.7.1 parts, gone in v3 */
+.kw-dv-val { font: 600 11px/16px Inter, ui-sans-serif, system-ui, sans-serif; min-width: 22px; text-align: right; color: theme('colors.zinc.400'); }
+.kw-dv[data-on] .kw-dv-val { color: theme('colors.sky.300'); }
+.kw-dv[data-armed] .kw-dv-val { color: var(--dv-armed); }
+.kw-dv-track {
+ position: relative; display: block; width: 40px; height: 22px; border-radius: 11px; flex-shrink: 0;
+ background: #2c2552; box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.14); transition: background-color 160ms var(--kw-ease), box-shadow 160ms var(--kw-ease);
+}
+.kw-dv:not([aria-disabled='true']):hover .kw-dv-track { background: #3f3868; }
+.kw-dv[data-on] .kw-dv-track { background: #6c58e0; box-shadow: none; }
+.kw-dv[data-on]:not([aria-disabled='true']):hover .kw-dv-track { background: #8270f5; }
+.kw-dv[data-armed] .kw-dv-track, .kw-dv[data-armed]:hover .kw-dv-track {
+ background: color-mix(in srgb, var(--dv-armed) 12%, var(--kw-surface-side)); box-shadow: inset 0 0 0 2px var(--dv-armed);
+}
+.kw-dv-knob {
+ position: absolute; left: 3px; top: 3px; width: 16px; height: 16px; border-radius: 50%;
+ background: var(--kw-surface-side); box-shadow: inset 0 0 0 2px theme('colors.zinc.300');
+ transition: transform 160ms var(--kw-ease);
+}
+.kw-dv[data-knob='right'] .kw-dv-knob { transform: translateX(18px); }
+.kw-dv[data-on] .kw-dv-knob { background: theme('colors.zinc.50'); box-shadow: none; }
+.kw-dv[data-on] .kw-dv-knob::after { content: ''; position: absolute; left: 5px; top: 5px; width: 6px; height: 6px; border-radius: 50%; background: #6c58e0; }
+.kw-dv[data-armed] .kw-dv-knob { background: color-mix(in srgb, var(--dv-armed) 25%, var(--kw-surface-side)); box-shadow: inset 0 0 0 2px var(--dv-armed); }
+.kw-dv[data-armed] .kw-dv-knob::after { display: none; }
+.kw-dv-lock { position: absolute; left: 6px; top: 6px; color: rgb(247 246 255 / 0.85); }
.kw-dv[data-armed] .kw-dv-lock { color: var(--dv-armed); }
-/* The cover (flow F1/F2): only while on. A 1 px violet ring closes 160 ms after the node lands
- (guards locked in); armed lifts it to a 2 px amber ring at once. Off and not-the-owner: none. */
-.kw-dv::after {
- content: ''; position: absolute; inset: 0; border-radius: 10px; pointer-events: none; opacity: 0;
- box-shadow: inset 0 0 0 1px rgb(157 143 255 / 0.45); transition: opacity 160ms var(--kw-ease);
-}
-.kw-dv[data-covered]::after { opacity: 1; transition-delay: 160ms; }
-.kw-dv[data-armed]::after { opacity: 1; box-shadow: inset 0 0 0 2px var(--dv-armed); transition-delay: 0s; }
-.kw-dv:disabled::after { opacity: 0; }
-.kw-dv-graph { display: block; width: 44px; height: 24px; overflow: visible; }
-.kw-dv-base { fill: none; stroke: theme('colors.zinc.500'); stroke-width: 2; stroke-linecap: round; transition: opacity 160ms var(--kw-ease); }
-.kw-dv[data-on] .kw-dv-base { opacity: 0.55; }
-.kw-dv-fork { fill: none; stroke: theme('colors.sky.400'); stroke-width: 2; stroke-linecap: round; opacity: 0; transition: opacity 160ms var(--kw-ease); }
-.kw-dv[data-on] .kw-dv-fork { opacity: 1; }
-.kw-dv[data-armed] .kw-dv-fork { opacity: 1; stroke: var(--dv-armed); stroke-dasharray: 2.5 3; }
-.kw-dv-node { transition: transform 160ms var(--kw-ease); }
-.kw-dv[data-on] .kw-dv-node { transform: translate(22px, -10px); }
-.kw-dv-dot { fill: var(--kw-surface-side); stroke: theme('colors.zinc.300'); stroke-width: 2; transition: fill 160ms var(--kw-ease), stroke 160ms var(--kw-ease); }
-.kw-dv[data-on] .kw-dv-dot { fill: theme('colors.sky.400'); stroke: theme('colors.sky.400'); }
-.kw-dv[data-armed] .kw-dv-dot { stroke: var(--dv-armed); fill: color-mix(in srgb, var(--dv-armed) 25%, var(--kw-surface-side)); }
-.kw-dv-pip { fill: var(--kw-surface-side); opacity: 0; transition: opacity 160ms var(--kw-ease); }
-.kw-dv[data-on] .kw-dv-pip { opacity: 1; }
-.kw-dv-halo { fill: none; stroke: var(--dv-armed); stroke-width: 1.5; opacity: 0; transform-box: fill-box; transform-origin: center; }
-.kw-dv[data-armed] .kw-dv-halo { animation: kw-dv-halo 900ms var(--kw-ease) infinite; }
-@keyframes kw-dv-halo { from { opacity: 0.9; transform: scale(1); } to { opacity: 0; transform: scale(2); } }
-/* Reduced motion: the same shapes, instant, no halo */
-.kw-dv-rm, .kw-dv-rm *, .kw-dv-rm::after { transition: none !important; }
-.kw-dv-rm .kw-dv-halo { animation: none !important; opacity: 0 !important; }
-.kw-dv-hint { animation: kw-dv-hint 150ms var(--kw-ease) both; }
+/* Reduced motion: the same shapes, instant */
+.kw-dv-rm, .kw-dv-rm * { transition: none !important; }
@keyframes kw-dv-hint { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
+
+/* The space controls block (explainer spec §1): two identical rows, Dev mode and Approvals. Full
+ sidebar content width, so it lines up with the nav rows below. */
+.kw-sc { margin-top: 6px; border: 1px solid rgb(255 255 255 / 0.07); border-radius: 12px; background: rgb(255 255 255 / 0.025); }
+.kw-sc-row { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; column-gap: 10px; align-items: center; min-height: 40px; padding: 6px 6px 6px 10px; }
+.kw-sc-row + .kw-sc-row { border-top: 1px solid rgb(255 255 255 / 0.07); }
+.kw-sc-icon { display: block; }
+.kw-sc-label { display: flex; align-items: center; gap: 4px; min-width: 0; font-size: 14px; line-height: 20px; font-weight: 500; color: theme('colors.zinc.100'); }
+.kw-sc-help {
+ position: relative; display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;
+ color: theme('colors.zinc.500');
+}
+.kw-sc-help:hover { color: theme('colors.zinc.300'); }
+.kw-sc-help[data-open] { color: theme('colors.sky.300'); background: rgb(157 143 255 / 0.14); }
+.kw-sc-help:focus-visible { outline: 2px solid theme('colors.sky.400'); outline-offset: 1px; }
+.kw-sc-sub {
+ grid-column: 2 / 4; display: flex; align-items: center; gap: 6px; min-width: 0;
+ font-size: 12px; line-height: 18px; color: theme('colors.zinc.400');
+}
+.kw-sc-sub[data-tone='warn'] { color: var(--dv-led-warn); }
+.kw-sc-sub-text { display: flex; min-width: 0; overflow: hidden; white-space: nowrap; }
+.kw-sc-repo { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: theme('colors.zinc.200'); font-weight: 400; }
+.kw-sc-branch { flex-shrink: 0; color: theme('colors.sky.300'); font-weight: 500; }
+.kw-sc-led[data-s='off'] { background: transparent; box-shadow: inset 0 0 0 1.5px theme('colors.zinc.500'); }
+/* Answer 3: the Approvals row while loading. Same grid and height as the row, no text. */
+.kw-sc-skel { display: block; border-radius: 9999px; background: rgb(255 255 255 / 0.06); animation: kw-sc-skel 1.4s ease-in-out infinite; }
+.kw-sc-skel-icon { width: 16px; height: 16px; border-radius: 5px; }
+.kw-sc-skel-line { width: 72px; height: 10px; }
+.kw-sc-skel-chip { width: 56px; height: 24px; }
+.kw-sc-skel-sub { width: 120px; height: 8px; margin-block: 5px; }
+.kw-sc-phone .kw-sc-skel-chip { margin-block: 10px; }
+@keyframes kw-sc-skel { 0%, 100% { opacity: 1; } 50% { opacity: 0.55; } }
+.kw-sc-act {
+ margin-left: auto; flex-shrink: 0; display: inline-flex; align-items: center; min-height: 24px; padding: 0 2px; border-radius: 6px;
+ font-size: 12px; line-height: 18px; font-weight: 600; color: theme('colors.sky.300');
+}
+.kw-sc-act:hover { color: theme('colors.sky.200'); }
+.kw-sc-act:focus-visible, .kw-sc-value:focus-visible { outline: 2px solid theme('colors.sky.400'); outline-offset: 2px; }
+.kw-sc-value { display: inline-flex; align-items: center; gap: 2px; border-radius: 9999px; padding-left: 0; }
+.kw-sc-chip {
+ display: inline-flex; align-items: center; height: 24px; padding: 0 9px; border-radius: 9999px; font-size: 12px; line-height: 18px; font-weight: 500;
+ background: rgb(255 255 255 / 0.04); box-shadow: inset 0 0 0 1px var(--kw-hairline-strong, rgb(255 255 255 / 0.14)); color: theme('colors.zinc.200');
+}
+.kw-sc-value:hover .kw-sc-chip { background: rgb(255 255 255 / 0.07); }
+.kw-sc-chip[data-tone='warn'] { background: rgb(252 211 77 / 0.10); box-shadow: inset 0 0 0 1px rgb(252 211 77 / 0.30); color: #fcd34d; }
+.kw-sc-phone .kw-sc-row { min-height: 52px; padding: 4px 4px 4px 12px; }
+.kw-sc-phone .kw-sc-sub { margin-top: -6px; padding-bottom: 4px; }
+.kw-sc-phone .kw-sc-help { margin: -10px; width: 44px; height: 44px; }
+.kw-sc-phone .kw-sc-help[data-open] { background: none; }
+.kw-sc-phone .kw-sc-act { min-height: 44px; padding: 0 4px; margin-block: -12px; }
+.kw-sc-phone .kw-sc-value { min-height: 44px; }
+
+/* The explainer (spec §4): a popover beside the sidebar on desktop, a bottom sheet on phones. */
+.kw-dvx {
+ background: #231d4b; border: 1px solid rgb(255 255 255 / 0.14); color: theme('colors.zinc.300');
+ box-shadow: 0 18px 48px -12px rgb(6 3 20 / 0.85), inset 0 1px 0 rgb(255 255 255 / 0.05);
+}
+.kw-dvx-pop { position: fixed; z-index: 60; width: 368px; border-radius: 16px; padding: 16px 16px 14px; animation: kw-dvx-in 160ms var(--kw-ease) both; }
+@keyframes kw-dvx-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
+.kw-dvx-arrow {
+ position: absolute; left: -6px; width: 11px; height: 11px; background: #231d4b; transform: rotate(45deg);
+ border-left: 1px solid rgb(255 255 255 / 0.14); border-bottom: 1px solid rgb(255 255 255 / 0.14);
+}
+.kw-dvx-kicker { font: 600 10.5px/16px 'JetBrains Mono', ui-monospace, monospace; letter-spacing: .08em; text-transform: uppercase; color: theme('colors.sky.300'); padding-right: 28px; }
+.kw-dvx-title { margin-top: 4px; font-size: 17px; line-height: 24px; font-weight: 600; color: theme('colors.zinc.50'); padding-right: 20px; }
+.kw-dvx-lead { margin-top: 8px; font-size: 14px; line-height: 22px; color: theme('colors.zinc.300'); }
+.kw-dvx-list { margin-top: 12px; padding-top: 12px; border-top: 1px solid rgb(255 255 255 / 0.08); display: flex; flex-direction: column; gap: 8px; font-size: 12.5px; line-height: 18px; color: theme('colors.zinc.400'); }
+.kw-dvx-list li { display: flex; gap: 10px; align-items: baseline; }
+.kw-dvx-list strong { font-weight: 600; color: theme('colors.zinc.100'); }
+.kw-dvx-n { font: 600 10.5px/18px 'JetBrains Mono', ui-monospace, monospace; color: theme('colors.sky.300'); flex-shrink: 0; }
+.kw-dvx-trust { margin-top: 12px; display: flex; gap: 8px; padding: 8px 10px; border-radius: 10px; background: rgb(255 255 255 / 0.04); font-size: 12px; line-height: 18px; color: theme('colors.zinc.400'); }
+.kw-dvx-trust strong { font-weight: 600; color: theme('colors.zinc.100'); }
+.kw-dvx-actions { margin-top: 14px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
+.kw-dvx-primary {
+ display: inline-flex; align-items: center; justify-content: center; height: 36px; padding: 0 14px; border-radius: 10px;
+ background: linear-gradient(135deg, #7a62f0, #5b47d6); color: #fff; font-size: 14px; font-weight: 600;
+}
+.kw-dvx-primary:hover { filter: brightness(1.08); }
+.kw-dvx-guide { display: inline-flex; align-items: center; gap: 4px; font-size: 14px; font-weight: 600; color: theme('colors.sky.300'); border-radius: 6px; }
+.kw-dvx-guide:hover { color: theme('colors.sky.200'); }
+.kw-dvx-owner { font-size: 12px; line-height: 18px; color: theme('colors.zinc.400'); }
+.kw-dvx-note { margin-top: 10px; font-size: 12px; line-height: 18px; color: theme('colors.zinc.500'); }
+.kw-dvx-close {
+ position: absolute; top: 8px; right: 8px; width: 28px; height: 28px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; color: theme('colors.zinc.400');
+}
+.kw-dvx-close:hover { color: theme('colors.zinc.100'); background: rgb(255 255 255 / 0.06); }
+.kw-dvx-primary:focus-visible, .kw-dvx-guide:focus-visible, .kw-dvx-close:focus-visible { outline: 2px solid theme('colors.sky.400'); outline-offset: 2px; }
+.kw-dvx-layer { position: fixed; inset: 0; z-index: 70; display: flex; flex-direction: column; justify-content: flex-end; }
+.kw-dvx-scrim { position: absolute; inset: 0; background: rgb(6 3 20 / 0.6); animation: kw-dvx-fade 200ms var(--kw-ease) both; }
+@keyframes kw-dvx-fade { from { opacity: 0; } to { opacity: 1; } }
+.kw-dvx-sheet {
+ position: relative; width: 100%; max-height: 88vh; overflow-y: auto; overscroll-behavior: contain; border-radius: 20px 20px 0 0; border-bottom: 0;
+ padding: 12px 20px calc(20px + env(safe-area-inset-bottom)); animation: kw-dvx-up 200ms var(--kw-ease) both;
+}
+@keyframes kw-dvx-up { from { transform: translateY(100%); } to { transform: none; } }
+/* Answer 1: the switch's knob turns into a small spinner only while its request is in flight. */
+/* Answer 1: the knob carries a plain border spinner while the PUT is in flight (no gradient). */
+.kw-dv[data-saving] .kw-dv-knob::after {
+ content: ''; position: absolute; left: 2px; top: 2px; width: 12px; height: 12px; box-sizing: border-box; border-radius: 50%;
+ background: none; border: 2px solid #6c58e0; border-top-color: transparent; animation: kw-dv-saving 800ms linear infinite;
+}
+@keyframes kw-dv-saving { to { rotate: 360deg; } }
+/* Answer 4: closing mirrors the open, 150 ms down (none under reduced motion, below). */
+.kw-dvx-sheet[data-closing] { animation: kw-dvx-down 150ms var(--kw-ease) both; }
+.kw-dvx-scrim[data-closing] { animation: kw-dvx-fade-out 150ms var(--kw-ease) both; }
+@keyframes kw-dvx-down { from { transform: none; } to { transform: translateY(100%); } }
+@keyframes kw-dvx-fade-out { from { opacity: 1; } to { opacity: 0; } }
+.kw-dvx-grab { display: block; width: 36px; height: 4px; border-radius: 2px; margin: 0 auto 12px; background: theme('colors.zinc.600'); }
+.kw-dvx-sheet .kw-dvx-close { top: 6px; right: 6px; width: 44px; height: 44px; }
+.kw-dvx-sheet .kw-dvx-actions { flex-direction: column; align-items: stretch; gap: 8px; }
+.kw-dvx-sheet .kw-dvx-primary { height: 44px; width: 100%; }
+.kw-dvx-sheet .kw-dvx-guide { justify-content: center; min-height: 44px; }
+@media (prefers-reduced-motion: reduce) {
+ .kw-dv-track, .kw-dv-knob { transition: none !important; }
+ .kw-dvx-pop, .kw-dvx-sheet, .kw-dvx-scrim, .kw-dvx-sheet[data-closing], .kw-dvx-scrim[data-closing] { animation: none; }
+ .kw-sc-skel { animation: none; }
+ .kw-dv[data-saving] .kw-dv-knob::after { animation: none; }
+}
/* The flip note under the space header: HEAD → dev / merged into main, one caret blink */
.kw-dv-note { animation: kw-dv-hint 150ms var(--kw-ease) both; }
.kw-dv-note .dv-caret { animation-iteration-count: 1; }
@@ -672,9 +778,8 @@ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow:
@keyframes kw-dv-grid { from { opacity: 0; } to { opacity: 1; } }
@media (prefers-reduced-motion: reduce) {
- .kw-dv, .kw-dv *, .kw-dv::after { transition: none !important; }
- .kw-dv-halo { animation: none !important; opacity: 0 !important; }
- .kw-dv-hint, .kw-dv-note, .kw-dev-badge, .kw-dev-hat, .kw-blueprint::before { animation: none; }
+ .kw-dv, .kw-dv * { transition: none !important; }
+ .kw-dv-note, .kw-dev-badge, .kw-dev-hat, .kw-blueprint::before { animation: none; }
.kw-dev-caret { animation: none; }
}
diff --git a/frontend/tests/approvalsOff.test.mjs b/frontend/tests/approvalsOff.test.mjs
index e9365685..8430f3a3 100644
--- a/frontend/tests/approvalsOff.test.mjs
+++ b/frontend/tests/approvalsOff.test.mjs
@@ -215,20 +215,27 @@ test('the marker has an icon and words, not colour alone', () => {
assert.match(m.badge({ onClick: () => {} }), /^<button type="button"/);
});
-test('sidebar: the bot list marks only bots that run without asking, and the space header says so', () => {
+test('sidebar: the bot list marks only bots that run without asking, and the Approvals row says so', () => {
const html = m.sidebar({ space: space('ask'), kwants: [bot('k1', 'Dev', 'off', 'off'), bot('k2', 'Writer', 'inherit', 'ask')] });
const rows = html.split('group/fleet').slice(1);
assert.equal(rows.length, 2);
assert.match(rows[0], /Dev[\s\S]*sr-only">Approvals off/);
assert.doesNotMatch(rows[1], /Approvals off/);
- assert.match(text(html), /Approvals off for 1 bot/);
+ assert.match(html, /data-approvals-value="ask"/);
+ assert.match(html, /data-approvals-sub="true"><span[^>]*>Off for 1 bot</);
+ assert.doesNotMatch(text(html), /Approvals off for/, 'the amber header pill is gone (spec §5)');
});
-test('sidebar: space off shows the header line; nothing at all while every bot asks', () => {
- assert.match(text(m.sidebar({ space: space('off'), kwants: [bot('k1', 'Dev', 'inherit', 'off')] })), /Approvals off/);
+test('sidebar: space off shows Off in the Approvals row; Ask with no sub-line while every bot asks; no row on an older server', () => {
+ const off = m.sidebar({ space: space('off'), kwants: [bot('k1', 'Dev', 'inherit', 'off')] });
+ assert.match(off, /data-approvals-value="off"/);
+ assert.match(text(off), /Approvals Off Bots act without asking/);
const asking = m.sidebar({ space: space('ask'), kwants: [bot('k1', 'Dev', 'inherit', 'ask')] });
+ assert.match(asking, /data-approvals-value="ask"/);
+ assert.doesNotMatch(asking, /data-approvals-sub/);
assert.doesNotMatch(text(asking), /Approvals off/);
const older = m.sidebar({ space: space(undefined), kwants: [bot('k1', 'Dev', undefined, undefined)] });
+ assert.doesNotMatch(older, /data-sc-row="approvals"/);
assert.doesNotMatch(text(older), /Approvals off/);
});
@@ -236,11 +243,11 @@ test('every approvals-off hover hint says payments still ask: badge, sidebar row
assert.match(m.badge({}), /title="[^"]*Payments still ask you\.[^"]*"/);
const html = m.sidebar({ space: space('off'), kwants: [bot('k1', 'Dev', 'inherit', 'off')] });
const tips = [...html.matchAll(/title="([^"]*without asking[^"]*)"/g)].map((x) => x[1]);
- assert.equal(tips.length, 1, 'said once, on the space header line: a bot that matches the space adds no icon');
+ assert.equal(tips.length, 1, 'said once, on the Approvals row value: a bot that matches the space adds no icon');
for (const t of tips) assert.match(t, /Payments still ask you\./);
const differing = m.sidebar({ space: space('ask'), kwants: [bot('k1', 'Dev', 'off', 'off')] });
const botTips = [...differing.matchAll(/title="([^"]*without asking[^"]*)"/g)].map((x) => x[1]);
- assert.equal(botTips.length, 2, 'the space header summary and the bot that differs from the space');
+ assert.equal(botTips.length, 1, 'only the bot that differs from the space; the Approvals row says Off for 1 bot in words');
assert.ok(botTips.some((t) => /^Dev acts without asking/.test(t)), 'a bot that differs from the space still shows its own icon');
for (const t of botTips) assert.match(t, /Payments still ask you\./);
assert.match(m.spaceSetting({ value: 'off' }), /title="Approvals are off in Work\. Payments still ask you\."/);
diff --git a/frontend/tests/devAutodetect.test.mjs b/frontend/tests/devAutodetect.test.mjs
index 957b844e..c1271b85 100644
--- a/frontend/tests/devAutodetect.test.mjs
+++ b/frontend/tests/devAutodetect.test.mjs
@@ -191,7 +191,7 @@ test('first-run block copy (flow copy §5): three numbered lines', () => {
[
'01 What landed. Every merge to main in plain words, and when main is ready to ship.',
'02 Reviews. A second bot reads each pull request before you merge it.',
- '03 Production floor. Deploys and live-database commands wait for your OK.',
+ '03 Production floor. Pushes to main, deploys and deleting data always wait for your OK, even with approvals off.',
],
);
});
@@ -843,14 +843,16 @@ test('F8-R3-1: a space never seen in this browser shows the switch as loading (n
assert.equal(sw().getAttribute('aria-busy'), 'true');
assert.equal(sw().disabled, true, 'not pressable before its state is known');
assert.equal(sw().hasAttribute('data-on'), false);
- assert.equal(sw().querySelector('.kw-dv-node').getAttribute('visibility'), 'hidden', 'no node on either side');
+ assert.equal(sw().querySelector('[data-dv-knob]').style.visibility, 'hidden', 'no knob on either side');
+ assert.equal(sw().querySelector('[data-dv-word]').textContent, '', 'neither Off nor On');
release();
await settle(20);
assert.notEqual(sw().dataset.devSwitch, 'loading');
assert.equal(sw().getAttribute('aria-checked'), 'true');
assert.equal(sw().hasAttribute('aria-busy'), false);
assert.equal(sw().disabled, false);
- assert.equal(sw().querySelector('.kw-dv-node').hasAttribute('visibility'), false);
+ assert.equal(sw().querySelector('[data-dv-knob]').style.visibility, '');
+ assert.equal(sw().querySelector('[data-dv-word]').textContent, 'On');
assert.equal(m.lastOn.get('spc_demo'), true, 'the next load starts on');
g.fetch = g.window.fetch = realFetch;
root.unmount();
diff --git a/frontend/tests/devMode.test.mjs b/frontend/tests/devMode.test.mjs
index 505c6ab1..2d19ae42 100644
--- a/frontend/tests/devMode.test.mjs
+++ b/frontend/tests/devMode.test.mjs
@@ -43,6 +43,7 @@ const m = await loadBundled(`
export * from './src/devMode';
export { DevModeSwitch, DevOffNote, DevFlipNote, DevBadge, HardHat } from './src/components/DevModeSwitch';
export { DevModeSetup } from './src/components/DevModeSetup';
+ export { SpaceControls } from './src/components/SpaceControls';
export { DevModeSettings } from './src/components/DevModeSettings';
export { ConnectionRow } from './src/components/ConnectionsView';
export { canMarkProduction } from './src/connections';
@@ -95,7 +96,7 @@ test('flow F1: off → on is one press (set up already); no cover while off', ()
assert.equal(look.label, 'Dev mode');
assert.equal(look.describe, 'Press twice to turn off.');
assert.equal(look.tooltip, 'Dev mode is on. Press twice to turn it off.');
- assert.equal(m.switchLook(m.initialSwitch()).describe, 'Turns on reviews, the ship gate and the production floor.');
+ assert.equal(m.switchLook(m.initialSwitch()).describe, 'For bots that write code');
assert.equal(m.switchLook(m.initialSwitch()).tooltip, 'Dev mode: plain-words merges, code reviews, production floor');
});
@@ -180,7 +181,7 @@ test('the server changing Dev mode closes a held-open cover; a disabled switch s
const d = R(m.initialSwitch({ on: true }), { type: 'server', state: null, disabled: true });
assert.equal(R(d, { type: 'press', now: 0 }), d);
const look = m.switchLook(d);
- assert.equal(look.tooltip, 'Only the space owner can change Dev mode.');
+ assert.equal(look.tooltip, 'Only the space owner can turn Dev mode on or off.');
assert.equal(look.ring, false, 'not the owner: no ring');
assert.equal(look.glyph, 'locked');
});
@@ -310,7 +311,8 @@ test('DOM: on → off with two presses saves PUT {on:false}, announces, and call
assert.equal(b.dataset.covered, undefined);
assert.ok(b.querySelector('[data-dv-glyph="unlocked"]'), 'armed: lock open');
assert.match(host.querySelector('[data-dv-live]').textContent, /Press again to turn Dev mode off, or Escape to keep it on\./);
- assert.ok(host.querySelector('[data-dv-hint]'));
+ assert.equal(!!host.querySelector('[data-dv-hint]'), false, 'v3: the armed hint is the space-controls sub-line, not a bubble');
+ assert.equal(b.querySelector('[data-dv-word]').textContent, 'Off?');
await click(b);
await click(b); // the double-click's third press: ignored while settling
// The save resolves on the event loop; a busy CI runner can take more than a few ticks, so wait for it
@@ -327,7 +329,7 @@ test('DOM: on → off with two presses saves PUT {on:false}, announces, and call
assert.equal(b.dataset.devSwitch, 'covered');
assert.equal(b.dataset.on, undefined);
assert.equal(b.getAttribute('aria-checked'), 'false');
- assert.equal(desc(host, b), 'Turns on reviews, the ship gate and the production floor.');
+ assert.equal(desc(host, b), 'For bots that write code');
await click(b); // a render mid-save once left the switch stuck; the next press still turns it on (one press)
assert.equal(b.dataset.on, 'true');
assert.deepEqual(server.calls.filter(([meth]) => meth === 'PUT').map(([, , body]) => body), [{ on: false }, { on: true }]);
@@ -373,7 +375,7 @@ test('DOM: a 403 on load shows the switch disabled', async () => {
reset();
server.fail = { method: 'GET', path: '/dev_mode', status: 403, error: 'only the person' };
const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
- assert.equal(switchEl(host).disabled, true);
+ assert.equal(switchEl(host).getAttribute('aria-disabled'), 'true', 'focusable but not pressable, so the reason can be read');
assert.ok(switchEl(host).querySelector('[data-dv-glyph="locked"]'), 'disabled shows a closed lock');
root.unmount();
});
@@ -384,8 +386,8 @@ test('DOM: reduced motion shows the same switch, turns on in one press and arms
const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
const b = switchEl(host);
assert.ok(b.classList.contains('kw-dv-rm'));
- assert.ok(b.querySelector('[data-dv-graph] .kw-dv-node'), 'the same branch graph');
- assert.equal(b.textContent.trim(), 'dev', 'the reduced-motion variant keeps its dev label');
+ assert.ok(b.querySelector('[data-dv-track] [data-dv-knob]'), 'the same track and knob');
+ assert.equal(b.querySelector('[data-dv-word]').textContent, 'Off', 'the reduced-motion variant keeps its word');
await click(b);
assert.equal(b.dataset.devSwitch, 'covered');
assert.equal(b.dataset.on, 'true');
@@ -393,7 +395,7 @@ test('DOM: reduced motion shows the same switch, turns on in one press and arms
await settle();
await click(b);
assert.equal(b.dataset.devSwitch, 'lifted', 'the next press arms at once: nothing to settle');
- assert.equal(b.querySelector('[data-dv-word]').textContent, 'off?');
+ assert.equal(b.querySelector('[data-dv-word]').textContent, 'Off?');
root.unmount();
delete window.matchMedia;
});
@@ -407,7 +409,7 @@ test('switchLook names the visual state and the knob glyph: off, armed, on, disa
assert.deepEqual(pick({ disabled: true, on: true }), ['disabled', 'locked']);
});
-test('0.7.1 look (style v2 §10): the Branch switch; label dev → (one press) dev → off?; 44 px tall on phone; no knob or track', async () => {
+test('switch v3 (dev-mode-explainer §3): a word and a track; Off → (one press) On → Off?; 44 px tall on phone; no branch graph', async () => {
reset({ ...off, on: false, repo: 'demo-org/demo-app', polled_at: 'x' });
const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' }, phone: true }));
const b = switchEl(host);
@@ -415,28 +417,26 @@ test('0.7.1 look (style v2 §10): the Branch switch; label dev → (one press) d
assert.ok(b.classList.contains('kw-dv') && !b.classList.contains('kw-dv-rm'));
assert.ok(b.classList.contains('h-11'), 'the phone target is 44 px tall');
assert.ok(host.querySelector('[data-dev-switch-wrap]').className.includes('min-w-[44px]'));
- for (const gone of ['.kw-dv-cover', '.kw-dv-hinge', '.kw-dv-ring', '.kw-dv-knob', '.kw-dv-track']) assert.equal(!!b.querySelector(gone), false, gone);
- const svg = b.querySelector('svg[data-dv-graph]');
- assert.equal(svg.getAttribute('viewBox'), '0 0 44 24');
- assert.equal(svg.querySelector('.kw-dv-base').getAttribute('d'), 'M2 17H42');
- assert.equal(svg.querySelector('.kw-dv-fork').getAttribute('d'), 'M12 17C19 17 18 7 26 7H42');
- assert.equal(svg.querySelector('.kw-dv-dot').getAttribute('r'), '5');
- assert.equal(svg.querySelector('.kw-dv-pip').getAttribute('r'), '1.6');
- assert.equal(word(), 'dev');
- assert.equal(b.dataset.armed, undefined);
+ assert.ok(b.querySelector('[data-dv-track] [data-dv-knob]'), 'a track with a knob');
+ assert.equal(b.querySelector('[data-dv-word]').getAttribute('aria-hidden'), 'true', 'the word is visual; aria-checked carries the state');
+ for (const gone of ['svg[data-dv-graph]', '.kw-dv-cover', '.kw-dv-hinge', '.kw-dv-ring']) assert.equal(!!b.querySelector(gone), false, gone);
+ assert.equal(word(), 'Off');
+ assert.equal(b.dataset.knob, 'left');
await click(b);
assert.equal(b.dataset.on, 'true', 'one press: on');
assert.equal(b.dataset.armed, undefined, 'never armed on the way on');
- assert.equal(word(), 'dev');
+ assert.equal(word(), 'On');
+ assert.equal(b.dataset.knob, 'right');
root.unmount();
reset({ ...off, on: true, repo: 'demo-org/demo-app', polled_at: 'x' });
const on = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
const b2 = switchEl(on.host);
assert.equal(b2.dataset.on, 'true');
- assert.equal(b2.querySelector('[data-dv-word]').textContent, 'dev');
+ assert.equal(b2.querySelector('[data-dv-word]').textContent, 'On');
await click(b2);
- assert.equal(b2.querySelector('[data-dv-word]').textContent, 'off?', 'armed to turn off asks off?');
- assert.equal(b2.dataset.on, 'true', 'the node stays on the fork while armed to turn off');
+ assert.equal(b2.querySelector('[data-dv-word]').textContent, 'Off?', 'armed to turn off asks Off?');
+ assert.equal(b2.dataset.on, 'true', 'still on while armed to turn off');
+ assert.ok(b2.querySelector('[data-dv-glyph="unlocked"]'));
on.root.unmount();
});
@@ -606,16 +606,16 @@ test('Dev desk: empty What landed, then the Reviews tab by keyboard', async () =
});
// Round 2 (Mira's review of #315): B1 toast, S2/S3 setup footer, S1 desk header, S4 tab targets.
-test('round 2: on phone the hint is a viewport toast above the tab bar with the short copy', async () => {
+test('v3: on phone the armed switch shows no toast; the space-controls sub-line says Press again to turn off', async () => {
reset({ ...off, on: true, repo: 'demo-org/demo-app', branch: 'main', polled_at: '2026-11-05T08:00:00Z' });
- const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' }, phone: true }));
+ const { host, root } = await mount(h(m.SpaceControls, { space: { id: 'spc_demo', name: 'Demo' }, phone: true, bots: [] }));
+ assert.match(host.querySelector('[data-dev-sub-text]').textContent, /Watching demo-org\/demo-app · main/);
await click(switchEl(host));
- const hint = host.querySelector('[data-dv-hint]');
- assert.equal(hint.textContent, 'Press again to turn Dev mode off');
- for (const c of ['fixed', 'inset-x-4', 'mx-auto', 'w-fit', 'max-w-[calc(100vw-32px)]', 'text-center', 'bottom-[calc(56px+env(safe-area-inset-bottom)+12px)]']) {
- assert.ok(hint.classList.contains(c), c);
- }
- assert.ok(!hint.classList.contains('whitespace-nowrap'), 'may wrap to 2 lines rather than run off');
+ assert.equal(!!document.querySelector('[data-dv-hint]'), false);
+ const sub = host.querySelector('[data-dev-sub]');
+ assert.equal(sub.dataset.devSub, 'armed');
+ assert.equal(host.querySelector('[data-dev-sub-text]').textContent, 'Press again to turn off');
+ assert.equal(!!sub.querySelector('kbd'), false, 'no Esc key hint on a phone');
root.unmount();
});
diff --git a/frontend/tests/ia.test.mjs b/frontend/tests/ia.test.mjs
index daac391d..8bb545d5 100644
--- a/frontend/tests/ia.test.mjs
+++ b/frontend/tests/ia.test.mjs
@@ -272,13 +272,13 @@ test('QA d: nothing tells the person to look in Settings → Profiles any more',
}
});
-test('desktop header: the Dev switch has its own row under the name; phones keep it in the name row', () => {
- const html = ui.sidebar(base);
- const header = html.slice(html.indexOf('data-space-header'), html.indexOf('data-dev-switch-row'));
- assert.doesNotMatch(header, /data-dev-switch[ =>]/, 'no switch in the desktop name row');
- assert.match(html, /class="h-8 flex items-center pl-12" data-dev-switch-row/);
- assert.match(html.slice(html.indexOf('data-dev-switch-row')), /data-dev-switch/);
- const phone = ui.sidebar({ ...base, phone: true, section: 'chats' });
- assert.doesNotMatch(phone, /data-dev-switch-row/);
- assert.match(phone, /data-dev-switch/);
+test('header (dev-mode-explainer §1): the name row holds no switch; the Space controls block under it holds Dev mode, on desktop and phone', () => {
+ for (const html of [ui.sidebar(base), ui.sidebar({ ...base, phone: true, section: 'chats' })]) {
+ const header = html.slice(0, html.indexOf('data-space-controls'));
+ assert.doesNotMatch(header, /data-dev-switch[ =>]/, 'no switch in the name row');
+ assert.doesNotMatch(html, /data-dev-switch-row|data-dev-meta/);
+ const block = html.slice(html.indexOf('data-space-controls'));
+ assert.match(block, /data-sc-row="dev"[\s\S]*data-dev-switch/);
+ assert.match(header, />0 bots · no account yet</, 'the subtitle stays the space summary');
+ }
});
diff --git a/frontend/tests/spaceControls.test.mjs b/frontend/tests/spaceControls.test.mjs
new file mode 100644
index 00000000..da007fb0
--- /dev/null
+++ b/frontend/tests/spaceControls.test.mjs
@@ -0,0 +1,452 @@
+// 0.7.2 space controls (dev-mode-explainer spec §1–§5): the Dev mode and Approvals rows under the space
+// name, the §2 sub-line priority, the "?" explainer (popover on desktop, sheet on phone) and the switch v3
+// wiring. Demo data only.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_demo', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', '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;
+
+const off = { on: false, repo: null, branch: null, deploy_hint: null, backup_command: null, last_seen_sha: null, polled_at: null, poll_error: null, calls_today: null, calls_cap: null };
+const R = (repo, status, extra = {}) => ({ repo, host: 'github.com', status, branch: 'main', team: 'Ship', from: 'repo', added_by: 'team', ...extra });
+let server = { state: { ...off }, calls: [] };
+g.fetch = g.window.fetch = async (url, init = {}) => {
+ const u = String(url);
+ const method = init.method ?? 'GET';
+ const body = init.body ? JSON.parse(init.body) : undefined;
+ server.calls.push([method, u.split('?')[0], body]);
+ const json = (b, status = 200) => new Response(JSON.stringify(b), { status, headers: { 'Content-Type': 'application/json' } });
+ if (server.fail && server.fail.method === method && u.includes(server.fail.path)) return json({ error: 'nope' }, server.fail.status);
+ if (u.includes('/dev_mode')) {
+ if (method === 'PUT') server.state = { ...server.state, ...body };
+ return json(server.state);
+ }
+ return json({});
+};
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { devSubLine, devListPending, parseDevMode, devStore, DEV_GUIDE_URL, EXPLAINER } from './src/devMode';
+ export { approvalsRow } from './src/approvalMode';
+ export { SpaceControls, SHEET_CLOSE_MS, APPROVALS_WAIT_MS } from './src/components/SpaceControls';
+`);
+const { React, createRoot } = m;
+const h = React.createElement;
+const ourEntry = () => !!window.history.state?.kwBrowserOverlay;
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+const settle = async (n = 10) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const reset = (state = off) => {
+ server = { state: { ...state }, calls: [], fail: null };
+ m.devStore._reset();
+ document.body.innerHTML = '';
+};
+const mount = async (props) => {
+ const host = document.createElement('div');
+ host.setAttribute('data-kw-sidebar', '');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(h(m.SpaceControls, { space: { id: 'spc_demo', name: 'Demo', approvals: 'ask' }, bots: [], onOpenSettings() {}, ...props }));
+ await settle();
+ return { host, root };
+};
+const click = async (el) => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const key = async (el, k, o = {}) => {
+ el.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, ...o }));
+ await settle();
+};
+const text = (sub) => sub.parts.map((p) => p.text).join('');
+const S = (o) => m.parseDevMode({ ...off, on: true, polled_at: 'x', status: 'watching', ...o });
+
+// ---------------------------------------------------------------- §2 sub-line
+
+test('§2 sub-line: one repo names it and its branch; several count; partial and errors say so', () => {
+ const one = m.devSubLine(S({ repos: [R('demo-org/app', 'watching', { branch: 'trunk' })] }));
+ assert.equal(one.state, 'watching');
+ assert.equal(text(one), 'Watching demo-org/app · trunk');
+ assert.equal(one.led, 'ok');
+ assert.equal(one.action, null);
+ assert.deepEqual(one.parts.filter((p) => p.repo).map((p) => p.text), ['demo-org/app']);
+ const noBranch = m.devSubLine(S({ repos: [R('demo-org/app', 'watching', { branch: null })] }));
+ assert.equal(text(noBranch), 'Watching demo-org/app · main');
+ const three = m.devSubLine(S({ repos: [R('demo-org/app', 'watching'), R('demo-org/api', 'watching'), R('demo-org/web', 'watching')] }));
+ assert.equal(text(three), 'Watching 3 repos');
+ assert.equal(three.action, 'repos');
+ const partial = m.devSubLine(S({ repos: [R('demo-org/app', 'watching'), R('demo-org/api', 'error')] }));
+ assert.deepEqual([partial.state, text(partial), partial.led, partial.action], ['partial', '1 of 2 watched', 'warn', 'repos']);
+ const err1 = m.devSubLine(S({ repos: [R('demo-org/app', 'error')] }));
+ assert.deepEqual([text(err1), err1.led], ['Can’t read a repo', 'bad']);
+ assert.equal(text(m.devSubLine(S({ repos: [R('demo-org/app', 'error'), R('demo-org/api', 'error')] }))), 'Can’t read 2 repos');
+});
+
+test('§2 sub-line: GitHub not connected, other hosts, a local folder, no repo, never a checking line', () => {
+ const nc = m.devSubLine(S({ repos: [R('demo-org/app', 'not_connected')] }));
+ assert.deepEqual([text(nc), nc.led, nc.action], ['Needs GitHub', 'warn', 'connect']);
+ const gl = m.devSubLine(S({ repos: [R('gitlab.example.test/demo/app', 'other_host', { host: 'gitlab.example.test' })] }));
+ assert.equal(text(gl), 'gitlab.example.test isn’t read yet');
+ assert.equal(gl.led, 'off');
+ const local = m.devSubLine(S({ repos: [R('app', 'other_host', { host: null, from: 'local' })] }));
+ assert.equal(text(local), 'Local folder, no remote');
+ const none = m.devSubLine(S({ repos: [], status: 'no_repo' }));
+ assert.deepEqual([none.state, text(none), none.action], ['no_repo', 'No repo yet', 'link']);
+ // Answer 1 + addendum 3: no "checking" words. Until the first repo list arrives the line is a skeleton,
+ // never "No repo yet": no state yet, on with neither a status nor a repo, or a press on still saving.
+ for (const [s, o] of [[null, { loading: true }], [m.parseDevMode({ ...off, on: true, repos: [] }), {}], [m.parseDevMode(off), { turningOn: true }]]) {
+ const l = m.devSubLine(s, o);
+ assert.deepEqual([l.state, text(l), l.led, l.action], ['loading', '', null, null]);
+ }
+ assert.equal(m.devSubLine(null, { disabled: true }).state, 'disabled', 'not the owner never waits on a list');
+ assert.equal(m.devSubLine(m.parseDevMode(off)).state, 'off');
+ assert.equal(m.devSubLine(null).state, 'off', 'a failed first load stops waiting');
+});
+
+test('§2 sub-line: armed beats everything, off says what it is for, not-owner is its own state', () => {
+ const s = S({ repos: [R('demo-org/app', 'error')] });
+ assert.deepEqual([m.devSubLine(s, { armed: true }).state, text(m.devSubLine(s, { armed: true }))], ['armed', 'Press again to turn off']);
+ assert.equal(text(m.devSubLine(m.parseDevMode(off))), 'For bots that write code');
+ assert.equal(text(m.devSubLine(null)), 'For bots that write code');
+ assert.equal(m.devSubLine(null, { disabled: true }).state, 'disabled');
+});
+
+// ---------------------------------------------------------------- Approvals row
+
+test('approvals row: chip and sub-line per §2, no row on an older server, never counts bots that ask', () => {
+ const b = (e) => ({ approvals_effective: e });
+ assert.equal(m.approvalsRow(undefined, [], false), null);
+ const ask = m.approvalsRow('ask', [b('ask')], false);
+ assert.deepEqual([ask.chip, ask.tone, ask.sub, ask.title], ['Ask', 'neutral', null, null]);
+ assert.equal(ask.label, 'Approvals: Ask. Change in space settings');
+ assert.equal(m.approvalsRow('smart', [b('off'), b('off'), b('smart')], false).sub, 'Off for 2 bots');
+ assert.equal(m.approvalsRow('ask', [b('off')], false).sub, 'Off for 1 bot');
+ const offRow = m.approvalsRow('off', [b('off')], false);
+ assert.deepEqual([offRow.chip, offRow.tone, offRow.sub], ['Off', 'warn', 'Bots act without asking']);
+ assert.match(offRow.title, /Payments still ask you\./);
+ assert.doesNotMatch(offRow.title, /With Dev mode on/);
+ const offDev = m.approvalsRow('off', [b('off')], true);
+ assert.equal(offDev.sub, 'Main and deploys still ask');
+ assert.match(offDev.title, /With Dev mode on, pushes to main, deploys and deleting data still ask\./);
+ assert.equal(m.approvalsRow('off', [b('off'), b('ask')], true).sub, '1 bot still asks');
+ assert.equal(m.approvalsRow('off', [b('ask'), b('smart')], false).sub, '2 bots still ask');
+});
+
+// ---------------------------------------------------------------- DOM
+
+test('DOM: two labelled rows; the switch is named by its label and described by the sub-line', async () => {
+ reset({ ...off, on: true, polled_at: 'x', status: 'watching', repos: [R('demo-org/app', 'watching')] });
+ const { host, root } = await mount({});
+ const group = host.querySelector('[data-space-controls]');
+ assert.equal(group.getAttribute('role'), 'group');
+ assert.equal(group.getAttribute('aria-label'), 'Space controls');
+ assert.deepEqual([...group.querySelectorAll('[data-sc-row]')].map((r) => r.dataset.scRow), ['dev', 'approvals']);
+ const sw = host.querySelector('[role="switch"]');
+ assert.equal(document.getElementById(sw.getAttribute('aria-labelledby')).textContent, 'Dev mode');
+ assert.equal(document.getElementById(sw.getAttribute('aria-describedby')).textContent, 'Watching demo-org/app · main');
+ assert.equal(sw.getAttribute('aria-checked'), 'true');
+ assert.equal(host.querySelector('[data-dev-sub]').dataset.devSub, 'watching');
+ assert.equal(!!host.querySelector('[data-dev-sub-action]'), false, 'one repo: no See repos');
+ const value = host.querySelector('[data-approvals-value]');
+ assert.equal(value.getAttribute('aria-label'), 'Approvals: Ask. Change in space settings');
+ root.unmount();
+});
+
+test('DOM: three repos say Watching 3 repos with See repos; the Approvals value opens settings', async () => {
+ reset({ ...off, on: true, polled_at: 'x', status: 'watching', repos: [R('demo-org/app', 'watching'), R('demo-org/api', 'watching'), R('demo-org/web', 'watching')] });
+ let seen = 0;
+ let settings = 0;
+ const { host, root } = await mount({ onSeeRepos: () => seen++, onOpenSettings: () => settings++ });
+ assert.equal(host.querySelector('[data-dev-sub-text]').textContent, 'Watching 3 repos');
+ const act = host.querySelector('[data-dev-sub-action]');
+ assert.equal(act.textContent, 'See repos');
+ assert.equal(act.tagName, 'BUTTON');
+ await click(act);
+ assert.equal(seen, 1);
+ await click(host.querySelector('[data-approvals-value]'));
+ assert.equal(settings, 1);
+ root.unmount();
+});
+
+test('DOM: armed off shows Off?, the sub-line Press again to turn off with an Esc hint on desktop; Escape keeps it on', async () => {
+ reset({ ...off, on: true, polled_at: 'x', status: 'watching', repos: [R('demo-org/app', 'watching')] });
+ const { host, root } = await mount({});
+ const sw = host.querySelector('[role="switch"]');
+ await click(sw);
+ assert.equal(sw.querySelector('[data-dv-word]').textContent, 'Off?');
+ const sub = host.querySelector('[data-dev-sub]');
+ assert.equal(sub.dataset.devSub, 'armed');
+ assert.equal(host.querySelector('[data-dev-sub-text]').textContent, 'Press again to turn off');
+ assert.equal(sub.querySelector('kbd')?.textContent, 'Esc');
+ await key(sw, 'Escape');
+ assert.equal(host.querySelector('[data-dev-sub]').dataset.devSub, 'watching');
+ assert.equal(server.calls.filter(([meth]) => meth === 'PUT').length, 0);
+ root.unmount();
+});
+
+test('DOM: the "?" opens the popover on desktop, focus goes to Turn on, Escape closes it back to "?"', async () => {
+ reset({ ...off });
+ const { host, root } = await mount({});
+ const q = host.querySelector('[data-dv-help]');
+ assert.equal(q.getAttribute('aria-label'), 'What is Dev mode?');
+ assert.equal(q.getAttribute('aria-haspopup'), 'dialog');
+ assert.equal(q.getAttribute('aria-expanded'), 'false');
+ await click(q);
+ assert.equal(q.getAttribute('aria-expanded'), 'true');
+ const pop = document.querySelector('[data-dev-explainer]');
+ assert.equal(pop.dataset.devExplainer, 'popover');
+ assert.equal(pop.id, q.getAttribute('aria-controls'));
+ assert.equal(pop.getAttribute('role'), 'dialog');
+ assert.equal(pop.hasAttribute('aria-modal'), false, 'non-modal on desktop');
+ assert.equal(document.getElementById(pop.getAttribute('aria-labelledby')).textContent, m.EXPLAINER.title);
+ assert.equal(pop.querySelectorAll('[data-dev-feature]').length, 3);
+ const guide = pop.querySelector('[data-dvx-guide]');
+ assert.equal(guide.getAttribute('href'), 'https://kwant.si/docs/dev-mode.html');
+ assert.equal(guide.getAttribute('target'), '_blank');
+ assert.match(guide.getAttribute('rel'), /noopener/);
+ assert.match(guide.textContent, /opens in a new tab/);
+ const primary = pop.querySelector('[data-dvx-primary]');
+ assert.equal(primary.dataset.dvxPrimary, 'on');
+ assert.equal(document.activeElement === primary, true, 'focus lands on Turn on Dev mode');
+ await key(primary, 'Escape');
+ await settle();
+ assert.equal(!!document.querySelector('[data-dev-explainer]'), false);
+ assert.equal(q.getAttribute('aria-expanded'), 'false');
+ assert.equal(document.activeElement === q, true, 'focus back on "?"');
+ root.unmount();
+});
+
+test('DOM: Turn on in the explainer presses the switch once (PUT {on:true}) and closes', async () => {
+ reset({ ...off });
+ let turnedOn = 0;
+ const { host, root } = await mount({ onTurnedOn: () => turnedOn++ });
+ await click(host.querySelector('[data-dv-help]'));
+ await click(document.querySelector('[data-dvx-primary="on"]'));
+ await settle(20);
+ assert.deepEqual(server.calls.filter(([meth]) => meth === 'PUT').map(([, , b]) => b), [{ on: true }]);
+ assert.equal(turnedOn, 1);
+ assert.equal(!!document.querySelector('[data-dev-explainer]'), false);
+ assert.equal(host.querySelector('[role="switch"]').getAttribute('aria-checked'), 'true');
+ root.unmount();
+});
+
+test('DOM: when on, the explainer offers Open Dev desk; an outside press closes it', async () => {
+ reset({ ...off, on: true, polled_at: 'x', status: 'watching', repos: [R('demo-org/app', 'watching')] });
+ let desk = 0;
+ const { host, root } = await mount({ onOpenDevDesk: () => desk++ });
+ await click(host.querySelector('[data-dv-help]'));
+ const primary = document.querySelector('[data-dvx-primary]');
+ assert.equal(primary.dataset.dvxPrimary, 'desk');
+ assert.equal(primary.textContent, 'Open Dev desk');
+ await click(primary);
+ assert.equal(desk, 1);
+ if (document.querySelector('[data-dev-explainer]')) {
+ document.body.dispatchEvent(new window.Event('pointerdown', { bubbles: true }));
+ await settle();
+ }
+ assert.equal(!!document.querySelector('[data-dev-explainer]'), false);
+ root.unmount();
+});
+
+test('DOM: not the owner (403): the switch is aria-disabled, the explainer says who can turn it on', async () => {
+ reset({ ...off });
+ server.fail = { method: 'GET', path: '/dev_mode', status: 403 };
+ const { host, root } = await mount({});
+ const sw = host.querySelector('[role="switch"]');
+ assert.equal(sw.getAttribute('aria-disabled'), 'true');
+ await click(host.querySelector('[data-dv-help]'));
+ const pop = document.querySelector('[data-dev-explainer]');
+ assert.equal(!!pop.querySelector('[data-dvx-primary]'), false);
+ assert.equal(pop.querySelector('[data-dvx-not-owner]').textContent, m.EXPLAINER.notOwner);
+ root.unmount();
+});
+
+test('DOM: on a phone the explainer is a modal sheet; the page behind is inert; the X closes it', async () => {
+ reset({ ...off });
+ const { host, root } = await mount({ phone: true });
+ assert.ok(host.querySelector('[data-space-controls]').classList.contains('kw-sc-phone'));
+ await click(host.querySelector('[data-dv-help]'));
+ const sheet = document.querySelector('[data-dev-explainer]');
+ assert.equal(sheet.dataset.devExplainer, 'sheet');
+ assert.equal(sheet.getAttribute('aria-modal'), 'true');
+ assert.equal(host.hasAttribute('inert'), true, 'the sidebar behind is inert');
+ assert.ok(document.querySelector('[data-dvx-scrim]'));
+ await click(sheet.querySelector('[data-dvx-close]'));
+ await wait(m.SHEET_CLOSE_MS + 40);
+ assert.equal(!!document.querySelector('[data-dev-explainer]'), false);
+ assert.equal(host.hasAttribute('inert'), false);
+ root.unmount();
+});
+
+// ---------------------------------------------------------------- Ada's answers 1, 3 and 4 (0.7.2)
+
+test('answer 4: the phone sheet slides down for 150 ms before it goes; the X takes its history entry off', async () => {
+ reset({ ...off });
+ const { host, root } = await mount({ phone: true });
+ assert.equal(ourEntry(), false);
+ await click(host.querySelector('[data-dv-help]'));
+ assert.equal(ourEntry(), true, 'opening the sheet pushes a history entry');
+ const sheet = document.querySelector('[data-dev-explainer]');
+ await click(sheet.querySelector('[data-dvx-close]'));
+ assert.equal(sheet.dataset.closing, 'true', 'the sheet is sliding down');
+ assert.equal(document.querySelector('[data-dvx-scrim]').dataset.closing, 'true', 'the scrim fades with it');
+ assert.ok(document.querySelector('[data-dev-explainer]'), 'still there during the slide');
+ await wait(m.SHEET_CLOSE_MS + 40);
+ assert.equal(!!document.querySelector('[data-dev-explainer]'), false);
+ await wait(30);
+ assert.equal(ourEntry(), false, 'closing with the X took the entry off');
+ root.unmount();
+});
+
+test('answer 4: the back gesture closes the phone sheet', async () => {
+ reset({ ...off });
+ const { host, root } = await mount({ phone: true });
+ await click(host.querySelector('[data-dv-help]'));
+ assert.ok(document.querySelector('[data-dev-explainer]'));
+ assert.equal(ourEntry(), true);
+ window.history.back();
+ await wait(m.SHEET_CLOSE_MS + 80);
+ assert.equal(ourEntry(), false);
+ assert.equal(!!document.querySelector('[data-dev-explainer]'), false);
+ assert.equal(host.hasAttribute('inert'), false);
+ root.unmount();
+});
+
+test('answer 4: under reduced motion the sheet closes at once; desktop pushes no history entry', async () => {
+ reset({ ...off });
+ const had = window.matchMedia;
+ window.matchMedia = (q) => ({ matches: q.includes('reduce'), media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+ try {
+ const { host, root } = await mount({ phone: true });
+ await click(host.querySelector('[data-dv-help]'));
+ await click(document.querySelector('[data-dvx-close]'));
+ assert.equal(!!document.querySelector('[data-dev-explainer]'), false, 'gone with no slide');
+ root.unmount();
+ } finally {
+ window.matchMedia = had;
+ }
+ await wait(30);
+ const { host, root } = await mount({});
+ await click(host.querySelector('[data-dv-help]'));
+ assert.equal(ourEntry(), false, 'the desktop popover adds no history entry');
+ root.unmount();
+ const css = readFileSync(new URL('../src/styles/modern.css', import.meta.url), 'utf8');
+ assert.match(css, /\.kw-dvx-sheet\[data-closing\][^{]*\{[^}]*150ms/);
+ assert.match(css, /prefers-reduced-motion: reduce\)\s*\{[^@]*\.kw-dvx-sheet\[data-closing\][^}]*animation: none/);
+});
+
+test('answer 3: while approvals load, the row is a same-height skeleton with no text', async () => {
+ reset({ ...off });
+ const { host, root } = await mount({ space: { id: 'spc_demo', name: 'Demo' } });
+ const sk = host.querySelector('[data-sc-row="approvals"]');
+ assert.ok(sk.hasAttribute('data-sc-skeleton'));
+ assert.ok(sk.classList.contains('kw-sc-row'), 'same row class, so the same height');
+ assert.equal(sk.getAttribute('aria-hidden'), 'true');
+ assert.equal(sk.textContent, '');
+ root.render(h(m.SpaceControls, { space: { id: 'spc_demo', name: 'Demo', approvals: 'ask' }, bots: [], onOpenSettings() {} }));
+ await settle();
+ const row = host.querySelector('[data-sc-row="approvals"]');
+ assert.equal(row.hasAttribute('data-sc-skeleton'), false);
+ assert.match(row.textContent, /Ask/);
+ root.unmount();
+});
+
+test('answer 3: an older server never sends approvals, so the skeleton goes and no row is drawn', async () => {
+ reset({ ...off });
+ const { host, root } = await mount({ space: { id: 'spc_demo', name: 'Demo' } });
+ assert.ok(host.querySelector('[data-sc-skeleton]'));
+ await wait(m.APPROVALS_WAIT_MS + 60);
+ assert.equal(!!host.querySelector('[data-sc-row="approvals"]'), false);
+ root.unmount();
+});
+
+test('addendum 3: a same-height skeleton sub-line until the first repo list arrives; never a flash of "No repo yet"', async () => {
+ reset({ ...off, on: true, status: 'no_repo', repos: [] });
+ let release;
+ const realFetch = g.fetch;
+ g.fetch = g.window.fetch = async (url, init = {}) => {
+ if ((init.method ?? 'GET') === 'GET' && String(url).includes('/dev_mode')) await new Promise((r) => (release = r));
+ return realFetch(url, init);
+ };
+ const seen = [];
+ const obs = new window.MutationObserver(() => seen.push(document.body.textContent));
+ obs.observe(document.body, { subtree: true, childList: true, characterData: true });
+ try {
+ const { host, root } = await mount({});
+ const sk = host.querySelector('[data-dev-sub]');
+ assert.equal(sk.dataset.devSub, 'loading');
+ assert.ok(sk.classList.contains('kw-sc-sub'), 'the sub-line class, so the same height');
+ assert.equal(sk.getAttribute('aria-hidden'), 'true');
+ assert.equal(sk.textContent, '');
+ assert.ok(host.querySelector('[data-sc-skeleton] .kw-sc-skel-sub'));
+ assert.ok(seen.every((t) => !/No repo yet/.test(t)), 'no "No repo yet" while the list loads');
+ release();
+ await settle(20);
+ assert.equal(host.querySelector('[data-dev-sub]').dataset.devSub, 'no_repo');
+ assert.match(host.querySelector('[data-dev-sub]').textContent, /No repo yet/);
+ root.unmount();
+ } finally {
+ obs.disconnect();
+ g.fetch = g.window.fetch = realFetch;
+ }
+});
+
+test('addendum 3: a failed first load stops the skeleton (the off line shows), it never waits forever', async () => {
+ reset({ ...off });
+ server.fail = { method: 'GET', path: '/dev_mode', status: 500 };
+ const { host, root } = await mount({});
+ await settle(20);
+ const sub = host.querySelector('[data-dev-sub]');
+ assert.equal(sub.dataset.devSub, 'off');
+ assert.equal(sub.textContent, 'For bots that write code');
+ root.unmount();
+});
+
+test('answer 1: no checking sub-line; the switch is busy only while its PUT is in flight', async () => {
+ reset({ ...off });
+ const { host, root } = await mount({});
+ const sw = host.querySelector('[role="switch"]');
+ let release;
+ const realFetch = g.fetch;
+ g.fetch = g.window.fetch = async (url, init = {}) => {
+ if ((init.method ?? 'GET') === 'PUT') await new Promise((r) => (release = r));
+ return realFetch(url, init);
+ };
+ try {
+ sw.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+ const dv = host.querySelector('[data-saving]');
+ assert.ok(dv, 'the knob spins while saving');
+ assert.equal(sw.getAttribute('aria-busy'), 'true');
+ assert.doesNotMatch(host.textContent, /Looking for repos/);
+ release();
+ await settle(20);
+ } finally {
+ g.fetch = g.window.fetch = realFetch;
+ }
+ assert.equal(!!host.querySelector('[data-saving]'), false);
+ assert.equal(!!host.querySelector('[aria-busy="true"]'), false);
+ assert.doesNotMatch(host.textContent, /Looking for repos/);
+ root.unmount();
+});
+
+test('copy: no emoji and no HTML from data in the controls or the explainer', async () => {
+ reset({ ...off, on: true, polled_at: 'x', status: 'watching', repos: [R('demo-org/<b>x</b>', 'watching')] });
+ const { host, root } = await mount({});
+ assert.equal(!!host.querySelector('b'), false, 'a repo name is text, never markup');
+ assert.match(host.querySelector('[data-dev-sub-text]').textContent, /demo-org\/<b>x<\/b>/);
+ await click(host.querySelector('[data-dv-help]'));
+ const all = host.textContent + document.querySelector('[data-dev-explainer]').textContent;
+ assert.doesNotMatch(all, /\p{Extended_Pictographic}/u);
+ root.unmount();
+});