⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(web): the comment @ menu offers only agents a mention would start (#570)
Pasqual Troncone16bac83a5e12
diff --git a/apps/web/src/features/issue/components/detail/CommentComposer.test.tsx b/apps/web/src/features/issue/components/detail/CommentComposer.test.tsxnew file mode 100644index 00000000..ee9d5362--- /dev/null+++ b/apps/web/src/features/issue/components/detail/CommentComposer.test.tsx@@ -0,0 +1,118 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { NextIntlClientProvider } from 'next-intl';+import { JSDOM } from 'jsdom';+import type { Assignee } from '@/lib/api/endpoints/projects';+import common from '../../../../../messages/en/common.json';+import issue from '../../../../../messages/en/issue.json';++const replacedGlobals = [+ 'window',+ 'document',+ 'navigator',+ 'HTMLElement',+ 'HTMLTextAreaElement',+ 'Event',+ 'fetch',+ 'IS_REACT_ACT_ENVIRONMENT',+] as const;++function assignee(over: Partial<Assignee>): Assignee {+ return {+ userId: over.username ?? 'u',+ name: over.username ?? 'u',+ email: '',+ username: null,+ image: null,+ kind: 'member',+ agentKind: null,+ restrictedToUserId: null,+ respondsToMention: null,+ canReadWorkItems: true,+ ...over,+ };+}++let dom: JSDOM;+let root: Root;+let client: QueryClient;+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;++beforeEach(async () => {+ originalGlobalDescriptors = new Map(+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),+ );+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/' });+ for (const name of replacedGlobals) {+ if (name in dom.window) {+ Object.defineProperty(globalThis, name, {+ configurable: true,+ value: dom.window[name as keyof typeof dom.window],+ });+ }+ }+ Object.defineProperties(globalThis, {+ fetch: { configurable: true, value: async () => Response.json(null) },+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },+ });+ Object.defineProperty(window, '__ITSAPLAN_ENV__', {+ value: { apiUrl: 'https://api.test', privacyUrl: '', termsUrl: '' },+ });+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const { createRoot } = await import('react-dom/client');+ root = createRoot(document.getElementById('root')!);+});++afterEach(async () => {+ await act(async () => root.unmount());+ client.clear();+ // Better Auth's stores dispose their browser listeners one second after unmount.+ await new Promise((resolve) => setTimeout(resolve, 1100));+ dom.window.close();+ for (const [name, descriptor] of originalGlobalDescriptors) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else Reflect.deleteProperty(globalThis, name);+ }+});++describe('CommentComposer', () => {+ it('leaves an agent that does not answer mentions out of the @ menu', async () => {+ const { default: CommentComposer } = await import('./CommentComposer');+ await act(async () => {+ root.render(+ <QueryClientProvider client={client}>+ <NextIntlClientProvider locale="en" messages={{ common, issue }} timeZone="UTC">+ <CommentComposer+ issueId={1}+ assignees={[+ assignee({ username: 'ana' }),+ assignee({ username: 'triage', kind: 'agent', respondsToMention: true }),+ assignee({ username: 'cleanup', kind: 'agent', respondsToMention: false }),+ ]}+ authorName="Ana"+ authorImage={null}+ />+ </NextIntlClientProvider>+ </QueryClientProvider>,+ );+ });++ const textarea = document.querySelector('textarea')!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(+ textarea,+ '@',+ );+ textarea.setSelectionRange(1, 1);+ textarea.dispatchEvent(new Event('input', { bubbles: true }));+ });++ const offered = [...document.querySelectorAll('li button span')]+ .map((span) => span.textContent!)+ .filter((text) => text.startsWith('@'));+ assert.deepEqual(offered, ['@ana', '@triage']);+ });+});diff --git a/apps/web/src/features/issue/components/detail/CommentComposer.tsx b/apps/web/src/features/issue/components/detail/CommentComposer.tsxindex e5f9ac25..e9233ca5 100644--- a/apps/web/src/features/issue/components/detail/CommentComposer.tsx+++ b/apps/web/src/features/issue/components/detail/CommentComposer.tsx@@ -5,6 +5,8 @@ import Avatar from '@/components/common/Avatar';import { Button } from '@/components/ui/button';import { Textarea } from '@/components/ui/textarea';import { cn } from '@/lib/utils';+import { useSession } from '@/lib/auth-client';+import { offersMention } from '@/hooks/useMentionCandidates';import { useCreateComment, useUpdateComment } from '../../services/comments.service';import { useTranslations } from 'next-intl';@@ -63,25 +65,28 @@ export default function CommentComposer({const [pendingCaret, setPendingCaret] = useState<number | null>(null);const [focused, setFocused] = useState(false);const taRef = useRef<HTMLTextAreaElement | null>(null);+ const { data: session } = useSession();+ const currentUserId = session?.user.id ?? null;const isReply = replyToId != null;const isEdit = commentId != null;const posting = (isEdit ? updateComment : createComment).isPending;const cmdKey = typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform) ? '⌘' : 'Ctrl';- // Members and both agent kinds can be mentioned, and only those that have a handle- // to be addressed by. An internal agent runs in the built-in runtime; an external- // agent is reached over its operator's webhook, which receives the comment.+ // The same people and agents the markdown editors offer: an agent a mention would+ // leave silent is not listed. An internal agent runs in the built-in runtime; an+ // external agent is reached over its operator's webhook, which receives the comment.const matches = useMemo(() => {if (!menu) return [];const q = menu.query.toLowerCase();return assignees.filter((a) =>- a.username && (a.name.toLowerCase().includes(q) || a.username.toLowerCase().includes(q)),+ offersMention(a, currentUserId) &&+ (a.name.toLowerCase().includes(q) || a.username!.toLowerCase().includes(q)),).slice(0, 8);- }, [assignees, menu]);+ }, [assignees, menu, currentUserId]);// A reply box or an edit box is opened by a deliberate click, so it takes the// caret — at the end of the text being edited.diff --git a/apps/web/src/hooks/useMentionCandidates.test.ts b/apps/web/src/hooks/useMentionCandidates.test.tsindex 3d59bed9..eaf47de9 100644--- a/apps/web/src/hooks/useMentionCandidates.test.ts+++ b/apps/web/src/hooks/useMentionCandidates.test.ts@@ -1,7 +1,7 @@import assert from 'node:assert/strict';import { describe, it } from 'node:test';import type { Assignee } from '@/lib/api/endpoints/projects';-import { mentionCandidatesFrom } from './useMentionCandidates';+import { mentionCandidatesFrom, offersMention } from './useMentionCandidates';function assignee(over: Partial<Assignee>): Assignee {return {@@ -49,3 +49,25 @@ describe('mentionCandidatesFrom', () => {);});});++// The comment box filters the project's assignees with this, as the editors do.+describe('offersMention', () => {+ it('offers people with a handle and the agents that answer mentions', () => {+ assert.equal(offersMention(assignee({ username: 'ana' }), 'me'), true);+ assert.equal(+ offersMention(+ assignee({ username: 'refinar', kind: 'agent', respondsToMention: true }),+ 'me',+ ),+ true,+ );+ assert.equal(+ offersMention(+ assignee({ username: 'higiene', kind: 'agent', respondsToMention: false }),+ 'me',+ ),+ false,+ );+ assert.equal(offersMention(assignee({ username: null }), 'me'), false);+ });+});diff --git a/apps/web/src/hooks/useMentionCandidates.ts b/apps/web/src/hooks/useMentionCandidates.tsindex e4592dea..85588add 100644--- a/apps/web/src/hooks/useMentionCandidates.ts+++ b/apps/web/src/hooks/useMentionCandidates.ts@@ -7,15 +7,20 @@ import { isForeignAgent } from '@/utils/foreignAgent';// An agent is offered only when a mention by this user would start a run: one that// does not answer mentions, or works only for another member, would stay silent.+export function offersMention(a: Assignee, currentUserId: string | null): boolean {+ if (!a.username) return false;+ return a.kind !== 'agent' || (!!a.respondsToMention && !isForeignAgent(a, currentUserId));+}+export function mentionCandidatesFrom(assignees: Assignee[],currentUserId: string | null,): MentionCandidate[] {- return assignees.flatMap((a) => {- if (!a.username) return [];- if (a.kind === 'agent' && (!a.respondsToMention || isForeignAgent(a, currentUserId))) return [];- return [{ userId: a.userId, name: a.name, username: a.username, kind: a.kind }];- });+ return assignees.flatMap((a) =>+ offersMention(a, currentUserId)+ ? [{ userId: a.userId, name: a.name, username: a.username!, kind: a.kind }]+ : [],+ );}// Who the editors offer after an "@": the active project's members and agents that