Browse Source

feat: AI chat: deny an approval with what should be different (from the card or the composer), status marks for chats that run or need the user, and Stop / Esc for a running reply

pull/16833/head
Igor Kulikov 1 month ago
parent
commit
bd65304a66
  1. 9
      application/src/main/java/org/thingsboard/server/controller/AiChatController.java
  2. 2
      application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
  3. 6
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  4. 16
      application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
  5. 4
      ui-ngx/src/app/core/http/ai-chat.service.ts
  6. 45
      ui-ngx/src/app/core/services/ai-chats.service.ts
  7. 7
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html
  8. 24
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss
  9. 33
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts
  10. 6
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  11. 5
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts
  12. 12
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html
  13. 24
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss
  14. 86
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  15. 40
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html
  16. 14
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss
  17. 21
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts
  18. 4
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html
  19. 16
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts
  20. 14
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  21. 8
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  22. 15
      ui-ngx/src/theme/ai-theme.scss

9
application/src/main/java/org/thingsboard/server/controller/AiChatController.java

@ -65,6 +65,15 @@ class AiChatController extends BaseController {
aiChatService.updateChat(chatId, request, user); aiChatService.updateChat(chatId, request, user);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{chatId}/stop")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void stopChat(@PathVariable UUID chatId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
aiChatService.stopChat(chatId, user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping @GetMapping
public JsonNode listChats() throws ThingsboardException { public JsonNode listChats() throws ThingsboardException {

2
application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java

@ -15,6 +15,8 @@ public interface AiChatService {
void updateChat(UUID chatId, JsonNode request, SecurityUser user); void updateChat(UUID chatId, JsonNode request, SecurityUser user);
void stopChat(UUID chatId, SecurityUser user);
JsonNode listChats(SecurityUser user); JsonNode listChats(SecurityUser user);
JsonNode getChatMessages(UUID chatId, SecurityUser user); JsonNode getChatMessages(UUID chatId, SecurityUser user);

6
application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java

@ -56,6 +56,12 @@ class DefaultAiChatService implements AiChatService {
new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false); new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false);
} }
@Override
public void stopChat(UUID chatId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_STOP, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false);
}
@Override @Override
public void deleteChat(UUID chatId, SecurityUser user) { public void deleteChat(UUID chatId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute( tbAiService.process(tokenProvider -> operations.execute(

16
application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java

@ -155,6 +155,22 @@ class DefaultAiChatServiceTest {
then(tbAiService).shouldHaveNoMoreInteractions(); then(tbAiService).shouldHaveNoMoreInteractions();
} }
@Test
void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopChatCalled() {
// GIVEN
UUID chatId = UUID.randomUUID();
given(tbAiService.process(any(), same(user), eq(false))).willReturn(null);
// WHEN
service.stopChat(chatId, user);
// THEN
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_STOP.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@Test @Test
void shouldProcessStreamAndDelegateToTransportWithTurnContext_whenSendChatMessageWithClientContextCalled() { void shouldProcessStreamAndDelegateToTransportWithTurnContext_whenSendChatMessageWithClientContextCalled() {
// GIVEN // GIVEN

4
ui-ngx/src/app/core/http/ai-chat.service.ts

@ -62,6 +62,10 @@ export class AiChatService {
* Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the * Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the
* live ones. Completes with no events when nothing is running. * live ones. Completes with no events when nothing is running.
*/ */
public stopChat(chatId: string, config?: RequestConfig): Observable<void> {
return this.http.post<void>(`/api/ai/chats/${chatId}/stop`, null, defaultHttpOptionsFromConfig(config));
}
public resumeChat(chatId: string, config?: RequestConfig): Observable<ChatEvent> { public resumeChat(chatId: string, config?: RequestConfig): Observable<ChatEvent> {
return this.streamEvents(`/api/ai/chats/${chatId}/resume`, null, config); return this.streamEvents(`/api/ai/chats/${chatId}/resume`, null, config);
} }

45
ui-ngx/src/app/core/services/ai-chats.service.ts

@ -1,13 +1,13 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
import { inject, Injectable, signal } from '@angular/core'; import { inject, Injectable, signal, untracked, WritableSignal } from '@angular/core';
import { Observable, of } from 'rxjs'; import { Observable, of } from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators'; import { map, switchMap, tap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { AiChatService } from '@core/http/ai-chat.service'; import { AiChatService } from '@core/http/ai-chat.service';
import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service';
import { DialogService } from '@core/services/dialog.service'; import { DialogService } from '@core/services/dialog.service';
import { ChatInfo } from '@shared/models/ai-chat.models'; import { ChatInfo, ChatLevel } from '@shared/models/ai-chat.models';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class AiChatsService { export class AiChatsService {
@ -26,6 +26,37 @@ export class AiChatsService {
private _replying = signal<ReadonlySet<string>>(new Set()); private _replying = signal<ReadonlySet<string>>(new Set());
readonly replying = this._replying.asReadonly(); readonly replying = this._replying.asReadonly();
private _waiting = signal<ReadonlySet<string>>(new Set());
private _open = signal<ReadonlySet<string>>(new Set());
levelOf(chat: ChatInfo): ChatLevel | null {
if (this._waiting().has(chat.id)) {
return 'needs';
}
if (this._replying().has(chat.id)) {
return 'running';
}
if (this._open().has(chat.id)) {
return null;
}
return chat.status === 'NEEDS_YOU' ? 'needs' : chat.status === 'RUNNING' ? 'running' : null;
}
setWaiting(chatId: string | undefined, waiting: boolean): void {
this.toggle(this._waiting, chatId, waiting);
}
setOpen(chatId: string | undefined, open: boolean): void {
this.toggle(this._open, chatId, open);
}
refresh(): Observable<ChatInfo[]> {
return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe(
tap(chats => this._chats.set(chats))
);
}
load(): Observable<ChatInfo[]> { load(): Observable<ChatInfo[]> {
return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe(
tap({ tap({
@ -93,12 +124,16 @@ export class AiChatsService {
} }
setReplying(chatId: string | undefined, replying: boolean): void { setReplying(chatId: string | undefined, replying: boolean): void {
if (!chatId) { this.toggle(this._replying, chatId, replying);
}
private toggle(target: WritableSignal<ReadonlySet<string>>, chatId: string | undefined, on: boolean): void {
if (!chatId || untracked(target).has(chatId) === on) {
return; return;
} }
this._replying.update(set => { target.update(set => {
const next = new Set(set); const next = new Set(set);
if (replying) { if (on) {
next.add(chatId); next.add(chatId);
} else { } else {
next.delete(chatId); next.delete(chatId);

7
ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html

@ -18,6 +18,13 @@
{{ data.approveLabel ?? ('ai-assistant.approve' | translate) }} {{ data.approveLabel ?? ('ai-assistant.approve' | translate) }}
</button> </button>
</div> </div>
@if (denying) {
<input #denyInput class="deny-line" type="text" maxlength="2000"
[placeholder]="'ai-assistant.what-should-be-different' | translate"
[attr.aria-label]="'ai-assistant.what-should-be-different' | translate"
(keydown.enter)="$event.preventDefault(); sendDeny(denyInput.value)"
(keydown.escape)="$event.stopPropagation(); closeDeny()">
}
<button mat-button class="approve-all" (click)="approveAll()"> <button mat-button class="approve-all" (click)="approveAll()">
<mat-icon>done_all</mat-icon> <mat-icon>done_all</mat-icon>
{{ 'ai-assistant.approve-all' | translate }} {{ 'ai-assistant.approve-all' | translate }}

24
ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss

@ -67,6 +67,30 @@
} }
} }
.deny-line {
display: block;
width: 100%;
height: 36px;
box-sizing: border-box;
margin-top: 8px;
padding: 0 12px;
border: 0;
border-radius: 8px;
outline: 0;
background: var(--tb-surface);
box-shadow: inset 0 0 0 1px var(--k-stroke-hover);
font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font);
color: var(--tb-ink);
&:focus {
box-shadow: inset 0 0 0 1.5px var(--ai-focus), 0 0 0 3px var(--ai-focus-shadow);
}
&::placeholder {
color: var(--tb-text-secondary);
}
}
.approve-all { .approve-all {
width: 100%; width: 100%;
margin-top: 8px; margin-top: 8px;

33
ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts

@ -3,13 +3,15 @@
import { import {
ChangeDetectorRef, ChangeDetectorRef,
Component, Component,
ElementRef,
EventEmitter, EventEmitter,
HostBinding, HostBinding,
inject, inject,
Input, Input,
OnChanges, OnChanges,
Output, Output,
SimpleChanges SimpleChanges,
ViewChild
} from '@angular/core'; } from '@angular/core';
import { import {
ApprovalResult, ApprovalResult,
@ -34,6 +36,12 @@ export class AiApprovalCardComponent implements OnChanges {
@Input() autoApprove = false; @Input() autoApprove = false;
@Input() answered = false;
@ViewChild('denyInput') denyInput: ElementRef<HTMLInputElement>;
denying = false;
@Output() approvalAction = new EventEmitter<ApprovalResult>(); @Output() approvalAction = new EventEmitter<ApprovalResult>();
@HostBinding('class') state: ApprovalCardState = 'pending'; @HostBinding('class') state: ApprovalCardState = 'pending';
@ -44,6 +52,10 @@ export class AiApprovalCardComponent implements OnChanges {
if (this.autoApprove && this.state === 'pending' && !this.completedExecution) { if (this.autoApprove && this.state === 'pending' && !this.completedExecution) {
this.approve(); this.approve();
} }
if (this.answered && this.state === 'pending' && !this.completedExecution) {
this.denying = false;
this.state = 'executing';
}
if (changes.completedExecution && this.completedExecution?.executionId === this.data.executionId) { if (changes.completedExecution && this.completedExecution?.executionId === this.data.executionId) {
const result = this.completedExecution; const result = this.completedExecution;
if (result.approvalStatus === ToolApprovalResult.DENIED || result.approvalStatus === ToolApprovalResult.TIMEOUT) { if (result.approvalStatus === ToolApprovalResult.DENIED || result.approvalStatus === ToolApprovalResult.TIMEOUT) {
@ -88,8 +100,25 @@ export class AiApprovalCardComponent implements OnChanges {
} }
deny(): void { deny(): void {
if (this.denying) {
this.sendDeny(this.denyInput?.nativeElement.value ?? '');
return;
}
this.denying = true;
setTimeout(() => this.denyInput?.nativeElement.focus());
}
sendDeny(words: string): void {
const reason = words.trim();
this.denying = false;
this.state = 'executing'; this.state = 'executing';
this.approvalAction.emit({executionId: this.data.executionId, approved: false}); this.approvalAction.emit(reason
? {executionId: this.data.executionId, approved: false, reason}
: {executionId: this.data.executionId, approved: false});
}
closeDeny(): void {
this.denying = false;
} }
private emitApproval(autoApprove = false): void { private emitApproval(autoApprove = false): void {

6
ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html

@ -26,6 +26,7 @@
[data]="getApprovalData(msg)" [data]="getApprovalData(msg)"
[completedExecution]="getCompletedExecution(msg)" [completedExecution]="getCompletedExecution(msg)"
[autoApprove]="autoApprove" [autoApprove]="autoApprove"
[answered]="!!denyReasons[getApprovalData(msg).executionId]"
(approvalAction)="approval($event)"> (approvalAction)="approval($event)">
</tb-ai-approval-card> </tb-ai-approval-card>
} @else if (msg.status === 'INCOMPLETE') { } @else if (msg.status === 'INCOMPLETE') {
@ -54,6 +55,11 @@
</div> </div>
} }
</div> </div>
@if (msg.from === 'APPROVAL' && denyReasonOf(msg); as reason) {
<div class="user">
<div class="msg">{{ reason }}</div>
</div>
}
} }
} }
@if (loading && !waitApproval) { @if (loading && !waitApproval) {

5
ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts

@ -21,6 +21,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
@Input() autoApprove = false; @Input() autoApprove = false;
@Input() scrollContainer: HTMLElement; @Input() scrollContainer: HTMLElement;
@Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage'; @Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage';
@Input() denyReasons: Record<string, string> = {};
@Output() approvalAction = new EventEmitter<ApprovalResult>(); @Output() approvalAction = new EventEmitter<ApprovalResult>();
waitApproval = false; waitApproval = false;
@ -52,6 +53,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
return msg.data; return msg.data;
} }
denyReasonOf(msg: ApprovalChatMessage): string | undefined {
return this.completedExecutions[msg.data.executionId]?.reason ?? this.denyReasons[msg.data.executionId];
}
getCompletedExecution(msg: ApprovalChatMessage): ToolExecutionResult | undefined { getCompletedExecution(msg: ApprovalChatMessage): ToolExecutionResult | undefined {
return this.completedExecutions[msg.data.executionId]; return this.completedExecutions[msg.data.executionId];
} }

12
ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html

@ -19,6 +19,12 @@
<span #chatName class="ai-chat-name" [matTooltip]="nameClipped() ? chat.title : ('ai-assistant.double-click-to-rename' | translate)" <span #chatName class="ai-chat-name" [matTooltip]="nameClipped() ? chat.title : ('ai-assistant.double-click-to-rename' | translate)"
matTooltipPosition="after" matTooltipPositionAtOrigin matTooltipClass="tb-ai-cursor-tooltip" matTooltipShowDelay="500" matTooltipPosition="after" matTooltipPositionAtOrigin matTooltipClass="tb-ai-cursor-tooltip" matTooltipShowDelay="500"
(mouseenter)="nameClipped.set(chatName.scrollWidth > chatName.clientWidth + 1)" (dblclick)="startRename()">{{ chat.title }}</span> (mouseenter)="nameClipped.set(chatName.scrollWidth > chatName.clientWidth + 1)" (dblclick)="startRename()">{{ chat.title }}</span>
@if (level(); as level) {
<span class="ai-chat-status" [class]="'ai-chat-status ' + level">
<span class="tb-ai-status-mark" [class]="'tb-ai-status-mark ' + level"></span>
<span>{{ ('ai-assistant.status-' + level) | translate }}</span>
</span>
}
} }
} @else { } @else {
<span class="ai-chat-name">{{ 'ai-assistant.new-chat' | translate }}</span> <span class="ai-chat-name">{{ 'ai-assistant.new-chat' | translate }}</span>
@ -52,6 +58,7 @@
[additionalStyles]="markdownStyles" [additionalStyles]="markdownStyles"
[scrollContainer]="chatArea" [scrollContainer]="chatArea"
initialScroll="bottom" initialScroll="bottom"
[denyReasons]="denyReasons()"
(approvalAction)="onApprovalAction($event)"> (approvalAction)="onApprovalAction($event)">
</tb-ai-chat-messages> </tb-ai-chat-messages>
} @else if (!chatId()) { } @else if (!chatId()) {
@ -65,11 +72,14 @@
<div class="ai-chat-composer"> <div class="ai-chat-composer">
<tb-ai-prompt-input <tb-ai-prompt-input
[placeholder]="placeholder()" [placeholder]="placeholder()"
[loading]="loading()" [loading]="loading() && !waitingApproval()"
[dropZone]="chatArea" [dropZone]="chatArea"
[showAutoApprove]="true" [showAutoApprove]="true"
[autoApprove]="autoApprove()" [autoApprove]="autoApprove()"
[autoApproveInChat]="!!chatId()" [autoApproveInChat]="!!chatId()"
[stoppable]="!!chatId()"
[stopping]="stopping()"
(stopped)="stop()"
(autoApproveChange)="setAutoApprove($event)" (autoApproveChange)="setAutoApprove($event)"
(messageSent)="sendMsgFromUser($event)"> (messageSent)="sendMsgFromUser($event)">
</tb-ai-prompt-input> </tb-ai-prompt-input>

24
ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss

@ -38,7 +38,7 @@
} }
.ai-chat-name { .ai-chat-name {
flex: 1 1 auto; flex: 0 1 auto;
min-width: 0; min-width: 0;
overflow: hidden; overflow: hidden;
white-space: nowrap; white-space: nowrap;
@ -51,6 +51,27 @@
font-size: var(--chat-line); font-size: var(--chat-line);
} }
.ai-chat-status {
flex: none;
display: inline-flex;
align-items: center;
gap: 6px;
font: 400 12.5px/20px var(--tb-font);
color: var(--tb-ink-54);
white-space: nowrap;
.tb-ai-status-mark {
width: 10px;
height: 10px;
&.running::before {
width: 8px;
height: 8px;
border-width: 1.5px;
}
}
}
.ai-chat-rename { .ai-chat-rename {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
@ -70,6 +91,7 @@
.ai-chat-actions { .ai-chat-actions {
flex: none; flex: none;
margin-left: auto;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 2px; gap: 2px;

86
ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts

@ -102,9 +102,28 @@ export class AiChatComponent implements OnInit, OnDestroy {
autoApprove = computed(() => this.chatId() ? this.panelService.isAutoApprove(this.chatId()) : this.newChatAutoApprove()); autoApprove = computed(() => this.chatId() ? this.panelService.isAutoApprove(this.chatId()) : this.newChatAutoApprove());
placeholder = computed(() => this.translate.instant(this.messages().length denyReasons = signal<Record<string, string>>({});
? 'ai-assistant.follow-up-prompt-placeholder'
: 'ai-assistant.prompt-placeholder')); stopping = signal<boolean>(false);
private answeredApprovals = signal<ReadonlySet<string>>(new Set());
waitingApproval = computed<ApprovalChatMessage | undefined>(() => {
if (this.autoApprove()) {
return undefined;
}
const completed = this.completedExecutions();
const answered = this.answeredApprovals();
return this.messages()
.filter((message): message is ApprovalChatMessage => message.from === 'APPROVAL')
.find(message => !completed[message.data.executionId] && !answered.has(message.data.executionId) && message.data.needsApproval);
});
placeholder = computed(() => this.translate.instant(this.waitingApproval()
? 'ai-assistant.deny-placeholder'
: this.messages().length
? 'ai-assistant.follow-up-prompt-placeholder'
: 'ai-assistant.prompt-placeholder'));
private aiChat = inject(AiChatService); private aiChat = inject(AiChatService);
private chats = inject(AiChatsService); private chats = inject(AiChatsService);
@ -130,6 +149,24 @@ export class AiChatComponent implements OnInit, OnDestroy {
untracked(() => this.show(chatId)); untracked(() => this.show(chatId));
}); });
level = computed(() => {
const chat = this.chat();
return chat ? this.chats.levelOf(chat) : null;
});
private openChatEffect = effect(onCleanup => {
const chatId = this.chatId();
untracked(() => this.chats.setOpen(chatId, true));
onCleanup(() => untracked(() => this.chats.setOpen(chatId, false)));
});
private waitingEffect = effect(onCleanup => {
const chatId = this.chatId();
const waiting = !!this.waitingApproval();
untracked(() => this.chats.setWaiting(chatId, waiting));
onCleanup(() => untracked(() => this.chats.setWaiting(chatId, false)));
});
private deletedChatEffect = effect(() => { private deletedChatEffect = effect(() => {
const chatId = this.chatId(); const chatId = this.chatId();
if (chatId && this.chats.loaded() && !this.chats.find(chatId)) { if (chatId && this.chats.loaded() && !this.chats.find(chatId)) {
@ -237,18 +274,44 @@ export class AiChatComponent implements OnInit, OnDestroy {
} }
} }
stop(): void {
const chatId = this.chatId();
if (!chatId || !this.loading() || this.stopping()) {
return;
}
this.stopping.set(true);
this.aiChat.stopChat(chatId, {ignoreLoading: true, ignoreErrors: true}).subscribe({
error: err => {
this.stopping.set(false);
this.showErrorMessage(err);
}
});
}
onApprovalAction(event: ApprovalResult): void { onApprovalAction(event: ApprovalResult): void {
const chatId = this.chatId(); const chatId = this.chatId();
if (event.autoApprove && chatId) { if (event.autoApprove && chatId) {
this.panelService.setAutoApprove(chatId, true); this.panelService.setAutoApprove(chatId, true);
} }
this.aiChat.resolveToolApproval( this.answeredApprovals.update(set => new Set(set).add(event.executionId));
{executionId: event.executionId, approved: event.approved}, if (event.reason) {
{ignoreLoading: true, ignoreErrors: true} this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason}));
).subscribe(); }
const result: ApprovalResult = {executionId: event.executionId, approved: event.approved};
if (event.reason) {
result.reason = event.reason;
}
this.aiChat.resolveToolApproval(result, {ignoreLoading: true, ignoreErrors: true}).subscribe();
} }
sendMsgFromUser(prompt: AiPromptMessage): void { sendMsgFromUser(prompt: AiPromptMessage): void {
const waiting = this.waitingApproval();
if (waiting) {
if (prompt.message.trim()) {
this.onApprovalAction({executionId: waiting.data.executionId, approved: false, reason: prompt.message.trim()});
}
return;
}
const userMessage: ChatMessage = prompt.resources.length const userMessage: ChatMessage = prompt.resources.length
? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()} ? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()}
: {from: 'USER', content: prompt.message, time: Date.now()}; : {from: 'USER', content: prompt.message, time: Date.now()};
@ -275,6 +338,8 @@ export class AiChatComponent implements OnInit, OnDestroy {
this.shownChatId = chatId; this.shownChatId = chatId;
this.messages.set([]); this.messages.set([]);
this.completedExecutions.set({}); this.completedExecutions.set({});
this.denyReasons.set({});
this.answeredApprovals.set(new Set());
if (chatId) { if (chatId) {
this.loadChat$.next(chatId); this.loadChat$.next(chatId);
} else { } else {
@ -381,6 +446,9 @@ export class AiChatComponent implements OnInit, OnDestroy {
this.affectedEntities.push(...event.data.affectedEntities); this.affectedEntities.push(...event.data.affectedEntities);
} }
break; break;
case 'turnStopped':
this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'INCOMPLETE', time: Date.now()}]);
break;
case 'chatTitleGenerated': case 'chatTitleGenerated':
if (this.chatId() && event.data.title) { if (this.chatId() && event.data.title) {
this.chats.setTitle(this.chatId(), event.data.title); this.chats.setTitle(this.chatId(), event.data.title);
@ -434,7 +502,11 @@ export class AiChatComponent implements OnInit, OnDestroy {
} }
private stopLoading(): void { private stopLoading(): void {
if (this.loading()) {
this.chats.refresh().subscribe({error: () => {}});
}
this.loading.set(false); this.loading.set(false);
this.stopping.set(false);
if (this.affectedEntities.length) { if (this.affectedEntities.length) {
this.panelService.emitUpdatedData(this.affectedEntities); this.panelService.emitUpdatedData(this.affectedEntities);
this.affectedEntities = []; this.affectedEntities = [];

40
ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html

@ -48,17 +48,28 @@
(paste)="onPaste($event)" (paste)="onPaste($event)"
(keydown)="onKeydown($event)"></textarea> (keydown)="onKeydown($event)"></textarea>
<span class="composer-send-slot"> <span class="composer-send-slot">
<button type="button" class="composer-send" @if (canStop) {
[class.fly]="flying()" <button type="button" class="composer-send composer-stop"
[disabled]="!canSend" [disabled]="stopping"
[attr.aria-label]="'ai-assistant.send' | translate" [attr.aria-label]="'ai-assistant.stop' | translate"
[tbAiTip]="sendTip" [tbAiTip]="stopTip"
tipClass="tip-mini" tipClass="tip-mini"
(click)="send()"> (click)="stop()">
<span class="return-glyph" aria-hidden="true"> <span class="stop-glyph" aria-hidden="true"></span>
<svg viewBox="0 0 24 24"><path d="M20 4v7a4 4 0 0 1-4 4H4" pathLength="1"/><polyline points="9 10 4 15 9 20" pathLength="1"/></svg> </button>
</span> } @else {
</button> <button type="button" class="composer-send"
[class.fly]="flying()"
[disabled]="!canSend"
[attr.aria-label]="'ai-assistant.send' | translate"
[tbAiTip]="sendTip"
tipClass="tip-mini"
(click)="send()">
<span class="return-glyph" aria-hidden="true">
<svg viewBox="0 0 24 24"><path d="M20 4v7a4 4 0 0 1-4 4H4" pathLength="1"/><polyline points="9 10 4 15 9 20" pathLength="1"/></svg>
</span>
</button>
}
</span> </span>
</div> </div>
<div class="composer-foot"> <div class="composer-foot">
@ -89,6 +100,13 @@
</div> </div>
</div> </div>
<ng-template #stopTip>
<div class="tip-keyrow">
<span>{{ 'ai-assistant.stop' | translate }}</span>
<span class="tip-caps"><kbd>Esc</kbd></span>
</div>
</ng-template>
<ng-template #sendTip> <ng-template #sendTip>
<div class="tip-keyrow"> <div class="tip-keyrow">
<span>{{ 'ai-assistant.send' | translate }}</span> <span>{{ 'ai-assistant.send' | translate }}</span>

14
ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss

@ -200,6 +200,20 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox=
display: inline-flex; display: inline-flex;
} }
.composer-stop {
&:disabled {
opacity: .6;
cursor: default;
}
.stop-glyph {
width: 10px;
height: 10px;
border-radius: 2px;
background: var(--ai-on-action);
}
}
.composer-send { .composer-send {
position: relative; position: relative;
display: inline-flex; display: inline-flex;

21
ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts

@ -83,6 +83,22 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr
@Output() autoApproveChange = new EventEmitter<boolean>(); @Output() autoApproveChange = new EventEmitter<boolean>();
@Input() stoppable = false;
@Input() stopping = false;
@Output() stopped = new EventEmitter<void>();
get canStop(): boolean {
return this.loading && this.stoppable;
}
stop(): void {
if (this.canStop && !this.stopping) {
this.stopped.emit();
}
}
@ViewChild('textarea') textarea!: ElementRef<HTMLTextAreaElement>; @ViewChild('textarea') textarea!: ElementRef<HTMLTextAreaElement>;
@ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>; @ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>;
@ -158,6 +174,11 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr
} }
onKeydown(event: KeyboardEvent): void { onKeydown(event: KeyboardEvent): void {
if (event.key === 'Escape' && this.canStop) {
event.preventDefault();
this.stop();
return;
}
if (event.key === 'Enter' && (!event.shiftKey || event.metaKey || event.ctrlKey)) { if (event.key === 'Enter' && (!event.shiftKey || event.metaKey || event.ctrlKey)) {
event.preventDefault(); event.preventDefault();
this.send(); this.send();

4
ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html

@ -58,8 +58,8 @@
<span class="ai-row-title" [matTooltip]="'ai-assistant.double-click-to-rename' | translate" matTooltipPosition="after" <span class="ai-row-title" [matTooltip]="'ai-assistant.double-click-to-rename' | translate" matTooltipPosition="after"
matTooltipPositionAtOrigin matTooltipClass="tb-ai-cursor-tooltip" matTooltipShowDelay="500" matTooltipPositionAtOrigin matTooltipClass="tb-ai-cursor-tooltip" matTooltipShowDelay="500"
(dblclick)="$event.stopPropagation(); startRename(chat)">{{ chat.title }}</span> (dblclick)="$event.stopPropagation(); startRename(chat)">{{ chat.title }}</span>
@if (aiChats.replying().has(chat.id)) { @if (aiChats.levelOf(chat); as level) {
<span class="tb-ai-status-mark running" [matTooltip]="'ai-assistant.in-progress' | translate" matTooltipPosition="above"></span> <span [class]="'tb-ai-status-mark ' + level" [matTooltip]="('ai-assistant.status-tip-' + level) | translate" matTooltipPosition="above"></span>
} }
<button type="button" class="ai-row-menu" [matMenuTriggerFor]="chatMenu" <button type="button" class="ai-row-menu" [matMenuTriggerFor]="chatMenu"
[matMenuTriggerData]="{chat: chat}" (click)="$event.stopPropagation()" [matMenuTriggerData]="{chat: chat}" (click)="$event.stopPropagation()"

16
ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts

@ -7,6 +7,7 @@ import {
ElementRef, ElementRef,
HostListener, HostListener,
inject, inject,
OnDestroy,
OnInit, OnInit,
signal, signal,
ViewChild ViewChild
@ -38,10 +39,11 @@ export interface AiChatsGroup {
'[class.rail-open]': 'railOpen()' '[class.rail-open]': 'railOpen()'
} }
}) })
export class AiAssistantComponent implements OnInit { export class AiAssistantComponent implements OnInit, OnDestroy {
private static readonly RAIL_OPEN_KEY = 'tbAiAssistantRailOpen'; private static readonly RAIL_OPEN_KEY = 'tbAiAssistantRailOpen';
private static readonly NARROW_WIDTH = 900; private static readonly NARROW_WIDTH = 900;
private static readonly REFRESH_MS = 20000;
@ViewChild(AiChatComponent) chat: AiChatComponent; @ViewChild(AiChatComponent) chat: AiChatComponent;
@ViewChild('searchInput') searchInput: ElementRef<HTMLInputElement>; @ViewChild('searchInput') searchInput: ElementRef<HTMLInputElement>;
@ -82,6 +84,8 @@ export class AiAssistantComponent implements OnInit {
const index = chat.pinned ? 0 : chat.createdTime >= today ? 1 : chat.createdTime >= today - DAY ? 2 : chat.createdTime >= today - WEEK ? 3 : 4; const index = chat.pinned ? 0 : chat.createdTime >= today ? 1 : chat.createdTime >= today - DAY ? 2 : chat.createdTime >= today - WEEK ? 3 : 4;
groups[index].chats.push(chat); groups[index].chats.push(chat);
} }
const needsFirst = (chat: ChatInfo) => this.aiChats.levelOf(chat) === 'needs' ? 0 : 1;
groups.forEach(group => group.chats.sort((a, b) => needsFirst(a) - needsFirst(b)));
return groups.filter(group => group.chats.length); return groups.filter(group => group.chats.length);
}); });
@ -104,6 +108,16 @@ export class AiAssistantComponent implements OnInit {
} }
}); });
private refreshTimer = setInterval(() => {
if (!document.hidden) {
this.aiChats.refresh().subscribe({error: () => {}});
}
}, AiAssistantComponent.REFRESH_MS);
ngOnDestroy(): void {
clearInterval(this.refreshTimer);
}
ngOnInit(): void { ngOnInit(): void {
this.aiChats.load().subscribe({ this.aiChats.load().subscribe({
next: chats => { next: chats => {

14
ui-ngx/src/app/shared/models/ai-chat.models.ts

@ -15,8 +15,13 @@ export interface ChatInfo extends ChatConfiguration {
id: string; id: string;
createdTime: number; createdTime: number;
pinned?: boolean; pinned?: boolean;
status?: ChatStatus;
} }
export type ChatStatus = 'RUNNING' | 'NEEDS_YOU';
export type ChatLevel = 'needs' | 'running';
export interface BaseChatEvent { export interface BaseChatEvent {
event: string; event: string;
} }
@ -70,6 +75,7 @@ export interface ToolExecutionResult extends BaseChatToolEventData {
message: string; message: string;
icon?: string; icon?: string;
affectedEntities?: Array<EntityId>; affectedEntities?: Array<EntityId>;
reason?: string;
} }
export interface ToolExecutionResultEvent extends BaseChatEvent { export interface ToolExecutionResultEvent extends BaseChatEvent {
@ -96,10 +102,16 @@ export interface TurnResumedEvent extends BaseChatEvent {
data: Record<string, never>; data: Record<string, never>;
} }
export interface TurnStoppedEvent extends BaseChatEvent {
event: 'turnStopped';
data: Record<string, never>;
}
export interface ApprovalResult { export interface ApprovalResult {
executionId: string; executionId: string;
approved: boolean; approved: boolean;
autoApprove?: boolean; autoApprove?: boolean;
reason?: string;
} }
export enum ToolApprovalResult { export enum ToolApprovalResult {
@ -109,7 +121,7 @@ export enum ToolApprovalResult {
} }
export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent
| TurnResumedEvent; | TurnResumedEvent | TurnStoppedEvent;
export enum AiAssistantViewType { export enum AiAssistantViewType {
DASHBOARD = 'DASHBOARD', DASHBOARD = 'DASHBOARD',

8
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -762,6 +762,14 @@
"double-click-to-rename": "Double-click to rename", "double-click-to-rename": "Double-click to rename",
"copy-answer": "Copy the answer", "copy-answer": "Copy the answer",
"copied": "Copied", "copied": "Copied",
"what-should-be-different": "What should be different?",
"deny-placeholder": "Or say what should be different…",
"status-needs": "Needs you",
"status-running": "Running",
"status-tip-needs": "An approval waits for you",
"status-tip-running": "In progress",
"stop": "Stop",
"stopped": "You stopped this reply. Nothing more was done.",
"auto-approve": "Auto-approve", "auto-approve": "Auto-approve",
"auto-approve-on": "On", "auto-approve-on": "On",
"auto-approve-off": "Off", "auto-approve-off": "Off",

15
ui-ngx/src/theme/ai-theme.scss

@ -286,6 +286,21 @@
display: block; display: block;
} }
&.needs::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--tb-caution);
}
&.error::before {
width: 6px;
height: 6px;
border-radius: 1px;
background: var(--tb-crit);
transform: rotate(45deg);
}
&.running::before { &.running::before {
width: 9px; width: 9px;
height: 9px; height: 9px;

Loading…
Cancel
Save