|
| 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