Skip to content

armgit / kwant

Public Imported from GitHub
0

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

0.7.3: Connect GitHub in one place (A3, B1, B2, B3 + C5–C7) (#371)

Oleksandr Ivanchenko692156e3cc5f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 38da3be3..a480ca70 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,13 +11,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- NVIDIA preset for custom servers: free models from build.nvidia.com (#365).
- **Dev mode reads any git repo.** Repos on GitLab, Gitea or any git server, and team folders with no remote, are watched with git, and what lands there shows on the Dev desk. Reviews, CI checks and Post to GitHub still work on GitHub repos only. The server needs git 2.31 or newer; without it, the desk says "Needs git on the server". (#366, #368)
+- **Connect GitHub in one place.** Every Connect GitHub (the Dev desk's status line and empty state, the Dev mode toast, Dev mode setup and Team settings) opens the same GitHub form right where you pressed it: a popover on the desktop, a sheet on the phone. It no longer jumps to Loose ends. The GitHub row in Loose ends says "Also used by Dev mode".
+- **Team settings say what Dev mode does with the repo.** Under Git Repo URL, one line: watched with GitHub connected, watched but needs Connect GitHub for reviews, can be watched once Dev mode is on, or read with git (reviews need GitHub).
### Changed
- **Dev mode reads commit history with git, not GitHub's API.** Each watched repo gets a copy in kwant's data folder, up to 1 GB each; a bigger repo reads "Too big to read". Repo addresses that point at this server, link-local addresses or cloud metadata addresses are refused, and https reads are pinned to the address that was checked. A team folder whose .git points somewhere else is refused. GitHub PRs, checks and logins still come from GitHub. (#366)
-- **Saving a password on this server no longer dead-ends.** An archived space, and the bots in it, no longer count as "Ask only when risky" or "Don't ask", so they don't block saving passwords. When a space or bot that doesn't ask is still active, you can choose to save the password on this server anyway. You make that choice once for the server, and a bot can never make it for you. The warning that such passwords are exposed stays. Restoring an archived space that doesn't ask needs the same choice.
+- **Saving a token or password while some bots don't ask first is a choice, not a wall.** The card "Before you save the token" explains the risk and offers **Save it on this server**, **Use Bitwarden** or **Make every bot ask first**. You make the "Save it on this server" choice once for the server, and a bot can never make it for you; the warning that such passwords are exposed stays. Archived spaces, and the bots in them, no longer count. Turning approvals off, or restoring an archived space that doesn't ask, with passwords on this server offers the same one-time choice. (#370, #371)
+- After a wrong master password on bitwarden.com or bitwarden.eu, the Bitwarden form asks whether the account is on the other one. (#371)
+- A token form waiting on Bitwarden or approvals checks again when you come back to the window, so connecting Bitwarden in another tab unblocks it. (#371)
### Fixed
-- **Connecting Bitwarden works with accounts whose key salt isn't their email.** kwant now uses the salt Bitwarden's server reports, and also reads the account key from Bitwarden's newer login reply. Each failed connect or unlock logs one line with what went wrong, the HTTP status and the server's host. That line never includes the email, password or codes.
+- **Connect in the Bitwarden form works again.** Inside the GitHub, email and approvals forms, Connect (or Enter) reloaded the page and sent nothing; it now connects. (#371)
+- **Connecting Bitwarden works with accounts whose key salt isn't their email.** kwant now uses the salt Bitwarden's server reports, and also reads the account key from Bitwarden's newer login reply. Each failed connect or unlock logs one line with what went wrong, the HTTP status and the server's host. That line never includes the email, password or codes. (#370)
- A custom server's models that have no name now show their id in the model picker instead of "[redacted]" (#365).
## [Mac 0.7.2] - 2026-11-06
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 8dfdc01c..589f0aa1 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -130,7 +130,8 @@ import { PromptContext, suggestedPrompts } from './suggestedPrompts';
import { isNotificationOpen, showDeviceNotification } from './push';
import { EMPTY_PILL, NUDGES_SETTING_EVENT, browserIconDoc, createArrivals, createNudgeIcon, nudgesEnabled, pillAdd, pillPrune, setAppBadgeCount, shouldPill, type Nudge, type PillState } from './attention';
import { NeedsYouPill } from './components/NeedsYouPill';
-import { devApi, devConnect, devStore } from './devMode';
+import { devApi, devStore } from './devMode';
+import { GitHubConnectHost, openGitHubConnect } from './components/GitHubConnect';
import { useDevModeOn } from './components/DevModeSwitch';
import { DEV_CARD_EVENT, DevDeskView, type DevCardEvent } from './components/DevDesk';
import { inDesktopApp, leaveForSignIn, mcpSignIn, pollUntil, signInChanged } from './externalLinks';
@@ -370,27 +371,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
const isPhoneRef = useRef(isPhone);
isPhoneRef.current = isPhone;
- // Dev mode Connect (flow F5): Loose ends opens on the GitHub form; once a GitHub source is added
- // the person lands back on the Dev desk, which reads Dev mode again.
- const [devConnecting, setDevConnecting] = useState(0);
- const connectDevGitHub = () => {
- if (!devConnect.pending()) devConnect.start(space.id);
- setDevConnecting((n) => n + 1);
- showPage('inbox', 'loose');
- };
- const devGitHubAdded = () => {
- const back = devConnect.finish();
- setDevConnecting(0);
- if (!back) return;
- devApi.get(back).then((st) => devStore.set(back, st), () => undefined);
- if (back === space.id) showPage('dev');
- };
- // Leaving Loose ends without connecting drops the trip back.
- useEffect(() => {
- if (page === 'inbox' || !devConnecting) return;
- setDevConnecting(0);
- devConnect.cancel();
- }, [page, devConnecting]);
+ // Dev mode Connect (0.7.3 B1): the one GitHub connect form opens in place, next to the button (a
+ // sheet on the phone); the host re-reads this space's Dev mode once the login is added.
+ const connectDevGitHub = (anchor?: HTMLElement) => openGitHubConnect({ space: space.id, anchor });
// Idea jar (0.7): the ready-takes badge, Open on board's mission, the drop toast and the
// app-wide live region (a take is announced on any screen; the open jar announces its own).
const ideaJarCount = useIdeaJarBadge(space.id);
@@ -3323,10 +3306,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
);
const loose = (
<LooseEndsPage
- key={devConnecting ? `dev-connect-${devConnecting}` : 'loose'}
onOpenChat={openThread}
- connectGitHub={devConnecting > 0}
- onGitHubAdded={devGitHubAdded}
/>
);
const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={awayCount} onBack={backToList} newPage={away} loosePage={loose} />;
@@ -3759,6 +3739,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
<StarAsk needsYou={Object.keys(needsYouByKwant).length > 0} waiting={awaitingTurns.size > 0 || pendingApprovals.length > 0} />
<Toasts toasts={toasts} onDismiss={dismissToast} />
+ <GitHubConnectHost onConnected={() => pushToast('GitHub connected', 'Loose ends and Dev mode both use it.')} />
{ideaToast && (
<IdeaDropToast
key={ideaToast.id}
diff --git a/frontend/src/approvalMode.ts b/frontend/src/approvalMode.ts
index a07b5938..a02654d6 100644
--- a/frontend/src/approvalMode.ts
+++ b/frontend/src/approvalMode.ts
@@ -81,7 +81,7 @@ export const offConsequences = (store: StoreStatus | null | undefined): string[]
/** The server refused "off" because passwords are still saved on it (audit F-10). */
export class NeedsBitwardenError extends Error {
- constructor(message: string, public localCount: number | null) {
+ constructor(message: string, public localCount: number | null, public canAccept = false) {
super(message);
}
}
@@ -137,7 +137,7 @@ async function errorText(res: Response, fallback: string): Promise<string | Need
try {
const body = await res.json();
const needs = needsBitwardenFrom(res.status, body);
- if (needs) return new NeedsBitwardenError(needs.message, needs.local_count);
+ if (needs) return new NeedsBitwardenError(needs.message, needs.local_count, needs.can_accept);
if (typeof body?.error === 'string' && body.error) {
if (res.status === 403) return 'Only you can change approvals, from the app.';
if (res.status === 409) return 'This space is archived. Restore it to change its approvals.';
@@ -150,10 +150,12 @@ async function errorText(res: Response, fallback: string): Promise<string | Need
return `${fallback} (HTTP ${res.status}).`;
}
-async function put(url: string, approvals: string, fallback: string): Promise<unknown> {
+/** `acceptRisk` (0.7.3 A2): the person confirmed keeping passwords on this server; sent once, person-only on the server. */
+async function put(url: string, approvals: string, fallback: string, acceptRisk = false): Promise<unknown> {
let res: Response;
try {
- res = await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ approvals }) });
+ const body = acceptRisk ? { approvals, accept_risk: true } : { approvals };
+ res = await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
} catch {
throw new Error('Couldn’t reach the server. Check your connection and try again.');
}
@@ -168,8 +170,8 @@ const enc = encodeURIComponent;
export const approvalModeApi = {
/** Resolves to the space's new value. */
- setSpace: async (spaceId: string, approvals: SpaceApprovals): Promise<SpaceApprovals> => {
- const body = (await put(`/api/spaces/${enc(spaceId)}/approvals`, approvals, 'Couldn’t change approvals')) as { approvals?: unknown };
+ setSpace: async (spaceId: string, approvals: SpaceApprovals, acceptRisk = false): Promise<SpaceApprovals> => {
+ const body = (await put(`/api/spaces/${enc(spaceId)}/approvals`, approvals, 'Couldn’t change approvals', acceptRisk)) as { approvals?: unknown };
return spaceMode(body?.approvals);
},
/** null when the server has no such endpoint or the call fails. */
@@ -181,15 +183,16 @@ export const approvalModeApi = {
return null;
}
},
- setBot: async (kwantId: string, approvals: BotApprovals, spaceId?: string): Promise<BotApprovalsState> => {
+ setBot: async (kwantId: string, approvals: BotApprovals, spaceId?: string, acceptRisk = false): Promise<BotApprovalsState> => {
const url = `/api/kwants/${enc(kwantId)}/approvals${spaceId ? `?space=${enc(spaceId)}` : ''}`;
- const state = parseBotApprovals(await put(url, approvals, 'Couldn’t change this bot’s approvals'));
+ const state = parseBotApprovals(await put(url, approvals, 'Couldn’t change this bot’s approvals', acceptRisk));
if (!state) throw new Error('The server sent an answer the app can’t read. Reload and check the setting.');
return state;
},
/**
* "Turn approvals back on" everywhere: every active space that's off or "Ask only when risky",
- * and every bot set to either, goes back to ask (both keep passwords off this server). Archived spaces can't be changed until they're restored; they count as failed.
+ * and every bot set to either, goes back to ask (both keep passwords off this server). Archived spaces are
+ * skipped: they can't run anything and don't count (0.7.3 A1).
*/
turnAllOn: async (): Promise<{ changed: number; failed: number }> => {
let changed = 0;
@@ -200,11 +203,10 @@ export const approvalModeApi = {
const body = await res.json();
return Array.isArray(body) ? body : [];
};
- // `/api/spaces` lists the active spaces only; `?archived=1` lists only the archived ones.
+ // `/api/spaces` lists the active spaces only.
let spaces: Array<Record<string, unknown>>;
try {
- const [active, archived] = await Promise.all([list('/api/spaces'), list('/api/spaces?archived=1').catch(() => [])]);
- spaces = [...active, ...archived];
+ spaces = (await list('/api/spaces')).filter((sp) => !sp.archived_at);
} catch {
throw new Error('Couldn’t reach the server. Check your connection and try again.');
}
@@ -219,11 +221,7 @@ export const approvalModeApi = {
for (const sp of spaces) {
const id = typeof sp.id === 'string' ? sp.id : null;
if (!id) continue;
- if (sp.approvals === 'off' || sp.approvals === 'smart') {
- if (sp.archived_at) failed++;
- else await attempt(() => approvalModeApi.setSpace(id, 'ask'));
- }
- if (sp.archived_at) continue;
+ if (sp.approvals === 'off' || sp.approvals === 'smart') await attempt(() => approvalModeApi.setSpace(id, 'ask'));
const bots = await list(`/api/kwants?space=${enc(id)}`).catch(() => null);
if (!bots) {
failed++;
diff --git a/frontend/src/components/ApprovalsSetting.tsx b/frontend/src/components/ApprovalsSetting.tsx
index a7e8b16c..0a5975f2 100644
--- a/frontend/src/components/ApprovalsSetting.tsx
+++ b/frontend/src/components/ApprovalsSetting.tsx
@@ -19,7 +19,7 @@ import {
OFF_HINT,
offConsequences,
} from '../approvalMode';
-import { StoreStatus, moveFirstLabel, moveFirstText } from '../passwordStore';
+import { StoreStatus, acceptRiskLabel, acceptRiskText } from '../passwordStore';
import { ExposedBanner, MoveToBitwardenFirst, PasswordStoreState, usePasswordStore } from './PasswordStorePanel';
/** "Approvals off": in a chat header (full) or a sidebar row (icon, with the words for screen readers). */
@@ -62,19 +62,21 @@ export const OffHint: React.FC = () => (
/**
* The plain-words confirm before anything runs without asking. With passwords still saved on this
- * server, "off" isn't offered: they move to Bitwarden first (the server refuses otherwise, F-10).
+ * server and the risk not accepted yet, it says so once (0.7.3 A3): keep them here (sends accept_risk,
+ * once per server) or move them to Bitwarden first.
*/
export const OffConfirm: React.FC<{
title: string;
busy: boolean;
onCancel: () => void;
- onConfirm: () => void;
+ /** `acceptRisk`: the person kept passwords on this server (the one-time confirm). */
+ onConfirm: (acceptRisk?: boolean) => void;
/** Where passwords are kept; missing on screens (and older servers) that don't know. */
passwords?: PasswordStoreState;
}> = ({ title, busy, onCancel, onConfirm, passwords }) => {
const id = useId();
const status = passwords?.status ?? null;
- const mustMove = !!status && status.local_count > 0;
+ const mustMove = !!status && status.local_count > 0 && !status.risk_accepted;
// Still finding out: don't offer "off" for the moment it takes.
const checking = !!passwords && !status && !passwords.problem;
return (
@@ -100,9 +102,9 @@ export const OffConfirm: React.FC<{
))}
</ul>
{mustMove ? (
- <div className="space-y-1.5 pt-0.5" data-off-needs-bitwarden>
- <p className="text-[11px] text-amber-100 leading-snug">{moveFirstText(status!.local_count)}</p>
- <MoveToBitwardenFirst store={passwords!} label={moveFirstLabel(status!.local_count)} />
+ <div className="space-y-1.5 pt-0.5" data-off-accept-risk>
+ <p className="text-[11px] text-amber-100 leading-snug">{acceptRiskText(status!.local_count)}</p>
+ <MoveToBitwardenFirst store={passwords!} label="Move them to Bitwarden first" />
</div>
) : (
<>
@@ -119,27 +121,26 @@ export const OffConfirm: React.FC<{
>
Cancel
</button>
- {!mustMove && (
- <button
- type="button"
- onClick={onConfirm}
- disabled={busy || checking}
- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-rose-600 hover:bg-rose-500 disabled:opacity-50"
- >
- {(busy || checking) && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
- {checking ? 'Checking saved passwords…' : 'Turn off approvals'}
- </button>
- )}
+ <button
+ type="button"
+ onClick={() => onConfirm(mustMove)}
+ disabled={busy || checking}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-rose-600 hover:bg-rose-500 disabled:opacity-50"
+ data-off-confirm={mustMove ? 'accept-risk' : 'off'}
+ >
+ {(busy || checking) && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {checking ? 'Checking saved passwords…' : mustMove ? acceptRiskLabel(status!.local_count) : 'Turn off approvals'}
+ </button>
</div>
</div>
);
};
-/** A refused "off": show the move step when the store is known, else the server's sentence. */
+/** A refused "off": show the one-time confirm when the store is known, else the server's sentence. */
function refusedOff(err: unknown, passwords: PasswordStoreState): string | null {
if (!(err instanceof NeedsBitwardenError)) return err instanceof Error ? err.message : null;
const known = passwords.status;
- if (known) passwords.set({ ...known, local_count: Math.max(err.localCount ?? 1, 1) });
+ if (known) passwords.set({ ...known, local_count: Math.max(err.localCount ?? 1, 1), risk_accepted: false });
passwords.reload();
return known ? null : err.message;
}
@@ -171,11 +172,11 @@ export const SpaceApprovalsSetting: React.FC<{
if (confirming) storeReload();
}, [confirming, storeReload]);
- const save = async (v: SpaceApprovals) => {
+ const save = async (v: SpaceApprovals, acceptRisk = false) => {
setBusy(true);
setError(null);
try {
- const next = await approvalModeApi.setSpace(spaceId, v);
+ const next = await approvalModeApi.setSpace(spaceId, v, acceptRisk);
setCurrent(next);
setConfirming(false);
onChanged(next);
@@ -230,7 +231,7 @@ export const SpaceApprovalsSetting: React.FC<{
))}
</div>
{confirming && (
- <OffConfirm title={offConfirmTitle({ space: spaceName })} busy={busy} passwords={passwords} onCancel={() => setConfirming(false)} onConfirm={() => save('off')} />
+ <OffConfirm title={offConfirmTitle({ space: spaceName })} busy={busy} passwords={passwords} onCancel={() => setConfirming(false)} onConfirm={(accept) => save('off', accept)} />
)}
{current === 'off' && !confirming && <OffHint />}
{exceptions.length > 0 && !confirming && (
@@ -288,11 +289,11 @@ export const BotApprovalsSetting: React.FC<{
// An older server without the switch: show nothing rather than a control that can't save.
if (state === null) return null;
- const save = async (v: BotApprovals) => {
+ const save = async (v: BotApprovals, acceptRisk = false) => {
setBusy(true);
setError(null);
try {
- const next = await approvalModeApi.setBot(kwantId, v);
+ const next = await approvalModeApi.setBot(kwantId, v, undefined, acceptRisk);
setState(next);
setPending(null);
onChanged?.(next);
@@ -344,7 +345,7 @@ export const BotApprovalsSetting: React.FC<{
}
/>
{pending && (
- <OffConfirm title={offConfirmTitle({ bot: kwantName })} busy={busy} passwords={passwords} onCancel={() => setPending(null)} onConfirm={() => save(pending)} />
+ <OffConfirm title={offConfirmTitle({ bot: kwantName })} busy={busy} passwords={passwords} onCancel={() => setPending(null)} onConfirm={(accept) => save(pending, accept)} />
)}
{error && (
<p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300">
diff --git a/frontend/src/components/DevDesk.tsx b/frontend/src/components/DevDesk.tsx
index e1989a7a..198b2fa9 100644
--- a/frontend/src/components/DevDesk.tsx
+++ b/frontend/src/components/DevDesk.tsx
@@ -9,6 +9,7 @@ import { FindingAction, LandedPage, ShellCard, asCard, parseCards, parseLandedPa
import { LandedList, ReleaseNotesSheet, ReviewCard, Rollup } from './DevDeskSlots';
import { useDevMode } from './DevModeSwitch';
import { DevStatusLine } from './DevStatusLine';
+import { openGitHubConnect } from './GitHubConnect';
/** App re-sends the `dev_card` SSE as this window event: detail `{space_id, id, kind, status}`. */
export const DEV_CARD_EVENT = 'kwant:dev-card';
@@ -187,14 +188,16 @@ export interface DevDeskViewProps {
onSaveToNotion?: (markdown: string) => Promise<void>;
initialTab?: Tab;
now?: number;
- /** Opens Loose ends, for the status line's Connect. */
- onOpenLooseEnds?: () => void;
+ /** Connect GitHub (the status line and the empty state). Defaults to the shared connect form in place (0.7.3 B1);
+ * the name stays from when it opened Loose ends. */
+ onOpenLooseEnds?: (anchor?: HTMLElement) => void;
/** The space's teams, so a team with no repo gets "Link a repo" in the repo list. */
teams?: DevTeamRef[];
}
export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds, teams }) => {
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=`.
const filters = repoFilters(dev);
const [repoPick, setRepoPick] = useState<string | null>(null);
@@ -415,7 +418,7 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
spaceId={spaceId}
state={dev}
teams={teams}
- onConnect={onOpenLooseEnds}
+ onConnect={connect}
checked={desk.checkedAt != null ? checkedLabel(desk.checkedAt) : null}
checkedAt={desk.checkedAt ?? null}
/>
@@ -506,7 +509,11 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav
{landedCards.length ? (
<LandedList cards={landedCards} reviews={reviews} now={now} onOpenReview={openReview} forge={dev?.forge ?? null} repoLabel={repoLabel} gitOnly={gitOnly} />
) : dev?.status === 'not_connected' ? (
- <TermEmpty out="(needs a GitHub connection)" title="Connect GitHub to see what landed." line="The last 5 merges show up here right after." />
+ <TermEmpty out="(needs a GitHub connection)" title="Connect GitHub to see what landed." line="The last 5 merges show up here right after.">
+ <button type="button" onClick={(e) => connect(e.currentTarget)} className="kw-btn-primary mt-3" data-dev-empty-connect>
+ Connect GitHub
+ </button>
+ </TermEmpty>
) : dev?.status === 'no_repo' ? (
<TermEmpty out="(no repo yet)" title="Cards show up once there’s a repo." line="The production floor already works." />
) : (
@@ -586,7 +593,7 @@ const SkeletonCards: React.FC<{ line?: string; n?: number }> = ({ line = 'Readin
);
/** Flow copy §6: a first-visit empty state as a tiny terminal, `$ git log main -5` and its output. */
-const TermEmpty: React.FC<{ cmd?: string; out: string; title: string; line: string }> = ({ cmd = 'git log main -5', out, title, line }) => (
+const TermEmpty: React.FC<{ cmd?: string; out: string; title: string; line: string; children?: React.ReactNode }> = ({ cmd = 'git log main -5', out, title, line, children }) => (
<div className="rounded-2xl border border-dashed border-hairline-strong px-5 py-6" data-dev-empty data-dev-empty-term>
<p className="font-mono text-[12px] text-zinc-500 break-words" aria-hidden="true">
<span className="text-sky-300">$</span> {cmd}
@@ -596,6 +603,7 @@ const TermEmpty: React.FC<{ cmd?: string; out: string; title: string; line: stri
</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>
);
diff --git a/frontend/src/components/DevModeSetup.tsx b/frontend/src/components/DevModeSetup.tsx
index 8fd1db30..00880838 100644
--- a/frontend/src/components/DevModeSetup.tsx
+++ b/frontend/src/components/DevModeSetup.tsx
@@ -4,6 +4,7 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Eye, GitMerge, Loader2, Lock, ShieldAlert } from 'lucide-react';
+import { openGitHubConnect } from './GitHubConnect';
import { CheckerUpdate, DevModeState, FieldState, createRepoChecker, deployLabel, devApi, fieldView, normaliseRepo, RepoCheck } from '../devMode';
export interface DevModeSetupProps {
@@ -11,8 +12,8 @@ export interface DevModeSetupProps {
initial?: DevModeState | null;
onCancel: () => void;
onDone: (s: DevModeState) => void;
- /** Opens Connections (Connect GitHub, Mark production keys). Hidden when not given. */
- onOpenConnections?: () => void;
+ /** Connect GitHub. Defaults to the shared connect form, opened in place (0.7.3 B1). */
+ onOpenConnections?: (anchor?: HTMLElement) => void;
/** Test hooks. */
check?: (repo: string) => Promise<RepoCheck>;
save?: (body: { on: boolean; repo: string; branch: string | null }) => Promise<DevModeState>;
@@ -161,8 +162,8 @@ export const DevModeSetup: React.FC<DevModeSetupProps> = ({ space, initial, onCa
) : (
view.help
)}
- {view.connect && onOpenConnections && (
- <button type="button" onClick={onOpenConnections} className="ml-2 font-medium text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
+ {view.connect && (
+ <button type="button" onClick={(e) => (onOpenConnections ? onOpenConnections(e.currentTarget) : openGitHubConnect({ space: space.id, anchor: e.currentTarget }))} data-dv-connect className="ml-2 font-medium text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
Connect GitHub
</button>
)}
@@ -186,7 +187,7 @@ export const DevModeSetup: React.FC<DevModeSetupProps> = ({ space, initial, onCa
<Tile label="Production keys" hint={!onOpenConnections && !productionCount ? 'Mark them in Connections' : undefined}>
<span className={productionCount ? '' : 'text-zinc-500'}>{productionCount ? `${productionCount} marked` : 'None marked'}</span>
{onOpenConnections ? (
- <button type="button" onClick={onOpenConnections} className="ml-1.5 text-meta font-medium text-sky-300 hover:text-sky-200">
+ <button type="button" onClick={(e) => onOpenConnections(e.currentTarget)} className="ml-1.5 text-meta font-medium text-sky-300 hover:text-sky-200">
Mark
</button>
) : null}
diff --git a/frontend/src/components/DevStatusLine.tsx b/frontend/src/components/DevStatusLine.tsx
index e81f4f09..595061f9 100644
--- a/frontend/src/components/DevStatusLine.tsx
+++ b/frontend/src/components/DevStatusLine.tsx
@@ -35,6 +35,7 @@ import {
typedRepo,
undoBody,
} from '../devMode';
+import { openGitHubConnect } from './GitHubConnect';
const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
@@ -49,7 +50,8 @@ export interface DevStatusLineProps {
/** The space's teams, so a team with no repo gets "Link a repo". */
teams?: DevTeamRef[];
/** Opens Loose ends (Connect GitHub). Connect hides without it. */
- onConnect?: () => void;
+ /** Connect GitHub; defaults to the shared connect form, opened in place (0.7.3 B1). */
+ onConnect?: (anchor?: HTMLElement) => void;
/** "Checked 19:58" at the right (style-v2 §4); the LED pings once each time it changes. */
checked?: string | null;
checkedAt?: number | null;
@@ -68,7 +70,7 @@ const linkError = (e: unknown): string => {
return LINK_ERROR;
};
-export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, teams = [], onConnect, checked = null, checkedAt = null, save = devApi.linkRepo, remove = devApi.removeRepo }) => {
+export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, teams = [], onConnect = (anchor) => openGitHubConnect({ space: spaceId, anchor }), checked = null, checkedAt = null, save = devApi.linkRepo, remove = devApi.removeRepo }) => {
const line = statusLine(state, teams);
const listId = useId();
// The header's "Link a repo" / the toast's "Type a repo" open the first Link form, focused; "See repos"
@@ -154,8 +156,8 @@ export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, te
);
};
- const act = (row: RepoRow | null, action: RowAction, id: string) => {
- if (action === 'connect') return onConnect?.();
+ const act = (row: RepoRow | null, action: RowAction, id: string, anchor?: HTMLElement) => {
+ if (action === 'connect') return onConnect(anchor);
if (action === 'link') {
setError(null);
return setLinking((l) => (l === id || (l === 'intent' && linkingId === id) ? null : id));
@@ -169,7 +171,7 @@ export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, te
return (
<button
type="button"
- onClick={() => act(row, action, id)}
+ onClick={(e) => act(row, action, id, e.currentTarget)}
disabled={busy === id}
aria-expanded={expandedAttr}
aria-label={action === 'remove' ? `Stop watching ${label}` : action === 'link' && row?.team ? `Link a repo for ${row.team}` : undefined}
diff --git a/frontend/src/components/GitHubConnect.tsx b/frontend/src/components/GitHubConnect.tsx
new file mode 100644
index 00000000..2908d417
--- /dev/null
+++ b/frontend/src/components/GitHubConnect.tsx
@@ -0,0 +1,148 @@
+import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useEscapeLayer } from '../escape';
+import { usePhoneLayout } from '../usePhoneLayout';
+import { devApi, devStore } from '../devMode';
+import type { LooseSource } from '../looseEnds';
+import { GitHubConnectForm } from './LooseEndsView';
+
+/**
+ * One GitHub connect form, opened in place (0.7.3 B1). Every Connect GitHub (the Dev desk's status
+ * line and empty state, the Dev mode toast, Dev mode setup, Team settings' repo line) calls
+ * `openGitHubConnect`; the host mounted once in App shows the form as a popover next to the button on
+ * the desktop and as a sheet on the phone. Nothing navigates to Loose ends any more.
+ */
+export const GITHUB_CONNECT_EVENT = 'kwnt:github-connect';
+/** Sent after a GitHub login is added from the in-place form; `detail.space` is the space it was opened for. */
+export const GITHUB_CONNECTED_EVENT = 'kwnt:github-connected';
+
+export interface GitHubConnectRequest {
+ /** The space whose Dev mode reads the login again once it's added. */
+ space?: string;
+ /** The button it opens next to (and focus goes back to). Defaults to the focused element. */
+ anchor?: HTMLElement | null;
+}
+
+export function openGitHubConnect(req: GitHubConnectRequest = {}): void {
+ if (typeof window === 'undefined') return;
+ const anchor = req.anchor ?? (document.activeElement instanceof HTMLElement && document.activeElement !== document.body ? document.activeElement : null);
+ window.dispatchEvent(new window.CustomEvent<GitHubConnectRequest>(GITHUB_CONNECT_EVENT, { detail: { space: req.space, anchor } }));
+}
+
+const WIDTH = 380;
+const GAP = 8;
+const EDGE = 12;
+
+/** Where the popover goes: under the anchor (or above it when there's no room), kept inside the window. */
+export function popoverPlace(anchor: { top: number; bottom: number; left: number; right: number } | null, vw: number, vh: number, height: number) {
+ const width = Math.min(WIDTH, vw - EDGE * 2);
+ if (!anchor) return { left: Math.round((vw - width) / 2), top: Math.max(EDGE, Math.round((vh - height) / 3)), width };
+ const left = Math.round(Math.min(Math.max(EDGE, anchor.left), vw - width - EDGE));
+ const below = anchor.bottom + GAP;
+ const above = anchor.top - GAP - height;
+ const top = below + height <= vh - EDGE ? below : above >= EDGE ? above : Math.max(EDGE, vh - EDGE - height);
+ return { left, top: Math.round(top), width };
+}
+
+export const GitHubConnectHost: React.FC<{ onConnected?: (space: string | undefined, source: LooseSource) => void }> = ({ onConnected }) => {
+ const [req, setReq] = useState<(GitHubConnectRequest & { n: number }) | null>(null);
+ useEffect(() => {
+ const on = (e: Event) => {
+ const detail = (e as CustomEvent<GitHubConnectRequest>).detail ?? {};
+ setReq((r) => ({ ...detail, n: (r?.n ?? 0) + 1 }));
+ };
+ window.addEventListener(GITHUB_CONNECT_EVENT, on);
+ return () => window.removeEventListener(GITHUB_CONNECT_EVENT, on);
+ }, []);
+ if (!req) return null;
+ return (
+ <GitHubConnectLayer
+ key={req.n}
+ req={req}
+ onClose={() => setReq(null)}
+ onAdded={(source) => {
+ setReq(null);
+ if (req.space) devApi.get(req.space).then((st) => devStore.set(req.space!, st), () => undefined);
+ window.dispatchEvent(new window.CustomEvent(GITHUB_CONNECTED_EVENT, { detail: { space: req.space } }));
+ onConnected?.(req.space, source);
+ }}
+ />
+ );
+};
+
+const GitHubConnectLayer: React.FC<{ req: GitHubConnectRequest; onClose: () => void; onAdded: (s: LooseSource) => void }> = ({ req, onClose, onAdded }) => {
+ const phone = usePhoneLayout();
+ const ref = useRef<HTMLDivElement>(null);
+ const [place, setPlace] = useState<{ left: number; top: number; width: number } | null>(null);
+ const close = () => {
+ onClose();
+ // Back to the button it opened from, when it's still on screen.
+ const a = req.anchor;
+ if (a?.isConnected) window.setTimeout(() => a.focus({ preventScroll: true }), 0);
+ };
+ useEscapeLayer(ref, true, close, { modal: true, fallback: () => (req.anchor?.isConnected ? req.anchor : null) });
+
+ // The desktop popover follows its button and its own height (the card, then the token field).
+ useLayoutEffect(() => {
+ if (phone) return undefined;
+ const measure = () => {
+ const r = req.anchor?.isConnected ? req.anchor.getBoundingClientRect() : null;
+ setPlace(popoverPlace(r, window.innerWidth, window.innerHeight, ref.current?.offsetHeight ?? 320));
+ };
+ measure();
+ const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
+ if (ref.current) ro?.observe(ref.current);
+ window.addEventListener('resize', measure);
+ window.addEventListener('scroll', measure, true);
+ return () => {
+ ro?.disconnect();
+ window.removeEventListener('resize', measure);
+ window.removeEventListener('scroll', measure, true);
+ };
+ }, [phone, req.anchor]);
+
+ // A click outside closes the popover (the phone sheet has its own backdrop).
+ useEffect(() => {
+ if (phone) return undefined;
+ const down = (e: MouseEvent) => {
+ const t = e.target as Node | null;
+ if (!t || ref.current?.contains(t) || req.anchor?.contains(t)) return;
+ // Bitwarden's login form and other layers opened from inside sit in the popover; anything else is outside.
+ close();
+ };
+ document.addEventListener('mousedown', down);
+ return () => document.removeEventListener('mousedown', down);
+ });
+
+ const form = <GitHubConnectForm onAdded={onAdded} onCancel={close} land scroll={false} />;
+
+ if (phone)
+ return createPortal(
+ <div className="fixed inset-0 z-[70] flex flex-col justify-end" data-github-connect-sheet>
+ <button type="button" aria-label="Close" tabIndex={-1} onClick={close} className="absolute inset-0 bg-black/50 cursor-default" />
+ <div ref={ref} tabIndex={-1} role="dialog" aria-modal="true" aria-label="Connect GitHub" className="kw-sheet outline-none relative max-h-[88vh] overflow-y-auto rounded-t-2xl bg-zinc-900 border-t border-zinc-800 p-2 pb-[calc(0.5rem+env(safe-area-inset-bottom))] shadow-2xl">
+ <div className="flex justify-center pt-1 pb-2" aria-hidden="true">
+ <span className="w-9 h-1 rounded-sm bg-zinc-700" />
+ </div>
+ {form}
+ </div>
+ </div>,
+ document.body,
+ );
+
+ return createPortal(
+ <div
+ ref={ref}
+ tabIndex={-1}
+ role="dialog"
+ aria-modal="false"
+ aria-label="Connect GitHub"
+ data-github-connect-popover
+ style={place ? { left: place.left, top: place.top, width: place.width } : { visibility: 'hidden', left: 0, top: 0, width: WIDTH }}
+ className="fixed z-[70] outline-none max-h-[calc(100vh-24px)] overflow-y-auto rounded-xl bg-zinc-900 shadow-2xl shadow-black/60 ring-1 ring-zinc-700"
+ >
+ {form}
+ </div>,
+ document.body,
+ );
+};
diff --git a/frontend/src/components/LooseEndsView.tsx b/frontend/src/components/LooseEndsView.tsx
index 08853d72..4ce8e3a8 100644
--- a/frontend/src/components/LooseEndsView.tsx
+++ b/frontend/src/components/LooseEndsView.tsx
@@ -37,7 +37,6 @@ import {
LooseOwner,
LooseOwnerChange,
LooseSource,
- NewSource,
Tone,
actionDoneText,
actionsFor,
@@ -302,7 +301,14 @@ export const LooseCaseCard: React.FC<LooseCaseCardProps> = ({ c, busy, now = Dat
* (or Bitwarden is locked): connect
* or unlock Bitwarden here, move any passwords already on this server, then save again.
*/
-export const NeedsBitwarden: React.FC<{ message: string; locked: boolean; onReady: () => void; onCancel: () => void }> = ({ message, locked, onReady, onCancel }) => {
+export const NeedsBitwarden: React.FC<{
+ message: string;
+ locked: boolean;
+ /** `acceptRisk`: the person chose Save it on this server (0.7.3 A2, when the server says `can_accept`). */
+ onReady: (acceptRisk?: boolean) => void;
+ onCancel: () => void;
+ canAccept?: boolean;
+}> = ({ message, locked, onReady, onCancel, canAccept = false }) => {
const store = usePasswordStore(true);
const [step, setStep] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -325,7 +331,12 @@ export const NeedsBitwarden: React.FC<{ message: string; locked: boolean; onRead
<p className="text-[11px] text-amber-100/80">Your login stays in this form until it’s saved. Nothing was saved yet.</p>
{!step ? (
<div className="flex flex-wrap gap-2">
- <button type="button" onClick={() => setStep(true)} disabled={!s} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`}>
+ {canAccept && !locked && (
+ <button type="button" onClick={() => onReady(true)} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`} data-needs-bitwarden-save>
+ {SAVE_FIRST.save}
+ </button>
+ )}
+ <button type="button" onClick={() => setStep(true)} disabled={!s} className={`${actionBtn} ${canAccept && !locked ? 'border border-zinc-600 bg-zinc-800/70 text-zinc-100 hover:bg-zinc-700' : 'bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold'}`}>
{mode === 'unlock' ? 'Unlock Bitwarden' : 'Move to Bitwarden'}
</button>
<button type="button" onClick={onCancel} className={quietBtn}>
@@ -352,20 +363,20 @@ export const NeedsBitwarden: React.FC<{ message: string; locked: boolean; onRead
};
/**
- * Dev mode's Connect (flow F5): when the token couldn't be saved right now (this server's store under
- * "Ask only when risky" or "Don't ask", or a locked Bitwarden), the two ways out come before the token
- * field, so nobody types a token and then hits the 409. The rule itself (audit F-10) stays on the server.
+ * The card before the token field (0.7.3 A3). With this server's store while some bot runs without
+ * asking, it's a warning, not a wall: Save it on this server (sends accept_risk with the save, once per
+ * server), Use Bitwarden, or Make every bot ask first. A locked Bitwarden offers Unlock only.
+ * `onReady(note, acceptRisk)` shows the token field.
*/
-export const SaveFirst: React.FC<{ gate: Exclude<SaveGate, 'open'>; onReady: (note: string) => void }> = ({ gate, onReady }) => {
+export const SaveFirst: React.FC<{ gate: Exclude<SaveGate, 'open'>; onReady: (note: string | null, acceptRisk?: boolean) => void }> = ({ gate, onReady }) => {
const id = useId();
const store = usePasswordStore(true, true);
const [step, setStep] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
- const first = useRef<HTMLButtonElement>(null);
const locked = gate === 'locked';
const box = useRef<HTMLDivElement>(null);
- // Connect/Unlock Bitwarden opens its form in place: focus goes to its first field, not back to the page
+ // Use/Unlock Bitwarden opens its form in place: focus goes to its first field, not back to the page
useEffect(() => {
if (!step) return undefined;
const h = window.setTimeout(() => box.current?.querySelector<HTMLElement>('input:not([disabled]), select:not([disabled])')?.focus(), 0);
@@ -376,12 +387,11 @@ export const SaveFirst: React.FC<{ gate: Exclude<SaveGate, 'open'>; onReady: (no
setBusy(true);
setError(null);
try {
- const r = await approvalModeApi.turnAllOn();
+ await approvalModeApi.turnAllOn();
const next = await storeApi.peek();
store.set(next);
if (saveGate(next) === 'open') onReady(SAVE_FIRST.asked);
- else if (r.failed) setError(`${r.failed} ${r.failed === 1 ? 'setting' : 'settings'} couldn’t be changed. An archived space keeps its approvals until you restore it.`);
- else setError('A space or bot still runs without asking. Try again.');
+ else setError(SAVE_FIRST.askLeft);
} catch (e) {
setError(e instanceof Error ? e.message : 'Couldn’t change approvals.');
} finally {
@@ -391,25 +401,40 @@ export const SaveFirst: React.FC<{ gate: Exclude<SaveGate, 'open'>; onReady: (no
return (
<div ref={box} role="group" aria-labelledby={`${id}-t`} className={`sm:col-span-2 rounded-xl border p-3 space-y-2 ${step ? 'border-white/10 bg-white/[0.03]' : 'border-amber-500/40 bg-amber-500/10'}`} data-save-first={gate} data-save-first-step={step || undefined}>
- <p id={`${id}-t`} className="text-xs font-medium text-amber-100">
+ <p id={`${id}-t`} className="flex items-start gap-1.5 text-xs font-medium text-amber-100">
+ {!step && <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />}
{locked ? SAVE_FIRST.lockedTitle : SAVE_FIRST.title}
</p>
{!locked && <p className="text-[11px] text-amber-100/80 leading-snug" data-save-first-why>{SAVE_FIRST.why}</p>}
{!step ? (
- <>
<div className="flex flex-wrap gap-2">
- <button ref={first} type="button" onClick={() => setStep(true)} disabled={!store.status} className={`${actionBtn} w-full sm:w-auto justify-center bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`} data-save-first-bitwarden data-land>
+ {!locked && (
+ <button type="button" onClick={() => onReady(null, true)} className={`${actionBtn} w-full sm:w-auto justify-center bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`} data-save-first-save data-land>
+ {SAVE_FIRST.save}
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => setStep(true)}
+ disabled={!store.status}
+ className={`${actionBtn} w-full sm:w-auto justify-center ${locked ? 'bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold' : 'border border-zinc-600 bg-zinc-800/70 text-zinc-100 hover:bg-zinc-700'}`}
+ data-save-first-bitwarden
+ data-land={locked || undefined}
+ >
{locked ? SAVE_FIRST.unlock : SAVE_FIRST.bitwarden}
</button>
{!locked && (
- <button type="button" onClick={ask} disabled={busy} className={`${quietBtn} w-full sm:w-auto justify-center`} data-save-first-ask>
+ <button type="button" onClick={ask} disabled={busy} aria-describedby={`${id}-scope`} className={`${quietBtn} w-full sm:w-auto justify-center`} data-save-first-ask>
{busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
{busy ? SAVE_FIRST.asking : SAVE_FIRST.ask}
</button>
)}
+ {!locked && (
+ <p id={`${id}-scope`} className="basis-full text-[11px] text-zinc-400" data-save-first-scope>
+ {SAVE_FIRST.askScope}
+ </p>
+ )}
</div>
- {!locked && <p className="text-[11px] text-amber-100/70 leading-snug" data-save-first-scope>{SAVE_FIRST.askScope}</p>}
- </>
) : (
store.status && (
<BitwardenLoginForm
@@ -437,49 +462,108 @@ export const SaveFirst: React.FC<{ gate: Exclude<SaveGate, 'open'>; onReady: (no
const EMPTY_IMAP: ImapFields = { label: '', host: '', port: '', security: 'tls', username: '', folders: '', accept_invalid_certs: false };
-/** Add an IMAP mailbox or GitHub. The password or token is read from its field at submit and never kept in state. */
-export const AddSourceForm: React.FC<{
+/** The GitHub login's hint under the token field: the same words wherever it's connected. */
+export const GITHUB_TOKEN_HINT = 'Read-only access to issues and pull requests is enough. To post reviews from Dev mode, give it Pull requests: Read and write.';
+/** Where else this connection is used (0.7.3 B1): one GitHub login for Loose ends and Dev mode. */
+export const GITHUB_ALSO_DEV = 'Also used by Dev mode';
+
+const KindPicker: React.FC<{ kind: 'imap' | 'github'; onKind: (k: 'imap' | 'github') => void }> = ({ kind, onKind }) => (
+ <div role="radiogroup" aria-label="Kind of source" className="grid grid-cols-2 gap-2">
+ {(['imap', 'github'] as const).map((k) => (
+ <button
+ key={k}
+ type="button"
+ role="radio"
+ aria-checked={kind === k}
+ onClick={() => onKind(k)}
+ className={`${actionBtn} justify-center border ${kind === k ? 'border-sky-500/50 bg-sky-500/10 text-sky-200' : 'border-zinc-700 bg-zinc-800/60 text-zinc-300 hover:bg-zinc-800'}`}
+ >
+ {SOURCE_ICON[k]} {k === 'imap' ? 'Email (IMAP)' : 'GitHub'}
+ </button>
+ ))}
+ </div>
+);
+
+/**
+ * The one GitHub connect form (0.7.3 B1): Loose ends' Add a source > GitHub, and every Connect GitHub in
+ * Dev mode (in a popover or a sheet). It reads the password store first; when the token would sit on this
+ * server while a bot runs without asking, the A3 card comes before the token field. The token is read from
+ * its field at submit and never kept in state.
+ */
+export const GitHubConnectForm: React.FC<{
onAdded: (s: LooseSource) => void;
onCancel: () => void;
- initialKind?: 'imap' | 'github';
- /** Dev mode's Connect (flow F5): check the password store first, and land on the first field once `land` is true. */
- connect?: boolean;
+ /** Focus the first control (the token, or the card's first button) once this turns true. */
land?: boolean;
-}> = ({ onAdded, onCancel, initialKind = 'imap', connect = false, land = false }) => {
+ /** Scroll into view on landing (a page); a popover or sheet is already in view. */
+ scroll?: boolean;
+ heading?: string;
+ /** Above the fields: Loose ends' kind picker. */
+ above?: React.ReactNode;
+ /** The line above the buttons. */
+ note?: string;
+ /** Test hook: start past the store check. */
+ initialGate?: SaveGate;
+}> = ({ onAdded, onCancel, land = false, scroll = true, heading = 'Connect GitHub', above, note, initialGate }) => {
const id = useId();
- const [kind, setKind] = useState<'imap' | 'github'>(initialKind);
- const [imap, setImap] = useState<ImapFields>(EMPTY_IMAP);
const [ghLabel, setGhLabel] = useState('');
const [ghBase, setGhBase] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
- const [vault, setVault] = useState<{ message: string; locked: boolean } | null>(null);
+ const [vault, setVault] = useState<{ message: string; locked: boolean; canAccept: boolean } | null>(null);
const secretRef = useRef<HTMLInputElement>(null);
const formRef = useRef<HTMLFormElement>(null);
- const local = isLoopbackHost(imap.host);
- // Connect reads the store before the token field shows ('checking' until it answers; a failed read
- // leaves the form as it was, and the 409 card still catches it).
- const [gate, setGate] = useState<SaveGate | 'checking'>(connect ? 'checking' : 'open');
+ // The store is read before the token field shows ('checking' until it answers; a failed read
+ // leaves the form open, and the 409 card still catches it).
+ const [gate, setGate] = useState<SaveGate | 'checking'>(initialGate ?? 'checking');
const [ready, setReady] = useState<string | null>(null);
+ const acceptRisk = useRef(false);
useEffect(() => {
- if (!connect) return undefined;
+ if (initialGate) return undefined;
let live = true;
storeApi.peek().then(
- (s) => live && setGate(saveGate(s)),
+ (st) => live && setGate(saveGate(st)),
() => live && setGate('open'),
);
return () => {
live = false;
};
- }, [connect]);
- // Land (B3): once the page has loaded, bring the form into view and focus its first control: the
- // token, or the first way out when the token can't be saved yet. Again after a way out is taken.
+ }, [initialGate]);
+ // 0.7.3 C6: Bitwarden connected or unlocked in Settings or another tab, or approvals changed there,
+ // unblocks this form when the person comes back to it: the store is read again on focus and on the
+ // tab turning visible, while the card is up.
+ const blocked = gate === 'store' || gate === 'locked';
+ useEffect(() => {
+ if (!blocked) return undefined;
+ let live = true;
+ const recheck = () => {
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
+ storeApi.peek().then(
+ (st) => {
+ if (!live) return;
+ const next = saveGate(st);
+ if (next === 'open') setReady(st.store === 'bitwarden' ? SAVE_FIRST.connected : !st.approvals_off ? SAVE_FIRST.asked : null);
+ setGate((g) => (g === 'store' || g === 'locked' ? next : g));
+ },
+ () => undefined,
+ );
+ };
+ window.addEventListener('focus', recheck);
+ document.addEventListener('visibilitychange', recheck);
+ return () => {
+ live = false;
+ window.removeEventListener('focus', recheck);
+ document.removeEventListener('visibilitychange', recheck);
+ };
+ }, [blocked]);
+ // Land: bring the form into view and focus its first control: the token, or the card's first way on.
+ // Again after a way on is taken.
const landed = useRef<string | null>(null);
useEffect(() => {
- if (!connect || !land || gate === 'checking' || kind !== 'github') return undefined;
+ if (!land || gate === 'checking') return undefined;
if (landed.current === gate) return undefined;
// Marked only once focus is in: a cancelled frame (StrictMode's second run, a re-render) tries
- // again, and a way out that renders a frame later (the store panel loading) is waited for.
+ // again, and a way on that renders a frame later (the store panel loading) is waited for.
let h = 0;
let tries = 0;
const step = () => {
@@ -490,17 +574,146 @@ export const AddSourceForm: React.FC<{
return;
}
landed.current = gate;
- form.scrollIntoView?.({ block: 'start', behavior: 'auto' });
+ if (scroll) form.scrollIntoView?.({ block: 'start', behavior: 'auto' });
target.focus({ preventScroll: true });
};
h = window.setTimeout(step, 0);
return () => window.clearTimeout(h);
- }, [connect, land, gate, kind]);
+ }, [land, gate, scroll]);
+
+ const submit = async (e?: React.FormEvent, accept = acceptRisk.current) => {
+ e?.preventDefault();
+ const req = githubSource(ghLabel, ghBase, secretRef.current?.value ?? '');
+ if ('error' in req) {
+ setError(req.error);
+ return;
+ }
+ setBusy(true);
+ setError(null);
+ setVault(null);
+ try {
+ const r = await looseApi.addSource(req, accept);
+ if (secretRef.current) secretRef.current.value = '';
+ playSfx('coin');
+ onAdded(r.source);
+ } catch (err) {
+ if (err instanceof LooseEndsError && (err.needsBitwarden || err.locked)) setVault({ message: err.message, locked: err.locked, canAccept: err.canAccept });
+ else setError(err instanceof Error ? err.message : 'Couldn’t add it.');
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <form ref={formRef} onSubmit={submit} className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 sm:p-4 space-y-3 scroll-mt-4" aria-labelledby={`${id}-h`} data-add-source="github" data-github-connect>
+ <div className="flex items-center justify-between gap-2">
+ <h4 id={`${id}-h`} className="text-xs font-semibold text-zinc-200">
+ {heading}
+ </h4>
+ <button type="button" onClick={onCancel} aria-label="Close" className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800">
+ <X size={14} />
+ </button>
+ </div>
+ {above}
+ {gate === 'checking' ? (
+ <p className="flex items-center gap-2 text-xs text-zinc-400" data-save-checking>
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Checking where the token goes…
+ </p>
+ ) : gate !== 'open' ? (
+ <SaveFirst
+ gate={gate}
+ onReady={(n, accept) => {
+ if (accept) acceptRisk.current = true;
+ setReady(n);
+ setGate('open');
+ }}
+ />
+ ) : (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {ready && (
+ <p role="status" className="sm:col-span-2 text-xs text-emerald-300" data-save-ready>
+ {ready}
+ </p>
+ )}
+ <div className="sm:col-span-2">
+ <label htmlFor={`${id}-tok`} className="block text-[11px] text-zinc-400 mb-1">
+ Token
+ </label>
+ <input id={`${id}-tok`} ref={secretRef} type="password" className={field} autoComplete="new-password" aria-describedby={`${id}-tok-hint`} data-github-token />
+ <p id={`${id}-tok-hint`} className="mt-1 text-[11px] text-zinc-400">
+ {GITHUB_TOKEN_HINT}
+ </p>
+ </div>
+ <div>
+ <label htmlFor={`${id}-glabel`} className="block text-[11px] text-zinc-400 mb-1">
+ Name (optional)
+ </label>
+ <input id={`${id}-glabel`} className={field} value={ghLabel} onChange={(e) => setGhLabel(e.target.value)} placeholder="GitHub" />
+ </div>
+ <div>
+ <label htmlFor={`${id}-base`} className="block text-[11px] text-zinc-400 mb-1">
+ API address (GitHub Enterprise only)
+ </label>
+ <input id={`${id}-base`} className={field} value={ghBase} onChange={(e) => setGhBase(e.target.value)} placeholder="https://api.github.com" spellCheck={false} />
+ </div>
+ </div>
+ )}
- const submit = async (e?: React.FormEvent) => {
+ <p className="text-[11px] text-zinc-500">{note ?? 'Loose ends and Dev mode share this login. It’s tested first, and nothing is saved if the test fails.'}</p>
+
+ {vault && <NeedsBitwarden message={vault.message} locked={vault.locked} canAccept={vault.canAccept} onReady={(accept) => submit(undefined, accept || acceptRisk.current)} onCancel={() => setVault(null)} />}
+ {error && (
+ <p role="alert" className="flex items-start gap-1.5 text-xs text-rose-300 break-words">
+ <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" /> {error}
+ </p>
+ )}
+
+ <div className="flex flex-wrap justify-end gap-2">
+ <button type="button" onClick={onCancel} className={quietBtn}>
+ Cancel
+ </button>
+ <button type="submit" disabled={busy || gate !== 'open'} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold disabled:opacity-50`}>
+ {busy ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Plus size={13} aria-hidden="true" />}
+ {busy ? 'Testing…' : 'Test and add'}
+ </button>
+ </div>
+ </form>
+ );
+};
+
+/** Add an IMAP mailbox or GitHub. GitHub is the shared connect form; the IMAP password is read from its field at submit and never kept in state. */
+export const AddSourceForm: React.FC<{
+ onAdded: (s: LooseSource) => void;
+ onCancel: () => void;
+ initialKind?: 'imap' | 'github';
+ /** Dev mode's Connect (flow F5): land on the first field once `land` is true. */
+ connect?: boolean;
+ land?: boolean;
+}> = ({ onAdded, onCancel, initialKind = 'imap', connect = false, land = false }) => {
+ const [kind, setKind] = useState<'imap' | 'github'>(initialKind);
+ // Choosing GitHub in the picker lands on its first control (the token, or the card), like Connect does.
+ const [picked, setPicked] = useState(false);
+ const onKind = (k: 'imap' | 'github') => {
+ setKind(k);
+ setPicked(k === 'github');
+ };
+ if (kind === 'github')
+ return <GitHubConnectForm heading="Add a source" above={<KindPicker kind={kind} onKind={onKind} />} onAdded={onAdded} onCancel={onCancel} land={(connect && land) || picked} />;
+ return <ImapSourceForm picker={<KindPicker kind={kind} onKind={onKind} />} onAdded={onAdded} onCancel={onCancel} />;
+};
+
+const ImapSourceForm: React.FC<{ picker: React.ReactNode; onAdded: (s: LooseSource) => void; onCancel: () => void }> = ({ picker, onAdded, onCancel }) => {
+ const id = useId();
+ const [imap, setImap] = useState<ImapFields>(EMPTY_IMAP);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [vault, setVault] = useState<{ message: string; locked: boolean; canAccept: boolean } | null>(null);
+ const secretRef = useRef<HTMLInputElement>(null);
+ const local = isLoopbackHost(imap.host);
+
+ const submit = async (e?: React.FormEvent, accept = false) => {
e?.preventDefault();
- const secret = secretRef.current?.value ?? '';
- const req: NewSource | { error: string } = kind === 'imap' ? imapSource(imap, secret) : githubSource(ghLabel, ghBase, secret);
+ const req = imapSource(imap, secretRef.current?.value ?? '');
if ('error' in req) {
setError(req.error);
return;
@@ -509,12 +722,12 @@ export const AddSourceForm: React.FC<{
setError(null);
setVault(null);
try {
- const r = await looseApi.addSource(req);
+ const r = await looseApi.addSource(req, accept);
if (secretRef.current) secretRef.current.value = '';
playSfx('coin');
onAdded(r.source);
} catch (err) {
- if (err instanceof LooseEndsError && (err.needsBitwarden || err.locked)) setVault({ message: err.message, locked: err.locked });
+ if (err instanceof LooseEndsError && (err.needsBitwarden || err.locked)) setVault({ message: err.message, locked: err.locked, canAccept: err.canAccept });
else setError(err instanceof Error ? err.message : 'Couldn’t add it.');
} finally {
setBusy(false);
@@ -529,7 +742,7 @@ export const AddSourceForm: React.FC<{
);
return (
- <form ref={formRef} onSubmit={submit} className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 sm:p-4 space-y-3 scroll-mt-4" aria-labelledby={`${id}-h`} data-add-source={kind}>
+ <form onSubmit={submit} className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 sm:p-4 space-y-3 scroll-mt-4" aria-labelledby={`${id}-h`} data-add-source="imap">
<div className="flex items-center justify-between gap-2">
<h4 id={`${id}-h`} className="text-xs font-semibold text-zinc-200">
Add a source
@@ -538,23 +751,8 @@ export const AddSourceForm: React.FC<{
<X size={14} />
</button>
</div>
- <div role="radiogroup" aria-label="Kind of source" className="grid grid-cols-2 gap-2">
- {(['imap', 'github'] as const).map((k) => (
- <button
- key={k}
- type="button"
- role="radio"
- aria-checked={kind === k}
- onClick={() => (setKind(k), setError(null), setVault(null))}
- className={`${actionBtn} justify-center border ${kind === k ? 'border-sky-500/50 bg-sky-500/10 text-sky-200' : 'border-zinc-700 bg-zinc-800/60 text-zinc-300 hover:bg-zinc-800'}`}
- >
- {SOURCE_ICON[k]} {k === 'imap' ? 'Email (IMAP)' : 'GitHub'}
- </button>
- ))}
- </div>
-
- {kind === 'imap' ? (
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {picker}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="sm:col-span-2">
{label(`${id}-host`, 'Mail server')}
<input id={`${id}-host`} className={field} value={imap.host} onChange={(e) => set('host', e.target.value)} placeholder="imap.gmail.com" autoComplete="off" spellCheck={false} />
@@ -596,40 +794,10 @@ export const AddSourceForm: React.FC<{
</label>
)}
</div>
- ) : gate === 'checking' ? (
- <p className="flex items-center gap-2 text-xs text-zinc-400" data-save-checking>
- <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Checking where the token goes…
- </p>
- ) : gate !== 'open' ? (
- <SaveFirst gate={gate} onReady={(note) => (setReady(note), setGate('open'))} />
- ) : (
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- {ready && (
- <p role="status" className="sm:col-span-2 text-xs text-emerald-300" data-save-ready>
- {ready}
- </p>
- )}
- <div className="sm:col-span-2">
- {label(`${id}-tok`, 'Token')}
- <input id={`${id}-tok`} ref={secretRef} type="password" className={field} autoComplete="new-password" aria-describedby={`${id}-tok-hint`} />
- <p id={`${id}-tok-hint`} className="mt-1 text-[11px] text-zinc-400">
- Read-only access to issues and pull requests is enough. To post reviews from Dev mode, give it Pull requests: Read and write.
- </p>
- </div>
- <div>
- {label(`${id}-glabel`, 'Name (optional)')}
- <input id={`${id}-glabel`} className={field} value={ghLabel} onChange={(e) => setGhLabel(e.target.value)} placeholder="GitHub" />
- </div>
- <div>
- {label(`${id}-base`, 'API address (GitHub Enterprise only)')}
- <input id={`${id}-base`} className={field} value={ghBase} onChange={(e) => setGhBase(e.target.value)} placeholder="https://api.github.com" spellCheck={false} />
- </div>
- </div>
- )}
<p className="text-[11px] text-zinc-500">Loose ends only reads this source. It tests the connection first and saves nothing if the test fails. The login goes to your password vault.</p>
- {vault && <NeedsBitwarden message={vault.message} locked={vault.locked} onReady={() => submit()} onCancel={() => setVault(null)} />}
+ {vault && <NeedsBitwarden message={vault.message} locked={vault.locked} canAccept={vault.canAccept} onReady={(accept) => submit(undefined, accept)} onCancel={() => setVault(null)} />}
{error && (
<p role="alert" className="flex items-start gap-1.5 text-xs text-rose-300 break-words">
<AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" /> {error}
@@ -640,7 +808,7 @@ export const AddSourceForm: React.FC<{
<button type="button" onClick={onCancel} className={quietBtn}>
Cancel
</button>
- <button type="submit" disabled={busy || (kind === 'github' && gate !== 'open')} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold disabled:opacity-50`}>
+ <button type="submit" disabled={busy} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold disabled:opacity-50`}>
{busy ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Plus size={13} aria-hidden="true" />}
{busy ? 'Testing…' : 'Test and add'}
</button>
@@ -733,6 +901,7 @@ export const LooseSources: React.FC<{
<p className={`text-[11px] break-words ${st.error ? 'text-rose-300' : 'text-zinc-500'}`}>
{sourceLabel(s.kind)}
{s.builtin ? ' · built in' : ''} · {st.text}
+ {s.kind === 'github' && <span data-github-also-dev> · {GITHUB_ALSO_DEV}</span>}
</p>
</div>
</div>
diff --git a/frontend/src/components/ManageTeamModal.tsx b/frontend/src/components/ManageTeamModal.tsx
index 4f2991ca..5ffbe7e2 100644
--- a/frontend/src/components/ManageTeamModal.tsx
+++ b/frontend/src/components/ManageTeamModal.tsx
@@ -7,6 +7,7 @@ import { playSfx } from '../audio/chiptune';
import { InstructionsField } from './Instructions';
import { MAX_INSTRUCTIONS } from '../continuity';
import { teamNameToSave } from '../teamChannel';
+import { TeamRepoDevLine } from './TeamRepoDevLine';
import { useEscapeLayer } from '../escape';
interface ManageTeamModalProps {
@@ -443,8 +444,9 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
placeholder="https://github.com/owner/repository.git"
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"
/>
+ <TeamRepoDevLine url={repoUrl} teamId={team?.id ?? null} />
<p className="text-[11px] text-zinc-500 mt-1">
- Repository will be cloned and managed in team workspace directory on first run.
+ Bots clone it into the team’s folder on first run.
</p>
</div>
)}
diff --git a/frontend/src/components/NewTeamModal.tsx b/frontend/src/components/NewTeamModal.tsx
index 688048f7..0f7936d6 100644
--- a/frontend/src/components/NewTeamModal.tsx
+++ b/frontend/src/components/NewTeamModal.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
+import { TeamRepoDevLine } from './TeamRepoDevLine';
import { X, Users, AlertCircle, Folder, GitBranch, FolderSearch } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { Kwant, Team } from './Sidebar';
@@ -382,8 +383,9 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({
placeholder="https://github.com/owner/repository.git"
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"
/>
+ <TeamRepoDevLine url={repoUrl} />
<p className="text-[11px] text-zinc-500 mt-1">
- Repository will be cloned and managed in team workspace directory on first run.
+ Bots clone it into the team’s folder on first run.
</p>
</div>
)}
diff --git a/frontend/src/components/PasswordStorePanel.tsx b/frontend/src/components/PasswordStorePanel.tsx
index 773b8079..824154e2 100644
--- a/frontend/src/components/PasswordStorePanel.tsx
+++ b/frontend/src/components/PasswordStorePanel.tsx
@@ -11,6 +11,7 @@ import {
UnlockProblem,
autofillGapNote,
checkServerUrl,
+ otherCloudHint,
exposedText,
migrateText,
serverLabel,
@@ -110,6 +111,8 @@ export const BitwardenLoginForm: React.FC<{
const [code, setCode] = useState('');
const [busy, setBusy] = useState(false);
const [problem, setProblem] = useState<UnlockProblem | null>(initialProblem);
+ // The server a connect was tried on (C5): the other cloud is named under a wrong password.
+ const [triedServer, setTriedServer] = useState<string>(initialServer);
const [formError, setFormError] = useState<string | null>(null);
const masterRef = useRef<HTMLInputElement>(null);
const secretRef = useRef<HTMLInputElement>(null);
@@ -128,8 +131,20 @@ export const BitwardenLoginForm: React.FC<{
[],
);
- const submit = async (e: React.FormEvent) => {
+ const noUsableTwoFactor = step?.kind === 'two-factor' && !step.providers.some((p) => p.usable);
+ // Enter in a field connects, and never reaches a form this one sits in.
+ const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
+ const t = e.target as HTMLElement;
+ if (e.key !== 'Enter' || e.nativeEvent.isComposing || t.tagName !== 'INPUT') return;
e.preventDefault();
+ e.stopPropagation();
+ void submit();
+ };
+
+ // Not a <form>: this form is shown inside other forms (GitHub, IMAP, the approvals confirm), and a
+ // nested <form> is dropped by the browser, so its submit became the outer form's (a page reload).
+ const submit = async () => {
+ if (busy || noUsableTwoFactor) return;
setFormError(null);
let serverUrl: string | undefined;
if (mode === 'connect') {
@@ -164,6 +179,7 @@ export const BitwardenLoginForm: React.FC<{
} catch (err) {
const p = err instanceof StoreError ? err.problem : ({ kind: 'error', message: 'Couldn’t reach the server.' } as UnlockProblem);
setProblem(p);
+ setTriedServer(server);
if (p.kind === 'two-factor') {
setStep(p);
setProvider(p.providers.find((x) => x.usable)?.id ?? null);
@@ -180,7 +196,6 @@ export const BitwardenLoginForm: React.FC<{
}
};
- const noUsableTwoFactor = step?.kind === 'two-factor' && !step.providers.some((p) => p.usable);
// The hint describes the field rather than naming it, so screen readers hear the label alone first.
const label = (text: string, input: React.ReactElement, hint?: React.ReactNode) => {
const hintId = `${id}-${text.replace(/\W+/g, '-').toLowerCase()}-hint`;
@@ -196,7 +211,7 @@ export const BitwardenLoginForm: React.FC<{
};
return (
- <form onSubmit={submit} className="space-y-2 text-xs" aria-labelledby={`${id}-t`} data-bitwarden-form={mode} noValidate>
+ <div role="group" onKeyDown={onKeyDown} className="space-y-2 text-xs" aria-labelledby={`${id}-t`} data-bitwarden-form={mode}>
<p id={`${id}-t`} className={plainTitle ? 'text-xs font-medium text-zinc-100 flex items-center gap-1.5' : 'text-[11px] font-semibold text-sky-400 flex items-center gap-1.5'}>
{mode === 'connect' ? <KeyRound size={12} aria-hidden="true" /> : <LockOpen size={12} aria-hidden="true" />}
{mode === 'connect' ? 'Connect Bitwarden' : 'Unlock Bitwarden'}
@@ -292,6 +307,11 @@ export const BitwardenLoginForm: React.FC<{
{formError && <ProblemLine text={formError} />}
{problem && !formError && problem.kind !== 'needs-token' && <ProblemLine text={unlockProblemText(problem)} />}
+ {mode === 'connect' && problem?.kind === 'wrong-password' && !formError && otherCloudHint(triedServer) && (
+ <p className="text-[11px] text-zinc-300 leading-snug" data-bw-other-cloud>
+ {otherCloudHint(triedServer)}
+ </p>
+ )}
{problem?.kind === 'needs-token' && (
<p role="alert" className="flex items-center gap-2 text-[11px] text-zinc-300">
{unlockProblemText(problem)}
@@ -305,12 +325,12 @@ export const BitwardenLoginForm: React.FC<{
<button type="button" onClick={onCancel} className={btnQuiet}>
Cancel
</button>
- <button type="submit" disabled={busy || noUsableTwoFactor} className={btnMain}>
+ <button type="button" onClick={() => void submit()} disabled={busy || noUsableTwoFactor} className={btnMain}>
{busy && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
{busy ? (mode === 'connect' ? 'Connecting…' : 'Unlocking…') : step ? 'Continue' : mode === 'connect' ? 'Connect' : 'Unlock'}
</button>
</div>
- </form>
+ </div>
);
};
@@ -525,7 +545,7 @@ export const PasswordStoreBar: React.FC<{
/>
<span>
<span className="block text-[11px] text-zinc-200 font-medium">Saved on this server</span>
- <span className="block text-[10px] text-zinc-500 leading-snug">Encrypted here. Works only while every space and bot is on “Ask before running commands”; otherwise use Bitwarden.</span>
+ <span className="block text-[10px] text-zinc-500 leading-snug">Encrypted here. While some bots run commands without asking, you confirm this once for this server; Bitwarden keeps passwords out of their reach.</span>
</span>
</label>
<label className={`flex items-start gap-2 p-2 rounded-lg border cursor-pointer ${onBitwarden || connecting ? 'border-sky-500/60 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-700'}`}>
@@ -737,7 +757,7 @@ export const ExposedBanner: React.FC<{
playSfx('click');
store.reload();
onApprovalsOn?.();
- if (r.failed) setError(`${r.failed} ${r.failed === 1 ? 'setting' : 'settings'} couldn’t be changed. An archived space keeps its approvals until you restore it.`);
+ if (r.failed) setError(`${r.failed} ${r.failed === 1 ? 'setting' : 'settings'} couldn’t be changed. Try again.`);
else setDone('Approvals are back on. Bots ask before running commands again.');
} catch (e) {
setError(e instanceof Error ? e.message : 'Couldn’t turn approvals back on.');
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 043ae4d3..837e4683 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -20,7 +20,7 @@ import { type NeedsYouRow, workingIds, directIds } from '../chatsTab';
import { DevFlipNote, useDevMode } from './DevModeSwitch';
import { SpaceControls } from './SpaceControls';
import { DevOnToast } from './DevOnToast';
-import { type DevModeState, deskIntent, devConnect, turnDevMode } from '../devMode';
+import { type DevModeState, deskIntent, turnDevMode } from '../devMode';
import { DevDeskRow } from './DevDesk';
import { IdeaJarRow } from './IdeaJarRow';
@@ -396,12 +396,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
setDevOnToast(s);
};
const focusDevSwitch = () => setTimeout(() => document.querySelector<HTMLElement>('[data-dev-switch]')?.focus(), 0);
- const connectDev = onConnectDevGitHub
- ? () => {
- devConnect.start(space.id);
- onConnectDevGitHub();
- }
- : undefined;
+ const connectDev = onConnectDevGitHub ? () => onConnectDevGitHub() : undefined;
const typeDevRepo = () => {
deskIntent.set(space.id, 'type');
onOpenDevDesk?.();
diff --git a/frontend/src/components/Spaces.tsx b/frontend/src/components/Spaces.tsx
index bd512aa8..62301b43 100644
--- a/frontend/src/components/Spaces.tsx
+++ b/frontend/src/components/Spaces.tsx
@@ -14,6 +14,9 @@ import {
spacesApi,
} from '../spaces';
import { useEscapeLayer } from '../escape';
+import { NeedsBitwardenError } from '../approvalMode';
+import { SAVE_FIRST, acceptRiskText } from '../passwordStore';
+import { MoveToBitwardenFirst, usePasswordStore } from './PasswordStorePanel';
import { devApi, devStore } from '../devMode';
import { DevBadge } from './DevModeSwitch';
@@ -444,20 +447,25 @@ export const ArchivedSpacesModal: React.FC<{ onClose: () => void; onRestored: (s
const [list, setList] = useState<Space[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
+ // The server wants the one-time choice before this space comes back (0.7.3 A3, as in the approvals confirm).
+ const [risk, setRisk] = useState<{ id: string; message: string; count: number | null } | null>(null);
+ const passwords = usePasswordStore(!!risk, true);
useEffect(() => {
spacesApi.archived().then(setList, (e) => setError(e instanceof Error ? e.message : 'Couldn’t load archived spaces.'));
}, []);
- const restore = async (s: Space) => {
+ const restore = async (s: Space, acceptRisk = false) => {
setBusy(s.id);
setError(null);
try {
- const restored = await spacesApi.patch(s.id, { archived: false });
+ const restored = await spacesApi.patch(s.id, acceptRisk ? { archived: false, accept_risk: true } : { archived: false });
+ setRisk(null);
setList((prev) => prev?.filter((x) => x.id !== s.id) ?? null);
playSfx('coin');
onRestored(restored);
} catch (e) {
- setError(e instanceof Error ? e.message : 'Couldn’t restore the space.');
+ if (e instanceof NeedsBitwardenError && e.canAccept && !acceptRisk) setRisk({ id: s.id, message: e.message, count: e.localCount });
+ else setError(e instanceof Error ? e.message : 'Couldn’t restore the space.');
} finally {
setBusy(null);
}
@@ -472,7 +480,7 @@ export const ArchivedSpacesModal: React.FC<{ onClose: () => void; onRestored: (s
{list?.length === 0 && <p className="text-xs text-zinc-500">No archived spaces.</p>}
<ul className="space-y-1.5">
{list?.map((s) => (
- <li key={s.id} className="flex items-center gap-3 p-2.5 rounded-xl border border-zinc-800 bg-zinc-950/50">
+ <li key={s.id} className="flex flex-wrap items-center gap-3 p-2.5 rounded-xl border border-zinc-800 bg-zinc-950/50">
<SpaceTile space={s} size={32} />
<div className="flex-1 min-w-0">
<p className="text-xs font-medium text-zinc-200 truncate">{s.name}</p>
@@ -492,6 +500,27 @@ export const ArchivedSpacesModal: React.FC<{ onClose: () => void; onRestored: (s
{busy === s.id ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" /> : <RotateCcw size={12} />}
Restore
</button>
+ {risk?.id === s.id && (
+ <div role="group" aria-label={`Restore ${s.name}`} className="basis-full rounded-lg border border-amber-500/40 bg-amber-500/10 p-2.5 space-y-2" data-restore-accept-risk>
+ <p className="text-[11px] text-amber-100 leading-snug">{risk.count ? acceptRiskText(risk.count) : risk.message}</p>
+ <div className="flex flex-wrap items-start gap-2">
+ <button
+ type="button"
+ autoFocus
+ disabled={busy === s.id}
+ onClick={() => restore(s, true)}
+ className="px-2.5 py-1.5 rounded-lg text-xs font-semibold text-zinc-950 bg-sky-500 hover:bg-sky-400 disabled:opacity-50"
+ data-restore-save
+ >
+ {SAVE_FIRST.save}
+ </button>
+ <MoveToBitwardenFirst store={passwords} label={SAVE_FIRST.bitwarden} onMoved={() => restore(s)} />
+ <button type="button" onClick={() => setRisk(null)} className="px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800">
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
</li>
))}
</ul>
diff --git a/frontend/src/components/TeamRepoDevLine.tsx b/frontend/src/components/TeamRepoDevLine.tsx
new file mode 100644
index 00000000..f9a56f94
--- /dev/null
+++ b/frontend/src/components/TeamRepoDevLine.tsx
@@ -0,0 +1,79 @@
+import React, { useEffect } from 'react';
+import { DevModeState, DevRepo, devApi, devStore, normaliseRepo } from '../devMode';
+import { useDevMode } from './DevModeSwitch';
+import { openGitHubConnect } from './GitHubConnect';
+
+/**
+ * Team settings > Git Repo, one line under the URL (0.7.3 B2): what Dev mode does with this team's repo,
+ * read from the space's Dev mode status (the same `/api/dev` the desk reads). Nothing shows for an
+ * empty URL or before the status is known.
+ */
+export const TEAM_REPO_LINES = {
+ connected: 'Dev mode watches this repo · GitHub connected',
+ connect: 'Dev mode watches this repo. Connect GitHub for reviews.',
+ off: 'Dev mode can watch this repo: turn it on next to the space name.',
+ git: 'Dev mode reads this repo with git. Reviews need GitHub.',
+} as const;
+export type TeamRepoLine = keyof typeof TEAM_REPO_LINES;
+
+/** `host/owner/name`, lowercased, without userinfo or `.git`: the key Dev mode's repos carry. */
+export function repoKeyOf(url: string): string | null {
+ const gh = normaliseRepo(url);
+ if (gh) return `github.com/${gh}`.toLowerCase();
+ let s = url.trim();
+ if (!s) return null;
+ s = s.replace(/^[a-z+]+:\/\//i, '').replace(/^[^@/]+@/, '');
+ // scp form: host:owner/name
+ s = s.replace(/^([^/:]+):(?!\d)/, '$1/');
+ s = s.replace(/[?#].*$/, '').replace(/\/+$/, '').replace(/\.git$/i, '');
+ return s.includes('/') ? s.toLowerCase() : null;
+}
+
+/** Which line a team's repo gets. null: say nothing. */
+export function teamRepoLine(state: DevModeState | null, url: string, teamId?: string | null): TeamRepoLine | null {
+ const key = repoKeyOf(url);
+ if (!state || !key) return null;
+ if (!state.on) return 'off';
+ // api.md B2: the team's own entry first, then the same repo (Dev mode keeps one entry per repo).
+ // A URL being edited that no longer matches the team's entry is read by the URL.
+ // Dev mode's key has no port (`127.0.0.1/owner/name`), a typed URL may (`127.0.0.1:9476/owner/name`).
+ const same = (r: DevRepo) => r.key === key || r.key === key.replace(/^([^/]+):\d+\//, '$1/');
+ const own = teamId ? state.repos.find((r) => r.team_id === teamId) : undefined;
+ const row: DevRepo | undefined = own && same(own) ? own : state.repos.find(same);
+ const github = row ? row.provider === 'github' : key.startsWith('github.com/');
+ if (!github) return 'git';
+ const notConnected = (row ? row.status === 'not_connected' : state.status === 'not_connected') || state.forge !== 'github';
+ return notConnected ? 'connect' : 'connected';
+}
+
+export const TeamRepoDevLine: React.FC<{ url: string; teamId?: string | null; spaceId?: string | null }> = ({ url, teamId = null, spaceId }) => {
+ const space = spaceId ?? devStore.current();
+ const state = useDevMode(space);
+ // Opened before the desk ever read this space: read it once.
+ useEffect(() => {
+ if (!space || devStore.get(space)) return;
+ devApi.get(space).then((st) => devStore.set(space, st), () => undefined);
+ }, [space]);
+ const line = teamRepoLine(state, url, teamId);
+ if (!line) return null;
+ return (
+ <p className="text-[11px] text-zinc-400 mt-1" data-team-repo-dev={line} aria-live="polite">
+ {line === 'connect' ? (
+ <>
+ Dev mode watches this repo.{' '}
+ <button
+ type="button"
+ onClick={(e) => openGitHubConnect({ space: space ?? undefined, anchor: e.currentTarget })}
+ className="font-medium text-sky-300 hover:text-sky-200 underline underline-offset-2"
+ data-team-repo-connect
+ >
+ Connect GitHub
+ </button>{' '}
+ for reviews.
+ </>
+ ) : (
+ TEAM_REPO_LINES[line]
+ )}
+ </p>
+ );
+};
diff --git a/frontend/src/looseEnds.ts b/frontend/src/looseEnds.ts
index fe8d74f3..15dafe6c 100644
--- a/frontend/src/looseEnds.ts
+++ b/frontend/src/looseEnds.ts
@@ -202,6 +202,8 @@ export class LooseEndsError extends Error {
public locked = false,
/** The server's `code`, e.g. `busy` on a 409. */
public code: string | null = null,
+ /** 0.7.3 (A2): with needsBitwarden, the person may save here anyway (`accept_risk`). */
+ public canAccept = false,
) {
super(message);
}
@@ -230,7 +232,7 @@ export async function call<T>(url: string, method = 'GET', body?: unknown): Prom
const answer = await res.json().catch(() => null);
if (res.ok) return answer as T;
const needs = needsBitwardenFrom(res.status, answer);
- if (needs) throw new LooseEndsError(needs.message, 409, true);
+ if (needs) throw new LooseEndsError(needs.message, 409, true, false, null, needs.can_accept);
const err = answer && typeof answer === 'object' ? (answer as Record<string, unknown>).error : null;
const code = answer && typeof answer === 'object' && typeof (answer as Record<string, unknown>).code === 'string' ? ((answer as Record<string, unknown>).code as string) : null;
const msg = typeof err === 'string' && err.trim() ? sentence(err) : `Something went wrong (HTTP ${res.status}).`;
@@ -285,7 +287,8 @@ export const looseApi = {
cases: () => call<{ cases: LooseCase[]; running: boolean }>('/api/zombie/cases'),
act: (id: string, action: CaseAction, body?: unknown) => call<LooseCase>(`/api/zombie/cases/${enc(id)}/${action}`, 'POST', body ?? {}),
sources: () => call<{ sources: LooseSource[]; vault_locked: boolean }>('/api/zombie/sources'),
- addSource: (s: NewSource) => call<{ source: LooseSource; test: unknown }>('/api/zombie/sources', 'POST', s),
+ /** `acceptRisk` (0.7.3 A2): keep the login on this server although some bot runs without asking. Once per server. */
+ addSource: (s: NewSource, acceptRisk = false) => call<{ source: LooseSource; test: unknown }>('/api/zombie/sources', 'POST', acceptRisk ? { ...s, accept_risk: true } : s),
setEnabled: (id: string, enabled: boolean) => call<{ source: LooseSource }>(`/api/zombie/sources/${enc(id)}`, 'PATCH', { enabled }),
removeSource: (id: string) => call<{ deleted: boolean; cases_removed: number }>(`/api/zombie/sources/${enc(id)}`, 'DELETE'),
testSource: (id: string) => call<{ ok: boolean; test: unknown }>(`/api/zombie/sources/${enc(id)}/test`, 'POST'),
diff --git a/frontend/src/passwordStore.ts b/frontend/src/passwordStore.ts
index 8bb2a8b5..d87bd512 100644
--- a/frontend/src/passwordStore.ts
+++ b/frontend/src/passwordStore.ts
@@ -29,6 +29,8 @@ export interface StoreStatus {
/** Approvals off while passwords are still saved here (an install from before the block): any
* bot that can run commands can read them. Nothing changes it on its own. */
exposed: boolean;
+ /** 0.7.3 (A2): the person accepted keeping logins on this server once; nothing refuses a save again. false on an older server. */
+ risk_accepted: boolean;
}
const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);
@@ -59,6 +61,7 @@ export function parseStoreStatus(raw: unknown): StoreStatus {
bitwarden,
approvals_off,
exposed: o.exposed === true,
+ risk_accepted: o.risk_accepted === true,
};
}
@@ -69,6 +72,16 @@ export const BITWARDEN_CLOUDS = [
] as const;
export const DEFAULT_BITWARDEN_SERVER = BITWARDEN_CLOUDS[0].value;
+/**
+ * 0.7.3 C5: a wrong password on one Bitwarden cloud is often an account on the other one (both answer
+ * "wrong email or master password"). The line naming the other cloud, or null for a self-hosted server.
+ */
+export function otherCloudHint(server: string): string | null {
+ const i = BITWARDEN_CLOUDS.findIndex((c) => c.value === server);
+ if (i < 0) return null;
+ return `Is your account on ${BITWARDEN_CLOUDS[1 - i].label}? Choose it under Server.`;
+}
+
/** A short name for the account's server: "bitwarden.com", or the self-hosted host. */
export function serverLabel(serverUrl: string): string {
const cloud = BITWARDEN_CLOUDS.find((c) => c.value === serverUrl.replace(/\/+$/, ''));
@@ -273,35 +286,44 @@ export const exposedText = (n: number) =>
`A space or bot is on “Ask only when risky” or “Don’t ask” and ${passwords(n)} ${n === 1 ? 'is' : 'are'} still on this server, so any bot that can run commands can read ${n === 1 ? 'it' : 'them'}.`;
/** A 409 that says the server wants Bitwarden first: its sentence, and how many passwords are here. */
-export function needsBitwardenFrom(status: number, body: unknown): { message: string; local_count: number | null } | null {
+export function needsBitwardenFrom(status: number, body: unknown): { message: string; local_count: number | null; can_accept: boolean } | null {
const o = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};
if (status !== 409 || o.needs_bitwarden !== true) return null;
const msg = str(o.error)?.trim();
return {
message: msg ? capitalise(msg.endsWith('.') ? msg : `${msg}.`) : 'Move the passwords on this server to Bitwarden first.',
local_count: num(o.local_count),
+ /** 0.7.3 (A2): the person can accept the risk and save here anyway (`accept_risk: true`). */
+ can_accept: o.can_accept === true,
};
}
/**
* Whether a new login (Dev mode's GitHub token) can be saved right now, read before the person types it:
- * `open`; `store` = this server's store under "Ask only when risky" or "Don't ask" (the 409
- * needs_bitwarden, audit F-10); `locked` = Bitwarden is the store and is locked.
+ * `open`; `store` = this server's store while some bot runs without asking, and the person hasn't
+ * accepted that yet (0.7.3 A2: a warning, not a wall); `locked` = Bitwarden is the store and is locked.
*/
export type SaveGate = 'open' | 'store' | 'locked';
export const saveGate = (s: StoreStatus | null | undefined): SaveGate =>
- !s ? 'open' : s.store === 'local' ? (s.approvals_off ? 'store' : 'open') : s.locked ? 'locked' : 'open';
+ !s ? 'open' : s.store === 'local' ? (s.approvals_off && !s.risk_accepted ? 'store' : 'open') : s.locked ? 'locked' : 'open';
-/** The two ways out, before the token field (flow F5). `ask` changes every space and bot, so `askScope` says so. */
+/** The card before the token field (0.7.3 A3): a warning with three ways on. Save sends `accept_risk`, once per server. */
export const SAVE_FIRST = {
- title: 'One step before the token',
+ title: 'Before you save the token',
lockedTitle: 'Bitwarden is locked. Unlock it to save this login there.',
- bitwarden: 'Connect Bitwarden',
+ why: 'Some bots here run commands without asking, so one of them could read a token saved on this server. A read-only token limited to the repos you need keeps that risk small.',
+ save: 'Save it on this server',
+ bitwarden: 'Use Bitwarden',
unlock: 'Unlock Bitwarden',
- why: 'Some bots here run commands without asking, so they could read a token saved on this server. Keep it in Bitwarden, or make every bot ask first.',
ask: 'Make every bot ask first',
askScope: 'Turns on “Ask before running commands” in every space. You can change it back in each space’s settings.',
asking: 'Switching…',
asked: 'Every bot now asks before running commands. Add the token below.',
+ askLeft: 'A space or bot still runs without asking. Try again, or save it on this server.',
connected: 'Bitwarden is connected. Add the token below.',
} as const;
+
+/** The approvals switch, with passwords on this server and the risk not yet accepted (0.7.3 A3): one confirm, once per server. */
+export const acceptRiskText = (n: number) =>
+ `${capitalise(passwords(n))} ${n === 1 ? 'is' : 'are'} kept on this server. Under “Ask only when risky” or “Don’t ask”, a bot that can run commands could read ${n === 1 ? 'it' : 'them'}. You confirm this once for this server; Bitwarden keeps ${n === 1 ? 'it' : 'them'} out of reach.`;
+export const acceptRiskLabel = (n: number) => `Keep ${n === 1 ? 'it' : 'them'} here and turn off approvals`;
diff --git a/frontend/src/spaces.ts b/frontend/src/spaces.ts
index d8ad411f..783f9a28 100644
--- a/frontend/src/spaces.ts
+++ b/frontend/src/spaces.ts
@@ -3,6 +3,8 @@
import { parseView, viewSegment, type SpaceView } from './nav';
import { pickedLine, serverReason } from './routeReason';
+import { NeedsBitwardenError } from './approvalMode';
+import { needsBitwardenFrom } from './passwordStore';
export interface SpaceCounts {
bots: number;
@@ -40,6 +42,8 @@ export interface SpacePatch {
icon?: string;
color?: string | null;
archived?: boolean;
+ /** 0.7.3: restore a space that doesn't ask while passwords are on this server (the one-time confirm). */
+ accept_risk?: boolean;
}
export const DEFAULT_SPACE_ID = 'spc_default';
@@ -361,5 +365,16 @@ export const spacesApi = {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
- }).then((r) => json<Space>(r, 'Couldn’t save the space')),
+ }).then(async (r) => {
+ // A space that doesn't ask, coming back while passwords are on this server: the same one-time choice.
+ if (r.status === 409) {
+ const body = await r
+ .clone()
+ .json()
+ .catch(() => null);
+ const needs = needsBitwardenFrom(r.status, body);
+ if (needs) throw new NeedsBitwardenError(needs.message, needs.local_count, needs.can_accept);
+ }
+ return json<Space>(r, 'Couldn’t save the space');
+ }),
};
diff --git a/frontend/tests/approvalsNeedBitwarden.test.mjs b/frontend/tests/approvalsNeedBitwarden.test.mjs
index 16cf7d0d..e3c6c146 100644
--- a/frontend/tests/approvalsNeedBitwarden.test.mjs
+++ b/frontend/tests/approvalsNeedBitwarden.test.mjs
@@ -148,7 +148,7 @@ test('saving here while a space or bot doesn\'t ask before commands: the 409 rea
assert.match(src, /err\.needsBitwarden\) setPassword\(''\)/);
});
-test('"Turn approvals back on": every active space that is off and every bot set to off → ask; archived counts as not changed', async () => {
+test('"Turn approvals back on": every active space that is off and every bot set to off → ask; archived spaces are skipped and don\'t count (0.7.3 A1)', async () => {
let changedEvents = 0;
await withFetch(
(url, init) => {
@@ -167,7 +167,8 @@ test('"Turn approvals back on": every active space that is off and every bot set
},
async (calls) => {
window.addEventListener(m.APPROVALS_CHANGED_EVENT, () => changedEvents++);
- assert.deepEqual(await m.approvalModeApi.turnAllOn(), { changed: 3, failed: 1 });
+ assert.deepEqual(await m.approvalModeApi.turnAllOn(), { changed: 3, failed: 0 });
+ assert.ok(!calls.some((c) => c.url === '/api/spaces?archived=1'), 'archived spaces are not even listed');
const puts = calls.filter((c) => c.method === 'PUT');
assert.deepEqual(
puts.map((c) => `${c.url} ${c.body}`),
@@ -181,18 +182,17 @@ test('"Turn approvals back on": every active space that is off and every bot set
// ---------------------------------------------------------------- the confirm
-test('confirm with passwords here: "off" isn\'t offered; it says why and offers to move them first', () => {
+test('confirm with passwords here (0.7.3 A3): it says why, offers to move them first, and lets the person keep them here once', () => {
const html = m.confirm(LOCAL3);
const t = text(html);
- assert.match(html, /data-off-needs-bitwarden/);
- assert.match(t, /3 saved passwords are kept on this server\. Under “Ask only when risky” or “Don't ask”, any bot that can run commands could read them, so move them to Bitwarden first\./);
- assert.deepEqual(buttons(html), ['Move 3 saved passwords to Bitwarden first', 'Cancel']);
+ assert.match(html, /data-off-accept-risk/);
+ assert.match(t, /3 saved passwords are kept on this server\. Under “Ask only when risky” or “Don.t ask”, a bot that can run commands could read them\. You confirm this once for this server; Bitwarden keeps them out of reach\./);
+ assert.deepEqual(buttons(html), ['Move them to Bitwarden first', 'Cancel', 'Keep them here and turn off approvals']);
+ assert.match(html, /data-off-confirm="accept-risk"/);
assert.ok(!buttons(html).includes('Turn off approvals'));
- // The paragraph says it; the note isn't repeated above it.
assert.ok(!t.includes(LOCAL_NOTE));
- // Bitwarden with leftovers here, and Bitwarden locked with some here: the same.
- assert.deepEqual(buttons(m.confirm(BW_LEFTOVER)), ['Move 2 saved passwords to Bitwarden first', 'Cancel']);
- assert.deepEqual(buttons(m.confirm(BW_LOCKED)), ['Move 3 saved passwords to Bitwarden first', 'Cancel']);
+ assert.deepEqual(buttons(m.confirm(BW_LEFTOVER)), ['Move them to Bitwarden first', 'Cancel', 'Keep them here and turn off approvals']);
+ assert.deepEqual(buttons(m.confirm(BW_LOCKED)), ['Move them to Bitwarden first', 'Cancel', 'Keep them here and turn off approvals']);
});
test('confirm with nothing here: "off" is offered, with the sentence for that store', () => {
@@ -215,12 +215,13 @@ test('confirm while the store is still loading: "off" waits; with no store info
});
test('space and bot settings use it: move first with passwords here, off with none', () => {
- assert.match(text(m.spaceSetting({ initialConfirm: true, initialPasswords: LOCAL3 })), /Move 3 saved passwords to Bitwarden first/);
+ assert.match(text(m.spaceSetting({ initialConfirm: true, initialPasswords: LOCAL3 })), /Move them to Bitwarden first/);
+ assert.ok(buttons(m.spaceSetting({ initialConfirm: true, initialPasswords: LOCAL3 })).includes('Keep them here and turn off approvals'));
assert.ok(!buttons(m.spaceSetting({ initialConfirm: true, initialPasswords: LOCAL3 })).includes('Turn off approvals'));
const state = { kwant_id: 'k1', approvals: 'inherit', approvals_effective: 'ask', space_approvals: 'ask' };
const bot = m.botSetting({ initial: state, initialPending: 'off', initialPasswords: LOCAL3 });
assert.match(text(bot), /Let Dev run everything without approval\?/);
- assert.match(text(bot), /Move 3 saved passwords to Bitwarden first/);
+ assert.match(text(bot), /Move them to Bitwarden first/);
assert.ok(!buttons(bot).includes('Turn off approvals'));
assert.ok(buttons(m.botSetting({ initial: state, initialPending: 'off', initialPasswords: BW })).includes('Turn off approvals'));
});
diff --git a/frontend/tests/bitwardenStore.test.mjs b/frontend/tests/bitwardenStore.test.mjs
index 00073503..d0fcb2d9 100644
--- a/frontend/tests/bitwardenStore.test.mjs
+++ b/frontend/tests/bitwardenStore.test.mjs
@@ -36,9 +36,9 @@ const buttons = (html) => [...html.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/g
const inputs = (html) => [...html.matchAll(/<input[^>]*>/g)].map((x) => x[0]);
const login = (p) => ({ id: 'c1', origin: 'https://example.com', domain: 'example.com', username: 'alice', created_at: null, last_used: null, ...p });
const bw = (p) => ({ server_url: 'https://vault.bitwarden.com', email: '[email protected]', login: 'password', client_id: null, unlocked: true, unlocked_at: 't', item_count: 4, last_sync: 't', ...p });
-const LOCAL = { store: 'local', locked: false, local_count: 3, bitwarden: null, approvals_off: false, exposed: false };
-const UNLOCKED = { store: 'bitwarden', locked: false, local_count: 0, bitwarden: bw(), approvals_off: false, exposed: false };
-const LOCKED = { store: 'bitwarden', locked: true, local_count: 0, bitwarden: bw({ unlocked: false, unlocked_at: null, item_count: null }), approvals_off: false, exposed: false };
+const LOCAL = { store: 'local', locked: false, local_count: 3, bitwarden: null, approvals_off: false, exposed: false, risk_accepted: false };
+const UNLOCKED = { store: 'bitwarden', locked: false, local_count: 0, bitwarden: bw(), approvals_off: false, exposed: false, risk_accepted: false };
+const LOCKED = { store: 'bitwarden', locked: true, local_count: 0, bitwarden: bw({ unlocked: false, unlocked_at: null, item_count: null }), approvals_off: false, exposed: false, risk_accepted: false };
// ---------------------------------------------------------------- the model
@@ -49,7 +49,7 @@ test('store status: local, Bitwarden unlocked, Bitwarden locked (also when only
assert.equal(u.bitwarden.email, '[email protected]');
assert.equal(m.parseStoreStatus({ store: 'bitwarden', locked: false, bitwarden: bw({ unlocked: false }) }).locked, true);
assert.equal(m.parseStoreStatus({ store: 'bitwarden', locked: true, bitwarden: bw() }).locked, true);
- assert.deepEqual(m.parseStoreStatus(null), { store: 'local', locked: false, local_count: 0, bitwarden: null, approvals_off: false, exposed: false });
+ assert.deepEqual(m.parseStoreStatus(null), { store: 'local', locked: false, local_count: 0, bitwarden: null, approvals_off: false, exposed: false, risk_accepted: false });
assert.equal(m.parseStoreStatus({ store: 'local', bitwarden: bw({ login: 'api_key', client_id: 'user.x' }) }).bitwarden.login, 'api_key');
});
@@ -174,7 +174,7 @@ test('the store bar: this server, Bitwarden unlocked with Lock, Bitwarden locked
test('the picker: two choices, said plainly; Bitwarden opens the connect form', () => {
const html = m.bar(LOCAL, { initialOpen: true });
assert.match(text(html), /Where passwords are kept, for every bot/);
- assert.match(text(html), /Saved on this server Encrypted here\. Works only while every space and bot is on “Ask before running commands”; otherwise use Bitwarden\./);
+ assert.match(text(html), /Saved on this server Encrypted here\. While some bots run commands without asking, you confirm this once for this server; Bitwarden keeps passwords out of their reach\./);
assert.match(text(html), /Bitwarden In your own Bitwarden account/);
assert.equal(inputs(html).filter((i) => /type="radio"/.test(i)).length, 2);
const connecting = m.bar(LOCAL, { initialOpen: true, initialConnecting: true });
@@ -228,7 +228,7 @@ test('two-step login and new-device code are asked for in the same form', () =>
assert.doesNotMatch(text(only), /Method/, 'no picker for one method');
const passkey = m.form({ mode: 'unlock', status: LOCKED, initialStep: { kind: 'two-factor', providers: m.twoFactorChoices(['7']) }, initialProblem: { kind: 'two-factor', providers: m.twoFactorChoices(['7']) } });
assert.match(text(passkey), /Use an API key instead/);
- assert.match(passkey, /<button type="submit" disabled=""/);
+ assert.match(passkey, /<button type="button" disabled=""[^>]*>Continue/);
const device = m.form({ mode: 'unlock', status: LOCKED, initialStep: { kind: 'new-device-code' } });
assert.match(text(device), /Code from Bitwarden's email/);
const wrong = m.form({ mode: 'unlock', status: LOCKED, initialProblem: { kind: 'wrong-password' } });
diff --git a/frontend/tests/devAutodetect.test.mjs b/frontend/tests/devAutodetect.test.mjs
index e21e1720..c064966c 100644
--- a/frontend/tests/devAutodetect.test.mjs
+++ b/frontend/tests/devAutodetect.test.mjs
@@ -258,16 +258,28 @@ test('PX-2 (style-v2 §3/§4): header chip and subtitle, LED per status, Checked
root.unmount();
});
-test('DOM: Connect opens Loose ends; it hides when the app gives no way there', async () => {
- let opened = 0;
- const { root } = await desk({ status: 'not_connected', repo: 'demo-org/demo-web', sources: [SOURCES[0]] }, { onOpenLooseEnds: () => opened++ });
+test('B1 DOM: Connect opens the shared GitHub form in place, next to the button; the app’s handler gets the button', async () => {
+ let opened = null;
+ const { root } = await desk({ status: 'not_connected', repo: 'demo-org/demo-web', sources: [SOURCES[0]] }, { onOpenLooseEnds: (a) => (opened = a) });
const connect = document.querySelector('[data-dv-status-action="connect"]');
assert.equal(connect.textContent.trim(), 'Connect GitHub');
await click(connect);
- assert.equal(opened, 1);
+ assert.ok(opened === connect, 'anchored to the button');
root.unmount();
+ const seen = [];
+ const on = (e) => seen.push(e.detail);
+ window.addEventListener('kwnt:github-connect', on);
const again = await desk({ status: 'not_connected', sources: [] });
- assert.equal(document.querySelector('[data-dv-status-action]'), null);
+ const b = document.querySelector('[data-dv-status-action="connect"]');
+ assert.ok(b, 'no handler given: still offered, it opens the shared form');
+ await click(b);
+ const empty = document.querySelector('[data-dev-empty-connect]');
+ if (empty) await click(empty);
+ window.removeEventListener('kwnt:github-connect', on);
+ assert.ok(seen.length >= 1);
+ assert.equal(seen[0].space, 'spc_demo');
+ assert.ok(seen[0].anchor === b);
+ assert.equal(server.calls.filter(([, u]) => u.includes('/loose')).length, 0, 'nothing navigates to Loose ends');
again.root.unmount();
});
@@ -647,23 +659,23 @@ const connectForm = async (store, spaces) => {
return r;
};
-test('B2 DOM: under "Ask only when risky" Connect offers the two ways out before any token field, and nothing is sent', async () => {
+test('A3 DOM: under "Ask only when risky" Connect shows the warning card before any token field, and nothing is sent', async () => {
const { root } = await connectForm({ store: 'local', local_count: 0, approvals_off: true }, [{ id: 'spc_demo', approvals: 'smart' }]);
const gate = document.querySelector('[data-save-first]');
- assert.ok(gate, 'the ways out show');
+ assert.ok(gate, 'the card shows');
assert.equal(gate.dataset.saveFirst, 'store');
assert.equal(document.querySelector('input[type="password"]'), null, 'no token field to type into yet');
- assert.match(gate.textContent, /One step before the token/);
- assert.equal(gate.querySelector('[data-save-first-bitwarden]').textContent.trim(), 'Connect Bitwarden');
+ assert.match(gate.textContent, /^Before you save the token/);
+ assert.equal(gate.querySelector('[data-save-first-why]').textContent, 'Some bots here run commands without asking, so one of them could read a token saved on this server. A read-only token limited to the repos you need keeps that risk small.');
+ assert.equal(gate.querySelector('[data-save-first-save]').textContent.trim(), 'Save it on this server');
+ assert.equal(gate.querySelector('[data-save-first-bitwarden]').textContent.trim(), 'Use Bitwarden');
assert.equal(gate.querySelector('[data-save-first-ask]').textContent.trim(), 'Make every bot ask first');
- assert.equal(gate.querySelector('[data-save-first-why]').textContent, 'Some bots here run commands without asking, so they could read a token saved on this server. Keep it in Bitwarden, or make every bot ask first.', 'M2: its own reason line');
- assert.equal(gate.querySelector('[data-save-first-scope]').textContent, 'Turns on “Ask before running commands” in every space. You can change it back in each space’s settings.', 'M1: the scope is said');
- assert.match(gate.querySelector('[data-save-first-scope]').className, /text-\[11px\] text-amber-100\/70/);
- for (const b of gate.querySelectorAll('[data-save-first-bitwarden], [data-save-first-ask]')) assert.match(b.className, /w-full sm:w-auto/, 'S2: equal width when stacked');
- assert.match(gate.className, /border-amber-500\/40 bg-amber-500\/10/, 'amber while it needs you');
- assert.ok(document.activeElement === gate.querySelector('[data-save-first-bitwarden]'), 'B3: focus lands on the first way out');
+ assert.match(gate.querySelector('[data-save-first-save]').className, /bg-sky-500/, 'Save is the primary');
+ assert.equal(gate.querySelector('[data-save-first-scope]').textContent, 'Turns on “Ask before running commands” in every space. You can change it back in each space’s settings.');
+ for (const b of gate.querySelectorAll('[data-save-first-save], [data-save-first-bitwarden], [data-save-first-ask]')) assert.match(b.className, /w-full sm:w-auto/, 'equal width when stacked');
+ assert.ok(document.activeElement === gate.querySelector('[data-save-first-save]'), 'focus lands on Save');
assert.equal(document.querySelector('button[type="submit"]').disabled, true);
- assert.equal(server.calls.filter(([meth, u]) => meth === 'POST' && u.includes('/loose')).length, 0);
+ assert.equal(server.calls.filter(([meth, u]) => meth === 'POST' && u.includes('/zombie')).length, 0);
root.unmount();
});
@@ -681,7 +693,7 @@ test('B2 DOM: "Ask before running commands" switches every space and bot to ask,
root.unmount();
});
-test('B2 DOM: Connect Bitwarden opens the existing Bitwarden form in place; a locked Bitwarden offers Unlock only', async () => {
+test('B2 DOM: Use Bitwarden opens the existing Bitwarden form in place; a locked Bitwarden offers Unlock only', async () => {
const one = await connectForm({ store: 'local', local_count: 0, approvals_off: true }, []);
await click(document.querySelector('[data-save-first-bitwarden]'));
assert.equal(document.querySelector('[data-save-first-bitwarden]'), null, 'the Bitwarden form replaces the buttons');
diff --git a/frontend/tests/githubConnect073.test.mjs b/frontend/tests/githubConnect073.test.mjs
new file mode 100644
index 00000000..4aeba6eb
--- /dev/null
+++ b/frontend/tests/githubConnect073.test.mjs
@@ -0,0 +1,561 @@
+// 0.7.3 github-connect (Pixel): A3 the warning card and its one-time Save, B1 one GitHub form opened
+// in place (popover on desktop, sheet on phone), B2 Team settings' repo line, B3 the helper text,
+// C5 the other-cloud hint under a wrong master password, C6 the gate re-checked on focus.
+// Demo data only: no real repos, tokens or emails, and nothing leaves this process.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_demo', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'HTMLSelectElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.IS_REACT_ACT_ENVIRONMENT = false;
+let phone = false;
+window.matchMedia = (q) => ({ matches: q.includes('max-width: 767px') ? phone : false, media: q, addEventListener() {}, removeEventListener() {} });
+
+let server;
+const OLD_SPACE = { id: 'spc_old', name: 'Old', icon: 'box', color: null, archived_at: '2026-10-01T00:00:00Z', counts: { bots: 2 } };
+const json = (b, status = 200) => new Response(JSON.stringify(b), { status, headers: { 'Content-Type': 'application/json' } });
+g.fetch = g.window.fetch = async (url, init = {}) => {
+ const u = String(url);
+ const method = init.method ?? 'GET';
+ const body = init.body ? JSON.parse(init.body) : undefined;
+ const path = u.split('?')[0];
+ server.calls.push([method, path, body]);
+ if (path === '/api/passwords/store') return json(server.store);
+ if (path === '/api/passwords/bitwarden/unlock') return json({ error: 'Wrong master password.', wrong_password: true }, 401);
+ if (path === '/api/zombie/sources' && method === 'POST') {
+ if (server.refuse && !body.accept_risk) return json({ error: 'Some bots here run commands without asking.', needs_bitwarden: true, can_accept: true }, 409);
+ return json({ source: { id: 'src_demo', kind: 'github', label: body.label || 'GitHub', enabled: true }, test: null });
+ }
+ if (/\/dev_mode$/.test(path)) return json(server.dev ?? { on: false, repos: [] });
+ if (path === '/api/spaces' && method === 'GET') return json([OLD_SPACE]);
+ if (path === `/api/spaces/${OLD_SPACE.id}` && method === 'PATCH') {
+ if (!body.accept_risk) return json({ error: 'Passwords are kept on this server and bots in this space run commands without asking.', needs_bitwarden: true, can_accept: true, local_count: 2 }, 409);
+ return json({ ...OLD_SPACE, archived_at: null });
+ }
+ return json({});
+};
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { saveGate, SAVE_FIRST, otherCloudHint, parseStoreStatus } from './src/passwordStore';
+ export { GitHubConnectForm, NeedsBitwarden, GITHUB_ALSO_DEV, LooseSources } from './src/components/LooseEndsView';
+ export { GitHubConnectHost, openGitHubConnect, popoverPlace, GITHUB_CONNECT_EVENT, GITHUB_CONNECTED_EVENT } from './src/components/GitHubConnect';
+ export { TeamRepoDevLine, teamRepoLine, repoKeyOf, TEAM_REPO_LINES } from './src/components/TeamRepoDevLine';
+ export { BitwardenLoginForm, MoveToBitwardenFirst } from './src/components/PasswordStorePanel';
+ export { AddSourceForm } from './src/components/LooseEndsView';
+ export { ArchivedSpacesModal } from './src/components/Spaces';
+ export { acceptRiskText } from './src/passwordStore';
+ export { parseDevMode, devStore } from './src/devMode';
+`);
+const { React, createRoot } = m;
+const h = React.createElement;
+const settle = async (n = 10) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const frame = () => new Promise((r) => setTimeout(r, 40));
+const click = async (el) => {
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const typeIn = (el, value) => {
+ const proto = el.tagName === 'SELECT' ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, value);
+ el.dispatchEvent(new window.Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
+};
+const mount = async (el) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(el);
+ await settle();
+ return { host, root };
+};
+const noop = () => {};
+const STORE_OFF = { store: 'local', locked: false, local_count: 0, bitwarden: null, approvals_off: true, exposed: false, risk_accepted: false };
+const reset = (over = {}) => {
+ server = { store: STORE_OFF, calls: [], refuse: false, ...over };
+ m.devStore._reset();
+ localStorage.clear();
+ document.body.innerHTML = '';
+ phone = false;
+};
+const posts = () => server.calls.filter(([meth, p]) => meth === 'POST' && p === '/api/zombie/sources').map(([, , b]) => b);
+
+// ---------------------------------------------------------------- A3: the card
+
+test('A3: the gate reads the store; once the risk is accepted the token field opens straight away', () => {
+ const st = (o) => m.parseStoreStatus({ ...STORE_OFF, ...o });
+ assert.equal(m.saveGate(st({})), 'store');
+ assert.equal(m.saveGate(st({ risk_accepted: true })), 'open', 'accepted once for this server');
+ assert.equal(m.saveGate(st({ approvals_off: false })), 'open');
+ assert.equal(m.saveGate(st({ store: 'bitwarden', locked: true, bitwarden: { server_url: 'https://vault.bitwarden.com', email: '[email protected]', login: 'password', unlocked: false } })), 'locked');
+ assert.equal(m.parseStoreStatus({ ...STORE_OFF, risk_accepted: true }).risk_accepted, true);
+ assert.equal(m.parseStoreStatus({ store: 'local' }).risk_accepted, false, 'an older server: not accepted');
+});
+
+test('A3 DOM: Save it on this server opens the token field, and the save carries accept_risk once', async () => {
+ reset();
+ const added = [];
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: (s) => added.push(s), onCancel: noop, land: true, scroll: false }));
+ await frame();
+ const gate = document.querySelector('[data-save-first]');
+ assert.equal(gate?.dataset.saveFirst, 'store');
+ assert.match(gate.textContent, /^Before you save the token/);
+ assert.equal(document.querySelector('[data-github-token]'), null);
+ assert.equal(document.activeElement, gate.querySelector('[data-save-first-save]'), 'Save it on this server is focused');
+ await click(gate.querySelector('[data-save-first-save]'));
+ await frame();
+ const tok = document.querySelector('[data-github-token]');
+ assert.ok(tok, 'the token field shows');
+ assert.equal(document.activeElement, tok);
+ tok.value = 'demo-not-a-token';
+ document.querySelector('form[data-github-connect]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle(20);
+ assert.equal(posts().length, 1);
+ assert.equal(posts()[0].accept_risk, true, 'the person pressed Save: sent with the save');
+ assert.equal(added.length, 1);
+ assert.equal(tok.value, '', 'the token leaves the field once saved');
+ root.unmount();
+});
+
+test('A3 DOM: with nothing to warn about, no card and no accept_risk', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false } });
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: noop, onCancel: noop }));
+ await frame();
+ assert.equal(document.querySelector('[data-save-first]'), null);
+ document.querySelector('[data-github-token]').value = 'demo-not-a-token';
+ document.querySelector('form[data-github-connect]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle(20);
+ assert.equal(posts()[0].accept_risk, undefined);
+ root.unmount();
+});
+
+test('A3 DOM: a 409 with can_accept offers Save it on this server first; pressing it retries with accept_risk', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false }, refuse: true });
+ const added = [];
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: (s) => added.push(s), onCancel: noop }));
+ await frame();
+ document.querySelector('[data-github-token]').value = 'demo-not-a-token';
+ document.querySelector('form[data-github-connect]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle(20);
+ const card = document.querySelector('[data-needs-bitwarden]');
+ assert.ok(card, 'the refusal card shows');
+ const save = card.querySelector('[data-needs-bitwarden-save]');
+ assert.equal(save.textContent.trim(), 'Save it on this server');
+ assert.match(save.className, /bg-sky-500/, 'Save is the primary');
+ // The token stays in the field until it's saved.
+ await click(save);
+ await settle(20);
+ assert.deepEqual(posts().map((b) => !!b.accept_risk), [false, true]);
+ assert.equal(added.length, 1);
+ root.unmount();
+});
+
+test('A3: the NeedsBitwarden card without can_accept keeps the old ways only', () => {
+ const html = m.renderToStaticMarkup(h(m.NeedsBitwarden, { message: 'x', locked: false, onReady: noop, onCancel: noop }));
+ assert.doesNotMatch(html, /data-needs-bitwarden-save/);
+ const locked = m.renderToStaticMarkup(h(m.NeedsBitwarden, { message: 'x', locked: true, canAccept: true, onReady: noop, onCancel: noop }));
+ assert.doesNotMatch(locked, /data-needs-bitwarden-save/, 'a locked Bitwarden is unlocked, not bypassed');
+});
+
+// ---------------------------------------------------------------- C6: re-check on focus
+
+test('C6 DOM: Bitwarden connected elsewhere unblocks the card when the window gets focus again', async () => {
+ reset();
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: noop, onCancel: noop }));
+ await frame();
+ assert.ok(document.querySelector('[data-save-first]'));
+ const peeks = () => server.calls.filter(([, p]) => p === '/api/passwords/store').length;
+ const before = peeks();
+ server.store = { ...STORE_OFF, store: 'bitwarden', local_count: 0, bitwarden: { server_url: 'https://vault.bitwarden.com', email: '[email protected]', login: 'password', unlocked: true } };
+ window.dispatchEvent(new window.Event('focus'));
+ await settle(20);
+ assert.equal(peeks(), before + 1, 'read again on focus');
+ assert.equal(document.querySelector('[data-save-first]'), null, 'the card goes');
+ assert.ok(document.querySelector('[data-github-token]'), 'the token field is there');
+ assert.match(document.querySelector('[data-save-ready]').textContent, /Bitwarden/);
+ root.unmount();
+});
+
+test('C6 DOM: approvals turned back on in another tab unblocks it when this tab is visible again; hidden does nothing', async () => {
+ reset();
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: noop, onCancel: noop }));
+ await frame();
+ const peeks = () => server.calls.filter(([, p]) => p === '/api/passwords/store').length;
+ const before = peeks();
+ Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });
+ document.dispatchEvent(new window.Event('visibilitychange'));
+ await settle();
+ assert.equal(peeks(), before, 'not while hidden');
+ server.store = { ...STORE_OFF, approvals_off: false };
+ Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
+ document.dispatchEvent(new window.Event('visibilitychange'));
+ await settle(20);
+ assert.equal(peeks(), before + 1);
+ assert.equal(document.querySelector('[data-save-first]'), null);
+ assert.equal(document.querySelector('[data-save-ready]').textContent, m.SAVE_FIRST.asked);
+ root.unmount();
+});
+
+test('C6 DOM: still blocked after the re-check keeps the card; once open, focus reads nothing', async () => {
+ reset();
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: noop, onCancel: noop }));
+ await frame();
+ window.dispatchEvent(new window.Event('focus'));
+ await settle(20);
+ assert.ok(document.querySelector('[data-save-first]'), 'nothing changed, the card stays');
+ await click(document.querySelector('[data-save-first-save]'));
+ const n = server.calls.length;
+ window.dispatchEvent(new window.Event('focus'));
+ await settle(20);
+ assert.equal(server.calls.length, n, 'the form is open: no more reads');
+ root.unmount();
+});
+
+test('C6 DOM: Loose ends’ own add form re-checks too (it is the same form)', async () => {
+ reset();
+ const { root } = await mount(h(m.LooseSources, { sources: [], error: null, onChanged: noop, initialAdding: true, initialKind: 'github', onAdded: noop, settled: true }));
+ await frame();
+ assert.ok(document.querySelector('[data-save-first]'));
+ server.store = { ...STORE_OFF, approvals_off: false };
+ window.dispatchEvent(new window.Event('focus'));
+ await settle(20);
+ assert.equal(document.querySelector('[data-save-first]'), null);
+ root.unmount();
+});
+
+// ---------------------------------------------------------------- B1: one form, in place
+
+test('B1: the popover sits under its button, above it when there is no room, inside the window', () => {
+ assert.deepEqual(m.popoverPlace({ top: 100, bottom: 130, left: 200, right: 300 }, 1280, 800, 300), { left: 200, top: 138, width: 380 });
+ assert.deepEqual(m.popoverPlace({ top: 700, bottom: 730, left: 1200, right: 1260 }, 1280, 800, 300), { left: 888, top: 392, width: 380 });
+ assert.equal(m.popoverPlace(null, 1280, 800, 300).left, 450, 'no button: centred');
+});
+
+test('B1 DOM: on the desktop Connect GitHub opens the shared form as a popover by its button; Escape closes it and focus goes back', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false } });
+ const { root } = await mount(h('div', null, h('button', { id: 'anchor' }, 'Connect GitHub'), h(m.GitHubConnectHost, {})));
+ const anchor = document.getElementById('anchor');
+ anchor.focus();
+ m.openGitHubConnect({ space: 'spc_demo', anchor });
+ await settle(20);
+ await frame();
+ const pop = document.querySelector('[data-github-connect-popover]');
+ assert.ok(pop, 'a popover');
+ assert.equal(document.querySelector('[data-github-connect-sheet]'), null);
+ assert.equal(pop.getAttribute('role'), 'dialog');
+ assert.ok(pop.querySelector('form[data-github-connect]'), 'the shared form is inside');
+ assert.equal(window.location.pathname, '/s/spc_demo', 'no jump to Loose ends');
+ document.activeElement.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle(20);
+ await frame();
+ assert.equal(document.querySelector('[data-github-connect-popover]'), null, 'Escape closes it');
+ assert.equal(document.activeElement, anchor, 'focus is back on the button');
+ root.unmount();
+});
+
+test('B1 DOM: on a phone it is a sheet; adding the login closes it, reads Dev mode again and says so', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false } });
+ phone = true;
+ const connected = [];
+ const heard = [];
+ const on = (e) => heard.push(e.detail.space);
+ window.addEventListener(m.GITHUB_CONNECTED_EVENT, on);
+ const { root } = await mount(h(m.GitHubConnectHost, { onConnected: (space) => connected.push(space) }));
+ m.openGitHubConnect({ space: 'spc_demo' });
+ await settle(20);
+ await frame();
+ const sheet = document.querySelector('[data-github-connect-sheet]');
+ assert.ok(sheet, 'a sheet');
+ assert.equal(document.querySelector('[data-github-connect-popover]'), null);
+ assert.equal(sheet.querySelector('[role="dialog"]').getAttribute('aria-modal'), 'true');
+ document.querySelector('[data-github-token]').value = 'demo-not-a-token';
+ document.querySelector('form[data-github-connect]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle(30);
+ assert.equal(document.querySelector('[data-github-connect-sheet]'), null, 'closed once added');
+ assert.deepEqual(connected, ['spc_demo']);
+ assert.deepEqual(heard, ['spc_demo']);
+ assert.ok(server.calls.some(([meth, p]) => meth === 'GET' && p === '/api/spaces/spc_demo/dev_mode'), 'Dev mode reads the new login');
+ window.removeEventListener(m.GITHUB_CONNECTED_EVENT, on);
+ root.unmount();
+});
+
+test('B1: every Connect GitHub goes through the shared form, and none opens Loose ends', () => {
+ const src = (f) => readFileSync(new URL(`../src/${f}`, import.meta.url), 'utf8');
+ for (const f of ['components/DevStatusLine.tsx', 'components/DevDesk.tsx', 'components/DevModeSetup.tsx', 'components/TeamRepoDevLine.tsx', 'App.tsx']) assert.match(src(f), /openGitHubConnect/, f);
+ assert.doesNotMatch(src('App.tsx'), /devConnect\(/);
+ assert.match(src('App.tsx'), /<GitHubConnectHost/);
+});
+
+test('B1: the Loose ends GitHub row says it is also used by Dev mode', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false } });
+ const src = { id: 'src_demo', kind: 'github', label: 'GitHub', enabled: true, config: {}, last_error: null, last_run_at: null };
+ const { root } = await mount(h(m.LooseSources, { sources: [src], error: null, onChanged: noop, onAdded: noop, settled: true }));
+ assert.equal(m.GITHUB_ALSO_DEV, 'Also used by Dev mode');
+ assert.match(document.querySelector('[data-github-also-dev]')?.textContent ?? '', /Also used by Dev mode/);
+ root.unmount();
+});
+
+// ---------------------------------------------------------------- B2 / B3: Team settings
+
+const dev = (over) => m.parseDevMode({ on: true, forge: 'github', forge_login: 'demo', status: 'watching', repos: [], ...over });
+const repo = (o) => ({ key: 'github.com/demo-org/demo-web', repo: 'demo-org/demo-web', host: 'github.com', team: 'Web', team_id: 'team_web', from: 'repo', provider: 'github', branch: 'main', status: 'watching', ...o });
+
+test('B2: each of the four lines, matched by team first, then by repo', () => {
+ const url = 'https://github.com/demo-org/demo-web.git';
+ assert.equal(m.repoKeyOf(url), 'github.com/demo-org/demo-web');
+ assert.equal(m.repoKeyOf('[email protected]:demo/app.git'), 'git.example.test/demo/app');
+ assert.equal(m.repoKeyOf(''), null);
+ assert.equal(m.teamRepoLine(dev({ repos: [repo()] }), url, 'team_web'), 'connected');
+ assert.equal(m.teamRepoLine(dev({ repos: [repo({ status: 'error' })] }), url, 'team_web'), 'connected');
+ assert.equal(m.teamRepoLine(dev({ repos: [repo({ status: 'not_connected' })] }), url, 'team_web'), 'connect');
+ assert.equal(m.teamRepoLine(dev({ forge: null, repos: [repo()] }), url, 'team_web'), 'connect');
+ assert.equal(m.teamRepoLine(dev({ on: false, repos: [] }), url, 'team_web'), 'off');
+ assert.equal(m.teamRepoLine(dev({ on: false }), 'https://git.example.test/demo/app.git', null), 'off', 'off for any host');
+ assert.equal(m.teamRepoLine(dev({ repos: [repo({ key: 'git.example.test/demo/app', host: 'git.example.test', provider: 'git' })] }), 'https://git.example.test/demo/app.git', 'team_web'), 'git');
+ assert.equal(m.teamRepoLine(dev({}), 'https://git.example.test/demo/app.git', null), 'git', 'a new team on another host');
+ // A second team on the same repo has no entry of its own: the repo's entry is used.
+ assert.equal(m.teamRepoLine(dev({ repos: [repo()] }), url, 'team_other'), 'connected');
+ // A URL typed over the team's saved repo is read by the new URL, not the old entry.
+ const gitRow = repo({ key: '127.0.0.1/demo-org/demo-app', host: '127.0.0.1', provider: 'git' });
+ assert.equal(m.teamRepoLine(dev({ forge: null, repos: [gitRow] }), 'https://github.com/demo-org/demo-app.git', 'team_web'), 'connect');
+ assert.equal(m.teamRepoLine(dev({ repos: [repo({ key: '127.0.0.1/demo-org/demo-app', host: '127.0.0.1' })] }), 'http://127.0.0.1:9476/demo-org/demo-app', 'team_web'), 'connected', 'a port in the URL still matches');
+ // A new team (no id yet) on GitHub reads on + forge.
+ assert.equal(m.teamRepoLine(dev({}), 'demo-org/new-repo', null), 'connected');
+ assert.equal(m.teamRepoLine(dev({ forge: null }), 'demo-org/new-repo', null), 'connect');
+ assert.equal(m.teamRepoLine(dev({}), '', 'team_web'), null, 'no URL, no line');
+ assert.equal(m.teamRepoLine(null, url, 'team_web'), null, 'unknown yet, no line');
+});
+
+test('B2 DOM: the spec’s copy for each line; Connect GitHub opens the shared form in place', async () => {
+ reset();
+ const url = 'https://github.com/demo-org/demo-web';
+ for (const [state, line, text] of [
+ [dev({ repos: [repo()] }), 'connected', 'Dev mode watches this repo · GitHub connected'],
+ [dev({ repos: [repo({ status: 'not_connected' })], forge: null }), 'connect', 'Dev mode watches this repo. Connect GitHub for reviews.'],
+ [dev({ on: false }), 'off', 'Dev mode can watch this repo: turn it on next to the space name.'],
+ [dev({ repos: [repo({ provider: 'git' })] }), 'git', 'Dev mode reads this repo with git. Reviews need GitHub.'],
+ ]) {
+ m.devStore.set('spc_demo', state);
+ const { root } = await mount(h(m.TeamRepoDevLine, { url, teamId: 'team_web', spaceId: 'spc_demo' }));
+ const p = document.querySelector('[data-team-repo-dev]');
+ assert.equal(p.dataset.teamRepoDev, line);
+ assert.equal(p.textContent, text);
+ assert.equal(m.TEAM_REPO_LINES[line], text);
+ if (line === 'connect') {
+ const got = [];
+ const on = (e) => got.push(e.detail);
+ window.addEventListener(m.GITHUB_CONNECT_EVENT, on);
+ const btn = p.querySelector('[data-team-repo-connect]');
+ await click(btn);
+ window.removeEventListener(m.GITHUB_CONNECT_EVENT, on);
+ assert.equal(got.length, 1);
+ assert.equal(got[0].space, 'spc_demo');
+ assert.equal(got[0].anchor, btn);
+ }
+ root.unmount();
+ document.body.innerHTML = '';
+ }
+});
+
+test('B2/B3: both team modals show the line under Git Repo URL, with the new helper text', () => {
+ for (const f of ['NewTeamModal.tsx', 'ManageTeamModal.tsx']) {
+ const src = readFileSync(new URL(`../src/components/${f}`, import.meta.url), 'utf8');
+ assert.match(src, /<TeamRepoDevLine url=\{repoUrl\}/, f);
+ assert.match(src, /Bots clone it into the team’s folder on first run\.\s*</, f);
+ assert.doesNotMatch(src, /Dev mode watches it too/, f);
+ }
+ assert.match(readFileSync(new URL('../src/components/ManageTeamModal.tsx', import.meta.url), 'utf8'), /<TeamRepoDevLine url=\{repoUrl\} teamId=/);
+});
+
+// ---------------------------------------------------------------- C5: the other cloud
+
+test('C5: the hint names the other Bitwarden cloud; nothing for self-hosted', () => {
+ assert.equal(m.otherCloudHint('https://vault.bitwarden.com'), 'Is your account on bitwarden.eu? Choose it under Server.');
+ assert.equal(m.otherCloudHint('https://vault.bitwarden.eu'), 'Is your account on bitwarden.com? Choose it under Server.');
+ assert.equal(m.otherCloudHint('self'), null);
+ assert.equal(m.otherCloudHint('https://vault.example.test'), null);
+});
+
+test('C5 SSR: shown only in connect mode under a wrong password', () => {
+ const r = (p) => m.renderToStaticMarkup(h(m.BitwardenLoginForm, { mode: 'connect', status: null, onDone: noop, onCancel: noop, ...p }));
+ assert.match(r({ initialProblem: { kind: 'wrong-password' } }), /data-bw-other-cloud[^>]*>Is your account on bitwarden\.eu\? Choose it under Server\./);
+ assert.match(r({ initialProblem: { kind: 'wrong-password' }, initialServer: 'https://vault.bitwarden.eu' }), /Is your account on bitwarden\.com\?/);
+ assert.doesNotMatch(r({ initialProblem: { kind: 'wrong-password' }, initialServer: 'self' }), /data-bw-other-cloud/);
+ assert.doesNotMatch(r({}), /data-bw-other-cloud/, 'no problem, no hint');
+ assert.doesNotMatch(r({ initialProblem: { kind: 'new-device-code' } }), /data-bw-other-cloud/);
+ const unlock = m.renderToStaticMarkup(
+ h(m.BitwardenLoginForm, { mode: 'unlock', status: m.parseStoreStatus({ store: 'bitwarden', locked: true, bitwarden: { server_url: 'https://vault.bitwarden.com', email: '[email protected]', login: 'password', unlocked: false } }), onDone: noop, onCancel: noop, initialProblem: { kind: 'wrong-password' } }),
+ );
+ assert.doesNotMatch(unlock, /data-bw-other-cloud/, 'unlock: the account is known already');
+});
+
+test('C5 DOM: a wrong password on bitwarden.eu names bitwarden.com, for the server it was tried on', async () => {
+ reset();
+ const { root } = await mount(h(m.BitwardenLoginForm, { mode: 'connect', status: null, onDone: noop, onCancel: noop }));
+ const form = document.querySelector('[data-bitwarden-form="connect"]');
+ typeIn(form.querySelector('select'), 'https://vault.bitwarden.eu');
+ typeIn(form.querySelector('input[type="email"]'), '[email protected]');
+ await settle();
+ const pw = [...form.querySelectorAll('input[type="password"]')].pop();
+ pw.value = 'demo-not-a-password';
+ [...form.querySelectorAll('button')].find((b) => b.textContent === 'Connect').click();
+ await settle(20);
+ const unlock = server.calls.find(([, p]) => p === '/api/passwords/bitwarden/unlock');
+ assert.equal(unlock[2].server_url, 'https://vault.bitwarden.eu');
+ assert.equal(document.querySelector('[data-bw-other-cloud]')?.textContent, 'Is your account on bitwarden.com? Choose it under Server.');
+ // Switching the picker afterwards doesn't change what was tried.
+ typeIn(form.querySelector('select'), 'https://vault.bitwarden.com');
+ await settle();
+ assert.equal(document.querySelector('[data-bw-other-cloud]')?.textContent, 'Is your account on bitwarden.com? Choose it under Server.');
+ root.unmount();
+});
+
+// ---------------------------------------------------------------- F1: no form inside a form
+
+const nested = () => [...document.querySelectorAll('form')].filter((f) => f.parentElement?.closest('form'));
+const unlocks = () => server.calls.filter(([meth, p]) => meth === 'POST' && p === '/api/passwords/bitwarden/unlock');
+const fillBitwarden = async (bw) => {
+ typeIn(bw.querySelector('input[type="email"]'), '[email protected]');
+ await settle();
+ [...bw.querySelectorAll('input[type="password"]')].pop().value = 'demo-not-a-password';
+};
+
+test('F1: the Bitwarden login form is never a <form>, so it can sit inside one', () => {
+ for (const mode of ['connect', 'unlock']) {
+ const html = m.renderToStaticMarkup(h(m.BitwardenLoginForm, { mode, status: null, onDone: noop, onCancel: noop }));
+ assert.doesNotMatch(html, /<form/, mode);
+ assert.match(html, /role="group"/);
+ assert.doesNotMatch(html, /type="submit"/, `${mode}: no submit button to reach an outer form`);
+ }
+});
+
+test('F1 DOM: GitHub > Use Bitwarden: no nested form; Connect and Enter each send exactly one unlock and never submit the GitHub form', async () => {
+ reset();
+ const submits = [];
+ const onSubmit = (e) => submits.push(e.target.getAttribute('data-add-source') ?? e.target.tagName);
+ document.addEventListener('submit', onSubmit, true);
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: noop, onCancel: noop, land: true, scroll: false }));
+ await frame();
+ await click(document.querySelector('[data-save-first-bitwarden]'));
+ const bw = document.querySelector('[data-bitwarden-form="connect"]');
+ assert.ok(bw.closest('form[data-github-connect]'), 'shown inside the GitHub form');
+ assert.equal(bw.tagName, 'DIV');
+ assert.deepEqual(nested(), []);
+ await fillBitwarden(bw);
+ [...bw.querySelectorAll('button')].find((b) => b.textContent === 'Connect').click();
+ await settle(20);
+ assert.equal(unlocks().length, 1, 'Connect: one unlock');
+ // Enter in the master password field: one more unlock, and the key never reaches the GitHub form.
+ const pw = [...bw.querySelectorAll('input[type="password"]')].pop();
+ pw.value = 'demo-not-a-password';
+ const enter = new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true });
+ pw.dispatchEvent(enter);
+ await settle(20);
+ assert.equal(enter.defaultPrevented, true, 'no implicit submit of the outer form');
+ assert.equal(unlocks().length, 2, 'Enter: one more unlock');
+ // Enter in the Server picker does nothing.
+ bw.querySelector('select').dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }));
+ await settle(20);
+ assert.equal(unlocks().length, 2);
+ assert.deepEqual(submits, [], 'no form was submitted');
+ assert.deepEqual(posts(), [], 'nothing saved to Loose ends');
+ document.removeEventListener('submit', onSubmit, true);
+ root.unmount();
+});
+
+test('F1 DOM: GitHub > 409 > Move to Bitwarden (NeedsBitwarden in the GitHub form): no nested form', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false }, refuse: true });
+ const { root } = await mount(h(m.GitHubConnectForm, { onAdded: noop, onCancel: noop, land: true, scroll: false }));
+ await frame();
+ document.querySelector('[data-github-connect] input[type="password"]').value = 'demo-token-not-real';
+ document.querySelector('[data-github-connect]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle(20);
+ await click([...document.querySelectorAll('[data-needs-bitwarden] button')].find((b) => b.textContent === 'Move to Bitwarden'));
+ assert.ok(document.querySelector('[data-github-connect] [data-bitwarden-form]'));
+ assert.deepEqual(nested(), []);
+ root.unmount();
+});
+
+test('F1 DOM: IMAP > 409 > Move to Bitwarden: no nested form, and Connect sends one unlock without submitting the IMAP form', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false }, refuse: true });
+ const submits = [];
+ const onSubmit = () => submits.push(1);
+ const { root } = await mount(h(m.AddSourceForm, { onAdded: noop, onCancel: noop }));
+ const form = document.querySelector('form[data-add-source="imap"]');
+ const inputs = [...form.querySelectorAll('input')];
+ typeIn(inputs.find((i) => i.placeholder === 'imap.gmail.com'), 'imap.example.test');
+ typeIn(inputs.find((i) => i.placeholder === '[email protected]'), '[email protected]');
+ form.querySelector('input[type="password"]').value = 'demo-not-a-password';
+ await settle();
+ form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle(20);
+ await click([...form.querySelectorAll('[data-needs-bitwarden] button')].find((b) => b.textContent === 'Move to Bitwarden'));
+ const bw = form.querySelector('[data-bitwarden-form="connect"]');
+ assert.ok(bw);
+ assert.deepEqual(nested(), []);
+ document.addEventListener('submit', onSubmit, true);
+ await fillBitwarden(bw);
+ [...bw.querySelectorAll('button')].find((b) => b.textContent === 'Connect').click();
+ await settle(20);
+ assert.equal(unlocks().length, 1);
+ assert.deepEqual(submits, []);
+ document.removeEventListener('submit', onSubmit, true);
+ root.unmount();
+});
+
+test('F1 DOM: Move to Bitwarden first (the approvals confirm) has no form in a form', async () => {
+ reset();
+ const status = m.parseStoreStatus({ ...STORE_OFF, local_count: 3 });
+ const { root } = await mount(h('form', null, h(m.MoveToBitwardenFirst, { store: { status, problem: null, reload: noop, set: noop }, label: 'Move them to Bitwarden first', initialStep: 'connect' })));
+ assert.ok(document.querySelector('[data-move-first] [data-bitwarden-form="connect"]'));
+ assert.deepEqual(nested(), []);
+ root.unmount();
+});
+
+// ---------------------------------------------------------------- F2: restoring an archived space
+
+test('F2 DOM: restore 409 → the one-time choice (A3 copy) → Save it on this server restores with accept_risk', async () => {
+ reset({ store: { ...STORE_OFF, local_count: 2 } });
+ const restored = [];
+ const { root } = await mount(h(m.ArchivedSpacesModal, { onClose: noop, onRestored: (s) => restored.push(s) }));
+ await settle(20);
+ await click([...document.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Restore'));
+ await settle(20);
+ const card = document.querySelector('[data-restore-accept-risk]');
+ assert.ok(card, 'the choice, not the raw 409 sentence');
+ assert.equal(document.querySelector('[role="alert"]'), null, 'no error line');
+ assert.match(card.textContent, new RegExp(m.acceptRiskText(2).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
+ assert.equal(card.querySelector('[data-restore-save]').textContent, 'Save it on this server');
+ assert.ok([...card.querySelectorAll('button')].some((b) => b.textContent.includes('Use Bitwarden')), 'Use Bitwarden');
+ assert.equal(restored.length, 0);
+ await click(card.querySelector('[data-restore-save]'));
+ await settle(20);
+ const patches = server.calls.filter(([meth, p]) => meth === 'PATCH' && p === '/api/spaces/spc_old').map(([, , b]) => b);
+ assert.deepEqual(patches, [{ archived: false }, { archived: false, accept_risk: true }]);
+ assert.equal(restored.length, 1);
+ assert.equal(document.querySelector('[data-restore-accept-risk]'), null);
+ root.unmount();
+});
+
+// ---------------------------------------------------------------- N4
+
+test('N4 DOM: choosing GitHub in Add a source focuses its first control', async () => {
+ reset({ store: { ...STORE_OFF, approvals_off: false } });
+ const { root } = await mount(h(m.AddSourceForm, { onAdded: noop, onCancel: noop }));
+ await click([...document.querySelectorAll('button')].find((b) => b.textContent.trim() === 'GitHub'));
+ await frame();
+ await settle(20);
+ assert.equal(document.activeElement?.getAttribute('type'), 'password', 'the token field');
+ assert.ok(document.activeElement.closest('[data-github-connect]'));
+ root.unmount();
+});