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.

Turn end: never settle on an older chat list, keep the 👍 answer (22r) (#737)

Oleksandr Ivanchenkoa682b54d6b72
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 273ad28b..6afb6326 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,4 +1,5 @@
import React, { Suspense, lazy, useState, useEffect, useRef, useCallback, useMemo } from 'react';
+import { flushSync } from 'react-dom';
import { askOrder } from './askOrder';
import { refreshDictation } from './dictation';
import { DecidingMap, applyDecideEvent, decisionsApi, hydrateDeciding } from './decideFirst';
@@ -117,6 +118,8 @@ import {
queuePosition,
queuedInChat,
reloadOnTurnEnd,
+ landedNewReply,
+ settlesOnTurnComplete,
shouldRenderDelta,
streamTarget,
waitsForOtherBot,
@@ -899,14 +902,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
delete streamsRef.current[ctx];
delete liveKwantRef.current[ctx];
}
+ if (ctx && ctx in liveRef.current) {
+ const next = { ...liveRef.current };
+ delete next[ctx];
+ liveRef.current = next;
+ // 22r: the working line goes in this commit, before its words are cleared below. The streamed text is an
+ // outside store that repaints at once; cleared first, the line showed blank until React's next render.
+ flushSync(() => setLive(next));
+ }
if (ctx === openCtxRef.current) {
streamStore.show({ text: '', thinking: '' });
}
- if (!ctx || !(ctx in liveRef.current)) return;
- const next = { ...liveRef.current };
- delete next[ctx];
- liveRef.current = next;
- setLive(next);
};
const kwantName = (id: unknown) => (typeof id === 'string' ? kwantsRef.current.find((k) => k.id === id)?.name : undefined);
// 0.8.1 F4: which bot runs in each live chat, so a name that wasn't known yet can be filled in. A page
@@ -925,28 +931,33 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const chatLoadsRef = useRef(new ChatLoads());
/** Loads a chat's latest messages into the cache, and on screen if it's open. */
- const refreshContext = async (ctx: string | null | undefined): Promise<void> => {
- if (!ctx) return;
- const n = chatLoadsRef.current.start(ctx);
- try {
- let data: ChatMessage[];
- if (knownThreadsRef.current.has(ctx)) {
- data = await threadsApi.messages<ChatMessage>(ctx);
- } else {
- const res = await fetch(`/api/channels/${encodeURIComponent(ctx)}/messages`);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- data = await res.json();
- }
- // A newer load of this chat started meanwhile: it has the newer messages
- if (!chatLoadsRef.current.isLatest(ctx, n)) return;
- messagesCacheRef.current[ctx] = data;
- if (openCtxRef.current === ctx) {
- setMessages(data);
- setMessagesError(null);
+ const refreshContext = (ctx: string | null | undefined): Promise<void> => {
+ if (!ctx) return Promise.resolve();
+ // Resolves once the newest load of this chat has landed (22r), so a settle after it never ends the turn on an older list.
+ return chatLoadsRef.current.run(ctx, async (isLatest) => {
+ try {
+ let data: ChatMessage[];
+ if (knownThreadsRef.current.has(ctx)) {
+ data = await threadsApi.messages<ChatMessage>(ctx);
+ } else {
+ const res = await fetch(`/api/channels/${encodeURIComponent(ctx)}/messages`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ data = await res.json();
+ }
+ // A newer load of this chat started meanwhile: it has the newer messages
+ if (!isLatest()) return;
+ messagesCacheRef.current[ctx] = data;
+ if (openCtxRef.current === ctx) {
+ // 22r: on screen now, so a settle after this load (which clears the streamed words) never paints before the saved reply.
+ flushSync(() => {
+ setMessages(data);
+ setMessagesError(null);
+ });
+ }
+ } catch {
+ if (openCtxRef.current === ctx && isLatest()) setMessagesError('Could not load this chat.');
}
- } catch {
- if (openCtxRef.current === ctx && chatLoadsRef.current.isLatest(ctx, n)) setMessagesError('Could not load this chat.');
- }
+ });
};
const rememberThreads = (list: Thread[]) => list.forEach((t) => knownThreadsRef.current.add(t.id));
@@ -1754,8 +1765,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
if (typeof event.turn_id === 'string') completed.add(event.turn_id);
// The stream stays up until the saved reply is on screen, so nothing jumps.
+ const shown = ctx ? messagesCacheRef.current[ctx] : undefined;
refreshContext(ctx).then(() => {
- if (!discussionInProgressRef.current) settle(ctx);
+ // 22r: a turn still running waits for turn_ended, whose load has the saved reply, unless this load has it.
+ if (discussionInProgressRef.current) return;
+ if (settlesOnTurnComplete(turnsRef.current, event.turn_id) || landedNewReply(shown, ctx ? messagesCacheRef.current[ctx] : undefined)) settle(ctx);
});
break;
}
diff --git a/frontend/src/approvalAsk.ts b/frontend/src/approvalAsk.ts
index 3b70ed59..8d6681ac 100644
--- a/frontend/src/approvalAsk.ts
+++ b/frontend/src/approvalAsk.ts
@@ -51,6 +51,21 @@ export function asksApproval(text: string | null | undefined): boolean {
return ASKS.some((r) => r.test(tail));
}
+/**
+ * The reply that gets Approve / Change…: the newest message, when it's a saved bot reply asking for an OK, nothing
+ * else is open (`busy`: a reply running, a question card, an approval card) and the person hasn't already answered
+ * it with a 👍 (`answered`, kept by id, so a turn-end reload with fresh copies of the messages doesn't bring it back, 22r).
+ */
+export function approveRowId(
+ last: { id: string; sender_role?: string | null; text?: string | null } | undefined,
+ meta: Record<string, unknown> | null | undefined,
+ o: { busy: boolean; answered: ReadonlySet<string> },
+): string | null {
+ if (!last || last.sender_role !== 'kwant' || last.id.startsWith('temp-') || o.busy || o.answered.has(last.id)) return null;
+ if (metaHidesApprove(meta)) return null;
+ return asksApproval(last.text) ? last.id : null;
+}
+
/** What Approve sends, as an ordinary reply to that message. */
export const APPROVE_TEXT = 'Approved, go ahead.';
/** The composer's placeholder after Change…. */
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index e46cee90..cee520c6 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -83,7 +83,7 @@ import { ConnectionSuggestionMeta, parseConnectionMeta } from '../connectionSugg
import { routeReasonText, routeWhyText } from '../routeReason';
import { useInbox } from '../inboxStore';
import { doneItemsOf, doneOf } from '../replyDone';
-import { APPROVE_TEXT, asksApproval, changePlaceholder, metaHidesApprove, refocusAfterApprove } from '../approvalAsk';
+import { APPROVE_TEXT, approveRowId, changePlaceholder, refocusAfterApprove } from '../approvalAsk';
import { DoneCheckLine } from './DoneMarker';
import { ApproveRow } from './ApproveRow';
import { CopyGhost } from './CopyGhost';
@@ -1234,13 +1234,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
const inboxData = useInbox().data;
const doneItems = useMemo(() => doneItemsOf([...(inboxData?.items ?? []), ...(inboxData?.batch_items ?? [])]), [inboxData]);
// reply-chrome part 2: the newest message, when it's a bot reply asking for an OK and nothing else is open.
+ // 22r: a 👍 that answered it counts as answered for good, across the turn-end reload.
const approveId = useMemo(() => {
const last = messages[messages.length - 1];
- if (!last || last.sender_role !== 'kwant' || last.id.startsWith('temp-') || isStreaming || awaitingAnswer || pendingApprovals.length > 0) return null;
- const meta = parseMetaObject(last.meta);
- if (metaHidesApprove(meta)) return null;
- return asksApproval(last.text) ? last.id : null;
- }, [messages, isStreaming, awaitingAnswer, pendingApprovals.length]);
+ return approveRowId(last, last ? parseMetaObject(last.meta) : null, { busy: isStreaming || !!awaitingAnswer || pendingApprovals.length > 0, answered });
+ }, [messages, isStreaming, awaitingAnswer, pendingApprovals.length, answered]);
const approve = async (msg: ChatMessage) => {
if (approving) return;
setApproving(msg.id);
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index 70c10c19..dd496014 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -137,6 +137,7 @@ export function reloadOnTurnEnd(_turnId: string | null | undefined): boolean {
*/
export class ChatLoads {
private seq: Record<string, number> = {};
+ private newest: Record<string, Promise<void>> = {};
start(ctx: string): number {
this.seq[ctx] = (this.seq[ctx] ?? 0) + 1;
@@ -146,6 +147,50 @@ export class ChatLoads {
isLatest(ctx: string, n: number): boolean {
return this.seq[ctx] === n;
}
+
+ /**
+ * Runs one load of a chat; `load` may only touch the screen while `isLatest()` holds. The promise resolves
+ * once the newest load of that chat has landed, never earlier: a load a newer one replaced waits for that one.
+ * 22r: TurnComplete's load was replaced by turn_ended's, came back first, and its follow-up ended the turn
+ * (dropped the working line) while the list without the reply was still on screen, so the asked-for OK was
+ * the newest message again and "… is waiting for your OK" came back for a few frames.
+ */
+ run(ctx: string, load: (isLatest: () => boolean) => Promise<void>): Promise<void> {
+ const n = this.start(ctx);
+ const p = load(() => this.isLatest(ctx, n));
+ this.newest[ctx] = p;
+ return this.landed(ctx, p);
+ }
+
+ private async landed(ctx: string, p: Promise<void>): Promise<void> {
+ await p.catch(() => undefined);
+ const next = this.newest[ctx];
+ if (next && next !== p) return this.landed(ctx, next);
+ }
+}
+
+/**
+ * Whether TurnComplete's load may settle the chat (clear the streamed text, drop the working line). Not while that
+ * turn is still running: TurnComplete comes before kwnt saves the reply, so its load can come back without it, and
+ * clearing the stream then blanks the reply for a few frames before it lands (22r). turn_ended settles it instead,
+ * after the load that has the reply. A TurnComplete with no turn id, or one that arrives after turn_ended, settles.
+ */
+export function settlesOnTurnComplete(turns: TurnMap, turnId: unknown): boolean {
+ return !(typeof turnId === 'string' && turnId in turns);
+}
+
+/**
+ * Whether a load brought a saved bot reply the list on screen didn't have: its newest message is the bot's, saved
+ * (not temp-) and new. Then TurnComplete may clear the streamed text even while the turn is still running, so the
+ * saved reply and its streamed copy are never on screen together (22r).
+ */
+export function landedNewReply(
+ before: readonly { id: string; sender_role?: string }[] | undefined,
+ after: readonly { id: string; sender_role?: string }[] | undefined,
+): boolean {
+ const last = after?.[after.length - 1];
+ if (!last || last.sender_role !== 'kwant' || last.id.startsWith('temp-')) return false;
+ return !(before ?? []).some((m) => m.id === last.id);
}
/** Applies one SSE event; returns the same map when the event isn't about turns. */
diff --git a/frontend/tests/liveReplies.test.mjs b/frontend/tests/liveReplies.test.mjs
index 80eb2c38..f6e6bef3 100644
--- a/frontend/tests/liveReplies.test.mjs
+++ b/frontend/tests/liveReplies.test.mjs
@@ -51,6 +51,8 @@ test('a slow load that finishes last never hides the reply a newer load showed',
test('App reloads on turn_ended through reloadOnTurnEnd and guards loads with ChatLoads', async () => {
const app = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8');
assert.match(app, /reloadOnTurnEnd\(/, 'turn_ended asks reloadOnTurnEnd');
- assert.match(app, /chatLoads(Ref)?\.current\.isLatest\(|chatLoads\.isLatest\(/, 'refreshContext drops stale loads');
+ // 22r: through ChatLoads.run, whose load gets isLatest() and whose promise waits for the newest load
+ assert.match(app, /chatLoadsRef\.current\.run\(ctx, async \(isLatest\)/, 'refreshContext drops stale loads');
+ assert.match(app, /if \(!isLatest\(\)\) return;/, 'a replaced load never lands');
assert.doesNotMatch(app, /completed\.delete\(d\.turn_id\)\) settle\(ctx\)/, 'turn_ended no longer skips the reload');
});
diff --git a/frontend/tests/replyChrome.test.mjs b/frontend/tests/replyChrome.test.mjs
index 9e905d6e..5cb97aa1 100644
--- a/frontend/tests/replyChrome.test.mjs
+++ b/frontend/tests/replyChrome.test.mjs
@@ -152,9 +152,10 @@ test('metaHidesApprove: a failed step\'s Blocked keeps the Approve row; any othe
assert.equal(m.metaHidesApprove({ kind: 'card' }), true);
assert.equal(m.metaHidesApprove({}), false);
assert.equal(m.metaHidesApprove(null), false);
- // ChatView's approveId reads it, instead of its own blocked/question/kind check
+ // ChatView's approveId reads it (through approveRowId, 22r), instead of its own blocked/question/kind check
const src = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');
- assert.match(src, /if \(metaHidesApprove\(meta\)\) return null;/);
+ assert.match(src, /approveRowId\(last,/);
+ assert.match(readFileSync(new URL('../src/approvalAsk.ts', import.meta.url), 'utf8'), /if \(metaHidesApprove\(meta\)\) return null;/);
assert.doesNotMatch(src, /meta\.blocked \|\| meta\.question_id/);
});
diff --git a/frontend/tests/turnEndNoStaleFrame.test.mjs b/frontend/tests/turnEndNoStaleFrame.test.mjs
new file mode 100644
index 00000000..e3a88934
--- /dev/null
+++ b/frontend/tests/turnEndNoStaleFrame.test.mjs
@@ -0,0 +1,207 @@
+// 22r: when an approve-by-reaction turn ends, the chat never shows an older state for a frame.
+// Mira's clip-v611-react (mac-v0.9.15) showed "TechLead is waiting for your OK · Approve / Change…" again for ~67 ms
+// after the 👍, right before the published reply. Cause: TurnComplete's chat load was replaced by turn_ended's,
+// came back first, and its settle dropped the working line while the list without the reply was still on screen.
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ts from 'typescript';
+
+const load = async (path) => {
+ const source = await readFile(new URL(path, import.meta.url), 'utf8');
+ const { outputText } = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } });
+ return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);
+};
+const t = await load('../src/threads.ts');
+const a = await load('../src/approvalAsk.ts');
+
+const deferred = () => { let resolve; const p = new Promise((r) => (resolve = r)); return { p, resolve }; };
+const tick = () => new Promise((r) => setImmediate(r));
+
+const ASK = { id: 'ask', sender_role: 'kwant', text: 'The release notes are ready. Shall I publish them now?' };
+const USER = { id: 'u1', sender_role: 'user', text: 'Can you write up the release notes for Trailhead 2.4?' };
+const REPLY = { id: 'pub', sender_role: 'kwant', text: 'Published. The 2.4 release notes are live on the changelog page.' };
+
+/**
+ * The open chat the way App keeps it: `refreshContext` (ChatLoads.run, only the newest load lands), `settle`
+ * (no turn left: the working line goes), and ChatView's Approve row from the list and the live state. A frame
+ * is what the browser paints: the state once a task (a load coming back, an event) and all its microtasks are done.
+ * App commits the list and the live state with flushSync and settles in the same task, so in-between states never paint.
+ */
+function scene({ answered = new Set(['ask']) } = {}) {
+ const loads = new t.ChatLoads();
+ let screen = [{ ...USER }, { ...ASK }];
+ let live = true; // the 👍 started the turn
+ let stream = REPLY.text; // the working line has streamed the reply
+ let turns = { 'turn-1': { turn_id: 'turn-1', context_id: 'c' } };
+ const server = [{ ...USER }, { ...ASK }];
+ const fetches = [];
+ const frames = [];
+ let why = 'after 👍';
+ const frame = (w) => { why = w; };
+ const paint = () => {
+ const last = screen[screen.length - 1];
+ const saved = screen.some((m) => m.id === 'pub');
+ const streamed = live && stream === REPLY.text;
+ const replyShown = saved || streamed;
+ frames.push({ why, ids: screen.map((m) => m.id), live, stream, replyShown, twice: saved && streamed, approve: a.approveRowId(last, null, { busy: live, answered }) });
+ };
+ const refreshContext = () =>
+ loads.run('c', async (isLatest) => {
+ const f = deferred();
+ fetches.push(f);
+ const snapshot = server.map((m) => ({ ...m })); // fresh copies, like a reload
+ await f.p;
+ if (!isLatest()) return;
+ screen = snapshot;
+ frame('load landed');
+ });
+ // App's settle: another turn in the chat keeps the working line (its stream starts empty); none left drops it.
+ const settle = () => {
+ stream = '';
+ if (Object.keys(turns).length === 0) live = false;
+ frame('settle');
+ };
+ paint();
+ // one load comes back: a task; the browser paints once it and its microtasks are done
+ const respond = async (i) => { fetches[i].resolve(); await tick(); paint(); };
+ return {
+ frames, fetches, respond, server, screen: () => screen,
+ turnComplete: () => {
+ const shown = screen;
+ return refreshContext().then(() => { if (t.settlesOnTurnComplete(turns, 'turn-1') || t.landedNewReply(shown, screen)) settle(); });
+ },
+ turnEnded: () => { turns = t.applyTurnEvent(turns, { type: 'turn_ended', data: { turn_id: 'turn-1' } }); return refreshContext().then(settle); },
+ };
+}
+
+test('turn end: a load a newer one replaced never ends the turn on the older list (no Approve row after the 👍)', async () => {
+ const s = scene();
+ const done1 = s.turnComplete(); // the driver is done, the reply isn't saved yet
+ s.server.push({ ...REPLY }); // kwnt saves the reply, then sends turn_ended
+ const done2 = s.turnEnded();
+ // the first load (no reply) comes back first: replaced, so nothing lands and nothing settles
+ await s.respond(0);
+ assert.equal(s.frames.at(-1).live, true, 'the working line stays while the newest load is out');
+ await s.respond(1);
+ await Promise.all([done1, done2]);
+ assert.deepEqual(s.screen().map((m) => m.id), ['u1', 'ask', 'pub']);
+ for (const f of s.frames) assert.equal(f.approve, null, `no Approve row at "${f.why}" (${f.ids.join(',')}, live ${f.live})`);
+ // the working line goes only once the reply is on screen, and the reply's words never blank out on the way
+ for (const f of s.frames) if (!f.live) assert.ok(f.ids.includes('pub'), `settled on an older list: ${f.ids.join(',')}`);
+ for (const f of s.frames) assert.ok(f.replyShown, `the reply blanked at "${f.why}" (${f.ids.join(',')}, live ${f.live})`);
+ for (const f of s.frames) assert.ok(!f.twice, `the reply showed twice at "${f.why}"`);
+});
+
+test('turn end: TurnComplete\'s load with the saved reply clears the streamed copy at once (never shown twice)', async () => {
+ const s = scene();
+ s.server.push({ ...REPLY }); // saved before TurnComplete's load reads it
+ const done1 = s.turnComplete();
+ await s.respond(0);
+ await done1;
+ for (const f of s.frames) assert.ok(!f.twice, `the reply showed twice at "${f.why}"`);
+ for (const f of s.frames) assert.equal(f.approve, null);
+ assert.equal(s.frames.at(-1).live, true, 'the turn is still running: its working line stays (empty) until turn_ended');
+ const done2 = s.turnEnded();
+ await s.respond(1);
+ await done2;
+ assert.equal(s.frames.at(-1).live, false);
+ for (const f of s.frames) assert.ok(f.replyShown && !f.twice && f.approve === null, `bad frame at "${f.why}"`);
+});
+
+test('landedNewReply: only a new, saved bot message at the end', () => {
+ const before = [USER, ASK];
+ assert.equal(t.landedNewReply(before, [USER, ASK]), false);
+ assert.equal(t.landedNewReply(before, [USER, ASK, REPLY]), true);
+ assert.equal(t.landedNewReply(before, [USER, ASK, { id: 'u2', sender_role: 'user' }]), false);
+ assert.equal(t.landedNewReply(before, [USER, ASK, { id: 'temp-1', sender_role: 'kwant' }]), false);
+ assert.equal(t.landedNewReply(undefined, [REPLY]), true);
+ assert.equal(t.landedNewReply(before, []), false);
+});
+
+test('turn end: TurnComplete\'s load landing alone (turn_ended not here yet) keeps the streamed reply up', async () => {
+ const s = scene();
+ const done1 = s.turnComplete();
+ await s.respond(0); // lands as the newest load, without the reply
+ await done1;
+ const f = s.frames.at(-1);
+ assert.equal(f.live, true);
+ assert.equal(f.replyShown, true, 'the streamed words stay until the saved reply lands');
+ assert.equal(f.approve, null);
+ s.server.push({ ...REPLY });
+ const done2 = s.turnEnded();
+ await s.respond(1);
+ await done2;
+ assert.deepEqual(s.frames.at(-1).ids, ['u1', 'ask', 'pub']);
+ assert.equal(s.frames.at(-1).live, false);
+ for (const fr of s.frames) assert.ok(fr.replyShown && fr.approve === null, `frame "${fr.why}"`);
+});
+
+test('settlesOnTurnComplete: only once that turn is no longer running (or the event has no turn id)', () => {
+ const turns = { 'turn-1': { turn_id: 'turn-1' } };
+ assert.equal(t.settlesOnTurnComplete(turns, 'turn-1'), false);
+ assert.equal(t.settlesOnTurnComplete({}, 'turn-1'), true, 'turn_ended came first');
+ assert.equal(t.settlesOnTurnComplete(turns, 'turn-2'), true);
+ assert.equal(t.settlesOnTurnComplete(turns, undefined), true);
+});
+
+test('turn end: the same race without the 👍 kept as answered still shows no Approve row (the load fix alone)', async () => {
+ const s = scene({ answered: new Set() });
+ const done1 = s.turnComplete();
+ s.server.push({ ...REPLY });
+ const done2 = s.turnEnded();
+ await s.respond(0);
+ await s.respond(1);
+ await Promise.all([done1, done2]);
+ assert.deepEqual(s.frames.filter((f) => f.approve).map((f) => f.why), []);
+});
+
+test('ChatLoads.run: resolves only once the newest load has landed, in either order', async () => {
+ const loads = new t.ChatLoads();
+ const order = [];
+ const f1 = deferred(), f2 = deferred();
+ const p1 = loads.run('c', async (isLatest) => { await f1.p; order.push(`1 latest=${isLatest()}`); }).then(() => order.push('1 resolved'));
+ const p2 = loads.run('c', async (isLatest) => { await f2.p; order.push(`2 latest=${isLatest()}`); }).then(() => order.push('2 resolved'));
+ f1.resolve();
+ await tick();
+ assert.deepEqual(order, ['1 latest=false'], 'the replaced load waits for the newer one');
+ f2.resolve();
+ await Promise.all([p1, p2]);
+ assert.deepEqual(order.slice(0, 2), ['1 latest=false', '2 latest=true']);
+ assert.deepEqual(order.slice(2).sort(), ['1 resolved', '2 resolved']);
+ // another chat's load is not held by this one
+ const f3 = deferred();
+ let other = false;
+ loads.run('c', () => f3.p);
+ await loads.run('d', async () => {}).then(() => (other = true));
+ assert.equal(other, true);
+ f3.resolve();
+ // a failed newer load still lets both resolve (refreshContext reports its own errors), so a settle never hangs
+ const f4 = deferred();
+ const p4 = loads.run('e', async () => {});
+ const p5 = loads.run('e', () => f4.p.then(() => { throw new Error('HTTP 500'); }));
+ f4.resolve();
+ await assert.doesNotReject(p4);
+ await assert.doesNotReject(p5);
+});
+
+test('approveRowId: a reply answered with a 👍 never gets the Approve row back, even as a fresh copy after a reload', () => {
+ const answered = new Set(['ask']);
+ assert.equal(a.approveRowId({ ...ASK }, null, { busy: false, answered: new Set() }), 'ask', 'unanswered: the row shows');
+ assert.equal(a.approveRowId({ ...ASK }, null, { busy: false, answered }), null, 'answered by id: hidden');
+ assert.equal(a.approveRowId({ ...ASK }, null, { busy: true, answered: new Set() }), null, 'a reply running: hidden');
+ assert.equal(a.approveRowId({ ...ASK, id: 'temp-1' }, null, { busy: false, answered: new Set() }), null);
+ assert.equal(a.approveRowId({ ...USER }, null, { busy: false, answered: new Set() }), null);
+ assert.equal(a.approveRowId({ ...ASK }, { question_id: 'q' }, { busy: false, answered: new Set() }), null);
+ assert.equal(a.approveRowId({ ...REPLY }, null, { busy: false, answered }), null);
+ assert.equal(a.approveRowId(undefined, null, { busy: false, answered }), null);
+});
+
+test('App loads the chat through ChatLoads.run, so every settle after refreshContext waits for the newest load', async () => {
+ const src = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ const body = src.slice(src.indexOf('const refreshContext = '), src.indexOf('const rememberThreads'));
+ assert.match(body, /chatLoadsRef\.current\.run\(ctx,/);
+ assert.doesNotMatch(body, /chatLoadsRef\.current\.start\(/);
+ const tc = src.slice(src.indexOf("case 'TurnComplete': {"), src.indexOf("case 'browser_navigated':"));
+ assert.match(tc, /settlesOnTurnComplete\(turnsRef\.current, event\.turn_id\) \|\| landedNewReply\(shown, /);
+});