From c268e1134c391ff3451f37b9a92f299f335aa0d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:18:04 +0000 Subject: [PATCH 1/3] feat(record-page): the comment panel resolves, reopens and filters threads, counts the unresolved ones, and offers Edit and Delete on others' comments to a record editor (#36075) - Rows' is_resolved / resolved_by / resolved_at (#36071) reach FeedItem; the check on a thread's first comment writes { is_resolved } alone. - Filter menu: show resolved (resolver named) and only threads I'm in. - Icon count is the unresolved threads; a reply reopens its thread. - Edit and Delete on other members' comments only on the explain engine's definite allow of a by-id update of the record (useRecordVerdict, three-state; useRecordEditable unchanged). - Ten i18n keys in every pack; README, docs page and changeset. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgT8AtWDue4oTFNAE6H --- .changeset/36075-comments-resolved.md | 22 ++ .../docs/frontend/plugins/plugin-detail.mdx | 16 +- ...DetailView.commentsResolved-36075.test.tsx | 361 ++++++++++++++++++ .../app-shell/src/views/RecordDetailView.tsx | 196 +++++++++- ui/packages/i18n/src/locales/ar.ts | 10 + ui/packages/i18n/src/locales/de.ts | 10 + ui/packages/i18n/src/locales/en.ts | 10 + ui/packages/i18n/src/locales/es.ts | 10 + ui/packages/i18n/src/locales/fr.ts | 10 + ui/packages/i18n/src/locales/ja.ts | 10 + ui/packages/i18n/src/locales/ko.ts | 10 + ui/packages/i18n/src/locales/pt-BR.ts | 10 + ui/packages/i18n/src/locales/ru.ts | 10 + ui/packages/i18n/src/locales/zh-Hans.ts | 10 + ui/packages/i18n/src/locales/zh-Hant.ts | 10 + ui/packages/plugin-detail/README.md | 22 +- .../src/comments/CommentHoverActions.tsx | 17 +- .../src/comments/CommentThread.tsx | 86 ++++- .../CommentsPanel.resolved-36075.test.tsx | 213 +++++++++++ .../src/comments/CommentsPanel.tsx | 86 ++++- .../src/comments/commentThreads.ts | 55 +++ .../plugin-detail/src/comments/index.ts | 13 +- .../src/comments/useRecordComments.ts | 29 +- ui/packages/plugin-detail/src/index.tsx | 9 +- .../plugin-detail/src/useDetailTranslation.ts | 10 + .../plugin-detail/src/useRecordEditable.ts | 43 ++- .../src/useRecordVerdict-36075.test.tsx | 84 ++++ .../react/src/context/DiscussionContext.tsx | 18 + ui/packages/types/src/views.ts | 22 ++ 29 files changed, 1359 insertions(+), 53 deletions(-) create mode 100644 .changeset/36075-comments-resolved.md create mode 100644 ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx create mode 100644 ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx diff --git a/.changeset/36075-comments-resolved.md b/.changeset/36075-comments-resolved.md new file mode 100644 index 00000000000..de0427e622c --- /dev/null +++ b/.changeset/36075-comments-resolved.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/plugin-detail': patch +'@object-ui/react': patch +'@object-ui/types': patch +'@object-ui/i18n': patch +--- + +feat(record-page): the desktop comment panel resolves and reopens threads, filters them, counts the unresolved ones, and offers Edit and Delete on other people's comments to a member who may edit the record + +Clause-②: yes (widening) — `@object-ui/react`'s `DiscussionContextValue` adds two optional members: `onResolveComment(itemId, resolved)` and `moderatesComments`. `@object-ui/types`' `FeedItem` adds five optional members: `resolved`, `resolvedById`, `resolvedByName`, `resolvedAt`, `mentionsViewer`. `@object-ui/plugin-detail` adds exports `useRecordVerdict` (the three-state verdict `useRecordEditable` fails open on; `useRecordEditable` reads exactly as before), `threadResolvable`, `threadResolved`, `threadInvolvesViewer`, `filterCommentThreads`, `unresolvedThreadCount`, `DEFAULT_COMMENT_THREAD_FILTER` and the type `CommentThreadFilter`; `RecordCommentsData` adds `resolvable`, `onResolveComment` and `moderates`, and its `count` is now the unresolved threads; `CommentItemActions` adds `onResolve` and `resolved`; `CommentHoverActionsProps` adds `resolved`; `RecordCommentThreadProps['comments']` may carry `onResolveComment` and `moderates`. `@object-ui/i18n` adds ten keys to every pack: `detail.reopenThread`, `detail.threadResolved`, `detail.threadResolvedBy`, `detail.filterComments`, `detail.showResolvedComments`, `detail.commentsInvolvingMe`, `detail.noUnresolvedComments`, `detail.noCommentsInvolvingMe`, `detail.showAllComments`, `detail.commentResolveFailed`. Nothing existing is removed or re-typed. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the console's comment panel; `content/docs/frontend/plugins/plugin-detail.mdx` and the plugin-detail README gain resolved threads, the filter and the moderator's Edit and Delete in this change. + +The desktop record page's comment panel (objectstack#36075) gains the resolved threads #36071 stores: + +- ✓ in a thread's first comment's action row marks the thread resolved: it leaves the list and the comments icon's number, now the unresolved threads, drops by one. Anyone who may comment on the record may resolve (maintainer ruling 7063285032). +- The filter menu at the panel's top right holds 「显示已解决」, which shows resolved threads marked 「已由 X 解决」 (their ✓ reopens them), and 「只看我参与的」, the threads the viewer started, replied in or is mentioned in. The filter is not stored. With every thread resolved, the panel says so and offers to show them all. +- A reply into a resolved thread shows the thread reopened, as the platform stores it. +- Edit and Delete under More are offered on other members' comments to a member the explain engine admits to update the record by id, the server's own rule for editing someone else's comment; only on a definite allow, so a member is never offered a write the server refuses. Their own comments keep them as before. + +Unchanged: no server permission changes; a deployment whose comment rows carry no `is_resolved` shows no ✓ and no filter, and the icon counts every thread; hand-written record pages and the phone keep their feed as before. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index 2bb06c67db9..0dc10ae8822 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -202,14 +202,22 @@ opened from the comments icon in the record header (on the record page and in the record drawer), and no longer inside the 动态 (Activity) tab (objectstack#36075): -- **The icon** shows how many top-level comments the record holds. A press +- **The icon** shows how many unresolved threads the record holds (a comment + and its replies are one thread). A press opens the panel, the next one closes it, and the browser remembers whether it was left open, once for the record page and once for the drawer. - **The panel** is 380 px wide: 「评论」 and ✕ at the top, the threads oldest first, the comment box at the foot. A thread's replies fold to 「N 条回复」 - and open in place. A comment's actions (Reply, an emoji, and More with Edit - and Delete on your own comments) appear at its top right while the pointer is - over it. + and open in place. A comment's actions (Reply, an emoji, ✓ on a thread's + first comment, and More with Edit and Delete) appear at its top right while + the pointer is over it. Edit and Delete are on your own comments, and on + everyone's for a member who may edit the record (the server lets them). +- **Resolved threads**: ✓ marks a thread resolved (anyone who may comment on + the record may) and it leaves the list; the icon's number drops by one. The + filter menu at the panel's top right holds 「显示已解决」, which shows resolved + threads marked with who resolved them (their ✓ reopens them), and + 「只看我参与的」, the threads you started, replied in or are mentioned in. A + reply into a resolved thread reopens it. - **Where it sits**: beside the record from a 1280 px window, the record giving way; over the record's right edge in a narrower window. In a drawer narrower than 760 px (the default drawer is 720) it covers the drawer's body, and ✕ or diff --git a/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx new file mode 100644 index 00000000000..e641112828a --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx @@ -0,0 +1,361 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36075 PR 2 — the comment panel's resolved threads and the + * moderator's Edit and Delete, pinned through the REAL `RecordDetailView`: + * + * - The rows' `is_resolved` / `resolved_by` (#36071) reach the panel: the + * icon counts the unresolved threads, a resolved one is hidden until + * 「显示已解决」 and names its resolver (an author of the discussion here). + * - ✓ writes `{ is_resolved: true }` and nothing else on the top-level + * comment; the thread leaves the list and the count drops. + * - A reply into a resolved thread shows it reopened, as the platform stores. + * - Edit and Delete on another member's comment only on the explain engine's + * definite allow of a by-id update of the record; an unanswered verdict + * offers them on the viewer's own comments alone. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, within, act, waitFor, fireEvent } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u-ada', name: 'Ada', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => vi.fn(), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), + error: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + loading: vi.fn(), + dismiss: vi.fn(), + }), +})); +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +import { I18nProvider } from '@object-ui/i18n'; +import { MetadataCtx } from '@object-ui/react'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { toast } from 'sonner'; +import { RecordDetailView } from './RecordDetailView'; +import { __clearRecordEditableCache } from '../../../plugin-detail/src/useRecordEditable'; + +const OBJECT_NAME = 'crm_case'; +const NO_FEEDS = 'crm_note'; +const RECORD_ID = 'case-41'; +const THREAD = `${OBJECT_NAME}:${RECORD_ID}`; + +const ADA_BODY = 'Ada: customer called back about the outage'; +const GRACE_BODY = 'Grace: escalated to tier two'; +const REPLY_BODY = 'Grace: tier two confirmed'; + +const ROWS = [ + { + id: 'c-ada', + thread_id: THREAD, + author_id: 'u-ada', + author_name: 'Ada', + body: ADA_BODY, + created_at: '2026-10-01T08:00:00.000Z', + is_resolved: false, + resolved_by: null, + resolved_at: null, + }, + { + id: 'c-grace', + thread_id: THREAD, + author_id: 'u-grace', + author_name: 'Grace', + body: GRACE_BODY, + created_at: '2026-10-01T09:00:00.000Z', + is_resolved: true, + resolved_by: 'u-linus', + resolved_at: '2026-10-01T11:00:00.000Z', + }, + { + id: 'c-linus', + thread_id: THREAD, + parent_id: 'c-grace', + author_id: 'u-linus', + author_name: 'Linus', + body: REPLY_BODY, + created_at: '2026-10-01T10:00:00.000Z', + is_resolved: false, + resolved_by: null, + resolved_at: null, + }, +]; + +const FIELDS = { id: { type: 'text', label: 'Id' }, subject: { type: 'text', label: 'Subject' } }; +const OBJECTS = [ + { name: OBJECT_NAME, label: 'Case', fields: FIELDS }, + { name: NO_FEEDS, label: 'Note', fields: FIELDS, enable: { feeds: false } }, +]; + +const AUTHORED_PAGE = { + name: 'case_detail_page', + type: 'record', + object: OBJECT_NAME, + regions: [ + { + name: 'main', + components: [{ type: 'page:header', properties: { title: '{subject}' } }, { type: 'record:discussion' }], + }, + ], +}; + +function makeDataSource() { + return { + find: vi.fn(async (objectName: string) => { + if (objectName === 'sys_comment') return { data: ROWS.map((r) => ({ ...r })) }; + return { data: [] }; + }), + findOne: vi.fn(async (_o: string, id: string) => ({ id, subject: `Case ${id}` })), + create: vi.fn(async (_o: string, data: any) => ({ id: 'c-new', ...data })), + update: vi.fn(async (_o: string, id: string, patch: any) => ({ + ...ROWS.find((r) => r.id === id), + ...patch, + ...(patch.is_resolved === true ? { resolved_by: 'u-ada', resolved_at: '2026-10-02T00:00:00.000Z' } : {}), + ...(patch.is_resolved === false ? { resolved_by: null, resolved_at: null } : {}), + })), + delete: vi.fn(async () => true), + } as any; +} + +function metadataFor(pages: unknown[]) { + return { + objects: OBJECTS, + pages, + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => pages, + getItem: async () => null, + getItemsByType: (type: string) => (type === 'page' ? pages : type === 'object' ? OBJECTS : []), + getTypeStatus: () => 'ready', + } as any; +} + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const PERMS = { + authenticated: true, + userId: 'u-ada', + tenantId: null, + positions: ['member'], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: ['member'], + objects: { [OBJECT_NAME]: FULL, [NO_FEEDS]: FULL, sys_comment: FULL }, + fields: {}, +} as MePermissionsAuthenticatedResponse; + +interface MountOptions { + objectName?: string; + pages?: unknown[]; + embedded?: boolean; +} + +async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false }: MountOptions = {}) { + const dataSource = makeDataSource(); + const rendered = render( + + + + + {}} + objectNameOverride={objectName} + recordIdOverride={RECORD_ID} + embedded={embedded} + /> + + + + , + ); + await within(rendered.container).findByText(`Case ${RECORD_ID}`, undefined, { timeout: 4000 }).catch(() => undefined); + await act(async () => {}); + return { ...rendered, dataSource }; +} + +const button = (root: HTMLElement) => root.querySelector('[data-comments-button]') as HTMLButtonElement | null; +const panel = (root: HTMLElement) => root.querySelector('[data-comments-panel]') as HTMLElement | null; +const placement = (root: HTMLElement) => + root.querySelector('[data-comments-placement]')?.getAttribute('data-comments-placement') ?? null; + +/** The explain engine's answer to every `POST /security/explain`: `verdict` true, false, or none. */ +function stubExplain(verdict: boolean | null) { + vi.stubGlobal( + 'fetch', + vi.fn(async (url: unknown) => { + const body = + String(url).includes('/security/explain') && verdict !== null + ? { allowed: true, record: { recordId: RECORD_ID, visible: verdict } } + : { data: [] }; + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); + }), + ); +} + +function setWindowWidth(width: number) { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width }); + window.dispatchEvent(new Event('resize')); +} + +beforeEach(() => { + window.localStorage.clear(); + setWindowWidth(1440); + // The explain verdicts live in a module-level cache: each case asks afresh. + __clearRecordEditableCache(); + stubExplain(null); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + + +const count = (root: HTMLElement) => button(root)?.querySelector('[data-comments-count]')?.textContent ?? null; +const commentIn = (root: HTMLElement, text: string) => + Array.from(panel(root)!.querySelectorAll('[data-comment-item]')).find((el) => + el.querySelector(':scope > .pl-7 [data-comment-body]')?.textContent?.includes(text), + ) as HTMLElement | undefined; + +async function openPanel() { + const mounted = await mount(); + await waitFor(() => expect(button(mounted.container)).not.toBeNull()); + fireEvent.click(button(mounted.container)!); + await within(panel(mounted.container)!).findByText(ADA_BODY); + return mounted; +} + +async function showResolved() { + fireEvent.pointerDown(document.querySelector('[data-comments-filter]')!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await within(document.body).findByRole('menuitemcheckbox', { name: 'Show resolved' })); +} + +describe('resolved threads in the record comment panel (objectstack#36075)', () => { + it('the icon counts the unresolved threads, and a resolved one waits behind 「显示已解决」 with its resolver', async () => { + const { container } = await mount(); + await waitFor(() => expect(count(container)).toBe('1')); + fireEvent.click(button(container)!); + const p = within(panel(container)!); + await p.findByText(ADA_BODY); + expect(p.queryByText(GRACE_BODY)).toBeNull(); + await showResolved(); + expect(await p.findByText(GRACE_BODY)).toBeInTheDocument(); + expect(p.getByText('Resolved by Linus')).toBeInTheDocument(); + }); + + it('✓ writes is_resolved alone on the top-level comment; the thread leaves and the count drops', async () => { + const { container, dataSource } = await openPanel(); + await waitFor(() => expect(count(container)).toBe('1')); + const ada = commentIn(container, ADA_BODY)!; + await act(async () => { + fireEvent.click(ada.querySelector('[data-comment-action="resolve"]')!); + }); + expect(dataSource.update).toHaveBeenCalledWith('sys_comment', 'c-ada', { is_resolved: true }); + await waitFor(() => expect(within(panel(container)!).queryByText(ADA_BODY)).toBeNull()); + // No unresolved thread: the icon draws no number. + expect(count(container)).toBeNull(); + await showResolved(); + expect(await within(panel(container)!).findByText('Resolved by Ada')).toBeInTheDocument(); + }); + + it('a refused ✓ says so and leaves the thread where it was', async () => { + const { container, dataSource } = await openPanel(); + dataSource.update.mockRejectedValueOnce(new Error('403')); + const ada = commentIn(container, ADA_BODY)!; + await act(async () => { + fireEvent.click(ada.querySelector('[data-comment-action="resolve"]')!); + }); + expect(toast.error).toHaveBeenCalledWith('The thread was not updated. Please try again.'); + expect(within(panel(container)!).getByText(ADA_BODY)).toBeInTheDocument(); + expect(count(container)).toBe('1'); + }); + + it('the reopen ✓ writes is_resolved false and the thread counts again', async () => { + const { container, dataSource } = await openPanel(); + await showResolved(); + const grace = await waitFor(() => commentIn(container, GRACE_BODY)!); + await act(async () => { + fireEvent.click(grace.querySelector('[data-comment-action="reopen"]')!); + }); + expect(dataSource.update).toHaveBeenCalledWith('sys_comment', 'c-grace', { is_resolved: false }); + await waitFor(() => expect(count(container)).toBe('2')); + }); + + it('a reply into a resolved thread shows it reopened', async () => { + const { container } = await openPanel(); + await showResolved(); + const thread = (await waitFor(() => commentIn(container, GRACE_BODY)!)).closest('[data-comment-thread]') as HTMLElement; + expect(thread).toHaveAttribute('data-comment-thread-resolved', 'true'); + fireEvent.click(within(thread).getByRole('button', { name: /1 reply/ })); + const box = within(thread).getByPlaceholderText('Reply…'); + fireEvent.change(box, { target: { value: 'one more thing' } }); + await act(async () => { + fireEvent.keyDown(box, { key: 'Enter', ctrlKey: true }); + }); + await waitFor(() => expect(thread).not.toHaveAttribute('data-comment-thread-resolved')); + expect(count(container)).toBe('2'); + }); +}); + +describe("Edit and Delete on another member's comment (objectstack#36075 item 6)", () => { + const moreOn = (root: HTMLElement, text: string) => commentIn(root, text)?.querySelector(':scope > [data-comment-actions] [data-comment-action="more"]') ?? null; + + it('offered where the explain engine admits a by-id update of the record', async () => { + stubExplain(true); + const { container, dataSource } = await openPanel(); + await showResolved(); + await waitFor(() => expect(moreOn(container, GRACE_BODY)).not.toBeNull()); + fireEvent.pointerDown(moreOn(container, GRACE_BODY)!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await within(document.body).findByRole('menuitem', { name: 'Delete' })); + const dialog = await within(document.body).findByRole('alertdialog'); + await act(async () => { + fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' })); + }); + expect(dataSource.delete).toHaveBeenCalledWith('sys_comment', 'c-grace'); + }); + + it('not offered where it refuses', async () => { + stubExplain(false); + const { container } = await openPanel(); + await showResolved(); + await waitFor(() => expect(commentIn(container, GRACE_BODY)).toBeDefined()); + await act(async () => {}); + expect(moreOn(container, GRACE_BODY)).toBeNull(); + expect(moreOn(container, ADA_BODY)).not.toBeNull(); + }); + + it('not offered on a guess: an explain answer with no record verdict offers the own comments alone', async () => { + stubExplain(null); + const { container } = await openPanel(); + await showResolved(); + await waitFor(() => expect(commentIn(container, GRACE_BODY)).toBeDefined()); + await act(async () => {}); + expect(moreOn(container, GRACE_BODY)).toBeNull(); + expect(moreOn(container, ADA_BODY)).not.toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 9a86e2e3c4a..65c3be59aad 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -11,6 +11,8 @@ import { useState, useEffect, useLayoutEffect, useCallback, useContext, useMemo, useRef, type ReactElement } from 'react'; import { useParams, useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom'; import { activityRowToFeedItem, buildCommentThreads, CommentsButton, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, isRefusedFeedRead, recordPageTierHasRightColumn, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; +// objectstack#36075 — the comment panel's unresolved count and the moderator's verdict. +import { unresolvedThreadCount, useRecordVerdict } from '@object-ui/plugin-detail'; import { Empty, EmptyTitle, EmptyDescription, Button, PageHeaderActions, PageHeaderPhoneContext, PageHeaderTrailingContext, PanelToggles, ObjectIconTile, RecordHeaderBarContext, RecordHeaderStateContext, RecordTopBar, RecordTopBarButton, cn, useRecordStepKeys, type PanelToggleItem, type RecordHeaderBar, type RecordHeaderGroupParts, type RecordHeaderState, type RecordTopBarStepper } from '@object-ui/components'; import { isActingApprover } from '../utils/approvalDecisionFold.js'; import { useAuth, createAuthenticatedFetch } from '@object-ui/auth'; @@ -497,6 +499,76 @@ function mergeFeedRows(prev: readonly FeedItem[], incoming: readonly FeedItem[]) }); } +/** + * Whether a `sys_comment` row's stored `mentions` name `userId` + * (objectstack#36075, 「只看我参与的」): a JSON id list, as this page writes + * it, or a list of ids or `{ id }` objects, as #36071's `threadsInvolvingUser` + * reads it. Anything unreadable names nobody. + */ +function rowMentionsUser(raw: unknown, userId: string | undefined): boolean { + if (!userId || raw == null) return false; + let list: unknown = raw; + if (typeof raw === 'string') { + try { + list = JSON.parse(raw); + } catch { + return false; + } + } + if (!Array.isArray(list)) return false; + return list.some((entry) => + entry != null && typeof entry === 'object' + ? String((entry as { id?: unknown }).id) === userId + : String(entry) === userId, + ); +} + +/** + * The resolution of a `sys_comment` row as the feed carries it + * (objectstack#36071, #36075): `resolved` only where the row carries + * `is_resolved` (a deployment that stores none offers no resolve control), + * the resolver's id and when, and the resolver's name where this page knows + * it — the viewer, or an author of the same discussion (`namesById`). + */ +function commentResolutionOf( + row: Record, + namesById: ReadonlyMap, +): Pick { + if (row.parent_id != null && row.parent_id !== '') return {}; + if (!Object.prototype.hasOwnProperty.call(row, 'is_resolved')) return {}; + const resolved = row.is_resolved === true; + if (!resolved) return { resolved: false }; + const by = row.resolved_by; + const byId = by != null && typeof by === 'object' ? (by as { id?: unknown }).id : by; + const resolvedById = byId != null && byId !== '' ? String(byId) : undefined; + const expandedName = by != null && typeof by === 'object' ? (by as { name?: unknown }).name : undefined; + return { + resolved: true, + resolvedById, + resolvedByName: + typeof expandedName === 'string' && expandedName !== '' + ? expandedName + : resolvedById + ? namesById.get(resolvedById) + : undefined, + resolvedAt: typeof row.resolved_at === 'string' ? row.resolved_at : undefined, + }; +} + +/** The top-level comment a comment's thread is resolved on: its topmost held ancestor. */ +function threadRootIdOf(items: readonly FeedItem[], itemId: string | number): string | number { + const byId = new Map(items.map((item) => [String(item.id), item])); + let current = byId.get(String(itemId)); + const seen = new Set(); + while (current && current.parentId != null && !seen.has(String(current.id))) { + seen.add(String(current.id)); + const parent = byId.get(String(current.parentId)); + if (!parent) break; + current = parent; + } + return current ? current.id : itemId; +} + /** * The record feed's own read of the activity window (`$top: * RECORD_PAGE_ACTIVITY_ROWS`, newest first): the feed's read where the page @@ -3574,6 +3646,15 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri for (const c of res.data as Array<{ parent_id?: unknown }>) { if (c.parent_id) replyCounts.set(c.parent_id, (replyCounts.get(c.parent_id) ?? 0) + 1); } + // objectstack#36075 — a resolver this page can name: the viewer, or an + // author of this discussion (their stored `author_name`). + const namesById = new Map(); + for (const c of res.data as Array<{ author_id?: unknown; author_name?: unknown }>) { + if (c.author_id != null && typeof c.author_name === 'string' && c.author_name !== '') { + namesById.set(String(c.author_id), c.author_name); + } + } + if (currentUser.id && currentUser.name) namesById.set(String(currentUser.id), currentUser.name); const mapped: FeedItem[] = res.data.map((c: any) => ({ id: c.id, type: 'comment' as const, @@ -3591,6 +3672,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // feed never derives it. edited: c.is_edited === true, authoredByViewer: isCommentAuthor(c.author_id, currentUser.id), + // objectstack#36075 — the thread's resolution (#36071) and whether + // the row mentions the viewer (「只看我参与的」). + ...commentResolutionOf(c, namesById), + mentionsViewer: rowMentionsUser(c.mentions, currentUser.id), reactions: reactionStore === 'records' ? toReactions(records?.stored.get(String(c.id))) @@ -3786,9 +3871,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri const timelineTotal = timelineServed ? Math.max(0, timelineServed.total - timelineServed.comments + (commentsPanelOffered ? 0 : heldCommentCount)) : null; - // The comments icon's number: the record's threads (its top-level comments), - // unknown while the read was refused or failed. - const commentThreadCount = useMemo(() => buildCommentThreads(feedItems).length, [feedItems]); + // The comments icon's number: the record's unresolved threads (#36075 item + // 8; every thread where the deployment stores no resolution), unknown while + // the read was refused or failed. + const commentThreadCount = useMemo(() => unresolvedThreadCount(buildCommentThreads(feedItems)), [feedItems]); const commentsCount = feedVerdict?.comments === 'refused' || feedVerdict?.comments === 'failed' ? null : commentThreadCount; const commentsButton = commentsPanelOffered ? ( @@ -3887,8 +3973,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri const threadId = `${objectName}:${pureRecordId}`; const roster = await mentionRosterFor(text); const mentionIds = extractMentions(text, roster); + let stored: unknown; try { - await dataSource.create('sys_comment', { + stored = await dataSource.create('sys_comment', { id: newItem.id, thread_id: threadId, author_id: currentUser.id, @@ -3901,13 +3988,20 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri } catch (err) { throw commentWriteFailed(err); } + // objectstack#36075 — a new thread is unresolved (the platform says so, + // #36071): resolvable at once where the stored row, or any comment of + // this discussion, shows the deployment stores resolution. const key = feedRecordKey; + const storesResolution = + (!!stored && typeof stored === 'object' && Object.prototype.hasOwnProperty.call(stored, 'is_resolved')) + || (feedItemsByRecord[key] ?? EMPTY_FEED).some(item => typeof item.resolved === 'boolean'); + if (storesResolution) newItem.resolved = false; setFeedItemsByRecord(prev => ({ ...prev, [key]: [...(prev[key] ?? EMPTY_FEED), newItem], })); }, - [currentUser, dataSource, objectName, pureRecordId, feedRecordKey, mentionRosterFor, commentWriteFailed, tellMentionsWithheld], + [currentUser, dataSource, objectName, pureRecordId, feedRecordKey, feedItemsByRecord, mentionRosterFor, commentWriteFailed, tellMentionsWithheld], ); const handleAddReply = useCallback( @@ -3949,13 +4043,20 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri const key = feedRecordKey; setFeedItemsByRecord(prev => { const updated = [...(prev[key] ?? EMPTY_FEED), newItem]; + // objectstack#36071 — a reply into a resolved thread reopens it (the + // platform does so on the stored row); the panel shows it reopened. + const rootId = threadRootIdOf(updated, parentId); return { ...prev, - [key]: updated.map(item => - item.id === parentId + [key]: updated.map(item => { + let next = item.id === parentId ? { ...item, replyCount: (item.replyCount ?? 0) + 1 } - : item - ), + : item; + if (next.id === rootId && next.resolved === true) { + next = { ...next, resolved: false, resolvedById: undefined, resolvedByName: undefined, resolvedAt: undefined }; + } + return next; + }), }; }); }, @@ -4082,6 +4183,77 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri [dataSource, feedRecordKey, feedItemsByRecord, confirmHandler, t], ); + /** + * Resolve or reopen a thread (objectstack#36071, #36075 item 7), by its + * top-level comment: `{ is_resolved }` and nothing else, the one update + * whoever may comment on the record is admitted to (maintainer ruling + * record 7063285032). The platform stamps who and when; the row changes + * only once the server has stored it, from the stored record it answers + * with, and a refused write raises a localized error and leaves the thread + * as it was. + */ + const handleResolveComment = useCallback( + async (itemId: string | number, resolved: boolean) => { + if (!dataSource || !feedRecordKey) return; + const key = feedRecordKey; + const row = (feedItemsByRecord[key] ?? EMPTY_FEED).find(item => item.id === itemId); + if (!row || row.type !== 'comment' || row.parentId != null) return; + let stored: Record | null | undefined; + try { + stored = await dataSource.update(COMMENT_OBJECT, String(itemId), { is_resolved: resolved }); + } catch (err) { + toast.error( + t('detail.commentResolveFailed', { defaultValue: 'The thread was not updated. Please try again.' }), + ); + throw err instanceof Error ? err : new Error(String(err)); + } + // The stored row's word where it answers with one; the viewer resolved it. + const names = new Map(); + if (currentUser.id && currentUser.name) names.set(String(currentUser.id), currentUser.name); + const fromStored = + stored && typeof stored === 'object' && Object.prototype.hasOwnProperty.call(stored, 'is_resolved') + ? commentResolutionOf({ ...stored, parent_id: null }, names) + : null; + const next: Pick = fromStored + ?? (resolved + ? { + resolved: true, + resolvedById: currentUser.id ? String(currentUser.id) : undefined, + resolvedByName: currentUser.name || undefined, + resolvedAt: new Date().toISOString(), + } + : { resolved: false }); + setFeedItemsByRecord(prev => ({ + ...prev, + [key]: (prev[key] ?? EMPTY_FEED).map(item => + item.id === itemId + ? { ...item, resolved: next.resolved, resolvedById: next.resolvedById, resolvedByName: next.resolvedByName, resolvedAt: next.resolvedAt } + : item, + ), + })); + }, + [currentUser, dataSource, feedRecordKey, feedItemsByRecord, t], + ); + + // objectstack#36075 item 6 — may the viewer edit and delete OTHER people's + // comments here? The server admits a comment's author, or a caller whose + // by-id update of the record is admitted (`comment-access-hooks.ts`, + // "Parent EDIT"): the explain engine's record verdict for `update`, the + // question `recordWriteAllowed` asks. Asked three-state and offered only on + // a definite allow: failing open here would offer every member a delete of + // their colleagues' words that the server refuses. The page's own edit + // gates (approval lock, `userActions.edit`, its predicates) are not the + // server's comment rule, so they do not join. Asked once the panel is open: + // where `userActions.edit: false` keeps the page from asking it, opening the + // record still sends no explain for it (objectui#13045); elsewhere the page's + // own question answers this one from the same cache. + const moderatesComments = useRecordVerdict( + objectDef?.name, + pureRecordId, + 'update', + commentsOpen, + ) === true; + /** * A reaction click shows at once and is stored in the background, and a * reaction whose write fails does not stay shown as applied (objectui#10899, @@ -5800,6 +5972,12 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // `authoredByViewer`. onEditComment={feedGates.commentEdit ? handleEditComment : undefined} onDeleteComment={feedGates.commentDelete ? handleDeleteComment : undefined} + // objectstack#36071 / #36075 — resolve and reopen ride the comment + // grant: whoever may comment on the record may resolve its threads + // (ruling 7063285032). The panel offers it where the rows say the + // deployment stores resolution. + onResolveComment={feedsEnabled && feedGates.commentEdit ? handleResolveComment : undefined} + moderatesComments={moderatesComments} onToggleReaction={ (reactionStore === 'records' ? feedGates.reactionAdd diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 82e975292a5..3bb51ee6997 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1510,6 +1510,16 @@ const ar = { commentActions: 'إجراءات التعليق', commentsEmptyHint: 'اكتب أول تعليق أدناه. استخدم @ للإشارة إلى زميل.', resolveThread: 'وضع علامة كمحلول', + reopenThread: "إعادة الفتح", + threadResolved: "تم الحل", + threadResolvedBy: "تم الحل بواسطة {{name}}", + filterComments: "تصفية التعليقات", + showResolvedComments: "إظهار المحلولة", + commentsInvolvingMe: "التي أشارك فيها فقط", + noUnresolvedComments: "لا توجد تعليقات غير محلولة", + noCommentsInvolvingMe: "لا توجد تعليقات تشارك فيها", + showAllComments: "إظهار كل التعليقات", + commentResolveFailed: "لم يتم تحديث المناقشة. يرجى المحاولة مرة أخرى.", pinned: "مثبت", pin: "تثبيت", unpin: "إلغاء التثبيت", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 405d129dc37..fe3041d8c98 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1360,6 +1360,16 @@ const de = { commentActions: 'Kommentaraktionen', commentsEmptyHint: 'Schreiben Sie unten den ersten. Mit @ erwähnen Sie Kollegen.', resolveThread: 'Als gelöst markieren', + reopenThread: "Wieder öffnen", + threadResolved: "Gelöst", + threadResolvedBy: "Gelöst von {{name}}", + filterComments: "Kommentare filtern", + showResolvedComments: "Gelöste anzeigen", + commentsInvolvingMe: "Nur meine Unterhaltungen", + noUnresolvedComments: "Keine offenen Kommentare", + noCommentsInvolvingMe: "Keine Kommentare, an denen Sie beteiligt sind", + showAllComments: "Alle Kommentare anzeigen", + commentResolveFailed: "Die Unterhaltung wurde nicht aktualisiert. Bitte versuchen Sie es erneut.", pinned: "Angeheftet", pin: "Anheften", unpin: "Lösen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index fd734098052..beb2440c72e 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1847,6 +1847,16 @@ const en = { commentActions: 'Comment actions', commentsEmptyHint: 'Write the first one below. Use @ to mention a colleague.', resolveThread: 'Mark resolved', + reopenThread: "Reopen", + threadResolved: "Resolved", + threadResolvedBy: "Resolved by {{name}}", + filterComments: "Filter comments", + showResolvedComments: "Show resolved", + commentsInvolvingMe: "Only threads I'm in", + noUnresolvedComments: "No unresolved comments", + noCommentsInvolvingMe: "No comments you're part of", + showAllComments: "Show all comments", + commentResolveFailed: "The thread was not updated. Please try again.", pinned: 'Pinned', pin: 'Pin', unpin: 'Unpin', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 8c6f9e714a8..feeebe1adfb 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1399,6 +1399,16 @@ const es = { commentActions: 'Acciones del comentario', commentsEmptyHint: 'Escribe el primero abajo. Usa @ para mencionar a un compañero.', resolveThread: 'Marcar como resuelto', + reopenThread: "Reabrir", + threadResolved: "Resuelto", + threadResolvedBy: "Resuelto por {{name}}", + filterComments: "Filtrar comentarios", + showResolvedComments: "Mostrar resueltos", + commentsInvolvingMe: "Solo en los que participo", + noUnresolvedComments: "No hay comentarios sin resolver", + noCommentsInvolvingMe: "No hay comentarios en los que participes", + showAllComments: "Mostrar todos los comentarios", + commentResolveFailed: "No se actualizó la conversación. Inténtalo de nuevo.", pinned: "Fijado", pin: "Fijar", unpin: "Desfijar", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 810987f9e99..65398037d65 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1396,6 +1396,16 @@ const fr = { commentActions: 'Actions du commentaire', commentsEmptyHint: 'Écrivez le premier ci-dessous. Utilisez @ pour mentionner un collègue.', resolveThread: 'Marquer comme résolu', + reopenThread: "Rouvrir", + threadResolved: "Résolu", + threadResolvedBy: "Résolu par {{name}}", + filterComments: "Filtrer les commentaires", + showResolvedComments: "Afficher les résolus", + commentsInvolvingMe: "Seulement mes discussions", + noUnresolvedComments: "Aucun commentaire non résolu", + noCommentsInvolvingMe: "Aucun commentaire auquel vous participez", + showAllComments: "Afficher tous les commentaires", + commentResolveFailed: "La discussion n'a pas été mise à jour. Veuillez réessayer.", pinned: "Épinglé", pin: "Épingler", unpin: "Désépingler", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index ce3e5e5acfc..ddd7642a437 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1441,6 +1441,16 @@ const ja = { commentActions: 'コメントの操作', commentsEmptyHint: '下に最初のコメントを書きましょう。@ で同僚にメンションできます。', resolveThread: '解決済みにする', + reopenThread: "未解決に戻す", + threadResolved: "解決済み", + threadResolvedBy: "{{name}} が解決", + filterComments: "コメントを絞り込む", + showResolvedComments: "解決済みを表示", + commentsInvolvingMe: "自分が参加しているもののみ", + noUnresolvedComments: "未解決のコメントはありません", + noCommentsInvolvingMe: "参加しているコメントはありません", + showAllComments: "すべてのコメントを表示", + commentResolveFailed: "スレッドを更新できませんでした。もう一度お試しください。", pinned: "ピン留め", pin: "ピン留め", unpin: "ピン解除", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6e6d3b7a865..96a4ab51135 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1360,6 +1360,16 @@ const ko = { commentActions: '댓글 작업', commentsEmptyHint: '아래에 첫 댓글을 남겨 보세요. @로 동료를 언급할 수 있습니다.', resolveThread: '해결됨으로 표시', + reopenThread: "다시 열기", + threadResolved: "해결됨", + threadResolvedBy: "{{name}} 님이 해결함", + filterComments: "댓글 필터", + showResolvedComments: "해결된 항목 표시", + commentsInvolvingMe: "내가 참여한 항목만", + noUnresolvedComments: "해결되지 않은 댓글이 없습니다", + noCommentsInvolvingMe: "참여한 댓글이 없습니다", + showAllComments: "모든 댓글 표시", + commentResolveFailed: "스레드를 업데이트하지 못했습니다. 다시 시도해 주세요.", pinned: "고정됨", pin: "고정", unpin: "고정 해제", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 7f9a87a48ad..338b2754814 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1396,6 +1396,16 @@ const pt = { commentActions: 'Ações do comentário', commentsEmptyHint: 'Escreva o primeiro abaixo. Use @ para mencionar um colega.', resolveThread: 'Marcar como resolvido', + reopenThread: "Reabrir", + threadResolved: "Resolvido", + threadResolvedBy: "Resolvido por {{name}}", + filterComments: "Filtrar comentários", + showResolvedComments: "Mostrar resolvidos", + commentsInvolvingMe: "Só os que participo", + noUnresolvedComments: "Nenhum comentário não resolvido", + noCommentsInvolvingMe: "Nenhum comentário em que você participa", + showAllComments: "Mostrar todos os comentários", + commentResolveFailed: "A conversa não foi atualizada. Tente novamente.", pinned: "Fixado", pin: "Fixar", unpin: "Desfixar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 60b5585048d..9d429d14b56 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1534,6 +1534,16 @@ const ru = { commentActions: 'Действия с комментарием', commentsEmptyHint: 'Напишите первый комментарий ниже. Чтобы упомянуть коллегу, введите @.', resolveThread: 'Отметить как решённое', + reopenThread: "Открыть снова", + threadResolved: "Решено", + threadResolvedBy: "Решено: {{name}}", + filterComments: "Фильтр комментариев", + showResolvedComments: "Показывать решённые", + commentsInvolvingMe: "Только с моим участием", + noUnresolvedComments: "Нет нерешённых комментариев", + noCommentsInvolvingMe: "Нет комментариев с вашим участием", + showAllComments: "Показать все комментарии", + commentResolveFailed: "Обсуждение не обновлено. Попробуйте ещё раз.", pinned: "Закреплено", pin: "Закрепить", unpin: "Открепить", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 9f35690c4a3..97c6d305cbc 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1547,6 +1547,16 @@ const zh = { commentActions: '评论操作', commentsEmptyHint: '在下面写第一条,用 @ 提到同事', resolveThread: '标记已解决', + reopenThread: "恢复为未解决", + threadResolved: "已解决", + threadResolvedBy: "已由 {{name}} 解决", + filterComments: "筛选评论", + showResolvedComments: "显示已解决", + commentsInvolvingMe: "只看我参与的", + noUnresolvedComments: "没有未解决的评论", + noCommentsInvolvingMe: "没有你参与的评论", + showAllComments: "显示全部评论", + commentResolveFailed: "操作没有保存,请重试。", pinned: '已置顶', pin: '置顶', unpin: '取消置顶', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 6aedba51ed4..c7e81c89526 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1547,6 +1547,16 @@ const zhHant = { commentActions: '評論操作', commentsEmptyHint: '在下面寫第一條,用 @ 提到同事', resolveThread: '標記已解決', + reopenThread: "恢復為未解決", + threadResolved: "已解決", + threadResolvedBy: "已由 {{name}} 解決", + filterComments: "篩選評論", + showResolvedComments: "顯示已解決", + commentsInvolvingMe: "只看我參與的", + noUnresolvedComments: "沒有未解決的評論", + noCommentsInvolvingMe: "沒有你參與的評論", + showAllComments: "顯示全部評論", + commentResolveFailed: "操作沒有儲存,請重試。", pinned: '已置頂', pin: '置頂', unpin: '取消置頂', diff --git a/ui/packages/plugin-detail/README.md b/ui/packages/plugin-detail/README.md index 90105fa9b6b..8c5fe2334b2 100644 --- a/ui/packages/plugin-detail/README.md +++ b/ui/packages/plugin-detail/README.md @@ -914,9 +914,25 @@ record rather than inside 动态 (objectstack#36075). `CommentsPanel` draws 「 and ✕ at its top, the threads oldest first (a thread's replies fold to 「N 条回复」 and open in place, with a reply box under them), and the comment box docked at its foot. Each comment's actions sit in one row at its top right while -the pointer is over it (`CommentHoverActions`): Reply, an emoji, and More with -Edit and Delete on the viewer's own comments. `CommentsButton` is the header's -switch: the comments icon with the number of top-level comments. +the pointer is over it (`CommentHoverActions`): Reply, an emoji, ✓ (resolve, on +a thread's first comment) and More with Edit and Delete. Edit and Delete are +offered on the viewer's own comments, and on everyone's where the host sets +`moderatesComments` on the `DiscussionContext` (the console sets it on the +explain engine's definite allow of a by-id update of the record, the server's +rule for editing another member's comment; read it three-state with +`useRecordVerdict`). `CommentsButton` is the header's switch: the comments icon +with the number of unresolved threads. + +Resolved threads (objectstack#36071 stores them): where the rows carry a +`resolved` (`FeedItem.resolved`, set by the host from `is_resolved`), ✓ hands +`onResolveComment(id, true)`, and a resolved thread leaves the list. The filter +menu at the panel's top right holds 「显示已解决」 (a resolved thread then shows +「已由 X 解决」, and its ✓ reopens it) and 「只看我参与的」 (threads the viewer +started, replied in or is mentioned in, from `authoredByViewer` and +`mentionsViewer`). The filter is held while the panel is open and not stored. +Where the rows carry no `resolved`, there is no ✓ and no menu, and the count is +every thread. `filterCommentThreads`, `unresolvedThreadCount` and +`threadInvolvesViewer` are the rules, exported. Every part reads the record's discussion off the host's `DiscussionContext` (`useRecordComments`) and offers each write exactly where the host hands it, so diff --git a/ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx b/ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx index f8e539c689a..e9d93495018 100644 --- a/ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx @@ -26,8 +26,13 @@ export interface CommentHoverActionsProps { onReply?: () => void; /** Adds (or takes back) the viewer's reaction. */ onReact?: (emoji: string) => void; - /** Marks the thread resolved; offered only where the deployment stores it. */ + /** + * Marks the thread resolved, or reopens it when `resolved`; offered only on + * a thread's top-level comment, where the deployment stores it. + */ onResolve?: () => void; + /** The thread is resolved: the ✓ reads 「恢复」 and shows pressed. */ + resolved?: boolean; /** The author's Edit; under 更多. */ onEdit?: () => void; /** The author's Delete; under 更多, the host confirms first. */ @@ -48,6 +53,7 @@ export const CommentHoverActions: React.FC = ({ onReply, onReact, onResolve, + resolved = false, onEdit, onDelete, }) => { @@ -114,11 +120,12 @@ export const CommentHoverActions: React.FC = ({ {onResolve && ( diff --git a/ui/packages/plugin-detail/src/comments/CommentThread.tsx b/ui/packages/plugin-detail/src/comments/CommentThread.tsx index 64b8edf395e..b508a613397 100644 --- a/ui/packages/plugin-detail/src/comments/CommentThread.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentThread.tsx @@ -8,12 +8,13 @@ import * as React from 'react'; import { cn } from '@object-ui/components'; +import { Check } from 'lucide-react'; import type { FeedItem } from '@object-ui/types'; import { useDetailTranslation } from '../useDetailTranslation'; import { CommentAuthorAvatar } from '../CommentAuthorAvatar'; import { CommentComposer } from './CommentComposer'; import { CommentItem } from './CommentItem'; -import { latestRepliers, type CommentThreadData } from './commentThreads'; +import { latestRepliers, threadResolvable, threadResolved, type CommentThreadData } from './commentThreads'; import type { RecordCommentsData } from './useRecordComments'; /** @@ -27,6 +28,14 @@ export interface CommentItemActions { isRoot: boolean; onReply?: () => void; onReact?: (emoji: string) => void; + /** + * Resolves the thread, or reopens it when it is resolved (`resolved`). + * Offered on the thread's top-level comment only, where the deployment + * stores resolution (objectstack#36071). + */ + onResolve?: () => void; + /** The thread is resolved: the resolve control reads as 「恢复」. */ + resolved?: boolean; onEdit?: () => void; onDelete?: () => void; } @@ -36,7 +45,14 @@ export interface RecordCommentThreadProps { /** The writes, as `useRecordComments` hands them. */ comments: Pick< RecordCommentsData, - 'onAddReply' | 'onToggleReaction' | 'onEditComment' | 'onDeleteComment' | 'mentionSuggestions' | 'onMentionSuggestionsWanted' + | 'onAddReply' + | 'onToggleReaction' + | 'onEditComment' + | 'onDeleteComment' + | 'onResolveComment' + | 'moderates' + | 'mentionSuggestions' + | 'onMentionSuggestionsWanted' >; /** * `expand`: the replies open in place, under the comment, with the reply @@ -51,9 +67,27 @@ export interface RecordCommentThreadProps { className?: string; } -/** Whether the viewer wrote this comment: the host's verdict, never re-derived here. */ -function ownComment(item: FeedItem): boolean { - return item.type === 'comment' && item.authoredByViewer === true; +/** + * Whether the viewer may edit and delete this comment (objectstack#36075 item + * 6): their own (`authoredByViewer`, the host's verdict, never re-derived + * here), or anyone's where the host says the viewer may moderate this + * record's comments (the server admits a parent record editor). + */ +function editableComment(item: FeedItem, moderates: boolean | undefined): boolean { + return item.type === 'comment' && (item.authoredByViewer === true || moderates === true); +} + +/** + * The resolver's name: the host's, else the mention list's entry for their id + * (the people of this workspace), else none — the mark then says 「已解决」. + */ +function resolverName( + root: FeedItem, + suggestions: RecordCommentsData['mentionSuggestions'], +): string | undefined { + if (root.resolvedByName) return root.resolvedByName; + if (root.resolvedById == null) return undefined; + return suggestions?.find((s) => s.id === root.resolvedById)?.label; } /** @@ -78,7 +112,17 @@ export const CommentThread: React.FC = ({ // on an open thread still lands it there. const [replyFocus, setReplyFocus] = React.useState(0); const [editingId, setEditingId] = React.useState(null); - const { onAddReply, onToggleReaction, onEditComment, onDeleteComment } = comments; + const { onAddReply, onToggleReaction, onEditComment, onDeleteComment, onResolveComment, moderates } = comments; + const resolvable = threadResolvable(thread); + const resolved = threadResolved(thread); + const resolvedBy = resolved ? resolverName(root, comments.mentionSuggestions) : undefined; + // A resolver the host could not name is looked up in the mention list, + // which the host reads once, on demand (objectstack#28470). + const wantNames = comments.onMentionSuggestionsWanted; + const nameMissing = resolved && !resolvedBy && root.resolvedById != null; + React.useEffect(() => { + if (nameMissing) wantNames?.(); + }, [nameMissing, wantNames]); const openReply = React.useCallback(() => { if (mode === 'summary') { @@ -94,14 +138,23 @@ export const CommentThread: React.FC = ({ isRoot, onReply: onAddReply ? openReply : undefined, onReact: onToggleReaction ? (emoji: string) => void onToggleReaction(item.id, emoji) : undefined, - onEdit: onEditComment && ownComment(item) ? () => setEditingId(item.id) : undefined, - onDelete: onDeleteComment && ownComment(item) ? () => void onDeleteComment(item.id) : undefined, + onResolve: + isRoot && resolvable && onResolveComment + ? () => { + // A refused write changed nothing, and the host has said so. + void Promise.resolve(onResolveComment(item.id, !resolved)).catch(() => undefined); + } + : undefined, + resolved: isRoot && resolved, + onEdit: onEditComment && editableComment(item, moderates) ? () => setEditingId(item.id) : undefined, + onDelete: onDeleteComment && editableComment(item, moderates) ? () => void onDeleteComment(item.id) : undefined, }); - const itemOf = (item: FeedItem, isRoot: boolean, footer?: React.ReactNode) => ( + const itemOf = (item: FeedItem, isRoot: boolean, footer?: React.ReactNode, itemClassName?: string) => ( = ({ ); return ( -
- {itemOf(root, true, summary || undefined)} +
+ {resolved && ( +

+

+ )} + {itemOf(root, true, summary || undefined, resolved && !open ? 'opacity-70' : undefined)} {open && (
{replies.map((reply) => itemOf(reply, false))} diff --git a/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx b/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx new file mode 100644 index 00000000000..d1612542cdb --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx @@ -0,0 +1,213 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The comment panel's resolved threads and its filter (objectstack#36075 + * items 3, 6, 7, 8; the backend is #36071): + * + * - ✓ on a thread's top-level comment resolves it, only where the rows say + * the deployment stores resolution; a resolved thread leaves the list and + * the icon's count drops by one. + * - The filter menu: 「显示已解决」 shows them, marked with who resolved them, + * and their ✓ reopens; 「只看我参与的」 keeps the threads the viewer started, + * replied in or is mentioned in. + * - Edit and Delete on OTHER people's comments only where the host says the + * viewer may moderate this record's comments. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent, within } from '@testing-library/react'; +import { DiscussionContextProvider, type DiscussionContextValue } from '@object-ui/react'; +import type { FeedItem } from '@object-ui/types'; +import { CommentsPanel } from './CommentsPanel'; +import { useRecordComments } from './useRecordComments'; + +afterEach(() => cleanup()); + +const at = (minute: number) => new Date(Date.UTC(2026, 10, 21, 9, minute)).toISOString(); + +// t1: the viewer's, open. t2: Grace's, resolved by Ada (named by the host). +// t3: Linus's, open, the viewer replied. t4: Grace's, open, mentions the +// viewer. t5: Linus's, open, the viewer nowhere in it. +const ITEMS: FeedItem[] = [ + { id: 't1', type: 'comment', actor: 'Me', body: 'mine', createdAt: at(1), authoredByViewer: true, resolved: false }, + { + id: 't2', + type: 'comment', + actor: 'Grace', + body: 'settled one', + createdAt: at(2), + resolved: true, + resolvedById: 'u-ada', + resolvedByName: 'Ada', + }, + { id: 't3', type: 'comment', actor: 'Linus', body: 'asked by linus', createdAt: at(3), resolved: false }, + { id: 'r3', type: 'comment', actor: 'Me', body: 'my answer', createdAt: at(4), parentId: 't3', authoredByViewer: true }, + { id: 't4', type: 'comment', actor: 'Grace', body: 'hey @me', createdAt: at(5), resolved: false, mentionsViewer: true }, + { id: 't5', type: 'comment', actor: 'Linus', body: 'not about me', createdAt: at(6), resolved: false }, +]; + +function renderPanel(value: Partial = {}) { + const writes = { + onAddComment: vi.fn(), + onAddReply: vi.fn(), + onEditComment: vi.fn(), + onDeleteComment: vi.fn(), + onResolveComment: vi.fn(), + }; + render( + + + , + ); + return writes; +} + +const shownRoots = () => + Array.from(document.querySelectorAll('[data-comment-thread] > [data-comment-item]')).map((el) => + el.getAttribute('data-comment-id'), + ); +const commentEl = (id: string) => document.querySelector(`[data-comment-id="${id}"]`) as HTMLElement; +const actionIn = (id: string, action: string) => + commentEl(id).querySelector(`:scope > [data-comment-actions] [data-comment-action="${action}"]`) as HTMLElement | null; + +async function toggleFilter(name: string) { + const trigger = document.querySelector('[data-comments-filter]') as HTMLElement; + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await screen.findByRole('menuitemcheckbox', { name })); +} + +describe('CommentsPanel — resolved threads (objectstack#36075)', () => { + it('hides resolved threads by default', () => { + renderPanel(); + expect(shownRoots()).toEqual(['t1', 't3', 't4', 't5']); + }); + + it('✓ on a top-level comment resolves its thread; a reply has none', () => { + const { onResolveComment } = renderPanel(); + fireEvent.click(screen.getByRole('button', { name: /1 reply/ })); + expect(actionIn('r3', 'resolve')).toBeNull(); + fireEvent.click(actionIn('t5', 'resolve')!); + expect(onResolveComment).toHaveBeenCalledWith('t5', true); + }); + + it('「显示已解决」 shows a resolved thread with its resolver, and its ✓ reopens it', async () => { + const { onResolveComment } = renderPanel(); + await toggleFilter('Show resolved'); + expect(shownRoots()).toEqual(['t1', 't2', 't3', 't4', 't5']); + const thread = commentEl('t2').closest('[data-comment-thread]') as HTMLElement; + expect(thread).toHaveAttribute('data-comment-thread-resolved', 'true'); + expect(within(thread).getByText('Resolved by Ada')).toBeInTheDocument(); + expect(actionIn('t2', 'resolve')).toBeNull(); + const reopen = actionIn('t2', 'reopen')!; + expect(reopen).toHaveAttribute('aria-pressed', 'true'); + expect(reopen).toHaveAccessibleName('Reopen'); + fireEvent.click(reopen); + expect(onResolveComment).toHaveBeenCalledWith('t2', false); + }); + + it('「只看我参与的」 keeps the threads the viewer started, replied in or is mentioned in', async () => { + renderPanel(); + await toggleFilter("Only threads I'm in"); + expect(shownRoots()).toEqual(['t1', 't3', 't4']); + }); + + it('names a resolver the host could not from the mention list, asking for it once', async () => { + const onMentionSuggestionsWanted = vi.fn(); + const items = ITEMS.map((item) => + item.id === 't2' ? { ...item, resolvedByName: undefined, resolvedById: 'u-zoe' } : item, + ); + const { rerender } = render( + + + , + ); + await toggleFilter('Show resolved'); + const thread = () => commentEl('t2').closest('[data-comment-thread]') as HTMLElement; + expect(within(thread()).getByText('Resolved')).toBeInTheDocument(); + expect(onMentionSuggestionsWanted).toHaveBeenCalled(); + rerender( + + + , + ); + expect(within(thread()).getByText('Resolved by Zoe')).toBeInTheDocument(); + }); + + it('says so when every thread is resolved, and shows them all on request', () => { + renderPanel({ items: [ITEMS[1]] as any[] }); + expect(screen.getByText('No unresolved comments')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Show all comments' })); + expect(shownRoots()).toEqual(['t2']); + }); + + it('offers no ✓ and no filter where the deployment stores no resolution, and shows every thread', () => { + const items = ITEMS.map(({ resolved, resolvedById, resolvedByName, ...item }) => item); + renderPanel({ items: items as any[] }); + expect(document.querySelector('[data-comments-filter]')).toBeNull(); + expect(document.querySelector('[data-comment-action="resolve"]')).toBeNull(); + expect(shownRoots()).toEqual(['t1', 't2', 't3', 't4', 't5']); + }); + + it('offers no ✓ where the host hands no resolve write', () => { + renderPanel({ onResolveComment: undefined }); + expect(document.querySelector('[data-comment-action="resolve"]')).toBeNull(); + // The filter still sorts what is shown. + expect(document.querySelector('[data-comments-filter]')).not.toBeNull(); + }); +}); + +describe('CommentsPanel — Edit and Delete for people with permission (objectstack#36075 item 6)', () => { + it('a moderator gets Edit and Delete on other people’s comments', async () => { + const { onDeleteComment } = renderPanel({ moderatesComments: true }); + fireEvent.pointerDown(actionIn('t5', 'more')!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + expect(await screen.findByRole('menuitem', { name: 'Edit' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' })); + expect(onDeleteComment).toHaveBeenCalledWith('t5'); + }); + + it('CONTROL: without it, only the viewer’s own comments have More', () => { + renderPanel({ moderatesComments: false }); + expect(actionIn('t1', 'more')).not.toBeNull(); + expect(actionIn('t5', 'more')).toBeNull(); + }); + + it('moderating needs the host’s write too', () => { + renderPanel({ moderatesComments: true, onEditComment: undefined, onDeleteComment: undefined }); + expect(actionIn('t5', 'more')).toBeNull(); + }); +}); + +describe('useRecordComments — the icon’s count (objectstack#36075 item 8)', () => { + const Probe: React.FC = () => {String(useRecordComments().count)}; + it('counts the unresolved threads', () => { + render( + + + , + ); + expect(screen.getByTestId('count')).toHaveTextContent('4'); + }); + + it('counts every thread where the deployment stores no resolution', () => { + const items = ITEMS.map(({ resolved, ...item }) => item); + render( + + + , + ); + expect(screen.getByTestId('count')).toHaveTextContent('5'); + }); +}); diff --git a/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx b/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx index d8cf6a678bc..f114ec99342 100644 --- a/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx @@ -7,12 +7,20 @@ */ import * as React from 'react'; -import { Button, cn } from '@object-ui/components'; -import { Loader2, MessageSquare, X } from 'lucide-react'; +import { + Button, + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuTrigger, + cn, +} from '@object-ui/components'; +import { ListFilter, Loader2, MessageSquare, X } from 'lucide-react'; import { useDetailTranslation } from '../useDetailTranslation'; import { CommentComposer } from './CommentComposer'; import { CommentHoverActions } from './CommentHoverActions'; import { CommentThread } from './CommentThread'; +import { DEFAULT_COMMENT_THREAD_FILTER, filterCommentThreads, type CommentThreadFilter } from './commentThreads'; import { useRecordComments } from './useRecordComments'; export interface CommentsPanelProps { @@ -31,8 +39,18 @@ export interface CommentsPanelProps { export const CommentsPanel: React.FC = ({ onClose, className }) => { const { t } = useDetailTranslation(); const comments = useRecordComments(); - const { threads, loading, denied, failed, onRetry, onAddComment } = comments; + const { threads, loading, denied, failed, onRetry, onAddComment, resolvable } = comments; const title = t('detail.comments'); + // The filter menu (objectstack#36075 item 7): resolved threads hidden by + // default, 「只看我参与的」 off. Held while the panel is open, never stored. + const [filter, setFilter] = React.useState(DEFAULT_COMMENT_THREAD_FILTER); + // Where the deployment stores no resolution there is nothing to hide: the + // menu is not offered and every thread shows. + const shown = React.useMemo( + () => (resolvable ? filterCommentThreads(threads, filter) : threads), + [resolvable, threads, filter], + ); + const filtering = resolvable && (filter.onlyMine || !filter.showResolved); // The newest comment is at the foot: the list opens scrolled to it, and // follows a thread the reader (or anyone) adds. @@ -70,10 +88,31 @@ export const CommentsPanel: React.FC = ({ onClose, className {onAddComment &&

{t('detail.commentsEmptyHint')}

}
); + } else if (shown.length === 0) { + // Every thread is filtered out: say why, and offer the way back. + body = ( +
+

+ {filter.onlyMine ? t('detail.noCommentsInvolvingMe') : t('detail.noUnresolvedComments')} +

+ +
+ ); } else { body = (
- {threads.map((thread) => ( + {shown.map((thread) => ( = ({ onClose, className @@ -113,6 +154,42 @@ export const CommentsPanel: React.FC = ({ onClose, className >

{title}

+
+ {resolvable && !denied && ( + + + + + + setFilter((f) => ({ ...f, showResolved: checked === true }))} + data-comments-filter-option="show-resolved" + > + {t('detail.showResolvedComments')} + + setFilter((f) => ({ ...f, onlyMine: checked === true }))} + data-comments-filter-option="only-mine" + > + {t('detail.commentsInvolvingMe')} + + + + )} {onClose && ( )} +
{body} diff --git a/ui/packages/plugin-detail/src/comments/commentThreads.ts b/ui/packages/plugin-detail/src/comments/commentThreads.ts index c7f836c8f1a..66dfade8ad3 100644 --- a/ui/packages/plugin-detail/src/comments/commentThreads.ts +++ b/ui/packages/plugin-detail/src/comments/commentThreads.ts @@ -94,3 +94,58 @@ export function latestRepliers(replies: readonly FeedItem[], max = 3): FeedItem[ } return out; } + +/** + * Whether the thread can be resolved and reopened (objectstack#36071): its + * first comment is a real top-level comment (not a reply whose parent is gone, + * which the server refuses to resolve) and the deployment stores resolution + * (the host set `resolved`). + */ +export function threadResolvable(thread: CommentThreadData): boolean { + return thread.root.parentId == null && typeof thread.root.resolved === 'boolean'; +} + +/** Whether the thread is resolved: its top-level comment's `resolved`. */ +export function threadResolved(thread: CommentThreadData): boolean { + return threadResolvable(thread) && thread.root.resolved === true; +} + +/** + * 「只看我参与的」 (objectstack#36075 item 7): the viewer started the thread, + * replied in it, or is mentioned in it — the rule #36071's + * `threadsInvolvingUser` states for the server, read here off the host's + * viewer-relative marks (`authoredByViewer`, `mentionsViewer`). + */ +export function threadInvolvesViewer(thread: CommentThreadData): boolean { + return [thread.root, ...thread.replies].some( + (item) => item.authoredByViewer === true || item.mentionsViewer === true, + ); +} + +/** What the comment panel's filter menu holds (objectstack#36075 item 7). */ +export interface CommentThreadFilter { + /** 「显示已解决」: resolved threads are shown too. Off by default. */ + showResolved: boolean; + /** 「只看我参与的」: only the threads the viewer is in. */ + onlyMine: boolean; +} + +export const DEFAULT_COMMENT_THREAD_FILTER: CommentThreadFilter = { showResolved: false, onlyMine: false }; + +/** The threads the filter keeps, in their order. */ +export function filterCommentThreads( + threads: readonly CommentThreadData[], + filter: CommentThreadFilter, +): CommentThreadData[] { + return threads.filter( + (thread) => (filter.showResolved || !threadResolved(thread)) && (!filter.onlyMine || threadInvolvesViewer(thread)), + ); +} + +/** + * The comments icon's number (objectstack#36075 item 8): the threads not + * resolved. Where the deployment stores no resolution, every thread. + */ +export function unresolvedThreadCount(threads: readonly CommentThreadData[]): number { + return threads.filter((thread) => !threadResolved(thread)).length; +} diff --git a/ui/packages/plugin-detail/src/comments/index.ts b/ui/packages/plugin-detail/src/comments/index.ts index 3513b453faa..9722be80aa8 100644 --- a/ui/packages/plugin-detail/src/comments/index.ts +++ b/ui/packages/plugin-detail/src/comments/index.ts @@ -9,7 +9,18 @@ // objectstack#36075 — the record's comment surfaces: the parts every surface // shares (the desktop panel, the phone's comment page) and the desktop's own. export { useRecordComments, type RecordCommentsData } from './useRecordComments'; -export { buildCommentThreads, latestRepliers, type CommentThreadData } from './commentThreads'; +export { + buildCommentThreads, + latestRepliers, + threadResolvable, + threadResolved, + threadInvolvesViewer, + filterCommentThreads, + unresolvedThreadCount, + DEFAULT_COMMENT_THREAD_FILTER, + type CommentThreadData, + type CommentThreadFilter, +} from './commentThreads'; export { CommentItem, type CommentItemProps } from './CommentItem'; export { CommentThread, type RecordCommentThreadProps, type CommentItemActions } from './CommentThread'; export { CommentComposer, type CommentComposerProps } from './CommentComposer'; diff --git a/ui/packages/plugin-detail/src/comments/useRecordComments.ts b/ui/packages/plugin-detail/src/comments/useRecordComments.ts index 5511d832799..f2279126487 100644 --- a/ui/packages/plugin-detail/src/comments/useRecordComments.ts +++ b/ui/packages/plugin-detail/src/comments/useRecordComments.ts @@ -9,7 +9,7 @@ import * as React from 'react'; import { useDiscussionContext, type DiscussionMentionSuggestion } from '@object-ui/react'; import type { FeedItem } from '@object-ui/types'; -import { buildCommentThreads, type CommentThreadData } from './commentThreads'; +import { buildCommentThreads, threadResolvable, unresolvedThreadCount, type CommentThreadData } from './commentThreads'; /** * A record's discussion as the comment surfaces draw it (objectstack#36075): @@ -20,11 +20,18 @@ export interface RecordCommentsData { /** The threads, oldest first; each thread's replies oldest first. */ threads: CommentThreadData[]; /** - * The number the comments icon shows: the top-level comments. `null` while - * the first read is in flight, or when it was refused or failed — an - * unknown count is not zero. + * The number the comments icon shows: the unresolved threads (a top-level + * comment and its replies are one; objectstack#36075 item 8). Where the + * deployment stores no resolution, every thread. `null` while the first + * read is in flight, or when it was refused or failed — an unknown count is + * not zero. */ count: number | null; + /** + * Some thread here can be resolved (the deployment stores resolution): the + * panel offers its filter menu and the resolve control only then. + */ + resolvable: boolean; loading: boolean; /** The comment read was refused (the member may not read the discussion). */ denied: boolean; @@ -36,6 +43,13 @@ export interface RecordCommentsData { onToggleReaction?: (itemId: string | number, emoji: string) => void | Promise; onEditComment?: (itemId: string | number, text: string) => void | Promise; onDeleteComment?: (itemId: string | number) => void | Promise; + /** Resolve (`true`) or reopen (`false`) a thread, by its top-level comment. */ + onResolveComment?: (itemId: string | number, resolved: boolean) => void | Promise; + /** + * The viewer may edit and delete other people's comments here (the host's + * definite verdict; objectstack#36075 item 6). Their own, always. + */ + moderates?: boolean; mentionSuggestions?: DiscussionMentionSuggestion[]; onMentionSuggestionsWanted?: () => void; } @@ -56,9 +70,12 @@ export function useRecordComments(): RecordCommentsData { const denied = !!discussion?.commentsDenied; const failed = !!discussion?.commentsFailed; const onAddComment = discussion?.onAddComment; + const unresolved = React.useMemo(() => unresolvedThreadCount(threads), [threads]); + const resolvable = React.useMemo(() => threads.some(threadResolvable), [threads]); return { threads, - count: !discussion || denied || failed || (loading && threads.length === 0) ? null : threads.length, + count: !discussion || denied || failed || (loading && threads.length === 0) ? null : unresolved, + resolvable, loading, denied, failed, @@ -68,6 +85,8 @@ export function useRecordComments(): RecordCommentsData { onToggleReaction: discussion?.onToggleReaction as RecordCommentsData['onToggleReaction'], onEditComment: discussion?.onEditComment, onDeleteComment: discussion?.onDeleteComment, + onResolveComment: discussion?.onResolveComment, + moderates: discussion?.moderatesComments === true, mentionSuggestions: discussion?.mentionSuggestions, onMentionSuggestionsWanted: discussion?.onMentionSuggestionsWanted, }; diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 1ecbb776901..672051ddfc0 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -132,7 +132,7 @@ export type { } from './ConcurrentUpdateDialog'; // `__clearRecordEditableCache` is test-only and stays off the barrel // (objectui#13453); tests import it from `useRecordEditable` directly. -export { useRecordEditable, seedRecordVerdict } from './useRecordEditable'; +export { useRecordEditable, useRecordVerdict, seedRecordVerdict } from './useRecordEditable'; // objectstack#27627 — the record page payload's field projection, for the // in-place edit blocks' first ask. export { seedRecordFieldAccess } from './recordFieldAccess'; @@ -266,6 +266,12 @@ export { useRecordComments, buildCommentThreads, latestRepliers, + threadResolvable, + threadResolved, + threadInvolvesViewer, + filterCommentThreads, + unresolvedThreadCount, + DEFAULT_COMMENT_THREAD_FILTER, CommentItem, CommentThread, CommentComposer, @@ -276,6 +282,7 @@ export { export type { RecordCommentsData, CommentThreadData, + CommentThreadFilter, CommentItemProps, RecordCommentThreadProps, CommentItemActions, diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index e8c05c6caed..5d4b87decdf 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -152,6 +152,16 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.commentActions': 'Comment actions', 'detail.commentsEmptyHint': 'Write the first one below. Use @ to mention a colleague.', 'detail.resolveThread': 'Mark resolved', + 'detail.reopenThread': "Reopen", + 'detail.threadResolved': "Resolved", + 'detail.threadResolvedBy': "Resolved by {{name}}", + 'detail.filterComments': "Filter comments", + 'detail.showResolvedComments': "Show resolved", + 'detail.commentsInvolvingMe': "Only threads I'm in", + 'detail.noUnresolvedComments': "No unresolved comments", + 'detail.noCommentsInvolvingMe': "No comments you're part of", + 'detail.showAllComments': "Show all comments", + 'detail.commentResolveFailed': "The thread was not updated. Please try again.", 'detail.pinned': 'Pinned', 'detail.pin': 'Pin', 'detail.unpin': 'Unpin', diff --git a/ui/packages/plugin-detail/src/useRecordEditable.ts b/ui/packages/plugin-detail/src/useRecordEditable.ts index 935bff0e30a..cf0c5c47b6f 100644 --- a/ui/packages/plugin-detail/src/useRecordEditable.ts +++ b/ui/packages/plugin-detail/src/useRecordEditable.ts @@ -363,6 +363,30 @@ export function useRecordEditable( operation: RecordOperation = 'update', enabled = true, ): boolean { + // Fail-open: every uncertainty — not asked, not answered yet, answered + // nothing usable — reads as allowed, and the server does its job. + return useRecordVerdict(objectName, recordId, operation, enabled) ?? true; +} + +/** + * The same verdict as {@link useRecordEditable}, THREE-STATE (objectstack#36075): + * `true` or `false` once the explain engine has answered for this principal and + * record, `undefined` while it has not — not asked (`enabled` false, no + * object or record), not answered yet, or answered nothing usable (non-OK, + * no record verdict, a network failure). Same cache, same in-flight sharing, + * same staling by a data change; only the uncertainty is left to the caller. + * + * For an affordance that must not be offered on a guess: the comment panel + * offers Edit and Delete on OTHER people's comments only on a definite `true` + * (the server admits a parent record editor there), where failing open would + * invite every member to a write the server refuses. + */ +export function useRecordVerdict( + objectName: string | undefined, + recordId: string | undefined, + operation: RecordOperation = 'update', + enabled = true, +): boolean | undefined { // [objectui#5683] The acting user, or `null` when the client has no answer — // a standalone embed with no provider, an anonymous session, or a load still // in flight. `usePermissions()` degrades to the no-provider value rather than @@ -379,8 +403,8 @@ export function useRecordEditable( // record (the same match `forgetChangedRecords` drops its entries by), so a // mounted header asks again in place. const invalidationNonce = useDataInvalidation(objectName, recordId); - const [allowed, setAllowed] = React.useState(() => - key && verdictCache.has(key) ? verdictCache.get(key)! : true, + const [verdict, setVerdict] = React.useState(() => + key && verdictCache.has(key) ? verdictCache.get(key)! : undefined, ); // Read the context directly (not `useSchemaContext`, which throws when no // provider is mounted): a standalone `detail:view` embed has no host fetch @@ -390,31 +414,30 @@ export function useRecordEditable( React.useEffect(() => { retainForPrincipal(principal); if (!enabled || !objectName || !recordId) { - setAllowed(true); + setVerdict(undefined); return; } if (verdictCache.has(key)) { - setAllowed(verdictCache.get(key)!); + setVerdict(verdictCache.get(key)!); return; } // No answer for THIS key yet. Whatever is on screen was computed for a // different key — another record, another operation, or (objectui#10107) // another principal — or for this key before the record changed // (objectui#10184), and holding it across the round trip is the same - // reuse the cache now forbids, just without the map. An unanswered - // question fails open, as every other uncertainty in this hook does. - setAllowed(true); + // reuse the cache now forbids, just without the map. Unanswered. + setVerdict(undefined); let cancelled = false; // Asked once per key however many mounts ask it at once (objectui#11699). - void askVerdict(key, objectName, recordId, operation, apiFetch).then((verdict) => { - if (verdict !== undefined && !cancelled) setAllowed(verdict); + void askVerdict(key, objectName, recordId, operation, apiFetch).then((answer) => { + if (answer !== undefined && !cancelled) setVerdict(answer); }); return () => { cancelled = true; }; }, [key, principal, objectName, recordId, operation, enabled, apiFetch, invalidationNonce]); - return allowed; + return verdict; } /** diff --git a/ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx b/ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx new file mode 100644 index 00000000000..78f922d28b1 --- /dev/null +++ b/ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx @@ -0,0 +1,84 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36075 item 6 — `useRecordVerdict`, the three-state reading of + * the same explain verdict `useRecordEditable` fails open on. The comment + * panel offers Edit and Delete on other people's comments only on a definite + * `true`, so every uncertainty must read `undefined`, never `true`; and + * `useRecordEditable` must read exactly as before. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { renderHook, waitFor } from '@testing-library/react'; +import { useRecordEditable, useRecordVerdict, __clearRecordEditableCache } from './useRecordEditable'; + +function mockExplain(body: unknown, ok = true) { + return vi.fn(async () => ({ ok, json: async () => body })) as any; +} + +describe('useRecordVerdict (objectstack#36075)', () => { + beforeEach(() => __clearRecordEditableCache()); + afterEach(() => vi.unstubAllGlobals()); + + it('reads true on an allow and false on a refusal', async () => { + vi.stubGlobal('fetch', mockExplain({ allowed: true, record: { recordId: 'r1', visible: true } })); + const allowed = renderHook(() => useRecordVerdict('note', 'r1')); + await waitFor(() => expect(allowed.result.current).toBe(true)); + __clearRecordEditableCache(); + vi.stubGlobal('fetch', mockExplain({ allowed: true, record: { recordId: 'r2', visible: false } })); + const refused = renderHook(() => useRecordVerdict('note', 'r2')); + await waitFor(() => expect(refused.result.current).toBe(false)); + }); + + it('reads undefined, never true, while unanswered and on every uncertainty', async () => { + let answer: (value: unknown) => void = () => {}; + vi.stubGlobal('fetch', vi.fn(() => new Promise((resolve) => { answer = resolve; })) as any); + const pending = renderHook(() => useRecordVerdict('note', 'r1')); + expect(pending.result.current).toBeUndefined(); + answer({ ok: false, json: async () => ({}) }); + await new Promise((r) => setTimeout(r, 0)); + expect(pending.result.current).toBeUndefined(); + + __clearRecordEditableCache(); + vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }) as any); + const offline = renderHook(() => useRecordVerdict('note', 'r3')); + await new Promise((r) => setTimeout(r, 0)); + expect(offline.result.current).toBeUndefined(); + + __clearRecordEditableCache(); + vi.stubGlobal('fetch', mockExplain({ allowed: false })); + const noRecordVerdict = renderHook(() => useRecordVerdict('note', 'r4')); + await new Promise((r) => setTimeout(r, 0)); + expect(noRecordVerdict.result.current).toBeUndefined(); + }); + + it('asks nothing and reads undefined when not enabled', () => { + const fetchMock = mockExplain({ allowed: true, record: { recordId: 'r1', visible: true } }); + vi.stubGlobal('fetch', fetchMock); + const { result } = renderHook(() => useRecordVerdict('note', 'r1', 'update', false)); + expect(result.current).toBeUndefined(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('CONTROL: useRecordEditable still fails open on the same uncertainty', async () => { + vi.stubGlobal('fetch', mockExplain({}, false)); + const { result } = renderHook(() => useRecordEditable('note', 'r1')); + await new Promise((r) => setTimeout(r, 0)); + expect(result.current).toBe(true); + }); + + it('shares one question with useRecordEditable', async () => { + const fetchMock = mockExplain({ allowed: true, record: { recordId: 'r1', visible: false } }); + vi.stubGlobal('fetch', fetchMock); + const verdict = renderHook(() => useRecordVerdict('note', 'r1')); + const editable = renderHook(() => useRecordEditable('note', 'r1')); + await waitFor(() => expect(verdict.result.current).toBe(false)); + await waitFor(() => expect(editable.result.current).toBe(false)); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ui/packages/react/src/context/DiscussionContext.tsx b/ui/packages/react/src/context/DiscussionContext.tsx index 9703364a1c2..3a3c43b2eda 100644 --- a/ui/packages/react/src/context/DiscussionContext.tsx +++ b/ui/packages/react/src/context/DiscussionContext.tsx @@ -60,6 +60,22 @@ export interface DiscussionContextValue { * nothing was deleted. */ onDeleteComment?: (itemId: string | number) => void | Promise; + /** + * Resolve (`true`) or reopen (`false`) the thread of a top-level comment + * (objectstack#36071, #36075). Offered to whoever may comment on the record + * (maintainer ruling record 7063285032); the comment panel draws it on the + * rows whose `resolved` the host set. A rejection means nothing changed. + */ + onResolveComment?: (itemId: string | number, resolved: boolean) => void | Promise; + /** + * The viewer may edit and delete OTHER people's comments on this record + * (objectstack#36075 item 6): the server admits a comment's author or a user + * whose by-id update of the record is admitted. `true` only on a definite + * allow; absent or `false`, the panel offers Edit and Delete on the viewer's + * own comments alone. The handlers still come from `onEditComment` / + * `onDeleteComment`. + */ + moderatesComments?: boolean; /** Optional list of users (or any mentionable entities) the comment * input can suggest after the user types `@`. When omitted the input * falls back to free-text @-mentions without autocompletion. */ @@ -124,6 +140,8 @@ export const DiscussionContextProvider: React.FC value.onToggleReaction, value.onEditComment, value.onDeleteComment, + value.onResolveComment, + value.moderatesComments, value.mentionSuggestions, value.onMentionSuggestionsWanted, value.onUploadAttachments, diff --git a/ui/packages/types/src/views.ts b/ui/packages/types/src/views.ts index 33b6b93a9ee..40877e93216 100644 --- a/ui/packages/types/src/views.ts +++ b/ui/packages/types/src/views.ts @@ -579,6 +579,28 @@ export interface FeedItem { * `Reaction.reacted`. */ authoredByViewer?: boolean; + /** + * Whether this top-level comment's thread is resolved (objectstack#36071, + * #36075): the row's `is_resolved`. `undefined` where the deployment stores + * no resolution (the row carries no `is_resolved`), so a surface offers no + * resolve control there. Meaningless on a reply. + */ + resolved?: boolean; + /** Who resolved the thread: the row's `resolved_by` user id. */ + resolvedById?: string; + /** + * The resolver's display name, where the host knows it (the viewer, or an + * author in the same discussion); a surface may look it up elsewhere. + */ + resolvedByName?: string; + /** When the thread was resolved (ISO 8601): the row's `resolved_at`. */ + resolvedAt?: string; + /** + * Whether the item's stored `mentions` name the signed-in viewer. Set by the + * host, relative to the viewer like `authoredByViewer`; the comment panel's + * 「只看我参与的」 reads it (objectstack#36075). + */ + mentionsViewer?: boolean; /** * Source rich-entity pointer (ADR-0052 ActivityPointer). When the activity * was derived from a separate record — an email in `sys_email`, a call/meeting From 9d503c614ec17c293a42dac946e3b781c348b9bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:57:44 +0000 Subject: [PATCH 2/3] test(plugin-form): enter handleResolveComment in the affordance grant census (#36075) Resolve / reopen is a by-id update of the root sys_comment row, offered behind the same feedCommentEdit row as Edit. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgT8AtWDue4oTFNAE6H --- ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx index 500efd81612..d99a153f763 100644 --- a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx +++ b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx @@ -709,6 +709,10 @@ const WRITE_SITES: Record = { mapped(['feedComment'], RECORD_PAGE), 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleEditComment :: update': mapped(['feedCommentEdit'], RECORD_PAGE), + // Resolve / reopen a thread (objectstack#36075) is a by-id update of the + // root `sys_comment` row, offered behind the same row as Edit. + 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleResolveComment :: update': + mapped(['feedCommentEdit'], RECORD_PAGE), 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleDeleteComment :: delete': mapped(['feedCommentDelete'], RECORD_PAGE), 'packages/app-shell/src/views/RecordDetailView.tsx :: RecordDetailView > handleToggleReaction :: update': From 59833c2b83fd2ff199d38040cdc9be377e33795c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 20:08:39 +0000 Subject: [PATCH 3/3] =?UTF-8?q?fix(record-page):=20offer=20=E2=9C=93=20and?= =?UTF-8?q?=20Edit=20on=20others'=20comments=20only=20where=20the=20server?= =?UTF-8?q?=20admits=20them=20(#36075)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The platform's row floor lets a rank-and-file member update only the rows they created, before the comment rules run, so a member's ✓ on a colleague's thread and a record editor's Edit of a colleague's comment were refused (measured 403 on the dev rig). The panel now asks the explain engine once, on the first top-level comment the viewer did not write, when the reader first reaches into the open panel; ✓ and Edit on others' rows need its definite allow (new DiscussionContext.updatesOthersComments). Delete keeps its own gate. Also from the declaration review: the moderation verdict needs `allowed` beside `record.visible` (S3); a resolver the page cannot name is read by id from sys_user instead of the capped mention list (S2); prose says the gate the code uses (S1); a page case pins the gates apart (N3). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgT8AtWDue4oTFNAE6H --- .changeset/36075-comments-resolved.md | 11 +- .../docs/frontend/plugins/plugin-detail.mdx | 12 +- ...DetailView.commentsResolved-36075.test.tsx | 130 ++++++++++++++++-- .../app-shell/src/views/RecordDetailView.tsx | 96 ++++++++++++- .../src/views/recordCommentsPanel.tsx | 18 ++- ui/packages/plugin-detail/README.md | 13 +- .../src/comments/CommentThread.tsx | 47 ++++--- .../CommentsPanel.resolved-36075.test.tsx | 43 +++++- .../src/comments/useRecordComments.ts | 7 + .../plugin-detail/src/useRecordEditable.ts | 15 +- .../src/useRecordVerdict-36075.test.tsx | 14 ++ .../react/src/context/DiscussionContext.tsx | 17 ++- 12 files changed, 362 insertions(+), 61 deletions(-) diff --git a/.changeset/36075-comments-resolved.md b/.changeset/36075-comments-resolved.md index de0427e622c..011a13c6a40 100644 --- a/.changeset/36075-comments-resolved.md +++ b/.changeset/36075-comments-resolved.md @@ -6,17 +6,18 @@ '@object-ui/i18n': patch --- -feat(record-page): the desktop comment panel resolves and reopens threads, filters them, counts the unresolved ones, and offers Edit and Delete on other people's comments to a member who may edit the record +feat(record-page): the desktop comment panel resolves and reopens threads, filters them, counts the unresolved ones, and offers Edit and Delete on other people's comments only where the server admits them -Clause-②: yes (widening) — `@object-ui/react`'s `DiscussionContextValue` adds two optional members: `onResolveComment(itemId, resolved)` and `moderatesComments`. `@object-ui/types`' `FeedItem` adds five optional members: `resolved`, `resolvedById`, `resolvedByName`, `resolvedAt`, `mentionsViewer`. `@object-ui/plugin-detail` adds exports `useRecordVerdict` (the three-state verdict `useRecordEditable` fails open on; `useRecordEditable` reads exactly as before), `threadResolvable`, `threadResolved`, `threadInvolvesViewer`, `filterCommentThreads`, `unresolvedThreadCount`, `DEFAULT_COMMENT_THREAD_FILTER` and the type `CommentThreadFilter`; `RecordCommentsData` adds `resolvable`, `onResolveComment` and `moderates`, and its `count` is now the unresolved threads; `CommentItemActions` adds `onResolve` and `resolved`; `CommentHoverActionsProps` adds `resolved`; `RecordCommentThreadProps['comments']` may carry `onResolveComment` and `moderates`. `@object-ui/i18n` adds ten keys to every pack: `detail.reopenThread`, `detail.threadResolved`, `detail.threadResolvedBy`, `detail.filterComments`, `detail.showResolvedComments`, `detail.commentsInvolvingMe`, `detail.noUnresolvedComments`, `detail.noCommentsInvolvingMe`, `detail.showAllComments`, `detail.commentResolveFailed`. Nothing existing is removed or re-typed. +Clause-②: yes (widening) — `@object-ui/react`'s `DiscussionContextValue` adds three optional members: `onResolveComment(itemId, resolved)`, `moderatesComments` and `updatesOthersComments`. `@object-ui/types`' `FeedItem` adds five optional members: `resolved`, `resolvedById`, `resolvedByName`, `resolvedAt`, `mentionsViewer`. `@object-ui/plugin-detail` adds exports `useRecordVerdict` (the three-state verdict `useRecordEditable` fails open on; a definite allow is the explain answer's `allowed` together with its `record.visible`, as the server admits a by-id write, so `useRecordEditable` reads as before except that an answer whose `allowed` is false beside a visible record, such as an on-behalf-of session whose delegator is gone, now reads not editable), `threadResolvable`, `threadResolved`, `threadInvolvesViewer`, `filterCommentThreads`, `unresolvedThreadCount`, `DEFAULT_COMMENT_THREAD_FILTER` and the type `CommentThreadFilter`; `RecordCommentsData` adds `resolvable`, `onResolveComment`, `moderates` and `updatesOthers`, and its `count` is now the unresolved threads; `CommentItemActions` adds `onResolve` and `resolved`; `CommentHoverActionsProps` adds `resolved`; `RecordCommentThreadProps['comments']` may carry `onResolveComment`, `moderates` and `updatesOthers`. `@object-ui/i18n` adds ten keys to every pack: `detail.reopenThread`, `detail.threadResolved`, `detail.threadResolvedBy`, `detail.filterComments`, `detail.showResolvedComments`, `detail.commentsInvolvingMe`, `detail.noUnresolvedComments`, `detail.noCommentsInvolvingMe`, `detail.showAllComments`, `detail.commentResolveFailed`. Nothing existing is removed or re-typed. Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches the console's comment panel; `content/docs/frontend/plugins/plugin-detail.mdx` and the plugin-detail README gain resolved threads, the filter and the moderator's Edit and Delete in this change. The desktop record page's comment panel (objectstack#36075) gains the resolved threads #36071 stores: -- ✓ in a thread's first comment's action row marks the thread resolved: it leaves the list and the comments icon's number, now the unresolved threads, drops by one. Anyone who may comment on the record may resolve (maintainer ruling 7063285032). +- ✓ in a thread's first comment's action row marks the thread resolved: it leaves the list and the comments icon's number, now the unresolved threads, drops by one. ✓ is offered under the `sys_comment` update grant: on a thread the viewer started, and on anyone's only where the explain engine admits the viewer's update of a comment they did not write. Today the platform's row floor admits that for administrators, not for rank-and-file members, so a member resolves only the threads they started until the server carries ruling 7063285032 (any reader of the record may resolve) past that floor. - The filter menu at the panel's top right holds 「显示已解决」, which shows resolved threads marked 「已由 X 解决」 (their ✓ reopens them), and 「只看我参与的」, the threads the viewer started, replied in or is mentioned in. The filter is not stored. With every thread resolved, the panel says so and offers to show them all. - A reply into a resolved thread shows the thread reopened, as the platform stores it. -- Edit and Delete under More are offered on other members' comments to a member the explain engine admits to update the record by id, the server's own rule for editing someone else's comment; only on a definite allow, so a member is never offered a write the server refuses. Their own comments keep them as before. +- The resolver is named from the people the page already knows (the viewer and the discussion's authors); any other resolver is named by one `sys_user` read of exactly those ids, after the discussion is drawn. Where that read is refused, the mark reads 「已解决」. +- Edit and Delete under More are offered on other members' comments to a viewer the explain engine admits to update the record by id, the server's rule for moderating someone else's comment; Edit also needs the explain engine to admit their update of a comment they did not write (the row floor above). Both are asked only on a definite allow: pending, a refusal, an error or a deployment without the explain service offers them on the viewer's own comments alone. Their own comments keep them as before. -Unchanged: no server permission changes; a deployment whose comment rows carry no `is_resolved` shows no ✓ and no filter, and the icon counts every thread; hand-written record pages and the phone keep their feed as before. +Unchanged: no server permission changes (a deployment without the explain service shows ✓ and Edit on the viewer's own rows only, administrators included); a deployment whose comment rows carry no `is_resolved` shows no ✓ and no filter, and the icon counts every thread; hand-written record pages and the phone keep their feed as before. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index 0dc10ae8822..aa3328ff247 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -210,10 +210,14 @@ the record drawer), and no longer inside the 动态 (Activity) tab first, the comment box at the foot. A thread's replies fold to 「N 条回复」 and open in place. A comment's actions (Reply, an emoji, ✓ on a thread's first comment, and More with Edit and Delete) appear at its top right while - the pointer is over it. Edit and Delete are on your own comments, and on - everyone's for a member who may edit the record (the server lets them). -- **Resolved threads**: ✓ marks a thread resolved (anyone who may comment on - the record may) and it leaves the list; the icon's number drops by one. The + the pointer is over it. Edit and Delete are on your own comments. On other + people's they appear only where the server would accept them: Delete for a + member who may edit the record, Edit when the server also lets you change a + comment you did not write (today, administrators). +- **Resolved threads**: ✓ marks a thread resolved and it leaves the list; the + icon's number drops by one. It is on the threads you started, and on other + people's only where the server would accept it: today administrators, since + the platform lets a member change only the rows they wrote. The filter menu at the panel's top right holds 「显示已解决」, which shows resolved threads marked with who resolved them (their ✓ reopens them), and 「只看我参与的」, the threads you started, replied in or are mentioned in. A diff --git a/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx index e641112828a..7fc6cd0b7e4 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.commentsResolved-36075.test.tsx @@ -120,10 +120,11 @@ const AUTHORED_PAGE = { ], }; -function makeDataSource() { +function makeDataSource(rows: ReadonlyArray> = ROWS, users: ReadonlyArray> = []) { return { find: vi.fn(async (objectName: string) => { - if (objectName === 'sys_comment') return { data: ROWS.map((r) => ({ ...r })) }; + if (objectName === 'sys_comment') return { data: rows.map((r) => ({ ...r })) }; + if (objectName === 'sys_user') return { data: users.map((u) => ({ ...u })) }; return { data: [] }; }), findOne: vi.fn(async (_o: string, id: string) => ({ id, subject: `Case ${id}` })), @@ -170,10 +171,12 @@ interface MountOptions { objectName?: string; pages?: unknown[]; embedded?: boolean; + rows?: ReadonlyArray>; + users?: ReadonlyArray>; } -async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false }: MountOptions = {}) { - const dataSource = makeDataSource(); +async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false, rows, users }: MountOptions = {}) { + const dataSource = makeDataSource(rows, users); const rendered = render( @@ -202,19 +205,30 @@ const panel = (root: HTMLElement) => root.querySelector('[data-comments-panel]') const placement = (root: HTMLElement) => root.querySelector('[data-comments-placement]')?.getAttribute('data-comments-placement') ?? null; -/** The explain engine's answer to every `POST /security/explain`: `verdict` true, false, or none. */ -function stubExplain(verdict: boolean | null) { +/** + * The explain engine's answer to every `POST /security/explain`: true, false, + * or none (`null`): `verdict` for the record, `commentVerdict` for a + * `sys_comment` row (the row floor on a comment the viewer did not write). + */ +function stubExplain(verdict: boolean | null, commentVerdict: boolean | null = verdict) { vi.stubGlobal( 'fetch', - vi.fn(async (url: unknown) => { + vi.fn(async (url: unknown, init?: { body?: unknown }) => { + let asked: { object?: string; recordId?: string } = {}; + try { asked = JSON.parse(String(init?.body ?? '{}')); } catch { /* not a JSON body */ } + const answer = asked.object === 'sys_comment' ? commentVerdict : verdict; const body = - String(url).includes('/security/explain') && verdict !== null - ? { allowed: true, record: { recordId: RECORD_ID, visible: verdict } } + String(url).includes('/security/explain') && answer !== null + ? { allowed: true, record: { recordId: asked.recordId ?? RECORD_ID, visible: answer } } : { data: [] }; return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); }), ); } +const explainAsked = () => + ((globalThis.fetch as any).mock.calls as Array<[unknown, { body?: unknown }?]>) + .filter(([url]) => String(url).includes('/security/explain')) + .map(([, init]) => JSON.parse(String(init?.body ?? '{}'))); function setWindowWidth(width: number) { Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width }); @@ -242,11 +256,15 @@ const commentIn = (root: HTMLElement, text: string) => el.querySelector(':scope > .pl-7 [data-comment-body]')?.textContent?.includes(text), ) as HTMLElement | undefined; +/** The reader reaches into the open panel: the pointer enters it. */ +const engage = (root: HTMLElement) => fireEvent.pointerEnter(root.querySelector('[data-comments-placement]')!); + async function openPanel() { const mounted = await mount(); await waitFor(() => expect(button(mounted.container)).not.toBeNull()); fireEvent.click(button(mounted.container)!); await within(panel(mounted.container)!).findByText(ADA_BODY); + engage(mounted.container); return mounted; } @@ -268,6 +286,27 @@ describe('resolved threads in the record comment panel (objectstack#36075)', () expect(p.getByText('Resolved by Linus')).toBeInTheDocument(); }); + it('a resolver the page cannot name is read by id, once, and named', async () => { + const rows = ROWS.map((r) => (r.id === 'c-grace' ? { ...r, resolved_by: 'u-zoe' } : r)); + const { container, dataSource } = await mount({ rows, users: [{ id: 'u-zoe', name: 'Zoe' }] }); + await waitFor(() => expect(button(container)).not.toBeNull()); + fireEvent.click(button(container)!); + await within(panel(container)!).findByText(ADA_BODY); + await showResolved(); + expect(await within(panel(container)!).findByText('Resolved by Zoe')).toBeInTheDocument(); + const userReads = dataSource.find.mock.calls.filter(([o]: [string]) => o === 'sys_user'); + expect(userReads).toEqual([ + ['sys_user', { $filter: { id: { $in: ['u-zoe'] } }, $top: 1, $select: ['id', 'name'] }], + ]); + }); + + it('reads no user when every resolver is named on the page', async () => { + const { container, dataSource } = await openPanel(); + await showResolved(); + expect(await within(panel(container)!).findByText('Resolved by Linus')).toBeInTheDocument(); + expect(dataSource.find.mock.calls.some(([o]: [string]) => o === 'sys_user')).toBe(false); + }); + it('✓ writes is_resolved alone on the top-level comment; the thread leaves and the count drops', async () => { const { container, dataSource } = await openPanel(); await waitFor(() => expect(count(container)).toBe('1')); @@ -296,9 +335,14 @@ describe('resolved threads in the record comment panel (objectstack#36075)', () }); it('the reopen ✓ writes is_resolved false and the thread counts again', async () => { + stubExplain(null, true); const { container, dataSource } = await openPanel(); await showResolved(); - const grace = await waitFor(() => commentIn(container, GRACE_BODY)!); + const grace = await waitFor(() => { + const el = commentIn(container, GRACE_BODY)!; + expect(el.querySelector('[data-comment-action="reopen"]')).not.toBeNull(); + return el; + }); await act(async () => { fireEvent.click(grace.querySelector('[data-comment-action="reopen"]')!); }); @@ -349,6 +393,72 @@ describe("Edit and Delete on another member's comment (objectstack#36075 item 6) expect(moreOn(container, ADA_BODY)).not.toBeNull(); }); + it('the resolve control rides its own gate: ✓ on another member\'s thread beside a moderation refusal', async () => { + stubExplain(false, true); + const { container } = await openPanel(); + await showResolved(); + await waitFor(() => + expect(commentIn(container, GRACE_BODY)!.querySelector('[data-comment-action="reopen"]')).not.toBeNull(), + ); + expect(moreOn(container, GRACE_BODY)).toBeNull(); + }); +}); + +describe("the row floor on another member's comment (objectstack#36075)", () => { + const moreOn = (root: HTMLElement, text: string) => commentIn(root, text)?.querySelector(':scope > [data-comment-actions] [data-comment-action="more"]') ?? null; + const reopenOn = (root: HTMLElement, text: string) => commentIn(root, text)?.querySelector('[data-comment-action="reopen"]') ?? null; + + it('asks ONE explain of a top-level comment the viewer did not write, once the reader reaches into the open panel', async () => { + stubExplain(true); + const mounted = await mount(); + await waitFor(() => expect(button(mounted.container)).not.toBeNull()); + expect(explainAsked().filter((q) => q.object === 'sys_comment')).toEqual([]); + fireEvent.click(button(mounted.container)!); + await within(panel(mounted.container)!).findByText(ADA_BODY); + // Opening the panel asks nothing (objectstack#28470). + await act(async () => {}); + expect(explainAsked().filter((q) => q.object === 'sys_comment')).toEqual([]); + engage(mounted.container); + // Twice in, still one question. + engage(mounted.container); + await waitFor(() => + expect(explainAsked().filter((q) => q.object === 'sys_comment')).toEqual([ + expect.objectContaining({ object: 'sys_comment', operation: 'update', recordId: 'c-grace' }), + ]), + ); + }); + + it('refused: no ✓ and no Edit on another member\'s rows, Delete still where the viewer moderates, own rows unchanged', async () => { + stubExplain(true, false); + const { container } = await openPanel(); + await showResolved(); + await waitFor(() => expect(moreOn(container, GRACE_BODY)).not.toBeNull()); + expect(reopenOn(container, GRACE_BODY)).toBeNull(); + fireEvent.pointerDown(moreOn(container, GRACE_BODY)!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + expect(await within(document.body).findByRole('menuitem', { name: 'Delete' })).toBeInTheDocument(); + expect(within(document.body).queryByRole('menuitem', { name: 'Edit' })).toBeNull(); + expect(commentIn(container, ADA_BODY)!.querySelector('[data-comment-action="resolve"]')).not.toBeNull(); + }); + + it('admitted: ✓ and Edit on another member\'s rows', async () => { + stubExplain(true, true); + const { container } = await openPanel(); + await showResolved(); + await waitFor(() => expect(reopenOn(container, GRACE_BODY)).not.toBeNull()); + fireEvent.pointerDown(moreOn(container, GRACE_BODY)!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + expect(await within(document.body).findByRole('menuitem', { name: 'Edit' })).toBeInTheDocument(); + }); + + it('not on a guess: no answer offers ✓ on the viewer\'s own threads alone', async () => { + stubExplain(null); + const { container } = await openPanel(); + await showResolved(); + await waitFor(() => expect(commentIn(container, GRACE_BODY)).toBeDefined()); + await act(async () => {}); + expect(reopenOn(container, GRACE_BODY)).toBeNull(); + expect(commentIn(container, ADA_BODY)!.querySelector('[data-comment-action="resolve"]')).not.toBeNull(); + }); + it('not offered on a guess: an explain answer with no record verdict offers the own comments alone', async () => { stubExplain(null); const { container } = await openPanel(); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 65c3be59aad..d6252cdb856 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -1069,6 +1069,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // The discussion feed, stored PER RECORD (objectui#3268). See the // `feedRecordKey` block below for why this is a map and not a `FeedItem[]`. const [feedItemsByRecord, setFeedItemsByRecord] = useState>({}); + // objectstack#36075 — resolver names this page read by id (`sys_user`), + // and the ids it asked for, so a re-read of the discussion asks no user twice. + const resolverNamesRef = useRef>(new Map()); + const resolverIdsAskedRef = useRef>(new Set()); // How each feed read ended (refused, objectui#11195; failed, // objectstack#29188), stored under the same per-record key as the rows, so a // refusal or a failure on record A never reaches record B's panel. @@ -3655,6 +3659,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri } } if (currentUser.id && currentUser.name) namesById.set(String(currentUser.id), currentUser.name); + for (const [id, name] of resolverNamesRef.current) if (!namesById.has(id)) namesById.set(id, name); const mapped: FeedItem[] = res.data.map((c: any) => ({ id: c.id, type: 'comment' as const, @@ -3690,6 +3695,48 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ...prev, [threadId]: mergeFeedRows(prev[threadId] ?? EMPTY_FEED, mapped), })); + // objectstack#36075 — a resolver the page cannot name (neither the + // viewer nor an author here) is read by id: ONE `sys_user` read of + // exactly those ids, after the discussion is drawn, so it never waits + // on it. A refused or failed read leaves the mark at 「已解决」. + const unnamedResolvers = Array.from(new Set( + mapped + .filter((item) => item.resolved === true && !item.resolvedByName && item.resolvedById != null) + .map((item) => String(item.resolvedById)) + .filter((id) => !resolverIdsAskedRef.current.has(id)), + )); + if (unnamedResolvers.length > 0) { + for (const id of unnamedResolvers) resolverIdsAskedRef.current.add(id); + void Promise.resolve(dataSource.find('sys_user', { + $filter: { id: { $in: unnamedResolvers } }, + $top: unnamedResolvers.length, + $select: ['id', 'name'], + })) + .then((usersRes: any) => { + const users: any[] = Array.isArray(usersRes) ? usersRes : usersRes?.data || []; + const names = new Map(); + for (const u of users) { + if (u?.id != null && typeof u.name === 'string' && u.name !== '') names.set(String(u.id), u.name); + } + for (const [id, name] of names) resolverNamesRef.current.set(id, name); + if (names.size === 0) return; + setFeedItemsByRecord(prev => { + const held = prev[threadId]; + if (!held) return prev; + let named = false; + const next = held.map((item) => { + const name = item.resolved === true && !item.resolvedByName && item.resolvedById != null + ? names.get(String(item.resolvedById)) + : undefined; + if (!name) return item; + named = true; + return { ...item, resolvedByName: name }; + }); + return named ? { ...prev, [threadId]: next } : prev; + }); + }) + .catch(() => undefined); + } }) // A refused comment read is the same panel's other half (objectui#11195): // the panel says the member may not see the comments, instead of "No @@ -4254,6 +4301,37 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri commentsOpen, ) === true; + // objectstack#36075 — may the viewer update a comment they did NOT write? + // The platform's row floor (`owner_only_writes`) lets a rank-and-file member + // update only the rows they created, and it runs before the comment rules + // (the resolve rule of #36104 and the parent-editor rule above), so today a + // member's ✓ on a colleague's thread and Edit of a colleague's comment are + // refused. The explain engine answers the floor: ONE probe, `update` of the + // first top-level comment here the viewer did not write; the floor answers + // the same for every such row. ✓ and Edit on others' rows are offered only + // on its definite allow (pending, a refusal, an error, no explain service, + // or a stale answer offer them on the viewer's own rows alone). Asked when + // the reader first reaches into the open panel (pointer or focus), so + // opening the record, and opening the panel, still read nothing more + // (objectstack#28470, objectui#13045). + const [commentsEngagedFor, setCommentsEngagedFor] = useState(null); + const engageComments = useCallback(() => { + if (feedRecordKey) setCommentsEngagedFor((prev) => (prev === feedRecordKey ? prev : feedRecordKey)); + }, [feedRecordKey]); + const commentsEngaged = feedRecordKey != null && commentsEngagedFor === feedRecordKey; + const foreignRootCommentId = useMemo(() => { + const root = feedItems.find( + (item) => item.type === 'comment' && item.parentId == null && item.authoredByViewer !== true, + ); + return root ? String(root.id) : undefined; + }, [feedItems]); + const updatesOthersComments = useRecordVerdict( + COMMENT_OBJECT, + foreignRootCommentId, + 'update', + commentsOpen && commentsEngaged && foreignRootCommentId != null, + ) === true; + /** * A reaction click shows at once and is stored in the background, and a * reaction whose write fails does not stay shown as applied (objectui#10899, @@ -5972,12 +6050,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // `authoredByViewer`. onEditComment={feedGates.commentEdit ? handleEditComment : undefined} onDeleteComment={feedGates.commentDelete ? handleDeleteComment : undefined} - // objectstack#36071 / #36075 — resolve and reopen ride the comment - // grant: whoever may comment on the record may resolve its threads - // (ruling 7063285032). The panel offers it where the rows say the - // deployment stores resolution. + // objectstack#36071 / #36075 — resolve and reopen are an update of + // the top-level `sys_comment` row, under the same grant as Edit. The + // server's rule is any reader of the record (ruling 7063285032), but + // its row floor admits a member's update of their own rows alone, so + // the panel offers ✓ on a thread the viewer started, and on others' + // only where `updatesOthersComments` holds; and only where the rows + // say the deployment stores resolution. onResolveComment={feedsEnabled && feedGates.commentEdit ? handleResolveComment : undefined} moderatesComments={moderatesComments} + updatesOthersComments={updatesOthersComments} onToggleReaction={ (reactionStore === 'records' ? feedGates.reactionAdd @@ -6269,7 +6351,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri {/* objectstack#36075 — the record's comment panel: beside the record (which gives it the width), or over it. */} {commentsOpen && ( - setCommentsOpen(false)} /> + setCommentsOpen(false)} + onEngage={engageComments} + /> )} = { cover: 'absolute inset-0 z-30', }; -/** The record's comment panel, in its place beside or over the record. */ +/** + * The record's comment panel, in its place beside or over the record. + * `onEngage` is called when the pointer first enters the panel or focus first + * moves into it: the reader is reaching for a comment, so the host may ask + * what that takes without opening the record or the panel asking anything + * (objectstack#28470). + */ export function RecordCommentsAside({ placement, onClose, + onEngage, }: { placement: CommentsPanelPlacement; onClose: () => void; + onEngage?: () => void; }) { const ref = useRef(null); // Closed from inside (✕, Esc), the focus goes back to the record: to the @@ -136,7 +144,13 @@ export function RecordCommentsAside({ if (hadFocus) button?.focus(); }, [onClose]); return ( -
+
); diff --git a/ui/packages/plugin-detail/README.md b/ui/packages/plugin-detail/README.md index 8c5fe2334b2..3ad0349745e 100644 --- a/ui/packages/plugin-detail/README.md +++ b/ui/packages/plugin-detail/README.md @@ -916,16 +916,21 @@ and ✕ at its top, the threads oldest first (a thread's replies fold to docked at its foot. Each comment's actions sit in one row at its top right while the pointer is over it (`CommentHoverActions`): Reply, an emoji, ✓ (resolve, on a thread's first comment) and More with Edit and Delete. Edit and Delete are -offered on the viewer's own comments, and on everyone's where the host sets +offered on the viewer's own comments. On other people's, Delete needs `moderatesComments` on the `DiscussionContext` (the console sets it on the explain engine's definite allow of a by-id update of the record, the server's -rule for editing another member's comment; read it three-state with -`useRecordVerdict`). `CommentsButton` is the header's switch: the comments icon +rule for moderating another member's comment), and Edit needs it together with +`updatesOthersComments` (the console sets that on the explain engine's definite +allow of an `update` of one comment the viewer did not write: the platform's +row floor lets most members update only their own rows). Read both three-state +with `useRecordVerdict`. `CommentsButton` is the header's switch: the comments icon with the number of unresolved threads. Resolved threads (objectstack#36071 stores them): where the rows carry a `resolved` (`FeedItem.resolved`, set by the host from `is_resolved`), ✓ hands -`onResolveComment(id, true)`, and a resolved thread leaves the list. The filter +`onResolveComment(id, true)`, and a resolved thread leaves the list. ✓ is on a +thread the viewer started (`authoredByViewer` on its first comment), and on +anyone's only where the host sets `updatesOthersComments`. The filter menu at the panel's top right holds 「显示已解决」 (a resolved thread then shows 「已由 X 解决」, and its ✓ reopens it) and 「只看我参与的」 (threads the viewer started, replied in or is mentioned in, from `authoredByViewer` and diff --git a/ui/packages/plugin-detail/src/comments/CommentThread.tsx b/ui/packages/plugin-detail/src/comments/CommentThread.tsx index b508a613397..0c4ee743024 100644 --- a/ui/packages/plugin-detail/src/comments/CommentThread.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentThread.tsx @@ -51,6 +51,7 @@ export interface RecordCommentThreadProps { | 'onDeleteComment' | 'onResolveComment' | 'moderates' + | 'updatesOthers' | 'mentionSuggestions' | 'onMentionSuggestionsWanted' >; @@ -67,19 +68,29 @@ export interface RecordCommentThreadProps { className?: string; } +/** The viewer wrote this comment (`authoredByViewer`, the host's verdict, never re-derived here). */ +function ownComment(item: FeedItem): boolean { + return item.type === 'comment' && item.authoredByViewer === true; +} + /** - * Whether the viewer may edit and delete this comment (objectstack#36075 item - * 6): their own (`authoredByViewer`, the host's verdict, never re-derived - * here), or anyone's where the host says the viewer may moderate this - * record's comments (the server admits a parent record editor). + * Whether the viewer may edit this comment (objectstack#36075 item 6): their + * own, or anyone's where the host says both that the viewer may moderate this + * record's comments (the server admits a parent record editor) and that the + * server admits their update of a row they did not write (the row floor). */ -function editableComment(item: FeedItem, moderates: boolean | undefined): boolean { - return item.type === 'comment' && (item.authoredByViewer === true || moderates === true); +function editableComment(item: FeedItem, moderates: boolean | undefined, updatesOthers: boolean | undefined): boolean { + return ownComment(item) || (item.type === 'comment' && moderates === true && updatesOthers === true); +} + +/** Whether the viewer may delete this comment: their own, or anyone's where they moderate. */ +function deletableComment(item: FeedItem, moderates: boolean | undefined): boolean { + return ownComment(item) || (item.type === 'comment' && moderates === true); } /** - * The resolver's name: the host's, else the mention list's entry for their id - * (the people of this workspace), else none — the mark then says 「已解决」. + * The resolver's name: the host's, else the entry for their id in a mention + * list the composer already loaded, else none — the mark then says 「已解决」. */ function resolverName( root: FeedItem, @@ -112,17 +123,13 @@ export const CommentThread: React.FC = ({ // on an open thread still lands it there. const [replyFocus, setReplyFocus] = React.useState(0); const [editingId, setEditingId] = React.useState(null); - const { onAddReply, onToggleReaction, onEditComment, onDeleteComment, onResolveComment, moderates } = comments; + const { onAddReply, onToggleReaction, onEditComment, onDeleteComment, onResolveComment, moderates, updatesOthers } = + comments; const resolvable = threadResolvable(thread); const resolved = threadResolved(thread); + // The host names the resolver (a by-id read of the ids it could not name); + // a mention list the composer already loaded is used too, never read for it. const resolvedBy = resolved ? resolverName(root, comments.mentionSuggestions) : undefined; - // A resolver the host could not name is looked up in the mention list, - // which the host reads once, on demand (objectstack#28470). - const wantNames = comments.onMentionSuggestionsWanted; - const nameMissing = resolved && !resolvedBy && root.resolvedById != null; - React.useEffect(() => { - if (nameMissing) wantNames?.(); - }, [nameMissing, wantNames]); const openReply = React.useCallback(() => { if (mode === 'summary') { @@ -138,16 +145,18 @@ export const CommentThread: React.FC = ({ isRoot, onReply: onAddReply ? openReply : undefined, onReact: onToggleReaction ? (emoji: string) => void onToggleReaction(item.id, emoji) : undefined, + // ✓ writes the top-level row: on a thread the viewer started, or anyone's + // where the server admits their update of a row they did not write. onResolve: - isRoot && resolvable && onResolveComment + isRoot && resolvable && onResolveComment && (ownComment(item) || updatesOthers === true) ? () => { // A refused write changed nothing, and the host has said so. void Promise.resolve(onResolveComment(item.id, !resolved)).catch(() => undefined); } : undefined, resolved: isRoot && resolved, - onEdit: onEditComment && editableComment(item, moderates) ? () => setEditingId(item.id) : undefined, - onDelete: onDeleteComment && editableComment(item, moderates) ? () => void onDeleteComment(item.id) : undefined, + onEdit: onEditComment && editableComment(item, moderates, updatesOthers) ? () => setEditingId(item.id) : undefined, + onDelete: onDeleteComment && deletableComment(item, moderates) ? () => void onDeleteComment(item.id) : undefined, }); const itemOf = (item: FeedItem, isRoot: boolean, footer?: React.ReactNode, itemClassName?: string) => ( diff --git a/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx b/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx index d1612542cdb..54a8477ee05 100644 --- a/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentsPanel.resolved-36075.test.tsx @@ -18,6 +18,8 @@ * replied in or is mentioned in. * - Edit and Delete on OTHER people's comments only where the host says the * viewer may moderate this record's comments. + * - ✓ and Edit on a row the viewer did not write only where the host says the + * server admits their update of such a row (the platform's row floor). */ import * as React from 'react'; @@ -91,7 +93,7 @@ describe('CommentsPanel — resolved threads (objectstack#36075)', () => { }); it('✓ on a top-level comment resolves its thread; a reply has none', () => { - const { onResolveComment } = renderPanel(); + const { onResolveComment } = renderPanel({ updatesOthersComments: true }); fireEvent.click(screen.getByRole('button', { name: /1 reply/ })); expect(actionIn('r3', 'resolve')).toBeNull(); fireEvent.click(actionIn('t5', 'resolve')!); @@ -99,7 +101,7 @@ describe('CommentsPanel — resolved threads (objectstack#36075)', () => { }); it('「显示已解决」 shows a resolved thread with its resolver, and its ✓ reopens it', async () => { - const { onResolveComment } = renderPanel(); + const { onResolveComment } = renderPanel({ updatesOthersComments: true }); await toggleFilter('Show resolved'); expect(shownRoots()).toEqual(['t1', 't2', 't3', 't4', 't5']); const thread = commentEl('t2').closest('[data-comment-thread]') as HTMLElement; @@ -119,7 +121,7 @@ describe('CommentsPanel — resolved threads (objectstack#36075)', () => { expect(shownRoots()).toEqual(['t1', 't3', 't4']); }); - it('names a resolver the host could not from the mention list, asking for it once', async () => { + it('names a resolver the host could not from a mention list already loaded, and never reads one for it', async () => { const onMentionSuggestionsWanted = vi.fn(); const items = ITEMS.map((item) => item.id === 't2' ? { ...item, resolvedByName: undefined, resolvedById: 'u-zoe' } : item, @@ -132,7 +134,9 @@ describe('CommentsPanel — resolved threads (objectstack#36075)', () => { await toggleFilter('Show resolved'); const thread = () => commentEl('t2').closest('[data-comment-thread]') as HTMLElement; expect(within(thread()).getByText('Resolved')).toBeInTheDocument(); - expect(onMentionSuggestionsWanted).toHaveBeenCalled(); + // The host names resolvers by id (objectstack#36075 L2 S2): the 50-user + // mention roster is not read for a resolver's name. + expect(onMentionSuggestionsWanted).not.toHaveBeenCalled(); rerender( { expect(shownRoots()).toEqual(['t1', 't2', 't3', 't4', 't5']); }); + it('without the host’s word that others’ rows take the viewer’s update, ✓ only on the viewer’s own threads', async () => { + const { onResolveComment } = renderPanel(); + expect(actionIn('t1', 'resolve')).not.toBeNull(); + expect(actionIn('t3', 'resolve')).toBeNull(); + expect(actionIn('t5', 'resolve')).toBeNull(); + await toggleFilter('Show resolved'); + expect(actionIn('t2', 'reopen')).toBeNull(); + fireEvent.click(actionIn('t1', 'resolve')!); + expect(onResolveComment).toHaveBeenCalledWith('t1', true); + }); + it('offers no ✓ where the host hands no resolve write', () => { renderPanel({ onResolveComment: undefined }); expect(document.querySelector('[data-comment-action="resolve"]')).toBeNull(); @@ -171,7 +186,7 @@ describe('CommentsPanel — resolved threads (objectstack#36075)', () => { describe('CommentsPanel — Edit and Delete for people with permission (objectstack#36075 item 6)', () => { it('a moderator gets Edit and Delete on other people’s comments', async () => { - const { onDeleteComment } = renderPanel({ moderatesComments: true }); + const { onDeleteComment } = renderPanel({ moderatesComments: true, updatesOthersComments: true }); fireEvent.pointerDown(actionIn('t5', 'more')!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); expect(await screen.findByRole('menuitem', { name: 'Edit' })).toBeInTheDocument(); fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' })); @@ -184,8 +199,24 @@ describe('CommentsPanel — Edit and Delete for people with permission (objectst expect(actionIn('t5', 'more')).toBeNull(); }); + it('a moderator whose update of others’ rows the server refuses gets Delete there, not Edit', async () => { + const { onDeleteComment } = renderPanel({ moderatesComments: true, updatesOthersComments: false }); + fireEvent.pointerDown(actionIn('t5', 'more')!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await screen.findByRole('menuitem', { name: 'Delete' })); + expect(onDeleteComment).toHaveBeenCalledWith('t5'); + fireEvent.pointerDown(actionIn('t5', 'more')!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await screen.findByRole('menuitem', { name: 'Delete' }); + expect(screen.queryByRole('menuitem', { name: 'Edit' })).toBeNull(); + }); + + it('others’ rows taking the update is not moderating: no More on others’ comments without it', () => { + renderPanel({ moderatesComments: false, updatesOthersComments: true }); + expect(actionIn('t5', 'more')).toBeNull(); + expect(actionIn('t5', 'resolve')).not.toBeNull(); + }); + it('moderating needs the host’s write too', () => { - renderPanel({ moderatesComments: true, onEditComment: undefined, onDeleteComment: undefined }); + renderPanel({ moderatesComments: true, updatesOthersComments: true, onEditComment: undefined, onDeleteComment: undefined }); expect(actionIn('t5', 'more')).toBeNull(); }); }); diff --git a/ui/packages/plugin-detail/src/comments/useRecordComments.ts b/ui/packages/plugin-detail/src/comments/useRecordComments.ts index f2279126487..311fb10ed00 100644 --- a/ui/packages/plugin-detail/src/comments/useRecordComments.ts +++ b/ui/packages/plugin-detail/src/comments/useRecordComments.ts @@ -50,6 +50,12 @@ export interface RecordCommentsData { * definite verdict; objectstack#36075 item 6). Their own, always. */ moderates?: boolean; + /** + * The server admits the viewer's update of a comment they did not write + * (the host's definite verdict; objectstack#36075). ✓ on another person's + * thread and Edit on another person's comment need it. + */ + updatesOthers?: boolean; mentionSuggestions?: DiscussionMentionSuggestion[]; onMentionSuggestionsWanted?: () => void; } @@ -87,6 +93,7 @@ export function useRecordComments(): RecordCommentsData { onDeleteComment: discussion?.onDeleteComment, onResolveComment: discussion?.onResolveComment, moderates: discussion?.moderatesComments === true, + updatesOthers: discussion?.updatesOthersComments === true, mentionSuggestions: discussion?.mentionSuggestions, onMentionSuggestionsWanted: discussion?.onMentionSuggestionsWanted, }; diff --git a/ui/packages/plugin-detail/src/useRecordEditable.ts b/ui/packages/plugin-detail/src/useRecordEditable.ts index cf0c5c47b6f..e2c3f23d563 100644 --- a/ui/packages/plugin-detail/src/useRecordEditable.ts +++ b/ui/packages/plugin-detail/src/useRecordEditable.ts @@ -308,9 +308,18 @@ function startVerdict( inFlight.add(probe); const answer = (async (): Promise => { try { - const decision = (await readDecision()) as { record?: { visible?: unknown } } | undefined; - const verdict = decision?.record?.visible; - if (typeof verdict !== 'boolean') return undefined; // no record verdict → fail open + const decision = (await readDecision()) as + | { allowed?: unknown; record?: { visible?: unknown } } + | undefined; + const visible = decision?.record?.visible; + const allowed = decision?.allowed; + if (typeof visible !== 'boolean') return undefined; // no record verdict → fail open + // The server admits a by-id write only when `allowed` holds too: it also + // folds in session-level refusals (an on-behalf-of session whose + // delegator is gone) that `record.visible` does not. So a definite allow + // is the conjunction, and `visible` with no `allowed` is no answer. + if (visible && typeof allowed !== 'boolean') return undefined; + const verdict = visible && allowed === true; if (probe.staled.size > 0) return undefined; // asked before the record changed → not an answer verdictCache.set(key, verdict); return verdict; diff --git a/ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx b/ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx index 78f922d28b1..783b1f9939f 100644 --- a/ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx +++ b/ui/packages/plugin-detail/src/useRecordVerdict-36075.test.tsx @@ -57,6 +57,20 @@ describe('useRecordVerdict (objectstack#36075)', () => { expect(noRecordVerdict.result.current).toBeUndefined(); }); + it('is a definite allow only when `allowed` holds beside `record.visible`, as the server admits', async () => { + // An on-behalf-of session whose delegator is gone: the record reads + // visible, the decision is still a refusal. + vi.stubGlobal('fetch', mockExplain({ allowed: false, record: { recordId: 'r1', visible: true } })); + const refused = renderHook(() => useRecordVerdict('note', 'r1')); + await waitFor(() => expect(refused.result.current).toBe(false)); + + __clearRecordEditableCache(); + vi.stubGlobal('fetch', mockExplain({ record: { recordId: 'r2', visible: true } })); + const noAllowed = renderHook(() => useRecordVerdict('note', 'r2')); + await new Promise((r) => setTimeout(r, 0)); + expect(noAllowed.result.current).toBeUndefined(); + }); + it('asks nothing and reads undefined when not enabled', () => { const fetchMock = mockExplain({ allowed: true, record: { recordId: 'r1', visible: true } }); vi.stubGlobal('fetch', fetchMock); diff --git a/ui/packages/react/src/context/DiscussionContext.tsx b/ui/packages/react/src/context/DiscussionContext.tsx index 3a3c43b2eda..2d9cbfeb521 100644 --- a/ui/packages/react/src/context/DiscussionContext.tsx +++ b/ui/packages/react/src/context/DiscussionContext.tsx @@ -62,9 +62,10 @@ export interface DiscussionContextValue { onDeleteComment?: (itemId: string | number) => void | Promise; /** * Resolve (`true`) or reopen (`false`) the thread of a top-level comment - * (objectstack#36071, #36075). Offered to whoever may comment on the record - * (maintainer ruling record 7063285032); the comment panel draws it on the - * rows whose `resolved` the host set. A rejection means nothing changed. + * (objectstack#36071, #36075). Offered under the viewer's `update` grant on + * `sys_comment`; the comment panel draws it on the rows whose `resolved` the + * host set, on a thread the viewer started, and on anyone's only where + * {@link updatesOthersComments} holds. A rejection means nothing changed. */ onResolveComment?: (itemId: string | number, resolved: boolean) => void | Promise; /** @@ -76,6 +77,15 @@ export interface DiscussionContextValue { * `onDeleteComment`. */ moderatesComments?: boolean; + /** + * The server admits the viewer's update of a comment they did NOT write + * (objectstack#36075): the platform's row floor lets most members update + * only the rows they created, before any comment rule is asked. `true` only + * on a definite allow; absent or `false`, the panel offers ✓ and Edit on the + * viewer's own rows alone. Edit on others' comments also needs + * {@link moderatesComments}; Delete does not read this. + */ + updatesOthersComments?: boolean; /** Optional list of users (or any mentionable entities) the comment * input can suggest after the user types `@`. When omitted the input * falls back to free-text @-mentions without autocompletion. */ @@ -142,6 +152,7 @@ export const DiscussionContextProvider: React.FC value.onDeleteComment, value.onResolveComment, value.moderatesComments, + value.updatesOthersComments, value.mentionSuggestions, value.onMentionSuggestionsWanted, value.onUploadAttachments,