Skip to content

Commit c6a1328

Browse files
fix(plugin-chatbot): a restored chat approval card reads its pending action and shows Expired for a lapsed one (#38326)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu52iwRDMp8T1eW25d28D4co)_ Fixes #38250 repo:objectstack#2 · os-sales · session_01L6bhgVC7KKvrgZyWpM75L8 Clause-②: no Metadata-protocol: none ## 维护者速读 - 控制台用户重新打开一段旧对话时,聊天里的 AI 确认卡片如果对应的操作已经失效,会直接显示「已过期」,不再显示「通过 / 拒绝」按钮;以前要点一下按钮才知道已过期。本人亲手拒绝过的,打开后显示为已拒绝。 - 这是上一张「AI 待确认操作过期显示已过期」留下的后半截,解决恢复对话时按钮还在的问题。 - 只多一次读取:每张还在等确认的卡片打开时,读一次它对应条目的状态(已有的单条读取接口,客户端 SDK 的 pendingActions.get 用的就是它),不改服务端;读不到时按钮照旧,点了仍会显示「已过期」。有问题可直接撤回。 - 无 ## What changes - `ui/packages/plugin-chatbot/src/useHitlInChat.ts`: each card the messages hold in `approval-requested` with a `pendingActionId` has its row read once per mount, `GET {apiBase}/pending-actions/:id` through the same authenticated fetch the decision uses (the item read `@objectstack/client`'s `pendingActions.get` uses; the AI Approvals inbox reads the list). `settledDecisionOf(row)`: a lapsed row (`isLapsedPendingAction`, from #34255) settles the card on `{ state: 'expired' }`; a row a person rejected settles it on the rejection, drawn as a rejection made in this session is (`success`, `decision: 'rejected'`, `Rejected: REASON` / `Rejected.`). Any other row, a non-2xx, or no answer leaves the card as it was. A decision made on the card before the read lands is never overwritten. The read is deduplicated by pending-action id, so a streamed message or a new `headers` object re-reads nothing. - New test `ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx` (4 cases, one of them the press-before-read race). - Four existing test files scripted `fetch` in call order (a fifth, the bearer-session pin, counted requests: see the CI notes below) for the decision POST, and the row read now comes first: `useHitlInChat.test.tsx`, `writeApprovalPending-37860.test.tsx` and `AiChatPage.approvalRehydration.test.tsx` answer the read 404 and keep their scripted POST replies in order (`decisionReply`); `useChatConversation.test.tsx`'s `pressApprove` builds a fresh `Response` per call and counts POST URLs only. Every assertion they made still holds; `AiChatPage.approvalRehydration` additionally pins that the read went to `…/pending-actions/pa_44`. - `AiChatPage.approvalRehydration.test.tsx` also gains a module-top `import '@object-ui/plugin-grid';` (`check:test-source-alias` asks it of an edited test whose source reach loads that plugin lazily). - `app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx`: the in-chat approval pin now expects the row read too (CI, below). - `.changeset/38250-restored-approval-card-reads-row.md`: patch for `@object-ui/plugin-chatbot`. - CI at 82915a7 (b1f7cfc): `Test UI (5/16)` failed in `app-shell/src/sameServerFetch.bearer.ratchet.test.ts`, which counted the row read's inline `(apiFetch ?? fetch)(…)` as a bare cookie-only fetch. The read now binds `const doFetch = apiFetch ?? fetch;` first, the renderer-package channel spelling the ratchet reads as the host's `apiFetch` and the one `decide` already uses: same transport, no allow-list row. The 8 `*ratchet*` test files under `ui/packages/*/src` pass locally (89 tests). - CI at 82915a7 (f97f74c): `Test UI (10/16)` failed in `app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx`, which records every request `useHitlInChat` sends and expected the approve `POST` alone. It now expects the row read first and the `POST` after, each with the stored bearer, so the pin also shows the read rides the authenticated channel. - Every test file under `ui/packages/*/src` and `ui/apps/*/src` that names `useHitlInChat`, `pending-actions`, `onToolApprove`, `toolDecisions`, `pendingActionId`, `pending_approval` or `approval-requested` re-run locally after these fixes: 32 files / 343 tests and 25 files / 257 tests, 0 failed. - Review 7240110232 (d5fc75e): the press-before-read race gets its own case (should-fix), and the changeset and hook comment name the item read rather than the inbox, which reads the list (nit). Restored rows settled approved/executed/failed/held keep their buttons, as before; the seat files that separately. ### Small calls this PR made (listed for review) 1. **The read runs for every awaiting card, not only restored ones.** The hook cannot tell a card restored from a saved conversation from one that just streamed in, and no host prop says so; a live proposal's read answers `pending` and changes nothing. Cost: one `GET` per awaiting card per mount. No new option or prop, so no public surface moves (`Clause-②: no`, as claimed). 2. **A row a person rejected reads as that rejection** (the card's second box), with the same English strip text the live reject path writes. Rows settled any other way (approved, executed, failed, held) keep their buttons: the card asks for the lapse, and a press on one still answers. 3. **The answer is read bare or in the `{ success, data }` envelope**, the two shapes `@objectstack/client`'s `pendingActions.get` reads; anything without a string `status` is ignored. 4. **A host whose own tests script `fetch` in call order** sees one extra `GET` before the decision POST; the changeset says so. Four such files in this repo were adjusted (above). 5. `usePendingActions.ts` is untouched (PR #38273 edits a comment there). ## Read first 1. `ui/packages/plugin-chatbot/src/useHitlInChat.ts`: the row-read effect and `settledDecisionOf`. Risky hunk: the functional update that must not overwrite a press. 2. `ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx`. 3. The four adjusted test files: each change only routes the row read away from the scripted replies. ## Tests <details><summary>New test (local, head f97f74c)</summary> `ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx` (zh, `useHitlInChat` and `ChatbotEnhanced` run together, nothing pressed): a lapsed row in the `{ success, data }` envelope draws `data-state="expired"` with 已过期, no buttons, and exactly one request, `GET /api/v1/ai/pending-actions/pa_9`; a row with `decided_by` (and `lapsed` typed as the reason) draws the rejection, never 已过期; a pending row and a 404 each leave the buttons and draw no strip; with the row read held open, Approve is pressed and answers `executed`, then the read answers a lapsed row, and the card still reads the approval, never 已过期 (review 7240110232 should-fix), with exactly `GET …/pa_9` then `POST …/pa_9/approve` sent. ``` cd ui && pnpm exec vitest run packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx Test Files 1 passed (1) Tests 4 passed (4) ``` </details> <details><summary>Ablation</summary> `settledDecisionOf` mutated on disk to answer `undefined` for every row (`if (row) return undefined;` first), the new file re-run at 675654b: 2 failed / 1 passed (the lapsed and person-rejected cases; the pending/404 case asserts the unchanged path), exit 1. Restored with `git checkout`. On the tree committed as d5fc75e, the press guard removed on disk (`setDecisions((prev) => ({ ...prev, [toolCallId]: settled }))`, no `toolCallId in prev` check), the new file re-run: 1 failed / 3 passed (the race case), exit 1. Restored from a copy; `git diff` clean. </details> <details><summary>Package runs, type-check, lint</summary> - `pnpm exec vitest run --maxWorkers=3 packages/plugin-chatbot/ packages/app-shell/src/console/ai/ packages/app-shell/src/assistant/ packages/app-shell/src/hooks/`: before the test adjustments 12 tests in 3 files failed (each on a scripted reply the row read consumed), and after them 1 more (`useChatConversation.test.tsx`, one `Response` body read twice). With the adjustments: 223 passed + that file re-run 58/58, so 224 files, 0 failed. - At f97f74c (since 82915a7: the new case, a hook comment, the read's channel binding, the changeset sentence, and the bearer-session pin): `pnpm exec vitest run --maxWorkers=3 packages/plugin-chatbot/` 81 files / 754 tests passed; plugin-chatbot type-check and app-shell `tsc -p tsconfig.test.json` exit 0; `eslint --no-inline-config` on the hook, the new test and the bearer-session pin exit 0. The app-shell runs below are from 82915a7; no app-shell file changed since. - `pnpm --filter @object-ui/plugin-chatbot run type-check` exit 0; `@object-ui/app-shell` `tsc --noEmit` and `tsc -p tsconfig.test.json` exit 0. - `eslint --no-inline-config` on `useHitlInChat.ts`, the new test and the four adjusted tests: exit 0, 0 problems. </details> <details><summary>Derived gate families (local)</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived the same 38 families at d5fc75e and at f97f74c (the run spans those commits: one line of `useHitlInChat.ts` and one test file moved meanwhile); each run locally, exit code captured before any pipe: ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-sdui-manifest.mjs :: exit 0 node scripts/check-sdui-manifest.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --dir ui exec vitest run scripts/ :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:skill-identifier-liveness :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` `dispatch-gates --ran`: `38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED (a DERIVED zero — all 38 recorded an exit code and none of them is 3)`. At 675654b `pnpm check:test-source-alias` exited 1: editing `AiChatPage.approvalRehydration.test.tsx` brought it under the gate's source-reach half (`ChatPane.tsx` imports `@object-ui/plugin-grid` lazily). 82915a7 adds the module-top `import '@object-ui/plugin-grid';` the gate names; the file passes (1/1) and the gate exits 0 above. </details> ## Acceptance notes - No server change and no new route: `GET /api/v1/ai/pending-actions/:id` is the existing read (hosted AI service; the console's API explorer and `@objectstack/client` list it). The open edition serves no AI service, so there the read answers non-2xx and the card is unchanged. - `test:repo` (vitest `repo` project) not run locally: this diff touches none of its tests; CI's `Test Core` runs it. ## Verification Two minutes: run the new test file above from `ui/`; expect 4 passing tests, the lapsed restored card reading 已过期 with nothing pressed, and a press made while the read was out standing. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgVC7KKvrgZyWpM75L8)_ <!-- signed: repo:objectstack#2 · os-sales · session_01L6bhgVC7KKvrgZyWpM75L8 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c679140 commit c6a1328

8 files changed

Lines changed: 429 additions & 25 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/plugin-chatbot': patch
3+
---
4+
5+
fix(plugin-chatbot): a chat approval card restored after its pending action lapsed reads "Expired" at once, not after a press
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A card restored from a saved conversation says `approval-requested` whatever became of its pending action since. `useHitlInChat` now reads each awaiting card's row once, through the item read `GET /api/v1/ai/pending-actions/:id` (the one `@objectstack/client`'s `pendingActions.get` uses; the AI Approvals inbox reads the list): a lapsed row (`status: 'rejected'`, `rejection_reason: 'lapsed'`, no `decided_by`) settles the card on "Expired" with no buttons, and a row a person rejected settles it on that rejection. A row still pending or settled any other way, or a read that gets no answer, leaves the buttons as before; a decision made on the card meanwhile is never overwritten. A host whose tests script `fetch` in call order sees one extra `GET` per awaiting card.

‎ui/packages/app-shell/src/assistant/__tests__/writeApprovalPending-37860.test.tsx‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,32 @@ function hydratePendingWrite() {
5757
);
5858
}
5959

60+
/**
61+
* The decision POSTs this file scripts, answered in order. Since
62+
* objectstack#38250 the hook also reads each awaiting card's row once
63+
* (`GET …/pending-actions/:id`); that read is answered 404 here, which leaves
64+
* the card as it is, so the scripted replies reach the decision they were
65+
* written for.
66+
*/
67+
const decisionReplies: Response[] = [];
68+
function decisionReply(reply: Response): void {
69+
decisionReplies.push(reply);
70+
}
71+
function stubDecisionFetch(): void {
72+
decisionReplies.length = 0;
73+
vi.stubGlobal(
74+
'fetch',
75+
vi.fn(async (_url: string, init?: RequestInit) =>
76+
init?.method === 'GET'
77+
? ({ ok: false, status: 404, text: async () => '' } as Response)
78+
: (decisionReplies.shift() as Response),
79+
),
80+
);
81+
}
82+
6083
describe('a write awaiting approval, as the drawer host reads it (objectstack#37860)', () => {
6184
beforeEach(() => {
62-
vi.stubGlobal('fetch', vi.fn());
85+
stubDecisionFetch();
6386
});
6487
afterEach(() => {
6588
vi.unstubAllGlobals();
@@ -72,8 +95,7 @@ describe('a write awaiting approval, as the drawer host reads it (objectstack#37
7295

7396
it('an approval the user made in the chat clears it; a failed one leaves it waiting', async () => {
7497
const messages = hydratePendingWrite();
75-
const fetchMock = globalThis.fetch as ReturnType<typeof vi.fn>;
76-
fetchMock.mockResolvedValueOnce({
98+
decisionReply({
7799
ok: true,
78100
text: async () => JSON.stringify({ status: 'executed', result: { deleted: 1 } }),
79101
} as Response);
@@ -84,7 +106,7 @@ describe('a write awaiting approval, as the drawer host reads it (objectstack#37
84106
expect(approved.result.current.decisions.c1?.state).toBe('success');
85107
expect(countWritesAwaitingApproval(messages, approved.result.current.decisions)).toBe(0);
86108

87-
fetchMock.mockResolvedValueOnce({ ok: false, status: 500, text: async () => 'boom' } as Response);
109+
decisionReply({ ok: false, status: 500, text: async () => 'boom' } as Response);
88110
const failed = renderHook(() => useHitlInChat({ messages, apiBase: '/api/v1/ai' }));
89111
await act(async () => {
90112
await failed.result.current.decide('c1', true);

‎ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.approvalRehydration.test.tsx‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2828
import { act, renderHook } from '@testing-library/react';
2929
import { useHitlInChat } from '@object-ui/plugin-chatbot';
3030
import { hydratedMessagesToChatMessages } from '../AiChatPage';
31+
// `ChatPane` (reached through `AiChatPage`) loads the grid plugin lazily; pay
32+
// that load at collection, never inside a clocked test window.
33+
import '@object-ui/plugin-grid';
3134
import {
3235
aiMessageRowsToServerMessages,
3336
toUIMessages,
@@ -77,9 +80,32 @@ function hydrateServerRows() {
7780
);
7881
}
7982

83+
/**
84+
* The decision POSTs this file scripts, answered in order. Since
85+
* objectstack#38250 the hook also reads each awaiting card's row once
86+
* (`GET …/pending-actions/:id`); that read is answered 404 here, which leaves
87+
* the card as it is, so the scripted replies reach the decision they were
88+
* written for.
89+
*/
90+
const decisionReplies: Response[] = [];
91+
function decisionReply(reply: Response): void {
92+
decisionReplies.push(reply);
93+
}
94+
function stubDecisionFetch(): void {
95+
decisionReplies.length = 0;
96+
vi.stubGlobal(
97+
'fetch',
98+
vi.fn(async (_url: string, init?: RequestInit) =>
99+
init?.method === 'GET'
100+
? ({ ok: false, status: 404, text: async () => '' } as Response)
101+
: (decisionReplies.shift() as Response),
102+
),
103+
);
104+
}
105+
80106
describe('a rehydrated ModelMessage approval is decidable end to end (objectui#9233)', () => {
81107
beforeEach(() => {
82-
vi.stubGlobal('fetch', vi.fn());
108+
stubDecisionFetch();
83109
});
84110
afterEach(() => {
85111
vi.unstubAllGlobals();
@@ -98,7 +124,7 @@ describe('a rehydrated ModelMessage approval is decidable end to end (objectui#9
98124
// HALF TWO — the decision. Drive the REAL hook over the REAL hydrated
99125
// messages: the id is never persisted as a part key, so the only way it can
100126
// be here is the shared `detectPendingApproval` parse.
101-
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
127+
decisionReply({
102128
ok: true,
103129
text: async () => JSON.stringify({ status: 'executed', result: { deleted: 1 } }),
104130
} as Response);
@@ -110,8 +136,14 @@ describe('a rehydrated ModelMessage approval is decidable end to end (objectui#9
110136
await result.current.decide('c1', true);
111137
});
112138

113-
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
114-
const [url, init] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
139+
// One decision POST. Beside it the hook read the restored card's row once
140+
// by the same id (objectstack#38250) — a second proof the id survived.
141+
const calls = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls;
142+
const posts = calls.filter(([, i]) => (i as RequestInit | undefined)?.method === 'POST');
143+
const reads = calls.filter(([, i]) => (i as RequestInit | undefined)?.method === 'GET');
144+
expect(posts).toHaveLength(1);
145+
expect(reads.map(([u]) => u)).toEqual(['http://localhost:3004/api/v1/ai/pending-actions/pa_44']);
146+
const [url, init] = posts[0];
115147
expect(url).toBe('http://localhost:3004/api/v1/ai/pending-actions/pa_44/approve');
116148
expect((init as RequestInit).method).toBe('POST');
117149
// Not merely "no crash": an unindexed invocation never calls fetch at all —

‎ui/packages/app-shell/src/console/rendererFetch.bearerSession-37225.test.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ describe('the chatbot hooks (plugin-chatbot) under a bearer-only session', () =>
155155
expect(sent.every((request) => request.authorization === `Bearer ${TOKEN}`)).toBe(true);
156156
});
157157

158-
it('useHitlInChat sends the in-chat approval with the stored bearer', async () => {
158+
it('useHitlInChat reads the card’s row and sends the in-chat approval with the stored bearer', async () => {
159159
TokenStorage.set(TOKEN);
160160
const messages = [
161161
{
@@ -171,7 +171,11 @@ describe('the chatbot hooks (plugin-chatbot) under a bearer-only session', () =>
171171
await act(async () => {
172172
await result.current.decide('call_1', true);
173173
});
174-
expect(sent).toEqual([{ path: `${AI}/pending-actions/pa_1/approve`, method: 'POST', ...withBearer }]);
174+
// The awaiting card's row read (objectstack#38250) rides the same channel.
175+
expect(sent).toEqual([
176+
{ path: `${AI}/pending-actions/pa_1`, method: 'GET', ...withBearer },
177+
{ path: `${AI}/pending-actions/pa_1/approve`, method: 'POST', ...withBearer },
178+
]);
175179
expect(result.current.decisions.call_1?.state).not.toBe('error');
176180
});
177181

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,7 +1389,9 @@ describe('sanitizeChatMessagesForCache — a pending approval survives the cache
13891389
* calls the decision made — an empty list means the affordance was dead.
13901390
*/
13911391
async function pressApprove(messages: ReturnType<typeof hydratedMessagesToChatMessages>) {
1392-
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ status: 'executed' }));
1392+
// A fresh Response per call: the row read (objectstack#38250) would
1393+
// otherwise consume the one body the decision POST reads.
1394+
const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => jsonResponse({ status: 'executed' }));
13931395
vi.stubGlobal('fetch', fetchMock);
13941396
const { result } = renderHook(() =>
13951397
useHitlInChat({ messages, apiBase: API_BASE }),
@@ -1398,7 +1400,11 @@ describe('sanitizeChatMessagesForCache — a pending approval survives the cache
13981400
await result.current.decide('tc-approve', true);
13991401
});
14001402
return {
1401-
urls: fetchMock.mock.calls.map((c) => String(c[0])),
1403+
// The decision POSTs only: since objectstack#38250 the hook also reads
1404+
// the restored card's row once (`GET …/pending-actions/:id`).
1405+
urls: fetchMock.mock.calls
1406+
.filter((c) => (c[1] as RequestInit | undefined)?.method === 'POST')
1407+
.map((c) => String(c[0])),
14021408
decision: result.current.decisions['tc-approve'],
14031409
};
14041410
}
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* A chat approval card RESTORED from a saved conversation reads its pending
11+
* action's row and shows where it settled, without waiting for a press
12+
* (objectstack#38250, after objectstack#34255).
13+
*
14+
* The transcript is the proposal, not its outcome: a restored card says
15+
* `approval-requested` whatever became of the item since. Before this, a card
16+
* whose item had lapsed kept Approve and Reject until someone pressed one and
17+
* met the lapse `409`. Now `useHitlInChat` reads each awaiting card's row once
18+
* (`GET …/pending-actions/:id`, the item read `@objectstack/client`'s
19+
* `pendingActions.get` uses): a lapsed row
20+
* reads Expired, a row a person rejected reads as that rejection, and anything
21+
* else, or no answer, leaves the buttons. A press made while the read is still
22+
* out stands when the read lands.
23+
*
24+
* The hook and the card run together and the assertions are on what a person
25+
* sees. Rendered in zh: 已过期 comes only from the pack.
26+
*/
27+
28+
import '@testing-library/jest-dom/vitest';
29+
import * as React from 'react';
30+
import { describe, it, expect, afterEach, vi } from 'vitest';
31+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
32+
import { I18nProvider } from '@object-ui/i18n';
33+
import { ChatbotEnhanced } from '../ChatbotEnhanced';
34+
import { uiMessagesToChatMessages } from '../mapMessages';
35+
import { useHitlInChat } from '../useHitlInChat';
36+
37+
const ZH_EXPIRED = '已过期';
38+
39+
/** A saved conversation's approval, restored: still `approval-requested`. */
40+
const restored = () =>
41+
uiMessagesToChatMessages([
42+
{
43+
id: 'a1',
44+
role: 'assistant',
45+
parts: [
46+
{
47+
type: 'tool-action_delete_task',
48+
toolCallId: 'c1',
49+
state: 'output-available',
50+
input: { id: 't1' },
51+
output: {
52+
type: 'text',
53+
value: JSON.stringify({ status: 'pending_approval', pendingActionId: 'pa_9', message: 'Needs approval' }),
54+
},
55+
},
56+
],
57+
},
58+
]);
59+
60+
function Harness() {
61+
const messages = React.useMemo(() => restored(), []);
62+
const hitl = useHitlInChat({ messages, apiBase: '/api/v1/ai' });
63+
return (
64+
<ChatbotEnhanced
65+
messages={messages}
66+
onSendMessage={vi.fn()}
67+
onToolApprove={hitl.decide}
68+
toolDecisions={hitl.decisions}
69+
toolApproveLabel="APPROVE"
70+
toolDenyLabel="DENY"
71+
/>
72+
);
73+
}
74+
75+
const row = (fields: Record<string, unknown>) => ({
76+
id: 'pa_9',
77+
tool_name: 'action_delete_task',
78+
action_name: 'delete',
79+
object_name: 'task',
80+
tool_input: '{"id":"t1"}',
81+
proposed_at: new Date().toISOString(),
82+
...fields,
83+
});
84+
85+
/** Answer the row read with `body`; any other request fails the test. */
86+
function stubRowRead(status: number, body: unknown) {
87+
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
88+
if (init?.method !== 'GET') throw new Error(`unexpected ${init?.method} ${url}`);
89+
return { ok: status >= 200 && status < 300, status, text: async () => JSON.stringify(body) } as Response;
90+
});
91+
vi.stubGlobal('fetch', fetchMock);
92+
return fetchMock;
93+
}
94+
95+
function renderZh() {
96+
return render(
97+
<I18nProvider config={{ defaultLanguage: 'zh', detectBrowserLanguage: false }}>
98+
<Harness />
99+
</I18nProvider>,
100+
);
101+
}
102+
103+
afterEach(() => {
104+
cleanup();
105+
vi.unstubAllGlobals();
106+
vi.restoreAllMocks();
107+
});
108+
109+
describe('a restored chat approval card reads where its pending action settled (objectstack#38250)', () => {
110+
it('shows Expired for a lapsed row, with no press and no buttons', async () => {
111+
const fetchMock = stubRowRead(200, {
112+
success: true,
113+
data: row({ status: 'rejected', rejection_reason: 'lapsed' }),
114+
});
115+
renderZh();
116+
117+
const strip = await screen.findByTestId('tool-decision');
118+
expect(strip).toHaveAttribute('data-state', 'expired');
119+
expect(strip).toHaveTextContent(ZH_EXPIRED);
120+
expect(screen.queryByText('APPROVE')).not.toBeInTheDocument();
121+
expect(screen.queryByText('DENY')).not.toBeInTheDocument();
122+
// One read of this card's row, and nothing else sent.
123+
expect(fetchMock.mock.calls.map(([u]) => u)).toEqual(['/api/v1/ai/pending-actions/pa_9']);
124+
});
125+
126+
it('keeps a row a person rejected a rejection, never Expired', async () => {
127+
// A decider is recorded, even with "lapsed" typed as the reason.
128+
stubRowRead(200, row({ status: 'rejected', rejection_reason: 'lapsed', decided_by: 'user_2' }));
129+
renderZh();
130+
131+
const strip = await screen.findByTestId('tool-decision');
132+
expect(strip).toHaveAttribute('data-state', 'success');
133+
expect(strip).toHaveTextContent('Rejected: lapsed');
134+
expect(strip).not.toHaveTextContent(ZH_EXPIRED);
135+
expect(screen.queryByText('APPROVE')).not.toBeInTheDocument();
136+
});
137+
138+
it('keeps a press made while the read is still out, when the read then answers lapsed', async () => {
139+
// The row read is held open; the decision answers at once.
140+
let answerRead: (r: Response) => void = () => {};
141+
const heldRead = new Promise<Response>((resolve) => {
142+
answerRead = resolve;
143+
});
144+
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
145+
if (init?.method === 'GET') return heldRead;
146+
if (init?.method === 'POST' && url.endsWith('/pending-actions/pa_9/approve')) {
147+
return { ok: true, status: 200, text: async () => JSON.stringify({ status: 'executed', result: { ok: true } }) } as Response;
148+
}
149+
throw new Error(`unexpected ${init?.method} ${url}`);
150+
});
151+
vi.stubGlobal('fetch', fetchMock);
152+
renderZh();
153+
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
154+
155+
fireEvent.click(screen.getByText('APPROVE'));
156+
const strip = await screen.findByTestId('tool-decision');
157+
await waitFor(() => expect(strip).toHaveAttribute('data-state', 'success'));
158+
expect(strip).toHaveTextContent('Approved — action executed.');
159+
160+
// Only now does the read answer, with a lapsed row.
161+
answerRead({
162+
ok: true,
163+
status: 200,
164+
text: async () => JSON.stringify(row({ status: 'rejected', rejection_reason: 'lapsed' })),
165+
} as Response);
166+
await heldRead;
167+
await new Promise((r) => setTimeout(r, 0));
168+
169+
// The press stands: the late read did not turn the card Expired.
170+
const after = screen.getByTestId('tool-decision');
171+
expect(after).toHaveAttribute('data-state', 'success');
172+
expect(after).toHaveTextContent('Approved — action executed.');
173+
expect(after).not.toHaveTextContent(ZH_EXPIRED);
174+
expect(fetchMock.mock.calls.map(([u, i]) => `${i?.method} ${u}`)).toEqual([
175+
'GET /api/v1/ai/pending-actions/pa_9',
176+
'POST /api/v1/ai/pending-actions/pa_9/approve',
177+
]);
178+
});
179+
180+
it('leaves the buttons for a row still pending, and when the read gets no answer', async () => {
181+
const pending = stubRowRead(200, row({ status: 'pending' }));
182+
renderZh();
183+
await waitFor(() => expect(pending).toHaveBeenCalledTimes(1));
184+
// Let the read settle before looking.
185+
await new Promise((r) => setTimeout(r, 0));
186+
expect(screen.getByText('APPROVE')).toBeInTheDocument();
187+
expect(screen.queryByTestId('tool-decision')).not.toBeInTheDocument();
188+
cleanup();
189+
190+
const missing = stubRowRead(404, { success: false, error: { code: 'NOT_FOUND', message: 'gone' } });
191+
renderZh();
192+
await waitFor(() => expect(missing).toHaveBeenCalledTimes(1));
193+
await new Promise((r) => setTimeout(r, 0));
194+
expect(screen.getByText('APPROVE')).toBeInTheDocument();
195+
expect(screen.queryByTestId('tool-decision')).not.toBeInTheDocument();
196+
});
197+
});

0 commit comments

Comments
 (0)