Skip to content

Commit e4a02be

Browse files
feat(console): read the in-app pending_confirmation answer beside the stored pending_approval one (#38446)
Fixes #38322 Part of: #33806 (step 2 of 4, UI and SDK; step 1 merged as PR #38273) Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用户无感。控制台聊天里待确认操作的审批卡片,今后服务端换成新的答复写法后照样出现;按旧写法保存的历史对话也照样出现,批准、拒绝都能用。 - 为什么做:这是「把应用内助手的待确认操作并入统一确认服务」四步中的第二步(界面与客户端),必须在第三步改服务端答复之前落地,否则新提案在聊天里看不到审批卡片。 - 出错会怎样:最坏情况是聊天里某条待确认操作不显示审批按钮,用户可改到 AI 审批收件箱处理;本改动只动控制台识别逻辑,可整体撤回。 - 要你做什么:无 ## What changes Step 1 (PR #38273) moved the in-app pending answer from `{ status: 'pending_approval', pendingActionId }` to `{ status: 'pending_confirmation', pendingId }` (`ActionConfirmationPending`, `packages/spec/src/contracts/ai-service.ts`), and its contract text ("A stored `pending_approval` answer") says a stored old answer is read by the SAME recogniser, taking `pendingActionId` as the `pendingId`, with no second reader. Ruling A on #33806 says the same. - `ui/packages/plugin-chatbot/src/toolResultParsers.ts`: `detectPendingApproval` is that one recogniser. It reads `pending_confirmation` + `pendingId` and `pending_approval` + `pendingActionId`. Each status pairs with its own id key only: a crossed pair (`pending_confirmation` + `pendingActionId`, or `pending_approval` + `pendingId`) is not read, so no lenient dialect gets in. The id still comes back as `pendingActionId`, the name `ChatToolInvocation.pendingActionId` and the approve/reject routes already use. Signature and return type are unchanged. An orphaned docblock that named only the old literal is gone. - Every reader already goes through it: `mapMessages.ts` (the live and stored-history mapper, plus the record-write, sample-data-cleanup and package-removal card detectors), app-shell `useChatConversation.ts` (`toUIMessages` approval promotion), and `aiChatHydration.ts`. `useHitlInChat.ts` and `useObjectChat.ts` read only the lifted `tool.pendingActionId`. No reader of either literal is left outside the recogniser (`git grep` over `ui/` for both literals, outside tests and CHANGELOGs, finds only the recogniser, the docblocks and the cache writer below). - Docblocks that named only the old literal now name both: `chat/types.ts`, `useHitlInChat.ts`, `useObjectChat.ts`, `mapMessages.ts`, and `useChatConversation.ts` (the cache writer). - SDK half of the card: nothing to move. `packages/client/src/index.ts` (`ai.pendingActions.*`) and `ui/packages/plugin-chatbot/src/usePendingActions.ts` call the REST routes `/ai/pending-actions/*`. They name none of the four retired `IAIService` members (`proposePendingAction`, `approvePendingAction`, `rejectPendingAction`, `listPendingActions`), so `git grep` over `packages/client`, `packages/client-react` and `ui/` (CHANGELOGs excluded) finds 0 hits. The routes belong to step 3, so both files are untouched. - No runtime, route or spec change, and no export added or removed. ## Tests - `ui/packages/plugin-chatbot/src/__tests__/mapMessages.test.ts`: a new top-level `describe`, "detectPendingApproval reads the current and the stored pending answer". It covers the new shape (bare, text-wrapped, JSON string), the old shape (bare, text-wrapped), crossed pairs and malformed ids refused, a live `pending_confirmation` result lifted to `approval-requested` + id, the record-write card drawn from a `pending_confirmation` envelope, and a conversation stored with the old answer re-drawing its approval card. A lit control checks that an ordinary result draws no card. - `ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx`: two new driven round trips that end in the REST call Approve makes. One restores a cached entry from the stored `pending_approval` envelope alone (part-key fallback removed, so the recogniser is what is proven). The other takes a live `pending_confirmation` answer through the cache to Approve. ## Acceptance notes - The chat's local cache writer (`pendingApprovalToCachedResult`) still mints `{ status: 'pending_approval', pendingActionId }`. This PR first switched it to the current answer, but `AiChatPage.runtimeMessageSeam.test.tsx` under `app-shell/src/console/ai/__tests__` pins that exact shape, and that file is outside this card's claimed file surface, so the writer change was reverted. The recogniser reads both, so a cached entry restores either way. Moving the writer to the current answer is a one-line change plus that one assertion. Carrier: #38448. - `detectPendingApproval` is a public export of `@object-ui/plugin-chatbot` (and `/core`). Its signature is unchanged, and it now also recognises the `pending_confirmation` answer. It refused that input before, so this PR declares `Clause-②: yes (widening)` (seat routing on the dev's question; the claim said `no`). The bump stays `patch`: the level follows `Metadata-protocol`, which is `none`. The declaration owes a TIER_DEFAULT review of record. ## Verification Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-chatbot/src/__tests__/mapMessages.test.ts`. Expect every test to pass, including the 7 under "detectPendingApproval reads the current and the stored pending answer". Read first (by risk): 1. `ui/packages/plugin-chatbot/src/toolResultParsers.ts`, the `detectPendingApproval` / `pendingAnswerIdKey` hunk: the strict literal-to-id-key pairing. 2. `ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx`: the two new round trips. 3. `ui/packages/plugin-chatbot/src/__tests__/mapMessages.test.ts`: the new `describe`. All readings below are at head `e5da5265` unless a line says otherwise. <details><summary>Tests (local, under the shared verify lock)</summary> - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-chatbot/` + all 14 `*ratchet*` tests under `packages/app-shell/src` + `packages/app-shell/src/console/*.test.tsx` + `packages/app-shell/src/console/ai/` + `packages/app-shell/src/hooks/` + `packages/app-shell/src/assistant/`: Test Files 238 passed (238), Tests 2086 passed (2086), VERDICT command-exit 0. - `pnpm --filter @object-ui/plugin-chatbot type-check`: exit 0. `--listFiles` shows `tsconfig.test.json` compiles `src/__tests__/mapMessages.test.ts`. - `pnpm --filter @object-ui/app-shell type-check` (after building the `@object-ui/app-shell^...` closure, 72/72 tasks): VERDICT command-exit 0. - eslint over the 8 changed `ui/` files: 0 errors (13 warnings, all on lines this PR does not touch). - Narrowing, declared: the full app-shell suite (about 2,459 files) was not run locally. CI `Test UI` runs it. </details> <details><summary>Ablation (on-disk mutation via scripts/ablation-replace.mjs, restored to the HEAD blob each time)</summary> The vitest config aliases the packages under test to `src`, so no `dist` was involved. - Removed the `pending_confirmation` arm (`toolResultParsers.ts` blob 9e4f150 to 9ba227b6). 4 red: the three new-shape pins in `mapMessages.test.ts` and the new-answer cache round trip. Restored: blob equals HEAD, `git diff HEAD` empty. - Removed the `pending_approval` arm (blob 9e4f150 to 89c4cedb). 6 red: the old-shape pin, the stored-conversation re-draw, the new stored-envelope-only cache restore, and three existing cache round trips that read the stored literal. Restored: blob equals HEAD, `git diff HEAD` empty. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands` derived 38 families for this diff. All 38 ran locally, each exit 0 (`pnpm --dir ui exec vitest run scripts/`: 172 files passed, 2 skipped). `--ran` reconciliation: "38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED (a DERIVED zero)". - `node scripts/pm/overlap-check.mjs`: "VERDICT clean exit 0". It merges cleanly with `origin/main` and shares a file with no open PR. - Families CI runs (repo-wide lint, the full UI test shards, typecheck lanes): read from this PR's check-runs, not re-run locally. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` is not touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran. eslint on the changed files shows 0 errors; repo-wide `pnpm lint` is left to CI. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not applicable. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English, apart from the maintainer quick-read section the fleet contract asks for in Chinese. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5nvFivDeQyYgTFkZhi)_ <!-- signed: repo:objectstack#5 · os-project-manager · session_01FEkQ5nvFivDeQyYgTFkZhi --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3b77188 commit e4a02be

9 files changed

Lines changed: 286 additions & 31 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/plugin-chatbot': patch
3+
'@object-ui/app-shell': patch
4+
---
5+
6+
feat(console): the chat reads the in-app `pending_confirmation` answer beside the stored `pending_approval` one
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
The in-app assistant's pending answer is moving from `{ status: 'pending_approval', pendingActionId }` to `{ status: 'pending_confirmation', pendingId }` (`ActionConfirmationPending` in `@objectstack/spec/contracts`). The console now draws the approval card for either answer: `detectPendingApproval` is the one recogniser for both, and each status pairs with its own id key only, so `pending_confirmation` with `pendingActionId` (or `pending_approval` with `pendingId`) is not read as a pending answer. A conversation stored with the old answer still shows its approval card, and Approve and Reject still reach its item. The id still arrives on the tool invocation as `pendingActionId`.
12+
13+
The chat's local message cache keeps the shape it writes for a pending approval; a live `pending_confirmation` answer goes through it and back to an approval card unchanged.
14+
15+
What widens: the public `detectPendingApproval` export of `@object-ui/plugin-chatbot` (and `@object-ui/plugin-chatbot/core`) now also recognises `{ status: 'pending_confirmation', pendingId }`, an input it refused before; its signature and return type are unchanged. Nothing changes on the server, in the routes or in the spec, and no export is added or removed.

‎ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1457,6 +1457,65 @@ describe('sanitizeChatMessagesForCache — a pending approval survives the cache
14571457
expect(decision?.state).toBe('success');
14581458
});
14591459

1460+
it('restores a cached entry from the stored pending_approval envelope alone', async () => {
1461+
// The retired literal with `pendingActionId` in `output`, as the cache
1462+
// writer mints it and as a conversation stored before the answer moved
1463+
// carries it. The writer also writes the id as a part key; it is left out
1464+
// here on purpose, so what is proven is the one recogniser reading the
1465+
// stored answer, not the cache-side fallback beside it. Approve still
1466+
// reaches the item.
1467+
const oldEntry: HydratedUIMessage[] = [
1468+
{
1469+
id: 'a1',
1470+
role: 'assistant',
1471+
parts: [
1472+
{ type: 'text', text: 'This needs your approval.' },
1473+
{
1474+
type: 'tool-action_delete_task',
1475+
toolCallId: 'tc-approve',
1476+
toolName: 'action_delete_task',
1477+
state: 'approval-requested',
1478+
output: { status: 'pending_approval', pendingActionId: PENDING_ACTION_ID },
1479+
},
1480+
],
1481+
},
1482+
];
1483+
const restored = hydratedMessagesToChatMessages(throughLocalStorage(oldEntry));
1484+
expect(restored[0]?.toolInvocations?.[0]?.pendingActionId).toBe(PENDING_ACTION_ID);
1485+
1486+
const { urls, decision } = await pressApprove(restored);
1487+
expect(urls).toEqual([`${API_BASE}/pending-actions/${PENDING_ACTION_ID}/approve`]);
1488+
expect(decision?.state).toBe('success');
1489+
});
1490+
1491+
it('round-trips a live pending_confirmation answer through the cache to Approve', async () => {
1492+
const live = uiMessageToChatMessage({
1493+
...liveUiMessage,
1494+
parts: liveUiMessage.parts.map((p) =>
1495+
'output' in p
1496+
? {
1497+
...p,
1498+
output: {
1499+
status: 'pending_confirmation',
1500+
pendingId: PENDING_ACTION_ID,
1501+
message: 'A confirmation was sent to you.',
1502+
actionName: 'delete_task',
1503+
},
1504+
}
1505+
: p,
1506+
),
1507+
});
1508+
expect(live.toolInvocations?.[0]?.pendingActionId).toBe(PENDING_ACTION_ID);
1509+
expect(live.toolInvocations?.[0]?.state).toBe('approval-requested');
1510+
1511+
const restored = hydratedMessagesToChatMessages(
1512+
throughLocalStorage(sanitizeChatMessagesForCache([live])),
1513+
);
1514+
const { urls, decision } = await pressApprove(restored);
1515+
expect(urls).toEqual([`${API_BASE}/pending-actions/${PENDING_ACTION_ID}/approve`]);
1516+
expect(decision?.state).toBe('success');
1517+
});
1518+
14601519
it('writes the AI SDK approval envelope as a part key, where the hydration mapper reads it', () => {
14611520
// The envelope rides the PART on both directions of the server path, so the
14621521
// cache writes it as a part key too. The input shape here is the one

‎ui/packages/app-shell/src/hooks/useChatConversation.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,10 @@ interface CacheableChatMessage {
266266
* second hand-rolled reader on the cache side would be the second dialect of
267267
* one contract that Commandment #0.1 refuses.
268268
*
269+
* It mints `{ status: 'pending_approval', pendingActionId }` whichever answer
270+
* the live result carried, `pending_confirmation` with `pendingId` included:
271+
* the one detector reads both, so a cached entry restores either way.
272+
*
269273
* The two keys the detector reads are the only two written: the framework's
270274
* real envelope also carries a human `message` and the proposed arguments, and
271275
* none of that is re-serialized, which is why a cached thread does not grow a

‎ui/packages/plugin-chatbot/src/__tests__/mapMessages.test.ts‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import { describe, it, expect } from 'vitest';
1010
import type { UIMessage } from '@ai-sdk/react';
1111
import {
12+
detectPendingApproval,
13+
detectRecordWrite,
1214
uiMessageToChatMessage,
1315
uiMessagesToChatMessages,
1416
} from '../mapMessages';
@@ -259,3 +261,141 @@ describe('uiMessagesToChatMessages', () => {
259261
expect(out[0]?.streaming).toBeFalsy();
260262
});
261263
});
264+
265+
/**
266+
* The in-app pending answer moved from `pending_approval` with
267+
* `pendingActionId` to `pending_confirmation` with `pendingId`
268+
* (`ActionConfirmationPending`, `@objectstack/spec/contracts`). Conversations
269+
* stored before the move still carry the old answer, and the contract reads it
270+
* through the SAME recogniser, taking `pendingActionId` as the `pendingId`.
271+
* Every approval card the console draws from a tool result asks
272+
* `detectPendingApproval`, so these pins hold that one function to both
273+
* shapes, and the mapper to both through it.
274+
*/
275+
describe('detectPendingApproval reads the current and the stored pending answer', () => {
276+
const CURRENT = {
277+
status: 'pending_confirmation',
278+
pendingId: 'pa_new_1',
279+
message: 'A confirmation was sent to you.',
280+
actionName: 'delete_task',
281+
objectName: 'task',
282+
};
283+
const STORED = {
284+
status: 'pending_approval',
285+
pendingActionId: 'pa_old_1',
286+
message: 'Delete task?',
287+
toolName: 'action_delete_task',
288+
};
289+
290+
it('reads pending_confirmation with pendingId, bare and in the text wrapper', () => {
291+
expect(detectPendingApproval(CURRENT)?.pendingActionId).toBe('pa_new_1');
292+
expect(
293+
detectPendingApproval({ type: 'text', value: JSON.stringify(CURRENT) })?.pendingActionId,
294+
).toBe('pa_new_1');
295+
expect(detectPendingApproval(JSON.stringify(CURRENT))?.raw).toEqual(CURRENT);
296+
});
297+
298+
it('reads pending_approval with pendingActionId, bare and in the text wrapper', () => {
299+
expect(detectPendingApproval(STORED)?.pendingActionId).toBe('pa_old_1');
300+
expect(
301+
detectPendingApproval({ type: 'text', value: JSON.stringify(STORED) })?.pendingActionId,
302+
).toBe('pa_old_1');
303+
});
304+
305+
it('pairs each literal with its own id key only', () => {
306+
// A crossed pair is neither shape: reading it would be a dialect of the
307+
// contract, not the contract.
308+
expect(detectPendingApproval({ status: 'pending_confirmation', pendingActionId: 'pa_x' })).toBeUndefined();
309+
expect(detectPendingApproval({ status: 'pending_approval', pendingId: 'pa_x' })).toBeUndefined();
310+
expect(detectPendingApproval({ status: 'pending_confirmation', pendingId: '' })).toBeUndefined();
311+
expect(detectPendingApproval({ status: 'pending_confirmation', pendingId: 7 })).toBeUndefined();
312+
expect(detectPendingApproval({ status: 'executed', pendingId: 'pa_x' })).toBeUndefined();
313+
expect(detectPendingApproval({ status: 'toString', pendingId: 'pa_x' })).toBeUndefined();
314+
});
315+
316+
it('lifts a live pending_confirmation result into an actionable approval card', () => {
317+
const out = uiMessageToChatMessage({
318+
id: 'm1',
319+
role: 'assistant',
320+
parts: [
321+
{
322+
type: 'tool-action_delete_task',
323+
toolCallId: 'c1',
324+
state: 'output-available',
325+
input: { recordId: 'task_1' },
326+
output: { type: 'text', value: JSON.stringify(CURRENT) },
327+
},
328+
],
329+
} as never);
330+
expect(out.toolInvocations?.[0]).toMatchObject({
331+
toolCallId: 'c1',
332+
state: 'approval-requested',
333+
pendingActionId: 'pa_new_1',
334+
});
335+
});
336+
337+
it('draws the record-write card from a pending_confirmation envelope too', () => {
338+
// The card detectors read the envelope through the same recogniser, so the
339+
// move does not strand the cards that ride a pending answer.
340+
const write = detectRecordWrite({
341+
...CURRENT,
342+
recordWrite: {
343+
operation: 'create',
344+
objectName: 'crm_lead',
345+
objectLabel: 'Lead',
346+
fields: [{ name: 'name', label: 'Name', type: 'text', value: 'Ada' }],
347+
dropped: [],
348+
},
349+
});
350+
expect(write?.objectName).toBe('crm_lead');
351+
expect(write?.fields.map((f) => f.name)).toEqual(['name']);
352+
});
353+
354+
it('re-draws the approval card of a conversation stored with the old answer', () => {
355+
// The shape a conversation persisted before the move reloads with: the
356+
// result as the server stored it (a text wrapper around the JSON string),
357+
// the turn long ended, no live tail.
358+
const out = uiMessagesToChatMessages(
359+
[
360+
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'delete the Q3 task' }] },
361+
{
362+
id: 'a1',
363+
role: 'assistant',
364+
parts: [
365+
{ type: 'text', text: 'This needs your approval.' },
366+
{
367+
type: 'tool-action_delete_task',
368+
toolCallId: 'c-old',
369+
state: 'output-available',
370+
input: { recordId: 'task_77' },
371+
output: { type: 'text', value: JSON.stringify(STORED) },
372+
},
373+
],
374+
},
375+
] as never,
376+
{ isStreaming: false },
377+
);
378+
expect(out[1]?.toolInvocations?.[0]).toMatchObject({
379+
toolCallId: 'c-old',
380+
state: 'approval-requested',
381+
pendingActionId: 'pa_old_1',
382+
});
383+
});
384+
385+
it('LIT CONTROL — an ordinary result draws no approval card', () => {
386+
const out = uiMessageToChatMessage({
387+
id: 'm2',
388+
role: 'assistant',
389+
parts: [
390+
{
391+
type: 'tool-action_delete_task',
392+
toolCallId: 'c2',
393+
state: 'output-available',
394+
output: { status: 'executed', pendingId: 'pa_done' },
395+
},
396+
],
397+
} as never);
398+
expect(out.toolInvocations?.[0]?.state).toBe('output-available');
399+
expect(out.toolInvocations?.[0]?.pendingActionId).toBeUndefined();
400+
});
401+
});

‎ui/packages/plugin-chatbot/src/chat/types.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,10 +156,14 @@ export interface ChatbotEnhancedToolInvocation {
156156
signature?: string;
157157
};
158158
/**
159-
* ObjectStack HITL extension. When the framework's `action-tools.ts`
160-
* proposes a destructive action that requires human approval, the tool
161-
* result carries `{ status: 'pending_approval', pendingActionId: 'pa_…' }`.
162-
* `mapMessages.ts` lifts that id here so chat UIs can call the
159+
* ObjectStack HITL extension. When the in-app assistant hands a gated call
160+
* off for the person's confirmation, the tool result carries
161+
* `{ status: 'pending_confirmation', pendingId: 'pa_…' }`; a conversation
162+
* stored before that answer replaced the old one carries
163+
* `{ status: 'pending_approval', pendingActionId: 'pa_…' }` instead. Both are
164+
* read by the one recogniser, `detectPendingApproval` (`toolResultParsers.ts`),
165+
* and `mapMessages.ts` lifts the item's id here, under this name whichever
166+
* answer carried it, so chat UIs can call the
163167
* `POST /api/v1/ai/pending-actions/:id/{approve,reject}` REST endpoints
164168
* without parsing the tool result JSON themselves.
165169
*/

‎ui/packages/plugin-chatbot/src/mapMessages.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,10 @@ export function detectRecordHandoff(result: unknown): RecordHandoff | undefined
139139
/**
140140
* cloud#3565 — the chat's ONE-record write proposal, which the user confirms
141141
* on a card before anything is written. `create_record` / `update_record`
142-
* queue a HITL pending action in the user's name and answer
143-
* `{ status:'pending_approval', pendingActionId, recordWrite:{…} }`: the
144-
* approval envelope `detectPendingApproval` already lifts, plus the record the
142+
* queue a HITL pending action in the user's name and answer the pending
143+
* envelope (`{ status:'pending_confirmation', pendingId, recordWrite:{…} }`, or
144+
* `pending_approval` with `pendingActionId` in a stored conversation) that
145+
* `detectPendingApproval` already lifts, plus the record the
145146
* card draws beside its three buttons (确认 / 打开完整表单 / 取消). An update
146147
* carries each field as stored (`current`) beside the proposed value, so the
147148
* card reads old → new. `dropped` names what the server refused to propose and
@@ -309,9 +310,11 @@ export function storedAnswerData(parts: readonly AnyPart[]): {
309310

310311
/**
311312
* cloud#3565 — 「清理示例数据」: the chat's `remove_sample_data` queues a HITL
312-
* pending action and answers `{ status:'pending_approval', pendingActionId,
313-
* sampleDataCleanup:{ tables:[{ objectName, label, count }], total, absent,
314-
* edited } }` — the tables and counts the card lists before the user confirms.
313+
* pending action and answers the pending envelope (`pending_confirmation` with
314+
* `pendingId`, or `pending_approval` with `pendingActionId` in a stored
315+
* conversation; `detectPendingApproval` reads both) plus
316+
* `sampleDataCleanup:{ tables:[{ objectName, label, count }], total, absent,
317+
* edited }` — the tables and counts the card lists before the user confirms.
315318
* Only the seed ledger's rows are counted; the generic Approve / Deny strip
316319
* stays the decision. An envelope without the id or without a table is not a
317320
* card. The removal cannot be undone (no recycle bin until objectstack#3146),
@@ -357,7 +360,9 @@ export function detectSampleDataCleanup(result: unknown): SampleDataCleanup | un
357360
* pending action and answers `{ success:true, status:'pending_approval',
358361
* pendingActionId, packageRemoval:{ packageId, label, objects:[{ name, label,
359362
* rows?, draft? }], totalRows, uncountedObjects, items, data, recycleBin },
360-
* message }` (the shape on objectstack#31025, read at cloud `d6288d27`). The
363+
* message }` (the shape on objectstack#31025, read at cloud `d6288d27`; once
364+
* the answer moves it is `pending_confirmation` with `pendingId`, and
365+
* `detectPendingApproval` reads either). The
361366
* card lists what goes before the user confirms; the generic Approve / Deny
362367
* strip stays the decision and sends nothing but the decision. An envelope
363368
* without the id or without the plan is not a card, and a refusal

‎ui/packages/plugin-chatbot/src/toolResultParsers.ts‎

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,6 @@ export interface AnyPart {
5555
data?: unknown;
5656
}
5757

58-
/**
59-
* Best-effort detector for the framework's HITL pending envelope. Server-side
60-
* `action-tools.ts` returns a JSON string of shape
61-
* `{ "status": "pending_approval", "pendingActionId": "pa_…", … }`
62-
* inside the tool's `output.value` when the action is dangerous and approval
63-
* is enabled. We surface this on the invocation so chat UIs can render an
64-
* inline approve/reject affordance without round-tripping back to the server.
65-
*/
6658
/**
6759
* Parse a tool result into the framework's JSON envelope object, if it is one.
6860
* The Vercel SDK wraps tool outputs as `{ type: 'text', value: string }`, so we
@@ -111,9 +103,28 @@ export function parseResultEnvelope(result: unknown): Record<string, unknown> |
111103
}
112104

113105
/**
114-
* The ObjectStack HITL envelope a tool result carries when the framework's
115-
* `action-tools.ts` proposes a destructive action:
116-
* `{ status: 'pending_approval', pendingActionId: 'pa_…', … }`.
106+
* The pending-confirmation answer a tool result carries when the in-app
107+
* assistant hands a gated call off to the host's pending-confirmation service
108+
* (`ActionConfirmationPending`, `@objectstack/spec/contracts`):
109+
* `{ status: 'pending_confirmation', pendingId: 'pa_…', … }`.
110+
*
111+
* It is ALSO the one reader of the answer that service replaced,
112+
* `{ status: 'pending_approval', pendingActionId: 'pa_…', … }`: no door gives
113+
* that answer any more, but conversations stored before the merge still carry
114+
* it, and the contract (`AI_ACTION_CONFIRMATION_CAPABILITY`, "A stored
115+
* `pending_approval` answer") reads it through the SAME recogniser, taking
116+
* `pendingActionId` as the `pendingId`. ⛔ So there is no second reader of the
117+
* retired literal anywhere in the console: every surface that draws an
118+
* approval card from a tool result asks this function.
119+
*
120+
* Each literal pairs with its own id key and with no other: a
121+
* `pending_confirmation` answer carrying only `pendingActionId`, or a
122+
* `pending_approval` answer carrying only `pendingId`, is neither shape and is
123+
* not read as one (one strict contract, never a dialect of it).
124+
*
125+
* The id is returned as `pendingActionId` whichever shape answered: that is
126+
* the name the console's invocation field (`ChatToolInvocation.pendingActionId`)
127+
* already carries, and the approve/reject routes take that id unchanged.
117128
*
118129
* Exported (objectui#8442) so the app-shell's HYDRATION mapper derives the id
119130
* from the same parse the live mapper uses. The id is never persisted as a part
@@ -126,13 +137,25 @@ export function detectPendingApproval(
126137
): { pendingActionId: string; raw: Record<string, unknown> } | undefined {
127138
const obj = parseResultEnvelope(result);
128139
if (!obj) return undefined;
129-
const id = obj.pendingActionId;
130-
if (obj.status === 'pending_approval' && typeof id === 'string' && id.length > 0) {
140+
const idKey = pendingAnswerIdKey(obj.status);
141+
if (!idKey) return undefined;
142+
const id = obj[idKey];
143+
if (typeof id === 'string' && id.length > 0) {
131144
return { pendingActionId: id, raw: obj };
132145
}
133146
return undefined;
134147
}
135148

149+
/**
150+
* The pending answer's literal → the key its item id rides under. The current
151+
* answer first; the retired one stays readable for stored conversations only.
152+
*/
153+
function pendingAnswerIdKey(status: unknown): 'pendingId' | 'pendingActionId' | undefined {
154+
if (status === 'pending_confirmation') return 'pendingId';
155+
if (status === 'pending_approval') return 'pendingActionId';
156+
return undefined;
157+
}
158+
136159
/**
137160
* Lift charts from the stream's `data-chart` parts (emitted by the
138161
* `visualize_data` tool via `ctx.onProgress`). Unlike `data-build-progress`

0 commit comments

Comments
 (0)