diff --git a/.changeset/36898-list-changed-column.md b/.changeset/36898-list-changed-column.md new file mode 100644 index 00000000000..f399704712b --- /dev/null +++ b/.changeset/36898-list-changed-column.md @@ -0,0 +1,18 @@ +--- +'@object-ui/data-objectstack': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): the metadata list shows when each item last changed and marks items with unpublished changes + +Clause-②: yes (widening) +Metadata-protocol: none + +The generic metadata list (Setup's catalog lists and Studio's "All metadata" area) gains a 「修改时间」 / "Modified" column, read off the list answer's `changedAt` sibling. Only an item served from a stored row has a time; a code-shipped item shows an empty cell. The sort control gains "Modified (newest first)" and "Modified (oldest first)", which ride the address as `sort=-changed` / `sort=changed`; items without a time sort last either way, and the item page's ‹ › follow the same order. + +Beneath the time, an item with a pending draft on the existing `GET /api/v1/meta/_drafts` ledger is marked 「有未发布的改动」 / "Unpublished changes", including drafts that existed before this change. A draft the AI assistant wrote (any of its recorded changes made by the AI copilot or through the MCP build door, the rule the item page's AI line uses) is marked 「AI 的改动未发布」 / "Unpublished AI changes" instead. A publish removes the mark. + +`MetadataClient.listResponse` now returns the list's `changedAt` beside the items (each entry read with the spec's own rule; an entry that does not parse is dropped, and absence stays absence). `list` is unchanged. + +New locale keys in the studio catalogue (en, zh): `engine.list.sort.changed.asc`, `engine.list.sort.changed.desc`, `engine.list.col.changedAt`, `engine.list.draftMark.human`, `engine.list.draftMark.humanTitle`, `engine.list.draftMark.ai`, `engine.list.draftMark.aiTitle`. diff --git a/ui/packages/app-shell/src/views/metadata-admin/ListChangedCell.tsx b/ui/packages/app-shell/src/views/metadata-admin/ListChangedCell.tsx new file mode 100644 index 00000000000..c84cbe10d10 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ListChangedCell.tsx @@ -0,0 +1,56 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The metadata list's 「修改时间」 cell (objectstack#36898): the item's change + * time (`listChangedAt.ts`), empty for an item with none, and beneath it the + * 「有未发布的改动」 mark when the item has a pending draft + * (`listDraftMarks.ts`) — the AI's draft marked apart from anyone else's. + */ + +import * as React from 'react'; +import { Sparkles } from 'lucide-react'; +import { EmptyValue, cn } from '@object-ui/components'; +import { formatChangedAt } from './listChangedAt.js'; +import type { ListDraftMarkKind } from './listDraftMarks.js'; +import { t } from './i18n.js'; + +export function ListChangedCell({ + changedAt, + draft, + locale, +}: { + /** The item's change time (ISO-8601); `undefined` for none. */ + changedAt: string | undefined; + /** The item's pending-draft mark; `null` for none. */ + draft: ListDraftMarkKind | null; + locale: string; +}): React.ReactElement { + const text = formatChangedAt(changedAt, locale); + return ( + + {text ? ( + + ) : ( + + )} + {draft && ( + + {draft === 'ai' && + )} + + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.changedColumn-36898.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.changedColumn-36898.test.tsx new file mode 100644 index 00000000000..c00c855dde7 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.changedColumn-36898.test.tsx @@ -0,0 +1,131 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36898 — the generic metadata list's 「修改时间」 column and its + * 「有未发布的改动」 mark, on the real page. The metadata client and the + * pending-drafts ledger it reads are stubbed. Pinned, each with its control: + * + * - an item served from a stored row shows its time; a code-shipped item an + * empty cell, with no error; + * - `?sort=-changed` draws newest first, code-shipped items last; + * - an item on the `_drafts` ledger is marked, the AI's draft apart from a person's; + * an item off the ledger (published) carries no mark. + */ +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, cleanup, screen, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +// Dynamic imports the page's anchors and editors reach, paid at collection +// rather than inside a case's clocked window. +import '@object-ui/plugin-detail'; +import '@objectstack/lint'; + +const ITEMS: Record[] = [ + { name: 'shipped', label: 'Shipped', _packageId: 'crm' }, + { name: 'by_person', label: 'By person', _packageId: 'crm' }, + { name: 'by_ai', label: 'By AI', _packageId: 'crm' }, +]; +const CHANGED_AT = { by_person: '2026-11-20T08:00:00Z', by_ai: '2026-11-24T10:15:00Z' }; +const DRAFT_CHANGES: Record = { + by_person: [{ path: ['label'], by: 'studio', actor: 'u1', at: '2026-11-24T09:00:00Z' }], + by_ai: [{ path: ['label'], by: 'copilot', actor: 'u1', at: '2026-11-24T09:30:00Z' }], +}; + +const CLIENT = { + list: async (type: string) => (type === 'skill' ? ITEMS : []), + listResponse: async (type: string) => + type === 'skill' ? { items: ITEMS, changedAt: CHANGED_AT } : { items: [] }, + listDrafts: async () => ledger.entries, + getDraft: async (_type: string, name: string) => ({ type: 'skill', name, item: {}, draftChanges: DRAFT_CHANGES[name] }), +}; +const SKILL_ENTRY = { type: 'skill', label: 'Skill', allowEnvironmentOverlay: false, allowRuntimeCreate: true }; + +const ledger = vi.hoisted(() => ({ entries: [] as Array<{ type: string; name: string; packageId: string | null }> })); + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => CLIENT, + useMetadataTypes: () => ({ loading: false, error: null, entries: [SKILL_ENTRY] }), +})); +vi.mock('./i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); +vi.mock('../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true })); +vi.mock('../../hooks/useTenancyPosture', async (importOriginal) => ({ + ...(await importOriginal>()), + useTenancyPosture: () => 'single', +})); + +// Imported AFTER the mocks so the page picks them up. +import { MetadataResourceListPage } from './ResourceListPage'; +import { registerBuiltinAnchors } from './anchors'; +import '../../services/builtinComponents'; + +registerBuiltinAnchors(); + +afterEach(() => { + cleanup(); + ledger.entries = []; +}); + +function mount(search = '') { + return render( + + + } /> + + , + ); +} + +const cellOf = (name: string) => within(screen.getByTestId(`metadata-row-${name}`)).getByTestId('metadata-changed-cell'); + +describe('the 「修改时间」 column (objectstack#36898)', () => { + it('an item with a stored row shows its time; a code-shipped item an empty cell', async () => { + mount(); + await screen.findByRole('table'); + expect(await screen.findByRole('columnheader', { name: 'Modified' })).toBeInTheDocument(); + const time = await within(screen.getByTestId('metadata-row-by_ai')).findByText( + new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short' }).format(Date.parse(CHANGED_AT.by_ai)), + ); + expect(time.closest('time')).toHaveAttribute('dateTime', CHANGED_AT.by_ai); + expect(cellOf('shipped').querySelector('time')).toBeNull(); + }); + + it('`?sort=-changed` draws newest first, the code-shipped item last', async () => { + mount('&sort=-changed'); + await within(await screen.findByTestId('metadata-row-by_ai')).findByText(/2026/); + const order = screen + .getAllByTestId(/^metadata-row-/) + .filter((el) => el.tagName === 'TR') + .map((tr) => tr.getAttribute('data-testid')); + expect(order).toEqual(['metadata-row-by_ai', 'metadata-row-by_person', 'metadata-row-shipped']); + }); +}); + +describe('the 「有未发布的改动」 mark (objectstack#36898)', () => { + it('marks each item on the ledger, the AI\'s draft apart from a person\'s', async () => { + ledger.entries = [ + { type: 'skill', name: 'by_person', packageId: 'crm' }, + { type: 'skill', name: 'by_ai', packageId: 'crm' }, + ]; + mount(); + await screen.findByRole('table'); + const ai = await within(cellOf('by_ai')).findByTestId('metadata-draft-mark'); + await vi.waitFor(() => expect(ai).toHaveAttribute('data-draft-by', 'ai')); + expect(ai).toHaveTextContent('Unpublished AI changes'); + const person = within(cellOf('by_person')).getByTestId('metadata-draft-mark'); + expect(person).toHaveAttribute('data-draft-by', 'human'); + expect(person).toHaveTextContent('Unpublished changes'); + expect(within(cellOf('shipped')).queryByTestId('metadata-draft-mark')).toBeNull(); + }); + + it('an item off the ledger — published — carries no mark (control)', async () => { + mount(); + await screen.findByRole('table'); + await within(screen.getByTestId('metadata-row-by_ai')).findByText(/2026/); + expect(screen.queryByTestId('metadata-draft-mark')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index 425cce28f76..1f06aa9c03a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -117,6 +117,9 @@ import { type MetadataListState, } from './metadataListState.js'; import { useListScrollRestore } from './useListScrollRestore.js'; +import { useListChangedAt } from './listChangedAt.js'; +import { useListDraftMarks } from './listDraftMarks.js'; +import { ListChangedCell } from './ListChangedCell.js'; /** * objectui#12982 — the Clone dialog of a declaration-only catalog @@ -625,6 +628,9 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string cancelled = true; }; }, [client, type, refreshKey, listInclude]); + // objectstack#36898 — each item's change time and its pending-draft mark. + const changedAt = useListChangedAt(client, type, listInclude ? { include: listInclude } : undefined, refreshKey); + const draftMarkOf = useListDraftMarks(client, type, refreshKey); const searchableFields = config.searchableFields ?? ['name', 'label', 'description']; // Structural scope — every row this package could ever show for this @@ -701,6 +707,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // one implementation the detail's ‹ › order reads too (`metadataListState.ts`). const rowReader: ListRowReader = { name: (row) => String(row.item[config.primaryKey ?? 'name'] ?? ''), + changedAt: (row) => changedAt?.[String(row.item[config.primaryKey ?? 'name'] ?? '')], label: (row) => (typeof row.item.label === 'string' ? row.item.label : undefined), matches: (row, q) => matchesQuery(row.item, q, searchableFields), source: (row) => row.source, @@ -1080,6 +1087,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string {localizeColumnLabel(ci === 0 && labelColumn ? labelColumn : c)} ))} + {t('engine.list.col.changedAt', locale)} {t('engine.list.col.source', locale)} {activation && ( @@ -1241,6 +1249,13 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ); })} + + + {(row.item._lock as string | undefined) && row.item._lock !== 'none' && ( = { + name: (row) => row.name, + label: () => undefined, + matches: (row, q) => row.name.includes(q), + source: (row) => (row.at ? 'runtime' : 'artifact'), + changedAt: (row) => row.at, +}; + +const sorted = (dir: 'asc' | 'desc'): MetadataListState => ({ ...DEFAULT_LIST_STATE, sort: { key: 'changed', dir } }); +const names = (rows: Row[]) => rows.map((row) => row.name); + +describe('the `changed` sort (objectstack#36898)', () => { + it('newest first; ties by name; items without a time last', () => { + expect(names(applyListState(ROWS, sorted('desc'), READ, 'en-US'))).toEqual([ + 'new', 'tie_a', 'tie_b', 'old', 'shipped_a', 'shipped_b', + ]); + }); + + it('oldest first; items without a time still last', () => { + expect(names(applyListState(ROWS, sorted('asc'), READ, 'en-US'))).toEqual([ + 'old', 'tie_a', 'tie_b', 'new', 'shipped_a', 'shipped_b', + ]); + }); + + it('the detail ‹ › order is the drawn order, under a filter too', () => { + for (const state of [sorted('desc'), sorted('asc'), { ...sorted('desc'), query: 'i' }]) { + expect(orderedListNames(ROWS, state, READ, 'en-US')).toEqual(names(applyListState(ROWS, state, READ, 'en-US'))); + } + }); + + it('a reader with no times sorts by name (control: the time is what moved them)', () => { + const { changedAt: _ignored, ...noTimes } = READ; + expect(names(applyListState(ROWS, sorted('desc'), noTimes, 'en-US'))).toEqual([ + 'new', 'old', 'shipped_a', 'shipped_b', 'tie_a', 'tie_b', + ]); + }); + + it('rides the address as `changed` / `-changed`', () => { + expect(encodeListSort({ key: 'changed', dir: 'desc' })).toBe('-changed'); + expect(decodeListSort('-changed')).toEqual({ key: 'changed', dir: 'desc' }); + expect(decodeListSort('changed')).toEqual({ key: 'changed', dir: 'asc' }); + }); + + it('a time that does not parse counts as none', () => { + expect(compareChangedAt('not a time', '2026-11-01T00:00:00Z', 'desc')).toBeGreaterThan(0); + expect(compareChangedAt(undefined, undefined, 'asc')).toBe(0); + }); +}); + +describe('the 「修改时间」 cell text (objectstack#36898)', () => { + it('an item with a time shows it in the reader\'s locale; one without shows none', () => { + const at = '2026-11-24T10:15:00.000Z'; + expect(formatChangedAt(at, 'en-US')).toBe( + new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short' }).format(Date.parse(at)), + ); + expect(formatChangedAt(undefined, 'zh-CN')).toBeNull(); + expect(formatChangedAt('garbage', 'zh-CN')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/listChangedAt.ts b/ui/packages/app-shell/src/views/metadata-admin/listChangedAt.ts new file mode 100644 index 00000000000..8212f4df4d0 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/listChangedAt.ts @@ -0,0 +1,80 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The metadata list's 「修改时间」 (objectstack#36898, epic objectstack#36890 + * decision 2): when each listed item last changed, read off the list answer's + * `changedAt` sibling (`GetMetaItemsResponseSchema.changedAt`, keyed by the + * item's name, objectstack#36894). + * + * Only an item served from a stored row has a time. A code-shipped item has + * none and its cell is empty — never an error, never a stand-in such as the + * read time — and it sorts after every item that has one, whichever way the + * list sorts. + */ + +import * as React from 'react'; +import type { MetadataClient, MetadataListOptions } from '@object-ui/data-objectstack'; + +/** The instant `iso` names, in ms; `null` for none or one that does not parse. */ +export function changedAtTime(iso: string | undefined): number | null { + if (!iso) return null; + const ms = Date.parse(iso); + return Number.isFinite(ms) ? ms : null; +} + +/** + * The `changed` sort's comparison: older first for `asc`, newer first for + * `desc`; a missing time after any present one in both directions. `0` for + * equal times or two missing ones (the caller breaks the tie). + */ +export function compareChangedAt(a: string | undefined, b: string | undefined, dir: 'asc' | 'desc'): number { + const ta = changedAtTime(a); + const tb = changedAtTime(b); + if (ta === null || tb === null) return ta === tb ? 0 : ta === null ? 1 : -1; + return dir === 'desc' ? tb - ta : ta - tb; +} + +const FORMATS = new Map(); + +/** The cell's text for `iso` in `locale`; `null` for no time. */ +export function formatChangedAt(iso: string | undefined, locale: string): string | null { + const ms = changedAtTime(iso); + if (ms === null) return null; + let format = FORMATS.get(locale); + if (!format) { + format = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }); + FORMATS.set(locale, format); + } + return format.format(ms); +} + +/** + * The `changedAt` map of `type`'s list, read with the same request the list + * page's items come from (`listResponse` and `list` share one in-flight GET). + * `null` while unread; empty when the read fails or the server serves no + * times — every cell is then empty, which is what an unknown time draws. + */ +export function useListChangedAt( + client: MetadataClient, + type: string, + options: MetadataListOptions | undefined, + refreshKey: unknown, +): Readonly> | null { + const [read, setRead] = React.useState<{ type: string; changedAt: Record } | null>(null); + const include = options?.include; + React.useEffect(() => { + let cancelled = false; + (async () => { + try { + const answer = await client.listResponse(type, include ? { include } : undefined); + if (!cancelled) setRead({ type, changedAt: answer.changedAt ?? {} }); + } catch { + if (!cancelled) setRead({ type, changedAt: {} }); + } + })(); + return () => { + cancelled = true; + }; + }, [client, type, include, refreshKey]); + return read?.type === type ? read.changedAt : null; +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/listDraftMarks-36898.test.ts b/ui/packages/app-shell/src/views/metadata-admin/listDraftMarks-36898.test.ts new file mode 100644 index 00000000000..5cdec5fb08c --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/listDraftMarks-36898.test.ts @@ -0,0 +1,60 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36898 — which listed row a `_drafts` ledger row marks, and + * whether the mark is the AI's: the rule the item pages' AI line uses + * (`isAgentDraftSurface`), over the draft's `draftChanges`. + */ + +import { describe, it, expect } from 'vitest'; +import type { DraftChange } from '@object-ui/data-objectstack'; +import { draftEntryOf, draftMarkKindOf, type ListDraftEntry } from './listDraftMarks'; + +const change = (by: DraftChange['by']): DraftChange => + ({ path: ['label'], by, actor: 'u1', at: '2026-11-24T10:00:00Z' }) as DraftChange; + +describe('AI or a person (objectstack#36898)', () => { + it('a draft with any copilot or MCP entry is the AI\'s', () => { + expect(draftMarkKindOf([change('studio'), change('copilot')])).toBe('ai'); + expect(draftMarkKindOf([change('mcp')])).toBe('ai'); + }); + + it('a person\'s draft, or one with no recorded provenance, carries the plain mark', () => { + expect(draftMarkKindOf([change('studio'), change('api')])).toBe('human'); + expect(draftMarkKindOf(null)).toBe('human'); + expect(draftMarkKindOf([])).toBe('human'); + }); +}); + +describe('which row a ledger row marks (objectstack#36898)', () => { + const entry = (over: Partial): ListDraftEntry => ({ + type: 'dashboard', + name: 'sales_board', + packageId: 'com.acme.crm', + ...over, + }); + + it('the same type and name in the same package', () => { + const e = entry({}); + expect(draftEntryOf([e], 'dashboard', { name: 'sales_board', packageId: 'com.acme.crm' })).toBe(e); + }); + + it('a stored plural type spelling folds to the list\'s type', () => { + const e = entry({ type: 'dashboards' }); + expect(draftEntryOf([e], 'dashboard', { name: 'sales_board' })).toBe(e); + }); + + it('a draft in the `.custom` pair marks the code-shipped base item it customizes', () => { + const e = entry({ packageId: 'com.acme.crm.custom' }); + expect(draftEntryOf([e], 'dashboard', { name: 'sales_board', packageId: 'com.acme.crm' })).toBe(e); + }); + + it('marks nothing for another name, type, package or bundle member (control)', () => { + expect(draftEntryOf([entry({})], 'dashboard', { name: 'ops_board' })).toBeNull(); + expect(draftEntryOf([entry({})], 'report', { name: 'sales_board' })).toBeNull(); + expect(draftEntryOf([entry({})], 'dashboard', { name: 'sales_board', packageId: 'com.other.app' })).toBeNull(); + expect( + draftEntryOf([entry({ type: 'email_template', member: 'zh-CN' })], 'email_template', { name: 'sales_board', member: 'en-US' }), + ).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/listDraftMarks.ts b/ui/packages/app-shell/src/views/metadata-admin/listDraftMarks.ts new file mode 100644 index 00000000000..9d8aae37116 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/listDraftMarks.ts @@ -0,0 +1,140 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The metadata list's 「有未发布的改动」 mark (objectstack#36898, epic + * objectstack#36890 decisions 2 and 14): a listed item with a pending draft + * on the existing ledger, `GET /api/v1/meta/_drafts`, whoever wrote it and + * whenever — a draft that existed before the list drew marks is marked too. + * + * ## The ledger + * + * Read through the list's own metadata client (`listDrafts`, the read the + * client's draft reads already ask first), so it is scoped exactly as the + * list's items are. Re-read with the list, and on the publish pulse + * (`emitMetadataRefresh`, which every publish path sends), so a publish takes + * the mark away from whichever door it came. The list may sit outside + * Studio's `StudioPendingDraftsContext` (Setup's lists do), and that + * context's rows carry no package or bundle member, so the list does not + * read it. + * + * A ledger that cannot be read (no authoring grant, a kernel without drafts) + * marks nothing: the list does not know, and says nothing. + * + * ## AI or a person + * + * Who drafted it is the draft's own per-key provenance (`draftChanges`, the + * strict draft read), judged by the rule the item pages' AI line uses + * (`StudioAiDraftNotice`, `isAgentDraftSurface`): a draft with any entry + * written by the AI copilot or through the MCP build door is the AI's; any + * other draft — a person's, one that recorded no provenance, or one whose + * read failed — carries the plain mark. The draft of each marked item of the + * type is read once per ledger read. + * + * ## Which row + * + * A ledger row marks a listed row of the same type (stored spellings folded + * as every `/meta` reader folds them) and name; where both name a package, + * the same app's — a base and its `.custom` pair are one app, since an edit + * to a code-shipped item is drafted into the pair (`appPackageOf`); where + * both name a bundle member, the same member. + */ + +import * as React from 'react'; +import { canonicalMetaUrlType } from '@objectstack/spec/shared'; +import { readDraftChanges, type DraftChange, type MetadataClient } from '@object-ui/data-objectstack'; +import { appPackageOf } from '../../preview/usePendingDrafts.js'; +import { subscribeMetadataRefresh } from '../../assistant/assistantBus.js'; +import { isAgentDraftSurface } from '../studio-design/StudioDraftMark.js'; + +/** The mark a row carries: an AI tool's unpublished draft, or anyone else's. */ +export type ListDraftMarkKind = 'ai' | 'human'; + +/** A ledger row, as far as matching reads it. */ +export interface ListDraftEntry { + type: string; + name: string; + packageId: string | null; + member?: string; +} + +/** What the list knows of a row, for matching it to a ledger row. */ +export interface ListDraftRow { + name: string; + packageId?: string; + member?: string; +} + +/** The kind a draft's provenance gives: `ai` when any entry is an AI tool's. */ +export function draftMarkKindOf(changes: readonly DraftChange[] | null | undefined): ListDraftMarkKind { + return (changes ?? []).some((change) => isAgentDraftSurface(change.by)) ? 'ai' : 'human'; +} + +function samePackage(entry: string | null, row: string | undefined): boolean { + if (!entry || !row || row === 'sys_metadata') return true; + return appPackageOf(entry) === appPackageOf(row); +} + +/** The ledger row that marks `row` of `type`, or `null` — see the module docblock. */ +export function draftEntryOf(entries: readonly E[], type: string, row: ListDraftRow): E | null { + return ( + entries.find( + (entry) => + entry.name === row.name && + canonicalMetaUrlType(entry.type) === type && + (!entry.member || !row.member || entry.member === row.member) && + samePackage(entry.packageId, row.packageId), + ) ?? null + ); +} + +interface JudgedEntry extends ListDraftEntry { + kind: ListDraftMarkKind; +} + +/** + * Each row's mark on `type`'s list; `null` for a row with no pending draft. + * `refreshKey` re-reads the ledger with the list. + */ +export function useListDraftMarks( + client: MetadataClient, + type: string, + refreshKey: unknown, +): (row: ListDraftRow) => ListDraftMarkKind | null { + const [pulse, setPulse] = React.useState(0); + React.useEffect(() => subscribeMetadataRefresh(() => setPulse((n) => n + 1)), []); + + const [judged, setJudged] = React.useState<{ type: string; entries: JudgedEntry[] } | null>(null); + React.useEffect(() => { + let cancelled = false; + (async () => { + let ofType: ListDraftEntry[]; + try { + ofType = (await client.listDrafts()).filter((entry) => canonicalMetaUrlType(entry.type) === type); + } catch { + ofType = []; + } + const entries = await Promise.all( + ofType.map(async (entry): Promise => { + try { + const answer = await client.getDraft(type, entry.name, { + ...(entry.packageId ? { packageId: entry.packageId } : {}), + ...(entry.member ? { member: entry.member } : {}), + }); + return { ...entry, kind: draftMarkKindOf(readDraftChanges(answer)) }; + } catch { + return { ...entry, kind: 'human' }; + } + }), + ); + if (!cancelled) setJudged({ type, entries }); + })(); + return () => { + cancelled = true; + }; + }, [client, type, refreshKey, pulse]); + + const entries = judged?.type === type ? judged.entries : NONE; + return (row: ListDraftRow) => draftEntryOf(entries, type, row)?.kind ?? null; +} + +const NONE: readonly JudgedEntry[] = []; diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts index da8c6c70a72..566943d9ad9 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts @@ -27,6 +27,8 @@ * its own params and meaning (`ResourceListPage`, `catalog-scope.ts`). */ +import { compareChangedAt } from './listChangedAt.js'; + /** The search text. */ export const LIST_QUERY_PARAM = 'q'; /** The source filter: `artifact` or `runtime`; absent = every source. */ @@ -51,12 +53,11 @@ export type ListSourceFilter = 'all' | 'artifact' | 'runtime'; export type ListStatusFilter = 'all' | 'active' | 'inactive'; /** - * The keys the list sorts by: the item's API name (its primary key) and its - * label. The seam for a third key — the modified time, once the list serves - * its modified-time sibling field — is one entry here and one member on - * {@link ListRowReader}; nothing else reads the set. + * The keys the list sorts by: the item's API name (its primary key), its + * label, and its change time (objectstack#36898, {@link ListRowReader.changedAt} + * — `listChangedAt.ts` holds the comparison). Nothing else reads the set. */ -export const LIST_SORT_KEYS = ['name', 'label'] as const; +export const LIST_SORT_KEYS = ['name', 'label', 'changed'] as const; export type ListSortKey = (typeof LIST_SORT_KEYS)[number]; export interface ListSort { @@ -174,6 +175,12 @@ export interface ListRowReader { * status. */ active?: (row: R) => boolean | null; + /** + * The row's change time, an ISO-8601 instant (the list's `changedAt` + * sibling); `undefined` for a row with none — a code-shipped item. Absent, + * every row has none and the `changed` sort is by name. + */ + changedAt?: (row: R) => string | undefined; } const COLLATORS = new Map(); @@ -221,6 +228,19 @@ export function applyListState( return true; }); const sign = state.sort.dir === 'desc' ? -1 : 1; + if (state.sort.key === 'changed') { + // Rows without a time come last either way, and ties read A to Z by name. + const at = (row: R) => read.changedAt?.(row); + return kept + .map((row, i) => ({ row, i })) + .sort((a, b) => { + const primary = compareChangedAt(at(a.row), at(b.row), state.sort.dir); + if (primary !== 0) return primary; + const byName = collator.compare(read.name(a.row), read.name(b.row)); + return byName !== 0 ? byName : a.i - b.i; + }) + .map(({ row }) => row); + } return kept .map((row, at) => ({ row, at })) .sort((a, b) => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts index 55129200da8..e6c8713603f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts @@ -34,6 +34,7 @@ import { holdersOfName, servedHolderOf } from './permission-set-holder.js'; import { usePackageCustomizations } from '../studio-design/CustomizationMark.js'; import { customizationMarkOf, customizationTotal } from '../studio-design/customizationMarks.js'; import { classifyProvenance } from './ResourceListPage.js'; +import { useListChangedAt } from './listChangedAt.js'; import { decodeListState, hasListContext, @@ -124,6 +125,9 @@ export function useListOrderedNames(type: string): ListOrderedNames { }; }, [client, type, listInclude]); + // objectstack#36898 — the change times the `changed` sort reads. + const changedAt = useListChangedAt(client, type, listInclude ? { include: listInclude } : undefined, null); + // The activation ledger, read only when the status filter needs it. const needsLedger = state.status !== 'all' && envScope && hasCatalogActivation(type); const [ledgerRead, setLedgerRead] = React.useState<{ type: string; read: CatalogLedgerRead | 'error' } | null>(null); @@ -147,6 +151,7 @@ export function useListOrderedNames(type: string): ListOrderedNames { if (rows === null || rows.type !== type) return { status: 'loading', names: EMPTY, fromList }; if (state.customizedOnly && customizations.status === 'loading') return { status: 'loading', names: EMPTY, fromList }; if (needsLedger && ledger === null) return { status: 'loading', names: EMPTY, fromList }; + if (state.sort.key === 'changed' && changedAt === null) return { status: 'loading', names: EMPTY, fromList }; const scoped = scopeListRows(rows.rows, { listFilter, unscoped, activePackage, pairId }); const markOf = (row: Row) => @@ -172,6 +177,7 @@ export function useListOrderedNames(type: string): ListOrderedNames { label: (row) => (typeof row.item.label === 'string' ? row.item.label : undefined), matches: (row, query) => matchesQuery(row.item, query, searchKey.split('\n')), source: (row) => row.source, + changedAt: (row) => changedAt?.[String(row.item[primaryKey] ?? '')], ...(customizedOffered ? { customized: (row: Row) => markOf(row) !== null } : {}), ...(envScope && hasCatalogActivation(type) ? { @@ -187,5 +193,5 @@ export function useListOrderedNames(type: string): ListOrderedNames { }; return { status: 'ready', names: orderedListNames(scoped, state, read, locale), fromList }; // Keyed on the config members read, never on `config`, rebuilt every render. - }, [rows, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey]); + }, [rows, changedAt, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey]); } diff --git a/ui/packages/data-objectstack/src/metadata-client.listChangedAt-36898.test.ts b/ui/packages/data-objectstack/src/metadata-client.listChangedAt-36898.test.ts new file mode 100644 index 00000000000..af0d0abce40 --- /dev/null +++ b/ui/packages/data-objectstack/src/metadata-client.listChangedAt-36898.test.ts @@ -0,0 +1,50 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36898 — `MetadataClient.listResponse` carries the list's + * `changedAt` sibling (objectstack#36894, `GetMetaItemsResponseSchema`): each + * listed item's change time, keyed by name, each entry read with the spec's + * own rule. `list` still returns the items alone. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { MetadataClient } from './metadata-client'; + +function clientAnswering(body: unknown) { + const fetchImpl = vi.fn( + async () => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }), + ) as unknown as typeof fetch; + return new MetadataClient({ baseUrl: 'http://localhost:3000', fetch: fetchImpl }); +} + +const ITEMS = [{ name: 'sales_board' }, { name: 'ops_board' }, { name: 'shipped_board' }]; + +describe('MetadataClient.listResponse — the change times beside a list (objectstack#36898)', () => { + it('returns each served change time by name; a code-shipped item has no entry', async () => { + const changedAt = { sales_board: '2026-11-24T10:15:00.000Z', ops_board: '2026-11-20T08:00:00Z' }; + const c = clientAnswering({ type: 'dashboard', items: ITEMS, changedAt }); + const answer = await c.listResponse('dashboard'); + expect(answer.items).toEqual(ITEMS); + expect(answer.changedAt).toEqual(changedAt); + expect(answer.changedAt?.shipped_board).toBeUndefined(); + }); + + it('absence stays absence: no `changedAt` key when the server sent none', async () => { + const answer = await clientAnswering({ type: 'dashboard', items: ITEMS }).listResponse('dashboard'); + expect('changedAt' in answer).toBe(false); + }); + + it('an entry that is not an instant is dropped; the others stand', async () => { + const c = clientAnswering({ + type: 'dashboard', + items: ITEMS, + changedAt: { sales_board: 'yesterday', ops_board: 1732440000, shipped_board: '2026-11-24T10:15:00Z' }, + }); + expect((await c.listResponse('dashboard')).changedAt).toEqual({ shipped_board: '2026-11-24T10:15:00Z' }); + }); + + it('`list` returns the items alone', async () => { + const c = clientAnswering({ type: 'dashboard', items: ITEMS, changedAt: { sales_board: '2026-11-24T10:15:00Z' } }); + expect(await c.list('dashboard')).toEqual(ITEMS); + }); +}); diff --git a/ui/packages/data-objectstack/src/metadata-client.ts b/ui/packages/data-objectstack/src/metadata-client.ts index aef18606cba..4c59689d35c 100644 --- a/ui/packages/data-objectstack/src/metadata-client.ts +++ b/ui/packages/data-objectstack/src/metadata-client.ts @@ -36,6 +36,7 @@ import { FindReferencesToMetaResponseSchema, FlowRegistrationSchema, GetMetaItemLayeredResponseSchema, + GetMetaItemsResponseSchema, } from '@objectstack/spec/api'; // objectui#8676 - the object-metadata write invariant, applied HERE because this // is a DOOR and not a writer. Every `client.save('object', ...)` call site in the @@ -285,8 +286,14 @@ export interface MetadataListOptions { * `flow`, a server with no automation service, or one that predates the key — * and absence means no engine judged the flow, ⛔ never `registered`. A name * the map has no entry for is unjudged in the same way. + * + * `changedAt` is when each listed item's served row last changed, keyed by the + * item's `name` (objectstack#36894): an ISO-8601 instant, present only for an + * item served from a stored row. A code-shipped item has no entry, and a + * server that predates the key sends none — either way the item has no known + * change time, ⛔ never a stand-in. */ -export type MetadataListAnswer = { items: T[] } & Pick; +export type MetadataListAnswer = { items: T[] } & Pick; /** * Keep the verdicts of a list answer's `registrations` that parse with the @@ -304,6 +311,23 @@ function readRegistrations(raw: unknown): Record | und return out; } +/** + * objectstack#36898 — keep the entries of a list answer's `changedAt` that + * parse with the spec's own rule (`GetMetaItemsResponseSchema.changedAt`, an + * ISO-8601 instant), one entry at a time: an entry that does not parse is not + * a time this client can read, so its item has no change time — what absence + * already means — and the others stand. + */ +function readChangedAt(raw: unknown): Record | undefined { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined; + const out: Record = {}; + for (const [name, at] of Object.entries(raw as Record)) { + if (typeof at !== 'string') continue; + if (GetMetaItemsResponseSchema.safeParse({ type: 'list', items: [], changedAt: { [name]: at } }).success) out[name] = at; + } + return out; +} + /** * A pending DRAFT metadata item (ADR-0033), as returned by {@link MetadataClient.listDrafts}. * Light header — no body — carrying the owning package so the console can group @@ -1201,8 +1225,9 @@ export class MetadataClient { /** * The same list read as {@link list}, with what the server serves beside - * the items (objectui#12349): today that is the automation engine's - * `registrations` on a `flow` list — see {@link MetadataListAnswer}. + * the items (objectui#12349): the automation engine's `registrations` on a + * `flow` list and each item's `changedAt` (objectstack#36898) — see + * {@link MetadataListAnswer}. * * One request for both methods: `list` is this read with the items picked * out, so a caller asking both at once shares one in-flight GET. @@ -1221,7 +1246,12 @@ export class MetadataClient { if (Array.isArray(data)) return { items: data as T[] }; if (data && Array.isArray((data as { items?: unknown[] }).items)) { const registrations = readRegistrations((data as { registrations?: unknown }).registrations); - return { items: (data as { items: T[] }).items, ...(registrations ? { registrations } : {}) }; + const changedAt = readChangedAt((data as { changedAt?: unknown }).changedAt); + return { + items: (data as { items: T[] }).items, + ...(registrations ? { registrations } : {}), + ...(changedAt ? { changedAt } : {}), + }; } return { items: [] }; }); diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index b9d885a8540..97c3edf13b6 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4054,6 +4054,13 @@ const STUDIO_EN: Record = { 'engine.list.sort.name.desc': 'API name (Z–A)', 'engine.list.sort.label.asc': 'Label (A–Z)', 'engine.list.sort.label.desc': 'Label (Z–A)', + 'engine.list.sort.changed.asc': 'Modified (oldest first)', + 'engine.list.sort.changed.desc': 'Modified (newest first)', + 'engine.list.col.changedAt': 'Modified', + 'engine.list.draftMark.human': 'Unpublished changes', + 'engine.list.draftMark.humanTitle': 'This item has a draft nobody has published yet. Publish or discard it from the item.', + 'engine.list.draftMark.ai': 'Unpublished AI changes', + 'engine.list.draftMark.aiTitle': 'The AI assistant drafted changes to this item that are not published yet. Review them on the item.', 'engine.package.writableRequired': 'Pick or create a writable base (package) first — this item cannot be authored into a read-only code package.', 'engine.list.source.artifact': 'Artifact', 'engine.list.source.runtime': 'Runtime', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 27012b6511b..26177bb33b3 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3601,6 +3601,13 @@ const STUDIO_ZH: Record = { 'engine.list.sort.name.desc': 'API 名称(Z–A)', 'engine.list.sort.label.asc': '显示名(A–Z)', 'engine.list.sort.label.desc': '显示名(Z–A)', + 'engine.list.sort.changed.asc': '修改时间(最早在前)', + 'engine.list.sort.changed.desc': '修改时间(最新在前)', + 'engine.list.col.changedAt': '修改时间', + 'engine.list.draftMark.human': '有未发布的改动', + 'engine.list.draftMark.humanTitle': '此项有尚未发布的草稿,可在详情里发布或放弃。', + 'engine.list.draftMark.ai': 'AI 的改动未发布', + 'engine.list.draftMark.aiTitle': 'AI 助手对此项的改动还是草稿,尚未发布,可在详情里查看。', 'engine.list.source.artifact': '代码包', 'engine.list.source.runtime': '运行时', 'engine.list.source.artifactDesc': '由代码包提供',