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.

Floor card is never a dead end: set a backup command inline, allow a guessed deploy without a backup (22f part 2) (#698)

Oleksandr Ivanchenkodbcf13034d2c
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 649b4c11..75f6030e 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -186,6 +186,7 @@ import { ModernAvatar } from './components/ModernAvatar';
import { PREPUSH_EVENT, messageNotSent as prepushMessageNotSent, needsYou as prepushNeedsYou, overrideMessage, prepushApi, retryMessage, type PrepushCard as PrepushCardData } from './dev/prepush';
import { StepReview } from './components/ShowOnce';
import { inDesktopApp, leaveForSignIn, mcpSignIn, pollUntil, signInChanged } from './externalLinks';
+import type { FloorResolveOpts } from './dev/types';
// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),
// so both load right after start-up and opening them never waits.
@@ -2050,21 +2051,26 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const handleResolveApproval = async (
ticketId: string,
- decision: 'allow_once' | 'always_allow' | 'deny'
+ decision: 'allow_once' | 'always_allow' | 'deny',
+ opts?: FloorResolveOpts
) => {
haptic('tap');
try {
const res = await fetch(`/api/approvals/${ticketId}/resolve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ decision }),
+ // 22f: the person's own "Allow without a backup" on a deploy kwant only guessed changes the database.
+ body: JSON.stringify(opts?.withoutBackup && decision === 'allow_once' ? { decision, without_backup: true } : { decision }),
});
// Production floor (Dev mode): Allow without a fresh backup is refused and the card stays waiting.
if (res.status === 409) {
const body = await res.clone().json().catch(() => null);
if (body && typeof body === 'object' && (body as { status?: unknown }).status === 'needs_backup') {
haptic('warning');
- pushToast('Back up first', 'This step needs a backup from the last 10 minutes. Take one on the card, then Allow.');
+ const b = body as { code?: unknown; error?: unknown };
+ // 22f: `without_backup` refused (a destructive step, a known database change, or a card from before 22f).
+ if (b.code === 'backup_required' && typeof b.error === 'string' && b.error) pushToast('Needs a fresh backup', b.error);
+ else pushToast('Needs a fresh backup', 'This step needs a backup from the last 10 minutes. Take one on the card, then Allow.');
return;
}
}
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index fd2af8fa..f98445ab 100644
--- a/frontend/src/away.ts
+++ b/frontend/src/away.ts
@@ -229,11 +229,43 @@ export function actionFailureNotice(status: number, serverMessage: string, title
}
export class AwayError extends Error {
- constructor(public status: number, message: string) {
+ constructor(public status: number, message: string, public body: unknown = null) {
super(message);
}
}
+/**
+ * 22f: a production-floor refusal (409 with `status: "needs_backup"`, any `code`). The card is still waiting on the
+ * server for a fresh backup, so it has not lapsed and must stay in the chat.
+ */
+export const isBackupRefusal = (err: unknown): err is AwayError =>
+ err instanceof AwayError && err.status === 409 && !!err.body && typeof err.body === 'object' && (err.body as { status?: unknown }).status === 'needs_backup';
+
+/** The notice for any failed one-tap action, given what was thrown. */
+export function failureNotice(err: unknown, title: string): AwayNotice {
+ if (isBackupRefusal(err)) {
+ const why = err.message && !/^Request failed \(HTTP/.test(err.message) ? err.message : 'This step needs a backup from the last 10 minutes. Take one on the card, then Allow.';
+ return { text: `${why} (“${title}”)`, error: true };
+ }
+ const status = err instanceof AwayError ? err.status : 0;
+ return actionFailureNotice(status, err instanceof Error ? err.message : 'Something went wrong.', title);
+}
+
+/**
+ * Resolve an approval from Away or the Inbox. The chat's copy of the card is dropped when it was answered or has
+ * lapsed (409/404), but not on a backup refusal: that card is still waiting.
+ */
+export async function resolveFromList<T>(id: string, onResolved: ((id: string) => void) | undefined, run: () => Promise<T>): Promise<T> {
+ try {
+ const r = await run();
+ onResolved?.(id);
+ return r;
+ } catch (err) {
+ if (err instanceof AwayError && (err.status === 409 || err.status === 404) && !isBackupRefusal(err)) onResolved?.(id);
+ throw err;
+ }
+}
+
async function call<T>(method: string, url: string, body?: unknown): Promise<T> {
const res = await fetch(url, {
method,
@@ -242,13 +274,15 @@ async function call<T>(method: string, url: string, body?: unknown): Promise<T>
});
if (!res.ok) {
let message = `Request failed (HTTP ${res.status}).`;
+ let data: unknown = null;
try {
- const data = await res.json();
- if (data && typeof data.error === 'string' && data.error) message = data.error;
+ data = await res.json();
+ const e = data && typeof data === 'object' ? (data as { error?: unknown }).error : undefined;
+ if (typeof e === 'string' && e) message = e;
} catch {
// no JSON body
}
- throw new AwayError(res.status, message);
+ throw new AwayError(res.status, message, data);
}
return res.json();
}
@@ -259,7 +293,8 @@ export const awayApi = {
get: (since?: string) => call<AwayResponse>('GET', `/api/away${since ? `?since=${enc(since)}` : ''}`).then(normalizeAway),
seen: () => call<{ last_seen: string }>('POST', '/api/away/seen'),
answer: (id: string, choice: number) => call<unknown>('POST', `/api/questions/${enc(id)}/answer`, { choice }),
- resolve: (id: string, decision: ApprovalDecision) => call<unknown>('POST', `/api/approvals/${enc(id)}/resolve`, { decision }),
+ resolve: (id: string, decision: ApprovalDecision, withoutBackup = false) =>
+ call<unknown>('POST', `/api/approvals/${enc(id)}/resolve`, withoutBackup && decision === 'allow_once' ? { decision, without_backup: true } : { decision }),
/** Approval records with this stored status, newest first (`answered_via` says where). */
approvals: (status: string) => call<unknown>('GET', `/api/approvals?status=${enc(status)}`),
/** 0.9.5: ask again for an approval that expired unanswered (starts a new turn; grants nothing). */
diff --git a/frontend/src/components/AwayView.tsx b/frontend/src/components/AwayView.tsx
index 35ae202c..7872609f 100644
--- a/frontend/src/components/AwayView.tsx
+++ b/frontend/src/components/AwayView.tsx
@@ -8,13 +8,13 @@ import {
AWAY_SORT_HINT,
sortAwaySection,
ApprovalDecision,
- AwayError,
AwayItem,
AwayResponse,
AwayNotice,
AwaySection,
Tone,
- actionFailureNotice,
+ failureNotice,
+ resolveFromList,
awaySummary,
awayApi,
isAwayEmpty,
@@ -52,7 +52,7 @@ export interface AwayViewProps {
onBack?: () => void;
onOpen: (item: AwayItem) => void;
onAnswer: (item: AwayItem, choice: number) => void;
- onResolve: (item: AwayItem, decision: ApprovalDecision) => void;
+ onResolve: (item: AwayItem, decision: ApprovalDecision, withoutBackup?: boolean) => void;
/** Above the lists: what holds every bot (today's spending stop), not one bot's item. */
top?: React.ReactNode;
}
@@ -115,7 +115,7 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice
{item.kind === 'approval' && (
<div className="px-3 pb-1 sm:pl-[54px] [&>div]:my-0 [&>div]:mb-2">
- <ModernApprovalCard approval={approvalFromAway(item)} disabled={disabled} onResolve={(_, decision) => onResolve(item, decision)} />
+ <ModernApprovalCard approval={approvalFromAway(item)} disabled={disabled} onResolve={(_, decision, opts) => onResolve(item, decision as ApprovalDecision, opts?.withoutBackup)} />
</div>
)}
@@ -305,8 +305,7 @@ export const AwayPage: React.FC<AwayPageProps> = ({ since = null, onSince, onOpe
const done = denied ? 'Denied, nothing ran:' : late ?? `Sent to ${item.kwant_name}:`;
setNotice({ text: `${done} “${awayTitle(item)}”`, error: false });
} catch (err) {
- const status = err instanceof AwayError ? err.status : 0;
- setNotice(actionFailureNotice(status, err instanceof Error ? err.message : 'Something went wrong.', awayTitle(item)));
+ setNotice(failureNotice(err, awayTitle(item)));
} finally {
setBusy(null);
}
@@ -326,18 +325,9 @@ export const AwayPage: React.FC<AwayPageProps> = ({ since = null, onSince, onOpe
top={top}
onOpen={onOpen}
onAnswer={(item, choice) => act(item, () => awayApi.answer(item.id, choice))}
- onResolve={(item, decision) =>
- act(item, async () => {
- try {
- const res = await awayApi.resolve(item.id, decision);
- onApprovalResolved?.(item.id);
- return res;
- } catch (err) {
- // Lapsed meanwhile: the chat's card is stale too.
- if (err instanceof AwayError && (err.status === 409 || err.status === 404)) onApprovalResolved?.(item.id);
- throw err;
- }
- }, decision === 'deny')
+ onResolve={(item, decision, withoutBackup) =>
+ // Lapsed meanwhile: the chat's card is stale too (but not on a backup refusal: it is still waiting).
+ act(item, () => resolveFromList(item.id, onApprovalResolved, () => awayApi.resolve(item.id, decision, withoutBackup)), decision === 'deny')
}
/>
);
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 6e008b68..f3c620cd 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -116,6 +116,7 @@ import { FilesPreviewOnly } from './results/Files';
import { ReactionButtons, ReplyButton, ReplyChip, ReplyQuote } from './MessageReactions';
import { DictationAnnouncer, DictationLine, DictationSetupPopover, MicButton, useDictation } from './DictationMic';
import { ReactResult, Reaction, ReplyRef, botNameOf, excerptOf, questionMessageId, reactionOf, replyRefOf } from '../reactReply';
+import type { FloorResolveOpts } from '../dev/types';
export interface ChatMessage {
id: string;
@@ -249,7 +250,7 @@ export interface ChatViewProps {
onSendMessage: (text: string, attachments: AttachmentRef[], opts?: SendOptions) => void | Promise<boolean | string | void>;
/** Saves the person's thumbs on a bot reply; absent hides the thumbs. */
onReact?: (msg: ChatMessage, reaction: Reaction | null) => Promise<ReactResult> | void;
- onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
+ onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny', opts?: FloorResolveOpts) => void;
kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string; preferred_model?: string }>;
teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
/** Prompts offered above an empty chat, made from who is in it; none hides the bar. */
diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsx
index 44c2f671..b07480e3 100644
--- a/frontend/src/components/InboxNew.tsx
+++ b/frontend/src/components/InboxNew.tsx
@@ -32,7 +32,7 @@ import { knownChecked, listsCriteria } from '../doneCheck';
import { CheckMarker, DoneCheck } from './DoneCheck';
import { usePhoneLayout } from '../usePhoneLayout';
import { approvalFromAway, awayTitle, lateAnswerText } from '../approvals';
-import { ApprovalDecision, AwayError, AwayItem, actionFailureNotice, awayApi, awaySummary, itemLabel, stoppedAction, windowLabel } from '../away';
+import { ApprovalDecision, AwayItem, awayApi, failureNotice, resolveFromList, awaySummary, itemLabel, stoppedAction, windowLabel } from '../away';
import { InboxGroup, InboxItem, ReviewItem, isBeingChecked, isReview, pendingHeld, reviewWord } from '../api/inbox';
import {
BatchRow,
@@ -212,7 +212,7 @@ interface RowProps {
busy: string | null;
onPick: (i: InboxItem) => void;
onAnswer: (i: InboxItem, choice: number) => void;
- onResolve: (i: InboxItem, d: ApprovalDecision) => void;
+ onResolve: (i: InboxItem, d: ApprovalDecision, withoutBackup?: boolean) => void;
/** 0.9.5: Retry on a stopped item whose approval expired unanswered. */
onRetry?: (i: InboxItem, approvalId: string) => void;
/** A routine's review task in Done: its run's first line, as the run's own row would show it. */
@@ -354,7 +354,7 @@ const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, o
{item.kind === 'approval' && (
<div className="px-3 pb-1 pl-[54px] [&>div]:my-0 [&>div]:mb-2">
- <ModernApprovalCard approval={approvalFromAway(item as AwayItem)} disabled={disabled} onResolve={(_, d) => onResolve(item, d)} />
+ <ModernApprovalCard approval={approvalFromAway(item as AwayItem)} disabled={disabled} onResolve={(_, d, opts) => onResolve(item, d as ApprovalDecision, opts?.withoutBackup)} />
</div>
)}
@@ -813,8 +813,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({
const done = denied ? 'Denied, nothing ran:' : late ?? `Sent to ${item.kwant_name}:`;
inboxStore.patch({ busy: null, notice: { text: `${done} “${title}”`, tone: 'ok' } });
} catch (err) {
- const status = err instanceof AwayError ? err.status : 0;
- const n = actionFailureNotice(status, err instanceof Error ? err.message : 'Something went wrong.', title);
+ const n = failureNotice(err, title);
inboxStore.patch({ busy: null, notice: { text: n.text, tone: n.error ? 'error' : 'info' } });
}
const next = await loadInbox();
@@ -823,19 +822,10 @@ export const InboxNew: React.FC<InboxNewProps> = ({
const onAnswer = (item: InboxItem, choice: number) => act(item, () => awayApi.answer(item.id, choice));
const onRetry = (item: InboxItem, approvalId: string) => act(item, () => awayApi.retryApproval(approvalId));
- const onResolve = (item: InboxItem, decision: ApprovalDecision) =>
+ const onResolve = (item: InboxItem, decision: ApprovalDecision, withoutBackup?: boolean) =>
act(
item,
- async () => {
- try {
- const r = await awayApi.resolve(item.id, decision);
- onApprovalResolved?.(item.id);
- return r;
- } catch (err) {
- if (err instanceof AwayError && (err.status === 409 || err.status === 404)) onApprovalResolved?.(item.id);
- throw err;
- }
- },
+ () => resolveFromList(item.id, onApprovalResolved, () => awayApi.resolve(item.id, decision, withoutBackup)),
decision === 'deny',
);
diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsx
index afeb001e..feb71194 100644
--- a/frontend/src/components/ModernApprovalCard.tsx
+++ b/frontend/src/components/ModernApprovalCard.tsx
@@ -6,7 +6,7 @@ import { tierReason } from '../flightSchool';
import { toolAction } from '../toolLabel';
import { localClock } from '../clock';
import { isPhoneLayout } from '../layout';
-import { parseProdFloor, type BackupResult } from '../dev/types';
+import { parseProdFloor, type BackupResult, type FloorBackup, type FloorResolveOpts } from '../dev/types';
import { ProdFloorCard } from './dev/ProdFloorCard';
export interface PendingApproval {
@@ -24,13 +24,17 @@ export interface PendingApproval {
interface ModernApprovalCardProps {
approval: PendingApproval;
- onResolve: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
+ /** `opts` only from the production-floor card: Allow without a backup (22f). */
+ onResolve: (id: string, decision: 'allow_once' | 'always_allow' | 'deny', opts?: FloorResolveOpts) => void;
/** While an answer is being sent. */
disabled?: boolean;
/** Forces the phone or desktop look (tests); by default it follows the window when the card appears. */
phone?: boolean;
/** Production floor (Dev mode): takes a backup; defaults to the space's backup route. */
onBackup?: (spaceId: string) => Promise<BackupResult>;
+ /** Floor card only (22f): saves the backup command / re-reads the backup state; tests and the rig fake them. */
+ onSetCommand?: (spaceId: string, command: string) => Promise<void>;
+ onLoadBackup?: (spaceId: string) => Promise<FloorBackup | null>;
}
/** Server/tool/arguments of an MCP approval, or null for other tools. */
@@ -231,6 +235,8 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
disabled = false,
phone,
onBackup,
+ onSetCommand,
+ onLoadBackup,
}) => {
// Dev mode's production floor has its own card: blast radius, backup row, and never "always allow".
const floor = parseProdFloor(approval.details);
@@ -246,10 +252,12 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
cwd={shellCmd?.cwd ?? null}
disabled={disabled}
onBackup={onBackup}
- onResolve={(id, decision) => {
+ onSetCommand={onSetCommand}
+ onLoadBackup={onLoadBackup}
+ onResolve={(id, decision, opts) => {
if (disabled) return;
playSfx('click');
- onResolve(id, decision);
+ onResolve(id, decision, opts);
}}
/>
);
diff --git a/frontend/src/components/dev/ProdFloorCard.tsx b/frontend/src/components/dev/ProdFloorCard.tsx
index 441394b6..50b19f1d 100644
--- a/frontend/src/components/dev/ProdFloorCard.tsx
+++ b/frontend/src/components/dev/ProdFloorCard.tsx
@@ -1,8 +1,10 @@
-import React, { useEffect, useReducer, useRef, useState } from 'react';
-import { Database, Folder, Target, X, Check } from 'lucide-react';
-import type { BackupResult, ProdFloor } from '../../dev/types';
-import { parseBackupResult } from '../../dev/types';
+import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react';
+import { Database, Folder, Target, X, Check, Terminal } from 'lucide-react';
+import type { BackupResult, FloorBackup, FloorResolveOpts, ProdFloor } from '../../dev/types';
+import { parseBackupResult, parseBackupState } from '../../dev/types';
import { allowReady, floorLed, floorReducer, floorSentence, floorSubline, floorView, floorWho, initialFloorUi, type RowTone } from '../../dev/logic';
+import { devApi, devStore } from '../../devMode';
+import { personFetch } from '../../auth';
export type FloorDecision = 'allow_once' | 'deny';
@@ -12,10 +14,15 @@ export interface ProdFloorCardProps {
bot: string | null;
command: string;
cwd: string | null;
- onResolve: (id: string, decision: FloorDecision) => void;
+ /** `opts.withoutBackup`: the person confirmed "Allow without a backup" on a deploy kwant only guessed (22f). */
+ onResolve: (id: string, decision: FloorDecision, opts?: FloorResolveOpts) => void;
disabled?: boolean;
/** Takes the backup; defaults to `POST /api/spaces/:space_id/dev/backup`. */
onBackup?: (spaceId: string) => Promise<BackupResult>;
+ /** Saves the space's backup command; defaults to the Dev mode settings' own PUT. */
+ onSetCommand?: (spaceId: string, command: string) => Promise<void>;
+ /** Re-reads the backup state (same shape as the card's `backup`); null when the server can't say. */
+ onLoadBackup?: (spaceId: string) => Promise<FloorBackup | null>;
/** A fixed clock for screenshots and tests; the card ticks on its own otherwise. */
now?: number;
}
@@ -31,6 +38,22 @@ export async function postBackup(spaceId: string): Promise<BackupResult> {
return parseBackupResult(body);
}
+/** The Dev mode settings' PUT, so the settings card sees the new command too; `on` stays as it is. */
+export async function putBackupCommand(spaceId: string, command: string): Promise<void> {
+ const s = await devApi.put(spaceId, { on: devStore.get(spaceId)?.on ?? true, backup_command: command });
+ devStore.set(spaceId, s);
+}
+
+/** Juno's 22f route: the card's current backup state. null on an older server (404) or a shape it doesn't know. */
+export async function getBackupState(spaceId: string): Promise<FloorBackup | null> {
+ const res = await personFetch(`/api/spaces/${encodeURIComponent(spaceId)}/dev/backup`);
+ if (!res.ok) return null;
+ return parseBackupState(await res.json().catch(() => null));
+}
+
+/** The longest backup command the server keeps (`BACKUP_COMMAND_CHARS`). */
+const COMMAND_MAX = 2000;
+
const ROW: Record<RowTone, string> = {
ok: 'border-teal-300/35 bg-teal-300/10 text-zinc-100',
warn: 'border-amber-300/35 bg-amber-300/10 text-zinc-100',
@@ -43,6 +66,8 @@ const LEAD: Record<RowTone, string> = { ok: 'text-ok', warn: 'text-warn', bad: '
const BTN = 'flex items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors min-h-[44px] sm:min-h-0 max-sm:w-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:opacity-50 aria-disabled:cursor-not-allowed';
const AMBER = `${BTN} bg-amber-600 text-white shadow-sm hover:bg-amber-500`;
const PLAIN = `${BTN} bg-zinc-800 text-zinc-300 hover:bg-zinc-700`;
+const QUIET = `${BTN} text-zinc-300 hover:bg-white/[.06] hover:text-zinc-100`;
+const FIELD = 'w-full rounded-lg border border-white/[0.14] bg-zinc-950/60 px-2.5 py-2 font-mono text-[12px] text-zinc-100 placeholder:text-zinc-500 focus:border-sky-400/60 focus:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400 max-sm:text-[16px]';
/** "kwant.jumpin.games · production": the place, then a warn chip for the word "production". */
const BlastValue: React.FC<{ label: string; value: string }> = ({ label, value }) => {
@@ -56,7 +81,19 @@ const BlastValue: React.FC<{ label: string; value: string }> = ({ label, value }
};
/** The production-floor variant of the approval card (design §6). Never offers "always allow". */
-export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, command, cwd, onResolve, disabled = false, onBackup = postBackup, now: fixedNow }) => {
+export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({
+ id,
+ floor,
+ bot,
+ command,
+ cwd,
+ onResolve,
+ disabled = false,
+ onBackup = postBackup,
+ onSetCommand = putBackupCommand,
+ onLoadBackup = getBackupState,
+ now: fixedNow,
+}) => {
const [ui, send] = useReducer(floorReducer, floor, initialFloorUi);
const mountedAt = useRef(fixedNow ?? Date.now()).current;
const [tick, setTick] = useState(() => Date.now());
@@ -75,16 +112,55 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, co
const why = floorSentence(floor.why);
const mainRef = useRef<HTMLButtonElement>(null);
const cardRef = useRef<HTMLDivElement>(null);
+ const cmdRef = useRef<HTMLInputElement>(null);
+ const skipRef = useRef<HTMLInputElement>(null);
+ const skipOpenerRef = useRef<HTMLButtonElement>(null);
+
+ // 22f: the inline backup command (no_command) and the one-step confirm for Allow without a backup.
+ const [cmd, setCmd] = useState<{ open: boolean; value: string; saving: boolean; error: string | null }>({ open: false, value: '', saving: false, error: null });
+ const [skip, setSkip] = useState<{ open: boolean; sure: boolean }>({ open: false, sure: false });
+ /** The command was just saved from this card: the row says so until the backup starts. */
+ const [justSaved, setJustSaved] = useState(false);
+
+ // The server's backup state, re-read on focus and after a backup or a new command, so a backup taken (or a
+ // command set) elsewhere counts without a reload. The server checks freshness again at answer time.
+ const spaceId = floor.space_id;
+ const busyRef = useRef(false);
+ busyRef.current = view.busy || cmd.saving;
+ const refresh = useCallback(async () => {
+ if (!spaceId) return null;
+ try {
+ const b = await onLoadBackup(spaceId);
+ if (b) send({ type: 'live', backup: b, now: Date.now() });
+ return b;
+ } catch {
+ return null;
+ }
+ }, [spaceId, onLoadBackup]);
+ useEffect(() => {
+ if (!spaceId || fixedNow !== undefined) return;
+ const onFocus = () => {
+ if (!busyRef.current && document.visibilityState !== 'hidden') void refresh();
+ };
+ window.addEventListener('focus', onFocus);
+ document.addEventListener('visibilitychange', onFocus);
+ return () => {
+ window.removeEventListener('focus', onFocus);
+ document.removeEventListener('visibilitychange', onFocus);
+ };
+ }, [spaceId, fixedNow, refresh]);
// `fromSecondary`: the secondary "Back up first" unmounts once the backup starts, so focus goes back to the
// main button (which turns into Allow in place) when the backup is done.
const takeBackup = async (fromSecondary = false) => {
if (off || !floor.space_id) return;
send({ type: 'backup_start' });
+ setJustSaved(false);
try {
const result = await onBackup(floor.space_id);
send({ type: 'backup_done', result, now: Date.now() });
setTick(Date.now());
+ void refresh();
} catch (e) {
send({ type: 'backup_error', error: e instanceof Error ? e.message : 'no reason given' });
} finally {
@@ -106,6 +182,61 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, co
onResolve(id, 'allow_once');
};
+ const openCommand = () => {
+ if (off) return;
+ setSkip({ open: false, sure: false });
+ setCmd((c) => ({ ...c, open: true, error: null }));
+ window.setTimeout(() => cmdRef.current?.focus(), 0);
+ };
+ const closeCommand = () => {
+ setCmd((c) => ({ ...c, open: false, error: null }));
+ window.setTimeout(() => mainRef.current?.focus(), 0);
+ };
+ const saveCommand = async (e?: React.FormEvent) => {
+ e?.preventDefault();
+ const value = cmd.value.trim();
+ if (!spaceId || cmd.saving) return;
+ if (!value) {
+ setCmd((c) => ({ ...c, error: 'Type the command that takes the backup.' }));
+ cmdRef.current?.focus();
+ return;
+ }
+ setCmd((c) => ({ ...c, saving: true, error: null }));
+ try {
+ await onSetCommand(spaceId, value);
+ } catch (err) {
+ setCmd((c) => ({ ...c, saving: false, error: err instanceof Error ? err.message : 'Couldn’t save the command.' }));
+ window.setTimeout(() => cmdRef.current?.focus(), 0);
+ return;
+ }
+ const b = await refresh();
+ // An older server can't re-read the state: the command is saved, so there is simply no backup yet.
+ if (!b || b.state === 'no_command') send({ type: 'live', backup: { state: 'none', age_s: null, bytes: null, path: null, error: null }, now: Date.now() });
+ setCmd({ open: false, value: '', saving: false, error: null });
+ setJustSaved(true);
+ // The main button is Back up first now, in the same place: focus goes there.
+ window.setTimeout(() => mainRef.current?.focus(), 0);
+ };
+
+ const openSkip = () => {
+ if (off) return;
+ setCmd((c) => ({ ...c, open: false, error: null }));
+ setSkip({ open: true, sure: false });
+ window.setTimeout(() => skipRef.current?.focus(), 0);
+ };
+ const closeSkip = () => {
+ setSkip({ open: false, sure: false });
+ window.setTimeout(() => (skipOpenerRef.current ?? mainRef.current)?.focus(), 0);
+ };
+ const allowWithoutBackup = () => {
+ if (off || !skip.sure || !view.skip) return;
+ onResolve(id, 'allow_once', { withoutBackup: true });
+ };
+ const showSkip = view.skip && skip.open;
+ const showCmd = view.main === 'set_command' && cmd.open;
+ const cmdId = `floor-${id}-cmd`;
+ const skipId = `floor-${id}-skip`;
+
const main =
view.main === 'allow'
? { label: allowLabel, icon: <Check size={14} aria-hidden="true" />, onClick: allow }
@@ -113,7 +244,9 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, co
? { label: 'Back up first', icon: <Database size={14} aria-hidden="true" />, onClick: () => void takeBackup() }
: view.main === 'retry'
? { label: 'Try the backup again', icon: <Database size={14} aria-hidden="true" />, onClick: () => void takeBackup() }
- : null;
+ : view.main === 'set_command'
+ ? { label: 'Set backup command', icon: <Terminal size={14} aria-hidden="true" />, onClick: openCommand }
+ : null;
return (
<div
@@ -178,7 +311,7 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, co
<span className="dv-led mt-[5px]" data-s={floorLed(view.tone, view.case)} data-backup-led aria-hidden="true" />
<p className="min-w-0 [overflow-wrap:anywhere]">
{view.lead && <span className={`font-semibold ${LEAD[view.tone]}`}>{view.lead}</span>}
- {view.text}
+ {justSaved && view.case === 'blocked' ? ' Command saved. Press Back up first to take one.' : view.text}
{view.file && (
<>
{' · '}
@@ -188,9 +321,92 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, co
</p>
</div>
- <div data-approval-actions className="flex flex-wrap items-center gap-2 max-sm:flex-col max-sm:items-stretch">
- <p className="text-[11px] text-zinc-400 sm:mr-auto">{view.note}</p>
- {main && (
+ {showCmd && (
+ <form data-floor-command onSubmit={(e) => void saveCommand(e)} className="mb-3 rounded-lg border border-white/[0.14] bg-zinc-950/40 p-3">
+ <label htmlFor={cmdId} className="mb-1 block text-xs font-medium text-zinc-200">
+ Backup command
+ </label>
+ <input
+ ref={cmdRef}
+ id={cmdId}
+ value={cmd.value}
+ maxLength={COMMAND_MAX}
+ onChange={(e) => setCmd((c) => ({ ...c, value: e.target.value, error: null }))}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ closeCommand();
+ }
+ }}
+ placeholder="./scripts/backup.sh"
+ spellCheck={false}
+ autoCapitalize="off"
+ autoComplete="off"
+ aria-invalid={cmd.error ? true : undefined}
+ aria-describedby={`${cmdId}-help${cmd.error ? ` ${cmdId}-err` : ''}`}
+ readOnly={cmd.saving}
+ className={FIELD}
+ />
+ <p id={`${cmdId}-help`} className="mt-1 text-[11px] leading-snug text-zinc-400 [overflow-wrap:anywhere]">
+ Runs in the bot’s folder when you press Back up first. It should print the backup file’s path. For example:{' '}
+ <code className="font-mono text-zinc-300">ssh root@server 'pg_dump app &gt; /srv/b.sql &amp;&amp; echo /srv/b.sql'</code>
+ </p>
+ {cmd.error && (
+ <p id={`${cmdId}-err`} role="alert" className="mt-1 text-[11px] text-rose-300 [overflow-wrap:anywhere]">
+ {cmd.error}
+ </p>
+ )}
+ <div className="mt-2 flex flex-wrap justify-end gap-2 max-sm:flex-col-reverse max-sm:items-stretch">
+ <button type="button" onClick={closeCommand} className={QUIET}>
+ Cancel
+ </button>
+ <button type="submit" data-floor-command-save aria-disabled={cmd.saving || undefined} aria-busy={cmd.saving || undefined} className={AMBER}>
+ <Check size={14} aria-hidden="true" />
+ {cmd.saving ? 'Saving…' : 'Save command'}
+ </button>
+ </div>
+ </form>
+ )}
+
+ {showSkip && (
+ <div data-floor-skip role="group" aria-labelledby={`${skipId}-h`} className="mb-3 rounded-lg border border-amber-300/35 bg-amber-300/[.07] p-3">
+ <p id={`${skipId}-h`} className="text-xs font-semibold text-zinc-100">
+ Allow without a backup?
+ </p>
+ <p className="mt-0.5 text-[11px] leading-snug text-zinc-300">If this deploy does change the database, there will be no copy to go back to.</p>
+ <label htmlFor={skipId} className="mt-2 flex min-h-[44px] cursor-pointer items-center gap-2 text-xs text-zinc-100 sm:min-h-0">
+ <input
+ ref={skipRef}
+ id={skipId}
+ type="checkbox"
+ checked={skip.sure}
+ onChange={(e) => setSkip((k) => ({ ...k, sure: e.target.checked }))}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ closeSkip();
+ }
+ }}
+ className="h-4 w-4 shrink-0 accent-amber-500"
+ />
+ This deploy doesn’t change the database
+ </label>
+ <div className="mt-2 flex flex-wrap justify-end gap-2 max-sm:flex-col-reverse max-sm:items-stretch">
+ <button type="button" onClick={closeSkip} className={QUIET}>
+ Cancel
+ </button>
+ <button type="button" data-floor-skip-allow aria-disabled={!skip.sure || off || undefined} onClick={allowWithoutBackup} className={`${AMBER} aria-disabled:hover:bg-amber-600`}>
+ <Check size={14} aria-hidden="true" />
+ Allow without a backup
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* With Allow without a backup there are three buttons: the note gets its own line so Deny never wraps alone. */}
+ <div data-approval-actions className={`flex flex-wrap items-center gap-2 max-sm:flex-col max-sm:items-stretch ${view.skip ? 'justify-end' : ''}`}>
+ {!showSkip && <p className={`text-[11px] text-zinc-400 ${view.skip ? 'basis-full' : 'sm:mr-auto'}`}>{view.note}</p>}
+ {main && !showCmd && (
// One element for Back up first, Allow and Try again, so the button changes in place and keeps focus.
// aria-disabled, never disabled: disabling the focused button sends focus to <body> (B2). The handlers
// ignore presses while `off`.
@@ -202,7 +418,8 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, co
aria-disabled={off || undefined}
aria-busy={view.busy || undefined}
onClick={() => !off && main.onClick()}
- className={AMBER}
+ // While the confirm is open its own button is the one amber action.
+ className={showSkip ? PLAIN : AMBER}
>
{main.icon}
{main.label}
@@ -221,6 +438,11 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, co
Back up first
</button>
)}
+ {view.skip && !skip.open && (
+ <button ref={skipOpenerRef} type="button" data-floor-skip-open aria-disabled={off || undefined} onClick={openSkip} className={PLAIN}>
+ Allow without a backup
+ </button>
+ )}
<button type="button" disabled={off} onClick={() => !off && onResolve(id, 'deny')} className={PLAIN}>
<X size={14} aria-hidden="true" />
Deny
diff --git a/frontend/src/dev/fixtures.ts b/frontend/src/dev/fixtures.ts
index 1c31b39e..2219aa2b 100644
--- a/frontend/src/dev/fixtures.ts
+++ b/frontend/src/dev/fixtures.ts
@@ -159,8 +159,9 @@ export const FLOOR_DESTRUCTIVE = floorApproval('ap_2', 'Lin', 'sqlite3 data/kwan
export const FLOOR_MIGRATION = floorApproval('ap_3', 'Vega', './scripts/deploy_test.sh 7c41e0a', {
kind: 'deploy_migration', why: 'This command runs ./scripts/deploy_test.sh, a deploy script', needs_backup: true,
blast: [['Where', 'kwant.jumpin.games · production'], ['What changes', 'App 4049325 → 7c41e0a · 1 change: #301 risk reasons'],
- ['Migration', '0031_landed_risk.sql · adds 1 column to landed_cards · has a way back'],
+ ['Database', '0031_landed_risk.sql · adds 1 column to landed_cards · has a way back'],
['If it fails', 'The app goes back on its own. The database goes back only from a backup.']],
+ migration: 'yes',
backup: { state: 'old', age_s: 41 * 60, bytes: 412_000_000, path: null, error: null },
});
@@ -183,6 +184,20 @@ export const FLOOR_NO_COMMAND = floorApproval('ap_6', 'Lin', 'psql -c "DELETE FR
backup: { state: 'no_command', age_s: null, bytes: null, path: null, error: null },
});
+// 22f: Oleks's deploy (Nov 15): the app can't tell if it changes the database, and the space has no backup command.
+const OLEKS_DEPLOY = 'set -e; [email protected]; D=/opt/tradebot; timeout 120 ssh -o BatchMode=yes -o ConnectTimeout=15 $R "cd $D && docker compose up -d --no-deps --force-recreate catalyst 2>&1 && docker compose ps catalyst"';
+const GUESS_BLAST: [string, string][] = [['Database', "Might change it. The app can't tell from the command."],
+ ['If it fails', 'The app goes back on its own. The database goes back only from a backup.'], ['Downtime', 'While the containers restart.'], ['Where', '[email protected]']];
+export const FLOOR_GUESS_NO_COMMAND = floorApproval('ap_8', 'Builder', OLEKS_DEPLOY, {
+ kind: 'deploy_migration', why: 'This command runs docker compose up over ssh', needs_backup: true, migration: 'guess', blast: GUESS_BLAST,
+ backup: { state: 'no_command', age_s: null, bytes: null, path: null, error: null },
+}, '~/dev/binance-trading-lab');
+
+export const FLOOR_GUESS_OLD = floorApproval('ap_9', 'Builder', OLEKS_DEPLOY, {
+ kind: 'deploy_migration', why: 'This command runs docker compose up over ssh', needs_backup: true, migration: 'guess', blast: GUESS_BLAST,
+ backup: { state: 'old', age_s: 2 * 3600, bytes: 18_400_000, path: '/srv/b.sql', error: null },
+}, '~/dev/binance-trading-lab');
+
export const FLOOR_FAILED = floorApproval('ap_7', 'Lin', 'sqlite3 data/kwant.db "DROP TABLE old_x;"', {
kind: 'destructive', why: 'This database command runs DROP TABLE', needs_backup: true,
blast: [['Where', 'kwant.jumpin.games database · production']],
diff --git a/frontend/src/dev/logic.ts b/frontend/src/dev/logic.ts
index 935da236..6adfb7df 100644
--- a/frontend/src/dev/logic.ts
+++ b/frontend/src/dev/logic.ts
@@ -139,20 +139,29 @@ export interface FloorUi {
error: string | null;
/** Epoch ms when Allow appeared in place of Back up first; presses before +500 ms are ignored. */
armedAt: number | null;
+ /** 22f: the server's backup state as last re-read (on focus, after a backup or a new command), with the
+ * epoch ms it arrived, so its `age_s` ages from then. null: the card's own snapshot still holds. */
+ live: { backup: FloorBackup; at: number } | null;
}
export type FloorEvent =
| { type: 'backup_start' }
| { type: 'backup_done'; result: BackupResult; now: number }
- | { type: 'backup_error'; error: string };
+ | { type: 'backup_error'; error: string }
+ | { type: 'live'; backup: FloorBackup; now: number };
export const initialFloorUi = (floor: ProdFloor): FloorUi => ({
phase: floor.backup.state === 'taking' ? 'taking' : floor.backup.state === 'failed' ? 'failed' : 'idle',
taken: null,
error: floor.backup.state === 'failed' ? floor.backup.error : null,
armedAt: null,
+ live: null,
});
+/** A backup state that lets Allow show (fresh from the server, whatever the card did). */
+const freshState = (b: FloorBackup, at: number, now: number) =>
+ (b.state === 'fresh' || b.state === 'old') && b.age_s !== null && b.age_s + Math.max(0, now - at) / 1000 <= FRESH_S;
+
export function floorReducer(ui: FloorUi, ev: FloorEvent): FloorUi {
switch (ev.type) {
case 'backup_start':
@@ -161,9 +170,19 @@ export function floorReducer(ui: FloorUi, ev: FloorEvent): FloorUi {
case 'backup_done':
if (ui.phase !== 'taking') return ui;
if (!ev.result.ok) return { ...ui, phase: 'failed', error: ev.result.error ?? 'no reason given', armedAt: null };
- return { phase: 'done', taken: { bytes: ev.result.bytes, path: ev.result.path, at: ev.now }, error: null, armedAt: ev.now };
+ return { ...ui, phase: 'done', taken: { bytes: ev.result.bytes, path: ev.result.path, at: ev.now }, error: null, armedAt: ev.now };
case 'backup_error':
return ui.phase !== 'taking' ? ui : { ...ui, phase: 'failed', error: ev.error, armedAt: null };
+ case 'live': {
+ // A running backup owns the card; its own result comes next.
+ if (ui.phase === 'taking') return { ...ui, live: { backup: ev.backup, at: ev.now } };
+ const was = ui.live ? freshState(ui.live.backup, ui.live.at, ev.now) : false;
+ const is = freshState(ev.backup, ev.now, ev.now);
+ // A fresh backup taken elsewhere counts, even over this card's failed one; an Allow that appears
+ // because of it gets the same 500 ms guard as the one that replaces Back up first.
+ const phase = is && ui.phase === 'failed' ? 'idle' : ui.phase;
+ return { ...ui, phase, error: phase === 'failed' ? ui.error : null, live: { backup: ev.backup, at: ev.now }, armedAt: is && !was ? ev.now : ui.armedAt };
+ }
}
}
@@ -181,10 +200,13 @@ export interface FloorView {
text: string;
/** The file name (mono) after the size, when known. */
file: string | null;
- /** The main button: Allow, Back up first (in Allow's place), Try the backup again, or none. */
- main: 'allow' | 'backup' | 'retry' | 'none';
+ /** The main button: Allow, Back up first (in Allow's place), Try the backup again, Set backup command (22f). */
+ main: 'allow' | 'backup' | 'retry' | 'set_command';
/** A secondary Back up first beside Allow (plain deploy, old backup). */
secondaryBackup: boolean;
+ /** 22f: a secondary "Allow without a backup" (behind one confirm): only when kwant guessed the database
+ * change, never for a known one or a destructive command. */
+ skip: boolean;
/** Every button waits (taking). */
busy: boolean;
/** The right-hand note. */
@@ -196,40 +218,53 @@ export interface FloorView {
* server's `age_s`, so a fresh backup ages on screen and turns old after 10 minutes.
*/
export function floorView(floor: ProdFloor, ui: FloorUi, now: number, mountedAt: number = now): FloorView {
- const b: FloorBackup = floor.backup;
+ const view = floorViewOf(floor, ui, now, mountedAt);
+ // Allow without a backup: a person's override of kwant's guess, offered wherever a backup is still missing.
+ const skip = canSkipBackup(floor) && (view.case === 'no_command' || view.case === 'blocked' || view.case === 'failed');
+ return skip ? { ...view, skip, note: 'Or allow it if this deploy doesn’t touch the database.' } : view;
+}
+
+/** True when this floor card may be allowed without a backup (22f): a deploy kwant only guessed changes the
+ * database. The server checks the same rule at answer time. */
+export const canSkipBackup = (floor: ProdFloor) => floor.kind === 'deploy_migration' && floor.migration === 'guess';
+
+function floorViewOf(floor: ProdFloor, ui: FloorUi, now: number, mountedAt: number): FloorView {
+ const b: FloorBackup = ui.live?.backup ?? floor.backup;
+ if (ui.live) mountedAt = ui.live.at;
const blockedNote = 'Nothing runs without a fresh backup.';
const plainNote = 'No “always allow” on the production floor.';
const note = floor.needs_backup ? blockedNote : plainNote;
+ const skip = false;
const sz = (bytes: number | null) => (size(bytes) ? ` · ${size(bytes)}` : '');
if (ui.phase === 'taking') {
const pct = typeof b.percent === 'number' && b.state === 'taking' ? ` ${Math.round(b.percent)} %` : '';
- return { case: 'taking', tone: 'info', lead: '', text: `Taking a backup…${pct}`, file: null, main: floor.needs_backup ? 'backup' : 'allow', secondaryBackup: !floor.needs_backup, busy: true, note };
+ return { case: 'taking', tone: 'info', lead: '', text: `Taking a backup…${pct}`, file: null, main: floor.needs_backup ? 'backup' : 'allow', secondaryBackup: !floor.needs_backup, skip, busy: true, note };
}
if (ui.phase === 'failed') {
const why = (ui.error ?? 'no reason given').replace(/[.\s]+$/, '');
- return { case: 'failed', tone: 'bad', lead: 'Backup failed:', text: ` ${why}.`, file: null, main: 'retry', secondaryBackup: false, busy: false, note: blockedNote };
+ return { case: 'failed', tone: 'bad', lead: 'Backup failed:', text: ` ${why}.`, file: null, main: 'retry', secondaryBackup: false, skip, busy: false, note: blockedNote };
}
if (ui.phase === 'done' && ui.taken) {
const secs = (now - ui.taken.at) / 1000;
if (secs <= FRESH_S) {
- return { case: 'just_taken', tone: 'ok', lead: `Backup taken ${age(secs)} ago`, text: sz(ui.taken.bytes), file: null, main: 'allow', secondaryBackup: false, busy: false, note: plainNote };
+ return { case: 'just_taken', tone: 'ok', lead: secs < 5 ? 'Backup taken just now' : `Backup taken ${age(secs)} ago`, text: sz(ui.taken.bytes), file: null, main: 'allow', secondaryBackup: false, skip, busy: false, note: plainNote };
}
}
if (b.state === 'no_data') {
- return { case: 'no_data', tone: 'neutral', lead: '', text: 'Nothing to back up: this site has no database or uploads.', file: null, main: 'allow', secondaryBackup: false, busy: false, note: plainNote };
+ return { case: 'no_data', tone: 'neutral', lead: '', text: 'Nothing to back up: this site has no database or uploads.', file: null, main: 'allow', secondaryBackup: false, skip, busy: false, note: plainNote };
}
if (b.state === 'no_command' && floor.needs_backup) {
- return { case: 'no_command', tone: 'bad', lead: 'No backup command.', text: ' Set a backup command in Dev mode settings.', file: null, main: 'none', secondaryBackup: false, busy: false, note: blockedNote };
+ return { case: 'no_command', tone: 'bad', lead: 'No backup command.', text: ' Set one here, then back up before this runs.', file: null, main: 'set_command', secondaryBackup: false, skip, busy: false, note: blockedNote };
}
const liveAge = b.age_s === null ? null : b.age_s + Math.max(0, now - mountedAt) / 1000;
const fresh = (b.state === 'fresh' || b.state === 'old') && liveAge !== null && liveAge <= FRESH_S;
if (fresh && liveAge !== null) {
- return { case: 'fresh', tone: 'ok', lead: `Backup taken ${age(liveAge)} ago`, text: sz(b.bytes), file: fileName(b.path), main: 'allow', secondaryBackup: false, busy: false, note: plainNote };
+ return { case: 'fresh', tone: 'ok', lead: liveAge < 5 ? 'Backup taken just now' : `Backup taken ${age(liveAge)} ago`, text: sz(b.bytes), file: fileName(b.path), main: 'allow', secondaryBackup: false, skip, busy: false, note: plainNote };
}
const never = liveAge === null || b.state === 'none' || b.state === 'no_command';
if (floor.needs_backup) {
- return { case: 'blocked', tone: 'bad', lead: never ? 'No backup yet.' : 'No fresh backup.', text: never ? '' : ` The last one is ${age(liveAge!)} old.`, file: null, main: 'backup', secondaryBackup: false, busy: false, note: blockedNote };
+ return { case: 'blocked', tone: 'bad', lead: never ? 'No backup yet.' : 'No fresh backup.', text: never ? '' : ` The last one is ${age(liveAge!)} old.`, file: null, main: 'backup', secondaryBackup: false, skip, busy: false, note: blockedNote };
}
return {
case: 'old_plain',
@@ -240,6 +275,7 @@ export function floorView(floor: ProdFloor, ui: FloorUi, now: number, mountedAt:
main: 'allow',
// Without a backup command there is nothing to run, so only Allow and Deny.
secondaryBackup: b.state !== 'no_command',
+ skip,
busy: false,
note: plainNote,
};
@@ -261,6 +297,8 @@ export function floorWho(floor: ProdFloor, bot: string): string {
destructive: 'delete data',
prod_key: 'use a production key',
};
+ // 22f: a guessed migration may not touch the database, so don't claim it does.
+ if (floor.kind === 'deploy_migration' && floor.migration === 'guess') return `${bot} wants to deploy to production`;
return `${bot} wants to ${what[floor.kind]}`;
}
@@ -285,6 +323,7 @@ export function floorSentence(why: string): string {
}
export function floorSubline(floor: ProdFloor): string {
+ if (floor.kind === 'deploy_migration' && floor.migration === 'guess') return 'The app can’t tell if this deploy changes the database, so it asks for a backup from the last 10 minutes first.';
if (floor.kind === 'deploy_migration') return 'This deploy changes the database, so it counts as destructive: it needs a backup from the last 10 minutes first.';
if (floor.kind === 'destructive') return 'Destructive commands need a backup from the last 10 minutes first.';
if (floor.kind === 'deploy') return 'Dev mode is on, so deploys always ask you, even with approvals off.';
diff --git a/frontend/src/dev/types.ts b/frontend/src/dev/types.ts
index 75603816..5803b6d8 100644
--- a/frontend/src/dev/types.ts
+++ b/frontend/src/dev/types.ts
@@ -215,6 +215,14 @@ export interface ProdFloor {
needs_backup: boolean;
space_id: string | null;
backup: FloorBackup;
+ /** 22f: "yes" when the deploy is known to change the database, "guess" when kwant can't tell (it then
+ * counts as one, but the person may allow it without a backup); null when there's no migration. */
+ migration: 'yes' | 'guess' | null;
+}
+
+/** How the card answers: `without_backup` only from the person's own confirm on a "guess" deploy (22f). */
+export interface FloorResolveOpts {
+ withoutBackup?: boolean;
}
/** `POST /api/spaces/:id/dev/backup`. */
@@ -574,9 +582,17 @@ export function parseProdFloor(details: unknown): ProdFloor | null {
needs_backup: p.needs_backup === true || p.kind === 'destructive' || p.kind === 'deploy_migration',
space_id: str(p.space_id, 80),
backup: parseBackup(p.backup),
+ migration: p.migration === 'yes' || p.migration === 'guess' ? p.migration : null,
};
}
+/** The card's live backup state (22f, Juno's GET): the bare state, or wrapped as `{backup: {...}}`. */
+export function parseBackupState(v: unknown): FloorBackup | null {
+ const b = isObj(v) && isObj(v.backup) ? v.backup : v;
+ if (!isObj(b) || !BACKUP_STATES.includes(b.state as BackupState)) return null;
+ return parseBackup(b);
+}
+
export function parseBackupResult(v: unknown): BackupResult {
const b = isObj(v) ? v : {};
return { id: str(b.id, 80), ok: b.ok === true, path: str(b.path, 400), bytes: num(b.bytes), taken_at: str(b.taken_at, 64), error: str(b.error, 200) };
diff --git a/frontend/tests/away.test.mjs b/frontend/tests/away.test.mjs
index 3f4576a9..69ad02f5 100644
--- a/frontend/tests/away.test.mjs
+++ b/frontend/tests/away.test.mjs
@@ -181,3 +181,41 @@ test('a limit message is never shown as a card summary', () => {
assert.equal(a.awaySummary({ title: 't', summary: 'Brief' }), 'Brief');
assert.equal(a.awaySummary({ title: 't', summary: "You've hit your session limit · resets 3am" }), '');
});
+
+test('22f round 2: a backup refusal (409 needs_backup) keeps the chat card and shows the server reason', async () => {
+ const refusal = (code) => new a.AwayError(409, 'This step needs a fresh backup before it runs.', { status: 'needs_backup', code, error: 'This step needs a fresh backup before it runs.' });
+ for (const code of ['backup_required', undefined]) {
+ const err = refusal(code);
+ assert.equal(a.isBackupRefusal(err), true);
+ const dropped = [];
+ await assert.rejects(a.resolveFromList('a1', (id) => dropped.push(id), () => Promise.reject(err)));
+ assert.deepEqual(dropped, [], `code ${code}: the card is still waiting, so the chat keeps it`);
+ assert.deepEqual(a.failureNotice(err, 'Deploy'), { text: 'This step needs a fresh backup before it runs. (“Deploy”)', error: true });
+ }
+ // A body with no reason falls back to the plain sentence.
+ const bare = new a.AwayError(409, 'Request failed (HTTP 409).', { status: 'needs_backup' });
+ assert.match(a.failureNotice(bare, 'X').text, /^This step needs a backup from the last 10 minutes/);
+ // A plain lapse (409 without needs_backup) and a 404 still drop the card; success drops it too.
+ for (const err of [new a.AwayError(409, 'Already answered', { error: 'Already answered' }), new a.AwayError(404, 'Not found')]) {
+ const dropped = [];
+ await assert.rejects(a.resolveFromList('a1', (id) => dropped.push(id), () => Promise.reject(err)));
+ assert.deepEqual(dropped, ['a1']);
+ assert.equal(a.isBackupRefusal(err), false);
+ }
+ const dropped = [];
+ assert.equal(await a.resolveFromList('a1', (id) => dropped.push(id), async () => 'ok'), 'ok');
+ assert.deepEqual(dropped, ['a1']);
+ assert.deepEqual(a.failureNotice(new a.AwayError(409, 'Already answered'), 'X'), { text: 'This request expired: “X”', error: true });
+});
+
+test('22f round 2: the server body reaches AwayError from a real 409', async () => {
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = async () => new Response(JSON.stringify({ status: 'needs_backup', code: 'backup_required', error: 'Needs one.' }), { status: 409 });
+ try {
+ const err = await a.awayApi.resolve('a1', 'allow_once', true).then(() => null, (e) => e);
+ assert.equal(a.isBackupRefusal(err), true);
+ assert.equal(err.message, 'Needs one.');
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
diff --git a/frontend/tests/devCards.test.mjs b/frontend/tests/devCards.test.mjs
index c7d79904..53a5c2a2 100644
--- a/frontend/tests/devCards.test.mjs
+++ b/frontend/tests/devCards.test.mjs
@@ -275,8 +275,9 @@ test('backup case 3: just taken via Back up first, then it ages and goes old aft
ui = m.floorReducer(ui, { type: 'backup_done', result: { id: 'b', ok: true, path: '/x/b.tgz', bytes: 412_000_000, taken_at: null, error: null }, now: NOW });
let v = m.floorView(f, ui, NOW + 3000, NOW);
assert.equal(v.case, 'just_taken');
- assert.equal(v.lead, 'Backup taken 3 s ago');
+ assert.equal(v.lead, 'Backup taken just now', 'under 5 s reads "just now", not "0 s ago"');
assert.equal(v.main, 'allow');
+ assert.equal(m.floorView(f, ui, NOW + 6000, NOW).lead, 'Backup taken 6 s ago');
v = m.floorView(f, ui, NOW + 11 * 60_000, NOW);
assert.equal(v.case, 'blocked', 'stale again after 10 minutes');
assert.equal(v.main, 'backup');
@@ -304,7 +305,8 @@ test('backup case 5: destructive or migration with no fresh backup replaces Allo
assert.equal(never.lead, 'No backup yet.');
const nc = viewOf(fx.FLOOR_NO_COMMAND);
assert.equal(nc.case, 'no_command');
- assert.equal(nc.main, 'none', 'nothing to run, so no main button');
+ assert.equal(nc.main, 'set_command', 'no command yet: set one in the card (22f)');
+ assert.equal(nc.skip, false, 'a destructive command is never allowed without a backup');
});
test('backup case 6: taking disables every button and shows a percent only when the server sends one', () => {
@@ -350,6 +352,23 @@ test('the floor card never offers "always allow", in any case', () => {
assert.match(mig, /wants to deploy a database change/);
assert.doesNotMatch(mig, /Allow this deploy/, 'blocked: Allow is replaced');
assert.match(mig, /Back up first/);
+ assert.match(mig, /<dt[^>]*>Database<\/dt>/, '22f round 2: the row is "Database", not "Migration"');
+});
+
+test('22f round 2: a guessed migration deploy says "deploy to production"; a known one keeps "a database change"', () => {
+ assert.equal(m.floorWho(floorOf(fx.FLOOR_GUESS_NO_COMMAND), 'Builder'), 'Builder wants to deploy to production');
+ assert.equal(m.floorWho(floorOf(fx.FLOOR_MIGRATION), 'Vega'), 'Vega wants to deploy a database change');
+ const out = html(m.ModernApprovalCard, { approval: fx.FLOOR_GUESS_NO_COMMAND, onResolve() {} });
+ assert.equal(heading(out), 'Production floor: Builder wants to deploy to production');
+ assert.match(out, /Might change it\. The app can(&#x27;|')t tell from the command\./);
+});
+
+test('22f round 2: a backup taken in the last 5 s reads "just now"', () => {
+ const f = floorOf(fx.FLOOR_DEPLOY_FRESH);
+ const ui = m.initialFloorUi(f);
+ const b = { ...f, backup: { ...f.backup, age_s: 2 } };
+ assert.equal(m.floorView(b, ui, NOW, NOW).lead, 'Backup taken just now');
+ assert.equal(m.floorView({ ...f, backup: { ...f.backup, age_s: 5 } }, ui, NOW, NOW).lead, 'Backup taken 5 s ago');
});
/** The floor card's <h3> as text (tags stripped). */
@@ -724,3 +743,202 @@ test('the floor card shows why as its own sentence, never "This is runs …" (0.
assert.doesNotMatch(html(m.ModernApprovalCard, { approval: f, onResolve() {} }), /This is /);
}
});
+
+// ---------------------------------------------------------------------------------------------------
+// 22f: a production-floor card is never a dead end (Oleks, Nov 15)
+
+const typeInto = async (el, v) => {
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(el, v);
+ el.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+};
+const NONE = { state: 'none', age_s: null, bytes: null, path: null, error: null };
+
+test('22f: the parser keeps migration "yes" | "guess" and drops anything else', () => {
+ assert.equal(floorOf(fx.FLOOR_GUESS_NO_COMMAND).migration, 'guess');
+ assert.equal(floorOf(fx.FLOOR_MIGRATION).migration, 'yes');
+ assert.equal(floorOf(fx.FLOOR_DESTRUCTIVE).migration, null);
+ assert.equal(m.parseProdFloor({ prod_floor: { kind: 'deploy_migration', migration: 'maybe', backup: {} } }).migration, null);
+ assert.deepEqual(m.parseBackupState({ backup: { state: 'fresh', age_s: 3 } }).state, 'fresh', 'wrapped');
+ assert.equal(m.parseBackupState({ state: 'none' }).state, 'none', 'bare');
+ assert.equal(m.parseBackupState({ state: 'weird' }), null);
+ assert.equal(m.parseBackupState(null), null);
+});
+
+test('22f: Allow without a backup only for a guessed deploy, in no_command, blocked and failed', () => {
+ const g = viewOf(fx.FLOOR_GUESS_NO_COMMAND);
+ assert.equal(g.case, 'no_command');
+ assert.equal(g.main, 'set_command');
+ assert.equal(g.skip, true);
+ assert.equal(g.note, 'Or allow it if this deploy doesn’t touch the database.');
+ const old = viewOf(fx.FLOOR_GUESS_OLD);
+ assert.equal(old.case, 'blocked');
+ assert.equal(old.main, 'backup');
+ assert.equal(old.skip, true);
+ const f = floorOf(fx.FLOOR_GUESS_OLD);
+ let ui = m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' });
+ assert.equal(m.floorView(f, ui, NOW, NOW).skip, false, 'not while a backup runs');
+ ui = m.floorReducer(ui, { type: 'backup_error', error: 'exit 1' });
+ assert.equal(m.floorView(f, ui, NOW, NOW).case, 'failed');
+ assert.equal(m.floorView(f, ui, NOW, NOW).skip, true, 'a failed backup still leaves a way forward');
+ ui = m.floorReducer(m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' }), { type: 'backup_done', result: { id: 'b', ok: true, path: null, bytes: 1, taken_at: null, error: null }, now: NOW });
+ assert.equal(m.floorView(f, ui, NOW, NOW).skip, false, 'backed up: plain Allow, no override');
+ for (const ap of [fx.FLOOR_MIGRATION, fx.FLOOR_DESTRUCTIVE, fx.FLOOR_NO_COMMAND, fx.FLOOR_FAILED, fx.FLOOR_DEPLOY_OLD, fx.FLOOR_DEPLOY_FRESH, fx.FLOOR_PAGES]) {
+ assert.equal(viewOf(ap).skip, false, `${ap.id}: never for a known migration, a destructive command or a plain deploy`);
+ }
+ assert.equal(m.canSkipBackup({ ...floorOf(fx.FLOOR_DESTRUCTIVE), migration: 'guess' }), false, 'destructive never, even if a payload says guess');
+});
+
+test('22f: a guessed deploy says the app can’t tell, not that it changes the database', () => {
+ assert.match(m.floorSubline(floorOf(fx.FLOOR_GUESS_NO_COMMAND)), /^The app can’t tell if this deploy changes the database/);
+ assert.match(m.floorSubline(floorOf(fx.FLOOR_MIGRATION)), /^This deploy changes the database/);
+});
+
+test('22f: the live backup state replaces the snapshot; a fresh one elsewhere arms Allow with the 500 ms guard', () => {
+ const f = floorOf(fx.FLOOR_GUESS_NO_COMMAND);
+ let ui = m.floorReducer(m.initialFloorUi(f), { type: 'live', backup: NONE, now: NOW });
+ let v = m.floorView(f, ui, NOW, NOW);
+ assert.equal(v.case, 'blocked');
+ assert.equal(v.main, 'backup', 'a command now: Back up first');
+ ui = m.floorReducer(ui, { type: 'live', backup: { state: 'fresh', age_s: 20, bytes: 9, path: '/srv/b.sql', error: null }, now: NOW });
+ v = m.floorView(f, ui, NOW + 1000, NOW);
+ assert.equal(v.case, 'fresh');
+ assert.equal(v.main, 'allow');
+ assert.equal(v.lead, 'Backup taken 21 s ago', 'ages from when it arrived');
+ assert.equal(m.allowReady(ui, NOW + 300), false);
+ assert.equal(m.allowReady(ui, NOW + 500), true);
+ // A backup that failed on the card stops counting once a fresh one arrives from elsewhere.
+ let failed = m.floorReducer(m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' }), { type: 'backup_error', error: 'x' });
+ failed = m.floorReducer(failed, { type: 'live', backup: { state: 'fresh', age_s: 5, bytes: 1, path: null, error: null }, now: NOW });
+ assert.equal(m.floorView(f, failed, NOW, NOW).case, 'fresh');
+ // A running backup owns the card.
+ const taking = m.floorReducer(m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' }), { type: 'live', backup: NONE, now: NOW });
+ assert.equal(taking.phase, 'taking');
+});
+
+test('22f (a): a guessed deploy with no backup command is allowed without a backup after one confirm', async () => {
+ const calls = [];
+ const host = await mount(m.ModernApprovalCard, { approval: fx.FLOOR_GUESS_NO_COMMAND, onResolve: (...a) => calls.push(a), onLoadBackup: async () => null });
+ assert.ok(!host.querySelector('[data-floor-skip]'), 'the confirm is closed at first');
+ await click(host.querySelector('[data-floor-skip-open]'));
+ const box = host.querySelector('[data-floor-skip] input[type=checkbox]');
+ assert.equal(document.activeElement, box, 'focus goes to the checkbox');
+ assert.match(host.querySelector('[data-floor-skip]').textContent, /This deploy doesn’t change the database/);
+ const go = host.querySelector('[data-floor-skip-allow]');
+ assert.equal(go.getAttribute('aria-disabled'), 'true');
+ await click(go);
+ assert.deepEqual(calls, [], 'nothing until the box is ticked');
+ await click(box);
+ assert.equal(box.checked, true);
+ assert.equal(go.hasAttribute('aria-disabled'), false);
+ await click(go);
+ assert.deepEqual(calls, [['ap_8', 'allow_once', { withoutBackup: true }]]);
+});
+
+test('22f: Cancel and Escape close the confirm and give focus back to its button', async () => {
+ const host = await mount(m.ModernApprovalCard, { approval: fx.FLOOR_GUESS_OLD, onResolve() {}, onLoadBackup: async () => null });
+ await click(host.querySelector('[data-floor-skip-open]'));
+ const box = host.querySelector('[data-floor-skip] input');
+ box.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ assert.ok(!host.querySelector('[data-floor-skip]'));
+ assert.equal(document.activeElement, host.querySelector('[data-floor-skip-open]'));
+});
+
+test('22f (b): set a command inline, back up and allow, without leaving the card', async () => {
+ const realNow = Date.now;
+ let clock = NOW;
+ Date.now = () => clock;
+ try {
+ const calls = [];
+ const saved = [];
+ let server = { state: 'no_command', age_s: null, bytes: null, path: null, error: null };
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_GUESS_NO_COMMAND,
+ onResolve: (...a) => calls.push(a),
+ onSetCommand: async (space, c) => {
+ saved.push([space, c]);
+ server = NONE;
+ },
+ onLoadBackup: async () => server,
+ onBackup: async () => {
+ server = { state: 'fresh', age_s: 0, bytes: 18_400_000, path: '/srv/b.sql', error: null };
+ return { id: 'b1', ok: true, path: '/srv/b.sql', bytes: 18_400_000, taken_at: null, error: null };
+ },
+ });
+ const main = host.querySelector('[data-floor-main]');
+ assert.equal(main.textContent.trim(), 'Set backup command');
+ await click(main);
+ const input = host.querySelector('[data-floor-command] input');
+ assert.equal(document.activeElement, input, 'focus goes to the field');
+ assert.equal(input.maxLength, 2000);
+ assert.match(host.querySelector('[data-floor-command]').textContent, /It should print the backup file’s path/);
+ assert.ok(!host.querySelector('[data-floor-main]'), 'Save replaces the main button while the field is open');
+ await click(host.querySelector('[data-floor-command-save]'));
+ assert.match(host.querySelector('[data-floor-command] [role=alert]').textContent, /Type the command/);
+ assert.deepEqual(saved, []);
+ await typeInto(input, " ssh [email protected] 'pg_dump app > /srv/b.sql && echo /srv/b.sql' ");
+ await click(host.querySelector('[data-floor-command-save]'));
+ assert.deepEqual(saved, [['s_kwant', "ssh [email protected] 'pg_dump app > /srv/b.sql && echo /srv/b.sql'"]]);
+ assert.ok(!host.querySelector('[data-floor-command]'), 'the field closes');
+ const backup = host.querySelector('[data-floor-main]');
+ assert.equal(backup.dataset.floorMain, 'backup');
+ assert.equal(document.activeElement, backup, 'focus is on Back up first');
+ assert.equal(host.querySelector('[data-backup-row]').dataset.backupRow, 'blocked');
+ await click(backup);
+ assert.equal(host.querySelector('[data-floor-main]').dataset.floorMain, 'allow');
+ assert.ok(!host.querySelector('[data-floor-skip-open]'), 'backed up: no override any more');
+ clock += 600;
+ await click(host.querySelector('[data-floor-main]'));
+ assert.deepEqual(calls, [['ap_8', 'allow_once', undefined]], 'a plain Allow, not without_backup');
+ } finally {
+ Date.now = realNow;
+ }
+});
+
+test('22f: a refused save keeps the field open with the server’s reason; an older server still moves on', async () => {
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_NO_COMMAND,
+ onResolve() {},
+ onSetCommand: async () => {
+ throw new Error('the backup command must be at most 2000 characters');
+ },
+ onLoadBackup: async () => null,
+ });
+ await click(host.querySelector('[data-floor-main]'));
+ await typeInto(host.querySelector('[data-floor-command] input'), 'x');
+ await click(host.querySelector('[data-floor-command-save]'));
+ assert.match(host.querySelector('[data-floor-command] [role=alert]').textContent, /at most 2000 characters/);
+ assert.equal(host.querySelector('[data-floor-command] input').getAttribute('aria-invalid'), 'true');
+ assert.ok(!host.querySelector('[data-floor-skip-open]'), 'destructive: no Allow without a backup, ever');
+
+ const host2 = await mount(m.ModernApprovalCard, { approval: fx.FLOOR_NO_COMMAND, onResolve() {}, onSetCommand: async () => {}, onLoadBackup: async () => null });
+ await click(host2.querySelector('[data-floor-main]'));
+ await typeInto(host2.querySelector('[data-floor-command] input'), './backup.sh');
+ await click(host2.querySelector('[data-floor-command-save]'));
+ assert.equal(host2.querySelector('[data-floor-main]').dataset.floorMain, 'backup', 'no GET route: saved means no backup yet');
+});
+
+test('22f: the card re-reads the backup state when the window gets focus', async () => {
+ let reads = 0;
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_GUESS_OLD,
+ onResolve() {},
+ onLoadBackup: async () => {
+ reads++;
+ return { state: 'fresh', age_s: 30, bytes: 1, path: '/srv/b.sql', error: null };
+ },
+ });
+ assert.equal(host.querySelector('[data-floor-main]').dataset.floorMain, 'backup');
+ window.dispatchEvent(new window.Event('focus'));
+ await settle();
+ assert.equal(reads, 1);
+ assert.equal(host.querySelector('[data-floor-main]').dataset.floorMain, 'allow', 'a backup taken elsewhere counts');
+});
+
+test('22f: a Destructive card renders no Allow of any kind without a fresh backup', () => {
+ for (const ap of [fx.FLOOR_DESTRUCTIVE, fx.FLOOR_NO_COMMAND, fx.FLOOR_FAILED]) {
+ const out = html(m.ModernApprovalCard, { approval: ap, onResolve() {} });
+ assert.doesNotMatch(out, /Allow/, `${ap.id}`);
+ }
+});