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.1: Dev mode turns on with no setup dialog; the Dev desk says what it found (flow F3–F10) (#344)

Oleksandr Ivanchenko1e0223f386b3
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index cf16ae8a..000b6a89 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -130,7 +130,7 @@ 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 { devApi, devConnect, 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';
@@ -370,6 +370,27 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
const isPhoneRef = useRef(isPhone);
isPhoneRef.current = isPhone;
+ // Dev mode Connect (flow F5): Loose ends opens on the GitHub form; once a GitHub source is added
+ // the person lands back on the Dev desk, which reads Dev mode again.
+ const [devConnecting, setDevConnecting] = useState(0);
+ const connectDevGitHub = () => {
+ if (!devConnect.pending()) devConnect.start(space.id);
+ setDevConnecting((n) => n + 1);
+ showPage('inbox', 'loose');
+ };
+ const devGitHubAdded = () => {
+ const back = devConnect.finish();
+ setDevConnecting(0);
+ if (!back) return;
+ devApi.get(back).then((st) => devStore.set(back, st), () => undefined);
+ if (back === space.id) showPage('dev');
+ };
+ // Leaving Loose ends without connecting drops the trip back.
+ useEffect(() => {
+ if (page === 'inbox' || !devConnecting) return;
+ setDevConnecting(0);
+ devConnect.cancel();
+ }, [page, devConnecting]);
// Idea jar (0.7): the ready-takes badge, Open on board's mission, the drop toast and the
// app-wide live region (a take is announced on any screen; the open jar announces its own).
const ideaJarCount = useIdeaJarBadge(space.id);
@@ -3235,6 +3256,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
showPage('dev');
playSfx('click');
}}
+ onConnectDevGitHub={connectDevGitHub}
ideaJarCount={ideaJarCount}
ideaJarActive={page === 'jar'}
onOpenIdeaJar={() => {
@@ -3299,7 +3321,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onOpenedMissionId={() => setPendingMissionId(null)}
/>
);
- const loose = <LooseEndsPage onOpenChat={openThread} />;
+ const loose = (
+ <LooseEndsPage
+ key={devConnecting ? `dev-connect-${devConnecting}` : 'loose'}
+ onOpenChat={openThread}
+ connectGitHub={devConnecting > 0}
+ onGitHubAdded={devGitHubAdded}
+ />
+ );
const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={awayCount} onBack={backToList} newPage={away} loosePage={loose} />;
const chat = (
<ChatView
@@ -3465,7 +3494,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}}
/>
);
- const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} />;
+ const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} onOpenLooseEnds={connectDevGitHub} />;
const mainPane = needsSetup ? setupChecklist : page === 'parallel' ? parallel : page === 'board' && missionBoard ? missionsPage : page === 'dev' && devOn ? devDeskPage : page === 'jar' ? jarPage : page === 'inbox' ? inbox : !loaded ? (
<main className="flex-1 flex items-center justify-center text-xs text-zinc-500">
<Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…
diff --git a/frontend/src/components/DevDesk.tsx b/frontend/src/components/DevDesk.tsx
index 5762ee69..be3dfc0d 100644
--- a/frontend/src/components/DevDesk.tsx
+++ b/frontend/src/components/DevDesk.tsx
@@ -4,10 +4,11 @@
import React, { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
import { ChevronLeft, Code, Loader2, RefreshCw } from 'lucide-react';
-import { devApi, deskStatus } from '../devMode';
+import { DevModeState, devApi, devStore, deskStatus, firstRun } from '../devMode';
import { FindingAction, LandedPage, ShellCard, asCard, parseCards, parseLandedPage } from '../dev/shellTypes';
import { LandedList, ReleaseNotesSheet, ReviewCard, Rollup } from './DevDeskSlots';
import { useDevMode } from './DevModeSwitch';
+import { DevStatusLine } from './DevStatusLine';
/** 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';
@@ -91,37 +92,71 @@ export function useDesk(space: string, on: boolean): DeskData {
export const openReviews = (reviews: ShellCard[] | null) => (reviews ?? []).filter((c) => c.status !== 'stale').length;
+/** The Dev desk row badge (flow F6): new review cards from the server, else the open reviews. */
+export const rowBadge = (dev: DevModeState | null, openReviewCount: number): number => dev?.new_reviews ?? openReviewCount;
+
+/** Flow F4: while the first poll reads the last merges, the desk shows still placeholder cards. */
+export const firstPolling = (dev: DevModeState | null, landedCount: number): boolean =>
+ !!dev?.on && dev.status === 'watching' && !dev.polled_at && landedCount === 0;
+
// ---------------------------------------------------------------------------
// 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 dev = useDevMode(spaceId);
const landed = desk.landed?.rollup?.count ?? 0;
const reviews = openReviews(desk.reviews);
- const count = landed + reviews;
+ // Flow F6: the badge is review cards new since the desk was last opened (the server keeps "seen",
+ // so phone and desktop agree). Landed cards are news, not needs; floor approvals stay in the chat.
+ // An older server without new_reviews falls back to the open reviews.
+ const count = rowBadge(dev, reviews);
+ // Flow F4: one soft highlight the first time the row appears in this space; never again, never looping.
+ const [fresh] = useState(() => !firstRun.rowSeen(spaceId));
+ useEffect(() => {
+ firstRun.claimRow(spaceId);
+ }, [spaceId]);
+ // Flow copy §4: one 160 ms pop when the count goes up, never when it goes down.
+ const prev = useRef(count);
+ const [pop, setPop] = useState(0);
+ useEffect(() => {
+ if (count > prev.current) setPop((n) => n + 1);
+ prev.current = count;
+ }, [count]);
+ const name = count > 0 ? `Dev desk, ${count} new ${count === 1 ? 'review' : 'reviews'}` : undefined;
return (
<button
type="button"
onClick={onOpen}
aria-current={active ? 'page' : undefined}
+ aria-label={name}
data-dev-desk-row
- className={
+ data-dev-row-fresh={fresh || undefined}
+ 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'}`
- }
+ }${fresh ? ' kw-dv-row-fresh' : ''}`}
>
<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-body font-medium truncate">
+ Dev desk<span className="sr-only">, </span>
+ </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
+ key={pop}
+ className={`kw-dv-row-badge shrink-0${pop ? ' kw-dv-row-badge-pop' : ''}`}
+ aria-hidden="true"
+ title={`${count === 1 ? '1 new review' : `${count} new reviews`} to look at`}
+ data-dev-row-badge
+ >
+ {count > 9 ? '9+' : count}
</span>
)}
</button>
@@ -141,12 +176,27 @@ export interface DevDeskViewProps {
onSaveToNotion?: (markdown: string) => Promise<void>;
initialTab?: Tab;
now?: number;
+ /** Opens Loose ends, for the status line's Connect. */
+ onOpenLooseEnds?: () => void;
}
-export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, onBack, onSaveToNotion, initialTab = 'landed', now }) => {
+export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds }) => {
const desk = useDesk(spaceId, true);
const dev = useDevMode(spaceId);
const [tab, setTab] = useState<Tab>(initialTab);
+ // Flow F6: opening the desk clears the row badge on every device.
+ useEffect(() => {
+ const s = devStore.get(spaceId);
+ if (s?.new_reviews) devStore.set(spaceId, { ...s, new_reviews: 0 });
+ devApi.deskSeen(spaceId).catch(() => undefined);
+ }, [spaceId]);
+ // Flow F4: what Dev mode does, on the first visit only; it can be closed and stays gone.
+ const [intro, setIntro] = useState(() => !firstRun.introSeen(spaceId));
+ // Flow copy §6: on the first visit the empty states speak in git terms and never say "Nothing has landed yet".
+ const [firstVisit] = useState(() => !firstRun.introSeen(spaceId));
+ useEffect(() => {
+ firstRun.claimIntro(spaceId);
+ }, [spaceId]);
const [marking, setMarking] = useState(false);
const [notes, setNotes] = useState<ShellCard | null>(null);
const [notesError, setNotesError] = useState<string | null>(null);
@@ -261,6 +311,7 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, on
const unseen = landed?.rollup?.count ?? 0;
const open = openReviews(desk.reviews);
const first = !landed && !desk.reviews;
+ const polling = firstPolling(dev, landedCards.length);
const tabs: Array<{ key: Tab; label: string; count: number }> = [
{ key: 'landed', label: 'What landed', count: unseen },
@@ -287,7 +338,7 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, on
<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 && (
+ {dev?.repo && !dev.status && (
<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>
@@ -311,6 +362,10 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, on
<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">
+ <DevStatusLine spaceId={spaceId} state={dev} onConnect={onOpenLooseEnds} />
+ {intro && dev?.on && (
+ <DevIntro repo={(dev.status ?? (dev.repo ? 'watching' : 'no_repo')) === 'watching' ? dev.repo : null} onClose={() => setIntro(false)} />
+ )}
<div role="tablist" aria-label="Dev desk" className="flex gap-1">
{tabs.map((t, i) => {
const on = t.key === tab;
@@ -350,14 +405,16 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, on
)}
<div ref={panelRef} role="tabpanel" id={`${tabsId}-panel`} aria-labelledby={`${tabsId}-${tab}`} className="space-y-3">
- {first && desk.loading ? (
+ {tab === 'landed' && polling ? (
+ <SkeletonCards />
+ ) : 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 && (
+ {landed?.rollup && landedCards.length > 0 && (
<Rollup
rollup={landed.rollup}
last_tag={landed.last_tag}
@@ -372,10 +429,17 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, on
)}
{landedCards.length ? (
<LandedList cards={landedCards} reviews={reviews} now={now} onOpenReview={openReview} forge={dev?.forge ?? null} />
+ ) : dev?.status === 'not_connected' ? (
+ <TermEmpty out="(needs a GitHub connection)" title="Connect GitHub to see what landed." line="The last 5 merges show up here right after." />
+ ) : dev?.status === 'no_repo' ? (
+ <TermEmpty out="(no repo yet)" title="Cards show up once there’s a repo." line="The production floor already works." />
) : (
- landed && (
+ landed &&
+ (firstVisit ? (
+ <TermEmpty out="(no merges yet)" title="No merges on main yet." line="They show up here as short cards in plain words." />
+ ) : (
<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 ? (
@@ -409,9 +473,89 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, spaceName, on
);
};
+/** Still placeholders (no shimmer, style v2 §9) while the first poll reads the last 5 merges. */
+const SkeletonCards: React.FC = () => (
+ <div data-dev-skeleton>
+ <p role="status" className="flex items-center gap-2 pb-1 font-mono text-[12px] text-zinc-300">
+ <span className="dv-led" data-s="run" aria-hidden="true" />
+ Reading the last 5 merges…<span className="kw-dv-intro-caret" aria-hidden="true" />
+ </p>
+ <div className="space-y-3" aria-hidden="true">
+ {[0, 1, 2].map((i) => (
+ <div key={i} className="kw-dv-skel rounded-2xl border border-hairline px-4 py-3.5">
+ <div className="flex items-center gap-2">
+ <span className="kw-dv-skel-bar w-12 h-3" />
+ <span className="kw-dv-skel-bar w-20 h-3" />
+ </div>
+ <span className="kw-dv-skel-bar block mt-3 h-3.5" style={{ width: `${78 - i * 12}%` }} />
+ <span className="kw-dv-skel-bar block mt-2 h-3" style={{ width: `${56 - i * 8}%` }} />
+ </div>
+ ))}
+ </div>
+ </div>
+);
+
+/** Flow copy §6: a first-visit empty state as a tiny terminal, `$ git log main -5` and its output. */
+const TermEmpty: React.FC<{ out: string; title: string; line: string }> = ({ out, title, line }) => (
+ <div className="rounded-2xl border border-dashed border-hairline-strong px-5 py-6" data-dev-empty data-dev-empty-term>
+ <p className="font-mono text-[12px] text-zinc-500" aria-hidden="true">
+ <span className="text-sky-300">$</span> git log main -5
+ <br />
+ {out}
+ <span className="kw-dv-intro-caret" />
+ </p>
+ <p className="mt-3 text-body font-medium text-zinc-200">{title}</p>
+ <p className="mt-1 text-meta text-zinc-400">{line}</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>
);
+
+// ---------------------------------------------------------------------------
+// First run (flow copy §5): a terminal-style block above the cards on the first visit only. Got it hides
+// it for good; it is the only control.
+
+export const DEV_FEATURES = [
+ { key: 'landed', n: '01', title: 'What landed.', line: 'Every merge to main in plain words, and when main is ready to ship.' },
+ { key: 'reviews', n: '02', title: 'Reviews.', line: 'A second bot reads each pull request before you merge it.' },
+ { key: 'floor', n: '03', title: 'Production floor.', line: 'Deploys and live-database commands wait for your OK.' },
+] as const;
+
+const DevIntro: React.FC<{ repo: string | null; onClose: () => void }> = ({ repo, onClose }) => (
+ <section className="kw-dv-intro relative" aria-labelledby="dv-intro-h" data-dev-intro>
+ <p className="font-mono text-[11px] leading-relaxed text-zinc-500" aria-hidden="true">
+ <span className="text-sky-300">$</span> dev --on
+ <br />
+ <span className="text-sky-300">HEAD → dev</span> · {repo ? `watching ${repo}` : 'guards up'}
+ <span className="kw-dv-intro-caret" />
+ </p>
+ <h3 id="dv-intro-h" className="mt-2 text-body font-semibold text-zinc-100">
+ Here’s what Dev mode does
+ </h3>
+ <ol className="mt-2.5 flex flex-col gap-2">
+ {DEV_FEATURES.map((f) => (
+ <li key={f.key} className="flex items-baseline gap-2.5 text-meta" data-dev-feature={f.key}>
+ <span className="font-mono text-[11px] font-semibold text-sky-300" aria-hidden="true">
+ {f.n}
+ </span>
+ <span className="min-w-0 flex-1 text-zinc-400">
+ <strong className="font-semibold text-zinc-100">{f.title}</strong> {f.line}
+ </span>
+ </li>
+ ))}
+ </ol>
+ <button
+ type="button"
+ onClick={onClose}
+ data-dev-intro-close
+ className={`mt-2.5 -ml-2 inline-flex items-center min-h-[44px] sm:min-h-[32px] px-2 rounded-lg text-meta font-semibold text-zinc-200 hover:bg-white/5 ${focusRing}`}
+ >
+ Got it
+ </button>
+ </section>
+);
diff --git a/frontend/src/components/DevModeSwitch.tsx b/frontend/src/components/DevModeSwitch.tsx
index 8aad5d43..0d89d761 100644
--- a/frontend/src/components/DevModeSwitch.tsx
+++ b/frontend/src/components/DevModeSwitch.tsx
@@ -2,12 +2,12 @@
// Off has no cover: one press turns it on (F1). On is covered by a 1 px violet ring and a lock; turning
// it off takes two presses (F2): press 1 arms (2 px amber ring, open lock, `off?`), press 2 within 5 s
// turns it off. Armed drops back after 5 s, on Esc or when focus leaves. Presses are ignored while a
-// flip settles (450 ms), so a double-click on Off can't turn it on and arm it.
+// flip settles (450 ms), so a double-click on Off can't turn it on and arm it. 0.7.1 (any-git S5):
+// there is no setup sheet; the server finds the repo and the Dev desk says what it found.
import React, { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
import { Lock, LockOpen, X } from 'lucide-react';
import {
- DROP_MS,
RECOVER_MS,
SwitchAction,
SwitchState,
@@ -17,11 +17,9 @@ import {
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;
@@ -53,19 +51,45 @@ export interface DevModeSwitchProps {
phone?: boolean;
/** Dev mode went off: the sidebar shows the turned-off note. */
onTurnedOff?: () => void;
- /** Dev mode went on: the sidebar shows the HEAD → dev note. */
- onTurnedOn?: () => void;
+ /** The person turned it on here (flow F3): the sidebar shows the toast. Never for a space already on. */
+ onTurnedOn?: (s: DevModeState) => void;
/** Test hooks: start in a given state, and a clock. */
initial?: Partial<SwitchState>;
now?: () => number;
}
+/** The last on/off seen per space, kept in this browser only (no repo, no token): the switch's first frame. */
+export const lastOn = {
+ key: (space: string) => `kw-dev-on:${space}`,
+ /** null: never seen here (a fresh browser), so the switch waits for the server instead of guessing. */
+ get(space: string): boolean | null {
+ try {
+ const v = localStorage.getItem(lastOn.key(space));
+ return v === '1' ? true : v === '0' ? false : null;
+ } catch {
+ return null;
+ }
+ },
+ set(space: string, on: boolean) {
+ try {
+ localStorage.setItem(lastOn.key(space), on ? '1' : '0');
+ } catch {
+ /* private mode: the switch waits for the server on each load */
+ }
+ },
+};
+
export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = false, onTurnedOff, onTurnedOn, initial, now = Date.now }) => {
const reduced = useReducedMotion();
const known = useDevMode(space.id);
+ // Until this space's state loads, start from the last value seen here, so a space that is on doesn't
+ // show "off" for a moment on every load.
const [state, setState] = useState<SwitchState>(() =>
- initialSwitch({ reduced, ...(known ? { on: known.on, setup: needsSetup(known) } : {}), ...initial }),
+ initialSwitch({ reduced, ...(known ? { on: known.on } : lastOn.get(space.id) ? { on: true } : {}), ...initial }),
);
+ // Never seen here and not loaded yet: neither on nor off (no node on the graph, busy) until dev_mode
+ // answers, so an on space never reads "off" for a moment (QA F8-R3-1).
+ const [loading, setLoading] = useState(() => !known && !initial && lastOn.get(space.id) === null);
// The 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);
@@ -93,6 +117,7 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
},
(e: unknown) => {
if (!live) return;
+ setLoading(false);
dispatch({ type: 'server', state: null, disabled: e instanceof DevModeError && (e.status === 403 || e.status === 404) });
},
);
@@ -103,8 +128,11 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
// The store changes (the load above, SSE, Settings): follow it.
useEffect(() => {
- if (known) dispatch({ type: 'server', state: known });
- }, [known, dispatch]);
+ if (!known) return;
+ setLoading(false);
+ dispatch({ type: 'server', state: known });
+ lastOn.set(space.id, known.on);
+ }, [known, dispatch, space.id]);
// A lifted cover drops back after 5 s; a flip settles at 450 ms.
useEffect(() => {
@@ -127,7 +155,7 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
devStore.set(space.id, s);
dispatch({ type: 'saved', on: s.on });
if (!s.on && was?.on) onTurnedOff?.();
- if (s.on && !was?.on) onTurnedOn?.();
+ if (s.on && on && !was?.on) onTurnedOn?.(s);
},
(e: unknown) => dispatch({ type: 'save_failed', error: e instanceof Error ? e.message : 'Dev mode couldn’t be changed.' }),
);
@@ -170,13 +198,14 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
}
},
onBlur: () => dispatch({ type: 'blur' }),
- disabled: state.disabled,
+ disabled: state.disabled || loading,
+ 'aria-busy': loading || undefined,
role: 'switch' as const,
'aria-checked': state.on,
'aria-label': look.label,
'aria-describedby': descId,
title: look.tooltip,
- 'data-dev-switch': state.phase,
+ 'data-dev-switch': loading ? 'loading' : state.phase,
'data-look': look.look,
'data-on': state.on || undefined,
'data-ring': look.ring || undefined,
@@ -206,7 +235,7 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
<svg className="kw-dv-graph" viewBox="0 0 44 24" aria-hidden="true" data-dv-graph>
<path className="kw-dv-base" d="M2 17H42" />
<path className="kw-dv-fork" d="M12 17C19 17 18 7 26 7H42" />
- <g className="kw-dv-node">
+ <g className="kw-dv-node" visibility={loading ? 'hidden' : undefined}>
<circle className="kw-dv-halo" cx="12" cy="17" r="5" />
<circle className="kw-dv-dot" cx="12" cy="17" r="5" />
<circle className="kw-dv-pip" cx="12" cy="17" r="1.6" />
@@ -230,45 +259,80 @@ export const DevModeSwitch: React.FC<DevModeSwitchProps> = ({ space, phone = fal
{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 });
- if (s.on) onTurnedOn?.();
- btn.current?.focus();
- }}
- />
- )}
</span>
);
};
/**
- * The flip note under the space header (style v2 §10): on reads `HEAD → dev` + "Dev mode is on for
- * {space}." with one caret blink; off reads `merged into main` + "Dev mode is off. Approvals stay on
- * {approvals}." role=status, 10 s or until dismissed.
+ * The flip note under the space header (style v2 §10). On reads `HEAD → dev` + "Dev mode is on for
+ * {space}." (the autodetect build shows the on toast instead). Off (flow copy §7) reads `HEAD → main`
+ * + the 0.7.0 text, with Turn back on (F8), one press. role=status, 10 s or until dismissed; the
+ * timer pauses while the pointer is over it or focus is inside it.
*/
-export const DevFlipNote: React.FC<{ on: boolean; space?: string; approvals?: string; onDismiss: () => void; ms?: number }> = ({ on, space, approvals, onDismiss, ms = 10_000 }) => {
+export const DevFlipNote: React.FC<{ on: boolean; space?: string; approvals?: string; onDismiss: () => void; ms?: number; onTurnBackOn?: () => Promise<unknown> }> = ({
+ on,
+ space,
+ approvals,
+ onDismiss,
+ ms = 10_000,
+ onTurnBackOn,
+}) => {
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [held, setHeld] = useState(false);
useEffect(() => {
+ if (busy || error || held) return undefined;
const t = setTimeout(onDismiss, ms);
return () => clearTimeout(t);
- }, [onDismiss, ms]);
+ }, [onDismiss, ms, busy, error, held]);
+ const back = () => {
+ if (!onTurnBackOn || busy) return;
+ setBusy(true);
+ setError(null);
+ onTurnBackOn().then(onDismiss, (e: unknown) => {
+ setBusy(false);
+ setError(e instanceof Error ? e.message : 'Dev mode couldn’t be turned back on.');
+ });
+ };
return (
- <div role="status" data-dev-flip-note={on ? 'on' : 'off'} {...(on ? {} : { 'data-dev-off-note': '' })} className="kw-dv-note mt-1.5 flex items-start gap-2 rounded-xl border border-white/14 bg-surface-overlay px-2.5 py-2 text-meta text-zinc-200 shadow-raised">
- <p className="min-w-0 flex-1 leading-snug">
- <span className="font-mono font-semibold text-sky-300 whitespace-nowrap">{on ? 'HEAD → dev' : 'merged into main'}</span>
- {on && <span className="dv-caret" aria-hidden="true" />}{' '}
- {on ? `Dev mode is on for ${space ?? 'this space'}.` : `Dev mode is off. Approvals stay on ${approvalsWord(approvals)}.`}
- </p>
+ <div
+ role="status"
+ data-dev-flip-note={on ? 'on' : 'off'}
+ {...(on ? {} : { 'data-dev-off-note': '' })}
+ onPointerEnter={() => setHeld(true)}
+ onPointerLeave={() => setHeld(false)}
+ onFocus={() => setHeld(true)}
+ onBlur={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setHeld(false);
+ }}
+ className="kw-dv-note mt-1.5 flex items-start gap-2 rounded-xl border border-white/14 bg-surface-overlay px-2.5 py-2 text-meta text-zinc-200 shadow-raised"
+ >
+ <div className="min-w-0 flex-1 leading-snug">
+ <p>
+ <span className="font-mono font-semibold text-sky-300 whitespace-nowrap">{on ? 'HEAD → dev' : 'HEAD → main'}</span>
+ {on && <span className="dv-caret" aria-hidden="true" />}{' '}
+ {on ? (
+ `Dev mode is on for ${space ?? 'this space'}.`
+ ) : (
+ <>
+ <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>
+ {!on && onTurnBackOn && (
+ <button
+ type="button"
+ onClick={back}
+ aria-disabled={busy || undefined}
+ data-dev-turn-back-on
+ className="mt-1.5 inline-flex items-center min-h-[44px] sm:min-h-[28px] -ml-1 px-2 rounded-lg text-meta font-semibold text-sky-300 hover:bg-sky-500/10 aria-disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"
+ >
+ {busy ? 'Turning on…' : 'Turn back on'}
+ </button>
+ )}
+ {error && <p className="mt-1 text-bad">{error}</p>}
+ </div>
<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>
@@ -277,7 +341,7 @@ export const DevFlipNote: React.FC<{ on: boolean; space?: string; approvals?: st
};
/** The turned-off note (kept for callers): the flip note's off side. */
-export const DevOffNote: React.FC<{ approvals?: string; onDismiss: () => void; ms?: number }> = (p) => <DevFlipNote on={false} {...p} />;
+export const DevOffNote: React.FC<{ approvals?: string; onDismiss: () => void; ms?: number; onTurnBackOn?: () => Promise<unknown> }> = (p) => <DevFlipNote on={false} {...p} />;
/** The </> badge with its caret on a space tile; `behind` is the surface it sits on. */
export const DevBadge: React.FC<{ behind?: string }> = ({ behind }) => (
diff --git a/frontend/src/components/DevOnToast.tsx b/frontend/src/components/DevOnToast.tsx
new file mode 100644
index 00000000..51a0eb9d
--- /dev/null
+++ b/frontend/src/components/DevOnToast.tsx
@@ -0,0 +1,246 @@
+// The toast after the switch turns Dev mode on (0.7.1, flow F3, Mira's flow copy §3). The person stays
+// on their page; this says what Dev mode found and offers the one next step, plus Undo, the only
+// one-press way off. role="status", 8 s (held while the pointer or focus is on it or on the switch), or
+// until dismissed. Keyboard (K1): the toast sits on the body, so Tab from the switch goes straight to its
+// actions, Shift+Tab from the first goes back, and Tab from the last carries on after the switch. Focus is
+// never moved without a key press.
+// Desktop: bottom-left over the main pane, 360 px. Phone: full width minus 12 px, docked above the chat
+// box so it never covers Send (above the tab bar when there is no chat box). A "checking" toast updates
+// in place when the status arrives, without restarting the 8 s.
+
+import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { X } from 'lucide-react';
+import { DevModeState, onToast } from '../devMode';
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 focus-visible:outline-offset-2';
+
+export interface DevOnToastProps {
+ state: DevModeState;
+ onOpenDesk: () => void;
+ onConnect?: () => void;
+ onTypeRepo: () => void;
+ /** Turns Dev mode off; resolves when saved. */
+ onUndo: () => Promise<unknown>;
+ onClose: () => void;
+ /** Phone layout: full width above the chat box. */
+ phone?: boolean;
+ timeout?: number;
+ /** The switch that turned Dev mode on; the toast's actions are its next Tab stops. */
+ anchor?: () => HTMLElement | null;
+}
+
+const TABBABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
+
+/** The next Tab stop after `from` in page order, skipping `skip` (the toast) and hidden elements. */
+export function nextTabStop(from: HTMLElement, skip: HTMLElement | null): HTMLElement | null {
+ const all = Array.from(document.querySelectorAll<HTMLElement>(TABBABLE)).filter(
+ (el) => el !== from && !skip?.contains(el) && !el.closest('[inert],[aria-hidden="true"]') && !el.closest('[hidden]') && (typeof el.checkVisibility !== 'function' || el.checkVisibility()),
+ );
+ return all.find((el) => from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) ?? null;
+}
+
+const defaultAnchor = () => (typeof document === 'undefined' ? null : document.querySelector<HTMLElement>('[data-dev-switch]'));
+
+/** Keyboard focus, not a mouse click's leftover focus (a clicked switch keeps focus but nobody is there). */
+const keyboardFocus = (el: HTMLElement): boolean => {
+ if (document.activeElement !== el) return false;
+ try {
+ return el.matches(':focus-visible');
+ } catch {
+ return true;
+ }
+};
+
+/** Bottom offset: 8 px above the chat box if one is on screen, else the shared toast offset. */
+function composerGap(): string | null {
+ if (typeof document === 'undefined') return null;
+ const form = document.querySelector('[data-composer-form]');
+ const r = form?.getBoundingClientRect();
+ if (!r || !r.height) return null;
+ const h = window.visualViewport?.height ?? window.innerHeight;
+ return `${Math.max(16, Math.round(h - r.top + 8))}px`;
+}
+
+/** Desktop left edge (flow copy §3): 16 px inside the main pane, never over the sidebar. */
+function paneLeft(): number {
+ if (typeof document === 'undefined') return 16;
+ const r = document.querySelector('[data-main-pane]')?.getBoundingClientRect();
+ return r && r.width ? Math.round(r.left + 16) : 16;
+}
+
+export const DevOnToast: React.FC<DevOnToastProps> = ({ state, onOpenDesk, onConnect, onTypeRepo, onUndo, onClose, phone = false, timeout = 8000, anchor = defaultAnchor }) => {
+ const t = onToast(state);
+ const [undo, setUndo] = useState<'idle' | 'busy' | 'failed'>('idle');
+ const [bottom, setBottom] = useState<string | null>(null);
+ const [held, setHeld] = useState(false);
+ const [left, setLeft] = useState(16);
+ const box = useRef<HTMLDivElement>(null);
+ const anchorRef = useRef(anchor);
+ anchorRef.current = anchor;
+ // The switch holds the toast too: keyboard focus on it, or the pointer over it.
+ const [onSwitch, setOnSwitch] = useState({ focus: false, hover: false });
+
+ useEffect(() => {
+ const a = anchorRef.current();
+ if (!a) return undefined;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== 'Tab' || e.shiftKey || e.altKey || e.ctrlKey || e.metaKey || e.defaultPrevented) return;
+ const first = box.current?.querySelector<HTMLElement>(TABBABLE);
+ if (!first) return;
+ e.preventDefault();
+ first.focus();
+ };
+ const focus = (v: boolean) => () => setOnSwitch((o) => (o.focus === v ? o : { ...o, focus: v }));
+ const hover = (v: boolean) => () => setOnSwitch((o) => (o.hover === v ? o : { ...o, hover: v }));
+ const fIn = () => setOnSwitch((o) => ({ ...o, focus: keyboardFocus(a) }));
+ const fOut = focus(false);
+ const hIn = hover(true);
+ const hOut = hover(false);
+ a.addEventListener('keydown', onKey);
+ a.addEventListener('focus', fIn);
+ a.addEventListener('blur', fOut);
+ a.addEventListener('pointerenter', hIn);
+ a.addEventListener('pointerleave', hOut);
+ if (keyboardFocus(a)) setOnSwitch((o) => ({ ...o, focus: true }));
+ return () => {
+ a.removeEventListener('keydown', onKey);
+ a.removeEventListener('focus', fIn);
+ a.removeEventListener('blur', fOut);
+ a.removeEventListener('pointerenter', hIn);
+ a.removeEventListener('pointerleave', hOut);
+ };
+ }, []);
+
+ // Inside the toast: Shift+Tab from the first action goes back to the switch; Tab from the last goes on
+ // to whatever follows the switch, as if the toast sat right after it.
+ const onToastKey = (e: React.KeyboardEvent) => {
+ if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey) return;
+ const a = anchorRef.current();
+ const stops = Array.from(box.current?.querySelectorAll<HTMLElement>(TABBABLE) ?? []);
+ if (!a || !stops.length) return;
+ const at = stops.indexOf(document.activeElement as HTMLElement);
+ if (e.shiftKey && at === 0) {
+ e.preventDefault();
+ a.focus();
+ } else if (!e.shiftKey && at === stops.length - 1) {
+ const next = nextTabStop(a, box.current);
+ if (!next) return;
+ e.preventDefault();
+ next.focus();
+ }
+ };
+
+ useLayoutEffect(() => {
+ const place = () => {
+ setBottom(composerGap());
+ setLeft(paneLeft());
+ };
+ place();
+ window.addEventListener('resize', place);
+ window.visualViewport?.addEventListener?.('resize', place);
+ return () => {
+ window.removeEventListener('resize', place);
+ window.visualViewport?.removeEventListener?.('resize', place);
+ };
+ }, []);
+
+ // 8 s, paused while the pointer is over it or focus is inside (WCAG 2.2.1); it starts again on leave.
+ useEffect(() => {
+ if (undo === 'busy' || held || onSwitch.focus || onSwitch.hover) return undefined;
+ const h = setTimeout(onClose, undo === 'failed' ? 6000 : timeout);
+ return () => clearTimeout(h);
+ }, [undo, held, onSwitch.focus, onSwitch.hover, timeout, onClose]);
+
+ const fix =
+ t.action === 'connect' && onConnect
+ ? { label: 'Connect GitHub', run: onConnect, key: 'connect' }
+ : t.action === 'type'
+ ? { label: 'Type a repo', run: onTypeRepo, key: 'type' }
+ : { label: 'Open Dev desk', run: onOpenDesk, key: 'open' };
+
+ const doUndo = () => {
+ if (undo === 'busy') return;
+ setUndo('busy');
+ onUndo().then(onClose, () => setUndo('failed'));
+ };
+
+ const mono = (p: { text: string; mono?: boolean }, i: number) =>
+ p.mono ? (
+ <code key={i} className="font-mono text-[12px] font-semibold text-zinc-50 break-all">
+ {p.text}
+ </code>
+ ) : (
+ <React.Fragment key={i}>{p.text}</React.Fragment>
+ );
+
+ const toast = (
+ <div
+ className={`kw-dv-ontoast-wrap fixed z-40 pointer-events-none ${phone ? 'inset-x-[6px]' : ''}`}
+ style={{ bottom: bottom ?? (phone ? 'calc(var(--kw-tabbar-h, 64px) + 8px)' : '16px'), ...(phone ? {} : { left: `${left}px` }) }}
+ data-dev-on-toast={state.status ?? 'checking'}
+ data-phone={phone || undefined}
+ >
+ <div
+ ref={box}
+ role="status"
+ aria-live="polite"
+ onKeyDown={onToastKey}
+ onPointerEnter={() => setHeld(true)}
+ onPointerLeave={() => setHeld(false)}
+ onFocus={() => setHeld(true)}
+ onBlur={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setHeld(false);
+ }}
+ className={`kw-dv-ontoast pointer-events-auto relative ${phone ? 'w-full' : 'w-[360px] max-w-[calc(100vw-32px)]'} pl-3.5 pr-10 pt-2.5 pb-1.5`}
+ >
+ <p className="text-meta leading-snug" data-dev-on-toast-title>
+ <span className="kw-dv-ontoast-head font-mono font-semibold text-sky-300" aria-hidden="true">
+ HEAD → dev
+ </span>{' '}
+ <strong className="font-semibold text-zinc-50">{t.title}</strong>
+ </p>
+ <p className="mt-0.5 text-meta text-zinc-300 leading-snug" data-dev-on-toast-text>
+ {undo === 'failed' ? <span className="text-bad">Couldn’t turn it off. It’s still on.</span> : t.body.map(mono)}
+ </p>
+ <div className="mt-1 -ml-2 flex items-center gap-0.5">
+ <button
+ type="button"
+ onClick={() => {
+ fix.run();
+ onClose();
+ }}
+ data-dev-on-toast-action={fix.key}
+ className={`min-h-[44px] sm:min-h-[32px] px-2 rounded-lg text-meta font-semibold text-[#c9c0ff] hover:bg-violet-500/10 ${focusRing}`}
+ >
+ {fix.label}
+ </button>
+ <button
+ type="button"
+ onClick={doUndo}
+ aria-disabled={undo === 'busy' || undefined}
+ data-dev-on-toast-undo
+ className={`min-h-[44px] sm:min-h-[32px] px-2 rounded-lg text-meta font-semibold text-zinc-300 hover:bg-white/5 aria-disabled:opacity-60 ${focusRing}`}
+ >
+ {undo === 'busy' ? 'Undoing…' : 'Undo'}
+ </button>
+ </div>
+ <button
+ type="button"
+ onClick={() => {
+ // Keyboard focus was in the toast: it goes back to the switch, not to the page top.
+ const back = box.current?.contains(document.activeElement) ? anchorRef.current() : null;
+ onClose();
+ back?.focus();
+ }}
+ aria-label="Dismiss"
+ className={`absolute top-1 right-1 grid place-items-center min-w-[44px] min-h-[44px] sm:min-w-[32px] sm:min-h-[32px] rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-white/5 ${focusRing}`}
+ >
+ <X size={14} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ );
+ // On the body, so a sliding sidebar drawer never carries it off screen.
+ return typeof document === 'undefined' ? toast : createPortal(toast, document.body);
+};
diff --git a/frontend/src/components/DevStatusLine.tsx b/frontend/src/components/DevStatusLine.tsx
new file mode 100644
index 00000000..116c2fde
--- /dev/null
+++ b/frontend/src/components/DevStatusLine.tsx
@@ -0,0 +1,231 @@
+// The Dev desk's one status line (0.7.1, any-git S5). Dev mode turns on with no question asked; the
+// server finds the repo in the space's teams and says what it can read. This line says it back, with
+// at most one action: Switch (several repos found), Connect GitHub, or Type a repo (none found). Nothing here
+// blocks anything: the production floor and the command guards are on in every status.
+
+import React, { useEffect, useId, useRef, useState } from 'react';
+import { Check, FolderGit2, FolderSearch, Hourglass, Link2, Loader2, LucideIcon, PlugZap, Radar } from 'lucide-react';
+import { DevModeState, DevSource, StatusLine, deskIntent, devApi, devStore, statusLine, typedRepo, watchedSource } from '../devMode';
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+
+const ICON: Record<StatusLine['status'], LucideIcon> = {
+ watching: Radar,
+ not_connected: PlugZap,
+ other_host: Hourglass,
+ no_repo: FolderSearch,
+};
+
+export const sourceWhere = (s: DevSource): string => (s.from === 'repo' ? `${s.team}’s repo link` : s.from === 'local' ? `${s.team}’s folder, no remote` : `${s.team}’s folder`);
+
+export interface DevStatusLineProps {
+ spaceId: string;
+ state: DevModeState | null;
+ /** Opens Loose ends (Connect GitHub). Connect hides without it. */
+ onConnect?: () => void;
+ /** Test hook. */
+ save?: typeof devApi.putRepo;
+}
+
+export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, onConnect, save = devApi.putRepo }) => {
+ const line = statusLine(state);
+ // The toast's "Type a repo" lands here with the list open and its input focused.
+ const [open, setOpen] = useState<false | 'list' | 'type'>(() => (deskIntent.take(spaceId) ? 'type' : false));
+ const switchBtn = useRef<HTMLButtonElement>(null);
+ if (!line || !state) return null;
+ const Icon = ICON[line.status];
+ const action =
+ line.action === 'switch' || line.action === 'type' ? (
+ <button
+ ref={switchBtn}
+ type="button"
+ onClick={() => setOpen((o) => (o ? false : line.action === 'type' ? 'type' : 'list'))}
+ aria-expanded={!!open}
+ aria-haspopup="true"
+ data-dv-status-action={line.action}
+ className={`kw-dv-status-btn ${line.action === 'type' ? 'kw-dv-status-btn-primary' : ''} ${focusRing}`}
+ >
+ {line.action === 'type' ? 'Type a repo' : 'Switch'}
+ </button>
+ ) : line.action === 'connect' && onConnect ? (
+ <button type="button" onClick={onConnect} data-dv-status-action="connect" className={`kw-dv-status-btn kw-dv-status-btn-primary ${focusRing}`}>
+ Connect GitHub
+ </button>
+ ) : null;
+ return (
+ <div className="relative" data-dv-status-wrap>
+ <div role="status" className="kw-dv-status" data-dv-status={line.status}>
+ <span className="kw-dv-status-icon" aria-hidden="true">
+ <Icon size={13} aria-hidden="true" />
+ {line.status === 'watching' && <span className="kw-dv-status-ping" />}
+ </span>
+ <p className="min-w-0 flex-1 text-meta text-zinc-300 leading-snug" data-dv-status-text>
+ {line.parts.map((p, i) =>
+ p.mono ? (
+ <code key={i} className="font-mono text-[12px] text-zinc-100 break-all">
+ {p.text}
+ </code>
+ ) : (
+ <React.Fragment key={i}>{p.text}</React.Fragment>
+ ),
+ )}
+ </p>
+ {action}
+ </div>
+ {open && (
+ <SourcePicker
+ spaceId={spaceId}
+ state={state}
+ save={save}
+ focusInput={open === 'type'}
+ onClose={(refocus) => {
+ setOpen(false);
+ if (refocus) switchBtn.current?.focus();
+ }}
+ />
+ )}
+ </div>
+ );
+};
+
+// ---------------------------------------------------------------------------
+// Switch: a one-tap list of the detected repos, and a typed repo below it.
+
+const SourcePicker: React.FC<{ spaceId: string; state: DevModeState; save: typeof devApi.putRepo; focusInput?: boolean; onClose: (refocus: boolean) => void }> = ({
+ spaceId,
+ state,
+ save,
+ focusInput = false,
+ onClose,
+}) => {
+ const id = useId();
+ const box = useRef<HTMLDivElement>(null);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [typed, setTyped] = useState('');
+ const current = watchedSource(state)?.repo ?? state.repo;
+
+ useEffect(() => {
+ if (focusInput) box.current?.querySelector<HTMLInputElement>('input')?.focus();
+ else box.current?.querySelector<HTMLButtonElement>('[aria-checked="true"]')?.focus() ?? box.current?.querySelector<HTMLButtonElement>('button')?.focus();
+ const away = (e: MouseEvent) => {
+ if (box.current && !box.current.contains(e.target as Node) && !(e.target as Element).closest?.('[data-dv-status-action]')) onClose(false);
+ };
+ document.addEventListener('mousedown', away);
+ return () => document.removeEventListener('mousedown', away);
+ }, [onClose]);
+
+ const pick = (repo: string) => {
+ if (busy) return;
+ if (repo === current) return onClose(true);
+ setBusy(repo);
+ setError(null);
+ save(spaceId, { on: true, repo }).then(
+ ({ state: s, refused }) => {
+ devStore.set(spaceId, s);
+ // Dev mode is on either way; a repo it can't read keeps the list open with why (Juno's check).
+ if (refused) {
+ setBusy(null);
+ setError(refused);
+ return;
+ }
+ onClose(true);
+ },
+ (e: unknown) => {
+ setBusy(null);
+ setError(e instanceof Error ? e.message : 'Couldn’t switch the repo.');
+ },
+ );
+ };
+
+ const typedOk = typed.trim() ? typedRepo(typed) : null;
+ const typedErr = typed.trim() && !typedOk ? 'Paste a repo URL, or owner/name for GitHub.' : null;
+
+ return (
+ <div
+ ref={box}
+ role="dialog"
+ aria-label="Which repo to watch"
+ data-dv-picker
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ onClose(true);
+ }
+ }}
+ className="kw-dv-picker"
+ >
+ {state.sources.length > 0 && (
+ <p id={`${id}-h`} className="px-1 pb-1.5 text-2xs font-semibold uppercase tracking-wider text-zinc-400">
+ Found in this space
+ </p>
+ )}
+ {state.sources.length > 0 && (
+ <div role="radiogroup" aria-labelledby={`${id}-h`} className="flex flex-col gap-1">
+ {state.sources.map((s) => {
+ const on = s.repo === current;
+ return (
+ <button
+ key={s.repo}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ disabled={!!busy}
+ onClick={() => pick(s.repo)}
+ data-dv-pick={s.repo}
+ className={`kw-dv-pick ${focusRing}`}
+ >
+ <span className="kw-dv-pick-icon" aria-hidden="true">
+ {s.from === 'repo' ? <Link2 size={13} /> : <FolderGit2 size={13} />}
+ </span>
+ <span className="min-w-0 flex-1 text-left">
+ <span className="block font-mono text-[12px] text-zinc-100 truncate">{s.repo}</span>
+ <span className="block text-2xs text-zinc-400 truncate">{sourceWhere(s)}</span>
+ </span>
+ {busy === s.repo ? (
+ <Loader2 size={13} className="shrink-0 animate-spin motion-reduce:animate-none text-zinc-300" aria-hidden="true" />
+ ) : on ? (
+ <Check size={14} className="shrink-0 text-ok" aria-hidden="true" />
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ <form
+ className={state.sources.length ? 'mt-2 border-t border-white/10 pt-2.5 px-1' : 'px-1'}
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (typedOk) pick(typedOk);
+ }}
+ >
+ <label htmlFor={`${id}-typed`} className="block text-2xs font-medium text-zinc-400 mb-1">
+ Type a repo
+ </label>
+ <div className="flex gap-1.5">
+ <input
+ id={`${id}-typed`}
+ value={typed}
+ onChange={(e) => {
+ setTyped(e.target.value);
+ setError(null);
+ }}
+ placeholder="owner/repo or a git URL"
+ spellCheck={false}
+ autoCapitalize="off"
+ autoComplete="off"
+ aria-invalid={!!typedErr || undefined}
+ aria-describedby={`${id}-err`}
+ className="kw-dv-picker-input"
+ />
+ <button type="submit" disabled={!typedOk || !!busy} className={`kw-dv-status-btn kw-dv-status-btn-primary ${focusRing}`}>
+ Watch
+ </button>
+ </div>
+ <p id={`${id}-err`} className="mt-1 min-h-[1em] text-2xs text-rose-300" aria-live="polite">
+ {error ?? typedErr}
+ </p>
+ </form>
+ </div>
+ );
+};
diff --git a/frontend/src/components/LooseEndsView.tsx b/frontend/src/components/LooseEndsView.tsx
index 3d9b7e44..08853d72 100644
--- a/frontend/src/components/LooseEndsView.tsx
+++ b/frontend/src/components/LooseEndsView.tsx
@@ -22,7 +22,8 @@ import {
} from 'lucide-react';
import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { playSfx } from '../audio/chiptune';
-import { storeApi } from '../passwordStore';
+import { SAVE_FIRST, SaveGate, saveGate, storeApi } from '../passwordStore';
+import { approvalModeApi } from '../approvalMode';
import { BitwardenLoginForm, usePasswordStore } from './PasswordStorePanel';
import { AddLetterForm, LetterPage } from './LetterView';
import {
@@ -350,12 +351,103 @@ export const NeedsBitwarden: React.FC<{ message: string; locked: boolean; onRead
);
};
+/**
+ * Dev mode's Connect (flow F5): when the token couldn't be saved right now (this server's store under
+ * "Ask only when risky" or "Don't ask", or a locked Bitwarden), the two ways out come before the token
+ * field, so nobody types a token and then hits the 409. The rule itself (audit F-10) stays on the server.
+ */
+export const SaveFirst: React.FC<{ gate: Exclude<SaveGate, 'open'>; onReady: (note: string) => void }> = ({ gate, onReady }) => {
+ const id = useId();
+ const store = usePasswordStore(true, true);
+ const [step, setStep] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const first = useRef<HTMLButtonElement>(null);
+ const locked = gate === 'locked';
+ const box = useRef<HTMLDivElement>(null);
+ // Connect/Unlock Bitwarden opens its form in place: focus goes to its first field, not back to the page
+ useEffect(() => {
+ if (!step) return undefined;
+ const h = window.setTimeout(() => box.current?.querySelector<HTMLElement>('input:not([disabled]), select:not([disabled])')?.focus(), 0);
+ return () => window.clearTimeout(h);
+ }, [step, !!store.status]);
+
+ const ask = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await approvalModeApi.turnAllOn();
+ const next = await storeApi.peek();
+ store.set(next);
+ if (saveGate(next) === 'open') onReady(SAVE_FIRST.asked);
+ else if (r.failed) setError(`${r.failed} ${r.failed === 1 ? 'setting' : 'settings'} couldn’t be changed. An archived space keeps its approvals until you restore it.`);
+ else setError('A space or bot still runs without asking. Try again.');
+ } catch (e) {
+ setError(e instanceof Error ? e.message : 'Couldn’t change approvals.');
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div ref={box} role="group" aria-labelledby={`${id}-t`} className={`sm:col-span-2 rounded-xl border p-3 space-y-2 ${step ? 'border-white/10 bg-white/[0.03]' : 'border-amber-500/40 bg-amber-500/10'}`} data-save-first={gate} data-save-first-step={step || undefined}>
+ <p id={`${id}-t`} className="text-xs font-medium text-amber-100">
+ {locked ? SAVE_FIRST.lockedTitle : SAVE_FIRST.title}
+ </p>
+ {!locked && <p className="text-[11px] text-amber-100/80 leading-snug" data-save-first-why>{SAVE_FIRST.why}</p>}
+ {!step ? (
+ <>
+ <div className="flex flex-wrap gap-2">
+ <button ref={first} type="button" onClick={() => setStep(true)} disabled={!store.status} className={`${actionBtn} w-full sm:w-auto justify-center bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`} data-save-first-bitwarden data-land>
+ {locked ? SAVE_FIRST.unlock : SAVE_FIRST.bitwarden}
+ </button>
+ {!locked && (
+ <button type="button" onClick={ask} disabled={busy} className={`${quietBtn} w-full sm:w-auto justify-center`} data-save-first-ask>
+ {busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {busy ? SAVE_FIRST.asking : SAVE_FIRST.ask}
+ </button>
+ )}
+ </div>
+ {!locked && <p className="text-[11px] text-amber-100/70 leading-snug" data-save-first-scope>{SAVE_FIRST.askScope}</p>}
+ </>
+ ) : (
+ store.status && (
+ <BitwardenLoginForm
+ mode={locked ? 'unlock' : 'connect'}
+ status={store.status}
+ plainTitle
+ onCancel={() => setStep(false)}
+ onDone={async (next) => {
+ store.set(next);
+ setStep(false);
+ try {
+ if (next.local_count > 0) await storeApi.migrate();
+ onReady(SAVE_FIRST.connected);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : 'Couldn’t move the passwords.');
+ }
+ }}
+ />
+ )
+ )}
+ {error && <p role="alert" className="text-[11px] text-rose-300">{error}</p>}
+ </div>
+ );
+};
+
const EMPTY_IMAP: ImapFields = { label: '', host: '', port: '', security: 'tls', username: '', folders: '', accept_invalid_certs: false };
/** Add an IMAP mailbox or GitHub. The password or token is read from its field at submit and never kept in state. */
-export const AddSourceForm: React.FC<{ onAdded: (s: LooseSource) => void; onCancel: () => void }> = ({ onAdded, onCancel }) => {
+export const AddSourceForm: React.FC<{
+ onAdded: (s: LooseSource) => void;
+ onCancel: () => void;
+ initialKind?: 'imap' | 'github';
+ /** Dev mode's Connect (flow F5): check the password store first, and land on the first field once `land` is true. */
+ connect?: boolean;
+ land?: boolean;
+}> = ({ onAdded, onCancel, initialKind = 'imap', connect = false, land = false }) => {
const id = useId();
- const [kind, setKind] = useState<'imap' | 'github'>('imap');
+ const [kind, setKind] = useState<'imap' | 'github'>(initialKind);
const [imap, setImap] = useState<ImapFields>(EMPTY_IMAP);
const [ghLabel, setGhLabel] = useState('');
const [ghBase, setGhBase] = useState('');
@@ -363,7 +455,47 @@ export const AddSourceForm: React.FC<{ onAdded: (s: LooseSource) => void; onCanc
const [error, setError] = useState<string | null>(null);
const [vault, setVault] = useState<{ message: string; locked: boolean } | null>(null);
const secretRef = useRef<HTMLInputElement>(null);
+ const formRef = useRef<HTMLFormElement>(null);
const local = isLoopbackHost(imap.host);
+ // Connect reads the store before the token field shows ('checking' until it answers; a failed read
+ // leaves the form as it was, and the 409 card still catches it).
+ const [gate, setGate] = useState<SaveGate | 'checking'>(connect ? 'checking' : 'open');
+ const [ready, setReady] = useState<string | null>(null);
+ useEffect(() => {
+ if (!connect) return undefined;
+ let live = true;
+ storeApi.peek().then(
+ (s) => live && setGate(saveGate(s)),
+ () => live && setGate('open'),
+ );
+ return () => {
+ live = false;
+ };
+ }, [connect]);
+ // Land (B3): once the page has loaded, bring the form into view and focus its first control: the
+ // token, or the first way out when the token can't be saved yet. Again after a way out is taken.
+ const landed = useRef<string | null>(null);
+ useEffect(() => {
+ if (!connect || !land || gate === 'checking' || kind !== 'github') return undefined;
+ if (landed.current === gate) return undefined;
+ // Marked only once focus is in: a cancelled frame (StrictMode's second run, a re-render) tries
+ // again, and a way out that renders a frame later (the store panel loading) is waited for.
+ let h = 0;
+ let tries = 0;
+ const step = () => {
+ const form = formRef.current;
+ const target = form && (gate === 'open' ? secretRef.current : form.querySelector<HTMLElement>('[data-land]:not([disabled])'));
+ if (!form || !target) {
+ if (++tries < 30) h = window.setTimeout(step, 50);
+ return;
+ }
+ landed.current = gate;
+ form.scrollIntoView?.({ block: 'start', behavior: 'auto' });
+ target.focus({ preventScroll: true });
+ };
+ h = window.setTimeout(step, 0);
+ return () => window.clearTimeout(h);
+ }, [connect, land, gate, kind]);
const submit = async (e?: React.FormEvent) => {
e?.preventDefault();
@@ -397,7 +529,7 @@ export const AddSourceForm: React.FC<{ onAdded: (s: LooseSource) => void; onCanc
);
return (
- <form onSubmit={submit} className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 sm:p-4 space-y-3" aria-labelledby={`${id}-h`}>
+ <form ref={formRef} onSubmit={submit} className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 sm:p-4 space-y-3 scroll-mt-4" aria-labelledby={`${id}-h`} data-add-source={kind}>
<div className="flex items-center justify-between gap-2">
<h4 id={`${id}-h`} className="text-xs font-semibold text-zinc-200">
Add a source
@@ -464,8 +596,19 @@ export const AddSourceForm: React.FC<{ onAdded: (s: LooseSource) => void; onCanc
</label>
)}
</div>
+ ) : gate === 'checking' ? (
+ <p className="flex items-center gap-2 text-xs text-zinc-400" data-save-checking>
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Checking where the token goes…
+ </p>
+ ) : gate !== 'open' ? (
+ <SaveFirst gate={gate} onReady={(note) => (setReady(note), setGate('open'))} />
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {ready && (
+ <p role="status" className="sm:col-span-2 text-xs text-emerald-300" data-save-ready>
+ {ready}
+ </p>
+ )}
<div className="sm:col-span-2">
{label(`${id}-tok`, 'Token')}
<input id={`${id}-tok`} ref={secretRef} type="password" className={field} autoComplete="new-password" aria-describedby={`${id}-tok-hint`} />
@@ -497,7 +640,7 @@ export const AddSourceForm: React.FC<{ onAdded: (s: LooseSource) => void; onCanc
<button type="button" onClick={onCancel} className={quietBtn}>
Cancel
</button>
- <button type="submit" disabled={busy} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`}>
+ <button type="submit" disabled={busy || (kind === 'github' && gate !== 'open')} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold disabled:opacity-50`}>
{busy ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Plus size={13} aria-hidden="true" />}
{busy ? 'Testing…' : 'Test and add'}
</button>
@@ -511,10 +654,16 @@ export const LooseSources: React.FC<{
sources: LooseSource[] | null;
error: string | null;
onChanged: () => void;
- /** Tests open the form. */
+ /** Tests open the form; Dev mode's Connect opens it on GitHub (flow F5). */
initialAdding?: boolean;
-}> = ({ sources, error, onChanged, initialAdding = false }) => {
+ initialKind?: 'imap' | 'github';
+ /** Called after a source is added, with it. */
+ onAdded?: (s: LooseSource) => void;
+ /** The page above has finished loading: Connect lands on the GitHub form now (B3), not before the cases push it down. */
+ settled?: boolean;
+}> = ({ sources, error, onChanged, initialAdding = false, initialKind, onAdded, settled = true }) => {
const [adding, setAdding] = useState(initialAdding);
+ const connect = initialAdding && initialKind === 'github';
const [busy, setBusy] = useState<string | null>(null);
const [confirmRemove, setConfirmRemove] = useState<string | null>(null);
const [note, setNote] = useState<{ text: string; error: boolean } | null>(null);
@@ -559,11 +708,15 @@ export const LooseSources: React.FC<{
</div>
{adding && (
<AddSourceForm
+ initialKind={initialKind}
+ connect={connect}
+ land={connect && settled}
onCancel={() => setAdding(false)}
onAdded={(s) => {
setAdding(false);
setNote({ text: `Added ${s.label}. It’s read at the next scan.`, error: false });
onChanged();
+ onAdded?.(s);
}}
/>
)}
@@ -895,7 +1048,13 @@ export const AddLetterButton: React.FC<{ onClick: () => void }> = ({ onClick })
);
/** Loads cases and sources, runs the card actions and scans. */
-export const LooseEndsPage: React.FC<{ onBack?: () => void; onOpenChat?: (kwantId: string, threadId: string) => void }> = ({ onBack, onOpenChat }) => {
+export const LooseEndsPage: React.FC<{
+ onBack?: () => void;
+ onOpenChat?: (kwantId: string, threadId: string) => void;
+ /** Dev mode's Connect (flow F5): open the add form on GitHub, and say when a GitHub source is added. */
+ connectGitHub?: boolean;
+ onGitHubAdded?: () => void;
+}> = ({ onBack, onOpenChat, connectGitHub = false, onGitHubAdded }) => {
const [cases, setCases] = useState<LooseCase[] | null>(null);
const [running, setRunning] = useState(false);
const [loading, setLoading] = useState(true);
@@ -1044,7 +1203,17 @@ export const LooseEndsPage: React.FC<{ onBack?: () => void; onOpenChat?: (kwantI
}
onBack={onBack}
owner={<LooseOwnerSetting />}
- sources={<LooseSources sources={sources} error={sourcesError} onChanged={() => (loadSources(), load())} />}
+ sources={
+ <LooseSources
+ sources={sources}
+ error={sourcesError}
+ onChanged={() => (loadSources(), load())}
+ initialAdding={connectGitHub}
+ initialKind={connectGitHub ? 'github' : undefined}
+ onAdded={(s) => s.kind === 'github' && onGitHubAdded?.()}
+ settled={!loading || cases !== null || error !== null}
+ />
+ }
/>
);
};
diff --git a/frontend/src/components/PasswordStorePanel.tsx b/frontend/src/components/PasswordStorePanel.tsx
index f96a37da..773b8079 100644
--- a/frontend/src/components/PasswordStorePanel.tsx
+++ b/frontend/src/components/PasswordStorePanel.tsx
@@ -95,7 +95,9 @@ export const BitwardenLoginForm: React.FC<{
initialProblem?: UnlockProblem | null;
initialApiKey?: boolean;
initialServer?: string;
-}> = ({ mode, status, onDone, onCancel, initialStep = null, initialProblem = null, initialApiKey, initialServer = DEFAULT_BITWARDEN_SERVER }) => {
+ /** A plain heading (zinc, not the sky link look), for a form shown inside another card. */
+ plainTitle?: boolean;
+}> = ({ mode, status, onDone, onCancel, initialStep = null, initialProblem = null, initialApiKey, initialServer = DEFAULT_BITWARDEN_SERVER, plainTitle = false }) => {
const id = useId();
const bw = status?.bitwarden ?? null;
const [server, setServer] = useState(initialServer);
@@ -195,7 +197,7 @@ export const BitwardenLoginForm: React.FC<{
return (
<form onSubmit={submit} className="space-y-2 text-xs" aria-labelledby={`${id}-t`} data-bitwarden-form={mode} noValidate>
- <p id={`${id}-t`} className="text-[11px] font-semibold text-sky-400 flex items-center gap-1.5">
+ <p id={`${id}-t`} className={plainTitle ? 'text-xs font-medium text-zinc-100 flex items-center gap-1.5' : 'text-[11px] font-semibold text-sky-400 flex items-center gap-1.5'}>
{mode === 'connect' ? <KeyRound size={12} aria-hidden="true" /> : <LockOpen size={12} aria-hidden="true" />}
{mode === 'connect' ? 'Connect Bitwarden' : 'Unlock Bitwarden'}
</p>
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index d1d977bb..10cdf054 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -18,6 +18,8 @@ import { InstallAppButton } from './InstallAppButton';
import { trapFocusTarget } from '../imports';
import { type NeedsYouRow, workingIds, directIds } from '../chatsTab';
import { DevModeSwitch, DevFlipNote, useDevMode } from './DevModeSwitch';
+import { DevOnToast } from './DevOnToast';
+import { type DevModeState, deskIntent, devConnect, turnDevMode } from '../devMode';
import { DevDeskRow } from './DevDesk';
import { IdeaJarRow } from './IdeaJarRow';
@@ -125,6 +127,8 @@ export interface SidebarProps {
/** Dev mode (0.7): the Dev desk row's page is open, and how to open it. */
devDeskActive?: boolean;
onOpenDevDesk?: () => void;
+ /** Dev mode Connect (flow F5): opens Loose ends on the GitHub form; after connecting the app returns to the Dev desk. */
+ onConnectDevGitHub?: () => void;
/** Idea jar (0.7): ready takes for the violet badge, whether its page is open, how to open it, and the quick-add. Hidden on phone, which has the Jar tab. */
ideaJarCount?: number;
ideaJarActive?: boolean;
@@ -287,6 +291,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
missionsActive = false,
devDeskActive = false,
onOpenDevDesk,
+ onConnectDevGitHub,
onOpenMissions,
ideaJarCount = 0,
ideaJarActive = false,
@@ -376,16 +381,59 @@ export const Sidebar: React.FC<SidebarProps> = ({
// Dev mode: on phones the switch sits after the name; on desktop it has its own row under it; on, the meta line says the branch.
const dev = useDevMode(space.id);
const devOn = !!dev?.on;
- // The flip note under the header: 'on' (HEAD → dev) or 'off' (merged into main), or none.
- const [devNote, setDevNote] = useState<'on' | 'off' | null>(null);
- const dismissDevNote = useCallback(() => setDevNote(null), []);
- useEffect(() => setDevNote(null), [space.id]);
+ // The off note under the header (flow copy §7: HEAD → main, with Turn back on).
+ const [devOffNote, setDevOffNote] = useState(false);
+ const dismissDevOff = useCallback(() => setDevOffNote(false), []);
+ useEffect(() => setDevOffNote(false), [space.id]);
+ // Flow F3: switching on keeps the person where they are; a toast says what was found, with one next
+ // step and Undo. It replaces the HEAD → dev note. The toast reads the live store, so a "checking"
+ // toast updates in place when the status arrives.
+ const [devOnToast, setDevOnToast] = useState<DevModeState | null>(null);
+ const closeDevOnToast = useCallback(() => setDevOnToast(null), []);
+ useEffect(() => setDevOnToast(null), [space.id]);
+ const showOn = (s: DevModeState) => {
+ setDevOffNote(false);
+ setDevOnToast(s);
+ };
const devSwitch = (
- <DevModeSwitch key={space.id} space={space} phone={phone} onTurnedOff={() => setDevNote('off')} onTurnedOn={() => setDevNote('on')} />
+ <DevModeSwitch
+ key={space.id}
+ space={space}
+ phone={phone}
+ onTurnedOff={() => {
+ setDevOnToast(null);
+ setDevOffNote(true);
+ }}
+ onTurnedOn={showOn}
+ />
);
+ const focusDevSwitch = () => setTimeout(() => document.querySelector<HTMLElement>('[data-dev-switch]')?.focus(), 0);
+ const connectDev = onConnectDevGitHub
+ ? () => {
+ devConnect.start(space.id);
+ onConnectDevGitHub();
+ }
+ : undefined;
+ const typeDevRepo = () => {
+ deskIntent.set(space.id, 'type');
+ onOpenDevDesk?.();
+ };
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>
+ // The repo truncates; the branch never does (Mira S3)
+ <span className="flex min-w-0 items-baseline gap-1 text-meta text-zinc-400" data-dev-meta>
+ <span className="shrink-0">Dev ·{' '}</span>
+ {dev?.repo ? (
+ <>
+ <span className="truncate min-w-0 font-mono text-zinc-200" title={dev.repo} data-dev-meta-repo>
+ {dev.repo}
+ </span>
+ <span className="shrink-0">
+ {' '}· <span className="font-mono text-sky-300">{dev.branch ?? 'main'}</span>
+ </span>
+ </>
+ ) : (
+ <span className="truncate min-w-0">no repo yet</span>
+ )}
</span>
) : null;
// Phones: section titles stay pinned while their list scrolls, so they are never cut off
@@ -760,7 +808,23 @@ export const Sidebar: React.FC<SidebarProps> = ({
{devSwitch}
</div>
)}
- {devNote && <DevFlipNote key={devNote} on={devNote === 'on'} space={space.name} approvals={space.approvals} onDismiss={dismissDevNote} />}
+ {devOffNote && <DevFlipNote on={false} approvals={space.approvals} onDismiss={dismissDevOff} onTurnBackOn={() => turnDevMode(space.id, true).then(showOn)} />}
+ {devOnToast && devOn && (
+ <DevOnToast
+ state={dev ?? devOnToast}
+ phone={phone}
+ onOpenDesk={() => onOpenDevDesk?.()}
+ onConnect={connectDev}
+ onTypeRepo={typeDevRepo}
+ onUndo={() =>
+ turnDevMode(space.id, false).then(() => {
+ setDevOffNote(true);
+ focusDevSwitch();
+ })
+ }
+ onClose={closeDevOnToast}
+ />
+ )}
{offLine && (
<button
type="button"
diff --git a/frontend/src/devMode.ts b/frontend/src/devMode.ts
index 04bf2cfa..dd8c7301 100644
--- a/frontend/src/devMode.ts
+++ b/frontend/src/devMode.ts
@@ -1,4 +1,4 @@
-// Dev mode (0.7): the switch's safety cover, the first-switch-on setup, the per-space store and the
+// Dev mode (0.7): the switch's safety cover, the detected repos (0.7.1), 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.
@@ -25,8 +25,27 @@ export interface DevModeState {
forge: Forge | null;
/** 0.7.1: that forge connection's login, for "Posts as {login}." on review cards. */
forge_login: string | null;
+ /** 0.7.1 (any-git S4): the repos found in the space's teams, in team order. [] on an older server. */
+ sources: DevSource[];
+ /** 0.7.1: what Dev mode can read right now. null on an older server (then the desk shows the repo chip). */
+ status: DevStatus | null;
+ /** 0.7.1 (flow F6): review cards new since the person last opened the Dev desk. null on an older server. */
+ new_reviews: number | null;
}
+/** Where a space's repo was found: a team's repo link, a git folder with a remote, or a folder with no remote. */
+export type SourceFrom = 'repo' | 'folder' | 'local';
+
+/** One detected repo. Team name only: the server never sends folder paths. */
+export interface DevSource {
+ team: string;
+ repo: string;
+ host: string | null;
+ from: SourceFrom;
+}
+
+export type DevStatus = 'watching' | 'no_repo' | 'not_connected' | 'other_host';
+
export type CheckState = 'found' | 'not_found' | 'not_connected';
/** POST /api/spaces/:id/dev_mode/check */
@@ -41,6 +60,26 @@ const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ?
export type Forge = 'github' | 'gitlab' | 'gitea';
export const forgeOf = (v: unknown): Forge | null => (v === 'github' || v === 'gitlab' || v === 'gitea' ? v : null);
const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const STATUSES: readonly DevStatus[] = ['watching', 'no_repo', 'not_connected', 'other_host'];
+
+/** Drops userinfo from a URL-looking repo (`https://user:token@host/…`), so a token never reaches the screen. */
+export const stripUserinfo = (repo: string): string => repo.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/i, '$1');
+
+export function parseSources(v: unknown): DevSource[] {
+ if (!Array.isArray(v)) return [];
+ const out: DevSource[] = [];
+ for (const x of v) {
+ if (!x || typeof x !== 'object') continue;
+ const o = x as Record<string, unknown>;
+ const team = str(o.team);
+ const repo = str(o.repo);
+ const from = o.from === 'repo' || o.from === 'folder' || o.from === 'local' ? o.from : null;
+ if (!team || !repo || !from) continue;
+ out.push({ team, repo: stripUserinfo(repo), host: str(o.host), from });
+ }
+ return out;
+}
+
const hint = (v: unknown): DeployHint => (v === 'docker' || v === 'cloudflare_pages' || v === 'fly' ? v : null);
export function parseDevMode(raw: unknown): DevModeState | null {
@@ -49,7 +88,10 @@ export function parseDevMode(raw: unknown): DevModeState | null {
if (typeof o.on !== 'boolean') return null;
return {
on: o.on,
- repo: str(o.repo),
+ repo: (() => {
+ const r = str(o.repo);
+ return r ? stripUserinfo(r) : null;
+ })(),
branch: str(o.branch),
deploy_hint: hint(o.deploy_hint),
backup_command: str(o.backup_command),
@@ -60,9 +102,22 @@ export function parseDevMode(raw: unknown): DevModeState | null {
calls_cap: num(o.calls_cap),
forge: forgeOf(o.forge),
forge_login: str(o.forge_login),
+ sources: parseSources(o.sources),
+ status: STATUSES.includes(o.status as DevStatus) ? (o.status as DevStatus) : null,
+ new_reviews: (() => {
+ const n = num(o.new_reviews);
+ return n === null ? null : Math.max(0, Math.floor(n));
+ })(),
};
}
+/** Why a typed repo wasn't watched, from the PUT reply's `check`. Dev mode is on either way. */
+export function putRefusal(c: RepoCheck | null, asked: string): string {
+ const repo = stripUserinfo(c?.repo ?? asked);
+ if (c?.state === 'not_connected') return `Connect GitHub so bots can read ${repo}. Dev mode is on, with the floor and guards.`;
+ return `Couldn’t read ${repo}. Check the name, or that your GitHub connection can see it. Dev mode is on, with the floor and guards.`;
+}
+
export function parseCheck(raw: unknown): RepoCheck | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const o = raw as Record<string, unknown>;
@@ -70,8 +125,114 @@ export function parseCheck(raw: unknown): RepoCheck | 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);
+/** The source Dev mode is watching: the one whose repo is the space's repo. */
+export const watchedSource = (s: DevModeState): DevSource | null => (s.repo ? s.sources.find((x) => x.repo.toLowerCase() === s.repo!.toLowerCase()) ?? null : null);
+
+export interface StatusLine {
+ status: DevStatus;
+ /** Plain text for the line; `{repo}` parts are marked so the view can set them in mono. */
+ parts: Array<{ text: string; mono?: boolean }>;
+ /** The one action on the line, if any: Switch (several repos), Connect GitHub, or Type a repo. */
+ action: 'switch' | 'connect' | 'type' | null;
+}
+
+/** The Dev desk header's one status line: Mira's signed-off copy (style-v2 §4). null on an older server. */
+export function statusLine(s: DevModeState | null): StatusLine | null {
+ if (!s || !s.status) return null;
+ const many = s.sources.length > 1;
+ switch (s.status) {
+ case 'watching': {
+ const src = watchedSource(s);
+ if (src?.from === 'local')
+ return {
+ status: 'watching',
+ parts: [{ text: `${src.team}’s folder has a local repo with no remote. It’s read from the next update. The floor and guards are on now.` }],
+ action: many ? 'switch' : null,
+ };
+ const parts: StatusLine['parts'] = [{ text: 'Watching ' }, { text: s.repo ?? '', mono: true }, { text: ' on ' }, { text: s.branch || 'main', mono: true }];
+ if (many) parts.push({ text: ` · 1 of ${s.sources.length} repos found` });
+ else if (src) parts.push({ text: src.from === 'repo' ? ` · from ${src.team}’s repo link` : ` · from ${src.team}’s folder` });
+ return { status: 'watching', parts, action: many ? 'switch' : null };
+ }
+ case 'not_connected': {
+ const repo = s.repo || s.sources[0]?.repo;
+ const parts: StatusLine['parts'] = repo ? [{ text: 'Found ' }, { text: repo, mono: true }, { text: '. Reviews need your GitHub connection.' }] : [{ text: 'Reviews need your GitHub connection.' }];
+ return { status: 'not_connected', parts, action: 'connect' };
+ }
+ case 'other_host': {
+ const src = watchedSource(s) ?? s.sources.find((x) => x.host && x.host !== 'github.com') ?? null;
+ const repo = s.repo || src?.repo;
+ const host = src?.host ?? null;
+ const parts: StatusLine['parts'] = repo ? [{ text: 'Found ' }, { text: repo, mono: true }, { text: '. ' }] : [];
+ parts.push(...(host ? [{ text: 'Repos on ' }, { text: host, mono: true }, { text: ' are read from the next update. The floor and guards are on now.' }] : [{ text: 'Repos on this host are read from the next update. The floor and guards are on now.' }]));
+ return { status: 'other_host', parts, action: many ? 'switch' : null };
+ }
+ default:
+ return { status: 'no_repo', parts: [{ text: 'No git repo in this space’s folders yet. The floor and guards are on.' }], action: 'type' };
+ }
+}
+
+/** The toast after the switch turns Dev mode on (flow F3, Mira's flow copy §3). `action` is the
+ * status's one fix; watching, other_host and "checking" offer Open Dev desk. Undo is always there. */
+export interface OnToast {
+ /** "Dev mode on", or "Dev mode on · guards are up" when reviews can't run yet. */
+ title: string;
+ /** Line 2; `mono` parts are a repo, branch or host. */
+ body: Array<{ text: string; mono?: boolean }>;
+ action: 'open' | 'connect' | 'type';
+ /** The response came before detection finished (no status yet): the same toast updates in place. */
+ checking: boolean;
+}
+
+const ON = 'Dev mode on';
+const GUARDS = 'Dev mode on · guards are up';
+
+export function onToast(s: DevModeState | null): OnToast {
+ if (!s?.status) return { title: ON, body: [{ text: 'Looking for a git repo in your teams’ folders…' }], action: 'open', checking: true };
+ const src = watchedSource(s);
+ switch (s.status) {
+ case 'watching':
+ if (src?.from === 'local')
+ return { title: GUARDS, body: [{ text: `${src.team}’s folder has a local repo with no remote. The floor works now.` }], action: 'open', checking: false };
+ return {
+ title: ON,
+ body: [{ text: 'Watching ' }, { text: s.repo ?? '', mono: true }, { text: ' on ' }, { text: s.branch || 'main', mono: true }, { text: '.' }],
+ action: 'open',
+ checking: false,
+ };
+ case 'not_connected': {
+ const repo = s.repo || s.sources[0]?.repo;
+ return {
+ title: GUARDS,
+ body: repo ? [{ text: 'Found ' }, { text: repo, mono: true }, { text: '. Connect GitHub to get reviews.' }] : [{ text: 'Connect GitHub to get reviews.' }],
+ action: 'connect',
+ checking: false,
+ };
+ }
+ case 'other_host': {
+ const host = (src ?? s.sources.find((x) => x.host && x.host !== 'github.com'))?.host;
+ return {
+ title: GUARDS,
+ body: host ? [{ text: host, mono: true }, { text: ' repos are read from the next update. The floor works now.' }] : [{ text: 'Repos on this host are read from the next update. The floor works now.' }],
+ action: 'open',
+ checking: false,
+ };
+ }
+ default:
+ return { title: GUARDS, body: [{ text: 'No git repo in this space’s folders yet. The floor works now.' }], action: 'type', checking: false };
+ }
+}
+
+export const onToastText = (t: OnToast) => `${t.title}. ${t.body.map((p) => p.text).join('')}`;
+
+/** The typed repo in the Switch list: a GitHub `owner/name` or URL, or any git URL with its userinfo dropped. */
+export function typedRepo(input: string): string | null {
+ const gh = normaliseRepo(input);
+ if (gh) return gh;
+ const s = stripUserinfo(input.trim());
+ if (/^(?:https?|ssh|git):\/\/[^\s/]+\/\S+$/i.test(s) || /^[\w.-]+@[\w.-]+:\S+$/.test(s)) return s.replace(/\/+$/, '');
+ return null;
+}
// ---------------------------------------------------------------------------
// Repo input: a URL, `owner/name` or `[email protected]:owner/name.git`, normalised to `owner/name`
@@ -100,7 +261,7 @@ export const RECOVER_MS = 5000;
export const SETTLE_MS = 450;
export const DROP_MS = 150;
-export type SwitchPhase = 'covered' | 'lifted' | 'pending' | 'settling';
+export type SwitchPhase = 'covered' | 'lifted' | 'settling';
export interface SwitchState {
/** The committed value, as the server last said (or as just pressed, while saving). */
@@ -110,8 +271,6 @@ export interface SwitchState {
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. */
@@ -129,8 +288,6 @@ export type SwitchAction =
| { 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 }
@@ -141,7 +298,6 @@ export const initialSwitch = (over: Partial<SwitchState> = {}): SwitchState => (
phase: 'covered',
liftedAt: null,
settleUntil: 0,
- setup: true,
disabled: false,
reduced: false,
announce: null,
@@ -169,15 +325,10 @@ export function switchReducer(s: SwitchState, a: SwitchAction, space = 'this spa
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;
- // Flow F1: on only adds guards, so off has no cover and one press turns it on (or opens the
- // setup the first time, on a server that still needs it).
- if (!s.on) {
- if (s.setup) return { ...s, phase: 'pending', liftedAt: null, error: null, announce: say(s, 'Dev mode, setting up.') };
- return flip(s, true, a.now, space);
- }
+ // Flow F1: on only adds guards, so off has no cover and one press turns it on.
+ if (!s.on) return flip(s, true, a.now, space);
// F2: off removes the guards, so it takes two presses: arm, then confirm within 5 s.
if (s.phase === 'covered') return { ...s, phase: 'lifted', liftedAt: a.now, error: null, announce: say(s, ARMED_TEXT) };
return flip(s, false, a.now, space);
@@ -192,14 +343,8 @@ export function switchReducer(s: SwitchState, a: SwitchAction, space = 'this spa
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: null };
case 'saved':
- return { ...s, saving: false, on: a.on, setup: a.on ? false : s.setup };
+ return { ...s, saving: false, on: a.on };
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) };
@@ -207,8 +352,8 @@ export function switchReducer(s: SwitchState, a: SwitchAction, space = 'this spa
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 };
+ if (s.saving) return { ...s, disabled };
+ return { ...s, disabled, on: a.state.on, phase: s.phase === 'lifted' && a.state.on !== s.on ? 'covered' : s.phase };
}
case 'reduced':
return { ...s, reduced: a.reduced };
@@ -229,10 +374,9 @@ function flip(s: SwitchState, on: boolean, now: number, space: string): SwitchSt
};
}
-/** What the switch looks like: cover open or closed, knob side, fill opacity, ring and hint. */
-/** The visual state the switch draws: off, armed (first press), on, pending (setup sheet open),
- * disabled. Styles key off this (data-look), so a new look is CSS plus the glyph map. */
-export type SwitchLookName = 'off' | 'armed' | 'on' | 'pending' | 'disabled';
+/** The visual state the switch draws: off, armed (first press), on, disabled. 0.7.1: no pending
+ * look, since there is no setup sheet. Styles key off this (data-look), so a new look is CSS plus the glyph map. */
+export type SwitchLookName = 'off' | 'armed' | 'on' | 'disabled';
/** The icon in the knob: the code mark at rest, an open lock when armed, a closed lock when disabled. */
export type SwitchGlyph = 'code' | 'unlocked' | 'locked';
@@ -260,7 +404,7 @@ export const ARMED_HINT = 'Press again to turn Dev mode off';
export function switchLook(s: SwitchState): SwitchLook {
const base = switchParts(s);
- const look: SwitchLookName = s.disabled ? 'disabled' : s.phase === 'pending' ? 'pending' : s.phase === 'lifted' ? 'armed' : s.on ? 'on' : 'off';
+ const look: SwitchLookName = s.disabled ? 'disabled' : s.phase === 'lifted' ? 'armed' : s.on ? 'on' : 'off';
// The lock: shut while on and covered (guards locked in) or not the owner, open while armed.
const glyph: SwitchGlyph = s.disabled ? 'locked' : s.phase === 'lifted' ? 'unlocked' : s.on ? 'locked' : 'code';
return { look, glyph, ...base };
@@ -273,8 +417,6 @@ function switchParts(s: SwitchState): Omit<SwitchLook, 'look' | 'glyph'> {
switch (s.phase) {
case 'lifted':
return { coverOpen: true, knobRight: true, fill: 1, ring: true, hint: ARMED_HINT, ...common };
- case 'pending':
- return { coverOpen: true, knobRight: true, fill: 0.45, ring: false, hint: null, ...common, describe: 'Setting up.' };
case 'settling':
return { coverOpen: !s.on, knobRight: s.on, fill: s.on ? 1 : 0, ring: false, hint: null, ...common };
default:
@@ -424,6 +566,17 @@ export const devApi = {
if (!s) throw new DevModeError('The server sent Dev mode in a shape this app doesn’t know.', 500);
return s;
},
+ /**
+ * PUT with a typed repo (Juno, 0.7.1): a repo that can't be read still turns Dev mode on, with no
+ * repo, and the reply's `check` says why. Returns the state and that reason (null when it's watched).
+ */
+ async putRepo(space: string, body: { on: true; repo: string; branch?: string | null }): Promise<{ state: DevModeState; refused: string | null }> {
+ 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);
+ const c = parseCheck((r.data as Record<string, unknown>).check);
+ return { state: s, refused: s.repo ? null : putRefusal(c, body.repo) };
+ },
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);
@@ -433,6 +586,8 @@ export const devApi = {
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),
+ /** Flow F6 (Juno): the person opened the Dev desk, so new_reviews goes back to 0 on every device. */
+ deskSeen: (space: string) => call<unknown>(`/api/spaces/${enc(space)}/dev_mode/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),
@@ -447,6 +602,66 @@ export const devApi = {
export const _call = call;
+/** One press from outside the switch (the toast's Undo, the off note's Turn back on): save, then the
+ * store tells the switch, the desk and the badge. */
+export async function turnDevMode(space: string, on: boolean, put: typeof devApi.put = devApi.put): Promise<DevModeState> {
+ const s = await put(space, { on });
+ devStore.set(space, s);
+ return s;
+}
+
+/** What the desk should open with once it mounts: the Switch list with "Type a repo" focused. */
+const deskIntents = new Map<string, 'type'>();
+export const deskIntent = {
+ set: (space: string, what: 'type') => void deskIntents.set(space, what),
+ take(space: string): 'type' | null {
+ const v = deskIntents.get(space) ?? null;
+ deskIntents.delete(space);
+ return v;
+ },
+};
+
+/** Connect from the Dev desk or the toast: Loose ends opens on the GitHub form, and after a GitHub
+ * source is added the app returns to this space's Dev desk (flow F5). */
+let connectReturn: string | null = null;
+export const devConnect = {
+ start: (space: string) => void (connectReturn = space),
+ pending: () => connectReturn,
+ /** A source was added: the space to return to, once. */
+ finish(): string | null {
+ const v = connectReturn;
+ connectReturn = null;
+ return v;
+ },
+ cancel: () => void (connectReturn = null),
+};
+
+// First-visit marks, per space and per device (they only steer hints, never what is on).
+const mark = (key: string): boolean => {
+ try {
+ if (localStorage.getItem(key)) return false;
+ localStorage.setItem(key, '1');
+ return true;
+ } catch {
+ return false;
+ }
+};
+const marked = (key: string): boolean => {
+ try {
+ return !!localStorage.getItem(key);
+ } catch {
+ return true;
+ }
+};
+export const firstRun = {
+ /** True the first time the desk opens in this space; it stays shown until dismissed this visit. */
+ claimIntro: (space: string) => mark(`kwnt.dev.intro.${space}`),
+ introSeen: (space: string) => marked(`kwnt.dev.intro.${space}`),
+ /** True the first time the Dev desk row shows in this space: one soft highlight. */
+ claimRow: (space: string) => mark(`kwnt.dev.row.${space}`),
+ rowSeen: (space: string) => marked(`kwnt.dev.row.${space}`),
+};
+
// ---------------------------------------------------------------------------
// The per-space store: the header, rail badge, hard hats and grid all read it
@@ -499,6 +714,9 @@ export const emptyState = (): DevModeState => ({
calls_cap: null,
forge: null,
forge_login: null,
+ sources: [],
+ status: null,
+ new_reviews: null,
});
// ---------------------------------------------------------------------------
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index f54aa1a7..ce5d8ac6 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -10,6 +10,7 @@ import './styles/stream.css';
import './styles/needsYou.css';
import './styles/ideas.css';
import './styles/ideaShell.css';
+import './styles/devStatus.css';
registerServiceWorker();
captureInstallPrompt();
diff --git a/frontend/src/passwordStore.ts b/frontend/src/passwordStore.ts
index 75e20816..8bb2a8b5 100644
--- a/frontend/src/passwordStore.ts
+++ b/frontend/src/passwordStore.ts
@@ -282,3 +282,26 @@ export function needsBitwardenFrom(status: number, body: unknown): { message: st
local_count: num(o.local_count),
};
}
+
+/**
+ * Whether a new login (Dev mode's GitHub token) can be saved right now, read before the person types it:
+ * `open`; `store` = this server's store under "Ask only when risky" or "Don't ask" (the 409
+ * needs_bitwarden, audit F-10); `locked` = Bitwarden is the store and is locked.
+ */
+export type SaveGate = 'open' | 'store' | 'locked';
+export const saveGate = (s: StoreStatus | null | undefined): SaveGate =>
+ !s ? 'open' : s.store === 'local' ? (s.approvals_off ? 'store' : 'open') : s.locked ? 'locked' : 'open';
+
+/** The two ways out, before the token field (flow F5). `ask` changes every space and bot, so `askScope` says so. */
+export const SAVE_FIRST = {
+ title: 'One step before the token',
+ lockedTitle: 'Bitwarden is locked. Unlock it to save this login there.',
+ bitwarden: 'Connect Bitwarden',
+ unlock: 'Unlock Bitwarden',
+ why: 'Some bots here run commands without asking, so they could read a token saved on this server. Keep it in Bitwarden, or make every bot ask first.',
+ ask: 'Make every bot ask first',
+ askScope: 'Turns on “Ask before running commands” in every space. You can change it back in each space’s settings.',
+ asking: 'Switching…',
+ asked: 'Every bot now asks before running commands. Add the token below.',
+ connected: 'Bitwarden is connected. Add the token below.',
+} as const;
diff --git a/frontend/src/styles/devStatus.css b/frontend/src/styles/devStatus.css
new file mode 100644
index 00000000..a80812b8
--- /dev/null
+++ b/frontend/src/styles/devStatus.css
@@ -0,0 +1,207 @@
+/* Dev desk status line, Switch list and first-run intro (0.7.1, any-git S5, Pixel).
+ Calm by default: one soft radar ping while watching, a caret that blinks four times, both gone
+ under reduced motion. Colours by status: watching teal (ok), not connected amber (warn, it needs you),
+ next update and no repo violet/zinc (nothing to do). Text is zinc-300 or brighter on the raised
+ surface, so every line passes AA. */
+
+.kw-dv-status {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 44px;
+ padding: 7px 8px 7px 10px;
+ border-radius: 14px;
+ border: 1px solid rgb(255 255 255 / 0.1);
+ background:
+ linear-gradient(90deg, rgb(var(--kw-dv-tint) / 0.1), transparent 55%),
+ rgb(255 255 255 / 0.025);
+ box-shadow: inset 2px 0 0 rgb(var(--kw-dv-tint) / 0.75);
+ --kw-dv-tint: 157 143 255;
+}
+.kw-dv-status[data-dv-status='watching'] { --kw-dv-tint: 45 212 191; }
+.kw-dv-status[data-dv-status='not_connected'] { --kw-dv-tint: 251 191 36; }
+.kw-dv-status[data-dv-status='no_repo'] { --kw-dv-tint: 161 161 170; }
+
+.kw-dv-status-icon {
+ position: relative;
+ flex: none;
+ width: 26px;
+ height: 26px;
+ display: grid;
+ place-items: center;
+ border-radius: 9px;
+ color: rgb(var(--kw-dv-tint));
+ background: rgb(var(--kw-dv-tint) / 0.12);
+ box-shadow: inset 0 0 0 1px rgb(var(--kw-dv-tint) / 0.25);
+}
+.kw-dv-status-ping {
+ position: absolute;
+ inset: 0;
+ border-radius: 9px;
+ box-shadow: 0 0 0 1px rgb(var(--kw-dv-tint) / 0.55);
+ animation: kw-dv-ping 2.4s var(--kw-ease) 3;
+ opacity: 0;
+}
+@keyframes kw-dv-ping {
+ 0% { transform: scale(1); opacity: 0.9; }
+ 70%, 100% { transform: scale(1.55); opacity: 0; }
+}
+
+.kw-dv-status-btn {
+ flex: none;
+ min-height: 32px;
+ padding: 0 12px;
+ border-radius: 10px;
+ font-size: 12px;
+ font-weight: 600;
+ color: rgb(228 228 231);
+ border: 1px solid rgb(255 255 255 / 0.14);
+ background: rgb(255 255 255 / 0.04);
+ transition: background-color 140ms var(--kw-ease), border-color 140ms var(--kw-ease), transform 140ms var(--kw-ease);
+}
+.kw-dv-status-btn:hover:not(:disabled) { background: rgb(255 255 255 / 0.08); border-color: rgb(255 255 255 / 0.22); }
+.kw-dv-status-btn:active:not(:disabled) { transform: translateY(1px); }
+.kw-dv-status-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+.kw-dv-status-btn[aria-expanded='true'] { background: rgb(255 255 255 / 0.1); }
+.kw-dv-status-btn-primary { color: #fff; border-color: transparent; background-image: linear-gradient(135deg, #7a62f0 0%, #5b47d6 100%); }
+.kw-dv-status-btn-primary:hover:not(:disabled) { filter: brightness(1.08); }
+
+.kw-dv-picker {
+ position: absolute;
+ right: 0;
+ top: calc(100% + 6px);
+ z-index: 30;
+ width: min(360px, calc(100vw - 32px));
+ padding: 10px 8px 6px;
+ border-radius: 16px;
+ border: 1px solid rgb(255 255 255 / 0.14);
+ background: var(--kw-surface-overlay);
+ box-shadow: 0 12px 32px rgb(6 3 20 / 0.55);
+ animation: kw-dv-picker-in 150ms var(--kw-ease) both;
+}
+@keyframes kw-dv-picker-in {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: none; }
+}
+.kw-dv-pick {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ min-height: 44px;
+ padding: 6px 8px;
+ border-radius: 11px;
+ border: 1px solid transparent;
+ transition: background-color 140ms var(--kw-ease), border-color 140ms var(--kw-ease);
+}
+.kw-dv-pick:hover:not(:disabled) { background: rgb(255 255 255 / 0.05); }
+.kw-dv-pick[aria-checked='true'] { background: rgb(45 212 191 / 0.07); border-color: rgb(45 212 191 / 0.25); }
+.kw-dv-pick-icon {
+ flex: none;
+ width: 26px;
+ height: 26px;
+ display: grid;
+ place-items: center;
+ border-radius: 8px;
+ color: rgb(196 189 255);
+ background: rgb(157 143 255 / 0.12);
+}
+.kw-dv-picker-input {
+ min-width: 0;
+ flex: 1;
+ height: 34px;
+ padding: 0 10px;
+ border-radius: 10px;
+ border: 1px solid rgb(255 255 255 / 0.14);
+ background: rgb(6 3 20 / 0.35);
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ font-size: 12px;
+ color: rgb(244 244 245);
+ outline: none;
+}
+.kw-dv-picker-input::placeholder { color: rgb(113 113 122); }
+.kw-dv-picker-input:focus { border-color: rgb(56 189 248 / 0.7); }
+.kw-dv-picker-input[aria-invalid='true'] { border-color: rgb(253 164 175 / 0.6); }
+
+.kw-dv-intro {
+ border-radius: 18px;
+ border: 1px dashed rgb(255 255 255 / 0.16);
+ padding: 16px 18px 18px;
+ background:
+ linear-gradient(rgb(157 143 255 / 0.05) 1px, transparent 1px) 0 0 / 16px 16px,
+ linear-gradient(90deg, rgb(157 143 255 / 0.05) 1px, transparent 1px) 0 0 / 16px 16px;
+}
+.kw-dv-intro-caret {
+ display: inline-block;
+ width: 6px;
+ height: 11px;
+ margin-left: 3px;
+ vertical-align: -1px;
+ background: rgb(125 211 252 / 0.8);
+ animation: kw-dv-caret 900ms steps(1) 4;
+}
+.kw-dv-intro-icon {
+ flex: none;
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ border-radius: 9px;
+ color: rgb(196 189 255);
+ background: rgb(157 143 255 / 0.12);
+ box-shadow: inset 0 0 0 1px rgb(157 143 255 / 0.22);
+}
+
+/* Flow F3: the switch-on toast. Same surface family as the status line; HEAD → dev as a small mono tag. */
+.kw-dv-ontoast {
+ border-radius: 14px;
+ border: 1px solid rgb(157 143 255 / 0.28);
+ background: linear-gradient(180deg, rgb(30 27 46 / 0.97), rgb(20 20 27 / 0.97));
+ box-shadow: 0 12px 32px -8px rgb(0 0 0 / 0.6), inset 0 1px 0 rgb(255 255 255 / 0.04);
+ animation: kw-dv-ontoast-in 180ms ease-out;
+}
+.kw-dv-ontoast-head {
+ font-size: 11px;
+ margin-right: 2px;
+}
+@keyframes kw-dv-ontoast-in { from { opacity: 0; transform: translateY(6px); } }
+
+/* Flow F4: still placeholders while the first poll runs (no shimmer). */
+.kw-dv-skel { background: rgb(255 255 255 / 0.015); }
+.kw-dv-skel-bar { display: inline-block; border-radius: 6px; background: rgb(255 255 255 / 0.06); }
+.kw-dv-skel-bar.block { display: block; }
+
+/* Flow copy §4: one soft highlight the first time the Dev desk row appears: accent-soft fades in over
+ 200 ms, holds 2.4 s, fades out over 200 ms. Once per space, no loop, nothing moves. */
+.kw-dv-row-fresh { animation: kw-dv-row-fresh 2800ms linear 1; }
+@keyframes kw-dv-row-fresh {
+ 0% { background-color: transparent; }
+ 7.1%, 92.9% { background-color: var(--kw-accent-soft, rgb(157 143 255 / 0.14)); }
+ 100% { background-color: transparent; }
+}
+/* Flow copy §4: the new-reviews pill. Mono 10.5/700, white on #6c58e0 (5.1:1), 18 px, radius 9; 9+ cap. */
+.kw-dv-row-badge {
+ display: inline-flex; align-items: center; justify-content: center;
+ min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px;
+ background: #6c58e0; color: #fff;
+ font: 700 10.5px/1 ui-monospace, 'JetBrains Mono', SFMono-Regular, Menlo, monospace;
+ font-variant-numeric: tabular-nums;
+}
+.kw-dv-row-badge-pop { animation: kw-dv-badge-pop 160ms ease-out 1; }
+@keyframes kw-dv-badge-pop { from { transform: scale(1.2); } to { transform: scale(1); } }
+
+@media (max-width: 639px) {
+ .kw-dv-status { flex-wrap: wrap; }
+ .kw-dv-status > p { flex-basis: calc(100% - 40px); }
+ .kw-dv-status-btn { min-height: 44px; margin-left: 36px; }
+ .kw-dv-picker { position: fixed; left: 16px; right: 16px; top: auto; bottom: calc(16px + env(safe-area-inset-bottom)); width: auto; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .kw-dv-status-ping, .kw-dv-intro-caret, .kw-dv-picker, .kw-dv-ontoast, .kw-dv-row-badge-pop { animation: none; }
+ /* Reduced motion: the highlight shows for 2.8 s with no fades. */
+ .kw-dv-row-fresh { animation: kw-dv-row-fresh-rm 2800ms steps(1, end) 1; }
+ @keyframes kw-dv-row-fresh-rm { 0% { background-color: var(--kw-accent-soft, rgb(157 143 255 / 0.14)); } 100% { background-color: transparent; } }
+ .kw-dv-status-ping { opacity: 0; }
+ .kw-dv-status-btn, .kw-dv-pick { transition: none; }
+}
diff --git a/frontend/tests/devAutodetect.test.mjs b/frontend/tests/devAutodetect.test.mjs
new file mode 100644
index 00000000..ff8c42f4
--- /dev/null
+++ b/frontend/tests/devAutodetect.test.mjs
@@ -0,0 +1,827 @@
+// 0.7.1 Dev mode on the existing setup (any-git S5, Pixel): GET dev_mode's `sources` and `status`
+// parse (absent on an older server), no token ever reaches the screen, the Dev desk's one status line
+// for each status, Switch's one-tap list and typed repo, Connect, and the first-run intro.
+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;
+
+// Demo data only: no real repos, tokens or emails.
+const base = { on: true, repo: null, branch: null, deploy_hint: null, backup_command: null, last_seen_sha: null, polled_at: null, poll_error: null, calls_today: null, calls_cap: null };
+const SOURCES = [
+ { team: 'Web', repo: 'demo-org/demo-web', host: 'github.com', from: 'folder' },
+ { team: 'API', repo: 'demo-org/demo-api', host: 'github.com', from: 'repo' },
+ { team: 'Docs', repo: 'demo-docs', host: null, from: 'local' },
+];
+let server;
+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 && method === 'PUT') return json({ error: server.fail }, 422);
+ if (server.unreadable && method === 'PUT' && body?.repo) {
+ server.state = { ...server.state, on: true, repo: null, status: 'no_repo' };
+ return json({ ...server.state, check: { state: server.unreadable, repo: body.repo, branch: null, deploy_hint: null } });
+ }
+ // Password store and approvals (B2): demo values only.
+ const path = u.split('?')[0];
+ if (path === '/api/passwords/store') return json(server.store ?? { store: 'local', local_count: 0, approvals_off: false });
+ if (path === '/api/spaces' && method === 'GET') return json(u.includes('archived=1') ? [] : server.spaces ?? []);
+ if (path === '/api/kwants' && method === 'GET') return json([]);
+ if (/^\/api\/spaces\/[^/]+\/approvals$/.test(path) && method === 'PUT') {
+ server.spaces = (server.spaces ?? []).map((sp) => (path.includes(sp.id) ? { ...sp, approvals: body.approvals } : sp));
+ if (server.store && server.spaces.every((sp) => sp.approvals === 'ask')) server.store = { ...server.store, approvals_off: false };
+ return json({ approvals: body.approvals });
+ }
+ if (u.includes('/dev_mode')) {
+ if (method === 'PUT') server.state = { ...server.state, ...body, status: 'watching' };
+ return json(server.state);
+ }
+ 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 * from './src/devMode';
+ export { DevDeskView, DevDeskRow, deskStore, DEV_FEATURES, rowBadge, firstPolling } from './src/components/DevDesk';
+ export { DevStatusLine } from './src/components/DevStatusLine';
+ export { DevOnToast } from './src/components/DevOnToast';
+ export { DevModeSwitch, DevOffNote } from './src/components/DevModeSwitch';
+ export { LooseSources, AddSourceForm } from './src/components/LooseEndsView';
+ export { saveGate, SAVE_FIRST } from './src/passwordStore';
+ export { nextTabStop } from './src/components/DevOnToast';
+ export { lastOn } from './src/components/DevModeSwitch';
+`);
+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 click = async (el) => {
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const mount = async (el) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(el);
+ await settle();
+ return { host, root };
+};
+const state = (over) => m.parseDevMode({ ...base, ...over });
+const reset = (over = {}) => {
+ server = { state: { ...base, ...over }, calls: [], fail: null };
+ m.devStore._reset();
+ m.deskStore._reset();
+ localStorage.clear();
+ document.body.innerHTML = '';
+};
+
+// ---------------------------------------------------------------------------
+// Parsing
+
+test('parseDevMode: an older server (no sources, no status) gives [] and null', () => {
+ const s = m.parseDevMode(base);
+ assert.deepEqual(s.sources, []);
+ assert.equal(s.status, null);
+ assert.equal(m.statusLine(s), null, 'no status line: the desk keeps the old repo chip');
+});
+
+test('parseDevMode: sources keep team, repo, host and from; bad rows and unknown statuses drop', () => {
+ const s = m.parseDevMode({ ...base, status: 'watching', sources: [...SOURCES, { team: 'X', repo: 'a/b', from: 'ftp' }, { repo: 'a/b', from: 'repo' }, 'nope'] });
+ assert.deepEqual(s.sources, SOURCES);
+ assert.equal(s.status, 'watching');
+ assert.equal(m.parseDevMode({ ...base, status: 'bogus' }).status, null);
+ for (const st of ['watching', 'no_repo', 'not_connected', 'other_host']) assert.equal(m.parseDevMode({ ...base, status: st }).status, st);
+});
+
+test('no URL token reaches the screen: userinfo is stripped from repo and sources', () => {
+ const s = m.parseDevMode({
+ ...base,
+ status: 'other_host',
+ repo: 'https://demo-user:[email protected]/demo/app.git',
+ sources: [{ team: 'Web', repo: 'https://oauth2:[email protected]/demo/app.git', host: 'git.example.test', from: 'folder' }],
+ });
+ assert.equal(s.repo, 'https://git.example.test/demo/app.git');
+ assert.equal(s.sources[0].repo, 'https://git.example.test/demo/app.git');
+ assert.doesNotMatch(JSON.stringify(m.statusLine(s)), /token|demo-user|oauth2/);
+});
+
+test('typedRepo: GitHub owner/name and URLs normalise; any git URL is kept without its userinfo', () => {
+ assert.equal(m.typedRepo('https://github.com/demo-org/demo-web'), 'demo-org/demo-web');
+ assert.equal(m.typedRepo('demo-org/demo-web'), 'demo-org/demo-web');
+ assert.equal(m.typedRepo('https://gitlab.example.test/demo/app.git'), 'https://gitlab.example.test/demo/app.git');
+ assert.equal(m.typedRepo('https://u:[email protected]/demo/app'), 'https://codeberg.example.test/demo/app');
+ assert.equal(m.typedRepo('[email protected]:demo/app.git'), '[email protected]:demo/app.git');
+ assert.equal(m.typedRepo('not a repo'), null);
+ assert.equal(m.typedRepo(''), null);
+});
+
+// ---------------------------------------------------------------------------
+// The status line, one per status (draft copy from any-git.md S5)
+
+const text = (l) => l.parts.map((p) => p.text).join('');
+
+test('watching: Mira’s copy, "Watching {repo} on {branch} · from {team}’s folder" or "’s repo link"; Switch only with several sources', () => {
+ const one = m.statusLine(state({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] }));
+ assert.equal(text(one), 'Watching demo-org/demo-web on main · from Web’s folder');
+ assert.equal(one.action, null);
+ assert.deepEqual(one.parts.filter((p) => p.mono).map((p) => p.text), ['demo-org/demo-web', 'main']);
+ const link = m.statusLine(state({ status: 'watching', repo: 'demo-org/demo-api', branch: 'trunk', sources: [SOURCES[1]] }));
+ assert.equal(text(link), 'Watching demo-org/demo-api on trunk · from API’s repo link');
+ const many = m.statusLine(state({ status: 'watching', repo: 'demo-org/demo-api', branch: 'trunk', sources: SOURCES }));
+ assert.equal(text(many), 'Watching demo-org/demo-api on trunk · 1 of 3 repos found');
+ assert.equal(many.action, 'switch');
+ const local = m.statusLine(state({ status: 'watching', repo: 'demo-docs', sources: [SOURCES[2]] }));
+ assert.equal(text(local), 'Docs’s folder has a local repo with no remote. It’s read from the next update. The floor and guards are on now.');
+ const typed = m.statusLine(state({ status: 'watching', repo: 'demo-org/elsewhere', branch: null, sources: [] }));
+ assert.equal(text(typed), 'Watching demo-org/elsewhere on main', 'a typed repo names no team');
+});
+
+test('not_connected: "Found {repo}. Reviews need your GitHub connection." with Connect GitHub', () => {
+ const l = m.statusLine(state({ status: 'not_connected', repo: 'demo-org/demo-web', sources: [SOURCES[0]] }));
+ assert.equal(text(l), 'Found demo-org/demo-web. Reviews need your GitHub connection.');
+ assert.equal(l.action, 'connect');
+});
+
+test('other_host: "Found {repo}. Repos on {host} are read from the next update. The floor and guards are on now."', () => {
+ const l = m.statusLine(state({ status: 'other_host', repo: 'https://gitlab.example.test/demo/app', sources: [{ team: 'Web', repo: 'https://gitlab.example.test/demo/app', host: 'gitlab.example.test', from: 'folder' }] }));
+ assert.equal(text(l), 'Found https://gitlab.example.test/demo/app. Repos on gitlab.example.test are read from the next update. The floor and guards are on now.');
+ assert.deepEqual(l.parts.filter((p) => p.mono).map((p) => p.text), ['https://gitlab.example.test/demo/app', 'gitlab.example.test']);
+ assert.equal(l.action, null);
+});
+
+test('no_repo: "No git repo in this space’s folders yet. The floor and guards are on." with Type a repo', () => {
+ const l = m.statusLine(state({ status: 'no_repo', sources: [] }));
+ assert.equal(text(l), 'No git repo in this space’s folders yet. The floor and guards are on.');
+ assert.equal(l.action, 'type');
+});
+
+test('flow F3: the switch-on toast by status (Mira’s flow copy §3), with its one action', () => {
+ const t = (over) => {
+ const o = m.onToast(over === null ? null : state(over));
+ return [m.onToastText(o), o.action];
+ };
+ assert.deepEqual(t({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] }), ['Dev mode on. Watching demo-org/demo-web on main.', 'open']);
+ assert.deepEqual(t({ status: 'not_connected', repo: 'demo-org/demo-web', sources: [SOURCES[0]] }), ['Dev mode on · guards are up. Found demo-org/demo-web. Connect GitHub to get reviews.', 'connect']);
+ assert.deepEqual(t({ status: 'other_host', repo: 'https://git.example.test/demo/app', sources: [{ team: 'Web', repo: 'https://git.example.test/demo/app', host: 'git.example.test', from: 'folder' }] }), [
+ 'Dev mode on · guards are up. git.example.test repos are read from the next update. The floor works now.',
+ 'open',
+ ]);
+ assert.deepEqual(t({ status: 'no_repo', sources: [] }), ['Dev mode on · guards are up. No git repo in this space’s folders yet. The floor works now.', 'type']);
+ assert.deepEqual(t({}), ['Dev mode on. Looking for a git repo in your teams’ folders…', 'open'], 'checking: no status yet');
+ assert.equal(m.onToast(state({})).checking, true);
+ assert.equal(t({ status: 'watching', repo: 'demo-docs', sources: [SOURCES[2]] })[1], 'open', 'a local repo is not watched yet');
+ assert.match(t({ status: 'watching', repo: 'demo-docs', sources: [SOURCES[2]] })[0], /guards are up\. Docs’s folder has a local repo with no remote/);
+});
+
+test('first-run block copy (flow copy §5): three numbered lines', () => {
+ assert.deepEqual(
+ m.DEV_FEATURES.map((f) => `${f.n} ${f.title} ${f.line}`),
+ [
+ '01 What landed. Every merge to main in plain words, and when main is ready to ship.',
+ '02 Reviews. A second bot reads each pull request before you merge it.',
+ '03 Production floor. Deploys and live-database commands wait for your OK.',
+ ],
+ );
+});
+
+// ---------------------------------------------------------------------------
+// In the Dev desk
+
+const desk = async (over, props = {}) => {
+ reset(over);
+ m.devStore.set('spc_demo', m.parseDevMode(server.state));
+ return mount(h(m.DevDeskView, { spaceId: 'spc_demo', spaceName: 'Demo', ...props }));
+};
+
+test('DOM: each status renders one status line under the header; an older server keeps the repo chip', async () => {
+ for (const [st, extra] of [
+ ['watching', { repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] }],
+ ['not_connected', { repo: 'demo-org/demo-web', sources: [SOURCES[0]] }],
+ ['other_host', { repo: 'https://gitlab.example.test/demo/app', sources: [{ team: 'Web', repo: 'https://gitlab.example.test/demo/app', host: 'gitlab.example.test', from: 'folder' }] }],
+ ['no_repo', { sources: [] }],
+ ]) {
+ const { root } = await desk({ status: st, ...extra }, { onOpenLooseEnds() {} });
+ const lines = document.querySelectorAll('[data-dv-status]');
+ assert.equal(lines.length, 1, st);
+ assert.equal(lines[0].dataset.dvStatus, st);
+ assert.equal(lines[0].getAttribute('role'), 'status');
+ assert.equal(document.querySelector('[data-dev-repo-chip]'), null, `${st}: no duplicate repo chip`);
+ assert.ok(document.querySelector('[data-dev-intro]'), `${st}: first-run intro on the first visit`);
+ root.unmount();
+ }
+ const { root } = await desk({ repo: 'demo-org/demo-web', branch: 'main' });
+ assert.equal(document.querySelector('[data-dv-status]'), null);
+ assert.ok(document.querySelector('[data-dev-repo-chip]'));
+ root.unmount();
+});
+
+test('DOM: Connect opens Loose ends; it hides when the app gives no way there', async () => {
+ let opened = 0;
+ const { root } = await desk({ status: 'not_connected', repo: 'demo-org/demo-web', sources: [SOURCES[0]] }, { onOpenLooseEnds: () => opened++ });
+ const connect = document.querySelector('[data-dv-status-action="connect"]');
+ assert.equal(connect.textContent.trim(), 'Connect GitHub');
+ await click(connect);
+ assert.equal(opened, 1);
+ root.unmount();
+ const again = await desk({ status: 'not_connected', sources: [] });
+ assert.equal(document.querySelector('[data-dv-status-action]'), null);
+ again.root.unmount();
+});
+
+test('DOM: Switch opens a one-tap list; a tap sends PUT {on: true, repo} and the line follows', async () => {
+ const { root } = await desk({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: SOURCES });
+ const sw = document.querySelector('[data-dv-status-action="switch"]');
+ assert.equal(sw.getAttribute('aria-expanded'), 'false');
+ await click(sw);
+ assert.equal(sw.getAttribute('aria-expanded'), 'true');
+ const picks = [...document.querySelectorAll('[data-dv-pick]')];
+ assert.deepEqual(picks.map((p) => p.dataset.dvPick), ['demo-org/demo-web', 'demo-org/demo-api', 'demo-docs']);
+ assert.equal(picks[0].getAttribute('aria-checked'), 'true');
+ assert.equal(document.activeElement, picks[0], 'focus starts on the watched repo');
+ assert.match(picks[1].textContent, /API’s repo link/);
+ assert.match(picks[2].textContent, /Docs’s folder, no remote/);
+ await click(picks[1]);
+ await settle();
+ assert.deepEqual(server.calls.filter(([meth]) => meth === 'PUT').map(([, , b]) => b), [{ on: true, repo: 'demo-org/demo-api' }]);
+ assert.equal(document.querySelector('[data-dv-picker]'), null, 'the list closes');
+ assert.equal(document.activeElement, sw, 'focus goes back to Switch');
+ assert.match(document.querySelector('[data-dv-status-text]').textContent, /Watching demo-org\/demo-api on main · 1 of 3 repos found/);
+ root.unmount();
+});
+
+test('DOM: tapping the watched repo just closes; Esc closes; a typed git URL is watched without its userinfo', async () => {
+ const { root } = await desk({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: SOURCES });
+ const sw = document.querySelector('[data-dv-status-action="switch"]');
+ await click(sw);
+ await click(document.querySelector('[data-dv-pick="demo-org/demo-web"]'));
+ assert.equal(document.querySelector('[data-dv-picker]'), null);
+ assert.equal(server.calls.filter(([meth]) => meth === 'PUT').length, 0);
+ await click(sw);
+ document.querySelector('[data-dv-picker]').dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ assert.equal(document.querySelector('[data-dv-picker]'), null);
+ assert.equal(document.activeElement, sw);
+ await click(sw);
+ const input = document.querySelector('[data-dv-picker] input');
+ const submit = document.querySelector('[data-dv-picker] button[type="submit"]');
+ const type = async (v) => {
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(input, v);
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+ };
+ await type('not a repo');
+ assert.equal(submit.disabled, true);
+ assert.equal(input.getAttribute('aria-invalid'), 'true');
+ await type('https://demo:[email protected]/demo/app.git');
+ assert.equal(submit.disabled, false);
+ input.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: 'https://gitea.example.test/demo/app.git' }]);
+ root.unmount();
+});
+
+test('DOM: a failed switch keeps the list open with the reason', async () => {
+ const { root } = await desk({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: SOURCES });
+ server.fail = 'Bots can’t read that repo.';
+ await click(document.querySelector('[data-dv-status-action="switch"]'));
+ await click(document.querySelector('[data-dv-pick="demo-org/demo-api"]'));
+ await settle();
+ assert.ok(document.querySelector('[data-dv-picker]'));
+ assert.match(document.querySelector('[data-dv-picker]').textContent, /Bots can’t read that repo\./);
+ root.unmount();
+});
+
+test('DOM: a typed repo the server can’t read (200, repo null, check) keeps the list open with why; Dev mode stays on', async () => {
+ for (const [why, re] of [['not_found', /Couldn’t read demo-org\/nope\. .*Dev mode is on/], ['not_connected', /Connect GitHub so bots can read demo-org\/nope\./]]) {
+ const { root } = await desk({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: SOURCES });
+ server.unreadable = why;
+ await click(document.querySelector('[data-dv-status-action="switch"]'));
+ const input = document.querySelector('[data-dv-picker] input');
+ const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
+ set.call(input, 'demo-org/nope');
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+ input.form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.deepEqual(server.calls.filter(([x]) => x === 'PUT').at(-1)[2], { on: true, repo: 'demo-org/nope' });
+ assert.ok(document.querySelector('[data-dv-picker]'), why);
+ assert.match(document.querySelector('[data-dv-picker]').textContent, re);
+ assert.equal(m.devStore.get('spc_demo').on, true);
+ assert.equal(m.devStore.get('spc_demo').repo, null);
+ root.unmount();
+ }
+});
+
+// ---------------------------------------------------------------------------
+// The user flow (user-flow.md F3–F10)
+
+const puts = () => server.calls.filter(([meth]) => meth === 'PUT').map(([, , b]) => b);
+const noop = () => {};
+
+const toast = async (over, props = {}) => {
+ reset(over);
+ const st = m.parseDevMode(server.state);
+ m.devStore.set('spc_demo', st);
+ return mount(h(m.DevOnToast, { state: st, onOpenDesk: noop, onConnect: noop, onTypeRepo: noop, onUndo: () => m.turnDevMode('spc_demo', false), onClose: noop, ...props }));
+};
+
+test('F3 DOM: the toast is role=status on the body, says what was found, and offers that status’s one action', async () => {
+ for (const [over, title, body, action, label] of [
+ [{ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] }, 'Dev mode on', 'Watching demo-org/demo-web on main.', 'open', 'Open Dev desk'],
+ [{ status: 'not_connected', repo: 'demo-org/demo-web', sources: [SOURCES[0]] }, 'Dev mode on · guards are up', 'Found demo-org/demo-web. Connect GitHub to get reviews.', 'connect', 'Connect GitHub'],
+ [{ status: 'other_host', repo: 'https://gitlab.example.test/demo/app', sources: [{ team: 'Web', repo: 'https://gitlab.example.test/demo/app', host: 'gitlab.example.test', from: 'folder' }] }, 'Dev mode on · guards are up', 'gitlab.example.test repos are read from the next update. The floor works now.', 'open', 'Open Dev desk'],
+ [{ status: 'no_repo', sources: [] }, 'Dev mode on · guards are up', 'No git repo in this space’s folders yet. The floor works now.', 'type', 'Type a repo'],
+ ]) {
+ let ran = '';
+ const { root } = await toast(over, { onOpenDesk: () => (ran = 'open'), onConnect: () => (ran = 'connect'), onTypeRepo: () => (ran = 'type') });
+ const el = document.querySelector('[data-dev-on-toast] [role="status"]');
+ assert.ok(el, over.status);
+ assert.equal(el.closest('[data-dev-on-toast]').parentElement, document.body, 'portalled to the body');
+ assert.equal(el.querySelector('[data-dev-on-toast-title] strong').textContent, title);
+ assert.match(el.querySelector('[data-dev-on-toast-title]').textContent, /^HEAD → dev/);
+ assert.equal(el.querySelector('[data-dev-on-toast-text]').textContent, body);
+ assert.equal(document.querySelectorAll('[data-dev-on-toast-action]').length, 1, 'one fix action');
+ const btn = document.querySelector('[data-dev-on-toast-action]');
+ assert.equal(btn.dataset.devOnToastAction, action);
+ assert.equal(btn.textContent.trim(), label);
+ assert.ok(document.querySelector('[data-dev-on-toast-undo]'), 'Undo is always there');
+ assert.ok(el.querySelector('button[aria-label="Dismiss"]'));
+ await click(btn);
+ assert.equal(ran, action);
+ root.unmount();
+ }
+});
+
+test('F3 DOM: a "checking" toast updates in place when the status arrives', async () => {
+ const { root } = await toast({});
+ assert.equal(document.querySelector('[data-dev-on-toast]').dataset.devOnToast, 'checking');
+ assert.match(document.querySelector('[data-dev-on-toast-text]').textContent, /Looking for a git repo/);
+ root.render(h(m.DevOnToast, { state: state({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] }), onOpenDesk: noop, onTypeRepo: noop, onUndo: async () => {}, onClose: noop }));
+ await settle();
+ assert.equal(document.querySelectorAll('[data-dev-on-toast]').length, 1, 'the same toast');
+ assert.equal(document.querySelector('[data-dev-on-toast-text]').textContent, 'Watching demo-org/demo-web on main.');
+ root.unmount();
+});
+
+test('F3 DOM: Undo turns Dev mode off in one press (PUT {on:false}) and closes; a failed Undo says it is still on', async () => {
+ let closed = 0;
+ const { root } = await toast({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] }, { onClose: () => closed++ });
+ await click(document.querySelector('[data-dev-on-toast-undo]'));
+ await settle();
+ assert.deepEqual(puts(), [{ on: false }]);
+ assert.equal(m.devStore.isOn('spc_demo'), false);
+ assert.equal(closed, 1);
+ root.unmount();
+ const again = await toast({ status: 'no_repo', sources: [] }, { onClose: () => closed++ });
+ server.fail = 'Offline.';
+ await click(document.querySelector('[data-dev-on-toast-undo]'));
+ await settle();
+ assert.match(document.querySelector('[data-dev-on-toast-text]').textContent, /Couldn’t turn it off\. It’s still on\./);
+ again.root.unmount();
+});
+
+test('F3 DOM: the toast goes after its time, paused while focus is inside; on a phone it sits above the chat box', async () => {
+ reset({ status: 'no_repo', sources: [] });
+ const form = document.createElement('form');
+ form.setAttribute('data-composer-form', '');
+ form.getBoundingClientRect = () => ({ top: 700, bottom: 800, height: 100, left: 0, right: 390, width: 390 });
+ document.body.appendChild(form);
+ Object.defineProperty(window, 'innerHeight', { value: 844, configurable: true });
+ let closed = 0;
+ const st = m.parseDevMode(server.state);
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(h(m.DevOnToast, { state: st, phone: true, onOpenDesk: noop, onTypeRepo: noop, onUndo: async () => {}, onClose: () => closed++, timeout: 40 }));
+ await settle();
+ const wrap = document.querySelector('[data-dev-on-toast]');
+ assert.equal(wrap.style.bottom, '152px', '844 − 700 + 8: above the chat box, never over Send');
+ const undo = wrap.querySelector('[data-dev-on-toast-undo]');
+ undo.focus();
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(closed, 0, 'held while focus is inside');
+ undo.blur();
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(closed, 1, 'closes once its time is up');
+ root.unmount();
+ form.remove();
+});
+
+test('F8 DOM: the off note’s Turn back on turns Dev mode on in one press and closes the note', async () => {
+ reset({ on: false });
+ let dismissed = 0;
+ const { root } = await mount(h(m.DevOffNote, { approvals: 'ask', onDismiss: () => dismissed++, onTurnBackOn: () => m.turnDevMode('spc_demo', true) }));
+ const b = document.querySelector('[data-dev-turn-back-on]');
+ assert.equal(b.textContent.trim(), 'Turn back on');
+ assert.ok(b.className.includes('min-h-[44px]'), '44 px on phones');
+ await click(b);
+ await settle();
+ assert.deepEqual(puts(), [{ on: true }]);
+ assert.equal(m.devStore.isOn('spc_demo'), true);
+ assert.equal(dismissed, 1);
+ root.unmount();
+});
+
+test('F10 DOM: a space already on shows no toast: onTurnedOn only follows a press that turned it on', async () => {
+ reset({ status: 'watching', repo: 'demo-org/typed-by-hand', branch: 'main', sources: [SOURCES[0]] });
+ let turnedOn = 0;
+ const { root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' }, onTurnedOn: () => turnedOn++ }));
+ await settle();
+ assert.equal(document.querySelector('[data-dev-switch]').getAttribute('aria-checked'), 'true');
+ assert.equal(turnedOn, 0);
+ assert.equal(puts().length, 0, 'nothing is saved, so the typed repo stays');
+ root.unmount();
+});
+
+test('F6: the row badge is new_reviews from the server (landed cards never count); an older server falls back to open reviews', () => {
+ assert.equal(m.rowBadge(state({ new_reviews: 2 }), 5), 2);
+ assert.equal(m.rowBadge(state({ new_reviews: 0 }), 5), 0);
+ assert.equal(m.rowBadge(state({}), 3), 3);
+ assert.equal(m.parseDevMode({ ...base, new_reviews: -4 }).new_reviews, 0);
+});
+
+test('F6 DOM: the row shows new_reviews; opening the desk posts /dev_mode/seen and clears it', async () => {
+ reset({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]], new_reviews: 2, polled_at: '2026-11-05T09:00:00Z' });
+ m.devStore.set('spc_demo', m.parseDevMode(server.state));
+ const row = await mount(h(m.DevDeskRow, { spaceId: 'spc_demo', active: false, onOpen: noop }));
+ await settle();
+ assert.equal(document.querySelector('[data-dev-row-badge]').textContent, '2');
+ assert.equal(document.querySelector('[data-dev-desk-row]').getAttribute('aria-label'), 'Dev desk, 2 new reviews');
+ assert.equal(document.querySelector('[data-dev-row-badge]').getAttribute('title'), '2 new reviews to look at');
+ const view = await mount(h(m.DevDeskView, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ await settle();
+ assert.ok(server.calls.some(([meth, u]) => meth === 'POST' && u.endsWith('/dev_mode/seen')));
+ assert.equal(document.querySelector('[data-dev-row-badge]'), null, 'the badge clears at once');
+ view.root.unmount();
+ row.root.unmount();
+});
+
+test('F4 DOM: the Dev desk row gets one soft highlight the first time it appears, then never again', async () => {
+ reset({ status: 'watching', repo: 'demo-org/demo-web', sources: [SOURCES[0]] });
+ const a = await mount(h(m.DevDeskRow, { spaceId: 'spc_demo', active: false, onOpen: noop }));
+ assert.ok(document.querySelector('[data-dev-desk-row]').classList.contains('kw-dv-row-fresh'));
+ a.root.unmount();
+ document.body.innerHTML = '';
+ const b = await mount(h(m.DevDeskRow, { spaceId: 'spc_demo', active: false, onOpen: noop }));
+ assert.equal(document.querySelector('[data-dev-desk-row]').classList.contains('kw-dv-row-fresh'), false);
+ b.root.unmount();
+});
+
+test('F4 DOM: while the first poll runs, still skeleton cards with "Reading the last 5 merges…", never "Nothing has landed yet"', async () => {
+ assert.equal(m.firstPolling(state({ status: 'watching', repo: 'demo-org/demo-web' }), 0), true);
+ assert.equal(m.firstPolling(state({ status: 'watching', repo: 'demo-org/demo-web', polled_at: '2026-11-05T09:00:00Z' }), 0), false);
+ assert.equal(m.firstPolling(state({ status: 'no_repo' }), 0), false);
+ const { root } = await desk({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] });
+ const sk = document.querySelector('[data-dev-skeleton]');
+ assert.ok(sk);
+ assert.equal(sk.querySelector('[role="status"]').textContent.trim(), 'Reading the last 5 merges…');
+ assert.equal(document.querySelector('[data-dev-empty]'), null);
+ assert.equal(document.querySelector('.animate-pulse'), null, 'no shimmer');
+ root.unmount();
+ const polled = await desk({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]], polled_at: '2026-11-05T09:00:00Z' });
+ assert.equal(document.querySelector('[data-dev-skeleton]'), null);
+ assert.ok(document.querySelector('[data-dev-empty]'));
+ polled.root.unmount();
+});
+
+test('F4 DOM: the first-run block shows on the first visit only, and Got it hides it for good', async () => {
+ const one = await desk({ status: 'no_repo', sources: [] });
+ const intro = document.querySelector('[data-dev-intro]');
+ assert.ok(intro);
+ assert.equal(intro.querySelector('h3').textContent, 'Here’s what Dev mode does');
+ assert.match(intro.textContent, /HEAD → dev · guards up/);
+ assert.equal(document.querySelectorAll('[data-dev-feature]').length, 3, 'three lines');
+ assert.equal(intro.querySelectorAll('button').length, 1, 'Got it is the only control');
+ const got = document.querySelector('[data-dev-intro-close]');
+ assert.equal(got.textContent.trim(), 'Got it');
+ await click(got);
+ assert.equal(document.querySelector('[data-dev-intro]'), null);
+ one.root.unmount();
+ document.body.innerHTML = '';
+ m.devStore.set('spc_demo', m.parseDevMode(server.state));
+ const two = await mount(h(m.DevDeskView, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ assert.equal(document.querySelector('[data-dev-intro]'), null, 'second visit: gone');
+ two.root.unmount();
+});
+
+test('F4 DOM: first-visit empty states speak git and never say "Nothing has landed yet"; 9+ caps the badge', async () => {
+ for (const [over, out, title] of [
+ [{ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]], polled_at: '2026-11-05T09:00:00Z' }, '(no merges yet)', 'No merges on main yet.'],
+ [{ status: 'not_connected', repo: 'demo-org/demo-web', sources: [SOURCES[0]] }, '(needs a GitHub connection)', 'Connect GitHub to see what landed.'],
+ [{ status: 'no_repo', sources: [] }, '(no repo yet)', 'Cards show up once there’s a repo.'],
+ ]) {
+ const { root } = await desk(over);
+ const e = document.querySelector('[data-dev-empty-term]');
+ assert.ok(e, over.status);
+ assert.match(e.textContent, /\$ git log main -5/);
+ assert.ok(e.textContent.includes(out), over.status);
+ assert.ok(e.textContent.includes(title), over.status);
+ assert.doesNotMatch(document.body.textContent, /Nothing has landed yet/);
+ assert.equal(document.querySelector('[data-dev-rollup]'), null, 'no "since you last looked" line with no cards');
+ root.unmount();
+ }
+ reset({ status: 'watching', repo: 'demo-org/demo-web', sources: [SOURCES[0]], new_reviews: 12 });
+ m.devStore.set('spc_demo', m.parseDevMode(server.state));
+ const row = await mount(h(m.DevDeskRow, { spaceId: 'spc_demo', active: false, onOpen: noop }));
+ assert.equal(document.querySelector('[data-dev-row-badge]').textContent, '9+');
+ assert.equal(document.querySelector('[data-dev-desk-row]').getAttribute('aria-label'), 'Dev desk, 12 new reviews');
+ row.root.unmount();
+});
+
+test('F5 DOM: no_repo’s Type a repo opens the list straight at the field; the toast’s Type a repo lands there too', async () => {
+ const { root } = await desk({ status: 'no_repo', sources: [] });
+ const t = document.querySelector('[data-dv-status-action="type"]');
+ assert.equal(t.textContent.trim(), 'Type a repo');
+ await click(t);
+ const input = document.querySelector('[data-dv-picker] input');
+ assert.ok(input);
+ assert.equal(document.activeElement, input);
+ assert.equal(document.querySelectorAll('[data-dv-pick]').length, 0);
+ root.unmount();
+ reset({ status: 'no_repo', sources: [] });
+ m.devStore.set('spc_demo', m.parseDevMode(server.state));
+ m.deskIntent.set('spc_demo', 'type');
+ const again = await mount(h(m.DevDeskView, { spaceId: 'spc_demo', spaceName: 'Demo' }));
+ assert.ok(document.querySelector('[data-dv-picker] input'), 'opened from the toast');
+ assert.equal(m.deskIntent.take('spc_demo'), null, 'used once');
+ again.root.unmount();
+});
+
+test('F5 DOM: Connect opens Loose ends’ add form on GitHub, and a GitHub source added says so (to return to the desk)', async () => {
+ reset({});
+ let added = null;
+ const { root } = await mount(h(m.LooseSources, { sources: [], error: null, onChanged: noop, initialAdding: true, initialKind: 'github', onAdded: (s) => (added = s) }));
+ const gh = [...document.querySelectorAll('[role="radio"]')].find((r) => /GitHub/.test(r.textContent));
+ assert.equal(gh.getAttribute('aria-checked'), 'true');
+ root.unmount();
+ m.devConnect.start('spc_demo');
+ assert.equal(m.devConnect.pending(), 'spc_demo');
+ assert.equal(m.devConnect.finish(), 'spc_demo');
+ assert.equal(m.devConnect.finish(), null, 'returns once');
+ assert.equal(added, null);
+});
+
+test('F3 DOM: on desktop the toast starts 16 px inside the main pane, never over the sidebar', async () => {
+ const over = { status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] };
+ reset(over);
+ const pane = document.createElement('div');
+ pane.setAttribute('data-main-pane', '');
+ pane.getBoundingClientRect = () => ({ left: 323, top: 0, right: 1440, bottom: 900, width: 1117, height: 900 });
+ document.body.appendChild(pane);
+ const st = m.parseDevMode(server.state);
+ const { root } = await mount(h(m.DevOnToast, { state: st, onOpenDesk: noop, onTypeRepo: noop, onUndo: async () => {}, onClose: noop }));
+ assert.equal(document.querySelector('[data-dev-on-toast]').style.left, '339px');
+ root.unmount();
+ const again = await toast({ status: 'no_repo', sources: [] });
+ assert.equal(document.querySelector('[data-dev-on-toast]').style.left, '16px', 'no pane: 16 px');
+ again.root.unmount();
+});
+
+// ---------------------------------------------------------------------------
+// Round 3 (Rigel's round 2: B2, B3, K1 and the minors)
+
+test('B2: saveGate reads the store: this server under approvals off is "store", a locked Bitwarden is "locked", else open', () => {
+ assert.equal(m.saveGate(null), 'open');
+ assert.equal(m.saveGate({ store: 'local', approvals_off: false, locked: false }), 'open');
+ assert.equal(m.saveGate({ store: 'local', approvals_off: true, locked: false }), 'store');
+ assert.equal(m.saveGate({ store: 'bitwarden', approvals_off: true, locked: true }), 'locked');
+ assert.equal(m.saveGate({ store: 'bitwarden', approvals_off: true, locked: false }), 'open');
+});
+
+const frame = () => new Promise((r) => setTimeout(r, 40));
+const connectForm = async (store, spaces) => {
+ reset({});
+ server.store = store;
+ server.spaces = spaces;
+ const r = await mount(h(m.LooseSources, { sources: [], error: null, onChanged: noop, initialAdding: true, initialKind: 'github', onAdded: noop, settled: true }));
+ await frame();
+ await settle();
+ return r;
+};
+
+test('B2 DOM: under "Ask only when risky" Connect offers the two ways out before any token field, and nothing is sent', async () => {
+ const { root } = await connectForm({ store: 'local', local_count: 0, approvals_off: true }, [{ id: 'spc_demo', approvals: 'smart' }]);
+ const gate = document.querySelector('[data-save-first]');
+ assert.ok(gate, 'the ways out show');
+ assert.equal(gate.dataset.saveFirst, 'store');
+ assert.equal(document.querySelector('input[type="password"]'), null, 'no token field to type into yet');
+ assert.match(gate.textContent, /One step before the token/);
+ assert.equal(gate.querySelector('[data-save-first-bitwarden]').textContent.trim(), 'Connect Bitwarden');
+ assert.equal(gate.querySelector('[data-save-first-ask]').textContent.trim(), 'Make every bot ask first');
+ assert.equal(gate.querySelector('[data-save-first-why]').textContent, 'Some bots here run commands without asking, so they could read a token saved on this server. Keep it in Bitwarden, or make every bot ask first.', 'M2: its own reason line');
+ assert.equal(gate.querySelector('[data-save-first-scope]').textContent, 'Turns on “Ask before running commands” in every space. You can change it back in each space’s settings.', 'M1: the scope is said');
+ assert.match(gate.querySelector('[data-save-first-scope]').className, /text-\[11px\] text-amber-100\/70/);
+ for (const b of gate.querySelectorAll('[data-save-first-bitwarden], [data-save-first-ask]')) assert.match(b.className, /w-full sm:w-auto/, 'S2: equal width when stacked');
+ assert.match(gate.className, /border-amber-500\/40 bg-amber-500\/10/, 'amber while it needs you');
+ assert.ok(document.activeElement === gate.querySelector('[data-save-first-bitwarden]'), 'B3: focus lands on the first way out');
+ assert.equal(document.querySelector('button[type="submit"]').disabled, true);
+ assert.equal(server.calls.filter(([meth, u]) => meth === 'POST' && u.includes('/loose')).length, 0);
+ root.unmount();
+});
+
+test('B2 DOM: "Ask before running commands" switches every space and bot to ask, then the GitHub form is back with the token focused', async () => {
+ const { root } = await connectForm({ store: 'local', local_count: 0, approvals_off: true }, [{ id: 'spc_demo', approvals: 'smart' }]);
+ await click(document.querySelector('[data-save-first-ask]'));
+ await settle(20);
+ await frame();
+ assert.deepEqual(puts(), [{ approvals: 'ask' }]);
+ assert.equal(document.querySelector('[data-save-first]'), null);
+ const tok = document.querySelector('input[type="password"]');
+ assert.ok(tok, 'the token field is back');
+ assert.ok(document.activeElement === tok, 'and focused');
+ assert.equal(document.querySelector('[data-save-ready]').textContent, 'Every bot now asks before running commands. Add the token below.');
+ root.unmount();
+});
+
+test('B2 DOM: Connect Bitwarden opens the existing Bitwarden form in place; a locked Bitwarden offers Unlock only', async () => {
+ const one = await connectForm({ store: 'local', local_count: 0, approvals_off: true }, []);
+ await click(document.querySelector('[data-save-first-bitwarden]'));
+ assert.equal(document.querySelector('[data-save-first-bitwarden]'), null, 'the Bitwarden form replaces the buttons');
+ const open = document.querySelector('[data-save-first]');
+ assert.match(open.className, /border-white\/10 bg-white\/\[0\.03\]/, 'S1: the open form is not on amber');
+ assert.doesNotMatch(open.className, /bg-amber-500/);
+ assert.match(open.querySelector('[data-bitwarden-form] > p').className, /text-xs font-medium text-zinc-100/, 'S1: a plain heading, not a link look');
+ assert.equal(open.querySelector('[data-save-first-scope]'), null, 'the scope line goes with its button');
+ assert.ok(document.querySelector('[data-save-first] form, [data-save-first] input'), 'Bitwarden sign-in fields show');
+ await frame();
+ assert.ok(['INPUT', 'SELECT'].includes(document.activeElement?.tagName) && document.activeElement.closest('[data-save-first]'), 'focus goes to its first field: ' + document.activeElement?.outerHTML?.slice(0, 120));
+ one.root.unmount();
+ const two = await connectForm({ store: 'bitwarden', local_count: 0, approvals_off: true, bitwarden: { server_url: 'https://vault.bitwarden.com', email: '[email protected]', login: 'password', unlocked: false } }, []);
+ const gate = document.querySelector('[data-save-first]');
+ assert.equal(gate.dataset.saveFirst, 'locked');
+ assert.ok(document.activeElement === gate.querySelector('[data-save-first-bitwarden]'), 'Unlock is focused');
+ assert.equal(gate.querySelector('[data-save-first-bitwarden]').textContent.trim(), 'Unlock Bitwarden');
+ assert.equal(gate.querySelector('[data-save-first-ask]'), null);
+ two.root.unmount();
+});
+
+test('B3 DOM: Connect lands on the GitHub form once the page has loaded: scrolled into view, token focused; not before', async () => {
+ reset({});
+ const scrolled = [];
+ const proto = window.HTMLElement.prototype;
+ const had = proto.scrollIntoView;
+ proto.scrollIntoView = function (o) {
+ scrolled.push([this.dataset.addSource, o?.block]);
+ };
+ const props = { sources: [], error: null, onChanged: noop, initialAdding: true, initialKind: 'github', onAdded: noop };
+ const { root } = await mount(h(m.LooseSources, { ...props, settled: false }));
+ assert.deepEqual(scrolled, [], 'nothing moves while the cases above are still loading');
+ assert.ok(document.activeElement?.type !== 'password');
+ root.render(h(m.LooseSources, { ...props, settled: true }));
+ await settle(20);
+ await frame();
+ assert.deepEqual(scrolled, [['github', 'start']]);
+ assert.ok(document.activeElement === document.querySelector('input[type="password"]'), 'focus: document.querySelector(\'input[type="password"]\')');
+ root.unmount();
+ proto.scrollIntoView = had;
+});
+
+test('B2/B3: Loose ends opened on its own (not from Connect) checks nothing and moves nothing', async () => {
+ reset({});
+ server.store = { store: 'local', local_count: 0, approvals_off: true };
+ const { root } = await mount(h(m.LooseSources, { sources: [], error: null, onChanged: noop, initialAdding: true, onAdded: noop }));
+ assert.equal(server.calls.filter(([, u]) => u === '/api/passwords/store').length, 0);
+ assert.equal(document.querySelector('[data-save-first]'), null);
+ root.unmount();
+});
+
+const withSwitch = async (props = {}) => {
+ reset({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] });
+ const page = document.createElement('div');
+ page.innerHTML = '<button data-dev-switch="on" id="sw">dev</button><a href="#x" id="after">Dev desk</a><button id="later">Later</button>';
+ document.body.appendChild(page);
+ const st = m.parseDevMode(server.state);
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(h(m.DevOnToast, { state: st, onOpenDesk: noop, onTypeRepo: noop, onUndo: async () => {}, onClose: noop, ...props }));
+ await settle();
+ return { root, sw: document.getElementById('sw'), after: document.getElementById('after') };
+};
+const tab = (el, shift = false) => {
+ const e = new window.KeyboardEvent('keydown', { key: 'Tab', shiftKey: shift, bubbles: true, cancelable: true });
+ el.dispatchEvent(e);
+ return e.defaultPrevented;
+};
+
+test('K1 DOM: Tab from the switch goes straight to the toast; Shift+Tab goes back; Tab from Dismiss carries on after the switch', async () => {
+ const { root, sw, after } = await withSwitch();
+ sw.focus();
+ assert.ok(document.activeElement === sw, 'nothing steals focus when the toast opens');
+ assert.equal(tab(sw), true);
+ const action = document.querySelector('[data-dev-on-toast-action]');
+ assert.ok(document.activeElement === action, 'one Tab: Open Dev desk');
+ assert.equal(action.textContent.trim(), 'Open Dev desk');
+ assert.equal(tab(action, true), true);
+ assert.ok(document.activeElement === sw, 'Shift+Tab: back to the switch');
+ const dismiss = document.querySelector('[data-dev-on-toast] [aria-label="Dismiss"]');
+ dismiss.focus();
+ assert.equal(tab(dismiss), true);
+ assert.ok(document.activeElement === after, 'the next stop after the switch, as if the toast sat right after it');
+ const undo = document.querySelector('[data-dev-on-toast-undo]');
+ undo.focus();
+ assert.equal(tab(undo), false, 'Undo → Dismiss is the normal order');
+ root.unmount();
+});
+
+test('K1 DOM: the toast stays while keyboard focus or the pointer is on the switch, and goes after its time once they leave', async () => {
+ let closed = 0;
+ const { root, sw } = await withSwitch({ onClose: () => closed++, timeout: 40 });
+ sw.focus();
+ sw.dispatchEvent(new window.FocusEvent('focus'));
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(closed, 0, 'held while focus is on the switch');
+ sw.blur();
+ sw.dispatchEvent(new window.Event('pointerenter'));
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(closed, 0, 'held while the pointer is over the switch');
+ sw.dispatchEvent(new window.Event('pointerleave'));
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(closed, 1);
+ root.unmount();
+});
+
+test('K1 DOM: Dismiss from the keyboard puts focus back on the switch', async () => {
+ let closed = 0;
+ const { root, sw } = await withSwitch({ onClose: () => closed++ });
+ const dismiss = document.querySelector('[data-dev-on-toast] [aria-label="Dismiss"]');
+ dismiss.focus();
+ await click(dismiss);
+ assert.equal(closed, 1);
+ assert.ok(document.activeElement === sw, 'focus: sw');
+ root.unmount();
+});
+
+test('minor: the Dev desk row reads "Dev desk, 0 landed…" (a separator for screen readers), never "Dev desk0 landed"', async () => {
+ reset({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] });
+ m.devStore.set('spc_demo', m.parseDevMode(server.state));
+ const { root } = await mount(h(m.DevDeskRow, { spaceId: 'spc_demo', active: false, onOpen: noop }));
+ await settle(20);
+ const row = document.querySelector('[data-dev-desk-row]');
+ assert.doesNotMatch(row.textContent, /Dev desk\d/);
+ assert.match(row.textContent, /^Dev desk, /);
+ assert.ok(row.querySelector('.sr-only'), 'the comma is for screen readers only');
+ root.unmount();
+});
+
+test('minor: the switch starts from the last value seen here, so an on space never shows "off" while it loads', async () => {
+ reset({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] });
+ m.lastOn.set('spc_demo', true);
+ let release;
+ assert.equal(m.lastOn.get('spc_never'), null, 'never seen here: no guess');
+ const realFetch = g.fetch;
+ g.fetch = g.window.fetch = (url, init) => (String(url).includes('/dev_mode') ? new Promise((r) => (release = () => r(realFetch(url, init)))) : realFetch(url, init));
+ const { root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
+ assert.equal(document.querySelector('[data-dev-switch]').getAttribute('aria-checked'), 'true', 'on from the first frame');
+ release();
+ await settle(20);
+ assert.equal(document.querySelector('[data-dev-switch]').getAttribute('aria-checked'), 'true');
+ g.fetch = g.window.fetch = realFetch;
+ root.unmount();
+ reset({ on: false });
+ const off = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
+ await settle(20);
+ assert.equal(m.lastOn.get('spc_demo'), false, 'turned off elsewhere: remembered as off');
+ off.root.unmount();
+});
+
+test('F8-R3-1: a space never seen in this browser shows the switch as loading (neither on nor off) until dev_mode answers', async () => {
+ reset({ status: 'watching', repo: 'demo-org/demo-web', branch: 'main', sources: [SOURCES[0]] });
+ localStorage.removeItem(m.lastOn.key('spc_demo'));
+ let release;
+ const realFetch = g.fetch;
+ g.fetch = g.window.fetch = (url, init) => (String(url).includes('/dev_mode') ? new Promise((r) => (release = () => r(realFetch(url, init)))) : realFetch(url, init));
+ const { root } = await mount(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' } }));
+ const sw = () => document.querySelector('[role="switch"]');
+ assert.equal(sw().dataset.devSwitch, 'loading');
+ assert.equal(sw().getAttribute('aria-busy'), 'true');
+ assert.equal(sw().disabled, true, 'not pressable before its state is known');
+ assert.equal(sw().hasAttribute('data-on'), false);
+ assert.equal(sw().querySelector('.kw-dv-node').getAttribute('visibility'), 'hidden', 'no node on either side');
+ release();
+ await settle(20);
+ assert.notEqual(sw().dataset.devSwitch, 'loading');
+ assert.equal(sw().getAttribute('aria-checked'), 'true');
+ assert.equal(sw().hasAttribute('aria-busy'), false);
+ assert.equal(sw().disabled, false);
+ assert.equal(sw().querySelector('.kw-dv-node').hasAttribute('visibility'), false);
+ assert.equal(m.lastOn.get('spc_demo'), true, 'the next load starts on');
+ g.fetch = g.window.fetch = realFetch;
+ root.unmount();
+});
diff --git a/frontend/tests/devMode.test.mjs b/frontend/tests/devMode.test.mjs
index caaf70f6..9b103199 100644
--- a/frontend/tests/devMode.test.mjs
+++ b/frontend/tests/devMode.test.mjs
@@ -143,7 +143,7 @@ test('Esc and blur re-cover an armed switch; they do nothing when covered', () =
assert.equal(s.on, true, type);
assert.equal(s.announce.text, 'Dev mode stays on.', type);
}
- const covered = m.initialSwitch();
+ const covered = m.initialSwitch({ on: true });
assert.equal(R(covered, { type: 'escape' }), covered);
assert.equal(R(covered, { type: 'blur' }), covered);
});
@@ -159,24 +159,8 @@ test('reduced motion: nothing to settle; on is one press, off still two', () =>
assert.equal(s.on, true);
});
-test('first time (older server): one press opens the setup (pending); cancel covers, done flips on', () => {
- let s = R(m.initialSwitch(), { type: 'press', now: 0 });
- 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(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 });
+ let s = R(R(m.initialSwitch({ on: true }), { 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);
@@ -184,6 +168,8 @@ test('a failed save puts the switch back, covered, with the reason announced', (
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.');
+ const f = R(R(m.initialSwitch(), { type: 'press', now: 0 }), { type: 'save_failed', error: 'Offline.' });
+ assert.equal(f.on, false, 'a failed one-press on goes back to off');
});
test('the server changing Dev mode closes a held-open cover; a disabled switch says so', () => {
@@ -410,13 +396,12 @@ test('DOM: reduced motion shows the same switch, turns on in one press and arms
delete window.matchMedia;
});
-test('switchLook names the visual state and the knob glyph: off, armed, on, pending, disabled', () => {
+test('switchLook names the visual state and the knob glyph: off, armed, on, disabled (0.7.1: no pending look)', () => {
const st = (o) => ({ ...m.initialSwitch({ reduced: false }), ...o });
const pick = (o) => { const l = m.switchLook(st(o)); return [l.look, l.glyph]; };
assert.deepEqual(pick({ on: false }), ['off', 'code']);
assert.deepEqual(pick({ on: true }), ['on', 'locked']);
assert.deepEqual(pick({ on: true, phase: 'lifted', liftedAt: 0 }), ['armed', 'unlocked']);
- assert.deepEqual(pick({ phase: 'pending' }), ['pending', 'code']);
assert.deepEqual(pick({ disabled: true, on: true }), ['disabled', 'locked']);
});
@@ -453,55 +438,35 @@ test('0.7.1 look (style v2 §10): the Branch switch; label dev → (one press) d
on.root.unmount();
});
-test('flip notes: HEAD → dev with one caret, and merged into main', () => {
+test('flip notes: HEAD → dev with one caret, and HEAD → main (flow copy §7)', () => {
const onNote = m.renderToStaticMarkup(h(m.DevFlipNote, { on: true, space: 'Trailhead', onDismiss: () => {} }));
assert.match(onNote, /role="status"/);
assert.match(onNote, /HEAD → dev/);
assert.match(onNote, /class="dv-caret"/);
assert.match(onNote, /Dev mode is on for Trailhead\./);
const offNote = m.renderToStaticMarkup(h(m.DevFlipNote, { on: false, approvals: 'smart', onDismiss: () => {} }));
- assert.match(offNote, /merged into main/);
- assert.match(offNote, /Dev mode is off\. Approvals stay on Smart\./);
+ assert.match(offNote, /HEAD → main/);
+ assert.match(offNote, /Dev mode is off\.<\/strong> Reviews, the ship gate and the production floor stopped\. Approvals stay on Smart\. What\s+landed keeps its history\./);
assert.doesNotMatch(offNote, /dv-caret/);
});
-test('DOM: first switch-on opens the setup sheet; typing checks after 400 ms; Turn on sends repo and branch', async () => {
+test('DOM 0.7.1: the first switch-on turns Dev mode on with no dialog and sends only {on: true}', 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);
- assert.equal(b.dataset.devSwitch, 'pending', 'one press opens the setup on an older server');
- assert.equal(b.dataset.armed, undefined, 'pending is not armed');
- 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);
+ let turnedOn = null;
+ root.render(h(m.DevModeSwitch, { space: { id: 'spc_demo', name: 'Demo' }, onTurnedOn: (s) => (turnedOn = s) }));
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.getAttribute('aria-checked'), 'false');
+ await click(b); // flow F1: one press
+ await settle();
+ assert.equal(turnedOn?.on, true, 'onTurnedOn gets the saved state, for the toast');
+ assert.equal(document.querySelector('[role="dialog"]'), null, 'no setup sheet');
+ assert.equal(document.querySelector('[data-dev-setup]'), null);
+ assert.deepEqual(server.calls.filter(([meth]) => meth === 'PUT').map(([, , body]) => body), [{ on: true }]);
+ assert.equal(server.calls.filter(([, u]) => u.endsWith('/check')).length, 0, 'no repo check');
assert.equal(b.dataset.on, 'true');
+ assert.equal(m.devStore.isOn('spc_demo'), true);
root.unmount();
});
@@ -654,10 +619,8 @@ test('round 2: on phone the hint is a viewport toast above the tab bar with the
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);
+ // 0.7.1: the switch no longer opens the sheet; the component is checked on its own.
+ const { root } = await mount(h(m.DevModeSetup, { space: { id: 'spc_demo', name: 'Demo' }, initial: null, onCancel() {}, onDone() {} }));
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))]'));