Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ the current canvas, or inspect the assistant's instructions. When screenshot
capture is enabled, the **+** button shows an indicator; open the menu to turn it
off. You can keep drafting your prompt while opening these controls.

The renderer menu beside Send switches to any configured renderer without
leaving the chat. It keeps your typed prompt and waits for the selected
renderer's catalog before you can send. You can manage renderer options in
Settings.

Once the A2UI JSON for your interface is rendered, you can:

- Use the chat panel to request changes
Expand Down
66 changes: 66 additions & 0 deletions shell/e2e/copilot-assistant.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ test.beforeEach(async ({page}) => {
rendererUrl: 'http://localhost:3456',
displayName: 'Angular Basic',
},
lit: {
rendererUrl: 'http://localhost:3457',
displayName: 'Lit Basic',
},
},
apiKeys: {
default: {
Expand Down Expand Up @@ -166,6 +170,68 @@ async function expectGeminiRequestForCurrentDraft(page: Page, expectedDraftText:
}

test.describe('Copilot assistant replacement browser journey', () => {
test('switches between configured renderers from the pill and keeps the typed prompt', async ({
page,
}) => {
await openDraftInWorkspace(page);
const prompt = page.getByRole('textbox', {name: 'Chat prompt'});
await prompt.fill('Create a simple card in this renderer');
const selector = page.getByRole('button', {name: /Choose renderer, current:/});

await selector.click();
await expect(page.getByRole('menuitemradio', {name: 'Angular Basic'})).toHaveAttribute(
'aria-checked',
'true',
);
await page.getByRole('menuitemradio', {name: 'Lit Basic'}).click();
await expect(selector).toHaveAccessibleName('Choose renderer, current: Lit Basic');
await expect(page.locator('.workspace-container iframe')).toHaveAttribute(
'src',
/localhost:3457/,
);
// Only Lit Basic's catalog has this title; Angular Basic's is "my_basic_catalog A2UI Catalog".
await expect(page.locator('.header-title')).toHaveText('A2UI Composer - Basic Catalog');
await expect(page.getByRole('button', {name: 'Send prompt'})).toBeEnabled();
await expect(prompt).toHaveValue('Create a simple card in this renderer');

await selector.click();
await expect(page.getByRole('menuitemradio', {name: 'Lit Basic'})).toHaveAttribute(
'aria-checked',
'true',
);
await page.getByRole('menuitemradio', {name: 'Angular Basic'}).click();
await expect(selector).toHaveAccessibleName('Choose renderer, current: Angular Basic');
await expect(page.locator('.header-title')).toContainText('my_basic_catalog');
await expect(page.getByRole('button', {name: 'Send prompt'})).toBeEnabled();
await expect(prompt).toHaveValue('Create a simple card in this renderer');
});

test('explains under the renderer menu why a renderer could not be selected', async ({page}) => {
// Seed in every frame: the shared setup clears storage in each same-origin frame as it loads.
await page.addInitScript(() => {
localStorage.setItem(
'a2ui_composer_custom_renderers',
JSON.stringify([
{id: 'legacy', name: 'Legacy preview', rendererUrl: 'ftp://files.example/renderer'},
]),
);
});
await openDraftInWorkspace(page);
const selector = page.getByRole('button', {name: /Choose renderer, current:/});

await selector.click();
await page.getByRole('menuitemradio', {name: 'Legacy preview'}).click();

await expect(page.locator('a2ui-composer-chat-panel').getByRole('alert')).toHaveText(
"Couldn't switch to Legacy preview because its URL isn't an http or https address. Fix its URL in Settings, or choose another renderer.",
);
await expect(selector).toHaveAccessibleName('Choose renderer, current: Angular Basic');
await expect(page.locator('.workspace-container iframe')).toHaveAttribute(
'src',
/localhost:3456/,
);
});

test('keeps prompt helpers in the Add menu and preserves drafted text', async ({page}) => {
await openDraftInWorkspace(page);
const prompt = page.getByRole('textbox', {name: 'Chat prompt'});
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,39 @@
</mat-menu>
</div>
<div class="action-bar-right">
<button
mat-button
type="button"
class="renderer-selector"
[matMenuTriggerFor]="rendererMenu"
[disabled]="isRendererSwitchDisabled()"
[attr.aria-label]="'Choose renderer, current: ' + rendererLabel()"
[title]="rendererLabel()"
>
<span class="renderer-selector-label">{{ rendererLabel() }}</span>
<mat-icon iconPositionEnd aria-hidden="true">expand_more</mat-icon>
</button>
<mat-menu
#rendererMenu="matMenu"
class="composer-renderer-menu"
yPosition="above"
xPosition="before"
>
@for (renderer of rendererSelection.renderers(); track renderer.id) {
<button
mat-menu-item
role="menuitemradio"
[attr.aria-checked]="renderer.id === rendererSelection.selectedRendererId()"
[disabled]="isRendererSwitchDisabled()"
(click)="selectRenderer(renderer.id)"
>
<mat-icon aria-hidden="true">{{
renderer.id === rendererSelection.selectedRendererId() ? 'check' : ''
}}</mat-icon>
{{ renderer.name }}
</button>
}
</mat-menu>
@if (isLocked()) {
<button
mat-icon-button
Expand All @@ -398,6 +431,7 @@
class="submit-button send-button"
[disabled]="
isReadingFiles() ||
rendererSelection.isSwitching() ||
!isHandshakeComplete() ||
(!userPrompt().trim() && attachedFiles().length === 0)
"
Expand All @@ -410,6 +444,11 @@
}
</div>
</div>
@if (rendererSelection.error(); as error) {
<p class="renderer-feedback renderer-error" role="alert">{{ error }}</p>
} @else if (rendererSelection.isSwitching()) {
<p class="renderer-feedback" role="status">Switching renderer…</p>
}
</div>
</ng-template>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,36 @@ a2ui-composer-chat-panel {
gap: 0;
}

.renderer-selector {
min-width: 0;
max-width: 180px;
padding: 0 10px;
border-radius: 24px;
background: var(--mat-sys-surface-container);
color: var(--mat-sys-on-surface-variant);
font: var(--mat-sys-label-medium);
}

.renderer-selector-label {
display: inline-block;
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}

.renderer-feedback {
margin: 8px 8px 0;
color: var(--mat-sys-on-surface-variant);
font: var(--mat-sys-body-small);
overflow-wrap: anywhere;
}

.renderer-error {
color: var(--mat-sys-error);
}

.add-prompt-button.has-screenshot {
color: var(--mat-sys-primary);
background: var(--mat-sys-primary-container);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {CopilotKitChatPanelHarness} from './test/copilotkit-chat-panel.harness';
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
import {ChatCoordinator} from '../chat-coordinator/chat-coordinator';
import {ChatState, LlmLogEntry, LlmLogType} from '../chat-state/chat-state';
import {signal, inject} from '@angular/core';
import {signal, inject, computed} from '@angular/core';
import {LlmMessage, MessageRole, Attachment} from '../llm-client/llm-client';
import {PipelineStatus} from '../pipeline-status/pipeline-status';
import {provideNoopAnimations} from '@angular/platform-browser/animations';
Expand All @@ -34,6 +34,8 @@ import {MatInputHarness} from '@angular/material/input/testing';
import {Catalog} from '../../storage/models/catalog-storage.model';
import {HostCommunication} from '../../shell/host-communication/host-communication';
import {ScreenshotCaptureService} from '../../shell/screenshot/screenshot-capture.service';
import {RendererSelection} from '../renderer-selection/renderer-selection';
import {RendererOption} from '../../settings/settings-service/settings.service';
import {FailureParseResult} from '../a2ui-payload-parser/a2ui-payload-parser';
import {McpClientManagerService} from '../../mcp/mcp-client-manager.service';
import {
Expand Down Expand Up @@ -138,8 +140,26 @@ class MockHostCommunication {
getIframeElement = vi.fn().mockReturnValue(null);
}

class MockRendererSelection {
readonly renderers = signal<RendererOption[]>([
{id: 'default', name: 'Angular Basic', rendererUrl: '/angular', readOnly: true},
{id: 'lit', name: 'Lit Basic', rendererUrl: '/lit', readOnly: true},
{id: 'custom', name: 'My renderer', rendererUrl: '/custom', readOnly: false},
]);
readonly selectedRendererId = signal<string | null>('default');
readonly activeRenderer = computed(
() => this.renderers().find(renderer => renderer.id === this.selectedRendererId()) || null,
);
readonly isSwitching = signal(false);
readonly error = signal<string | null>(null);
readonly selectRenderer = vi.fn(async (rendererId: string) => {
this.selectedRendererId.set(rendererId);
});
}

describe('CopilotKitChatPanel Gemini Dialogue Panel Integration', () => {
let fixture: ComponentFixture<CopilotKitChatPanel>;
let rendererSelectionMock: MockRendererSelection;
let harness: CopilotKitChatPanelHarness;
let chatServiceMock: MockChatCoordinator;
let chatStateMock: MockChatState;
Expand All @@ -164,6 +184,7 @@ describe('CopilotKitChatPanel Gemini Dialogue Panel Integration', () => {
provideRouter([]),
{provide: ChatCoordinator, useClass: MockChatCoordinator},
{provide: ChatPromptFactoryService, useClass: MockChatPromptFactoryService},
{provide: RendererSelection, useClass: MockRendererSelection},
{provide: ChatState, useClass: MockChatState},
{provide: CatalogManagement, useClass: MockCatalogManagement},
{provide: AppConfigProvider, useClass: MockAppConfigProvider},
Expand All @@ -184,6 +205,7 @@ describe('CopilotKitChatPanel Gemini Dialogue Panel Integration', () => {
hostCommunicationMock = TestBed.inject(HostCommunication) as unknown as MockHostCommunication;
screenshotServiceMock = TestBed.inject(ScreenshotCaptureService);
stateSyncMock = TestBed.inject(StateSync) as unknown as MockStateSync;
rendererSelectionMock = TestBed.inject(RendererSelection) as unknown as MockRendererSelection;
fixture = TestBed.createComponent(CopilotKitChatPanel);
fixture.detectChanges();
harness = await TestbedHarnessEnvironment.harnessForFixture(
Expand All @@ -199,6 +221,69 @@ describe('CopilotKitChatPanel Gemini Dialogue Panel Integration', () => {
vi.restoreAllMocks();
});

it('switches the renderer through the shared service without discarding the typed prompt', async () => {
await harness.setPromptText('Create a score card');
expect(await harness.getRendererLabel()).toBe('Angular Basic');
await harness.selectRenderer('Lit Basic');
expect(rendererSelectionMock.selectRenderer).toHaveBeenCalledWith('lit');
expect(await harness.getRendererLabel()).toBe('Lit Basic');
expect(await harness.getPromptText()).toBe('Create a score card');
expect(chatServiceMock.submitPrompt).not.toHaveBeenCalled();
});

it('lists configured renderers with the active option selected and reacts to external switches', async () => {
rendererSelectionMock.selectedRendererId.set('custom');
fixture.detectChanges();
expect(await harness.getRendererLabel()).toBe('My renderer');
const choices = await harness.getRendererChoices();
expect(choices).toHaveLength(3);
expect(choices.map(choice => choice.selected)).toEqual([false, false, true]);
expect(choices[1].label).toContain('Lit Basic');
rendererSelectionMock.selectedRendererId.set('lit');
fixture.detectChanges();
expect(await harness.getRendererLabel()).toBe('Lit Basic');
});

it('disables renderer changes during generation and renderer loading', async () => {
expect(await harness.isRendererSelectorDisabled()).toBe(false);
chatStateMock.isProgrammaticStreamActive.set(true);
fixture.detectChanges();
expect(await harness.isRendererSelectorDisabled()).toBe(true);
chatStateMock.isProgrammaticStreamActive.set(false);
rendererSelectionMock.isSwitching.set(true);
fixture.detectChanges();
expect(await harness.isRendererSelectorDisabled()).toBe(true);
expect(await harness.getRendererFeedback()).toBe('Switching renderer…');
await harness.setPromptText('Keep this request');
expect(await harness.isSubmitDisabled()).toBe(true);
await harness.pressKeyOnPrompt('Enter');
expect(chatServiceMock.submitPrompt).not.toHaveBeenCalled();
expect(await harness.getPromptText()).toBe('Keep this request');
});

it('displays renderer failures and preserves the request for recovery', async () => {
rendererSelectionMock.selectRenderer.mockImplementationOnce(async () => {
rendererSelectionMock.error.set('The Lit Basic renderer could not connect. Try again.');
throw new Error('Renderer handshake timed out');
});
await harness.setPromptText('Generate a Lit Basic message');
await harness.selectRenderer('Lit Basic');
expect(await harness.getRendererFeedback()).toBe(
'The Lit Basic renderer could not connect. Try again.',
);
expect(await harness.getPromptText()).toBe('Generate a Lit Basic message');
expect(await harness.isRendererSelectorDisabled()).toBe(false);
});

it('prevents renderer changes while attachments are being read', async () => {
fixture.componentInstance.isReadingFiles.set(true);
fixture.detectChanges();
expect(await harness.isRendererSelectorDisabled()).toBe(true);
fixture.componentInstance.isReadingFiles.set(false);
fixture.detectChanges();
expect(await harness.isRendererSelectorDisabled()).toBe(false);
});

it('renders native CopilotKit prose from ChatState and clears it on a new session', async () => {
expect(await harness.hasCopilotChatView()).toBe(true);
chatStateMock.chatHistory.set([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import {Component, computed, ViewEncapsulation} from '@angular/core';
import {Component, computed, inject, ViewEncapsulation} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {
CopilotChatView,
Expand All @@ -35,6 +35,7 @@ import {RouterLink} from '@angular/router';
import {AutoScroll, ChatPanelBase} from '../chat-panel/chat-panel-base';
import {isRenderA2uiItem, parseAndHealJsonLines} from '../a2ui-payload-parser/a2ui-payload-parser';
import {LlmMessage, MessageRole} from '../llm-client/llm-client';
import {RendererSelection} from '../renderer-selection/renderer-selection';

/** A chat turn as the CopilotKit panel presents it. */
export interface PresentedTurn extends LlmMessage {
Expand Down Expand Up @@ -80,6 +81,56 @@ export interface PresentedTurn extends LlmMessage {
encapsulation: ViewEncapsulation.None,
})
export class CopilotKitChatPanel extends ChatPanelBase {
/**
* Backs the renderer menu in the prompt pill, which switches renderers in
* one step instead of a trip to Settings.
*/
protected readonly rendererSelection = inject(RendererSelection);

/** The active renderer's configured display name, so no renderer is special-cased. */
protected readonly rendererLabel = computed(
() => this.rendererSelection.activeRenderer()?.name ?? 'Renderer',
);

/**
* Whether the renderer menu is disabled: while a response is generating,
* while attachments are being read, or while a switch is in progress.
*/
protected readonly isRendererSwitchDisabled = computed(
() => this.isLocked() || this.isReadingFiles() || this.rendererSelection.isSwitching(),
);

protected async selectRenderer(rendererId: string): Promise<void> {
if (this.isRendererSwitchDisabled()) {
return;
}
try {
await this.rendererSelection.selectRenderer(rendererId);
} catch {
// RendererSelection publishes the failure, which the template shows under the menu.
}
}

/**
* Sends the prompt, unless a renderer switch is in progress.
*
* During a switch the Send button is disabled and the panel shows "Switching
* renderer…". Pressing Enter calls this method directly, so it repeats that
* check. The prompt stays in the input, and the user sends it once the new
* renderer's catalog is active, so it's never generated against the old one.
*/
protected override async submitPrompt(options?: {
promptId?: string;
promptTurnIndex?: number;
retryOfPromptId?: string;
}): Promise<void> {
if (this.rendererSelection.isSwitching()) {
// Not sent: the text stays in the input until the switch finishes.
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a comment here -- reading the code seems to contradict the JSDoc. If a renderer switch is underway, how does the prompt get submitted?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, the doc was wrong: it doesn't wait, it skips sending. During a switch the Send button is disabled and the panel shows "Switching renderer…". Pressing Enter calls submitPrompt directly, so the override repeats that check. The prompt stays in the input, and the user sends it once the new renderer's catalog is active, so it's never generated against the old catalog. I rewrote the JSDoc to say that and added a comment at the early return.

}
await super.submitPrompt(options);
}

/**
* The visible conversation, prepared for CopilotKit.
*
Expand Down
Loading
Loading