Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.7 Dev mode: switch, setup sheet, Dev desk shell, settings, production mark (Pixel) (#315)

Oleksandr Ivanchenkoba610aed2b8e
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ac59c7b4..68fe0b95 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -125,6 +125,9 @@ import { PromptContext, suggestedPrompts } from './suggestedPrompts';
import { isNotificationOpen, showDeviceNotification } from './push';
import { EMPTY_PILL, NUDGES_SETTING_EVENT, browserIconDoc, createArrivals, createNudgeIcon, nudgesEnabled, pillAdd, pillPrune, setAppBadgeCount, shouldPill, type Nudge, type PillState } from './attention';
import { NeedsYouPill } from './components/NeedsYouPill';
+import { devApi, devStore } from './devMode';
+import { useDevModeOn } from './components/DevModeSwitch';
+import { DEV_CARD_EVENT, DevDeskView, type DevCardEvent } from './components/DevDesk';
import { inDesktopApp, leaveForSignIn, mcpSignIn, pollUntil, signInChanged } from './externalLinks';
// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),
@@ -340,11 +343,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const switchLogRef = useRef(createOutageLog());
// What fills the main pane instead of a chat: the Inbox (New or Loose ends), the Mission board
// or Parallel Universe. The Inbox's unseen count is the sidebar badge.
- const [page, setPage] = useState<'chat' | 'inbox' | 'board' | 'parallel'>(() =>
- initialView?.kind === 'inbox' || initialView?.kind === 'board' || initialView?.kind === 'parallel' ? initialView.kind : 'chat',
+ const [page, setPage] = useState<'chat' | 'inbox' | 'board' | 'parallel' | 'dev'>(() =>
+ initialView?.kind === 'inbox' || initialView?.kind === 'board' || initialView?.kind === 'parallel' || initialView?.kind === 'dev' ? initialView.kind : 'chat',
);
const [inboxTab, setInboxTab] = useState<InboxTab>(() => (initialView?.kind === 'inbox' ? initialView.tab : 'new'));
- const showPage = (next: 'inbox' | 'board' | 'parallel', tab: InboxTab = 'new') => {
+ const showPage = (next: 'inbox' | 'board' | 'parallel' | 'dev', tab: InboxTab = 'new') => {
setPage(next);
if (next === 'inbox') setInboxTab(tab);
if (spaceSettingsTab) closeSpaceSettings();
@@ -352,6 +355,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
// Mission board: shown in the sidebar only when the server has it switched on.
const [missionBoard, setMissionBoard] = useState(false);
+ // Dev mode (0.7): the open space's state, read by the switch, the hats and the grid.
+ useEffect(() => devStore.setCurrent(space.id), [space.id]);
+ const devOn = useDevModeOn(space.id);
// A task to open on the board once it shows (from a lesson on a bot's Memory tab).
const [pendingTaskId, setPendingTaskId] = useState<string | null>(null);
const [awayCount, setAwayCount] = useState(0);
@@ -1039,6 +1045,24 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
case 'FactDispute':
if (event.data?.dispute?.id) emitMission({ type: 'fact_dispute', data: { dispute: event.data.dispute } });
break;
+ // Dev mode (0.7): the switch, tiles, hats and grid follow `dev_mode`; the desk refetches on `dev_card`.
+ case 'dev_mode':
+ case 'DevMode': {
+ const d = event.data ?? {};
+ if (typeof d.space_id === 'string' && typeof d.on === 'boolean') {
+ devStore.setOn(d.space_id, d.on);
+ devApi.get(d.space_id).then((st) => devStore.set(d.space_id, st), () => undefined);
+ }
+ break;
+ }
+ case 'dev_card':
+ case 'DevCard': {
+ const d = event.data ?? {};
+ if (typeof d.space_id === 'string' && typeof d.id === 'string') {
+ window.dispatchEvent(new CustomEvent<DevCardEvent>(DEV_CARD_EVENT, { detail: { space_id: d.space_id, id: d.id, kind: String(d.kind ?? ''), status: String(d.status ?? '') } }));
+ }
+ break;
+ }
// Goals (0.6.5): the board's Goals strip reads the goal again.
case 'goal_updated':
case 'GoalUpdated': {
@@ -3110,6 +3134,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
showPage('board');
playSfx('click');
}}
+ devDeskActive={page === 'dev'}
+ onOpenDevDesk={() => {
+ showPage('dev');
+ playSfx('click');
+ }}
/>
);
@@ -3310,7 +3339,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (viewRequest) applyViewRef.current(viewRequest.view);
}, [viewRequest?.seq]);
- const mainPane = needsSetup ? setupChecklist : page === 'parallel' ? parallel : page === 'board' && missionBoard ? missionsPage : page === 'inbox' ? inbox : !loaded ? (
+ const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} />;
+ const mainPane = needsSetup ? setupChecklist : page === 'parallel' ? parallel : page === 'board' && missionBoard ? missionsPage : page === 'dev' && devOn ? devDeskPage : page === 'inbox' ? inbox : !loaded ? (
<main className="flex-1 flex items-center justify-center text-xs text-zinc-500">
<Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…
</main>
@@ -3343,7 +3373,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
)}
</div>
) : (
- <div className="flex-1 min-h-0 flex">{mainPane}</div>
+ <div className={`flex-1 min-h-0 flex ${devOn ? 'kw-blueprint' : ''}`} data-main-pane>{mainPane}</div>
)}
{(showPhoneList || needsSetup) && (
<PhoneTabBar
@@ -3369,7 +3399,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
) : (
<>
{sidebar('all')}
- {mainPane}
+ <div className={`flex-1 min-w-0 min-h-0 flex ${devOn ? 'kw-blueprint' : ''}`} data-main-pane>
+ {mainPane}
+ </div>
</>
)}
</div>
diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsx
index a72d04bd..1be58703 100644
--- a/frontend/src/components/ConnectionsView.tsx
+++ b/frontend/src/components/ConnectionsView.tsx
@@ -4,6 +4,8 @@ import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { relativeTime } from '../away';
import { quotaLine } from '../clock';
import { UnlockDialog, usePasswordStore } from './PasswordStorePanel';
+import { devApi, devStore } from '../devMode';
+import { useDevModeOn } from './DevModeSwitch';
import {
CatalogEntry,
ComposioApp,
@@ -17,6 +19,7 @@ import {
countsLine,
groupConnections,
isRawCommand,
+ canMarkProduction,
mcpServerId,
statusBadge,
storedLabel,
@@ -68,9 +71,12 @@ export interface ConnectionRowProps {
checking?: boolean;
links?: ManageLinks;
onCheck?: (c: Connection) => void;
+ /** Dev mode is on in this space: MCP servers and Composio apps get a Production mark (D10). */
+ onProduction?: (c: Connection, production: boolean) => void;
+ markingProduction?: boolean;
}
-export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(), checking = false, links = {}, onCheck }) => {
+export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(), checking = false, links = {}, onCheck, onProduction, markingProduction = false }) => {
const id = useId();
const badge = statusBadge(c.status);
const manage = manageFor(c.kind, links);
@@ -89,6 +95,11 @@ export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(
<span className={`inline-flex items-center px-1.5 py-px rounded border text-[11px] font-medium ${TONES[badge.tone]}`} data-status={c.status}>
{badge.label}
</span>
+ {c.production && (
+ <span className="inline-flex items-center px-1.5 py-px rounded border border-amber-400/40 bg-amber-500/10 text-[11px] font-medium text-amber-200" data-production-badge>
+ Production
+ </span>
+ )}
</div>
{c.detail &&
(isRawCommand(c) ? (
@@ -123,8 +134,22 @@ export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(
</div>
</dl>
</div>
- {(canCheck || manage) && (
- <div className="flex gap-2 shrink-0">
+ {(canCheck || manage || (onProduction && canMarkProduction(c))) && (
+ <div className="flex flex-wrap gap-2 shrink-0">
+ {onProduction && canMarkProduction(c) && (
+ <label className={`${quietBtn} cursor-pointer has-[:focus-visible]:outline has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-sky-500`} title="Steps that use a production connection always ask you while Dev mode is on.">
+ <input
+ type="checkbox"
+ className="accent-amber-400"
+ checked={!!c.production}
+ disabled={markingProduction}
+ onChange={(e) => onProduction(c, e.target.checked)}
+ aria-label={`${c.name} is production`}
+ data-production-toggle={c.id}
+ />
+ Production
+ </label>
+ )}
{canCheck && (
<button type="button" className={quietBtn} disabled={checking} onClick={() => onCheck!(c)} aria-label={`Check ${c.name} now`}>
<RefreshCw size={12} className={checking ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
@@ -530,6 +555,8 @@ export interface ConnectionsViewProps extends ManageLinks {
onBack?: () => void;
/** Inside Settings › This space: the screen has the heading and the scrolling. */
embedded?: boolean;
+ onProduction?: (c: Connection, production: boolean) => void;
+ marking?: string | null;
/** Tests open the Composio form. */
composioOpen?: boolean;
/** Tests and screenshots open the "+ Add connection" list. */
@@ -550,6 +577,8 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
onAddComposio,
onBack,
embedded = false,
+ onProduction,
+ marking = null,
composioOpen = false,
addMenuOpen = false,
...links
@@ -660,7 +689,7 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
{g.items.length > 0 ? (
<ul className="rounded-xl border border-zinc-800 bg-zinc-900/60 divide-y divide-zinc-800">
{g.items.map((c) => (
- <ConnectionRow key={c.id} c={c} now={now} checking={checking === c.id} links={links} onCheck={onCheck} />
+ <ConnectionRow key={c.id} c={c} now={now} checking={checking === c.id} links={links} onCheck={onCheck} onProduction={onProduction} markingProduction={marking === c.id} />
))}
</ul>
) : (
@@ -764,6 +793,24 @@ export const ConnectionsPage: React.FC<ManageLinks & { onBack?: () => void; embe
}
};
+ // Dev mode D10: the open space's production marks. Shown only while Dev mode is on there.
+ const devOn = useDevModeOn();
+ const [marking, setMarking] = useState<string | null>(null);
+ const markProduction = async (c: Connection, production: boolean) => {
+ const space = devStore.current();
+ if (!space || marking) return;
+ setMarking(c.id);
+ setNotice(null);
+ try {
+ await devApi.production(c.id, space, production);
+ if (alive.current) setData((d) => (d ? { ...d, connections: d.connections.map((x) => (x.id === c.id ? { ...x, production } : x)) } : d));
+ } catch (e) {
+ if (alive.current) setNotice({ text: `Couldn’t change ${c.name}: ${e instanceof Error ? e.message : 'something went wrong.'}`, error: true });
+ } finally {
+ if (alive.current) setMarking(null);
+ }
+ };
+
const addComposio = async (url: string, apiKey: string, enabled: boolean): Promise<string | null> => {
try {
await connectionsApi.addComposio(apiKey ? { url, api_key: apiKey, enabled } : { url, enabled });
@@ -790,6 +837,8 @@ export const ConnectionsPage: React.FC<ManageLinks & { onBack?: () => void; embe
onAddComposio={addComposio}
onBack={onBack}
embedded={embedded}
+ onProduction={devOn ? markProduction : undefined}
+ marking={marking}
{...links}
/>
{unlocking && (
diff --git a/frontend/src/components/DevDesk.tsx b/frontend/src/components/DevDesk.tsx
new file mode 100644
index 00000000..3486fc5e
--- /dev/null
+++ b/frontend/src/components/DevDesk.tsx
@@ -0,0 +1,377 @@
+// The Dev desk: a row pinned at the top of the sidebar in a Dev space, and its page with two tabs,
+// What landed and Reviews. The page fetches plan §3.2's routes, updates live on the `dev_card`
+// SSE (App re-sends it as DEV_CARD_EVENT) and mounts Iris's renderers through DevDeskSlots.
+
+import React, { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
+import { ChevronLeft, Code, Loader2, RefreshCw } from 'lucide-react';
+import { devApi, deskStatus } from '../devMode';
+import { FindingAction, LandedPage, ShellCard, asCard, parseCards, parseLandedPage } from '../dev/shellTypes';
+import { LandedList, ReleaseNotesSheet, ReviewCard, Rollup } from './DevDeskSlots';
+import { useDevMode } from './DevModeSwitch';
+
+/** App re-sends the `dev_card` SSE as this window event: detail `{space_id, id, kind, status}`. */
+export const DEV_CARD_EVENT = 'kwant:dev-card';
+export interface DevCardEvent {
+ space_id: string;
+ id: string;
+ kind: string;
+ status: string;
+}
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+
+// ---------------------------------------------------------------------------
+// One shared cache per space: the sidebar row and the page read the same lists.
+
+export interface DeskData {
+ landed: LandedPage | null;
+ reviews: ShellCard[] | null;
+ loading: boolean;
+ error: string | null;
+ /** When the last load succeeded (ms), for the header's "Checked 14:32". */
+ checkedAt: number | null;
+}
+
+const EMPTY: DeskData = { landed: null, reviews: null, loading: false, error: null, checkedAt: null };
+const desks = new Map<string, DeskData>();
+const deskListeners = new Set<() => void>();
+const inflight = new Map<string, Promise<void>>();
+
+function setDesk(space: string, patch: Partial<DeskData>) {
+ desks.set(space, { ...(desks.get(space) ?? EMPTY), ...patch });
+ deskListeners.forEach((l) => l());
+}
+
+export const deskStore = {
+ get: (space: string): DeskData => desks.get(space) ?? EMPTY,
+ subscribe(l: () => void) {
+ deskListeners.add(l);
+ return () => void deskListeners.delete(l);
+ },
+ /** Loads both lists; concurrent calls share one request. */
+ load(space: string): Promise<void> {
+ const running = inflight.get(space);
+ if (running) return running;
+ setDesk(space, { loading: true });
+ const p = Promise.all([devApi.landed(space), devApi.reviews(space)])
+ .then(([l, r]) => setDesk(space, { landed: parseLandedPage(l), reviews: parseCards(r), loading: false, error: null, checkedAt: Date.now() }))
+ .catch((e: unknown) => setDesk(space, { loading: false, error: e instanceof Error ? e.message : 'The Dev desk couldn’t load.' }))
+ .finally(() => inflight.delete(space));
+ inflight.set(space, p);
+ return p;
+ },
+ /** Tests and shots. */
+ _set: setDesk,
+ _reset() {
+ desks.clear();
+ inflight.clear();
+ },
+};
+
+/** "14:32", 24-hour local time. */
+export function checkedLabel(ms: number): string {
+ const d = new Date(ms);
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
+}
+
+export function useDesk(space: string, on: boolean): DeskData {
+ const data = useSyncExternalStore(deskStore.subscribe, () => deskStore.get(space), () => EMPTY);
+ useEffect(() => {
+ if (!on) return undefined;
+ void deskStore.load(space);
+ const onCard = (e: Event) => {
+ const d = (e as CustomEvent<DevCardEvent>).detail;
+ if (d?.space_id === space && d.kind !== 'release_notes') void deskStore.load(space);
+ };
+ window.addEventListener(DEV_CARD_EVENT, onCard);
+ return () => window.removeEventListener(DEV_CARD_EVENT, onCard);
+ }, [space, on]);
+ return data;
+}
+
+export const openReviews = (reviews: ShellCard[] | null) => (reviews ?? []).filter((c) => c.status !== 'stale').length;
+
+// ---------------------------------------------------------------------------
+// The sidebar row
+
+export const DevDeskRow: React.FC<{ spaceId: string; active: boolean; onOpen: () => void; className?: string }> = ({ spaceId, active, onOpen, className }) => {
+ const desk = useDesk(spaceId, true);
+ const landed = desk.landed?.rollup?.count ?? 0;
+ const reviews = openReviews(desk.reviews);
+ const count = landed + reviews;
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ aria-current={active ? 'page' : undefined}
+ data-dev-desk-row
+ className={
+ className ??
+ `w-full flex items-center gap-2.5 rounded-xl px-2.5 py-1.5 text-left ${focusRing} ${active ? 'bg-accent-soft text-zinc-50' : 'text-zinc-300 hover:bg-white/[0.05] hover:text-zinc-50'}`
+ }
+ >
+ <span className="w-7 h-7 shrink-0 rounded-lg bg-accent-soft text-sky-300 flex items-center justify-center" aria-hidden="true">
+ <Code size={14} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-body font-medium truncate">Dev desk</span>
+ <span className="block text-2xs text-zinc-400 truncate" data-dev-desk-status>
+ {desk.landed || desk.reviews ? deskStatus(landed, reviews) : desk.error ? 'Couldn’t load' : 'Loading…'}
+ </span>
+ </span>
+ {count > 0 && (
+ <span className="shrink-0 min-w-[20px] h-5 px-1.5 rounded-full bg-accent-gradient text-2xs font-semibold text-white flex items-center justify-center tabular-nums" aria-label={`${count} new`}>
+ {count}
+ </span>
+ )}
+ </button>
+ );
+};
+
+// ---------------------------------------------------------------------------
+// The page
+
+type Tab = 'landed' | 'reviews';
+
+export interface DevDeskViewProps {
+ spaceId: string;
+ spaceName: string;
+ onBack?: () => void;
+ /** Shown only when Notion is connected (Iris's sheet hides "Save to Notion" otherwise). */
+ onSaveToNotion?: (markdown: string) => Promise<void>;
+ initialTab?: Tab;
+ now?: number;
+}
+
+export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, onBack, onSaveToNotion, initialTab = 'landed', now }) => {
+ const desk = useDesk(spaceId, true);
+ const dev = useDevMode(spaceId);
+ const [tab, setTab] = useState<Tab>(initialTab);
+ const [marking, setMarking] = useState(false);
+ const [notes, setNotes] = useState<ShellCard | null>(null);
+ const [notesError, setNotesError] = useState<string | null>(null);
+ const [actionError, setActionError] = useState<string | null>(null);
+ const tabsId = useId();
+ const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
+ const notesId = notes?.id ?? null;
+
+ // The release-notes draft: 202 gives the pending card; its ready card comes after the SSE.
+ useEffect(() => {
+ if (!notesId) return undefined;
+ const onCard = (e: Event) => {
+ const d = (e as CustomEvent<DevCardEvent>).detail;
+ if (!d || d.id !== notesId || d.status === 'pending') return;
+ devApi.card(notesId).then(
+ (raw) => {
+ const c = asCard(raw);
+ if (c) setNotes(c);
+ else setNotesError('The draft came back in a shape this app doesn’t know.');
+ },
+ (err: unknown) =>
+ setNotesError(
+ err && typeof err === 'object' && 'status' in err && ((err as { status: number }).status === 404 || (err as { status: number }).status === 405)
+ ? 'The draft is ready, but this server can’t send it to the app yet. Update the server.'
+ : err instanceof Error
+ ? err.message
+ : 'The draft couldn’t load.',
+ ),
+ );
+ };
+ window.addEventListener(DEV_CARD_EVENT, onCard);
+ return () => window.removeEventListener(DEV_CARD_EVENT, onCard);
+ }, [notesId]);
+
+ const markSeen = useCallback(() => {
+ if (marking) return;
+ setMarking(true);
+ setActionError(null);
+ devApi
+ .seen(spaceId)
+ .then(() => deskStore.load(spaceId))
+ .catch((e: unknown) => setActionError(e instanceof Error ? e.message : 'Couldn’t mark them seen.'))
+ .finally(() => setMarking(false));
+ }, [spaceId, marking]);
+
+ const draftNotes = useCallback(() => {
+ setActionError(null);
+ setNotesError(null);
+ devApi.releaseNotes(spaceId).then(
+ (raw) => {
+ const c = asCard(raw);
+ if (c) setNotes(c);
+ else setActionError('The draft came back in a shape this app doesn’t know.');
+ },
+ (e: unknown) => setActionError(e instanceof Error ? e.message : 'Couldn’t start the draft.'),
+ );
+ }, [spaceId]);
+
+ const onFinding = useCallback(
+ async (cardId: string, findingId: string, action: FindingAction): Promise<ShellCard> => {
+ const card = asCard(await devApi.finding(cardId, findingId, action));
+ if (!card) throw new Error('The review came back in a shape this app doesn’t know.');
+ const reviews = deskStore.get(spaceId).reviews ?? [];
+ deskStore._set(spaceId, { reviews: reviews.map((c) => (c.id === card.id ? card : c)) });
+ return card;
+ },
+ [spaceId],
+ );
+
+ const landed = desk.landed;
+ const reviews = desk.reviews ?? [];
+ const landedCards = (landed?.cards ?? []).filter((c) => c.kind === 'landed');
+ const newest = landedCards[0];
+ const lastMerge = newest && typeof newest.pr === 'number' ? { pr: newest.pr, merged_at: newest.merged_at ?? null } : null;
+ const unseen = landed?.rollup?.count ?? 0;
+ const open = openReviews(desk.reviews);
+ const first = !landed && !desk.reviews;
+
+ const tabs: Array<{ key: Tab; label: string; count: number }> = [
+ { key: 'landed', label: 'What landed', count: unseen },
+ { key: 'reviews', label: 'Reviews', count: open },
+ ];
+ const onTabKey = (e: React.KeyboardEvent, i: number) => {
+ const n = e.key === 'ArrowRight' ? i + 1 : e.key === 'ArrowLeft' ? i - 1 : e.key === 'Home' ? 0 : e.key === 'End' ? tabs.length - 1 : null;
+ if (n === null) return;
+ e.preventDefault();
+ const k = (n + tabs.length) % tabs.length;
+ setTab(tabs[k].key);
+ tabRefs.current[k]?.focus();
+ };
+
+ return (
+ <div className="flex-1 flex flex-col h-full overflow-hidden" data-dev-desk>
+ <div className={`h-14 shrink-0 border-b border-zinc-800/80 ${onBack ? 'px-2' : 'px-4'} sm:px-6 flex items-center justify-between gap-3 bg-zinc-900/30 backdrop-blur-sm select-none`}>
+ {onBack && (
+ <button type="button" onClick={onBack} aria-label="Back to chats" className={`shrink-0 p-2 -ml-0.5 -mr-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 ${focusRing}`}>
+ <ChevronLeft size={18} />
+ </button>
+ )}
+ <div className="min-w-0 flex-1">
+ <h2 className="text-sm font-semibold text-zinc-100 truncate">Dev desk</h2>
+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">What landed in {spaceName}, and the open pull requests</p>
+ </div>
+ {dev?.repo && (
+ <span className="hidden sm:inline-flex shrink-0 font-mono text-[11px] text-zinc-300 px-2 py-0.5 rounded-md bg-white/[0.04] border border-zinc-700/60" data-dev-repo-chip>
+ {dev.repo} · {dev.branch || 'main'}
+ </span>
+ )}
+ {desk.checkedAt != null && (
+ <span className="shrink-0 text-[11px] text-zinc-500 tabular-nums" data-dev-checked>
+ Checked {checkedLabel(desk.checkedAt)}
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={() => void deskStore.load(spaceId)}
+ disabled={desk.loading}
+ aria-label="Refresh"
+ className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs text-zinc-300 border border-zinc-700/60 hover:bg-zinc-800 disabled:opacity-60 ${focusRing}`}
+ >
+ <RefreshCw size={12} className={desk.loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
+ <span className="hidden sm:inline">Refresh</span>
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 sm:p-6" aria-busy={desk.loading}>
+ <div className="max-w-[760px] mx-auto space-y-4">
+ <div role="tablist" aria-label="Dev desk" className="flex gap-1">
+ {tabs.map((t, i) => {
+ const on = t.key === tab;
+ return (
+ <button
+ key={t.key}
+ ref={(el) => (tabRefs.current[i] = el)}
+ type="button"
+ role="tab"
+ id={`${tabsId}-${t.key}`}
+ aria-selected={on}
+ aria-controls={`${tabsId}-panel`}
+ tabIndex={on ? 0 : -1}
+ onKeyDown={(e) => onTabKey(e, i)}
+ onClick={() => setTab(t.key)}
+ data-dev-tab={t.key}
+ className={`inline-flex items-center gap-1.5 min-h-[44px] sm:min-h-[36px] px-3 rounded-lg text-xs font-medium ${focusRing} ${
+ on ? 'bg-zinc-800 text-zinc-100 border border-zinc-700' : 'text-zinc-400 border border-transparent hover:text-zinc-200'
+ }`}
+ >
+ {t.label}
+ {t.count > 0 && <span className="min-w-[18px] h-[18px] px-1 rounded-full bg-zinc-700 text-2xs text-zinc-100 flex items-center justify-center tabular-nums">{t.count}</span>}
+ </button>
+ );
+ })}
+ </div>
+
+ {(desk.error || actionError) && (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-400/30 bg-rose-500/10 flex flex-wrap items-center gap-2 text-xs text-rose-100">
+ <span className="min-w-0 flex-1">{actionError ?? desk.error}</span>
+ {desk.error && !actionError && (
+ <button type="button" onClick={() => void deskStore.load(spaceId)} className={`px-2 py-0.5 rounded border border-rose-400/40 hover:bg-rose-500/10 min-h-[32px] ${focusRing}`}>
+ Try again
+ </button>
+ )}
+ </div>
+ )}
+
+ <div role="tabpanel" id={`${tabsId}-panel`} aria-labelledby={`${tabsId}-${tab}`} className="space-y-3">
+ {first && desk.loading ? (
+ <p className="flex items-center gap-2 py-8 justify-center text-meta text-zinc-400" data-dev-loading>
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ Loading the Dev desk…
+ </p>
+ ) : tab === 'landed' ? (
+ <>
+ {landed?.rollup && (
+ <Rollup
+ rollup={landed.rollup}
+ last_tag={landed.last_tag}
+ last_merge={lastMerge}
+ onMarkSeen={markSeen}
+ onDraftNotes={draftNotes}
+ drafting={!!notes && notes.status === 'pending'}
+ />
+ )}
+ {landedCards.length ? (
+ <LandedList cards={landedCards} reviews={reviews} now={now} />
+ ) : (
+ landed && (
+ <Empty title="Nothing has landed yet" line="Each merge to main shows up here as a short card in plain words. kwant checks every 5 minutes." />
+ )
+ )}
+ </>
+ ) : reviews.length ? (
+ reviews.map((c) => <ReviewCard key={c.id} card={c} onFinding={onFinding} now={now} />)
+ ) : (
+ desk.reviews && <Empty title="No open pull requests" line="Each open PR gets a review here from a bot that didn’t write it." />
+ )}
+ </div>
+ </div>
+ </div>
+
+ {notes && (
+ <>
+ <ReleaseNotesSheet
+ card={notes}
+ onSaveToNotion={onSaveToNotion}
+ onClose={() => setNotes(null)}
+ onDiscard={() => {
+ setNotes(null);
+ setNotesError(null);
+ }}
+ />
+ {notesError && (
+ <p role="alert" className="fixed left-1/2 -translate-x-1/2 bottom-6 z-[60] max-w-[90vw] rounded-lg border border-amber-400/30 bg-surface-overlay px-3 py-2 text-meta text-amber-100">
+ {notesError}
+ </p>
+ )}
+ </>
+ )}
+ </div>
+ );
+};
+
+const Empty: React.FC<{ title: string; line: string }> = ({ title, line }) => (
+ <div className="rounded-2xl border border-dashed border-hairline-strong px-5 py-8 text-center" data-dev-empty>
+ <p className="text-body font-medium text-zinc-200">{title}</p>
+ <p className="mt-1 text-meta text-zinc-400">{line}</p>
+ </div>
+);
diff --git a/frontend/src/components/DevDeskSlots.tsx b/frontend/src/components/DevDeskSlots.tsx
new file mode 100644
index 00000000..133ad5f7
--- /dev/null
+++ b/frontend/src/components/DevDeskSlots.tsx
@@ -0,0 +1,121 @@
+// Where the Dev desk mounts Iris's renderers (components/dev/{Rollup,LandedList,ReviewCard,ReleaseNotesSheet}).
+// Until hers land on main these are thin placeholders with the props in iris-dev-cards `dev/types.ts`
+// (11c6d23), so the shell, its fetching and its live updates can be built and tested now. Swapping
+// them is this one file: import hers and parse each card with her parse* first.
+
+import React from 'react';
+import { GitMerge, GitPullRequest, Loader2, X } from 'lucide-react';
+import type { FindingAction, LandedRollup, ShellCard } from '../dev/shellTypes';
+import { withDayLabels } from '../devMode';
+
+export interface RollupProps {
+ rollup: LandedRollup;
+ last_tag: string | null;
+ last_merge: { pr: number; merged_at: string | null } | null;
+ onDraftNotes: () => void;
+ onMarkSeen: () => void;
+ drafting?: boolean;
+}
+
+export interface LandedListProps {
+ cards: ShellCard[];
+ reviews: ShellCard[];
+ now?: number;
+}
+
+export interface ReviewCardProps {
+ card: ShellCard;
+ onFinding: (cardId: string, findingId: string, action: FindingAction) => Promise<ShellCard>;
+ sample?: boolean;
+ now?: number;
+}
+
+export interface ReleaseNotesSheetProps {
+ card: ShellCard;
+ onSaveToNotion?: (markdown: string) => Promise<void>;
+ onDiscard: () => void;
+ onClose: () => void;
+}
+
+const cardBox = 'rounded-2xl border border-hairline bg-surface-raised px-4 py-3';
+const ghost =
+ 'inline-flex items-center gap-1.5 rounded-xl border border-hairline-strong px-3 py-1.5 text-meta font-medium text-zinc-200 hover:bg-zinc-800 disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+
+const text = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v : null);
+
+export const Rollup: React.FC<RollupProps> = ({ rollup, last_tag, last_merge, onMarkSeen, onDraftNotes, drafting }) => (
+ <section className={cardBox} data-dev-slot="rollup" aria-label="Since you last looked">
+ <p className="text-body font-semibold text-zinc-50">
+ {rollup.count ? `${rollup.count} landed since you last looked` : 'Nothing new since you last looked'}
+ </p>
+ <p className="mt-0.5 text-meta text-zinc-400">
+ {rollup.areas.length ? rollup.areas.map((a) => `${a.area} ${a.count}`).join(' · ') : last_merge ? `Last merge: #${last_merge.pr}` : 'No merges yet.'}
+ </p>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <button type="button" className={ghost} onClick={onMarkSeen} disabled={!rollup.count}>
+ Mark all seen
+ </button>
+ <button type="button" className={ghost} onClick={onDraftNotes} disabled={drafting}>
+ {drafting && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ Draft release notes{last_tag ? ` since ${last_tag}` : ''}
+ </button>
+ </div>
+ </section>
+);
+
+export const LandedList: React.FC<LandedListProps> = ({ cards, now }) => (
+ <div className="flex flex-col gap-2" data-dev-slot="landed-list">
+ {withDayLabels(cards, now === undefined ? new Date() : new Date(now)).map(({ card, dayLabel }) => (
+ <React.Fragment key={card.id}>
+ {dayLabel && <h3 className="pt-2 text-2xs font-semibold uppercase tracking-wider text-zinc-500">{dayLabel}</h3>}
+ <article className={cardBox} data-dev-slot="landed" data-status={card.status}>
+ <p className="flex items-start gap-2 text-body font-medium text-zinc-100">
+ <GitMerge size={14} className="mt-0.5 shrink-0 text-sky-300" aria-hidden="true" />
+ <span className="min-w-0 break-words">{text(card.headline) ?? text(card.title) ?? `Merge ${card.id}`}</span>
+ </p>
+ <p className="mt-1 text-meta text-zinc-400">
+ {[card.pr ? `#${card.pr}` : null, text(card.area), card.status !== 'ready' ? card.status : null].filter(Boolean).join(' · ')}
+ </p>
+ </article>
+ </React.Fragment>
+ ))}
+ </div>
+);
+
+export const ReviewCard: React.FC<ReviewCardProps> = ({ card }) => (
+ <article className={cardBox} data-dev-slot="review" data-status={card.status}>
+ <p className="flex items-start gap-2 text-body font-medium text-zinc-100">
+ <GitPullRequest size={14} className="mt-0.5 shrink-0 text-sky-300" aria-hidden="true" />
+ <span className="min-w-0 break-words">
+ {card.pr ? `#${card.pr} ` : ''}
+ {text(card.title) ?? 'Pull request'}
+ </span>
+ </p>
+ <p className="mt-1 text-meta text-zinc-400">{card.status === 'pending' ? 'Reviewing…' : card.status}</p>
+ </article>
+);
+
+export const ReleaseNotesSheet: React.FC<ReleaseNotesSheetProps> = ({ card, onClose, onDiscard }) => (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" data-dev-slot="release-notes">
+ <div role="dialog" aria-modal="true" aria-label="Release notes draft" className="w-full max-w-[540px] rounded-3xl border border-hairline-strong bg-surface-raised p-6">
+ <div className="flex items-start justify-between gap-3">
+ <h2 className="text-lg font-semibold text-zinc-50">Release notes draft</h2>
+ <button type="button" onClick={onClose} aria-label="Close" className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100">
+ <X size={16} aria-hidden="true" />
+ </button>
+ </div>
+ {card.status === 'pending' ? (
+ <p className="mt-3 flex items-center gap-2 text-meta text-zinc-400">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Writing the draft…
+ </p>
+ ) : (
+ <pre className="mt-3 max-h-[50vh] overflow-auto whitespace-pre-wrap text-meta text-zinc-300">{text(card.markdown) ?? ''}</pre>
+ )}
+ <div className="mt-4 flex justify-end gap-2">
+ <button type="button" className={ghost} onClick={onDiscard}>
+ Discard
+ </button>
+ </div>
+ </div>
+ </div>
+);
diff --git a/frontend/src/components/DevModeSettings.tsx b/frontend/src/components/DevModeSettings.tsx
new file mode 100644
index 00000000..f972a1ac
--- /dev/null
+++ b/frontend/src/components/DevModeSettings.tsx
@@ -0,0 +1,134 @@
+// Settings › This space › Dev mode: the repo, the branch to watch, the optional backup command
+// (plan D9) and Turn off. Off keeps the settings and What landed's history.
+
+import React, { useEffect, useState } from 'react';
+import { Check, Code } from 'lucide-react';
+import { DevModeState, approvalsWord, devApi, devStore, normaliseRepo } from '../devMode';
+import { useDevMode } from './DevModeSwitch';
+
+const card = 'rounded-xl border border-zinc-800 bg-zinc-950/60';
+const rowBtn =
+ 'flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-300 border border-zinc-700/60 bg-zinc-800/60 hover:bg-zinc-700/70 hover:text-zinc-100 transition-colors disabled:opacity-50';
+const primaryBtn = 'flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50';
+const input = 'w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm font-mono text-zinc-100 focus:outline-none border-zinc-800 focus:border-sky-500';
+
+export const DevModeSettings: React.FC<{ spaceId: string; spaceName: string; approvals?: string; save?: typeof devApi.put }> = ({ spaceId, spaceName, approvals, save = devApi.put }) => {
+ const state = useDevMode(spaceId);
+ const [repo, setRepo] = useState('');
+ const [branch, setBranch] = useState('');
+ const [backup, setBackup] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [saved, setSaved] = useState(false);
+
+ useEffect(() => {
+ if (!state) devApi.get(spaceId).then((s) => devStore.set(spaceId, s), (e: unknown) => setError(e instanceof Error ? e.message : 'Dev mode couldn’t load.'));
+ }, [spaceId, state]);
+ useEffect(() => {
+ setRepo(state?.repo ?? '');
+ setBranch(state?.branch ?? '');
+ setBackup(state?.backup_command ?? '');
+ }, [state?.repo, state?.branch, state?.backup_command]);
+
+ if (!state) return null;
+ // Before the first switch-on there's nothing to set: the switch in the header opens the setup.
+ if (!state.on && !state.last_seen_sha && !state.polled_at) return null;
+
+ const normal = repo.trim() ? normaliseRepo(repo) : null;
+ const repoErr = repo.trim() && !normal ? 'Paste a GitHub repo, like owner/name or its URL.' : null;
+ const dirty = (normal ?? '') !== (state.repo ?? '') || branch.trim() !== (state.branch ?? '') || backup.trim() !== (state.backup_command ?? '');
+
+ const put = (body: Partial<Pick<DevModeState, 'repo' | 'branch' | 'backup_command'>> & { on: boolean }) => {
+ setBusy(true);
+ setError(null);
+ setSaved(false);
+ save(spaceId, body).then(
+ (s) => {
+ devStore.set(spaceId, s);
+ setSaved(true);
+ setBusy(false);
+ },
+ (e: unknown) => {
+ setError(e instanceof Error ? e.message : 'Couldn’t save Dev mode.');
+ setBusy(false);
+ },
+ );
+ };
+
+ return (
+ <form
+ className={`${card} p-4 space-y-3`}
+ data-dev-settings
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (!dirty || repoErr || busy) return;
+ put({ on: state.on, repo: normal, branch: branch.trim() || null, backup_command: backup.trim() });
+ }}
+ >
+ <p className="flex items-center gap-2 text-xs font-medium text-zinc-200">
+ <Code size={14} className="text-zinc-400" aria-hidden="true" /> Dev mode
+ <span className={`ml-auto kw-chip ${state.on ? 'kw-chip-accent' : ''}`}>{state.on ? 'On' : 'Off'}</span>
+ </p>
+ <p className="text-[11px] text-zinc-500">
+ {state.on
+ ? `${spaceName} reads this repo to show what landed, review PRs and guard deploys. Only you can change it.`
+ : `Off. Reviews, the ship gate and the production floor are stopped; approvals stay on ${approvalsWord(approvals)}. Turn it on with the switch next to the space’s name.`}
+ </p>
+ <div>
+ <label htmlFor="dv-set-repo" className="block text-xs font-medium text-zinc-300 mb-1">
+ Repository
+ </label>
+ <input id="dv-set-repo" value={repo} onChange={(e) => setRepo(e.target.value)} placeholder="owner/repo" spellCheck={false} autoCapitalize="off" className={input} aria-invalid={!!repoErr} aria-describedby="dv-set-repo-err" />
+ <p id="dv-set-repo-err" className="mt-1 text-[11px] text-rose-300 min-h-[1em]">
+ {repoErr}
+ </p>
+ </div>
+ <div>
+ <label htmlFor="dv-set-branch" className="block text-xs font-medium text-zinc-300 mb-1">
+ Branch to watch
+ </label>
+ <input id="dv-set-branch" value={branch} onChange={(e) => setBranch(e.target.value)} placeholder="main" spellCheck={false} autoCapitalize="off" className={input} />
+ </div>
+ <div>
+ <label htmlFor="dv-set-backup" className="block text-xs font-medium text-zinc-300 mb-1">
+ Backup command <span className="text-zinc-500 font-normal">(optional)</span>
+ </label>
+ <input
+ id="dv-set-backup"
+ value={backup}
+ maxLength={2000}
+ onChange={(e) => setBackup(e.target.value)}
+ placeholder="./scripts/backup.sh"
+ spellCheck={false}
+ autoCapitalize="off"
+ className={input}
+ aria-describedby="dv-set-backup-help"
+ />
+ <p id="dv-set-backup-help" className="mt-1 text-[11px] text-zinc-500">
+ Runs in the bot’s folder when you press Back up first on a production step. It should print the backup file’s path.
+ </p>
+ </div>
+ {error && (
+ <p role="alert" className="text-[11px] text-rose-300">
+ {error}
+ </p>
+ )}
+ <div className="flex items-center gap-2">
+ {state.on && (
+ <button type="button" className={rowBtn} disabled={busy} onClick={() => put({ on: false })} data-dev-turn-off>
+ Turn off Dev mode
+ </button>
+ )}
+ <span className="flex-1" />
+ {saved && !dirty && (
+ <span className="flex items-center gap-1 text-xs text-emerald-400" role="status">
+ <Check size={13} aria-hidden="true" /> Saved
+ </span>
+ )}
+ <button type="submit" disabled={!dirty || !!repoErr || busy} className={primaryBtn}>
+ {busy ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </form>
+ );
+};
diff --git a/frontend/src/components/DevModeSetup.tsx b/frontend/src/components/DevModeSetup.tsx
new file mode 100644
index 00000000..9991a600
--- /dev/null
+++ b/frontend/src/components/DevModeSetup.tsx
@@ -0,0 +1,251 @@
+// First switch-on: which repo is this space about? (design §3). The Repository field checks the
+// repo 400 ms after typing stops; Turn on Dev mode stays disabled until the check says Found.
+// The design's fourth row, "Ready to ship", is out of 0.7 (plan D-cut), so three rows show.
+
+import React, { useEffect, useMemo, useRef, useState } from 'react';
+import { Eye, GitMerge, Loader2, Lock, ShieldAlert } from 'lucide-react';
+import { CheckerUpdate, DevModeState, FieldState, createRepoChecker, deployLabel, devApi, fieldView, normaliseRepo, RepoCheck } from '../devMode';
+
+export interface DevModeSetupProps {
+ space: { id: string; name: string };
+ initial?: DevModeState | null;
+ onCancel: () => void;
+ onDone: (s: DevModeState) => void;
+ /** Opens Connections (Connect GitHub, Mark production keys). Hidden when not given. */
+ onOpenConnections?: () => void;
+ /** Test hooks. */
+ check?: (repo: string) => Promise<RepoCheck>;
+ save?: (body: { on: boolean; repo: string; branch: string | null }) => Promise<DevModeState>;
+ productionCount?: number;
+}
+
+const ROWS = [
+ { icon: GitMerge, title: 'What landed', line: 'Each merge to main becomes a short card in plain words. Checked every 5 minutes.' },
+ { icon: Eye, title: 'Second pair of eyes', line: 'Each open PR is reviewed by a bot that didn’t write it, on a different engine.' },
+ { icon: ShieldAlert, title: 'Production floor', line: 'Deploys, pushes to main and destructive commands always ask you, even with approvals off.' },
+];
+
+const chipTone: Record<string, string> = { ok: 'kw-chip-ok', warn: 'kw-chip-warn', bad: 'kw-chip-bad', info: 'kw-chip-info' };
+
+export const DevModeSetup: React.FC<DevModeSetupProps> = ({ space, initial, onCancel, onDone, onOpenConnections, check, save, productionCount = 0 }) => {
+ const [raw, setRaw] = useState(initial?.repo ?? '');
+ const [field, setField] = useState<CheckerUpdate>({ state: initial?.repo ? 'checking' : 'empty', check: null, error: null });
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState<string | null>(null);
+ const primary = useRef<HTMLButtonElement>(null);
+ const dialog = useRef<HTMLDivElement>(null);
+
+ const checker = useMemo(() => createRepoChecker(check ?? ((r) => devApi.check(space.id, r)), setField), [check, space.id]);
+ useEffect(() => {
+ if (initial?.repo) checker.input(initial.repo);
+ return () => checker.cancel();
+ // Only the pre-filled repo is checked on open; typing calls checker.input.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [checker]);
+
+ // Focus starts on the primary button (design §3), even while it's disabled for the check: then the field.
+ useEffect(() => {
+ const b = primary.current;
+ if (b && !b.disabled) b.focus();
+ else dialog.current?.querySelector<HTMLInputElement>('input')?.focus();
+ }, []);
+ // The pre-filled repo's check comes back Found: focus moves to the primary button, unless the person typed.
+ const typed = useRef(false);
+ useEffect(() => {
+ if (field.state === 'found' && !typed.current && dialog.current?.contains(document.activeElement)) primary.current?.focus();
+ }, [field.state]);
+
+ const repo = normaliseRepo(raw);
+ const view = fieldView(field.state as FieldState, repo, field.error);
+ const found = field.state === 'found' ? field.check : null;
+ const deploy = deployLabel(found?.deploy_hint ?? null);
+ const canTurnOn = view.canTurnOn && !saving;
+
+ const turnOn = () => {
+ if (!canTurnOn || !repo) return;
+ setSaving(true);
+ setSaveError(null);
+ (save ?? ((b) => devApi.put(space.id, b)))({ on: true, repo: found?.repo ?? repo, branch: found?.branch ?? null }).then(onDone, (e: unknown) => {
+ setSaving(false);
+ setSaveError(e instanceof Error ? e.message : 'Dev mode couldn’t be turned on.');
+ });
+ };
+
+ const onKey = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ onCancel();
+ return;
+ }
+ if (e.key !== 'Tab' || !dialog.current) return;
+ const items = Array.from(dialog.current.querySelectorAll<HTMLElement>('button:not([disabled]),input'));
+ if (!items.length) return;
+ const first = items[0];
+ const last = items[items.length - 1];
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && document.activeElement === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+
+ const help = view.helpRepo && view.help ? view.help.split('{repo}') : null;
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/70 backdrop-blur-[4px] p-0 sm:p-4" data-dev-setup onMouseDown={(e) => e.target === e.currentTarget && onCancel()}>
+ <div
+ ref={dialog}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="dv-setup-title"
+ onKeyDown={onKey}
+ className="kw-dv-sheet w-full sm:w-[540px] max-h-[92dvh] overflow-y-auto rounded-t-3xl sm:rounded-3xl border border-white/14 bg-surface-raised px-6 pt-6 flex flex-col gap-[18px] text-left"
+ >
+ <header>
+ <h2 id="dv-setup-title" className="text-lg font-semibold text-zinc-50">
+ Which repo is this space about?
+ </h2>
+ <p className="mt-1 text-body text-zinc-400">
+ Dev mode for <strong className="font-semibold text-zinc-100">{space.name}</strong> reads this repo to show what landed, review PRs and guard deploys.
+ </p>
+ </header>
+
+ <div>
+ <label htmlFor="dv-repo" className="text-meta font-medium text-zinc-300">
+ Repository
+ </label>
+ <div className="mt-1.5 flex items-center gap-2 rounded-xl border border-hairline-strong bg-surface-main px-3 h-10 focus-within:border-sky-400/70">
+ <span className="font-mono text-[13px] text-zinc-500 shrink-0" aria-hidden="true">
+ github.com/
+ </span>
+ <input
+ id="dv-repo"
+ value={raw}
+ onChange={(e) => {
+ typed.current = true;
+ setRaw(e.target.value);
+ setSaveError(null);
+ checker.input(e.target.value);
+ }}
+ placeholder="owner/repo"
+ spellCheck={false}
+ autoCapitalize="off"
+ autoComplete="off"
+ aria-describedby="dv-repo-help"
+ aria-invalid={field.state === 'invalid' || field.state === 'not_found' || undefined}
+ className="min-w-0 flex-1 bg-transparent font-mono text-[13px] text-zinc-100 placeholder:text-zinc-600 outline-none"
+ />
+ {view.chip && (
+ <span className={`kw-chip ${chipTone[view.chip.tone]} shrink-0`} data-dv-chip={field.state}>
+ {view.chip.spinner && <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {view.chip.text}
+ </span>
+ )}
+ </div>
+ <p id="dv-repo-help" className="mt-1.5 text-meta text-zinc-400 min-h-[18px]" aria-live="polite">
+ {help ? (
+ <>
+ {help[0]}
+ <strong className="font-semibold text-zinc-200">{view.helpRepo}</strong>
+ {help[1]}
+ </>
+ ) : (
+ view.help
+ )}
+ {view.connect && onOpenConnections && (
+ <button type="button" onClick={onOpenConnections} className="ml-2 font-medium text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
+ Connect GitHub
+ </button>
+ )}
+ </p>
+ </div>
+
+ {found && (
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2" data-dv-tiles>
+ <Tile label="Branch to watch">
+ <span className="font-mono text-sky-300">{found.branch ?? 'main'}</span>
+ </Tile>
+ <Tile label="Deploy target">
+ {deploy ? (
+ <>
+ {deploy.name} <span className="text-zinc-500">({deploy.detail})</span>
+ </>
+ ) : (
+ <span className="text-zinc-500">None found</span>
+ )}
+ </Tile>
+ <Tile label="Production keys">
+ <span className={productionCount ? '' : 'text-zinc-500'}>{productionCount ? `${productionCount} marked` : 'None marked'}</span>
+ {onOpenConnections && (
+ <button type="button" onClick={onOpenConnections} className="ml-1.5 text-meta font-medium text-sky-300 hover:text-sky-200">
+ Mark
+ </button>
+ )}
+ </Tile>
+ </div>
+ )}
+
+ <section aria-labelledby="dv-turns-on">
+ <h3 id="dv-turns-on" className="text-2xs font-semibold uppercase tracking-wider text-zinc-500">
+ What turns on
+ </h3>
+ <ul className="mt-2 flex flex-col gap-3">
+ {ROWS.map(({ icon: Icon, title, line }) => (
+ <li key={title} className="flex items-start gap-3">
+ <span className="w-7 h-7 shrink-0 rounded-lg bg-accent-soft text-sky-300 flex items-center justify-center" aria-hidden="true">
+ <Icon size={14} />
+ </span>
+ <span className="min-w-0">
+ <span className="block text-[13px] font-semibold text-zinc-100">{title}</span>
+ <span className="block text-meta text-zinc-400">{line}</span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+
+ {saveError && (
+ <p role="alert" className="text-meta text-bad">
+ {saveError}
+ </p>
+ )}
+
+ <footer className="sticky bottom-0 -mx-6 px-6 bg-[#120e26] border-t border-white/[0.07] pt-3 pb-[max(16px,env(safe-area-inset-bottom))] flex flex-col sm:flex-row sm:items-center gap-3" data-dv-setup-footer>
+ <p className="flex-1 flex items-start gap-1.5 text-meta text-zinc-500">
+ <Lock size={12} className="mt-0.5 shrink-0" aria-hidden="true" />
+ Only you can turn this on or off. Nothing is posted to GitHub.
+ </p>
+ <div className="flex gap-2 justify-end">
+ <button
+ type="button"
+ onClick={onCancel}
+ className="rounded-xl border border-hairline-strong px-3.5 min-h-[44px] sm:min-h-[36px] text-meta font-medium text-zinc-200 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400"
+ >
+ Cancel
+ </button>
+ <button
+ ref={primary}
+ type="button"
+ onClick={turnOn}
+ disabled={!canTurnOn}
+ data-dv-turn-on
+ className="inline-flex items-center gap-1.5 rounded-xl bg-accent-gradient px-3.5 min-h-[44px] sm:min-h-[36px] text-meta font-semibold text-white disabled:opacity-45 disabled:cursor-not-allowed focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400"
+ >
+ {saving && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ Turn on Dev mode
+ </button>
+ </div>
+ </footer>
+ </div>
+ </div>
+ );
+};
+
+const Tile: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
+ <div className="rounded-xl border border-hairline bg-surface-main px-3 py-2">
+ <p className="text-2xs font-semibold uppercase tracking-wider text-zinc-500">{label}</p>
+ <p className="mt-0.5 text-meta text-zinc-200 truncate">{children}</p>
+ </div>
+);
diff --git a/frontend/src/components/DevModeSwitch.tsx b/frontend/src/components/DevModeSwitch.tsx
new file mode 100644
index 00000000..473a2674
--- /dev/null
+++ b/frontend/src/components/DevModeSwitch.tsx
@@ -0,0 +1,294 @@
+// The Dev mode switch in the sidebar space header: a safety cover over a launch switch (design §1).
+// Press 1 lifts the cover, press 2 flips (or opens the setup sheet the first time). A lifted cover
+// drops back after 5 s, on Esc or when focus leaves. Presses are ignored while a flip settles.
+// It's a <button>, not role="switch": a switch promises one press.
+
+import React, { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { Code, Lock, LockOpen, X } from 'lucide-react';
+import {
+ DROP_MS,
+ RECOVER_MS,
+ SwitchAction,
+ SwitchState,
+ approvalsWord,
+ devApi,
+ devStore,
+ DevModeError,
+ DevModeState,
+ initialSwitch,
+ needsSetup,
+ switchLook,
+ switchReducer,
+} from '../devMode';
+import { DevModeSetup } from './DevModeSetup';
+
+export function useReducedMotion(): boolean {
+ const query = typeof window !== 'undefined' && typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
+ const [reduced, setReduced] = useState(() => !!query?.matches);
+ useEffect(() => {
+ if (!query) return;
+ const on = () => setReduced(query.matches);
+ query.addEventListener?.('change', on);
+ return () => query.removeEventListener?.('change', on);
+ }, [query]);
+ return reduced;
+}
+
+/** Whether Dev mode is on in a space (the open one when no id is given), live. */
+export function useDevModeOn(space?: string | null): boolean {
+ return useSyncExternalStore(
+ devStore.subscribe,
+ () => devStore.isOn(space === undefined ? devStore.current() : space),
+ () => false,
+ );
+}
+
+export function useDevMode(space: string | null | undefined): DevModeState | null {
+ return useSyncExternalStore(devStore.subscribe, () => devStore.get(space), () => null);
+}
+
+export interface DevModeSwitchProps {
+ space: { id: string; name: string; approvals?: string };
+ phone?: boolean;
+ /** Dev mode went off: the sidebar shows the turned-off note. */
+ onTurnedOff?: () => void;
+ /** Test hooks: start in a given state, and a clock. */
+ initial?: Partial<SwitchState>;
+ now?: () => number;
+}
+
+export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = false, onTurnedOff, initial, now = Date.now }) => {
+ const reduced = useReducedMotion();
+ const known = useDevMode(space.id);
+ const [state, setState] = useState<SwitchState>(() =>
+ initialSwitch({ reduced, ...(known ? { on: known.on, setup: needsSetup(known) } : {}), ...initial }),
+ );
+ // 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 dispatch = useCallback(
+ (a: SwitchAction): SwitchState => {
+ const next = switchReducer(ref.current, a, space.name);
+ ref.current = next;
+ setState(next);
+ return next;
+ },
+ [space.name],
+ );
+
+ useEffect(() => void dispatch({ type: 'reduced', reduced }), [reduced, dispatch]);
+
+ // Load this space's state; a 403 is a bot or not the owner: the switch shows disabled.
+ useEffect(() => {
+ let live = true;
+ devApi.get(space.id).then(
+ (s) => {
+ if (!live) return;
+ devStore.set(space.id, s);
+ },
+ (e: unknown) => {
+ if (!live) return;
+ dispatch({ type: 'server', state: null, disabled: e instanceof DevModeError && (e.status === 403 || e.status === 404) });
+ },
+ );
+ return () => {
+ live = false;
+ };
+ }, [space.id, dispatch]);
+
+ // The store changes (the load above, SSE, Settings): follow it.
+ useEffect(() => {
+ if (known) dispatch({ type: 'server', state: known });
+ }, [known, dispatch]);
+
+ // A lifted cover drops back after 5 s; a flip settles at 450 ms.
+ useEffect(() => {
+ if (state.phase === 'lifted' && state.liftedAt !== null) {
+ const t = setTimeout(() => dispatch({ type: 'recover', now: now() }), Math.max(0, state.liftedAt + RECOVER_MS - now()));
+ return () => clearTimeout(t);
+ }
+ if (state.phase === 'settling') {
+ const t = setTimeout(() => dispatch({ type: 'settled', now: now() }), Math.max(0, state.settleUntil - now()));
+ return () => clearTimeout(t);
+ }
+ return undefined;
+ }, [state.phase, state.liftedAt, state.settleUntil, dispatch, now]);
+
+ const save = useCallback(
+ (on: boolean) => {
+ const was = devStore.get(space.id);
+ devApi.put(space.id, { on }).then(
+ (s) => {
+ devStore.set(space.id, s);
+ dispatch({ type: 'saved', on: s.on });
+ if (!s.on && was?.on) onTurnedOff?.();
+ },
+ (e: unknown) => dispatch({ type: 'save_failed', error: e instanceof Error ? e.message : 'Dev mode couldn’t be changed.' }),
+ );
+ },
+ [space.id, dispatch, onTurnedOff],
+ );
+
+ const press = () => {
+ const before = ref.current;
+ const next = dispatch({ type: 'press', now: now() });
+ if (next.saving && !before.saving) save(next.on);
+ };
+
+ const look = switchLook(state);
+ 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 -right-9 top-full mt-1.5 z-30 whitespace-nowrap rounded-lg border border-white/14 bg-surface-overlay px-2.5 py-1.5 text-meta text-zinc-100 shadow-raised'
+ }
+ aria-hidden="true"
+ data-dv-hint
+ >
+ {look.hint}
+ </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' });
+ }
+ },
+ onBlur: () => dispatch({ type: 'blur' }),
+ disabled: state.disabled,
+ 'aria-label': look.label,
+ title: look.tooltip,
+ 'data-dev-switch': state.phase,
+ '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,
+ };
+
+ const button = state.reduced ? (
+ <button {...common} className="kw-dv-rm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400">
+ <span className="text-meta font-semibold text-zinc-300" aria-hidden="true">
+ Dev
+ </span>
+ <span className="kw-dv-track" aria-hidden="true">
+ <span className="kw-dv-fill" />
+ <span className="kw-dv-knob">
+ {state.phase === 'lifted' || state.phase === 'pending' ? (
+ <LockOpen size={8} strokeWidth={2.6} className="text-sky-600" data-dv-glyph="unlocked" />
+ ) : (
+ <Lock size={8} strokeWidth={2.6} className="text-sky-600" data-dv-glyph="locked" />
+ )}
+ </span>
+ </span>
+ </button>
+ ) : (
+ <button {...common} className="kw-dv focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400">
+ <span className="kw-dv-track" aria-hidden="true">
+ <span className="kw-dv-fill" />
+ <span className="kw-dv-ring" />
+ <span className="kw-dv-knob" />
+ </span>
+ <span className="kw-dv-cover" aria-hidden="true">
+ &lt;/&gt;
+ </span>
+ <span className="kw-dv-hinge" aria-hidden="true" />
+ </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 className="sr-only" aria-live="polite" data-dv-live>
+ {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">
+ {state.error}
+ </span>
+ )}
+ {state.phase === 'pending' && (
+ <DevModeSetup
+ space={space}
+ initial={known}
+ onCancel={() => {
+ dispatch({ type: 'setup_cancel' });
+ // The cover drops before focus returns, so the ring isn't drawn on a moving switch.
+ setTimeout(() => btn.current?.focus(), state.reduced ? 0 : DROP_MS);
+ }}
+ onDone={(s) => {
+ devStore.set(space.id, s);
+ dispatch({ type: 'setup_done', now: now() });
+ dispatch({ type: 'saved', on: s.on });
+ btn.current?.focus();
+ }}
+ />
+ )}
+ </span>
+ );
+};
+
+/** "Dev mode is off." under the space header: role=status, 10 s or until dismissed. */
+export const DevOffNote: React.FC<{ approvals?: string; onDismiss: () => void; ms?: number }> = ({ approvals, onDismiss, ms = 10_000 }) => {
+ useEffect(() => {
+ const t = setTimeout(onDismiss, ms);
+ return () => clearTimeout(t);
+ }, [onDismiss, ms]);
+ return (
+ <div role="status" data-dev-off-note className="mt-1.5 flex items-start gap-2 rounded-xl border border-white/14 bg-surface-raised px-2.5 py-2 text-meta text-zinc-300">
+ <Code size={13} className="mt-px shrink-0 text-zinc-400" aria-hidden="true" />
+ <p className="min-w-0 flex-1">
+ <strong className="font-semibold text-zinc-100">Dev mode is off.</strong> Reviews, the ship gate and the production floor stopped. Approvals stay on {approvalsWord(approvals)}. What
+ landed keeps its history.
+ </p>
+ <button type="button" onClick={onDismiss} aria-label="Dismiss" className="-m-1 p-1 shrink-0 rounded text-zinc-400 hover:text-zinc-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400">
+ <X size={13} aria-hidden="true" />
+ </button>
+ </div>
+ );
+};
+
+/** The </> badge with its caret on a space tile; `behind` is the surface it sits on. */
+export const DevBadge: React.FC<{ behind?: string }> = ({ behind }) => (
+ <span className="kw-dev-badge" aria-hidden="true" data-dev-badge style={behind ? ({ ['--kw-dev-behind' as string]: behind } as React.CSSProperties) : undefined}>
+ &lt;/&gt;
+ <span className="kw-dev-caret" />
+ </span>
+);
+
+/** The hard hat: 10×8 pixels, zinc-100 with a 2 px sky-400 ridge. */
+const HAT: Array<[number, number, number, string]> = [
+ [3, 0, 4, '#ecebfa'],
+ [2, 1, 6, '#ecebfa'],
+ [1, 2, 8, '#ecebfa'],
+ [1, 3, 8, '#ecebfa'],
+ [1, 4, 8, '#ecebfa'],
+ [0, 5, 10, '#ecebfa'],
+ [0, 6, 10, '#ecebfa'],
+ [4, 0, 2, '#9d8fff'],
+ [4, 1, 2, '#9d8fff'],
+ [4, 2, 2, '#9d8fff'],
+ [4, 3, 2, '#9d8fff'],
+ [4, 4, 2, '#9d8fff'],
+];
+
+export const HardHat: React.FC = () => (
+ <span className="kw-dev-hat" title="Working under Dev mode rules" data-dev-hat>
+ <svg width="10" height="8" viewBox="0 0 10 8" aria-hidden="true" style={{ shapeRendering: 'crispEdges' }}>
+ {HAT.map(([x, y, w, fill], i) => (
+ <rect key={i} x={x} y={y} width={w} height={1} fill={fill} />
+ ))}
+ </svg>
+ <span className="sr-only">Working under Dev mode rules</span>
+ </span>
+);
diff --git a/frontend/src/components/ModernAvatar.tsx b/frontend/src/components/ModernAvatar.tsx
index 9512a8cf..3cb653fd 100644
--- a/frontend/src/components/ModernAvatar.tsx
+++ b/frontend/src/components/ModernAvatar.tsx
@@ -1,4 +1,5 @@
import React, { useCallback, useSyncExternalStore } from 'react';
+import { HardHat, useDevModeOn } from './DevModeSwitch';
import { isKwantWorking, subscribeKwant } from '../kwantActivity';
import { AvatarMood, useKwantMood, useKwantNotices } from './AvatarMood';
import { moodLabel, restingUntilOf } from '../kwantMood';
@@ -344,6 +345,9 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({
const moodText = moodLabel(mood, name, restingUntilOf(kwantId));
const label = moodText ?? (shown ? statusText(name, shown) : name ? (working ? `${name} is working…` : name) : undefined);
const creature = pickCreature(role, name);
+ // Dev mode: every bot avatar of 28 px and up wears the hard hat (top-left, clear of the status dot).
+ const devOn = useDevModeOn();
+ const hat = devOn && !!kwantId && size >= 28;
// At tiny sizes the frame would dominate, so zoom in on the creature alone
const framed = size > 20;
// Small framed avatars enlarge the creature so it stays readable
@@ -388,6 +392,7 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({
</g>
</svg>
<AvatarMood mood={mood} size={size} />
+ {hat && <HardHat />}
{shown && (
<>
<span className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full ring-2 ring-zinc-950 ${STATUS_DOT[shown]}`} aria-hidden="true" />
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 145caed6..9da78a0e 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -17,6 +17,8 @@ import { layaRoutes } from '../channels';
import { InstallAppButton } from './InstallAppButton';
import { trapFocusTarget } from '../imports';
import { type NeedsYouRow, workingIds, directIds } from '../chatsTab';
+import { DevModeSwitch, DevOffNote, useDevMode } from './DevModeSwitch';
+import { DevDeskRow } from './DevDesk';
export interface Kwant {
id: string;
@@ -119,6 +121,9 @@ export interface SidebarProps {
missionBoard?: boolean;
missionsActive?: boolean;
onOpenMissions?: () => void;
+ /** Dev mode (0.7): the Dev desk row's page is open, and how to open it. */
+ devDeskActive?: boolean;
+ onOpenDevDesk?: () => void;
/** Opens Space settings → Accounts from the footer. */
onOpenAccounts?: () => void;
/** Opens Accounts at "Sign in with Claude", when Claude being signed out is why nothing runs. */
@@ -274,6 +279,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
onOpenParallel,
missionBoard = false,
missionsActive = false,
+ devDeskActive = false,
+ onOpenDevDesk,
onOpenMissions,
onOpenAccounts,
onSignInClaude,
@@ -356,6 +363,18 @@ export const Sidebar: React.FC<SidebarProps> = ({
};
const offLine = spaceOffLine(space.approvals, kwants);
+ // Dev mode: the switch sits between the name and the gear; on, the meta line says the branch.
+ const dev = useDevMode(space.id);
+ const devOn = !!dev?.on;
+ const [devOffNote, setDevOffNote] = useState(false);
+ const dismissDevOff = useCallback(() => setDevOffNote(false), []);
+ useEffect(() => setDevOffNote(false), [space.id]);
+ const devSwitch = <DevModeSwitch key={space.id} space={space} phone={phone} onTurnedOff={() => setDevOffNote(true)} />;
+ const devMeta = devOn ? (
+ <span className="block text-meta text-zinc-400 truncate" data-dev-meta>
+ Dev · <span className="font-mono text-sky-300">{dev?.branch ?? 'main'}</span>
+ </span>
+ ) : null;
// 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' : ''
@@ -678,6 +697,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
phones have no rail, so here it is their one switcher. */}
<div className="relative p-2 border-b border-zinc-800/60">
{phone ? (
+ <div className="flex items-center gap-1">
<button
type="button"
onClick={() => {
@@ -689,20 +709,23 @@ 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} />
+ <SpaceTile space={space} size={32} dev={devOn} devBehind="var(--kw-surface-side)" />
<span className="flex-1 min-w-0">
<span className="block text-body font-semibold text-zinc-50 truncate">{space.name}</span>
- <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>
+ {devMeta ?? <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} />
+ <SpaceTile space={space} size={32} dev={devOn} devBehind="var(--kw-surface-side)" />
<span className="flex-1 min-w-0">
<h1 className="text-body font-semibold text-zinc-50 truncate">{space.name}</h1>
- <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>
+ {devMeta ?? <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>}
</span>
+ {devSwitch}
<button
type="button"
onClick={() => {
@@ -718,6 +741,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
</button>
</div>
)}
+ {devOffNote && <DevOffNote approvals={space.approvals} onDismiss={dismissDevOff} />}
{offLine && (
<button
type="button"
@@ -802,6 +826,11 @@ export const Sidebar: React.FC<SidebarProps> = ({
<div className="mt-1 space-y-0.5">{workingBots.map((k) => botRow(k, undefined, {}))}</div>
</section>
)}
+ {devOn && onOpenDevDesk && showChats && (
+ <div data-dev-desk-pin>
+ <DevDeskRow spaceId={space.id} active={devDeskActive} onOpen={onOpenDevDesk} className={navRow(devDeskActive)} />
+ </div>
+ )}
{/* Channels Section */}
{showChats && (
diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsx
index a7ea9943..71b6b24c 100644
--- a/frontend/src/components/SpaceSettings.tsx
+++ b/frontend/src/components/SpaceSettings.tsx
@@ -37,6 +37,7 @@ import { ImportDialog, RecentImports } from './ImportDialog';
import { ImportError, ImportRecord, downloadExport, importApi, importErrorText } from '../imports';
import { memberIdsOf, type Channel, type Kwant, type Team } from './Sidebar';
import { SpaceApprovalsSetting } from './ApprovalsSetting';
+import { DevModeSettings } from './DevModeSettings';
import type { SettingsScope, SpaceSettingsTab } from '../nav';
import { InstallAppButton } from './InstallAppButton';
@@ -484,6 +485,8 @@ const GeneralTab: React.FC<Props> = ({ space, spaces, kwants, onSpaceSaved, onAr
onChanged={() => onApprovalsChanged?.()}
/>
+ <DevModeSettings key={`dev-${space.id}`} spaceId={space.id} spaceName={space.name} approvals={space.approvals} />
+
<div className={`${card} p-4 space-y-3`}>
<p className="flex items-center gap-2 text-xs font-medium text-zinc-200">
<Archive size={14} className="text-zinc-400" /> Archive space
diff --git a/frontend/src/components/Spaces.tsx b/frontend/src/components/Spaces.tsx
index d1a1a657..bd512aa8 100644
--- a/frontend/src/components/Spaces.tsx
+++ b/frontend/src/components/Spaces.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { Archive, Check, Loader2, Plus, RotateCcw, Settings, X, AlertTriangle, KeyRound } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import {
@@ -14,23 +14,50 @@ import {
spacesApi,
} from '../spaces';
import { useEscapeLayer } from '../escape';
+import { devApi, devStore } from '../devMode';
+import { DevBadge } from './DevModeSwitch';
const badge = (n: number) => (n > 99 ? '99+' : String(n));
-/** A space's emoji on its colour. */
-export const SpaceTile: React.FC<{ space: Pick<Space, 'id' | 'icon' | 'color'>; size?: number; className?: string }> = ({
+/** A space's emoji on its colour; `dev` adds the Dev mode `</>` badge bottom-right. */
+export const SpaceTile: React.FC<{ space: Pick<Space, 'id' | 'icon' | 'color'>; size?: number; className?: string; dev?: boolean; devBehind?: string }> = ({
space,
size = 40,
className = '',
-}) => (
- <span
- aria-hidden="true"
- className={`inline-flex items-center justify-center shrink-0 rounded-xl ${className}`}
- style={{ width: size, height: size, background: `${spaceColor(space)}33`, boxShadow: `inset 0 0 0 1px ${spaceColor(space)}66`, fontSize: size * 0.5 }}
- >
- {spaceIcon(space)}
- </span>
-);
+ dev = false,
+ devBehind,
+}) => {
+ const tile = (
+ <span
+ aria-hidden="true"
+ className={`inline-flex items-center justify-center shrink-0 rounded-xl ${dev ? '' : className}`}
+ style={{ width: size, height: size, background: `${spaceColor(space)}33`, boxShadow: `inset 0 0 0 1px ${spaceColor(space)}66`, fontSize: size * 0.5 }}
+ >
+ {spaceIcon(space)}
+ </span>
+ );
+ if (!dev) return tile;
+ return (
+ <span className={`relative inline-flex shrink-0 ${className}`} data-dev-tile>
+ {tile}
+ <DevBadge behind={devBehind} />
+ </span>
+ );
+};
+
+/** The rail shows the badge on every Dev space, but the spaces list has no dev_mode field: ask each once. */
+function useRailDevMode(spaces: Space[]) {
+ useSyncExternalStore(devStore.subscribe, () => spaces.map((s) => (devStore.isOn(s.id) ? 1 : 0)).join(''), () => '');
+ const ids = spaces.map((s) => s.id).join(',');
+ useEffect(() => {
+ for (const id of ids ? ids.split(',') : []) {
+ if (devStore.get(id) || railAsked.has(id)) continue;
+ railAsked.add(id);
+ devApi.get(id).then((st) => devStore.set(id, st), () => undefined);
+ }
+ }, [ids]);
+}
+const railAsked = new Set<string>();
// ---------------------------------------------------------------------------
// Desktop rail
@@ -43,7 +70,9 @@ interface RailProps {
onOpenAppSettings: () => void;
}
-export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, onCreate, onOpenAppSettings }) => (
+export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, onCreate, onOpenAppSettings }) => {
+ useRailDevMode(spaces);
+ return (
<nav aria-label="Spaces" className="hidden md:flex w-[68px] shrink-0 flex-col items-center gap-2 pt-1.5 pb-3 border-r border-hairline bg-surface-rail select-none">
{/* The list scrolls, so it clips whatever sticks out of it. pt-1.5/pb-1.5 leave room for the
active tile's ring (2px + 2px offset) and the unread badge (-6px); the nav's pt-1.5 keeps the
@@ -60,14 +89,14 @@ export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, on
onClick={() => onSwitch(s.id)}
data-rail-space={s.id}
aria-current={active ? 'true' : undefined}
- aria-label={`${s.name}${unread ? `, ${unread} unread` : ''}`}
+ aria-label={`${s.name}${devStore.isOn(s.id) ? ', Dev mode on' : ''}${unread ? `, ${unread} unread` : ''}`}
title={`${s.name}${i < 9 ? ` (Ctrl/⌘ ${i + 1})` : ''}`}
className={`relative rounded-xl transition-all focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${
active ? 'ring-2 ring-offset-2 ring-offset-zinc-950' : 'opacity-75 hover:opacity-100'
}`}
style={active ? ({ '--tw-ring-color': spaceColor(s) } as React.CSSProperties) : undefined}
>
- <SpaceTile space={s} size={40} />
+ <SpaceTile space={s} size={40} dev={devStore.isOn(s.id)} devBehind="var(--kw-surface-rail)" />
{unread > 0 && (
<span className="absolute -top-1.5 -right-1.5 min-w-[18px] px-1 py-px rounded-full bg-rose-500 text-white text-[10px] font-semibold text-center border-2 border-zinc-950">
{badge(unread)}
@@ -100,7 +129,8 @@ export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, on
<Settings size={18} />
</button>
</nav>
-);
+ );
+};
// ---------------------------------------------------------------------------
// Switcher: a popover under the space header (desktop) or a bottom sheet (phone)
diff --git a/frontend/src/connections.ts b/frontend/src/connections.ts
index 02a12b2f..7ad3f025 100644
--- a/frontend/src/connections.ts
+++ b/frontend/src/connections.ts
@@ -29,6 +29,8 @@ export interface Connection {
used_by: UsedBy[];
logins_stored: LoginsStored | string;
manage: string;
+ /** Dev mode D10: marked as a production connection in this space (0.7 servers). */
+ production?: boolean;
}
export interface CatalogEntry {
@@ -211,6 +213,9 @@ export function usedByText(used: UsedBy[], status: string): string {
}
/** The MCP server id inside a connection id (`mcp:<id>`), for "Check now". */
+/** Dev mode D10: only MCP servers and Composio apps can be marked production. */
+export const canMarkProduction = (c: Pick<Connection, 'id'>): boolean => c.id.startsWith('mcp:') || /^composio:[a-z0-9_-]{1,64}$/.test(c.id);
+
export const mcpServerId = (c: Pick<Connection, 'id' | 'kind'>): string | null =>
c.kind === 'mcp' && c.id.startsWith('mcp:') ? c.id.slice(4) : null;
diff --git a/frontend/src/dev/shellTypes.ts b/frontend/src/dev/shellTypes.ts
new file mode 100644
index 00000000..7ab7c328
--- /dev/null
+++ b/frontend/src/dev/shellTypes.ts
@@ -0,0 +1,64 @@
+// The Dev desk shell's view of a card. Iris owns the full card types in `./types.ts`; until hers
+// land the shell needs only these fields, and passes the rest through to her renderers untouched.
+
+export type CardKind = 'landed' | 'review' | 'release_notes';
+export type CardStatus = 'pending' | 'ready' | 'failed' | 'stale';
+
+export interface ShellCard {
+ id: string;
+ kind: CardKind | string;
+ status: CardStatus | string;
+ created_at?: string | null;
+ merged_at?: string | null;
+ pr?: number | null;
+ title?: string | null;
+ headline?: string | null;
+ [k: string]: unknown;
+}
+
+export interface LandedRollup {
+ since: string | null;
+ until: string | null;
+ count: number;
+ needs_you: number;
+ main_green: boolean | null;
+ areas: Array<{ area: string; count: number; first_headline: string }>;
+}
+
+export interface LandedPage {
+ cards: ShellCard[];
+ rollup: LandedRollup | null;
+ last_tag: string | null;
+}
+
+/** Same shape as iris-dev-cards `dev/types.ts` FindingAction. */
+export type FindingAction = { action: 'fix' } | { action: 'undo_fix' } | { action: 'dismiss'; reason: 'not_a_problem' | 'fine_here' | 'later' | 'wrong'; note?: string };
+
+const isCard = (v: unknown): v is ShellCard =>
+ !!v && typeof v === 'object' && typeof (v as ShellCard).id === 'string' && typeof (v as ShellCard).kind === 'string' && typeof (v as ShellCard).status === 'string';
+
+export function parseCards(raw: unknown): ShellCard[] {
+ const list = raw && typeof raw === 'object' ? (raw as { cards?: unknown }).cards : null;
+ return Array.isArray(list) ? list.filter(isCard) : [];
+}
+
+export function parseLandedPage(raw: unknown): LandedPage {
+ const o = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
+ const r = o.rollup && typeof o.rollup === 'object' ? (o.rollup as Record<string, unknown>) : null;
+ return {
+ cards: parseCards(raw),
+ rollup: r
+ ? {
+ since: typeof r.since === 'string' ? r.since : null,
+ until: typeof r.until === 'string' ? r.until : null,
+ count: typeof r.count === 'number' ? r.count : 0,
+ needs_you: typeof r.needs_you === 'number' ? r.needs_you : 0,
+ main_green: typeof r.main_green === 'boolean' ? r.main_green : null,
+ areas: Array.isArray(r.areas) ? (r.areas as LandedRollup['areas']) : [],
+ }
+ : null,
+ last_tag: typeof o.last_tag === 'string' ? o.last_tag : null,
+ };
+}
+
+export const asCard = (raw: unknown): ShellCard | null => (isCard(raw) ? raw : null);
diff --git a/frontend/src/devMode.ts b/frontend/src/devMode.ts
new file mode 100644
index 00000000..1ef18d4c
--- /dev/null
+++ b/frontend/src/devMode.ts
@@ -0,0 +1,495 @@
+// Dev mode (0.7): the switch's safety cover, the first-switch-on setup, the per-space store and the
+// API client. Person-only on the server: a bot's token gets 403, so the switch shows disabled.
+// Contract: dev-mode/plan/plan.md §3.2 and §3.6, the route JSON in dev-mode/impl/lin.md.
+
+import { personFetch } from './auth';
+
+// ---------------------------------------------------------------------------
+// Server shapes
+
+export type DeployHint = 'docker' | 'cloudflare_pages' | 'fly' | null;
+
+/** GET/PUT /api/spaces/:id/dev_mode */
+export interface DevModeState {
+ on: boolean;
+ repo: string | null;
+ branch: string | null;
+ deploy_hint: DeployHint;
+ backup_command: string | null;
+ last_seen_sha: string | null;
+ polled_at: string | null;
+ poll_error: string | null;
+ calls_today: number | null;
+ calls_cap: number | null;
+}
+
+export type CheckState = 'found' | 'not_found' | 'not_connected';
+
+/** POST /api/spaces/:id/dev_mode/check */
+export interface RepoCheck {
+ state: CheckState;
+ repo: string | null;
+ branch: string | null;
+ deploy_hint: DeployHint;
+}
+
+const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v : null);
+const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const hint = (v: unknown): DeployHint => (v === 'docker' || v === 'cloudflare_pages' || v === 'fly' ? v : null);
+
+export function parseDevMode(raw: unknown): DevModeState | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const o = raw as Record<string, unknown>;
+ if (typeof o.on !== 'boolean') return null;
+ return {
+ on: o.on,
+ repo: str(o.repo),
+ branch: str(o.branch),
+ deploy_hint: hint(o.deploy_hint),
+ backup_command: str(o.backup_command),
+ last_seen_sha: str(o.last_seen_sha),
+ polled_at: str(o.polled_at),
+ poll_error: str(o.poll_error),
+ calls_today: num(o.calls_today),
+ calls_cap: num(o.calls_cap),
+ };
+}
+
+export function parseCheck(raw: unknown): RepoCheck | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const o = raw as Record<string, unknown>;
+ if (o.state !== 'found' && o.state !== 'not_found' && o.state !== 'not_connected') return null;
+ return { state: o.state, repo: str(o.repo), branch: str(o.branch), deploy_hint: hint(o.deploy_hint) };
+}
+
+/** A space that was never switched on (or has no repo) gets the setup sheet on its first switch-on. */
+export const needsSetup = (s: DevModeState | null): boolean => !s || !s.repo || (!s.on && !s.polled_at && !s.last_seen_sha);
+
+// ---------------------------------------------------------------------------
+// Repo input: a URL, `owner/name` or `[email protected]:owner/name.git`, normalised to `owner/name`
+
+const PART = /^[A-Za-z0-9_.-]{1,100}$/;
+
+export function normaliseRepo(input: string): string | null {
+ let s = input.trim();
+ if (!s) return null;
+ s = s.replace(/^git@github\.com:/i, '');
+ s = s.replace(/^(?:https?:\/\/|git:\/\/|ssh:\/\/git@)?(?:www\.)?github\.com\//i, '');
+ s = s.replace(/[?#].*$/, '').replace(/\/+$/, '').replace(/\.git$/i, '');
+ const [owner, name, ...rest] = s.split('/');
+ // github.com/owner/name/tree/main and /pull/3 still name the repo
+ if (!owner || !name || (rest.length && !['tree', 'blob', 'pull', 'pulls', 'issues', 'actions', 'commit', 'commits'].includes(rest[0]))) return null;
+ if (!PART.test(owner) || !PART.test(name) || name === '.' || name === '..') return null;
+ return `${owner}/${name}`;
+}
+
+// ---------------------------------------------------------------------------
+// The switch: a safety cover over a launch switch (design §1)
+
+/** How long a lifted cover waits before it drops back with nothing changed. */
+export const RECOVER_MS = 5000;
+/** After a flip the cover drops back at 450 ms (150 ms drop), and presses are ignored until then. */
+export const SETTLE_MS = 450;
+export const DROP_MS = 150;
+
+export type SwitchPhase = 'covered' | 'lifted' | 'pending' | 'settling';
+
+export interface SwitchState {
+ /** The committed value, as the server last said (or as just pressed, while saving). */
+ on: boolean;
+ phase: SwitchPhase;
+ /** When the cover was lifted, for the 5 s re-cover. */
+ liftedAt: number | null;
+ /** Presses are ignored until this time (the settle after a flip). */
+ settleUntil: number;
+ /** The space hasn't been set up: the second press asks for the setup sheet. */
+ setup: boolean;
+ /** Not the person (403), or the server doesn't have Dev mode. */
+ disabled: boolean;
+ /** Under prefers-reduced-motion every change is instant, so there is nothing to settle. */
+ reduced: boolean;
+ /** What the polite live region says next; seq changes on every announcement. */
+ announce: { text: string; seq: number } | null;
+ /** A save is in flight (the press already flipped the switch). */
+ saving: boolean;
+ error: string | null;
+}
+
+export type SwitchAction =
+ | { type: 'press'; now: number }
+ | { type: 'recover'; now: number }
+ | { type: 'escape' }
+ | { type: 'blur' }
+ | { type: 'settled'; now: number }
+ | { type: 'setup_done'; now: number }
+ | { type: 'setup_cancel' }
+ | { type: 'saved'; on: boolean }
+ | { type: 'save_failed'; error: string }
+ | { type: 'server'; state: DevModeState | null; disabled?: boolean }
+ | { type: 'reduced'; reduced: boolean };
+
+export const initialSwitch = (over: Partial<SwitchState> = {}): SwitchState => ({
+ on: false,
+ phase: 'covered',
+ liftedAt: null,
+ settleUntil: 0,
+ setup: true,
+ disabled: false,
+ reduced: false,
+ announce: null,
+ saving: false,
+ error: null,
+ ...over,
+});
+
+const say = (s: SwitchState, text: string) => ({ text, seq: (s.announce?.seq ?? 0) + 1 });
+
+export const onText = (space: string) => `Dev mode on for ${space}.`;
+export const offText = (space: string) => `Dev mode off for ${space}. Reviews, the ship gate and the production floor stopped.`;
+export const liftText = (on: boolean) => `Unlocked. Press again to turn Dev mode ${on ? 'off' : 'on'}.`;
+
+/**
+ * The switch's state machine. Pure: time comes in on the actions, and the component runs the timers
+ * (re-cover at liftedAt + 5 s, settled at settleUntil). `space` names the space in announcements.
+ */
+export function switchReducer(s: SwitchState, a: SwitchAction, space = 'this space'): SwitchState {
+ switch (a.type) {
+ case 'press': {
+ if (s.disabled || s.saving) return s;
+ if (s.phase === 'pending') return s;
+ // A fast double-click: the second press lands while the cover settles, and is ignored.
+ if (s.phase === 'settling' || a.now < s.settleUntil) return s;
+ if (s.phase === 'covered') return { ...s, phase: 'lifted', liftedAt: a.now, error: null, announce: say(s, liftText(s.on)) };
+ // phase lifted: the second press flips, or opens the setup the first time
+ if (!s.on && s.setup) return { ...s, phase: 'pending', liftedAt: null, announce: say(s, 'Dev mode, setting up.') };
+ return flip(s, !s.on, a.now, space);
+ }
+ case 'recover':
+ if (s.phase !== 'lifted' || s.liftedAt === null || a.now - s.liftedAt < RECOVER_MS) return s;
+ return { ...s, phase: 'covered', liftedAt: null, announce: say(s, 'Locked.') };
+ case 'escape':
+ case 'blur':
+ if (s.phase !== 'lifted') return s;
+ return { ...s, phase: 'covered', liftedAt: null, announce: say(s, 'Locked.') };
+ case 'settled':
+ if (s.phase !== 'settling' || a.now < s.settleUntil) return s;
+ return { ...s, phase: 'covered' };
+ case 'setup_done':
+ if (s.phase !== 'pending') return s;
+ return flip({ ...s, setup: false }, true, a.now, space);
+ case 'setup_cancel':
+ if (s.phase !== 'pending') return s;
+ return { ...s, phase: 'covered', liftedAt: null, announce: say(s, 'Locked.') };
+ case 'saved':
+ return { ...s, saving: false, on: a.on, setup: a.on ? false : s.setup };
+ case 'save_failed':
+ // The press didn't take: back to what it was, covered, with the reason.
+ return { ...s, saving: false, on: !s.on, phase: 'covered', liftedAt: null, settleUntil: 0, error: a.error, announce: say(s, a.error) };
+ case 'server': {
+ const disabled = a.disabled ?? s.disabled;
+ if (!a.state) return { ...s, disabled };
+ // A save in flight, or a cover the person is holding open, keeps what they see.
+ if (s.saving || s.phase === 'pending') return { ...s, disabled, setup: needsSetup(a.state) };
+ return { ...s, disabled, on: a.state.on, setup: needsSetup(a.state), phase: s.phase === 'lifted' && a.state.on !== s.on ? 'covered' : s.phase };
+ }
+ case 'reduced':
+ return { ...s, reduced: a.reduced };
+ }
+}
+
+function flip(s: SwitchState, on: boolean, now: number, space: string): SwitchState {
+ return {
+ ...s,
+ on,
+ saving: true,
+ liftedAt: null,
+ // Reduced motion: no hinge to settle, it locks at once. Still two presses to the next flip.
+ phase: s.reduced ? 'covered' : 'settling',
+ settleUntil: s.reduced ? 0 : now + SETTLE_MS,
+ error: null,
+ announce: say(s, on ? onText(space) : offText(space)),
+ };
+}
+
+/** What the switch looks like: cover open or closed, knob side, fill opacity, ring and hint. */
+export interface SwitchLook {
+ coverOpen: boolean;
+ knobRight: boolean;
+ fill: number;
+ ring: boolean;
+ hint: string | null;
+ label: string;
+ tooltip: string;
+}
+
+export function switchLook(s: SwitchState): SwitchLook {
+ const unavailable = s.disabled ? ', unavailable' : '';
+ const tooltip = s.disabled ? 'Only the space owner can change Dev mode' : `Dev mode is ${s.on ? 'on' : 'off'}. Press to unlock.`;
+ switch (s.phase) {
+ case 'lifted':
+ return {
+ coverOpen: true,
+ knobRight: s.on,
+ fill: s.on ? 1 : 0,
+ ring: true,
+ hint: `Press again to turn Dev mode ${s.on ? 'off' : 'on'}`,
+ label: `Dev mode, ${s.on ? 'on' : 'off'}. Unlocked. Press again to turn it ${s.on ? 'off' : 'on'}`,
+ tooltip,
+ };
+ case 'pending':
+ return { coverOpen: true, knobRight: true, fill: 0.45, ring: true, hint: null, label: 'Dev mode, setting up.', tooltip };
+ case 'settling':
+ // Open while it settles, then it drops; the label is already the final state.
+ return { coverOpen: true, knobRight: s.on, fill: s.on ? 1 : 0, ring: false, hint: null, label: `Dev mode, ${s.on ? 'on' : 'off'}. Press to unlock`, tooltip };
+ default:
+ return { coverOpen: false, knobRight: s.on, fill: s.on ? 1 : 0, ring: false, hint: null, label: `Dev mode, ${s.on ? 'on' : 'off'}. Press to unlock${unavailable}`, tooltip };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Setup sheet: the Repository field (design §3 table)
+
+export type FieldState = 'empty' | 'invalid' | 'checking' | 'found' | 'not_found' | 'not_connected' | 'error';
+
+export interface FieldView {
+ chip: { tone: 'info' | 'ok' | 'bad' | 'warn'; text: string; spinner?: boolean } | null;
+ /** Plain help text, or null for the "filled in from this team's repo" default. */
+ help: string | null;
+ /** The repo name shown bold inside the not-found help line. */
+ helpRepo: string | null;
+ connect: boolean;
+ canTurnOn: boolean;
+}
+
+export const DEFAULT_HELP = 'Filled in from this team’s repo. Read with your GitHub connection from Loose ends; nothing is written.';
+export const EMPTY_HELP = 'Paste a GitHub repo, like owner/name or its URL.';
+
+export function fieldView(state: FieldState, repo: string | null, error: string | null = null): FieldView {
+ switch (state) {
+ case 'checking':
+ return { chip: { tone: 'info', text: 'Checking', spinner: true }, help: null, helpRepo: null, connect: false, canTurnOn: false };
+ case 'found':
+ return { chip: { tone: 'ok', text: 'Found' }, help: DEFAULT_HELP, helpRepo: null, connect: false, canTurnOn: true };
+ case 'not_found':
+ return {
+ chip: { tone: 'bad', text: 'Can’t see it' },
+ help: 'Bots can’t see {repo} with your GitHub connection. Check the name, or give Loose ends access to it.',
+ helpRepo: repo,
+ connect: false,
+ canTurnOn: false,
+ };
+ case 'not_connected':
+ return { chip: { tone: 'warn', text: 'Not connected' }, help: 'Connect GitHub to read this repo. Bots only read it.', helpRepo: null, connect: true, canTurnOn: false };
+ case 'invalid':
+ return { chip: { tone: 'bad', text: 'Not a repo' }, help: EMPTY_HELP, helpRepo: null, connect: false, canTurnOn: false };
+ case 'error':
+ return { chip: { tone: 'warn', text: 'Can’t check' }, help: error ?? 'GitHub can’t be reached right now. Try again in a minute.', helpRepo: null, connect: false, canTurnOn: false };
+ default:
+ return { chip: null, help: EMPTY_HELP, helpRepo: null, connect: false, canTurnOn: false };
+ }
+}
+
+export const CHECK_DEBOUNCE_MS = 400;
+
+export interface CheckerTimers {
+ setTimeout: (fn: () => void, ms: number) => unknown;
+ clearTimeout: (h: unknown) => void;
+}
+
+export interface CheckerUpdate {
+ state: FieldState;
+ check: RepoCheck | null;
+ error: string | null;
+}
+
+/**
+ * The Repository field's checker: each input waits 400 ms, then asks the server. Only the latest
+ * input's answer counts, so a slow reply to an earlier name never overwrites a newer one.
+ */
+export function createRepoChecker(
+ check: (repo: string) => Promise<RepoCheck>,
+ onUpdate: (u: CheckerUpdate) => void,
+ timers: CheckerTimers = { setTimeout: (f, ms) => setTimeout(f, ms), clearTimeout: (h) => clearTimeout(h as ReturnType<typeof setTimeout>) },
+ delay = CHECK_DEBOUNCE_MS,
+) {
+ let handle: unknown = null;
+ let seq = 0;
+ return {
+ input(raw: string) {
+ const mine = ++seq;
+ if (handle !== null) timers.clearTimeout(handle);
+ handle = null;
+ if (!raw.trim()) return onUpdate({ state: 'empty', check: null, error: null });
+ const repo = normaliseRepo(raw);
+ if (!repo) return onUpdate({ state: 'invalid', check: null, error: null });
+ onUpdate({ state: 'checking', check: null, error: null });
+ handle = timers.setTimeout(() => {
+ handle = null;
+ check(repo).then(
+ (c) => mine === seq && onUpdate({ state: c.state, check: c, error: null }),
+ (e: unknown) => mine === seq && onUpdate({ state: 'error', check: null, error: e instanceof Error ? e.message : null }),
+ );
+ }, delay);
+ },
+ cancel() {
+ seq++;
+ if (handle !== null) timers.clearTimeout(handle);
+ handle = null;
+ },
+ };
+}
+
+export const deployLabel = (h: DeployHint): { name: string; detail: string } | null =>
+ h === 'docker' ? { name: 'Docker', detail: 'compose file' } : h === 'cloudflare_pages' ? { name: 'Cloudflare Pages', detail: 'static site' } : h === 'fly' ? { name: 'Fly.io', detail: 'fly.toml' } : null;
+
+export const approvalsWord = (a: string | undefined) => (a === 'off' ? 'Off' : a === 'smart' ? 'Smart' : 'Ask');
+
+// ---------------------------------------------------------------------------
+// API
+
+export class DevModeError extends Error {
+ constructor(message: string, public status: number) {
+ super(message);
+ }
+}
+
+async function call<T>(url: string, method = 'GET', body?: unknown, send: typeof fetch = (...a) => personFetch(a[0] as string, a[1])): Promise<{ status: number; data: T }> {
+ let res: Response;
+ try {
+ res = await send(url, {
+ method,
+ cache: 'no-store',
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch {
+ throw new DevModeError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const data = await res.json().catch(() => null);
+ if (res.ok) return { status: res.status, data: data as T };
+ const err = data && typeof data === 'object' ? (data as Record<string, unknown>).error : null;
+ if (res.status === 403) throw new DevModeError('Only the space owner can change Dev mode.', 403);
+ if (res.status === 404 && !err) throw new DevModeError('This server doesn’t have Dev mode yet. Update the app.', 404);
+ throw new DevModeError(typeof err === 'string' && err.trim() ? err : `Something went wrong (HTTP ${res.status}).`, res.status);
+}
+
+const enc = encodeURIComponent;
+
+export const devApi = {
+ async get(space: string): Promise<DevModeState> {
+ const r = await call<unknown>(`/api/spaces/${enc(space)}/dev_mode`);
+ const s = parseDevMode(r.data);
+ if (!s) throw new DevModeError('The server sent Dev mode in a shape this app doesn’t know.', 500);
+ return s;
+ },
+ async put(space: string, body: { on: boolean; repo?: string | null; branch?: string | null; backup_command?: string | null }): Promise<DevModeState> {
+ const r = await call<unknown>(`/api/spaces/${enc(space)}/dev_mode`, 'PUT', body);
+ const s = parseDevMode(r.data);
+ if (!s) throw new DevModeError('The server sent Dev mode in a shape this app doesn’t know.', 500);
+ return s;
+ },
+ async check(space: string, repo: string): Promise<RepoCheck> {
+ const r = await call<unknown>(`/api/spaces/${enc(space)}/dev_mode/check`, 'POST', { repo });
+ const c = parseCheck(r.data);
+ if (!c) throw new DevModeError('The server sent a repo check this app doesn’t know.', 500);
+ return c;
+ },
+ landed: (space: string, before?: string) =>
+ call<unknown>(`/api/spaces/${enc(space)}/dev/landed?limit=30${before ? `&before=${enc(before)}` : ''}`).then((r) => r.data),
+ seen: (space: string) => call<{ seen_at: string }>(`/api/spaces/${enc(space)}/dev/landed/seen`, 'POST').then((r) => r.data),
+ reviews: (space: string) => call<unknown>(`/api/spaces/${enc(space)}/dev/reviews`).then((r) => r.data),
+ finding: (card: string, fid: string, body: { action: string; reason?: string; note?: string }) =>
+ call<unknown>(`/api/dev/cards/${enc(card)}/findings/${enc(fid)}`, 'POST', body).then((r) => r.data),
+ /** Not in lin-dev-core 492019f yet (asked Lin): the ready release-notes card after its SSE. */
+ card: (id: string) => call<unknown>(`/api/dev/cards/${enc(id)}`).then((r) => r.data),
+ releaseNotes: (space: string) => call<unknown>(`/api/spaces/${enc(space)}/dev/release_notes`, 'POST').then((r) => r.data),
+ production: (connection: string, space: string, production: boolean) =>
+ call<{ id: string; production: boolean }>(`/api/connections/${enc(connection)}/production?space=${enc(space)}`, 'PUT', { production }).then((r) => r.data),
+};
+
+export const _call = call;
+
+// ---------------------------------------------------------------------------
+// The per-space store: the header, rail badge, hard hats and grid all read it
+
+type Listener = () => void;
+const states = new Map<string, DevModeState>();
+const listeners = new Set<Listener>();
+let current: string | null = null;
+
+export const devStore = {
+ get: (space: string | null | undefined): DevModeState | null => (space ? states.get(space) ?? null : null),
+ isOn: (space: string | null | undefined): boolean => !!(space && states.get(space)?.on),
+ set(space: string, s: DevModeState) {
+ states.set(space, s);
+ listeners.forEach((l) => l());
+ },
+ /** The `dev_mode {space_id, on}` SSE event: flips the cached value at once, then the caller refetches. */
+ setOn(space: string, on: boolean) {
+ const s = states.get(space);
+ if (s && s.on === on) return;
+ states.set(space, { ...(s ?? emptyState()), on });
+ listeners.forEach((l) => l());
+ },
+ setCurrent(space: string | null) {
+ if (current === space) return;
+ current = space;
+ listeners.forEach((l) => l());
+ },
+ current: () => current,
+ subscribe(l: Listener) {
+ listeners.add(l);
+ return () => void listeners.delete(l);
+ },
+ /** Tests only. */
+ _reset() {
+ states.clear();
+ current = null;
+ },
+};
+
+export const emptyState = (): DevModeState => ({
+ 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,
+});
+
+// ---------------------------------------------------------------------------
+// Dev desk
+
+/** "Today", "Yesterday", or "Tue 3 Nov", in the viewer's local time. */
+export function dayLabel(iso: string, now = new Date()): string {
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '';
+ const day = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
+ const diff = Math.round((day(now) - day(d)) / 86_400_000);
+ if (diff === 0) return 'Today';
+ if (diff === 1) return 'Yesterday';
+ return d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
+}
+
+/** The day separator goes on the first card of each day, newest first. */
+export function withDayLabels<T extends { created_at?: string | null; merged_at?: string | null }>(cards: T[], now = new Date()): Array<{ card: T; dayLabel: string | null }> {
+ let last = '';
+ return cards.map((card) => {
+ const label = dayLabel(card.merged_at ?? card.created_at ?? '', now);
+ const show = label && label !== last ? label : null;
+ if (label) last = label;
+ return { card, dayLabel: show };
+ });
+}
+
+/** The Dev desk row's status: "3 landed · 1 review open". */
+export function deskStatus(unseenLanded: number, openReviews: number): string {
+ const parts = [];
+ parts.push(`${unseenLanded} landed`);
+ parts.push(`${openReviews} ${openReviews === 1 ? 'review' : 'reviews'} open`);
+ return parts.join(' · ');
+}
diff --git a/frontend/src/nav.ts b/frontend/src/nav.ts
index adea402c..ec2949b0 100644
--- a/frontend/src/nav.ts
+++ b/frontend/src/nav.ts
@@ -1,5 +1,5 @@
-// Where you are inside a space besides a chat: Inbox, Mission board, Parallel Universe or
-// Settings. Each has its own address under /s/<space>/, so a reload, a bookmark or a link
+// Where you are inside a space besides a chat: Inbox, Mission board, Parallel Universe, the Dev
+// desk or Settings. Each has its own address under /s/<space>/, so a reload, a bookmark or a link
// lands on the same place. Older names (While you were away, Loose ends, Connections,
// Routines) still resolve and are rewritten to the new address.
@@ -15,6 +15,7 @@ export type SpaceView =
| { kind: 'inbox'; tab: InboxTab }
| { kind: 'board' }
| { kind: 'parallel' }
+ | { kind: 'dev' }
| { kind: 'settings'; scope: 'space'; tab: SpaceSettingsTab }
| { kind: 'settings'; scope: 'app' };
@@ -27,6 +28,8 @@ export function viewSegment(v: SpaceView): string {
return 'board';
case 'parallel':
return 'parallel';
+ case 'dev':
+ return 'dev';
case 'settings':
return v.scope === 'app' ? 'settings/app' : `settings/${v.tab}`;
}
@@ -62,6 +65,7 @@ export function parseView(segment: string): { view: SpaceView; legacy: boolean }
}
if (head === 'board' && !sub) return { view: { kind: 'board' }, legacy: false };
if (head === 'parallel' && !sub) return { view: { kind: 'parallel' }, legacy: false };
+ if (head === 'dev' && !sub) return { view: { kind: 'dev' }, legacy: false };
if (head === 'settings') {
if (!sub) return { view: { kind: 'settings', scope: 'space', tab: 'general' }, legacy: true };
if (sub === 'app' || sub === 'all') return { view: { kind: 'settings', scope: 'app' }, legacy: sub !== 'app' };
diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.css
index e98252c6..19981b88 100644
--- a/frontend/src/styles/modern.css
+++ b/frontend/src/styles/modern.css
@@ -561,3 +561,102 @@ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow:
animation: none;
}
}
+/* ---- Dev mode (0.7): the switch's safety cover, the </> badge, the hard hat and the blueprint grid.
+ design.md §1–§2. Motion is transform and opacity only; under reduced motion nothing animates and
+ the switch is a plain labelled track with a lock glyph (DevModeSwitch renders that variant). */
+.kw-dv { position: relative; width: 44px; height: 32px; border-radius: 10px; flex-shrink: 0; }
+.kw-dv:disabled { opacity: 0.5; cursor: not-allowed; }
+.kw-dv-track {
+ position: absolute; left: 5px; top: 7px; width: 34px; height: 18px; border-radius: 9999px;
+ background: #2c2552; box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.14);
+}
+.kw-dv-fill {
+ position: absolute; inset: 0; border-radius: 9999px;
+ background: linear-gradient(135deg, #7a62f0 0%, #5b47d6 100%);
+ opacity: var(--kw-dv-fill, 0); transition: opacity 160ms var(--kw-ease);
+}
+.kw-dv-ring {
+ position: absolute; inset: -3px; border-radius: 12px; pointer-events: none; opacity: 0;
+ box-shadow: 0 0 0 1.5px rgb(157 143 255 / 0.7), 0 0 10px rgb(157 143 255 / 0.35);
+ transition: opacity 150ms var(--kw-ease);
+}
+.kw-dv[data-ring] .kw-dv-ring { opacity: 1; }
+.kw-dv-knob {
+ position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; border-radius: 9999px;
+ display: flex; align-items: center; justify-content: center;
+ background: #ecebfa; box-shadow: 0 1px 2px rgb(6 3 20 / 0.5);
+ transition: transform 160ms var(--kw-ease);
+}
+.kw-dv[data-knob='right'] .kw-dv-knob { transform: translateX(16px); }
+.kw-dv-cover {
+ position: absolute; left: 1px; top: 3px; width: 42px; height: 26px; border-radius: 9px;
+ display: flex; align-items: center; justify-content: center;
+ background: rgb(236 235 250 / 0.11); border: 1px solid rgb(255 255 255 / 0.24);
+ -webkit-backdrop-filter: blur(1.6px) saturate(1.2); backdrop-filter: blur(1.6px) saturate(1.2);
+ box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.22), 0 2px 6px rgb(6 3 20 / 0.35);
+ font: 700 9px/1 'JetBrains Mono', ui-monospace, monospace; color: rgb(154 148 196 / 0.85);
+ transform-origin: top; transition: transform 150ms var(--kw-ease), opacity 150ms var(--kw-ease), background-color 150ms var(--kw-ease);
+}
+.kw-dv:not(:disabled):hover[data-cover='closed'] .kw-dv-cover { background: rgb(255 255 255 / 0.16); }
+.kw-dv[data-cover='open'] .kw-dv-cover { transform: perspective(220px) rotateX(112deg); opacity: 0.9; }
+.kw-dv-hinge { position: absolute; left: 12px; top: 1px; width: 20px; height: 3px; pointer-events: none; }
+.kw-dv-hinge::before, .kw-dv-hinge::after { content: ''; position: absolute; top: 0; width: 5px; height: 3px; border-radius: 1px; background: #8d87b8; }
+.kw-dv-hinge::before { left: 0; }
+.kw-dv-hinge::after { right: 0; }
+/* Reduced motion: "Dev" label, track, lock glyph in the knob; every change instant */
+.kw-dv-rm { position: relative; display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 4px; border-radius: 10px; flex-shrink: 0; }
+.kw-dv-rm:disabled { opacity: 0.5; cursor: not-allowed; }
+.kw-dv-rm .kw-dv-track { position: relative; left: auto; top: auto; display: block; }
+.kw-dv-rm[data-ring] .kw-dv-track { box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.14), 0 0 0 1.5px rgb(157 143 255 / 0.7), 0 0 10px rgb(157 143 255 / 0.35); }
+.kw-dv-rm[data-knob='right'] .kw-dv-knob { transform: translateX(16px); }
+.kw-dv-hint { animation: kw-dv-hint 150ms var(--kw-ease) both; }
+@keyframes kw-dv-hint { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
+
+/* The </> badge on a space tile: bottom-right, mirroring the unread badge top-right */
+.kw-dev-badge {
+ position: absolute; right: -6px; bottom: -5px; height: 15px; padding: 0 3px; border-radius: 5px;
+ display: inline-flex; align-items: center; gap: 1px; pointer-events: none;
+ background: #1a1538; box-shadow: 0 0 0 1.5px var(--kw-dev-behind, #0a0719), inset 0 0 0 1px rgb(157 143 255 / 0.6);
+ font: 700 10px/1 'JetBrains Mono', ui-monospace, monospace; color: #b8adff;
+ animation: kw-dv-pop 160ms var(--kw-ease) both;
+}
+.kw-dev-caret { display: inline-block; width: 1.5px; height: 8px; background: currentColor; animation: kw-dv-caret 900ms steps(1) 4; }
+@keyframes kw-dv-pop { from { opacity: 0; transform: scale(0.6); } to { opacity: 1; transform: none; } }
+@keyframes kw-dv-caret { 0% { opacity: 1; } 50% { opacity: 0; } }
+
+/* The hard hat: top-left on avatars of 28 px and up, so it never covers the status dot */
+.kw-dev-hat {
+ position: absolute; left: -4px; top: -4px; width: 14px; height: 14px; border-radius: 9999px; z-index: 2;
+ display: flex; align-items: center; justify-content: center;
+ background: #0a0719; box-shadow: 0 0 0 1.5px #0e0a21;
+ animation: kw-dv-pop 160ms var(--kw-ease) both;
+}
+
+/* The blueprint grid: only the main pane, fading down it; cards stay opaque on top. The pane's own
+ root background goes transparent so the grid sits between the surface and the content. */
+.kw-blueprint { position: relative; isolation: isolate; background-color: var(--kw-surface-main); }
+.kw-blueprint > * { background-color: transparent !important; }
+.kw-blueprint::before {
+ content: ''; position: absolute; inset: 0; z-index: -1; pointer-events: none;
+ background-image:
+ linear-gradient(to right, rgb(157 143 255 / 0.085) 1px, transparent 1px),
+ linear-gradient(to bottom, rgb(157 143 255 / 0.085) 1px, transparent 1px),
+ linear-gradient(to right, rgb(157 143 255 / 0.045) 1px, transparent 1px),
+ linear-gradient(to bottom, rgb(157 143 255 / 0.045) 1px, transparent 1px);
+ background-size: 120px 120px, 120px 120px, 24px 24px, 24px 24px;
+ -webkit-mask-image: linear-gradient(180deg, #000 0%, rgb(0 0 0 / 0.25) 100%);
+ mask-image: linear-gradient(180deg, #000 0%, rgb(0 0 0 / 0.25) 100%);
+ animation: kw-dv-grid 200ms var(--kw-ease) both;
+}
+@keyframes kw-dv-grid { from { opacity: 0; } to { opacity: 1; } }
+
+@media (prefers-reduced-motion: reduce) {
+ .kw-dv-fill, .kw-dv-ring, .kw-dv-knob, .kw-dv-cover { transition: none; }
+ .kw-dv-hint, .kw-dev-badge, .kw-dev-hat, .kw-blueprint::before { animation: none; }
+ .kw-dev-caret { animation: none; }
+}
+
+/* Dev mode setup sheet: 180 ms entry (design §3). */
+.kw-dv-sheet { animation: kw-dv-sheet-in 180ms var(--kw-ease) both; }
+@keyframes kw-dv-sheet-in { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }
+@media (prefers-reduced-motion: reduce) { .kw-dv-sheet { animation: none; } }
diff --git a/frontend/tests/devMode.test.mjs b/frontend/tests/devMode.test.mjs
new file mode 100644
index 00000000..bc22e1c9
--- /dev/null
+++ b/frontend/tests/devMode.test.mjs
@@ -0,0 +1,578 @@
+// 0.7 Dev mode, the frontend slice (Pixel): the switch's state machine (two presses, the 5 s re-cover,
+// Esc/blur, the settle that eats a double-click, reduced motion), the setup sheet's Repository field
+// (400 ms debounce, stale replies, every chip), the switch and the sheet in a DOM against the real
+// /api/spaces/:id/dev_mode client, Settings' Dev mode card, the Production mark and the Dev desk shell.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/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;
+
+// The server, as Lin's lin-dev-core routes answer (demo data only).
+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 };
+let server = { state: { ...off }, check: { state: 'found', repo: 'demo-org/demo-app', branch: 'main', deploy_hint: null }, fail: null, 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: server.fail.error }, server.fail.status);
+ if (u.endsWith('/dev_mode/check')) return json(server.check);
+ if (u.includes('/dev_mode')) {
+ if (method === 'PUT') server.state = { ...server.state, ...body, polled_at: body.on ? '2026-11-05T09:00:00Z' : server.state.polled_at };
+ return json(server.state);
+ }
+ if (u.includes('/production')) return json({ id: decodeURIComponent(u.split('/')[3]), production: body.production });
+ if (u.includes('/dev/landed')) return json({ cards: [], rollup: { count: 0, areas: [] }, last_tag: null, last_merge: null });
+ if (u.includes('/dev/reviews')) return json({ cards: [] });
+ return json({});
+};
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export * from './src/devMode';
+ export { DevModeSwitch, DevOffNote, DevBadge, HardHat } from './src/components/DevModeSwitch';
+ export { DevModeSetup } from './src/components/DevModeSetup';
+ export { DevModeSettings } from './src/components/DevModeSettings';
+ export { ConnectionRow } from './src/components/ConnectionsView';
+ export { canMarkProduction } from './src/connections';
+ export { DevDeskRow, DevDeskView, deskStore } from './src/components/DevDesk';
+ export { parseView, viewSegment } from './src/nav';
+`);
+const { React, createRoot } = m;
+const h = React.createElement;
+
+const settle = async (n = 10) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const reset = (state = off) => {
+ server = { state: { ...state }, check: { state: 'found', repo: 'demo-org/demo-app', branch: 'main', deploy_hint: null }, fail: null, calls: [] };
+ m.devStore._reset();
+ document.body.innerHTML = '';
+};
+
+const mount = async (el) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(el);
+ await settle();
+ return { host, root };
+};
+
+// ---------------------------------------------------------------------------
+// The state machine
+
+const R = (s, a) => m.switchReducer(s, a, 'Demo');
+
+test('two presses: the first lifts the cover, the second flips (set up already)', () => {
+ let s = m.initialSwitch({ setup: false });
+ s = R(s, { type: 'press', now: 1000 });
+ assert.equal(s.phase, 'lifted');
+ assert.equal(s.on, false);
+ assert.equal(s.announce.text, 'Unlocked. Press again to turn Dev mode on.');
+ assert.equal(m.switchLook(s).hint, 'Press again to turn Dev mode on');
+ s = R(s, { type: 'press', now: 1200 });
+ assert.equal(s.on, true);
+ assert.equal(s.saving, true);
+ assert.equal(s.phase, 'settling');
+ assert.equal(s.settleUntil, 1200 + m.SETTLE_MS);
+ assert.equal(s.announce.text, 'Dev mode on for Demo.');
+ assert.equal(m.switchLook(s).label, 'Dev mode, on. Press to unlock');
+});
+
+test('a double-click while it settles is ignored, and so is a press while saving', () => {
+ let s = m.initialSwitch({ setup: false });
+ s = R(R(s, { type: 'press', now: 0 }), { type: 'press', now: 100 });
+ const settling = s;
+ assert.equal(R(settling, { type: 'press', now: 150 }), settling, 'third press inside the settle');
+ s = R({ ...settling, saving: false }, { type: 'press', now: 300 });
+ assert.equal(s.phase, 'settling', 'still settling at 300 ms');
+ s = R({ ...settling, saving: false }, { type: 'settled', now: 100 + m.SETTLE_MS });
+ assert.equal(s.phase, 'covered');
+ assert.equal(R({ ...s, saving: true }, { type: 'press', now: 9999 }).phase, 'covered', 'a save in flight eats the press');
+ assert.equal(R({ ...s, saving: false }, { type: 'press', now: 9999 }).phase, 'lifted');
+});
+
+test('a lifted cover drops back after 5 s with nothing changed, not before', () => {
+ let s = R(m.initialSwitch({ on: true, setup: false }), { type: 'press', now: 1000 });
+ assert.equal(R(s, { type: 'recover', now: 1000 + m.RECOVER_MS - 1 }).phase, 'lifted');
+ s = R(s, { type: 'recover', now: 1000 + m.RECOVER_MS });
+ assert.equal(s.phase, 'covered');
+ assert.equal(s.on, true);
+ assert.equal(s.announce.text, 'Locked.');
+});
+
+test('Esc and blur drop a lifted cover; they do nothing when covered', () => {
+ const lifted = R(m.initialSwitch({ setup: false }), { type: 'press', now: 0 });
+ for (const type of ['escape', 'blur']) {
+ const s = R(lifted, { type });
+ assert.equal(s.phase, 'covered', type);
+ assert.equal(s.on, false, type);
+ }
+ const covered = m.initialSwitch();
+ assert.equal(R(covered, { type: 'escape' }), covered);
+ assert.equal(R(covered, { type: 'blur' }), covered);
+});
+
+test('reduced motion: still two presses, but nothing to settle, so the next press lifts at once', () => {
+ let s = m.initialSwitch({ setup: false, reduced: true });
+ s = R(s, { type: 'press', now: 0 });
+ assert.equal(s.phase, 'lifted');
+ s = R(s, { type: 'press', now: 10 });
+ assert.equal(s.on, true);
+ assert.equal(s.phase, 'covered');
+ assert.equal(s.settleUntil, 0);
+ s = R({ ...s, saving: false }, { type: 'press', now: 20 });
+ assert.equal(s.phase, 'lifted', 'one press lifts, never flips');
+ assert.equal(s.on, true);
+});
+
+test('first time: the second press opens the setup (pending, half-flipped); cancel covers, done flips on', () => {
+ let s = R(R(m.initialSwitch(), { type: 'press', now: 0 }), { type: 'press', now: 100 });
+ assert.equal(s.phase, 'pending');
+ assert.equal(s.on, false);
+ const look = m.switchLook(s);
+ assert.equal(look.fill, 0.45);
+ assert.equal(look.knobRight, true);
+ assert.equal(look.coverOpen, true);
+ assert.equal(R(s, { type: 'press', now: 200 }), s, 'presses wait for the sheet');
+ assert.equal(R(s, { type: 'setup_cancel' }).phase, 'covered');
+ assert.equal(R(s, { type: 'setup_cancel' }).on, false);
+ const done = R(s, { type: 'setup_done', now: 300 });
+ assert.equal(done.on, true);
+ assert.equal(done.setup, false);
+ assert.equal(done.phase, 'settling');
+});
+
+test('a failed save puts the switch back, covered, with the reason announced', () => {
+ let s = R(R(m.initialSwitch({ on: true, setup: false }), { type: 'press', now: 0 }), { type: 'press', now: 100 });
+ assert.equal(s.on, false);
+ s = R(s, { type: 'save_failed', error: 'Only the space owner can change Dev mode.' });
+ assert.equal(s.on, true);
+ assert.equal(s.phase, 'covered');
+ assert.equal(s.saving, false);
+ assert.equal(s.error, 'Only the space owner can change Dev mode.');
+ assert.equal(s.announce.text, 'Only the space owner can change Dev mode.');
+});
+
+test('the server changing Dev mode closes a held-open cover; a disabled switch says so', () => {
+ const lifted = R(m.initialSwitch({ setup: false }), { type: 'press', now: 0 });
+ const s = R(lifted, { type: 'server', state: { ...off, on: true, repo: 'demo-org/demo-app', polled_at: 'x' } });
+ assert.equal(s.on, true);
+ assert.equal(s.phase, 'covered');
+ const d = R(m.initialSwitch(), { type: 'server', state: null, disabled: true });
+ assert.equal(R(d, { type: 'press', now: 0 }), d);
+ assert.match(m.switchLook(d).label, /unavailable$/);
+ assert.equal(m.switchLook(d).tooltip, 'Only the space owner can change Dev mode');
+});
+
+// ---------------------------------------------------------------------------
+// Repository field
+
+test('normaliseRepo takes owner/name, URLs, SSH and repo sub-pages; refuses the rest', () => {
+ for (const [input, want] of [
+ ['demo-org/demo-app', 'demo-org/demo-app'],
+ [' https://github.com/demo-org/demo-app.git ', 'demo-org/demo-app'],
+ ['github.com/demo-org/demo-app/', 'demo-org/demo-app'],
+ ['[email protected]:demo-org/demo-app.git', 'demo-org/demo-app'],
+ ['https://www.github.com/demo-org/demo-app/pull/12', 'demo-org/demo-app'],
+ ['https://github.com/demo-org/demo-app/tree/main?x=1', 'demo-org/demo-app'],
+ ['demo-org', null],
+ ['', null],
+ ['demo org/app', null],
+ ['https://github.com/demo-org/demo-app/settings', null],
+ ['demo-org/..', null],
+ ])
+ assert.equal(m.normaliseRepo(input), want, input);
+});
+
+test('fieldView: each state has its chip, help and whether Turn on is allowed', () => {
+ const v = (s) => m.fieldView(s, 'demo-org/demo-app', 'GitHub is slow');
+ assert.equal(v('empty').chip, null);
+ assert.equal(v('empty').help, m.EMPTY_HELP);
+ assert.deepEqual(v('checking').chip, { tone: 'info', text: 'Checking', spinner: true });
+ assert.deepEqual(v('found').chip, { tone: 'ok', text: 'Found' });
+ assert.equal(v('found').canTurnOn, true);
+ assert.equal(v('not_found').chip.text, 'Can’t see it');
+ assert.equal(v('not_found').helpRepo, 'demo-org/demo-app');
+ assert.match(v('not_found').help, /\{repo\}/);
+ assert.equal(v('not_connected').connect, true);
+ assert.equal(v('invalid').chip.text, 'Not a repo');
+ assert.equal(v('error').help, 'GitHub is slow');
+ for (const s of ['empty', 'checking', 'not_found', 'not_connected', 'invalid', 'error']) assert.equal(v(s).canTurnOn, false, s);
+});
+
+const fakeTimers = () => {
+ let t = 0;
+ let id = 0;
+ const q = new Map();
+ return {
+ timers: { setTimeout: (f, ms) => (q.set(++id, { f, at: t + ms }), id), clearTimeout: (h) => q.delete(h) },
+ advance(ms) {
+ t += ms;
+ for (const [k, v] of [...q]) if (v.at <= t) (q.delete(k), v.f());
+ },
+ pending: () => q.size,
+ };
+};
+
+test('the checker waits 400 ms after the last keystroke, then asks once', async () => {
+ const asked = [];
+ const updates = [];
+ const ft = fakeTimers();
+ const c = m.createRepoChecker(async (r) => (asked.push(r), { state: 'found', repo: r, branch: 'main', deploy_hint: null }), (u) => updates.push(u.state), ft.timers);
+ c.input('demo-org/d');
+ ft.advance(200);
+ c.input('demo-org/de');
+ ft.advance(399);
+ c.input('demo-org/demo-app');
+ assert.deepEqual(asked, [], 'nothing asked while typing');
+ assert.equal(ft.pending(), 1);
+ ft.advance(m.CHECK_DEBOUNCE_MS - 1);
+ assert.deepEqual(asked, []);
+ ft.advance(1);
+ assert.deepEqual(asked, ['demo-org/demo-app']);
+ await settle();
+ assert.deepEqual(updates, ['checking', 'checking', 'checking', 'found']);
+});
+
+test('the checker: empty and invalid answer at once without asking; a stale reply is dropped', async () => {
+ const replies = [];
+ const updates = [];
+ const ft = fakeTimers();
+ const c = m.createRepoChecker((r) => new Promise((res) => replies.push(() => res({ state: r.endsWith('old') ? 'not_found' : 'found', repo: r, branch: null, deploy_hint: null }))), (u) => updates.push(u.state), ft.timers);
+ c.input('nope');
+ c.input('');
+ assert.deepEqual(updates, ['invalid', 'empty']);
+ assert.equal(ft.pending(), 0);
+ c.input('demo-org/old');
+ ft.advance(400);
+ c.input('demo-org/new');
+ ft.advance(400);
+ replies[1]();
+ await settle();
+ replies[0]();
+ await settle();
+ assert.equal(updates.at(-1), 'found', 'the old name’s late answer is ignored');
+ assert.equal(updates.filter((u) => u === 'not_found').length, 0);
+});
+
+// ---------------------------------------------------------------------------
+// In a DOM
+
+const switchEl = (host) => host.querySelector('[data-dev-switch]');
+const click = async (el) => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+
+test('DOM: on → off with two presses saves PUT {on:false}, announces, and calls onTurnedOff', async () => {
+ reset({ ...off, on: true, repo: 'demo-org/demo-app', branch: 'main', polled_at: '2026-11-05T08:00:00Z' });
+ let turnedOff = 0;
+ const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' }, onTurnedOff: () => turnedOff++ }));
+ const b = switchEl(host);
+ assert.equal(b.tagName, 'BUTTON');
+ assert.equal(b.getAttribute('role'), null, 'a button, not role=switch');
+ assert.equal(b.dataset.on, 'true');
+ assert.equal(b.getAttribute('aria-label'), 'Dev mode, on. Press to unlock');
+ await click(b);
+ assert.equal(b.dataset.devSwitch, 'lifted');
+ assert.equal(b.dataset.cover, 'open');
+ assert.equal(b.dataset.ring, 'true');
+ assert.match(host.querySelector('[data-dv-live]').textContent, /Unlocked\. Press again to turn Dev mode off\./);
+ assert.ok(host.querySelector('[data-dv-hint]'));
+ await click(b);
+ await click(b); // the double-click's third press: ignored while settling
+ assert.deepEqual(
+ server.calls.filter(([meth]) => meth === 'PUT').map(([, , body]) => body),
+ [{ on: false }],
+ );
+ assert.match(host.querySelector('[data-dv-live]').textContent, /Dev mode off for Demo/);
+ assert.equal(turnedOff, 1);
+ await wait(m.SETTLE_MS + 30);
+ assert.equal(b.dataset.devSwitch, 'covered');
+ assert.equal(b.dataset.on, undefined);
+ await click(b); // a render mid-save once left the switch stuck; the next press still lifts
+ assert.equal(b.dataset.devSwitch, 'lifted');
+ root.unmount();
+});
+
+test('DOM: Escape and blur drop a lifted cover without saving', async () => {
+ reset({ ...off, on: true, repo: 'demo-org/demo-app', polled_at: 'x' });
+ const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
+ const b = switchEl(host);
+ await click(b);
+ b.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ assert.equal(b.dataset.devSwitch, 'covered');
+ await click(b);
+ b.focus();
+ b.blur();
+ await settle();
+ assert.equal(b.dataset.devSwitch, 'covered');
+ assert.equal(server.calls.filter(([meth]) => meth === 'PUT').length, 0);
+ root.unmount();
+});
+
+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);
+ root.unmount();
+});
+
+test('DOM: reduced motion shows the Dev label and the lock glyph, and opens with no settle', async () => {
+ reset({ ...off, on: false, repo: 'demo-org/demo-app', polled_at: 'x' });
+ window.matchMedia = (q) => ({ matches: q.includes('reduce'), media: q, addEventListener() {}, removeEventListener() {} });
+ 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-glyph="locked"]'));
+ await click(b);
+ assert.ok(b.querySelector('[data-dv-glyph="unlocked"]'));
+ await click(b);
+ assert.equal(b.dataset.devSwitch, 'covered');
+ assert.equal(b.dataset.on, 'true');
+ await wait(30); // the save comes back; presses wait for it, motion or not
+ await settle();
+ await click(b);
+ assert.equal(b.dataset.devSwitch, 'lifted', 'the next press lifts at once: nothing to settle');
+ root.unmount();
+ delete window.matchMedia;
+});
+
+test('DOM: first switch-on opens the setup sheet; typing checks after 400 ms; Turn on sends repo and branch', async () => {
+ reset();
+ server.check = { state: 'found', repo: 'demo-org/demo-app', branch: 'trunk', deploy_hint: null };
+ const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
+ const b = switchEl(host);
+ await click(b);
+ await click(b);
+ assert.equal(b.dataset.devSwitch, 'pending');
+ const dialog = document.querySelector('[role="dialog"]');
+ assert.equal(dialog.getAttribute('aria-modal'), 'true');
+ assert.match(dialog.textContent, /Which repo is this space about\?/);
+ assert.doesNotMatch(dialog.textContent, /Ready to ship/);
+ const turnOn = dialog.querySelector('[data-dv-turn-on]');
+ assert.equal(turnOn.disabled, true);
+ const input = dialog.querySelector('#dv-repo');
+ const type = async (v) => {
+ const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
+ set.call(input, v);
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+ };
+ await type('demo-org');
+ assert.equal(dialog.querySelector('[data-dv-chip]').dataset.dvChip, 'invalid');
+ await type('https://github.com/demo-org/demo-app');
+ assert.equal(dialog.querySelector('[data-dv-chip]').dataset.dvChip, 'checking');
+ await wait(200);
+ assert.equal(server.calls.filter(([, u]) => u.endsWith('/check')).length, 0, 'not before 400 ms');
+ await wait(260);
+ await settle();
+ assert.deepEqual(server.calls.filter(([, u]) => u.endsWith('/check')).map(([, , body]) => body), [{ repo: 'demo-org/demo-app' }]);
+ assert.equal(dialog.querySelector('[data-dv-chip]').dataset.dvChip, 'found');
+ assert.match(dialog.querySelector('[data-dv-tiles]').textContent, /trunk/);
+ assert.equal(turnOn.disabled, false);
+ await click(turnOn);
+ assert.deepEqual(server.calls.filter(([meth]) => meth === 'PUT').map(([, , body]) => body), [{ on: true, repo: 'demo-org/demo-app', branch: 'trunk' }]);
+ assert.equal(document.querySelector('[role="dialog"]'), null);
+ assert.equal(b.dataset.on, 'true');
+ root.unmount();
+});
+
+test('DOM: the setup sheet’s chips for not found and not connected, and Esc cancels', async () => {
+ reset();
+ let cancelled = 0;
+ for (const [state, chip, text] of [
+ ['not_found', 'not_found', /Bots can’t see demo-org\/demo-app with your GitHub connection/],
+ ['not_connected', 'not_connected', /Connect GitHub to read this repo/],
+ ]) {
+ const { root } = await mount(
+ h(m.DevModeSetup, {
+ space: { id: 'spc_demo', name: 'Demo' },
+ initial: { ...off, repo: 'demo-org/demo-app' },
+ onCancel: () => cancelled++,
+ onDone: () => {},
+ onOpenConnections: () => {},
+ check: async (r) => ({ state, repo: r, branch: null, deploy_hint: null }),
+ }),
+ );
+ await wait(450);
+ await settle();
+ const d = document.querySelector('[role="dialog"]');
+ assert.equal(d.querySelector('[data-dv-chip]').dataset.dvChip, chip);
+ assert.match(d.querySelector('#dv-repo-help').textContent, text);
+ assert.equal(d.querySelector('[data-dv-turn-on]').disabled, true);
+ if (state === 'not_connected') assert.match(d.textContent, /Connect GitHub/);
+ d.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ root.unmount();
+ document.body.innerHTML = '';
+ }
+ assert.equal(cancelled, 2);
+});
+
+test('DOM: a failed Turn on keeps the sheet open with the server’s reason', async () => {
+ reset();
+ const { root } = await mount(
+ h(m.DevModeSetup, {
+ space: { id: 'spc_demo', name: 'Demo' },
+ initial: { ...off, repo: 'demo-org/demo-app' },
+ onCancel: () => {},
+ onDone: () => assert.fail('not done'),
+ check: async (r) => ({ state: 'found', repo: r, branch: 'main', deploy_hint: null }),
+ save: async () => {
+ throw new Error('GitHub didn’t answer. Try again in a minute.');
+ },
+ }),
+ );
+ await wait(450);
+ await settle();
+ await click(document.querySelector('[data-dv-turn-on]'));
+ assert.match(document.querySelector('[role="alert"]').textContent, /GitHub didn’t answer/);
+ assert.ok(document.querySelector('[role="dialog"]'));
+ root.unmount();
+});
+
+// ---------------------------------------------------------------------------
+// Settings, Connections, the desk, the looks
+
+test('Settings › Dev mode: hidden before the first switch-on; saves repo, branch, backup command; Turn off', async () => {
+ reset();
+ let v = await mount(h(m.DevModeSettings, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ assert.equal(v.host.querySelector('[data-dev-settings]'), null);
+ v.root.unmount();
+
+ reset({ ...off, on: true, repo: 'demo-org/demo-app', branch: 'main', polled_at: 'x' });
+ v = await mount(h(m.DevModeSettings, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ const form = v.host.querySelector('[data-dev-settings]');
+ assert.ok(form);
+ assert.equal(form.querySelector('#dv-set-repo').value, 'demo-org/demo-app');
+ const save = form.querySelector('button[type="submit"]');
+ assert.equal(save.disabled, true, 'nothing changed yet');
+ const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
+ const input = form.querySelector('#dv-set-backup');
+ set.call(input, './scripts/backup.sh');
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+ assert.equal(save.disabled, false);
+ form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.deepEqual(server.calls.filter(([meth]) => meth === 'PUT').map(([, , b]) => b), [{ on: true, repo: 'demo-org/demo-app', branch: 'main', backup_command: './scripts/backup.sh' }]);
+ assert.match(form.textContent, /Saved/);
+ await click(form.querySelector('[data-dev-turn-off]'));
+ assert.deepEqual(server.calls.filter(([meth]) => meth === 'PUT').at(-1)[2], { on: false });
+ assert.equal(m.devStore.isOn('spc_demo'), false);
+ assert.match(form.textContent, /Off\. Reviews, the ship gate and the production floor are stopped/);
+ v.root.unmount();
+});
+
+test('Production mark: only MCP servers and Composio apps, and only when asked for', () => {
+ assert.equal(m.canMarkProduction({ id: 'mcp:demo-db' }), true);
+ assert.equal(m.canMarkProduction({ id: 'composio:github' }), true);
+ assert.equal(m.canMarkProduction({ id: 'composio:Bad Slug' }), false);
+ assert.equal(m.canMarkProduction({ id: 'engine:claude' }), false);
+ const c = { id: 'mcp:demo-db', kind: 'mcp', name: 'Demo DB', detail: null, status: 'ok', status_detail: null, last_check: null, used_by: [], logins_stored: 'vault', manage: '', production: true };
+ const without = m.renderToStaticMarkup(h(m.ConnectionRow, { c, now: 0 }));
+ assert.doesNotMatch(without, /data-production-toggle/);
+ assert.match(without, /data-production-badge/);
+ const withMark = m.renderToStaticMarkup(h(m.ConnectionRow, { c, now: 0, onProduction: () => {} }));
+ assert.match(withMark, /data-production-toggle="mcp:demo-db"/);
+ assert.match(withMark, /aria-label="Demo DB is production"/);
+ assert.match(withMark, /checked=""/);
+});
+
+test('looks: the hard hat, the </> badge, and the turned-off note', () => {
+ const hat = m.renderToStaticMarkup(h(m.HardHat));
+ assert.match(hat, /title="Working under Dev mode rules"/);
+ assert.match(hat, /<svg width="10" height="8"/);
+ assert.match(m.renderToStaticMarkup(h(m.DevBadge, { behind: 'var(--kw-surface-side)' })), /&lt;\/&gt;.*kw-dev-caret/);
+ const note = m.renderToStaticMarkup(h(m.DevOffNote, { approvals: 'smart', onDismiss: () => {} }));
+ assert.match(note, /role="status"/);
+ assert.match(note, /Dev mode is off\./);
+});
+
+test('nav: /dev is the Dev desk', () => {
+ assert.deepEqual(m.parseView('dev')?.view, { kind: 'dev' });
+ assert.equal(m.viewSegment({ kind: 'dev' }), 'dev');
+});
+
+test('Dev desk: empty What landed, then the Reviews tab by keyboard', async () => {
+ reset({ ...off, on: true, repo: 'demo-org/demo-app', polled_at: 'x' });
+ m.deskStore._reset();
+ const { host, root } = await mount(h(m.DevDeskView, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ await settle(20);
+ const tabs = [...host.querySelectorAll('[role="tab"]')];
+ assert.deepEqual(tabs.map((t) => t.textContent.replace(/\d+/g, '').trim()), ['What landed', 'Reviews']);
+ assert.equal(tabs[0].getAttribute('aria-selected'), 'true');
+ assert.doesNotMatch(host.textContent, /Loading/);
+ tabs[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+ await settle();
+ const now = [...host.querySelectorAll('[role="tab"]')];
+ assert.equal(now[1].getAttribute('aria-selected'), 'true');
+ assert.equal(document.activeElement, now[1]);
+ root.unmount();
+});
+
+// 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 () => {
+ 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 }));
+ 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');
+ root.unmount();
+});
+
+test('round 2: the setup footer is sticky, says nothing is posted, and its buttons are 44 px on phone', async () => {
+ reset();
+ const { host, root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
+ const b = switchEl(host);
+ await click(b);
+ await click(b);
+ const footer = document.querySelector('[data-dv-setup-footer]');
+ assert.ok(footer.classList.contains('sticky') && footer.classList.contains('bottom-0'));
+ assert.ok(footer.classList.contains('pb-[max(16px,env(safe-area-inset-bottom))]'));
+ assert.match(footer.textContent, /Only you can turn this on or off\. Nothing is posted to GitHub\./);
+ assert.doesNotMatch(document.body.textContent, /without asking/);
+ for (const btn of footer.querySelectorAll('button')) assert.ok(btn.classList.contains('min-h-[44px]'), btn.textContent);
+ root.unmount();
+});
+
+test('round 2: the Dev desk header shows the repo chip and when it was checked; tabs are 44 px on phone', async () => {
+ reset();
+ m.devStore.set('spc_demo', { ...off, on: true, repo: 'demo-org/demo-app', branch: 'trunk' });
+ m.deskStore._reset();
+ const { host, root } = await mount(h(m.DevDeskView, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ await settle(20);
+ const chip = host.querySelector('[data-dev-repo-chip]');
+ assert.equal(chip.textContent, 'demo-org/demo-app · trunk');
+ assert.ok(chip.classList.contains('hidden') && chip.classList.contains('sm:inline-flex'), 'chip hides at 390');
+ assert.match(host.querySelector('[data-dev-checked]').textContent, /^Checked \d\d:\d\d$/);
+ for (const t of host.querySelectorAll('[role="tab"]')) assert.ok(t.classList.contains('min-h-[44px]'));
+ root.unmount();
+ m.devStore.set('spc_demo', { ...off, on: true, repo: null });
+ m.deskStore._reset();
+ const again = await mount(h(m.DevDeskView, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ await settle(20);
+ assert.equal(again.host.querySelector('[data-dev-repo-chip]'), null, 'no repo known: no chip');
+ again.root.unmount();
+});