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.

frontend: "While you were away" page and sidebar badge (batch3)

Lin (kwant bot)f319fb5ead96
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index af7b4bec..fa465cab 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -5,6 +5,7 @@ import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } fro
import { ThreadBar, ThreadHeader } from './components/ThreadBar';
import { DelegationCard } from './components/DelegationCard';
import { QuestionCard } from './components/QuestionCard';
+import { AwayPage } from './components/AwayView';
import { HelpCircle, ListChecks, Loader2 } from 'lucide-react';
import { PendingApproval } from './components/ModernApprovalCard';
import type { AgentFormData } from './components/NewAgentModal';
@@ -57,6 +58,7 @@ import {
questionsApi,
turnsAwaitingAnswer,
} from './questions';
+import { AwayItem, affectsAway, awayApi, awayTarget } from './away';
// 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.
@@ -144,6 +146,17 @@ export const App: React.FC = () => {
const [historyWindow, setHistoryWindow] = useState<{ ctx: string; messages: ChatMessage[] } | null>(null);
const [profiles, setProfiles] = useState<Profile[]>([]);
const [toasts, setToasts] = useState<Toast[]>([]);
+ // "While you were away": open instead of a chat, and its unseen count for the sidebar badge.
+ const [showAway, setShowAway] = useState(false);
+ const [awayCount, setAwayCount] = useState(0);
+ const awaySinceRef = useRef<string | null>(null);
+ const awayTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const refreshAwayCount = (delay = 0) => {
+ clearTimeout(awayTimerRef.current);
+ awayTimerRef.current = setTimeout(() => {
+ awayApi.get().then((r) => setAwayCount(r.unseen.total), () => undefined);
+ }, delay);
+ };
const toastIdRef = useRef(0);
const dismissToast = useCallback((id: number) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);
// Set each render once the select handlers exist; the SSE handler and notification clicks go through it.
@@ -256,6 +269,7 @@ export const App: React.FC = () => {
/** Running turns after a (re)connect; chats whose reply ended meanwhile stop spinning. */
const hydrateFromServer = async () => {
skillsApi.list({ status: 'pending' }).then(setPendingSkills, () => undefined);
+ refreshAwayCount();
questionsApi.listOpen().then((list) => {
// Closed ones seen live stay; open ones come from the server.
setQuestions((prev) => {
@@ -446,6 +460,7 @@ export const App: React.FC = () => {
sse.onmessage = (e) => {
try {
const event = JSON.parse(e.data);
+ if (affectsAway(event.type)) refreshAwayCount(800);
switch (event.type) {
case 'turn_queued':
case 'TurnQueued':
@@ -942,6 +957,7 @@ export const App: React.FC = () => {
const handleSelectTeam = (team: Team) => {
setOpenThreadId(null);
+ setShowAway(false);
setSelectedTeamId(team.id);
const targetChannel = channels.find(
(c) => c.name === `team-${team.name}` || c.id === team.id
@@ -980,6 +996,7 @@ export const App: React.FC = () => {
const handleSelectChannel = (channel: Channel) => {
setOpenThreadId(null);
+ setShowAway(false);
setSelectedId(channel.id);
selectedIdRef.current = channel.id;
setIsChannel(true);
@@ -994,6 +1011,7 @@ export const App: React.FC = () => {
const handleSelectKwant = (kwant: Kwant) => {
setOpenThreadId(null);
+ setShowAway(false);
setSelectedId(kwant.id);
selectedIdRef.current = kwant.id;
setIsChannel(false);
@@ -1048,12 +1066,22 @@ export const App: React.FC = () => {
return;
}
knownThreadsRef.current.add(threadId);
+ setShowAway(false);
if (selectedIdRef.current !== kwant.id || isChannelRef.current) handleSelectKwant(kwant);
else playSfx('click');
setOpenThreadId(threadId);
if (threadsByKwantRef.current[kwantId] === undefined) loadThreads(kwantId);
};
+ /** Opens the thread, channel or direct chat an away item links to. */
+ const openAwayItem = (item: AwayItem) => {
+ const t = awayTarget(item);
+ if ('thread' in t) return openThread(t.kwant, t.thread);
+ const ok = 'channel' in t ? openTarget({ channel_id: t.channel, kwant_id: null }) : openTarget({ channel_id: null, kwant_id: t.direct });
+ if (!ok) return pushToast('That chat no longer exists.');
+ setShowAway(false);
+ };
+
const openDirectChat = () => {
if (!openThreadId) return;
setOpenThreadId(null);
@@ -1816,8 +1844,17 @@ export const App: React.FC = () => {
setIsNewTeamOpen(true);
playSfx('click');
}}
+ awayCount={awayCount}
+ awayActive={showAway}
+ onOpenAway={() => {
+ setShowAway(true);
+ playSfx('click');
+ }}
/>
+ {showAway ? (
+ <AwayPage since={awaySinceRef.current} onSince={(t) => (awaySinceRef.current = t)} onOpen={openAwayItem} onCounts={setAwayCount} />
+ ) : (
<ChatView
title={chatTitle}
subtitle={chatSubtitle}
@@ -1893,6 +1930,7 @@ export const App: React.FC = () => {
awaitingAnswer={awaitingHere}
contextKey={openCtx}
/>
+ )}
</div>
{/* New Agent Modal */}
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
new file mode 100644
index 00000000..cb764bb9
--- /dev/null
+++ b/frontend/src/away.ts
@@ -0,0 +1,175 @@
+// "While you were away" (batch 3): what agents need from you, finished and failed since you last
+// looked. Pure helpers, so the page and the node tests share them; the API calls are at the bottom.
+
+export type AwayKind = 'question' | 'approval' | 'delegation' | 'routine_run';
+export type AwaySection = 'waiting' | 'finished' | 'failed';
+export type ApprovalDecision = 'allow_once' | 'always_allow' | 'deny';
+
+export interface AwayLink {
+ thread_id: string | null;
+ channel_id: string | null;
+ direct_kwant_id: string | null;
+}
+
+export interface AwayItem {
+ kind: AwayKind;
+ id: string;
+ kwant_id: string;
+ kwant_name: string;
+ title: string;
+ summary: string;
+ status: string;
+ timestamp: string;
+ link: AwayLink;
+ /** Questions only. */
+ choices?: string[];
+}
+
+export interface AwayCounts {
+ waiting: number;
+ finished: number;
+ failed: number;
+ total: number;
+}
+
+export interface AwayResponse {
+ since: string;
+ last_seen: string | null;
+ now: string;
+ stuck_after_minutes: number;
+ waiting: AwayItem[];
+ finished: AwayItem[];
+ failed: AwayItem[];
+ unseen: AwayCounts;
+}
+
+export const AWAY_SECTIONS: { key: AwaySection; label: string; empty: string }[] = [
+ { key: 'waiting', label: 'Waiting on you', empty: 'No questions or approvals waiting.' },
+ { key: 'finished', label: 'Finished', empty: 'Nothing finished since you last looked.' },
+ { key: 'failed', label: 'Failed or stuck', empty: 'Nothing failed or stuck.' },
+];
+
+/** "just now", "5 min ago", "3 h ago", "yesterday", "4 days ago", else the date. */
+export function relativeTime(ts: string, now: number = Date.now()): string {
+ const t = Date.parse(ts);
+ if (Number.isNaN(t)) return '';
+ const s = Math.max(0, Math.round((now - t) / 1000));
+ if (s < 60) return 'just now';
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m} min ago`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h} h ago`;
+ const d = Math.floor(h / 24);
+ if (d === 1) return 'yesterday';
+ if (d < 7) return `${d} days ago`;
+ return new Date(t).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+/** Page subtitle: the 7-day default window, or since the last visit. */
+export function windowLabel(since: string, now: number = Date.now()): string {
+ const t = Date.parse(since);
+ if (Number.isNaN(t)) return '';
+ if (now - t >= 7 * 86400_000 - 60_000) return 'From the last 7 days';
+ return `Since you last looked, ${relativeTime(since, now)}`;
+}
+
+export type Tone = 'amber' | 'emerald' | 'rose' | 'zinc';
+
+/** Short label and colour for an item's kind and status. */
+export function itemLabel(item: Pick<AwayItem, 'kind' | 'status'>): { label: string; tone: Tone } {
+ switch (item.kind) {
+ case 'question':
+ return { label: 'Question', tone: 'amber' };
+ case 'approval':
+ return { label: 'Needs approval', tone: 'amber' };
+ case 'routine_run':
+ return item.status === 'ok' ? { label: 'Routine ran', tone: 'emerald' } : { label: 'Routine failed', tone: 'rose' };
+ case 'delegation':
+ switch (item.status) {
+ case 'completed':
+ return { label: 'Handoff done', tone: 'emerald' };
+ case 'stuck':
+ return { label: 'Stuck', tone: 'amber' };
+ case 'interrupted':
+ return { label: 'Interrupted', tone: 'rose' };
+ default:
+ return { label: 'Handoff failed', tone: 'rose' };
+ }
+ }
+ return { label: item.status, tone: 'zinc' };
+}
+
+/** Sidebar badge text: nothing at 0, "99+" past 99. */
+export const badgeText = (n: number): string => (n <= 0 ? '' : n > 99 ? '99+' : String(n));
+
+export const isAwayEmpty = (r: Pick<AwayResponse, AwaySection> | null): boolean =>
+ !!r && r.waiting.length === 0 && r.finished.length === 0 && r.failed.length === 0;
+
+/** Where clicking an item goes: exactly one of thread, channel or direct chat. */
+export type AwayTarget = { thread: string; kwant: string } | { channel: string } | { direct: string };
+
+export function awayTarget(item: Pick<AwayItem, 'kwant_id' | 'link'>): AwayTarget {
+ const l = item.link;
+ if (l.thread_id) return { thread: l.thread_id, kwant: item.kwant_id };
+ if (l.channel_id) return { channel: l.channel_id };
+ return { direct: l.direct_kwant_id || item.kwant_id };
+}
+
+/** Drops an acted-on item right away, before the refresh confirms it. */
+export function withoutItem(r: AwayResponse, section: AwaySection, id: string): AwayResponse {
+ const list = r[section].filter((i) => i.id !== id);
+ if (list.length === r[section].length) return r;
+ const dropped = section === 'waiting' ? 1 : 0;
+ return {
+ ...r,
+ [section]: list,
+ unseen: { ...r.unseen, waiting: Math.max(0, r.unseen.waiting - dropped), total: Math.max(0, r.unseen.total - dropped) },
+ };
+}
+
+/** The message for a failed one-tap action; a 409 means the request lapsed meanwhile. */
+export const actionErrorText = (status: number, fallback: string): string =>
+ status === 409 || status === 404 ? 'This request expired' : fallback;
+
+export class AwayError extends Error {
+ constructor(public status: number, message: string) {
+ super(message);
+ }
+}
+
+async function call<T>(method: string, url: string, body?: unknown): Promise<T> {
+ const res = await fetch(url, {
+ method,
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ if (!res.ok) {
+ let message = `Request failed (HTTP ${res.status}).`;
+ try {
+ const data = await res.json();
+ if (data && typeof data.error === 'string' && data.error) message = data.error;
+ } catch {
+ // no JSON body
+ }
+ throw new AwayError(res.status, message);
+ }
+ return res.json();
+}
+
+const enc = encodeURIComponent;
+
+export const awayApi = {
+ get: (since?: string) => call<AwayResponse>('GET', `/api/away${since ? `?since=${enc(since)}` : ''}`),
+ 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 }),
+};
+
+/** SSE events that can change what the page shows, so the badge re-counts. */
+const AWAY_EVENTS = new Set([
+ 'question_updated', 'QuestionUpdated',
+ 'delegation_updated', 'DelegationUpdated',
+ 'routine_run', 'RoutineRun',
+ 'ApprovalRequired', 'ApprovalWithdrawn',
+]);
+export const affectsAway = (type: unknown): boolean => typeof type === 'string' && AWAY_EVENTS.has(type);
diff --git a/frontend/src/components/AwayView.tsx b/frontend/src/components/AwayView.tsx
new file mode 100644
index 00000000..f5ba4932
--- /dev/null
+++ b/frontend/src/components/AwayView.tsx
@@ -0,0 +1,294 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { AlertTriangle, Check, CheckCheck, CheckCircle2, Inbox, Loader2, RefreshCw, X } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import {
+ AWAY_SECTIONS,
+ ApprovalDecision,
+ AwayError,
+ AwayItem,
+ AwayResponse,
+ AwaySection,
+ Tone,
+ actionErrorText,
+ awayApi,
+ isAwayEmpty,
+ itemLabel,
+ relativeTime,
+ windowLabel,
+ withoutItem,
+} from '../away';
+
+const TONES: Record<Tone, string> = {
+ amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',
+ emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200',
+ rose: 'border-rose-500/30 bg-rose-500/10 text-rose-200',
+ zinc: 'border-zinc-700 bg-zinc-800 text-zinc-300',
+};
+
+const SECTION_ICON: Record<AwaySection, React.ReactNode> = {
+ waiting: <Inbox size={13} className="text-amber-300" aria-hidden="true" />,
+ finished: <CheckCircle2 size={13} className="text-emerald-400" aria-hidden="true" />,
+ failed: <AlertTriangle size={13} className="text-rose-400" aria-hidden="true" />,
+};
+
+export interface AwayViewProps {
+ data: AwayResponse | null;
+ loading: boolean;
+ error: string | null;
+ /** Outcome of the last one-tap action (e.g. "This request expired"); the item may be gone by now. */
+ notice?: { text: string; error: boolean } | null;
+ /** Item id being acted on. */
+ busy?: string | null;
+ now?: number;
+ onRefresh: () => void;
+ onOpen: (item: AwayItem) => void;
+ onAnswer: (item: AwayItem, choice: number) => void;
+ onResolve: (item: AwayItem, decision: ApprovalDecision) => void;
+}
+
+const actionBtn =
+ 'inline-flex items-center gap-1.5 min-h-[36px] sm:min-h-[30px] px-3 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400';
+
+/** The "While you were away" page: what's waiting on you, what finished and what failed. */
+export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice = null, busy = null, now = Date.now(), onRefresh, onOpen, onAnswer, onResolve }) => {
+ const renderItem = (item: AwayItem) => {
+ const { label, tone } = itemLabel(item);
+ const when = relativeTime(item.timestamp, now);
+ const disabled = busy !== null;
+ return (
+ <li key={`${item.kind}:${item.id}`} className="rounded-xl border border-zinc-800 bg-zinc-900/60 hover:border-zinc-700 transition-colors">
+ <button
+ type="button"
+ onClick={() => onOpen(item)}
+ className="w-full flex items-start gap-3 p-3 text-left rounded-xl focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ aria-label={`${item.title}, ${label}, from ${item.kwant_name}, ${when}. Open the chat.`}
+ >
+ <ModernAvatar role={item.kwant_name} name={item.kwant_name} size={30} kwantId={item.kwant_id} />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 min-w-0 text-[11px]">
+ <span className="font-semibold text-zinc-200 truncate">{item.kwant_name}</span>
+ <span className={`shrink-0 px-1.5 py-px rounded-full border ${TONES[tone]}`}>{label}</span>
+ <time dateTime={item.timestamp} title={new Date(item.timestamp).toLocaleString()} className="ml-auto shrink-0 text-zinc-500">
+ {when}
+ </time>
+ </div>
+ <p className="mt-0.5 text-sm font-medium text-zinc-100 truncate">{item.title}</p>
+ {/* A question's summary just lists its choices, which are buttons below. */}
+ {item.summary && !(item.kind === 'question' && item.choices?.length) && <p className="text-xs text-zinc-400 truncate">{item.summary}</p>}
+ </div>
+ </button>
+
+ {item.kind === 'question' && (item.choices?.length ?? 0) > 0 && (
+ <div role="group" aria-label={`Answer: ${item.title}`} className="px-3 pb-3 sm:pl-[54px] flex flex-wrap gap-2">
+ {item.choices!.map((c, i) => (
+ <button
+ key={i}
+ type="button"
+ disabled={disabled}
+ onClick={() => onAnswer(item, i)}
+ className={`${actionBtn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`}
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {item.kind === 'approval' && (
+ <div role="group" aria-label={`Decide: ${item.title}`} className="px-3 pb-3 sm:pl-[54px] flex flex-wrap gap-2">
+ <button type="button" disabled={disabled} onClick={() => onResolve(item, 'allow_once')} className={`${actionBtn} text-white bg-emerald-600 hover:bg-emerald-500`}>
+ <Check size={13} aria-hidden="true" /> Allow once
+ </button>
+ <button type="button" disabled={disabled} onClick={() => onResolve(item, 'always_allow')} className={`${actionBtn} text-white bg-sky-600 hover:bg-sky-500`}>
+ <CheckCheck size={13} aria-hidden="true" /> Always allow
+ </button>
+ <button type="button" disabled={disabled} onClick={() => onResolve(item, 'deny')} className={`${actionBtn} text-zinc-300 bg-zinc-800 hover:bg-zinc-700`}>
+ <X size={13} aria-hidden="true" /> Deny
+ </button>
+ </div>
+ )}
+
+ {busy === item.id && (
+ <p className="px-3 pb-3 sm:pl-[54px] inline-flex items-center gap-1.5 text-[11px] text-zinc-400">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Sending…
+ </p>
+ )}
+ </li>
+ );
+ };
+
+ const empty = isAwayEmpty(data);
+
+ return (
+ <div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">
+ <div className="h-14 border-b border-zinc-800/80 px-4 sm:px-6 flex items-center justify-between gap-3 bg-zinc-900/30 backdrop-blur-sm select-none">
+ <div className="min-w-0">
+ <h2 className="text-sm font-semibold text-zinc-100 truncate">While you were away</h2>
+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">
+ {data ? windowLabel(data.since, now) : 'What your agents need, finished and failed'}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={loading}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs text-zinc-300 border border-zinc-700/60 hover:bg-zinc-800 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <RefreshCw size={12} className={loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
+ Refresh
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto p-4 sm:p-6" aria-busy={loading}>
+ <div className="max-w-3xl mx-auto space-y-6">
+ {error && (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">
+ <span>Couldn't load what happened: {error}</span>
+ <button
+ type="button"
+ onClick={onRefresh}
+ className="ml-auto px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10 focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-500"
+ >
+ Retry
+ </button>
+ </div>
+ )}
+
+ <div role="status" aria-live="polite">
+ {notice && (
+ <p
+ className={`px-3 py-2 rounded-lg border text-xs ${
+ notice.error ? 'border-amber-500/30 bg-amber-500/10 text-amber-200' : 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200'
+ }`}
+ >
+ {notice.text}
+ </p>
+ )}
+ </div>
+
+ {!data && loading && (
+ <p className="flex items-center gap-2 text-xs text-zinc-400">
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading…
+ </p>
+ )}
+
+ {data && empty && (
+ <div className="py-16 flex flex-col items-center text-center gap-2">
+ <CheckCircle2 size={28} className="text-emerald-400" aria-hidden="true" />
+ <p className="text-sm font-medium text-zinc-200">You're all caught up</p>
+ <p className="text-xs text-zinc-500 max-w-xs">Nothing new since you last looked. Questions, approvals and finished work will show up here.</p>
+ </div>
+ )}
+
+ {data &&
+ !empty &&
+ AWAY_SECTIONS.map(({ key, label, empty: none }) => (
+ <section key={key} aria-labelledby={`away-${key}`}>
+ <h3 id={`away-${key}`} className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">
+ {SECTION_ICON[key]}
+ {label}
+ <span className="font-mono normal-case text-zinc-600">({data[key].length})</span>
+ </h3>
+ {data[key].length > 0 ? (
+ <ul className="space-y-2">{data[key].map(renderItem)}</ul>
+ ) : (
+ <p className="px-1 text-xs text-zinc-500">{none}</p>
+ )}
+ </section>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export interface AwayPageProps {
+ /** Window start kept from the first visit this session, so coming back from an item keeps the list. */
+ since?: string | null;
+ onSince?: (since: string) => void;
+ onOpen: (item: AwayItem) => void;
+ /** New unseen counts for the sidebar badge. */
+ onCounts: (total: number) => void;
+}
+
+/** Loads the page, marks it seen, and runs the one-tap actions. */
+export const AwayPage: React.FC<AwayPageProps> = ({ since = null, onSince, onOpen, onCounts }) => {
+ const [data, setData] = useState<AwayResponse | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
+ // Refreshes keep the first load's window, so marking it seen doesn't empty the page.
+ const sinceRef = useRef<string | null>(since);
+ const onCountsRef = useRef(onCounts);
+ onCountsRef.current = onCounts;
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const next = await awayApi.get(sinceRef.current ?? undefined);
+ if (!sinceRef.current) {
+ sinceRef.current = next.since;
+ onSince?.(next.since);
+ }
+ setData(next);
+ setError(null);
+ return next;
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Something went wrong.');
+ return null;
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ let cancelled = false;
+ load().then(async (first) => {
+ if (cancelled || !first) return;
+ try {
+ await awayApi.seen();
+ // Finished and failed are now seen; what still waits on you keeps the badge.
+ onCountsRef.current(first.unseen.waiting);
+ } catch {
+ // the badge just stays until the next visit
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [load]);
+
+ const act = async (item: AwayItem, run: () => Promise<unknown>) => {
+ if (busy) return;
+ setBusy(item.id);
+ setNotice(null);
+ try {
+ await run();
+ setData((d) => (d ? withoutItem(d, 'waiting', item.id) : d));
+ setNotice({ text: `Sent to ${item.kwant_name}: “${item.title}”`, error: false });
+ } catch (err) {
+ const status = err instanceof AwayError ? err.status : 0;
+ const text = actionErrorText(status, `Couldn't send it: ${err instanceof Error ? err.message : 'Something went wrong.'}`);
+ setNotice({ text: `${text}: “${item.title}”`, error: true });
+ } finally {
+ setBusy(null);
+ }
+ const next = await load();
+ if (next) onCountsRef.current(next.unseen.total);
+ };
+
+ return (
+ <AwayView
+ data={data}
+ loading={loading}
+ error={error}
+ busy={busy}
+ notice={notice}
+ onRefresh={() => load().then((next) => next && onCountsRef.current(next.unseen.total))}
+ onOpen={onOpen}
+ onAnswer={(item, choice) => act(item, () => awayApi.answer(item.id, choice))}
+ onResolve={(item, decision) => act(item, () => awayApi.resolve(item.id, decision))}
+ />
+ );
+};
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 1bf86567..71d3bceb 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -1,7 +1,8 @@
import React, { useState } from 'react';
-import { Hash, Plus, CheckCircle2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil } from 'lucide-react';
+import { Hash, Plus, CheckCircle2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { playSfx } from '../audio/chiptune';
+import { badgeText } from '../away';
export interface Kwant {
id: string;
@@ -60,6 +61,10 @@ export interface SidebarProps {
/** Opens the new-agent form; with a team, the new agent joins it. */
onSummonKwant: (team?: Team) => void;
onCreateTeam: () => void;
+ /** "While you were away": unseen count for the badge, whether it's open, and how to open it. */
+ awayCount?: number;
+ awayActive?: boolean;
+ onOpenAway?: () => void;
}
export const memberIdsOf = (t: Team): string[] =>
@@ -85,6 +90,9 @@ export const Sidebar: React.FC<SidebarProps> = ({
onEditKwant,
onSummonKwant,
onCreateTeam,
+ awayCount = 0,
+ awayActive = false,
+ onOpenAway,
}) => {
const [teamsOpen, setTeamsOpen] = useState(true);
const [fleetOpen, setFleetOpen] = useState(() => localStorage.getItem('kwant.fleetOpen') === '1');
@@ -143,6 +151,28 @@ export const Sidebar: React.FC<SidebarProps> = ({
</div>
<div className="flex-1 overflow-y-auto p-2 space-y-4">
+ {onOpenAway && (
+ <button
+ type="button"
+ onClick={onOpenAway}
+ aria-current={awayActive ? 'page' : undefined}
+ className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
+ awayActive
+ ? 'bg-zinc-800 text-zinc-100 shadow-sm border border-zinc-700/50'
+ : 'text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800/50 border border-transparent'
+ }`}
+ >
+ <Inbox size={15} className={awayActive ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" />
+ <span className="truncate flex-1">While you were away</span>
+ {awayCount > 0 && (
+ <span className="shrink-0 min-w-[18px] px-1.5 py-px rounded-full bg-amber-500 text-zinc-950 text-[10px] font-semibold text-center">
+ {badgeText(awayCount)}
+ <span className="sr-only"> new</span>
+ </span>
+ )}
+ </button>
+ )}
+
{/* Channels Section */}
<div>
<div className="px-2 py-1 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">
diff --git a/frontend/tests/away.test.mjs b/frontend/tests/away.test.mjs
new file mode 100644
index 00000000..9bd93311
--- /dev/null
+++ b/frontend/tests/away.test.mjs
@@ -0,0 +1,140 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+// Sidebar's sound settings read localStorage on import.
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const a = await loadBundled(`export * from './src/away';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { AwayView } from './src/components/AwayView';
+ import { Sidebar } from './src/components/Sidebar';
+ export const render = (props) => renderToStaticMarkup(React.createElement(AwayView, props));
+ export const sidebar = (props) => renderToStaticMarkup(React.createElement(Sidebar, props));
+`);
+
+const NOW = Date.parse('2026-10-17T12:47:00Z');
+const item = (over = {}) => ({
+ kind: 'delegation', id: 'd1', kwant_id: 'k2', kwant_name: 'Scout', title: 'Write the brief', summary: 'Brief',
+ status: 'completed', timestamp: '2026-10-17T10:15:00Z', link: { thread_id: 't1', channel_id: null, direct_kwant_id: null }, ...over,
+});
+const question = item({ kind: 'question', id: 'q1', title: 'Ship tonight?', summary: 'Choices: Yes · No', status: 'open', choices: ['Yes', 'No'],
+ link: { thread_id: null, channel_id: 'c1', direct_kwant_id: null } });
+const approval = item({ kind: 'approval', id: 'a1', kwant_id: 'k1', kwant_name: 'Lead', title: 'Use send (mail)', status: 'pending',
+ summary: 'api_key: [redacted]', link: { thread_id: null, channel_id: null, direct_kwant_id: 'k1' } });
+const resp = (over = {}) => ({
+ since: '2026-10-10T12:47:00Z', last_seen: null, now: '2026-10-17T12:47:00Z', stuck_after_minutes: 30,
+ waiting: [question, approval], finished: [item()], failed: [item({ id: 'd3', status: 'stuck', title: 'Long crawl' })],
+ unseen: { waiting: 2, finished: 1, failed: 1, total: 4 }, ...over,
+});
+
+test('relative time reads naturally and survives bad input', () => {
+ const ago = (s) => new Date(NOW - s * 1000).toISOString();
+ assert.equal(a.relativeTime(ago(5), NOW), 'just now');
+ assert.equal(a.relativeTime(ago(-30), NOW), 'just now', 'clock skew is not "in the future"');
+ assert.equal(a.relativeTime(ago(5 * 60), NOW), '5 min ago');
+ assert.equal(a.relativeTime(ago(3 * 3600 + 59), NOW), '3 h ago');
+ assert.equal(a.relativeTime(ago(30 * 3600), NOW), 'yesterday');
+ assert.equal(a.relativeTime(ago(4 * 86400), NOW), '4 days ago');
+ assert.doesNotMatch(a.relativeTime(ago(9 * 86400), NOW), /ago/);
+ assert.equal(a.relativeTime('nope', NOW), '');
+});
+
+test('the subtitle names the default week or the last visit', () => {
+ assert.equal(a.windowLabel('2026-10-10T12:47:00Z', NOW), 'From the last 7 days');
+ assert.equal(a.windowLabel('2026-10-17T09:47:00Z', NOW), 'Since you last looked, 3 h ago');
+ assert.equal(a.windowLabel('bad', NOW), '');
+});
+
+test('labels per kind and status', () => {
+ const l = (kind, status) => a.itemLabel({ kind, status });
+ assert.deepEqual(l('question', 'open'), { label: 'Question', tone: 'amber' });
+ assert.deepEqual(l('approval', 'pending'), { label: 'Needs approval', tone: 'amber' });
+ assert.deepEqual(l('delegation', 'completed'), { label: 'Handoff done', tone: 'emerald' });
+ assert.deepEqual(l('delegation', 'failed'), { label: 'Handoff failed', tone: 'rose' });
+ assert.deepEqual(l('delegation', 'interrupted'), { label: 'Interrupted', tone: 'rose' });
+ assert.deepEqual(l('delegation', 'stuck'), { label: 'Stuck', tone: 'amber' });
+ assert.deepEqual(l('routine_run', 'ok'), { label: 'Routine ran', tone: 'emerald' });
+ assert.deepEqual(l('routine_run', 'error'), { label: 'Routine failed', tone: 'rose' });
+ assert.equal(l('mystery', 'x').tone, 'zinc');
+});
+
+test('badge text, empty check and the event filter', () => {
+ assert.equal(a.badgeText(0), '');
+ assert.equal(a.badgeText(7), '7');
+ assert.equal(a.badgeText(120), '99+');
+ assert.equal(a.isAwayEmpty(null), false, 'not loaded is not "all caught up"');
+ assert.equal(a.isAwayEmpty(resp({ waiting: [], finished: [], failed: [] })), true);
+ assert.equal(a.isAwayEmpty(resp()), false);
+ assert.ok(a.affectsAway('question_updated') && a.affectsAway('ApprovalRequired') && a.affectsAway('RoutineRun'));
+ assert.equal(a.affectsAway('TextDelta'), false);
+ assert.equal(a.affectsAway(undefined), false);
+});
+
+test('each item opens its thread, channel or direct chat', () => {
+ assert.deepEqual(a.awayTarget(item()), { thread: 't1', kwant: 'k2' });
+ assert.deepEqual(a.awayTarget(question), { channel: 'c1' });
+ assert.deepEqual(a.awayTarget(approval), { direct: 'k1' });
+ assert.deepEqual(a.awayTarget(item({ link: { thread_id: null, channel_id: null, direct_kwant_id: null } })), { direct: 'k2' });
+});
+
+test('an acted-on item leaves the list and the waiting count right away', () => {
+ const r = resp();
+ const next = a.withoutItem(r, 'waiting', 'q1');
+ assert.deepEqual(next.waiting.map((i) => i.id), ['a1']);
+ assert.deepEqual(next.unseen, { waiting: 1, finished: 1, failed: 1, total: 3 });
+ assert.equal(a.withoutItem(r, 'waiting', 'nope'), r);
+});
+
+test('a lapsed request reads "This request expired"', () => {
+ assert.equal(a.actionErrorText(409, 'x'), 'This request expired');
+ assert.equal(a.actionErrorText(404, 'x'), 'This request expired');
+ assert.equal(a.actionErrorText(500, 'Couldn’t send it'), 'Couldn’t send it');
+});
+
+const noop = () => {};
+const view = (over = {}) => ui.render({ data: resp(), loading: false, error: null, now: NOW, onRefresh: noop, onOpen: noop, onAnswer: noop, onResolve: noop, ...over });
+
+test('three sections with agent, title, summary and time; one-tap actions', () => {
+ const html = view();
+ const order = ['Waiting on you', 'Finished', 'Failed or stuck'].map((s) => html.indexOf(s));
+ assert.ok(order.every((i) => i > 0) && order[0] < order[1] && order[1] < order[2]);
+ assert.match(html, /Scout/);
+ assert.match(html, /Write the brief/);
+ assert.match(html, /Brief/, 'a summary line');
+ assert.doesNotMatch(html, /Choices: Yes · No/, 'a question shows its choices as buttons, not a summary');
+ assert.match(html, /2 h ago/);
+ assert.match(html, /From the last 7 days/);
+ assert.match(html, />Yes<\/button>/);
+ assert.match(html, />No<\/button>/);
+ for (const b of ['Allow once', 'Always allow', 'Deny']) assert.match(html, new RegExp(b));
+ assert.match(html, /Handoff done/);
+ assert.match(html, /Stuck/);
+ assert.doesNotMatch(html, /all caught up/);
+});
+
+test('empty, loading, error and expired states', () => {
+ assert.match(view({ data: resp({ waiting: [], finished: [], failed: [] }) }), /You&#x27;re all caught up/);
+ const loading = view({ data: null, loading: true });
+ assert.match(loading, /Loading…/);
+ assert.doesNotMatch(loading, /caught up/);
+ const err = view({ data: null, error: 'Request failed (HTTP 500).' });
+ assert.match(err, /role="alert"/);
+ assert.match(err, /Retry/);
+ assert.match(view({ notice: { text: 'This request expired', error: true } }), /This request expired/);
+ const busy = view({ busy: 'a1' });
+ assert.match(busy, /Sending…/);
+ assert.ok((busy.match(/disabled=""/g) || []).length >= 5, 'every action is disabled while one is sending');
+});
+
+test('sidebar entry shows the unseen badge only when there is something new', () => {
+ const base = { kwants: [], channels: [], teams: [], selectedId: '', isChannel: true, onSelectKwant: noop, onSelectChannel: noop,
+ onSelectTeam: noop, onSummonKwant: noop, onCreateTeam: noop, onOpenAway: noop };
+ const withNew = ui.sidebar({ ...base, awayCount: 7 });
+ assert.match(withNew, /While you were away/);
+ assert.match(withNew, />7<span class="sr-only"> new<\/span>/);
+ assert.doesNotMatch(ui.sidebar({ ...base, awayCount: 0 }), /sr-only"> new/);
+ assert.match(ui.sidebar({ ...base, awayCount: 3, awayActive: true }), /aria-current="page"/);
+});