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.9.0 H1: Worktrees tab on the Dev desk (#493)

Oleksandr Ivanchenkoca4041c5da91
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 7ab53942..15c5c36e 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -4040,7 +4040,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}}
/>
);
- const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} onOpenLooseEnds={connectDevGitHub} teams={devTeamRefs(teams, kwants)} bots={kwants.map((k) => ({ id: k.id, name: k.name }))} onOpenChat={(id) => { if (!openTarget({ channel_id: null, kwant_id: id })) pushToast('That bot no longer exists.'); }} />;
+ const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} onOpenLooseEnds={connectDevGitHub} teams={devTeamRefs(teams, kwants)} bots={kwants.map((k) => ({ id: k.id, name: k.name, role: k.title }))} defaultBotId={!isChannel ? selectedId : null} onOpenChat={(id, thread) => { if (thread) { openThread(id, thread); return; } if (!openTarget({ channel_id: null, kwant_id: id })) pushToast('That bot no longer exists.'); }} />;
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 b018a55b..a8673c75 100644
--- a/frontend/src/components/DevDesk.tsx
+++ b/frontend/src/components/DevDesk.tsx
@@ -16,6 +16,9 @@ import { JiraHint, useJira } from './JiraSettings';
import { deskBadge } from '../dev/jiraSetup';
import { fetchCaller, lineNotesApi } from '../dev/lineNotesApi';
import { personFetch } from '../auth';
+import { WorktreesPanel, useWorktrees } from './dev/WorktreesTab';
+import { worktreeCount, worktreeStore } from '../dev/worktrees';
+import { usePhoneLayout } from '../usePhoneLayout';
/** 0.9.0 G1: the review cards' line notes, over the person's session. */
const LINE_NOTES = lineNotesApi(fetchCaller((input, init) => personFetch(input as string, init)));
@@ -198,7 +201,7 @@ export const DevDeskRow: React.FC<{ spaceId: string; active: boolean; onOpen: ()
// ---------------------------------------------------------------------------
// The page
-type Tab = 'landed' | 'reviews' | 'tickets';
+type Tab = 'landed' | 'reviews' | 'tickets' | 'worktrees';
export interface DevDeskViewProps {
spaceId: string;
@@ -214,12 +217,15 @@ export interface DevDeskViewProps {
/** The space's teams, so a team with no repo gets "Link a repo" in the repo list. */
teams?: DevTeamRef[];
/** 0.7.6: the space's bots, so a ticket's work reads "Built by Ann and Ben", not ids. */
- bots?: { id: string; name: string }[];
- /** 0.9.0 G1: "Open {bot}'s chat" after line notes are sent: opens that bot's 1:1. */
- onOpenChat?: (botId: string) => void;
+ bots?: { id: string; name: string; role?: string | null }[];
+ /** Opens a bot's chat: 0.9.0 G1 "Open {bot}'s chat" after line notes are sent (1:1, no thread), and
+ * 0.9.0 H1 the Worktrees tab's "Open chat" (that thread when the worktree has one). */
+ onOpenChat?: (botId: string, threadId?: string | null) => void;
+ /** 0.9.0 H1: the create dialog's default bot. */
+ defaultBotId?: string | null;
}
-export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds, teams, bots, onOpenChat }) => {
+export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds, teams, bots, onOpenChat, defaultBotId }) => {
const dev = useDevMode(spaceId);
const connect = (anchor?: HTMLElement) => (onOpenLooseEnds ? onOpenLooseEnds(anchor) : openGitHubConnect({ space: spaceId, anchor }));
// 0.7.2: with several repos, both lists filter by one (All · app · site) through `?repo=`.
@@ -242,6 +248,13 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
useEffect(() => {
if (tab === 'tickets' && !ticketsOn && !jira.loading) setTab('landed');
}, [tab, ticketsOn, jira.loading]);
+ // 0.9.0 H1: Worktrees shows while Dev mode is on and the server has the routes (#486).
+ const wt = useWorktrees(spaceId, !!dev?.on);
+ const worktreesOn = !!dev?.on && !wt.missing;
+ const phone = usePhoneLayout();
+ useEffect(() => {
+ if (tab === 'worktrees' && !worktreesOn) setTab('landed');
+ }, [tab, worktreesOn]);
// Flow F6: opening the desk clears the row badge on every device. On a deep link to /s/<space>/dev
// the store is still empty here, so the first state to arrive (fetched before the server saw the
// desk) is cleared too, and again once the server has it.
@@ -401,6 +414,7 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
const tabs: Array<{ key: Tab; label: string; count: number; tone?: 'needs' }> = [
{ key: 'landed', label: 'What landed', count: unseen },
{ key: 'reviews', label: 'Reviews', count: open },
+ ...(worktreesOn ? [{ key: 'worktrees' as Tab, label: 'Worktrees', count: worktreeCount(wt.list) }] : []),
...(ticketsOn ? [{ key: 'tickets' as Tab, label: 'Tickets', count: jira.needs, tone: 'needs' as const }] : []),
];
const onTabKey = (e: React.KeyboardEvent, i: number) => {
@@ -442,13 +456,13 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
)}
<button
type="button"
- onClick={() => void deskStore.load(spaceId, repo)}
- disabled={desk.loading}
+ onClick={() => void (tab === 'worktrees' ? worktreeStore.load(spaceId) : deskStore.load(spaceId, repo))}
+ disabled={tab === 'worktrees' ? wt.loading : desk.loading}
aria-label="Refresh"
data-dev-refresh
className="kw-btn-ghost shrink-0 max-sm:w-11 max-sm:h-11 max-sm:px-0 disabled:opacity-60"
>
- <RefreshCw size={14} className={desk.loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
+ <RefreshCw size={14} className={(tab === 'worktrees' ? wt.loading : desk.loading) ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
<span className="hidden sm:inline">Refresh</span>
</button>
</div>
@@ -496,7 +510,7 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
})}
</div>
- {filters.length > 1 && (
+ {filters.length > 1 && tab !== 'worktrees' && (
<div role="group" aria-label="Show cards from" className="kw-dv-filters" data-dev-repo-filters>
{[{ key: null as string | null, label: 'All', repo: 'All repos' }, ...filters].map((f) => (
<button
@@ -514,7 +528,7 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
</div>
)}
- {(desk.error || actionError) && (
+ {(desk.error || actionError) && tab !== 'worktrees' && (
<div role="alert" className="px-3 py-2 rounded-lg border border-rose-400/30 bg-rose-500/10 flex flex-wrap items-center gap-2 text-xs text-rose-100">
<span className="min-w-0 flex-1">{actionError ?? desk.error}</span>
{desk.error && !actionError && (
@@ -526,7 +540,9 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
)}
<div ref={panelRef} role="tabpanel" id={`${tabsId}-panel`} aria-labelledby={`${tabsId}-${tab}`} className="space-y-3">
- {tab === 'tickets' && ticketsOn ? (
+ {tab === 'worktrees' && worktreesOn ? (
+ <WorktreesPanel space={spaceId} data={wt} bots={bots ?? []} defaultBotId={defaultBotId} onOpenChat={onOpenChat} phone={phone} now={now} />
+ ) : tab === 'tickets' && ticketsOn ? (
<TicketsPanel space={spaceId} data={jira} names={ticketNames} />
) : tab === 'landed' && polling ? (
<SkeletonCards />
diff --git a/frontend/src/components/dev/WorktreesTab.tsx b/frontend/src/components/dev/WorktreesTab.tsx
new file mode 100644
index 00000000..99ba7b4e
--- /dev/null
+++ b/frontend/src/components/dev/WorktreesTab.tsx
@@ -0,0 +1,1020 @@
+// 0.9.0 H1 + P3: the Dev desk's Worktrees tab (Mira, designs/h1-worktrees.md). One group per linked repo,
+// a row per worktree, New worktree (new or existing branch) and Remove (refuses a dirty checkout until
+// "Remove anyway" is ticked; never deletes the branch). Finished worktrees carry the P3 cleanup line.
+
+import React, { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import { AlertTriangle, Check, Clock, Copy, Eraser, Folder, FolderGit2, GitBranch, Info, Loader2, MessageSquare, MoreHorizontal, Plus, Trash2 } from 'lucide-react';
+import {
+ BranchInfo,
+ OtherWorktree,
+ P3,
+ Worktree,
+ WorktreeError,
+ WorktreeRepo,
+ WorktreesData,
+ branchProblem,
+ branchSlug,
+ changesLabel,
+ createErrorCopy,
+ cleanToast,
+ keptNotes,
+ p3State,
+ removeErrorCopy,
+ rowStatus,
+ rowTask,
+ localNameOf,
+ pickableBranches,
+ createBodyFor,
+ rowTime,
+ shortPath,
+ suggestBranch,
+ upToDate,
+ worktreeApi,
+ worktreeStore,
+} from '../../dev/worktrees';
+import { ModernAvatar } from '../ModernAvatar';
+import { threadsApi } from '../../threads';
+import { trapFocusTarget } from '../../imports';
+
+const ring = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300';
+const FOCUSABLE = 'button:not([disabled]), input:not([disabled]), select:not([disabled]), a[href]';
+
+export interface WtBot {
+ id: string;
+ name: string;
+ role?: string | null;
+}
+
+export function useWorktrees(space: string, on: boolean): WorktreesData {
+ const data = useSyncExternalStore(worktreeStore.subscribe, () => worktreeStore.get(space), () => worktreeStore.get(space));
+ useEffect(() => {
+ if (on) void worktreeStore.load(space);
+ }, [space, on]);
+ return data;
+}
+
+interface Toast {
+ id: number;
+ text: string;
+ action?: { label: string; run: () => void };
+}
+
+export interface WorktreesPanelProps {
+ space: string;
+ data: WorktreesData;
+ bots: WtBot[];
+ /** "Last bot you chatted with in Dev mode": the create dialog's default. */
+ defaultBotId?: string | null;
+ onOpenChat?: (botId: string, threadId: string | null) => void;
+ /** Phone layout (below 768 px): ⋯ menus and bottom sheets. */
+ phone?: boolean;
+ now?: number;
+ home?: string | null;
+}
+
+export const WorktreesPanel: React.FC<WorktreesPanelProps> = ({ space, data, bots, defaultBotId, onOpenChat, phone = false, now: nowProp, home = null }) => {
+ const now = nowProp ?? Date.now();
+ const botName = useCallback((id: string | null) => (id ? bots.find((b) => b.id === id)?.name ?? null : null), [bots]);
+ const [creating, setCreating] = useState<WorktreeRepo | null>(null);
+ const [removing, setRemoving] = useState<Worktree | null>(null);
+ const [menu, setMenu] = useState<Worktree | null>(null);
+ const [announce, setAnnounce] = useState('');
+ const [toasts, setToasts] = useState<Toast[]>([]);
+ const [busy, setBusy] = useState<Record<string, 'cleaning' | 'keeping' | undefined>>({});
+ const [failed, setFailed] = useState<Record<string, string | undefined>>({});
+ const [rowError, setRowError] = useState<Record<string, string | undefined>>({});
+ const returnFocus = useRef<HTMLElement | null>(null);
+
+ const toast = useCallback((text: string, action?: Toast['action']) => {
+ const id = Date.now() + Math.random();
+ setToasts((t) => [...t.slice(-2), { id, text, action }]);
+ setAnnounce(text);
+ setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 7000);
+ }, []);
+
+ const copyPath = useCallback((p: string) => {
+ const done = () => setAnnounce('Path copied');
+ navigator.clipboard?.writeText(p).then(done, done) ?? done();
+ }, []);
+
+ const keep = useCallback(
+ (w: Worktree, on: boolean) => {
+ setBusy((b) => ({ ...b, [w.id]: 'keeping' }));
+ worktreeApi
+ .keep(w.id, on)
+ .then((n) => n && worktreeStore.patch(space, n))
+ .catch((e: unknown) => setRowError((r) => ({ ...r, [w.id]: e instanceof Error ? e.message : 'Couldn’t change it.' })))
+ .finally(() => setBusy((b) => ({ ...b, [w.id]: undefined })));
+ },
+ [space],
+ );
+
+ const clean = useCallback(
+ (w: Worktree) => {
+ setBusy((b) => ({ ...b, [w.id]: 'cleaning' }));
+ setFailed((f) => ({ ...f, [w.id]: undefined }));
+ worktreeApi
+ .clean(w.id)
+ .then((n) => {
+ if (!n) return;
+ worktreeStore.patch(space, n);
+ toast(cleanToast(n));
+ })
+ .catch((e: unknown) => {
+ const code = e instanceof WorktreeError ? e.code : null;
+ const reason = code === 'working' ? `${botName(w.kwant_id) ?? 'a bot'} is working here` : code === 'missing' ? 'the folder is gone' : code === 'not_ours' ? 'the folder wasn’t made here' : e instanceof Error ? e.message.replace(/\.$/, '') : 'it failed';
+ setFailed((f) => ({ ...f, [w.id]: reason }));
+ })
+ .finally(() => setBusy((b) => ({ ...b, [w.id]: undefined })));
+ },
+ [space, botName, toast],
+ );
+
+ const forget = useCallback(
+ (w: Worktree) => {
+ setRowError((r) => ({ ...r, [w.id]: undefined }));
+ worktreeApi.remove(w.id, false).then(
+ () => void worktreeStore.load(space),
+ (e: unknown) => setRowError((r) => ({ ...r, [w.id]: removeErrorCopy({ code: e instanceof WorktreeError ? e.code : null, message: e instanceof Error ? e.message : 'it failed' }, botName(w.kwant_id)) })),
+ );
+ },
+ [space, botName],
+ );
+
+ const openRemove = (w: Worktree, from: HTMLElement | null) => {
+ returnFocus.current = from;
+ setMenu(null);
+ setRemoving(w);
+ };
+ const openCreate = (r: WorktreeRepo, from: HTMLElement | null) => {
+ returnFocus.current = from;
+ setCreating(r);
+ };
+ const closeDialog = () => {
+ setCreating(null);
+ setRemoving(null);
+ setMenu(null);
+ const el = returnFocus.current;
+ returnFocus.current = null;
+ if (el?.isConnected) el.focus();
+ };
+
+ const list = data.list;
+ const rowProps = { now, home, botName, busy, failed, rowError, phone, onOpenChat, copyPath, keep, clean, forget, openRemove, openMenu: (w: Worktree, from: HTMLElement) => ((returnFocus.current = from), setMenu(w)) };
+
+ let body: React.ReactNode;
+ if (!list && data.loading) body = <Loading />;
+ else if (!list && data.error)
+ body = (
+ <div role="alert" className="flex items-center gap-2 rounded-[14px] border border-hairline bg-surface-raised px-3.5 py-3 text-[13px] text-zinc-200" data-wt-error>
+ <AlertTriangle size={15} className="shrink-0 text-zinc-400" aria-hidden="true" />
+ <span className="min-w-0 flex-1">Couldn’t read the worktrees. {data.error}</span>
+ <button type="button" onClick={() => void worktreeStore.load(space)} className={`shrink-0 rounded-md px-2 py-1 text-sky-300 hover:bg-sky-500/10 ${ring}`}>
+ Try again
+ </button>
+ </div>
+ );
+ else if (!list || !list.repos.length)
+ body = <EmptyTerm out="(no repo yet)" title="Worktrees show up once there’s a repo." line="Link a repo from Dev mode in the sidebar." data="no-repo" />;
+ else
+ body = list.repos.map((r) => (
+ <RepoGroup key={r.repo} space={space} repo={r} home={home} phone={phone} onNew={(el) => openCreate(r, el)}>
+ {r.worktrees.map((w) => (
+ <WorktreeRow key={w.id} w={w} repo={r.repo} {...rowProps} />
+ ))}
+ {r.other.map((o) => (
+ <OtherRow key={o.path} o={o} home={home} phone={phone} copyPath={copyPath} />
+ ))}
+ </RepoGroup>
+ ));
+
+ return (
+ <div className="space-y-6" data-wt-panel>
+ <p className="hidden sm:block -mt-2 text-right text-[12px] text-zinc-500" data-wt-note>
+ Cleans build output an hour after a task finishes
+ </p>
+ {body}
+ <p className="sr-only" aria-live="polite" data-wt-live>
+ {announce}
+ </p>
+ {toasts.length > 0 && (
+ <div className="fixed inset-x-0 bottom-4 z-[70] flex flex-col items-center gap-2 px-4 pointer-events-none" data-wt-toasts>
+ {toasts.map((t) => (
+ <div key={t.id} className="kw-toast pointer-events-auto flex items-center gap-3 max-w-[480px] w-full sm:w-auto rounded-xl border border-zinc-700 bg-zinc-900/95 px-3.5 py-2.5 text-[13px] text-zinc-100 shadow-xl" data-wt-toast>
+ <span className="min-w-0 flex-1">{t.text}</span>
+ {t.action && (
+ <button type="button" onClick={t.action.run} className={`shrink-0 rounded-md px-2 py-1 font-medium text-sky-300 hover:bg-sky-500/10 ${ring}`}>
+ {t.action.label}
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ {creating && (
+ <CreateDialog
+ space={space}
+ repo={creating}
+ bots={bots}
+ defaultBotId={defaultBotId ?? null}
+ home={home}
+ phone={phone}
+ existing={creating.worktrees}
+ onClose={closeDialog}
+ onCreated={(w) => {
+ const who = botName(w.kwant_id);
+ closeDialog();
+ void worktreeStore.load(space);
+ toast(who ? `Worktree ready for ${who}` : 'Worktree ready', who && onOpenChat && w.kwant_id ? { label: 'Open chat', run: () => onOpenChat(w.kwant_id as string, w.thread_id) } : undefined);
+ }}
+ />
+ )}
+ {removing && (
+ <RemoveDialog
+ w={removing}
+ bot={botName(removing.kwant_id)}
+ home={home}
+ phone={phone}
+ onClose={closeDialog}
+ onRemoved={(w) => {
+ const who = botName(w.kwant_id);
+ closeDialog();
+ void worktreeStore.load(space);
+ toast(`Removed ${who ? `${who}’s` : 'the'} worktree. The branch ${w.branch} stays.`);
+ }}
+ />
+ )}
+ {menu && (
+ <RowSheet
+ w={menu}
+ bot={botName(menu.kwant_id)}
+ onClose={closeDialog}
+ onOpenChat={onOpenChat}
+ copyPath={copyPath}
+ keep={keep}
+ clean={clean}
+ openRemove={(w) => {
+ setMenu(null);
+ setRemoving(w);
+ }}
+ />
+ )}
+ </div>
+ );
+};
+
+// ---------------------------------------------------------------------------
+// Groups and rows
+
+const RepoGroup: React.FC<{ space: string; repo: WorktreeRepo; home: string | null; phone: boolean; onNew: (el: HTMLElement) => void; children: React.ReactNode }> = ({ space, repo, home, phone, onNew, children }) => {
+ const n = repo.worktrees.length + repo.other.length;
+ const headId = useId();
+ return (
+ <section aria-labelledby={headId} data-wt-repo={repo.repo}>
+ <div className="mb-2 flex items-center gap-2">
+ <FolderGit2 size={15} className="shrink-0 text-zinc-300" aria-hidden="true" />
+ <h3 id={headId} className="min-w-0 flex flex-wrap items-baseline gap-x-2 text-[14px]">
+ <span className="font-semibold text-zinc-50">{repo.repo}</span>
+ <span className="text-zinc-500" data-wt-count>
+ {n === 1 ? '1 worktree' : `${n} worktrees`}
+ </span>
+ {!phone && repo.checkout && (
+ <span className="font-mono text-[11.5px] text-zinc-500">
+ {shortPath(repo.checkout, home)} · main checkout
+ </span>
+ )}
+ </h3>
+ <span className="flex-1" />
+ {!repo.error && (
+ <button
+ type="button"
+ onClick={(e) => onNew(e.currentTarget)}
+ aria-label={phone ? `New worktree in ${repo.repo}` : undefined}
+ data-wt-new
+ className={`kw-btn-ghost shrink-0 ${phone ? 'w-11 h-11 px-0 justify-center' : ''} ${ring}`}
+ >
+ <Plus size={14} aria-hidden="true" />
+ {!phone && <span>New worktree</span>}
+ </button>
+ )}
+ </div>
+ {repo.error ? (
+ <RepoError space={space} repo={repo.repo} />
+ ) : n === 0 ? (
+ <EmptyTerm
+ out={`${repo.checkout ? shortPath(repo.checkout, home) : repo.repo} [${repo.default_branch ?? 'main'}]`}
+ title="Each bot task can get its own folder."
+ line="Bots then work side by side without touching each other’s files. kwant cleans build output an hour after a task finishes."
+ data="empty"
+ >
+ <button type="button" onClick={(e) => onNew(e.currentTarget)} className={`kw-btn-primary mt-3 ${ring}`} data-wt-empty-new>
+ <Plus size={14} aria-hidden="true" /> New worktree
+ </button>
+ </EmptyTerm>
+ ) : (
+ <ul className="rounded-[14px] border border-hairline bg-surface-raised divide-y divide-[color:var(--kw-hairline)]">{children}</ul>
+ )}
+ </section>
+ );
+};
+
+const RepoError: React.FC<{ space: string; repo: string }> = ({ space, repo }) => (
+ <div className="rounded-[14px] border border-hairline bg-surface-raised px-3.5 py-3 flex items-center gap-2.5 text-[13px] text-zinc-200" role="alert" data-wt-repo-error>
+ <AlertTriangle size={15} className="shrink-0 text-zinc-400" aria-hidden="true" />
+ <span className="min-w-0 flex-1">Couldn’t read the worktrees of {repo}.</span>
+ <button type="button" onClick={() => void worktreeStore.load(space)} className={`shrink-0 rounded-md px-2 py-1 font-medium text-sky-300 hover:bg-sky-500/10 min-h-[32px] ${ring}`}>
+ Try again
+ </button>
+ </div>
+);
+
+interface RowProps {
+ w: Worktree;
+ repo: string;
+ now: number;
+ home: string | null;
+ phone: boolean;
+ botName: (id: string | null) => string | null;
+ busy: Record<string, 'cleaning' | 'keeping' | undefined>;
+ failed: Record<string, string | undefined>;
+ rowError: Record<string, string | undefined>;
+ onOpenChat?: (botId: string, threadId: string | null) => void;
+ copyPath: (p: string) => void;
+ keep: (w: Worktree, on: boolean) => void;
+ clean: (w: Worktree) => void;
+ forget: (w: Worktree) => void;
+ openRemove: (w: Worktree, from: HTMLElement | null) => void;
+ openMenu: (w: Worktree, from: HTMLElement) => void;
+}
+
+const IconBtn: React.FC<{ label: string; title?: string; disabled?: boolean; describe?: string; onClick: (e: React.MouseEvent<HTMLButtonElement>) => void; children: React.ReactNode; data?: string }> = ({ label, title, disabled, describe, onClick, children, data }) => {
+ const descId = useId();
+ return (
+ <>
+ <button
+ type="button"
+ aria-label={label}
+ title={title ?? label}
+ aria-disabled={disabled || undefined}
+ aria-describedby={describe ? descId : undefined}
+ onClick={(e) => (disabled ? e.preventDefault() : onClick(e))}
+ data-wt-act={data}
+ className={`w-[30px] h-[30px] inline-flex items-center justify-center rounded-lg text-zinc-400 ${disabled ? 'opacity-40 cursor-not-allowed' : 'hover:text-zinc-100 hover:bg-white/[0.06]'} ${ring}`}
+ >
+ {children}
+ </button>
+ {describe && (
+ <span id={descId} className="sr-only">
+ {describe}
+ </span>
+ )}
+ </>
+ );
+};
+
+const WorktreeRow: React.FC<RowProps> = ({ w, repo, now, home, phone, botName, busy, failed, rowError, onOpenChat, copyPath, keep, clean, forget, openRemove, openMenu }) => {
+ const st = rowStatus(w, now);
+ const bot = botName(w.kwant_id);
+ const who = bot ?? 'You';
+ const path = shortPath(w.path, home);
+ const err = rowError[w.id];
+
+ if (st.kind === 'missing' || st.kind === 'leftover' || st.kind === 'leftover_foreign') {
+ const missing = st.kind === 'missing';
+ return (
+ <li className="grid grid-cols-[22px_1fr_auto] gap-3 px-3.5 py-3 items-start" data-wt-row={w.id} data-wt-state={st.kind}>
+ <Folder size={18} className="mt-0.5 text-zinc-400" aria-hidden="true" />
+ <div className="min-w-0">
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[14px]">
+ <span className="dv-led" data-s={st.led} aria-hidden="true" />
+ <span className="font-semibold text-zinc-50">{st.text}</span>
+ {missing ? <Branch name={w.branch} /> : <span className="font-mono text-[12px] text-zinc-400 break-all">{path}</span>}
+ </p>
+ <p className="mt-1 text-[12.5px] text-zinc-300">
+ {missing ? `Git still lists ${path}, but the folder is gone.` : st.kind === 'leftover' ? `Git doesn’t list it any more. It was a worktree of ${repo}, so kwant can remove it.` : `This folder isn’t from ${repo}, so kwant won’t delete it.`}
+ </p>
+ {err && (
+ <p role="alert" className="mt-1 text-[12px] text-rose-300">
+ {err}
+ </p>
+ )}
+ </div>
+ {st.kind !== 'leftover_foreign' && (
+ <button type="button" onClick={(e) => (missing ? forget(w) : openRemove(w, e.currentTarget))} className={`kw-btn-ghost ${phone ? 'min-h-[44px]' : ''} ${ring}`} data-wt-act={missing ? 'forget' : 'remove-folder'}>
+ {missing ? 'Forget it' : 'Remove folder'}
+ </button>
+ )}
+ </li>
+ );
+ }
+
+ const changes = changesLabel(w.dirty);
+ const time = rowTime(w, now);
+ const p3 = p3State(w, { cleaning: busy[w.id] === 'cleaning', failed: failed[w.id] });
+ const blocked = w.working ? `${who} is working here. Stop ${who} first.` : undefined;
+ const removeLabel = bot ? `Remove ${bot}’s worktree` : 'Remove this worktree';
+ return (
+ <li className={`grid ${phone ? 'grid-cols-[24px_1fr_44px]' : 'grid-cols-[22px_1fr_auto]'} gap-3 px-3.5 py-3 items-start`} data-wt-row={w.id} data-wt-state={st.kind}>
+ <ModernAvatar name={who} role={w.kwant_id ? undefined : 'person'} size={phone ? 24 : 22} kwantId={w.kwant_id ?? undefined} />
+ <div className="min-w-0">
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[14px]">
+ <span className="dv-led" data-s={st.led} aria-hidden="true" />
+ <span className="font-semibold text-zinc-50">{who}</span>
+ <span className="text-zinc-400" data-wt-status>
+ {st.text}
+ </span>
+ <span className={phone ? 'basis-full' : ''}>
+ <Branch name={w.branch} />
+ </span>
+ </p>
+ <p className="mt-1 text-[12.5px] text-zinc-300 break-words" data-wt-task>
+ {rowTask(w, now)}
+ </p>
+ <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11.5px] text-zinc-500" data-wt-facts>
+ {changes &&
+ (w.dirty === 0 ? (
+ <span className="inline-flex items-center gap-1">
+ <Check size={12} aria-hidden="true" /> {changes}
+ </span>
+ ) : (
+ <span className="text-zinc-200" data-wt-dirty>
+ <span aria-hidden="true">● </span>
+ {changes}
+ </span>
+ ))}
+ {upToDate(w) ? (
+ <span className="font-mono">up to date</span>
+ ) : (
+ <>
+ {!!w.ahead && (
+ <span style={{ color: 'var(--dv-add)' }} aria-label={`${w.ahead} ahead of ${w.base ?? 'the default branch'}`}>
+ ↑{w.ahead}
+ </span>
+ )}
+ {!!w.behind && (
+ <span style={{ color: 'var(--dv-del)' }} aria-label={`${w.behind} behind ${w.base ?? 'the default branch'}`}>
+ ↓{w.behind}
+ </span>
+ )}
+ </>
+ )}
+ {!phone && <span className="font-mono text-zinc-400 break-all">{path}</span>}
+ {time && <span data-wt-time>{time}</span>}
+ </p>
+ {p3 && <P3Line p={p3} w={w} busy={!!busy[w.id]} keep={keep} clean={clean} />}
+ {err && (
+ <p role="alert" className="mt-1 text-[12px] text-rose-300">
+ {err}
+ </p>
+ )}
+ </div>
+ {phone ? (
+ <button type="button" aria-label={`More for ${bot ? `${bot}’s` : 'this'} worktree`} aria-haspopup="dialog" onClick={(e) => openMenu(w, e.currentTarget)} className={`w-11 h-11 -mr-1.5 inline-flex items-center justify-center rounded-lg text-zinc-300 hover:bg-white/[0.06] ${ring}`} data-wt-more>
+ <MoreHorizontal size={18} aria-hidden="true" />
+ </button>
+ ) : (
+ <div className="flex items-center gap-1">
+ {w.kwant_id && onOpenChat && (
+ <IconBtn label={`Open ${bot ?? 'the bot'}’s chat`} onClick={() => onOpenChat(w.kwant_id as string, w.thread_id)} data="chat">
+ <MessageSquare size={15} aria-hidden="true" />
+ </IconBtn>
+ )}
+ <IconBtn label="Copy the folder path" onClick={() => copyPath(w.path)} data="copy">
+ <Copy size={15} aria-hidden="true" />
+ </IconBtn>
+ <IconBtn label={removeLabel} title={blocked ?? removeLabel} disabled={w.working} describe={blocked} onClick={(e) => openRemove(w, e.currentTarget)} data="remove">
+ <Trash2 size={15} aria-hidden="true" />
+ </IconBtn>
+ </div>
+ )}
+ </li>
+ );
+};
+
+const OtherRow: React.FC<{ o: OtherWorktree; home: string | null; phone: boolean; copyPath: (p: string) => void }> = ({ o, home, phone, copyPath }) => (
+ <li className={`grid ${phone ? 'grid-cols-[24px_1fr_44px]' : 'grid-cols-[22px_1fr_auto]'} gap-3 px-3.5 py-3 items-start`} data-wt-row={o.path} data-wt-state={o.missing ? 'outside-missing' : 'outside'}>
+ <Folder size={18} className="mt-0.5 text-zinc-400" aria-hidden="true" />
+ <div className="min-w-0">
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[14px]">
+ <span className="dv-led" data-s={o.missing ? 'warn' : 'off'} aria-hidden="true" />
+ <span className="font-semibold text-zinc-50">{o.missing ? 'Folder missing' : o.folder_name}</span>
+ <span className="text-zinc-400">made outside kwant</span>
+ {o.branch && <Branch name={o.branch} />}
+ </p>
+ <p className="mt-1 text-[12.5px] text-zinc-300 break-words">
+ {o.missing ? `Git still lists ${shortPath(o.path, home)}, but the folder is gone.` : <span className="font-mono text-[11.5px] text-zinc-400 break-all">{shortPath(o.path, home)}</span>}
+ </p>
+ </div>
+ {!o.missing && (
+ <div className="flex items-center">
+ <IconBtn label="Copy the folder path" onClick={() => copyPath(o.path)} data="copy">
+ <Copy size={15} aria-hidden="true" />
+ </IconBtn>
+ </div>
+ )}
+ </li>
+);
+
+const Branch: React.FC<{ name: string }> = ({ name }) => (
+ <code className="dv-branch max-w-full" data-wt-branch>
+ <GitBranch className="i" aria-hidden="true" />
+ <span className="h">{name}</span>
+ </code>
+);
+
+const P3Line: React.FC<{ p: P3; w: Worktree; busy: boolean; keep: (w: Worktree, on: boolean) => void; clean: (w: Worktree) => void }> = ({ p, w, busy, keep, clean }) => {
+ const link = `rounded px-0.5 font-medium text-sky-300 hover:underline disabled:opacity-60 ${ring}`;
+ const notes = p.kind === 'cleaned' ? keptNotes(w) : [];
+ const Icon = p.kind === 'due' || p.kind === 'kept' ? Clock : p.kind === 'cleaning' ? Loader2 : p.kind === 'cleaned' ? Eraser : AlertTriangle;
+ return (
+ <p className="mt-2 inline-flex max-w-full items-start gap-1.5 rounded-md border border-hairline bg-white/[.03] px-2 py-[3px] text-[11.5px] leading-[18px] text-zinc-400" data-wt-p3={p.kind}>
+ <Icon size={12} className={`mt-[3px] shrink-0 ${p.kind === 'cleaning' ? 'animate-spin motion-reduce:animate-none' : ''}`} aria-hidden="true" />
+ <span className="min-w-0">
+ {p.kind === 'due' && (
+ <>
+ Build output{p.dirs.length ? ` (${p.dirs.join(', ')})` : ''} is cleaned at <strong className="font-semibold text-zinc-100">{p.at}</strong>
+ {' · '}
+ <button type="button" disabled={busy} onClick={() => keep(w, true)} className={link} data-wt-keep>
+ Keep it
+ </button>
+ </>
+ )}
+ {p.kind === 'kept' && (
+ <>
+ Build output kept{' · '}
+ <button type="button" disabled={busy || w.working} onClick={() => clean(w)} className={link} data-wt-clean>
+ Clean now
+ </button>
+ </>
+ )}
+ {p.kind === 'cleaning' && <span role="status">Cleaning build output…</span>}
+ {p.kind === 'cleaned' && (
+ <>
+ Cleaned <strong className="font-semibold text-zinc-100">{p.size}</strong> of build output at {p.at} ({p.dirs.join(', ')})
+ {notes.map((n) => (
+ <span key={n}>
+ {' · '}
+ <Info size={11} className="inline -mt-0.5" aria-hidden="true" /> {n}
+ </span>
+ ))}
+ </>
+ )}
+ {p.kind === 'failed' && (
+ <>
+ Couldn’t clean build output: {p.reason}. Nothing else was touched.{' · '}
+ <button type="button" disabled={busy} onClick={() => clean(w)} className={link} data-wt-retry>
+ Try again
+ </button>
+ </>
+ )}
+ </span>
+ </p>
+ );
+};
+
+const Loading: React.FC = () => (
+ <div data-wt-loading className="rounded-[14px] border border-hairline bg-surface-raised px-3.5 py-3.5">
+ <p role="status" className="flex items-center gap-2 text-[13px] text-zinc-300">
+ <Loader2 size={13} className="motion-safe:animate-spin" aria-hidden="true" /> Reading worktrees…
+ </p>
+ <div className="mt-3 space-y-2" aria-hidden="true">
+ {[62, 40, 58].map((w, i) => (
+ <span key={i} className={`kw-dv-skel-bar block h-2.5 ${i === 2 ? 'mt-4' : ''}`} style={{ width: `${w}%` }} />
+ ))}
+ </div>
+ </div>
+);
+
+const EmptyTerm: React.FC<{ out: string; title: string; line: string; data: string; children?: React.ReactNode }> = ({ out, title, line, data, children }) => (
+ <div className="rounded-2xl border border-dashed border-hairline-strong px-5 py-6" data-dev-empty data-wt-empty={data}>
+ <p className="font-mono text-[12px] text-zinc-500 break-words" aria-hidden="true">
+ <span className="text-sky-300">$</span> git worktree list
+ <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>
+ {children}
+ </div>
+);
+
+// ---------------------------------------------------------------------------
+// Dialogs: a centred 520 px box on desktop, a bottom sheet on the phone. Focus is trapped; Esc closes.
+
+const Dialog: React.FC<{ role: 'dialog' | 'alertdialog'; labelledBy: string; describedBy?: string; phone: boolean; onClose: () => void; busy?: boolean; children: React.ReactNode; data: string }> = ({ role, labelledBy, describedBy, phone, onClose, busy, children, data }) => {
+ const box = useRef<HTMLDivElement>(null);
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ if (!busy) onClose();
+ return;
+ }
+ if (e.key !== 'Tab' || !box.current) return;
+ const items = Array.from(box.current.querySelectorAll<HTMLElement>(FOCUSABLE));
+ const to = trapFocusTarget(items.length, items.indexOf(document.activeElement as HTMLElement), e.shiftKey);
+ if (to !== null) {
+ e.preventDefault();
+ items[to]?.focus();
+ }
+ };
+ return (
+ <div className={`fixed inset-0 z-[60] flex ${phone ? 'items-end' : 'items-center justify-center p-4'} bg-black/60 backdrop-blur-sm`} onMouseDown={(e) => e.target === e.currentTarget && !busy && onClose()} data-wt-dialog-backdrop>
+ <div
+ ref={box}
+ role={role}
+ aria-modal="true"
+ aria-labelledby={labelledBy}
+ aria-describedby={describedBy}
+ onKeyDown={onKeyDown}
+ data-wt-dialog={data}
+ className={
+ phone
+ ? 'kw-sheet w-full max-h-[90vh] overflow-y-auto rounded-t-2xl border-t border-zinc-800 bg-zinc-900 px-4 pt-4 pb-[calc(1rem+env(safe-area-inset-bottom))] shadow-2xl'
+ : 'w-full max-w-[520px] max-h-[90vh] overflow-y-auto rounded-2xl border border-hairline-strong bg-surface-overlay p-5 shadow-2xl'
+ }
+ >
+ {children}
+ </div>
+ </div>
+ );
+};
+
+const btnRow = (phone: boolean) => (phone ? 'mt-5 grid grid-cols-2 gap-2 [&>button]:h-[46px] [&>button]:justify-center' : 'mt-5 flex justify-end gap-2');
+
+const CreateDialog: React.FC<{
+ space: string;
+ repo: WorktreeRepo;
+ bots: WtBot[];
+ defaultBotId: string | null;
+ home: string | null;
+ phone: boolean;
+ existing: Worktree[];
+ onClose: () => void;
+ onCreated: (w: Worktree) => void;
+}> = ({ space, repo, bots, defaultBotId, home, phone, existing, onClose, onCreated }) => {
+ const ids = { title: useId(), sub: useId(), branch: useId(), hint: useId(), err: useId(), base: useId(), pick: useId() };
+ const forRef = useRef<HTMLSelectElement>(null);
+ const [bot, setBot] = useState<string>(() => (defaultBotId && bots.some((b) => b.id === defaultBotId) ? defaultBotId : bots[0]?.id ?? ''));
+ const botName = bots.find((b) => b.id === bot)?.name ?? null;
+ const [mode, setMode] = useState<'new' | 'existing'>('new');
+ const [branch, setBranch] = useState(() => suggestBranch(botName, null));
+ const [touched, setTouched] = useState(false);
+ const [base, setBase] = useState(repo.default_branch ?? 'main');
+ const [pick, setPick] = useState('');
+ const [branches, setBranches] = useState<BranchInfo[] | null>(null);
+ const [saving, setSaving] = useState(false);
+ const [serverErr, setServerErr] = useState<{ field: boolean; text: string } | null>(null);
+
+ useEffect(() => forRef.current?.focus(), []);
+ useEffect(() => {
+ if (!repo.team_id) return;
+ let live = true;
+ worktreeApi.branches(space, repo.team_id).then(
+ (b) => live && setBranches(b),
+ () => live && setBranches(null),
+ );
+ return () => {
+ live = false;
+ };
+ }, [space, repo.team_id]);
+ // The suggestion follows the bot until the person types their own name.
+ useEffect(() => {
+ if (!touched) setBranch(suggestBranch(botName, null));
+ }, [botName, touched]);
+
+ const pickedRemote = mode === 'existing' && branches?.find((b) => b.remote && b.name === pick) ? pick : null;
+ const name = (mode === 'new' ? branch : pickedRemote ? localNameOf(pick) : pick).trim();
+ const taken = useMemo(() => {
+ const w = existing.find((x) => x.branch === name && x.state !== 'removed');
+ if (w) return w.path;
+ return branches?.find((b) => b.name === name)?.checked_out_at ?? null;
+ }, [existing, branches, name]);
+ const slug = branchSlug(name);
+ const folderPath = `${shortPath(existing[0]?.path.replace(/\/[^/]+\/[^/]+$/, '') ?? '', home) || '…/worktrees'}/${repo.repo}/${slug}`;
+ const folderTaken = existing.some((x) => x.folder.endsWith(`/${slug}`) && x.branch !== name);
+ const exists = mode === 'new' && !!branches?.some((b) => !b.remote && b.name === name);
+ const problem = branchProblem(name);
+ const localErr = !name
+ ? null
+ : problem?.kind === 'spaces'
+ ? `Branch names can’t have spaces. Try ${problem.suggestion}.`
+ : problem
+ ? 'That isn’t a valid branch name.'
+ : taken
+ ? `${name} already has a worktree: ${shortPath(taken, home)}.`
+ : folderTaken
+ ? `${folderPath} already exists and isn’t empty. kwant won’t write into it.`
+ : exists
+ ? `${name} already exists. Pick Existing branch to use it, or choose another name.`
+ : null;
+ const fieldErr = localErr ?? (serverErr?.field ? serverErr.text : null);
+ const ok = !!name && !fieldErr && !saving && (mode === 'new' ? !!base.trim() : true);
+
+ const submit = () => {
+ if (!ok || !repo.team_id) return;
+ setSaving(true);
+ setServerErr(null);
+ // A bot's main 1:1 has no thread id and v1 keeps it in the team folder, so the worktree gets its own
+ // chat on that bot, titled with the branch (Lin, #486). Until `new_thread: true` lands there, make the
+ // thread first; if create then fails, the empty thread stays (harmless).
+ const fail = (e: unknown) => {
+ setSaving(false);
+ setServerErr(createErrorCopy({ code: e instanceof WorktreeError ? e.code : null, message: e instanceof Error ? e.message : 'it failed' }, { branch: name, path: folderPath, checkedOutAt: taken }));
+ };
+ const team = repo.team_id;
+ (bot ? threadsApi.create(bot, name).then((t) => t.id) : Promise.resolve(null))
+ .then((thread) => worktreeApi.create(space, createBodyFor({ team, mode, name, base: base.trim(), pickedRemote, bot, thread })))
+ .then(onCreated, fail);
+ };
+
+ const field = 'w-full h-10 rounded-lg border bg-black/30 px-3 text-[13.5px] text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300';
+ const seg = (on: boolean) => `text-left rounded-xl border px-3 py-2 ${on ? 'border-violet-400/70 bg-violet-500/15' : 'border-hairline-strong hover:bg-white/[0.04]'} ${ring}`;
+ const localBranches = branches?.filter((b) => !b.remote) ?? [];
+
+ return (
+ <Dialog role="dialog" labelledBy={ids.title} describedBy={ids.sub} phone={phone} onClose={onClose} busy={saving} data="create">
+ <h2 id={ids.title} className="flex items-center gap-2 text-[17px] font-semibold text-zinc-50">
+ <FolderGit2 size={17} aria-hidden="true" /> New worktree in {repo.repo}
+ </h2>
+ <p id={ids.sub} className="mt-1 text-[13px] text-zinc-400">
+ A separate folder for one bot’s task, so bots don’t work in each other’s files.
+ </p>
+ <form
+ className="mt-4 space-y-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ submit();
+ }}
+ >
+ <label className="block">
+ <span className="block mb-1.5 text-[13px] font-medium text-zinc-200">For</span>
+ <select ref={forRef} value={bot} onChange={(e) => setBot(e.target.value)} className={`${field} border-hairline-strong`} data-wt-for>
+ {bots.map((b) => (
+ <option key={b.id} value={b.id}>
+ {b.name}
+ </option>
+ ))}
+ <option value="">Nobody (just me)</option>
+ </select>
+ </label>
+ <fieldset>
+ <legend className="mb-1.5 text-[13px] font-medium text-zinc-200">Start from</legend>
+ <div className="grid grid-cols-2 gap-2" role="radiogroup">
+ {(
+ [
+ ['new', 'New branch', 'from a base branch'],
+ ['existing', 'Existing branch', 'check out one that’s there'],
+ ] as const
+ ).map(([k, t, s]) => (
+ <button key={k} type="button" role="radio" aria-checked={mode === k} onClick={() => (setMode(k), setServerErr(null))} className={seg(mode === k)} data-wt-mode={k}>
+ <span className="block text-[13.5px] font-semibold text-zinc-100">{t}</span>
+ <span className="block text-[12.5px] text-zinc-400">{s}</span>
+ </button>
+ ))}
+ </div>
+ </fieldset>
+ {mode === 'new' ? (
+ <div className={phone ? 'space-y-3' : 'grid grid-cols-[1fr_150px] gap-3'}>
+ <div>
+ <label htmlFor={ids.branch} className="block mb-1.5 text-[13px] font-medium text-zinc-200">
+ New branch
+ </label>
+ <input
+ id={ids.branch}
+ value={branch}
+ onChange={(e) => (setBranch(e.target.value), setTouched(true), setServerErr(null))}
+ spellCheck={false}
+ autoCapitalize="off"
+ autoComplete="off"
+ aria-invalid={!!fieldErr || undefined}
+ aria-describedby={fieldErr ? `${ids.err} ${ids.hint}` : ids.hint}
+ className={`${field} font-mono ${fieldErr ? 'border-rose-400/70' : 'border-violet-400/60'}`}
+ data-wt-branch-input
+ />
+ {fieldErr && (
+ <p id={ids.err} className="mt-1.5 text-[12.5px] text-rose-300 break-words" data-wt-field-error>
+ {fieldErr}
+ </p>
+ )}
+ <p id={ids.hint} className="mt-1 text-[12px] text-zinc-500">
+ Lowercase, no spaces. kwant suggests one from the task.
+ </p>
+ </div>
+ <div>
+ <label htmlFor={ids.base} className="block mb-1.5 text-[13px] font-medium text-zinc-200">
+ From
+ </label>
+ {localBranches.length ? (
+ <select id={ids.base} value={base} onChange={(e) => setBase(e.target.value)} className={`${field} font-mono border-hairline-strong`} data-wt-base>
+ {localBranches.map((b) => (
+ <option key={b.name} value={b.name}>
+ {b.name}
+ </option>
+ ))}
+ </select>
+ ) : (
+ <input id={ids.base} value={base} onChange={(e) => setBase(e.target.value)} spellCheck={false} autoCapitalize="off" className={`${field} font-mono border-hairline-strong`} data-wt-base />
+ )}
+ </div>
+ </div>
+ ) : (
+ <div>
+ <label htmlFor={ids.pick} className="block mb-1.5 text-[13px] font-medium text-zinc-200">
+ Branch
+ </label>
+ {branches && branches.length ? (
+ <select id={ids.pick} value={pick} onChange={(e) => (setPick(e.target.value), setServerErr(null))} aria-invalid={!!fieldErr || undefined} aria-describedby={fieldErr ? ids.err : undefined} className={`${field} font-mono border-hairline-strong`} data-wt-pick>
+ <option value="">Pick a branch</option>
+ {pickableBranches(branches).map((b) => (
+ <option key={`${b.remote}-${b.name}`} value={b.name} disabled={!!b.checked_out_at}>
+ {b.name}
+ {b.remote ? ' — new local branch' : ''}
+ {b.checked_out_at ? ` — checked out at ${shortPath(b.checked_out_at, home)}` : ''}
+ </option>
+ ))}
+ </select>
+ ) : (
+ <input id={ids.pick} value={pick} onChange={(e) => (setPick(e.target.value), setServerErr(null))} placeholder="the branch name" spellCheck={false} autoCapitalize="off" aria-invalid={!!fieldErr || undefined} aria-describedby={fieldErr ? ids.err : undefined} className={`${field} font-mono border-hairline-strong`} data-wt-pick />
+ )}
+ {fieldErr && (
+ <p id={ids.err} className="mt-1.5 text-[12.5px] text-rose-300 break-words" data-wt-field-error>
+ {fieldErr}
+ </p>
+ )}
+ </div>
+ )}
+ {name && !problem && (
+ <div className="rounded-lg border border-hairline bg-black/30 px-3 py-2 font-mono text-[12px] leading-5 text-zinc-300 break-all" data-wt-preview>
+ <div>
+ <span className="text-zinc-500">folder</span> {folderPath}
+ </div>
+ <div>
+ <span className="text-zinc-500">branch</span> {name} {mode === 'new' ? `(new, from ${base.trim() || '…'})` : pickedRemote ? `(new, from ${pickedRemote})` : '(existing)'}
+ </div>
+ </div>
+ )}
+ {serverErr && !serverErr.field && (
+ <p role="alert" className="text-[12.5px] text-rose-300" data-wt-dialog-error>
+ {serverErr.text}
+ </p>
+ )}
+ <div className={btnRow(phone)}>
+ <button type="button" onClick={onClose} disabled={saving} className={`kw-btn-ghost ${ring}`}>
+ Cancel
+ </button>
+ <button type="submit" disabled={!ok} className={`kw-btn-primary ${ring}`} data-wt-create>
+ {saving ? (
+ <>
+ <Loader2 size={14} className="motion-safe:animate-spin" aria-hidden="true" /> Creating…
+ </>
+ ) : (
+ 'Create worktree'
+ )}
+ </button>
+ </div>
+ </form>
+ </Dialog>
+ );
+};
+
+const RemoveDialog: React.FC<{ w: Worktree; bot: string | null; home: string | null; phone: boolean; onClose: () => void; onRemoved: (w: Worktree) => void }> = ({ w, bot, home, phone, onClose, onRemoved }) => {
+ const ids = { title: useId(), body: useId(), box: useId() };
+ const cancelRef = useRef<HTMLButtonElement>(null);
+ const [dirty, setDirty] = useState<{ n: number; changes: Worktree['changes'] }>({ n: w.dirty ?? 0, changes: w.changes });
+ const [force, setForce] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [err, setErr] = useState<string | null>(null);
+ useEffect(() => cancelRef.current?.focus(), []);
+ const leftover = w.state === 'leftover';
+ const n = dirty.n;
+ const needsForce = n > 0 && !leftover;
+ const go = () => {
+ if (saving || (needsForce && !force)) return;
+ setSaving(true);
+ setErr(null);
+ worktreeApi.remove(w.id, needsForce && force).then(
+ () => onRemoved(w),
+ (e: unknown) => {
+ setSaving(false);
+ if (e instanceof WorktreeError && e.code === 'dirty') {
+ // The checkout changed since the list was read: show what the server found and ask again.
+ const b = e.body ?? {};
+ const changes = Array.isArray(b.changes) ? (b.changes as Worktree['changes']) : [];
+ setDirty({ n: typeof b.dirty === 'number' ? b.dirty : changes.length, changes });
+ setForce(false);
+ return;
+ }
+ setErr(removeErrorCopy({ code: e instanceof WorktreeError ? e.code : null, message: e instanceof Error ? e.message : 'it failed' }, bot));
+ },
+ );
+ };
+ const commits = w.ahead && w.ahead > 0 ? `, with its ${w.ahead === 1 ? '1 commit' : `${w.ahead} commits`}` : '';
+ return (
+ <Dialog role="alertdialog" labelledBy={ids.title} describedBy={ids.body} phone={phone} onClose={onClose} busy={saving} data="remove">
+ <h2 id={ids.title} className="flex items-center gap-2 text-[17px] font-semibold text-zinc-50">
+ <Trash2 size={16} aria-hidden="true" /> {leftover ? 'Remove this leftover folder?' : bot ? `Remove ${bot}’s worktree?` : 'Remove this worktree?'}
+ </h2>
+ <p id={ids.body} className="mt-1.5 text-[13px] leading-relaxed text-zinc-400">
+ This deletes the folder <code className="rounded bg-black/40 px-1.5 py-0.5 font-mono text-[12px] text-zinc-200 break-all">{shortPath(w.path, home)}</code>. The branch <strong className="font-semibold text-zinc-100">{w.branch}</strong> stays{commits}.
+ </p>
+ {needsForce ? (
+ <>
+ <p className="mt-4 text-[13px] font-semibold text-zinc-100" data-wt-dirty-head>
+ {n === 1 ? '1 file has changes nobody committed. Removing loses it.' : `${n} files have changes nobody committed. Removing loses them.`}
+ </p>
+ <ul className="mt-2 rounded-lg border border-hairline bg-black/30 px-3 py-2 font-mono text-[12px] leading-[21px] text-zinc-300" data-wt-changes>
+ {dirty.changes.slice(0, 8).map((c) => (
+ <li key={c.path} className="break-all">
+ <span className={c.status === '?' ? 'text-zinc-500' : 'text-amber-300'}>{c.status === '??' ? '?' : c.status}</span> {c.path}
+ </li>
+ ))}
+ {n > Math.min(8, dirty.changes.length) && <li className="text-zinc-500">and {n - Math.min(8, dirty.changes.length)} more</li>}
+ </ul>
+ <label className="mt-3 flex items-center gap-2.5 text-[13px] text-zinc-200 min-h-[32px] cursor-pointer">
+ <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} className={`h-[18px] w-[18px] rounded accent-rose-600 ${ring}`} data-wt-force />
+ {n === 1 ? 'Remove anyway and lose this change' : `Remove anyway and lose these ${n} changes`}
+ </label>
+ </>
+ ) : (
+ <p className="mt-4 text-[13px] text-zinc-300">{leftover ? 'Git doesn’t list this folder any more.' : 'No uncommitted changes.'}</p>
+ )}
+ {err && (
+ <p role="alert" className="mt-3 text-[12.5px] text-rose-300" data-wt-dialog-error>
+ {err}
+ </p>
+ )}
+ <div className={btnRow(phone)}>
+ <button ref={cancelRef} type="button" onClick={onClose} disabled={saving} className={`kw-btn-ghost ${ring}`} data-wt-cancel>
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={go}
+ disabled={saving || (needsForce && !force)}
+ className={`inline-flex items-center gap-1.5 rounded-lg px-3.5 h-9 text-[13px] font-medium text-white bg-rose-700 hover:bg-rose-600 disabled:bg-rose-900/60 disabled:text-rose-200/50 disabled:cursor-not-allowed ${ring}`}
+ data-wt-remove
+ >
+ {saving && <Loader2 size={14} className="motion-safe:animate-spin" aria-hidden="true" />}
+ {leftover ? 'Remove folder' : 'Remove worktree'}
+ </button>
+ </div>
+ </Dialog>
+ );
+};
+
+/** Phone: the row's ⋯ opens these actions as a bottom sheet. */
+const RowSheet: React.FC<{
+ w: Worktree;
+ bot: string | null;
+ onClose: () => void;
+ onOpenChat?: (botId: string, threadId: string | null) => void;
+ copyPath: (p: string) => void;
+ keep: (w: Worktree, on: boolean) => void;
+ clean: (w: Worktree) => void;
+ openRemove: (w: Worktree) => void;
+}> = ({ w, bot, onClose, onOpenChat, copyPath, keep, clean, openRemove }) => {
+ const title = useId();
+ const first = useRef<HTMLButtonElement>(null);
+ useEffect(() => first.current?.focus(), []);
+ const item = 'w-full flex items-center gap-3 rounded-xl px-3 min-h-[48px] text-left text-[15px] text-zinc-100 hover:bg-white/[0.05] disabled:opacity-40';
+ const p3 = p3State(w);
+ const who = bot ?? 'You';
+ const act = (f: () => void) => () => {
+ f();
+ onClose();
+ };
+ return (
+ <Dialog role="dialog" labelledBy={title} phone onClose={onClose} data="row-menu">
+ <h2 id={title} className="px-3 pb-2 text-[13px] font-medium text-zinc-400">
+ {bot ? `${bot}’s worktree` : 'Your worktree'} · <span className="font-mono">{w.branch}</span>
+ </h2>
+ {w.kwant_id && onOpenChat && (
+ <button ref={first} type="button" className={`${item} ${ring}`} onClick={act(() => onOpenChat(w.kwant_id as string, w.thread_id))}>
+ <MessageSquare size={17} aria-hidden="true" /> Open chat
+ </button>
+ )}
+ <button ref={w.kwant_id && onOpenChat ? undefined : first} type="button" className={`${item} ${ring}`} onClick={act(() => copyPath(w.path))}>
+ <Copy size={17} aria-hidden="true" /> Copy path
+ </button>
+ {p3?.kind === 'due' && (
+ <button type="button" className={`${item} ${ring}`} onClick={act(() => keep(w, true))}>
+ <Clock size={17} aria-hidden="true" /> Keep build output
+ </button>
+ )}
+ {(p3?.kind === 'kept' || p3?.kind === 'due') && (
+ <button type="button" disabled={w.working} className={`${item} ${ring}`} onClick={act(() => clean(w))}>
+ <Eraser size={17} aria-hidden="true" /> Clean now
+ </button>
+ )}
+ <button type="button" disabled={w.working} className={`${item} text-rose-300 ${ring}`} onClick={() => openRemove(w)} aria-describedby={w.working ? `${title}-why` : undefined}>
+ <Trash2 size={17} aria-hidden="true" /> Remove
+ </button>
+ {w.working && (
+ <p id={`${title}-why`} className="px-3 pt-1 text-[12.5px] text-zinc-400">
+ {who} is working here. Stop {who} first.
+ </p>
+ )}
+ </Dialog>
+ );
+};
diff --git a/frontend/src/dev/worktreeFixtures.ts b/frontend/src/dev/worktreeFixtures.ts
new file mode 100644
index 00000000..3999ef0d
--- /dev/null
+++ b/frontend/src/dev/worktreeFixtures.ts
@@ -0,0 +1,114 @@
+// 0.9.0 H1: sample worktrees for the tests and the 390/1280 shots (the states in Mira's h1-states-board).
+// Names and paths are made up; the shape is Lin's contract v2 (GET /api/spaces/:id/dev/worktrees).
+
+export const NOW = Date.parse('2026-11-10T14:20:00Z');
+export const ROOT = '/home/ann/.kwant/spaces/sp1/worktrees';
+export const BOTS = [
+ { id: 'k-pixel', name: 'Pixel', role: 'frontend' },
+ { id: 'k-lin', name: 'Lin', role: 'backend' },
+ { id: 'k-rigel', name: 'Rigel', role: 'qa' },
+];
+
+const base = {
+ team_id: 't-shop',
+ team: 'Shop',
+ repo: 'shop',
+ base: 'main',
+ made_branch: true,
+ head: '3f2c9a1b7e',
+ changes: [],
+ ahead: 0,
+ behind: 0,
+ state: 'live',
+ ours: true,
+ working: false,
+ thread_id: null,
+ task_id: null,
+ kwant_id: null,
+ task_title: null,
+ created_at: '2026-11-10T09:12:00Z',
+ done_at: null,
+ clean_at: null,
+ keep_build: false,
+ cleaned_at: null,
+ cleaned: [],
+ cleaned_bytes: null,
+ kept: [],
+ removed_at: null,
+};
+
+export const wt = (id: string, branch: string, extra: Record<string, unknown> = {}) => ({
+ ...base,
+ id,
+ branch,
+ folder: `shop/${branch.toLowerCase().replace(/[^a-z0-9_]+/g, '-')}`,
+ path: `${ROOT}/shop/${branch.toLowerCase().replace(/[^a-z0-9_]+/g, '-')}`,
+ ...extra,
+});
+
+export const WORKING = wt('w1', 'pixel/inbox-empty-state', {
+ kwant_id: 'k-pixel',
+ thread_id: 'th-pixel',
+ working: true,
+ task_title: 'Inbox: empty state and keyboard order',
+ dirty: 3,
+ changes: [
+ { status: 'M', path: 'src/components/Inbox.tsx' },
+ { status: 'M', path: 'src/styles/modern.css' },
+ { status: '?', path: 'src/components/InboxEmpty.tsx' },
+ ],
+ ahead: 2,
+ behind: 0,
+});
+export const FINISHED_DUE = wt('w2', 'lin/worktree-routes', {
+ kwant_id: 'k-lin',
+ thread_id: 'th-lin',
+ task_title: 'Worktree routes and the cleanup job',
+ dirty: 0,
+ ahead: 4,
+ behind: 1,
+ done_at: '2026-11-10T13:42:00Z',
+ clean_at: '2026-11-10T14:42:00Z',
+});
+export const CLEANED = wt('w3', 'rigel/f6-notification', {
+ kwant_id: 'k-rigel',
+ task_title: 'QA: notification opens the origin chat',
+ dirty: 0,
+ ahead: 1,
+ behind: 3,
+ done_at: '2026-11-09T17:40:00Z',
+ cleaned_at: '2026-11-09T18:40:00Z',
+ cleaned: ['node_modules/.vite', 'target'],
+ cleaned_bytes: 1_240_000_000,
+ kept: [{ dir: 'dist', why: 'tracked' }],
+});
+export const MINE = wt('w4', 'try-vite-6', { dirty: 1, changes: [{ status: 'M', path: 'package.json' }], ahead: 0, behind: 0 });
+export const MISSING = wt('w5', 'old/spike', { state: 'missing', dirty: null, ahead: null, behind: null });
+
+export const LIST = {
+ repos: [
+ {
+ repo: 'shop',
+ team_id: 't-shop',
+ team: 'Shop',
+ checkout: '/home/ann/code/shop',
+ default_branch: 'main',
+ error: false,
+ worktrees: [WORKING, FINISHED_DUE, CLEANED, MINE],
+ other: [{ folder_name: 'shop-hotfix', path: '/home/ann/code/shop-hotfix', branch: 'hotfix/1.4.2', head: 'aa11bb2', missing: false }],
+ },
+ { repo: 'site', team_id: 't-site', team: 'Site', checkout: '/home/ann/code/site', default_branch: 'main', error: false, worktrees: [], other: [] },
+ ],
+ clean_after_minutes: 60,
+ build_dirs: ['target', 'node_modules/.vite', 'dist', '.next'],
+};
+
+export const BRANCHES = {
+ branches: [
+ { name: 'main', remote: false, checked_out_at: '/home/ann/code/shop' },
+ { name: 'origin/main', remote: true, checked_out_at: null },
+ { name: 'release/0.9', remote: false, checked_out_at: null },
+ { name: 'pixel/inbox-empty-state', remote: false, checked_out_at: `${ROOT}/shop/pixel-inbox-empty-state` },
+ { name: 'origin/feature/search', remote: true, checked_out_at: null },
+ ],
+};
diff --git a/frontend/src/dev/worktrees.ts b/frontend/src/dev/worktrees.ts
new file mode 100644
index 00000000..72335f61
--- /dev/null
+++ b/frontend/src/dev/worktrees.ts
@@ -0,0 +1,532 @@
+// 0.9.0 H1 + P3: the Dev desk's Worktrees tab. Types and client for Lin's routes (release-090/h1-contract.md
+// v2, PR #486), the pure copy helpers the tab and the tests share (Mira's designs/h1-worktrees.md), and one
+// cache per space. Until #486 merges the routes may 404: the tab then says the server doesn't have them yet.
+
+import { personFetch } from '../auth';
+
+export type WorktreeState = 'live' | 'missing' | 'leftover' | 'removed';
+
+export interface WorktreeChange {
+ status: string;
+ path: string;
+}
+
+export interface Worktree {
+ id: string;
+ team_id: string | null;
+ team: string | null;
+ repo: string;
+ folder: string;
+ path: string;
+ branch: string;
+ base: string | null;
+ made_branch: boolean;
+ head: string | null;
+ dirty: number | null;
+ changes: WorktreeChange[];
+ ahead: number | null;
+ behind: number | null;
+ state: WorktreeState;
+ ours: boolean;
+ working: boolean;
+ thread_id: string | null;
+ task_id: string | null;
+ kwant_id: string | null;
+ task_title: string | null;
+ /** The chat the worktree is bound to (contract v3); null without a thread. */
+ thread_title: string | null;
+ created_at: string | null;
+ done_at: string | null;
+ clean_at: string | null;
+ keep_build: boolean;
+ cleaned_at: string | null;
+ cleaned: string[];
+ cleaned_bytes: number | null;
+ kept: { dir: string; why: string }[];
+ removed_at: string | null;
+}
+
+/** A linked worktree git lists that kwant didn't make: read-only on the desk. */
+export interface OtherWorktree {
+ folder_name: string;
+ path: string;
+ branch: string | null;
+ head: string | null;
+ missing: boolean;
+}
+
+export interface WorktreeRepo {
+ repo: string;
+ team_id: string | null;
+ team: string | null;
+ checkout: string | null;
+ default_branch: string | null;
+ error: boolean;
+ worktrees: Worktree[];
+ other: OtherWorktree[];
+}
+
+export interface WorktreeList {
+ repos: WorktreeRepo[];
+ clean_after_minutes: number;
+ build_dirs: string[];
+}
+
+/** The create dialog's branch pickers (Lin, contract v3; optional until the route exists).
+ * A remote name carries its remote: `origin/foo`. */
+export interface BranchInfo {
+ name: string;
+ remote: boolean;
+ checked_out_at: string | null;
+}
+
+// ---------------------------------------------------------------------------
+// Parsing: the server's shape, defensively (an older or newer server never crashes the tab).
+
+const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
+const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const rec = (v: unknown): Record<string, unknown> | null => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null);
+const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
+
+export function parseWorktree(v: unknown): Worktree | null {
+ const o = rec(v);
+ const id = str(o?.id);
+ const path = str(o?.path);
+ const branch = str(o?.branch);
+ if (!o || !id || !path || !branch) return null;
+ const state = (['live', 'missing', 'leftover', 'removed'] as const).find((s) => s === o.state) ?? 'live';
+ return {
+ id,
+ team_id: str(o.team_id),
+ team: str(o.team),
+ repo: str(o.repo) ?? '',
+ folder: str(o.folder) ?? '',
+ path,
+ branch,
+ base: str(o.base),
+ made_branch: o.made_branch === true,
+ head: str(o.head),
+ dirty: num(o.dirty),
+ changes: arr(o.changes).flatMap((c) => {
+ const r = rec(c);
+ const p = str(r?.path);
+ return p ? [{ status: str(r?.status) ?? '?', path: p }] : [];
+ }),
+ ahead: num(o.ahead),
+ behind: num(o.behind),
+ state,
+ ours: o.ours !== false,
+ working: o.working === true,
+ thread_id: str(o.thread_id),
+ task_id: str(o.task_id),
+ kwant_id: str(o.kwant_id),
+ task_title: str(o.task_title),
+ thread_title: str(o.thread_title),
+ created_at: str(o.created_at),
+ done_at: str(o.done_at),
+ clean_at: str(o.clean_at),
+ keep_build: o.keep_build === true,
+ cleaned_at: str(o.cleaned_at),
+ cleaned: arr(o.cleaned).filter((d): d is string => typeof d === 'string'),
+ cleaned_bytes: num(o.cleaned_bytes),
+ kept: arr(o.kept).flatMap((k) => {
+ const r = rec(k);
+ const dir = str(r?.dir);
+ return dir ? [{ dir, why: str(r?.why) ?? '' }] : [];
+ }),
+ removed_at: str(o.removed_at),
+ };
+}
+
+export function parseList(v: unknown): WorktreeList | null {
+ const o = rec(v);
+ if (!o || !Array.isArray(o.repos)) return null;
+ return {
+ repos: o.repos.flatMap((r) => {
+ const g = rec(r);
+ const repo = str(g?.repo);
+ if (!g || !repo) return [];
+ return [
+ {
+ repo,
+ team_id: str(g.team_id),
+ team: str(g.team),
+ checkout: str(g.checkout),
+ default_branch: str(g.default_branch),
+ error: g.error === true,
+ worktrees: arr(g.worktrees)
+ .map(parseWorktree)
+ .filter((w): w is Worktree => !!w && w.state !== 'removed'),
+ other: arr(g.other).flatMap((x) => {
+ const q = rec(x);
+ const p = str(q?.path);
+ return p ? [{ folder_name: str(q?.folder_name) ?? p.split('/').pop() ?? p, path: p, branch: str(q?.branch), head: str(q?.head), missing: q?.missing === true }] : [];
+ }),
+ },
+ ];
+ }),
+ clean_after_minutes: num(o.clean_after_minutes) ?? 60,
+ build_dirs: arr(o.build_dirs).filter((d): d is string => typeof d === 'string'),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Client
+
+export class WorktreeError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ public code: string | null = null,
+ public body: Record<string, unknown> | null = null,
+ ) {
+ super(message);
+ }
+}
+
+async function call(url: string, method = 'GET', body?: unknown): Promise<unknown> {
+ let res: Response;
+ try {
+ res = await personFetch(url, {
+ method,
+ cache: 'no-store',
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch {
+ throw new WorktreeError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const data = await res.json().catch(() => null);
+ if (res.ok) return data;
+ const o = rec(data);
+ const code = str(o?.code);
+ const err = str(o?.error);
+ if (res.status === 404 && !code) throw new WorktreeError('This server doesn’t have worktrees yet. Update the app.', 404, 'no_route', o);
+ throw new WorktreeError(err ?? `Something went wrong (HTTP ${res.status}).`, res.status, code, o);
+}
+
+const enc = encodeURIComponent;
+
+export interface CreateBody {
+ team_id: string;
+ branch: string;
+ base?: string;
+ thread_id?: string;
+ kwant_id?: string;
+ task_id?: string;
+}
+
+export const worktreeApi = {
+ list: async (space: string): Promise<WorktreeList> => {
+ const l = parseList(await call(`/api/spaces/${enc(space)}/dev/worktrees`));
+ if (!l) throw new WorktreeError('The server sent worktrees in a shape this app doesn’t know.', 500);
+ return l;
+ },
+ /** Contract v3 (Lin, coming to #486). A 404 means "type the branch name". */
+ branches: async (space: string, team: string): Promise<BranchInfo[]> => {
+ const o = rec(await call(`/api/spaces/${enc(space)}/dev/worktrees/branches?team_id=${enc(team)}`));
+ return arr(o?.branches).flatMap((b) => {
+ const r = rec(b);
+ const name = str(r?.name);
+ return name ? [{ name, remote: r?.remote === true, checked_out_at: str(r?.checked_out_at) }] : [];
+ });
+ },
+ create: async (space: string, body: CreateBody): Promise<Worktree> => {
+ const w = parseWorktree(await call(`/api/spaces/${enc(space)}/dev/worktrees`, 'POST', body));
+ if (!w) throw new WorktreeError('The server sent the worktree in a shape this app doesn’t know.', 500);
+ return w;
+ },
+ remove: (id: string, force: boolean) => call(`/api/dev/worktrees/${enc(id)}?force=${force ? 'true' : 'false'}`, 'DELETE'),
+ keep: async (id: string, keep: boolean) => parseWorktree(await call(`/api/dev/worktrees/${enc(id)}/keep`, 'POST', { keep })),
+ clean: async (id: string) => parseWorktree(await call(`/api/dev/worktrees/${enc(id)}/clean`, 'POST', {})),
+};
+
+/** A remote-only `origin/foo` has no "existing branch" form in create: it goes in as a new local
+ * branch `foo` made from `origin/foo` (Lin, #486). Returns the local name. */
+export const localNameOf = (remote: string): string => remote.replace(/^[^/]+\//, '');
+
+/** The Existing picker: local branches, plus remote ones with no local branch of the same name. */
+export function pickableBranches(all: BranchInfo[]): BranchInfo[] {
+ const local = new Set(all.filter((b) => !b.remote).map((b) => b.name));
+ return all.filter((b) => !b.remote || !local.has(localNameOf(b.name)));
+}
+
+/** The create request for what the dialog holds. */
+export function createBodyFor(o: { team: string; mode: 'new' | 'existing'; name: string; base: string; pickedRemote: string | null; bot: string; thread: string | null }): CreateBody {
+ const b: CreateBody =
+ o.mode === 'new' ? { team_id: o.team, branch: o.name, base: o.base } : o.pickedRemote ? { team_id: o.team, branch: o.name, base: o.pickedRemote } : { team_id: o.team, branch: o.name };
+ if (o.bot) b.kwant_id = o.bot;
+ if (o.thread) b.thread_id = o.thread;
+ return b;
+}
+
+// ---------------------------------------------------------------------------
+// One cache per space; the tab count and the tab read it.
+
+export interface WorktreesData {
+ list: WorktreeList | null;
+ loading: boolean;
+ error: string | null;
+ /** The server has no worktree routes yet (#486 not merged there): the tab stays hidden. */
+ missing: boolean;
+}
+
+const EMPTY: WorktreesData = { list: null, loading: false, error: null, missing: false };
+const cache = new Map<string, WorktreesData>();
+const listeners = new Set<() => void>();
+const inflight = new Map<string, Promise<void>>();
+
+function put(space: string, patch: Partial<WorktreesData>) {
+ cache.set(space, { ...(cache.get(space) ?? EMPTY), ...patch });
+ listeners.forEach((l) => l());
+}
+
+export const worktreeStore = {
+ get: (space: string): WorktreesData => cache.get(space) ?? EMPTY,
+ subscribe(l: () => void) {
+ listeners.add(l);
+ return () => void listeners.delete(l);
+ },
+ load(space: string): Promise<void> {
+ const running = inflight.get(space);
+ if (running) return running;
+ put(space, { loading: true });
+ const p = worktreeApi
+ .list(space)
+ .then((list) => put(space, { list, loading: false, error: null, missing: false }))
+ .catch((e: unknown) => {
+ const gone = e instanceof WorktreeError && (e.code === 'no_route' || e.code === 'off');
+ put(space, { loading: false, missing: gone, error: gone ? null : e instanceof Error ? e.message : 'Couldn’t read the worktrees.' });
+ })
+ .finally(() => inflight.delete(space));
+ inflight.set(space, p);
+ return p;
+ },
+ /** One worktree changed (keep, clean): swap it in place. */
+ patch(space: string, w: Worktree) {
+ const l = cache.get(space)?.list;
+ if (!l) return;
+ put(space, { list: { ...l, repos: l.repos.map((r) => ({ ...r, worktrees: r.worktrees.map((x) => (x.id === w.id ? w : x)) })) } });
+ },
+ _set: (space: string, patch: Partial<WorktreesData>) => put(space, patch),
+ _reset() {
+ cache.clear();
+ inflight.clear();
+ },
+};
+
+/** The tab count: linked worktrees (kwant's and git's others), never the main checkout. */
+export const worktreeCount = (l: WorktreeList | null): number => (l ? l.repos.reduce((n, r) => n + r.worktrees.length + r.other.length, 0) : 0);
+
+// ---------------------------------------------------------------------------
+// Copy (designs/h1-worktrees.md "Copy (all)")
+
+const pad = (n: number) => String(n).padStart(2, '0');
+export const hhmm = (d: Date) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
+const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
+const dayStart = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
+
+/** "14:05" today, "yesterday", "Mon" within a week, else "3 Nov". */
+export function dayLabel(iso: string, now: number): { day: string; time: string; today: boolean } {
+ const d = new Date(iso);
+ const days = Math.round((dayStart(new Date(now)) - dayStart(d)) / 86_400_000);
+ const time = hhmm(d);
+ if (days <= 0) return { day: '', time, today: true };
+ if (days === 1) return { day: 'yesterday', time, today: false };
+ if (days < 7) return { day: DAYS[d.getDay()], time, today: false };
+ return { day: `${d.getDate()} ${d.toLocaleString('en', { month: 'short' })}`, time, today: false };
+}
+
+export type Led = 'run' | 'ok' | 'off' | 'warn';
+
+export interface RowStatus {
+ led: Led;
+ /** The words after the name (or the name's replacement for missing and leftover). */
+ text: string;
+ kind: 'working' | 'finished' | 'mine' | 'outside' | 'missing' | 'leftover' | 'leftover_foreign';
+}
+
+export function rowStatus(w: Worktree, now: number): RowStatus {
+ if (w.state === 'missing') return { led: 'warn', text: 'Folder missing', kind: 'missing' };
+ if (w.state === 'leftover') return { led: 'off', text: 'Leftover folder', kind: w.ours ? 'leftover' : 'leftover_foreign' };
+ if (w.working) return { led: 'run', text: 'is working here', kind: 'working' };
+ if (w.done_at) {
+ const f = dayLabel(w.done_at, now);
+ const fresh = now - new Date(w.done_at).getTime() < 86_400_000;
+ return { led: fresh ? 'ok' : 'off', text: `finished ${f.today ? f.time : f.day}`, kind: 'finished' };
+ }
+ return { led: 'off', text: 'made by you', kind: 'mine' };
+}
+
+/** Line 3's time: "active now", "finished Mon 17:40", or when it was made. */
+export function rowTime(w: Worktree, now: number): string | null {
+ if (w.working) return 'active now';
+ if (w.done_at) {
+ const f = dayLabel(w.done_at, now);
+ return `finished ${f.today ? f.time : `${f.day} ${f.time}`}`;
+ }
+ if (!w.created_at) return null;
+ const c = dayLabel(w.created_at, now);
+ return c.today ? c.time : `${c.day} ${c.time}`;
+}
+
+/** Line 2: the task, or how it was made. */
+export function rowTask(w: Worktree, now: number): string {
+ if (w.task_title) return w.task_title;
+ if (w.thread_title) return `Chat: ${w.thread_title}`;
+ if (!w.created_at) return 'No task.';
+ const c = dayLabel(w.created_at, now);
+ return `No task. Made from the Dev desk ${c.today ? c.time : `${c.day} ${c.time}`}`;
+}
+
+export const changesLabel = (dirty: number | null): string | null =>
+ dirty === null ? null : dirty === 0 ? 'No uncommitted changes' : dirty === 1 ? '1 uncommitted file' : `${dirty} uncommitted files`;
+
+export const upToDate = (w: { ahead: number | null; behind: number | null }) => w.ahead === 0 && w.behind === 0;
+
+/** "1.2 GB", "412 MB", "88 KB": decimal units, one decimal under 10. */
+export function sizeLabel(bytes: number): string {
+ const units = ['bytes', 'KB', 'MB', 'GB', 'TB'];
+ let v = bytes;
+ let i = 0;
+ while (v >= 1000 && i < units.length - 1) {
+ v /= 1000;
+ i++;
+ }
+ if (i === 0) return `${Math.round(v)} bytes`;
+ return `${v < 10 ? v.toFixed(1).replace(/\.0$/, '') : Math.round(v)} ${units[i]}`;
+}
+
+export type P3 =
+ | { kind: 'due'; at: string; dirs: string[] }
+ | { kind: 'kept' }
+ | { kind: 'cleaning' }
+ | { kind: 'cleaned'; size: string; at: string; dirs: string[] }
+ | { kind: 'failed'; reason: string };
+
+/** The P3 line under a finished worktree, or null (nothing to clean, or not finished). */
+export function p3State(w: Worktree, opts: { cleaning?: boolean; failed?: string | null } = {}): P3 | null {
+ if (w.state !== 'live' || !w.ours) return null;
+ if (opts.cleaning) return { kind: 'cleaning' };
+ if (opts.failed) return { kind: 'failed', reason: opts.failed };
+ if (w.clean_at && !w.keep_build) return { kind: 'due', at: hhmm(new Date(w.clean_at)), dirs: [] };
+ const cleaned = !!w.cleaned_at && w.cleaned.length > 0 && (w.cleaned_bytes ?? 0) > 0;
+ // A kept worktree shows "kept" until someone presses Clean now; a clean since this finish wins.
+ const cleanedSinceDone = cleaned && (!w.done_at || Date.parse(w.cleaned_at as string) >= Date.parse(w.done_at));
+ if (w.keep_build && w.done_at && !cleanedSinceDone) return { kind: 'kept' };
+ if (cleaned) {
+ return { kind: 'cleaned', size: sizeLabel(w.cleaned_bytes ?? 0), at: hhmm(new Date(w.cleaned_at as string)), dirs: w.cleaned.map((d) => d.split('/').pop() ?? d).filter((d, i, a) => a.indexOf(d) === i) };
+ }
+ return null;
+}
+
+/** The toast after a manual Clean now, from the server's answer. */
+export function cleanToast(w: Worktree): string {
+ const bytes = w.cleaned_bytes ?? 0;
+ if (!w.cleaned.length || bytes <= 0) return w.kept.length ? `Nothing cleaned. ${keptNotes(w).join(' ')}` : 'Nothing to clean: no build output left.';
+ return `Cleaned ${sizeLabel(bytes)} of build output.${w.kept.length ? ` ${keptNotes(w).join(' ')}` : ''}`;
+}
+
+/** "· Kept dist: Git tracks a file in it." for each skipped folder, after a clean. */
+export const keptNotes = (w: Worktree): string[] =>
+ w.kept.map((k) => (k.why === 'tracked' ? `Kept ${k.dir}: Git tracks a file in it.` : k.why === 'not_ignored' ? `Kept ${k.dir}: Git doesn’t ignore it.` : `Kept ${k.dir}.`));
+
+// ---------------------------------------------------------------------------
+// Branch names (create dialog)
+
+/** The folder slug, as Lin's server makes it (contract v2): lowercase, runs outside [a-z0-9_] → "-", 60 max. */
+export function branchSlug(branch: string): string {
+ const s = branch
+ .toLowerCase()
+ .replace(/[^a-z0-9_]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 60)
+ .replace(/-+$/g, '');
+ return s || 'worktree';
+}
+
+/** `git check-ref-format --branch`, close enough for the field; the server has the last word. */
+export function branchProblem(name: string): { kind: 'spaces'; suggestion: string } | { kind: 'invalid' } | null {
+ const n = name.trim();
+ if (!n) return null;
+ if (/\s/.test(n)) {
+ const suggestion = n.replace(/\s+/g, '-');
+ return { kind: 'spaces', suggestion: branchProblem(suggestion) ? branchSlug(suggestion) : suggestion };
+ }
+ if (
+ n === '@' ||
+ n.startsWith('-') ||
+ n.startsWith('/') ||
+ n.endsWith('/') ||
+ n.endsWith('.') ||
+ n.endsWith('.lock') ||
+ n.includes('..') ||
+ n.includes('//') ||
+ n.includes('@{') ||
+ /[~^:?*[\\\x00-\x1f\x7f]/.test(n) ||
+ n.split('/').some((c) => c.startsWith('.') || c.endsWith('.lock'))
+ )
+ return { kind: 'invalid' };
+ return null;
+}
+
+/** A branch name suggested from the bot and the task: "pixel/inbox-empty-state". */
+export function suggestBranch(bot: string | null, task: string | null): string {
+ const words = (task ?? '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, ' ')
+ .trim()
+ .split(' ')
+ .filter(Boolean)
+ .slice(0, 4)
+ .join('-');
+ const who = bot ? bot.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') : '';
+ return [who, words].filter(Boolean).join('/');
+}
+
+/** The create dialog's inline error for a server refusal; `dialog` errors go above the buttons. */
+export function createErrorCopy(e: { code: string | null; message: string }, ctx: { branch: string; path: string; checkedOutAt?: string | null }): { field: boolean; text: string } {
+ switch (e.code) {
+ case 'bad_branch':
+ return { field: true, text: 'That isn’t a valid branch name.' };
+ case 'branch_exists':
+ return { field: true, text: `${ctx.branch} already exists. Pick Existing branch to use it, or choose another name.` };
+ case 'branch_checked_out':
+ return { field: true, text: ctx.checkedOutAt ? `${ctx.branch} already has a worktree: ${ctx.checkedOutAt}.` : `${ctx.branch} is already checked out in another folder.` };
+ case 'folder_taken':
+ return { field: true, text: `${ctx.path} already exists and isn’t empty. kwant won’t write into it.` };
+ case 'unknown_branch':
+ return { field: true, text: `There’s no branch called ${ctx.branch}.` };
+ case 'bad_base':
+ case 'unknown_base':
+ return { field: true, text: 'That base branch doesn’t exist here.' };
+ case 'thread_has_worktree':
+ return { field: false, text: 'Couldn’t create it: that chat already has a worktree. Nothing was changed.' };
+ case 'git_failed':
+ return { field: false, text: 'Couldn’t create it: Git refused. Nothing was changed.' };
+ case 'no_git':
+ return { field: false, text: 'Couldn’t create it: Git isn’t installed on this server. Nothing was changed.' };
+ default:
+ return { field: false, text: `Couldn’t create it: ${e.message.replace(/\.$/, '')}. Nothing was changed.` };
+ }
+}
+
+export function removeErrorCopy(e: { code: string | null; message: string }, bot: string | null): string {
+ switch (e.code) {
+ case 'working':
+ return `${bot ?? 'A bot'} is working here. Stop ${bot ?? 'it'} first.`;
+ case 'not_ours':
+ return 'Couldn’t remove it: the folder isn’t a worktree made here. Nothing was deleted.';
+ case 'git_failed':
+ return 'Couldn’t remove it: Git refused. Nothing was deleted.';
+ default:
+ return `Couldn’t remove it: ${e.message.replace(/\.$/, '')}. Nothing was deleted.`;
+ }
+}
+
+/** "~/kwant-wt/shop/x" from an absolute path under the person's home, for display only. */
+export function shortPath(p: string, home: string | null = null): string {
+ if (home && p.startsWith(home + '/')) return `~${p.slice(home.length)}`;
+ const m = p.match(/^\/(?:home|Users)\/[^/]+(\/.*)$/);
+ return m ? `~${m[1]}` : p;
+}
diff --git a/frontend/tests/devDeskWorktrees.test.mjs b/frontend/tests/devDeskWorktrees.test.mjs
new file mode 100644
index 00000000..018f1c4a
--- /dev/null
+++ b/frontend/tests/devDeskWorktrees.test.mjs
@@ -0,0 +1,90 @@
+// 0.9.0 H1 (Pixel): the Dev desk's third tab. Worktrees shows with its count when the server has
+// Lin's routes, Refresh on it reloads the worktrees, and a server without them (404) shows no tab.
+process.env.TZ = 'UTC';
+
+import assert from 'node:assert/strict';
+import test, { afterEach } 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/sp1/dev', 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.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+g.IS_REACT_ACT_ENVIRONMENT = false;
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export * as fx from './src/dev/worktreeFixtures';
+ export { DevDeskView, deskStore } from './src/components/DevDesk';
+ export { worktreeStore } from './src/dev/worktrees';
+ export { devStore, parseDevMode } from './src/devMode';
+`);
+const { React, createRoot, fx } = m;
+const h = React.createElement;
+
+let hasRoutes = true;
+let listCalls = 0;
+g.fetch = g.window.fetch = async (url) => {
+ const u = String(url);
+ const json = (b, status = 200) => new Response(JSON.stringify(b), { status, headers: { 'Content-Type': 'application/json' } });
+ if (u.includes('/dev/worktrees/branches')) return json({}, 404);
+ if (u.endsWith('/dev/worktrees')) return (listCalls++, hasRoutes ? json(fx.LIST) : json({}, 404));
+ if (u.includes('/dev/landed')) return json({ cards: [] });
+ if (u.includes('/dev/reviews')) return json({ cards: [] });
+ if (u.includes('/dev_mode')) return json({ on: true, repo: 'ann/shop', branch: 'main' });
+ return json({});
+};
+
+const settle = async (n = 25) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mounted = [];
+afterEach(() => {
+ while (mounted.length) mounted.pop()();
+ document.body.replaceChildren();
+});
+const desk = async () => {
+ m.deskStore._reset();
+ m.worktreeStore._reset();
+ localStorage.setItem('kwnt.dev.intro.sp1', '1');
+ m.devStore.set('sp1', m.parseDevMode({ on: true, repo: 'ann/shop', branch: 'main' }));
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(h(m.DevDeskView, { spaceId: 'sp1', spaceName: 'Shop', now: fx.NOW, bots: fx.BOTS }));
+ await settle();
+ mounted.push(() => root.unmount());
+ return host;
+};
+const click = async (el) => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+
+test('Worktrees is a tab with its count; it lists the repos; Refresh reloads it', async () => {
+ hasRoutes = true;
+ const host = await desk();
+ const tab = host.querySelector('[data-dev-tab="worktrees"]');
+ assert.ok(tab, 'the tab exists');
+ assert.equal(tab.textContent.replace(/\s+/g, ' ').trim(), 'Worktrees5');
+ assert.deepEqual([...host.querySelectorAll('[data-dev-tab]')].map((t) => t.dataset.devTab), ['landed', 'reviews', 'worktrees']);
+ await click(tab);
+ assert.equal(tab.getAttribute('aria-selected'), 'true');
+ assert.ok(host.querySelector('[role="tabpanel"] [data-wt-panel] [data-wt-repo="shop"]'));
+ assert.equal(host.querySelector('[data-dev-repo-filters]'), null);
+ const before = listCalls;
+ await click(host.querySelector('[data-dev-refresh]'));
+ assert.equal(listCalls, before + 1);
+});
+
+test('a server without the worktree routes shows no Worktrees tab', async () => {
+ hasRoutes = false;
+ const host = await desk();
+ assert.equal(host.querySelector('[data-dev-tab="worktrees"]'), null);
+ assert.deepEqual([...host.querySelectorAll('[data-dev-tab]')].map((t) => t.dataset.devTab), ['landed', 'reviews']);
+});
diff --git a/frontend/tests/wording.test.mjs b/frontend/tests/wording.test.mjs
index 16eb6401..c0af24c7 100644
--- a/frontend/tests/wording.test.mjs
+++ b/frontend/tests/wording.test.mjs
@@ -29,7 +29,9 @@ const MAESTRO = /\bAgent Maestro\b|\bHermes Agent\b/g;
// Import from this computer, a folder or a GitHub link (0.8.0 A4): Mira's a4-import.md names kwant, the program
// that looks and fetches, in these sentences. A4 follow-ups: Mira's ui-check-459 Later 4 ("kwant can’t download it") and
// the https-only reason ("kwant only downloads from github.com").
-const RULED = /\bso kwant can read\b|\bmanifests kwant knows\b|\bnames kwant knows\b|\bkwant’s (?:browser|log|own data|tools)\b|\bkwant (?:adds it|couldn’t|won’t share|keeps|is running as root|can’t pass|can’t fetch|can’t download|only downloads)\b|\b[Rr]estart kwant\b|\bStart kwant as\b|\bkwant (?:looked|never follows|downloads it|found nothing|doesn’t fetch)\b|\bNothing kwant can bring\b|\bwhere kwant looked\b|\bsent kwant somewhere\b/g;
+// Worktrees tab (0.9.0 H1): Mira's h1-worktrees.md names kwant, the program that makes and cleans the folders, in its
+// status and inline-error copy.
+const RULED = /\bkwant (?:can remove it|won’t delete it|won’t write into it|suggests one from the task|cleans build output)\b|\bmade outside kwant\b|\bso kwant can read\b|\bmanifests kwant knows\b|\bnames kwant knows\b|\bkwant’s (?:browser|log|own data|tools)\b|\bkwant (?:adds it|couldn’t|won’t share|keeps|is running as root|can’t pass|can’t fetch|can’t download|only downloads)\b|\b[Rr]estart kwant\b|\bStart kwant as\b|\bkwant (?:looked|never follows|downloads it|found nothing|doesn’t fetch)\b|\bNothing kwant can bring\b|\bwhere kwant looked\b|\bsent kwant somewhere\b/g;
/** Whether a literal reads like text a person sees (a sentence, or a capitalised word). */
const looksVisible = (text, node) => {
diff --git a/frontend/tests/worktrees.test.mjs b/frontend/tests/worktrees.test.mjs
new file mode 100644
index 00000000..3b64b2fb
--- /dev/null
+++ b/frontend/tests/worktrees.test.mjs
@@ -0,0 +1,496 @@
+// 0.9.0 H1 + P3 (Pixel): the Dev desk's Worktrees tab. Copy helpers, the parser, the list with every row
+// state, the P3 line, New worktree (new and existing branch, inline errors) and Remove (a dirty checkout
+// needs "Remove anyway"; the branch is never deleted). The server is a mocked fetch on Lin's contract v2.
+process.env.TZ = 'UTC';
+
+import assert from 'node:assert/strict';
+import test, { afterEach, beforeEach } 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/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'HTMLSelectElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+
+const m = await loadBundled(`
+ export * from './src/dev/worktrees';
+ export * as fx from './src/dev/worktreeFixtures';
+ export { WorktreesPanel } from './src/components/dev/WorktreesTab';
+ export { createRoot } from 'react-dom/client';
+ export { createElement } from 'react';
+ export { act } from 'react';
+`);
+const { fx } = m;
+const h = m.createElement;
+
+// ---------------------------------------------------------------------------------------------------
+// Mocked server
+
+let calls = [];
+let routes = {};
+const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+beforeEach(() => {
+ calls = [];
+ routes = {
+ 'GET /api/spaces/sp1/dev/worktrees': () => json(200, fx.LIST),
+ 'GET /api/spaces/sp1/dev/worktrees/branches': () => json(200, fx.BRANCHES),
+ ...Object.fromEntries(fx.BOTS.map((b) => [`POST /api/kwants/${b.id}/threads`, (_u, init) => json(201, { id: `th-${b.id}`, kwant_id: b.id, title: JSON.parse(init.body).title })])),
+ };
+ g.fetch = async (url, init = {}) => {
+ const method = init.method ?? 'GET';
+ const path = String(url).split('?')[0];
+ calls.push({ method, url: String(url), body: init.body ? JSON.parse(init.body) : undefined });
+ const r = routes[`${method} ${path}`];
+ return r ? r(String(url), init) : json(404, {});
+ };
+ m.worktreeStore._reset();
+});
+
+const mounted = new Set();
+afterEach(() => {
+ for (const u of mounted) u();
+ document.body.replaceChildren();
+});
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const Panel = (props) => {
+ const data = m.worktreeStore.get('sp1');
+ return h(m.WorktreesPanel, { space: 'sp1', data, bots: fx.BOTS, now: fx.NOW, home: '/home/ann', ...props });
+};
+let rerender = () => undefined;
+const mount = async (props = {}) => {
+ await m.worktreeStore.load('sp1');
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ rerender = () => root.render(h(Panel, props));
+ const stop = m.worktreeStore.subscribe(() => rerender());
+ rerender();
+ await settle();
+ const u = () => {
+ if (!mounted.delete(u)) return;
+ stop();
+ root.unmount();
+ host.remove();
+ };
+ mounted.add(u);
+ return host;
+};
+const click = async (el) => {
+ assert.ok(el, 'element to click exists');
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const setValue = async (el, v) => {
+ const proto = el.tagName === 'SELECT' ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, v);
+ el.dispatchEvent(new window.Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
+ await settle();
+};
+const tick = async (el) => {
+ el.click();
+ await settle();
+};
+const row = (host, id) => host.querySelector(`[data-wt-row="${id}"]`);
+const text = (el) => {
+ // Block boundaries read as a space, the way a screen reader or a person reads the row.
+ if (!el.querySelectorAll) return el.textContent.replace(/\s+/g, ' ').trim();
+ const c = el.cloneNode(true);
+ for (const b of c.querySelectorAll('p, h2, h3, div, li, ul, button, label, select, input, span, code')) { b.before(' '); b.after(' '); }
+ return c.textContent.replace(/\s+/g, ' ').replace(/ ([.,?’)])/g, '$1').replace(/\( /g, '(').trim();
+};
+
+// ---------------------------------------------------------------------------------------------------
+// Helpers
+
+test('parseList keeps repos, drops removed and malformed rows, and reads other worktrees', () => {
+ const l = m.parseList({ ...fx.LIST, repos: [{ ...fx.LIST.repos[0], worktrees: [...fx.LIST.repos[0].worktrees, { id: 'x' }, fx.wt('gone', 'gone', { state: 'removed' })] }] });
+ assert.equal(l.repos.length, 1);
+ assert.equal(l.repos[0].worktrees.length, 4);
+ assert.equal(l.repos[0].other[0].branch, 'hotfix/1.4.2');
+ assert.equal(m.worktreeCount(l), 5);
+ assert.equal(m.parseList({ nope: 1 }), null);
+ assert.equal(m.parseList({ repos: [] }).clean_after_minutes, 60);
+});
+
+test('row status and time copy', () => {
+ const W = (o) => m.parseWorktree(o);
+ assert.deepEqual(m.rowStatus(W(fx.WORKING), fx.NOW), { led: 'run', text: 'is working here', kind: 'working' });
+ assert.equal(m.rowStatus(W(fx.FINISHED_DUE), fx.NOW).text, 'finished 13:42');
+ assert.equal(m.rowStatus(W(fx.FINISHED_DUE), fx.NOW).led, 'ok');
+ assert.equal(m.rowStatus(W(fx.CLEANED), fx.NOW).text, 'finished yesterday');
+ assert.equal(m.rowStatus(W(fx.MINE), fx.NOW).text, 'made by you');
+ assert.equal(m.rowStatus(W(fx.MISSING), fx.NOW).kind, 'missing');
+ assert.equal(m.rowTime(W(fx.WORKING), fx.NOW), 'active now');
+ assert.equal(m.rowTask(W(fx.MINE), fx.NOW), 'No task. Made from the Dev desk 09:12');
+ assert.equal(m.rowTask(W({ ...fx.MINE, thread_title: 'lin/search-index' }), fx.NOW), 'Chat: lin/search-index', 'thread_title (contract v3) when there is no task');
+ assert.equal(m.changesLabel(0), 'No uncommitted changes');
+ assert.equal(m.changesLabel(1), '1 uncommitted file');
+ assert.equal(m.changesLabel(3), '3 uncommitted files');
+ assert.equal(m.changesLabel(null), null);
+});
+
+test('P3 states: due, kept, cleaning, cleaned with kept notes, failed', () => {
+ const W = (o) => m.parseWorktree(o);
+ assert.deepEqual(m.p3State(W(fx.FINISHED_DUE)), { kind: 'due', at: '14:42', dirs: [] });
+ assert.deepEqual(m.p3State(W({ ...fx.FINISHED_DUE, keep_build: true })), { kind: 'kept' });
+ assert.deepEqual(m.p3State(W(fx.FINISHED_DUE), { cleaning: true }), { kind: 'cleaning' });
+ assert.deepEqual(m.p3State(W(fx.CLEANED)), { kind: 'cleaned', size: '1.2 GB', at: '18:40', dirs: ['.vite', 'target'] });
+ assert.deepEqual(m.keptNotes(W(fx.CLEANED)), ['Kept dist: Git tracks a file in it.']);
+ assert.equal(m.p3State(W(fx.WORKING)), null);
+ assert.equal(m.p3State(W(fx.MISSING)), null);
+ assert.deepEqual(m.p3State(W(fx.FINISHED_DUE), { failed: 'Lin is working here' }), { kind: 'failed', reason: 'Lin is working here' });
+ // D1: Clean now on a kept worktree shows the cleaned result, its kept notes and a toast.
+ const keptClean = { ...fx.FINISHED_DUE, keep_build: true, clean_at: null, cleaned_at: '2026-11-10T15:10:00Z', cleaned: ['node_modules', 'web/dist'], cleaned_bytes: 300_000, kept: [{ dir: 'dist', why: 'tracked' }] };
+ assert.deepEqual(m.p3State(W(keptClean)), { kind: 'cleaned', size: '300 KB', at: '15:10', dirs: ['node_modules', 'dist'] });
+ assert.deepEqual(m.keptNotes(W(keptClean)), ['Kept dist: Git tracks a file in it.']);
+ assert.equal(m.cleanToast(W(keptClean)), 'Cleaned 300 KB of build output. Kept dist: Git tracks a file in it.');
+ // A clean from before this finish doesn't hide "kept".
+ assert.deepEqual(m.p3State(W({ ...keptClean, cleaned_at: '2026-11-10T10:00:00Z' })), { kind: 'kept' });
+ // Nothing left to clean: still kept, and the toast says so.
+ const keptEmpty = { ...keptClean, cleaned: [], cleaned_bytes: 0, kept: [] };
+ assert.deepEqual(m.p3State(W(keptEmpty)), { kind: 'kept' });
+ assert.equal(m.cleanToast(W(keptEmpty)), 'Nothing to clean: no build output left.');
+ assert.equal(m.sizeLabel(512), '512 bytes');
+ assert.equal(m.sizeLabel(340_000_000), '340 MB');
+});
+
+test('branch names: slug matches the server, spaces get a suggestion, bad refs are refused', () => {
+ assert.equal(m.branchSlug('Pixel/Inbox Empty.State'), 'pixel-inbox-empty-state');
+ assert.equal(m.branchSlug('a'.repeat(80)).length, 60);
+ assert.equal(m.branchSlug('///'), 'worktree');
+ assert.deepEqual(m.branchProblem('fix the inbox'), { kind: 'spaces', suggestion: 'fix-the-inbox' });
+ for (const bad of ['-x', 'a..b', 'a/', 'a.lock', 'x~1', 'a:b', '@', 'a//b', '.hidden/x']) assert.deepEqual(m.branchProblem(bad), { kind: 'invalid' }, bad);
+ assert.equal(m.branchProblem('pixel/inbox-empty'), null);
+ assert.equal(m.suggestBranch('Pixel', 'Inbox: empty state & keyboard order now'), 'pixel/inbox-empty-state-keyboard');
+ assert.equal(m.suggestBranch(null, null), '');
+});
+
+test('error copy names the problem and says nothing changed', () => {
+ assert.equal(m.createErrorCopy({ code: 'branch_exists', message: '' }, { branch: 'a', path: 'p' }).field, true);
+ assert.match(m.createErrorCopy({ code: 'git_failed', message: '' }, { branch: 'a', path: 'p' }).text, /Nothing was changed\.$/);
+ assert.equal(m.removeErrorCopy({ code: 'working', message: '' }, 'Lin'), 'Lin is working here. Stop Lin first.');
+ assert.match(m.removeErrorCopy({ code: null, message: 'Boom.' }, null), /^Couldn’t remove it: Boom\. Nothing was deleted\.$/);
+ assert.equal(m.shortPath('/home/ann/code/shop', '/home/ann'), '~/code/shop');
+ assert.equal(m.shortPath('/srv/x'), '/srv/x');
+});
+
+test('store: a 404 without a code means the server has no routes yet (the tab hides)', async () => {
+ routes['GET /api/spaces/sp1/dev/worktrees'] = () => json(404, {});
+ await m.worktreeStore.load('sp1');
+ assert.equal(m.worktreeStore.get('sp1').missing, true);
+ assert.equal(m.worktreeStore.get('sp1').error, null);
+ routes['GET /api/spaces/sp1/dev/worktrees'] = () => json(500, { error: 'Disk is full.' });
+ await m.worktreeStore.load('sp1');
+ assert.equal(m.worktreeStore.get('sp1').missing, false);
+ assert.equal(m.worktreeStore.get('sp1').error, 'Disk is full.');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// The list
+
+test('the list groups by repo with counts, rows in every state, and an empty repo', async () => {
+ const host = await mount();
+ const shop = host.querySelector('[data-wt-repo="shop"]');
+ assert.match(text(shop.querySelector('h3')), /shop 5 worktrees ~\/code\/shop · main checkout/);
+ const w1 = row(host, 'w1');
+ assert.equal(w1.dataset.wtState, 'working');
+ assert.match(text(w1), /Pixel is working here pixel\/inbox-empty-state/);
+ assert.match(text(w1), /3 uncommitted files/);
+ assert.match(text(w1), /↑2/);
+ assert.equal(w1.querySelector('[data-wt-act="remove"]').getAttribute('aria-disabled'), 'true');
+ assert.match(text(w1), /Pixel is working here\. Stop Pixel first\./);
+ assert.match(text(row(host, 'w2')), /Lin finished 13:42/);
+ assert.match(text(row(host, 'w2')), /up to date|↑4/);
+ assert.match(text(row(host, 'w4')), /You made by you try-vite-6/);
+ assert.match(text(row(host, 'w4')), /No task\. Made from the Dev desk 09:12/);
+ assert.match(text(row(host, '/home/ann/code/shop-hotfix')), /shop-hotfix made outside kwant hotfix\/1\.4\.2/);
+ assert.equal(row(host, '/home/ann/code/shop-hotfix').querySelector('[data-wt-act="remove"]'), null, 'outside rows are read-only');
+ const site = host.querySelector('[data-wt-repo="site"]');
+ assert.ok(site.querySelector('[data-wt-empty="empty"]'));
+ assert.match(text(site), /Each bot task can get its own folder\./);
+});
+
+test('P3 line: Keep it, then Clean now; a refused clean says why and nothing else was touched', async () => {
+ routes['POST /api/dev/worktrees/w2/keep'] = (_u, init) => json(200, { ...fx.FINISHED_DUE, keep_build: JSON.parse(init.body).keep });
+ routes['POST /api/dev/worktrees/w2/clean'] = () => json(409, { code: 'working', error: 'A bot is working here.' });
+ const host = await mount();
+ const p3 = () => row(host, 'w2').querySelector('[data-wt-p3]');
+ assert.equal(p3().dataset.wtP3, 'due');
+ assert.match(text(p3()), /Build output is cleaned at 14:42 · Keep it/);
+ await click(p3().querySelector('[data-wt-keep]'));
+ assert.deepEqual(calls.at(-2).body ?? calls.find((c) => c.url.endsWith('/keep')).body, { keep: true });
+ assert.equal(p3().dataset.wtP3, 'kept');
+ await click(p3().querySelector('[data-wt-clean]'));
+ assert.equal(p3().dataset.wtP3, 'failed');
+ assert.match(text(p3()), /Couldn’t clean build output: Lin is working here\. Nothing else was touched\. · Try again/);
+ const cleaned = row(host, 'w3').querySelector('[data-wt-p3]');
+ assert.match(text(cleaned), /Cleaned 1\.2 GB of build output at 18:40 \(\.vite, target\) · Kept dist: Git tracks a file in it\./);
+});
+
+test('D1: Clean now on a kept worktree shows the cleaned line, its kept notes and a toast', async () => {
+ const kept = { ...fx.FINISHED_DUE, keep_build: true, clean_at: null };
+ routes['GET /api/spaces/sp1/dev/worktrees'] = () => json(200, { ...fx.LIST, repos: [{ ...fx.LIST.repos[0], worktrees: [kept] }] });
+ routes['POST /api/dev/worktrees/w2/clean'] = () =>
+ json(200, { ...kept, cleaned_at: '2026-11-10T15:10:00Z', cleaned: ['node_modules', 'web/node_modules'], cleaned_bytes: 300_000, kept: [{ dir: 'dist', why: 'tracked' }] });
+ const host = await mount();
+ const p3 = () => row(host, 'w2').querySelector('[data-wt-p3]');
+ assert.equal(p3().dataset.wtP3, 'kept');
+ assert.match(text(p3()), /Build output kept · Clean now/);
+ await click(p3().querySelector('[data-wt-clean]'));
+ assert.ok(calls.some((c) => c.method === 'POST' && c.url.endsWith('/w2/clean')));
+ assert.equal(p3().dataset.wtP3, 'cleaned');
+ assert.match(text(p3()), /Cleaned 300 KB of build output at 15:10 \(node_modules\) · Kept dist: Git tracks a file in it\./);
+ assert.match(text(host.querySelector('[data-wt-toast]')), /^Cleaned 300 KB of build output\. Kept dist: Git tracks a file in it\.$/);
+});
+
+test('missing folder: Forget it removes the record', async () => {
+ routes['GET /api/spaces/sp1/dev/worktrees'] = () => json(200, { ...fx.LIST, repos: [{ ...fx.LIST.repos[0], worktrees: [fx.MISSING] }] });
+ routes['DELETE /api/dev/worktrees/w5'] = () => json(200, { ok: true });
+ const host = await mount();
+ assert.match(text(row(host, 'w5')), /Folder missing old\/spike Git still lists ~\/\.kwant\/spaces\/sp1\/worktrees\/shop\/old-spike, but the folder is gone\./);
+ await click(row(host, 'w5').querySelector('[data-wt-act="forget"]'));
+ assert.ok(calls.some((c) => c.method === 'DELETE' && c.url.endsWith('/w5?force=false')));
+});
+
+test('loading, no repo, a whole-list error with Try again, and a repo that can’t be read', async () => {
+ m.worktreeStore._set('sp1', { loading: true });
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(h(Panel));
+ await settle();
+ assert.ok(host.querySelector('[data-wt-loading] [role="status"]'));
+ m.worktreeStore._set('sp1', { loading: false, list: { repos: [], clean_after_minutes: 60, build_dirs: [] } });
+ root.render(h(Panel));
+ await settle();
+ assert.ok(host.querySelector('[data-wt-empty="no-repo"]'));
+ m.worktreeStore._set('sp1', { list: null, error: 'Disk is full.' });
+ root.render(h(Panel));
+ await settle();
+ assert.match(text(host.querySelector('[data-wt-error]')), /Couldn’t read the worktrees\. Disk is full\. Try again/);
+ m.worktreeStore._set('sp1', { error: null, list: m.parseList({ ...fx.LIST, repos: [{ ...fx.LIST.repos[1], error: true }] }) });
+ root.render(h(Panel));
+ await settle();
+ assert.match(text(host.querySelector('[data-wt-repo-error]')), /Couldn’t read the worktrees of site\. Try again/);
+ assert.equal(host.querySelector('[data-wt-new]'), null, 'no New worktree on a repo that can’t be read');
+ root.unmount();
+});
+
+test('Copy path announces politely', async () => {
+ let copied = null;
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText: async (t) => void (copied = t) }, configurable: true });
+ const host = await mount();
+ await click(row(host, 'w2').querySelector('[data-wt-act="copy"]'));
+ assert.equal(copied, `${fx.ROOT}/shop/lin-worktree-routes`);
+ assert.equal(host.querySelector('[data-wt-live]').getAttribute('aria-live'), 'polite');
+ assert.equal(text(host.querySelector('[data-wt-live]')), 'Path copied');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// New worktree
+
+test('create a new branch: default bot, suggested name, preview, request body, toast with Open chat', async () => {
+ let created = null;
+ routes['POST /api/spaces/sp1/dev/worktrees'] = (_u, init) => json(201, (created = fx.wt('w9', JSON.parse(init.body).branch, { kwant_id: 'k-lin', thread_id: 'th-lin', base: 'main' })));
+ const opened = [];
+ const host = await mount({ defaultBotId: 'k-lin', onOpenChat: (b, t) => opened.push([b, t]) });
+ const newBtn = host.querySelector('[data-wt-repo="shop"] [data-wt-new]');
+ await click(newBtn);
+ const dlg = document.querySelector('[data-wt-dialog="create"]');
+ assert.equal(dlg.getAttribute('role'), 'dialog');
+ assert.equal(dlg.getAttribute('aria-modal'), 'true');
+ assert.equal(document.activeElement, dlg.querySelector('[data-wt-for]'), 'focus starts on For');
+ assert.equal(dlg.querySelector('[data-wt-for]').value, 'k-lin');
+ const input = dlg.querySelector('[data-wt-branch-input]');
+ assert.equal(input.value, 'lin');
+ await setValue(input, 'lin/search-index');
+ assert.match(text(dlg.querySelector('[data-wt-preview]')), /folder ~\/\.kwant\/spaces\/sp1\/worktrees\/shop\/lin-search-index branch lin\/search-index \(new, from main\)/);
+ const base = dlg.querySelector('[data-wt-base]');
+ assert.equal(base.tagName, 'SELECT', 'base is a picker when the branch list exists');
+ await setValue(base, 'release/0.9');
+ dlg.querySelector('form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ const posts = calls.filter((c) => c.method === 'POST');
+ assert.deepEqual(posts.map((c) => c.url.replace(/\?.*/, '')), ['/api/kwants/k-lin/threads', '/api/spaces/sp1/dev/worktrees'], 'the bot gets its own chat first: its main 1:1 has no thread id');
+ assert.deepEqual(posts[0].body, { title: 'lin/search-index' });
+ assert.deepEqual(posts[1].body, { team_id: 't-shop', branch: 'lin/search-index', base: 'release/0.9', kwant_id: 'k-lin', thread_id: 'th-k-lin' });
+ assert.ok(created);
+ assert.equal(document.querySelector('[data-wt-dialog]'), null);
+ assert.equal(document.activeElement, newBtn, 'focus returns to New worktree');
+ const t = host.querySelector('[data-wt-toast]');
+ assert.match(text(t), /Worktree ready for Lin Open chat/);
+ await click(t.querySelector('button'));
+ assert.deepEqual(opened, [['k-lin', 'th-lin']]);
+});
+
+test('create: inline errors for spaces, a branch with a worktree, an existing branch, and the server', async () => {
+ routes['POST /api/spaces/sp1/dev/worktrees'] = () => json(409, { code: 'folder_taken', error: 'Folder taken.' });
+ const host = await mount();
+ await click(host.querySelector('[data-wt-repo="shop"] [data-wt-new]'));
+ const dlg = document.querySelector('[data-wt-dialog="create"]');
+ const input = dlg.querySelector('[data-wt-branch-input]');
+ const create = dlg.querySelector('[data-wt-create]');
+ const err = () => text(dlg.querySelector('[data-wt-field-error]') ?? { textContent: '' });
+ await setValue(input, 'fix the inbox');
+ assert.equal(err(), 'Branch names can’t have spaces. Try fix-the-inbox.');
+ assert.equal(input.getAttribute('aria-invalid'), 'true');
+ assert.ok(input.getAttribute('aria-describedby').includes(dlg.querySelector('[data-wt-field-error]').id));
+ assert.equal(create.disabled, true);
+ await setValue(input, 'pixel/inbox-empty-state');
+ assert.equal(err(), 'pixel/inbox-empty-state already has a worktree: ~/.kwant/spaces/sp1/worktrees/shop/pixel-inbox-empty-state.');
+ await setValue(input, 'release/0.9');
+ assert.equal(err(), 'release/0.9 already exists. Pick Existing branch to use it, or choose another name.');
+ await setValue(input, 'pixel/new-thing');
+ assert.equal(err(), '');
+ assert.equal(create.disabled, false);
+ await click(create);
+ assert.equal(err(), '~/.kwant/spaces/sp1/worktrees/shop/pixel-new-thing already exists and isn’t empty. kwant won’t write into it.');
+ assert.ok(document.querySelector('[data-wt-dialog="create"]'), 'the dialog stays open');
+});
+
+test('create from an existing branch: checked-out branches are disabled, no base is sent', async () => {
+ routes['POST /api/spaces/sp1/dev/worktrees'] = (_u, init) => json(201, fx.wt('w8', JSON.parse(init.body).branch));
+ const host = await mount();
+ await click(host.querySelector('[data-wt-repo="shop"] [data-wt-new]'));
+ const dlg = document.querySelector('[data-wt-dialog="create"]');
+ await setValue(dlg.querySelector('[data-wt-for]'), '');
+ await click(dlg.querySelector('[data-wt-mode="existing"]'));
+ assert.equal(dlg.querySelector('[data-wt-mode="existing"]').getAttribute('aria-checked'), 'true');
+ const pick = dlg.querySelector('[data-wt-pick]');
+ const opt = (v) => [...pick.options].find((o) => o.value === v);
+ assert.equal(opt('main').disabled, true);
+ assert.match(opt('main').textContent, /checked out at ~\/code\/shop/);
+ assert.equal(dlg.querySelector('[data-wt-create]').disabled, true);
+ assert.equal(opt('origin/main'), undefined, 'a remote with a local branch of the same name shows only the local one');
+ await setValue(pick, 'release/0.9');
+ assert.match(text(dlg.querySelector('[data-wt-preview]')), /branch release\/0\.9 \(existing\)/);
+ await click(dlg.querySelector('[data-wt-create]'));
+ assert.deepEqual(calls.find((c) => c.method === 'POST').body, { team_id: 't-shop', branch: 'release/0.9' });
+ assert.equal(calls.some((c) => c.url.includes('/threads')), false, 'Nobody: no chat is made');
+ assert.match(text(host.querySelector('[data-wt-toast]')), /^Worktree ready$/);
+});
+
+test('create from a remote-only branch: it goes in as a new local branch made from the remote', async () => {
+ routes['POST /api/spaces/sp1/dev/worktrees'] = (_u, init) => json(201, fx.wt('w7', JSON.parse(init.body).branch));
+ const host = await mount();
+ await click(host.querySelector('[data-wt-repo="shop"] [data-wt-new]'));
+ const dlg = document.querySelector('[data-wt-dialog="create"]');
+ await setValue(dlg.querySelector('[data-wt-for]'), '');
+ await click(dlg.querySelector('[data-wt-mode="existing"]'));
+ const pick = dlg.querySelector('[data-wt-pick]');
+ assert.match([...pick.options].find((o) => o.value === 'origin/feature/search').textContent, /new local branch/);
+ await setValue(pick, 'origin/feature/search');
+ assert.match(text(dlg.querySelector('[data-wt-preview]')), /branch feature\/search \(new, from origin\/feature\/search\)/);
+ await click(dlg.querySelector('[data-wt-create]'));
+ assert.deepEqual(calls.find((c) => c.method === 'POST').body, { team_id: 't-shop', branch: 'feature/search', base: 'origin/feature/search' });
+});
+
+test('create without the branch route: the base and branch become text fields', async () => {
+ delete routes['GET /api/spaces/sp1/dev/worktrees/branches'];
+ const host = await mount();
+ await click(host.querySelector('[data-wt-repo="shop"] [data-wt-new]'));
+ const dlg = document.querySelector('[data-wt-dialog="create"]');
+ assert.equal(dlg.querySelector('[data-wt-base]').tagName, 'INPUT');
+ assert.equal(dlg.querySelector('[data-wt-base]').value, 'main');
+ await click(dlg.querySelector('[data-wt-mode="existing"]'));
+ assert.equal(dlg.querySelector('[data-wt-pick]').tagName, 'INPUT');
+});
+
+test('create dialog: Esc closes, Tab wraps', async () => {
+ const host = await mount();
+ await click(host.querySelector('[data-wt-repo="shop"] [data-wt-new]'));
+ const dlg = document.querySelector('[data-wt-dialog="create"]');
+ const items = [...dlg.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled])')];
+ items.at(-1).focus();
+ items.at(-1).dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Tab', bubbles: true }));
+ await settle();
+ assert.equal(document.activeElement, items[0]);
+ dlg.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ assert.equal(document.querySelector('[data-wt-dialog]'), null);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Remove
+
+test('remove a clean worktree: alertdialog, focus on Cancel, the branch stays', async () => {
+ routes['DELETE /api/dev/worktrees/w2'] = () => json(200, { ok: true });
+ const host = await mount();
+ await click(row(host, 'w2').querySelector('[data-wt-act="remove"]'));
+ const dlg = document.querySelector('[data-wt-dialog="remove"]');
+ assert.equal(dlg.getAttribute('role'), 'alertdialog');
+ assert.equal(document.activeElement, dlg.querySelector('[data-wt-cancel]'));
+ assert.match(text(dlg), /Remove Lin’s worktree\? This deletes the folder ~\/\.kwant\/spaces\/sp1\/worktrees\/shop\/lin-worktree-routes\. The branch lin\/worktree-routes stays, with its 4 commits\./);
+ assert.match(text(dlg), /No uncommitted changes\./);
+ assert.equal(dlg.querySelector('[data-wt-force]'), null);
+ await click(dlg.querySelector('[data-wt-remove]'));
+ assert.ok(calls.some((c) => c.method === 'DELETE' && c.url.endsWith('/w2?force=false')));
+ assert.match(text(host.querySelector('[data-wt-toast]')), /Removed Lin’s worktree\. The branch lin\/worktree-routes stays\./);
+});
+
+test('remove a dirty worktree: refused until "Remove anyway" is ticked, then force=true', async () => {
+ routes['DELETE /api/dev/worktrees/w4'] = (u) => (u.endsWith('force=true') ? json(200, { ok: true }) : json(409, { code: 'dirty', dirty: 1, changes: [{ status: 'M', path: 'package.json' }] }));
+ const host = await mount();
+ await click(row(host, 'w4').querySelector('[data-wt-act="remove"]'));
+ const dlg = document.querySelector('[data-wt-dialog="remove"]');
+ assert.match(text(dlg), /1 file has changes nobody committed\. Removing loses it\./);
+ assert.match(text(dlg.querySelector('[data-wt-changes]')), /M package\.json/);
+ const go = dlg.querySelector('[data-wt-remove]');
+ assert.equal(go.disabled, true);
+ await click(go);
+ assert.equal(calls.filter((c) => c.method === 'DELETE').length, 0);
+ await tick(dlg.querySelector('[data-wt-force]'));
+ assert.equal(go.disabled, false);
+ await click(go);
+ assert.deepEqual(calls.filter((c) => c.method === 'DELETE').map((c) => c.url), ['/api/dev/worktrees/w4?force=true']);
+ assert.match(text(host.querySelector('[data-wt-toast]')), /The branch try-vite-6 stays\./);
+});
+
+test('remove: a checkout that got dirty since the list was read shows the server’s changes and asks again', async () => {
+ routes['DELETE /api/dev/worktrees/w2'] = () =>
+ json(409, { code: 'dirty', dirty: 2, changes: [{ status: 'M', path: 'src/a.rs' }, { status: '?', path: 'notes.md' }] });
+ const host = await mount();
+ await click(row(host, 'w2').querySelector('[data-wt-act="remove"]'));
+ const dlg = document.querySelector('[data-wt-dialog="remove"]');
+ await click(dlg.querySelector('[data-wt-remove]'));
+ assert.match(text(dlg), /2 files have changes nobody committed\. Removing loses them\./);
+ assert.match(text(dlg), /Remove anyway and lose these 2 changes/);
+ assert.equal(dlg.querySelector('[data-wt-remove]').disabled, true);
+ assert.ok(document.querySelector('[data-wt-dialog="remove"]'));
+});
+
+test('remove refused by the server says why and nothing was deleted', async () => {
+ routes['DELETE /api/dev/worktrees/w2'] = () => json(409, { code: 'working', error: 'busy' });
+ const host = await mount();
+ await click(row(host, 'w2').querySelector('[data-wt-act="remove"]'));
+ const dlg = document.querySelector('[data-wt-dialog="remove"]');
+ await click(dlg.querySelector('[data-wt-remove]'));
+ assert.equal(text(dlg.querySelector('[data-wt-dialog-error]')), 'Lin is working here. Stop Lin first.');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Phone
+
+test('phone: rows get a ⋯ sheet with Open chat, Copy path, Keep, Clean now and Remove', async () => {
+ const opened = [];
+ const host = await mount({ phone: true, onOpenChat: (b, t) => opened.push([b, t]) });
+ assert.equal(row(host, 'w2').querySelector('[data-wt-act="remove"]'), null);
+ assert.equal(host.querySelector('[data-wt-repo="shop"] [data-wt-new]').getAttribute('aria-label'), 'New worktree in shop');
+ await click(row(host, 'w2').querySelector('[data-wt-more]'));
+ const sheet = document.querySelector('[data-wt-dialog="row-menu"]');
+ assert.deepEqual([...sheet.querySelectorAll('button')].map((b) => text(b)), ['Open chat', 'Copy path', 'Keep build output', 'Clean now', 'Remove']);
+ await click([...sheet.querySelectorAll('button')].find((b) => text(b) === 'Remove'));
+ assert.ok(document.querySelector('[data-wt-dialog="remove"]'));
+ assert.equal(document.querySelector('[data-wt-dialog="row-menu"]'), null);
+ await click(document.querySelector('[data-wt-cancel]'));
+ await click(row(host, 'w1').querySelector('[data-wt-more]'));
+ const s2 = document.querySelector('[data-wt-dialog="row-menu"]');
+ assert.equal([...s2.querySelectorAll('button')].find((b) => text(b) === 'Remove').disabled, true);
+ assert.match(text(s2), /Pixel is working here\. Stop Pixel first\./);
+});