8000 fix: surface invalid session errors from agent runs by KevinAndrewDong · Pull Request #564 · google/adk-web · GitHub
[go: up one dir, main page]

Skip to content
Open
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
2 changes: 2 additions & 0 deletions src/app/components/chat/chat.component.i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export const CHAT_MESSAGES = {
cancelUserIdEditTooltip: 'Cancel editing user ID',
invalidUserIdMessage: 'User ID cannot be empty',
loadingSessionLabel: 'Loading session...',
sessionNotFoundMessage:
'This session is no longer available. Start a new session to continue.',
tokenStreamingLabel: 'Token Streaming',
moreOptionsTooltip: 'More options',
createNewSessionTooltip: 'Create a new Session',
Expand Down
54 changes: 54 additions & 0 deletions src/app/components/chat/chat.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {ActivatedRoute, NavigationEnd, Router, UrlTree} from '@angular/router';
// 1p-ONLY-IMPORTS: import {beforeEach, describe, expect, it}
import {BehaviorSubject, NEVER, of, ReplaySubject, Subject, throwError} from 'rxjs';

import {AgentRunRequest} from '../../core/models/AgentRunRequest';
import {EvalCase} from '../../core/models/Eval';
import {OPERATION_GENERATE_CONTENT} from '../../core/models/Trace';
import {Session} from '../../core/models/Session';
Expand Down Expand Up @@ -85,6 +86,7 @@ import {TelemetryConsentDialogComponent} from '../telemetry-consent-dialog/telem
import {computed, signal} from '@angular/core';

import {ChatComponent, HIDE_SIDE_PANEL_QUERY_PARAM, INITIAL_USER_INPUT_QUERY_PARAM} from './chat.component';
import {CHAT_MESSAGES} from './chat.component.i18n';

// Mock EvalTabComponent to satisfy the required viewChild in ChatComponent
@Component({
Expand Down Expand Up @@ -1173,6 +1175,58 @@ describe('ChatComponent', () => {
});
});

describe('Agent run errors', () => {
const request: AgentRunRequest = {
appName: TEST_APP_1_NAME,
userId: USER_ID,
sessionId: SESSION_1_ID,
newMessage: {role: 'user', parts: [{text: TEST_MESSAGE}]},
};

beforeEach(() => {
mockAgentService.listAppsResponse.next([TEST_APP_1_NAME]);
component.sessionId = SESSION_1_ID;
component.submitAgentRunRequest(request);
});

it('should explain how to recover from a missing session', () => {
const events = component.uiEvents();
mockAgentService.runSseResponse.error(
new HttpErrorResponse({status: 404, statusText: 'Not Found'}));

expect(mockSnackBar.open).toHaveBeenCalledWith(
CHAT_MESSAGES.sessionNotFoundMessage, OK_BUTTON_TEXT);
expect(component.sessionId).toBe(SESSION_1_ID);
expect(component.uiEvents()).toBe(events);
expect(mockSessionService.createSession).not.toHaveBeenCalled();
expect(mockAgentService.runSse).toHaveBeenCalledTimes(1);
});

it('should display other HTTP errors as readable text', () => {
const error = new HttpErrorResponse(
{status: 500, statusText: 'Internal Server Error'});
mockAgentService.runSseResponse.error(error);

expect(mockSnackBar.open)
.toHaveBeenCalledWith(error.message, OK_BUTTON_TEXT);
});

it('should display network errors as readable text', () => {
const error = new Error('Network request failed');
mockAgentService.runSseResponse.error(error);

expect(mockSnackBar.open)
.toHaveBeenCalledWith(String(error), OK_BUTTON_TEXT);
});

it('should keep cancelled requests silent', () => {
mockAgentService.runSseResponse.error(
new DOMException('The operation was aborted.', 'AbortError'));

expect(mockSnackBar.open).not.toHaveBeenCalled();
});
});

describe('ChatPanel integration', () => {
beforeEach(() => {
mockAgentService.listAppsResponse.next(
Expand Down
8 changes: 7 additions & 1 deletion src/app/components/chat/chat.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1409,7 +1409,13 @@ export class ChatComponent implements OnInit, AfterViewInit, OnDestroy {
if (errString.includes('aborted') || errString.includes('AbortError')) {
return;
}
this.openSnackBar(err, 'OK');
let errorMessage = errString;
if (err instanceof HttpErrorResponse) {
errorMessage = err.status === 404
? this.i18n.sessionNotFoundMessage
: err.message;
}
this.openSnackBar(errorMessage, 'OK');
},
complete: () => {
this.activeSseSubscription = undefined;
Expand Down
35 changes: 35 additions & 0 deletions src/app/core/services/agent.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import {HttpErrorResponse} from '@angular/common/http';
import {HttpClientTestingModule, HttpTestingController,} from '@angular/common/http/testing';
import {TestBed} from '@angular/core/testing';
// 1p-ONLY-IMPORTS: import {beforeEach, describe, expect, it}
Expand Down Expand Up @@ -128,6 +129,40 @@ describe('AgentService', () => {
});

describe('runSse', () => {
for (const {status, statusText, body} of [
{
status: 404,
statusText: 'Not Found',
body: JSON.stringify({detail: 'Session not found'}),
},
{status: 401, statusText: 'Unauthorized', body: 'Unauthorized'},
{
status: 500,
statusText: 'Internal Server Error',
body: '<html>Server error</html>',
},
]) {
it(`should reject HTTP ${status} without reading it as SSE`, async () => {
const response = new Response(body, {status, statusText});
const getReader = spyOn(response.body!, 'getReader').and.callThrough();
spyOn(window, 'fetch').and.resolveTo(response);

const result = firstValueFrom(
service.runSse(RUN_SSE_PAYLOAD).pipe(toArray()),
);
await expectAsync(result)
.toBeRejectedWith(jasmine.any(HttpErrorResponse));
await expectAsync(result).toBeRejectedWith(jasmine.objectContaining({
name: 'HttpErrorResponse',
status,
statusText,
url: API_SERVER_BASE_URL + RUN_SSE_PATH,
}));
expect(getReader).not.toHaveBeenCalled();
expect(service.getLoadingState().value).toBeFalse();
});
}

it('should set loading state to true when called', async () => {
spyOn(window, 'fetch').and.resolveTo(new Response());
service.runSse(RUN_SSE_PAYLOAD).subscribe();
Expand Down
9 changes: 8 additions & 1 deletion src/app/core/services/agent.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import { HttpClient } from '@angular/common/http';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, NgZone } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { URLUtil } from '../../../utils/url-util';
Expand Down Expand Up @@ -68,6 +68,13 @@ export class AgentService implements AgentServiceInterface {
signal,
})
.then((response) => {
if (!response.ok) {
throw new HttpErrorResponse({
status: response.status,
statusText: response.statusText,
url: response.url || url,
});
}
reader = response.body?.getReader();
const decoder = new TextDecoder('utf-8');
let lastData = '';
Expand Down
Loading
0