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.

0.8.1 F6: a needs-you notification opens the chat it came from (#485)

Oleksandr Ivanchenko720bee5330f0
diff --git a/apps/mac/src/nudge.rs b/apps/mac/src/nudge.rs
index 1297e6b1..81511990 100644
--- a/apps/mac/src/nudge.rs
+++ b/apps/mac/src/nudge.rs
@@ -293,21 +293,26 @@ pub fn inbox_path(space_id: Option<&str>) -> String {
format!("{}/inbox", space_base(space_id))
}
-/// Where an item opens in the kwant window: its channel, else its bot's chat. A thread has no
-/// address of its own in the page, so a thread item opens the Inbox, where it is one click away.
+/// Where an item opens in the kwant window: its channel (a team chat is one), its bot's
+/// conversation (`/b/<bot>/t/<thread>`, 0.8.1 F6), else its bot's chat. An approval adds
+/// `?card=<id>` so the page shows that card. With no bot to open, the Inbox.
pub fn target_path(item: &Item) -> String {
let base = space_base(item.space_id.as_deref());
+ let card = match item.kind {
+ Kind::Approval if !item.id.is_empty() => format!("?card={}", encode(&item.id)),
+ _ => String::new(),
+ };
if let Some(c) = &item.channel_id {
- return format!("{base}/c/{}", encode(c));
- }
- if item.thread_id.is_some() {
- return format!("{base}/inbox");
+ return format!("{base}/c/{}{card}", encode(c));
}
- let bot = item.direct_kwant_id.as_deref().unwrap_or(&item.kwant_id);
+ let bot = item.direct_kwant_id.as_deref().filter(|b| !b.is_empty()).unwrap_or(&item.kwant_id);
if bot.is_empty() {
return format!("{base}/inbox");
}
- format!("{base}/b/{}", encode(bot))
+ if let Some(t) = item.thread_id.as_deref().filter(|t| !t.is_empty()) {
+ return format!("{base}/b/{}/t/{}{card}", encode(bot), encode(t));
+ }
+ format!("{base}/b/{}{card}", encode(bot))
}
/// Percent-encodes everything but RFC 3986 unreserved characters (a path segment or query value).
@@ -551,7 +556,7 @@ mod tests {
let p = pill(&remote.items).unwrap();
assert_eq!(p.detail, "kwant.jumpin.games · title a");
assert_eq!(p.place, server);
- assert_eq!(p.target, "/s/spc_default/b/k-a");
+ assert_eq!(p.target, "/s/spc_default/b/k-a?card=a");
let three = waiting(vec![item(Kind::Question, "q", "Juno"), item(Kind::Approval, "b", "Mira"), item(Kind::Approval, "c", "Iris")])
.in_place(server, "kwant.jumpin.games");
@@ -643,7 +648,7 @@ mod tests {
assert_eq!(p.headline, "juno needs your OK");
assert_eq!(p.detail, "title a");
assert_eq!(p.initial, "J");
- assert_eq!(p.target, "/s/spc_default/c/ch%2F1");
+ assert_eq!(p.target, "/s/spc_default/c/ch%2F1?card=a");
let q = item(Kind::Question, "q", "Mira");
let p = pill(&[q]).unwrap();
assert_eq!(p.headline, "Mira asked you something");
@@ -674,7 +679,22 @@ mod tests {
i.direct_kwant_id = Some("k9".into());
assert_eq!(target_path(&i), "/s/my%20space/b/k9");
i.thread_id = Some("t1".into());
- assert_eq!(target_path(&i), "/s/my%20space/inbox", "a thread opens the Inbox");
+ assert_eq!(target_path(&i), "/s/my%20space/b/k9/t/t1", "a thread opens itself (0.8.1 F6)");
+ let mut in_thread = item(Kind::Question, "q", "J");
+ in_thread.space_id = Some("s".into());
+ in_thread.kwant_id = "k 1".into();
+ in_thread.thread_id = Some("t/2".into());
+ assert_eq!(target_path(&in_thread), "/s/s/b/k%201/t/t%2F2", "a thread item without a direct link names its bot");
+ let mut approval = item(Kind::Approval, "ap 1", "J");
+ approval.space_id = Some("s".into());
+ approval.kwant_id = "k1".into();
+ approval.thread_id = Some("t1".into());
+ assert_eq!(target_path(&approval), "/s/s/b/k1/t/t1?card=ap%201", "an approval names its card");
+ approval.thread_id = None;
+ approval.channel_id = Some("team-c".into());
+ assert_eq!(target_path(&approval), "/s/s/c/team-c?card=ap%201", "a team chat approval opens the team chat");
+ approval.channel_id = None;
+ assert_eq!(target_path(&approval), "/s/s/b/k1?card=ap%201");
i.channel_id = Some("c1".into());
assert_eq!(target_path(&i), "/s/my%20space/c/c1");
let mut none = item(Kind::Question, "q", "J");
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ba5e7dea..095f36e2 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -50,7 +50,7 @@ import { AwayPage } from './components/AwayView';
import { LooseEndsPage } from './components/LooseEndsView';
import { MissionBoardPage } from './components/MissionBoardView';
import { MISSION_BOARD_SETTING_EVENT, emitMission, parseMissionBoardSetting, sourceChat } from './missions';
-import { type ChatTarget, planOpenTarget } from './chatTarget';
+import { type ChatTarget, type NotifiedChat, notifiedPlace, planOpenTarget } from './chatTarget';
import { ParallelPage } from './components/ParallelUniverseView';
import { ConnectionsPage } from './components/ConnectionsView';
import { IdeaJarView, deleteIdea, dropIdea, emitIdeaUpdated, isIdeaCommand, onIdeaUpdated, useIdeaJarBadge } from './components/ideas';
@@ -175,6 +175,10 @@ export interface SpaceTarget {
botId?: string;
/** W2: the chat's `/live` address, with the browser panel open. */
live?: boolean;
+ /** 0.8.1 F6: one of the bot's conversations (`/b/<bot>/t/<thread>`). */
+ threadId?: string;
+ /** 0.8.1 F6: the card to show there (`?card=`), an approval's id. */
+ cardId?: string;
}
export interface SpaceAppProps {
@@ -559,17 +563,18 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Opens the chat of a bot's newest open browser step; false when it has none.
const openHumanStepRef = useRef<(kwantId: string) => boolean>(() => false);
const openTargetRef = useRef<(t: ChatTarget) => boolean>(() => false);
+ // 0.8.1 F6: opens the chat a notification names (thread, channel or team chat, 1:1) at its card.
+ const openPlaceRef = useRef<(n: NotifiedChat) => boolean>(() => false);
// A tier request or a fact dispute is decided on the board's Needs-you list.
const openBoardForTier = () => showPage('board');
const showNotification = (n: NotifyEvent) => {
// Another space's news is the shell's to show, with a way to switch there.
if (n.space_id && n.space_id !== space.id) return;
if (n.kind === 'automation_suggested') emitContinuity({ type: 'automation_suggested', data: n });
- const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
// Failed routines and finished or slow delegations show in the app; the OS notification is for a hidden tab.
// A question or browser step gets the "needs you" pill instead of a toast (approvals get it from the away list too).
if (!document.hidden && nudgesOnRef.current && (n.kind === 'question_asked' || n.kind === 'human_step')) {
- if (pageRef.current === 'chat' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
+ if (pageRef.current === 'chat' && openCtxRef.current === (n.channel_id ?? (n.thread_id || n.kwant_id))) return;
if (n.kind === 'human_step') {
const nudge = arrivalsRef.current.fromHumanStep(n);
if (nudge) offerNudges([nudge]);
@@ -578,7 +583,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
return;
}
if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {
- if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && n.kind !== 'tier_proposed' && n.kind !== 'fact_disputed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
+ if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && n.kind !== 'tier_proposed' && n.kind !== 'fact_disputed' && openCtxRef.current === (n.channel_id ?? (n.thread_id || n.kwant_id))) return;
const id = ++toastIdRef.current;
const action =
n.kind === 'routine_failed'
@@ -592,10 +597,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
: n.kind === 'fact_disputed'
? { label: 'Settle', onClick: openBoardForTier }
: n.kind === 'question_asked'
- ? { label: 'Answer', onClick: () => openQuestionRef.current(n.kwant_id) || openTargetRef.current(target) }
+ ? { label: 'Answer', onClick: () => openQuestionRef.current(n.kwant_id) || openPlaceRef.current(n) }
: n.kind === 'human_step'
- ? { label: 'Open', onClick: () => openHumanStepRef.current(n.kwant_id) || openTargetRef.current(target) }
- : { label: 'Open', onClick: () => openTargetRef.current(target) };
+ ? { label: 'Open', onClick: () => openHumanStepRef.current(n.kwant_id) || openPlaceRef.current(n) }
+ : { label: 'Open', onClick: () => openPlaceRef.current(n) };
setToasts((prev) => [...prev.slice(-2), { id, title: n.title, detail: n.body, action }]);
if (n.kind !== 'routine_failed') playSfx('alert');
return;
@@ -605,9 +610,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
// A tap on a notification: the bot's skill, question or browser step, else its chat. One about no
// bot opens its place: today's spending stop opens Needs you on it, with Continue today; any other
- // kind (an app update, a loose-end reminder) opens home.
- const openNotified = (n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id'>) => {
- const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
+ // kind (an app update, a loose-end reminder) opens home. 0.8.1 F6: an approval, and anything else
+ // about a chat, opens the exact chat it came from (a thread, a channel or team chat, the 1:1) at
+ // its card; when that chat is gone, the bot's direct chat.
+ const openNotified = (n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id' | 'thread_id' | 'card_id'>) => {
const place = placeOfNotification(n);
if (place === 'spend_stop') openSpendStop();
else if (place === 'home') openHome();
@@ -621,7 +627,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// A CAPTCHA lands straight in the solve view
if (latestOpenStep(humanStepsRef.current, n.kwant_id)?.kind === 'captcha') setSolveRequest((v) => v + 1);
}
- else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openTargetRef.current(target);
+ else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openPlaceRef.current(n);
};
const openNotifiedRef = useRef(openNotified);
const openSpendStopRef = useRef(openSpendStop);
@@ -642,8 +648,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (place === 'spend_stop') return openSpendStopRef.current();
if (m.space_id && m.space_id !== space.id) return;
if (place === 'home') return openHomeRef.current();
- if (!m.kwant_id) return;
- openNotifiedRef.current({ kind: m.kind as NotifyKind, kwant_id: m.kwant_id, channel_id: m.channel_id });
+ // 0.8.1 F6: a tap about a channel or team chat alone (no bot) opens it too
+ openNotifiedRef.current({
+ kind: m.kind as NotifyKind,
+ kwant_id: m.kwant_id ?? '',
+ channel_id: m.channel_id,
+ thread_id: m.thread_id ?? null,
+ card_id: m.card_id ?? null,
+ });
};
sw.addEventListener('message', onMessage);
return () => sw.removeEventListener('message', onMessage);
@@ -939,6 +951,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setIsChannel(false);
isChannelRef.current = false;
setSelectedTeamId(null);
+ // 0.8.1 F6: a notification about one of the bot's conversations opens that one
+ if (initialTarget?.threadId && initialTarget.botId === first.bot.id) openThreadChecked(first.bot.id, initialTarget.threadId);
} else if (first?.kind === 'channel') {
const init = first.channel;
setSelectedId(init.id);
@@ -948,6 +962,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const matchedTeam = teamOfChannel(normalizedTeams, init);
setSelectedTeamId(matchedTeam ? matchedTeam.id : null);
}
+ // 0.8.1 F6: and shows the approval's card it names, when that chat opened
+ const landed = first?.kind === 'bot' ? initialTarget?.botId === first.bot.id : first?.kind === 'channel' && initialTarget?.channelId === first.channel.id;
+ if (landed && initialTarget?.cardId) setHighlightMessageId(initialTarget.cardId);
} catch (err) {
console.error('Failed to load initial data:', err);
} finally {
@@ -2043,13 +2060,63 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (threadsByKwantRef.current[kwantId] === undefined) loadThreads(kwantId);
};
+ /**
+ * 0.8.1 F6: shows one of a bot's conversations a link or notification names. When kwant doesn't
+ * know it yet, asks the server (archived ones included); if it is gone, the bot's direct chat
+ * shows instead, with a line saying so, never an empty pane.
+ */
+ function openThreadChecked(kwantId: string, threadId: string) {
+ const known = knownThreadsRef.current.has(threadId);
+ knownThreadsRef.current.add(threadId);
+ setOpenThreadId(threadId);
+ if (known) return;
+ threadsApi.list(kwantId, true).then((list) => {
+ rememberThreads(list);
+ if (list.some((t) => t.id === threadId)) return;
+ knownThreadsRef.current.delete(threadId);
+ setOpenThreadId((cur) => (cur === threadId ? null : cur));
+ pushToast('That conversation no longer exists, so here is the direct chat.');
+ }, () => undefined);
+ }
+
+ /** 0.8.1 F6: opens the chat a notification names, at its card; false when neither it nor the bot exists. */
+ const openPlace = (n: NotifiedChat): boolean => {
+ const place = notifiedPlace(n, {
+ channel: (id) => channels.some((c) => c.id === id),
+ kwant: (id) => kwants.some((k) => k.id === id),
+ });
+ if (place.kind === 'gone') {
+ pushToast('That chat no longer exists.');
+ return false;
+ }
+ if (place.kind === 'thread') {
+ const kwant = kwants.find((k) => k.id === place.kwant_id)!;
+ setPage('chat');
+ setPhoneView('chat');
+ if (selectedIdRef.current !== kwant.id || isChannelRef.current) handleSelectKwant(kwant);
+ openThreadChecked(place.kwant_id, place.thread_id);
+ } else {
+ // A gone channel lands in the bot's direct chat: say so
+ if (n.channel_id && !place.target.channel_id) pushToast('That chat no longer exists, so here is the direct chat.');
+ openTarget(place.target);
+ setPage('chat');
+ }
+ if (n.card_id) setHighlightMessageId(n.card_id);
+ return true;
+ };
+ openPlaceRef.current = openPlace;
+
/** 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.');
- setPage('chat');
+ // 0.8.1 F6: the same opener as a notification's tap, so a gone chat lands in the bot's 1:1 and
+ // an approval row shows its card
+ openPlace({
+ channel_id: 'channel' in t ? t.channel : null,
+ kwant_id: 'thread' in t ? t.kwant : 'direct' in t ? t.direct : item.kwant_id,
+ thread_id: 'thread' in t ? t.thread : null,
+ card_id: item.kind === 'approval' ? item.id : null,
+ });
};
/** 0.8.0 B3: a pre-push Inbox item opens the bot's chat at its card. */
diff --git a/frontend/src/Shell.tsx b/frontend/src/Shell.tsx
index 62c5d75c..a81da281 100644
--- a/frontend/src/Shell.tsx
+++ b/frontend/src/Shell.tsx
@@ -24,7 +24,7 @@ import {
spacesApi,
} from './spaces';
import { NotifyEvent, TOAST_KINDS, browserNotifyEnabled, notificationPermission, shouldShowOsNotification } from './continuity';
-import { isNotificationOpen, placeOfQuery, resyncPushOnLoad, showDeviceNotification, targetFromQuery } from './push';
+import { cardFromQuery, isNotificationOpen, placeOfQuery, resyncPushOnLoad, showDeviceNotification, spaceTargetOfNotification, targetFromQuery } from './push';
import { requestSpendStopFocus } from './spendStop';
const INBOX_NEW: SpaceView = { kind: 'inbox', tab: 'new' };
@@ -105,13 +105,28 @@ export const App: React.FC = () => {
// The chat's own address with `?live=1` opens its live panel too, as `/live` does (W-L11)
const routed = parseSpacePath(window.location.pathname);
const liveFlag = (routed.channelId || routed.botId) && new URLSearchParams(window.location.search).get('live') === '1';
- const route = q ? { spaceId: q.spaceId, channelId: q.channelId ?? undefined, botId: q.botId ?? undefined, live: q.live } : liveFlag ? { ...routed, live: true } : routed;
+ const route = q
+ ? { spaceId: q.spaceId, channelId: q.channelId ?? undefined, botId: q.botId ?? undefined, live: q.live, threadId: q.threadId ?? undefined }
+ : liveFlag ? { ...routed, live: true } : routed;
const s = pickSpace(list, route.spaceId, lastSpace());
if (!s) return;
const here = route.spaceId === s.id;
- const fromUrl = here && (route.channelId || route.botId || route.live) ? { channelId: route.channelId, botId: route.botId, ...(route.live ? { live: true } : {}) } : null;
+ // 0.8.1 F6: a notification's link names one of the bot's conversations and the card to show
+ const cardId = (q ? q.cardId : cardFromQuery(window.location.search)) || undefined;
+ const fromUrl =
+ here && (route.channelId || route.botId || route.live)
+ ? {
+ channelId: route.channelId,
+ botId: route.botId,
+ ...(route.live ? { live: true } : {}),
+ ...(route.botId && route.threadId ? { threadId: route.threadId } : {}),
+ ...(cardId ? { cardId } : {}),
+ }
+ : null;
// An old address (/away, /loose-ends, /connections…) opens its new place, rewritten in place.
open(s.id, fromUrl, true, here && 'view' in route ? route.view ?? null : null);
+ // The card is shown once: a reload doesn't flash it again
+ if (cardId && window.location.search) window.history.replaceState(null, '', window.location.pathname);
});
}, [reload, open]);
@@ -123,7 +138,7 @@ export const App: React.FC = () => {
const view = route.view ?? null;
if (route.spaceId !== currentRef.current) {
setCurrentSpace(route.spaceId);
- setTarget({ channelId: route.channelId, botId: route.botId, live: route.live });
+ setTarget({ channelId: route.channelId, botId: route.botId, live: route.live, ...(route.threadId ? { threadId: route.threadId } : {}) });
setStartView(view);
setViewRequest(null);
viewRef.current = view;
@@ -191,7 +206,7 @@ export const App: React.FC = () => {
const sid = n.space_id ?? event.space_id;
if (!sid || sid === currentRef.current) return;
const name = n.space_name ?? 'another space';
- const go = () => switchTo(sid, n.channel_id ? { channelId: n.channel_id } : n.kwant_id ? { botId: n.kwant_id } : null);
+ const go = () => switchTo(sid, spaceTargetOfNotification(n));
reload();
if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {
const id = ++toastIdRef.current;
@@ -216,7 +231,7 @@ export const App: React.FC = () => {
const m = e.data;
if (!isNotificationOpen(m) || !m.space_id || m.space_id === currentRef.current) return;
if (!spaces?.some((s) => s.id === m.space_id)) return;
- switchTo(m.space_id, m.channel_id ? { channelId: m.channel_id } : m.kwant_id ? { botId: m.kwant_id } : null);
+ switchTo(m.space_id, spaceTargetOfNotification(m));
};
sw.addEventListener('message', onMessage);
return () => sw.removeEventListener('message', onMessage);
diff --git a/frontend/src/chatTarget.ts b/frontend/src/chatTarget.ts
index 2cab6a2a..7fc81869 100644
--- a/frontend/src/chatTarget.ts
+++ b/frontend/src/chatTarget.ts
@@ -29,3 +29,35 @@ export function planOpenTarget(
if (!t.kwant_id || !exists.kwant(t.kwant_id)) return 'gone';
return !shown.isChannel && shown.selectedId === t.kwant_id && !shown.openThreadId ? 'reveal' : 'select';
}
+
+/** What a needs-you notification names (0.8.1 F6): the chat it was asked in, and the card to show there. */
+export interface NotifiedChat {
+ channel_id?: string | null;
+ kwant_id?: string | null;
+ thread_id?: string | null;
+ card_id?: string | null;
+}
+
+/** Where a tap on a notification lands: one of the bot's conversations, a chat, or nowhere. */
+export type NotifiedPlace =
+ | { kind: 'thread'; kwant_id: string; thread_id: string }
+ | { kind: 'chat'; target: ChatTarget }
+ | { kind: 'gone' };
+
+/**
+ * 0.8.1 F6: the exact place a notification names, else the closest one still there. A channel (a
+ * team chat is one) or the bot's conversation first; when that place is gone, the bot's direct
+ * chat, so a tap never does nothing while the bot exists. `thread` answers false only when the
+ * bot's conversations are known and this one isn't among them (unknown means try it).
+ */
+export function notifiedPlace(
+ n: NotifiedChat,
+ exists: { channel: (id: string) => boolean; kwant: (id: string) => boolean; thread?: (kwantId: string, threadId: string) => boolean },
+): NotifiedPlace {
+ const bot = n.kwant_id && exists.kwant(n.kwant_id) ? n.kwant_id : null;
+ if (n.channel_id && exists.channel(n.channel_id)) return { kind: 'chat', target: { channel_id: n.channel_id, kwant_id: null } };
+ if (!n.channel_id && bot && n.thread_id && (exists.thread?.(bot, n.thread_id) ?? true)) {
+ return { kind: 'thread', kwant_id: bot, thread_id: n.thread_id };
+ }
+ return bot ? { kind: 'chat', target: { channel_id: null, kwant_id: bot } } : { kind: 'gone' };
+}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index b2a96811..fe449a47 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -830,7 +830,19 @@ export const ChatView: React.FC<ChatViewProps> = ({
// A search hit glows amber for 2.4 s; the original of a reply quote gets a violet ring for 1.6 s.
const [flashKind, setFlashKind] = useState<'search' | 'quote'>('search');
useEffect(() => {
- if (!highlightMessageId || !messages.some((m) => m.id === highlightMessageId)) return;
+ if (!highlightMessageId) return;
+ // 0.8.1 F6: an approval's card (a notification names it), not a message
+ if (pendingApprovals.some((a) => a.id === highlightMessageId)) {
+ const card = scrollRef.current?.querySelector<HTMLElement>(`[data-approval-card="${CSS.escape(highlightMessageId)}"]`);
+ if (!card) return;
+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ card.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
+ setFlashKind('search');
+ setFlashId(highlightMessageId);
+ onHighlightDone?.();
+ return;
+ }
+ if (!messages.some((m) => m.id === highlightMessageId)) return;
const thread = groupDiscussionThreads(messages).find(
(item) => item.kind === 'thread' && item.turns.some((t) => t.id === highlightMessageId),
);
@@ -845,7 +857,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
setFlashKind('search');
setFlashId(highlightMessageId);
onHighlightDone?.();
- }, [highlightMessageId, messages, openThoughts, onHighlightDone]);
+ }, [highlightMessageId, messages, openThoughts, onHighlightDone, pendingApprovals]);
useEffect(() => {
if (!flashId) return;
const t = setTimeout(() => setFlashId(null), flashKind === 'quote' ? 1600 : 2400);
@@ -2072,9 +2084,16 @@ export const ChatView: React.FC<ChatViewProps> = ({
{prepush}
{/* Pending Security Approval Ticket */}
- {pendingApprovals.map((approval) => (
- <ModernApprovalCard key={approval.id} approval={approval} onResolve={onResolveApproval} />
- ))}
+ {pendingApprovals.map((approval) =>
+ // 0.8.1 F6: a notification's tap lands on this card and flashes it
+ flashId === approval.id ? (
+ <div key={approval.id} className="rounded-xl kw-flash">
+ <ModernApprovalCard approval={approval} onResolve={onResolveApproval} />
+ </div>
+ ) : (
+ <ModernApprovalCard key={approval.id} approval={approval} onResolve={onResolveApproval} />
+ ),
+ )}
</div>
{/* Suggested prompts for who is in this chat: one swipeable row on phones */}
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index 69ea9a8e..a86be53c 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -200,6 +200,10 @@ export interface NotifyEvent {
/** The space it happened in (servers with spaces). */
space_id?: string;
space_name?: string;
+ /** One of the bot's conversations, when it happened there (0.8.1 F6; absent from older servers). */
+ thread_id?: string | null;
+ /** The card to show there: an approval's id (0.8.1 F6). */
+ card_id?: string | null;
}
// ---------------------------------------------------------------------------
diff --git a/frontend/src/push.ts b/frontend/src/push.ts
index 3ac80319..36bf1538 100644
--- a/frontend/src/push.ts
+++ b/frontend/src/push.ts
@@ -6,15 +6,27 @@ import { BROWSER_NOTIFY_KEY, NotifyEvent, notificationPermission } from './conti
import { isIos, isStandalone } from './pwa';
import { spacePath } from './spaces';
-/** Same as the server's push tag: `kwnt-<space|none>-<kind>-<channel|bot>`. */
-export function notificationTag(n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id'> & { space_id?: string | null }): string {
- return `kwnt-${n.space_id || 'none'}-${n.kind}-${n.channel_id ?? n.kwant_id}`;
+/** Same as the server's push tag: `kwnt-<space|none>-<kind>-<channel|thread|bot>`. */
+export function notificationTag(n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id' | 'thread_id'> & { space_id?: string | null }): string {
+ const thread = !n.channel_id && n.kwant_id && n.thread_id ? n.thread_id : null;
+ return `kwnt-${n.space_id || 'none'}-${n.kind}-${n.channel_id ?? thread ?? n.kwant_id}`;
}
-/** Where a tap on the notification goes: the chat's own address, or the app's start. */
-export function notificationPath(n: { space_id?: string | null; channel_id?: string | null; kwant_id?: string | null }): string {
+/**
+ * Where a tap on the notification goes: the chat's own address (a channel or team chat, the bot's
+ * conversation, else its direct chat), with `?card=` for the card to show there; or the app's start.
+ */
+export function notificationPath(n: {
+ space_id?: string | null;
+ channel_id?: string | null;
+ kwant_id?: string | null;
+ thread_id?: string | null;
+ card_id?: string | null;
+}): string {
if (!n.space_id) return '/';
- return spacePath(n.space_id, { channelId: n.channel_id, botId: n.channel_id ? null : n.kwant_id });
+ const botId = n.channel_id ? null : n.kwant_id;
+ const path = spacePath(n.space_id, { channelId: n.channel_id, botId, threadId: botId ? n.thread_id : null });
+ return n.card_id && (n.channel_id || botId) ? `${path}?card=${encodeURIComponent(n.card_id)}` : path;
}
/** What a tap on a notification asks the open app to show (sw.js posts it; App and Shell act on it). */
@@ -24,6 +36,9 @@ export interface NotificationOpen {
space_id: string | null;
channel_id: string | null;
kwant_id: string | null;
+ /** 0.8.1 F6; absent from a service worker that predates it. */
+ thread_id?: string | null;
+ card_id?: string | null;
}
export function isNotificationOpen(m: unknown): m is NotificationOpen {
@@ -38,6 +53,10 @@ export interface QueryTarget {
live?: boolean;
/** `?notify=<kind>`: a notification about no bot or chat (spend_stopped, app_update, loose ends…). */
notify?: string;
+ /** `&thread=<id>` (0.8.1 F6): the bot's conversation. */
+ threadId?: string | null;
+ /** `&card=<id>` (0.8.1 F6): the card to show, an approval's id. */
+ cardId?: string | null;
}
/**
@@ -52,9 +71,17 @@ export function targetFromQuery(search: string): QueryTarget | null {
const channelId = q.get('channel');
const botId = channelId ? null : q.get('kwant');
if (!spaceId && !channelId && !botId) return null;
- return q.get('live') === '1' && (channelId || botId) ? { spaceId, channelId, botId, live: true } : { spaceId, channelId, botId };
+ const base: QueryTarget = q.get('live') === '1' && (channelId || botId) ? { spaceId, channelId, botId, live: true } : { spaceId, channelId, botId };
+ const threadId = botId ? q.get('thread') : null;
+ const cardId = channelId || botId ? q.get('card') : null;
+ if (threadId) base.threadId = threadId;
+ if (cardId) base.cardId = cardId;
+ return base;
}
+/** `?card=<id>` on a chat's own address (a notification's path, the Mac pill): the card to show. */
+export const cardFromQuery = (search: string): string | null => new URLSearchParams(search).get('card') || null;
+
/** A tap on a notification that opens today's spending stop (it names no bot or chat). */
export const opensSpendStop = (n: { kind?: unknown } | null | undefined): boolean => !!n && n.kind === 'spend_stopped';
@@ -268,6 +295,9 @@ export async function showDeviceNotification(
space_id: n.space_id ?? null,
channel_id: n.channel_id ?? null,
kwant_id: n.kwant_id ?? null,
+ // 0.8.1 F6: only when named, so a notification without them looks as before
+ ...(n.thread_id ? { thread_id: n.thread_id } : {}),
+ ...(n.card_id ? { card_id: n.card_id } : {}),
},
});
return;
@@ -279,3 +309,23 @@ export async function showDeviceNotification(
note.close();
};
}
+
+/**
+ * 0.8.1 F6: where in its space a notification opens: its channel or team chat, else one of the
+ * bot's conversations or its direct chat, with the card to show. A channel's bot rides along so a
+ * gone channel still lands in that bot's direct chat.
+ */
+export function spaceTargetOfNotification(n: {
+ channel_id?: string | null;
+ kwant_id?: string | null;
+ thread_id?: string | null;
+ card_id?: string | null;
+}): { channelId?: string; botId?: string; threadId?: string; cardId?: string } | null {
+ const t: { channelId?: string; botId?: string; threadId?: string; cardId?: string } = {};
+ if (n.channel_id) t.channelId = n.channel_id;
+ if (n.kwant_id) t.botId = n.kwant_id;
+ if (n.kwant_id && !n.channel_id && n.thread_id) t.threadId = n.thread_id;
+ if (!t.channelId && !t.botId) return null;
+ if (n.card_id) t.cardId = n.card_id;
+ return t;
+}
diff --git a/frontend/src/spaces.ts b/frontend/src/spaces.ts
index 43cc0f04..075818f7 100644
--- a/frontend/src/spaces.ts
+++ b/frontend/src/spaces.ts
@@ -170,6 +170,8 @@ export interface SpaceRoute {
spaceId: string | null;
channelId?: string;
botId?: string;
+ /** `/b/<bot>/t/<thread>` (0.8.1 F6): one of the bot's conversations. */
+ threadId?: string;
/** `/live` on a chat address (W2): open it with the browser panel showing. */
live?: boolean;
/** Inbox, Mission board, Parallel Universe or Settings (see nav.ts). */
@@ -183,6 +185,9 @@ export function parseSpacePath(path: string): SpaceRoute {
if (!m) return { spaceId: null };
const spaceId = decodeURIComponent(m[1]);
const rest = m[2] ?? '';
+ // A bot's conversation (0.8.1 F6): what a notification about a thread opens
+ const thread = rest.match(/^b\/([^/]+)\/t\/([^/]+)$/);
+ if (thread) return { spaceId, botId: decodeURIComponent(thread[1]), threadId: decodeURIComponent(thread[2]) };
const chat = rest.match(/^(c|b)\/([^/]+)(\/live)?$/);
const live = chat?.[3] ? { live: true } : {};
if (chat?.[1] === 'c') return { spaceId, channelId: decodeURIComponent(chat[2]), ...live };
@@ -197,13 +202,14 @@ export function parseSpacePath(path: string): SpaceRoute {
export function spacePath(
spaceId: string,
- target?: { channelId?: string | null; botId?: string | null; live?: boolean | null } | null,
+ target?: { channelId?: string | null; botId?: string | null; threadId?: string | null; live?: boolean | null } | null,
view?: SpaceView | null,
): string {
const base = `/s/${encodeURIComponent(spaceId)}`;
if (view) return `${base}/${viewSegment(view)}`;
const live = target?.live ? '/live' : '';
if (target?.channelId) return `${base}/c/${encodeURIComponent(target.channelId)}${live}`;
+ if (target?.botId && target.threadId) return `${base}/b/${encodeURIComponent(target.botId)}/t/${encodeURIComponent(target.threadId)}`;
if (target?.botId) return `${base}/b/${encodeURIComponent(target.botId)}${live}`;
return base;
}
diff --git a/frontend/sw.js b/frontend/sw.js
index 643f51e2..bf7f06b1 100644
--- a/frontend/sw.js
+++ b/frontend/sw.js
@@ -65,12 +65,18 @@ self.addEventListener('fetch', (event) => {
// (src/server/push.rs) to each device that turned on "Notify me on this device"; the open page
// shows its own through showNotification with the same tag and data (src/push.ts).
-/** The chat's address in the app: /s/<space>/c/<channel> or /s/<space>/b/<bot>. */
+/**
+ * The chat's address in the app: /s/<space>/c/<channel>, /s/<space>/b/<bot>/t/<thread> (one of
+ * the bot's conversations) or /s/<space>/b/<bot>, with ?card=<id> for an approval's card
+ * (0.8.1 F6). Same as notificationPath in src/push.ts.
+ */
function notificationPath(p) {
if (!p.space_id) return typeof p.url === 'string' && p.url.startsWith('/') && !p.url.startsWith('//') ? p.url : '/';
const base = `/s/${encodeURIComponent(p.space_id)}`;
- if (p.channel_id) return `${base}/c/${encodeURIComponent(p.channel_id)}`;
- if (p.kwant_id) return `${base}/b/${encodeURIComponent(p.kwant_id)}`;
+ const card = p.card_id && (p.channel_id || p.kwant_id) ? `?card=${encodeURIComponent(p.card_id)}` : '';
+ if (p.channel_id) return `${base}/c/${encodeURIComponent(p.channel_id)}${card}`;
+ if (p.kwant_id && p.thread_id) return `${base}/b/${encodeURIComponent(p.kwant_id)}/t/${encodeURIComponent(p.thread_id)}${card}`;
+ if (p.kwant_id) return `${base}/b/${encodeURIComponent(p.kwant_id)}${card}`;
return base;
}
@@ -100,6 +106,9 @@ self.addEventListener('push', (event) => {
space_id: p.space_id || null,
channel_id: p.channel_id || null,
kwant_id: p.kwant_id || null,
+ // 0.8.1 F6: only when the server named them, so older payloads stay as they were
+ ...(p.thread_id ? { thread_id: p.thread_id } : {}),
+ ...(p.card_id ? { card_id: p.card_id } : {}),
};
event.waitUntil(
windows().then((list) => {
@@ -140,6 +149,9 @@ self.addEventListener('notificationclick', (event) => {
space_id: d.space_id || null,
channel_id: d.channel_id || null,
kwant_id: d.kwant_id || null,
+ // 0.8.1 F6: only when the server named them, so older payloads stay as they were
+ ...(d.thread_id ? { thread_id: d.thread_id } : {}),
+ ...(d.card_id ? { card_id: d.card_id } : {}),
});
return client.focus().catch(() => self.clients.openWindow(path));
}),
diff --git a/frontend/tests/chatTarget.test.mjs b/frontend/tests/chatTarget.test.mjs
index b4fc94f9..d6cf23e5 100644
--- a/frontend/tests/chatTarget.test.mjs
+++ b/frontend/tests/chatTarget.test.mjs
@@ -42,3 +42,37 @@ test("App's openTarget closes the board and Inbox when the chat is already selec
assert.ok(open, 'openTarget exists');
assert.match(open[1], /if \(plan === 'reveal'\) revealChat\(\);/);
});
+
+// ---------------------------------------------------------------------------
+// 0.8.1 F6: a needs-you notification opens the exact chat it came from, else the bot's 1:1
+
+const { notifiedPlace } = await loadBundled(`export * from './src/chatTarget';`);
+
+test('an approval asked in a team chat or channel opens that chat', () => {
+ // A team chat is a channel ("team-core")
+ assert.deepEqual(notifiedPlace({ channel_id: 'c1', kwant_id: 'shelly', card_id: 'ap1' }, exists), {
+ kind: 'chat',
+ target: { channel_id: 'c1', kwant_id: null },
+ });
+});
+
+test('an approval asked in one of the bot’s conversations opens that conversation', () => {
+ assert.deepEqual(notifiedPlace({ channel_id: null, kwant_id: 'shelly', thread_id: 't1' }, exists), { kind: 'thread', kwant_id: 'shelly', thread_id: 't1' });
+});
+
+test('an approval asked in the 1:1, or an old notification without a thread, opens the 1:1', () => {
+ assert.deepEqual(notifiedPlace({ channel_id: null, kwant_id: 'shelly' }, exists), { kind: 'chat', target: { channel_id: null, kwant_id: 'shelly' } });
+});
+
+test('a gone channel or conversation lands in the bot’s 1:1, never a dead tap', () => {
+ const direct = { kind: 'chat', target: { channel_id: null, kwant_id: 'shelly' } };
+ assert.deepEqual(notifiedPlace({ channel_id: 'c-gone', kwant_id: 'shelly' }, exists), direct);
+ assert.deepEqual(notifiedPlace({ channel_id: null, kwant_id: 'shelly', thread_id: 't-gone' }, { ...exists, thread: () => false }), direct);
+});
+
+test('with the bot gone too there is nowhere to go; a channel alone still opens', () => {
+ assert.deepEqual(notifiedPlace({ channel_id: 'c-gone', kwant_id: 'ghost' }, exists), { kind: 'gone' });
+ assert.deepEqual(notifiedPlace({ channel_id: null, kwant_id: 'ghost', thread_id: 't1' }, exists), { kind: 'gone' });
+ // A tap about a channel with no bot named (the page used to drop these)
+ assert.deepEqual(notifiedPlace({ channel_id: 'c2', kwant_id: null }, exists), { kind: 'chat', target: { channel_id: 'c2', kwant_id: null } });
+});
diff --git a/frontend/tests/push.test.mjs b/frontend/tests/push.test.mjs
index cd93d206..7bf688b5 100644
--- a/frontend/tests/push.test.mjs
+++ b/frontend/tests/push.test.mjs
@@ -296,3 +296,75 @@ test('a replaced subscription is sent to the server and the old one dropped', as
{ url: '/api/push/unsubscribe', body: { endpoint: 'https://push.example/old' } },
]);
});
+
+// ---------------------------------------------------------------------------
+// 0.8.1 F6: a tap lands in the exact chat the notification came from, at its card
+
+test('a notification about a bot’s conversation names it in its tag and its address', () => {
+ // Same cases as payload_names_the_thread_and_the_card in src/server/push.rs
+ assert.equal(p.notificationTag({ space_id: 's1', kind: 'approval_needed', channel_id: null, kwant_id: 'k1', thread_id: 't 1' }), 'kwnt-s1-approval_needed-t 1');
+ assert.equal(p.notificationTag({ space_id: 's1', kind: 'approval_needed', channel_id: 'c1', kwant_id: 'k1', thread_id: 't1' }), 'kwnt-s1-approval_needed-c1');
+ assert.equal(p.notificationPath({ space_id: 's1', channel_id: null, kwant_id: 'k1', thread_id: 't 1', card_id: 'ap1' }), '/s/s1/b/k1/t/t%201?card=ap1');
+ assert.equal(p.notificationPath({ space_id: 's1', channel_id: 'team-core', kwant_id: 'k1', card_id: 'ap 1' }), '/s/s1/c/team-core?card=ap%201');
+ assert.equal(p.notificationPath({ space_id: 's1', channel_id: null, kwant_id: 'k1', card_id: 'ap1' }), '/s/s1/b/k1?card=ap1');
+ // No space: the app's start, as before
+ assert.equal(p.notificationPath({ space_id: null, kwant_id: 'k1', thread_id: 't1', card_id: 'ap1' }), '/');
+});
+
+test('the push url’s thread and card work as a link too', () => {
+ assert.deepEqual(p.targetFromQuery('?space=s1&kwant=k1&thread=t%201&card=ap1'), { spaceId: 's1', channelId: null, botId: 'k1', threadId: 't 1', cardId: 'ap1' });
+ assert.deepEqual(p.targetFromQuery('?space=s1&channel=c1&card=ap1'), { spaceId: 's1', channelId: 'c1', botId: null, cardId: 'ap1' });
+ // A thread needs its bot
+ assert.deepEqual(p.targetFromQuery('?space=s1&channel=c1&thread=t1'), { spaceId: 's1', channelId: 'c1', botId: null });
+ assert.equal(p.cardFromQuery('?card=ap1'), 'ap1');
+ assert.equal(p.cardFromQuery(''), null);
+});
+
+test('another space opens on the notification’s chat, conversation and card', () => {
+ assert.deepEqual(p.spaceTargetOfNotification({ channel_id: 'team-core', kwant_id: 'k1', card_id: 'ap1' }), { channelId: 'team-core', botId: 'k1', cardId: 'ap1' });
+ assert.deepEqual(p.spaceTargetOfNotification({ channel_id: null, kwant_id: 'k1', thread_id: 't1', card_id: 'ap1' }), { botId: 'k1', threadId: 't1', cardId: 'ap1' });
+ assert.deepEqual(p.spaceTargetOfNotification({ channel_id: 'c1', kwant_id: null }), { channelId: 'c1' });
+ assert.equal(p.spaceTargetOfNotification({ channel_id: null, kwant_id: null, card_id: 'x' }), null);
+});
+
+test('the page’s own notification carries the thread and card to the tap', async () => {
+ const shown = [];
+ const reg = { showNotification: async (title, opts) => shown.push({ title, opts }) };
+ await p.showDeviceNotification(
+ { kind: 'approval_needed', kwant_id: 'k1', kwant_name: 'Ada', channel_id: null, thread_id: 't1', card_id: 'ap1', title: 'Ada needs approval', body: 'Run tests?', space_id: 's1' },
+ () => undefined,
+ { serviceWorker: { getRegistration: async () => reg } },
+ );
+ assert.equal(shown[0].opts.tag, 'kwnt-s1-approval_needed-t1');
+ assert.deepEqual(shown[0].opts.data, {
+ path: '/s/s1/b/k1/t/t1?card=ap1', kind: 'approval_needed', space_id: 's1', channel_id: null, kwant_id: 'k1', thread_id: 't1', card_id: 'ap1',
+ });
+});
+
+test('a push about a conversation opens it at the card, kwant closed or open', async () => {
+ const payload = { ...PAYLOAD, channel_id: null, thread_id: 't1', card_id: 'ap1', url: '/?space=s1&kwant=k1&thread=t1&card=ap1', tag: 'kwnt-s1-approval_needed-t1' };
+ const sw = loadWorker();
+ await sw.push(payload);
+ const data = plain(sw.log.shown[0].data);
+ assert.deepEqual(data, { path: '/s/s1/b/k1/t/t1?card=ap1', kind: 'approval_needed', space_id: 's1', channel_id: null, kwant_id: 'k1', thread_id: 't1', card_id: 'ap1' });
+ // Closed: it opens on that address
+ await sw.click(data);
+ assert.deepEqual(sw.log.opened, ['/s/s1/b/k1/t/t1?card=ap1']);
+ // Open (another space or chat): the app is told the thread and card
+ const open = loadWorker({ clients: [{ url: '/s/s2/c/zz' }] });
+ await open.click(data);
+ assert.deepEqual(plain(open.log.posted.map((x) => x.m)), [
+ { type: 'kwnt-notification-open', kind: 'approval_needed', space_id: 's1', channel_id: null, kwant_id: 'k1', thread_id: 't1', card_id: 'ap1' },
+ ]);
+});
+
+test('a tap about a team chat alone (no bot) is posted to the app, which opens it', async () => {
+ const sw = loadWorker({ clients: [{ url: '/s/s1/c/zz' }] });
+ await sw.click({ path: '/s/s1/c/team-core?card=ap1', kind: 'approval_needed', space_id: 's1', channel_id: 'team-core', kwant_id: null, card_id: 'ap1' });
+ assert.deepEqual(plain(sw.log.posted.map((x) => x.m)), [
+ { type: 'kwnt-notification-open', kind: 'approval_needed', space_id: 's1', channel_id: 'team-core', kwant_id: null, card_id: 'ap1' },
+ ]);
+ // App.tsx no longer drops it for having no bot
+ const app = readFileSync(`${root}/src/App.tsx`, 'utf8');
+ assert.ok(!app.includes('if (!m.kwant_id) return;'));
+});
diff --git a/frontend/tests/spaces.test.mjs b/frontend/tests/spaces.test.mjs
index dfdbeff1..83748b58 100644
--- a/frontend/tests/spaces.test.mjs
+++ b/frontend/tests/spaces.test.mjs
@@ -105,3 +105,14 @@ test('a reload or link reopens the bot or channel in the address, and a gone one
assert.equal(m.pickInitialChat({ botId: 'gone' }, bots, [], 'ch1')?.bot.id, 'k1');
assert.equal(m.pickInitialChat({ botId: 'gone' }, [], [], 'ch1'), null);
});
+
+// 0.8.1 F6: a notification about one of a bot's conversations opens that conversation
+test('a bot’s conversation has its own address, and reads back', () => {
+ assert.equal(m.spacePath('spc_b', { botId: 'k1', threadId: 't 1' }), '/s/spc_b/b/k1/t/t%201');
+ assert.deepEqual(m.parseSpacePath('/s/spc_b/b/k1/t/t%201'), { spaceId: 'spc_b', botId: 'k1', threadId: 't 1' });
+ // A channel wins; a thread without a bot is no address
+ assert.equal(m.spacePath('spc_b', { channelId: 'c1', botId: 'k1', threadId: 't1' }), '/s/spc_b/c/c1');
+ assert.equal(m.spacePath('spc_b', { threadId: 't1' }), '/s/spc_b');
+ // The old addresses are unchanged
+ assert.deepEqual(m.parseSpacePath('/s/spc_b/b/k1'), { spaceId: 'spc_b', botId: 'k1' });
+});
diff --git a/frontend/tests/spendStop.test.mjs b/frontend/tests/spendStop.test.mjs
index c578d995..2edd37db 100644
--- a/frontend/tests/spendStop.test.mjs
+++ b/frontend/tests/spendStop.test.mjs
@@ -237,7 +237,10 @@ test('with the app open: the worker’s message for a stop opens Needs you; othe
assert.equal(m.placeOfNotification({ ...open, kind: 'app_update', kwant_id: '' }), 'home');
// The App branches on it before the old kwant_id check, and the page's own notification goes the same way.
const app = src('App.tsx');
- assert.match(app, /const place = placeOfNotification\(m\);\s*if \(place === 'spend_stop'\) return openSpendStopRef\.current\(\);[\s\S]*?if \(place === 'home'\) return openHomeRef\.current\(\);\s*if \(!m\.kwant_id\) return;/);
+ // 0.8.1 F6: after those two, the rest opens its chat; a channel or team chat with no bot is no longer dropped.
+ assert.match(app, /const place = placeOfNotification\(m\);\s*if \(place === 'spend_stop'\) return openSpendStopRef\.current\(\);[\s\S]*?if \(place === 'home'\) return openHomeRef\.current\(\);[^\n]*\n(?:\s*\/\/[^\n]*\n)*\s*openNotifiedRef\.current\(\{[^}]*channel_id: m\.channel_id,[^}]*thread_id: m\.thread_id \?\? null,[^}]*card_id: m\.card_id \?\? null,[^}]*\}\);/);
+ assert.doesNotMatch(app, /if \(place === 'home'\) return openHomeRef\.current\(\);\s*if \(!m\.kwant_id\) return;/);
+ assert.equal(m.placeOfNotification({ ...open, kind: 'approval_needed', channel_id: 'c1' }), null);
assert.match(app, /const place = placeOfNotification\(n\);\s*if \(place === 'spend_stop'\) openSpendStop\(\);\s*else if \(place === 'home'\) openHome\(\);/);
assert.match(app, /top=\{\s*<>\s*<PrepushNeedsYou [^\n]*\/>\s*<SpendStopNeedsYou refreshKey=\{spendStopSeq\}/);
});
diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rs
index e718d2ae..c98d2ac1 100644
--- a/src/db/approval_modes.rs
+++ b/src/db/approval_modes.rs
@@ -239,6 +239,16 @@ impl Database {
Ok(())
}
+ /// The chat approval `id`'s card is in, as [`Self::set_approval_chat`] stored it; `None` when
+ /// the ticket is unknown or was stored without one.
+ pub async fn approval_chat(&self, id: &str) -> Result<Option<serde_json::Value>, DbError> {
+ let row: Option<(Option<String>,)> = sqlx::query_as("SELECT resume FROM approvals WHERE id = ?")
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.and_then(|(r,)| r).and_then(|r| serde_json::from_str(&r).ok()))
+ }
+
/// Cards left `pending` by an earlier run of kwant: nothing waits on them any more, so they
/// become `waiting` (answerable, a late Allow resumes the work). A card stored before its chat
/// was recorded gets the chat of the turn that asked, else the bot's direct chat. Returns how
diff --git a/src/documents/reminders.rs b/src/documents/reminders.rs
index 139f0304..ca0550a0 100644
--- a/src/documents/reminders.rs
+++ b/src/documents/reminders.rs
@@ -142,6 +142,8 @@ pub async fn run_once(state: &crate::server::AppState, now: DateTime<Utc>) -> Fi
channel_id: None,
title: fired.title(),
body: fired.body(),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index a560e9f2..bc4cc38e 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -379,6 +379,13 @@ pub enum RuntimeEvent {
/// a mission or a Jira task, so Telegram may tell them to send it again.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
held_message: bool,
+ /// The bot's conversation (thread) the notification is about, when it is one: a tap
+ /// opens it instead of the bot's direct chat (0.8.1 F6). Absent on older events.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ thread_id: Option<String>,
+ /// The card to show in that chat: an approval's id (0.8.1 F6).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ card_id: Option<String>,
},
}
diff --git a/src/server/app_update_routes.rs b/src/server/app_update_routes.rs
index 34354dd5..e14fbf90 100644
--- a/src/server/app_update_routes.rs
+++ b/src/server/app_update_routes.rs
@@ -73,6 +73,8 @@ pub async fn notify_once(state: &AppState, version: &str) -> bool {
channel_id: None,
title: format!("kwant bots {version} is ready"),
body: "Open kwant bots to update and restart.".into(),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 7cc77e11..8015a007 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -1770,7 +1770,7 @@ fn clip(text: &str, max: usize) -> String {
}
/// A notification: what the SSE event carries and the webhook posts.
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Default)]
pub struct Notification {
pub kind: &'static str,
pub kwant_id: String,
@@ -1778,6 +1778,11 @@ pub struct Notification {
pub channel_id: Option<String>,
pub title: String,
pub body: String,
+ /// The bot's conversation it is about, when it is one (a question, a browser step or an
+ /// approval asked there): a tap opens that thread, not the bot's direct chat (0.8.1 F6).
+ pub thread_id: Option<String>,
+ /// The card to show once there: an approval's id (0.8.1 F6).
+ pub card_id: Option<String>,
}
/// Sends `n` to the UI, the webhook and push subscriptions, if the user wants this kind. The body never holds chat
@@ -1814,7 +1819,8 @@ pub async fn notify_held(state: &AppState, n: Notification, space: Option<&crate
None => (None, None),
};
if !state.push.subscriptions().is_empty() {
- let payload = super::push::Payload::new(n.kind, &title, &body, space_id.clone(), n.channel_id.clone(), n.kwant_id.clone());
+ let payload = super::push::Payload::new(n.kind, &title, &body, space_id.clone(), n.channel_id.clone(), n.kwant_id.clone())
+ .at(n.thread_id.clone(), n.card_id.clone());
let push = state.push.clone();
tokio::spawn(async move { push.send_all(&payload).await });
}
@@ -1828,6 +1834,8 @@ pub async fn notify_held(state: &AppState, n: Notification, space: Option<&crate
space_id,
space_name,
held_message,
+ thread_id: n.thread_id,
+ card_id: n.card_id,
});
let Some(url) = state
.db
@@ -1950,6 +1958,11 @@ async fn place(state: &AppState, context_id: Option<&str>) -> (Option<String>, S
pub async fn turn_finished(state: &AppState, kwant_id: &str, context_id: Option<&str>) -> Notification {
let name = kwant_name(state, kwant_id).await;
let (channel_id, where_) = place(state, context_id).await;
+ // A turn in one of the bot's conversations opens that conversation (0.8.1 F6)
+ let thread_id = match (&channel_id, context_id) {
+ (None, Some(id)) if id != kwant_id && state.db.get_thread(id).await.ok().flatten().is_some() => Some(id.to_string()),
+ _ => None,
+ };
Notification {
kind: "turn_finished",
kwant_id: kwant_id.to_string(),
@@ -1957,6 +1970,8 @@ pub async fn turn_finished(state: &AppState, kwant_id: &str, context_id: Option<
body: format!("{name} finished replying in {where_}."),
kwant_name: name,
channel_id,
+ thread_id,
+ card_id: None,
}
}
@@ -1979,13 +1994,16 @@ async fn notification_for(state: &AppState, event: &RuntimeEvent) -> Option<Noti
Some(turn_finished(state, kwant_id, context_id.as_deref()).await)
}
RuntimeEvent::ApprovalRequired {
- tool_name, details, ..
+ id, tool_name, details,
} => {
let kwant_id = details["kwant_id"].as_str().unwrap_or("").to_string();
let name = match details["kwant_name"].as_str() {
Some(n) => n.to_string(),
None => kwant_name(state, &kwant_id).await,
};
+ // The chat the card is in (stored with the ticket before the event is sent): a tap
+ // opens that channel, team chat or conversation, else the bot's direct chat (0.8.1 F6)
+ let (channel_id, thread_id) = approval_place(state, id).await;
Some(Notification {
kind: "approval_needed",
kwant_id,
@@ -1995,17 +2013,45 @@ async fn notification_for(state: &AppState, event: &RuntimeEvent) -> Option<Noti
clip(tool_name, 80)
),
kwant_name: name,
- channel_id: None,
+ channel_id,
+ thread_id,
+ card_id: Some(id.clone()),
})
}
_ => None,
}
}
+/// Where approval `id`'s card is: `(channel, thread)` from the chat stored with the ticket, both
+/// `None` for the bot's direct chat (or a ticket stored without one, as before 0.8.1).
+async fn approval_place(state: &AppState, id: &str) -> (Option<String>, Option<String>) {
+ let chat = state.db.approval_chat(id).await.ok().flatten();
+ place_of_chat(chat.as_ref())
+}
+
+/// `{"channel_id"|"thread_id"|"direct_kwant_id": …}` (the approvals `resume` column) as `(channel, thread)`.
+fn place_of_chat(chat: Option<&serde_json::Value>) -> (Option<String>, Option<String>) {
+ let field = |k: &str| chat.and_then(|c| c[k].as_str()).filter(|s| !s.is_empty()).map(str::to_string);
+ match field("thread_id") {
+ Some(t) => (None, Some(t)),
+ None => (field("channel_id"), None),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn approval_chat_names_the_place() {
+ use serde_json::json;
+ assert_eq!(place_of_chat(Some(&json!({"channel_id": "c1"}))), (Some("c1".into()), None));
+ assert_eq!(place_of_chat(Some(&json!({"thread_id": "t1"}))), (None, Some("t1".into())));
+ assert_eq!(place_of_chat(Some(&json!({"direct_kwant_id": "k1"}))), (None, None));
+ assert_eq!(place_of_chat(Some(&json!({"channel_id": ""}))), (None, None));
+ assert_eq!(place_of_chat(None), (None, None));
+ }
+
fn memory(id: &str, text: &str) -> Memory {
let now = chrono::Utc::now();
Memory {
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 90eec1e5..948b3235 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -733,6 +733,8 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R
channel_id: done.origin_channel_id.clone(),
title: format!("{} finished a task for {lead_name}", specialist.name),
body: format!("“{}”: {status}.", clip(&done.title, 80)),
+ thread_id: None,
+ card_id: None,
},
)
.await;
@@ -1345,6 +1347,8 @@ pub async fn follow_ups(state: &AppState, now: chrono::DateTime<Utc>) -> usize {
channel_id: d.origin_channel_id.clone(),
title: format!("{specialist} is still on a delegated task"),
body: format!("“{}”: {minutes} min so far.", clip(&d.title, 80)),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/goals/mod.rs b/src/server/goals/mod.rs
index de170ac4..3b137a4e 100644
--- a/src/server/goals/mod.rs
+++ b/src/server/goals/mod.rs
@@ -445,7 +445,7 @@ pub async fn notice(state: &AppState, g: &Goal, kind: &str, title: String, body:
return false;
};
let _ = state.db.add_goal_event(&g.id, "notified", "kwant", &json!({ "kind": kind })).await;
- notify(state, Notification { kind: "goal_alert", kwant_id: bot.id, kwant_name: bot.name, channel_id: None, title, body }).await;
+ notify(state, Notification { kind: "goal_alert", kwant_id: bot.id, kwant_name: bot.name, channel_id: None, title, body, thread_id: None, card_id: None }).await;
true
}
diff --git a/src/server/human_steps.rs b/src/server/human_steps.rs
index 4081cc62..9e3f2d2a 100644
--- a/src/server/human_steps.rs
+++ b/src/server/human_steps.rs
@@ -542,6 +542,8 @@ async fn raise_step(
channel_id: origin.channel_id.clone(),
title: format!("{} needs you in the browser", scope.kwant_name),
body: format!("{}. Open the chat, do it in the browser panel, then press Done.", kind_label(&step.kind)),
+ thread_id: step.thread_id.clone(),
+ card_id: None,
},
)
.await;
diff --git a/src/server/idea_jar.rs b/src/server/idea_jar.rs
index 132e9f85..0171228a 100644
--- a/src/server/idea_jar.rs
+++ b/src/server/idea_jar.rs
@@ -425,6 +425,8 @@ where
channel_id: None,
title: format!("{} peeked at your idea", bot.name),
body: "Open the idea jar to see the take.".into(),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/missions/discovery.rs b/src/server/missions/discovery.rs
index d555fa9a..956e7055 100644
--- a/src/server/missions/discovery.rs
+++ b/src/server/missions/discovery.rs
@@ -254,6 +254,8 @@ async fn announce(state: &AppState, o: &Offer) {
title: format!("Suggested routine: {}", o.name),
kwant_name,
channel_id: None,
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/missions/flight_school.rs b/src/server/missions/flight_school.rs
index 0e3fe5ca..b9b690fd 100644
--- a/src/server/missions/flight_school.rs
+++ b/src/server/missions/flight_school.rs
@@ -591,6 +591,8 @@ pub async fn call_propose(state: &AppState, scope: &crate::server::continuity::S
channel_id: None,
title: format!("{} asks for {to} on {class}", bot.name),
body: format!("{} asks to move from {tier} to {to} on {class} tasks, with {verified} verified in the last {WINDOW_DAYS} days.", bot.name),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/missions/truth_ledger.rs b/src/server/missions/truth_ledger.rs
index 60cde86d..3890396b 100644
--- a/src/server/missions/truth_ledger.rs
+++ b/src/server/missions/truth_ledger.rs
@@ -526,6 +526,8 @@ async fn announce(state: &AppState, d: &Dispute, new: bool) {
channel_id: None,
title: format!("{name}: two facts disagree"),
body: "Two saved facts can't both hold. Open Facts to choose which one stands, or mark them as not a conflict.".into(),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/push.rs b/src/server/push.rs
index 9380be66..6e269237 100644
--- a/src/server/push.rs
+++ b/src/server/push.rs
@@ -67,9 +67,16 @@ pub struct Payload {
pub space_id: Option<String>,
pub channel_id: Option<String>,
pub kwant_id: String,
- /// Relative: `/?space=<id>&channel=<id>`, or `&kwant=<id>` without a channel.
+ /// Relative: `/?space=<id>&channel=<id>`, or `&kwant=<id>` without a channel, plus
+ /// `&thread=<id>` and `&card=<id>` when [`Payload::at`] names them.
pub url: String,
pub tag: String,
+ /// The bot's conversation it is about (0.8.1 F6); old service workers ignore it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub thread_id: Option<String>,
+ /// The card to show there: an approval's id (0.8.1 F6).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub card_id: Option<String>,
}
impl Payload {
@@ -106,7 +113,30 @@ impl Payload {
kwant_id,
url: format!("/?{}", query.join("&")),
tag,
+ thread_id: None,
+ card_id: None,
+ }
+ }
+
+ /// The same notification about one of the bot's conversations (`thread`, kept with `kwant=`
+ /// so an older page still opens the bot) and the card to show there. The tag names the
+ /// thread, so one conversation's notification doesn't replace another's.
+ pub fn at(mut self, thread_id: Option<String>, card_id: Option<String>) -> Self {
+ let enc = |s: &str| percent_encoding::utf8_percent_encode(s, QUERY_VALUE).to_string();
+ if self.channel_id.is_none() && !self.kwant_id.is_empty() {
+ if let Some(t) = thread_id.as_deref().filter(|t| !t.is_empty()) {
+ self.url.push_str(&format!("&thread={}", enc(t)));
+ self.tag = format!("kwnt-{}-{}-{t}", self.space_id.as_deref().unwrap_or("none"), self.kind);
+ self.thread_id = Some(t.to_string());
+ }
+ }
+ if !self.url.contains("notify=") {
+ if let Some(c) = card_id.as_deref().filter(|c| !c.is_empty()) {
+ self.url.push_str(&format!("&card={}", enc(c)));
+ self.card_id = Some(c.to_string());
+ }
}
+ self
}
/// The person is waiting on these: kept a day and sent at high urgency (a spending stop that
@@ -883,4 +913,27 @@ mod tests {
assert!(huge.to_bytes().len() <= MAX_PAYLOAD_BYTES);
assert_eq!(topic("kwnt-x").len(), 32);
}
+
+ /// 0.8.1 F6: a notification about a conversation opens it, and an approval names its card.
+ #[test]
+ fn payload_names_the_thread_and_the_card() {
+ let p = Payload::new("approval_needed", "Ada needs approval", "b", Some("s1".into()), None, "k1".into()).at(Some("t 1".into()), Some("ap1".into()));
+ assert_eq!(p.url, "/?space=s1&kwant=k1&thread=t%201&card=ap1", "kwant= stays for older pages");
+ assert_eq!(p.tag, "kwnt-s1-approval_needed-t 1");
+ assert_eq!((p.thread_id.as_deref(), p.card_id.as_deref()), (Some("t 1"), Some("ap1")));
+ let json: serde_json::Value = serde_json::from_slice(&p.to_bytes()).unwrap();
+ assert_eq!((json["thread_id"].as_str(), json["card_id"].as_str()), (Some("t 1"), Some("ap1")));
+ // A channel (or team chat) wins over a thread: its card is in the channel
+ let p = Payload::new("approval_needed", "t", "b", Some("s1".into()), Some("c1".into()), "k1".into()).at(Some("t1".into()), Some("ap1".into()));
+ assert_eq!((p.url.as_str(), p.tag.as_str(), p.thread_id), ("/?space=s1&channel=c1&card=ap1", "kwnt-s1-approval_needed-c1", None));
+ // Nothing to add: unchanged, and the JSON has no new keys (old service workers)
+ let plain = Payload::new("turn_finished", "t", "b", None, None, "k1".into());
+ let p = plain.clone().at(None, None);
+ assert_eq!(p, plain);
+ let json: serde_json::Value = serde_json::from_slice(&p.to_bytes()).unwrap();
+ assert!(json.get("thread_id").is_none() && json.get("card_id").is_none());
+ // About no bot: no thread or card to open
+ let p = Payload::new("spend_stopped", "t", "b", None, None, String::new()).at(Some("t1".into()), Some("x".into()));
+ assert_eq!(p.url, "/?notify=spend_stopped");
+ }
}
diff --git a/src/server/questions.rs b/src/server/questions.rs
index 94daaf34..1291c9e3 100644
--- a/src/server/questions.rs
+++ b/src/server/questions.rs
@@ -301,6 +301,8 @@ pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (Str
channel_id: origin.channel_id.clone(),
title: format!("{} has a question", scope.kwant_name),
body: "Open the chat to answer.".into(),
+ thread_id: q.thread_id.clone(),
+ card_id: None,
},
)
.await;
@@ -565,6 +567,8 @@ pub async fn ask_without_waiter(state: &AppState, place: &QuestionPlace, kwant_n
channel_id: q.channel_id.clone(),
title: format!("{kwant_name} has a question"),
body: "Open the chat to answer.".into(),
+ thread_id: q.thread_id.clone(),
+ card_id: None,
},
)
.await;
@@ -692,6 +696,8 @@ pub async fn record_native(state: &AppState, place: &QuestionPlace, kwant_name:
channel_id: q.channel_id.clone(),
title: format!("{kwant_name} has a question"),
body: "Open the chat to answer.".into(),
+ thread_id: q.thread_id.clone(),
+ card_id: None,
},
)
.await;
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 504e8ec1..c7048a6d 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -581,6 +581,8 @@ pub async fn start_run(state: &AppState, routine: RoutineRow, trigger: &str) ->
"The routine \"{}\" did not finish. Open kwant bots to see its run history.",
routine.name
),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/show_once/draft.rs b/src/server/show_once/draft.rs
index 894a7ae5..9e2dd4d3 100644
--- a/src/server/show_once/draft.rs
+++ b/src/server/show_once/draft.rs
@@ -474,6 +474,8 @@ where
channel_id: None,
title: format!("{bot_name} wrote the skill you showed"),
body: format!("{bot_name} wrote {} from what you showed. Review it before it's used.", skill.name),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/skills.rs b/src/server/skills.rs
index ecf81e4a..90481351 100644
--- a/src/server/skills.rs
+++ b/src/server/skills.rs
@@ -500,6 +500,8 @@ pub async fn tool_propose(state: &AppState, scope: &SelfScope, args: &Value) ->
channel_id: None,
title: format!("{} proposed a skill", scope.kwant_name),
body: format!("{} proposed the skill {} for your review.", scope.kwant_name, skill.name),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/server/spend_stop.rs b/src/server/spend_stop.rs
index bc0b7e65..c2bc72e0 100644
--- a/src/server/spend_stop.rs
+++ b/src/server/spend_stop.rs
@@ -215,6 +215,8 @@ async fn tripped(state: &AppState, s: &Status, space: Option<&SpaceId>, held_mes
channel_id: None,
title: "Today's spending limit is reached".into(),
body: format!("Used {}, so bots won't start new work until tomorrow. Open to continue today.", used_of(s)),
+ thread_id: None,
+ card_id: None,
};
super::continuity::notify_held(state, n, space, held_message).await;
}
diff --git a/src/server/sse.rs b/src/server/sse.rs
index bb485101..eb7ddbf5 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -335,6 +335,8 @@ mod tests {
space_id: Some(s("spc_x")),
space_name: None,
held_message: false,
+ thread_id: None,
+ card_id: None,
},
];
for e in &all {
diff --git a/src/server/waiting.rs b/src/server/waiting.rs
index f2fb12a1..ae48b9a9 100644
--- a/src/server/waiting.rs
+++ b/src/server/waiting.rs
@@ -164,6 +164,8 @@ async fn remind(state: &AppState, w: &WaitingItem) -> bool {
channel_id: w.channel_id.clone(),
title: format!("{} is still waiting on you", kwant.name),
body: "Open the chat to answer.".into(),
+ thread_id: w.thread_id.clone(),
+ card_id: None,
},
)
.await;
diff --git a/src/server/work_ahead.rs b/src/server/work_ahead.rs
index 9d468555..ddd2ee20 100644
--- a/src/server/work_ahead.rs
+++ b/src/server/work_ahead.rs
@@ -221,6 +221,8 @@ pub async fn run(state: &AppState, c: Candidate, row: WorkAheadRun) -> Option<Me
channel_id: c.channel_id.clone(),
title: format!("{} worked ahead while you were away", c.lead.name),
body: "Open the chat to see what's ready.".into(),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/src/zombie/hunt.rs b/src/zombie/hunt.rs
index 01049d24..4f346afa 100644
--- a/src/zombie/hunt.rs
+++ b/src/zombie/hunt.rs
@@ -562,6 +562,8 @@ pub async fn review(state: &AppState, trigger: &str) -> Result<Vec<String>, Scan
channel_id: None,
title: format!("Loose ends review: {n} thing{} to pick back up", if n == 1 { "" } else { "s" }),
body: review_body(&picked, total),
+ thread_id: None,
+ card_id: None,
},
)
.await;
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index e83206da..0bbe6e7a 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1788,6 +1788,8 @@ async fn notifications_are_filtered_and_content_free() {
channel_id: None,
title: "t".into(),
body: "b".into(),
+ thread_id: None,
+ card_id: None,
},
)
.await;
@@ -1800,6 +1802,8 @@ async fn notifications_are_filtered_and_content_free() {
channel_id: None,
title: "t".into(),
body: "word ".repeat(100),
+ thread_id: None,
+ card_id: None,
},
)
.await;
@@ -1843,3 +1847,108 @@ async fn prompt_sends_website_logins_to_a_browser_sign_in_only_with_the_browser(
assert!(!block.contains("Never handle keys, passwords or sign-ins"));
}
}
+
+/// 0.8.1 F6: an approval's notification names the chat its card is in (a team chat, a channel,
+/// one of the bot's conversations, or its direct chat) and the card, so a tap lands there.
+#[tokio::test]
+async fn approval_notification_opens_the_chat_it_was_asked_in() {
+ let (_app, state, _tmp) = setup().await;
+ let space = kwnt::db::spaces::SpaceId::default_space();
+ let kwants = state.db.list_kwants(&space).await.unwrap();
+ let k = &kwants[0];
+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();
+ state
+ .db
+ .create_team(&space, &NewTeam {
+ name: "core".into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: k.id.clone(),
+ member_kwants: vec![k.id.clone()],
+ workspace_path: None,
+ repo_url: None,
+ })
+ .await
+ .unwrap();
+ let team_chat = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "team-core").unwrap();
+ let thread = state.db.create_thread(&k.id, "Launch plan", "chat", None, "user").await.unwrap();
+ state.db.set_setting("notify_on", r#"["approval_needed"]"#).await.unwrap();
+
+ let cases: Vec<(&str, Value, Option<String>, Option<String>)> = vec![
+ ("team chat", json!({"channel_id": team_chat.id}), Some(team_chat.id.clone()), None),
+ ("channel", json!({"channel_id": general.id}), Some(general.id.clone()), None),
+ ("thread", json!({"thread_id": thread.id}), None, Some(thread.id.clone())),
+ ("1:1", json!({"direct_kwant_id": k.id}), None, None),
+ ];
+ let handle = continuity::spawn_notifier(state.clone());
+ for (label, chat, want_channel, want_thread) in cases {
+ let ticket = state
+ .db
+ .save_approval(&kwnt::db::models::NewApproval {
+ turn_id: format!("turn-{label}"),
+ kwant_id: k.id.clone(),
+ tool_name: "mcp__github__create_issue".into(),
+ parameters: json!({}),
+ })
+ .await
+ .unwrap()
+ .id;
+ state.db.set_approval_chat(&ticket, &chat).await.unwrap();
+ let mut rx = state.event_sender.subscribe();
+ let _ = state.event_sender.send(RuntimeEvent::ApprovalRequired {
+ id: ticket.clone(),
+ tool_name: "mcp__github__create_issue".into(),
+ details: json!({"kwant_id": k.id, "kwant_name": k.name}),
+ });
+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
+ let mut got = None;
+ while got.is_none() && tokio::time::Instant::now() < deadline {
+ if let Ok(Ok(RuntimeEvent::Notify { kind, kwant_id, channel_id, thread_id, card_id, .. })) =
+ tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await
+ {
+ if kind == "approval_needed" && card_id.as_deref() == Some(ticket.as_str()) {
+ got = Some((kwant_id, channel_id, thread_id));
+ }
+ }
+ }
+ let (kwant_id, channel_id, thread_id) = got.unwrap_or_else(|| panic!("{label}: no notification"));
+ assert_eq!(kwant_id, k.id, "{label}");
+ assert_eq!(channel_id, want_channel, "{label}");
+ assert_eq!(thread_id, want_thread, "{label}");
+ }
+
+ // A ticket stored without a chat (older servers, the computer's shell card) opens the bot as before
+ let mut rx = state.event_sender.subscribe();
+ let _ = state.event_sender.send(RuntimeEvent::ApprovalRequired {
+ id: "no-such-ticket".into(),
+ tool_name: "execute_shell".into(),
+ details: json!({"kwant_id": k.id, "kwant_name": k.name}),
+ });
+ let mut got = None;
+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
+ while got.is_none() && tokio::time::Instant::now() < deadline {
+ if let Ok(Ok(RuntimeEvent::Notify { kind, channel_id, thread_id, card_id, .. })) =
+ tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await
+ {
+ if kind == "approval_needed" {
+ got = Some((channel_id, thread_id, card_id));
+ }
+ }
+ }
+ handle.abort();
+ assert_eq!(got, Some((None, None, Some("no-such-ticket".to_string()))));
+}
+
+/// 0.8.1 F6: a reply finished in one of the bot's conversations notifies with that thread.
+#[tokio::test]
+async fn a_turn_in_a_thread_notifies_with_the_thread() {
+ let (_app, state, _tmp) = setup().await;
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
+ let k = &kwants[0];
+ let thread = state.db.create_thread(&k.id, "Launch plan", "chat", None, "user").await.unwrap();
+ let n = continuity::turn_finished(&state, &k.id, Some(&thread.id)).await;
+ assert_eq!(n.thread_id.as_deref(), Some(thread.id.as_str()));
+ assert_eq!(n.channel_id, None);
+ let n = continuity::turn_finished(&state, &k.id, Some(&k.id)).await;
+ assert_eq!(n.thread_id, None, "the direct chat is no thread");
+}
diff --git a/tests/push_test.rs b/tests/push_test.rs
index 5a8106ab..5612891f 100644
--- a/tests/push_test.rs
+++ b/tests/push_test.rs
@@ -129,6 +129,8 @@ fn note(kind: &'static str) -> Notification {
channel_id: Some("ch-1".into()),
title: "Ada needs your approval".into(),
body: "Run `cargo test`?".into(),
+ thread_id: None,
+ card_id: None,
}
}