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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Mission board: send held Review actions on page close; fold only routine runs
Pixel (kwant bot)1da6da901500
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2fde12c5..c510a235 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -61,6 +61,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).page; screen readers read it as "Made in Germany with love".### Fixed+- **A Review action survives closing the tab.** Mark verified, Send back or Dismiss on the Mission board+ waits 6 seconds for Undo. Closing, reloading or backgrounding the page in that window used to drop the+ action; now it is sent then, with `keepalive`, and still only once.+- **Only routine runs fold on the Review column.** Worked-ahead and loose-end cards with the same title+ can be different work, so they stay separate cards and "Dismiss N older" never covers them.- **A hand-off card the lead reviewed no longer loses its fixed result.** When the lead's review sentwork back and the lead's earlier results turn ran late, that turn put the card back in Review while theteammate was still fixing it, and the fix's result was never attached. The lead's turn now also makes adiff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsxindex e2c8fc0f..edae9dc6 100644--- a/frontend/src/components/MissionBoardView.tsx+++ b/frontend/src/components/MissionBoardView.tsx@@ -49,6 +49,8 @@ import {QUICK_LABELS,QuickAction,UNDO_MS,+ HeldActionSlot,+ flushOnPageLeave,collapseRepeats,elapsedText,filterByTeams,@@ -3327,42 +3329,49 @@ export const MissionBoardPage: React.FC<{const [groupBy, setGroupBy] = useState<GroupBy>(readGroupBy);const [teamFilter, setTeamFilter] = useState<string[]>([]);const [undo, setUndo] = useState<{ id: number; text: string } | null>(null);- const pending = useRef<{ id: number; tasks: Task[]; run: () => Promise<void>; timer: number } | null>(null);+ const pending = useRef(new HeldActionSlot()).current;const [hidden, setHidden] = useState<Set<string>>(() => new Set());const pendingSeq = useRef(0);- const commitPending = useCallback(() => {- const p = pending.current;- if (!p) return;- pending.current = null;- window.clearTimeout(p.timer);- if (alive.current) setUndo((u) => (u?.id === p.id ? null : u));- p.run().finally(() => {- if (!alive.current) return;- setHidden((h) => {- const next = new Set(h);- p.tasks.forEach((t) => next.delete(t.id));- return next;+ const commitPending = useCallback(+ (leaving = false) => {+ const c = pending.commit(leaving);+ if (!c) return;+ const p = c.action;+ if (alive.current) setUndo((u) => (u?.id === p.id ? null : u));+ c.sent.finally(() => {+ if (!alive.current) return;+ setHidden((h) => {+ const next = new Set(h);+ p.tasks.forEach((t) => next.delete(t.id));+ return next;+ });});- });- }, []);+ },+ [pending],+ );- // Leaving the board sends what's still waiting: the person saw it done.+ // Leaving the board, or closing or backgrounding the page, sends what's still waiting: the person+ // saw it done.useEffect(() => () => commitPending(), [commitPending]);+ useEffect(() => flushOnPageLeave(() => commitPending(true)), [commitPending]);- const runCardActions = useCallback(async (list: Task[], a: QuickAction, note?: string) => {+ const runCardActions = useCallback(async (list: Task[], a: QuickAction, note: string | undefined, leaving: boolean) => {let failed = 0;let lastError = '';- for (const t of list) {+ const one = async (t: Task) => {try {- const next = await missionsApi.act(t.id, a, a === 'reject' ? note?.trim() || DEFAULT_SEND_BACK : undefined);+ const next = await missionsApi.act(t.id, a, a === 'reject' ? note?.trim() || DEFAULT_SEND_BACK : undefined, leaving);if (alive.current) setTasks((l) => (l ? (next.state === 'cancelled' ? l.filter((x) => x.id !== next.id) : upsertTask(l, next)) : l));} catch (e) {failed++;lastError = failMsg(e);if (e instanceof MissionError && e.status === 401 && alive.current) setNeedsToken(true);}- }+ };+ // A closing page won't wait for one request to finish before the next starts, so all go at once.+ if (leaving) await Promise.all(list.map(one));+ else for (const t of list) await one(t);if (!alive.current) return;if (failed) setNotice({ text: list.length === 1 ? `Couldn’t do that: ${lastError}` : `${failed} of ${list.length} didn’t go through: ${lastError}`, error: true });else if (a === 'verify') playSfx('coin');@@ -3379,17 +3388,15 @@ export const MissionBoardPage: React.FC<{return next;});const timer = window.setTimeout(() => commitPending(), UNDO_MS);- pending.current = { id, tasks: list, run: () => runCardActions(list, a, note), timer };+ pending.hold({ id, tasks: list, send: (leaving) => runCardActions(list, a, note, leaving), timer });setUndo({ id, text: quickDoneText(a, list.length, list[0]?.title) });setNotice(null);playSfx('click');};const undoPending = () => {- const p = pending.current;+ const p = pending.take();if (!p) return setUndo(null);- pending.current = null;- window.clearTimeout(p.timer);setUndo(null);setHidden((h) => {const next = new Set(h);@@ -3468,7 +3475,7 @@ export const MissionBoardPage: React.FC<{onClearOld={(ts) => queueCardAction(ts, 'cancel')}undo={undo}onUndo={undoPending}- onCloseUndo={commitPending}+ onCloseUndo={() => commitPending()}/>{openId && (<TaskPanel title={detail?.task.title ?? listed?.title ?? 'Task'} onClose={closeTask}>diff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex ca961dfd..f92b036d 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -1530,7 +1530,7 @@ export function errorFrom(status: number, answer: unknown): MissionError {return new MissionError(err ?? `Something went wrong (HTTP ${status}).`, status, code);}-async function call<T>(url: string, method = 'GET', body?: unknown, extra?: Record<string, string>): Promise<T> {+async function call<T>(url: string, method = 'GET', body?: unknown, extra?: Record<string, string>, keepalive = false): Promise<T> {let res: Response;const headers = { ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...extra };try {@@ -1539,6 +1539,7 @@ async function call<T>(url: string, method = 'GET', body?: unknown, extra?: Recocache: 'no-store',headers: Object.keys(headers).length ? headers : undefined,body: body === undefined ? undefined : JSON.stringify(body),+ ...(keepalive ? { keepalive: true } : {}),});} catch (e) {if (e instanceof PersonCancelledError) throw new MissionError(e.message, 401);@@ -1600,20 +1601,23 @@ export const missionsApi = {resolveRisk: (id: string, riskId: string, resolution: RiskResolution, note?: string) =>call<{ risk: Risk; unresolved: boolean }>(`/api/tasks/${enc(id)}/risks/${enc(riskId)}/resolve`, 'POST', note ? { resolution, note } : { resolution }),decideChange: (id: string, approve: boolean) => call<WorkflowChange>(`/api/workflow-changes/${enc(id)}/${approve ? 'approve' : 'reject'}`, 'POST', {}),- /** One person action on a task. `run_checks` answers `{checks, task}`, the others the Task. */- act: async (id: string, action: TaskAction, reason?: string): Promise<Task> => {+ /**+ * One person action on a task. `run_checks` answers `{checks, task}`, the others the Task.+ * `keepalive` lets the request finish after the page closes.+ */+ act: async (id: string, action: TaskAction, reason?: string, keepalive = false): Promise<Task> => {const base = `/api/tasks/${enc(id)}`;switch (action) {case 'verify':- return call<Task>(`${base}/verify`, 'POST', reason ? { note: reason } : {});+ return call<Task>(`${base}/verify`, 'POST', reason ? { note: reason } : {}, undefined, keepalive);case 'reject':- return call<Task>(`${base}/reject`, 'POST', { reason: reason ?? '' });+ return call<Task>(`${base}/reject`, 'POST', { reason: reason ?? '' }, undefined, keepalive);case 'block':- return call<Task>(`${base}/block`, 'POST', { reason: reason ?? '' });+ return call<Task>(`${base}/block`, 'POST', { reason: reason ?? '' }, undefined, keepalive);case 'run_checks':- return call<{ task: Task }>(`${base}/checks/run`, 'POST', {}).then((r) => r.task);+ return call<{ task: Task }>(`${base}/checks/run`, 'POST', {}, undefined, keepalive).then((r) => r.task);default:- return call<Task>(`${base}/${action}`, 'POST', {});+ return call<Task>(`${base}/${action}`, 'POST', {}, undefined, keepalive);}},};@@ -1697,27 +1701,28 @@ export function teamOfBots(teams: BoardTeam[]): Record<string, BoardTeam> {/** The bot a card belongs to: its owner, else the bot holding it. */export const taskBot = (t: Pick<Task, 'owner_kwant_id' | 'claim'>): string | null => t.owner_kwant_id ?? t.claim?.kwant_id ?? null;-/** Sources the person didn't ask for one by one: they pile up, so they fold and can be cleared in bulk. */+/** Sources the person didn't ask for one by one: they pile up, so they can be cleared in bulk. */const AUTO_SOURCES = new Set<SourceKind>(['routine', 'work_ahead', 'zombie']);export const isAutoTask = (t: Pick<Task, 'source_kind'>): boolean => AUTO_SOURCES.has(t.source_kind);-/** One card on the board: the newest task, and older repeats of the same routine folded under it. */+/** One card on the board: the newest task, and older runs of the same routine folded under it. */export interface BoardItem {task: Task;older: Task[];}/**- * What makes two cards "the same run again": the same automatic source, bot and title. A routine- * card's source is its run, not the routine, so its title ("Routine: Morning overview") stands in.+ * What makes two cards "the same run again": a routine run by the same bot with the same title. A+ * routine card's source is its run, not the routine, so its title ("Routine: Morning overview")+ * stands in. Worked-ahead and loose-end cards never fold: the same title can be different work.*/export function repeatKey(t: Task): string | null {- if (!isAutoTask(t)) return null;- return `${t.source_kind}:${taskBot(t) ?? ''}:${t.title.trim().toLowerCase()}`;+ if (t.source_kind !== 'routine') return null;+ return `routine:${taskBot(t) ?? ''}:${t.title.trim().toLowerCase()}`;}/**- * Folds repeated automatic runs into one card, newest first, keeping the input's order otherwise.+ * Folds repeated routine runs into one card, newest first, keeping the input's order otherwise.* Only cards in the same column fold together, so callers pass one column's tasks.*/export function collapseRepeats(tasks: Task[]): BoardItem[] {@@ -1968,3 +1973,63 @@ export function quickDoneText(a: QuickAction, n: number, title?: string): string/** How long Undo stays on screen before the action goes to the server. */export const UNDO_MS = 6000;++/** A card action waiting out its Undo window. `send(leaving)` is told when the page is going away. */+export interface HeldAction {+ id: number;+ tasks: Task[];+ send: (leaving: boolean) => Promise<void>;+ timer: number;+}++/**+ * Holds at most one card action. Taking it out is the only way to send it, so an action goes once:+ * the timer, the next action, Undo, leaving the board and the page closing all race for the same one.+ */+export class HeldActionSlot {+ private held: HeldAction | null = null;+ constructor(private clearTimer: (t: number) => void = (t) => clearTimeout(t)) {}++ get current(): HeldAction | null {+ return this.held;+ }++ hold(a: HeldAction): void {+ this.held = a;+ }++ /** Takes the action out and stops its timer, without sending it. */+ take(): HeldAction | null {+ const a = this.held;+ if (!a) return null;+ this.held = null;+ this.clearTimer(a.timer);+ return a;+ }++ /** Sends the held action now, if there is one. */+ commit(leaving = false): { action: HeldAction; sent: Promise<void> } | null {+ const a = this.take();+ return a ? { action: a, sent: a.send(leaving) } : null;+ }+}++/**+ * Sends a held action when the page is closed, reloaded or put in the background (a phone's app+ * switcher often never fires pagehide). Returns the cleanup.+ */+export function flushOnPageLeave(+ flush: () => void,+ win: Pick<EventTarget, 'addEventListener' | 'removeEventListener'> = window,+ doc: Pick<EventTarget, 'addEventListener' | 'removeEventListener'> & { visibilityState: string } = document,+): () => void {+ const onHide = () => {+ if (doc.visibilityState === 'hidden') flush();+ };+ win.addEventListener('pagehide', flush);+ doc.addEventListener('visibilitychange', onHide);+ return () => {+ win.removeEventListener('pagehide', flush);+ doc.removeEventListener('visibilitychange', onHide);+ };+}diff --git a/frontend/tests/missionBoardLive.test.mjs b/frontend/tests/missionBoardLive.test.mjsindex 8d17f09a..398b94f1 100644--- a/frontend/tests/missionBoardLive.test.mjs+++ b/frontend/tests/missionBoardLive.test.mjs@@ -72,12 +72,24 @@ test('work the person asked for never folds, even with the same title', () => {assert.equal(m.repeatKey(task({ source_kind: 'delegation' })), null);});-test('worked-ahead and loose-end cards fold by bot and title (case and spaces ignored)', () => {- const a = task({ source_kind: 'work_ahead', title: 'Worked ahead: API Error 529', state: 'review' });- const b = task({ source_kind: 'work_ahead', title: ' worked ahead: api error 529 ', state: 'review' });+test('routine runs fold by bot and title with case and spaces ignored', () => {+ const a = routineRun(3);+ const b = routineRun(5, { title: ' routine: MORNING overview ' });assert.equal(m.collapseRepeats([a, b]).length, 1);});+test('worked-ahead and loose-end cards never fold, even with identical titles: they can be different work', () => {+ const ahead = (over) => task({ source_kind: 'work_ahead', title: 'Worked ahead: API Error 529', state: 'review', owner_kwant_id: 'k_tw', ...over });+ const loose = (over) => task({ source_kind: 'zombie', title: 'Loose end: reply to Maya', state: 'review', owner_kwant_id: 'k_tw', ...over });+ const cards = [ahead({ source_id: 'w1' }), ahead({ source_id: 'w2' }), loose({ source_id: 'z1' }), loose({ source_id: 'z2' })];+ const items = m.collapseRepeats(cards);+ assert.equal(items.length, 4);+ assert.ok(items.every((i) => i.older.length === 0), 'nothing folded under them, so "Dismiss N older" never covers them');+ for (const c of cards) assert.equal(m.repeatKey(c), null);+ const html = ui.card({ task: cards[0], names, now: NOW, older: m.collapseRepeats(cards)[0].older, onQuick: noop, onDismissMany: noop });+ assert.doesNotMatch(html, /older/i);+});+// ---------- Verified fades out ----------test('Verified keeps the last 24 hours; older cards wait behind Show older, none deleted', () => {@@ -323,3 +335,89 @@ test('without live data the view stays as before: no strip, no toolbar', () => {assert.doesNotMatch(html, /Live now/);assert.doesNotMatch(html, /data-board-toolbar/);});++// ---------- A held action is sent exactly once ----------++const held = (sent, over = {}) => ({ id: 1, tasks: [task()], timer: 7, send: (leaving) => (sent.push(leaving), Promise.resolve()), ...over });++test('a held action is sent once, however many flushes race for it', async () => {+ const sent = [];+ const cleared = [];+ const slot = new m.HeldActionSlot((t) => cleared.push(t));+ slot.hold(held(sent));+ const first = slot.commit(true);+ assert.ok(first);+ await first.sent;+ assert.equal(slot.commit(true), null, 'pagehide after visibilitychange finds nothing');+ assert.equal(slot.commit(), null, 'the Undo timer firing late finds nothing');+ assert.equal(slot.take(), null, 'Undo after it went finds nothing');+ assert.deepEqual(sent, [true]);+ assert.deepEqual(cleared, [7], 'its timer is stopped');+});++test('Undo drops the held action: nothing is sent', () => {+ const sent = [];+ const slot = new m.HeldActionSlot(noop);+ slot.hold(held(sent));+ assert.equal(slot.take()?.id, 1);+ assert.equal(slot.commit(true), null);+ assert.deepEqual(sent, []);+});++const fakePage = () => {+ const win = new EventTarget();+ const doc = new EventTarget();+ doc.visibilityState = 'visible';+ return { win, doc };+};++test('closing the page sends the held action once, with keepalive', () => {+ const sent = [];+ const slot = new m.HeldActionSlot(noop);+ const { win, doc } = fakePage();+ const stop = m.flushOnPageLeave(() => slot.commit(true), win, doc);+ slot.hold(held(sent));+ // A phone closing a tab: hidden first, then pagehide.+ doc.visibilityState = 'hidden';+ doc.dispatchEvent(new Event('visibilitychange'));+ win.dispatchEvent(new Event('pagehide'));+ assert.deepEqual(sent, [true]);+ stop();+});++test('pagehide alone sends it; becoming visible again does not', () => {+ const sent = [];+ const slot = new m.HeldActionSlot(noop);+ const { win, doc } = fakePage();+ const stop = m.flushOnPageLeave(() => slot.commit(true), win, doc);+ slot.hold(held(sent));+ doc.dispatchEvent(new Event('visibilitychange'));+ assert.deepEqual(sent, [], 'still visible: keep waiting');+ win.dispatchEvent(new Event('pagehide'));+ assert.deepEqual(sent, [true]);+ stop();+ slot.hold(held(sent, { id: 2 }));+ win.dispatchEvent(new Event('pagehide'));+ assert.deepEqual(sent, [true], 'after cleanup the page no longer flushes');+});++test('card actions can ask for keepalive, so they finish after the page closes', async () => {+ const seen = [];+ const real = globalThis.fetch;+ globalThis.fetch = async (url, init) => {+ seen.push({ url, keepalive: init?.keepalive === true });+ return new Response(JSON.stringify(task({ state: 'verified' })), { status: 200 });+ };+ try {+ await m.missionsApi.act('t1', 'verify', undefined, true);+ await m.missionsApi.act('t1', 'cancel', undefined, true);+ await m.missionsApi.act('t1', 'reject', 'nope');+ } finally {+ globalThis.fetch = real;+ }+ assert.deepEqual(seen, [+ { url: '/api/tasks/t1/verify', keepalive: true },+ { url: '/api/tasks/t1/cancel', keepalive: true },+ { url: '/api/tasks/t1/reject', keepalive: false },+ ]);+});