Skip to content
15 changes: 15 additions & 0 deletions .changeset/37860-ask-ai-opens-new-conversation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
---

feat(app-shell): opening the assistant from 「Ask AI」 after closing it starts a new conversation, and the drawer's header names the conversation (ui ADR-0057 Amendment A5)

Clause-②: no
Metadata-protocol: none

- **What an opening from the entry shows.** The entry is the top bar's 「Ask AI」 button, the keyboard toggle (Ctrl/Cmd+Shift+I), Home's 「Ask AI」 and the record pane's 「Ask AI」. After the user closes the drawer (×, the entry or the toggle again, dismissing the phone sheet), and the first time in a browser tab, it opens a new conversation; the last one stays in history. After the console closed the phone sheet because the page under it moved (a link in an answer, Back), it shows the same conversation. While a write the AI proposed waits for the user's approval in the conversation shown at the close, it shows that conversation. A build conversation (the `build` agent, a package, an app whose `defaultAgent` is `build`) opens as before. A named conversation (a history row, an `/ai…` address), a reload, the assistant bus and filling the window are unchanged.
- **A new conversation leaves no empty row.** It is started with `forceNew`: nothing is created until the first message is sent.
- **The header.** One row in the side panel, the full window and the phone sheet: the conversation's label as the history list shows it ("New conversation" before the first send), then + (a new conversation), the history as an icon button (side panel and sheet; the full window shows the history beside the chat), 「···」 and ×. The drawer is no longer titled "AI Assistant".
- **Writes awaiting approval reach the assistant bus.** The chat now records, per conversation, an AI-proposed write that waits for the user's approval, so the entry's amber marker also shows for it while the chat is closed. The marker's text (`console.ai.dock.planAwaitingApproval`, key unchanged) now reads "An action is waiting for your approval" (「有一项操作等待确认」) in every pack, since no plan is published any more.
- **The record pane's assistant button** reads 「Ask AI」 with the chat-bubble icon, like the top bar's, and opens as the entry does.
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* ui ADR-0057 Amendment A5, row 3 (objectstack#37860) — a conversation holds a
* write awaiting the user's approval while a proposed write the framework
* parked as a pending action has no decision in the chat, or one that failed.
*
* ## Real subjects
*
* The real hydration of stored server rows (the path a reopened conversation
* takes) and the real `useHitlInChat` decisions, as `ChatPane` hands both to
* `countWritesAwaitingApproval` before publishing the answer to the bus.
*/

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, renderHook } from '@testing-library/react';
// `ChatPane` reaches `import('@object-ui/plugin-grid')`; pay its first load at
// collection, never inside a clocked case (`check:test-source-alias`).
import '@object-ui/plugin-grid';
import { useHitlInChat } from '@object-ui/plugin-chatbot';
import { hydratedMessagesToChatMessages } from '../../console/ai/AiChatPage';
import { aiMessageRowsToServerMessages, toUIMessages } from '../../hooks/useChatConversation';
import { countWritesAwaitingApproval } from '../writeApprovalPending';

/** A stored conversation whose last tool call came back as a pending approval. */
function hydratePendingWrite() {
return hydratedMessagesToChatMessages(
toUIMessages(
aiMessageRowsToServerMessages([
{ id: 'u1', role: 'user', content: 'delete the task' },
{
id: 'a1',
role: 'assistant',
content: 'This needs your approval.',
tool_calls: JSON.stringify([
{ type: 'tool-call', toolCallId: 'c1', toolName: 'action_delete_task', input: { id: 't1' } },
]),
},
{
id: 't1',
role: 'tool',
tool_call_id: 'c1',
content: JSON.stringify([
{
type: 'tool-result',
toolCallId: 'c1',
toolName: 'action_delete_task',
output: {
type: 'text',
value: JSON.stringify({ status: 'pending_approval', pendingActionId: 'pa_1', toolName: 'action_delete_task' }),
},
},
]),
},
]),
),
);
}

describe('a write awaiting approval, as the drawer host reads it (objectstack#37860)', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn());
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});

it('a reopened conversation with an undecided pending write counts it', () => {
expect(countWritesAwaitingApproval(hydratePendingWrite(), {})).toBe(1);
});

it('an approval the user made in the chat clears it; a failed one leaves it waiting', async () => {
const messages = hydratePendingWrite();
const fetchMock = globalThis.fetch as ReturnType<typeof vi.fn>;
fetchMock.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ status: 'executed', result: { deleted: 1 } }),
} as Response);
const approved = renderHook(() => useHitlInChat({ messages, apiBase: '/api/v1/ai' }));
await act(async () => {
await approved.result.current.decide('c1', true);
});
expect(approved.result.current.decisions.c1?.state).toBe('success');
expect(countWritesAwaitingApproval(messages, approved.result.current.decisions)).toBe(0);

fetchMock.mockResolvedValueOnce({ ok: false, status: 500, text: async () => 'boom' } as Response);
const failed = renderHook(() => useHitlInChat({ messages, apiBase: '/api/v1/ai' }));
await act(async () => {
await failed.result.current.decide('c1', true);
});
expect(failed.result.current.decisions.c1?.state).toBe('error');
expect(countWritesAwaitingApproval(messages, failed.result.current.decisions)).toBe(1);
});

it('control: a conversation with no parked write has none', () => {
const messages = hydratedMessagesToChatMessages(
toUIMessages(
aiMessageRowsToServerMessages([
{ id: 'u1', role: 'user', content: 'how many accounts?' },
{ id: 'a1', role: 'assistant', content: 'Twelve.' },
]),
),
);
expect(countWritesAwaitingApproval(messages, {})).toBe(0);
});
});
12 changes: 12 additions & 0 deletions ui/packages/app-shell/src/assistant/assistantBus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,18 @@ export function publishPlanApprovalPending(reading: {
for (const l of planApprovalListeners) l();
}

/**
* ui ADR-0057 Amendment A5, row 3 — whether `conversationId` holds a proposal
* awaiting `userId`'s approval, as a mounted chat last read it. Read outside
* render, at the moment the drawer is opened from the entry, so it is a plain
* read, not a hook. A reading taken for another user is no answer.
*/
export function isApprovalPendingIn(conversationId: string | undefined, userId: string | undefined): boolean {
if (!conversationId) return false;
const reading = planApprovalOwners.get(conversationId);
return reading !== undefined && reading.owner === (userId ?? '');
}

/**
* True while any conversation of the signed-in user has a proposed plan
* awaiting approval, as last read by a mounted chat. Read by the launchers.
Expand Down
43 changes: 43 additions & 0 deletions ui/packages/app-shell/src/assistant/writeApprovalPending.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* ui ADR-0057 Amendment A5, row 3 — whether a conversation holds a write the
* AI proposed that still waits for the user's approval: a tool call the
* framework parked as a pending action (`pendingActionId`, state
* `approval-requested`) that the user has not decided in this chat, or whose
* decision failed and so still waits. The chat host publishes the answer to
* the assistant bus (`publishPlanApprovalPending`), where the drawer's host
* reads it when the drawer is opened from the entry.
*/

interface ToolCallReading {
toolCallId: string;
state?: string;
pendingActionId?: string;
}

interface MessageReading {
toolInvocations?: readonly ToolCallReading[];
}

/** The decision a chat holds for one tool call; only its `state` is read. */
interface DecisionReading {
state: string;
}

/** How many proposed writes in `messages` still await the user's approval. */
export function countWritesAwaitingApproval(
messages: readonly MessageReading[],
decisions: Readonly<Record<string, DecisionReading | undefined>>,
): number {
let count = 0;
for (const message of messages) {
for (const tool of message.toolInvocations ?? []) {
if (tool.state !== 'approval-requested' || !tool.pendingActionId) continue;
const decision = decisions[tool.toolCallId];
if (decision === undefined || decision.state === 'error') count += 1;
}
}
return count;
}
20 changes: 20 additions & 0 deletions ui/packages/app-shell/src/console/ai/ChatPane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useObjectTranslation } from '@object-ui/i18n';
import { useAuth } from '@object-ui/auth';
import { translateMetadataType } from '../../views/metadata-admin/i18n.js';
import {
Select,
Expand Down Expand Up @@ -47,6 +48,8 @@ import {
} from '@object-ui/plugin-chatbot/core';

import { useOpenAssistant } from '../../layout/chatDockControl.js';
import { publishPlanApprovalPending } from '../../assistant/assistantBus.js';
import { countWritesAwaitingApproval } from '../../assistant/writeApprovalPending.js';
import type { ChatSurfaceContext } from '../../layout/chatSurfaceContext.js';
import { buildFocusContext, type ConversationFocus } from '../../layout/chatFocus.js';
import { ChatFocusRow } from './ChatFocusRow.js';
Expand Down Expand Up @@ -422,6 +425,23 @@ export function ChatPane({
},
});

// ui ADR-0057 Amendment A5, row 3 — a write the AI proposed that still waits
// for this user's approval is published per conversation to the assistant
// bus, where it outlives this pane: the drawer's host reads it when the
// drawer is next opened from the entry, and reopens this conversation.
const { user } = useAuth();
const approvalOwner = user?.id;
const writesAwaiting = countWritesAwaitingApproval(runtimeMessages, hitl.decisions);
useEffect(() => {
if (!conversationId) return;
publishPlanApprovalPending({
userId: approvalOwner,
conversationId,
pending: writesAwaiting > 0,
count: writesAwaiting,
});
}, [approvalOwner, conversationId, writesAwaiting]);

// The real send, shared by a normal submit and by the deferred-first-message
// replay below (resetSuppression → send → onSent, in that order).
//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => {
import { I18nProvider } from '@object-ui/i18n';
import type { AgentDescriptor } from '@object-ui/plugin-chatbot';
import { ChatPane } from '../AiChatPage';
import { isApprovalPendingIn, publishPlanApprovalPending } from '../../../assistant/assistantBus';

window.matchMedia = ((query: string) => ({
matches: false,
Expand Down Expand Up @@ -207,3 +208,22 @@ describe('AI chat tool-approval labels follow the UI locale (objectui#11667)', (
expect(JSON.parse(String((init as RequestInit).body))).toEqual({ reason: 'Operator rejected from chat' });
});
});

// ui ADR-0057 Amendment A5, row 3 (objectstack#37860) — the pane publishes a
// write awaiting approval to the assistant bus, per conversation, where the
// drawer's host reads it when the drawer is next opened from the entry; the
// user's decision in the chat clears it. Same fixture, same real pane.
describe('the pane tells the assistant bus a write awaits approval (objectstack#37860)', () => {
afterEach(() => publishPlanApprovalPending({ userId: undefined, conversationId: 'conv-1', pending: false }));

it('pending while the card waits; cleared once the user decides', async () => {
renderPane('en');
expect(await screen.findByRole('button', { name: 'Reject' })).toBeInTheDocument();
expect(isApprovalPendingIn('conv-1', undefined)).toBe(true);
// Control: the reading is the conversation's, not every conversation's.
expect(isApprovalPendingIn('conv-2', undefined)).toBe(false);

fireEvent.click(screen.getByRole('button', { name: 'Reject' }));
await waitFor(() => expect(isApprovalPendingIn('conv-1', undefined)).toBe(false));
});
});
46 changes: 46 additions & 0 deletions ui/packages/app-shell/src/hooks/useConversationList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,49 @@ export function useConversationList(

return { conversations, isLoading, error, refetch, remove, rename };
}

export interface UseConversationLabelOptions {
apiBase: string;
/** The conversation the drawer shows; absent before the first send creates it. */
conversationId: string | undefined;
/** Bump to read the label again (a sent turn, the server titling the thread). */
refreshKey?: number | string;
}

export interface ConversationLabelReading {
/** The label the history list gives this conversation's row; absent when it has none yet. */
label: string | undefined;
/** False while the label of the conversation now shown has not been read yet. */
settled: boolean;
}

/**
* ui ADR-0057 Amendment A5 — the drawer's header names the conversation it
* shows by the label its history row carries: the title the server gave it,
* else the latest message the user wrote in it (`normalize`, the list's own
* reading of one row). A read that fails settles with no label.
*/
export function useConversationLabel({
apiBase,
conversationId,
refreshKey,
}: UseConversationLabelOptions): ConversationLabelReading {
const [reading, setReading] = useState<{ id: string; label: string | undefined } | undefined>(undefined);
useEffect(() => {
if (!conversationId) return;
let cancelled = false;
fetchConversationDetail(apiBase, conversationId).then(
(row) => {
if (!cancelled) setReading({ id: conversationId, label: row?.title || row?.preview || undefined });
},
() => {
if (!cancelled) setReading({ id: conversationId, label: undefined });
},
);
return () => {
cancelled = true;
};
}, [apiBase, conversationId, refreshKey]);
if (!conversationId) return { label: undefined, settled: true };
return reading?.id === conversationId ? { label: reading.label, settled: true } : { label: undefined, settled: false };
}
25 changes: 15 additions & 10 deletions ui/packages/app-shell/src/layout/AssistantTopBarButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
* entry: it opens and closes the right-side drawer without leaving the page.
* The floating bottom-right button it replaces is gone; what that button
* carried moved here:
* - objectui#11666 — while a proposed plan awaits the user's approval the
* - objectui#11666 — while something the AI proposed awaits the user's
* approval (since ui ADR-0057 A5, a write parked as a pending action) the
* entry carries a marker, so a user who closed the chat still sees the
* assistant is waiting on them. Read off the assistant bus; only a change
* of the plan's state clears it, never opening the chat.
* of that approval's state clears it, never opening the chat.
*
* objectstack#37858 — the entry is an outlined button that says what it does,
* 「Ask AI」, beside a chat-bubble icon, on every page: the
Expand Down Expand Up @@ -56,22 +57,26 @@ function isMacPlatform(): boolean {

/**
* The Ask AI entry's opening, for a button elsewhere on a page that asks the
* assistant the way the standing entry does — Home's 「Ask AI」. Absent a
* target it opens the drawer on whatever it shows now: the drawer's own
* toggle, which is what the standing button runs (a handoff the drawer still
* holds is kept); with one, on that target. Under no drawer host it goes to
* the pre-drawer address. What opening means changes here and in the
* button's toggle together.
* assistant the way the standing entry does — Home's 「Ask AI」, the record
* pane's. With the drawer closed it is an opening from the entry (ui ADR-0057
* Amendment A5, the host's `openEntry`): a new conversation after the user's
* own close, else as A5's table says; a target's `agent` is the agent the
* entry asks. With the drawer open, a target opens on it as before and no
* target leaves the drawer as it is. Under no drawer host it goes to the
* pre-drawer address.
*/
export function useAskAiEntry(): (target?: ChatDockTarget) => void {
const control = useChatDockControl();
const openAssistant = useOpenAssistant();
return React.useCallback(
(target?: ChatDockTarget) => {
if (control && target === undefined) {
if (!control.expanded) control.toggle();
if (control && !control.expanded) {
if (control.openEntry) control.openEntry(target?.agent);
else if (target === undefined) control.toggle();
else control.open(target);
return;
}
if (control && target === undefined) return;
openAssistant(target);
},
[control, openAssistant],
Expand Down
Loading
Loading