diff --git a/.changeset/38983-chat-review-card-publish.md b/.changeset/38983-chat-review-card-publish.md new file mode 100644 index 00000000000..c15400a0668 --- /dev/null +++ b/.changeset/38983-chat-review-card-publish.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): the chat's draft review card publishes a draft, pinned to the version the turn saved + +Clause-②: yes (widening) +Metadata-protocol: added + +Widened: `DraftReviewItemSchema` (`@objectstack/spec/ai`, the row of the `data-draft-review` stream part) gains the optional `version`, the draft's version token as the turn's last save of it wrote it (the save receipt's `version`). `DraftReviewCardProps` and `ChatbotEnhancedProps` gain the optional `onPublishDraft`, and `@object-ui/plugin-chatbot` exports the type `DraftReviewPublishResult`; the card's Publish strings are added to every shipped locale pack. + +The contract that nothing is published from the chat changes. The review card under an ask turn's answer now carries a Publish button per draft: one click publishes that one draft as the signed-in person, through the item's own publish (`POST /meta/:type/:name/publish?package=`), with the row's `version` sent as the body's `draftVersion`. A draft changed after the turn saved it is refused `409 METADATA_CONFLICT`, nothing is published, and the row says the draft changed since the turn. Any other refusal (a member who may not publish gets `PERMISSION_DENIED`) is shown on the row with the platform's code and sentence. Publish is offered only on a row that carries a `version` and whose verdict is `publishable`; a refused, withheld or unversioned row shows it disabled with the reason and is published in Studio through the review links, as before. The agent is given no publish: the click is always the person's. Nothing is discarded from the chat. + +`verdictWithheld`'s description now also covers a draft the door left unjudged under a bound such as `MAX_RECORDS_EXCEEDED`, not only a verdict the person may not read; its shape is unchanged. + +A host that fills the `data-draft-review` part must state each row's `version` for the button to be enabled; a part without it draws the card as before, with Publish disabled. + +Why the protocol line reads added: `DraftReviewItem` is on the authorable surface the ratchet records (`packages/spec/authorable-surface/ai.json`), and `version` is a key that enters it. Nothing a released version accepts is refused now. diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index 7495729c189..63b28e7a38c 100644 --- a/content/docs/frontend/plugins/plugin-chatbot.mdx +++ b/content/docs/frontend/plugins/plugin-chatbot.mdx @@ -627,17 +627,20 @@ itself; a part the schema refuses draws nothing. ```tsx import { DraftReviewCard } from '@object-ui/plugin-chatbot'; -import type { DraftReviewListParsed } from '@objectstack/spec/ai'; +import type { DraftReviewPublishResult } from '@object-ui/plugin-chatbot'; +import type { DraftReviewItemParsed, DraftReviewListParsed } from '@objectstack/spec/ai'; -export function TurnDrafts({ review, navigate }: { +export function TurnDrafts({ review, navigate, publish }: { review: DraftReviewListParsed; navigate: (path: string) => void; + publish: (draft: DraftReviewItemParsed) => Promise; }) { return ( `/_console${path}`} // the router's basename, for a new tab + onPublishDraft={publish} // one draft, as the person, pinned to its version /> ); } @@ -649,7 +652,15 @@ export function TurnDrafts({ review, navigate }: { by the save rather than at the turn's end says "checked when saved". - Rows are grouped by package, in save order; each package has one "Review and publish" link to its Changes drawer. `omitted` shows as "+N more". -- The card has no publish and no discard control: a person publishes or +- With `onPublishDraft`, each row has a Publish button that publishes that one + draft as the signed-in person. The host sends the item's own publish with + the row's `version` as the body's `draftVersion`, so a draft changed since + the turn is refused (`409 METADATA_CONFLICT`) and nothing is published. The + button is enabled only on a row with a `version` and a publishable verdict; + any other row shows it disabled with the reason. The row keeps the result: + "Published", "Changed since this turn", or the platform's refusal with its + code. The Console's chat pane passes a host that does exactly this. + Without the prop the card has no publish control. It never discards: a person discards in Studio, through the links. - A plain click on a link calls `onOpenReviewLink` with the Console path; a modified or middle click keeps the browser's own behaviour, on the href diff --git a/content/docs/references/ai/draft-review.mdx b/content/docs/references/ai/draft-review.mdx index 9f8237f9f8d..90be9d4dab6 100644 --- a/content/docs/references/ai/draft-review.mdx +++ b/content/docs/references/ai/draft-review.mdx @@ -32,8 +32,10 @@ draws them in a card under the answer. draft — `publishable` is "no refusal", `refusals` are what a publish would refuse it on and `advisories` are findings that do not block it — read as the person who asked. `null` when no verdict was read: `verdictWithheld` - then says why the person may not read one, or `verdictError` that reading - it failed. Both carry the door's `{ code, message, status }`. + then says why the door gave none (the person may not read one, or the door + left the draft unjudged under a bound such as `MAX_RECORDS_EXCEEDED`; the + `message` says which), or `verdictError` that reading it failed. Both carry + the door's `{ code, message, status }`. - `verdictRead` says when the verdict was read: `turn-end`, after the turn's last save, or `save`, by the save that wrote this draft (a later save in the same turn can change it). @@ -42,13 +44,25 @@ draws them in a card under the answer. `studioItemReviewLink` in `@objectstack/types`): `changes`, the package's Changes drawer, where it is published, and `item`, the draft's own review. Both are Console paths, so each starts with one `/`. - -## What the card does not do - -Nothing is published or discarded from the chat: a person publishes in -Studio, through the review routes, as for any draft. The part is drawn live -only: it is not stored with the message, so a conversation reloaded from -history shows no card. +- `version` is the draft's version token as the turn's last save of it + wrote it (the save receipt's `version`), when the producer states one. + +## What the card publishes + +A person may publish a listed draft from the chat, one draft per click, as +the person signed in: the card sends that draft's own publish +(`POST /meta/:type/:name/publish?package=`) with `version` as the body's +`draftVersion` (`PublishMetaItemRequestSchema.draftVersion`). The pin is +what makes the click mean "publish what the card shows": a draft changed +after the turn saved it is refused `409 METADATA_CONFLICT` and nothing is +published. So the card offers Publish only on a row that carries a +`version` and whose `verdict` is `publishable`; any other row is published +in Studio, through the review routes, as for any draft. The agent is given +no publish: the click is always the person's. Nothing is discarded from the +chat. + +The part is drawn live only: it is not stored with the message, so a +conversation reloaded from history shows no card. **Source:** `packages/spec/src/ai/draft-review.zod.ts` @@ -77,10 +91,11 @@ const result = DraftReviewItemSchema.parse(data); | **package** | `string` | ✅ | The package the draft was saved into | | **label** | `string` | optional | The draft's display label, when it has one | | **verdict** | `{ publishable: boolean; refusals: object[]; advisories: object[] } \| null` | ✅ | The door's `list_drafts` verdict, read as the person who asked; `null` when none was read (see `verdictWithheld` and `verdictError`) | -| **verdictWithheld** | `{ code: string; message: string; status: integer }` | optional | Why the person may not read a verdict, when `verdict` is `null` for that reason | +| **verdictWithheld** | `{ code: string; message: string; status: integer }` | optional | Why the door gave no verdict, when `verdict` is `null` for that reason: the person may not read it, or the door left the draft unjudged under a bound such as `MAX_RECORDS_EXCEEDED`; the `message` says which | | **verdictError** | `{ code: string; message: string; status: integer }` | optional | That reading the verdict failed, when `verdict` is `null` for that reason | | **verdictRead** | `Enum<'turn-end' \| 'save'>` | ✅ | When the verdict was read: `turn-end`, after the turn's last save, or `save`, by the save that wrote this draft | | **review** | `{ changes: string; item: string }` | ✅ | | +| **version** | `string` | optional | The draft's version token as the turn's last save of it wrote it (the save receipt's `version`). The card's Publish sends it as the publish body's `draftVersion`, so a draft changed since is refused 409 `METADATA_CONFLICT`, never published; absent, the row offers no Publish in the chat | ### Nested Shape: `DraftReviewItem.verdict` @@ -146,10 +161,11 @@ const result = DraftReviewItemSchema.parse(data); | **package** | `string` | ✅ | The package the draft was saved into | | **label** | `string` | optional | The draft's display label, when it has one | | **verdict** | `{ publishable: boolean; refusals: object[]; advisories: object[] } \| null` | ✅ | The door's `list_drafts` verdict, read as the person who asked; `null` when none was read (see `verdictWithheld` and `verdictError`) | -| **verdictWithheld** | `{ code: string; message: string; status: integer }` | optional | Why the person may not read a verdict, when `verdict` is `null` for that reason | +| **verdictWithheld** | `{ code: string; message: string; status: integer }` | optional | Why the door gave no verdict, when `verdict` is `null` for that reason: the person may not read it, or the door left the draft unjudged under a bound such as `MAX_RECORDS_EXCEEDED`; the `message` says which | | **verdictError** | `{ code: string; message: string; status: integer }` | optional | That reading the verdict failed, when `verdict` is `null` for that reason | | **verdictRead** | `Enum<'turn-end' \| 'save'>` | ✅ | When the verdict was read: `turn-end`, after the turn's last save, or `save`, by the save that wrote this draft | | **review** | `{ changes: string; item: string }` | ✅ | | +| **version** | `string` | optional | The draft's version token as the turn's last save of it wrote it (the save receipt's `version`). The card's Publish sends it as the publish body's `draftVersion`, so a draft changed since is refused 409 `METADATA_CONFLICT`, never published; absent, the row offers no Publish in the chat | --- diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index ab5bb1bb688..8dfa24785cf 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -230,6 +230,7 @@ "ai/DraftReviewItem:verdictError", "ai/DraftReviewItem:verdictRead", "ai/DraftReviewItem:verdictWithheld", + "ai/DraftReviewItem:version", "ai/DraftReviewLinks:changes", "ai/DraftReviewLinks:item", "ai/DraftReviewList:drafts", diff --git a/packages/spec/src/ai/draft-review.test.ts b/packages/spec/src/ai/draft-review.test.ts index 461d158ecc3..e319062db31 100644 --- a/packages/spec/src/ai/draft-review.test.ts +++ b/packages/spec/src/ai/draft-review.test.ts @@ -118,6 +118,16 @@ describe('DraftReviewItemSchema', () => { expect(firstIssue(DraftReviewItemSchema, { ...ROW, [key]: '' })).toMatchObject({ code: 'too_small', path: [key] }); } }); + + it('keeps the draft version the card pins its Publish to, optional, and refuses an empty or non-string one', () => { + const parsed = DraftReviewItemSchema.safeParse({ ...ROW, version: 'v-7f3a' }); + expect(parsed.success).toBe(true); + expect(parsed.data!.version).toBe('v-7f3a'); + // Absent stays absent: a row with no version is still a row (the card offers no Publish on it). + expect(DraftReviewItemSchema.safeParse(ROW).data).not.toHaveProperty('version'); + expect(firstIssue(DraftReviewItemSchema, { ...ROW, version: '' })).toMatchObject({ code: 'too_small', path: ['version'] }); + expect(firstIssue(DraftReviewItemSchema, { ...ROW, version: 7 })).toMatchObject({ code: 'invalid_type', path: ['version'] }); + }); }); describe('DraftReviewListSchema and the data part', () => { diff --git a/packages/spec/src/ai/draft-review.zod.ts b/packages/spec/src/ai/draft-review.zod.ts index 8bee29eeb75..8c1063a1c6d 100644 --- a/packages/spec/src/ai/draft-review.zod.ts +++ b/packages/spec/src/ai/draft-review.zod.ts @@ -32,8 +32,10 @@ import { strictObject } from '../shared/strict-object'; * draft — `publishable` is "no refusal", `refusals` are what a publish would * refuse it on and `advisories` are findings that do not block it — read as * the person who asked. `null` when no verdict was read: `verdictWithheld` - * then says why the person may not read one, or `verdictError` that reading - * it failed. Both carry the door's `{ code, message, status }`. + * then says why the door gave none (the person may not read one, or the door + * left the draft unjudged under a bound such as `MAX_RECORDS_EXCEEDED`; the + * `message` says which), or `verdictError` that reading it failed. Both carry + * the door's `{ code, message, status }`. * - `verdictRead` says when the verdict was read: `turn-end`, after the turn's * last save, or `save`, by the save that wrote this draft (a later save in * the same turn can change it). @@ -42,13 +44,25 @@ import { strictObject } from '../shared/strict-object'; * `studioItemReviewLink` in `@objectstack/types`): `changes`, the package's * Changes drawer, where it is published, and `item`, the draft's own review. * Both are Console paths, so each starts with one `/`. + * - `version` is the draft's version token as the turn's last save of it + * wrote it (the save receipt's `version`), when the producer states one. * - * ## What the card does not do + * ## What the card publishes * - * Nothing is published or discarded from the chat: a person publishes in - * Studio, through the review routes, as for any draft. The part is drawn live - * only: it is not stored with the message, so a conversation reloaded from - * history shows no card. + * A person may publish a listed draft from the chat, one draft per click, as + * the person signed in: the card sends that draft's own publish + * (`POST /meta/:type/:name/publish?package=`) with `version` as the body's + * `draftVersion` (`PublishMetaItemRequestSchema.draftVersion`). The pin is + * what makes the click mean "publish what the card shows": a draft changed + * after the turn saved it is refused `409 METADATA_CONFLICT` and nothing is + * published. So the card offers Publish only on a row that carries a + * `version` and whose `verdict` is `publishable`; any other row is published + * in Studio, through the review routes, as for any draft. The agent is given + * no publish: the click is always the person's. Nothing is discarded from the + * chat. + * + * The part is drawn live only: it is not stored with the message, so a + * conversation reloaded from history shows no card. */ /** @@ -133,12 +147,20 @@ export const DraftReviewItemSchema = lazySchema(() => strictObject( 'The door\'s `list_drafts` verdict, read as the person who asked; `null` when none was read ' + '(see `verdictWithheld` and `verdictError`)', ), - verdictWithheld: DraftReviewVerdictRefusalSchema.optional().describe('Why the person may not read a verdict, when `verdict` is `null` for that reason'), + verdictWithheld: DraftReviewVerdictRefusalSchema.optional().describe( + 'Why the door gave no verdict, when `verdict` is `null` for that reason: the person may not read it, or the door ' + + 'left the draft unjudged under a bound such as `MAX_RECORDS_EXCEEDED`; the `message` says which', + ), verdictError: DraftReviewVerdictRefusalSchema.optional().describe('That reading the verdict failed, when `verdict` is `null` for that reason'), verdictRead: z.enum(['turn-end', 'save']).describe( 'When the verdict was read: `turn-end`, after the turn\'s last save, or `save`, by the save that wrote this draft', ), review: DraftReviewLinksSchema, + version: z.string().min(1).optional().describe( + 'The draft\'s version token as the turn\'s last save of it wrote it (the save receipt\'s `version`). ' + + 'The card\'s Publish sends it as the publish body\'s `draftVersion`, so a draft changed since is ' + + 'refused 409 `METADATA_CONFLICT`, never published; absent, the row offers no Publish in the chat', + ), }, )); diff --git a/ui/packages/app-shell/src/console/ai/ChatPane.tsx b/ui/packages/app-shell/src/console/ai/ChatPane.tsx index 6830a401b52..e292489ab6d 100644 --- a/ui/packages/app-shell/src/console/ai/ChatPane.tsx +++ b/ui/packages/app-shell/src/console/ai/ChatPane.tsx @@ -71,6 +71,7 @@ import { useUpload } from '@object-ui/fields'; import { isSpreadsheetAttachment, uploadChatAttachments, chatAttachmentNotes } from './chatAttachments.js'; import { listLinkTarget, recordOpenTarget, nextSectionOpening } from './aiChatLinks.js'; import { documentHref } from '../../views/documentHref.js'; +import { useDraftReviewPublish } from './draftReviewPublish.js'; import { hydratedMessagesToChatMessages } from './aiChatHydration.js'; import { localizeAgentLabel, agentEmptyState, buildAgentSuggestions } from './agentCopy.js'; import { drawerSuggestions, type EmptyConversationSize } from './emptyConversationModel.js'; @@ -318,6 +319,7 @@ export function ChatPane({ [navigate, openLinksInNewTab, openInNewTab], ); const reviewLinkHref = useCallback((path: string) => documentHref(routerRootHref, path), [routerRootHref]); + const publishReviewedDraft = useDraftReviewPublish(); // The pane's root, measured by the composer-draft handoff below. const paneRef = useRef(null); @@ -850,6 +852,7 @@ export function ChatPane({ onOpenList={openList} onOpenReviewLink={openReviewLink} reviewLinkHref={reviewLinkHref} + onPublishDraft={publishReviewedDraft} // cloud#3565 — the record-write card's three buttons and its states. onOpenRecordForm={openRecordForm} recordWriteCreateTitle={(objectLabel) => t('console.ai.recordWriteCreateTitle', { object: objectLabel })} diff --git a/ui/packages/app-shell/src/console/ai/draftReviewPublish-38983.test.ts b/ui/packages/app-shell/src/console/ai/draftReviewPublish-38983.test.ts new file mode 100644 index 00000000000..dad82a4e752 --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/draftReviewPublish-38983.test.ts @@ -0,0 +1,72 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38983 — the chat draft review card's Publish + * (`publishReviewedDraft`) makes one listed draft live through the item + * publish, pinned to the version the turn saved. A draft changed since the + * turn is refused as a conflict and published by nobody; a member who may not + * publish gets the platform's refusal, code and sentence; a refusal never + * takes the assistant's draft back; a row with no version is never sent. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { DraftReviewItemParsed } from '@objectstack/spec/ai'; +import { publishReviewedDraft } from './draftReviewPublish'; +import { draftReceiptVersion } from '../../views/metadata-admin/draftVersionGuard'; +import { draftPublishDoor } from '../../views/__tests__/draftPublishDoor-37440'; + +const PKG = 'com.acme.crm'; + +const row = (version?: string): DraftReviewItemParsed => ({ + type: 'flow', + name: 'acme_flow', + package: PKG, + verdict: { publishable: true, refusals: [], advisories: [] }, + verdictRead: 'turn-end', + review: { changes: '/studio/com.acme.crm/data?changes=review', item: '/studio/com.acme.crm/metadata/flow/acme_flow?review=1' }, + ...(version ? { version } : {}), +}); + +/** The turn's save of the draft, as the assistant made it; answers its receipt version. */ +async function turnSaved(door: ReturnType): Promise { + const version = draftReceiptVersion(await door.client.save('flow', 'acme_flow', { label: 'assistant' }, { mode: 'draft', packageId: PKG })); + expect(version).toBeTruthy(); + return version!; +} + +describe('the chat review card publishes the draft it lists, pinned to its saved version (objectstack#38983)', () => { + it('publishes the draft the turn saved, naming its package and pin', async () => { + const door = draftPublishDoor(); + const version = await turnSaved(door); + await expect(publishReviewedDraft(door.metadataClient, row(version))).resolves.toEqual({ kind: 'published' }); + expect(door.liveOf('flow', 'acme_flow', PKG)).toEqual({ label: 'assistant' }); + expect(door.calls.find(([c]) => c === 'publish')?.[3]).toEqual({ packageId: PKG, draftVersion: version }); + }); + + it('PIN: a draft another writer changed after the turn is a conflict, published by nobody and kept', async () => { + const door = draftPublishDoor(); + const version = await turnSaved(door); + door.interleave('flow', 'acme_flow', PKG, { label: 'theirs' }); + await expect(publishReviewedDraft(door.metadataClient, row(version))).resolves.toEqual({ kind: 'conflict' }); + expect(door.liveOf('flow', 'acme_flow', PKG)).toBeUndefined(); + expect(door.draftOf('flow', 'acme_flow', PKG)).toEqual({ label: 'theirs' }); + expect(door.calls.some(([c]) => c === 'reset')).toBe(false); + }); + + it("carries the platform's refusal (a member who may not publish) and never takes the draft back", async () => { + const refusal = Object.assign(new Error('You may not publish flow metadata.'), { status: 403, code: 'PERMISSION_DENIED' }); + const client = { publish: vi.fn(async () => { throw refusal; }), reset: vi.fn(), getDraft: vi.fn() }; + await expect(publishReviewedDraft(client as never, row('v-1'))).resolves.toEqual({ + kind: 'refused', + code: 'PERMISSION_DENIED', + message: 'You may not publish flow metadata.', + }); + expect(client.reset).not.toHaveBeenCalled(); + }); + + it('never sends a row with no version: an unpinned publish would promote whatever draft is pending', async () => { + const client = { publish: vi.fn(), reset: vi.fn(), getDraft: vi.fn() }; + await expect(publishReviewedDraft(client as never, row())).resolves.toEqual({ kind: 'refused' }); + expect(client.publish).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/draftReviewPublish.ts b/ui/packages/app-shell/src/console/ai/draftReviewPublish.ts new file mode 100644 index 00000000000..e42a98d383d --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/draftReviewPublish.ts @@ -0,0 +1,65 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The chat draft review card's Publish (`DraftReviewCard`'s `onPublishDraft`): + * one listed draft made live by the person who clicked, through the same item + * publish Studio's Save takes (`publishDetailSave`), pinned to the version the + * turn saved. + * + * Invariants: + * - The publish names the draft's package (`?package=`) and sends the row's + * `version` as the body's `draftVersion` + * (`PublishMetaItemRequestSchema.draftVersion`): a draft another writer + * changed after the turn is refused `409 METADATA_CONFLICT` and nothing is + * published on that writer's behalf. A row with no `version` is never sent: + * an unpinned publish would promote whatever draft is pending, not the one + * the card shows. + * - The draft is the assistant's, pending before the click, so a refusal + * never takes it back (`hadDraft` true): it stays listed under Changes. + * - The refusal is the platform's, carried to the card with its code and + * sentence (a member who may not publish sees `PERMISSION_DENIED`), never + * replaced or hidden. + */ + +import { useCallback } from 'react'; +import type { DraftReviewItemParsed } from '@objectstack/spec/ai'; +import type { MetadataClient } from '@object-ui/data-objectstack'; +import type { DraftReviewPublishResult } from '@object-ui/plugin-chatbot'; +import { publishDetailSave } from '../../views/metadata-admin/detailSaveAtOnce.js'; +import { isDraftVersionConflict } from '../../views/metadata-admin/draftVersionGuard.js'; +import { useMetadataClient } from '../../views/metadata-admin/useMetadata.js'; + +/** The refusal as the card shows it: the platform's code and sentence, when it stated them. */ +function refusalOf(error: unknown): DraftReviewPublishResult { + const raw = error as { code?: unknown; message?: unknown } | null | undefined; + return { + kind: 'refused', + ...(typeof raw?.code === 'string' && raw.code ? { code: raw.code } : {}), + ...(typeof raw?.message === 'string' && raw.message ? { message: raw.message } : {}), + }; +} + +/** Publish one row of the review card, pinned to its saved version (see the module docblock). */ +export async function publishReviewedDraft( + client: Pick, + draft: DraftReviewItemParsed, +): Promise { + if (!draft.version) { + // Never sent unpinned; the card offers no Publish on such a row. + return { kind: 'refused' }; + } + const outcome = await publishDetailSave( + client, + { type: draft.type, name: draft.name, packageId: draft.package, draftVersion: draft.version }, + true, + ); + if (outcome.kind === 'published') return { kind: 'published' }; + if (outcome.kind === 'refused' && isDraftVersionConflict(outcome.error)) return { kind: 'conflict' }; + return outcome.kind === 'refused' ? refusalOf(outcome.error) : { kind: 'refused' }; +} + +/** The review card's `onPublishDraft`, on the app's metadata client. */ +export function useDraftReviewPublish(): (draft: DraftReviewItemParsed) => Promise { + const client = useMetadataClient(); + return useCallback((draft: DraftReviewItemParsed) => publishReviewedDraft(client, draft), [client]); +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index f026a7d9694..d1f0e828471 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5074,6 +5074,18 @@ const ar = { more_few: 'و{{count}} أخرى', more_many: 'و{{count}} أخرى', more_other: 'و{{count}} أخرى', + hintPublish: 'لم يُنشر شيء بعد. انشر مسودة هنا، أو راجع المسودات في App Studio.', + publish: 'نشر', + publishing: 'جارٍ النشر…', + publishAria: 'نشر المسودة {{name}}', + published: 'تم النشر', + publishConflict: 'تغيّرت بعد هذه الجولة، ولم تُنشر. راجعها في App Studio.', + publishInStudio: 'انشر هذه المسودة في App Studio.', + publishNeedsVerdict: 'لم يُقرأ أي حكم لهذه المسودة، لذا لا يمكن نشرها هنا.', + publishBlocked: 'أصلح المشكلات قبل النشر.', + publishRefusedCode: 'لم تُنشر ({{code}}): {{message}}', + publishRefused: 'لم تُنشر: {{message}}', + publishRefusedBare: 'لم تُنشر.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 76b505ec64a..3a65b5e3d72 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4692,6 +4692,18 @@ const de = { more: '+{{count}} weitere', more_one: '+{{count}} weiterer', more_other: '+{{count}} weitere', + hintPublish: 'Noch ist nichts veröffentlicht. Veröffentlichen Sie einen Entwurf hier oder prüfen Sie die Entwürfe in App Studio.', + publish: 'Veröffentlichen', + publishing: 'Wird veröffentlicht…', + publishAria: 'Den Entwurf {{name}} veröffentlichen', + published: 'Veröffentlicht', + publishConflict: 'Seit diesem Schritt geändert, nicht veröffentlicht. Prüfen Sie ihn in App Studio.', + publishInStudio: 'Veröffentlichen Sie diesen Entwurf in App Studio.', + publishNeedsVerdict: 'Für diesen Entwurf wurde kein Urteil gelesen, daher kann er hier nicht veröffentlicht werden.', + publishBlocked: 'Beheben Sie die Probleme vor dem Veröffentlichen.', + publishRefusedCode: 'Nicht veröffentlicht ({{code}}): {{message}}', + publishRefused: 'Nicht veröffentlicht: {{message}}', + publishRefusedBare: 'Nicht veröffentlicht.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index a12e5f3b8da..f3e35ec1e6e 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5631,6 +5631,18 @@ const en = { more: '+{{count}} more', more_one: '+{{count}} more', more_other: '+{{count}} more', + hintPublish: 'Nothing is published yet. Publish a draft here, or review the drafts in App Studio.', + publish: 'Publish', + publishing: 'Publishing…', + publishAria: 'Publish the draft {{name}}', + published: 'Published', + publishConflict: 'Changed since this turn, not published. Review it in App Studio.', + publishInStudio: 'Publish this draft in App Studio.', + publishNeedsVerdict: 'No verdict was read for this draft, so it cannot be published here.', + publishBlocked: 'Fix the problems before publishing.', + publishRefusedCode: 'Not published ({{code}}): {{message}}', + publishRefused: 'Not published: {{message}}', + publishRefusedBare: 'Not published.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 6c8ff1706b5..94a699fadbd 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4788,6 +4788,18 @@ const es = { more_one: '+{{count}} más', more_many: '+{{count}} más', more_other: '+{{count}} más', + hintPublish: 'Todavía no se ha publicado nada. Publique un borrador aquí o revise los borradores en App Studio.', + publish: 'Publicar', + publishing: 'Publicando…', + publishAria: 'Publicar el borrador {{name}}', + published: 'Publicado', + publishConflict: 'Cambió después de este turno; no se publicó. Revíselo en App Studio.', + publishInStudio: 'Publique este borrador en App Studio.', + publishNeedsVerdict: 'No se leyó ningún veredicto para este borrador, así que no se puede publicar aquí.', + publishBlocked: 'Corrija los problemas antes de publicar.', + publishRefusedCode: 'No publicado ({{code}}): {{message}}', + publishRefused: 'No publicado: {{message}}', + publishRefusedBare: 'No publicado.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 6e6689e3775..26c89c4369e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4784,6 +4784,18 @@ const fr = { more_one: '+{{count}} autre', more_many: '+{{count}} autres', more_other: '+{{count}} autres', + hintPublish: 'Rien n\'est encore publié. Publiez un brouillon ici, ou vérifiez les brouillons dans App Studio.', + publish: 'Publier', + publishing: 'Publication…', + publishAria: 'Publier le brouillon {{name}}', + published: 'Publié', + publishConflict: 'Modifié depuis ce tour, non publié. Vérifiez-le dans App Studio.', + publishInStudio: 'Publiez ce brouillon dans App Studio.', + publishNeedsVerdict: 'Aucun verdict n\'a été lu pour ce brouillon : il ne peut pas être publié ici.', + publishBlocked: 'Corrigez les problèmes avant de publier.', + publishRefusedCode: 'Non publié ({{code}}) : {{message}}', + publishRefused: 'Non publié : {{message}}', + publishRefusedBare: 'Non publié.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 2ad40b73947..5b8903b910b 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4694,6 +4694,18 @@ const ja = { more: 'ほか {{count}} 件', more_one: 'ほか {{count}} 件', more_other: 'ほか {{count}} 件', + hintPublish: 'まだ何も公開されていません。ここで下書きを公開するか、App Studio で確認してください。', + publish: '公開', + publishing: '公開中…', + publishAria: '下書き {{name}} を公開', + published: '公開しました', + publishConflict: 'このターンの後に変更されたため、公開していません。App Studio で確認してください。', + publishInStudio: 'この下書きは App Studio で公開してください。', + publishNeedsVerdict: 'この下書きの判定を読み取れなかったため、ここでは公開できません。', + publishBlocked: '問題を解決してから公開してください。', + publishRefusedCode: '公開されませんでした({{code}}): {{message}}', + publishRefused: '公開されませんでした: {{message}}', + publishRefusedBare: '公開されませんでした。', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 4e04adcc9fe..b72c3c82d91 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4691,6 +4691,18 @@ const ko = { more: '외 {{count}}개', more_one: '외 {{count}}개', more_other: '외 {{count}}개', + hintPublish: '아직 게시된 것은 없습니다. 여기서 초안을 게시하거나 App Studio에서 검토하세요.', + publish: '게시', + publishing: '게시 중…', + publishAria: '초안 {{name}} 게시', + published: '게시됨', + publishConflict: '이 턴 이후 변경되어 게시하지 않았습니다. App Studio에서 검토하세요.', + publishInStudio: '이 초안은 App Studio에서 게시하세요.', + publishNeedsVerdict: '이 초안의 판정을 읽지 못해 여기서 게시할 수 없습니다.', + publishBlocked: '게시하기 전에 문제를 해결하세요.', + publishRefusedCode: '게시되지 않음 ({{code}}): {{message}}', + publishRefused: '게시되지 않음: {{message}}', + publishRefusedBare: '게시되지 않았습니다.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index a9d836ce3ab..b907f31efc4 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4783,6 +4783,18 @@ const pt = { more_one: '+{{count}} outro', more_many: '+{{count}} outros', more_other: '+{{count}} outros', + hintPublish: 'Nada foi publicado ainda. Publique um rascunho aqui ou revise os rascunhos no App Studio.', + publish: 'Publicar', + publishing: 'Publicando…', + publishAria: 'Publicar o rascunho {{name}}', + published: 'Publicado', + publishConflict: 'Alterado depois desta rodada; não foi publicado. Revise-o no App Studio.', + publishInStudio: 'Publique este rascunho no App Studio.', + publishNeedsVerdict: 'Nenhum veredito foi lido para este rascunho, então ele não pode ser publicado aqui.', + publishBlocked: 'Corrija os problemas antes de publicar.', + publishRefusedCode: 'Não publicado ({{code}}): {{message}}', + publishRefused: 'Não publicado: {{message}}', + publishRefusedBare: 'Não publicado.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 581c33ab50e..3fc77dee6a6 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4893,6 +4893,18 @@ const ru = { more_few: 'ещё {{count}}', more_many: 'ещё {{count}}', more_other: 'ещё {{count}}', + hintPublish: 'Пока ничего не опубликовано. Опубликуйте черновик здесь или проверьте черновики в App Studio.', + publish: 'Опубликовать', + publishing: 'Публикация…', + publishAria: 'Опубликовать черновик {{name}}', + published: 'Опубликован', + publishConflict: 'Изменён после этого шага, не опубликован. Проверьте его в App Studio.', + publishInStudio: 'Опубликуйте этот черновик в App Studio.', + publishNeedsVerdict: 'Для этого черновика не получен вердикт, поэтому его нельзя опубликовать здесь.', + publishBlocked: 'Исправьте проблемы перед публикацией.', + publishRefusedCode: 'Не опубликован ({{code}}): {{message}}', + publishRefused: 'Не опубликован: {{message}}', + publishRefusedBare: 'Не опубликован.', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index e2de293d0ce..5bad88ccb01 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4946,6 +4946,18 @@ const zh = { more: '还有 {{count}} 个', more_one: '还有 {{count}} 个', more_other: '还有 {{count}} 个', + hintPublish: '还没有发布。可以在这里发布草稿,或在应用搭建中审阅。', + publish: '发布', + publishing: '正在发布…', + publishAria: '发布草稿 {{name}}', + published: '已发布', + publishConflict: '本轮之后草稿有改动,未发布。请在应用搭建中审阅。', + publishInStudio: '请在应用搭建中发布这个草稿。', + publishNeedsVerdict: '这个草稿没有读到判定,不能在这里发布。', + publishBlocked: '请先解决问题再发布。', + publishRefusedCode: '未发布({{code}}):{{message}}', + publishRefused: '未发布:{{message}}', + publishRefusedBare: '未发布。', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 4fce3fa8e8d..17422dbbc61 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4946,6 +4946,18 @@ const zhHant = { more: '還有 {{count}} 個', more_one: '還有 {{count}} 個', more_other: '還有 {{count}} 個', + hintPublish: '還沒有釋出。可以在這裡釋出草稿,或在應用搭建中審閱。', + publish: '釋出', + publishing: '正在釋出…', + publishAria: '釋出草稿 {{name}}', + published: '已釋出', + publishConflict: '本輪之後草稿有改動,未釋出。請在應用搭建中審閱。', + publishInStudio: '請在應用搭建中釋出這個草稿。', + publishNeedsVerdict: '這個草稿沒有讀到判定,不能在這裡釋出。', + publishBlocked: '請先解決問題再發布。', + publishRefusedCode: '未釋出({{code}}):{{message}}', + publishRefused: '未釋出:{{message}}', + publishRefusedBare: '未釋出。', }, // The Continue control under an answer the server says may be carried on. continueTurn: { diff --git a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx index 47f58c616c4..af960790c75 100644 --- a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx +++ b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx @@ -300,6 +300,7 @@ const ChatbotEnhanced = React.forwardRef( onOpenList, onOpenReviewLink, reviewLinkHref, + onPublishDraft, surfaceContextLabel, surfaceContextTitle, promptInputHeaderSlot, @@ -1068,12 +1069,13 @@ const ChatbotEnhanced = React.forwardRef( {!isUser && message.recordCitations ? ( ) : null} - {/* The drafts the turn saved; reviewed and published in Studio, never here. */} + {/* The drafts the turn saved; a person publishes one here (pinned to its version) or in Studio. */} {!isUser && message.draftReview ? ( ) : null} {!isUser && sources.length > 0 ? ( diff --git a/ui/packages/plugin-chatbot/src/__tests__/DraftReviewCard-38048.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/DraftReviewCard-38048.test.tsx index b98bc06fdbe..60687b6f8d4 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/DraftReviewCard-38048.test.tsx +++ b/ui/packages/plugin-chatbot/src/__tests__/DraftReviewCard-38048.test.tsx @@ -15,7 +15,12 @@ * - N rows, the right badges, the right links with accessible names. * - A plain click goes through `onOpenReviewLink`; a modified click keeps the * browser's own; the href is the host's `reviewLinkHref`. - * - The card has no publish and no discard control. + * - With no host `onPublishDraft` the card has no publish and no discard + * control. + * - objectstack#38983 — with one, a row with a `version` and a `publishable` + * verdict publishes that one draft through it; any other row shows Publish + * disabled with the reason; each result (published, conflict, refused with + * the platform's code) stays on its row. * - A part the parse refuses draws nothing and does not throw, and the CONTROL * (the same turn with a part that parses) draws the card. * - A turn without the part renders as before. @@ -23,12 +28,13 @@ */ import '@testing-library/jest-dom/vitest'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { DRAFT_REVIEW_PART_TYPE } from '@objectstack/spec/ai'; +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { DRAFT_REVIEW_PART_TYPE, type DraftReviewItemParsed } from '@objectstack/spec/ai'; import { ChatbotEnhanced } from '../ChatbotEnhanced'; import { extractDraftReview, storedAnswerData, uiMessageToChatMessage } from '../mapMessages'; import { STORED_ANSWER_DATA_PARTS } from '../toolResultParsers'; import { groupDraftsByPackage } from '../chat/draftReviewGroups'; +import type { DraftReviewPublishResult } from '../chat/DraftReviewCard'; afterEach(() => { cleanup(); @@ -92,7 +98,14 @@ const turn = (parts: unknown[]) => const question = { id: 'u1', role: 'user' as const, content: 'Build me invoicing.' }; -function renderTurn(parts: unknown[], props: { onOpenReviewLink?: (path: string) => void; reviewLinkHref?: (path: string) => string } = {}) { +function renderTurn( + parts: unknown[], + props: { + onOpenReviewLink?: (path: string) => void; + reviewLinkHref?: (path: string) => string; + onPublishDraft?: (draft: DraftReviewItemParsed) => Promise; + } = {}, +) { return render(); } @@ -162,7 +175,7 @@ describe('objectstack#38048 — the card under the answer', () => { expect(within(card).getByTestId('draft-review-omitted')).toHaveTextContent('+4 more'); }); - it('has no publish and no discard control: every control is a review link', () => { + it('with no host onPublishDraft, has no publish and no discard control: every control is a review link', () => { renderTurn([draftReviewPart(LIST)]); const card = screen.getByTestId('draft-review-card'); expect(within(card).queryAllByRole('button')).toHaveLength(0); @@ -214,3 +227,107 @@ describe('objectstack#38048 — live only', () => { expect(storedAnswerData([draftReviewPart(LIST)] as never)).toEqual({}); }); }); + +/** LIST with versions: the publishable invoice and the refused flow carry one, the withheld view too. */ +const VERSIONED = { + ...LIST, + drafts: [ + { ...LIST.drafts[0], version: 'v-invoice-3' }, + { ...LIST.drafts[1], version: 'v-flow-1' }, + { ...LIST.drafts[2], version: 'v-view-2' }, + ], +}; + +/** The rows of a rendered card, by draft name. */ +function rowsByName() { + const card = screen.getByTestId('draft-review-card'); + const rows = within(card).getAllByTestId('draft-review-row'); + const byName = (text: string) => rows.find((row) => row.textContent?.includes(text))!; + return { card, invoice: byName('Invoice'), flow: byName('close_invoices'), view: byName('acme_invoice_list') }; +} + +describe('objectstack#38983 — Publish on the card, pinned to the version the turn saved', () => { + it('publishes the one publishable, versioned draft through onPublishDraft and shows it published', async () => { + const onPublishDraft = vi.fn(async () => ({ kind: 'published' }) as const); + renderTurn([draftReviewPart(VERSIONED)], { onPublishDraft }); + const { card, invoice } = rowsByName(); + expect(card).toHaveTextContent('Publish a draft here, or review the drafts in App Studio.'); + + const button = within(invoice).getByRole('button', { name: 'Publish the draft Invoice' }); + expect(button).toBeEnabled(); + await act(async () => { + fireEvent.click(button); + }); + expect(onPublishDraft).toHaveBeenCalledTimes(1); + expect(onPublishDraft).toHaveBeenCalledWith( + expect.objectContaining({ type: 'object', name: 'acme_invoice', package: 'acme', version: 'v-invoice-3' }), + ); + expect(within(invoice).getByTestId('draft-review-publish-result')).toHaveAttribute('data-result', 'published'); + expect(within(invoice).queryByTestId('draft-review-publish')).toBeNull(); + }); + + it('offers no Publish on a row that is refused, withheld or carries no version, and says why', () => { + const onPublishDraft = vi.fn(async () => ({ kind: 'published' }) as const); + const noVersion = { ...VERSIONED, drafts: [LIST.drafts[0], VERSIONED.drafts[1], VERSIONED.drafts[2]] }; + renderTurn([draftReviewPart(noVersion)], { onPublishDraft }); + const { invoice, flow, view } = rowsByName(); + + const cases = [ + [invoice, 'noVersion', 'Publish this draft in App Studio.'], + [flow, 'refusals', 'Fix the problems before publishing.'], + [view, 'withheld', 'No verdict was read for this draft, so it cannot be published here.'], + ] as const; + for (const [row, block, reason] of cases) { + const button = within(row).getByTestId('draft-review-publish'); + expect(button).toBeDisabled(); + expect(button).toHaveAttribute('data-block', block); + expect(button).toHaveAttribute('title', reason); + expect(button.getAttribute('aria-label')).toContain(reason); + fireEvent.click(button); + } + expect(onPublishDraft).not.toHaveBeenCalled(); + }); + + it('shows a draft changed since the turn as a conflict, not published, with no second Publish', async () => { + const onPublishDraft = vi.fn(async () => ({ kind: 'conflict' }) as const); + renderTurn([draftReviewPart(VERSIONED)], { onPublishDraft }); + const { invoice } = rowsByName(); + await act(async () => { + fireEvent.click(within(invoice).getByTestId('draft-review-publish')); + }); + const result = within(invoice).getByTestId('draft-review-publish-result'); + expect(result).toHaveAttribute('data-result', 'conflict'); + expect(result).toHaveTextContent('Changed since this turn, not published.'); + expect(within(invoice).queryByTestId('draft-review-publish')).toBeNull(); + }); + + it('shows the platform\'s refusal with its code, and keeps Publish for another try', async () => { + const onPublishDraft = vi.fn(async () => ({ + kind: 'refused', + code: 'PERMISSION_DENIED', + message: 'You may not publish object metadata.', + }) as const); + renderTurn([draftReviewPart(VERSIONED)], { onPublishDraft }); + const { invoice } = rowsByName(); + await act(async () => { + fireEvent.click(within(invoice).getByTestId('draft-review-publish')); + }); + const result = within(invoice).getByTestId('draft-review-publish-result'); + expect(result).toHaveAttribute('data-result', 'refused'); + expect(result).toHaveAttribute('data-code', 'PERMISSION_DENIED'); + expect(result).toHaveTextContent('Not published (PERMISSION_DENIED): You may not publish object metadata.'); + expect(within(invoice).getByTestId('draft-review-publish')).toBeEnabled(); + }); + + it('shows a host that throws as a refusal, never swallows it', async () => { + const onPublishDraft = vi.fn(async () => { + throw Object.assign(new Error('Network down'), { code: 'NETWORK_ERROR' }); + }); + renderTurn([draftReviewPart(VERSIONED)], { onPublishDraft }); + const { invoice } = rowsByName(); + await act(async () => { + fireEvent.click(within(invoice).getByTestId('draft-review-publish')); + }); + expect(within(invoice).getByTestId('draft-review-publish-result')).toHaveTextContent('Not published (NETWORK_ERROR): Network down'); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/chat/DraftReviewCard.tsx b/ui/packages/plugin-chatbot/src/chat/DraftReviewCard.tsx index f2a4a9295a8..1755e11e790 100644 --- a/ui/packages/plugin-chatbot/src/chat/DraftReviewCard.tsx +++ b/ui/packages/plugin-chatbot/src/chat/DraftReviewCard.tsx @@ -16,17 +16,53 @@ * order, and each package carries one "Review and publish" link to its Changes * drawer. `omitted` is shown as "+N more". * - * The card publishes and discards nothing: a person does that in Studio, - * through the links. It receives only the list `extractDraftReview` lifted and - * draws it as it is. + * With a host `onPublishDraft`, a row also carries a Publish button: one + * click publishes that one draft as the person signed in, pinned to the + * version the turn saved (`version`, sent as the publish's `draftVersion`), so + * a draft changed since the turn is refused as a conflict and nothing is + * published. Publish is offered only on a row with a `version` and a + * `publishable` verdict; any other row shows it disabled with the reason, and + * is published in Studio through the links. Each click's result stays on its + * row: published, refused with the platform's code and sentence, or changed + * since the turn. The agent is given no publish: the click is the person's. + * Nothing is discarded from the card. It receives only the list + * `extractDraftReview` lifted and draws it as it is. */ import * as React from 'react'; import { Badge, cn } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; -import { FileClockIcon } from 'lucide-react'; +import { CheckIcon, FileClockIcon } from 'lucide-react'; import type { DraftReviewItemParsed, DraftReviewListParsed } from '@objectstack/spec/ai'; import { groupDraftsByPackage } from './draftReviewGroups'; +/** + * What one Publish click did, as the host's `onPublishDraft` reports it. + * `conflict` is the draft pin's refusal (`409 METADATA_CONFLICT`): the draft + * changed after the turn saved it, and nothing was published. `refused` is + * any other refusal, carried as the platform stated it, so the card shows it + * instead of hiding it. + */ +export type DraftReviewPublishResult = + | { kind: 'published' } + | { kind: 'conflict' } + | { kind: 'refused'; code?: string; message?: string }; + +/** A row's Publish state: in flight, or the last click's result. */ +type RowPublishState = { kind: 'publishing' } | DraftReviewPublishResult; + +/** Why a row offers no Publish, or `null` when it does. */ +type PublishBlock = 'noVersion' | 'withheld' | 'refusals' | null; + +function publishBlock(draft: DraftReviewItemParsed): PublishBlock { + if (!draft.version) return 'noVersion'; + if (!draft.verdict) return 'withheld'; + if (!draft.verdict.publishable) return 'refusals'; + return null; +} + +/** One row's key: a draft is unique by package, type and name. */ +const rowKey = (draft: DraftReviewItemParsed) => `${draft.package}\u0000${draft.type}\u0000${draft.name}`; + export interface DraftReviewCardProps { /** The turn's draft review list, as `extractDraftReview` read it. */ review: DraftReviewListParsed; @@ -38,6 +74,13 @@ export interface DraftReviewCardProps { onOpenReviewLink?: (path: string) => void; /** The anchor href for a review route, e.g. with the router's basename joined. Absent, the path itself. */ reviewLinkHref?: (path: string) => string; + /** + * Publish one listed draft as the signed-in person, pinned to its `version` + * (the publish body's `draftVersion`), and report what happened. Called only + * for a row that carries a `version` and a `publishable` verdict. Absent, + * the card offers no Publish and every draft is published in Studio. + */ + onPublishDraft?: (draft: DraftReviewItemParsed) => Promise; className?: string; } @@ -50,10 +93,98 @@ const LINK_CLASS = 'shrink-0 rounded-sm font-medium text-primary underline-offset-2 hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-ring'; /** The drafts the turn saved, with their verdicts and Studio review links. */ -export function DraftReviewCard({ review, onOpenReviewLink, reviewLinkHref, className }: DraftReviewCardProps) { +export function DraftReviewCard({ review, onOpenReviewLink, reviewLinkHref, onPublishDraft, className }: DraftReviewCardProps) { const { t } = useObjectTranslation(); const titleId = React.useId(); const groups = groupDraftsByPackage(review.drafts); + const [publishStates, setPublishStates] = React.useState>({}); + + const publish = async (draft: DraftReviewItemParsed) => { + if (!onPublishDraft || publishBlock(draft)) return; + const key = rowKey(draft); + setPublishStates((prev) => ({ ...prev, [key]: { kind: 'publishing' } })); + let result: DraftReviewPublishResult; + try { + result = await onPublishDraft(draft); + } catch (error) { + // A host that throws instead of reporting: shown as a refusal, never swallowed. + const raw = error as { code?: unknown; message?: unknown } | null | undefined; + result = { + kind: 'refused', + ...(typeof raw?.code === 'string' ? { code: raw.code } : {}), + ...(typeof raw?.message === 'string' ? { message: raw.message } : {}), + }; + } + setPublishStates((prev) => ({ ...prev, [key]: result })); + }; + + const publishControl = (draft: DraftReviewItemParsed, shown: string) => { + if (!onPublishDraft) return null; + const state = publishStates[rowKey(draft)]; + if (state?.kind === 'published') { + return ( + + + ); + } + if (state?.kind === 'conflict') { + return ( + + {t('chatbot.draftReview.publishConflict', { defaultValue: 'Changed since this turn, not published. Review it in App Studio.' })} + + ); + } + const block = publishBlock(draft); + const publishing = state?.kind === 'publishing'; + const blockReason = + block === 'noVersion' + ? t('chatbot.draftReview.publishInStudio', { defaultValue: 'Publish this draft in App Studio.' }) + : block === 'withheld' + ? t('chatbot.draftReview.publishNeedsVerdict', { defaultValue: 'No verdict was read for this draft, so it cannot be published here.' }) + : block === 'refusals' + ? t('chatbot.draftReview.publishBlocked', { defaultValue: 'Fix the problems before publishing.' }) + : undefined; + return ( + <> + {state?.kind === 'refused' ? ( + + {state.code && state.message + ? t('chatbot.draftReview.publishRefusedCode', { + code: state.code, + message: state.message, + defaultValue: 'Not published ({{code}}): {{message}}', + }) + : state.message || state.code + ? t('chatbot.draftReview.publishRefused', { + message: state.message || state.code, + defaultValue: 'Not published: {{message}}', + }) + : t('chatbot.draftReview.publishRefusedBare', { defaultValue: 'Not published.' })} + + ) : null} + + + ); + }; const link = (path: string, text: string, ariaLabel: string, testId: string) => (

- {t('chatbot.draftReview.hint', { defaultValue: 'Nothing is published yet. Review the drafts and publish them in App Studio.' })} + {onPublishDraft + ? t('chatbot.draftReview.hintPublish', { defaultValue: 'Nothing is published yet. Publish a draft here, or review the drafts in App Studio.' }) + : t('chatbot.draftReview.hint', { defaultValue: 'Nothing is published yet. Review the drafts and publish them in App Studio.' })}

{groups.map((group) => ( @@ -155,6 +288,7 @@ export function DraftReviewCard({ review, onOpenReviewLink, reviewLinkHref, clas t('chatbot.draftReview.reviewAria', { name: shown, defaultValue: 'Review the draft {{name}} in App Studio' }), 'draft-review-item-link', )} + {publishControl(draft, shown)} ); diff --git a/ui/packages/plugin-chatbot/src/chat/types.ts b/ui/packages/plugin-chatbot/src/chat/types.ts index 104db7a7469..cce29f639c4 100644 --- a/ui/packages/plugin-chatbot/src/chat/types.ts +++ b/ui/packages/plugin-chatbot/src/chat/types.ts @@ -14,8 +14,10 @@ import * as React from 'react'; import type { OpenListLink } from '../recordLink'; import type { RecordWrite, SampleDataCleanup, PackageRemoval } from '../mapMessages'; +import type { DraftReviewPublishResult } from './DraftReviewCard'; import type { DatasetProvenance, + DraftReviewItemParsed, DraftReviewListParsed, ObjectQuerySource, RecordCitationParsed, @@ -68,7 +70,8 @@ export interface ChatbotEnhancedMessage { /** * The drafts the turn saved, lifted from the message's `data-draft-review` * part by `extractDraftReview`. Drawn as a review card under the answer, - * with Studio review links through `onOpenReviewLink`. Live only: a + * with Studio review links through `onOpenReviewLink` and, with a host + * `onPublishDraft`, a pinned Publish per draft. Live only: a * history rebuild does not carry it. */ draftReview?: DraftReviewListParsed; @@ -540,6 +543,13 @@ export interface ChatbotEnhancedProps extends React.HTMLAttributes string; + /** + * Publish one draft of the draft review card as the signed-in person, + * pinned to the version the turn saved (the publish body's `draftVersion`), + * and report the result (`DraftReviewCard`'s `onPublishDraft`). Absent → the + * card offers no Publish; every draft is published in Studio. + */ + onPublishDraft?: (draft: DraftReviewItemParsed) => Promise; /** cloud#1658 — the record hand-off card's title. */ recordHandoffTitleLabel?: string; /** cloud#1658 — the record hand-off card's action label. */ diff --git a/ui/packages/plugin-chatbot/src/index.tsx b/ui/packages/plugin-chatbot/src/index.tsx index 64574b2ada4..abb3919fa5f 100644 --- a/ui/packages/plugin-chatbot/src/index.tsx +++ b/ui/packages/plugin-chatbot/src/index.tsx @@ -447,4 +447,4 @@ export { QUESTION_SKIP_STORAGE_PREFIX } from './chat/questionSkip'; // part), with Studio review links. `ChatbotEnhanced` draws it itself; the // reader is exported for hosts that render their own transcript. export { DraftReviewCard } from './chat/DraftReviewCard'; -export type { DraftReviewCardProps } from './chat/DraftReviewCard'; +export type { DraftReviewCardProps, DraftReviewPublishResult } from './chat/DraftReviewCard';