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.

22x: a Needs-attention row lands on its ask in a thread, however old (#741)

Oleksandr Ivanchenko24e8ec148309
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index e7b3b3c6..99b7ab55 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -160,7 +160,7 @@ import {
turnsAwaitingAnswer,
} from './questions';
import { AwayError, AwayItem, affectsAway, awayApi } from './away';
-import { asksHere, closedId, isHandOff, dismissKind, dropClosed, openTarget as askOpenTarget, resendTarget, retryRoute, switchFor, type AskAction, type Here } from './askHere';
+import { asksHere, closedId, isHandOff, dismissKind, dropClosed, loadAskWindow, openTarget as askOpenTarget, resendTarget, retryRoute, switchFor, type AskAction, type Here } from './askHere';
import { NeedsYouStrip } from './components/NeedsYouStrip';
import { chainBudgetApi } from './chainBudget';
import { needsYouRows, attentionRows } from './chatsTab';
@@ -2425,18 +2425,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
if (t.focusKind === 'approval') return document.querySelector(`[data-approval-card="${CSS.escape(focus)}"]`) ? ring() : false;
if (shownMessagesRef.current.some((m) => m.id === focus)) return ring();
- if (quiet || t.thread_id) return false;
- const ctx = t.channel_id ?? t.kwant_id;
- try {
- const res = await fetch(`/api/channels/${encodeURIComponent(ctx)}/messages?around=${encodeURIComponent(focus)}`);
- if (!res.ok) return false;
- const around: ChatMessage[] = await res.json();
- if (!around.some((m) => m.id === focus) || selectedIdRef.current !== ctx) return false;
- setHistoryWindow({ ctx, messages: around });
- return ring();
- } catch {
- return false;
- }
+ if (quiet) return false;
+ // 22x: a thread too (its route takes `around`); the window shows only while that chat is open.
+ const w = await loadAskWindow<ChatMessage>(t, focus);
+ if (!w || openCtxRef.current !== w.ctx) return false;
+ setHistoryWindow(w);
+ return ring();
};
/** 22i: where an away item lands: its exact chat, and its own message or card to ring there. */
diff --git a/frontend/src/askHere.ts b/frontend/src/askHere.ts
index 022cd14b..ddd82d00 100644
--- a/frontend/src/askHere.ts
+++ b/frontend/src/askHere.ts
@@ -200,6 +200,41 @@ export function openTarget(item: AwayItem, look: OpenLookups = {}): OpenTarget {
return { ...place, focus: msg, focusKind: msg ? 'message' : null };
}
+/**
+ * 22x: where to load the messages around an ask that is older than the chat's latest page. A thread
+ * has its own route (it answers `around` like the chat route since 22x); a channel or direct chat
+ * uses the chat route. `ctx` is the chat the window belongs to (the open thread's id, or the
+ * channel's or bot's), so it shows only while that chat is on screen.
+ */
+export function askWindowUrl(t: Pick<OpenTarget, 'channel_id' | 'kwant_id' | 'thread_id'>, focus: string): { ctx: string; url: string } {
+ const around = `around=${encodeURIComponent(focus)}`;
+ if (t.thread_id) return { ctx: t.thread_id, url: `/api/threads/${encodeURIComponent(t.thread_id)}/messages?${around}` };
+ const ctx = t.channel_id ?? t.kwant_id;
+ return { ctx, url: `/api/channels/${encodeURIComponent(ctx)}/messages?${around}` };
+}
+
+/**
+ * Loads the window around an ask's message. `null` when it can't be shown: the load failed, the
+ * server said it isn't in that chat, or (an older server's thread route ignores `around`) the
+ * window it sent doesn't hold the message.
+ */
+export async function loadAskWindow<M extends { id: string }>(
+ t: Pick<OpenTarget, 'channel_id' | 'kwant_id' | 'thread_id'>,
+ focus: string,
+ get: (url: string) => Promise<Pick<Response, 'ok' | 'json'>> = (url) => fetch(url),
+): Promise<{ ctx: string; messages: M[] } | null> {
+ const { ctx, url } = askWindowUrl(t, focus);
+ try {
+ const res = await get(url);
+ if (!res.ok) return null;
+ const messages: unknown = await res.json();
+ if (!Array.isArray(messages) || !messages.some((m: M) => m?.id === focus)) return null;
+ return { ctx, messages: messages as M[] };
+ } catch {
+ return null;
+ }
+}
+
/** Whether an item lives in the chat on screen. */
export function isHere(item: Pick<AwayItem, 'kwant_id' | 'link'>, here: Here | null): boolean {
if (!here) return false;
diff --git a/frontend/tests/threadAskWindow.test.mjs b/frontend/tests/threadAskWindow.test.mjs
new file mode 100644
index 00000000..9d7138b3
--- /dev/null
+++ b/frontend/tests/threadAskWindow.test.mjs
@@ -0,0 +1,124 @@
+// 22x (brief: autonomy/thread-ask-lands-when-old/brief.md): a Needs-attention row whose notice sits in a
+// thread, older than the thread's latest page (Rigel's F1 on 22i: 150+ messages, the notice near the top),
+// loads the window around it from the thread's own route, shows it, and rings it, like a channel or 1:1.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'DOMParser', 'localStorage', 'sessionStorage', 'getComputedStyle', 'requestAnimationFrame', 'cancelAnimationFrame']) {
+ if (k in dom.window) Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.IS_REACT_ACT_ENVIRONMENT = false;
+dom.window.HTMLElement.prototype.scrollIntoView = function () {};
+dom.window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+if (!('ResizeObserver' in dom.window)) dom.window.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };
+g.ResizeObserver = dom.window.ResizeObserver;
+if (!g.CSS) g.CSS = { escape: (s) => String(s).replace(/["\\]/g, '\\$&') };
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export * from './src/askHere';
+ export { ChatView } from './src/components/ChatView';
+`);
+
+// Rigel's case: a thread with 160 messages; the latest page is the newest 100, the notice is the 4th.
+const thread = Array.from({ length: 160 }, (_, i) => ({
+ id: `m${i}`,
+ thread_id: 'th-1',
+ channel_id: null,
+ direct_kwant_id: null,
+ sender_role: i % 2 ? 'user' : 'kwant',
+ sender_id: i % 2 ? 'me' : 'Quant',
+ text: i === 3 ? 'Stopped: I need you to sign in to GitHub' : `t${i}`,
+ created_at: new Date(Date.UTC(2026, 10, 16, 8, 0, i)).toISOString(),
+ tokens_used: 0,
+}));
+const latestPage = thread.slice(60);
+const notice = 'm3';
+const target = { channel_id: null, kwant_id: 'k-quant', thread_id: 'th-1', focus: notice, focusKind: 'message' };
+
+/** A server: the thread route with `around` (22x) or, for `old`, one that ignores it (before 22x). */
+const server = ({ old = false } = {}) => {
+ const calls = [];
+ const get = async (url) => {
+ calls.push(url);
+ const u = new URL(url, 'http://localhost');
+ const around = u.searchParams.get('around');
+ if (u.pathname !== '/api/threads/th-1/messages') return { ok: false, json: async () => ({ error: 'thread not found' }) };
+ if (old || !around) return { ok: true, json: async () => latestPage };
+ const i = thread.findIndex((x) => x.id === around);
+ if (i < 0) return { ok: false, json: async () => ({ error: "That message isn't in this chat." }) };
+ return { ok: true, json: async () => thread.slice(Math.max(0, i - 50), i + 50) };
+ };
+ return { calls, get };
+};
+
+test('a thread notice older than the latest page: loaded from the thread route, around the notice', async () => {
+ assert.ok(!latestPage.some((x) => x.id === notice), 'the notice is not on the latest page');
+ const s = server();
+ const w = await m.loadAskWindow(target, notice, s.get);
+ assert.deepEqual(s.calls, ['/api/threads/th-1/messages?around=m3']);
+ assert.equal(w.ctx, 'th-1', 'the window belongs to the thread, so it shows while the thread is open');
+ assert.ok(w.messages.some((x) => x.id === notice));
+ assert.deepEqual(w.messages.map((x) => x.id), thread.slice(0, 53).map((x) => x.id));
+});
+
+test('channels and 1:1s keep the chat route; ids are encoded', () => {
+ assert.deepEqual(m.askWindowUrl({ channel_id: 'c 1', kwant_id: 'k', thread_id: null }, 'a/b'), {
+ ctx: 'c 1',
+ url: '/api/channels/c%201/messages?around=a%2Fb',
+ });
+ assert.deepEqual(m.askWindowUrl({ channel_id: null, kwant_id: 'k-1', thread_id: null }, 'x'), {
+ ctx: 'k-1',
+ url: '/api/channels/k-1/messages?around=x',
+ });
+ assert.equal(m.askWindowUrl(target, notice).url, '/api/threads/th-1/messages?around=m3');
+});
+
+test('nothing to show: a 404, a failed load, or an older server that sends the latest page without the notice', async () => {
+ assert.equal(await m.loadAskWindow(target, 'gone', server().get), null);
+ assert.equal(await m.loadAskWindow({ ...target, thread_id: 'th-gone' }, notice, server().get), null);
+ assert.equal(await m.loadAskWindow(target, notice, async () => { throw new Error('offline'); }), null);
+ assert.equal(await m.loadAskWindow(target, notice, server({ old: true }).get), null);
+ assert.equal(await m.loadAskWindow(target, notice, async () => ({ ok: true, json: async () => ({ error: 'x' }) })), null);
+});
+
+test('the window, shown in the thread pane, rings the notice as an ask', async () => {
+ const w = await m.loadAskWindow(target, notice, server().get);
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ const props = {
+ title: 'Quant', subtitle: 'Thread', messages: w.messages, streamingText: '', streamingThinking: '', isStreaming: false,
+ pendingApprovals: [], onSendMessage: () => {}, onResolveApproval: () => {}, kwants: [], teams: [],
+ highlightMessageId: notice, highlightRing: true, onHighlightDone: () => {},
+ };
+ m.flushSync(() => root.render(m.React.createElement(m.ChatView, props)));
+ let el = null;
+ for (let i = 0; i < 20 && !el?.querySelector('[data-flash-kind="ask"]') && el?.getAttribute('data-flash-kind') !== 'ask'; i++) {
+ await new Promise((r) => setTimeout(r, 10));
+ el = host.querySelector(`[data-message-id="${notice}"]`);
+ }
+ assert.ok(el, 'the notice is rendered from the window');
+ const flagged = el.getAttribute('data-flash-kind') === 'ask' ? el : el.querySelector('[data-flash-kind="ask"]');
+ assert.ok(flagged, 'the notice carries the ask ring');
+ root.unmount();
+ host.remove();
+});
+
+test('findAsk no longer gives up on threads: it loads the window, shows it while that chat is open, and rings', () => {
+ const src = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ const body = src.slice(src.indexOf('const findAsk = async'), src.indexOf('const awayLanding ='));
+ assert.ok(body.length > 0);
+ assert.doesNotMatch(body, /t\.thread_id\)\s*return false/, 'threads are not skipped');
+ assert.match(body, /if \(quiet\) return false;/, 'the strip\'s quiet check still never fetches');
+ assert.match(body, /loadAskWindow<ChatMessage>\(t, focus\)/);
+ assert.match(body, /openCtxRef\.current !== w\.ctx\) return false;/);
+ assert.match(body, /setHistoryWindow\(w\);\s*return ring\(\);/);
+});
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 6f55505f..6e41aab0 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -1706,18 +1706,22 @@ pub async fn patch_thread(State(state): State<AppState>, Path(id): Path<String>,
}
}
-pub async fn thread_messages(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+/// A thread's latest 100 messages, or with `around`/`before` an older window, answered exactly
+/// like the chat route ([`crate::server::routes::messages_page`]). 22x: a Needs-attention row
+/// whose notice is older than the latest page loads the window around it.
+pub async fn thread_messages(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+ Query(q): Query<crate::server::routes::MessagesQuery>,
+) -> Response {
match state.db.get_thread(&id).await {
Ok(Some(_)) => {}
Ok(None) => return error(StatusCode::NOT_FOUND, "thread not found"),
Err(_) => return internal(),
}
- match state.db.list_messages(&id, 100).await {
- Ok(mut m) => {
- state.db.attach_chat_fields(&mut m).await;
- Json(m).into_response()
- }
- Err(_) => internal(),
+ match crate::server::routes::messages_page(&state.db, &id, &q).await {
+ Ok(m) => Json(m).into_response(),
+ Err(e) => e.into_response(),
}
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 08c59f87..f00532aa 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -533,6 +533,18 @@ pub async fn list_messages(
Path(channel_or_kwant_id): Path<String>,
Query(q): Query<MessagesQuery>,
) -> Result<Json<Vec<Message>>, (StatusCode, Json<serde_json::Value>)> {
+ messages_page(&state.db, &channel_or_kwant_id, &q).await.map(Json)
+}
+
+/// One page of a chat's messages (channel, direct chat or thread) for [`MessagesQuery`]: the
+/// latest `limit` (default 100), or the window around / page before a message of this chat.
+/// 400 for a bad limit or both anchors, 404 when the anchor isn't in this chat. 22x: the
+/// thread route answers through this too, so an old ask in a thread can be loaded and rung.
+pub(crate) async fn messages_page(
+ db: &crate::db::Database,
+ chat_id: &str,
+ q: &MessagesQuery,
+) -> Result<Vec<Message>, (StatusCode, Json<serde_json::Value>)> {
let err = |status: StatusCode, m: &str| (status, Json(json!({ "error": m })));
let max = crate::db::history::MAX_HISTORY_PAGE;
let limit = match q.limit {
@@ -540,17 +552,16 @@ pub async fn list_messages(
Some(n) if (1..=max).contains(&n) => n,
Some(_) => return Err(err(StatusCode::BAD_REQUEST, &format!("limit must be 1–{max}"))),
};
- let db = &state.db;
let rows = match (q.around.as_deref(), q.before.as_deref()) {
(Some(_), Some(_)) => return Err(err(StatusCode::BAD_REQUEST, "use around or before, not both")),
- (Some(id), None) => db.list_messages_around(&channel_or_kwant_id, id, limit).await,
- (None, Some(id)) => db.list_messages_before(&channel_or_kwant_id, id, limit).await,
- (None, None) => db.list_messages(&channel_or_kwant_id, limit).await.map(Some),
+ (Some(id), None) => db.list_messages_around(chat_id, id, limit).await,
+ (None, Some(id)) => db.list_messages_before(chat_id, id, limit).await,
+ (None, None) => db.list_messages(chat_id, limit).await.map(Some),
};
match rows {
Ok(Some(mut rows)) => {
db.attach_chat_fields(&mut rows).await;
- Ok(Json(rows))
+ Ok(rows)
}
Ok(None) => Err(err(StatusCode::NOT_FOUND, "That message isn't in this chat.")),
Err(_) => Err(err(StatusCode::INTERNAL_SERVER_ERROR, "Could not load messages.")),
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 6820de33..a45eef55 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1557,6 +1557,7 @@ async fn messages_load_around_and_before_a_message() {
for q in [format!("around={foreign}"), format!("before={foreign}"), "around=nope".into()] {
let (s, v) = req(&app, "GET", &format!("{base}?{q}"), None).await;
assert_eq!(s, StatusCode::NOT_FOUND, "{q}");
+ assert_eq!(v, json!({ "code": "not_found", "error": "That message isn't in this chat." }), "{q}");
assert!(!v.to_string().contains("elsewhere"));
}
// Bounded, and one mode at a time
@@ -1587,6 +1588,82 @@ async fn messages_load_around_and_before_a_message() {
assert_eq!(s, StatusCode::UNAUTHORIZED);
}
+/// 22x: a thread takes the same `around`/`before`/`limit` as the chat route, so a Needs-attention
+/// row whose notice is older than the thread's latest page can load it and ring it (Rigel's F1 on
+/// 22i: 150+ messages, the notice near the top). Before 22x the route ignored the query and always
+/// sent the latest 100, so the window had no notice in it.
+#[tokio::test]
+async fn thread_messages_load_around_and_before_an_old_notice() {
+ use kwnt::db::models::MessageExtra;
+ let (app, state, _tmp) = setup().await;
+ let kwant = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap().remove(0);
+ let thread = state.db.create_thread(&kwant.id, "Long hand-off", "chat", None, "user").await.unwrap();
+ let other = state.db.create_thread(&kwant.id, "Another", "chat", None, "user").await.unwrap();
+ let in_thread = |t: &str| MessageExtra { thread_id: Some(t.to_string()), meta: None };
+ let mut ids = Vec::new();
+ for i in 0..160 {
+ let text = if i == 3 { "Stopped: I need you to sign in".to_string() } else { format!("t{i}") };
+ let role = if i % 2 == 0 { "kwant" } else { "user" };
+ ids.push(state.db.insert_message_with(&msg(None, None, role, "x", &text), &in_thread(&thread.id)).await.unwrap().id);
+ if i % 40 == 0 {
+ state.db.insert_message_with(&msg(None, None, "user", "x", "elsewhere"), &in_thread(&other.id)).await.unwrap();
+ }
+ }
+ let notice = ids[3].clone();
+ let foreign = state.db.insert_message_with(&msg(None, None, "user", "x", "elsewhere"), &in_thread(&other.id)).await.unwrap().id;
+ let direct = state.db.insert_message(&msg(None, Some(&kwant.id), "user", "me", "elsewhere")).await.unwrap().id;
+ let ids_of = |v: &Value| v.as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();
+ let span = |a: usize, b: usize| ids[a..b].to_vec();
+ let base = format!("/api/threads/{}/messages", thread.id);
+
+ // Unchanged without parameters: the latest 100, oldest first, and the notice isn't among them
+ let (s, v) = req(&app, "GET", &base, None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(ids_of(&v), span(60, 160));
+ assert!(!ids_of(&v).contains(&notice));
+
+ // Around the notice: the window holds it (3 before it exist, it, and 49 after)
+ let (s, v) = req(&app, "GET", &format!("{base}?around={notice}"), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(ids_of(&v), span(0, 53));
+ assert_eq!(v[3]["text"], "Stopped: I need you to sign in");
+ let (_, v) = req(&app, "GET", &format!("{base}?around={}&limit=10", ids[80]), None).await;
+ assert_eq!(ids_of(&v), span(75, 85));
+
+ // Paging back
+ let (s, v) = req(&app, "GET", &format!("{base}?before={}&limit=30", ids[60]), None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(ids_of(&v), span(30, 60));
+ let (_, v) = req(&app, "GET", &format!("{base}?before={}", ids[0]), None).await;
+ assert_eq!(v, json!([]));
+
+ // A message of another thread, of the bot's 1:1, or none: the chat route's 404, revealing nothing
+ for q in [format!("around={foreign}"), format!("before={foreign}"), format!("around={direct}"), "around=nope".into()] {
+ let (s, v) = req(&app, "GET", &format!("{base}?{q}"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{q}");
+ assert_eq!(v, json!({ "code": "not_found", "error": "That message isn't in this chat." }), "{q}");
+ }
+ // Bounded, and one mode at a time: the chat route's 400s
+ for q in ["limit=0", "limit=201", "limit=-1", &format!("around={}&before={}", ids[1], ids[2])] {
+ let (s, v) = req(&app, "GET", &format!("{base}?{q}"), None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{q}");
+ assert!(v["error"].is_string(), "{q}: {v}");
+ }
+ let (_, v) = req(&app, "GET", &format!("{base}?limit=200"), None).await;
+ assert_eq!(ids_of(&v), span(0, 160));
+
+ // An unknown thread is still "thread not found", with or without a query
+ for q in ["", "?around=nope"] {
+ let (s, v) = req(&app, "GET", &format!("/api/threads/nope/messages{q}"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{q}");
+ assert_eq!(v["error"], "thread not found", "{q}");
+ }
+
+ // Same auth as the rest of the API
+ let (s, _) = call(&app, "GET", &format!("{base}?around={notice}"), None, &[("host", "kwnt.example.com")]).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED);
+}
+
// Notifications
#[tokio::test]