diff --git a/shell/e2e/user-journey.e2e.ts b/shell/e2e/user-journey.e2e.ts index 63cc02b61..2edeb04d2 100644 --- a/shell/e2e/user-journey.e2e.ts +++ b/shell/e2e/user-journey.e2e.ts @@ -179,4 +179,82 @@ test.describe('E2E Workspace User Journey', () => { await expect(previewIframe.locator('body')).toBeVisible({timeout: 10000}); await expect(previewIframe.locator('a2ui-v09-surface').first()).toBeVisible({timeout: 10000}); }); + + test('should create, overwrite in-place, preview in system instructions, and disable custom instruction presets', async ({ + page, + }) => { + await page.addInitScript(() => { + if (window === window.top) { + localStorage.setItem('a2ui_composer_selected_api_key', 'fake'); + } + }); + await page.goto('/'); + + const customInstructionsLink = page.locator('.custom-instructions-link'); + const systemInstructionsLink = page.locator('.system-instructions-link'); + + // 1. Open the Gemini chat panel and click "Custom Instructions" next to "Instructions" + await expect(customInstructionsLink).toHaveText('Custom Instructions'); + await customInstructionsLink.click(); + + const dialog = page.locator('a2ui-composer-custom-instructions-dialog'); + await expect(dialog).toBeVisible(); + const box = await dialog.boundingBox(); + expect(box?.width).toBeCloseTo(600, 0); + + // 2. Create a named preset, click Save, and verify the link label updates to "Custom Instructions: " + await dialog.locator('.preset-name-input').fill('Compact Theme'); + await dialog + .locator('.instructions-textarea') + .fill('Always use compact spacing and high-contrast cards.'); + await dialog.locator('.save-button').click(); + await expect(dialog).toBeHidden(); + + await expect(customInstructionsLink).toHaveText('Custom Instructions: Compact Theme'); + + // 3. Click "Instructions" and verify "## Custom User Instructions" appears at the end of the system prompt + await systemInstructionsLink.click(); + const sysDialog = page.locator('a2ui-composer-system-instructions-dialog'); + await expect(sysDialog).toBeVisible(); + await expect(sysDialog.locator('.instructions-textarea')).toHaveValue( + /## Custom User Instructions\s+Always use compact spacing and high-contrast cards\./, + ); + await sysDialog.getByRole('button', {name: 'Close'}).click(); + await expect(sysDialog).toBeHidden(); + + // 4. Reopen "Custom Instructions", edit the existing preset in-place, click Save, and verify overwrite + await customInstructionsLink.click(); + await expect(dialog).toBeVisible(); + await dialog.locator('.preset-name-input').fill('Compact Theme v2'); + await dialog + .locator('.instructions-textarea') + .fill('Updated: strictly use compact spacing and dark elevation.'); + await dialog.locator('.save-button').click(); + await expect(dialog).toBeHidden(); + + await expect(customInstructionsLink).toHaveText('Custom Instructions: Compact Theme v2'); + + // Verify the overwritten content in SystemInstructionsDialog and after page reload + await page.reload(); + await expect(customInstructionsLink).toHaveText('Custom Instructions: Compact Theme v2'); + await systemInstructionsLink.click(); + await expect(sysDialog.locator('.instructions-textarea')).toHaveValue( + /## Custom User Instructions\s+Updated: strictly use compact spacing and dark elevation\./, + ); + await sysDialog.getByRole('button', {name: 'Close'}).click(); + + // 5. Switch preset dropdown to "None (Off)" and click Save to disable custom instructions + await customInstructionsLink.click(); + await dialog.locator('.preset-select').click(); + await page.locator('mat-option.preset-option-none').click(); + await dialog.locator('.save-button').click(); + await expect(dialog).toBeHidden(); + + await expect(customInstructionsLink).toHaveText('Custom Instructions'); + await systemInstructionsLink.click(); + await expect(sysDialog.locator('.instructions-textarea')).not.toHaveValue( + /## Custom User Instructions/, + ); + await sysDialog.getByRole('button', {name: 'Close'}).click(); + }); }); diff --git a/shell/src/app/chat/chat-coordinator/chat-coordinator.ts b/shell/src/app/chat/chat-coordinator/chat-coordinator.ts index 0324f01cf..590a6f377 100644 --- a/shell/src/app/chat/chat-coordinator/chat-coordinator.ts +++ b/shell/src/app/chat/chat-coordinator/chat-coordinator.ts @@ -77,6 +77,12 @@ export class ChatCoordinator { /** Turn index counter for telemetry. */ readonly currentTurnIndex = signal(0); + /** + * A dynamic, reactive, computed signal property constructing conformed JSON + * catalog schema specifications system instructions. + */ + readonly systemPrompt = this.promptFactory.systemPrompt; + private activePromptId: string | null = null; constructor() { @@ -484,10 +490,4 @@ export class ChatCoordinator { return updated; }); } - - /** - * A dynamic, reactive, computed signal property constructing conformed JSON - * catalog schema specifications system instructions. - */ - readonly systemPrompt = this.promptFactory.systemPrompt; } diff --git a/shell/src/app/chat/chat-panel/chat-panel.ng.html b/shell/src/app/chat/chat-panel/chat-panel.ng.html index 021e6d9c2..957253fdf 100644 --- a/shell/src/app/chat/chat-panel/chat-panel.ng.html +++ b/shell/src/app/chat/chat-panel/chat-panel.ng.html @@ -290,6 +290,13 @@ Instructions } + @if (isLocked()) { + } + + + + diff --git a/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.scss b/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.scss new file mode 100644 index 000000000..1eef3c854 --- /dev/null +++ b/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.scss @@ -0,0 +1,98 @@ +/** + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +:host { + display: block; + width: 600px; + max-width: 100%; + box-sizing: border-box; +} + +.dialog-header { + padding: 0 16px; + + .dialog-title-text { + margin: 0; + padding: 20px 0 16px 0; + color: var(--mat-sys-on-surface-variant); + } +} + +mat-dialog-content { + padding-left: 16px !important; + padding-right: 16px !important; + display: flex; + flex-direction: column; + gap: 12px; + min-width: 320px; + max-width: 600px; +} + +.preset-select-field, +.preset-name-field { + width: 100%; +} + +.instructions-container { + display: flex; + flex-direction: column; + gap: 6px; +} + +.instructions-label { + font-size: var(--mat-sys-label-medium-size, 12px); + color: var(--mat-sys-on-surface-variant); +} + +.instructions-textarea { + width: 100%; + min-width: 0; + max-width: 100%; + min-height: 180px; + height: 210px; + resize: vertical; + background-color: var(--mat-sys-surface-container-high); + padding: 12px; + border-radius: 4px; + border: 1px solid var(--mat-sys-outline-variant); + font-family: 'Roboto Mono', Consolas, monospace; + font-size: var(--mat-sys-body-small-size, 12px); + line-height: var(--mat-sys-body-small-line-height, 1.5); + color: var(--mat-sys-on-surface); + box-sizing: border-box; +} + +.instructions-textarea:focus { + outline: 2px solid var(--mat-sys-primary); + outline-offset: -2px; +} + +.none-selected-message { + padding: 24px 0; + color: var(--mat-sys-on-surface-variant); + font-size: var(--mat-sys-body-medium-size, 14px); + font-style: italic; +} + +.dialog-actions { + display: flex; + align-items: center; + padding: 12px 16px; + + .actions-spacer { + flex: 1 1 auto; + } +} diff --git a/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.spec.ts b/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.spec.ts new file mode 100644 index 000000000..ed9152a44 --- /dev/null +++ b/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.spec.ts @@ -0,0 +1,237 @@ +/** + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from '@angular/material/dialog'; +import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; +import {provideNoopAnimations} from '@angular/platform-browser/animations'; +import {describe, it, expect, beforeEach, vi} from 'vitest'; +import {CustomInstructionsDialog} from './custom-instructions-dialog'; +import {CustomInstructionsDialogHarness} from './test/custom-instructions-dialog.harness'; +import {CustomInstructionsState} from '../chat-prompt-factory/chat-prompt-factory.service'; + +describe('CustomInstructionsDialog', () => { + let fixture: ComponentFixture; + let harness: CustomInstructionsDialogHarness; + let mockDialogRef: {close: ReturnType}; + + const createComponent = async (data: CustomInstructionsState | null) => { + mockDialogRef = {close: vi.fn()}; + + await TestBed.configureTestingModule({ + imports: [CustomInstructionsDialog, MatDialogModule], + providers: [ + provideNoopAnimations(), + {provide: MAT_DIALOG_DATA, useValue: data}, + {provide: MatDialogRef, useValue: mockDialogRef}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(CustomInstructionsDialog); + fixture.detectChanges(); + harness = await TestbedHarnessEnvironment.harnessForFixture( + fixture, + CustomInstructionsDialogHarness, + ); + }; + + describe('When no presets exist initially', () => { + beforeEach(async () => { + await createComponent({presets: [], activePresetId: null}); + }); + + it('defaults to "+ New preset..." option with empty inputs and disabled save', async () => { + expect(await harness.getSelectedPresetOptionText()).toBe('+ New preset...'); + expect(await harness.getPresetName()).toBe(''); + expect(await harness.getInstructions()).toBe(''); + expect(await harness.isSaveDisabled()).toBe(true); + expect(await harness.hasDeleteButton()).toBe(false); + }); + + it('enables save button when valid name and instructions are entered, and saves new preset', async () => { + await harness.setPresetName('Test Preset'); + await harness.setInstructions('Test instruction text'); + expect(await harness.isSaveDisabled()).toBe(false); + + await harness.clickSave(); + expect(mockDialogRef.close).toHaveBeenCalledTimes(1); + const savedData: CustomInstructionsState = mockDialogRef.close.mock.calls[0][0]; + expect(savedData.presets.length).toBe(1); + expect(savedData.presets[0].name).toBe('Test Preset'); + expect(savedData.presets[0].content).toBe('Test instruction text'); + expect(savedData.presets[0].id).toBeTruthy(); + expect(savedData.activePresetId).toBe(savedData.presets[0].id); + }); + + it('keeps save disabled if name or instructions are only whitespace', async () => { + await harness.setPresetName(' '); + await harness.setInstructions('Some instructions'); + expect(await harness.isSaveDisabled()).toBe(true); + + await harness.setPresetName('Valid Name'); + await harness.setInstructions(' \n '); + expect(await harness.isSaveDisabled()).toBe(true); + }); + + it('closes dialog without data when cancel is clicked', async () => { + await harness.clickCancel(); + expect(mockDialogRef.close).toHaveBeenCalledWith(); + }); + }); + + describe('When presets exist with an active preset', () => { + const existingState: CustomInstructionsState = { + presets: [ + {id: 'p-1', name: 'Concise', content: 'Be concise and direct.'}, + {id: 'p-2', name: 'Verbose', content: 'Provide extensive explanations.'}, + ], + activePresetId: 'p-1', + }; + + beforeEach(async () => { + await createComponent(existingState); + }); + + it('defaults to the active preset and shows delete button', async () => { + expect(await harness.getSelectedPresetOptionText()).toBe('Concise'); + expect(await harness.getPresetName()).toBe('Concise'); + expect(await harness.getInstructions()).toBe('Be concise and direct.'); + expect(await harness.hasDeleteButton()).toBe(true); + expect(await harness.isSaveDisabled()).toBe(false); + }); + + it('overwrites the existing preset in-place when edited and saved', async () => { + await harness.setPresetName('Concise v2'); + await harness.setInstructions('Updated concise rules.'); + await harness.clickSave(); + + expect(mockDialogRef.close).toHaveBeenCalledWith({ + presets: [ + {id: 'p-1', name: 'Concise v2', content: 'Updated concise rules.'}, + {id: 'p-2', name: 'Verbose', content: 'Provide extensive explanations.'}, + ], + activePresetId: 'p-1', + }); + }); + + it('switches between presets when dropdown selection changes', async () => { + await harness.selectOption('Verbose'); + expect(await harness.getSelectedPresetOptionText()).toBe('Verbose'); + expect(await harness.getPresetName()).toBe('Verbose'); + expect(await harness.getInstructions()).toBe('Provide extensive explanations.'); + expect(await harness.hasDeleteButton()).toBe(true); + }); + + it('switches to "+ New preset..." and clears inputs', async () => { + await harness.selectOption('+ New preset...'); + expect(await harness.getPresetName()).toBe(''); + expect(await harness.getInstructions()).toBe(''); + expect(await harness.hasDeleteButton()).toBe(false); + expect(await harness.isSaveDisabled()).toBe(true); + }); + + it('deletes the selected preset and switches to None (Off)', async () => { + await harness.clickDelete(); + expect(await harness.getSelectedPresetOptionText()).toBe('None (Off)'); + expect(await harness.hasDeleteButton()).toBe(false); + expect(await harness.isSaveDisabled()).toBe(false); + + await harness.clickSave(); + expect(mockDialogRef.close).toHaveBeenCalledWith({ + presets: [{id: 'p-2', name: 'Verbose', content: 'Provide extensive explanations.'}], + activePresetId: null, + }); + }); + + it('preserves edits to existing preset when switching between options before clicking save', async () => { + await harness.setPresetName('Concise Updated'); + await harness.setInstructions('Updated concise rules.'); + + // Switch away to another preset + await harness.selectOption('Verbose'); + expect(await harness.getPresetName()).toBe('Verbose'); + expect(await harness.getInstructions()).toBe('Provide extensive explanations.'); + + // Switch back to Concise Updated + await harness.selectOption('Concise Updated'); + expect(await harness.getPresetName()).toBe('Concise Updated'); + expect(await harness.getInstructions()).toBe('Updated concise rules.'); + + await harness.clickSave(); + expect(mockDialogRef.close).toHaveBeenCalledWith({ + presets: [ + {id: 'p-1', name: 'Concise Updated', content: 'Updated concise rules.'}, + {id: 'p-2', name: 'Verbose', content: 'Provide extensive explanations.'}, + ], + activePresetId: 'p-1', + }); + }); + + it('preserves draft preset inputs when switching to an existing preset and back to "+ New preset..."', async () => { + await harness.selectOption('+ New preset...'); + await harness.setPresetName('Draft Preset'); + await harness.setInstructions('Draft instruction body'); + + // Switch to existing preset + await harness.selectOption('Concise'); + expect(await harness.getPresetName()).toBe('Concise'); + + // Switch back to "+ New preset..." + await harness.selectOption('+ New preset...'); + expect(await harness.getPresetName()).toBe('Draft Preset'); + expect(await harness.getInstructions()).toBe('Draft instruction body'); + + await harness.clickSave(); + expect(mockDialogRef.close).toHaveBeenCalledTimes(1); + const result: CustomInstructionsState = mockDialogRef.close.mock.calls[0][0]; + expect(result.presets.length).toBe(3); + expect(result.presets[2].name).toBe('Draft Preset'); + expect(result.presets[2].content).toBe('Draft instruction body'); + expect(result.activePresetId).toBe(result.presets[2].id); + }); + + it('discards preset deletion when dialog is cancelled', async () => { + await harness.clickDelete(); + expect(await harness.getSelectedPresetOptionText()).toBe('None (Off)'); + + await harness.clickCancel(); + expect(mockDialogRef.close).toHaveBeenCalledWith(); + }); + }); + + describe('When presets exist but activePresetId is null', () => { + const existingState: CustomInstructionsState = { + presets: [{id: 'p-1', name: 'Concise', content: 'Be concise.'}], + activePresetId: null, + }; + + beforeEach(async () => { + await createComponent(existingState); + }); + + it('defaults to "None (Off)" and enables save to persist disabled state', async () => { + expect(await harness.getSelectedPresetOptionText()).toBe('None (Off)'); + expect(await harness.hasDeleteButton()).toBe(false); + expect(await harness.isSaveDisabled()).toBe(false); + + await harness.clickSave(); + expect(mockDialogRef.close).toHaveBeenCalledWith({ + presets: [{id: 'p-1', name: 'Concise', content: 'Be concise.'}], + activePresetId: null, + }); + }); + }); +}); diff --git a/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.ts b/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.ts new file mode 100644 index 000000000..33c6540fe --- /dev/null +++ b/shell/src/app/chat/custom-instructions-dialog/custom-instructions-dialog.ts @@ -0,0 +1,201 @@ +/** + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Component, computed, inject, signal} from '@angular/core'; +import {FormsModule} from '@angular/forms'; +import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from '@angular/material/dialog'; +import {MatButtonModule} from '@angular/material/button'; +import {MatIconModule} from '@angular/material/icon'; +import {MatFormFieldModule} from '@angular/material/form-field'; +import {MatInputModule} from '@angular/material/input'; +import {MatSelectModule} from '@angular/material/select'; +import {generateUuid} from '../../utils/uuid'; +import { + CustomInstructionPreset, + CustomInstructionsState, +} from '../chat-prompt-factory/chat-prompt-factory.service'; + +const NONE_OPTION = '__none__'; +const NEW_OPTION = '__new__'; + +/** + * Dialog component allowing users to manage, select, edit, and create named Custom Instruction presets. + */ +@Component({ + selector: 'a2ui-composer-custom-instructions-dialog', + standalone: true, + imports: [ + FormsModule, + MatDialogModule, + MatButtonModule, + MatIconModule, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + ], + templateUrl: './custom-instructions-dialog.ng.html', + styleUrl: './custom-instructions-dialog.scss', +}) +export class CustomInstructionsDialog { + protected readonly NONE_OPTION = NONE_OPTION; + protected readonly NEW_OPTION = NEW_OPTION; + + private readonly dialogRef = inject(MatDialogRef); + protected readonly data = inject(MAT_DIALOG_DATA, { + optional: true, + }); + + protected readonly presets = signal( + this.data?.presets ? [...this.data.presets] : [], + ); + + protected readonly selectedOption = signal(this.computeInitialOption()); + protected readonly presetName = signal(this.computeInitialName()); + protected readonly instructionsContent = signal(this.computeInitialContent()); + protected readonly draftName = signal(''); + protected readonly draftContent = signal(''); + + protected readonly isExistingPreset = computed(() => { + const opt = this.selectedOption(); + return opt !== NONE_OPTION && opt !== NEW_OPTION; + }); + + protected readonly isNoneSelected = computed(() => this.selectedOption() === NONE_OPTION); + + protected readonly isSaveDisabled = computed(() => { + const anyInvalidExistingPreset = this.presets().some( + p => p.name.trim().length === 0 || p.content.trim().length === 0, + ); + if (anyInvalidExistingPreset) { + return true; + } + if (this.isNoneSelected()) { + return false; + } + return this.presetName().trim().length === 0 || this.instructionsContent().trim().length === 0; + }); + + private computeInitialOption(): string { + const list = this.presets(); + if (list.length === 0) { + return NEW_OPTION; + } + const activeId = this.data?.activePresetId; + if (activeId && list.some(p => p.id === activeId)) { + return activeId; + } + return NONE_OPTION; + } + + private computeInitialName(): string { + const initialOpt = this.computeInitialOption(); + if (initialOpt === NONE_OPTION || initialOpt === NEW_OPTION) { + return ''; + } + const preset = this.presets().find(p => p.id === initialOpt); + return preset?.name ?? ''; + } + + private computeInitialContent(): string { + const initialOpt = this.computeInitialOption(); + if (initialOpt === NONE_OPTION || initialOpt === NEW_OPTION) { + return ''; + } + const preset = this.presets().find(p => p.id === initialOpt); + return preset?.content ?? ''; + } + + protected onOptionChange(option: string): void { + this.selectedOption.set(option); + if (option === NEW_OPTION) { + this.presetName.set(this.draftName()); + this.instructionsContent.set(this.draftContent()); + } else if (option === NONE_OPTION) { + this.presetName.set(''); + this.instructionsContent.set(''); + } else { + const preset = this.presets().find(p => p.id === option); + this.presetName.set(preset?.name ?? ''); + this.instructionsContent.set(preset?.content ?? ''); + } + } + + protected onNameChange(value: string): void { + this.presetName.set(value); + if (this.selectedOption() === NEW_OPTION) { + this.draftName.set(value); + } else if (this.isExistingPreset()) { + const currentId = this.selectedOption(); + this.presets.update(list => list.map(p => (p.id === currentId ? {...p, name: value} : p))); + } + } + + protected onContentChange(value: string): void { + this.instructionsContent.set(value); + if (this.selectedOption() === NEW_OPTION) { + this.draftContent.set(value); + } else if (this.isExistingPreset()) { + const currentId = this.selectedOption(); + this.presets.update(list => list.map(p => (p.id === currentId ? {...p, content: value} : p))); + } + } + + protected deletePreset(): void { + const idToDelete = this.selectedOption(); + this.presets.update(list => list.filter(p => p.id !== idToDelete)); + this.selectedOption.set(NONE_OPTION); + this.presetName.set(''); + this.instructionsContent.set(''); + } + + protected cancel(): void { + this.dialogRef.close(); + } + + protected save(): void { + const opt = this.selectedOption(); + if (opt === NONE_OPTION) { + this.dialogRef.close({ + presets: this.presets(), + activePresetId: null, + }); + return; + } + + const name = this.presetName().trim(); + const content = this.instructionsContent().trim(); + + if (opt === NEW_OPTION) { + const newPreset: CustomInstructionPreset = { + id: generateUuid(), + name, + content, + }; + this.dialogRef.close({ + presets: [...this.presets(), newPreset], + activePresetId: newPreset.id, + }); + return; + } + + // Existing preset: overwrite in place + const updatedPresets = this.presets().map(p => (p.id === opt ? {...p, name, content} : p)); + this.dialogRef.close({ + presets: updatedPresets, + activePresetId: opt, + }); + } +} diff --git a/shell/src/app/chat/custom-instructions-dialog/test/custom-instructions-dialog.harness.ts b/shell/src/app/chat/custom-instructions-dialog/test/custom-instructions-dialog.harness.ts new file mode 100644 index 000000000..cc82300a1 --- /dev/null +++ b/shell/src/app/chat/custom-instructions-dialog/test/custom-instructions-dialog.harness.ts @@ -0,0 +1,153 @@ +/** + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ComponentHarness} from '@angular/cdk/testing'; +import {MatSelectHarness} from '@angular/material/select/testing'; +import {MatOptionHarness} from '@angular/material/core/testing'; +import {MatInputHarness} from '@angular/material/input/testing'; +import {MatButtonHarness} from '@angular/material/button/testing'; + +/** + * Harness for interacting with the CustomInstructionsDialog in unit tests. + */ +export class CustomInstructionsDialogHarness extends ComponentHarness { + /** The CSS selector used to locate the host element. */ + static hostSelector = 'a2ui-composer-custom-instructions-dialog'; + + private readonly getSelect = this.locatorFor(MatSelectHarness.with({selector: '.preset-select'})); + private readonly getNameInput = this.locatorForOptional(MatInputHarness); + private readonly getTextarea = this.locatorForOptional('.instructions-textarea'); + private readonly getSaveButton = this.locatorFor( + MatButtonHarness.with({selector: '.save-button'}), + ); + private readonly getCancelButton = this.locatorFor( + MatButtonHarness.with({selector: '.cancel-button'}), + ); + private readonly getDeleteButton = this.locatorForOptional( + MatButtonHarness.with({selector: '.delete-button'}), + ); + + /** + * Retrieves the displayed text of the currently selected preset option. + */ + async getSelectedPresetOptionText(): Promise { + const select = await this.getSelect(); + return select.getValueText(); + } + + /** + * Selects an option from the preset dropdown by option text. + */ + async selectOption(optionText: string): Promise { + const select = await this.getSelect(); + await select.open(); + const getOptions = this.locatorFactory + .documentRootLocatorFactory() + .locatorForAll(MatOptionHarness); + const options = await getOptions(); + for (const opt of options) { + const text = (await opt.getText()).trim(); + if (text === optionText || text.startsWith(optionText)) { + await opt.click(); + return; + } + } + throw new Error(`Option "${optionText}" not found in preset select dropdown.`); + } + + /** + * Retrieves the current preset name input value. + */ + async getPresetName(): Promise { + const input = await this.getNameInput(); + return input ? input.getValue() : ''; + } + + /** + * Sets the preset name input value. + */ + async setPresetName(value: string): Promise { + const input = await this.getNameInput(); + if (!input) { + throw new Error('Preset name input not found'); + } + await input.setValue(value); + } + + /** + * Retrieves the instructions textarea value. + */ + async getInstructions(): Promise { + const textarea = await this.getTextarea(); + if (!textarea) return ''; + return (await textarea.getProperty('value')) as string; + } + + /** + * Sets the instructions textarea value. + */ + async setInstructions(value: string): Promise { + const textarea = await this.getTextarea(); + if (!textarea) { + throw new Error('Instructions textarea not found'); + } + await textarea.setInputValue(value); + await textarea.dispatchEvent('input'); + } + + /** + * Returns true if the save button is currently disabled. + */ + async isSaveDisabled(): Promise { + const button = await this.getSaveButton(); + return button.isDisabled(); + } + + /** + * Clicks the save button. + */ + async clickSave(): Promise { + const button = await this.getSaveButton(); + await button.click(); + } + + /** + * Clicks the cancel button. + */ + async clickCancel(): Promise { + const button = await this.getCancelButton(); + await button.click(); + } + + /** + * Returns true if the delete button is visible in the dialog. + */ + async hasDeleteButton(): Promise { + const button = await this.getDeleteButton(); + return button !== null; + } + + /** + * Clicks the delete button. + */ + async clickDelete(): Promise { + const button = await this.getDeleteButton(); + if (!button) { + throw new Error('Delete button not found'); + } + await button.click(); + } +} diff --git a/shell/src/app/shell/composer-shell/composer-shell.spec.ts b/shell/src/app/shell/composer-shell/composer-shell.spec.ts index 3447f9318..57627f431 100644 --- a/shell/src/app/shell/composer-shell/composer-shell.spec.ts +++ b/shell/src/app/shell/composer-shell/composer-shell.spec.ts @@ -216,6 +216,9 @@ describe('ComposerShell Layout', () => { expect(localStorageServiceMock.removeItem).not.toHaveBeenCalledWith( LocalStorageKey.DOCKVIEW_LAYOUT, ); + expect(localStorageServiceMock.removeItem).not.toHaveBeenCalledWith( + LocalStorageKey.CUSTOM_INSTRUCTIONS, + ); expect(sessionStorageServiceMock.clear).toHaveBeenCalled(); expect(consoleSpy).toHaveBeenCalledWith('Session state cleared.'); }); diff --git a/shell/src/app/storage/models/local-storage-keys.ts b/shell/src/app/storage/models/local-storage-keys.ts index 0ff8d8cc6..3fd96c3e9 100644 --- a/shell/src/app/storage/models/local-storage-keys.ts +++ b/shell/src/app/storage/models/local-storage-keys.ts @@ -50,6 +50,8 @@ export enum LocalStorageKey { A2A_BACKEND_MODE = 'a2ui_composer_a2a_backend_mode', /** Key for storing configured MCP servers. */ MCP_SERVERS = 'a2ui_composer_mcp_servers', + /** Key for storing user custom instruction presets and active preset selection. */ + CUSTOM_INSTRUCTIONS = 'a2ui_composer_custom_instructions', /** @deprecated Key for retrieving the active workspace prompt in-progress draft content. */ ACTIVE_DRAFT = 'a2ui_composer_active_draft',