This is an automated email from the ASF dual-hosted git repository.
voidmatcha pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/zeppelin.git
The following commit(s) were added to refs/heads/master by this push:
new af17379078 [ZEPPELIN-6776] Preserve unsent Assistant drafts when
reopening the notebook sidebar
af17379078 is described below
commit af17379078e5dda5b60deda80ceeb402ac9a9e73
Author: Minho Jang <[email protected]>
AuthorDate: Sat Nov 28 19:31:05 2026 +0900
[ZEPPELIN-6776] Preserve unsent Assistant drafts when reopening the
notebook sidebar
### What is this PR for?
Closing the AI Assistant sidebar discards unsent text. Reopening it on the
same notebook in the same authenticated session now restores each draft to the
conversation it belongs to, including the draft for a conversation that has not
been created yet.
Each conversation session decides what to retain when the sidebar closes.
An already submitted run can finish while the sidebar is closed, and restoring
a draft does not create a conversation or send a question. A successful pending
deletion removes the draft with its conversation; a failed deletion leaves the
draft intact. Drafts do not carry over to another notebook, authenticated
session, or page reload.
### What type of PR is it?
Improvement
### What is the Jira issue?
* https://issues.apache.org/jira/browse/ZEPPELIN-6776
### How should this be tested?
From `zeppelin-web-angular/projects/zeppelin-react`, run:
```bash
npm test -- AssistantWorkspace.spec.tsx useAssistantPanel.spec.tsx
AssistantConversationPanel.spec.tsx
```
1. Type a question without sending it, close the sidebar, and reopen it on
the same notebook. Verify that the text is restored and no question is sent.
2. Start a response in conversation A, switch to B, and type an unsent
draft. Close and reopen the sidebar before or after A finishes. Verify that A's
answer and B's draft are both available without resubmitting either.
3. Switch to another notebook or authenticated session and verify that the
draft does not carry over.
### Questions:
* Does the license files need to update? No.
* Is there breaking changes for older versions? No.
* Does this needs documentation? No.
Closes #5622 from miinhho/ZEPPELIN-6776-assistant-draft-reopen.
Signed-off-by: YONGJAE LEE <[email protected]>
---
.../src/pages/AssistantWorkspace.spec.tsx | 260 +++++++++++++++++++--
.../model/assistantConversation.ts | 58 +++--
.../assistant-workspace/model/assistantHistory.ts | 19 +-
.../model/assistantPanelModel.ts | 93 ++++----
.../model/useAssistantPanel.spec.tsx | 93 ++++++++
5 files changed, 440 insertions(+), 83 deletions(-)
diff --git
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/AssistantWorkspace.spec.tsx
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/AssistantWorkspace.spec.tsx
index 09a26c4911..255bf88db3 100644
---
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/AssistantWorkspace.spec.tsx
+++
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/AssistantWorkspace.spec.tsx
@@ -11,7 +11,7 @@
*/
import { act, StrictMode } from 'react';
-import { fireEvent, render, screen, type RenderResult } from
'@testing-library/react';
+import { fireEvent, render, screen, within, type RenderResult } from
'@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
NOTEBOOK_SIDEBAR_WIDTH,
@@ -357,6 +357,65 @@ describe('AssistantWorkspace', () => {
expect(onPanelVisibilityChange).toHaveBeenLastCalledWith(true);
});
+ it('restores an unsent new conversation without sending and ignores the
previous list response', async () => {
+ const oldList = Promise.withResolvers<Response>();
+ const socket = socketHarness();
+ const fetch = vi
+ .fn()
+ .mockReturnValueOnce(oldList.promise)
+ .mockResolvedValueOnce(json([conversation]));
+ vi.stubGlobal('fetch', fetch);
+ const { open } = await setup({ connection: connection(socket) });
+ await open();
+ await act(async () => fireEvent.change(question(), { target: { value:
'Keep this unsent question' } }));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Close AI Assistant' })));
+ await open();
+ expect(question().value).toBe('Keep this unsent question');
+
+ await act(async () => oldList.resolve(json([{ ...conversation, id: 'old',
title: 'Obsolete conversation' }])));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Open conversations' })));
+ expect(screen.getByRole('button', { name: /^Saved conversation/
})).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /^Obsolete conversation/
})).toBeNull();
+ expect(fetch.mock.calls).toEqual([
+ ['/zeppelin/api/notes/note-a/conversations', expect.objectContaining({
method: 'GET' })],
+ ['/zeppelin/api/notes/note-a/conversations', expect.objectContaining({
method: 'GET' })]
+ ]);
+ expect(socket.send).not.toHaveBeenCalled();
+ });
+
+ it('does not show an empty conversation list while reloading a restored
draft', async () => {
+ const reload = Promise.withResolvers<Response>();
+ const socket = socketHarness();
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(json([conversation]))
+ .mockReturnValueOnce(reload.promise)
+ );
+ const { open } = await setup({ connection: connection(socket) });
+ const openList = async () =>
+ act(async () => fireEvent.click(screen.getByRole('button', { name: 'Open
conversations' })));
+
+ await open();
+ await openList();
+ expect(screen.getByRole('button', { name: /^Saved conversation/
})).toBeTruthy();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Back' })));
+ await act(async () => fireEvent.change(question(), { target: { value:
'Keep this unsent question' } }));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Close AI Assistant' })));
+
+ await open();
+ expect(question().value).toBe('Keep this unsent question');
+ await openList();
+ expect(screen.getByText('Loading conversations…')).toBeTruthy();
+ expect(screen.queryByText('No conversations yet.')).toBeNull();
+
+ await act(async () => reload.resolve(json([])));
+ expect(screen.queryByText('Loading conversations…')).toBeNull();
+ expect(screen.getByText('No conversations yet.')).toBeTruthy();
+ expect(socket.send).not.toHaveBeenCalled();
+ });
+
it('uses the host REST and socket by default and resolves saved and
streaming paragraph references', async () => {
const paragraphId = 'paragraph_1423500782552_-1439281894';
const unknownId = 'paragraph_1423500782553_1439281894';
@@ -509,15 +568,27 @@ describe('AssistantWorkspace', () => {
expect(socket.consumers()).toEqual([0, 0]);
});
- it('keeps the submitted run across slot removal without restoring unrelated
drafts or auth errors', async () => {
+ it.each(['before', 'after'] as const)('keeps a separate draft when reopened
%s completion', async reopen => {
const socket = socketHarness();
const host = connection(socket);
const oldHistory = Promise.withResolvers<Response>();
const empty = { messages: [], cursor: null };
+ let completed = false;
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
if (url.includes('/unrelated-history/messages')) return
oldHistory.promise;
+ if (url.includes('/saved/messages') && completed) {
+ return Promise.resolve(
+ json({
+ messages: [
+ { id: 'a1', role: 'assistant', content: 'Saved final reply' },
+ { id: 'u1', role: 'user', content: 'Keep the submitted run' }
+ ],
+ cursor: null
+ })
+ );
+ }
if (url.includes('/messages')) return Promise.resolve(json(empty));
return Promise.resolve(
json([
@@ -541,7 +612,7 @@ describe('AssistantWorkspace', () => {
socket.emit({ conversationId: 'saved', type: 'message.delta', payload: {
messageId: 'a1', delta: 'Reply' } });
});
await select(/^Other conversation/);
- await act(async () => fireEvent.change(question(), { target: { value: 'Do
not keep this draft' } }));
+ await act(async () => fireEvent.change(question(), { target: { value:
'Keep this separate draft' } }));
await select(/^Pending history/);
await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Close AI Assistant' })));
await update({ slots: [] });
@@ -552,17 +623,26 @@ describe('AssistantWorkspace', () => {
payload: { messageId: 'a1', delta: ' continues' }
});
});
- await update({ slots });
- await open();
+ const restorePanel = async () => {
+ await update({ slots });
+ await open();
+ };
+ if (reopen === 'before') await restorePanel();
+ expect(Boolean(screen.queryByText('Reply continues'))).toBe(reopen ===
'before');
- expect(screen.getByText('Reply continues')).toBeTruthy();
+ completed = true;
+ await act(async () => socket.emit({ conversationId: 'saved', type:
'run.completed', payload: { runId: 'run-1' } }));
+ if (reopen === 'after') await restorePanel();
+ expect(screen.getAllByText('Saved final reply')).toHaveLength(1);
+ expect(screen.getAllByText('Keep the submitted run')).toHaveLength(1);
await act(async () =>
oldHistory.resolve(new Response(null, { status: 401, headers: {
Location: '/obsolete-login' } }))
);
expect(host.onAuthError).not.toHaveBeenCalled();
await select(/^Other conversation/);
- expect(question().value).toBe('');
+ expect(question().value).toBe('Keep this separate draft');
expect(socket.send).toHaveBeenCalledTimes(1);
+ expect(socket.consumers()).toEqual([0, 0]);
});
it.each(['note', 'session', 'unmount'] as const)(
@@ -589,6 +669,8 @@ describe('AssistantWorkspace', () => {
});
expect(screen.getByText('Previous session answer')).toBeTruthy();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'New conversation' })));
+ await act(async () => fireEvent.change(question(), { target: { value:
'Previous session draft' } }));
await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Close AI Assistant' })));
switch (change) {
case 'note':
@@ -612,6 +694,8 @@ describe('AssistantWorkspace', () => {
);
if (change !== 'unmount') await open();
expect(screen.queryByText(/Previous session answer|Late old
answer/)).toBeNull();
+ const field = screen.queryByRole('textbox', { name: 'Question' }) as
HTMLTextAreaElement | null;
+ expect(field?.value).toBe(change === 'unmount' ? undefined : '');
expect(socket.send).toHaveBeenCalledTimes(1);
}
);
@@ -652,16 +736,29 @@ describe('AssistantWorkspace', () => {
}
);
- it.each(['close', 'note', 'session', 'unmount'] as const)('ignores late
history data after %s', async change => {
+ it.each(['close', 'note', 'session', 'unmount'] as const)('ignores stale
history after %s', async change => {
const pending = Promise.withResolvers<Response>();
- const host = connection();
- const fetch = vi.fn((url: string) =>
- url.includes('/messages') ? pending.promise :
Promise.resolve(json([conversation]))
- );
+ const socket = socketHarness();
+ const host = connection(socket);
+ let historyRequests = 0;
+ const fetch = vi.fn((url: string, _options?: RequestInit) => {
+ if (!url.includes('/messages')) return
Promise.resolve(json([conversation]));
+ if (++historyRequests === 1) return pending.promise;
+ return Promise.resolve(
+ json({ messages: [{ id: 'current', role: 'assistant', content:
'Current saved answer' }], cursor: null })
+ );
+ });
vi.stubGlobal('fetch', fetch);
const { open, update, unmount } = await setup({ connection: host });
await open();
await selectSaved();
+ await act(async () => fireEvent.change(question(), { target: { value:
'Existing conversation draft' } }));
+ expect(screen.getByText('Loading conversation…')).toBeTruthy();
+ expect(historyRequests).toBe(1);
+ expect(fetch).toHaveBeenCalledWith(
+ expect.stringContaining('/notes/note-a/conversations/saved/messages'),
+ expect.objectContaining({ method: 'GET' })
+ );
switch (change) {
case 'close':
await act(async () => fireEvent.click(screen.getByRole('button', {
name: 'Close AI Assistant' })));
@@ -677,15 +774,89 @@ describe('AssistantWorkspace', () => {
break;
}
expect(screen.queryByRole('complementary')).toBeNull();
- if (change !== 'unmount') await open();
+ if (change !== 'unmount') {
+ await open();
+ if (change !== 'close') await selectSaved();
+ }
+ expect(historyRequests).toBe(change === 'unmount' ? 1 : 2);
+ expect(Boolean(screen.queryByText('Current saved answer'))).toBe(change
!== 'unmount');
await act(async () =>
pending.resolve(
json({ messages: [{ id: 'old', role: 'assistant', content: 'Obsolete
saved answer' }], cursor: null })
)
);
expect(screen.queryByText('Obsolete saved answer')).toBeNull();
+ expect(Boolean(screen.queryByText('Current saved answer'))).toBe(change
!== 'unmount');
const field = screen.queryByRole('textbox', { name: 'Question' }) as
HTMLTextAreaElement | null;
- expect(field?.value).toBe(change === 'unmount' ? undefined : '');
+ expect(field?.value).toBe(
+ change === 'close' ? 'Existing conversation draft' : change ===
'unmount' ? undefined : ''
+ );
+ expect(fetch.mock.calls.every(([, options]) => options?.method ===
'GET')).toBe(true);
+ expect(socket.send).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { result: 'succeeds', settles: 'before' },
+ { result: 'succeeds', settles: 'after' },
+ { result: 'fails', settles: 'before' },
+ { result: 'fails', settles: 'after' }
+ ])('handles an outstanding draft deletion that $result $settles reopening',
async ({ result, settles }) => {
+ const oldHistory = Promise.withResolvers<Response>();
+ const deletion = Promise.withResolvers<Response>();
+ const socket = socketHarness();
+ const succeeds = result === 'succeeds';
+ let deleted = false;
+ let historyRequests = 0;
+ const fetch = vi.fn((url: string, options?: RequestInit) => {
+ if (options?.method === 'DELETE') return deletion.promise;
+ if (!url.includes('/messages')) return Promise.resolve(json(deleted ? []
: [conversation]));
+ if (++historyRequests === 1) return oldHistory.promise;
+ if (deleted) return Promise.resolve(new Response(null, { status: 404 }));
+ return Promise.resolve(
+ json({ messages: [{ id: 'current', role: 'assistant', content:
'Current saved answer' }], cursor: null })
+ );
+ });
+ vi.stubGlobal('fetch', fetch);
+ const { open } = await setup({ connection: connection(socket) });
+ await open();
+ await selectSaved();
+ await act(async () => fireEvent.change(question(), { target: { value:
'Unsent deletion draft' } }));
+ expect(screen.getByText('Loading conversation…')).toBeTruthy();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Delete Saved conversation' })));
+ const confirm = within(screen.getByRole('dialog')).getByRole('button', {
name: 'Delete conversation' });
+ await act(async () => fireEvent.click(confirm));
+ expect(fetch).toHaveBeenCalledWith(
+ '/zeppelin/api/notes/note-a/conversations/saved',
+ expect.objectContaining({ method: 'DELETE' })
+ );
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Close AI Assistant' })));
+ expect(screen.queryByRole('complementary')).toBeNull();
+ if (settles === 'after') await open();
+ expect(historyRequests).toBe(1);
+
+ await act(async () =>
+ oldHistory.resolve(
+ json({ messages: [{ id: 'old', role: 'assistant', content: 'Obsolete
saved answer' }], cursor: null })
+ )
+ );
+ expect(screen.queryByText('Obsolete saved answer')).toBeNull();
+ expect(historyRequests).toBe(1);
+
+ await act(async () => {
+ deleted = succeeds;
+ deletion.resolve(new Response(null, { status: succeeds ? 204 : 500 }));
+ });
+ expect(historyRequests).toBe(!succeeds && settles === 'after' ? 2 : 1);
+ if (settles === 'before') await open();
+
+ expect(historyRequests).toBe(succeeds ? 1 : 2);
+ expect(question().value).toBe(succeeds ? '' : 'Unsent deletion draft');
+ expect(screen.queryByText('Obsolete saved answer')).toBeNull();
+ expect(Boolean(screen.queryByText('Current saved
answer'))).toBe(!succeeds);
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Open conversations' })));
+ expect(Boolean(screen.queryByRole('button', { name: /^Saved conversation/
}))).toBe(!succeeds);
+ expect(fetch.mock.calls.filter(([, options]) => options?.method !==
'GET')).toHaveLength(1);
+ expect(socket.send).not.toHaveBeenCalled();
});
it.each(['close', 'note', 'session', 'unmount'] as const)(
@@ -694,14 +865,17 @@ describe('AssistantWorkspace', () => {
const pending = Promise.withResolvers<Response>();
const socket = socketHarness();
const host = connection(socket);
- vi.stubGlobal(
- 'fetch',
- vi.fn((_url: string, options?: RequestInit) =>
- options?.method === 'POST' ? pending.promise :
Promise.resolve(json([]))
- )
- );
+ const fetch = vi.fn((url: string, options?: RequestInit) => {
+ if (options?.method === 'POST') return pending.promise;
+ if (url.includes('/messages')) return Promise.resolve(json({ messages:
[], cursor: null }));
+ return Promise.resolve(json([conversation]));
+ });
+ vi.stubGlobal('fetch', fetch);
const { open, update, unmount } = await setup({ connection: host });
await open();
+ await selectSaved();
+ await act(async () => fireEvent.change(question(), { target: { value:
'Unrelated unsent draft' } }));
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'New conversation' })));
await submit('Obsolete creation');
switch (change) {
case 'close':
@@ -718,10 +892,21 @@ describe('AssistantWorkspace', () => {
break;
}
if (change !== 'unmount') await open();
- await act(async () => pending.resolve(json(conversation, 201)));
+ await act(async () => pending.resolve(json({ ...conversation, id:
'created', title: 'Obsolete creation' }, 201)));
expect(socket.send).not.toHaveBeenCalled();
const field = screen.queryByRole('textbox', { name: 'Question' }) as
HTMLTextAreaElement | null;
expect(field?.value).toBe(change === 'unmount' ? undefined : '');
+ if (change !== 'unmount') await selectSaved();
+ const savedField = screen.queryByRole('textbox', { name: 'Question' })
as HTMLTextAreaElement | null;
+ expect(savedField?.value).toBe(
+ change === 'close' ? 'Unrelated unsent draft' : change === 'unmount' ?
undefined : ''
+ );
+ // None of the list responses contain the newly created ID, so only the
obsolete POST could introduce it.
+ if (change !== 'unmount') {
+ await act(async () => fireEvent.click(screen.getByRole('button', {
name: 'Open conversations' })));
+ }
+ expect(screen.queryByRole('button', { name: /^Obsolete creation/
})).toBeNull();
+ expect(fetch.mock.calls.filter(([, options]) => options?.method ===
'POST')).toHaveLength(1);
}
);
@@ -739,13 +924,16 @@ describe('AssistantWorkspace', () => {
expect(socket.send).not.toHaveBeenCalled();
});
- it('keeps unknown outcome after a real history reload and a subsequent 409
without automatically resending', async () => {
+ it('preserves unknown outcome through reopen, history reload, and an
explicit retry rejected with 409', async () => {
const socket = socketHarness();
+ const oldHistory = Promise.withResolvers<Response>();
+ let historyRequests = 0;
vi.stubGlobal(
'fetch',
- vi.fn((url: string) =>
- Promise.resolve(url.includes('/messages') ? json({ messages: [],
cursor: null }) : json([conversation]))
- )
+ vi.fn((url: string) => {
+ if (!url.includes('/messages')) return
Promise.resolve(json([conversation]));
+ return ++historyRequests === 2 ? oldHistory.promise :
Promise.resolve(json({ messages: [], cursor: null }));
+ })
);
const { open } = await setup({ connection: connection(socket) });
await open();
@@ -754,6 +942,21 @@ describe('AssistantWorkspace', () => {
await act(async () => socket.close());
expect(screen.getByText(/The outcome of an earlier question is
unknown/)).toBeTruthy();
await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Reload conversation' })));
+ expect(historyRequests).toBe(2);
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Close AI Assistant' })));
+ await open();
+ await act(async () =>
+ oldHistory.resolve(
+ json({ messages: [{ id: 'old', role: 'assistant', content: 'Obsolete
saved answer' }], cursor: null })
+ )
+ );
+ expect(historyRequests).toBe(2);
+ expect(screen.queryByText('Obsolete saved answer')).toBeNull();
+ expect(screen.getByText(/The outcome of an earlier question is
unknown/)).toBeTruthy();
+ expect(question().value).toBe('Uncertain question');
+ expect(socket.send).toHaveBeenCalledTimes(1);
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Reload conversation' })));
+ expect(historyRequests).toBe(3);
expect(screen.getByText(/The outcome of an earlier question is
unknown/)).toBeTruthy();
expect(socket.send).toHaveBeenCalledTimes(1);
@@ -766,6 +969,13 @@ describe('AssistantWorkspace', () => {
expect(question().value).toBe('Explicit new submission');
expect(socket.send).toHaveBeenCalledTimes(2);
expect(socket.consumers()).toEqual([0, 0]);
+
+ await act(async () => fireEvent.click(screen.getByRole('button', { name:
'Close AI Assistant' })));
+ await open();
+ expect(screen.getByText(/The outcome of an earlier question is
unknown/)).toBeTruthy();
+ expect(question().value).toBe('Explicit new submission');
+ expect(historyRequests).toBe(3);
+ expect(socket.send).toHaveBeenCalledTimes(2);
});
it('marks the toggle as pressed while the panel is open', async () => {
diff --git
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantConversation.ts
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantConversation.ts
index 4f90947e8e..c292ddc07c 100644
---
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantConversation.ts
+++
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantConversation.ts
@@ -32,7 +32,8 @@ export class AssistantConversationSession {
private uncertainty?: string;
private submittedQuestion?: string;
private deleting = false;
- private historyRefreshPending = false;
+ private postRunHistoryRefreshPending = false;
+ private deferredInitialHistory?: 'awaiting-selection' | 'awaiting-delete';
private disposed = false;
private controller?: AbortController;
@@ -57,10 +58,6 @@ export class AssistantConversationSession {
return this.entry;
}
- get hasSubmittedRun(): boolean {
- return this.phase === 'pending' || this.phase === 'running';
- }
-
/** Does not emit a change notification. */
updateConversation(conversation: AssistantConversation): void {
const current = this.conversation;
@@ -109,9 +106,37 @@ export class AssistantConversationSession {
this.changed();
}
- ensureHistory(): void {
- const history = this.history.snapshot;
- if (!history.loaded && !history.loading && !this.deleting && this.phase
=== 'idle') void this.reload();
+ onSidebarClosed(): 'submitted-run' | 'draft' | 'discarded' {
+ if (this.phase === 'pending' || this.phase === 'running') return
'submitted-run';
+
+ // A pending create is part of a submission, not an unsent draft.
+ if (!this.draft || this.phase === 'creating') {
+ this.dispose();
+ return 'discarded';
+ }
+
+ this.postRunHistoryRefreshPending = false;
+ this.deferredInitialHistory = this.deleting && !this.entry.loaded ?
'awaiting-selection' : undefined;
+ if (this.deleting || this.uncertainty) {
+ this.history.ignorePendingResponses();
+ } else {
+ // Keep the draft and its conversation, not the history and errors from
the closed view.
+ this.history.reset(!!this.conversation);
+ this.failure = undefined;
+ this.submittedQuestion = undefined;
+ }
+
+ this.publish();
+ return 'draft';
+ }
+
+ onSelected(): void {
+ if (this.entry.loaded || this.entry.loading || this.phase !== 'idle')
return;
+ if (this.deleting) {
+ if (this.deferredInitialHistory === 'awaiting-selection')
this.deferredInitialHistory = 'awaiting-delete';
+ return;
+ }
+ void this.reload(this.deferredInitialHistory !== undefined);
}
async reload(preserveFailure = false): Promise<void> {
@@ -119,7 +144,8 @@ export class AssistantConversationSession {
return;
}
- this.historyRefreshPending = false;
+ this.postRunHistoryRefreshPending = false;
+ this.deferredInitialHistory = undefined;
if (!preserveFailure) this.failure = undefined;
const result = await this.history.loadLatest(this.source.api,
this.conversation.id);
if (this.disposed || result.status === 'ignored' ||
!this.history.isCurrent(result)) return;
@@ -137,8 +163,8 @@ export class AssistantConversationSession {
this.publish();
}
- private async refreshHistory(): Promise<void> {
- if (!this.historyRefreshPending || this.disposed || this.deleting ||
this.phase !== 'idle') return;
+ private async refreshHistoryAfterRun(): Promise<void> {
+ if (!this.postRunHistoryRefreshPending || this.disposed || this.deleting
|| this.phase !== 'idle') return;
await this.reload(this.failure?.kind === 'failed');
}
@@ -189,7 +215,7 @@ export class AssistantConversationSession {
this.submittedQuestion = content;
this.failure = undefined;
this.phase = this.conversation ? 'pending' : 'creating';
- if (this.history.snapshot.loading) this.historyRefreshPending = true;
+ if (this.history.snapshot.loading) this.postRunHistoryRefreshPending =
true;
const answerKey = this.history.beginTurn();
const conversation = this.conversation ?? (await
this.createConversation(controller));
@@ -241,12 +267,12 @@ export class AssistantConversationSession {
if (this.disposed) return;
// The next send must wait for this consumer to release the conversation.
- this.historyRefreshPending ||= run.snapshot.outcome === 'completed';
+ this.postRunHistoryRefreshPending ||= run.snapshot.outcome === 'completed';
this.phase = run.snapshot.outcome === 'unknown' ? 'unknown' : 'idle';
this.publish();
if (run.snapshot.accepted) this.activity();
- await this.refreshHistory();
+ await this.refreshHistoryAfterRun();
}
private async createConversation(controller: AbortController):
Promise<AssistantConversation | undefined> {
@@ -294,7 +320,9 @@ export class AssistantConversationSession {
this.deleting = false;
this.failure = { message, kind: 'failed' };
this.publish();
- void this.refreshHistory();
+ // Resume a discarded initial GET only if the view selected this session
while DELETE was pending.
+ if (this.deferredInitialHistory === 'awaiting-delete') void
this.reload(true);
+ else void this.refreshHistoryAfterRun();
return { status: 'failed', message };
}
diff --git
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantHistory.ts
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantHistory.ts
index 37769baa08..5c91c036a3 100644
---
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantHistory.ts
+++
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantHistory.ts
@@ -217,7 +217,7 @@ export class AssistantHistory {
/** Starts a new turn and retains any preceding unreconciled answer. */
beginTurn(): string {
- this.invalidateRequests();
+ this.ignorePendingResponses();
this.promoteTurn();
const sequence = ++this.turnSequence;
@@ -264,11 +264,24 @@ export class AssistantHistory {
this.changed();
}
- private invalidateRequests(): void {
+ /** Makes in-flight results ineligible to commit without cancelling HTTP or
clearing loaded history. */
+ ignorePendingResponses(): void {
++this.requestVersion;
this.requestStatus = 'idle';
}
+ reset(hasConversation: boolean): void {
+ this.ignorePendingResponses();
+ this.messages = [];
+ this.messageKeys = new Map();
+ this.localAnswerViews = new Map();
+ this.cursor = null;
+ this.loaded = !hasConversation;
+ this.consumedCursors.clear();
+ this.turnSequence = 0;
+ this.turn = undefined;
+ }
+
async loadLatest(api: AssistantConversationApi, conversationId: string):
Promise<HistoryLoadResult> {
if (this.disposed) return { status: 'ignored' };
@@ -349,6 +362,6 @@ export class AssistantHistory {
dispose(): void {
this.disposed = true;
- this.invalidateRequests();
+ this.ignorePendingResponses();
}
}
diff --git
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantPanelModel.ts
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantPanelModel.ts
index 52954bd2e7..aa45c0003f 100644
---
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantPanelModel.ts
+++
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/assistantPanelModel.ts
@@ -37,7 +37,7 @@ export class AssistantPanelModel {
private active = false;
private generation = 0;
private listVersion = 0;
- private closedWithRun = false;
+ private closed = false;
private snapshot: AssistantPanel;
constructor(private readonly source: AssistantDataSource) {
@@ -52,33 +52,42 @@ export class AssistantPanelModel {
return () => this.listeners.delete(listener);
};
- /** Discard view state except for conversations with a submitted run. */
+ /** Keep submitted runs and unsent text, but discard ordinary history
requests with the view. */
close(): boolean {
- let firstRun: string | undefined;
- this.sessions.forEach(session => {
- if (session.hasSubmittedRun) firstRun ??= session.key;
- });
- if (firstRun === undefined) return false;
-
- this.closedWithRun = true;
+ this.closed = true;
++this.listVersion;
+
+ let firstRun: string | undefined;
+ let hasDraft = false;
this.sessions.forEach((session, key) => {
- if (session.hasSubmittedRun) return;
- session.dispose();
- this.sessions.delete(key);
+ const retention = session.onSidebarClosed();
+ if (retention === 'submitted-run') firstRun ??= key;
+ else if (retention === 'draft') hasDraft = true;
+ else this.sessions.delete(key);
});
- this.draftKey = undefined;
- if (!this.sessions.has(this.selectedKey)) this.selectedKey = firstRun;
- this.publish();
+ if (firstRun === undefined) {
+ if (!hasDraft) return false;
+ this.conversationList = INITIAL_CONVERSATION_LIST;
+ this.deleted.clear();
+ } else {
+ this.conversationList = { ...this.conversationList, loading: true,
error: undefined };
+ }
+
+ if (this.draftKey && !this.sessions.has(this.draftKey)) this.draftKey =
undefined;
+ if (!this.sessions.has(this.selectedKey)) {
+ if (firstRun !== undefined) this.selectedKey = firstRun;
+ else this.selectDraft();
+ }
+ this.snapshot = this.project();
return true;
}
reopen(): void {
- if (!this.closedWithRun) return;
- this.closedWithRun = false;
- this.conversationList = { ...this.conversationList, loading: true, error:
undefined };
+ if (!this.closed) return;
+ this.closed = false;
this.publish();
this.refreshConversations();
+ this.sessions.get(this.selectedKey)!.onSelected();
}
start(): void {
@@ -86,7 +95,7 @@ export class AssistantPanelModel {
this.active = true;
const generation = ++this.generation;
- this.closedWithRun = false;
+ this.closed = false;
this.sessions.forEach(session => session.dispose());
this.sessions.clear();
@@ -153,11 +162,13 @@ export class AssistantPanelModel {
}
private readonly refreshConversations = (): void => {
- if (this.active && !this.closedWithRun) void
this.loadList(this.generation);
+ if (this.active && !this.closed) void this.loadList(this.generation);
};
readonly retryList = (): Promise<void> => {
- if (!this.active || this.conversationList.loading ||
!this.conversationList.error) return Promise.resolve();
+ if (!this.active || this.closed || this.conversationList.loading ||
!this.conversationList.error) {
+ return Promise.resolve();
+ }
this.conversationList = { ...this.conversationList, loading: true };
this.publish();
@@ -176,7 +187,7 @@ export class AssistantPanelModel {
};
readonly select = (id: string): void => {
- if (!this.active) return;
+ if (!this.active || this.closed) return;
const conversation = this.conversationList.conversations.find(item =>
item.id === id);
if (!conversation) return;
@@ -188,7 +199,7 @@ export class AssistantPanelModel {
this.selectedKey = session.key;
this.publish();
- session.ensureHistory();
+ session.onSelected();
};
private selectDraft(): void {
@@ -201,38 +212,39 @@ export class AssistantPanelModel {
}
readonly newConversation = (): void => {
- if (!this.active || (this.draftKey &&
this.sessions.get(this.draftKey)!.snapshot.phase === 'creating')) return;
+ if (!this.active || this.closed) return;
+ if (this.draftKey && this.sessions.get(this.draftKey)!.snapshot.phase ===
'creating') return;
this.selectDraft();
this.publish();
};
readonly setDraft = (value: string): void => {
- if (!this.active) return;
+ if (!this.active || this.closed) return;
this.sessions.get(this.selectedKey)!.setDraft(value);
};
readonly send = (question?: string): Promise<void> => {
- if (!this.active) return Promise.resolve();
+ if (!this.active || this.closed) return Promise.resolve();
return this.sessions.get(this.selectedKey)!.send(question);
};
readonly reload = (): Promise<void> => {
- if (!this.active) return Promise.resolve();
+ if (!this.active || this.closed) return Promise.resolve();
return this.sessions.get(this.selectedKey)!.reload();
};
readonly loadEarlier = (): Promise<boolean> => {
- if (!this.active) return Promise.resolve(false);
+ if (!this.active || this.closed) return Promise.resolve(false);
return this.sessions.get(this.selectedKey)!.loadEarlier();
};
readonly deleteConversation = async (id: string):
Promise<AssistantDeletionResult> => {
- if (!this.active) return { status: 'ignored' };
+ if (!this.active || this.closed) return { status: 'ignored' };
const conversation = this.conversationList.conversations.find(item =>
item.id === id);
if (!conversation) return { status: 'ignored' };
@@ -248,16 +260,17 @@ export class AssistantPanelModel {
if (!this.active || this.generation !== generation ||
this.sessions.get(session.key) !== session) {
return { status: 'ignored' };
}
- if (result.status !== 'deleted') return result;
-
- this.deleted.add(id);
- this.sessions.delete(session.key);
- this.conversationList = {
- ...this.conversationList,
- conversations: this.conversationList.conversations.filter(item =>
item.id !== id)
- };
- if (this.selectedKey === session.key) this.selectDraft();
- this.publish();
+ if (result.status === 'deleted') {
+ this.deleted.add(id);
+ this.sessions.delete(session.key);
+ this.conversationList = {
+ ...this.conversationList,
+ conversations: this.conversationList.conversations.filter(item =>
item.id !== id)
+ };
+ if (this.selectedKey === session.key) this.selectDraft();
+ }
+ if (this.closed) this.snapshot = this.project();
+ else if (result.status === 'deleted') this.publish();
return result;
};
@@ -286,7 +299,7 @@ export class AssistantPanelModel {
}
private readonly publish = (): void => {
- if (!this.active) return;
+ if (!this.active || this.closed) return;
this.snapshot = this.project();
this.listeners.forEach(listener => listener());
diff --git
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/useAssistantPanel.spec.tsx
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/useAssistantPanel.spec.tsx
index cdd7892d6d..48edaf60fa 100644
---
a/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/useAssistantPanel.spec.tsx
+++
b/zeppelin-web-angular/projects/zeppelin-react/src/pages/assistant-workspace/model/useAssistantPanel.spec.tsx
@@ -1414,6 +1414,99 @@ describe('useAssistantPanel', () => {
model.dispose();
});
+ it('reloads a saved draft on reopen without carrying over its loaded history
or prior error', async () => {
+ const harness = sourceHarness();
+ const oldMessage = { id: 'old', role: 'user', content: 'Earlier history' }
as const;
+ const currentMessage = { id: 'current', role: 'user', content: 'Refreshed
history' } as const;
+ const reopened = Promise.withResolvers<AssistantMessagePage>();
+ harness.api.getMessages
+ .mockResolvedValueOnce({ messages: [oldMessage], cursor: 'older' })
+ .mockRejectedValueOnce(new Error('Obsolete reload failure'))
+ .mockReturnValueOnce(reopened.promise);
+ const model = new AssistantPanelModel(harness.source);
+ model.start();
+ await Promise.resolve();
+ model.select('a');
+ await Promise.resolve();
+ model.setDraft('Still editing');
+ await model.reload();
+ expect(model.getSnapshot().entry).toMatchObject({
+ messages: [oldMessage],
+ cursor: 'older',
+ failure: { message: 'Obsolete reload failure' }
+ });
+
+ expect(model.close()).toBe(true);
+ model.reopen();
+ expect(model.getSnapshot().entry).toMatchObject({
+ conversation: { id: 'a' },
+ draft: 'Still editing',
+ loaded: false,
+ loading: true,
+ messages: [],
+ cursor: null,
+ failure: undefined
+ });
+ expect(harness.api.getMessages.mock.calls).toEqual([['a'], ['a'], ['a']]);
+
+ reopened.resolve({ messages: [currentMessage], cursor: null });
+ await reopened.promise;
+ expect(model.getSnapshot().entry).toMatchObject({
+ draft: 'Still editing',
+ loaded: true,
+ loading: false,
+ messages: [currentMessage]
+ });
+ expect(harness.run).not.toHaveBeenCalled();
+ model.dispose();
+ });
+
+ it('ignores an earlier-page response from before close while the reopened
draft loads its first page', async () => {
+ const harness = sourceHarness();
+ const earlier = Promise.withResolvers<AssistantMessagePage>();
+ const reopened = Promise.withResolvers<AssistantMessagePage>();
+ harness.api.getMessages
+ .mockResolvedValueOnce({ messages: [], cursor: 'before-close' })
+ .mockReturnValueOnce(earlier.promise)
+ .mockReturnValueOnce(reopened.promise);
+
+ const model = new AssistantPanelModel(harness.source);
+ model.start();
+ await Promise.resolve();
+ model.select('a');
+ await Promise.resolve();
+ model.setDraft('Still editing');
+
+ const loadingEarlier = model.loadEarlier();
+ expect(harness.api.getMessages).toHaveBeenNthCalledWith(2, 'a',
'before-close');
+ expect(model.close()).toBe(true);
+ model.reopen();
+ expect(harness.api.getMessages).toHaveBeenNthCalledWith(3, 'a');
+
+ earlier.resolve({
+ messages: [{ id: 'old', role: 'user', content: 'Stale earlier page' }],
+ cursor: 'obsolete'
+ });
+ await expect(loadingEarlier).resolves.toBe(false);
+ expect(model.getSnapshot().entry).toMatchObject({
+ draft: 'Still editing',
+ loading: true,
+ loadingEarlier: false,
+ messages: [],
+ cursor: null
+ });
+ const fresh = { id: 'fresh', role: 'user', content: 'Fresh initial page' }
as const;
+ reopened.resolve({ messages: [fresh], cursor: 'fresh-cursor' });
+ await reopened.promise;
+ expect(model.getSnapshot().entry).toMatchObject({
+ draft: 'Still editing',
+ loading: false,
+ messages: [fresh],
+ cursor: 'fresh-cursor'
+ });
+ model.dispose();
+ });
+
it('keeps a loaded failed answer after a later reload fails and permits the
next send', async () => {
const harness = sourceHarness();
const panel = await mountPanel(harness.source);