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.

feat(assistant): collapse long pastes into composer chips

rcourtman8a0c6fc9a816
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 0bd7f30220..e56ac5364e 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -2081,6 +2081,78 @@ describe('AIChat', () => {
expect(mockChat.sendMessage).toHaveBeenCalledWith('hello world', undefined, undefined);
});
+ it('collapses a long paste into a chip and appends it to the sent prompt', () => {
+ renderChat();
+ const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
+ const pasted = Array.from({ length: 12 }, (_, i) => `log line ${i}`).join('\n');
+
+ fireEvent.paste(textarea, { clipboardData: { getData: () => pasted } });
+
+ // The textarea stays clean; the paste becomes a chip.
+ expect((textarea as HTMLTextAreaElement).value).toBe('');
+ expect(screen.getByTestId('assistant-pasted-blocks')).toBeInTheDocument();
+ expect(screen.getByText('Pasted text (12 lines)')).toBeInTheDocument();
+
+ fireEvent.input(textarea, { target: { value: 'what is failing here?' } });
+ fireEvent.keyDown(textarea, { key: 'Enter' });
+
+ expect(mockChat.sendMessage).toHaveBeenCalledWith(
+ `what is failing here?\n\n${pasted}`,
+ undefined,
+ undefined,
+ );
+ // Chip is consumed by the send.
+ expect(screen.queryByTestId('assistant-pasted-blocks')).not.toBeInTheDocument();
+ });
+
+ it('keeps short pastes inline in the textarea', () => {
+ renderChat();
+ const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
+
+ fireEvent.paste(textarea, { clipboardData: { getData: () => 'short question' } });
+
+ // Collapse handler must not intercept; jsdom does not perform native
+ // paste insertion, so the absence of a chip is the assertion.
+ expect(screen.queryByTestId('assistant-pasted-blocks')).not.toBeInTheDocument();
+ });
+
+ it('sends a chip-only message and expands a chip back into the textarea', () => {
+ renderChat();
+ const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
+ const pasted = Array.from({ length: 9 }, (_, i) => `row ${i}`).join('\n');
+
+ fireEvent.paste(textarea, { clipboardData: { getData: () => pasted } });
+ const chipBody = screen.getByText('Pasted text (9 lines)');
+
+ // Expand puts the text back for inline editing and removes the chip.
+ fireEvent.click(chipBody);
+ expect((textarea as HTMLTextAreaElement).value).toBe(pasted);
+ expect(screen.queryByTestId('assistant-pasted-blocks')).not.toBeInTheDocument();
+
+ // Re-collapse via a fresh paste, clear the typed text, send chip-only.
+ fireEvent.input(textarea, { target: { value: '' } });
+ fireEvent.paste(textarea, { clipboardData: { getData: () => pasted } });
+ const sendButton = screen.getByRole('button', { name: 'Send message' });
+ expect(sendButton).not.toBeDisabled();
+ fireEvent.keyDown(textarea, { key: 'Enter' });
+
+ expect(mockChat.sendMessage).toHaveBeenCalledWith(pasted, undefined, undefined);
+ });
+
+ it('removes a pasted chip without sending it', () => {
+ renderChat();
+ const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
+ const pasted = Array.from({ length: 10 }, (_, i) => `cfg ${i}`).join('\n');
+
+ fireEvent.paste(textarea, { clipboardData: { getData: () => pasted } });
+ fireEvent.click(screen.getByRole('button', { name: 'Remove Pasted text (10 lines)' }));
+
+ expect(screen.queryByTestId('assistant-pasted-blocks')).not.toBeInTheDocument();
+ fireEvent.input(textarea, { target: { value: 'hello' } });
+ fireEvent.keyDown(textarea, { key: 'Enter' });
+ expect(mockChat.sendMessage).toHaveBeenCalledWith('hello', undefined, undefined);
+ });
+
it('shows slash command suggestions and runs the selected command with Enter', async () => {
renderChat();
const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/composerPaste.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/composerPaste.test.ts
new file mode 100644
index 0000000000..212a5d221a
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/composerPaste.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import {
+ PASTE_COLLAPSE_MIN_CHARS,
+ PASTE_COLLAPSE_MIN_LINES,
+ composePromptWithPastedBlocks,
+ createPastedTextBlock,
+ pastedBlockLabel,
+ shouldCollapsePastedText,
+} from '../composerPaste';
+
+describe('composerPaste', () => {
+ describe('shouldCollapsePastedText', () => {
+ it('ignores empty and whitespace-only pastes', () => {
+ expect(shouldCollapsePastedText('')).toBe(false);
+ expect(shouldCollapsePastedText(' \n\n ')).toBe(false);
+ });
+
+ it('keeps short pastes inline', () => {
+ expect(shouldCollapsePastedText('restart the vm please')).toBe(false);
+ expect(shouldCollapsePastedText('line one\nline two\nline three')).toBe(false);
+ });
+
+ it('collapses many-line pastes', () => {
+ const lines = Array.from({ length: PASTE_COLLAPSE_MIN_LINES }, (_, i) => `log line ${i}`);
+ expect(shouldCollapsePastedText(lines.join('\n'))).toBe(true);
+ expect(shouldCollapsePastedText(lines.slice(0, -1).join('\n'))).toBe(false);
+ });
+
+ it('collapses long single-line pastes', () => {
+ expect(shouldCollapsePastedText('x'.repeat(PASTE_COLLAPSE_MIN_CHARS))).toBe(true);
+ expect(shouldCollapsePastedText('x'.repeat(PASTE_COLLAPSE_MIN_CHARS - 1))).toBe(false);
+ });
+ });
+
+ describe('createPastedTextBlock and pastedBlockLabel', () => {
+ it('counts lines and chars and labels multi-line blocks by lines', () => {
+ const block = createPastedTextBlock('a\nb\nc');
+ expect(block.lineCount).toBe(3);
+ expect(block.charCount).toBe(5);
+ expect(pastedBlockLabel(block)).toBe('Pasted text (3 lines)');
+ });
+
+ it('labels single-line blocks by chars', () => {
+ const block = createPastedTextBlock('y'.repeat(1200));
+ expect(pastedBlockLabel(block)).toBe(`Pasted text (${(1200).toLocaleString()} chars)`);
+ });
+
+ it('assigns unique ids', () => {
+ expect(createPastedTextBlock('a').id).not.toBe(createPastedTextBlock('a').id);
+ });
+ });
+
+ describe('composePromptWithPastedBlocks', () => {
+ it('returns the typed prompt untouched without blocks', () => {
+ expect(composePromptWithPastedBlocks('hello', [])).toBe('hello');
+ });
+
+ it('appends blocks after the typed prompt separated by blank lines', () => {
+ const blocks = [createPastedTextBlock('log a\nlog b'), createPastedTextBlock('log c')];
+ expect(composePromptWithPastedBlocks('what broke?', blocks)).toBe(
+ 'what broke?\n\nlog a\nlog b\n\nlog c',
+ );
+ });
+
+ it('sends blocks alone when nothing was typed', () => {
+ const blocks = [createPastedTextBlock(' raw payload ')];
+ expect(composePromptWithPastedBlocks('', blocks)).toBe('raw payload');
+ });
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/composerPaste.ts b/frontend-modern/src/components/AI/Chat/composerPaste.ts
new file mode 100644
index 0000000000..5563718c80
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/composerPaste.ts
@@ -0,0 +1,55 @@
+// Long pastes into the Assistant composer collapse into removable chips so a
+// pasted log or config does not flood the textarea. The full text is appended
+// to the typed prompt at send time; the chip is presentation-only state.
+
+export interface PastedTextBlock {
+ id: string;
+ text: string;
+ lineCount: number;
+ charCount: number;
+}
+
+// A paste collapses when it is clearly a payload rather than a sentence the
+// user would keep editing inline: many lines (logs, YAML, stack traces) or a
+// long single-line blob (JSON, a command with args).
+export const PASTE_COLLAPSE_MIN_LINES = 8;
+export const PASTE_COLLAPSE_MIN_CHARS = 800;
+
+export function shouldCollapsePastedText(text: string): boolean {
+ if (!text.trim()) return false;
+ if (text.length >= PASTE_COLLAPSE_MIN_CHARS) return true;
+ return countLines(text) >= PASTE_COLLAPSE_MIN_LINES;
+}
+
+let pastedBlockCounter = 0;
+
+export function createPastedTextBlock(text: string): PastedTextBlock {
+ pastedBlockCounter += 1;
+ return {
+ id: `pasted-block-${pastedBlockCounter}`,
+ text,
+ lineCount: countLines(text),
+ charCount: text.length,
+ };
+}
+
+export function pastedBlockLabel(block: PastedTextBlock): string {
+ if (block.lineCount > 1) {
+ return `Pasted text (${block.lineCount.toLocaleString()} lines)`;
+ }
+ return `Pasted text (${block.charCount.toLocaleString()} chars)`;
+}
+
+// The typed prompt leads; pasted blocks follow in paste order, separated by
+// blank lines, so the model reads the question before the payload.
+export function composePromptWithPastedBlocks(
+ typedPrompt: string,
+ blocks: readonly PastedTextBlock[],
+): string {
+ const parts = [typedPrompt.trim(), ...blocks.map((block) => block.text.trim())].filter(Boolean);
+ return parts.join('\n\n');
+}
+
+function countLines(text: string): number {
+ return text.split('\n').length;
+}
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index a169aa9749..f848a66b2b 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -185,6 +185,13 @@ import {
type AssistantSlashCommandAction,
} from './assistantSlashCommands';
import { getAssistantWorkflowStarters, type AssistantWorkflowStarter } from './workflowStarters';
+import {
+ composePromptWithPastedBlocks,
+ createPastedTextBlock,
+ pastedBlockLabel,
+ shouldCollapsePastedText,
+ type PastedTextBlock,
+} from './composerPaste';
import {
assistantNotificationsEnabled,
assistantNotificationsSupported,
@@ -738,6 +745,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
const [mentionStartIndex, setMentionStartIndex] = createSignal(0);
const [mentionResources, setMentionResources] = createSignal<MentionResource[]>([]);
const [accumulatedMentions, setAccumulatedMentions] = createSignal<MentionResource[]>([]);
+ const [pastedBlocks, setPastedBlocks] = createSignal<PastedTextBlock[]>([]);
const [slashCommandActive, setSlashCommandActive] = createSignal(false);
const [slashCommandQuery, setSlashCommandQuery] = createSignal('');
let textareaRef: HTMLTextAreaElement | undefined;
@@ -3144,12 +3152,17 @@ export const AIChat: Component<AIChatProps> = (props) => {
setMentionResources(dedupeMentionResources(mentionCandidates));
});
- const restoreFailedSubmitDraft = (draft: string, mentions: MentionResource[]) => {
- if (input().trim() || accumulatedMentions().length > 0) {
+ const restoreFailedSubmitDraft = (
+ draft: string,
+ mentions: MentionResource[],
+ blocks: PastedTextBlock[] = [],
+ ) => {
+ if (input().trim() || accumulatedMentions().length > 0 || pastedBlocks().length > 0) {
return;
}
setInput(draft);
setAccumulatedMentions(cloneMentions(mentions));
+ setPastedBlocks(blocks);
setMentionActive(false);
setSlashCommandActive(false);
queueMicrotask(() => {
@@ -3158,6 +3171,34 @@ export const AIChat: Component<AIChatProps> = (props) => {
});
};
+ // Long pastes collapse into chips instead of flooding the textarea; the
+ // full text rejoins the prompt at send time (composePromptWithPastedBlocks).
+ const handleComposerPaste = (e: ClipboardEvent) => {
+ const text = e.clipboardData?.getData('text/plain') ?? '';
+ if (!shouldCollapsePastedText(text)) return;
+ e.preventDefault();
+ setPastedBlocks((prev) => [...prev, createPastedTextBlock(text)]);
+ };
+
+ const removePastedBlock = (id: string) => {
+ setPastedBlocks((prev) => prev.filter((block) => block.id !== id));
+ focusComposer();
+ };
+
+ // Clicking the chip body un-collapses: the text returns to the textarea so
+ // the user can trim or edit it inline.
+ const expandPastedBlock = (id: string) => {
+ const block = pastedBlocks().find((candidate) => candidate.id === id);
+ if (!block) return;
+ setPastedBlocks((prev) => prev.filter((candidate) => candidate.id !== id));
+ const current = input();
+ setInput(current ? `${current}\n${block.text}` : block.text);
+ queueMicrotask(() => {
+ resizeTextarea();
+ focusComposer();
+ });
+ };
+
const readComposerInputForSubmit = () => {
// Composition/IME updates can reach the textarea before the controlled signal
// flushes, so the live DOM value is authoritative for submit.
@@ -3172,6 +3213,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
setRestoredPromptDraft(null);
setInput('');
setAccumulatedMentions([]);
+ setPastedBlocks([]);
setMentionActive(false);
setSlashCommandActive(false);
setSlashCommandQuery('');
@@ -3335,8 +3377,9 @@ export const AIChat: Component<AIChatProps> = (props) => {
if (composerSubmitDispatchLocked) return;
const submittedInput = readComposerInputForSubmit();
- const prompt = submittedInput.trim();
- if (!prompt) return;
+ const typedPrompt = submittedInput.trim();
+ const submittedBlocks = pastedBlocks();
+ if (!typedPrompt && submittedBlocks.length === 0) return;
composerSubmitDispatchLocked = true;
queueMicrotask(() => {
composerSubmitDispatchLocked = false;
@@ -3344,11 +3387,12 @@ export const AIChat: Component<AIChatProps> = (props) => {
if (submittedInput !== input()) {
setInput(submittedInput);
}
- const slashCommand = parseAssistantSlashCommandInput(prompt);
+ const slashCommand = typedPrompt ? parseAssistantSlashCommandInput(typedPrompt) : null;
if (slashCommand) {
executeSlashCommand(slashCommand.action, slashCommand.args);
return;
}
+ const prompt = composePromptWithPastedBlocks(typedPrompt, submittedBlocks);
setSlashCommandActive(false);
setSlashCommandQuery('');
const mentions = accumulatedMentions();
@@ -3413,7 +3457,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
sendPromise
.then((ok) => {
if (!ok) {
- restoreFailedSubmitDraft(submittedInput, submittedMentions);
+ restoreFailedSubmitDraft(submittedInput, submittedMentions, submittedBlocks);
return;
}
stashedComposerDraft = null;
@@ -3429,11 +3473,12 @@ export const AIChat: Component<AIChatProps> = (props) => {
})
.catch((error) => {
logger.warn('[AIChat] Failed to send Assistant message:', error);
- restoreFailedSubmitDraft(submittedInput, submittedMentions);
+ restoreFailedSubmitDraft(submittedInput, submittedMentions, submittedBlocks);
});
stashedComposerDraft = null;
setInput('');
setAccumulatedMentions([]);
+ setPastedBlocks([]);
setMentionActive(false);
setSlashCommandActive(false);
setSlashCommandQuery('');
@@ -3718,6 +3763,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
setEditingQueuedFollowUp(null);
setInput('');
setAccumulatedMentions([]);
+ setPastedBlocks([]);
setMentionActive(false);
setSlashCommandActive(false);
notificationStore.success(AI_CHAT_REDO_LAST_TURN_SUCCESS_MESSAGE, 2000);
@@ -5140,6 +5186,39 @@ export const AIChat: Component<AIChatProps> = (props) => {
</For>
</div>
</Show>
+ <Show when={pastedBlocks().length > 0}>
+ <div
+ class="mb-2 flex min-w-0 flex-wrap items-center gap-1.5"
+ aria-label="Pasted text attachments"
+ data-testid="assistant-pasted-blocks"
+ >
+ <For each={pastedBlocks()}>
+ {(block) => (
+ <div class="inline-flex h-7 max-w-full items-center gap-0.5 rounded-md border border-border bg-surface-alt pl-2 pr-0.5 text-[11px] font-medium text-base-content">
+ <ClipboardCopyIcon class="h-3 w-3 shrink-0 text-muted" aria-hidden="true" />
+ <button
+ type="button"
+ onClick={() => expandPastedBlock(block.id)}
+ class="min-w-0 truncate px-1 hover:text-blue-700 dark:hover:text-blue-300"
+ title="Click to edit the pasted text in the composer"
+ aria-label={`Edit ${pastedBlockLabel(block)} in the composer`}
+ >
+ {pastedBlockLabel(block)}
+ </button>
+ <ActionIconButton
+ onClick={() => removePastedBlock(block.id)}
+ tone="muted"
+ size="2xs"
+ title="Remove pasted text"
+ label={`Remove ${pastedBlockLabel(block)}`}
+ >
+ <XIcon class="h-3 w-3" aria-hidden="true" />
+ </ActionIconButton>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
<form
data-assistant-composer
onSubmit={(e) => {
@@ -5160,6 +5239,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
value={input()}
onInput={handleInputChange}
onKeyDown={handleKeyDown}
+ onPaste={handleComposerPaste}
placeholder={AI_CHAT_INPUT_PLACEHOLDER}
rows={1}
class="max-h-40 min-h-[54px] flex-1 resize-none bg-transparent px-3.5 py-3.5 pr-14 text-sm leading-5 text-base-content placeholder-slate-400 focus:outline-none"
@@ -5185,7 +5265,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
<div class="absolute bottom-2 right-2 flex items-center gap-1.5">
<ActionIconButton
type="submit"
- disabled={!input().trim()}
+ disabled={!input().trim() && pastedBlocks().length === 0}
tone="primary"
size="lg"
title={chat.isLoading() ? 'Queue follow-up' : 'Send'}