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.

Hand-off cards: refetch open delegations after a reconnect (#521)

Oleksandr Ivanchenkobfa2e07d8ae9
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 94907596..430d54be 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -95,7 +95,9 @@ import {
applyDelegation,
applyTurnEvent,
backgroundTurns,
+ delegationsToRefresh,
hydrateTurns,
+ isStaleDelegationFetch,
messageContextId,
parseDelegationMeta,
queuePosition,
@@ -300,6 +302,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const knownThreadsRef = useRef<Set<string>>(new Set());
const threadsLoadingRef = useRef<Set<string>>(new Set());
const delegationsFetchedRef = useRef<Set<string>>(new Set());
+ /** One counter for live hand-off updates (`live[id]`) and refetches, so an older fetch can't win. */
+ const delegationSeqRef = useRef<{ n: number; live: Record<string, number> }>({ n: 0, live: {} });
+ const noteLiveDelegation = (id: string) => {
+ delegationSeqRef.current.live[id] = ++delegationSeqRef.current.n;
+ };
const selectedIdRef = useRef<string>(selectedId);
selectedIdRef.current = selectedId;
const isChannelRef = useRef<boolean>(isChannel);
@@ -1066,6 +1073,25 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
}, [messages]);
+ /** After a stream drop: refetch hand-offs still open here (and failed first fetches), whose cards may
+ * have missed their running/finished event. A live update that lands first is kept. */
+ const refreshOpenDelegations = () => {
+ for (const id of delegationsToRefresh(delegationsRef.current, delegationsFetchedRef.current)) {
+ const sent = ++delegationSeqRef.current.n;
+ threadsApi.delegation(id).then(
+ (d) => {
+ if (isStaleDelegationFetch(delegationSeqRef.current.live, d.id, sent)) return;
+ setDelegations((prev) => ({ ...prev, [d.id]: d }));
+ setThreadsByKwant((prev) => {
+ const next = applyDelegation(prev[d.specialist_kwant_id], d);
+ return next === prev[d.specialist_kwant_id] ? prev : { ...prev, [d.specialist_kwant_id]: next };
+ });
+ },
+ () => undefined,
+ );
+ }
+ };
+
// Connect to SSE stream
useEffect(() => {
const sse = new EventSource(eventsUrl(space.id));
@@ -1113,12 +1139,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
dropped = true;
};
// First connect and every reconnect: running turns from the server. After a drop, also
- // whatever changed meanwhile in the open chat and the open bot's conversations.
+ // whatever changed meanwhile in the open chat, the open bot's conversations and open hand-offs.
sse.onopen = () => {
hydrateFromServer();
if (dropped) {
refreshContext(openCtxRef.current);
if (!isChannelRef.current && selectedIdRef.current) loadThreads(selectedIdRef.current);
+ refreshOpenDelegations();
}
dropped = false;
};
@@ -1180,6 +1207,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const dl: Delegation | undefined = event.data?.delegation;
if (!dl?.id) break;
knownThreadsRef.current.add(dl.thread_id);
+ noteLiveDelegation(dl.id);
setDelegations((prev) => ({ ...prev, [dl.id]: dl }));
const list = threadsByKwantRef.current[dl.specialist_kwant_id];
if (list && !list.some((t) => t.id === dl.thread_id)) loadThreads(dl.specialist_kwant_id);
@@ -2273,6 +2301,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
try {
if (d && (d.status === 'queued' || d.status === 'running')) {
const next = await threadsApi.cancelDelegation(d.id);
+ noteLiveDelegation(next.id);
setDelegations((prev) => ({ ...prev, [next.id]: next }));
} else {
await threadsApi.cancel(t.id);
@@ -2298,6 +2327,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const handleCancelDelegation = async (id: string): Promise<string | void> => {
try {
const next = await threadsApi.cancelDelegation(id);
+ noteLiveDelegation(next.id);
setDelegations((prev) => ({ ...prev, [next.id]: next }));
} catch (err) {
return `Couldn't stop it: ${errText(err)}`;
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index 567a8300..567b18ec 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -283,6 +283,29 @@ export function threadBadge(thread: Pick<Thread, 'id' | 'delegation'>, turns: Tu
export const isOpenDelegation = (d: Pick<Delegation, 'status'> | null | undefined): boolean =>
!!d && (d.status === 'queued' || d.status === 'running');
+/**
+ * After the live stream drops and comes back, the hand-offs whose cards may have missed an update:
+ * every open one held, plus ones a chat note named whose first fetch never landed. Sorted, no repeats.
+ */
+export function delegationsToRefresh(
+ held: Record<string, Pick<Delegation, 'status'> | undefined>,
+ named: Iterable<string> = [],
+): string[] {
+ const ids = new Set<string>();
+ for (const [id, d] of Object.entries(held)) if (isOpenDelegation(d)) ids.add(id);
+ // Array.from, not for…of or spread: the node tests transpile to ES5, where those skip a Set.
+ for (const id of Array.from(named)) if (!held[id]) ids.add(id);
+ return Array.from(ids).sort();
+}
+
+/**
+ * Whether a refetched record is older than a live update for the same hand-off. `seq` is one counter
+ * for both: a live update stores its number in `live[id]`, a fetch takes its own when it goes out.
+ * The record has no updated_at, and a resumed hand-off goes back to queued, so the status can't tell.
+ */
+export const isStaleDelegationFetch = (live: Record<string, number>, id: string, sentSeq: number): boolean =>
+ (live[id] ?? 0) > sentSeq;
+
/** Visible threads: delegated ones first, then the person's, newest activity first within each. */
export function sortThreads(threads: Thread[], includeArchived = false): Thread[] {
return threads
diff --git a/frontend/tests/threads.test.mjs b/frontend/tests/threads.test.mjs
index 6b57330b..30d68752 100644
--- a/frontend/tests/threads.test.mjs
+++ b/frontend/tests/threads.test.mjs
@@ -282,3 +282,45 @@ test('vm_busy (#446): its own line across bots, slots kept, cleared by the secon
m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'q4', kwant_id: 'c', context_id: 'c', reason: 'something_new' }));
assert.equal(m.q4.reason, 'agent_busy', 'unknown reasons read as the bot being busy');
});
+
+// ---------------------------------------------------------------------------
+// After a stream drop, open hand-off cards refetch their status
+
+test('delegationsToRefresh: open hand-offs and never-landed fetches, not finished ones', () => {
+ const held = {
+ q: { status: 'queued' },
+ r: { status: 'running' },
+ c: { status: 'completed' },
+ f: { status: 'failed' },
+ x: { status: 'cancelled' },
+ i: { status: 'interrupted' },
+ };
+ assert.deepEqual(t.delegationsToRefresh(held), ['q', 'r']);
+ // A note named "lost" but its first fetch failed (the drop itself): fetch it again. "c" is held and done.
+ assert.deepEqual(t.delegationsToRefresh(held, new Set(['lost', 'c', 'q'])), ['lost', 'q', 'r']);
+ assert.deepEqual(t.delegationsToRefresh({}), []);
+ assert.deepEqual(t.delegationsToRefresh({ gone: undefined }, ['gone']), ['gone']);
+});
+
+test('isStaleDelegationFetch: a live update after the fetch went out wins; one before it does not', () => {
+ // seq: live update #3 for "a", then the fetch goes out as #4: the fetch is newer.
+ assert.equal(t.isStaleDelegationFetch({ a: 3 }, 'a', 4), false);
+ // fetch #4 goes out, then live update #5 arrives before the fetch returns: keep the live one.
+ assert.equal(t.isStaleDelegationFetch({ a: 5 }, 'a', 4), true);
+ // No live update for this hand-off at all, or only for another one.
+ assert.equal(t.isStaleDelegationFetch({}, 'a', 1), false);
+ assert.equal(t.isStaleDelegationFetch({ b: 9 }, 'a', 1), false);
+});
+
+test('App refetches open hand-offs on a reconnect, and live updates and stops guard against older fetches', async () => {
+ const app = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ const onopen = app.slice(app.indexOf('sse.onopen'), app.indexOf('sse.onmessage'));
+ assert.match(onopen, /if \(dropped\) \{[^}]*refreshOpenDelegations\(\);/, 'only after a drop');
+ const refresh = app.slice(app.indexOf('const refreshOpenDelegations'), app.indexOf('// Connect to SSE stream'));
+ assert.match(refresh, /delegationsToRefresh\(delegationsRef\.current, delegationsFetchedRef\.current\)/);
+ assert.match(refresh, /isStaleDelegationFetch\(delegationSeqRef\.current\.live, d\.id, sent\)\) return;/);
+ assert.match(refresh, /applyDelegation\(/, 'the specialist thread list gets the record too');
+ const live = app.slice(app.indexOf("case 'DelegationUpdated'"), app.indexOf("case 'message_added'"));
+ assert.match(live, /noteLiveDelegation\(dl\.id\);/);
+ assert.equal(app.match(/noteLiveDelegation\(next\.id\);/g)?.length, 2, 'both Stop paths');
+});