Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Preserve Assistant composer drafts across drawer remounts

rcourtmane80feaed05b9
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index e4f8aeb60c..d7d0ee3266 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -141,6 +141,17 @@ runtime cost control, and shared AI transport surfaces.
Assistant drawer follows that draft-safe recall model rather than limiting
history recall to an empty composer. Scoped context replay remains owned by
explicit session handoff metadata or queued follow-up edit state.
+ Unsent composer drafts are recoverable remount state, not prompt history:
+ closing or remounting the Assistant drawer must restore the current prompt,
+ structured mentions, cursor position, and any queued-follow-up edit metadata
+ without writing the draft into submitted prompt history. The referenced
+ OpenCode source at commit `9ed17da55ab1f7360cc0e01075f763e27fa899e9`
+ keeps a module-local `stashed` prompt in
+ `packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx`, restores it
+ in `Prompt` `onMount` (lines 595-604), and captures it in `onCleanup`
+ (lines 607-610). Pulse adapts that source behavior with a drawer-local
+ composer stash so normal close/reopen does not drop an unsent user thought
+ or downgrade a scoped queued follow-up into a plain prompt.
Failed-turn retry is part of that same local chat-runtime boundary: a
retryable in-memory assistant error may replay the original user turn's
structured mentions, finding id, approval override, handoff resources,
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
index a140c7c8b7..2f277b12e4 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -332,6 +332,7 @@ vi.mock('@/hooks/useResources', () => ({
// ── Lazy import after mocks ────────────────────────────────────────────────
let AIChat: typeof import('../index').AIChat;
+let resetAIChatComposerDraftStashForTests: typeof import('../index').resetAIChatComposerDraftStashForTests;
let resetAIRuntimeState: typeof import('@/stores/aiRuntimeState').resetAIRuntimeState;
beforeAll(async () => {
@@ -340,6 +341,7 @@ beforeAll(async () => {
import('@/stores/aiRuntimeState'),
]);
AIChat = chatModule.AIChat;
+ resetAIChatComposerDraftStashForTests = chatModule.resetAIChatComposerDraftStashForTests;
resetAIRuntimeState = runtimeModule.resetAIRuntimeState;
});
@@ -376,6 +378,7 @@ beforeEach(() => {
vi.clearAllMocks();
mockChatMessagesProps.length = 0;
mockModelSelectorProps.length = 0;
+ resetAIChatComposerDraftStashForTests();
setViewportWidth(1440);
resetAIRuntimeState();
mockAiChatStore.isOpenSignal.mockReturnValue(true);
@@ -1445,6 +1448,65 @@ describe('AIChat', () => {
await waitFor(() => expect(textarea.value).toBe('new draft while waiting'));
});
+ it('restores an unsent composer draft after the assistant drawer remounts', async () => {
+ const firstRender = renderChat();
+ const textarea = screen.getByPlaceholderText(
+ 'Ask about your infrastructure...',
+ ) as HTMLTextAreaElement;
+
+ fireEvent.input(textarea, { target: { value: 'keep this draft while I check another page' } });
+ textarea.setSelectionRange(10, 10);
+
+ firstRender.unmount();
+ renderChat();
+
+ const restoredTextarea = screen.getByPlaceholderText(
+ 'Ask about your infrastructure...',
+ ) as HTMLTextAreaElement;
+ await waitFor(() =>
+ expect(restoredTextarea.value).toBe('keep this draft while I check another page'),
+ );
+ await waitFor(() => expect(restoredTextarea.selectionStart).toBe(10));
+ expect(document.activeElement).toBe(restoredTextarea);
+ });
+
+ it('restores queued follow-up edit metadata after remounting the composer', async () => {
+ const queued: QueuedFollowUp = {
+ id: 'queued-1',
+ messageId: 'msg-queued-1',
+ prompt: 'queued scoped prompt',
+ mentions: [{ id: 'vm-1', name: 'web-1', type: 'vm', node: 'pve-1' }],
+ findingId: 'finding-1',
+ sendOptions: { autonomousMode: false, handoffContext: 'scoped context' },
+ timestamp: new Date('2026-06-06T08:00:00Z'),
+ };
+ mockChat.queuedFollowUps.mockReturnValue([queued]);
+ mockChat.queuedFollowUpCount.mockReturnValue(1);
+ mockChat.takeQueuedFollowUp.mockReturnValue(queued);
+ const firstRender = renderChat();
+
+ mockChatMessagesProps.at(-1)?.onEditQueuedFollowUp?.('queued-1');
+ let textarea = screen.getByPlaceholderText('Ask about your infrastructure...') as HTMLTextAreaElement;
+ await waitFor(() => expect(textarea.value).toBe('queued scoped prompt'));
+
+ firstRender.unmount();
+ mockChat.queuedFollowUps.mockReturnValue([]);
+ mockChat.queuedFollowUpCount.mockReturnValue(0);
+ renderChat();
+
+ textarea = screen.getByPlaceholderText('Ask about your infrastructure...') as HTMLTextAreaElement;
+ await waitFor(() => expect(textarea.value).toBe('queued scoped prompt'));
+ fireEvent.input(textarea, { target: { value: 'edited scoped prompt' } });
+ fireEvent.keyDown(textarea, { key: 'Enter' });
+
+ expect(mockChat.sendMessage).toHaveBeenCalledWith(
+ 'edited scoped prompt',
+ [{ id: 'vm-1', name: 'web-1', type: 'vm', node: 'pve-1' }],
+ 'finding-1',
+ { autonomousMode: false, handoffContext: 'scoped context' },
+ );
+ });
+
it('allows newlines with Shift+Enter', () => {
renderChat();
const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index 1c202ff4f9..482eff2b9a 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -121,10 +121,24 @@ interface PromptHistoryEntry {
mentions: MentionResource[];
}
+interface ComposerDraftStash {
+ input: string;
+ mentions: MentionResource[];
+ cursorStart: number;
+ cursorEnd: number;
+ editingQueuedFollowUp: QueuedFollowUp | null;
+}
+
interface AIChatProps {
onClose: () => void;
}
+let stashedComposerDraft: ComposerDraftStash | null = null;
+
+export const resetAIChatComposerDraftStashForTests = () => {
+ stashedComposerDraft = null;
+};
+
const compactText = (items: Array<string | undefined>): string[] =>
items.filter((item): item is string => typeof item === 'string' && item.trim().length > 0);
@@ -547,6 +561,25 @@ export const AIChat: Component<AIChatProps> = (props) => {
const cloneMentions = (mentions: MentionResource[]) =>
mentions.map((mention) => ({ ...mention }));
+ const cloneSendMessageOptions = (
+ sendOptions?: SendMessageOptions,
+ ): SendMessageOptions | undefined => {
+ if (!sendOptions) return undefined;
+ return {
+ ...sendOptions,
+ handoffResources: sendOptions.handoffResources?.map((resource) => ({ ...resource })),
+ handoffActions: sendOptions.handoffActions?.map((action) => ({ ...action })),
+ handoffMetadata: sendOptions.handoffMetadata ? { ...sendOptions.handoffMetadata } : undefined,
+ };
+ };
+
+ const cloneQueuedFollowUp = (queued: QueuedFollowUp): QueuedFollowUp => ({
+ ...queued,
+ mentions: queued.mentions?.map((mention) => ({ ...mention })),
+ sendOptions: cloneSendMessageOptions(queued.sendOptions),
+ timestamp: new Date(queued.timestamp),
+ });
+
const loadPromptHistory = (): PromptHistoryEntry[] => {
try {
const raw = localStorage.getItem(PROMPT_HISTORY_STORAGE_KEY);
@@ -607,6 +640,47 @@ export const AIChat: Component<AIChatProps> = (props) => {
setSavedPromptDraft(null);
};
+ const stashComposerDraftForRemount = () => {
+ const text = input();
+ const mentions = accumulatedMentions();
+ const queuedDraft = editingQueuedFollowUp();
+ if (!text.trim() && mentions.length === 0 && !queuedDraft) {
+ stashedComposerDraft = null;
+ return;
+ }
+
+ const fallbackCursor = text.length;
+ stashedComposerDraft = {
+ input: text,
+ mentions: cloneMentions(mentions),
+ cursorStart: textareaRef?.selectionStart ?? fallbackCursor,
+ cursorEnd: textareaRef?.selectionEnd ?? fallbackCursor,
+ editingQueuedFollowUp: queuedDraft ? cloneQueuedFollowUp(queuedDraft) : null,
+ };
+ };
+
+ const restoreStashedComposerDraft = () => {
+ const draft = stashedComposerDraft;
+ stashedComposerDraft = null;
+ if (!draft) return;
+ if (input().trim() || accumulatedMentions().length > 0 || editingQueuedFollowUp()) return;
+
+ setInput(draft.input);
+ setAccumulatedMentions(cloneMentions(draft.mentions));
+ setEditingQueuedFollowUp(
+ draft.editingQueuedFollowUp ? cloneQueuedFollowUp(draft.editingQueuedFollowUp) : null,
+ );
+ setMentionActive(false);
+ resetPromptHistoryNavigation();
+ queueMicrotask(() => {
+ resizeTextarea();
+ textareaRef?.focus();
+ const start = Math.min(draft.cursorStart, draft.input.length);
+ const end = Math.min(draft.cursorEnd, draft.input.length);
+ textareaRef?.setSelectionRange(start, end);
+ });
+ };
+
const applyPromptHistoryEntry = (entry: PromptHistoryEntry, cursor: 'start' | 'end') => {
setInput(entry.prompt);
setAccumulatedMentions(cloneMentions(entry.mentions));
@@ -1357,6 +1431,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
onMount(() => {
setPromptHistory(loadPromptHistory());
aiChatStore.registerInput?.(textareaRef ?? null);
+ restoreStashedComposerDraft();
focusComposer();
const handleClickOutside = (e: MouseEvent) => {
@@ -1375,6 +1450,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
};
document.addEventListener('click', handleClickOutside);
onCleanup(() => {
+ stashComposerDraftForRemount();
document.removeEventListener('click', handleClickOutside);
aiChatStore.registerInput?.(null);
clearInterruptArm();
@@ -1737,6 +1813,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
restoreFailedSubmitDraft(submittedInput, submittedMentions);
return;
}
+ stashedComposerDraft = null;
setEditingQueuedFollowUp(null);
if (!queuedDraft && findingId) {
aiChatStore.clearFindingId?.();
@@ -1749,6 +1826,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
logger.warn('[AIChat] Failed to send Assistant message:', error);
restoreFailedSubmitDraft(submittedInput, submittedMentions);
});
+ stashedComposerDraft = null;
setInput('');
setAccumulatedMentions([]);
setMentionActive(false);