Skip to content

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

fix(console): undo brings back a removed mention with whom it named

raullopez-sandboxab64d8fca58b
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 fec33f407..aa6a06bb2 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
@@ -14,6 +14,7 @@ import { snippetOf } from '../chat-threads';
import {
agentTargets,
composeMentions,
+ editMentions,
filterMentionAgents,
filterMentionPeople,
mentionAgentIds,
@@ -22,6 +23,7 @@ import {
mentionSegments,
type MentionToken,
mentionUserIds,
+ type RememberedMention,
personTargets,
shiftMentions,
tokenToRemove,
@@ -186,10 +188,20 @@ export const ChatComposer = observer(function ChatComposer({
}, [draftKey, draft, picked]);
/** A pick the next edit inserts, placed once that edit has moved the others. */
const pendingPick = useRef<MentionToken | null>(null);
- const edit = (next: string) => {
+ /** Picked mentions an edit removed, so undo and redo can bring them back with who they named. */
+ const removed = useRef<RememberedMention[]>([]);
+ const edit = (next: string, inputType: string | null) => {
const pick = pendingPick.current;
pendingPick.current = null;
- setPicked((current) => [...shiftMentions(draft, next, current), ...(pick ? [pick] : [])]);
+ const result = editMentions(
+ draft,
+ next,
+ picked,
+ removed.current,
+ inputType === 'historyUndo' || inputType === 'historyRedo'
+ );
+ removed.current = result.remembered;
+ setPicked([...result.mentions, ...(pick ? [pick] : [])]);
setDraft(next);
};
const [files, setFiles] = useState<{ id: string; file: File }[]>([]);
@@ -272,7 +284,7 @@ export const ChatComposer = observer(function ChatComposer({
textarea.setSelectionRange(query.start, caret);
// insertText keeps the native undo stack; a controlled-value write would wipe it.
if (!document.execCommand('insertText', false, `@${name} `)) {
- edit(`${draft.slice(0, query.start)}@${name} ${draft.slice(caret)}`);
+ edit(`${draft.slice(0, query.start)}@${name} ${draft.slice(caret)}`, null);
setCaret(query.start + name.length + 2);
}
setMentionIndex(0);
@@ -507,7 +519,7 @@ export const ChatComposer = observer(function ChatComposer({
}
onKeyDown={onKeyDown}
onChange={(event) => {
- edit(event.target.value);
+ edit(event.target.value, (event.nativeEvent as InputEvent).inputType ?? null);
setCaret(event.target.selectionStart);
setMentionIndex(0);
if (!mentionQuery(event.target.value, event.target.selectionStart))
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 bb6ef5798..06462d62e 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
@@ -131,16 +131,25 @@ export function mentionSegments(
export const MENTION_BADGE =
'rounded-sm bg-background-tertiary-1 ring-2 ring-background-tertiary-1';
+/** A picked mention an edit removed, with the text it read, for undo to bring back. */
+export type RememberedMention = MentionToken & { text: string };
+
+/** How many removed mentions undo can bring back. */
+const REMEMBERED_MENTIONS = 20;
+
/**
* Picked mentions carried across an edit from `before` to `after`: those wholly
* before or after the changed run keep their place (shifted), and one the edit
- * touches is dropped.
+ * touches is dropped but remembered. An undo or redo (`history`) brings back a
+ * remembered mention whose exact text reappears where it was.
*/
-export function shiftMentions(
+export function editMentions(
before: string,
after: string,
- mentions: MentionToken[]
-): MentionToken[] {
+ mentions: MentionToken[],
+ remembered: RememberedMention[],
+ history: boolean
+): { mentions: MentionToken[]; remembered: RememberedMention[] } {
let start = 0;
while (start < before.length && start < after.length && before[start] === after[start]) start++;
let tail = 0;
@@ -152,12 +161,37 @@ export function shiftMentions(
tail++;
const endBefore = before.length - tail;
const delta = after.length - before.length;
- return mentions.flatMap((mention) => {
- if (mention.end <= start) return [mention];
- if (mention.start >= endBefore)
- return [{ ...mention, start: mention.start + delta, end: mention.end + delta }];
- return [];
- });
+ const kept: MentionToken[] = [];
+ const dropped: RememberedMention[] = [];
+ for (const mention of mentions) {
+ if (mention.end <= start) kept.push(mention);
+ else if (mention.start >= endBefore)
+ kept.push({ ...mention, start: mention.start + delta, end: mention.end + delta });
+ else dropped.push({ ...mention, text: before.slice(mention.start, mention.end) });
+ }
+ let memory = [...remembered, ...dropped].slice(-REMEMBERED_MENTIONS);
+ if (!history) return { mentions: kept, remembered: memory };
+ const back = memory.filter(
+ (entry) =>
+ after.slice(entry.start, entry.end) === entry.text &&
+ !kept.some((mention) => entry.start < mention.end && mention.start < entry.end)
+ );
+ memory = memory.filter((entry) => !back.includes(entry));
+ return {
+ mentions: [...kept, ...back.map(({ text: _text, ...mention }) => mention)].sort(
+ (a, b) => a.start - b.start
+ ),
+ remembered: memory,
+ };
+}
+
+/** {@link editMentions} without the memory: the picked mentions that survive an edit. */
+export function shiftMentions(
+ before: string,
+ after: string,
+ mentions: MentionToken[]
+): MentionToken[] {
+ return editMentions(before, after, mentions, [], false).mentions;
}
/**
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 6c3135c7c..f771e3733 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
@@ -104,3 +104,51 @@ describe('PromptInputTextarea', () => {
expect(onSubmit).toHaveBeenCalledTimes(1);
});
});
+
+describe('ChatComposer picked mentions', () => {
+ it('keeps a picked person as the person through delete and undo, beside a same-name agent', async () => {
+ const sharer = { ...agent, id: 'a9', name: 'Bob Member' };
+ const textarea = await render(
+ <ChatComposer
+ serverId="s"
+ timeline={new ChatTimeline('room-undo', {} as TimelineApi)}
+ agents={[sharer]}
+ people={[{ userId: 'u1', name: 'Bob Member', email: '[email protected]' }]}
+ groupName="Ship review"
+ activity={null}
+ replyTo={null}
+ onClearReply={() => {}}
+ disabled={null}
+ />
+ );
+ const kinds = () =>
+ [...container!.querySelectorAll('mark[data-mention]')].map(
+ (mark) => (mark as HTMLElement).dataset.mention
+ );
+ await act(async () => {
+ textarea.focus();
+ document.execCommand('insertText', false, '@bo');
+ });
+ // The agent comes first in the list; the person is next.
+ await act(async () => {
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
+ });
+ await act(async () => {
+ textarea.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })
+ );
+ });
+ expect(textarea.value).toBe('@Bob Member ');
+ expect(kinds()).toEqual(['person']);
+ await act(async () => {
+ textarea.setSelectionRange(0, textarea.value.length);
+ document.execCommand('delete');
+ });
+ expect(kinds()).toEqual([]);
+ await act(async () => {
+ document.execCommand('undo');
+ });
+ expect(textarea.value).toBe('@Bob Member ');
+ expect(kinds()).toEqual(['person']);
+ });
+});
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 102df2856..312e59fe8 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
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
agentTargets,
composeMentions,
+ editMentions,
shiftMentions,
filterMentionAgents,
filterMentionPeople,
@@ -167,3 +168,21 @@ describe('picked mentions', () => {
expect(composeMentions('hi @Bob', [mention], targets)).toEqual([]);
});
});
+
+describe('undoing the removal of a picked mention', () => {
+ const sharer = [{ id: 'a9', name: 'Bob Member', alias: null }];
+ const bob = [{ userId: 'u1', name: 'Bob Member' }];
+ const targets = [...agentTargets(sharer), ...personTargets(bob)];
+ const person = { kind: 'person' as const, id: 'u1', start: 3, end: 14 };
+
+ it('brings the mention back as the person on undo, and not on a plain retype', () => {
+ const removed = editMentions('hi @Bob Member', 'hi ', [person], [], false);
+ expect(removed.mentions).toEqual([]);
+ const retyped = editMentions('hi ', 'hi @Bob Member', [], removed.remembered, false);
+ expect(retyped.mentions).toEqual([]);
+ const undone = editMentions('hi ', 'hi @Bob Member', [], removed.remembered, true);
+ expect(undone.mentions).toEqual([person]);
+ expect(undone.remembered).toEqual([]);
+ expect(composeMentions('hi @Bob Member', undone.mentions, targets)[0]!.kind).toBe('person');
+ });
+});