|
| 1 | +/** |
| 2 | + * ObjectUI |
| 3 | + * Copyright (c) 2024-present ObjectStack Inc. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * objectstack#28737 — the record page draws the 动态 stream's count the server |
| 11 | + * counted, and asks only the activity rows the 动态 panel draws. |
| 12 | + * |
| 13 | + * Before: the page asked the activity window (`activity: { top: 200 }`) on |
| 14 | + * every open, because the panel's count chip and the 动态 tab's count were |
| 15 | + * the size of the merged rows it held — so a busy record carried 200 rows for |
| 16 | + * a panel that draws five, and the count stopped at the window. |
| 17 | + * |
| 18 | + * Pinned here, through the real adapter under StrictMode: the page asks the |
| 19 | + * panel's rows and the `timeline` count; a record with more than 200 merged |
| 20 | + * entries names the served total on the chip and reads the window only when |
| 21 | + * the 动态 tab opens; a record with none names 0 and reads nothing more; a |
| 22 | + * page opening on the 动态 tab asks the window itself and reads nothing more. |
| 23 | + */ |
| 24 | +import * as React from 'react'; |
| 25 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 26 | +import { render, cleanup, act, fireEvent } from '@testing-library/react'; |
| 27 | +import { MemoryRouter } from 'react-router-dom'; |
| 28 | + |
| 29 | +vi.mock('@object-ui/auth', async (importOriginal) => ({ |
| 30 | + ...(await importOriginal<Record<string, unknown>>()), |
| 31 | + useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }), |
| 32 | +})); |
| 33 | +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ |
| 34 | + ...(await importOriginal<Record<string, unknown>>()), |
| 35 | + useRecordPresence: () => [], |
| 36 | + PresenceAvatars: () => null, |
| 37 | +})); |
| 38 | +vi.mock('sonner', () => ({ |
| 39 | + toast: Object.assign(vi.fn(), { |
| 40 | + success: vi.fn(), error: vi.fn(), info: vi.fn(), |
| 41 | + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), |
| 42 | + }), |
| 43 | +})); |
| 44 | + |
| 45 | +import { MetadataCtx } from '@object-ui/react'; |
| 46 | +import { RelatedCountStore } from '@object-ui/components'; |
| 47 | +import { ObjectStackAdapter } from '@object-ui/data-objectstack'; |
| 48 | +import { __clearRecordEditableCache } from '../../../plugin-detail/src/useRecordEditable'; |
| 49 | +import { __resetRecordApprovalsStore } from '../hooks/useRecordApprovals'; |
| 50 | +import { RecordDetailView } from './RecordDetailView'; |
| 51 | +// The `record:attachments` block the synthesized page places for `enable.files` |
| 52 | +// (registered by the package entry, which this file does not import). |
| 53 | +import './record-attachments-renderer'; |
| 54 | + |
| 55 | +const BASE = 'http://test.local'; |
| 56 | +const OBJECT = 'os_28737_contact'; |
| 57 | +const CHILD = 'os_28737_task'; |
| 58 | + |
| 59 | +const contactDef = { |
| 60 | + name: OBJECT, |
| 61 | + label: 'Contact', |
| 62 | + enable: { files: true }, |
| 63 | + fields: { |
| 64 | + id: { label: 'Id', type: 'text' }, |
| 65 | + name: { label: 'Name', type: 'text' }, |
| 66 | + account: { label: 'Account', type: 'lookup', reference: 'os_28737_account' }, |
| 67 | + }, |
| 68 | +}; |
| 69 | +const accountDef = { name: 'os_28737_account', label: 'Account', fields: { id: { label: 'Id', type: 'text' }, name: { label: 'Name', type: 'text' } } }; |
| 70 | +const childDef = { |
| 71 | + name: CHILD, |
| 72 | + label: 'Task', |
| 73 | + fields: { |
| 74 | + id: { label: 'Id', type: 'text' }, |
| 75 | + name: { label: 'Name', type: 'text' }, |
| 76 | + contact: { label: 'Contact', type: 'lookup', reference: OBJECT }, |
| 77 | + owner: { label: 'Owner', type: 'lookup', reference: 'sys_user' }, |
| 78 | + }, |
| 79 | +}; |
| 80 | +const ALL = [contactDef, accountDef, childDef]; |
| 81 | + |
| 82 | +const COMMENT = { id: 'cm1', thread_id: `${OBJECT}:c1`, author_id: 'u2', author_name: 'Grace', body: 'hello from the payload', created_at: '2026-10-01T10:00:00.000Z' }; |
| 83 | +const ACTIVITY = { id: 'ac1', type: 'created', object_name: OBJECT, record_id: 'c1', actor_name: 'Grace', summary: 'created the contact', timestamp: '2026-09-30T10:00:00.000Z' }; |
| 84 | +const ATTACHMENT = { id: 'f1', parent_object: OBJECT, parent_id: 'c1', file_id: 'file-1', file_name: 'contract.pdf', created_at: '2026-10-02T10:00:00.000Z' }; |
| 85 | + |
| 86 | +interface Answers { |
| 87 | + /** Answer the related rows' owner as a bare id even when the request expands it. */ |
| 88 | + ignoreExpand?: boolean; |
| 89 | + activity?: unknown; |
| 90 | + /** The discussion's comments (default: one). */ |
| 91 | + comments?: unknown[]; |
| 92 | + /** The timeline part's answer (default: none). */ |
| 93 | + timeline?: unknown; |
| 94 | +} |
| 95 | + |
| 96 | +interface Held { method: string; path: string; body: any; released: boolean; release: () => void } |
| 97 | + |
| 98 | +const json = (body: unknown) => |
| 99 | + new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); |
| 100 | + |
| 101 | +function pageAnswer(id: string, body: any, answers: Answers) { |
| 102 | + return { |
| 103 | + success: true, |
| 104 | + data: { |
| 105 | + object: OBJECT, |
| 106 | + id, |
| 107 | + record: { id, name: `Contact ${id}`, account: 'a1' }, |
| 108 | + related: (body.related ?? []).map((r: any) => ({ |
| 109 | + object: r.object, |
| 110 | + field: r.field, |
| 111 | + total: 2, |
| 112 | + records: [0, 1].slice(0, r.top).map((i) => ({ |
| 113 | + id: `t${i}`, |
| 114 | + name: `Task ${i}`, |
| 115 | + contact: id, |
| 116 | + owner: !answers.ignoreExpand && r.expand?.includes('owner') ? { id: 'u9', name: 'Una Owner' } : 'u9', |
| 117 | + })), |
| 118 | + })), |
| 119 | + ...(body.fieldAccess ? { fieldAccess: { object: OBJECT, recordId: id, readable: ['name', 'account'], editable: ['name'], writable: true } } : {}), |
| 120 | + ...(body.explain ? { explain: Object.fromEntries(body.explain.map((op: string) => [op, { allowed: true, record: { recordId: id, visible: true } }])) } : {}), |
| 121 | + ...(body.approvals ? { approvals: { requests: [], lock: { locked: false } } } : {}), |
| 122 | + ...(body.discussion ? { discussion: { comments: answers.comments ?? [COMMENT], reactions: { records: [] } } } : {}), |
| 123 | + ...(body.activity ? { activity: answers.activity ?? { total: 1, records: [ACTIVITY] } } : {}), |
| 124 | + ...(body.attachments ? { attachments: { total: 3, records: [ATTACHMENT] } } : {}), |
| 125 | + ...(body.timeline && answers.timeline !== undefined ? { timeline: answers.timeline } : {}), |
| 126 | + }, |
| 127 | + }; |
| 128 | +} |
| 129 | + |
| 130 | +function answerFor(h: Held, answers: Answers): unknown { |
| 131 | + const meta = /\/api\/v1\/meta\/object\/([^/?]+)/.exec(h.path); |
| 132 | + if (meta) return { success: true, data: ALL.find((o) => o.name === meta[1]) ?? null }; |
| 133 | + const page = /\/api\/v1\/data\/[^/?]+\/([^/?]+)\/page$/.exec(h.path); |
| 134 | + if (page) return pageAnswer(page[1], h.body, answers); |
| 135 | + const one = new RegExp(`/api/v1/data/${OBJECT}\\?.*\\["id","=","([^"]+)"\\]`).exec(h.path); |
| 136 | + if (one) return { success: true, data: { records: [{ id: one[1], name: `Contact ${one[1]}`, account: 'a1' }], total: 1 } }; |
| 137 | + if (h.path.startsWith('/api/v1/data/sys_user?')) return { success: true, data: { records: [{ id: 'u9', name: 'Una Owner' }], total: 1 } }; |
| 138 | + return { success: true, data: { records: [], total: 0 } }; |
| 139 | +} |
| 140 | + |
| 141 | +function heldTransport(answers: Answers) { |
| 142 | + const held: Held[] = []; |
| 143 | + const fetch = vi.fn((input: RequestInfo | URL, init?: RequestInit) => { |
| 144 | + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; |
| 145 | + const method = (init?.method ?? 'GET').toUpperCase(); |
| 146 | + const path = decodeURIComponent(url.replace(BASE, '')); |
| 147 | + if (path.endsWith('/api/v1/discovery')) return Promise.resolve(json({ success: true, data: { capabilities: {}, routes: {} } })); |
| 148 | + return new Promise<Response>((resolve) => { |
| 149 | + const h: Held = { |
| 150 | + method, path, |
| 151 | + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, |
| 152 | + released: false, |
| 153 | + release: () => { if (h.released) return; h.released = true; resolve(json(answerFor(h, answers))); }, |
| 154 | + }; |
| 155 | + held.push(h); |
| 156 | + }); |
| 157 | + }); |
| 158 | + return { fetch, held }; |
| 159 | +} |
| 160 | + |
| 161 | +async function idle() { |
| 162 | + await act(async () => { for (let i = 0; i < 8; i++) await new Promise((r) => setTimeout(r, 0)); }); |
| 163 | +} |
| 164 | +async function settle(held: Held[]) { |
| 165 | + await idle(); |
| 166 | + for (let round = 0; round < 12; round++) { |
| 167 | + const pending = held.filter((h) => !h.released); |
| 168 | + if (pending.length === 0) return; |
| 169 | + await act(async () => { for (const h of pending) h.release(); await new Promise((r) => setTimeout(r, 0)); }); |
| 170 | + await idle(); |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +const isMeta = (h: Held) => h.path.startsWith('/api/v1/meta/'); |
| 175 | +const isPage = (h: Held) => h.method === 'POST' && /\/api\/v1\/data\/[^/?]+\/[^/?]+\/page$/.test(h.path); |
| 176 | +const readsOf = (held: Held[], object: string) => held.filter((h) => h.method === 'GET' && h.path.startsWith(`/api/v1/data/${object}?`)); |
| 177 | + |
| 178 | +beforeEach(() => { |
| 179 | + cleanup(); |
| 180 | + __clearRecordEditableCache(); |
| 181 | + __resetRecordApprovalsStore(); |
| 182 | + RelatedCountStore._reset(); |
| 183 | + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1440 }); |
| 184 | +}); |
| 185 | +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); |
| 186 | + |
| 187 | +async function boot(answers: Answers = {}, entry = `/apps/demo/${OBJECT}/record/c1`) { |
| 188 | + const { fetch, held } = heldTransport(answers); |
| 189 | + vi.stubGlobal('fetch', fetch); |
| 190 | + const ds = new ObjectStackAdapter({ baseUrl: BASE, fetch, autoReconnect: false }); |
| 191 | + await ds.connect(); |
| 192 | + const metadata = { |
| 193 | + objects: ALL, pages: [], loading: false, error: null, |
| 194 | + refresh: async () => {}, invalidate: () => {}, |
| 195 | + ensureType: async () => [], getItem: async () => null, getItemsByType: () => [], |
| 196 | + } as never; |
| 197 | + const open = () => render( |
| 198 | + <React.StrictMode> |
| 199 | + <MemoryRouter initialEntries={[entry]}> |
| 200 | + <MetadataCtx.Provider value={metadata}> |
| 201 | + <RecordDetailView dataSource={ds as never} objects={ALL as never} onEdit={() => {}} objectNameOverride={OBJECT} recordIdOverride="c1" /> |
| 202 | + </MetadataCtx.Provider> |
| 203 | + </MemoryRouter> |
| 204 | + </React.StrictMode>, |
| 205 | + ); |
| 206 | + return { held, open, ds }; |
| 207 | +} |
| 208 | + |
| 209 | + |
| 210 | +const ROWS = (n: number) => Array.from({ length: n }, (_, i) => ({ |
| 211 | + ...ACTIVITY, |
| 212 | + id: `ac${i}`, |
| 213 | + type: 'system', |
| 214 | + summary: `step ${i}`, |
| 215 | + timestamp: new Date(Date.UTC(2026, 8, 30, 10, 59 - i)).toISOString(), |
| 216 | +})); |
| 217 | +const activityReads = (held: Held[]) => readsOf(held, 'sys_activity'); |
| 218 | +const chipOf = (container: HTMLElement) => |
| 219 | + container.querySelector('[data-record-timeline-panel] [data-record-timeline-count]')?.textContent ?? null; |
| 220 | + |
| 221 | +describe('objectstack#28737 — the 动态 count is the server\'s, and the page asks only the panel\'s rows', () => { |
| 222 | + it('a record with more than 200 merged entries shows the served total, and the request asks only the panel\'s rows', async () => { |
| 223 | + const { held, open } = await boot({ activity: { total: 330, records: ROWS(5) }, timeline: { total: 341 } }); |
| 224 | + const view = open(); |
| 225 | + await settle(held); |
| 226 | + |
| 227 | + const [page] = held.filter(isPage); |
| 228 | + expect(page.body.activity).toEqual({ top: 5 }); |
| 229 | + expect(page.body.timeline).toEqual({ discussion: true, activity: true, fieldChanges: false }); |
| 230 | + expect(chipOf(view.container)).toBe('341'); |
| 231 | + expect(activityReads(held)).toEqual([]); |
| 232 | + |
| 233 | + // The 动态 tab draws the whole stream: it reads the window once, and the |
| 234 | + // count stays the served one. |
| 235 | + const openTab = view.container.querySelector('[data-record-timeline-panel-open]') as HTMLButtonElement; |
| 236 | + await act(async () => { fireEvent.click(openTab); }); |
| 237 | + await settle(held); |
| 238 | + expect(activityReads(held)).toHaveLength(1); |
| 239 | + expect(activityReads(held)[0].path).toMatch(/[?&]\$?top=200\b/); |
| 240 | + expect(view.container.textContent).toContain('341'); |
| 241 | + }); |
| 242 | + |
| 243 | + it('a record with none shows 0 and makes no fallback read, the 动态 tab opened included', async () => { |
| 244 | + const { held, open } = await boot({ activity: { total: 0, records: [] }, comments: [], timeline: { total: 0 } }); |
| 245 | + const view = open(); |
| 246 | + await settle(held); |
| 247 | + expect(chipOf(view.container)).toBe('0'); |
| 248 | + const openTab = view.container.querySelector('[data-record-timeline-panel-open]') as HTMLButtonElement; |
| 249 | + await act(async () => { fireEvent.click(openTab); }); |
| 250 | + await settle(held); |
| 251 | + expect(held.filter((h) => !isMeta(h)).map((h) => `${h.method} ${h.path}`)).toEqual([`POST /api/v1/data/${OBJECT}/c1/page`]); |
| 252 | + }); |
| 253 | + |
| 254 | + it('a page opening on the 动态 tab asks the whole window and the count, and reads nothing more', async () => { |
| 255 | + const { held, open } = await boot( |
| 256 | + { activity: { total: 330, records: ROWS(200) }, timeline: { total: 341 } }, |
| 257 | + `/apps/demo/${OBJECT}/record/c1?related=timeline`, |
| 258 | + ); |
| 259 | + open(); |
| 260 | + await settle(held); |
| 261 | + const [page] = held.filter(isPage); |
| 262 | + expect(page.body.activity).toEqual({ top: 200 }); |
| 263 | + expect(page.body.timeline).toEqual({ discussion: true, activity: true, fieldChanges: false }); |
| 264 | + expect(activityReads(held)).toEqual([]); |
| 265 | + }); |
| 266 | + |
| 267 | + it('ablation — a payload without the count leaves the chip on the rows the page holds', async () => { |
| 268 | + const { held, open } = await boot({ activity: { total: 330, records: ROWS(5) } }); |
| 269 | + const view = open(); |
| 270 | + await settle(held); |
| 271 | + // One comment + five activity rows: what the page holds, not the record's stream. |
| 272 | + expect(chipOf(view.container)).toBe('6'); |
| 273 | + }); |
| 274 | +}); |
0 commit comments