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.

Person-only deletes: retry after "Confirm it's you", no extra error

Lin (kwant bot)da0ccf3fb601
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index c0bd83cd..026e2d18 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -72,6 +72,7 @@ import { Space, eventsUrl, pickInitialChat, spaceColor } from './spaces';
import { canRunNow } from './engines';
import { useEngines } from './useEngines';
import { claudeNeedsSignIn } from './claudeLogin';
+import { personFetch } from './auth';
// 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.
@@ -1889,34 +1890,30 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
};
+ // Throws when the team wasn't deleted, so the dialog stays open and says why.
const handleDeleteTeam = async (id: string) => {
+ // Person-only: after "Confirm it's you" the delete goes through without pressing it again.
+ const res = await personFetch(`/api/teams/${encodeURIComponent(id)}`, { method: 'DELETE' });
+ if (!res.ok && res.status !== 404) throw new Error(`Couldn’t delete the team (HTTP ${res.status}).`);
+ setTeams((prev) => prev.filter((t) => t.id !== id));
+ if (selectedTeamId === id) {
+ setSelectedTeamId(null);
+ if (channels.length > 0) {
+ setSelectedId(channels[0].id);
+ setIsChannel(true);
+ }
+ }
+ setEditingTeam(null);
+ playSfx('click');
+ // Refresh channels
try {
- const res = await fetch(`/api/teams/${id}`, {
- method: 'DELETE',
- });
-
- if (res.ok) {
- setTeams((prev) => prev.filter((t) => t.id !== id));
- if (selectedTeamId === id) {
- setSelectedTeamId(null);
- if (channels.length > 0) {
- setSelectedId(channels[0].id);
- setIsChannel(true);
- }
- }
-
- // Refresh channels
- const cRes = await fetch('/api/channels');
- if (cRes.ok) {
- const freshChannels: Channel[] = await cRes.json();
- setChannels(freshChannels);
- }
-
- setEditingTeam(null);
- playSfx('click');
+ const cRes = await fetch('/api/channels');
+ if (cRes.ok) {
+ const freshChannels: Channel[] = await cRes.json();
+ setChannels(freshChannels);
}
} catch (err) {
- console.error('Failed deleting team:', err);
+ console.error('Failed refreshing channels after deleting a team:', err);
}
};
diff --git a/frontend/src/auth.ts b/frontend/src/auth.ts
index 0e02fd00..0c4b0b67 100644
--- a/frontend/src/auth.ts
+++ b/frontend/src/auth.ts
@@ -9,6 +9,49 @@ export const UNAUTHORIZED_EVENT = 'kwnt:unauthorized';
export const PERSON_TOKEN_EVENT = 'kwnt:person-token';
/** Fired after the person signed in from that prompt, so open panels can load again. */
export const PERSON_SIGNED_IN_EVENT = 'kwnt:person-signed-in';
+/** Fired when the person closed that prompt without signing in. */
+export const PERSON_PROMPT_CLOSED_EVENT = 'kwnt:person-prompt-closed';
+
+/** What a person-only action says when the person closed "Confirm it's you" instead of signing in. */
+export const PERSON_CANCELLED_TEXT = 'Nothing was changed. Only you can do this: confirm it’s you, then try again.';
+
+/** Thrown by `personFetch` when the person closed "Confirm it's you"; nothing was changed. */
+export class PersonCancelledError extends Error {
+ constructor() {
+ super(PERSON_CANCELLED_TEXT);
+ }
+}
+
+/** Resolves true once the person signs in from the prompt, false when they close it. */
+export function waitForPersonSignIn(target: EventTarget = window): Promise<boolean> {
+ return new Promise((resolve) => {
+ const done = (ok: boolean) => () => {
+ target.removeEventListener(PERSON_SIGNED_IN_EVENT, onIn);
+ target.removeEventListener(PERSON_PROMPT_CLOSED_EVENT, onClosed);
+ resolve(ok);
+ };
+ const onIn = done(true);
+ const onClosed = done(false);
+ target.addEventListener(PERSON_SIGNED_IN_EVENT, onIn);
+ target.addEventListener(PERSON_PROMPT_CLOSED_EVENT, onClosed);
+ });
+}
+
+/**
+ * `fetch` for a person-only action (deleting a bot or team, undoing an action or import). On a
+ * person-only 401 the fetch wrapper has already asked "Confirm it's you"; this waits for that and
+ * sends the request once more, so the person doesn't see an error and press Delete again. Throws
+ * `PersonCancelledError` when they close the prompt instead.
+ */
+export async function personFetch(input: string, init?: RequestInit, target?: EventTarget, send: typeof fetch = (...a) => fetch(...a)): Promise<Response> {
+ const res = await send(input, init);
+ if (res.status !== 401) return res;
+ const body = await res.clone().json().catch(() => null);
+ if (!isPersonOnlyBody(body)) return res;
+ // Listen before anything can answer the prompt the wrapper just opened.
+ if (!(await waitForPersonSignIn(target ?? window))) throw new PersonCancelledError();
+ return send(input, init);
+}
export interface AuthStatus {
auth_required: boolean;
diff --git a/frontend/src/botActions.ts b/frontend/src/botActions.ts
index 01e9842a..3f0e2359 100644
--- a/frontend/src/botActions.ts
+++ b/frontend/src/botActions.ts
@@ -3,6 +3,7 @@
// Contract: docs/bot-actions.md.
import { parseMetaObject } from './questions';
import { Schedule, WEEKDAYS, describeSchedule, formatWhen } from './continuity';
+import { PersonCancelledError, personFetch } from './auth';
// ---------------------------------------------------------------------------
// Bot actions
@@ -463,7 +464,8 @@ export class ApiError extends Error {
}
async function call<T>(method: string, url: string, body?: unknown): Promise<T> {
- const res = await fetch(url, {
+ // Undo, confirm and decline are person-only: after "Confirm it's you" the call goes through.
+ const res = await personFetch(url, {
method,
headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
@@ -482,6 +484,7 @@ export function decisionError(err: unknown, what: string): string {
const why = err.message && !/^Request failed/.test(err.message) ? ` (${err.message.replace(/\.$/, '')})` : '';
return `Couldn’t ${what}: it was already decided or changed${why}.`;
}
+ if (err instanceof PersonCancelledError) return err.message;
if (err instanceof ApiError && err.status === 403) return `Couldn’t ${what}: only you can do this, from your own browser.`;
return `Couldn’t ${what}: ${err instanceof Error ? err.message : 'something went wrong.'}`;
}
diff --git a/frontend/src/botDelete.ts b/frontend/src/botDelete.ts
index 544f43c3..70587e7b 100644
--- a/frontend/src/botDelete.ts
+++ b/frontend/src/botDelete.ts
@@ -1,6 +1,8 @@
// Deleting a bot: what it takes with it, and the call. The person starts it from the bot's
// settings; a bot can only propose it (bot_delete action card).
+import { PersonCancelledError, personFetch } from './auth';
+
/** What deleting a bot removes, from GET /api/kwants/:id/usage; null when the server can't say. */
export interface BotUsage {
conversations: number;
@@ -73,8 +75,9 @@ export const botDeleteApi = {
remove: async (id: string, name: string): Promise<string | null> => {
let res: Response;
try {
- res = await fetch(`/api/kwants/${enc(id)}`, { method: 'DELETE' });
- } catch {
+ res = await personFetch(`/api/kwants/${enc(id)}`, { method: 'DELETE' });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) return e.message;
return 'Couldn’t reach the server. Check your connection and try again.';
}
if (res.ok || res.status === 404) return null;
diff --git a/frontend/src/components/AuthGate.tsx b/frontend/src/components/AuthGate.tsx
index afb9fc15..1b9c6924 100644
--- a/frontend/src/components/AuthGate.tsx
+++ b/frontend/src/components/AuthGate.tsx
@@ -2,6 +2,7 @@ import React, { createContext, useCallback, useContext, useEffect, useRef, useSt
import { KeyRound, Loader2, RefreshCw, Terminal, X } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import {
+ PERSON_PROMPT_CLOSED_EVENT,
PERSON_SIGNED_IN_EVENT,
PERSON_TOKEN_EVENT,
UNAUTHORIZED_EVENT,
@@ -89,7 +90,10 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })
{children}
{personPrompt && (
<PersonTokenDialog
- onClose={() => setPersonPrompt(false)}
+ onClose={() => {
+ setPersonPrompt(false);
+ window.dispatchEvent(new Event(PERSON_PROMPT_CLOSED_EVENT));
+ }}
onSignedIn={() => {
setPersonPrompt(false);
window.dispatchEvent(new Event(PERSON_SIGNED_IN_EVENT));
@@ -206,7 +210,7 @@ const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void; perso
</h2>
<p className="text-xs text-zinc-400 leading-relaxed">
{personOnly
- ? 'Saved passwords and answers to approval cards need your access token, even on this computer, so a bot can’t reach them. You need it once per browser. Get it on the server:'
+ ? 'Saved passwords, answers to approval cards and deleting bots or teams need your access token, even on this computer, so a bot can’t do them for you. You need it once per browser. Get it on the server:'
: 'This server is reachable from other machines, so it needs its token once per browser. Get it on the server:'}
</p>
<div className="space-y-1 text-[11px] font-mono text-zinc-300">
diff --git a/frontend/src/components/ManageTeamModal.tsx b/frontend/src/components/ManageTeamModal.tsx
index 7764c58f..f77196cf 100644
--- a/frontend/src/components/ManageTeamModal.tsx
+++ b/frontend/src/components/ManageTeamModal.tsx
@@ -178,7 +178,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
onClose();
} catch (err) {
setIsDeleting(false);
- setError('Failed to delete team.');
+ setError(err instanceof Error && err.message ? err.message : 'Couldn’t delete the team.');
}
};
@@ -208,7 +208,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
</div>
{error && (
- <div className="p-2.5 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs text-rose-300 flex items-center gap-2">
+ <div role="alert" className="p-2.5 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs text-rose-300 flex items-center gap-2">
<AlertTriangle size={14} className="flex-shrink-0 text-rose-400" />
<span>{error}</span>
</div>
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index ab7736c7..66d9f2e7 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -82,7 +82,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
// No event fires when the browser catches a login, so a new screenshot or page loads the list again.
const passwords = useSavedPasswords(teamId, `${activeUrl}|${screenshotBase64?.length ?? 0}|${screenshotBase64?.slice(-32) ?? ''}`);
const savedCount = passwords.logins.length;
- const passwordStore = usePasswordStore(!!teamId && teamId !== 'default');
+ // Quiet while the pane is closed: a background load mustn't open "Confirm it's you" on page load.
+ const passwordStore = usePasswordStore(!!teamId && teamId !== 'default', !isOpen);
// Local Chrome streams here like the VM, unless the person opened it as a window: then there's
// nothing to show. Unknown counts as vm.
diff --git a/frontend/src/imports.ts b/frontend/src/imports.ts
index 25f67201..054987ff 100644
--- a/frontend/src/imports.ts
+++ b/frontend/src/imports.ts
@@ -1,6 +1,8 @@
// Bring bots over from another app, and export them again (IMPORT-API.md). The export prompt
// text lives only on the server (src/import/prompts.rs); this file never copies it.
+import { PersonCancelledError, personFetch } from './auth';
+
export type ImportSourceId = 'grok' | 'chatgpt' | 'claude' | 'other';
export interface ExportPrompt {
@@ -125,8 +127,9 @@ const enc = encodeURIComponent;
async function call<T>(method: string, url: string, init: RequestInit = {}): Promise<T> {
let res: Response;
try {
- res = await fetch(url, { method, ...init });
- } catch {
+ res = await personFetch(url, { method, ...init });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new ImportError(e.message, 'person_cancelled', 401);
throw new ImportError('Couldn’t reach the server. Check your connection and try again.', 'network', 0);
}
if (!res.ok) {
@@ -187,6 +190,8 @@ export function importErrorText(err: unknown): { title: string; detail: string }
return { title: 'That import is gone', detail: detail || 'It may have been in another space.' };
case 'network':
return { title: 'No connection', detail };
+ case 'person_cancelled':
+ return { title: 'Not undone', detail };
default:
return { title: 'Something went wrong', detail: 'The server couldn’t finish this. Try again in a moment.' };
}
diff --git a/frontend/tests/personOnlyDeletes.test.mjs b/frontend/tests/personOnlyDeletes.test.mjs
new file mode 100644
index 00000000..0907ba1a
--- /dev/null
+++ b/frontend/tests/personOnlyDeletes.test.mjs
@@ -0,0 +1,85 @@
+// Person-only deletes and undos (2026-10-20): deleting a bot or team and undoing a bot action or
+// import need the person's token. A person-only 401 asks "Confirm it's you"; once they sign in the
+// call is sent again, so no error shows and they don't press Delete twice. Closing the prompt
+// changes nothing and says so.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ export * from './src/auth';
+ export { decisionError } from './src/botActions';
+ export { importErrorText, ImportError } from './src/imports';
+`);
+
+const personOnly = () => new Response(JSON.stringify({ error: 'person_only', person_only: true }), { status: 401 });
+const ok = () => new Response('{}', { status: 200 });
+
+/** A fake fetch answering from a list, recording each call. */
+function sender(answers) {
+ const calls = [];
+ const send = async (url, init) => {
+ calls.push([url, init?.method]);
+ return answers.shift()();
+ };
+ return { send, calls };
+}
+
+test('a person-only 401 waits for sign-in, then sends the delete once more', async () => {
+ const target = new EventTarget();
+ const { send, calls } = sender([personOnly, ok]);
+ const p = m.personFetch('/api/kwants/k1', { method: 'DELETE' }, target, send);
+ await new Promise((r) => setTimeout(r, 0));
+ assert.equal(calls.length, 1, 'no retry before the person signs in');
+ target.dispatchEvent(new Event(m.PERSON_SIGNED_IN_EVENT));
+ const res = await p;
+ assert.equal(res.status, 200);
+ assert.deepEqual(calls, [
+ ['/api/kwants/k1', 'DELETE'],
+ ['/api/kwants/k1', 'DELETE'],
+ ]);
+});
+
+test('closing "Confirm it’s you" throws PersonCancelledError and sends nothing more', async () => {
+ const target = new EventTarget();
+ const { send, calls } = sender([personOnly]);
+ const p = m.personFetch('/api/teams/t1', { method: 'DELETE' }, target, send);
+ await new Promise((r) => setTimeout(r, 0));
+ target.dispatchEvent(new Event(m.PERSON_PROMPT_CLOSED_EVENT));
+ await assert.rejects(p, (e) => e instanceof m.PersonCancelledError && /Nothing was changed/.test(e.message));
+ assert.equal(calls.length, 1);
+});
+
+test('other answers pass straight through, including a 401 that is not person-only', async () => {
+ for (const [answer, status] of [
+ [ok, 200],
+ [() => new Response('{"error":"nope"}', { status: 403 }), 403],
+ [() => new Response('{"error":"unauthorized"}', { status: 401 }), 401],
+ [() => new Response('not json', { status: 401 }), 401],
+ ]) {
+ const { send, calls } = sender([answer]);
+ const res = await m.personFetch('/api/x', { method: 'DELETE' }, new EventTarget(), send);
+ assert.equal(res.status, status);
+ assert.equal(calls.length, 1);
+ }
+});
+
+test('the wait stops listening once answered', async () => {
+ const target = new EventTarget();
+ const p = m.waitForPersonSignIn(target);
+ target.dispatchEvent(new Event(m.PERSON_PROMPT_CLOSED_EVENT));
+ assert.equal(await p, false);
+ // A later sign-in for another action doesn't reach this one.
+ const q = m.waitForPersonSignIn(target);
+ target.dispatchEvent(new Event(m.PERSON_SIGNED_IN_EVENT));
+ assert.equal(await q, true);
+});
+
+test('a cancelled undo reads as "nothing changed", not as an HTTP error', () => {
+ const cancelled = new m.PersonCancelledError();
+ assert.equal(m.decisionError(cancelled, 'undo it'), m.PERSON_CANCELLED_TEXT);
+ const t = m.importErrorText(new m.ImportError(m.PERSON_CANCELLED_TEXT, 'person_cancelled', 401));
+ assert.equal(t.title, 'Not undone');
+ assert.equal(t.detail, m.PERSON_CANCELLED_TEXT);
+ assert.doesNotMatch(t.detail, /HTTP/);
+});
diff --git a/frontend/tests/savedPasswords.test.mjs b/frontend/tests/savedPasswords.test.mjs
index 5c046cbe..c4e2b911 100644
--- a/frontend/tests/savedPasswords.test.mjs
+++ b/frontend/tests/savedPasswords.test.mjs
@@ -219,7 +219,7 @@ test('the token dialog says why it is asked on this computer and can be dismisse
assert.match(html, /aria-modal="true"/);
const t = text(html);
assert.match(t, /Confirm it's you/);
- assert.match(t, /even on this computer, so a bot can't reach them/);
+ assert.match(t, /deleting bots or teams need your access token, even on this computer, so a bot can't do them for you/);
assert.match(t, /kwnt token/);
assert.ok(buttons(html).includes('Not now'));
assert.ok(buttons(html).includes('Continue'));