Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(console): mention the people in a chat as well as its agents

raullopez-sandboxc90300597790
diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts
index 2042547fb..f7b715489 100644
--- a/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts
@@ -36,6 +36,7 @@ function message(roomId: string, seq: number): ChatMessage {
attachments: [],
clientTxn: null,
namedAgentIds: [],
+ namedUserIds: [],
threadReplyCount: 0,
threadLastReplySeq: null,
};
diff --git a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts b/console/apps/switch-console-desktop/src/main/core/chats/controller.ts
index b0a24c232..f2108b897 100644
--- a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/chats/controller.ts
@@ -214,6 +214,7 @@ export const chatsController = createRPCController({
threadRootId: input.threadRootId,
uploadIds: input.uploadIds,
mentionAgentIds: input.mentionAgentIds,
+ mentionUserIds: input.mentionUserIds,
})
),
threadMessages: (params: {
diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts
index 381766abb..ba2cd72c4 100644
--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts
+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts
@@ -227,6 +227,7 @@ export async function sendChatMessage(
threadRootId: string | null;
uploadIds: string[];
mentionAgentIds?: string[];
+ mentionUserIds?: string[];
}
): Promise<ChatMessage[]> {
return (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.ts
new file mode 100644
index 000000000..16ef22c70
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/chat-people.ts
@@ -0,0 +1,42 @@
+import { useQuery } from '@tanstack/react-query';
+import { rpc } from '@renderer/lib/ipc';
+import type { ChatSummary } from '@shared/core/chats/chats';
+import { chatsStore } from './stores/chats';
+
+/**
+ * The query for a chat's members, keyed on who the live summary says is in it,
+ * so an add, a removal or a swap by anyone reads the list again.
+ */
+export function chatMembersQueryKey(serverId: string, chat: ChatSummary) {
+ return ['chat-members', serverId, chat.roomId, chat.memberUserIds.join(',')] as const;
+}
+
+/** The workspace roster, the people a chat can hold; shared with Add participants. */
+export function workspaceRosterQuery(serverId: string, tenantId: string | null) {
+ return {
+ queryKey: ['workspace-members', serverId, tenantId] as const,
+ queryFn: () => rpc.chats.workspaceMembers({ serverId, tenantId: tenantId as string }),
+ enabled: tenantId !== null,
+ };
+}
+
+/** The other people in a chat, with their email from the roster when it has one. */
+export function useChatPeople(
+ serverId: string,
+ chat: ChatSummary | undefined
+): { userId: string; name: string; email: string | null }[] {
+ const members = useQuery({
+ queryKey: chat ? chatMembersQueryKey(serverId, chat) : ['chat-members', serverId, null],
+ queryFn: () => rpc.chats.members(serverId, (chat as ChatSummary).roomId),
+ enabled: chat !== undefined,
+ });
+ const roster = useQuery(workspaceRosterQuery(serverId, chatsStore.tenantId));
+ const emails = new Map((roster.data ?? []).map((person) => [person.userId, person.email]));
+ return (members.data ?? [])
+ .filter((member) => member.userId !== chatsStore.userId)
+ .map((member) => ({
+ userId: member.userId,
+ name: member.name,
+ email: emails.get(member.userId) ?? null,
+ }));
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
index bbceea88b..47b0fb5c9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
@@ -8,14 +8,20 @@ import { modalStore } from '@renderer/lib/modal/modal-store';
import { Button } from '@renderer/lib/ui/button';
import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@renderer/lib/ui/popover';
import { cn } from '@renderer/utils/utils';
+import { agentInitials } from '@shared/core/agents/agent-avatar';
import { type ChatAgent, type ChatMessage, chatAgentLabel } from '@shared/core/chats/chats';
import { snippetOf } from '../chat-threads';
import {
+ agentTargets,
filterMentionAgents,
+ filterMentionPeople,
mentionAgentIds,
+ type MentionPerson,
mentionQuery,
mentionSegments,
mentionTokens,
+ mentionUserIds,
+ personTargets,
tokenToRemove,
} from '../mentions';
import { isInterruptAck } from '../stop-rows';
@@ -43,6 +49,10 @@ function chatFile(file: File): ChatFile {
return { name: file.name, type: file.type, size: file.size, read: () => toBase64(file) };
}
+type Suggestion =
+ | { kind: 'agent'; id: string; agent: ChatAgent }
+ | { kind: 'person'; id: string; person: MentionPerson & { email: string | null } };
+
/** Drafts by chat, so a draft outlives navigating away. */
const drafts = new Map<string, string>();
@@ -146,6 +156,7 @@ export const ChatComposer = observer(function ChatComposer({
serverId,
timeline,
agents,
+ people,
groupName,
activity,
replyTo,
@@ -155,6 +166,8 @@ export const ChatComposer = observer(function ChatComposer({
serverId: string;
timeline: ChatTimeline;
agents: ChatAgent[];
+ /** The other people in the chat, who can be mentioned after its agents. */
+ people: (MentionPerson & { email: string | null })[];
/** The chat's name when it is a group, which is who a message goes to; null in a direct chat. */
groupName: string | null;
activity: AgentActivity | null;
@@ -177,9 +190,26 @@ export const ChatComposer = observer(function ChatComposer({
const [mentionIndex, setMentionIndex] = useState(0);
/** Where the `@` of a suggestion list Esc closed sits, so it stays closed for that `@`. */
const [dismissedAt, setDismissedAt] = useState<number | null>(null);
- const tokens = mentionTokens(draft, agents);
- const query = agents.length ? mentionQuery(draft, caret) : null;
- const suggestions = query ? filterMentionAgents(agents, query.query) : [];
+ /** People picked from the list; one sharing an agent's name is read as the person. */
+ const [pickedPeople, setPickedPeople] = useState<ReadonlySet<string>>(new Set());
+ const targets = [
+ ...personTargets(people.filter((person) => pickedPeople.has(person.userId))),
+ ...agentTargets(agents),
+ ...personTargets(people.filter((person) => !pickedPeople.has(person.userId))),
+ ];
+ const tokens = mentionTokens(draft, targets);
+ const mentionable = agents.length > 0 || people.length > 0;
+ const query = mentionable ? mentionQuery(draft, caret) : null;
+ const suggestions: Suggestion[] = query
+ ? [
+ ...filterMentionAgents(agents, query.query).map(
+ (agent): Suggestion => ({ kind: 'agent', id: agent.id, agent })
+ ),
+ ...filterMentionPeople(people, query.query).map(
+ (person): Suggestion => ({ kind: 'person', id: `user:${person.userId}`, person })
+ ),
+ ]
+ : [];
const suggesting = query !== null && query.start !== dismissedAt && suggestions.length > 0;
const activeIndex = Math.min(mentionIndex, suggestions.length - 1);
const listId = `mentions-${timeline.roomId}`;
@@ -221,16 +251,19 @@ export const ChatComposer = observer(function ChatComposer({
input.current?.focus();
};
- const pick = (picked: ChatAgent) => {
+ const pick = (picked: Suggestion) => {
const textarea = input.current;
if (!textarea || !query) return;
+ const name = picked.kind === 'agent' ? picked.agent.name : picked.person.name;
+ if (picked.kind === 'person')
+ setPickedPeople((current) => new Set(current).add(picked.person.userId));
textarea.focus();
textarea.setSelectionRange(query.start, caret);
// insertText keeps the native undo stack; a controlled-value write would wipe it.
- if (!document.execCommand('insertText', false, `@${picked.name} `)) {
- const next = `${draft.slice(0, query.start)}@${picked.name} ${draft.slice(caret)}`;
+ if (!document.execCommand('insertText', false, `@${name} `)) {
+ const next = `${draft.slice(0, query.start)}@${name} ${draft.slice(caret)}`;
setDraft(next);
- setCaret(query.start + picked.name.length + 2);
+ setCaret(query.start + name.length + 2);
}
setMentionIndex(0);
};
@@ -280,12 +313,14 @@ export const ChatComposer = observer(function ChatComposer({
timeline.send({
body,
threadRootId: replyTo?.messageId ?? null,
- mentionAgentIds: mentionAgentIds(mentionTokens(body, agents)),
+ mentionAgentIds: mentionAgentIds(mentionTokens(body, targets)),
+ mentionUserIds: mentionUserIds(mentionTokens(body, targets)),
files: files.map(({ file }) => chatFile(file)),
});
void chatTitler.sent(serverId, timeline.roomId, body);
setDraft('');
setFiles([]);
+ setPickedPeople(new Set());
onClearReply();
};
@@ -364,7 +399,7 @@ export const ChatComposer = observer(function ChatComposer({
<div
id={listId}
role="listbox"
- aria-label="Mention an agent"
+ aria-label="Mention an agent or person"
className="absolute bottom-full left-0 z-50 mb-3 flex max-h-60 w-72 flex-col overflow-y-auto rounded-md border bg-background-quaternary p-1 text-sm shadow-sm"
>
{suggestions.map((each, index) => (
@@ -382,17 +417,36 @@ export const ChatComposer = observer(function ChatComposer({
onMouseDown={(event) => event.preventDefault()}
onClick={() => pick(each)}
>
- <AgentAvatar
- name={each.name}
- iconUrl={each.iconUrl}
- serverId={serverId}
- size={20}
- />
- <span className="truncate">{chatAgentLabel(each)}</span>
- {each.alias && (
- <span className="truncate text-xs text-foreground-muted">
- @{each.alias}
- </span>
+ {each.kind === 'agent' ? (
+ <>
+ <AgentAvatar
+ name={each.agent.name}
+ iconUrl={each.agent.iconUrl}
+ serverId={serverId}
+ size={20}
+ />
+ <span className="truncate">{chatAgentLabel(each.agent)}</span>
+ {each.agent.alias && (
+ <span className="truncate text-xs text-foreground-muted">
+ @{each.agent.alias}
+ </span>
+ )}
+ </>
+ ) : (
+ <>
+ <span
+ aria-hidden
+ className="flex size-5 shrink-0 items-center justify-center rounded-full bg-[var(--fill-2)] text-[9px] font-medium text-foreground"
+ >
+ {agentInitials(each.person.name)}
+ </span>
+ <span className="truncate">{each.person.name}</span>
+ {each.person.email && (
+ <span className="ml-auto truncate text-xs text-foreground-muted">
+ {each.person.email}
+ </span>
+ )}
+ </>
)}
</div>
))}
@@ -404,10 +458,16 @@ export const ChatComposer = observer(function ChatComposer({
className="pointer-events-none absolute inset-0 overflow-y-auto px-1 py-1.5 text-sm break-words whitespace-pre-wrap text-transparent"
>
{mentionSegments(draft, tokens).map((segment, index) =>
- segment.agentId ? (
+ segment.token ? (
<MentionMark
key={index}
- agent={agents.find((each) => each.id === segment.agentId) ?? null}
+ kind={segment.token.kind}
+ // People are never tinted: their badge stays grey.
+ agent={
+ segment.token.kind === 'agent'
+ ? (agents.find((each) => each.id === segment.token?.id) ?? null)
+ : null
+ }
serverId={serverId}
className="text-transparent"
>
@@ -427,9 +487,9 @@ export const ChatComposer = observer(function ChatComposer({
placeholder={disabled ?? `Message ${recipient}...`}
value={draft}
disabled={disabled !== null}
- role={agents.length ? 'combobox' : undefined}
- aria-autocomplete={agents.length ? 'list' : undefined}
- aria-expanded={agents.length ? suggesting : undefined}
+ role={mentionable ? 'combobox' : undefined}
+ aria-autocomplete={mentionable ? 'list' : undefined}
+ aria-expanded={mentionable ? suggesting : undefined}
aria-controls={suggesting ? listId : undefined}
aria-activedescendant={
suggesting ? `${listId}-${suggestions[activeIndex]!.id}` : undefined
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
index defc68e8c..ad13a01d8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from 'react';
import { Button } from '@renderer/lib/ui/button';
import { SERVER_TOO_OLD_FOR_ACTIVITY } from '@shared/core/chats/activity';
import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';
+import { useChatPeople } from '../chat-people';
import { agentActivities } from '../stores/activities';
import type { AgentActivity } from '../stores/chat-activity-store';
import type { ChatTimeline } from '../stores/chat-timeline-store';
@@ -76,6 +77,7 @@ export const ChatPanel = observer(function ChatPanel({
const timeline = chatsStore.timelines.get(serverId, roomId);
const chat = chatsStore.chat(roomId);
const activities = useAgentActivities(serverId, chat);
+ const people = useChatPeople(serverId, chat);
const [replyTo, setReplyTo] = useState<ChatMessage | null>(null);
const lost = timeline.accessLost || chatsStore.removed.has(roomId);
@@ -154,6 +156,7 @@ export const ChatPanel = observer(function ChatPanel({
serverId={serverId}
timeline={timeline}
agents={chat?.agents ?? []}
+ people={people}
activities={activities}
onReply={setReplyTo}
/>
@@ -177,6 +180,7 @@ export const ChatPanel = observer(function ChatPanel({
serverId={serverId}
timeline={timeline}
agents={chat?.agents ?? []}
+ people={people}
groupName={chat && chat.channelType !== 'direct' ? chat.name : null}
activity={activities[0] ?? null}
replyTo={replyTo}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx
index 236013ae7..777a4e6fa 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx
@@ -15,7 +15,13 @@ import {
} from '@shared/core/chats/chats';
import { foldTurnEndNotices, placeTurns, type TurnActivity } from '../activity-join';
import { messageAnchorId, threadChip } from '../chat-threads';
-import { mentionSegments, mentionTokens } from '../mentions';
+import {
+ agentTargets,
+ type MentionPerson,
+ mentionSegments,
+ mentionTokens,
+ personTargets,
+} from '../mentions';
import { hiddenStopRows } from '../stop-rows';
import type { AgentActivity } from '../stores/chat-activity-store';
import type { ChatTimeline, PendingSend } from '../stores/chat-timeline-store';
@@ -58,19 +64,33 @@ function isBridged(message: ChatMessage): boolean {
/** A person's initials disc: people have no picture in Switch. */
/** `body` with each `@name` or `@alias` of a chat agent drawn as a badge. */
function MentionText({
- body,
+ message,
agents,
+ people,
serverId,
}: {
- body: string;
+ message: ChatMessage;
agents: ChatAgent[];
+ people: MentionPerson[];
serverId: string;
}) {
- return mentionSegments(body, mentionTokens(body, agents)).map((segment, index) =>
- segment.agentId ? (
+ // The people the message names come first, so one sharing an agent's name reads as the person.
+ const targets = [
+ ...personTargets(people.filter((person) => message.namedUserIds.includes(person.userId))),
+ ...agentTargets(agents),
+ ];
+ const body = message.body;
+ return mentionSegments(body, mentionTokens(body, targets)).map((segment, index) =>
+ segment.token ? (
<MentionMark
key={index}
- agent={agents.find((agent) => agent.id === segment.agentId) ?? null}
+ kind={segment.token.kind}
+ // People are never tinted: their badge stays grey.
+ agent={
+ segment.token.kind === 'agent'
+ ? (agents.find((agent) => agent.id === segment.token?.id) ?? null)
+ : null
+ }
serverId={serverId}
className="text-foreground"
>
@@ -131,6 +151,8 @@ type Props = {
serverId: string;
timeline: ChatTimeline;
agents: ChatAgent[];
+ /** The chat's people, to name the ones a message mentions. */
+ people: MentionPerson[];
activities: AgentActivity[];
onReply: (message: ChatMessage) => void;
};
@@ -144,6 +166,7 @@ export const ChatTimelineView = observer(function ChatTimelineView({
serverId,
timeline,
agents,
+ people,
activities,
onReply,
}: Props) {
@@ -305,7 +328,12 @@ export const ChatTimelineView = observer(function ChatTimelineView({
</span>
{chip && <ThreadChipButton chip={chip} />}
<div className="min-w-0 rounded-2xl bg-background-1 px-4 py-2.5 text-sm leading-relaxed break-words whitespace-pre-wrap">
- <MentionText body={message.body} agents={agents} serverId={serverId} />
+ <MentionText
+ message={message}
+ agents={agents}
+ people={people}
+ serverId={serverId}
+ />
</div>
<ChatAttachments
serverId={serverId}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/mention-mark.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/mention-mark.tsx
index 56096a0da..46b8e037a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/mention-mark.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/mention-mark.tsx
@@ -10,11 +10,14 @@ import { MENTION_BADGE } from '../mentions';
* behind the composer's text, so it must not change the text's width.
*/
export function MentionMark({
+ kind,
agent,
serverId,
className,
children,
}: {
+ kind: 'agent' | 'person';
+ /** The agent mentioned; null for a person, whose badge is never tinted. */
agent: ChatAgent | null;
serverId: string;
className: string;
@@ -24,6 +27,7 @@ export function MentionMark({
const tint = accent ? `color-mix(in srgb, ${accent} 18%, transparent)` : null;
return (
<mark
+ data-mention={kind}
className={cn(tint ? 'rounded-sm' : MENTION_BADGE, className)}
style={tint ? { backgroundColor: tint, boxShadow: `0 0 0 2px ${tint}` } : undefined}
>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts
index 7312e9a21..695f3fae6 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/mentions.ts
@@ -4,19 +4,36 @@ import type { ChatAgent } from '@shared/core/chats/chats';
const NAME_CHAR = /[A-Za-z0-9._-]/;
export type MentionAgent = Pick<ChatAgent, 'id' | 'name' | 'alias'>;
-export type MentionToken = { agentId: string; start: number; end: number };
+/** A person in the chat, mentioned by their whole display name, spaces and all. */
+export type MentionPerson = { userId: string; name: string };
+/** Someone a mention can name: an agent or a person, by the names they answer to. */
+export type MentionTarget = { kind: 'agent' | 'person'; id: string; names: string[] };
+export type MentionToken = { kind: 'agent' | 'person'; id: string; start: number; end: number };
+
+/** Agents as mention targets, by name and alias. */
+export function agentTargets(agents: MentionAgent[]): MentionTarget[] {
+ return agents.map((agent) => ({
+ kind: 'agent',
+ id: agent.id,
+ names: [agent.name, agent.alias].filter((name): name is string => Boolean(name)),
+ }));
+}
+
+/** People as mention targets, by their display name. */
+export function personTargets(people: MentionPerson[]): MentionTarget[] {
+ return people.map((person) => ({ kind: 'person', id: person.userId, names: [person.name] }));
+}
/**
- * Every whole `@name` or `@alias` of a chat agent in `text`, in order. Derived
- * from the text alone, so undo, paste and a restored draft keep their badges,
- * and an edit inside one (or the agent leaving the chat) turns it back to text.
+ * Every whole `@name` of a target in `text`, in order. Where a person and an
+ * agent share a name, the target listed first wins. Derived from the text
+ * alone, so undo, paste and a restored draft keep their badges, and an edit
+ * inside one (or its owner leaving the chat) turns it back to text.
*/
-export function mentionTokens(text: string, agents: MentionAgent[]): MentionToken[] {
- const spoken = agents
- .flatMap((agent) =>
- [agent.name, agent.alias].flatMap((name) => (name ? [{ agent, name }] : []))
- )
- // Longest first, so `@cc-2` is never read as `@cc` followed by text.
+export function mentionTokens(text: string, targets: MentionTarget[]): MentionToken[] {
+ const spoken = targets
+ .flatMap((target) => target.names.map((name) => ({ target, name })))
+ // Longest first, so `@cc-2` is never read as `@cc` followed by text; the sort is stable, so ties keep the callers' order.
.sort((a, b) => b.name.length - a.name.length);
const tokens: MentionToken[] = [];
for (let at = text.indexOf('@'); at !== -1; at = text.indexOf('@', at + 1)) {
@@ -29,7 +46,12 @@ export function mentionTokens(text: string, agents: MentionAgent[]): MentionToke
);
});
if (!hit) continue;
- tokens.push({ agentId: hit.agent.id, start: at, end: at + 1 + hit.name.length });
+ tokens.push({
+ kind: hit.target.kind,
+ id: hit.target.id,
+ start: at,
+ end: at + 1 + hit.name.length,
+ });
at += hit.name.length;
}
return tokens;
@@ -37,7 +59,21 @@ export function mentionTokens(text: string, agents: MentionAgent[]): MentionToke
/** The agents a message is for, each once. */
export function mentionAgentIds(tokens: MentionToken[]): string[] {
- return [...new Set(tokens.map((token) => token.agentId))];
+ return [...new Set(tokens.filter((token) => token.kind === 'agent').map((token) => token.id))];
+}
+
+/** The people a message mentions, each once; they are never sent as agents. */
+export function mentionUserIds(tokens: MentionToken[]): string[] {
+ return [...new Set(tokens.filter((token) => token.kind === 'person').map((token) => token.id))];
+}
+
+/** People whose name contains `query`, those it starts first. */
+export function filterMentionPeople<T extends MentionPerson>(people: T[], query: string): T[] {
+ const q = query.toLowerCase();
+ const rank = (person: T) => (person.name.toLowerCase().startsWith(q) ? 0 : 1);
+ return people
+ .filter((person) => person.name.toLowerCase().includes(q))
+ .sort((a, b) => rank(a) - rank(b));
}
/** The `@query` being typed at the caret, if any: `@` at the start or after whitespace. */
@@ -75,19 +111,19 @@ export function tokenToRemove(
);
}
-/** `text` split into plain runs and mention runs (with their agent), for drawing badges. */
+/** `text` split into plain runs and mention runs (with their token), for drawing badges. */
export function mentionSegments(
text: string,
tokens: MentionToken[]
-): { text: string; agentId: string | null }[] {
- const segments: { text: string; agentId: string | null }[] = [];
+): { text: string; token: MentionToken | null }[] {
+ const segments: { text: string; token: MentionToken | null }[] = [];
let at = 0;
for (const token of tokens) {
- if (token.start > at) segments.push({ text: text.slice(at, token.start), agentId: null });
- segments.push({ text: text.slice(token.start, token.end), agentId: token.agentId });
+ if (token.start > at) segments.push({ text: text.slice(at, token.start), token: null });
+ segments.push({ text: text.slice(token.start, token.end), token });
at = token.end;
}
- if (at < text.length) segments.push({ text: text.slice(at), agentId: null });
+ if (at < text.length) segments.push({ text: text.slice(at), token: null });
return segments;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts
index 81f7fd977..3b6f816e8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts
@@ -42,6 +42,7 @@ export type PendingSend = {
body: string;
threadRootId: string | null;
mentionAgentIds: string[];
+ mentionUserIds: string[];
files: PendingFile[];
state: 'sending' | 'failed' | 'conflict';
error: string | null;
@@ -56,6 +57,8 @@ export type SendInput = {
threadRootId: string | null;
/** The agents picked as mentions; the server adds `@name` for any the body does not name. */
mentionAgentIds: string[];
+ /** The people picked as mentions; they are told, and no agent is addressed by them. */
+ mentionUserIds: string[];
files: ChatFile[];
};
@@ -79,6 +82,7 @@ export type TimelineApi = {
threadRootId: string | null;
uploadIds: string[];
mentionAgentIds?: string[];
+ mentionUserIds?: string[];
}
) => Promise<ChatMessage[]>;
newId: () => string;
@@ -203,6 +207,7 @@ export class ChatTimeline {
body: input.body,
threadRootId: input.threadRootId,
mentionAgentIds: input.mentionAgentIds,
+ mentionUserIds: input.mentionUserIds,
files: input.files.map((file) => ({
id: this.api.newId(),
uploadId: this.api.newId(),
@@ -319,6 +324,7 @@ export class ChatTimeline {
threadRootId: send.threadRootId,
// A copy: IPC cannot clone a MobX array.
mentionAgentIds: [...send.mentionAgentIds],
+ mentionUserIds: [...send.mentionUserIds],
uploadIds: send.files.map((file) => file.uploadId),
});
runInAction(() => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-threads.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-threads.test.ts
index 00abac417..5cd9a2879 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-threads.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-threads.test.ts
@@ -21,6 +21,7 @@ const makeMessage = (overrides: Partial<ChatMessage> = {}): ChatMessage => ({
attachments: [],
clientTxn: null,
namedAgentIds: [],
+ namedUserIds: [],
threadReplyCount: 0,
threadLastReplySeq: null,
...overrides,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts
index af25d4312..3e3be644f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts
@@ -47,6 +47,7 @@ const makeMessage = (overrides: Partial<ChatMessage> = {}): ChatMessage => ({
attachments: [],
clientTxn: null,
namedAgentIds: [],
+ namedUserIds: [],
threadReplyCount: 0,
threadLastReplySeq: null,
...overrides,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index 2f8a680a3..8ab2c1fcb 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ExternalLink, FileText, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
+import { chatMembersQueryKey, workspaceRosterQuery } from '@renderer/features/chats/chat-people';
import { opensAsConsoleChat } from '@renderer/features/chats/console-chat-redirect';
import { chatFailure } from '@renderer/features/chats/stores/chat-errors';
import { chatsStore } from '@renderer/features/chats/stores/chats';
@@ -107,14 +108,6 @@ const ChatConfiguration = observer(function ChatConfiguration({
);
});
-/**
- * The query for a chat's members, keyed on who the live summary says is in it,
- * so an add, a removal or a swap by anyone reads the list again.
- */
-export function chatMembersQueryKey(serverId: string, chat: ChatSummary) {
- return ['chat-members', serverId, chat.roomId, chat.memberUserIds.join(',')] as const;
-}
-
/** Who is in a group chat; a manager adds and removes agents and people through the chat. */
const ChatParticipantsSection = observer(function ChatParticipantsSection({
serverId,
@@ -293,11 +286,7 @@ const ChatAddParticipantPanel = observer(function ChatAddParticipantPanel({
}) {
const tenantId = chatsStore.tenantId;
const agents = useWorkspaceAgents(workspaceId);
- const roster = useQuery({
- queryKey: ['workspace-members', serverId, tenantId],
- queryFn: () => rpc.chats.workspaceMembers({ serverId, tenantId: tenantId as string }),
- enabled: tenantId !== null,
- });
+ const roster = useQuery(workspaceRosterQuery(serverId, tenantId));
const allowed = useQuery({
// Keyed by the chat's agents, so adding or removing one asks again.
queryKey: [
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx
index b5d8261a6..6c3135c7c 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-composer-mentions.test.tsx
@@ -55,6 +55,7 @@ describe('ChatComposer mention badges', () => {
serverId="s"
timeline={new ChatTimeline('room-geometry', {} as TimelineApi)}
agents={[agent]}
+ people={[]}
groupName="Ship review"
activity={null}
replyTo={null}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts
index f34c206bb..46f5fa584 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts
@@ -2,11 +2,11 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest';
+import { chatMembersQueryKey } from '@renderer/features/chats/chat-people';
import {
addAllToChat,
addLabel,
addToChat,
- chatMembersQueryKey,
InviteHint,
RoomConfigurationPanel,
} from '@renderer/features/switch-rooms/room-configuration-panel';
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts
index 433e2f22d..40528abaa 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-mentions.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
import {
+ agentTargets,
filterMentionAgents,
+ filterMentionPeople,
+ mentionUserIds,
+ personTargets,
mentionAgentIds,
mentionQuery,
mentionSegments,
@@ -18,45 +22,45 @@ const agents = [
describe('mentionTokens', () => {
it('finds whole @name and @alias mentions, case-insensitively', () => {
const text = 'hi @Agent-Two and @reviewer, @agent-one!';
- expect(mentionTokens(text, agents)).toEqual([
- { agentId: 'a2', start: 3, end: 13 },
- { agentId: 'a2', start: 18, end: 27 },
- { agentId: 'a1', start: 29, end: 39 },
+ expect(mentionTokens(text, agentTargets(agents))).toEqual([
+ { kind: 'agent', id: 'a2', start: 3, end: 13 },
+ { kind: 'agent', id: 'a2', start: 18, end: 27 },
+ { kind: 'agent', id: 'a1', start: 29, end: 39 },
]);
});
it('prefers the longest name and never matches inside a longer word', () => {
- expect(mentionTokens('@cc-2 @cc @cc-3 bob@cc', agents).map((t) => t.agentId)).toEqual([
+ expect(mentionTokens('@cc-2 @cc @cc-3 bob@cc', agentTargets(agents)).map((t) => t.id)).toEqual([
'a4',
'a3',
]);
});
it('drops a mention once an edit lands inside it, or its agent leaves', () => {
- expect(mentionTokens('@agent-tXwo hi', agents)).toEqual([]);
- expect(mentionTokens('@agent-twos hi', agents)).toEqual([]);
- expect(mentionTokens('@agent-two hi', agents.slice(0, 1))).toEqual([]);
+ expect(mentionTokens('@agent-tXwo hi', agentTargets(agents))).toEqual([]);
+ expect(mentionTokens('@agent-twos hi', agentTargets(agents))).toEqual([]);
+ expect(mentionTokens('@agent-two hi', agentTargets(agents.slice(0, 1)))).toEqual([]);
});
it('addresses an agent once however often it is mentioned', () => {
- expect(mentionAgentIds(mentionTokens('@agent-two @reviewer @agent-two', agents))).toEqual([
- 'a2',
- ]);
+ expect(
+ mentionAgentIds(mentionTokens('@agent-two @reviewer @agent-two', agentTargets(agents)))
+ ).toEqual(['a2']);
});
it('splits text into plain and mention runs', () => {
const text = 'x @cc y';
- expect(mentionSegments(text, mentionTokens(text, agents))).toEqual([
- { text: 'x ', agentId: null },
- { text: '@cc', agentId: 'a3' },
- { text: ' y', agentId: null },
+ expect(mentionSegments(text, mentionTokens(text, agentTargets(agents)))).toEqual([
+ { text: 'x ', token: null },
+ { text: '@cc', token: { kind: 'agent', id: 'a3', start: 2, end: 5 } },
+ { text: ' y', token: null },
]);
});
});
describe('mention editing', () => {
const text = 'a @agent-two b';
- const tokens = mentionTokens(text, agents);
+ const tokens = mentionTokens(text, agentTargets(agents));
it('removes a whole mention on Backspace at its end or inside it', () => {
expect(tokenToRemove(tokens, 12, 'Backspace')).toEqual(tokens[0]);
@@ -89,3 +93,37 @@ describe('mention suggestions', () => {
expect(filterMentionAgents(named, 'ann').map((a) => a.id)).toEqual(['y', 'x']);
});
});
+
+describe('people mentions', () => {
+ const people = [
+ { userId: 'u1', name: 'Bob Member' },
+ { userId: 'u2', name: 'cc' },
+ ];
+
+ it('matches a whole display name with spaces, and sends people apart from agents', () => {
+ const text = 'hi @Bob Member, ask @agent-one';
+ const tokens = mentionTokens(text, [...agentTargets(agents), ...personTargets(people)]);
+ expect(tokens).toEqual([
+ { kind: 'person', id: 'u1', start: 3, end: 14 },
+ { kind: 'agent', id: 'a1', start: 20, end: 30 },
+ ]);
+ expect(mentionAgentIds(tokens)).toEqual(['a1']);
+ expect(mentionUserIds(tokens)).toEqual(['u1']);
+ expect(mentionTokens('@Bob Memberx', personTargets(people))).toEqual([]);
+ });
+
+ it('reads a name shared by a person and an agent as whichever is listed first', () => {
+ const asPerson = mentionTokens('@cc', [...personTargets(people), ...agentTargets(agents)]);
+ expect(asPerson).toEqual([{ kind: 'person', id: 'u2', start: 0, end: 3 }]);
+ // A person-only mention addresses no agent.
+ expect(mentionAgentIds(asPerson)).toEqual([]);
+ expect(mentionTokens('@cc', [...agentTargets(agents), ...personTargets(people)])[0]!.kind).toBe(
+ 'agent'
+ );
+ });
+
+ it('suggests people whose name contains the query, those it starts first', () => {
+ expect(filterMentionPeople(people, 'm').map((p) => p.userId)).toEqual(['u1']);
+ expect(filterMentionPeople(people, '').map((p) => p.userId)).toEqual(['u1', 'u2']);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts
index 5e4a4c644..99c28359a 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts
@@ -22,6 +22,7 @@ function message(seq: number, extra: Partial<ChatMessage> = {}): ChatMessage {
attachments: [],
clientTxn: null,
namedAgentIds: [],
+ namedUserIds: [],
threadReplyCount: 0,
threadLastReplySeq: null,
...extra,
@@ -79,6 +80,7 @@ const input = (files: ChatFile[] = []) => ({
body: 'hello',
threadRootId: null,
mentionAgentIds: [],
+ mentionUserIds: [],
files,
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts
index 497809b52..bcd145a0a 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-view.test.ts
@@ -30,6 +30,7 @@ function message(seq: number, userId: string, name: string): ChatMessage {
attachments: [],
clientTxn: null,
namedAgentIds: [],
+ namedUserIds: [],
threadReplyCount: 0,
threadLastReplySeq: null,
};
@@ -47,6 +48,7 @@ describe('ChatTimelineView', () => {
serverId: 's',
timeline,
agents: [],
+ people: [],
activities: [],
onReply: () => {},
})
@@ -74,6 +76,7 @@ describe('ChatTimelineView thread replies', () => {
serverId: 's',
timeline,
agents: [],
+ people: [],
activities: [],
onReply: () => {},
})
@@ -90,3 +93,38 @@ describe('ChatTimelineView thread replies', () => {
}
});
});
+
+describe('ChatTimelineView mentions', () => {
+ const cc = {
+ id: 'a3',
+ name: 'cc',
+ displayName: null,
+ iconUrl: null,
+ provider: null,
+ alias: null,
+ ownerName: null,
+ ownedByViewer: false,
+ };
+ const render = (namedUserIds: string[], namedAgentIds: string[]) => {
+ const timeline = new ChatTimeline('room-1', api);
+ timeline.apply({ ...message(1, 'me', 'Alice'), body: '@cc hi', namedUserIds, namedAgentIds });
+ return renderToStaticMarkup(
+ createElement(ChatTimelineView, {
+ serverId: 's',
+ timeline,
+ agents: [cc],
+ people: [{ userId: 'u2', name: 'cc' }],
+ activities: [],
+ onReply: () => {},
+ })
+ );
+ };
+
+ it('shows a person the message names as the person, even with an agent of the same name', () => {
+ expect(render(['u2'], [])).toContain('data-mention="person"');
+ });
+
+ it('shows the agent when the message names no person', () => {
+ expect(render([], ['a3'])).toContain('data-mention="agent"');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
index 239fbbef1..c40241fc4 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
@@ -54,6 +54,7 @@ function message(roomId: string, seq: number): ChatMessage {
attachments: [],
clientTxn: null,
namedAgentIds: [],
+ namedUserIds: [],
threadReplyCount: 0,
threadLastReplySeq: null,
};
diff --git a/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts b/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts
index 3e88468a4..1fd7c35a5 100644
--- a/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts
@@ -74,6 +74,8 @@ export const chatMessageSchema = z.object({
attachments: z.array(chatAttachmentSchema),
clientTxn: z.string().nullable(),
namedAgentIds: z.array(z.string()),
+ /** The people the message mentions; empty from a server older than people mentions. */
+ namedUserIds: z.array(z.string()).default([]),
threadReplyCount: z.number().int(),
threadLastReplySeq: z.number().int().nullable(),
});
@@ -158,6 +160,7 @@ export type ChatSendInput = {
threadRootId: string | null;
uploadIds: string[];
mentionAgentIds?: string[];
+ mentionUserIds?: string[];
};
export type ChatUploadInput = {