Browse Source

Fixed AI chat tooltips not showing and Generate dashboard with AI doing nothing on Home and the AI Assistant page

- AI chat tooltips keep Material's own show/hide animations with the scale held at 1, so they fade in at full size and are detached after hiding.
- Generate dashboard with AI always starts a new chat; a draft typed in the open chat comes back when that chat is opened again. Where the docked panel can't open (Home, the AI Assistant page), the prompt goes to a new chat on the AI Assistant page.
- Keyboard focus shows an AI tooltip at once, also the first time; the tooltip directives use the host object and module declarations.
- A new chat's name keeps periods and colons inside words (Sensor v1.2, 192.168.1.10) and underscores inside names.
- Alarm lists loaded through /api/alarm and /api/v2/alarms (the Alarms page and entity Alarms tabs) sort severity by priority too; the test also covers text search.
- Removed unused code and merged duplicate container queries.
pull/16882/head
Igor Kulikov 2 days ago
parent
commit
c5bc6bc17f
  1. 33
      dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java
  2. 21
      dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java
  3. 25
      ui-ngx/src/app/core/services/ai-assistant-panel.service.ts
  4. 73
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts
  5. 13
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  6. 8
      ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts
  7. 2
      ui-ngx/src/app/modules/home/components/ai/ai-text.ts
  8. 44
      ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts
  9. 8
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts
  10. 14
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts
  11. 35
      ui-ngx/src/theme/ai-theme.scss

33
dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java

@ -12,6 +12,8 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@ -145,6 +147,25 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
return findByIdAsync(tenantId, key);
}
private static final String SEVERITY_PROPERTY = "severity";
private static final String SEVERITY_RANK = "(case a.severity"
+ Arrays.stream(AlarmSeverity.values())
.map(severity -> " when " + AlarmSeverity.class.getName() + "." + severity.name() + " then " + severity.ordinal())
.collect(Collectors.joining())
+ " else " + AlarmSeverity.values().length + " end)";
private static Pageable toAlarmPageable(PageLink pageLink) {
Pageable pageable = DaoUtil.toPageable(pageLink);
if (pageable.getSort().getOrderFor(SEVERITY_PROPERTY) == null) {
return pageable;
}
List<Sort.Order> orders = pageable.getSort().stream()
.map(order -> SEVERITY_PROPERTY.equals(order.getProperty()) ? JpaSort.unsafe(order.getDirection(), SEVERITY_RANK).iterator().next() : order)
.toList();
return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(orders));
}
@Override
public PageData<AlarmInfo> findAlarms(TenantId tenantId, AlarmQuery query) {
log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getStatus(), query.getPageLink());
@ -164,7 +185,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink())
toAlarmPageable(query.getPageLink())
)
);
} else {
@ -179,7 +200,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink())
toAlarmPageable(query.getPageLink())
)
);
}
@ -201,7 +222,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink())
toAlarmPageable(query.getPageLink())
)
);
}
@ -230,7 +251,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink())
toAlarmPageable(query.getPageLink())
)
);
} else {
@ -247,7 +268,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink())
toAlarmPageable(query.getPageLink())
)
);
}
@ -273,7 +294,7 @@ public class JpaAlarmDao extends JpaAbstractDao<AlarmEntity, Alarm> implements A
asf.hasAckFilter() && asf.getAckFilter(),
DaoUtil.getId(query.getAssigneeId()),
query.getPageLink().getTextSearch(),
DaoUtil.toPageable(query.getPageLink())
toAlarmPageable(query.getPageLink())
)
);
}

21
dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java

@ -64,6 +64,7 @@ import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.exception.DataValidationException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@ -834,6 +835,26 @@ public class AlarmServiceTest extends AbstractServiceTest {
pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.DESC));
Assert.assertEquals(byPriority.reversed(), alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery)
.getData().stream().map(AlarmData::getId).toList());
pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC));
pageLink.setTextSearch("Severity");
Assert.assertEquals(byPriority, alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery)
.getData().stream().map(AlarmData::getId).toList());
Assert.assertEquals(byPriority, alarmService.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, toQuery(pageLink), List.of(device.getId()))
.getData().stream().map(AlarmData::getId).toList());
List<String> types = Arrays.stream(AlarmSeverity.values()).map(severity -> "Severity " + severity).toList();
for (SortOrder.Direction direction : SortOrder.Direction.values()) {
List<AlarmId> expected = direction == SortOrder.Direction.ASC ? byPriority : byPriority.reversed();
TimePageLink timePageLink = new TimePageLink(10, 0, null, new SortOrder("severity", direction), null, null);
Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder()
.affectedEntityId(device.getId()).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList());
Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder()
.typeList(types).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList());
Assert.assertEquals(expected, alarmService.findAlarms(tenantId, AlarmQuery.builder()
.affectedEntityId(device.getId()).pageLink(new TimePageLink(10, 0, "Severity", new SortOrder("severity", direction), null, null)).build())
.getData().stream().map(AlarmInfo::getId).toList());
}
}
private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) {

25
ui-ngx/src/app/core/services/ai-assistant-panel.service.ts

@ -84,6 +84,9 @@ export class AiAssistantPanelService implements OnDestroy {
).subscribe(event => {
const suppressed = AiAssistantPanelService.withoutPanel(event.urlAfterRedirects);
this._suppressed.set(suppressed);
if (suppressed && !AiAssistantPanelService.onAiPage(event.urlAfterRedirects)) {
this._composed.set(null);
}
const openHere = this._openOnArrival && !suppressed;
if (!suppressed) {
this._openOnArrival = false;
@ -128,6 +131,11 @@ export class AiAssistantPanelService implements OnDestroy {
this._lastChatIdByContext.size ? JSON.stringify(Object.fromEntries(this._lastChatIdByContext)) : null);
}
private static onAiPage(url: string): boolean {
const path = (url || '/').split(/[?#]/)[0];
return path === '/ai-assistant' || path.startsWith('/ai-assistant/');
}
private static withoutPanel(url: string): boolean {
const path = (url || '/').split(/[?#]/)[0];
return path === '/' || AiAssistantPanelService.WITHOUT_PANEL.some(page => path === page || path.startsWith(page + '/'));
@ -382,22 +390,19 @@ export class AiAssistantPanelService implements OnDestroy {
this._open.set(true);
}
private _composed = signal<{text: string; fresh: boolean} | null>(null);
private _composed = signal<string | null>(null);
readonly composed = this._composed.asReadonly();
compose(text: string): void {
if (this._suppressed()) {
return;
this._composed.set(text);
if (!this._suppressed()) {
this.openPanel();
} else if (!AiAssistantPanelService.onAiPage(this.router.url)) {
this.router.navigateByUrl('/ai-assistant');
}
this._composed.set({text, fresh: !this._open()});
this.openPanel();
}
composesFresh(): boolean {
return !!this._composed()?.fresh;
}
takeComposed(): {text: string; fresh: boolean} | null {
takeComposed(): string | null {
const composed = this._composed();
this._composed.set(null);
return composed;

73
ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts

@ -99,43 +99,50 @@ export class AiAssistantPanelComponent {
onCleanup(() => document.documentElement.classList.remove('tb-ai-docked'));
});
private wasOpen = false;
private openEffect = effect(() => {
if (this.panelService.open()) {
untracked(() => {
if (this.panelService.composesFresh()) {
this.chatId.set(undefined);
this.chats.load().subscribe();
return;
}
const carried = this.panelService.hasCarriedChat();
if (!carried) {
this.dropChatFromOtherContext();
}
this.chats.load().subscribe(() => {
if (carried) {
const chatId = this.panelService.takeCarriedChat();
if (chatId && this.chats.find(chatId)) {
this.chatId.set(chatId);
return;
}
}
this.selectLastChat();
});
});
}
const open = this.panelService.open();
const composed = this.panelService.composed();
untracked(() => {
const opened = open && !this.wasOpen;
this.wasOpen = open;
if (!open) {
return;
}
if (composed) {
this.startComposed(this.panelService.takeComposed(), opened);
} else if (opened) {
this.restoreChat();
}
});
});
private composeEffect = effect(() => {
if (this.panelService.composed() && this.panelService.open()) {
untracked(() => {
const composed = this.panelService.takeComposed();
if (composed.fresh) {
this.chatId.set(undefined);
}
setTimeout(() => this.chat?.composeText(composed.text), AiAssistantPanelComponent.COMPOSE_DELAY_MS);
});
private startComposed(text: string, opened: boolean): void {
this.chat?.keepDraft();
this.chatId.set(undefined);
if (opened) {
this.chats.load().subscribe();
}
});
setTimeout(() => this.chat?.composeText(text), AiAssistantPanelComponent.COMPOSE_DELAY_MS);
}
private restoreChat(): void {
const carried = this.panelService.hasCarriedChat();
if (!carried) {
this.dropChatFromOtherContext();
}
this.chats.load().subscribe(() => {
if (carried) {
const chatId = this.panelService.takeCarriedChat();
if (chatId && this.chats.find(chatId)) {
this.chatId.set(chatId);
return;
}
}
this.selectLastChat();
});
}
private contextSwitchEffect = effect(() => {
const key = this.panelService.contextKey();

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

@ -530,9 +530,16 @@ export class AiChatComponent implements OnInit, OnDestroy {
untracked(() => this.countNewTurns());
});
private keptDraft: {chatId: string; text: string} | null = null;
private chatIdEffect = effect(() => {
const chatId = this.chatId();
untracked(() => {
if (chatId && this.keptDraft?.chatId === chatId) {
const draft = this.keptDraft.text;
this.keptDraft = null;
setTimeout(() => this.promptInput?.setValue(draft));
}
if (this.fileChat !== chatId) {
this.shownFile.set(null);
this.fileOpen.set(false);
@ -635,6 +642,12 @@ export class AiChatComponent implements OnInit, OnDestroy {
setTimeout(() => this.focus());
}
keepDraft(): void {
const chatId = this.chatId();
const draft = this.promptInput?.message.value ?? '';
this.keptDraft = chatId && draft.trim() ? {chatId, text: draft} : null;
}
composeText(text: string): void {
this.promptInput?.setValue(text);
setTimeout(() => this.focus());

8
ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts

@ -22,13 +22,13 @@ import { AiTipIfCutDirective, AiTooltipChainDirective } from '@home/components/a
AiFadeInImageDirective,
AiSpinComponent,
AiSevMarkComponent,
AiNoTelemetryModalComponent
AiNoTelemetryModalComponent,
AiTooltipChainDirective,
AiTipIfCutDirective
],
imports: [
CommonModule,
SharedModule,
AiTooltipChainDirective,
AiTipIfCutDirective
SharedModule
],
exports: [
AiAssistantButtonComponent,

2
ui-ngx/src/app/modules/home/components/ai/ai-text.ts

@ -21,7 +21,7 @@ const CHAT_NAME_MAX = 44;
const CHAT_NAME_MIN_CUT = 20;
export function aiChatNameOf(prompt: string): string {
const first = prompt.replace(/[*_`#>]/g, '').trim().split(/[.:\n]/)[0].trim();
const first = prompt.replace(/[*`#>]|(?<![^\s])_+|_+(?![^\s])/g, '').trim().split(/[.!?](?:\s|$)|:\s|\n/)[0].trim();
if (first.length <= CHAT_NAME_MAX) {
return first;
}

44
ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Directive, ElementRef, HostListener, inject, Provider } from '@angular/core';
import { Directive, ElementRef, inject, Provider } from '@angular/core';
import { MAT_TOOLTIP_DEFAULT_OPTIONS, MatTooltip, MatTooltipDefaultOptions } from '@angular/material/tooltip';
export const AI_TOOLTIP_OPTIONS: MatTooltipDefaultOptions = {
@ -17,54 +17,66 @@ const NEXT_AT_ONCE_MS = 400;
let lastTipAt = 0;
function focusedByKeyboard(element: HTMLElement): boolean {
return element.matches(':focus-visible');
}
@Directive({
selector: '[matTooltip]',
standalone: true
standalone: false,
host: {
'(mouseenter)': 'onEnter()',
'(mouseleave)': 'onLeave()',
'(focus)': 'onFocus()'
}
})
export class AiTooltipChainDirective {
private tooltip = inject(MatTooltip, {self: true});
private host = inject<ElementRef<HTMLElement>>(ElementRef);
private inChat = inject(MAT_TOOLTIP_DEFAULT_OPTIONS, {optional: true}) === AI_TOOLTIP_OPTIONS;
@HostListener('mouseenter')
onEnter(): void {
if (this.inChat()) {
if (this.inChat) {
this.tooltip.showDelay = Date.now() - lastTipAt < NEXT_AT_ONCE_MS ? 0 : AI_TOOLTIP_OPTIONS.showDelay;
}
}
@HostListener('mouseleave')
onLeave(): void {
if (this.inChat() && this.tooltip._isTooltipVisible()) {
if (this.inChat && this.tooltip._isTooltipVisible()) {
lastTipAt = Date.now();
}
}
@HostListener('focus')
onFocus(): void {
if (this.inChat()) {
this.tooltip.showDelay = this.host.nativeElement.matches(':focus-visible') ? 0 : AI_TOOLTIP_OPTIONS.showDelay;
if (this.inChat && !this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) {
this.tooltip.show(0);
}
}
private inChat(): boolean {
return (this.tooltip.tooltipClass as string | string[]) === AI_TOOLTIP_OPTIONS.tooltipClass;
}
}
@Directive({
selector: '[aiTipIfCut]',
standalone: true
standalone: false,
host: {
'(mouseenter)': 'check()',
'(focus)': 'onFocus()'
}
})
export class AiTipIfCutDirective {
private tooltip = inject(MatTooltip, {self: true});
private host = inject<ElementRef<HTMLElement>>(ElementRef);
@HostListener('mouseenter')
@HostListener('focus')
check(): void {
const element = this.host.nativeElement.querySelector<HTMLElement>('.tb-ai-cut') ?? this.host.nativeElement;
this.tooltip.disabled = element.scrollWidth <= element.clientWidth + 1;
}
onFocus(): void {
this.check();
if (!this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) {
this.tooltip.show(0);
}
}
}

8
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts

@ -303,10 +303,6 @@ export class SolutionInstalledComponent {
return (severity ?? '').toLowerCase();
}
dashboardUser(row: AggregatedEntityResult): string {
return this.userName(row.primary?.additionalData?.userId);
}
canViewAs(row: AggregatedEntityResult): boolean {
return !!row.primary?.additionalData?.userId && row.status !== IssueStatus.ERROR;
}
@ -319,10 +315,6 @@ export class SolutionInstalledComponent {
this.authService.loginAsUser(userId).subscribe(() => {});
}
private userName(userId: string | undefined): string {
return userId ? this.findUser(userId)?.additionalData?.name ?? '' : '';
}
private findUser(userId: string): EntityResult | undefined {
return this.solution()?.metadata?.installResult?.entityResults?.[EntityType.USER]?.find(user => user.id?.id === userId);
}

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

@ -217,6 +217,18 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
}
});
private composeEffect = effect(() => {
const composed = this.panelService.composed();
if (composed && this.ready() && this.panelService.suppressed()) {
untracked(() => {
const text = this.panelService.takeComposed();
this.chat?.keepDraft();
this.newChat();
setTimeout(() => this.chat?.composeText(text));
});
}
});
private listEdgesEffect = effect(() => {
this.groups();
setTimeout(() => this.listEdges());
@ -267,7 +279,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
next: ([, chats]) => {
const params = this.route.snapshot.queryParamMap;
const handOff = this.panelService.takeHandOff();
const first = !handOff && !params.get('chatId') && !params.get('solutionId') && !chats.length;
const first = !handOff && !this.panelService.composed() && !params.get('chatId') && !params.get('solutionId') && !chats.length;
this.openFromUrl(params.get('chatId'), params.get('solutionId'), chats, first || params.get('getStarted') === 'true',
params.get('cli') === 'true');
this.ready.set(true);

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

@ -475,31 +475,22 @@
}
}
@keyframes tb-ai-tip-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes tb-ai-tip-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.mat-mdc-tooltip.tb-ai-tip {
opacity: 0;
transform: scale(1) !important;
&.mat-mdc-tooltip-show {
animation: tb-ai-tip-in 100ms ease-out forwards;
animation-duration: 100ms;
animation-timing-function: ease-out;
}
&.mat-mdc-tooltip-hide {
animation: tb-ai-tip-out 60ms ease-in forwards;
animation-duration: 60ms;
animation-timing-function: ease-in;
}
&._mat-animation-noopable.mat-mdc-tooltip-show {
opacity: 1;
}
}
@ -2263,9 +2254,7 @@ code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); }
width: 56px;
}
}
}
@container k-chat (max-width: 560px) {
.k-fields {
grid-template-columns: minmax(0, 1fr);
gap: 1px 0;
@ -4230,7 +4219,7 @@ cursor: pointer;
vertical-align: 1px;
}
.composer-ghost-end {
.composer-ghost-end {
white-space: nowrap;
}

Loading…
Cancel
Save