⭐️⭐️⭐️ 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
feat: link directly to a comment (#724)
Bogdan Dolin6c43b368b6eb
diff --git a/apps/api/src/modules/issues/__tests__/integration/activity.test.ts b/apps/api/src/modules/issues/__tests__/integration/activity.test.tsindex b3e0fde0..d7842311 100644--- a/apps/api/src/modules/issues/__tests__/integration/activity.test.ts+++ b/apps/api/src/modules/issues/__tests__/integration/activity.test.ts@@ -725,7 +725,11 @@ describe('issue activity', () => {const inbox = await member.api.notifications.get({ query: { types: 'mentioned' } });expect(inbox.data!.items).toHaveLength(1);- expect(inbox.data!.items[0]).toMatchObject({ type: 'mentioned', issueId: issue.id });+ expect(inbox.data!.items[0]).toMatchObject({+ type: 'mentioned',+ issueId: issue.id,+ issueCommentId: comment.id,+ });});it('lets a project owner edit another member’s comment', async () => {diff --git a/apps/api/src/modules/issues/webhook-payload.ts b/apps/api/src/modules/issues/webhook-payload.tsindex b559f64e..d47b8dfc 100644--- a/apps/api/src/modules/issues/webhook-payload.ts+++ b/apps/api/src/modules/issues/webhook-payload.ts@@ -2,7 +2,7 @@ import { db, issue, issueType, label, project, projectColumn, team, user } fromimport { eq, inArray } from 'drizzle-orm';import { emitWebhookEvents } from '#modules/webhooks/emit';import type { WebhookEventType } from '#modules/webhooks/service';-import { issueUrl, teamRef } from '#modules/teams/ref';+import { commentUrl, issueUrl, teamRef } from '#modules/teams/ref';import type { ActivityActor, FeedItemRow } from './activity';import type { IssueRow } from './service';@@ -109,7 +109,8 @@ export async function emitIssueEvent();}-// A comment payload names the issue it is on, so a receiver can link to it.+// A comment payload links to the comment and names the issue it is on, so a receiver can+// link to either.export async function emitCommentEvent(projectId: number,eventType: WebhookEventType,@@ -132,19 +133,18 @@ export async function emitCommentEvent(.innerJoin(project, eq(project.id, issue.projectId)).innerJoin(team, eq(team.id, project.teamId)).where(eq(issue.id, comment.issueId));+ if (!row) return [{ ...comment, url: null, issue: null }];+ const ref = teamRef({ id: row.teamId, slug: row.teamSlug });return [{...comment,- issue: row- ? {- id: comment.issueId,- identifier: `${row.key}-${row.seq}`,- title: row.title,- url:- issueUrl(teamRef({ id: row.teamId, slug: row.teamSlug }), row.key, row.seq) ??- null,- }- : null,+ url: commentUrl(ref, row.key, row.seq, comment.id) ?? null,+ issue: {+ id: comment.issueId,+ identifier: `${row.key}-${row.seq}`,+ title: row.title,+ url: issueUrl(ref, row.key, row.seq) ?? null,+ },},];},diff --git a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.tsindex f3abe44b..71f191e7 100644--- a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts+++ b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts@@ -1,4 +1,6 @@import { describe, it, expect, beforeEach } from 'bun:test';+import { db, notificationDelivery } from '@repo/db';+import { asc } from 'drizzle-orm';import { authedApi, type Api, createProject } from '#tests/helpers/app';import { signUpTestUser } from '#tests/helpers/auth';import { resetDb } from '#tests/helpers/db';@@ -14,7 +16,7 @@ interface Member {username: string;}-async function setup(): Promise<{ owner: Member; columnId: number; doneColumnId: number }> {+async function setup() {const u = await signUpTestUser();const api = authedApi(u.cookie);await createProject(api, { key: 'MKT', name: 'Marketing' });@@ -23,6 +25,7 @@ async function setup(): Promise<{ owner: Member; columnId: number; doneColumnId:const done = columns.find((c) => c.stateType === 'completed') ?? columns[columns.length - 1];return {owner: { api, userId: u.userId, username: u.username },+ project: view.data!.project,columnId: columns[0].id,doneColumnId: done.id,};@@ -185,7 +188,11 @@ describe('notifications', () => {const inbox = await member.api.notifications.get({ query: { types: 'mentioned' } });expect(inbox.data!.items).toHaveLength(1);- expect(inbox.data!.items[0]).toMatchObject({ type: 'mentioned', actorUserId: owner.userId });+ expect(inbox.data!.items[0]).toMatchObject({+ type: 'mentioned',+ actorUserId: owner.userId,+ issueCommentId: null,+ });});it('notifies a member mentioned in a markdown custom field', async () => {@@ -280,16 +287,74 @@ describe('notifications', () => {// Member comments -> owner (a watcher) gets a 'commented' notification.await owner.api.issues({ issueId }).comments.post({ body: 'looking into it' } as never);- await member.api.issues({ issueId }).comments.post({ body: 'done' } as never);+ const comment = (await member.api.issues({ issueId }).comments.post({ body: 'done' })).data!;const ownerInbox = await owner.api.notifications.get({ query: { types: 'commented' } });expect(ownerInbox.data!.items).toHaveLength(1);expect(ownerInbox.data!.items[0]).toMatchObject({type: 'commented',actorUserId: member.userId,+ issueCommentId: comment.id,});});+ it('keeps the notification of a deleted comment, pointing at the issue only', async () => {+ const { owner, columnId } = await setup();+ const member = await addMember(owner);+ const issue = (await createIssue(owner.api, columnId)).data!;+ const comment = (+ await owner.api+ .issues({ issueId: issue.id })+ .comments.post({ body: `@${member.username} look` })+ ).data!;++ await owner.api.comments({ commentId: comment.id }).delete();++ const inbox = await member.api.notifications.get({ query: {} });+ expect(inbox.data!.items).toHaveLength(1);+ expect(inbox.data!.items[0]).toMatchObject({+ type: 'mentioned',+ issueId: issue.id,+ issueCommentId: null,+ });+ });++ it('links the email about a comment to the comment, and about a description to the issue', async () => {+ const { owner, project, columnId } = await setup();+ const member = await addMember(owner);+ await owner.api.teams({ teamId: project.teamId })['notification-settings'].put({+ smtp: {+ enabled: true,+ host: 'smtp.example.com',+ port: 587,+ encryption: 'none',+ username: '[email protected]',+ password: 'secret',+ timeout: null,+ },+ });+ const events = { assigned: true, mentioned: true, commented: true, state_changed: true };+ await member.api.projects({ projectKey: 'MKT' })['notification-preferences'].put({+ emailEvents: events,+ telegramEvents: events,+ });+ const issue = (await createIssue(owner.api, columnId)).data!;+ const client = owner.api.issues({ issueId: issue.id });+ const comment = (await client.comments.post({ body: `@${member.username} have a look` })).data!;+ await client.patch({ description: `@${member.username} size this` });++ // No route reads the outbox, and its rows are what the worker sends.+ const queued = await db+ .select({ payload: notificationDelivery.payload })+ .from(notificationDelivery)+ .orderBy(asc(notificationDelivery.id));+ const issueLink = `${process.env.APP_URL}/${project.teamRef}/issue/${issue.identifier}`;+ expect(queued.map((row) => row.payload.url)).toEqual([+ `${issueLink}#comment-${comment.id}`,+ issueLink,+ ]);+ });+it('a status change notification names the states it moved between', async () => {const { owner, columnId, doneColumnId } = await setup();const member = await addMember(owner);diff --git a/apps/api/src/modules/notifications/model.ts b/apps/api/src/modules/notifications/model.tsindex 799a4572..c86c1dc8 100644--- a/apps/api/src/modules/notifications/model.ts+++ b/apps/api/src/modules/notifications/model.ts@@ -14,6 +14,7 @@ const NotificationResponse = t.Object({issueSeq: t.Nullable(t.Number()),issueTitle: t.Nullable(t.String()),issueStateType: t.Nullable(t.String()),+ issueCommentId: t.Nullable(t.Number()),documentId: t.Nullable(t.Number()),documentTitle: t.Nullable(t.String()),documentIcon: t.Nullable(t.String()),diff --git a/apps/api/src/modules/notifications/outbound.ts b/apps/api/src/modules/notifications/outbound.tsindex 2035f993..92a03f85 100644--- a/apps/api/src/modules/notifications/outbound.ts+++ b/apps/api/src/modules/notifications/outbound.ts@@ -17,7 +17,7 @@ import { readRedactedSettings } from '#modules/notification-settings/service';import { getPreferencesForUsers } from '#modules/notification-preferences/service';import { getTelegramChatIds, hasUsableInstanceBot } from '#modules/telegram/service';import { escapeHtml } from '#shared/lib';-import { documentUrl, issueUrl, teamRef } from '#modules/teams/ref';+import { commentUrl, documentUrl, issueUrl, teamRef } from '#modules/teams/ref';import type { NotificationType, NewNotificationRow } from './service';// Outbound notification delivery: turns the inbox notification rows produced by an@@ -164,11 +164,12 @@ interface Messages {}// The copy of one event, about the issue or the document its rows point at. Null when-// that is gone.+// that is gone. A comment's event links to the comment.async function composeMessages(notifications: NewNotificationRow[],projectRow: { key: string; teamId: number; teamSlug: string | null },actor: string,+ commentId: number | null,): Promise<Messages | null> {const first = notifications[0];const ref = teamRef({ id: projectRow.teamId, slug: projectRow.teamSlug });@@ -194,7 +195,10 @@ async function composeMessages(.where(eq(issue.id, first.issueId));if (!issueRow) return null;const issueKey = issueRef(projectRow.key, issueRow.seq);- const url = issueUrl(ref, projectRow.key, issueRow.seq);+ const url =+ commentId != null+ ? commentUrl(ref, projectRow.key, issueRow.seq, commentId)+ : issueUrl(ref, projectRow.key, issueRow.seq);// One issue event, so every 'state_changed' row points at the same activity row.const statusActivityId =notifications.find((n) => n.type === 'state_changed')?.sourceActivityId ?? null;@@ -212,6 +216,7 @@ async function composeMessages(export async function enqueueOutbound(notifications: NewNotificationRow[],actorName: string | null,+ commentId: number | null,): Promise<void> {if (notifications.length === 0) return;const projectId = notifications[0].projectId;@@ -242,7 +247,12 @@ export async function enqueueOutbound(settings.telegram.enabled && (settings.telegram.hasBotToken || (await hasUsableInstanceBot()));if (!emailEnabled && !telegramEnabled) return;- const messages = await composeMessages(notifications, projectRow, actorName ?? 'Someone');+ const messages = await composeMessages(+ notifications,+ projectRow,+ actorName ?? 'Someone',+ commentId,+ );if (!messages) return;const userIds = [...new Set(notifications.map((n) => n.userId))];diff --git a/apps/api/src/modules/notifications/service.ts b/apps/api/src/modules/notifications/service.tsindex c4eca9c6..9d20f204 100644--- a/apps/api/src/modules/notifications/service.ts+++ b/apps/api/src/modules/notifications/service.ts@@ -59,14 +59,18 @@ async function actorName(id: string | null): Promise<string | null> {return rows[0]?.name ?? null;}-async function insertNotifications(rows: NewNotificationRow[]): Promise<void> {+// commentId names the comment the event is about, which its email and Telegram link to.+async function insertNotifications(+ rows: NewNotificationRow[],+ commentId: number | null = null,+): Promise<void> {if (rows.length === 0) return;const name = await actorName(rows[0].actorUserId);await db.insert(notification).values(rows.map((r) => ({ ...r, actorName: name })));// Fan out to the project's enabled delivery channels (email, Telegram). Best-effort:// a delivery failure must not break the inbox insert or the domain mutation.try {- await enqueueOutbound(rows, name);+ await enqueueOutbound(rows, name, commentId);} catch (err) {console.error('[notifications] outbound enqueue failed:', err);}@@ -109,7 +113,7 @@ export async function notifyComment(actorUserId: actor,});}- await insertNotifications(rows);+ await insertNotifications(rows, comment.id);}// Fan out the mentions an edit newly added to a comment. The handles the comment@@ -135,6 +139,7 @@ export async function notifyEditedCommentMentions(type: 'mentioned' as const,actorUserId: comment.actorUserId,})),+ comment.id,);}@@ -273,6 +278,8 @@ export interface NotificationRow {issueSeq: number | null;issueTitle: string | null;issueStateType: string | null;+ // Set while the issue comment it is about still exists.+ issueCommentId: number | null;documentId: number | null;documentTitle: string | null;documentIcon: string | null;@@ -327,6 +334,8 @@ function mapRow(r: {issueSeq: number | null;issueTitle: string | null;issueStateType: string | null;+ activityId: number | null;+ activityKind: string | null;documentId: number | null;documentTitle: string | null;documentIcon: string | null;@@ -349,6 +358,7 @@ function mapRow(r: {issueSeq: r.issueSeq,issueTitle: r.issueTitle,issueStateType: r.issueStateType,+ issueCommentId: r.activityKind === 'comment' ? r.activityId : null,documentId: r.documentId,documentTitle: r.documentTitle,documentIcon: r.documentIcon,@@ -406,6 +416,8 @@ export async function listNotifications(issueSeq: issue.sequenceNumber,issueTitle: issue.title,issueStateType: projectColumn.stateType,+ activityId: issueActivity.id,+ activityKind: issueActivity.kind,documentId: projectDocument.id,documentTitle: projectDocument.title,documentIcon: projectDocument.icon,diff --git a/apps/api/src/modules/teams/ref.ts b/apps/api/src/modules/teams/ref.tsindex 711a2892..1a30a49a 100644--- a/apps/api/src/modules/teams/ref.ts+++ b/apps/api/src/modules/teams/ref.ts@@ -54,6 +54,17 @@ export function issueUrl(teamRef: string, key: string, seq: number): string | unreturn base ? `${base}${issueWebPath(teamRef, key, seq)}` : undefined;}+// The full URL of a comment on its issue's page, or undefined as for issueUrl.+export function commentUrl(+ teamRef: string,+ key: string,+ seq: number,+ commentId: number,+): string | undefined {+ const url = issueUrl(teamRef, key, seq);+ return url && `${url}#comment-${commentId}`;+}+// The full URL of a document's page, e.g. "/acme/MKT/docs/12" on the web origin, or// undefined as for issueUrl.export function documentUrl(teamRef: string, key: string, documentId: number): string | undefined {diff --git a/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.tsindex 85ef7452..08bc89cc 100644--- a/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts+++ b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts@@ -16,6 +16,7 @@ async function setupOwnerProject() {owner,asOwner,projectId: project.data!.id,+ teamRef: project.data!.teamRef,columnId: view.data!.columns[0].id,columns: view.data!.columns,};@@ -485,19 +486,24 @@ describe('webhooks', () => {});it('names the issue a comment is on', async () => {- const { asOwner, columnId } = await setupOwnerProject();+ const { asOwner, columnId, teamRef } = await setupOwnerProject();const id = await createWebhook(asOwner, ['comment.created']);const issue = (await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })).data!;- await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'looks good' });+ const comment = (+ await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'looks good' })+ ).data!;const [payload] = await payloads(asOwner, id);+ const issueLink = `${process.env.APP_URL}/${teamRef}/issue/${issue.identifier}`;+ expect(payload.data.url).toBe(`${issueLink}#comment-${comment.id}`);expect(payload.data.issue).toMatchObject({id: issue.id,identifier: issue.identifier,title: 'Task',+ url: issueLink,});});});diff --git a/apps/web/messages/ar/issue.json b/apps/web/messages/ar/issue.jsonindex aad7c267..5ee13687 100644--- a/apps/web/messages/ar/issue.json+++ b/apps/web/messages/ar/issue.json@@ -247,6 +247,8 @@"toSend": "للإرسال","unknownAuthor": "غير معروف","goToLastComment": "الانتقال إلى آخر تعليق",+ "copyLink": "نسخ الرابط",+ "linkCopied": "تم نسخ الرابط","edit": "تعديل","edited": "تم التعديل","deleteComment": "حذف التعليق",diff --git a/apps/web/messages/en/issue.json b/apps/web/messages/en/issue.jsonindex 58947f30..8f8f40a4 100644--- a/apps/web/messages/en/issue.json+++ b/apps/web/messages/en/issue.json@@ -247,6 +247,8 @@"toSend": "to send","unknownAuthor": "Unknown","goToLastComment": "Go to the last comment",+ "copyLink": "Copy link",+ "linkCopied": "Link copied","edit": "Edit","edited": "edited","deleteComment": "Delete comment",diff --git a/apps/web/messages/es-ES/issue.json b/apps/web/messages/es-ES/issue.jsonindex 4b8e8b4a..b3c5bec5 100644--- a/apps/web/messages/es-ES/issue.json+++ b/apps/web/messages/es-ES/issue.json@@ -247,6 +247,8 @@"toSend": "para enviar","unknownAuthor": "Desconocido","goToLastComment": "Ir al último comentario",+ "copyLink": "Copiar el enlace",+ "linkCopied": "Enlace copiado","edit": "Editar","edited": "editado","deleteComment": "Eliminar comentario",diff --git a/apps/web/messages/fa/issue.json b/apps/web/messages/fa/issue.jsonindex 68ac8d07..e455dd1b 100644--- a/apps/web/messages/fa/issue.json+++ b/apps/web/messages/fa/issue.json@@ -247,6 +247,8 @@"toSend": "برای ارسال","unknownAuthor": "ناشناس","goToLastComment": "رفتن به آخرین دیدگاه",+ "copyLink": "کپی لینک",+ "linkCopied": "لینک کپی شد","edit": "ویرایش","edited": "ویرایششده","deleteComment": "حذف دیدگاه",diff --git a/apps/web/messages/fr/issue.json b/apps/web/messages/fr/issue.jsonindex 1ce1b48b..c25f70dc 100644--- a/apps/web/messages/fr/issue.json+++ b/apps/web/messages/fr/issue.json@@ -247,6 +247,8 @@"toSend": "pour envoyer","unknownAuthor": "Inconnu","goToLastComment": "Aller au dernier commentaire",+ "copyLink": "Copier le lien",+ "linkCopied": "Lien copié","edit": "Modifier","edited": "modifié","deleteComment": "Supprimer le commentaire",diff --git a/apps/web/messages/id/issue.json b/apps/web/messages/id/issue.jsonindex b766a277..983bd7fa 100644--- a/apps/web/messages/id/issue.json+++ b/apps/web/messages/id/issue.json@@ -247,6 +247,8 @@"toSend": "untuk mengirim","unknownAuthor": "Tidak diketahui","goToLastComment": "Buka komentar terakhir",+ "copyLink": "Salin tautan",+ "linkCopied": "Tautan disalin","edit": "Ubah","edited": "diedit","deleteComment": "Hapus komentar",diff --git a/apps/web/messages/ko/issue.json b/apps/web/messages/ko/issue.jsonindex d6926113..27ce1067 100644--- a/apps/web/messages/ko/issue.json+++ b/apps/web/messages/ko/issue.json@@ -247,6 +247,8 @@"toSend": "전송","unknownAuthor": "알 수 없음","goToLastComment": "마지막 댓글로 이동",+ "copyLink": "링크 복사",+ "linkCopied": "링크 복사됨","edit": "편집","edited": "편집됨","deleteComment": "댓글 삭제",diff --git a/apps/web/messages/pt-BR/issue.json b/apps/web/messages/pt-BR/issue.jsonindex 4ce2d2d8..cbbedd94 100644--- a/apps/web/messages/pt-BR/issue.json+++ b/apps/web/messages/pt-BR/issue.json@@ -247,6 +247,8 @@"toSend": "para enviar","unknownAuthor": "Desconhecido","goToLastComment": "Ir para o último comentário",+ "copyLink": "Copiar link",+ "linkCopied": "Link copiado","edit": "Editar","edited": "editado","deleteComment": "Excluir comentário",diff --git a/apps/web/messages/ru/issue.json b/apps/web/messages/ru/issue.jsonindex 23b04726..bf5d29a0 100644--- a/apps/web/messages/ru/issue.json+++ b/apps/web/messages/ru/issue.json@@ -247,6 +247,8 @@"toSend": "чтобы отправить","unknownAuthor": "Неизвестный","goToLastComment": "Перейти к последнему комментарию",+ "copyLink": "Копировать ссылку",+ "linkCopied": "Ссылка скопирована","edit": "Редактировать","edited": "изменено","deleteComment": "Удалить комментарий",diff --git a/apps/web/messages/tr/issue.json b/apps/web/messages/tr/issue.jsonindex 71c741d9..462c9f60 100644--- a/apps/web/messages/tr/issue.json+++ b/apps/web/messages/tr/issue.json@@ -247,6 +247,8 @@"toSend": "göndermek için","unknownAuthor": "Bilinmeyen","goToLastComment": "Son yoruma git",+ "copyLink": "Bağlantıyı kopyala",+ "linkCopied": "Bağlantı kopyalandı","edit": "Düzenle","edited": "düzenlendi","deleteComment": "Yorumu sil",diff --git a/apps/web/messages/uk/issue.json b/apps/web/messages/uk/issue.jsonindex ac98a8c9..6d6461e4 100644--- a/apps/web/messages/uk/issue.json+++ b/apps/web/messages/uk/issue.json@@ -247,6 +247,8 @@"toSend": "щоб надіслати","unknownAuthor": "Невідомий","goToLastComment": "Перейти до останнього коментаря",+ "copyLink": "Копіювати посилання",+ "linkCopied": "Посилання скопійовано","edit": "Редагувати","edited": "змінено","deleteComment": "Видалити коментар",diff --git a/apps/web/messages/zh-CN/issue.json b/apps/web/messages/zh-CN/issue.jsonindex d85022b4..0140766a 100644--- a/apps/web/messages/zh-CN/issue.json+++ b/apps/web/messages/zh-CN/issue.json@@ -247,6 +247,8 @@"toSend": "发送","unknownAuthor": "未知用户","goToLastComment": "跳转到最新评论",+ "copyLink": "复制链接",+ "linkCopied": "链接已复制","edit": "编辑","edited": "已编辑","deleteComment": "删除评论",diff --git a/apps/web/messages/zh-TW/issue.json b/apps/web/messages/zh-TW/issue.jsonindex ddfcdd84..73215c4f 100644--- a/apps/web/messages/zh-TW/issue.json+++ b/apps/web/messages/zh-TW/issue.json@@ -247,6 +247,8 @@"toSend": "傳送","unknownAuthor": "未知使用者","goToLastComment": "跳轉到最新留言",+ "copyLink": "複製連結",+ "linkCopied": "連結已複製","edit": "編輯","edited": "已編輯","deleteComment": "刪除留言",diff --git a/apps/web/src/features/inbox/components/InboxDetail.tsx b/apps/web/src/features/inbox/components/InboxDetail.tsxindex 390fdb9d..76d7fdb9 100644--- a/apps/web/src/features/inbox/components/InboxDetail.tsx+++ b/apps/web/src/features/inbox/components/InboxDetail.tsx@@ -47,6 +47,7 @@ export default function InboxDetail({issueId={notification.issueId!}layout={isMobile ? 'panel' : 'split'}onDeleted={onDeleted}+ commentId={notification.issueCommentId}/></div>)}diff --git a/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsx b/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsxindex 882ecb52..8eebd94e 100644--- a/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsx+++ b/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsx@@ -24,6 +24,7 @@ let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;function render({projectKey = 'acme.TEST',issueSeq = 42 as number | null,+ issueCommentId = null as number | null,documentId = null as number | null,documentTitle = null as string | null,isMobile = false,@@ -33,7 +34,7 @@ function render({<NextIntlClientProvider locale="en" messages={{ documents, inbox, issue }} timeZone="UTC"><InboxDetailHeaderprojectKey={projectKey}- notification={{ issueSeq, documentId, documentTitle }}+ notification={{ issueSeq, issueCommentId, documentId, documentTitle }}isMobile={isMobile}onBack={() => {backCalls += 1;@@ -106,6 +107,15 @@ describe('InboxDetailHeader', () => {assert.equal(backCalls, 0);});+ it('opens the page of a comment notification at the comment', () => {+ render({ issueCommentId: 7 });+ assert.equal(+ document.querySelector('a')?.getAttribute('href'),+ '/acme/issue/TEST-42#comment-7',+ );+ assert.ok(document.querySelector('#root')?.textContent?.includes('TEST-42'));+ });+it('uses the canonical route builder for project keys', () => {render({ projectKey: '12.R&D', issueSeq: 9 });assert.equal(document.querySelector('a')?.getAttribute('href'), '/12/issue/R%26D-9');diff --git a/apps/web/src/features/inbox/components/InboxDetailHeader.tsx b/apps/web/src/features/inbox/components/InboxDetailHeader.tsxindex 956f6d24..bfc13564 100644--- a/apps/web/src/features/inbox/components/InboxDetailHeader.tsx+++ b/apps/web/src/features/inbox/components/InboxDetailHeader.tsx@@ -5,7 +5,7 @@ import { ChevronLeft, Maximize2 } from 'lucide-react';import { useTranslations } from 'next-intl';import type { Notification } from '@/lib/api/endpoints/notifications';import { Button } from '@/components/ui/button';-import { documentPath, issuePath, splitProjectRef } from '@/utils/paths';+import { commentPath, documentPath, issuePath, splitProjectRef } from '@/utils/paths';export default function InboxDetailHeader({projectKey,@@ -14,7 +14,7 @@ export default function InboxDetailHeader({onBack,}: {projectKey: string;- notification: Pick<Notification, 'issueSeq' | 'documentId' | 'documentTitle'>;+ notification: Pick<Notification, 'issueSeq' | 'issueCommentId' | 'documentId' | 'documentTitle'>;isMobile: boolean;onBack: () => void;}) {@@ -22,6 +22,10 @@ export default function InboxDetailHeader({const tIssue = useTranslations('issue');const tDocuments = useTranslations('documents');const openLabel = tIssue('openAsPage');+ const issueHref =+ n.issueCommentId != null+ ? commentPath(projectKey, n.issueSeq!, n.issueCommentId)+ : issuePath(projectKey, n.issueSeq!);const { label, href } =n.documentId != null? {@@ -30,7 +34,7 @@ export default function InboxDetailHeader({}: {label: `${splitProjectRef(projectKey).key}-${n.issueSeq}`,- href: issuePath(projectKey, n.issueSeq!),+ href: issueHref,};return (diff --git a/apps/web/src/features/issue/IssueViewPage.tsx b/apps/web/src/features/issue/IssueViewPage.tsxindex 19bd8279..17b2b24b 100644--- a/apps/web/src/features/issue/IssueViewPage.tsx+++ b/apps/web/src/features/issue/IssueViewPage.tsx@@ -12,6 +12,7 @@ import { useProjectsQuery } from '@/services/projects.service';import IssueDetailContent from './components/detail/IssueDetailContent';import IssueDetailSkeleton from './components/detail/IssueDetailSkeleton';import { useIssueTitle } from './hooks/useIssueTitle';+import { useCommentHash } from './hooks/useCommentHash';import { useTranslations } from 'next-intl';// The full-page issue view (/:team/issue/:identifier), rendered inside the Shell@@ -22,6 +23,7 @@ export default function IssueViewPage() {const router = useRouter();const { project } = useShell();const seq = useShellRoute().routeIssueSeq;+ const commentId = useCommentHash();const exit = () => project && router.push(projectPath(project.project.ref));useExitOnEscape(exit);@@ -37,7 +39,7 @@ export default function IssueViewPage() {const movedTo = moved ? projects?.find((p) => p.id === issueQuery.data!.projectId) : undefined;useEffect(() => {if (movedTo && issueQuery.data)- router.replace(issuePath(movedTo.ref, issueQuery.data.sequenceNumber));+ router.replace(issuePath(movedTo.ref, issueQuery.data.sequenceNumber) + window.location.hash);}, [movedTo, issueQuery.data, router]);useIssueTitle(moved || issueQuery.isError ? null : (issueQuery.data?.id ?? null), 'page');@@ -52,6 +54,7 @@ export default function IssueViewPage() {issueId={issueQuery.data.id}layout="page"onDeleted={exit}+ commentId={commentId}/>) : issueQuery.isLoading || (moved && (!projects || movedTo)) ? (<IssueDetailSkeleton />diff --git a/apps/web/src/features/issue/components/detail/CommentItem.tsx b/apps/web/src/features/issue/components/detail/CommentItem.tsxindex 8b394664..e68ca9a3 100644--- a/apps/web/src/features/issue/components/detail/CommentItem.tsx+++ b/apps/web/src/features/issue/components/detail/CommentItem.tsx@@ -1,16 +1,20 @@import { useState } from 'react';-import { Pencil, Reply, Trash2 } from 'lucide-react';+import { Link2, Pencil, Reply, Trash2 } from 'lucide-react';+import { toast } from 'sonner';import type { FeedItem } from '@/lib/api/endpoints/activity';import Avatar from '@/components/common/Avatar';import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';import MarkdownEditor from '@/components/common/editor/MarkdownEditor';import { Button } from '@/components/ui/button';import { useRelativeTime } from '@/context/relativeTimeContext';+import { commentPath } from '@/utils/paths';import CommentComposer, { type ComposerContext } from './CommentComposer';+import { useCommentLink } from '../../context/commentLink';import { useDeleteComment } from '../../services/comments.service';+import { writeClipboardText } from '../../utils/clipboard';import { useTranslations } from 'next-intl';-// One comment inside a thread: a line of author, age and the reply button over the+// One comment inside a thread: a line of author, age and its actions over the// rendered markdown body. A feed entry stores the author's name, not their picture,// so the uploaded avatar comes in as a prop (null falls back to the initials circle).// The indent of a reply belongs to CommentThread.@@ -36,15 +40,34 @@ export default function CommentItem({composer?: ComposerContext;}) {const t = useTranslations('issue.comments');+ const tMenu = useTranslations('issue.menu');const deleteComment = useDeleteComment();+ const link = useCommentLink();const relativeTime = useRelativeTime();const author = item.actorName ?? t('unknownAuthor');const [editing, setEditing] = useState(false);const [confirmingDelete, setConfirmingDelete] = useState(false);+ async function copyLink(projectKey: string, sequenceNumber: number) {+ try {+ await writeClipboardText(+ `${window.location.origin}${commentPath(projectKey, sequenceNumber, item.id)}`,+ );+ toast.success(t('linkCopied'));+ } catch {+ toast.error(tMenu('copyFailed'));+ }+ }+return (- // The id is the scroll target of the last-comment bubble.- <div id={`feed-item-${item.id}`} className="group/comment">+ // The id is the scroll target of the last-comment bubble and of a comment link.+ <div id={`feed-item-${item.id}`} className="group/comment relative scroll-mt-20">+ {link?.highlightedId === item.id && (+ <span+ aria-hidden+ className="pointer-events-none absolute -inset-x-2 -inset-y-1.5 animate-out rounded-lg bg-primary/10 delay-1000 duration-1000 fill-mode-forwards fade-out motion-reduce:animate-none"+ />+ )}<div className="flex items-center gap-2.5"><Avatar name={author} image={image} className="size-6 shrink-0 text-[10px]" /><span className="truncate text-[13px] font-semibold">{author}</span>@@ -54,6 +77,17 @@ export default function CommentItem({</span>{(onReply || canEdit || canDelete) && (<div className="ms-auto flex shrink-0 items-center gap-0.5 focus-within:opacity-100 sm:opacity-0 sm:group-hover/comment:opacity-100">+ {link && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => void copyLink(link.projectKey, link.sequenceNumber)}+ className="h-6 px-2 text-xs text-muted-foreground"+ title={t('copyLink')}+ >+ <Link2 className="size-3.5" />+ </Button>+ )}{canEdit && (<Buttonsize="sm"diff --git a/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx b/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsxindex ef9e65ab..d799bf4a 100644--- a/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx+++ b/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx@@ -3,6 +3,8 @@ import type { Column } from '@/lib/api/endpoints/columns';import { useSession } from '@/lib/auth-client';import { Tabs, TabsContent } from '@/components/ui/tabs';import { type ActivityFeedView, type ActivityTab } from '../../hooks/useActivityFeedView';+import { useCommentAnchor } from '../../hooks/useCommentAnchor';+import { CommentLinkProvider } from '../../context/commentLink';import CommentComposer, { type ComposerContext } from './CommentComposer';import IssueActivityToolbar from './IssueActivityToolbar';import IssueFeedList from './IssueFeedList';@@ -20,21 +22,26 @@ const EMPTY_TEXT = {export default function IssueActivityFeed({issueId,projectKey,+ sequenceNumber,columns,imageByUserId,view,canReadAgentRuns,+ commentId,}: {issueId: number;projectKey: string;+ sequenceNumber: number;columns: Column[];imageByUserId: Map<string, string | null>;view: ActivityFeedView;canReadAgentRuns: boolean;+ commentId: number | null;}) {const tIssue = useTranslations('issue');const t = useTranslations('issue.comments');const { data: session } = useSession();+ const highlightedId = useCommentAnchor(issueId, view, commentId);const user = session?.user ?? null;const composer: ComposerContext = {@@ -86,7 +93,15 @@ export default function IssueActivityFeed({className="mt-5 gap-3"><IssueActivityToolbar issueId={issueId} view={view} canReadAgentRuns={canReadAgentRuns} />- <TabsContent value={view.tab}>{content}</TabsContent>+ <TabsContent value={view.tab}>+ <CommentLinkProvider+ projectKey={projectKey}+ sequenceNumber={sequenceNumber}+ highlightedId={highlightedId}+ >+ {content}+ </CommentLinkProvider>+ </TabsContent></Tabs>)}</div>diff --git a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsxindex 29e4375d..d2a8c3e5 100644--- a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx+++ b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx@@ -45,6 +45,7 @@ export default function IssueDetailContent({onIssueLoaded,onDeleted,layout = 'panel',+ commentId = null,}: {project: ProjectDetail;issueId: number;@@ -58,6 +59,8 @@ export default function IssueDetailContent({// two-column shape but in normal flow (no fixed positioning), so it fits// inside a narrower container like the inbox pane.layout?: 'panel' | 'page' | 'split';+ // The comment to bring into view: the one a link or a notification points at.+ commentId?: number | null;}) {const t = useTranslations('issue');const tCommon = useTranslations('common');@@ -283,19 +286,25 @@ export default function IssueDetailContent({<IssueActivityFeedissueId={issue.id}projectKey={project.project.ref}+ sequenceNumber={issue.sequenceNumber}columns={project.columns}imageByUserId={imageByUserId}view={effectiveActivityView}canReadAgentRuns={canReadAgentRuns}+ commentId={commentId}/></div>- <LastCommentBubble- key={issue.id}- issueId={issue.id}- feedRef={feedRef}- imageByUserId={imageByUserId}- view={effectiveActivityView}- />+ {/* The reader came for that comment, and the bubble would rise while the feed+ loads the pages before it. */}+ {commentId == null && (+ <LastCommentBubble+ key={issue.id}+ issueId={issue.id}+ feedRef={feedRef}+ imageByUserId={imageByUserId}+ view={effectiveActivityView}+ />+ )}</>);diff --git a/apps/web/src/features/issue/context/commentLink.tsx b/apps/web/src/features/issue/context/commentLink.tsxnew file mode 100644index 00000000..bc1f3f45--- /dev/null+++ b/apps/web/src/features/issue/context/commentLink.tsx@@ -0,0 +1,28 @@+'use client';++import { createContext, useContext, type ReactNode } from 'react';++// What a comment of the live feed needs to copy its own link and to show that a link+// brought the reader to it. Provided by the feed so the comments deep in its threads+// read it instead of every list between them passing it down.+type CommentLink = { projectKey: string; sequenceNumber: number; highlightedId: number | null };++const CommentLinkContext = createContext<CommentLink | null>(null);++export function CommentLinkProvider({+ projectKey,+ sequenceNumber,+ highlightedId,+ children,+}: CommentLink & { children: ReactNode }) {+ return (+ <CommentLinkContext.Provider value={{ projectKey, sequenceNumber, highlightedId }}>+ {children}+ </CommentLinkContext.Provider>+ );+}++// Null outside the live feed: the share page and the timeline popover offer no link.+export function useCommentLink(): CommentLink | null {+ return useContext(CommentLinkContext);+}diff --git a/apps/web/src/features/issue/hooks/useActivityFeedView.ts b/apps/web/src/features/issue/hooks/useActivityFeedView.tsindex 73fc60f8..13e41204 100644--- a/apps/web/src/features/issue/hooks/useActivityFeedView.ts+++ b/apps/web/src/features/issue/hooks/useActivityFeedView.ts@@ -14,7 +14,8 @@ const ORDER_KEY = 'issue-activity-order';// How the activity log of every issue is shown: the tab and the order are the last// ones picked in this browser, and grouping by status is the account preference, so-// switching it here changes it on the preferences page too.+// switching it here changes it on the preferences page too. showAll does not save the+// tab, so following a link to a comment keeps the saved one.//// The stored values are read in an effect, not in the state initializer: the// initializer also runs during the server render, where there is no localStorage.@@ -43,6 +44,8 @@ export function useActivityFeedView() {setStored((prev) => prev && { ...prev, order });}, []);+ const showAll = useCallback(() => setStored((prev) => prev && { ...prev, tab: 'all' }), []);+const setGrouped = useCallback((grouped: boolean) => mutate({ issueActivityView: grouped ? 'grouped' : 'flat' }),[mutate],@@ -60,6 +63,7 @@ export function useActivityFeedView() {setTab,setOrder,setGrouped,+ showAll,};}diff --git a/apps/web/src/features/issue/hooks/useCommentAnchor.test.tsx b/apps/web/src/features/issue/hooks/useCommentAnchor.test.tsxnew file mode 100644index 00000000..011fa75c--- /dev/null+++ b/apps/web/src/features/issue/hooks/useCommentAnchor.test.tsx@@ -0,0 +1,308 @@+import assert from 'node:assert/strict';+import { createRequire } from 'node:module';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act, StrictMode } 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 * as auth from '@/lib/auth-client';+import { type FeedSlice, useFeedQuery } from '../services/comments.service';+import { type ActivityFeedView, useActivityFeedView } from './useActivityFeedView';+import { useCommentAnchor } from './useCommentAnchor';++const spyOn = createRequire(import.meta.url)('bun:test').spyOn as (+ target: object,+ method: string,+) => { mockReturnValue(value: unknown): { mockRestore(): void } };++const ISSUE_ID = 1;+const replacedGlobals = [+ 'window',+ 'document',+ 'navigator',+ 'HTMLElement',+ 'localStorage',+ 'getComputedStyle',+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ 'ResizeObserver',+ 'fetch',+ 'IS_REACT_ACT_ENVIRONMENT',+] as const;++interface ObserverHarness {+ target: Element | null;+ disconnected: boolean;+ trigger: () => void;+}++// The entry ids of each page the feed api serves, by the tab's filter.+let feeds: Record<string, number[][]>;+let failingPage: number | null;+// A page the api answers only once the test calls releaseHeldPage, so the test acts+// while that page is in flight.+let heldPage: number | null;+let releaseHeldPage: () => void;+// Every feed page asked for, as "<filter>:<page>".+let requests: string[];+let scrolls: string[];+let observers: ObserverHarness[];+let view: ActivityFeedView;++let dom: JSDOM;+let root: Root;+let client: QueryClient;+let restoreSession: () => void;+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++async function serve(input: RequestInfo | URL): Promise<Response> {+ const url = new URL(String(input));+ if (url.pathname === '/account/preferences') {+ return Response.json({ issueActivityView: 'flat' });+ }+ assert.equal(url.pathname, `/issues/${ISSUE_ID}/feed`);+ const filter = url.searchParams.get('filter') ?? 'all';+ const cursor = url.searchParams.get('cursor');+ const page = cursor ? (JSON.parse(cursor) as { id: number }).id : 0;+ requests.push(`${filter}:${page}`);+ const held = page === heldPage && new Promise<void>((resolve) => (releaseHeldPage = resolve));+ // A page arrives after the commit that starts its fetch, as it does over the network.+ await sleep(5);+ await held;+ if (page === failingPage) return Response.json({ error: 'Server error' }, { status: 500 });+ const pages = feeds[filter] ?? [[]];+ return Response.json({+ items: pages[page].map((id) => ({ id, kind: 'comment' })),+ nextCursor: page + 1 < pages.length ? { ts: '2026-01-01T00:00:00.000Z', id: page + 1 } : null,+ });+}++// The activity log as IssueActivityFeed wires it: the real feed view and feed query,+// with a bare element per loaded entry in place of the comment threads.+function Feed({ commentId }: { commentId: number | null }) {+ view = useActivityFeedView();+ const highlightedId = useCommentAnchor(ISSUE_ID, view, commentId);+ return (+ <div data-testid="scroller" style={{ overflowY: 'auto' }}>+ <div>+ <p data-testid="state">{`${view.tab}:${highlightedId ?? ''}`}</p>+ {view.ready && <FeedEntries slice={view.slice} />}+ </div>+ </div>+ );+}++function FeedEntries({ slice }: { slice: FeedSlice }) {+ const feed = useFeedQuery(ISSUE_ID, slice);+ return (feed.data?.pages ?? [])+ .flatMap((page) => page.items)+ .map((item) => <div key={item.id} id={`feed-item-${item.id}`} />);+}++async function render(commentId: number) {+ window.history.replaceState(null, '', `/acme/issue/TEST-1#comment-${commentId}`);+ await act(async () =>+ root.render(+ <StrictMode>+ <QueryClientProvider client={client}>+ <NextIntlClientProvider locale="en" messages={{}} timeZone="UTC">+ <Feed commentId={commentId} />+ </NextIntlClientProvider>+ </QueryClientProvider>+ </StrictMode>,+ ),+ );+}++async function until(check: () => boolean) {+ for (let i = 0; i < 100 && !check(); i++) await act(() => sleep(10));+ assert.ok(check(), 'the condition never held');+}++const tabAndHighlightedId = () => document.querySelector('[data-testid="state"]')?.textContent;+const anchoredId = () => window.history.state?.__itsaplanCommentAnchor;++beforeEach(async () => {+ feeds = {};+ failingPage = null;+ heldPage = null;+ requests = [];+ scrolls = [];+ observers = [];+ originalGlobalDescriptors = new Map(+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),+ );+ dom = new JSDOM('<!doctype html><div id="root"></div>', {+ url: 'https://example.test/acme/issue/TEST-1',+ pretendToBeVisual: true,+ });+ dom.window.HTMLElement.prototype.scrollIntoView = function (this: HTMLElement) {+ scrolls.push(this.id);+ };++ class TestResizeObserver {+ private readonly harness: ObserverHarness;++ constructor(callback: ResizeObserverCallback) {+ this.harness = {+ target: null,+ disconnected: false,+ trigger: () => callback([], this as unknown as ResizeObserver),+ };+ observers.push(this.harness);+ }++ observe(target: Element) {+ this.harness.target = target;+ }++ unobserve() {}++ disconnect() {+ this.harness.disconnected = true;+ }+ }++ Object.defineProperties(globalThis, {+ window: { configurable: true, value: dom.window },+ document: { configurable: true, value: dom.window.document },+ navigator: { configurable: true, value: dom.window.navigator },+ HTMLElement: { configurable: true, value: dom.window.HTMLElement },+ localStorage: { configurable: true, value: dom.window.localStorage },+ getComputedStyle: { configurable: true, value: dom.window.getComputedStyle.bind(dom.window) },+ requestAnimationFrame: {+ configurable: true,+ value: dom.window.requestAnimationFrame.bind(dom.window),+ },+ cancelAnimationFrame: {+ configurable: true,+ value: dom.window.cancelAnimationFrame.bind(dom.window),+ },+ ResizeObserver: { configurable: true, value: TestResizeObserver },+ fetch: { configurable: true, value: serve },+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },+ });+ const session = spyOn(auth, 'useSession').mockReturnValue({+ data: { user: { id: 'reader' } },+ isPending: false,+ error: null,+ });+ restoreSession = () => session.mockRestore();+ 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();+ restoreSession();+ dom.window.close();+ for (const [name, descriptor] of originalGlobalDescriptors) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else Reflect.deleteProperty(globalThis, name);+ }+});++describe('useCommentAnchor', () => {+ it('loads pages until the comment renders, then scrolls to it once and highlights it', async () => {+ feeds.all = [+ [1, 2],+ [3, 4],+ [5, 6],+ ];+ await render(5);+ await until(() => tabAndHighlightedId() === 'all:5');++ assert.deepEqual(requests, ['all:0', 'all:1', 'all:2']);+ assert.deepEqual(scrolls, ['feed-item-5']);+ assert.equal(anchoredId(), 5);++ // Content loading above the comment moves it, so a resize aligns it again until+ // the reader scrolls.+ const observer = observers.at(-1)!;+ assert.equal(observer.target, document.querySelector('[data-testid="scroller"] > div'));+ observer.trigger();+ assert.deepEqual(scrolls, ['feed-item-5', 'feed-item-5']);+ act(() => window.dispatchEvent(new dom.window.Event('wheel')));+ assert.equal(observer.disconnected, true);+ });++ it('gives up after the last page when the comment is not in the feed', async () => {+ feeds.all = [+ [1, 2],+ [3, 4],+ ];+ await render(9);+ await until(() => anchoredId() === 9);+ await act(() => sleep(100));++ assert.deepEqual(requests, ['all:0', 'all:1']);+ assert.deepEqual(scrolls, []);+ assert.equal(tabAndHighlightedId(), 'all:');+ });++ it('stops after a page fails instead of asking for it again', async () => {+ feeds.all = [+ [1, 2],+ [3, 4],+ [5, 6],+ ];+ failingPage = 1;+ await render(5);+ await until(() => anchoredId() === 5);+ await act(() => sleep(100));++ assert.deepEqual(requests, ['all:0', 'all:1']);+ assert.deepEqual(scrolls, []);+ assert.equal(tabAndHighlightedId(), 'all:');+ });++ it('stops when the reader scrolls before the comment is found', async () => {+ feeds.all = [[1], [2], [3]];+ heldPage = 1;+ await render(3);+ await until(() => requests.includes('all:1'));+ act(() => window.dispatchEvent(new dom.window.Event('wheel')));+ releaseHeldPage();+ await act(() => sleep(100));++ assert.deepEqual(requests, ['all:0', 'all:1']);+ assert.deepEqual(scrolls, []);+ assert.equal(anchoredId(), 3);+ });++ it('switches a saved History tab to All without saving the switch', async () => {+ localStorage.setItem('issue-activity-tab', 'history');+ feeds.history = [[10]];+ feeds.all = [[1, 2]];+ await render(2);+ await until(() => tabAndHighlightedId() === 'all:2');++ assert.deepEqual(scrolls, ['feed-item-2']);+ assert.deepEqual(+ requests.filter((request) => request.startsWith('all')),+ ['all:0'],+ );+ assert.equal(localStorage.getItem('issue-activity-tab'), 'history');+ });++ it('leaves the reader on a tab without comments they pick during the search', async () => {+ localStorage.setItem('issue-activity-tab', 'history');+ feeds.history = [[10]];+ feeds.all = [[1], [2], [3]];+ heldPage = 1;+ await render(3);+ await until(() => requests.includes('all:1'));+ act(() => view.setTab('history'));+ releaseHeldPage();+ await act(() => sleep(100));++ assert.equal(tabAndHighlightedId(), 'history:');+ assert.deepEqual(scrolls, []);+ assert.equal(anchoredId(), 3);+ });+});diff --git a/apps/web/src/features/issue/hooks/useCommentAnchor.ts b/apps/web/src/features/issue/hooks/useCommentAnchor.tsnew file mode 100644index 00000000..6db8aa6b--- /dev/null+++ b/apps/web/src/features/issue/hooks/useCommentAnchor.ts@@ -0,0 +1,156 @@+import { useEffect, useState } from 'react';+import { useFeedQuery, useGroupedFeedQuery } from '../services/comments.service';+import type { ActivityFeedView } from './useActivityFeedView';+import { markCommentAnchored } from './useCommentHash';++// How long the comment is kept in place after the jump while the content above it still+// loads, and how long it stays highlighted.+const SETTLE_MS = 3000;+const HIGHLIGHT_MS = 2000;+// The reader scrolling, touching, typing or clicking: from then on they move on their own.+const READER_EVENTS = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const;++// Brings the comment a link or a notification points at into view, and returns its id+// while it is highlighted. The feed renders 25 entries a page, so the hook loads pages+// through the list's own cache until the comment's element exists. It stops when the+// feed ends without it (the comment is deleted, or the id is not a comment's), when a+// page fails, or when the reader starts moving first.+export function useCommentAnchor(+ issueId: number,+ view: ActivityFeedView,+ commentId: number | null,+): number | null {+ const request = commentId == null ? null : `${issueId}:${commentId}`;+ const [prevRequest, setPrevRequest] = useState(request);+ const [searching, setSearching] = useState(request != null);+ const [tabSwitched, setTabSwitched] = useState(false);+ const [landedId, setLandedId] = useState<number | null>(null);+ const [highlightedId, setHighlightedId] = useState<number | null>(null);+ if (request !== prevRequest) {+ setPrevRequest(request);+ setSearching(request != null);+ setTabSwitched(false);+ setLandedId(null);+ setHighlightedId(null);+ }++ const flatFeed = useFeedQuery(issueId, view.slice, false);+ const groupedFeed = useGroupedFeedQuery(issueId, view.slice, false);+ const { data, isPending, isFetching, hasNextPage, isFetchNextPageError, fetchNextPage } =+ view.grouped ? groupedFeed : flatFeed;+ const { ready, tab, showAll } = view;++ // `data` is a dependency because the comment is looked for in the DOM rendered from it.+ useEffect(() => {+ if (!searching || commentId == null || !ready) return;+ const finish = () => {+ setSearching(false);+ markCommentAnchored(commentId);+ };+ if (tab !== 'all' && tab !== 'comments') {+ // After the one switch, a tab without comments is one the reader picked.+ if (tabSwitched) {+ finish();+ } else {+ setTabSwitched(true);+ showAll();+ }+ return;+ }+ if (document.getElementById(`feed-item-${commentId}`)) {+ setSearching(false);+ setLandedId(commentId);+ return;+ }+ // Pending means no page has arrived yet, also in the commit where the list only+ // starts the fetch.+ if (isPending || isFetching) return;+ if (hasNextPage && !isFetchNextPageError) {+ // Joins a live-refresh refetch in flight instead of cancelling it.+ void fetchNextPage({ cancelRefetch: false });+ } else {+ finish();+ }+ }, [+ searching,+ commentId,+ ready,+ tab,+ tabSwitched,+ showAll,+ data,+ isPending,+ isFetching,+ hasNextPage,+ isFetchNextPageError,+ fetchNextPage,+ ]);++ useEffect(() => {+ if (!searching || commentId == null) return;+ const stop = () => {+ setSearching(false);+ markCommentAnchored(commentId);+ };+ for (const type of READER_EVENTS)+ window.addEventListener(type, stop, { capture: true, passive: true });+ return () => {+ for (const type of READER_EVENTS) window.removeEventListener(type, stop, true);+ };+ }, [searching, commentId]);++ useEffect(() => {+ if (landedId == null) return;+ let observer: ResizeObserver | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const release = () => {+ observer?.disconnect();+ clearTimeout(timer);+ for (const type of READER_EVENTS) window.removeEventListener(type, release, true);+ };+ // A comment's body renders a tick after its element, so the jump waits a frame.+ const frame = requestAnimationFrame(() => {+ const el = document.getElementById(`feed-item-${landedId}`);+ if (!el) return;+ const scroller = scrollParent(el);+ const align = () =>+ el.scrollIntoView({+ block: scroller && el.offsetHeight > scroller.clientHeight / 2 ? 'start' : 'center',+ });+ align();+ setHighlightedId(landedId);+ markCommentAnchored(landedId);+ // The sections above the feed and the images load later and push the comment+ // down, and the page scroller has scroll anchoring off, so every resize aligns+ // it again.+ const content = scroller?.firstElementChild;+ if (content) {+ observer = new ResizeObserver(align);+ observer.observe(content);+ }+ timer = setTimeout(release, SETTLE_MS);+ for (const type of READER_EVENTS)+ window.addEventListener(type, release, { capture: true, passive: true });+ });+ return () => {+ cancelAnimationFrame(frame);+ release();+ };+ }, [landedId]);++ useEffect(() => {+ if (highlightedId == null) return;+ const timer = setTimeout(() => setHighlightedId(null), HIGHLIGHT_MS);+ return () => clearTimeout(timer);+ }, [highlightedId]);++ return highlightedId;+}++function scrollParent(el: HTMLElement): HTMLElement | null {+ for (let node = el.parentElement; node; node = node.parentElement) {+ const { overflowY } = getComputedStyle(node);+ if (overflowY === 'auto' || overflowY === 'scroll') return node;+ }+ return null;+}diff --git a/apps/web/src/features/issue/hooks/useCommentHash.ts b/apps/web/src/features/issue/hooks/useCommentHash.tsnew file mode 100644index 00000000..4f1c2fa1--- /dev/null+++ b/apps/web/src/features/issue/hooks/useCommentHash.ts@@ -0,0 +1,45 @@+import { useEffect, useState } from 'react';+import { usePathname } from 'next/navigation';++const ANCHORED_KEY = '__itsaplanCommentAnchor';++function hashCommentId(): number | null {+ const match = /^#comment-([1-9]\d{0,9})$/.exec(window.location.hash);+ return match ? Number(match[1]) : null;+}++// The comment the address points at (/acme/issue/MKT-42#comment-7), or null. The hash is+// read after each navigation: the issue page stays mounted from one issue to the next,+// and Next writes the new address after it renders. A comment already brought into view+// in this history entry gives null, so a reload or Back keeps the reader's own scroll+// position, as a browser does for a fragment it has followed.+export function useCommentHash(): number | null {+ const pathname = usePathname();+ const [read, setRead] = useState<{ pathname: string; commentId: number | null } | null>(null);++ useEffect(() => {+ const readHash = () => {+ const commentId = hashCommentId();+ const anchored = commentId != null && window.history.state?.[ANCHORED_KEY] === commentId;+ setRead({ pathname, commentId: anchored ? null : commentId });+ };+ readHash();+ window.addEventListener('hashchange', readHash);+ return () => window.removeEventListener('hashchange', readHash);+ }, [pathname]);++ // Read for the previous issue until the effect runs for this one.+ return read?.pathname === pathname ? read.commentId : null;+}++// Records on the history entry that its comment has been brought into view. The spread+// keeps the state Next and the scroll restoration store there. A target without a hash+// (the inbox) leaves the entry alone.+export function markCommentAnchored(commentId: number) {+ if (hashCommentId() !== commentId) return;+ window.history.replaceState(+ { ...window.history.state, [ANCHORED_KEY]: commentId },+ '',+ window.location.href,+ );+}diff --git a/apps/web/src/lib/api/endpoints/notifications.ts b/apps/web/src/lib/api/endpoints/notifications.tsindex 13ac32cd..022144da 100644--- a/apps/web/src/lib/api/endpoints/notifications.ts+++ b/apps/web/src/lib/api/endpoints/notifications.ts@@ -19,6 +19,8 @@ export interface Notification {issueSeq: number | null;issueTitle: string | null;issueStateType: StateType | null;+ // Set while the comment it is about still exists.+ issueCommentId: number | null;documentId: number | null;documentTitle: string | null;documentIcon: string | null;diff --git a/apps/web/src/utils/paths.ts b/apps/web/src/utils/paths.tsindex 5ec110c9..f65c1a70 100644--- a/apps/web/src/utils/paths.ts+++ b/apps/web/src/utils/paths.ts@@ -77,6 +77,9 @@ export const issuePath = (ref: string, sequenceNumber: number) => {return `/${encodeURIComponent(teamRef)}/issue/${encodeURIComponent(key)}-${sequenceNumber}`;};+export const commentPath = (ref: string, sequenceNumber: number, commentId: number) =>+ `${issuePath(ref, sequenceNumber)}#comment-${commentId}`;+// "MKT-42" -> { key: 'MKT', sequenceNumber: 42 }, or null for anything else.export function parseIssueIdentifier(identifier: string,