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.

Cards settle when their bot has since been deleted

Lin (kwant bot)052ceac769a1
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index e794eb2f..2fdd9e89 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,4 +1,4 @@
-import React, { Suspense, lazy, useState, useEffect, useRef, useCallback } from 'react';
+import React, { Suspense, lazy, useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';
import { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';
import { SpaceTile } from './components/Spaces';
@@ -140,6 +140,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [phoneTab, setPhoneTab] = useState<PhoneTab>('chats');
const [loaded, setLoaded] = useState(false);
const [kwants, setKwants] = useState<Kwant[]>([]);
+ // Whether the bot list is as new as the last bot change seen. Until then cards can't tell a
+ // deleted bot from one not fetched yet (a card for a new bot arrives before the list reloads).
+ const [rosterFresh, setRosterFresh] = useState(false);
+ const botIds = useMemo(() => (rosterFresh ? new Set(kwants.map((k) => k.id)) : null), [kwants, rosterFresh]);
const [channels, setChannels] = useState<Channel[]>([]);
const [teams, setTeams] = useState<Team[]>([]);
const [selectedId, setSelectedId] = useState<string>('');
@@ -310,6 +314,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
]);
if (seq !== rosterSeqRef.current || !Array.isArray(kRes)) return;
setKwants(kRes);
+ setRosterFresh(true);
// The space header counts bots too.
onSpacesChangedRef.current();
if (Array.isArray(tRes)) {
@@ -481,6 +486,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}));
setKwants(kRes);
+ if (Array.isArray(kRes)) setRosterFresh(true);
setChannels(cRes);
setTeams(normalizedTeams);
@@ -612,7 +618,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
try {
const event = JSON.parse(e.data);
if (affectsAway(event.type)) refreshAwayCount(800);
- if (changesBots(event.type, event.data)) refreshRoster();
+ if (changesBots(event.type, event.data)) {
+ setRosterFresh(false);
+ refreshRoster();
+ }
switch (event.type) {
case 'turn_queued':
case 'TurnQueued':
@@ -1469,6 +1478,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
} catch (err) {
// Already decided elsewhere: pick up the real state so the card stops offering the button.
if (err instanceof ApiError && err.status === 409) {
+ // "The bot no longer exists": the bot list drops it and the card settles.
+ setRosterFresh(false);
+ refreshRoster();
botActionsApi
.list()
.then((list) => setBotActions((prev) => list.reduce((m, a) => applyBotAction(m, a), prev)))
@@ -1495,7 +1507,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
window.dispatchEvent(new Event('kwnt:hire-updated'));
playSfx('click');
} catch (err) {
- if (err instanceof ApiError && err.status === 409) refreshHires();
+ if (err instanceof ApiError && err.status === 409) {
+ refreshHires();
+ setRosterFresh(false);
+ refreshRoster();
+ }
return decisionError(err, d === 'deny' ? 'say no' : d === 'undo' ? 'undo the hire' : 'hire it');
}
};
@@ -1511,6 +1527,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onDecide={handleBotActionDecision}
onOpenRoutine={handleOpenRoutine}
flash={flash}
+ botIds={botIds}
/>
);
};
@@ -1525,6 +1542,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
live={hires[meta.hire_id]}
onDecide={handleHireDecision}
flash={flash}
+ botIds={botIds}
/>
);
};
diff --git a/frontend/src/botActions.ts b/frontend/src/botActions.ts
index 7d90dfd7..26612da8 100644
--- a/frontend/src/botActions.ts
+++ b/frontend/src/botActions.ts
@@ -106,8 +106,29 @@ export const actionVerb = (action: string) => VERBS[action] ?? 'changed somethin
/** "Coach set up a routine": the card's heading. */
export const actionHeading = (botName: string, action: string) => `${botName} ${actionVerb(action)}`;
-/** The state line in plain words. Never "Done" once the change was undone or declined. */
-export function actionStateText(m: Pick<BotActionMeta, 'status' | 'action'>): { label: string; tone: 'ok' | 'wait' | 'off' } {
+const BOT_ACTIONS_WITH_UNDO = ['bot_create', 'bot_update', 'bot_hire'];
+
+/**
+ * The bot an applied card made or changed no longer exists (deleted since, here or elsewhere), so
+ * there's nothing left to undo. `botIds` is null until the bot list has loaded: never guess then.
+ */
+export function botGone(m: Pick<BotActionMeta, 'status' | 'action' | 'target_kind' | 'target_id'>, botIds: ReadonlySet<string> | null): boolean {
+ return !!botIds && m.status === 'applied' && m.target_kind === 'bot' && BOT_ACTIONS_WITH_UNDO.includes(m.action) && !!m.target_id && !botIds.has(m.target_id);
+}
+
+/** An accepted hire whose bot has since been deleted. */
+export function hiredBotGone(h: Pick<HireMeta, 'status' | 'hired_kwant_id'>, botIds: ReadonlySet<string> | null): boolean {
+ return !!botIds && (h.status === 'accepted' || h.status === 'auto_accepted') && !!h.hired_kwant_id && !botIds.has(h.hired_kwant_id);
+}
+
+/** The state line in plain words. Never "Done" once the change was undone or declined, or its bot is gone. */
+export function actionStateText(m: Pick<BotActionMeta, 'status' | 'action'> & Partial<Pick<BotActionMeta, 'details'>>, gone = false): { label: string; tone: 'ok' | 'wait' | 'off' } {
+ if (gone) {
+ const name = str(m.details?.name);
+ if (m.action === 'bot_create') return { label: name ? `Created ${name}. It’s since been deleted.` : 'Created. The bot has since been deleted.', tone: 'off' };
+ if (m.action === 'bot_hire') return { label: name ? `Hired ${name}. It’s since been deleted.` : 'Hired. The bot has since been deleted.', tone: 'off' };
+ return { label: name ? `Done. ${name} has since been deleted.` : 'Done. The bot has since been deleted.', tone: 'off' };
+ }
switch (m.status) {
case 'pending':
return { label: 'Needs your OK. Nothing changes until you confirm.', tone: 'wait' };
@@ -316,7 +337,8 @@ export function evidenceText(e: HireEvidence | null, requestedByPerson: boolean)
/** "auto" or empty means the app picks; anything else is shown as is. */
export const modelText = (model: string | null) => (!model || model === 'auto' ? 'Picked automatically' : model);
-export function hireStateText(h: Pick<HireMeta, 'status' | 'name' | 'team' | 'proposer_name'>): { label: string; tone: 'ok' | 'wait' | 'off' } {
+export function hireStateText(h: Pick<HireMeta, 'status' | 'name' | 'team' | 'proposer_name'>, gone = false): { label: string; tone: 'ok' | 'wait' | 'off' } {
+ if (gone) return { label: `Hired ${h.name}. It’s since been deleted.`, tone: 'off' };
switch (h.status) {
case 'accepted':
return { label: `Hired. ${h.name} ${h.team ? `joined ${h.team.name}` : 'is ready'}.`, tone: 'ok' };
@@ -427,13 +449,14 @@ export const hiresApi = {
export function changesBots(type: string, data: unknown): boolean {
const d = data && typeof data === 'object' ? (data as Record<string, unknown>) : null;
if (!d) return false;
- if (type === 'bot_action_updated' || type === 'BotActionUpdated') {
- const card = parseBotActionMeta((d.action as BotAction | undefined)?.card);
- return !!card && card.target_kind === 'bot' && ['applied', 'undone', 'confirmed'].includes(card.status);
- }
- if (type === 'hire_updated' || type === 'HireUpdated') {
- const card = parseHireMeta((d.hire as Hire | undefined)?.card);
- return !!card && ['accepted', 'auto_accepted', 'undone'].includes(card.status);
+ const action = (card: BotActionMeta | null) => !!card && card.target_kind === 'bot' && ['applied', 'undone', 'confirmed'].includes(card.status);
+ const hire = (card: HireMeta | null) => !!card && ['accepted', 'auto_accepted', 'undone'].includes(card.status);
+ if (type === 'bot_action_updated' || type === 'BotActionUpdated') return action(parseBotActionMeta((d.action as BotAction | undefined)?.card));
+ if (type === 'hire_updated' || type === 'HireUpdated') return hire(parseHireMeta((d.hire as Hire | undefined)?.card));
+ // A card can land before its update event; until the list is fetched again it can't be judged.
+ if (type === 'message_added' || type === 'MessageAdded') {
+ const meta = (d.message as { meta?: unknown } | undefined)?.meta;
+ return action(parseBotActionMeta(meta)) || hire(parseHireMeta(meta));
}
return false;
}
diff --git a/frontend/src/components/BotActionCard.tsx b/frontend/src/components/BotActionCard.tsx
index b44bc799..18d851ab 100644
--- a/frontend/src/components/BotActionCard.tsx
+++ b/frontend/src/components/BotActionCard.tsx
@@ -1,7 +1,7 @@
import React, { useState } from 'react';
import { AlertTriangle, CalendarClock, CheckCircle2, Loader2, MinusCircle, Pause, Pencil, ShieldQuestion, Undo2, Wrench } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
-import { BotActionMeta, actionStateText, actionVerb, botActionView, routineButtons, routineFacts, sentence } from '../botActions';
+import { BotActionMeta, actionStateText, botGone, actionVerb, botActionView, routineButtons, routineFacts, sentence } from '../botActions';
export type BotActionDecision = 'undo' | 'confirm' | 'decline';
@@ -17,6 +17,8 @@ export interface BotActionCardProps {
/** Opens Space settings → Routines at this routine. */
onOpenRoutine?: (routineId: string, mode: 'edit' | 'pause') => void;
flash?: boolean;
+ /** Ids of the bots that exist now; null until loaded. A card whose bot is gone settles. */
+ botIds?: ReadonlySet<string> | null;
}
const btn =
@@ -28,8 +30,11 @@ const quiet = `${btn} text-zinc-200 border border-zinc-700 hover:bg-zinc-800 foc
* the routine's facts when it's a routine, and the person's buttons (Undo, or Confirm/Decline).
* Once resolved it says so plainly, so an undone change never still reads "Done".
*/
-export const BotActionCard: React.FC<BotActionCardProps> = ({ meta, messageId, kwantName, kwantId, live, onDecide, onOpenRoutine, flash }) => {
- const view = botActionView(meta, live);
+export const BotActionCard: React.FC<BotActionCardProps> = ({ meta, messageId, kwantName, kwantId, live, onDecide, onOpenRoutine, flash, botIds = null }) => {
+ const shown = botActionView(meta, live);
+ const gone = botGone(shown, botIds);
+ // Nothing to undo once the bot it made or changed is deleted.
+ const view = gone ? { ...shown, can_undo: false } : shown;
const [busy, setBusy] = useState<BotActionDecision | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -43,13 +48,13 @@ export const BotActionCard: React.FC<BotActionCardProps> = ({ meta, messageId, k
};
const headingId = `bot-action-${messageId}`;
- const state = actionStateText(view);
+ const state = actionStateText(view, gone);
const facts = routineFacts(view);
const { edit, pause } = routineButtons(view);
const reason = view.status === 'pending' && typeof view.details.reason === 'string' ? view.details.reason : '';
const isRoutine = view.target_kind === 'routine';
const resolved = view.status === 'undone' || view.status === 'declined';
- const border = view.status === 'pending' ? 'border-amber-500/40' : resolved ? 'border-zinc-800' : 'border-emerald-500/25';
+ const border = view.status === 'pending' ? 'border-amber-500/40' : resolved || gone ? 'border-zinc-800' : 'border-emerald-500/25';
const Icon = view.status === 'pending' ? ShieldQuestion : isRoutine ? CalendarClock : Wrench;
return (
diff --git a/frontend/src/components/HireCard.tsx b/frontend/src/components/HireCard.tsx
index d36b0535..c4bc3645 100644
--- a/frontend/src/components/HireCard.tsx
+++ b/frontend/src/components/HireCard.tsx
@@ -1,7 +1,7 @@
import React, { useId, useState } from 'react';
import { AlertTriangle, CheckCircle2, ChevronDown, ChevronRight, Loader2, MinusCircle, Undo2, UserPlus } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
-import { HireMeta, evidenceText, hireStateText, hireView, modelText } from '../botActions';
+import { HireMeta, evidenceText, hireStateText, hireView, hiredBotGone, modelText } from '../botActions';
export type HireDecision = 'deny' | 'accept_once' | 'always_accept' | 'undo';
@@ -15,6 +15,8 @@ export interface HireCardProps {
/** Resolves to an error message on failure. */
onDecide: (hire: HireMeta, decision: HireDecision) => Promise<string | void>;
flash?: boolean;
+ /** Ids of the bots that exist now; null until loaded. A hire whose bot is gone settles. */
+ botIds?: ReadonlySet<string> | null;
}
const btn =
@@ -26,8 +28,11 @@ const spin = <Loader2 size={13} className="animate-spin motion-reduce:animate-no
* A bot's proposal to hire a new bot: who it would be, which team it joins, why, and what that
* rests on. The person denies, accepts once or always accepts; an accepted hire can be undone.
*/
-export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName, kwantId, live, onDecide, flash }) => {
- const view = hireView(meta, live);
+export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName, kwantId, live, onDecide, flash, botIds = null }) => {
+ const shown = hireView(meta, live);
+ const gone = hiredBotGone(shown, botIds);
+ // Nothing to undo once the hired bot is deleted.
+ const view = gone ? { ...shown, can_undo: false } : shown;
const [busy, setBusy] = useState<HireDecision | null>(null);
const [error, setError] = useState<string | null>(null);
const [showInstructions, setShowInstructions] = useState(false);
@@ -44,9 +49,9 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
const headingId = `hire-${messageId}`;
const proposer = view.proposer_name || kwantName;
- const state = hireStateText({ ...view, proposer_name: proposer });
+ const state = hireStateText({ ...view, proposer_name: proposer }, gone);
const pending = view.status === 'pending';
- const done = view.status === 'denied' || view.status === 'undone';
+ const done = view.status === 'denied' || view.status === 'undone' || gone;
const evidence = evidenceText(view.evidence, view.requested_by_person);
const border = pending ? 'border-violet-500/40' : done ? 'border-zinc-800' : 'border-emerald-500/25';
const can = (c: string) => pending && view.choices.includes(c);
diff --git a/frontend/tests/botActions.test.mjs b/frontend/tests/botActions.test.mjs
index 743646dc..9d92cbdf 100644
--- a/frontend/tests/botActions.test.mjs
+++ b/frontend/tests/botActions.test.mjs
@@ -294,5 +294,40 @@ test('bot and hire events that add or remove a bot ask the sidebar to reload', (
assert.equal(b.changesBots('hire_updated', { hire: hireEv('pending') }), false);
assert.equal(b.changesBots('hire_updated', { hire: hireEv('denied') }), false);
assert.equal(b.changesBots('message_added', { message: {} }), false);
+ // A new bot's card can arrive before its update event: the list is reloaded for it too.
+ assert.equal(b.changesBots('message_added', { message: { meta: routineMeta({ action: 'bot_create', target_kind: 'bot', target_id: 'k2' }) } }), true);
+ assert.equal(b.changesBots('MessageAdded', { message: { meta: hireEv('accepted').card } }), true);
+ assert.equal(b.changesBots('message_added', { message: { meta: routineMeta() } }), false);
assert.equal(b.changesBots('hire_updated', null), false);
});
+
+test('a card whose bot has since been deleted settles: no Undo, says so', () => {
+ const created = routineMeta({
+ action: 'bot_create', target_kind: 'bot', target_id: 'k7', summary: 'created bot Chef (Cook), model auto',
+ details: { id: 'k7', name: 'Chef', title: 'Cook', model: 'auto' },
+ });
+ // The bot is still there, or the list hasn't loaded yet: Done with Undo.
+ for (const botIds of [new Set(['k1', 'k7']), null, undefined]) {
+ const html = ui.action(actionProps(created, { botIds }));
+ assert.match(text(html), /Done\./);
+ assert.deepEqual(buttons(html), ['Undo']);
+ }
+ // Deleted since: settled, no Undo, never "Done".
+ const html = ui.action(actionProps(created, { botIds: new Set(['k1']) }));
+ assert.match(text(html), /Created Chef\. It's since been deleted\./);
+ assert.doesNotMatch(text(html), /Done/);
+ assert.deepEqual(buttons(html), []);
+ // An undone or still-pending card keeps its own state; routines are never "gone" bots.
+ const meta = b.parseBotActionMeta(created);
+ assert.equal(b.botGone({ ...meta, status: 'undone' }, new Set()), false);
+ assert.equal(b.botGone(b.parseBotActionMeta(routineMeta()), new Set()), false);
+ assert.equal(b.botGone(meta, new Set()), true);
+ assert.equal(b.botGone(meta, null), false);
+
+ // Same for an accepted hire whose bot was deleted.
+ const hired = hireMeta({ status: 'accepted', choices: [], hired_kwant_id: 'k9', action_id: 'a9', can_undo: true });
+ assert.deepEqual(buttons(ui.hire(hireProps(hired, { botIds: new Set(['k9']) }))), ['Show its instructions', 'Undo']);
+ const gone = ui.hire(hireProps(hired, { botIds: new Set() }));
+ assert.match(text(gone), /Hired Ledger\. It's since been deleted\./);
+ assert.deepEqual(buttons(gone), ['Show its instructions']);
+});