committed by
GitHub
487 changed files with 58062 additions and 14123 deletions
@ -0,0 +1,20 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.exception; |
|||
|
|||
import lombok.Getter; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
|
|||
@Getter |
|||
public class AiCreditsExceededException extends ThingsboardRuntimeException { |
|||
|
|||
public static final String TENANT_LIMIT = "TENANT"; |
|||
|
|||
private final String limitType; |
|||
|
|||
public AiCreditsExceededException(String limitType) { |
|||
super("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS); |
|||
this.limitType = limitType; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.exception; |
|||
|
|||
import io.swagger.v3.oas.annotations.media.Schema; |
|||
import org.springframework.http.HttpStatus; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
|
|||
@Schema |
|||
public class ThingsboardAiCreditsExceededResponse extends ThingsboardErrorResponse { |
|||
|
|||
private final String aiCreditsLimit; |
|||
|
|||
protected ThingsboardAiCreditsExceededResponse(String message, String aiCreditsLimit) { |
|||
super(message, ThingsboardErrorCode.TOO_MANY_REQUESTS, HttpStatus.TOO_MANY_REQUESTS); |
|||
this.aiCreditsLimit = aiCreditsLimit; |
|||
} |
|||
|
|||
public static ThingsboardAiCreditsExceededResponse of(String message, String aiCreditsLimit) { |
|||
return new ThingsboardAiCreditsExceededResponse(message, aiCreditsLimit); |
|||
} |
|||
|
|||
@Schema(description = "Which AI credits limit is used up: TENANT for the tenant's monthly limit", accessMode = Schema.AccessMode.READ_ONLY) |
|||
public String getAiCreditsLimit() { |
|||
return aiCreditsLimit; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,41 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.install.lts; |
|||
|
|||
import lombok.RequiredArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.notification.NotificationType; |
|||
import org.thingsboard.server.dao.notification.DefaultNotifications; |
|||
import org.thingsboard.server.dao.notification.NotificationSettingsService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
@Slf4j |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class V4_4_2_0Migration implements Migration { |
|||
|
|||
private final NotificationSettingsService notificationSettingsService; |
|||
private final DefaultNotifications defaultNotifications; |
|||
|
|||
@Override |
|||
public String getVersion() { |
|||
return "4.4.2.0"; |
|||
} |
|||
|
|||
@Override |
|||
public void apply() { |
|||
createAiCreditsLimitIncreaseRequestTemplate(); |
|||
} |
|||
|
|||
private void createAiCreditsLimitIncreaseRequestTemplate() { |
|||
if (notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) { |
|||
log.debug("The AI credits limit increase request notification template already exists"); |
|||
return; |
|||
} |
|||
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); |
|||
log.info("Created the AI credits limit increase request notification template"); |
|||
} |
|||
} |
|||
@ -0,0 +1,56 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.install.lts; |
|||
|
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.InjectMocks; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.notification.NotificationType; |
|||
import org.thingsboard.server.dao.notification.DefaultNotifications; |
|||
import org.thingsboard.server.dao.notification.NotificationSettingsService; |
|||
|
|||
import static org.junit.jupiter.api.Assertions.assertEquals; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
class V4_4_2_0MigrationTest { |
|||
|
|||
@Mock |
|||
private NotificationSettingsService notificationSettingsService; |
|||
@Mock |
|||
private DefaultNotifications defaultNotifications; |
|||
|
|||
@InjectMocks |
|||
private V4_4_2_0Migration migration; |
|||
|
|||
@Test |
|||
void hasItsVersion() { |
|||
assertEquals("4.4.2.0", migration.getVersion()); |
|||
} |
|||
|
|||
@Test |
|||
void createsAiCreditsLimitIncreaseRequestTemplateWhenMissing() { |
|||
when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) |
|||
.thenReturn(false); |
|||
|
|||
migration.apply(); |
|||
|
|||
verify(defaultNotifications).create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); |
|||
} |
|||
|
|||
@Test |
|||
void keepsAiCreditsLimitIncreaseRequestTemplateWhenPresent() { |
|||
when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) |
|||
.thenReturn(true); |
|||
|
|||
migration.apply(); |
|||
|
|||
verify(defaultNotifications, never()).create(any(), any()); |
|||
} |
|||
} |
|||
@ -0,0 +1,137 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.subscription; |
|||
|
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.ArgumentCaptor; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.thingsboard.server.common.data.alarm.Alarm; |
|||
import org.thingsboard.server.common.data.id.AlarmId; |
|||
import org.thingsboard.server.common.data.id.DeviceId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.page.PageData; |
|||
import org.thingsboard.server.common.data.query.AlarmData; |
|||
import org.thingsboard.server.common.data.query.AlarmDataPageLink; |
|||
import org.thingsboard.server.common.data.query.AlarmDataQuery; |
|||
import org.thingsboard.server.common.data.query.SingleEntityFilter; |
|||
import org.thingsboard.server.dao.alarm.AlarmService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.ws.WebSocketService; |
|||
import org.thingsboard.server.service.ws.WebSocketSessionRef; |
|||
import org.thingsboard.server.service.ws.telemetry.cmd.v2.AlarmDataUpdate; |
|||
import org.thingsboard.server.service.ws.telemetry.cmd.v2.CmdUpdate; |
|||
|
|||
import java.util.ArrayList; |
|||
import java.util.List; |
|||
import java.util.UUID; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.ArgumentMatchers.same; |
|||
import static org.mockito.BDDMockito.given; |
|||
import static org.mockito.BDDMockito.then; |
|||
import static org.mockito.Mockito.lenient; |
|||
import static org.mockito.Mockito.mock; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
public class TbAlarmDataSubCtxTest { |
|||
|
|||
private final String sessionId = "session"; |
|||
private final int cmdId = 7; |
|||
private final int maxEntitiesPerAlarmSubscription = 100; |
|||
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); |
|||
private final DeviceId deviceId = new DeviceId(UUID.randomUUID()); |
|||
|
|||
@Mock |
|||
private WebSocketService webSocketService; |
|||
@Mock |
|||
private AlarmService alarmService; |
|||
@Mock |
|||
private WebSocketSessionRef sessionRef; |
|||
@Mock |
|||
private SecurityUser securityUser; |
|||
|
|||
private TbAlarmDataSubCtx subCtx; |
|||
|
|||
@BeforeEach |
|||
public void setUp() { |
|||
lenient().when(sessionRef.getSessionId()).thenReturn(sessionId); |
|||
lenient().when(sessionRef.getSecurityCtx()).thenReturn(securityUser); |
|||
lenient().when(securityUser.getTenantId()).thenReturn(tenantId); |
|||
subCtx = new TbAlarmDataSubCtx("service", webSocketService, mock(), mock(), mock(), new SubscriptionServiceStatistics(), |
|||
alarmService, sessionRef, cmdId, maxEntitiesPerAlarmSubscription, 10); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldBeOwnerScoped_onlyWhenQueryHasNoEntityFilter() { |
|||
assertThat(subCtx.isOwnerScoped()).isFalse(); |
|||
|
|||
subCtx.setQuery(query(null, 0)); |
|||
assertThat(subCtx.isOwnerScoped()).isTrue(); |
|||
|
|||
subCtx.setQuery(query(new SingleEntityFilter(), 0)); |
|||
assertThat(subCtx.isOwnerScoped()).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldSendNothing_whenOwnerScopedRefreshReturnsTheSamePage() { |
|||
AlarmDataQuery query = query(null, 0); |
|||
subCtx.setQuery(query); |
|||
List<AlarmData> alarms = List.of(alarmData(), alarmData()); |
|||
subCtx.setAlarms(new PageData<>(alarms, 1, 2, false)); |
|||
given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))) |
|||
.willReturn(new PageData<>(new ArrayList<>(alarms), 1, 2, false)); |
|||
|
|||
subCtx.checkAndResetInvocationCounter(); |
|||
|
|||
then(alarmService).should().findAlarmDataByQuery(eq(tenantId), any(), any(), same(query)); |
|||
then(webSocketService).shouldHaveNoInteractions(); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldSendTheFreshPage_whenOwnerScopedRefreshReturnsAChangedPage() { |
|||
AlarmDataQuery query = query(null, 0); |
|||
subCtx.setQuery(query); |
|||
subCtx.setAlarms(new PageData<>(List.of(alarmData()), 1, 1, false)); |
|||
PageData<AlarmData> fresh = new PageData<>(List.of(alarmData(), alarmData()), 1, 2, false); |
|||
given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))).willReturn(fresh); |
|||
|
|||
subCtx.checkAndResetInvocationCounter(); |
|||
|
|||
ArgumentCaptor<CmdUpdate> updateCaptor = ArgumentCaptor.forClass(CmdUpdate.class); |
|||
then(webSocketService).should().sendUpdate(eq(sessionId), updateCaptor.capture()); |
|||
AlarmDataUpdate update = (AlarmDataUpdate) updateCaptor.getValue(); |
|||
assertThat(update.getCmdId()).isEqualTo(cmdId); |
|||
assertThat(update.getData()).isSameAs(fresh); |
|||
assertThat(update.getUpdate()).isNull(); |
|||
assertThat(update.getAllowedEntities()).isEqualTo(maxEntitiesPerAlarmSubscription); |
|||
assertThat(subCtx.getAlarms()).isSameAs(fresh); |
|||
assertThat(subCtx.getAlarmsMap()).hasSize(2); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldNotTouchAlarms_whenCleanupCalledWithoutTimeWindow() { |
|||
subCtx.setQuery(query(new SingleEntityFilter(), 0)); |
|||
|
|||
subCtx.cleanupOldAlarms(); |
|||
|
|||
then(alarmService).shouldHaveNoInteractions(); |
|||
then(webSocketService).shouldHaveNoInteractions(); |
|||
} |
|||
|
|||
private static AlarmDataQuery query(SingleEntityFilter entityFilter, long timeWindow) { |
|||
AlarmDataPageLink pageLink = new AlarmDataPageLink(10, 0, null, null, false, false, 0, 0, timeWindow, null, null, null, null); |
|||
return new AlarmDataQuery(entityFilter, pageLink, null, null, null, null); |
|||
} |
|||
|
|||
private AlarmData alarmData() { |
|||
Alarm alarm = new Alarm(new AlarmId(UUID.randomUUID())); |
|||
alarm.setOriginator(deviceId); |
|||
return new AlarmData(alarm, deviceId); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,40 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
|
|||
package org.thingsboard.server.common.data.notification.info; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
|
|||
import java.util.Map; |
|||
|
|||
import static org.thingsboard.server.common.data.util.CollectionsUtil.mapOf; |
|||
|
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
@Builder |
|||
public class AiCreditsLimitIncreaseRequestNotificationInfo implements NotificationInfo { |
|||
|
|||
private String userEmail; |
|||
private String tenantName; |
|||
private String limitDescription; |
|||
private String increaseLimitActionLabel; |
|||
private String increaseLimitLink; |
|||
private String baseUrl; |
|||
|
|||
@Override |
|||
public Map<String, String> getTemplateData() { |
|||
return mapOf( |
|||
"userEmail", userEmail, |
|||
"tenantName", tenantName, |
|||
"limitDescription", limitDescription, |
|||
"increaseLimitActionLabel", increaseLimitActionLabel, |
|||
"increaseLimitLink", increaseLimitLink, |
|||
"baseUrl", baseUrl |
|||
); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,21 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
export function readStored(key: string): string | null { |
|||
try { |
|||
return localStorage.getItem(key); |
|||
} catch { |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
export function writeStored(key: string, value: string | null): void { |
|||
try { |
|||
if (value === null) { |
|||
localStorage.removeItem(key); |
|||
} else { |
|||
localStorage.setItem(key, value); |
|||
} |
|||
} catch { |
|||
return; |
|||
} |
|||
} |
|||
@ -0,0 +1,36 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { inject, Injectable } from '@angular/core'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { UserPermissionsService } from '@core/http/user-permissions.service'; |
|||
import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; |
|||
import { EntityId } from '@shared/models/id/entity-id'; |
|||
import { HeaderActionDescriptor } from '@home/models/entity/entities-table-config.models'; |
|||
|
|||
@Injectable({ |
|||
providedIn: 'root' |
|||
}) |
|||
export class AiAssistantConfigService { |
|||
|
|||
private userPermissionsService = inject(UserPermissionsService); |
|||
private translate = inject(TranslateService); |
|||
|
|||
configureAction(onAction: ($event: MouseEvent) => void): HeaderActionDescriptor[] { |
|||
return this.userPermissionsService.isAiAvailable() ? [{ |
|||
name: this.translate.instant('ai-assistant.configure-with-ai'), |
|||
icon: 'mdi:creation', |
|||
isEnabled: () => true, |
|||
onAction |
|||
}] : []; |
|||
} |
|||
|
|||
tableConfig(listView: AiAssistantViewType, entityView?: AiAssistantViewType, listEntityId?: EntityId): AiAssistantPanelConfig | null { |
|||
if (!this.userPermissionsService.isAiAvailable()) { |
|||
return null; |
|||
} |
|||
return { |
|||
view: {listView, entityView, listEntityId}, |
|||
initialPromptPlaceholder: this.translate.instant('ai-assistant.welcome.placeholder') |
|||
}; |
|||
} |
|||
} |
|||
@ -0,0 +1,353 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { computed, DestroyRef, effect, inject, Injectable, Injector, signal, untracked, WritableSignal } from '@angular/core'; |
|||
import { interval, Observable, of } from 'rxjs'; |
|||
import { distinctUntilChanged, filter, map, skip, switchMap, tap } from 'rxjs/operators'; |
|||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; |
|||
import { Store } from '@ngrx/store'; |
|||
import { AppState } from '@core/core.state'; |
|||
import { selectAuthUser } from '@core/auth/auth.selectors'; |
|||
import { UserPermissionsService } from '@core/http/user-permissions.service'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { AiChatService } from '@core/http/ai-chat.service'; |
|||
import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; |
|||
import { DialogService } from '@core/services/dialog.service'; |
|||
import { AnswerFeedback, ChatConfiguration, ChatInfo, ChatLevel } from '@shared/models/ai-chat.models'; |
|||
|
|||
@Injectable({ providedIn: 'root' }) |
|||
export class AiChatsService { |
|||
|
|||
private aiChat = inject(AiChatService); |
|||
private panelService = inject(AiAssistantPanelService); |
|||
private dialog = inject(DialogService); |
|||
private translate = inject(TranslateService); |
|||
private destroyRef = inject(DestroyRef); |
|||
private injector = inject(Injector); |
|||
|
|||
private _chats = signal<ChatInfo[]>([]); |
|||
readonly chats = this._chats.asReadonly(); |
|||
|
|||
private _loaded = signal(false); |
|||
readonly loaded = this._loaded.asReadonly(); |
|||
|
|||
private _replying = signal<ReadonlySet<string>>(new Set()); |
|||
readonly replying = this._replying.asReadonly(); |
|||
|
|||
private _waiting = signal<ReadonlySet<string>>(new Set()); |
|||
|
|||
private _open = signal<ReadonlySet<string>>(new Set()); |
|||
|
|||
private _failed = signal<ReadonlyMap<string, string>>(new Map()); |
|||
|
|||
private static readonly STATUS_POLL_MS = 15000; |
|||
|
|||
private _statuses = signal<ChatInfo[]>([]); |
|||
|
|||
private _statusResolved = signal(false); |
|||
|
|||
readonly statusChats = computed(() => this._loaded() ? this._chats() : this._statuses()); |
|||
|
|||
readonly statusResolved = computed(() => this._loaded() || this._statusResolved()); |
|||
|
|||
private watching = false; |
|||
|
|||
private polling = false; |
|||
|
|||
private generation = 0; |
|||
|
|||
private store = inject(Store<AppState>); |
|||
|
|||
private userPermissions = inject(UserPermissionsService); |
|||
|
|||
private userWatch = this.store.select(selectAuthUser).pipe( |
|||
map(user => user?.userId ?? null), |
|||
distinctUntilChanged(), |
|||
skip(1), |
|||
takeUntilDestroyed(this.destroyRef) |
|||
).subscribe(userId => this.reset(userId)); |
|||
|
|||
private reset(userId: string | null): void { |
|||
this.generation++; |
|||
this.polling = false; |
|||
this.ensuring = false; |
|||
this._chats.set([]); |
|||
this._loaded.set(false); |
|||
this._replying.set(new Set()); |
|||
this._waiting.set(new Set()); |
|||
this._open.set(new Set()); |
|||
this._failed.set(new Map()); |
|||
this._statuses.set([]); |
|||
this._statusResolved.set(false); |
|||
if (userId && this.watching) { |
|||
this.pollStatus(); |
|||
} |
|||
} |
|||
|
|||
private aiAvailable(): boolean { |
|||
return this.userPermissions.isAiAvailable(); |
|||
} |
|||
|
|||
watchStatus(): void { |
|||
if (this.watching) { |
|||
return; |
|||
} |
|||
this.watching = true; |
|||
this.pollStatus(); |
|||
let wasOpen = untracked(this.panelService.open); |
|||
const panelWatch = effect(() => { |
|||
const open = this.panelService.open(); |
|||
if (wasOpen && !open) { |
|||
this.pollStatus(); |
|||
} |
|||
wasOpen = open; |
|||
}, {injector: this.injector}); |
|||
const poll = interval(AiChatsService.STATUS_POLL_MS).subscribe(() => { |
|||
if (!untracked(this.panelService.open) && document.visibilityState === 'visible' |
|||
&& untracked(this.statusChats).some(chat => this.levelOf(chat) === 'running')) { |
|||
this.pollStatus(); |
|||
} |
|||
}); |
|||
this.destroyRef.onDestroy(() => { |
|||
panelWatch.destroy(); |
|||
poll.unsubscribe(); |
|||
}); |
|||
} |
|||
|
|||
private pollStatus(): void { |
|||
if (this.polling || !this.aiAvailable()) { |
|||
return; |
|||
} |
|||
this.polling = true; |
|||
const generation = this.generation; |
|||
this.aiChat.listChatStatuses({ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
filter(() => generation === this.generation) |
|||
).subscribe({ |
|||
next: statuses => { |
|||
this.polling = false; |
|||
this._statuses.set(statuses); |
|||
this._statusResolved.set(true); |
|||
if (untracked(this._loaded)) { |
|||
const byId = new Map(statuses.map(chat => [chat.id, chat])); |
|||
this._chats.update(list => list.map(chat => { |
|||
const live = byId.get(chat.id); |
|||
return live?.status === chat.status && live?.statusReason === chat.statusReason && (!live || live.updatedTime === chat.updatedTime) |
|||
? chat : {...chat, status: live?.status, statusReason: live?.statusReason, updatedTime: live?.updatedTime ?? chat.updatedTime}; |
|||
})); |
|||
} |
|||
}, |
|||
error: () => { |
|||
if (generation === this.generation) { |
|||
this.polling = false; |
|||
this._statusResolved.set(true); |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
|
|||
levelOf(chat: ChatInfo): ChatLevel | null { |
|||
if (this._waiting().has(chat.id)) { |
|||
return 'needs'; |
|||
} |
|||
if (this._replying().has(chat.id)) { |
|||
return 'running'; |
|||
} |
|||
if (this._failed().has(chat.id)) { |
|||
return 'error'; |
|||
} |
|||
if (this._open().has(chat.id)) { |
|||
return chat.status === 'FAILED' ? 'error' : null; |
|||
} |
|||
return chat.status === 'NEEDS_YOU' ? 'needs' : chat.status === 'NO_DATA' ? 'nodata' : chat.status === 'RUNNING' ? 'running' : chat.status === 'FAILED' ? 'error' : null; |
|||
} |
|||
|
|||
needsAttention(chat: ChatInfo): boolean { |
|||
const level = this.levelOf(chat); |
|||
return level === 'needs' || level === 'error'; |
|||
} |
|||
|
|||
tipOf(chat: ChatInfo): string { |
|||
const level = this.levelOf(chat); |
|||
if (!level) { |
|||
return ''; |
|||
} |
|||
const reason = level === 'error' ? this._failed().get(chat.id) ?? chat.statusReason : undefined; |
|||
return reason || this.translate.instant('ai-assistant.status-tip-' + level); |
|||
} |
|||
|
|||
setFailed(chatId: string | undefined, reason: string): void { |
|||
if (chatId) { |
|||
this._failed.update(map => new Map(map).set(chatId, reason)); |
|||
} |
|||
} |
|||
|
|||
clearFailure(chatId: string | undefined): void { |
|||
if (!chatId) { |
|||
return; |
|||
} |
|||
if (untracked(this._failed).has(chatId)) { |
|||
this._failed.update(map => { |
|||
const next = new Map(map); |
|||
next.delete(chatId); |
|||
return next; |
|||
}); |
|||
} |
|||
if (untracked(this._chats).some(chat => chat.id === chatId && chat.status === 'FAILED')) { |
|||
this._chats.update(list => list.map(chat => chat.id === chatId && chat.status === 'FAILED' |
|||
? {...chat, status: undefined, statusReason: undefined} : chat)); |
|||
} |
|||
} |
|||
|
|||
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[]> { |
|||
const generation = this.generation; |
|||
return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(chats => { |
|||
if (generation === this.generation) { |
|||
this._chats.set(chats); |
|||
} |
|||
}) |
|||
); |
|||
} |
|||
|
|||
private ensuring = false; |
|||
|
|||
ensureLoaded(): void { |
|||
if (this._loaded() || this.ensuring) { |
|||
return; |
|||
} |
|||
this.ensuring = true; |
|||
const generation = this.generation; |
|||
const done = () => { |
|||
if (generation === this.generation) { |
|||
this.ensuring = false; |
|||
} |
|||
}; |
|||
this.load().subscribe({error: done, complete: done}); |
|||
} |
|||
|
|||
load(): Observable<ChatInfo[]> { |
|||
const generation = this.generation; |
|||
return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
filter(() => generation === this.generation), |
|||
tap({ |
|||
next: chats => { |
|||
this._chats.set(chats); |
|||
this._loaded.set(true); |
|||
this.moveStoredAutoApprove(chats); |
|||
}, |
|||
error: () => this._loaded.set(true) |
|||
}) |
|||
); |
|||
} |
|||
|
|||
find(chatId: string | undefined): ChatInfo | undefined { |
|||
return chatId ? this._chats().find(chat => chat.id === chatId) : undefined; |
|||
} |
|||
|
|||
create(title: string, autoApprove = false): Observable<ChatInfo> { |
|||
const request: ChatConfiguration = autoApprove ? {title, autoApprove} : {title}; |
|||
return this.aiChat.createChat(request, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
map(id => ({id, title, createdTime: Date.now(), autoApprove} as ChatInfo)), |
|||
tap(chat => { |
|||
this._chats.update(list => [chat, ...list]); |
|||
}) |
|||
); |
|||
} |
|||
|
|||
rename(chatId: string, title: string): Observable<void> { |
|||
return this.aiChat.updatedChat(chatId, {title}, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(() => this.setTitle(chatId, title)) |
|||
); |
|||
} |
|||
|
|||
sendFeedback(chatId: string, feedback: AnswerFeedback): Observable<void> { |
|||
return this.aiChat.updatedChat(chatId, {feedback}, {ignoreLoading: true}); |
|||
} |
|||
|
|||
isAutoApprove(chatId: string | undefined): boolean { |
|||
return !!this.find(chatId)?.autoApprove; |
|||
} |
|||
|
|||
setAutoApprove(chatId: string, autoApprove: boolean): Observable<void> { |
|||
const before = this.isAutoApprove(chatId); |
|||
this.applyAutoApprove(chatId, autoApprove); |
|||
return this.aiChat.updatedChat(chatId, {autoApprove}, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap({error: () => this.applyAutoApprove(chatId, before)}) |
|||
); |
|||
} |
|||
|
|||
private applyAutoApprove(chatId: string, autoApprove: boolean): void { |
|||
this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, autoApprove} : chat)); |
|||
} |
|||
|
|||
private moveStoredAutoApprove(chats: ChatInfo[]): void { |
|||
const stored = new Set(this.panelService.takeStoredAutoApproveChats()); |
|||
chats.filter(chat => stored.has(chat.id) && !chat.autoApprove) |
|||
.forEach(chat => this.setAutoApprove(chat.id, true).subscribe({error: () => {}})); |
|||
} |
|||
|
|||
setPinned(chatId: string, pinned: boolean): Observable<void> { |
|||
return this.aiChat.updatedChat(chatId, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(() => this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, pinned, pinnedTime: pinned ? Date.now() : undefined} : chat))) |
|||
); |
|||
} |
|||
|
|||
setTitle(chatId: string, title: string): void { |
|||
this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, title} : chat)); |
|||
} |
|||
|
|||
discard(chatId: string): Observable<void> { |
|||
return this.aiChat.deleteChat(chatId, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(() => { |
|||
this._chats.update(list => list.filter(c => c.id !== chatId)); |
|||
this.panelService.forgetChat(chatId); |
|||
}) |
|||
); |
|||
} |
|||
|
|||
confirmAndDelete(chat: ChatInfo): Observable<boolean> { |
|||
const title = chat.title || this.translate.instant('ai-assistant.new-chat'); |
|||
return this.dialog.confirm( |
|||
this.translate.instant('ai-assistant.delete-chat-title', {name: title}), |
|||
this.translate.instant('ai-assistant.delete-chat-text'), |
|||
this.translate.instant('action.no'), |
|||
this.translate.instant('ai-assistant.delete-chat-confirm') |
|||
).pipe( |
|||
switchMap(confirmed => confirmed |
|||
? this.aiChat.deleteChat(chat.id, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(() => { |
|||
this._chats.update(list => list.filter(c => c.id !== chat.id)); |
|||
this.panelService.forgetChat(chat.id); |
|||
}), |
|||
map(() => true) |
|||
) |
|||
: of(false)) |
|||
); |
|||
} |
|||
|
|||
setReplying(chatId: string | undefined, replying: boolean): void { |
|||
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; |
|||
} |
|||
target.update(set => { |
|||
const next = new Set(set); |
|||
if (on) { |
|||
next.add(chatId); |
|||
} else { |
|||
next.delete(chatId); |
|||
} |
|||
return next; |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,73 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { inject, Injectable, NgZone } from '@angular/core'; |
|||
import { MatDialog } from '@angular/material/dialog'; |
|||
|
|||
export interface AiSlashComposer { |
|||
field(): HTMLTextAreaElement | undefined; |
|||
focusEnd(): void; |
|||
} |
|||
|
|||
export interface AiSlashOpener { |
|||
canOpen(): boolean; |
|||
open(): void; |
|||
} |
|||
|
|||
@Injectable({ |
|||
providedIn: 'root' |
|||
}) |
|||
export class AiSlashService { |
|||
|
|||
private zone = inject(NgZone); |
|||
private dialog = inject(MatDialog); |
|||
private composers = new Set<AiSlashComposer>(); |
|||
private opener: AiSlashOpener | null = null; |
|||
private listening = false; |
|||
|
|||
addComposer(composer: AiSlashComposer): () => void { |
|||
this.listen(); |
|||
this.composers.add(composer); |
|||
return () => this.composers.delete(composer); |
|||
} |
|||
|
|||
setOpener(opener: AiSlashOpener): () => void { |
|||
this.listen(); |
|||
this.opener = opener; |
|||
return () => { |
|||
if (this.opener === opener) { |
|||
this.opener = null; |
|||
} |
|||
}; |
|||
} |
|||
|
|||
private listen(): void { |
|||
if (this.listening) { |
|||
return; |
|||
} |
|||
this.listening = true; |
|||
this.zone.runOutsideAngular(() => document.addEventListener('keydown', event => this.onKeydown(event))); |
|||
} |
|||
|
|||
private onKeydown(event: KeyboardEvent): void { |
|||
if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented || this.dialog.openDialogs.length |
|||
|| (event.target as HTMLElement)?.closest?.('input, textarea, select, [contenteditable]')) { |
|||
return; |
|||
} |
|||
const visible = Array.from(this.composers) |
|||
.filter(composer => { |
|||
const field = composer.field(); |
|||
return !!field?.offsetParent && !field.closest('tb-ai-assistant-panel:not(.open)'); |
|||
}) |
|||
.sort((a, b) => a.field().compareDocumentPosition(b.field()) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1); |
|||
const last = visible[visible.length - 1]; |
|||
if (last) { |
|||
event.preventDefault(); |
|||
this.zone.run(() => last.focusEnd()); |
|||
return; |
|||
} |
|||
if (this.opener?.canOpen()) { |
|||
event.preventDefault(); |
|||
this.zone.run(() => this.opener.open()); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,253 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { DestroyRef, inject, Injectable, signal } from '@angular/core'; |
|||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; |
|||
import { Store } from '@ngrx/store'; |
|||
import { AppState } from '@core/core.state'; |
|||
import { selectAuthUser } from '@core/auth/auth.selectors'; |
|||
import { EMPTY, Observable, of, Subscription, timer } from 'rxjs'; |
|||
import { catchError, distinctUntilChanged, filter, finalize, map, skip, switchMap, takeWhile, tap } from 'rxjs/operators'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { ChatLevel } from '@shared/models/ai-chat.models'; |
|||
import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; |
|||
import { DialogService } from '@core/services/dialog.service'; |
|||
import { |
|||
SolutionCreatorInfo, |
|||
SolutionInfo, |
|||
SolutionInstallProgress, |
|||
SolutionStep, |
|||
SolutionUpdateRequest |
|||
} from '@shared/models/solution-creator.models'; |
|||
|
|||
const SOLUTIONS_POLL_MS = 5000; |
|||
|
|||
@Injectable({providedIn: 'root'}) |
|||
export class AiSolutionsService { |
|||
|
|||
private following: Subscription | null = null; |
|||
|
|||
private _solutions = signal<SolutionInfo[]>([]); |
|||
readonly solutions = this._solutions.asReadonly(); |
|||
|
|||
private _loaded = signal(false); |
|||
readonly loaded = this._loaded.asReadonly(); |
|||
|
|||
private _running = signal<ReadonlySet<string>>(new Set()); |
|||
readonly running = this._running.asReadonly(); |
|||
private _failed = signal<ReadonlyMap<string, string>>(new Map()); |
|||
|
|||
private api = inject(SolutionsCreatorService); |
|||
private dialog = inject(DialogService); |
|||
private translate = inject(TranslateService); |
|||
|
|||
private generation = 0; |
|||
|
|||
private userWatch = inject(Store<AppState>).select(selectAuthUser).pipe( |
|||
map(user => user?.userId ?? null), |
|||
distinctUntilChanged(), |
|||
skip(1), |
|||
takeUntilDestroyed(inject(DestroyRef)) |
|||
).subscribe(() => this.reset()); |
|||
|
|||
private reset(): void { |
|||
this.generation++; |
|||
this.ensuring = false; |
|||
this.following?.unsubscribe(); |
|||
this.following = null; |
|||
this._solutions.set([]); |
|||
this._loaded.set(false); |
|||
this._running.set(new Set()); |
|||
this._failed.set(new Map()); |
|||
} |
|||
|
|||
private ensuring = false; |
|||
|
|||
ensureLoaded(): void { |
|||
if (this._loaded() || this.ensuring) { |
|||
return; |
|||
} |
|||
this.ensuring = true; |
|||
const generation = this.generation; |
|||
const done = () => { |
|||
if (generation === this.generation) { |
|||
this.ensuring = false; |
|||
} |
|||
}; |
|||
this.load().subscribe({error: done, complete: done}); |
|||
} |
|||
|
|||
load(): Observable<SolutionInfo[]> { |
|||
const generation = this.generation; |
|||
return this.api.getSolutions({ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
filter(() => generation === this.generation), |
|||
tap({ |
|||
next: solutions => { |
|||
this._solutions.set(solutions); |
|||
this._loaded.set(true); |
|||
this.followRunning(); |
|||
}, |
|||
error: () => this._loaded.set(true) |
|||
}) |
|||
); |
|||
} |
|||
|
|||
keepRunning(solutionId: string | undefined): void { |
|||
if (!solutionId) { |
|||
return; |
|||
} |
|||
this.update(solutionId, {status: 'RUNNING', statusReason: undefined}); |
|||
this.followRunning(); |
|||
} |
|||
|
|||
followRunning(): void { |
|||
if (this.following) { |
|||
return; |
|||
} |
|||
this.following = timer(SOLUTIONS_POLL_MS, SOLUTIONS_POLL_MS).pipe( |
|||
takeWhile(() => this._solutions().some(solution => solution.status === 'RUNNING' && !this._running().has(solution.id))), |
|||
switchMap(() => this.load().pipe(catchError(() => EMPTY))), |
|||
finalize(() => this.following = null) |
|||
).subscribe(); |
|||
} |
|||
|
|||
setRunning(solutionId: string | undefined, running: boolean): void { |
|||
if (!solutionId || this._running().has(solutionId) === running) { |
|||
return; |
|||
} |
|||
if (running) { |
|||
this.update(solutionId, {status: undefined, statusReason: undefined}); |
|||
} |
|||
this._running.update(set => { |
|||
const next = new Set(set); |
|||
if (running) { |
|||
next.add(solutionId); |
|||
} else { |
|||
next.delete(solutionId); |
|||
} |
|||
return next; |
|||
}); |
|||
} |
|||
|
|||
isRunning(solutionId: string): boolean { |
|||
return this._running().has(solutionId); |
|||
} |
|||
|
|||
setFailed(solutionId: string | undefined, reason: string | null): void { |
|||
if (!solutionId || this._failed().get(solutionId) === (reason ?? undefined)) { |
|||
return; |
|||
} |
|||
this._failed.update(map => { |
|||
const next = new Map(map); |
|||
if (reason) { |
|||
next.set(solutionId, reason); |
|||
} else { |
|||
next.delete(solutionId); |
|||
} |
|||
return next; |
|||
}); |
|||
} |
|||
|
|||
levelOf(solution: SolutionInfo, open = false): ChatLevel | null { |
|||
if (this._running().has(solution.id)) { |
|||
return 'running'; |
|||
} |
|||
if (this._failed().has(solution.id)) { |
|||
return 'error'; |
|||
} |
|||
if (open) { |
|||
return solution.status === 'FAILED' ? 'error' : null; |
|||
} |
|||
return solution.status === 'NEEDS_YOU' ? 'needs' : solution.status === 'RUNNING' ? 'running' : solution.status === 'FAILED' ? 'error' : null; |
|||
} |
|||
|
|||
tipOf(solution: SolutionInfo, open = false): string { |
|||
const level = this.levelOf(solution, open); |
|||
if (!level) { |
|||
return ''; |
|||
} |
|||
const reason = level === 'error' ? this._failed().get(solution.id) ?? solution.statusReason : undefined; |
|||
return reason || this.translate.instant('ai-assistant.status-tip-' + level); |
|||
} |
|||
|
|||
find(solutionId: string | undefined): SolutionInfo | undefined { |
|||
return solutionId ? this._solutions().find(solution => solution.id === solutionId) : undefined; |
|||
} |
|||
|
|||
titleOf(solution: SolutionInfo): string { |
|||
return solution.solutionTitle || this.translate.instant('solution-creator.new-solution'); |
|||
} |
|||
|
|||
upsert(info: SolutionCreatorInfo): void { |
|||
const solution: SolutionInfo = { |
|||
id: info.id, |
|||
createdTime: info.createdTime, |
|||
solutionTitle: info.data?.solutionTitle || info.data?.aiSolutionTitle || this.find(info.id)?.solutionTitle || '', |
|||
built: !!info.metadata?.built, |
|||
installed: !!info.metadata?.installed |
|||
}; |
|||
this._solutions.update(list => list.some(item => item.id === solution.id) |
|||
? list.map(item => item.id === solution.id ? {...item, ...solution, createdTime: item.createdTime ?? solution.createdTime} : item) |
|||
: [solution, ...list]); |
|||
} |
|||
|
|||
update(solutionId: string, fields: Partial<SolutionInfo>): void { |
|||
this._solutions.update(list => list.map(item => item.id === solutionId ? {...item, ...fields} : item)); |
|||
} |
|||
|
|||
rename(solution: SolutionInfo, title: string): Observable<SolutionCreatorInfo> { |
|||
return this.api.updateSolutionData(solution.id, 'solutionTitle', JSON.stringify(title), {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(() => this.update(solution.id, {solutionTitle: title})) |
|||
); |
|||
} |
|||
|
|||
setPinned(solution: SolutionInfo, pinned: boolean): Observable<void> { |
|||
return this.api.updateSolution(solution.id, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(() => this.update(solution.id, {pinned})) |
|||
); |
|||
} |
|||
|
|||
sendFeedback(solutionId: string, step: SolutionStep, feedback: SolutionUpdateRequest['feedback']): Observable<void> { |
|||
return this.api.updateSolution(solutionId, {step, feedback}, {ignoreLoading: true}); |
|||
} |
|||
|
|||
installProgress(solutionId: string): Observable<SolutionInstallProgress> { |
|||
return this.api.getInstallProgress(solutionId, {ignoreLoading: true, ignoreErrors: true}); |
|||
} |
|||
|
|||
confirmAndUninstall(solution: SolutionInfo): Observable<SolutionCreatorInfo | null> { |
|||
return this.dialog.confirm( |
|||
this.translate.instant('solution-creator.uninstall-solution-dialog-title', {name: this.titleOf(solution)}), |
|||
this.translate.instant('solution-creator.uninstall-solution-dialog-text'), |
|||
this.translate.instant('action.no'), |
|||
this.translate.instant('solution-creator.uninstall-solution-dialog-confirm') |
|||
).pipe( |
|||
switchMap(confirmed => confirmed |
|||
? this.api.uninstallSolution(solution.id, {ignoreErrors: true}).pipe( |
|||
tap(() => this.update(solution.id, {installed: false})) |
|||
) |
|||
: of(null)) |
|||
); |
|||
} |
|||
|
|||
discard(solutionId: string): Observable<void> { |
|||
return this.api.deleteSolution(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe( |
|||
tap(() => this._solutions.update(list => list.filter(item => item.id !== solutionId))) |
|||
); |
|||
} |
|||
|
|||
confirmAndDelete(solution: SolutionInfo): Observable<boolean> { |
|||
return this.dialog.confirm( |
|||
this.translate.instant('solution-creator.delete-solution-title', {name: this.titleOf(solution)}), |
|||
this.translate.instant('solution-creator.delete-solution-text'), |
|||
this.translate.instant('action.no'), |
|||
this.translate.instant('solution-creator.delete-solution-confirm') |
|||
).pipe( |
|||
switchMap(confirmed => confirmed |
|||
? this.api.deleteSolution(solution.id, {ignoreErrors: true}).pipe( |
|||
tap(() => this._solutions.update(list => list.filter(item => item.id !== solution.id))), |
|||
map(() => true) |
|||
) |
|||
: of(false)) |
|||
); |
|||
} |
|||
} |
|||
@ -0,0 +1,71 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { createNgModule, inject, Injectable, Injector, signal, untracked } from '@angular/core'; |
|||
import { Store } from '@ngrx/store'; |
|||
import { MatDialog } from '@angular/material/dialog'; |
|||
import { AppState } from '@core/core.state'; |
|||
import { getCurrentUserSettings } from '@core/auth/auth.selectors'; |
|||
import { UserPermissionsService } from '@core/http/user-permissions.service'; |
|||
import { AiTourStep } from '@shared/models/user-settings.models'; |
|||
import { AiChatsService } from '@core/services/ai-chats.service'; |
|||
|
|||
export interface TourLauncherApi { |
|||
welcome(): void; |
|||
assistantTour(): Promise<void>; |
|||
} |
|||
|
|||
const OFFER_DELAY_MS = 1200; |
|||
|
|||
@Injectable({providedIn: 'root'}) |
|||
export class TourService { |
|||
|
|||
readonly active = signal(false); |
|||
|
|||
private store = inject(Store<AppState>); |
|||
private injector = inject(Injector); |
|||
private userPermissions = inject(UserPermissionsService); |
|||
private chats = inject(AiChatsService); |
|||
private dialog = inject(MatDialog); |
|||
|
|||
private launcher: Promise<TourLauncherApi> | null = null; |
|||
|
|||
private offered = false; |
|||
|
|||
aiAvailable(): boolean { |
|||
return this.userPermissions.isAiAvailable(); |
|||
} |
|||
|
|||
offerWelcome(): void { |
|||
if (this.offered || !this.aiAvailable() || this.seen(AiTourStep.WELCOME)) { |
|||
return; |
|||
} |
|||
this.offered = true; |
|||
this.chats.watchStatus(); |
|||
setTimeout(() => { |
|||
if (this.active() || this.seen(AiTourStep.WELCOME) || this.dialog.openDialogs.length |
|||
|| untracked(this.chats.statusChats).some(chat => this.chats.levelOf(chat) === 'running')) { |
|||
this.offered = false; |
|||
return; |
|||
} |
|||
this.load().then(launcher => launcher.welcome()); |
|||
}, OFFER_DELAY_MS); |
|||
} |
|||
|
|||
playAssistantTour(): void { |
|||
if (this.aiAvailable() && !this.active()) { |
|||
this.load().then(launcher => launcher.assistantTour()); |
|||
} |
|||
} |
|||
|
|||
private seen(step: AiTourStep): boolean { |
|||
return !!getCurrentUserSettings(this.store)?.aiTour?.[step]; |
|||
} |
|||
|
|||
private load(): Promise<TourLauncherApi> { |
|||
if (!this.launcher) { |
|||
this.launcher = import('@modules/tour/tour.module').then(m => createNgModule(m.TourModule, this.injector).injector.get(m.TourLauncher)); |
|||
this.launcher.catch(() => this.launcher = null); |
|||
} |
|||
return this.launcher; |
|||
} |
|||
} |
|||
@ -0,0 +1,506 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
@mixin ai-code-blocks { |
|||
div.code-wrapper { |
|||
margin-top: 14px; |
|||
} |
|||
|
|||
.tb-codeblock { |
|||
position: relative; |
|||
min-width: 0; |
|||
font-size: 14px; |
|||
line-height: 20px; |
|||
border-radius: 10px; |
|||
background: var(--tb-code-bg); |
|||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); |
|||
|
|||
&.folded { |
|||
.tb-code { |
|||
display: none; |
|||
} |
|||
|
|||
.tb-codeblock-head { |
|||
border-bottom-color: transparent; |
|||
} |
|||
} |
|||
|
|||
&:not(.labeled) .tb-code { |
|||
padding-right: 44px; |
|||
} |
|||
|
|||
&.labeled .tb-code { |
|||
border-radius: 0 0 10px 10px; |
|||
} |
|||
|
|||
&:is([data-lang="python"], [data-lang="js"], [data-lang="c"], [data-lang="json"], [data-lang="yaml"]) .tb-code { |
|||
overflow-x: auto; |
|||
scrollbar-width: thin; |
|||
scrollbar-color: rgba(255, 255, 255, 0.2) transparent; |
|||
|
|||
&, code { |
|||
white-space: pre; |
|||
overflow-wrap: normal; |
|||
} |
|||
} |
|||
|
|||
&.wrap .tb-code { |
|||
&, code { |
|||
white-space: pre-wrap; |
|||
overflow-wrap: anywhere; |
|||
} |
|||
} |
|||
} |
|||
|
|||
.tb-codeblock-head { |
|||
display: flex; |
|||
align-items: center; |
|||
gap: 8px; |
|||
height: 36px; |
|||
box-sizing: border-box; |
|||
padding: 0 4px 0 12px; |
|||
border-bottom: 1px solid var(--tb-code-line); |
|||
font-family: var(--tb-font); |
|||
font-size: 12px; |
|||
line-height: 16px; |
|||
letter-spacing: .2px; |
|||
font-weight: 500; |
|||
color: var(--tb-code-head-fg); |
|||
|
|||
.mat-icon { |
|||
flex: none; |
|||
color: rgba(255, 255, 255, 0.42); |
|||
} |
|||
|
|||
> .tb-codeblock-label { |
|||
flex: 1; |
|||
min-width: 0; |
|||
overflow: hidden; |
|||
text-overflow: ellipsis; |
|||
white-space: nowrap; |
|||
font-size: 12px; |
|||
line-height: 16px; |
|||
letter-spacing: .2px; |
|||
color: var(--tb-code-head-fg); |
|||
} |
|||
} |
|||
|
|||
.tb-codetabs { |
|||
flex: 1; |
|||
display: flex; |
|||
align-self: stretch; |
|||
gap: 2px; |
|||
min-width: 0; |
|||
margin-left: -4px; |
|||
overflow-x: auto; |
|||
scrollbar-width: none; |
|||
} |
|||
|
|||
.tb-codetab { |
|||
position: relative; |
|||
height: 100%; |
|||
padding: 0 8px; |
|||
border: 0; |
|||
border-radius: 6px 6px 0 0; |
|||
background: none; |
|||
font: 500 12px/16px var(--tb-font); |
|||
letter-spacing: .2px; |
|||
white-space: nowrap; |
|||
color: rgba(255, 255, 255, 0.62); |
|||
cursor: pointer; |
|||
|
|||
&:hover { |
|||
color: rgba(255, 255, 255, 0.85); |
|||
} |
|||
|
|||
&[aria-selected="true"] { |
|||
color: #fff; |
|||
|
|||
&::after { |
|||
content: ''; |
|||
position: absolute; |
|||
left: 8px; |
|||
right: 8px; |
|||
bottom: -1px; |
|||
height: 2px; |
|||
border-radius: 2px 2px 0 0; |
|||
background: var(--hl-cmd); |
|||
} |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--tb-primary-300, #7fb5ff); |
|||
outline-offset: -4px; |
|||
} |
|||
} |
|||
|
|||
.tb-codefold { |
|||
flex: 1; |
|||
min-width: 0; |
|||
display: flex; |
|||
align-items: center; |
|||
gap: 8px; |
|||
height: 100%; |
|||
margin-left: -6px; |
|||
padding: 0 6px; |
|||
border: 0; |
|||
border-radius: 6px; |
|||
background: none; |
|||
color: inherit; |
|||
font: inherit; |
|||
letter-spacing: inherit; |
|||
text-align: left; |
|||
cursor: pointer; |
|||
|
|||
&:hover { |
|||
background: rgba(255, 255, 255, 0.05); |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--tb-primary-300); |
|||
outline-offset: -2px; |
|||
} |
|||
|
|||
.tb-codeblock-label { |
|||
flex: none; |
|||
overflow: hidden; |
|||
text-overflow: ellipsis; |
|||
white-space: nowrap; |
|||
} |
|||
|
|||
.tb-codeblock-size { |
|||
flex: none; |
|||
color: rgba(255, 255, 255, 0.55); |
|||
font-weight: 400; |
|||
white-space: nowrap; |
|||
} |
|||
|
|||
.tb-codefold-tg { |
|||
margin-left: auto; |
|||
transition: transform .2s ease; |
|||
} |
|||
} |
|||
|
|||
.tb-codeblock:not(.folded) .tb-codefold-tg { |
|||
transform: rotate(180deg); |
|||
} |
|||
|
|||
.tb-codecopy { |
|||
position: relative; |
|||
flex: none; |
|||
display: inline-flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
width: 28px; |
|||
height: 28px; |
|||
margin: 0; |
|||
padding: 0; |
|||
border: 0; |
|||
border-radius: 6px; |
|||
background: none; |
|||
color: rgba(255, 255, 255, 0.72); |
|||
font: inherit; |
|||
letter-spacing: normal; |
|||
cursor: pointer; |
|||
outline: none; |
|||
|
|||
&:hover { |
|||
background: rgba(255, 255, 255, 0.1); |
|||
color: #fff; |
|||
} |
|||
|
|||
&[aria-pressed="true"] { |
|||
background: rgba(255, 255, 255, 0.12); |
|||
color: #fff; |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--tb-primary-300); |
|||
outline-offset: 1px; |
|||
} |
|||
|
|||
&.floating { |
|||
position: absolute; |
|||
top: 8px; |
|||
right: 8px; |
|||
} |
|||
|
|||
&::after { |
|||
content: attr(data-tip); |
|||
position: absolute; |
|||
right: 0; |
|||
bottom: calc(100% + 6px); |
|||
padding: 3px 8px; |
|||
border-radius: 5px; |
|||
background: #10181d; |
|||
color: #fff; |
|||
font: 500 11px/16px var(--tb-font); |
|||
letter-spacing: .2px; |
|||
white-space: nowrap; |
|||
box-shadow: 0 2px 8px rgba(16, 24, 40, 0.3); |
|||
opacity: 0; |
|||
pointer-events: none; |
|||
transition: opacity .12s ease; |
|||
} |
|||
|
|||
&.copied::after { |
|||
content: attr(data-copied); |
|||
} |
|||
|
|||
&:hover::after, &:focus-visible::after, &.copied::after { |
|||
opacity: 1; |
|||
} |
|||
} |
|||
|
|||
.tb-codecopy > .mat-icon { |
|||
transition: opacity .15s ease, transform .15s cubic-bezier(.2, 0, 0, 1); |
|||
} |
|||
|
|||
.tb-codecopy > .mat-icon.tb-copy-ok { |
|||
position: absolute; |
|||
inset: 0; |
|||
margin: auto; |
|||
opacity: 0; |
|||
transform: scale(.5); |
|||
color: var(--ai-dark-accent); |
|||
} |
|||
|
|||
.tb-codecopy.copied > .mat-icon:not(.tb-copy-ok) { |
|||
opacity: 0; |
|||
transform: scale(.5); |
|||
} |
|||
|
|||
.tb-codecopy.copied > .mat-icon.tb-copy-ok { |
|||
opacity: 1; |
|||
transform: scale(1); |
|||
} |
|||
|
|||
.tb-codecopy.labelled { |
|||
width: auto; |
|||
gap: 5px; |
|||
padding: 0 8px 0 6px; |
|||
|
|||
&::after { |
|||
display: none; |
|||
} |
|||
} |
|||
|
|||
.tb-codeblock.value { |
|||
display: flex; |
|||
align-items: center; |
|||
gap: 8px; |
|||
min-height: 36px; |
|||
box-sizing: border-box; |
|||
padding: 0 4px 0 12px; |
|||
color: var(--tb-code-fg); |
|||
font: 500 12px/16px var(--tb-font); |
|||
letter-spacing: .2px; |
|||
|
|||
.tb-codeblock-label { |
|||
flex: none; |
|||
min-width: 84px; |
|||
overflow: hidden; |
|||
text-overflow: ellipsis; |
|||
white-space: nowrap; |
|||
color: rgba(255, 255, 255, 0.62); |
|||
} |
|||
|
|||
> code.tb-value { |
|||
flex: 1; |
|||
min-width: 0; |
|||
overflow: hidden; |
|||
text-overflow: ellipsis; |
|||
white-space: nowrap; |
|||
padding: 0; |
|||
border: 0; |
|||
border-radius: 0; |
|||
background: none; |
|||
font: 13px/20px var(--tb-mono); |
|||
letter-spacing: 0; |
|||
color: var(--tb-code-fg); |
|||
} |
|||
} |
|||
|
|||
.tb-cmdrow { |
|||
display: flex; |
|||
align-items: center; |
|||
gap: 10px; |
|||
min-height: 40px; |
|||
box-sizing: border-box; |
|||
padding: 6px 6px 6px 12px; |
|||
border-radius: 8px; |
|||
background: var(--tb-code-bg); |
|||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); |
|||
|
|||
.tb-cmd-p { |
|||
flex: none; |
|||
font: 500 13px/20px var(--tb-mono); |
|||
color: #7d8c96; |
|||
} |
|||
|
|||
> code.tb-cmd-t { |
|||
flex: 1; |
|||
min-width: 0; |
|||
overflow-x: auto; |
|||
scrollbar-width: none; |
|||
white-space: nowrap; |
|||
padding: 0; |
|||
border: 0; |
|||
border-radius: 0; |
|||
background: none; |
|||
font: 400 13px/20px var(--tb-mono); |
|||
color: #e8eef2; |
|||
-webkit-font-smoothing: antialiased; |
|||
} |
|||
|
|||
.tb-codecopy.tb-cmd-copy { |
|||
color: #b4bec6; |
|||
} |
|||
} |
|||
|
|||
pre.tb-code, pre.tb-code[class*=language-] { |
|||
margin: 0; |
|||
padding: 12px 16px 14px; |
|||
border: 0; |
|||
border-radius: 10px; |
|||
background: none; |
|||
box-shadow: none; |
|||
font-family: var(--tb-mono); |
|||
font-size: var(--chat-code); |
|||
line-height: var(--chat-code-lh); |
|||
color: var(--tb-code-fg); |
|||
white-space: pre-wrap; |
|||
overflow-wrap: anywhere; |
|||
-webkit-font-smoothing: antialiased; |
|||
|
|||
code, code[class*=language-] { |
|||
display: block; |
|||
white-space: inherit; |
|||
overflow-wrap: inherit; |
|||
padding: 0; |
|||
border: 0; |
|||
border-radius: 0; |
|||
background: none; |
|||
font: inherit; |
|||
color: inherit; |
|||
text-shadow: none; |
|||
} |
|||
} |
|||
|
|||
.tb-line { |
|||
display: block; |
|||
min-height: 20px; |
|||
|
|||
&.add, &.del { |
|||
margin: 0 -16px; |
|||
padding: 0 16px; |
|||
} |
|||
|
|||
&.add { |
|||
background: rgba(143, 227, 211, 0.12); |
|||
color: var(--hl-cmd); |
|||
} |
|||
|
|||
&.del { |
|||
background: rgba(255, 157, 146, 0.12); |
|||
color: var(--hl-err); |
|||
} |
|||
} |
|||
|
|||
.tb-codeblock.shell .tb-line { |
|||
padding-left: 24px; |
|||
text-indent: -24px; |
|||
|
|||
&.cont { |
|||
padding-left: 40px; |
|||
} |
|||
} |
|||
|
|||
pre.tb-code div.tb-cmd { |
|||
font: inherit; |
|||
letter-spacing: inherit; |
|||
color: inherit; |
|||
} |
|||
|
|||
.tb-cmd { |
|||
position: relative; |
|||
margin: 0 -8px; |
|||
padding: 2px 36px 2px 8px; |
|||
border-radius: 6px; |
|||
|
|||
& + .tb-cmd { |
|||
margin-top: 4px; |
|||
} |
|||
|
|||
&:hover, &:focus-within { |
|||
background: rgba(255, 255, 255, 0.05); |
|||
|
|||
.tb-cmdcopy { |
|||
opacity: 1; |
|||
} |
|||
} |
|||
} |
|||
|
|||
.tb-codecopy.tb-cmdcopy { |
|||
position: absolute; |
|||
top: 0; |
|||
right: 4px; |
|||
width: 24px; |
|||
height: 24px; |
|||
opacity: 0; |
|||
text-indent: 0; |
|||
|
|||
&.copied { |
|||
opacity: 1; |
|||
} |
|||
} |
|||
|
|||
@media (hover: none) { |
|||
.tb-codecopy.tb-cmdcopy { |
|||
opacity: .6; |
|||
} |
|||
} |
|||
|
|||
.hl-cmd, .hl-ok { |
|||
color: var(--hl-cmd); |
|||
} |
|||
|
|||
.hl-flag { |
|||
color: var(--hl-flag); |
|||
} |
|||
|
|||
.hl-str, .hl-warn { |
|||
color: var(--hl-str); |
|||
} |
|||
|
|||
.hl-num, .hl-kw { |
|||
color: var(--hl-num); |
|||
} |
|||
|
|||
.hl-key, .hl-var { |
|||
color: var(--hl-key); |
|||
} |
|||
|
|||
.hl-com, .hl-op { |
|||
color: var(--hl-com); |
|||
} |
|||
|
|||
.hl-err { |
|||
color: var(--hl-err); |
|||
} |
|||
|
|||
.hl-val { |
|||
color: var(--tb-code-fg); |
|||
} |
|||
|
|||
.hl-fn { |
|||
color: var(--hl-fn); |
|||
} |
|||
|
|||
.hl-bool { |
|||
color: var(--hl-bool); |
|||
} |
|||
|
|||
.hl-lvl { |
|||
color: var(--hl-lvl); |
|||
} |
|||
} |
|||
@ -0,0 +1,40 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
@mixin ai-icon-button($color: var(--tb-ink-54), $icon: 19px, $tap: true, $relative: true) { |
|||
@if $relative { |
|||
position: relative; |
|||
} |
|||
flex: none; |
|||
width: 32px; |
|||
height: 32px; |
|||
@if $tap { |
|||
min-width: var(--chat-tap); |
|||
min-height: var(--chat-tap); |
|||
} |
|||
padding: 0; |
|||
border: 0; |
|||
border-radius: 8px; |
|||
background: none; |
|||
color: $color; |
|||
display: inline-flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
cursor: pointer; |
|||
transition: background-color .15s ease, color .15s ease; |
|||
|
|||
&:hover { |
|||
background: rgba(0, 0, 0, 0.06); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--ai-focus); |
|||
outline-offset: 1px; |
|||
} |
|||
|
|||
.mat-icon { |
|||
font-size: $icon; |
|||
width: $icon; |
|||
height: $icon; |
|||
} |
|||
} |
|||
@ -0,0 +1,187 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
@if (hood()) { |
|||
<p class="k-hood"><mat-icon class="tb-mat-16" aria-hidden="true">code</mat-icon><span>{{ hood() }}</span></p> |
|||
} |
|||
@for (block of view().blocks; track $index) { |
|||
@switch (block.type) { |
|||
@case ('hub') { |
|||
<div class="k-detail-recs k-detail-hub tb-list-body" role="list"> |
|||
@for (rec of shown(hub(), 'hub'); track rec.key) { |
|||
<tb-ai-record role="listitem" [entityType]="rec.entityType" [alarmRule]="rec.alarmRule" [name]="rec.name" [badge]="rec.badge" [url]="rec.url" |
|||
[hub]="rec.hub"></tb-ai-record> |
|||
} |
|||
@if (hub().length > LIST_SHOWN) { |
|||
<ng-container *ngTemplateOutlet="moreToggle; context: {key: 'hub', count: hub().length - LIST_SHOWN}"></ng-container> |
|||
} |
|||
</div> |
|||
} |
|||
@case ('records') { |
|||
@if (block.label) { |
|||
<div class="k-detail-label">{{ say(block.label) }}</div> |
|||
} |
|||
<div class="k-detail-recs k-detail-list tb-list-body" role="list"> |
|||
@for (row of shown(block.rows, 'records' + $index); track $index) { |
|||
<div class="tb-rec line" [attr.data-pal]="kind(row.entityType).palette"> |
|||
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ kind(row.entityType).icon }}</mat-icon></span> |
|||
@if (recordUrl(row); as url) { |
|||
<a class="tb-rec-name" [routerLink]="url">{{ row.name }}</a> |
|||
} @else { |
|||
<span class="tb-rec-name">{{ row.name }}</span> |
|||
} |
|||
@if (row.meta) { |
|||
<span class="tb-rec-meta">{{ row.meta }}</span> |
|||
} |
|||
</div> |
|||
} |
|||
@if (block.rows.length > LIST_SHOWN) { |
|||
<ng-container *ngTemplateOutlet="moreToggle; context: {key: 'records' + $index, count: block.rows.length - LIST_SHOWN}"></ng-container> |
|||
} |
|||
</div> |
|||
@if (more(block); as rest) { |
|||
<div class="k-detail-more">{{ 'ai-assistant.detail.more' | translate:{count: rest} }}</div> |
|||
} |
|||
} |
|||
@case ('values') { |
|||
@if (block.label) { |
|||
<div class="k-detail-label">{{ say(block.label) }}</div> |
|||
} |
|||
<div class="k-tels"> |
|||
@for (row of block.rows; track $index) { |
|||
<span class="k-tel" [matTooltip]="row.time ? time(row.time) : ''" [matTooltipDisabled]="!row.time" matTooltipPosition="above"><code class="k-tel-key">{{ row.key }}</code><span class="k-tel-val">{{ row.value }}</span></span> |
|||
} |
|||
</div> |
|||
} |
|||
@case ('series') { |
|||
<div class="k-series"> |
|||
@for (row of block.rows; track row.key) { |
|||
<div class="k-series-row"> |
|||
<code class="k-tel-key">{{ row.key }}</code> |
|||
<svg class="k-series-spark" viewBox="0 0 96 20" preserveAspectRatio="none" aria-hidden="true"><path [attr.d]="row.path"></path></svg> |
|||
<span class="k-series-meta">{{ 'ai-assistant.detail.series' | translate:{points: row.points, min: number(row.min), max: number(row.max), last: number(row.last)} }}</span> |
|||
</div> |
|||
} |
|||
</div> |
|||
} |
|||
@case ('keys') { |
|||
@if (block.label) { |
|||
<div class="k-detail-label">{{ say(block.label) }}</div> |
|||
} |
|||
<div class="k-tels"> |
|||
@for (key of block.keys; track $index) { |
|||
<code class="k-tel-key">{{ key }}</code> |
|||
} |
|||
</div> |
|||
} |
|||
@case ('facts') { |
|||
<dl class="k-fields k-detail-facts"> |
|||
@for (fact of block.rows; track $index) { |
|||
<dt>{{ label(fact) }}</dt> |
|||
<dd [class.mono]="fact.mono"> |
|||
@if (fact.images; as pair) { |
|||
<span class="k-detail-images"> |
|||
@if (pair.current) { |
|||
<img tbAiFadeIn class="k-detail-img was" [src]="pair.current | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> |
|||
<mat-icon class="tb-mat-16" aria-hidden="true">arrow_forward</mat-icon> |
|||
} |
|||
@if (pair.value) { |
|||
<img tbAiFadeIn class="k-detail-img" [src]="pair.value | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> |
|||
} @else { |
|||
{{ 'ai-assistant.review.not-set' | translate }} |
|||
} |
|||
</span> |
|||
} @else if (fact.chip; as chip) { |
|||
<span class="k-fact-chip"> |
|||
@if (chip.image) { |
|||
<img [src]="chip.image" alt="" aria-hidden="true"> |
|||
} @else if (chip.icon) { |
|||
<mat-icon class="tb-mat-16" aria-hidden="true">{{ chip.icon }}</mat-icon> |
|||
} |
|||
{{ factValue(fact) }} |
|||
</span> |
|||
} @else if (factLink(fact); as url) { |
|||
<a [routerLink]="url">{{ factValue(fact) }}</a> |
|||
} @else if (fact.secret && !revealed().has(view().hood?.key + $index)) { |
|||
<span>{{ masked(factValue(fact)) }}</span> |
|||
<button type="button" class="k-reveal" (click)="reveal(view().hood?.key + $index)" [attr.aria-label]="'ai-assistant.detail.show' | translate" [matTooltip]="'ai-assistant.detail.show' | translate" matTooltipPosition="above"> |
|||
<mat-icon class="tb-mat-16" aria-hidden="true">visibility</mat-icon> |
|||
</button> |
|||
} @else { |
|||
{{ factValue(fact) }} |
|||
} |
|||
</dd> |
|||
} |
|||
</dl> |
|||
} |
|||
@case ('list') { |
|||
@if (block.label) { |
|||
<div class="k-detail-label">{{ say(block.label) }}</div> |
|||
} |
|||
<ul class="k-made"> |
|||
@for (row of block.rows; track $index) { |
|||
<li>{{ rowText(row) }}</li> |
|||
} |
|||
</ul> |
|||
} |
|||
@case ('commands') { |
|||
<div class="k-codetabs-slot" [attr.data-block]="$index"></div> |
|||
} |
|||
@case ('code') { |
|||
@if (block.title) { |
|||
<div class="k-detail-label">{{ ('ai-assistant.action.' + block.title) | translate }}</div> |
|||
} |
|||
<pre><code [class]="'language-' + (block.lang || block.label.toLowerCase())" [attr.data-label]="block.lang ? codeLabel(block.label) : null">{{ block.text }}</code></pre> |
|||
} |
|||
@case ('links') { |
|||
<div class="k-detail-links"> |
|||
@for (row of block.rows; track $index) { |
|||
<a class="k-detail-link" [href]="row.url" target="_blank" rel="noopener"> |
|||
<span class="k-detail-link-t">{{ row.title }}</span> |
|||
<span class="k-detail-link-from">{{ row.from }}</span> |
|||
@if (row.snippet) { |
|||
<span class="k-detail-link-s">{{ row.snippet }}</span> |
|||
} |
|||
</a> |
|||
} |
|||
</div> |
|||
} |
|||
@case ('markdown') { |
|||
<div class="k-detail-md"> |
|||
<tb-markdown usePlainMarkdown [highlight]="false" [data]="block.text"></tb-markdown> |
|||
</div> |
|||
} |
|||
@case ('images') { |
|||
<div class="k-detail-images"> |
|||
@for (image of block.rows; track image.url) { |
|||
<figure> |
|||
<img tbAiFadeIn [src]="image.url | image: {preview: true, ignoreLoadingImage: true} | async" [alt]="image.label ? say(image.label) : ''"> |
|||
@if (image.label) { |
|||
<figcaption>{{ say(image.label) }}</figcaption> |
|||
} |
|||
</figure> |
|||
} |
|||
</div> |
|||
} |
|||
@case ('note') { |
|||
<p class="k-detail-note">{{ say(block.text) }}</p> |
|||
} |
|||
@case ('text') { |
|||
<p class="k-detail-text">{{ block.text }}</p> |
|||
} |
|||
@case ('json') { |
|||
<div class="k-detail-label">{{ ('ai-assistant.action.' + block.label) | translate }}</div> |
|||
<pre class="k-detail-json"><code class="language-json">{{ block.text }}</code></pre> |
|||
} |
|||
} |
|||
} |
|||
|
|||
<ng-template #moreToggle let-key="key" let-count="count"> |
|||
<button type="button" class="tb-ai-more" [attr.aria-expanded]="isOpen(key)" (click)="toggleMore(key)"> |
|||
<mat-icon class="tb-mat-16" aria-hidden="true">{{ isOpen(key) ? 'expand_less' : 'expand_more' }}</mat-icon> |
|||
{{ isOpen(key) ? ('ai-assistant.summary.fewer' | translate) : ('ai-assistant.summary.more' | translate: {count}) }} |
|||
</button> |
|||
</ng-template> |
|||
@ -0,0 +1,271 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { afterRenderEffect, ChangeDetectionStrategy, Component, computed, DestroyRef, effect, ElementRef, inject, input, signal, untracked } from '@angular/core'; |
|||
import { ClipboardService } from 'ngx-clipboard'; |
|||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { forkJoin, of } from 'rxjs'; |
|||
import { catchError, map } from 'rxjs/operators'; |
|||
import { EntityType, baseDetailsPageByEntityType } from '@shared/models/entity-type.models'; |
|||
import { EntityService } from '@core/http/entity.service'; |
|||
import { IotHubApiService } from '@core/http/iot-hub-api.service'; |
|||
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; |
|||
import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; |
|||
import { AiRecordView } from '@home/components/ai/ai-record.models'; |
|||
import { getEntityDetailsPageURL } from '@core/utils'; |
|||
import { aiEntityKind, aiJoinWords, aiThingWord, isAiWordList } from '@home/components/ai/ai-action.models'; |
|||
import { codeTabsBlock, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; |
|||
import { readStored, writeStored } from '@core/local-storage/stored'; |
|||
import { |
|||
AiDetailBlock, |
|||
AiDetailEntity, |
|||
AiDetailFact, |
|||
AiDetailNames, |
|||
AiDetailRecord, |
|||
AiDetailText, |
|||
AiDetailView |
|||
} from '@home/components/ai/ai-action-detail.models'; |
|||
|
|||
const FETCHED = new Set<string>([ |
|||
EntityType.DEVICE, EntityType.ASSET, EntityType.DASHBOARD, EntityType.CUSTOMER, EntityType.USER, EntityType.DEVICE_PROFILE, |
|||
EntityType.ASSET_PROFILE, EntityType.ENTITY_VIEW, EntityType.EDGE, EntityType.RULE_CHAIN |
|||
]); |
|||
|
|||
const MAX_HUB = 50; |
|||
|
|||
const PROTOCOL_KEY = 'tb-ai-code-protocol'; |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-action-detail', |
|||
templateUrl: './ai-action-detail.component.html', |
|||
standalone: false, |
|||
changeDetection: ChangeDetectionStrategy.OnPush, |
|||
host: { |
|||
'class': 'k-detail' |
|||
} |
|||
}) |
|||
export class AiActionDetailComponent { |
|||
|
|||
view = input.required<AiDetailView>(); |
|||
|
|||
names = input<AiDetailNames>(new Map()); |
|||
|
|||
private translate = inject(TranslateService); |
|||
private entityService = inject(EntityService); |
|||
private iotHubApi = inject(IotHubApiService); |
|||
private recordLoader = inject(AiRecordLoaderService); |
|||
private destroyRef = inject(DestroyRef); |
|||
private host = inject(ElementRef<HTMLElement>); |
|||
private clipboard = inject(ClipboardService); |
|||
|
|||
private fetched = signal<ReadonlyMap<string, string>>(new Map()); |
|||
|
|||
private hubItems = signal<ReadonlyMap<string, MpItemVersionView>>(new Map()); |
|||
|
|||
revealed = signal<ReadonlySet<string>>(new Set()); |
|||
|
|||
readonly LIST_SHOWN = 8; |
|||
|
|||
private opened = signal<ReadonlySet<string>>(new Set()); |
|||
|
|||
isOpen(key: string): boolean { |
|||
return this.opened().has(key); |
|||
} |
|||
|
|||
toggleMore(key: string): void { |
|||
const next = new Set(this.opened()); |
|||
if (!next.delete(key)) { |
|||
next.add(key); |
|||
} |
|||
this.opened.set(next); |
|||
} |
|||
|
|||
shown<T>(rows: T[], key: string): T[] { |
|||
return this.isOpen(key) ? rows : rows.slice(0, this.LIST_SHOWN); |
|||
} |
|||
|
|||
hood = computed(() => { |
|||
const hood = this.view().hood; |
|||
this.fetched(); |
|||
return hood ? this.say(hood) : ''; |
|||
}); |
|||
|
|||
hub = computed<AiRecordView[]>(() => { |
|||
const block = this.view().blocks.find(item => item.type === 'hub'); |
|||
const items = this.hubItems(); |
|||
if (block?.type !== 'hub') { |
|||
return []; |
|||
} |
|||
return block.rows.map(row => { |
|||
const item = items.get(row.id); |
|||
if (item) { |
|||
const view = this.recordLoader.hubView(item); |
|||
return {...view, description: row.description ?? view.description}; |
|||
} |
|||
return { |
|||
key: `HUB:${row.id}`, entityType: 'SOLUTION_TEMPLATE', alarmRule: false, name: row.name, meta: '', |
|||
url: `/iot-hub/version/${row.id}`, description: row.description, |
|||
hub: {type: '', creator: row.vendor} |
|||
}; |
|||
}); |
|||
}); |
|||
|
|||
constructor() { |
|||
effect(() => { |
|||
const view = this.view(); |
|||
untracked(() => { |
|||
this.resolveNames(view); |
|||
this.loadHub(view); |
|||
}); |
|||
}); |
|||
afterRenderEffect(() => { |
|||
const view = this.view(); |
|||
const copy = (text: string) => this.clipboard.copyFromContent(text); |
|||
decorateCodeBlocks(this.host.nativeElement, this.translate, copy); |
|||
this.host.nativeElement.querySelectorAll('.k-codetabs-slot:empty').forEach((slot: HTMLElement) => { |
|||
const block = view.blocks[Number(slot.dataset.block)]; |
|||
if (block?.type === 'commands' && block.rows.length) { |
|||
const remembered = this.rememberedTab(); |
|||
const initial = Math.max(block.rows.findIndex(row => row.label === remembered), 0); |
|||
slot.append(codeTabsBlock(block.rows, 'bash', this.translate, copy, initial, tab => this.rememberTab(tab.label))); |
|||
} |
|||
}); |
|||
}); |
|||
} |
|||
|
|||
say(text: AiDetailText): string { |
|||
const params: Record<string, string | number> = {}; |
|||
for (const [key, value] of Object.entries(text.params ?? {})) { |
|||
params[key] = isAiWordList(value) ? aiJoinWords(this.translate, value) |
|||
: typeof value === 'object' ? this.entityText(value) : typeof value === 'string' && value.startsWith('ai-assistant.') ? this.translate.instant(value) : value; |
|||
} |
|||
return this.translate.instant(text.key, params); |
|||
} |
|||
|
|||
codeLabel(label: string): string { |
|||
return label.startsWith('ai-assistant.') ? this.translate.instant(label) : label; |
|||
} |
|||
|
|||
label(fact: AiDetailFact): string { |
|||
return fact.raw ? fact.label : this.translate.instant(fact.label); |
|||
} |
|||
|
|||
rowText(row: string | AiDetailText): string { |
|||
return typeof row === 'string' ? row : this.say(row); |
|||
} |
|||
|
|||
factValue(fact: AiDetailFact): string { |
|||
if (fact.say) { |
|||
return this.say(fact.say); |
|||
} |
|||
if (fact.entity) { |
|||
return this.nameOf(fact.entity) ?? fact.entity.id ?? '—'; |
|||
} |
|||
return fact.value && (fact.chip || fact.value.startsWith('ai-assistant.')) ? this.translate.instant(fact.value) : fact.value ?? ''; |
|||
} |
|||
|
|||
factLink(fact: AiDetailFact): string | null { |
|||
return fact.entity ? this.urlOf(fact.entity.id, fact.entity.entityType) : null; |
|||
} |
|||
|
|||
masked(value: string): string { |
|||
return value.length <= 6 ? '••••••' : '••••••••' + value.slice(-4); |
|||
} |
|||
|
|||
reveal(key: string): void { |
|||
this.revealed.update(set => new Set(set).add(key)); |
|||
} |
|||
|
|||
recordUrl(record: AiDetailRecord): string | null { |
|||
if (record.entityType === EntityType.ENTITY_GROUP) { |
|||
const base = record.id && record.groupType ? baseDetailsPageByEntityType.get(record.groupType as EntityType) : undefined; |
|||
return base ? `${base.replace(/\/all$/, '/groups')}/${record.id}` : null; |
|||
} |
|||
return this.urlOf(record.id, record.entityType); |
|||
} |
|||
|
|||
kind(entityType: string) { |
|||
return entityType === 'IMAGE' ? {icon: 'image', palette: 'view'} : aiEntityKind(entityType, entityType === 'ALARM_RULE'); |
|||
} |
|||
|
|||
more(block: AiDetailBlock): number { |
|||
return block.type === 'records' && block.total ? Math.max(block.total - block.rows.length, 0) : 0; |
|||
} |
|||
|
|||
time(ts: number): string { |
|||
return new Date(ts).toLocaleString([], {dateStyle: 'short', timeStyle: 'short'}); |
|||
} |
|||
|
|||
number(value: number): string { |
|||
return Number.isInteger(value) ? String(value) : String(Math.round(value * 100) / 100); |
|||
} |
|||
|
|||
private rememberedTab(): string | null { |
|||
return readStored(PROTOCOL_KEY); |
|||
} |
|||
|
|||
private rememberTab(label: string): void { |
|||
writeStored(PROTOCOL_KEY, label); |
|||
} |
|||
|
|||
private entityText(entity: AiDetailEntity): string { |
|||
const name = this.nameOf(entity); |
|||
if (name) { |
|||
return `'${name}'`; |
|||
} |
|||
return this.translate.instant('ai-assistant.detail.this', {what: this.typeWord(entity.entityType)}); |
|||
} |
|||
|
|||
private typeWord(entityType?: string): string { |
|||
return aiThingWord(this.translate, entityType, 'ai-assistant.detail.thing.entity'); |
|||
} |
|||
|
|||
private nameOf(entity: AiDetailEntity): string | undefined { |
|||
return entity.name ?? (entity.id ? this.names().get(entity.id)?.name ?? this.fetched().get(entity.id) : undefined); |
|||
} |
|||
|
|||
private urlOf(id?: string, entityType?: string): string | null { |
|||
return id && entityType && FETCHED.has(entityType) ? getEntityDetailsPageURL(id, entityType as EntityType) || null : null; |
|||
} |
|||
|
|||
private resolveNames(view: AiDetailView): void { |
|||
const wanted = new Map<string, string>(); |
|||
const want = (entity?: AiDetailEntity) => { |
|||
if (entity?.id && !entity.name && entity.entityType && FETCHED.has(entity.entityType) && !this.names().has(entity.id) && !this.fetched().has(entity.id)) { |
|||
wanted.set(entity.id, entity.entityType); |
|||
} |
|||
}; |
|||
Object.values(view.hood?.params ?? {}).forEach(value => typeof value === 'object' && !isAiWordList(value) && want(value)); |
|||
view.blocks.forEach(block => block.type === 'facts' && block.rows.forEach(fact => want(fact.entity))); |
|||
if (!wanted.size) { |
|||
return; |
|||
} |
|||
const config = {ignoreLoading: true, ignoreErrors: true}; |
|||
forkJoin([...wanted].map(([id, type]) => this.entityService.getEntity(type as EntityType, id, config).pipe( |
|||
map(found => [id, (found as {name?: string; title?: string})?.name ?? (found as {title?: string})?.title] as [string, string]), |
|||
catchError(() => of([id, undefined] as [string, string])) |
|||
))).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(found => { |
|||
const next = new Map(this.fetched()); |
|||
found.filter(([, name]) => !!name).forEach(([id, name]) => next.set(id, name)); |
|||
this.fetched.set(next); |
|||
}); |
|||
} |
|||
|
|||
private loadHub(view: AiDetailView): void { |
|||
const block = view.blocks.find(item => item.type === 'hub'); |
|||
if (block?.type !== 'hub' || !this.iotHubApi.baseUrl) { |
|||
return; |
|||
} |
|||
const ids = block.rows.slice(0, MAX_HUB).map(row => row.id).filter(id => !this.hubItems().has(id)); |
|||
if (!ids.length) { |
|||
return; |
|||
} |
|||
const config = {ignoreLoading: true, ignoreErrors: true}; |
|||
forkJoin(ids.map(id => this.iotHubApi.getVersionInfo(id, config).pipe(catchError(() => of(null))))).pipe(takeUntilDestroyed(this.destroyRef)) |
|||
.subscribe(items => { |
|||
const next = new Map(this.hubItems()); |
|||
items.filter(Boolean).forEach(item => next.set(item.id, item)); |
|||
this.hubItems.set(next); |
|||
}); |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,43 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
@switch (action().status) { |
|||
@case ('RUNNING') { |
|||
<tb-ai-work-line [words]="running()" [kind]="words().kind" [since]="action().startedAt"></tb-ai-work-line> |
|||
} |
|||
@case ('STOPPED') { |
|||
<tb-ai-work-line [words]="running()" kind="stop" [held]="true"></tb-ai-work-line> |
|||
} |
|||
@default { |
|||
<div class="out"> |
|||
<mat-icon class="mark" aria-hidden="true">{{ action().status === 'FAILURE' ? 'error_outline' : 'check' }}</mat-icon> |
|||
<span class="say">@if (outcomeChip(); as chip) {{{ chip.before }}@if (chip.link) {<a class="tb-chiplink" [routerLink]="chip.link"><code class="k-ent" [attr.data-pal]="chip.palette"><span class="mat-icon notranslate material-icons mat-ligature-font k-ent-ic" aria-hidden="true">{{ chip.icon }}</span>{{ chip.name }}<span class="mat-icon notranslate material-icons mat-ligature-font tb-chip-go" aria-hidden="true">chevron_right</span></code></a>} @else {<code class="k-ent" [attr.data-pal]="chip.palette"><span class="mat-icon notranslate material-icons mat-ligature-font k-ent-ic" aria-hidden="true">{{ chip.icon }}</span>{{ chip.name }}</code>}{{ chip.after }}} @else {{{ outcome() }}}</span> |
|||
@if (duration()) { |
|||
<span class="dur">{{ duration() }}</span> |
|||
} |
|||
</div> |
|||
@if (arrival()?.readings?.length) { |
|||
<div class="k-arrived"> |
|||
@for (reading of arrival().readings; track reading.key) { |
|||
<span class="k-reading"><code>{{ reading.key }}</code><b>{{ reading.value }}</b></span> |
|||
} |
|||
</div> |
|||
} |
|||
@if (listing(); as hub) { |
|||
<div class="k-recs k-out-recs"> |
|||
<tb-ai-record [entityType]="hub.entityType" [alarmRule]="hub.alarmRule" [name]="hub.name" [url]="hub.url" [hub]="hub.hub"></tb-ai-record> |
|||
</div> |
|||
} |
|||
@if (hasDetails()) { |
|||
<tb-ai-disclosure class="action-details" variant="details" [summary]="'ai-assistant.action.details' | translate" [key]="'action:' + action().executionId"> |
|||
@if (records().length) { |
|||
<tb-ai-run-summary class="records" [entities]="records()"></tb-ai-run-summary> |
|||
} |
|||
<tb-ai-action-detail [view]="detail()" [names]="names()"></tb-ai-action-detail> |
|||
</tb-ai-disclosure> |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,95 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
:host { |
|||
display: block; |
|||
font-family: var(--tb-mono); |
|||
font-size: 15px; |
|||
letter-spacing: var(--chat-text-ls); |
|||
} |
|||
|
|||
.out { |
|||
display: flex; |
|||
align-items: flex-start; |
|||
gap: 8px; |
|||
margin-top: 2px; |
|||
font-family: var(--tb-font); |
|||
font-size: var(--chat-line); |
|||
line-height: var(--chat-line-lh); |
|||
color: var(--tb-ink); |
|||
|
|||
.mark { |
|||
flex: none; |
|||
display: flex; |
|||
width: 20px; |
|||
height: 22px; |
|||
font-size: 22px; |
|||
line-height: 22px; |
|||
margin-top: 0; |
|||
color: var(--tb-ok); |
|||
} |
|||
|
|||
.say { |
|||
min-width: 0; |
|||
overflow-wrap: anywhere; |
|||
} |
|||
|
|||
.dur { |
|||
flex: none; |
|||
margin-left: auto; |
|||
font-family: var(--tb-mono); |
|||
font-size: 12px; |
|||
line-height: var(--chat-line-lh); |
|||
color: var(--k-faint); |
|||
white-space: nowrap; |
|||
} |
|||
} |
|||
|
|||
:host(.fail) .out .mark { |
|||
color: var(--tb-crit); |
|||
} |
|||
|
|||
.action-details { |
|||
display: block; |
|||
margin: 4px 0 0 28px; |
|||
|
|||
::ng-deep .tb-disc.tb-disc-details { |
|||
margin: 0; |
|||
|
|||
> summary { |
|||
color: var(--tb-ink-76); |
|||
} |
|||
} |
|||
|
|||
.records { |
|||
display: block; |
|||
margin: 8px 0 4px; |
|||
} |
|||
} |
|||
|
|||
.k-arrived { |
|||
display: flex; |
|||
flex-wrap: wrap; |
|||
gap: 4px 14px; |
|||
margin: 4px 0 0 28px; |
|||
font-size: var(--chat-line, 14px); |
|||
line-height: 22px; |
|||
|
|||
.k-reading { |
|||
display: inline-flex; |
|||
align-items: baseline; |
|||
gap: 6px; |
|||
} |
|||
|
|||
code { |
|||
padding: 0 6px; |
|||
border-radius: 5px; |
|||
background: rgba(0, 0, 0, 0.06); |
|||
font: 13px/18px var(--tb-mono); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
b { |
|||
font: 600 13px/18px var(--tb-mono); |
|||
color: var(--tb-ink); |
|||
} |
|||
} |
|||
@ -0,0 +1,185 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { ChangeDetectionStrategy, Component, computed, inject, input } from '@angular/core'; |
|||
import { toObservable, toSignal } from '@angular/core/rxjs-interop'; |
|||
import { of } from 'rxjs'; |
|||
import { catchError, distinctUntilChanged, switchMap } from 'rxjs/operators'; |
|||
import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; |
|||
import { AiRecordView } from '@home/components/ai/ai-record.models'; |
|||
import { EntityId } from '@shared/models/id/entity-id'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; |
|||
import { aiActionDetailView, AiDetailFact, AiDetailNames, aiParse } from '@home/components/ai/ai-action-detail.models'; |
|||
import { |
|||
AiAction, |
|||
aiConnectionCheckOf, |
|||
aiEntityKind, |
|||
aiActionDuration, |
|||
aiActionText, |
|||
aiActionWords |
|||
} from '@home/components/ai/ai-action.models'; |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-action-line', |
|||
templateUrl: './ai-action-line.component.html', |
|||
styleUrls: ['./ai-action-line.component.scss'], |
|||
standalone: false, |
|||
changeDetection: ChangeDetectionStrategy.OnPush, |
|||
host: { |
|||
'[class.run]': 'action().status === "RUNNING"', |
|||
'[class.fail]': 'action().status === "FAILURE"', |
|||
'[class.stopped]': 'action().status === "STOPPED"' |
|||
} |
|||
}) |
|||
export class AiActionLineComponent { |
|||
|
|||
action = input.required<AiAction>(); |
|||
|
|||
private translate = inject(TranslateService); |
|||
|
|||
private loader = inject(AiRecordLoaderService); |
|||
|
|||
hubVersionId = computed(() => { |
|||
const action = this.action(); |
|||
const id = action.tool === 'install_iot_hub_item' && action.status !== 'RUNNING' ? (action.arguments as {versionId?: unknown})?.versionId : null; |
|||
return typeof id === 'string' && id ? id : null; |
|||
}); |
|||
|
|||
private groupId = computed(() => { |
|||
const affected = this.action().status === 'SUCCESS' ? this.action().affectedEntities ?? [] : []; |
|||
const entity = this.action().tool === 'update_group_members' ? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) : affected[0]; |
|||
return entity?.entityType === EntityType.ENTITY_GROUP ? entity.id : null; |
|||
}); |
|||
|
|||
private groupView = toSignal(toObservable(this.groupId).pipe( |
|||
distinctUntilChanged(), |
|||
switchMap(id => id ? this.loader.entity({entityType: EntityType.ENTITY_GROUP, id} as EntityId).pipe(catchError(() => of(null))) : of(null)) |
|||
), {initialValue: null as AiRecordView | null}); |
|||
|
|||
listing = toSignal(toObservable(this.hubVersionId).pipe( |
|||
distinctUntilChanged(), |
|||
switchMap(id => id ? this.loader.hub(id).pipe(catchError(() => of(null))) : of(null)) |
|||
), {initialValue: null as AiRecordView | null}); |
|||
|
|||
words = computed(() => aiActionWords(this.action().tool, this.action().arguments)); |
|||
|
|||
more = input(0); |
|||
|
|||
outcomeText = input<string>(); |
|||
|
|||
autoApproved = input(false); |
|||
|
|||
linkEntity = input(true); |
|||
|
|||
outcomeChip = computed(() => { |
|||
const affected = this.action().affectedEntities ?? []; |
|||
const entity = this.action().tool === 'update_group_members' |
|||
? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) ?? affected[0] |
|||
: affected[0]; |
|||
const text = this.outcome(); |
|||
const match = entity && this.action().status === 'SUCCESS' ? /(?:^|\s)'(.{1,120}?)'(?=$|[\s.,:;!?)])/.exec(text) : null; |
|||
if (!match) { |
|||
return null; |
|||
} |
|||
const start = match.index + match[0].indexOf('\''); |
|||
const alarmRule = entity.entityType === EntityType.CALCULATED_FIELD && this.isAlarmRule(); |
|||
const kind = aiEntityKind(entity.entityType, alarmRule); |
|||
const base = alarmRule ? '/alarms/alarm-rules' : baseDetailsPageByEntityType.get(entity.entityType as EntityType); |
|||
const groupUrl = entity.entityType === EntityType.ENTITY_GROUP ? this.groupView()?.url : undefined; |
|||
return { |
|||
before: text.slice(0, start), |
|||
name: match[1], |
|||
after: text.slice(match.index + match[0].length), |
|||
icon: kind.icon, |
|||
palette: kind.palette, |
|||
link: this.linkEntity() ? (groupUrl ?? (base ? `${base}/${entity.id}` : null)) : null |
|||
}; |
|||
}); |
|||
|
|||
private isAlarmRule(): boolean { |
|||
const action = this.action(); |
|||
if (action.tool === 'save_alarm_rule') { |
|||
return true; |
|||
} |
|||
const result = aiParse(action.result) as {type?: unknown} | null; |
|||
return action.tool === 'install_iot_hub_item' && result?.type === 'ALARM_RULE'; |
|||
} |
|||
|
|||
private runWords = computed(() => aiActionText(this.translate, this.words(), 'run')); |
|||
|
|||
running = computed(() => this.more() > 0 |
|||
? this.translate.instant('ai-assistant.work.more', {words: this.runWords(), count: this.more()}) |
|||
: this.action().progress ? `${this.runWords()} · ${this.action().progress}` : this.runWords()); |
|||
|
|||
outcome = computed(() => { |
|||
const words = this.outcomeWords(); |
|||
return this.autoApproved() ? this.translate.instant('ai-assistant.action.auto-approved', {words}) : words; |
|||
}); |
|||
|
|||
arrival = computed(() => { |
|||
const action = this.action(); |
|||
const values = aiParse(action.arguments) as {waitSeconds?: unknown} | null; |
|||
if (action.tool !== 'check_connection' || action.status !== 'SUCCESS' || !(Number(values?.waitSeconds) > 0)) { |
|||
return null; |
|||
} |
|||
const check = aiConnectionCheckOf(action.result); |
|||
if (!check?.dataArriving) { |
|||
return null; |
|||
} |
|||
const time = new Date(action.startedAt + (action.durationMs ?? 0)).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); |
|||
if (check.gateway) { |
|||
return {text: this.translate.instant('ai-assistant.hand-over.gateway-connected', {name: check.name, time}), readings: []}; |
|||
} |
|||
return { |
|||
text: this.translate.instant('ai-assistant.hand-over.' + (!check.keyCount ? 'arrived-message' : check.keyCount === 1 ? 'arrived-key' : 'arrived-keys') |
|||
+ (check.name ? '-from' : ''), {name: check.name, time, count: check.keyCount}), |
|||
readings: check.readings |
|||
}; |
|||
}); |
|||
|
|||
private outcomeWords(): string { |
|||
const action = this.action(); |
|||
if (this.outcomeText()) { |
|||
return this.outcomeText(); |
|||
} |
|||
if (this.arrival()) { |
|||
return this.arrival().text; |
|||
} |
|||
if (action.status === 'FAILURE') { |
|||
return this.reason(action.result) ?? this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.runWords())}); |
|||
} |
|||
const words = this.words(); |
|||
return aiActionText(this.translate, words, 'done'); |
|||
} |
|||
|
|||
duration = computed(() => this.action().durationMs != null ? aiActionDuration(this.translate, this.action().durationMs) : ''); |
|||
|
|||
names = input<AiDetailNames>(new Map()); |
|||
|
|||
facts = input<AiDetailFact[]>([]); |
|||
|
|||
detail = computed(() => { |
|||
const view = aiActionDetailView(this.action(), this.names()); |
|||
const facts = this.facts(); |
|||
const reason = this.action().status === 'FAILURE' && this.outcomeText() && !view.blocks.length ? this.reason(this.action().result) : undefined; |
|||
const blocks = [...view.blocks, ...(reason ? [{type: 'text' as const, text: reason}] : []), ...(facts.length ? [{type: 'facts' as const, rows: facts}] : [])]; |
|||
return {...view, blocks}; |
|||
}); |
|||
|
|||
records = computed(() => this.action().status === 'SUCCESS' ? this.action().affectedEntities ?? [] : []); |
|||
|
|||
hasDetails = computed(() => !!this.detail().hood || !!this.detail().blocks.length || !!this.records().length); |
|||
|
|||
private reason(result?: string): string | undefined { |
|||
const text = result?.trim(); |
|||
if (!text || text.startsWith('{') || text.startsWith('[')) { |
|||
return undefined; |
|||
} |
|||
const line = text.split('\n')[0].trim(); |
|||
return line.length > 300 ? line.slice(0, 300) + '…' : line; |
|||
} |
|||
|
|||
private lowerFirst(words: string): string { |
|||
return words ? words.charAt(0).toLocaleLowerCase() + words.slice(1) : words; |
|||
} |
|||
} |
|||
@ -0,0 +1,817 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { AiQuestion } from '@shared/models/solution-creator.models'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
|
|||
export type { AiAction, AiActionStatus } from '@shared/models/ai-chat.models'; |
|||
|
|||
export type AiSpinKind = 'think' | 'gen' | 'install' | 'listen' | 'stop'; |
|||
|
|||
export interface AiActionWords { |
|||
key: string; |
|||
params?: Record<string, string | AiWordList>; |
|||
kind: AiSpinKind; |
|||
} |
|||
|
|||
export type AiWorkMoment = 'reading-request' | 'going-through-results' | 'applying-change' | 'reading-what-to-change'; |
|||
|
|||
export interface AiWorkState { |
|||
moment: AiWorkMoment; |
|||
since: number; |
|||
headline?: string; |
|||
} |
|||
const HIDDEN_TOOLS = new Set(['read_current_time']); |
|||
|
|||
const TOOL_WORDS: Record<string, string> = { |
|||
create_solution: 'create-solution', |
|||
install_solution: 'install-solution', |
|||
read_entity: 'read-entity', |
|||
read_timeseries_keys: 'read-telemetry-keys', |
|||
read_attributes: 'read-attributes', |
|||
discover_attribute_keys: 'read-attributes', |
|||
save_attributes: 'save-attributes', |
|||
delete_attributes: 'delete-attributes', |
|||
read_entity_relations: 'read-relations', |
|||
read_device_credentials: 'read-credentials', |
|||
save_device_credentials: 'save-credentials', |
|||
test_converter: 'test-converter', |
|||
read_converter_library: 'read-converter-library', |
|||
create_dashboard: 'create-dashboard', |
|||
update_dashboard: 'update-dashboard', |
|||
add_dashboard_state: 'add-dashboard-state', |
|||
update_dashboard_state: 'update-dashboard-state', |
|||
add_dashboard_entity_alias: 'add-entity-alias', |
|||
update_dashboard_entity_alias: 'update-entity-alias', |
|||
read_dashboard_entity_alias: 'read-entity-alias', |
|||
add_dashboard_filter: 'add-dashboard-filter', |
|||
update_dashboard_filter: 'update-dashboard-filter', |
|||
read_dashboard_filter: 'read-dashboard-filter', |
|||
read_dashboard_overview: 'read-dashboard', |
|||
update_dashboard_widget: 'update-widget', |
|||
place_dashboard_widgets: 'place-widgets', |
|||
read_dashboard_widget: 'read-widget', |
|||
read_dashboard_html_page: 'read-dashboard-page', |
|||
search_iot_hub_devices: 'search-iot-hub', |
|||
search_iot_hub: 'search-iot-hub', |
|||
read_iot_hub_item: 'read-iot-hub-item', |
|||
list_installed_iot_hub_items: 'list-installed-iot-hub-items', |
|||
install_iot_hub_item: 'install-iot-hub-item', |
|||
update_group_members: 'update-group-members', |
|||
change_owner: 'change-owner', |
|||
share_entity_group: 'share-group', |
|||
grant_role: 'grant-role', |
|||
read_access: 'read-access', |
|||
check_dashboard_access: 'check-dashboard-access', |
|||
read_transport_endpoints: 'read-connection-settings', |
|||
read_api_usage: 'read-api-usage', |
|||
read_audit_logs: 'read-audit-logs', |
|||
read_tasks: 'read-tasks', |
|||
save_image: 'save-image', |
|||
read_platform_settings: 'read-platform-settings', |
|||
save_relations: 'save-relations', |
|||
read_versions: 'read-versions', |
|||
read_gateway_status: 'read-gateway-status', |
|||
read_ota: 'read-ota', |
|||
read_edges: 'read-edges', |
|||
read_edge_events: 'read-edge-events', |
|||
read_edge_instructions: 'read-edge-instructions', |
|||
save_edge: 'save-edge', |
|||
assign_to_edge: 'assign-to-edge', |
|||
sync_edge: 'sync-edge', |
|||
read_rule_chain_templates: 'read-rule-chain-templates', |
|||
set_rule_chain_template: 'set-rule-chain-template', |
|||
read_agents: 'read-agents', |
|||
read_agent_instructions: 'read-agent-instructions', |
|||
save_agent: 'save-agent', |
|||
install_agent_application: 'install-agent-application', |
|||
run_agent_operation: 'run-agent-operation', |
|||
read_agent_profiles: 'read-agent-profiles', |
|||
save_agent_profile: 'save-agent-profile', |
|||
save_agent_app_profile: 'save-agent-app-profile', |
|||
run_agent_bulk_action: 'run-agent-bulk-action', |
|||
wait_agent_operation: 'wait-agent-operation', |
|||
read_white_labeling: 'read-white-labeling', |
|||
read_website_brand: 'read-website-brand', |
|||
save_white_labeling: 'save-white-labeling', |
|||
read_mail_templates: 'read-mail-templates', |
|||
save_mail_template: 'save-mail-template', |
|||
read_custom_translation: 'read-custom-translation', |
|||
save_custom_translation: 'save-custom-translation', |
|||
read_custom_menus: 'read-custom-menus', |
|||
read_security_settings: 'read-security-settings', |
|||
read_mobile_center: 'read-mobile-center', |
|||
save_mobile_app: 'save-mobile-app', |
|||
save_mobile_bundle: 'save-mobile-bundle', |
|||
save_mobile_qr_code: 'save-mobile-qr-code', |
|||
read_scheduler_events: 'read-scheduler-events', |
|||
save_scheduler_event: 'save-scheduler-event', |
|||
create_report_template: 'create-report-template', |
|||
update_report_template: 'update-report-template', |
|||
add_report_components: 'add-report-components', |
|||
update_report_component: 'update-report-component', |
|||
move_report_component: 'move-report-component', |
|||
save_report_entity_alias: 'save-report-alias', |
|||
save_report_filter: 'save-report-filter', |
|||
test_report_template: 'test-report-template', |
|||
read_reports: 'read-reports', |
|||
save_scheduled_report: 'save-scheduled-report', |
|||
generate_report: 'generate-report', |
|||
read_widgets: 'read-widgets', |
|||
read_widget: 'read-widget-type', |
|||
create_widget: 'create-widget', |
|||
build_widget: 'build-widget', |
|||
update_widget: 'update-widget-type', |
|||
check_widget: 'check-widget', |
|||
save_widgets_bundle: 'save-widgets-bundle', |
|||
read_scada_symbols: 'read-scada-symbols', |
|||
build_scada_symbol: 'build-scada-symbol', |
|||
create_scada_symbol: 'copy-scada-symbol', |
|||
update_scada_symbol: 'update-scada-symbol', |
|||
check_scada_symbol: 'check-scada-symbol', |
|||
create_scada_symbol_widget: 'create-scada-symbol-widget', |
|||
save_two_factor_settings: 'save-two-factor-settings', |
|||
save_oauth2_domain: 'save-oauth2-domain', |
|||
read_my_account: 'read-my-account', |
|||
save_my_profile: 'save-my-profile', |
|||
save_my_two_factor: 'save-my-two-factor', |
|||
update_api_key: 'update-api-key', |
|||
read_mail_server: 'read-mail-server', |
|||
save_mail_server: 'save-mail-server', |
|||
save_custom_menu: 'save-custom-menu', |
|||
save_ota_package: 'save-ota-package', |
|||
assign_ota_package: 'assign-ota-package', |
|||
save_platform_settings: 'save-platform-settings', |
|||
read_device_connect_commands: 'read-connection-settings', |
|||
search_web: 'search-web', |
|||
send_notification: 'send-notification', |
|||
read_notifications: 'read-notifications', |
|||
mark_notifications_read: 'mark-notifications-read', |
|||
save_notification_settings: 'save-notification-settings', |
|||
save_notification_preferences: 'save-notification-preferences' |
|||
}; |
|||
|
|||
const GENERATING_TOOLS: Record<string, string> = { |
|||
set_dashboard_html_page: 'lay-out-dashboard', |
|||
reprocess_calculated_field: 'recalculate-history', |
|||
commit_version: 'commit-version', |
|||
restore_version: 'restore-version', |
|||
research_device_connectivity: 'research-device' |
|||
}; |
|||
|
|||
const SAVED_KINDS: Record<string, [string, string]> = { |
|||
save_device: ['device', ''], |
|||
save_calculated_field: ['calculated-field', ''], |
|||
save_alarm_rule: ['alarm-rule', 'alarmRule'], |
|||
save_notification_target: ['notification-target', 'target'], |
|||
save_notification_template: ['notification-template', 'template'], |
|||
save_notification_rule: ['notification-rule', 'rule'], |
|||
save_customer: ['customer', ''], |
|||
save_user: ['user', ''], |
|||
save_entity_group: ['entity-group', ''], |
|||
save_role: ['role', ''], |
|||
save_entity_view: ['entity-view', ''], |
|||
save_asset: ['asset', ''], |
|||
save_asset_profile: ['asset-profile', ''], |
|||
save_device_profile: ['device-profile', ''], |
|||
save_converter: ['converter', ''], |
|||
save_integration: ['integration', ''], |
|||
save_secret: ['secret', ''], |
|||
save_ai_model: ['ai-model', ''], |
|||
save_resource: ['resource', ''] |
|||
}; |
|||
|
|||
const SEARCHED_TYPES: Record<string, string> = { |
|||
DEVICE: 'search-devices', |
|||
ASSET: 'search-assets', |
|||
DASHBOARD: 'search-dashboards', |
|||
CUSTOMER: 'search-customers', |
|||
USER: 'search-users' |
|||
}; |
|||
|
|||
const DELETED_TARGETS: Record<string, string> = { |
|||
CALCULATED_FIELD: 'delete-calculated-field', |
|||
ALARM_RULE: 'delete-alarm-rule', |
|||
NOTIFICATION_RULE: 'delete-notification-rule', |
|||
NOTIFICATION_TARGET: 'delete-notification-target', |
|||
NOTIFICATION_TEMPLATE: 'delete-notification-template', |
|||
NOTIFICATION_REQUEST: 'delete-sent-notification', |
|||
NOTIFICATION: 'delete-inbox-notification', |
|||
DASHBOARD: 'delete-dashboard', |
|||
DASHBOARD_WIDGET: 'delete-widget', |
|||
DASHBOARD_STATE: 'delete-dashboard-state', |
|||
DASHBOARD_ENTITY_ALIAS: 'delete-entity-alias', |
|||
DASHBOARD_FILTER: 'delete-dashboard-filter', |
|||
DEVICE: 'delete-device', |
|||
CUSTOMER: 'delete-customer', |
|||
USER: 'delete-user', |
|||
ENTITY_GROUP: 'delete-entity-group', |
|||
ROLE: 'delete-role', |
|||
GROUP_PERMISSION: 'delete-grant', |
|||
ALARM: 'delete-alarm', |
|||
ASSET: 'delete-asset', |
|||
OTA_PACKAGE: 'delete-ota-package', |
|||
EDGE: 'delete-edge', |
|||
AGENT: 'delete-agent', |
|||
AGENT_PROFILE: 'delete-agent-profile', |
|||
AGENT_APP_PROFILE: 'delete-agent-app-profile', |
|||
IMAGE: 'delete-image', |
|||
ENTITY_VIEW: 'delete-entity-view', |
|||
ASSET_PROFILE: 'delete-asset-profile', |
|||
DEVICE_PROFILE: 'delete-device-profile', |
|||
INTEGRATION: 'delete-integration', |
|||
CONVERTER: 'delete-converter', |
|||
SECRET: 'delete-secret', |
|||
AI_MODEL: 'delete-ai-model', |
|||
RESOURCE: 'delete-resource', |
|||
CUSTOM_MENU: 'delete-custom-menu', |
|||
MOBILE_APP: 'delete-mobile-app', |
|||
MOBILE_BUNDLE: 'delete-mobile-bundle', |
|||
SCHEDULER_EVENT: 'delete-scheduler-event', |
|||
REPORT_TEMPLATE: 'delete-report-template', |
|||
REPORT_COMPONENT: 'delete-report-component', |
|||
REPORT_ENTITY_ALIAS: 'delete-report-alias', |
|||
REPORT_FILTER: 'delete-report-filter', |
|||
REPORT: 'delete-report', |
|||
WIDGET_TYPE: 'delete-widget-type', |
|||
WIDGETS_BUNDLE: 'delete-widgets-bundle' |
|||
}; |
|||
|
|||
const ACTION_PREFIX = 'ai-assistant.action.'; |
|||
|
|||
export const isHiddenAiAction = (tool: string): boolean => HIDDEN_TOOLS.has(tool); |
|||
|
|||
export const SUGGEST_PROMPTS_TOOL = 'suggest_next_prompts'; |
|||
|
|||
export const ASK_USER_TOOL = 'ask_user'; |
|||
|
|||
export const PROPOSE_PLAN_TOOL = 'propose_plan'; |
|||
|
|||
export const CITE_SOURCES_TOOL = 'cite_sources'; |
|||
|
|||
export interface AiSource { |
|||
url: string; |
|||
title: string; |
|||
from: string; |
|||
quote?: string; |
|||
icon: string; |
|||
external: boolean; |
|||
} |
|||
|
|||
const humanize = (segment: string): string => { |
|||
const words = decodeURIComponent(segment).replace(/\.[a-z]+$/i, '').replace(/[-_]+/g, ' ').trim(); |
|||
return words ? words.charAt(0).toUpperCase() + words.slice(1) : ''; |
|||
}; |
|||
|
|||
export function aiSourcesOf(args: unknown): AiSource[] { |
|||
const sources = (args as {sources?: unknown})?.sources; |
|||
if (!Array.isArray(sources)) { |
|||
return []; |
|||
} |
|||
return sources.flatMap(source => { |
|||
if (typeof source?.url !== 'string' || typeof source?.title !== 'string') { |
|||
return []; |
|||
} |
|||
let url: URL; |
|||
try { |
|||
url = new URL(source.url); |
|||
} catch { |
|||
return []; |
|||
} |
|||
if (url.protocol !== 'https:' && url.protocol !== 'http:') { |
|||
return []; |
|||
} |
|||
const host = url.hostname.replace(/^www\./, ''); |
|||
const product = host === 'thingsboard.io' || host.endsWith('.thingsboard.io') || host.endsWith('thingsboard.cloud'); |
|||
const path = url.pathname.split('/').filter(segment => segment.length > 2).slice(0, 2).map(humanize).filter(Boolean); |
|||
return [{ |
|||
url: url.href, |
|||
title: source.title.trim(), |
|||
from: [host, ...path].join(' › '), |
|||
quote: typeof source.quote === 'string' && source.quote.trim() ? source.quote.trim() : undefined, |
|||
icon: !product ? 'public' : /pricing/i.test(url.pathname) ? 'sell' : 'menu_book', |
|||
external: !product |
|||
}]; |
|||
}).slice(0, 3); |
|||
} |
|||
|
|||
export const UPDATE_PLAN_TOOL = 'update_plan'; |
|||
|
|||
export const HAND_OVER_TOOL = 'hand_over'; |
|||
|
|||
export const CHECK_CONNECTION_TOOL = 'check_connection'; |
|||
|
|||
const KIT_CARD_TOOLS = new Set([SUGGEST_PROMPTS_TOOL, ASK_USER_TOOL, PROPOSE_PLAN_TOOL, UPDATE_PLAN_TOOL, 'write_file', 'create_file', CITE_SOURCES_TOOL, 'show_records', |
|||
HAND_OVER_TOOL]); |
|||
|
|||
export interface AiHandOverValue { |
|||
label: string; |
|||
value: string; |
|||
secret: boolean; |
|||
icon: string; |
|||
} |
|||
|
|||
export interface AiHandOverStep { |
|||
title: string; |
|||
detail?: string; |
|||
markdown?: string; |
|||
values: AiHandOverValue[]; |
|||
file?: string; |
|||
done: boolean; |
|||
} |
|||
|
|||
export interface AiHandOverOption { |
|||
id: string; |
|||
label: string; |
|||
icon?: string; |
|||
text: string; |
|||
steps?: AiHandOverStep[]; |
|||
} |
|||
|
|||
export interface AiHandOver { |
|||
title: string; |
|||
text?: string; |
|||
choice?: {question: string; icon: string; value: string; options: AiHandOverOption[]}; |
|||
steps: AiHandOverStep[]; |
|||
waitFor?: 'message' | 'uplink' | 'gateway'; |
|||
intervalSeconds?: number; |
|||
quiet?: string; |
|||
test?: AiHandOverTest; |
|||
paste?: {label: string; icon: string; intro: string}; |
|||
} |
|||
|
|||
export interface AiHandOverTest { |
|||
hint?: string; |
|||
commands: {os: 'macos' | 'windows' | 'linux'; command: string}[]; |
|||
outcomes: {output: string; meaning: string; ok: boolean}[]; |
|||
sample?: Record<string, unknown>; |
|||
accessToken?: string; |
|||
} |
|||
|
|||
function handOverTestOf(value: any): AiHandOverTest | undefined { |
|||
const commands = (Array.isArray(value?.commands) ? value.commands : []) |
|||
.filter(item => ['macos', 'windows', 'linux'].includes(item?.os) && text(item?.command)) |
|||
.slice(0, 3) |
|||
.map(item => ({os: item.os, command: item.command.trim()})); |
|||
if (!commands.length) { |
|||
return undefined; |
|||
} |
|||
const outcomes = (Array.isArray(value.outcomes) ? value.outcomes : []) |
|||
.filter(item => text(item?.output) && text(item?.meaning)) |
|||
.slice(0, 4) |
|||
.map(item => ({output: text(item.output), meaning: text(item.meaning), ok: item.ok === true})); |
|||
let sample: Record<string, unknown> | undefined; |
|||
try { |
|||
const parsed = typeof value.sample === 'string' ? JSON.parse(value.sample) : value.sample; |
|||
sample = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined; |
|||
} catch { |
|||
sample = undefined; |
|||
} |
|||
const accessToken = text(value.accessToken); |
|||
return {hint: text(value.hint), commands, outcomes, ...(sample && accessToken ? {sample, accessToken} : {})}; |
|||
} |
|||
|
|||
const text = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; |
|||
|
|||
const ICON_NAME = /^[a-z0-9_]{2,40}$/; |
|||
|
|||
const iconOf = (value: unknown, fallback: string): string => typeof value === 'string' && ICON_NAME.test(value) ? value : fallback; |
|||
|
|||
export function aiHandOverOf(args: unknown): AiHandOver | null { |
|||
const values = (args ?? {}) as Record<string, any>; |
|||
const title = text(values.title); |
|||
if (!title) { |
|||
return null; |
|||
} |
|||
const steps = handOverStepsOf(values.steps); |
|||
const options: AiHandOverOption[] = (Array.isArray(values.choice?.options) ? values.choice.options : []) |
|||
.filter(option => text(option?.id) && text(option?.label)) |
|||
.slice(0, 4) |
|||
.map(option => ({id: text(option.id), label: text(option.label), icon: typeof option.icon === 'string' && ICON_NAME.test(option.icon) ? option.icon : undefined, |
|||
text: text(option.text) ?? '', steps: handOverStepsOf(option.steps)})); |
|||
const choice = options.length >= 2 ? { |
|||
question: text(values.choice.question) ?? '', |
|||
icon: iconOf(values.choice.icon, 'tune'), |
|||
value: options.some(option => option.id === values.choice.value) ? values.choice.value : options[0].id, |
|||
options |
|||
} : undefined; |
|||
const waitFor = ['message', 'uplink', 'gateway'].includes(values.waitFor) ? values.waitFor : undefined; |
|||
const interval = Number(values.intervalSeconds); |
|||
return {title, text: text(values.text), choice, steps, waitFor, |
|||
intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, quiet: text(values.quiet), |
|||
test: handOverTestOf(values.test), paste: handOverPasteOf(values.paste)}; |
|||
} |
|||
|
|||
function handOverPasteOf(value: any): AiHandOver['paste'] { |
|||
const label = text(value?.label); |
|||
const intro = text(value?.intro); |
|||
return label && intro ? {label, intro, icon: iconOf(value.icon, 'terminal')} : undefined; |
|||
} |
|||
|
|||
function handOverStepsOf(list: unknown): AiHandOverStep[] { |
|||
return (Array.isArray(list) ? list : []) |
|||
.filter(step => text(step?.title)) |
|||
.slice(0, 6) |
|||
.map(step => ({ |
|||
title: text(step.title), |
|||
detail: text(step.detail), |
|||
markdown: text(step.markdown), |
|||
file: text(step.file), |
|||
done: step.done === true, |
|||
values: (Array.isArray(step.values) ? step.values : []) |
|||
.filter(value => text(value?.label) && typeof value?.value === 'string' && value.value) |
|||
.slice(0, 4) |
|||
.map(value => ({label: text(value.label), value: value.value, secret: value.secret === true, |
|||
icon: iconOf(value.icon, value.secret === true ? 'key' : /^https?:\/\//.test(value.value) ? 'link' : 'label')})) |
|||
})); |
|||
} |
|||
|
|||
export interface AiConnectionCheck { |
|||
dataArriving: boolean; |
|||
failedStep?: string; |
|||
name?: string; |
|||
note?: string; |
|||
readings: {key: string; value: string}[]; |
|||
keyCount: number; |
|||
gateway: boolean; |
|||
} |
|||
|
|||
export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { |
|||
let values: any = result; |
|||
if (typeof result === 'string') { |
|||
try { |
|||
values = JSON.parse(result); |
|||
} catch { |
|||
return null; |
|||
} |
|||
} |
|||
if (!values || typeof values !== 'object' || !values.steps) { |
|||
return null; |
|||
} |
|||
const readings: {key: string; value: string}[] = []; |
|||
const add = (telemetry: unknown) => Object.entries(telemetry && typeof telemetry === 'object' ? telemetry : {}) |
|||
.map(([key, item]) => ({key, value: String((item as any)?.value ?? '')})) |
|||
.filter(reading => !/^\s*[{[]/.test(reading.value)) |
|||
.forEach(reading => readings.push(reading)); |
|||
const gateway = values.gateway === true; |
|||
if (!gateway) { |
|||
add(values.telemetry); |
|||
} |
|||
(Array.isArray(values.devices) ? values.devices : []).forEach(device => add(device?.telemetry)); |
|||
return {dataArriving: values.steps.dataArriving === true, failedStep: text(values.failedStep), name: text(values.name), |
|||
note: text(values.note), readings: readings.slice(0, 6), keyCount: new Set(readings.map(reading => reading.key)).size, gateway}; |
|||
} |
|||
|
|||
export const isKitCardTool = (tool: string): boolean => KIT_CARD_TOOLS.has(tool); |
|||
|
|||
const PLAN_NEEDS = new Set(['device', 'account', 'computer', 'phone']); |
|||
|
|||
export interface AiPlanStep { |
|||
text: string; |
|||
by: 'agent' | 'user'; |
|||
needs?: string; |
|||
optional?: boolean; |
|||
makes?: {type: string; name: string}[]; |
|||
} |
|||
|
|||
export interface AiPlanProgress { |
|||
done: number[]; |
|||
now?: number; |
|||
skipped: number[]; |
|||
} |
|||
|
|||
export function aiPlanOf(args: unknown): AiPlanStep[] { |
|||
const steps = (args as {steps?: unknown})?.steps; |
|||
if (!Array.isArray(steps)) { |
|||
return []; |
|||
} |
|||
return steps |
|||
.filter(step => typeof step?.text === 'string' && step.text.trim()) |
|||
.slice(0, 8) |
|||
.map(step => ({ |
|||
text: step.text.trim(), |
|||
by: step.by === 'user' ? 'user' : 'agent', |
|||
needs: step.by === 'user' && PLAN_NEEDS.has(step.needs) ? step.needs : undefined, |
|||
optional: step.optional === true, |
|||
makes: Array.isArray(step.makes) |
|||
? step.makes.filter(made => typeof made?.type === 'string' && typeof made?.name === 'string' && made.name.trim()).slice(0, 4) |
|||
: [] |
|||
})); |
|||
} |
|||
|
|||
export function aiPlanProgressOf(args: unknown): AiPlanProgress { |
|||
const values = (args ?? {}) as {done?: unknown; now?: unknown; skipped?: unknown}; |
|||
const numbers = (list: unknown): number[] => Array.isArray(list) ? list.filter(item => Number.isInteger(item) && item > 0) : []; |
|||
return { |
|||
done: numbers(values.done), |
|||
now: Number.isInteger(values.now) && (values.now as number) > 0 ? values.now as number : undefined, |
|||
skipped: numbers(values.skipped) |
|||
}; |
|||
} |
|||
|
|||
export function aiQuestionsOf(args: unknown): AiQuestion[] { |
|||
const questions = (args as {questions?: unknown})?.questions; |
|||
if (!Array.isArray(questions)) { |
|||
return []; |
|||
} |
|||
return questions |
|||
.filter(question => typeof question?.question === 'string' && question.question.trim()) |
|||
.slice(0, 3) |
|||
.map((question, index) => ({ |
|||
id: typeof question.id === 'string' && question.id ? question.id : 'q' + index, |
|||
question: question.question.trim(), |
|||
why: typeof question.why === 'string' ? question.why : undefined, |
|||
options: (Array.isArray(question.options) ? question.options : []) |
|||
.filter(option => typeof option?.label === 'string' && option.label.trim()) |
|||
.slice(0, 6) |
|||
.map(option => ({label: option.label.trim(), hint: typeof option.hint === 'string' ? option.hint : undefined})), |
|||
recommended: Array.isArray(question.recommended) ? question.recommended.filter(label => typeof label === 'string') : undefined, |
|||
multiple: question.multiple === true, |
|||
secret: question.secret === true && !(Array.isArray(question.options) && question.options.length), |
|||
color: question.color === true && question.multiple !== true |
|||
})); |
|||
} |
|||
|
|||
const MAX_PROMPTS = 4; |
|||
|
|||
export interface AiPrompt { |
|||
text: string; |
|||
icon?: string; |
|||
} |
|||
|
|||
export function aiTurnPrompts(messages: Array<{from: string; data?: any}>): AiPrompt[] { |
|||
for (let i = messages.length - 1; i >= 0; i--) { |
|||
const message = messages[i]; |
|||
if (message.from === 'USER') { |
|||
return []; |
|||
} |
|||
if (message.from === 'ACTION' && message.data?.tool === SUGGEST_PROMPTS_TOOL) { |
|||
return aiPromptsOf(message.data.arguments); |
|||
} |
|||
} |
|||
return []; |
|||
} |
|||
|
|||
export function aiPromptsOf(args: unknown): AiPrompt[] { |
|||
const prompts = (args as {prompts?: unknown})?.prompts; |
|||
if (!Array.isArray(prompts)) { |
|||
return []; |
|||
} |
|||
return prompts |
|||
.filter(prompt => typeof prompt?.text === 'string' && prompt.text.trim()) |
|||
.map(prompt => ({text: prompt.text.trim(), icon: typeof prompt.icon === 'string' && /^[a-z0-9_]+$/.test(prompt.icon) ? prompt.icon : undefined})) |
|||
.slice(0, MAX_PROMPTS); |
|||
} |
|||
|
|||
const ALARM_UPDATE_ACTIONS = ['acknowledge', 'assign', 'clear', 'comment', 'unassign']; |
|||
|
|||
export const alarmUpdateAction = (action: unknown): string => { |
|||
const name = String(action ?? '').toLowerCase(); |
|||
return ALARM_UPDATE_ACTIONS.includes(name) ? name : 'other'; |
|||
}; |
|||
|
|||
const PART_WORDS = new Set(['html', 'css', 'js', 'resources', 'settingsForm', 'dataKeySettingsForm', 'latestDataKeySettingsForm', |
|||
'defaultConfig', 'svg', 'metadata', 'functions', 'behavior', 'properties']); |
|||
|
|||
export interface AiWordList { |
|||
words: string[]; |
|||
commas?: boolean; |
|||
} |
|||
|
|||
export const aiPartWord = (part: string): string => PART_WORDS.has(part) ? 'ai-assistant.part.' + part : part; |
|||
|
|||
export const aiPartTitle = (part: string): string => PART_WORDS.has(part) ? 'ai-assistant.part-title.' + part : part.charAt(0).toUpperCase() + part.slice(1); |
|||
|
|||
export const aiWordList = (words: string[], commas = false): AiWordList => commas ? {words, commas} : {words}; |
|||
|
|||
export const isAiWordList = (value: unknown): value is AiWordList => !!value && typeof value === 'object' && Array.isArray((value as AiWordList).words); |
|||
|
|||
export function aiJoinWords(translate: TranslateService, list: AiWordList): string { |
|||
const said = list.words.map(word => word.startsWith('ai-assistant.') ? translate.instant(word) as string : word); |
|||
if (said.length < 2) { |
|||
return said.join(''); |
|||
} |
|||
const more = (first: string, rest: string) => translate.instant('ai-assistant.list.more', {first, rest}) as string; |
|||
const last = list.commas ? more(said[said.length - 2], said[said.length - 1]) |
|||
: translate.instant('ai-assistant.list.pair', {first: said[said.length - 2], second: said[said.length - 1]}) as string; |
|||
return said.slice(0, -2).reduceRight((rest, first) => more(first, rest), last); |
|||
} |
|||
|
|||
const THING_KEYS: Record<string, string> = { |
|||
DASHBOARD_WIDGET: 'widget', |
|||
DASHBOARD_STATE: 'state', |
|||
DASHBOARD_ENTITY_ALIAS: 'alias', |
|||
DASHBOARD_FILTER: 'filter' |
|||
}; |
|||
|
|||
export function aiThingWord(translate: TranslateService, entityType: string | undefined, fallback: string): string { |
|||
if (!entityType) { |
|||
return translate.instant(fallback); |
|||
} |
|||
const key = 'ai-assistant.detail.thing.' + (THING_KEYS[entityType] ?? entityType.toLowerCase().replace(/_/g, '-')); |
|||
const word: string = translate.instant(key); |
|||
return word !== key ? word : translate.instant(fallback); |
|||
} |
|||
|
|||
export function aiActionText(translate: TranslateService, words: AiActionWords, phase: 'run' | 'done'): string { |
|||
const params: Record<string, string> = {}; |
|||
for (const [key, value] of Object.entries(words.params ?? {})) { |
|||
params[key] = isAiWordList(value) ? aiJoinWords(translate, value) : value; |
|||
} |
|||
return translate.instant(words.key + '.' + phase, params); |
|||
} |
|||
|
|||
export function widgetParts(values: Record<string, any>): string[] { |
|||
const parts = Array.isArray(values.sections) ? values.sections.map(String) : []; |
|||
return parts.length ? parts : typeof values.section === 'string' ? [values.section] : ['overview']; |
|||
} |
|||
|
|||
export function aiActionWords(tool: string, args: unknown): AiActionWords { |
|||
const values = (args && typeof args === 'object' ? args : {}) as Record<string, any>; |
|||
if (GENERATING_TOOLS[tool]) { |
|||
return {key: ACTION_PREFIX + GENERATING_TOOLS[tool], kind: 'gen'}; |
|||
} |
|||
if (SAVED_KINDS[tool]) { |
|||
const [kind, nested] = SAVED_KINDS[tool]; |
|||
return {key: ACTION_PREFIX + (hasId(nested ? values[nested] : values) ? 'update-' : 'create-') + kind, kind: 'think'}; |
|||
} |
|||
switch (tool) { |
|||
case 'add_dashboard_widgets': |
|||
return {key: ACTION_PREFIX + (Array.isArray(values.widgets) && values.widgets.length === 1 ? 'add-widget' : 'add-widgets'), kind: 'think'}; |
|||
case 'add_scada_connectors': |
|||
return {key: ACTION_PREFIX + 'add-scada-connectors', kind: 'think'}; |
|||
case 'read_widget': { |
|||
const parts = widgetParts(values).filter(part => part !== 'overview'); |
|||
return parts.length && !parts.includes('all') |
|||
? {key: ACTION_PREFIX + 'read-widget-parts', params: {parts: aiWordList(parts.map(aiPartWord))}, kind: 'think'} |
|||
: {key: ACTION_PREFIX + 'read-widget-type', kind: 'think'}; |
|||
} |
|||
case 'read_scada_symbol': { |
|||
const parts = widgetParts(values).filter(part => part !== 'overview'); |
|||
return parts.length && !parts.includes('all') |
|||
? {key: ACTION_PREFIX + 'read-scada-symbol-parts', params: {parts: aiWordList(parts.map(aiPartWord))}, kind: 'think'} |
|||
: {key: ACTION_PREFIX + 'read-scada-symbol', kind: 'think'}; |
|||
} |
|||
case 'read_report_template': |
|||
return {key: ACTION_PREFIX + (typeof values.path === 'string' && values.path ? 'read-report-component' : 'read-report-template'), kind: 'think'}; |
|||
case 'search_entities': |
|||
return {key: ACTION_PREFIX + searchedWords(values), kind: 'think'}; |
|||
case 'update_alarms': |
|||
return {key: ACTION_PREFIX + 'update-alarms.' + alarmUpdateAction(values.action), kind: 'think'}; |
|||
case 'read_timeseries': |
|||
return {key: ACTION_PREFIX + telemetryWords(values), kind: 'think'}; |
|||
case 'delete': |
|||
return {key: ACTION_PREFIX + (DELETED_TARGETS[values.targetType] ?? 'delete-other'), kind: 'think'}; |
|||
case 'check_connection': |
|||
return {key: ACTION_PREFIX + (Number(values.waitSeconds) > 0 ? 'wait-for-data' : 'check-connection'), kind: 'think'}; |
|||
case 'fetch_web_page': { |
|||
const site = siteOf(values.url); |
|||
return site ? {key: ACTION_PREFIX + 'read-site', params: {site}, kind: 'think'} : {key: ACTION_PREFIX + 'read-page', kind: 'think'}; |
|||
} |
|||
} |
|||
return {key: ACTION_PREFIX + (TOOL_WORDS[tool] ?? 'other'), kind: 'think'}; |
|||
} |
|||
|
|||
export function aiActionDuration(translate: TranslateService, ms: number): string { |
|||
if (ms < 1000) { |
|||
return translate.instant('ai-assistant.duration.seconds', {seconds: Math.max(Math.round(ms / 100), 1) / 10}); |
|||
} |
|||
const seconds = Math.round(ms / 1000); |
|||
if (seconds < 60) { |
|||
return translate.instant('ai-assistant.duration.seconds', {seconds}); |
|||
} |
|||
const rest = seconds % 60; |
|||
return rest ? translate.instant('ai-assistant.duration.minutes-seconds', {minutes: Math.floor(seconds / 60), seconds: rest}) |
|||
: translate.instant('ai-assistant.duration.minutes', {minutes: seconds / 60}); |
|||
} |
|||
|
|||
export function aiWorkClock(ms: number): string { |
|||
const seconds = Math.round(ms / 1000); |
|||
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; |
|||
} |
|||
|
|||
function hasId(value: unknown): boolean { |
|||
let object = value; |
|||
if (typeof value === 'string') { |
|||
try { |
|||
object = JSON.parse(value); |
|||
} catch { |
|||
return false; |
|||
} |
|||
} |
|||
const id = (object as {id?: unknown})?.id; |
|||
return !!id && (typeof id === 'string' || typeof (id as {id?: unknown}).id === 'string'); |
|||
} |
|||
|
|||
function searchedWords(values: Record<string, any>): string { |
|||
const filter = values.entityFilter ?? values; |
|||
const types = new Set<string>(); |
|||
const add = (type: unknown) => typeof type === 'string' && types.add(type); |
|||
add(filter?.entityType); |
|||
add(filter?.singleEntity?.entityType); |
|||
if (filter?.deviceType || filter?.deviceTypes || filter?.filterType === 'deviceType') { |
|||
types.add('DEVICE'); |
|||
} |
|||
if (filter?.assetType || filter?.assetTypes || filter?.filterType === 'assetType') { |
|||
types.add('ASSET'); |
|||
} |
|||
(filter?.filters ?? []).forEach((relationFilter: any) => (relationFilter?.entityTypes ?? []).forEach(add)); |
|||
if (types.size === 1) { |
|||
return SEARCHED_TYPES[[...types][0]] ?? 'search-tenant'; |
|||
} |
|||
return 'search-tenant'; |
|||
} |
|||
|
|||
function telemetryWords(values: Record<string, any>): string { |
|||
switch (values.mode) { |
|||
case 'LATEST': |
|||
return 'read-latest-values'; |
|||
case 'KEYS': |
|||
return 'read-telemetry-keys'; |
|||
default: |
|||
return values.mode ? 'read-history' : 'read-latest-values'; |
|||
} |
|||
} |
|||
|
|||
function siteOf(url: unknown): string | undefined { |
|||
if (typeof url !== 'string') { |
|||
return undefined; |
|||
} |
|||
try { |
|||
return new URL(url).hostname.replace(/^www\./, '') || undefined; |
|||
} catch { |
|||
return undefined; |
|||
} |
|||
} |
|||
|
|||
export type AiEntityPalette = 'device' | 'path' | 'chain' | 'rule' | 'view' | 'people' | 'solution'; |
|||
|
|||
export interface AiEntityKind { |
|||
icon: string; |
|||
palette: AiEntityPalette; |
|||
} |
|||
|
|||
const ENTITY_KINDS: Record<string, AiEntityKind> = { |
|||
DEVICE: {icon: 'memory', palette: 'device'}, |
|||
GATEWAY: {icon: 'lan', palette: 'device'}, |
|||
ENTITY_VIEW: {icon: 'view_quilt', palette: 'device'}, |
|||
EDGE: {icon: 'router', palette: 'device'}, |
|||
SOLUTION_TEMPLATE: {icon: 'dashboard_customize', palette: 'solution'}, |
|||
DEVICE_PROFILE: {icon: 'category', palette: 'device'}, |
|||
ASSET: {icon: 'domain', palette: 'device'}, |
|||
ASSET_PROFILE: {icon: 'category', palette: 'device'}, |
|||
INTEGRATION: {icon: 'input', palette: 'path'}, |
|||
CONVERTER: {icon: 'transform', palette: 'path'}, |
|||
CALCULATED_FIELD: {icon: 'functions', palette: 'path'}, |
|||
RULE_CHAIN: {icon: 'account_tree', palette: 'chain'}, |
|||
EDGE_RULE_CHAIN: {icon: 'account_tree', palette: 'chain'}, |
|||
AGENT: {icon: 'memory', palette: 'device'}, |
|||
AGENT_APPLICATION: {icon: 'apps', palette: 'device'}, |
|||
AGENT_PROFILE: {icon: 'badge', palette: 'device'}, |
|||
AGENT_APP_PROFILE: {icon: 'inventory_2', palette: 'device'}, |
|||
IOT_HUB: {icon: 'hub', palette: 'solution'}, |
|||
ALARM_RULE: {icon: 'rule', palette: 'rule'}, |
|||
ALARM: {icon: 'notification_important', palette: 'rule'}, |
|||
NOTIFICATION_RULE: {icon: 'notifications_active', palette: 'rule'}, |
|||
NOTIFICATION_TEMPLATE: {icon: 'description', palette: 'path'}, |
|||
NOTIFICATION_TARGET: {icon: 'group', palette: 'people'}, |
|||
DASHBOARD: {icon: 'dashboard', palette: 'view'}, |
|||
DASHBOARD_WIDGET: {icon: 'widgets', palette: 'view'}, |
|||
DASHBOARD_STATE: {icon: 'tab', palette: 'view'}, |
|||
DASHBOARD_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, |
|||
DASHBOARD_FILTER: {icon: 'filter_list', palette: 'view'}, |
|||
WIDGET_TYPE: {icon: 'widgets', palette: 'view'}, |
|||
WIDGETS_BUNDLE: {icon: 'now_widgets', palette: 'view'}, |
|||
OTA_PACKAGE: {icon: 'system_update', palette: 'device'}, |
|||
MAIL_TEMPLATE: {icon: 'mail', palette: 'view'}, |
|||
CUSTOM_TRANSLATION: {icon: 'translate', palette: 'view'}, |
|||
CUSTOM_MENU: {icon: 'menu', palette: 'view'}, |
|||
MOBILE_APP: {icon: 'smartphone', palette: 'device'}, |
|||
MOBILE_BUNDLE: {icon: 'phonelink_setup', palette: 'device'}, |
|||
MOBILE_QR_CODE: {icon: 'qr_code_2', palette: 'device'}, |
|||
SCHEDULER_EVENT: {icon: 'schedule', palette: 'rule'}, |
|||
REPORT_TEMPLATE: {icon: 'description', palette: 'view'}, |
|||
REPORT_COMPONENT: {icon: 'view_agenda', palette: 'view'}, |
|||
REPORT_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, |
|||
REPORT_FILTER: {icon: 'filter_list', palette: 'view'}, |
|||
SCHEDULED_REPORT: {icon: 'event_repeat', palette: 'rule'}, |
|||
REPORT: {icon: 'summarize', palette: 'view'}, |
|||
TWO_FACTOR_SETTINGS: {icon: 'phonelink_lock', palette: 'people'}, |
|||
DOMAIN: {icon: 'language', palette: 'people'}, |
|||
MY_PROFILE: {icon: 'account_circle', palette: 'people'}, |
|||
MY_TWO_FACTOR: {icon: 'phonelink_lock', palette: 'people'}, |
|||
API_KEY: {icon: 'vpn_key', palette: 'people'}, |
|||
MAIL_SERVER: {icon: 'outgoing_mail', palette: 'view'}, |
|||
IMAGE: {icon: 'image', palette: 'view'}, |
|||
TB_RESOURCE: {icon: 'image', palette: 'view'}, |
|||
SCADA_SYMBOL: {icon: 'view_in_ar', palette: 'view'}, |
|||
CUSTOMER: {icon: 'supervisor_account', palette: 'people'}, |
|||
USER: {icon: 'account_circle', palette: 'people'}, |
|||
TENANT: {icon: 'business', palette: 'people'}, |
|||
ENTITY_GROUP: {icon: 'folder_shared', palette: 'people'}, |
|||
ROLE: {icon: 'admin_panel_settings', palette: 'people'}, |
|||
GROUP_PERMISSION: {icon: 'key', palette: 'people'} |
|||
}; |
|||
|
|||
export function aiEntityKind(entityType: string, alarmRule = false): AiEntityKind { |
|||
return ENTITY_KINDS[alarmRule ? 'ALARM_RULE' : entityType] ?? {icon: 'category', palette: 'solution'}; |
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
<div class="art-pane-edge" role="separator" tabindex="0" aria-orientation="vertical" |
|||
[attr.aria-label]="'ai-assistant.artifact.resize' | translate" |
|||
[matTooltip]="'ai-assistant.artifact.resize-hint' | translate" matTooltipPosition="left" matTooltipShowDelay="600" |
|||
(pointerdown)="startResize($event)" (dblclick)="resetWidth()" (keydown)="onEdgeKey($event)"></div> |
|||
<div class="art-pane-head"> |
|||
<button type="button" class="art-ib art-pane-close" (click)="closed.emit()" |
|||
[matTooltip]="'ai-assistant.artifact.close' | translate" matTooltipPosition="below" |
|||
[attr.aria-label]="'ai-assistant.artifact.close' | translate"> |
|||
<mat-icon class="wide-only">chevron_right</mat-icon> |
|||
<mat-icon class="narrow-only">arrow_back</mat-icon> |
|||
</button> |
|||
<ng-content select="[artHead]"></ng-content> |
|||
</div> |
|||
<div #body class="art-pane-body" [class.dark]="dark()" (scroll)="refreshEdges()"> |
|||
<ng-content></ng-content> |
|||
</div> |
|||
<ng-content select="[artFoot]"></ng-content> |
|||
@ -0,0 +1,134 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { readStored, writeStored } from '@core/local-storage/stored'; |
|||
import { AfterViewInit, Component, ElementRef, EventEmitter, inject, input, Output, signal, ViewChild } from '@angular/core'; |
|||
|
|||
const PANE_MIN = 360; |
|||
const CHAT_MIN = 340; |
|||
const WIDTH_KEY = 'tbSolutionPaneWidth'; |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-artifact-pane', |
|||
templateUrl: './ai-artifact-pane.component.html', |
|||
standalone: false, |
|||
host: { |
|||
class: 'art-pane', |
|||
'[class.scrolled]': 'scrolled()', |
|||
'[class.more]': 'more()', |
|||
'[style.flex-basis]': 'width() ? width() + "px" : null', |
|||
'(keydown.escape)': 'onEscape($event)' |
|||
} |
|||
}) |
|||
export class AiArtifactPaneComponent implements AfterViewInit { |
|||
|
|||
dark = input(false); |
|||
|
|||
@Output() closed = new EventEmitter<void>(); |
|||
|
|||
@ViewChild('body', {static: true}) body: ElementRef<HTMLElement>; |
|||
|
|||
width = signal<number | null>(AiArtifactPaneComponent.storedWidth()); |
|||
scrolled = signal(false); |
|||
more = signal(false); |
|||
|
|||
private host = inject(ElementRef<HTMLElement>); |
|||
|
|||
ngAfterViewInit(): void { |
|||
setTimeout(() => this.refreshEdges(), 50); |
|||
} |
|||
|
|||
refreshEdges(): void { |
|||
const body = this.body?.nativeElement; |
|||
if (body) { |
|||
this.scrolled.set(body.scrollTop > 0); |
|||
this.more.set(body.scrollTop + body.clientHeight < body.scrollHeight - 1); |
|||
} |
|||
} |
|||
|
|||
onEscape(event: Event): void { |
|||
if (event.defaultPrevented) { |
|||
return; |
|||
} |
|||
event.stopPropagation(); |
|||
this.closed.emit(); |
|||
} |
|||
|
|||
startResize(event: PointerEvent): void { |
|||
event.preventDefault(); |
|||
const edge = event.target as HTMLElement; |
|||
const pane = this.host.nativeElement as HTMLElement; |
|||
const cols = pane.parentElement; |
|||
if (!cols) { |
|||
return; |
|||
} |
|||
const startX = event.clientX; |
|||
const startWidth = pane.getBoundingClientRect().width; |
|||
const max = cols.getBoundingClientRect().width - CHAT_MIN; |
|||
edge.setPointerCapture(event.pointerId); |
|||
edge.classList.add('held'); |
|||
let closing = false; |
|||
const move = (e: PointerEvent) => { |
|||
const width = startWidth + (startX - e.clientX); |
|||
closing = width < PANE_MIN - 72; |
|||
pane.classList.toggle('closing', closing); |
|||
this.width.set(Math.round(Math.min(max, Math.max(PANE_MIN, width)))); |
|||
}; |
|||
const up = () => { |
|||
edge.removeEventListener('pointermove', move); |
|||
edge.removeEventListener('pointerup', up); |
|||
edge.removeEventListener('pointercancel', up); |
|||
edge.classList.remove('held'); |
|||
pane.classList.remove('closing'); |
|||
if (closing) { |
|||
this.width.set(startWidth); |
|||
this.closed.emit(); |
|||
} else { |
|||
this.storeWidth(); |
|||
} |
|||
}; |
|||
edge.addEventListener('pointermove', move); |
|||
edge.addEventListener('pointerup', up); |
|||
edge.addEventListener('pointercancel', up); |
|||
} |
|||
|
|||
resetWidth(): void { |
|||
this.width.set(null); |
|||
this.storeWidth(); |
|||
} |
|||
|
|||
onEdgeKey(event: KeyboardEvent): void { |
|||
if (event.key === 'Enter') { |
|||
this.resetWidth(); |
|||
return; |
|||
} |
|||
const pane = this.host.nativeElement as HTMLElement; |
|||
const cols = pane.parentElement; |
|||
if (!cols) { |
|||
return; |
|||
} |
|||
const max = cols.getBoundingClientRect().width - CHAT_MIN; |
|||
let width: number; |
|||
if (event.key === 'Home') { |
|||
width = max; |
|||
} else if (event.key === 'End') { |
|||
width = PANE_MIN; |
|||
} else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { |
|||
const step = event.shiftKey ? 64 : 16; |
|||
width = pane.getBoundingClientRect().width + (event.key === 'ArrowLeft' ? step : -step); |
|||
} else { |
|||
return; |
|||
} |
|||
event.preventDefault(); |
|||
this.width.set(Math.round(Math.min(max, Math.max(PANE_MIN, width)))); |
|||
this.storeWidth(); |
|||
} |
|||
|
|||
private static storedWidth(): number | null { |
|||
return Number(readStored(WIDTH_KEY)) || null; |
|||
} |
|||
|
|||
private storeWidth(): void { |
|||
const width = this.width(); |
|||
writeStored(WIDTH_KEY, width ? String(width) : null); |
|||
} |
|||
} |
|||
@ -0,0 +1,253 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { |
|||
ChangeDetectionStrategy, |
|||
Component, |
|||
computed, |
|||
DestroyRef, |
|||
effect, |
|||
ElementRef, |
|||
inject, |
|||
Renderer2, |
|||
signal, |
|||
untracked, |
|||
viewChild, |
|||
ViewContainerRef |
|||
} from '@angular/core'; |
|||
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; |
|||
import { NavigationEnd, NavigationStart, Router } from '@angular/router'; |
|||
import { filter } from 'rxjs/operators'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { AiChatsService } from '@core/services/ai-chats.service'; |
|||
import { ChatLevel } from '@shared/models/ai-chat.models'; |
|||
import { MatDialog } from '@angular/material/dialog'; |
|||
import { Store } from '@ngrx/store'; |
|||
import { AppState } from '@core/core.state'; |
|||
import { getCurrentAuthState, selectAiTourStepSeen } from '@core/auth/auth.selectors'; |
|||
import { ActionPreferencesUpdateAiTour } from '@core/auth/auth.actions'; |
|||
import { AiTourStep } from '@shared/models/user-settings.models'; |
|||
import { UserPermissionsService } from '@core/http/user-permissions.service'; |
|||
import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; |
|||
import { escapeTourText, TourPopupRef, TourPopupService } from '@shared/components/tour/tour-popup.service'; |
|||
import { TourService } from '@core/services/tour.service'; |
|||
import { AiAssistantContextService } from '@home/components/ai/ai-assistant-context.service'; |
|||
import { AiSlashService } from '@core/services/ai-slash.service'; |
|||
import { AiMarkCue } from '@home/components/ai/ai-mark.component'; |
|||
|
|||
const INTRO_DELAY_MS = 900; |
|||
|
|||
const intro: { owner: AiAssistantButtonComponent | null } = {owner: null}; |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-assistant-button', |
|||
template: ` |
|||
@if (available && !panelService.open() && !panelService.suppressed()) { |
|||
@let status = cue(); |
|||
<button #aiButton tb-ai-mark class="tb-ai-assistant-button" [cue]="markCue()" |
|||
[working]="status?.level === 'running'" [glow]="introOpen()" |
|||
tb-popover [tbAiTip]="buttonTip" [tbPopoverTrigger]="introOpen() ? null : 'hover'" |
|||
[attr.aria-label]="status ? ('ai-assistant.ai-assistant-cue' | translate: {cue: status.tip}) : ('ai-assistant.ai-assistant' | translate)" |
|||
aria-keyshortcuts="/" |
|||
(click)="toggle($event)"> |
|||
</button> |
|||
<ng-template #buttonTip> |
|||
<div class="tb-ai-tip-body tip-mini"> |
|||
<div class="tip-keyrow"> |
|||
<span>{{ status ? ('ai-assistant.ai-assistant-cue' | translate: {cue: status.tip}) : ('ai-assistant.ai-assistant' | translate) }}</span> |
|||
<span class="tip-caps"><kbd>/</kbd></span> |
|||
</div> |
|||
</div> |
|||
</ng-template> |
|||
} |
|||
`,
|
|||
styles: [` |
|||
:host { |
|||
display: contents; |
|||
} |
|||
`],
|
|||
standalone: false, |
|||
changeDetection: ChangeDetectionStrategy.OnPush |
|||
}) |
|||
export class AiAssistantButtonComponent { |
|||
|
|||
panelService = inject(AiAssistantPanelService); |
|||
|
|||
private store = inject(Store<AppState>); |
|||
|
|||
private readonly authState = getCurrentAuthState(this.store); |
|||
|
|||
readonly available = inject(UserPermissionsService).isAiAvailable(); |
|||
|
|||
private dialog = inject(MatDialog); |
|||
|
|||
private chats = inject(AiChatsService); |
|||
|
|||
private translate = inject(TranslateService); |
|||
|
|||
private context = inject(AiAssistantContextService); |
|||
|
|||
private tourPopup = inject(TourPopupService); |
|||
|
|||
private tourService = inject(TourService); |
|||
|
|||
private renderer = inject(Renderer2); |
|||
|
|||
private viewContainerRef = inject(ViewContainerRef); |
|||
|
|||
private buttonRef = viewChild('aiButton', {read: ElementRef<HTMLElement>}); |
|||
|
|||
private introSeen = toSignal(this.store.select(selectAiTourStepSeen(AiTourStep.AI_BUTTON)), {initialValue: true}); |
|||
|
|||
private welcomeSeen = toSignal(this.store.select(selectAiTourStepSeen(AiTourStep.WELCOME)), {initialValue: false}); |
|||
|
|||
readonly introOpen = signal(false); |
|||
|
|||
private introPopup: TourPopupRef | null = null; |
|||
|
|||
private introTimer: ReturnType<typeof setTimeout> | null = null; |
|||
|
|||
readonly cue = computed<{level: ChatLevel; tip: string} | null>(() => { |
|||
const chats = this.chats.statusChats(); |
|||
const titleOf = (title: string) => title || this.translate.instant('ai-assistant.new-chat'); |
|||
const attention = chats.filter(chat => this.chats.needsAttention(chat)); |
|||
if (attention.length) { |
|||
const level: AiMarkCue = attention.some(chat => this.chats.levelOf(chat) === 'needs') ? 'needs' : 'error'; |
|||
return { |
|||
level, |
|||
tip: attention.length === 1 |
|||
? this.translate.instant('ai-assistant.waiting-one-tip', {title: titleOf(attention[0].title), status: this.chats.tipOf(attention[0])}) |
|||
: this.translate.instant('ai-assistant.waiting-many', {count: attention.length}) |
|||
}; |
|||
} |
|||
const running = chats.filter(chat => this.chats.levelOf(chat) === 'running'); |
|||
if (running.length) { |
|||
return { |
|||
level: 'running', |
|||
tip: running.length === 1 |
|||
? this.translate.instant('ai-assistant.running-one-tip', {title: titleOf(running[0].title)}) |
|||
: this.translate.instant('ai-assistant.running-many', {count: running.length}) |
|||
}; |
|||
} |
|||
return null; |
|||
}); |
|||
|
|||
readonly markCue = computed<AiMarkCue | null>(() => { |
|||
const level = this.cue()?.level; |
|||
return level === 'needs' || level === 'error' ? level : null; |
|||
}); |
|||
|
|||
private introWanted = computed(() => this.available && this.welcomeSeen() && !this.tourService.active() && !this.introSeen() && this.cue()?.level !== 'running' && !this.panelService.open() |
|||
&& !this.panelService.suppressed() && !!this.buttonRef()); |
|||
|
|||
private introEffect = effect(() => { |
|||
const wanted = this.introWanted(); |
|||
untracked(() => { |
|||
this.clearIntroTimer(); |
|||
if (wanted && !this.introOpen()) { |
|||
this.introTimer = setTimeout(() => this.showIntro(), INTRO_DELAY_MS); |
|||
} else if (!wanted && this.introOpen()) { |
|||
this.hideIntro(); |
|||
} |
|||
}); |
|||
}); |
|||
|
|||
constructor() { |
|||
if (this.available) { |
|||
this.chats.watchStatus(); |
|||
} |
|||
inject(Router).events.pipe( |
|||
filter(event => event instanceof NavigationStart || event instanceof NavigationEnd), |
|||
takeUntilDestroyed() |
|||
).subscribe(event => { |
|||
this.clearIntroTimer(); |
|||
if (event instanceof NavigationStart) { |
|||
this.hideIntro(); |
|||
} else if (this.introWanted()) { |
|||
this.introTimer = setTimeout(() => this.showIntro(), INTRO_DELAY_MS); |
|||
} |
|||
}); |
|||
const removeOpener = inject(AiSlashService).setOpener({ |
|||
canOpen: () => this.available && !this.panelService.open() && !this.panelService.suppressed(), |
|||
open: () => this.openChat() |
|||
}); |
|||
inject(DestroyRef).onDestroy(() => { |
|||
removeOpener(); |
|||
this.clearIntroTimer(); |
|||
this.hideIntro(); |
|||
}); |
|||
} |
|||
|
|||
toggle($event: Event): void { |
|||
$event.stopPropagation(); |
|||
this.openChat(); |
|||
} |
|||
|
|||
private openChat(): void { |
|||
if (this.introOpen()) { |
|||
this.closeIntro(); |
|||
} |
|||
this.panelService.openPanel(); |
|||
} |
|||
|
|||
private showIntro(): void { |
|||
this.introTimer = null; |
|||
const trigger: HTMLElement | undefined = this.buttonRef()?.nativeElement; |
|||
if (!this.introWanted() || !trigger || intro.owner || this.dialog.openDialogs.length || !this.visible(trigger)) { |
|||
return; |
|||
} |
|||
intro.owner = this; |
|||
const welcome = this.context.welcome(); |
|||
const example = welcome.examples[0]?.label?.trim(); |
|||
const lead = this.translate.instant(`ai-assistant.intro.lead-${welcome.place}${example ? '-example' : ''}`, {example}); |
|||
const keys = matchMedia('(hover: hover) and (pointer: fine)').matches ? ' ' + this.translate.instant('ai-assistant.intro.keys') : ''; |
|||
this.introOpen.set(true); |
|||
this.introPopup = this.tourPopup.show({ |
|||
target: trigger, |
|||
hostView: this.viewContainerRef, |
|||
renderer: this.renderer, |
|||
placement: ['bottomRight', 'bottom', 'bottomLeft'], |
|||
title: welcome.title || this.translate.instant('ai-assistant.panel-title'), |
|||
text: escapeTourText(lead) + keys, |
|||
skipLabel: this.translate.instant('ai-assistant.intro.got-it'), |
|||
nextLabel: this.translate.instant('ai-assistant.intro.open-chat'), |
|||
onSkip: () => this.closeIntro(), |
|||
onClose: () => this.closeIntro(), |
|||
onNext: () => this.openChat(), |
|||
onHidden: () => { |
|||
if (this.introOpen()) { |
|||
this.introPopup = null; |
|||
this.hideIntro(); |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
|
|||
private closeIntro(): void { |
|||
this.hideIntro(); |
|||
if (!this.introSeen()) { |
|||
this.store.dispatch(new ActionPreferencesUpdateAiTour({step: AiTourStep.AI_BUTTON, seen: true})); |
|||
} |
|||
} |
|||
|
|||
private hideIntro(): void { |
|||
if (intro.owner === this) { |
|||
intro.owner = null; |
|||
} |
|||
this.introOpen.set(false); |
|||
const popup = this.introPopup; |
|||
this.introPopup = null; |
|||
popup?.close(); |
|||
} |
|||
|
|||
private clearIntroTimer(): void { |
|||
if (this.introTimer) { |
|||
clearTimeout(this.introTimer); |
|||
this.introTimer = null; |
|||
} |
|||
} |
|||
|
|||
private visible(element: HTMLElement): boolean { |
|||
const rect = element.getBoundingClientRect(); |
|||
return rect.width > 0 && rect.height > 0 && (element.checkVisibility?.({visibilityProperty: true}) ?? element.offsetParent !== null); |
|||
} |
|||
} |
|||
@ -0,0 +1,58 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { computed, inject, Injectable } from '@angular/core'; |
|||
import { toSignal } from '@angular/core/rxjs-interop'; |
|||
import { NavigationEnd, Router } from '@angular/router'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { filter, map, startWith } from 'rxjs/operators'; |
|||
import { aiClientOs, aiPageView, AiChatClientContext } from '@shared/models/ai-chat.models'; |
|||
import { getDefaultTimezone } from '@shared/models/time/time.models'; |
|||
import { BreadCrumb } from '@shared/components/breadcrumb'; |
|||
import { BreadcrumbService } from '@core/services/breadcrumb.service'; |
|||
import { UtilsService } from '@core/services/utils.service'; |
|||
import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; |
|||
import { aiWelcome } from '@home/components/ai/ai-welcome.models'; |
|||
|
|||
@Injectable({providedIn: 'root'}) |
|||
export class AiAssistantContextService { |
|||
|
|||
private panelService = inject(AiAssistantPanelService); |
|||
private translate = inject(TranslateService); |
|||
private utils = inject(UtilsService); |
|||
private router = inject(Router); |
|||
|
|||
private pageTitle = toSignal(inject(BreadcrumbService).breadcrumbs$.pipe( |
|||
map(crumbs => crumbs.map(crumb => this.crumbLabel(crumb)).filter(label => !!label).join(' › ')) |
|||
), {initialValue: ''}); |
|||
|
|||
readonly pagePath = toSignal(this.router.events.pipe( |
|||
filter((event): event is NavigationEnd => event instanceof NavigationEnd), |
|||
map(event => event.urlAfterRedirects), |
|||
startWith(this.router.url), |
|||
map(url => (url || '/').split(/[?#]/)[0]) |
|||
), {initialValue: '/'}); |
|||
|
|||
readonly clientContext = computed<AiChatClientContext | undefined>(() => { |
|||
const context = this.panelService.clientContext(); |
|||
if (context) { |
|||
const name = this.panelService.viewName(); |
|||
return context.view?.entityId && name && !context.view.title ? {...context, view: {...context.view, title: name}} : context; |
|||
} |
|||
const title = this.pageTitle(); |
|||
const path = this.pagePath(); |
|||
const type = aiPageView(path); |
|||
return title || path !== '/' ? {view: {type, title, path}, timeZone: getDefaultTimezone(), os: aiClientOs()} : undefined; |
|||
}); |
|||
|
|||
readonly welcome = computed(() => aiWelcome(this.clientContext()?.view, this.panelService.viewName(), this.panelService.config(), |
|||
this.translate)); |
|||
|
|||
private crumbLabel(crumb: BreadCrumb): string { |
|||
try { |
|||
return crumb.labelFunction ? crumb.labelFunction() : crumb.customTranslate ? this.utils.customTranslation(crumb.label, crumb.label) |
|||
: this.translate.instant(crumb.label); |
|||
} catch { |
|||
return ''; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,52 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core'; |
|||
|
|||
export interface AiCardAction { |
|||
id: string; |
|||
label: string; |
|||
icon?: string; |
|||
quiet?: boolean; |
|||
compose?: string; |
|||
pressed?: boolean; |
|||
tip?: string; |
|||
} |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-card-actions', |
|||
template: ` |
|||
@for (action of actions(); track action.id) { |
|||
<button type="button" class="ob-chip" [class.k-chip-quiet]="action.quiet" [class.k-chip-compose]="!!action.compose" |
|||
[attr.aria-pressed]="action.pressed ?? null" |
|||
[matTooltip]="action.tip ?? ''" [matTooltipDisabled]="!action.tip" matTooltipPosition="above" |
|||
(click)="press(action)"> |
|||
@if (action.icon) { |
|||
<mat-icon aria-hidden="true">{{ action.icon }}</mat-icon> |
|||
} |
|||
{{ action.label }} |
|||
</button> |
|||
} |
|||
`,
|
|||
standalone: false, |
|||
changeDetection: ChangeDetectionStrategy.OnPush, |
|||
host: { |
|||
'class': 'k-chips', |
|||
'role': 'group' |
|||
} |
|||
}) |
|||
export class AiCardActionsComponent { |
|||
|
|||
actions = input.required<AiCardAction[]>(); |
|||
|
|||
act = output<string>(); |
|||
|
|||
compose = output<string>(); |
|||
|
|||
press(action: AiCardAction): void { |
|||
if (action.compose) { |
|||
this.compose.emit(action.compose); |
|||
} else { |
|||
this.act.emit(action.id); |
|||
} |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,56 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { WritableSignal } from '@angular/core'; |
|||
import { Observable } from 'rxjs'; |
|||
import { AnswerRatingEvent, AnswerReportEvent } from '@home/components/ai/ai-chat-messages.component'; |
|||
import { AnswerFeedback, AnswerRating } from '@shared/models/ai-chat.models'; |
|||
|
|||
const END_IN_VIEW = 160; |
|||
|
|||
export interface AiLogScrollState { |
|||
scrolled: WritableSignal<boolean>; |
|||
atEnd: WritableSignal<boolean>; |
|||
newTurns: WritableSignal<number>; |
|||
} |
|||
|
|||
export function aiTrackLogScroll(area: HTMLElement, state: AiLogScrollState, reachedEnd: () => void): void { |
|||
const scrolled = area.scrollTop > 0; |
|||
if (scrolled !== state.scrolled()) { |
|||
state.scrolled.set(scrolled); |
|||
} |
|||
const atEnd = area.scrollHeight - area.scrollTop - area.clientHeight < END_IN_VIEW; |
|||
if (atEnd !== state.atEnd()) { |
|||
state.atEnd.set(atEnd); |
|||
} |
|||
if (atEnd) { |
|||
state.newTurns.set(0); |
|||
reachedEnd(); |
|||
} |
|||
} |
|||
|
|||
export interface AiAnswerFeedback { |
|||
patch: (patch: {rating?: Exclude<AnswerRating, 'NONE'>; reported?: boolean}) => void; |
|||
send: (feedback: Omit<AnswerFeedback, 'answer'>) => Observable<void>; |
|||
failed: () => void; |
|||
} |
|||
|
|||
export function aiRateAnswer(event: AnswerRatingEvent, before: Exclude<AnswerRating, 'NONE'> | undefined, feedback: AiAnswerFeedback): void { |
|||
feedback.patch({rating: event.rating === 'NONE' ? undefined : event.rating}); |
|||
feedback.send({rating: event.rating}).subscribe({ |
|||
error: () => { |
|||
feedback.patch({rating: before}); |
|||
feedback.failed(); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
export function aiReportAnswer(event: AnswerReportEvent, feedback: AiAnswerFeedback, reported: () => void): void { |
|||
feedback.patch({reported: true}); |
|||
feedback.send({problem: event.problem, comment: event.comment}).subscribe({ |
|||
next: () => reported(), |
|||
error: () => { |
|||
feedback.patch({reported: false}); |
|||
feedback.failed(); |
|||
} |
|||
}); |
|||
} |
|||
@ -0,0 +1,49 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
@if (title(); as name) { |
|||
@if (renaming()) { |
|||
<span class="ai-chat-renaming"> |
|||
<input #titleInput class="ai-chat-rename" [class.compact]="compact()" [value]="name" |
|||
[attr.aria-label]="'ai-assistant.chat-title' | translate" |
|||
(keydown)="onRenameKeydown($event)" (blur)="finishRename(titleInput.value)"> |
|||
<button type="button" class="ai-ib" [attr.aria-label]="'ai-assistant.rename-save' | translate" |
|||
[matTooltip]="'ai-assistant.rename-save' | translate" matTooltipPosition="above" |
|||
(mousedown)="$event.preventDefault()" (click)="finishRename(titleInput.value)"> |
|||
<mat-icon>check</mat-icon> |
|||
</button> |
|||
<button type="button" class="ai-ib" [attr.aria-label]="'ai-assistant.rename-discard' | translate" |
|||
[matTooltip]="'ai-assistant.rename-discard' | translate" matTooltipPosition="above" |
|||
(mousedown)="$event.preventDefault()" (click)="cancelRename()"> |
|||
<mat-icon>close</mat-icon> |
|||
</button> |
|||
</span> |
|||
} @else { |
|||
<span class="ai-chat-name-wrap" [class.static]="!renamable()"> |
|||
<button #chatName type="button" class="ai-chat-name" [class.clipped]="nameClipped()" [class.compact]="compact()" |
|||
[matTooltip]="nameClipped() ? name : renamable() ? ('ai-assistant.double-click-to-rename' | translate) : ''" |
|||
[matTooltipDisabled]="!nameClipped() && !renamable()" |
|||
matTooltipPosition="after" matTooltipPositionAtOrigin matTooltipClass="tb-ai-cursor-tooltip" matTooltipShowDelay="500" |
|||
(mouseenter)="nameClipped.set(chatName.scrollWidth > chatName.clientWidth + 1)" |
|||
(keydown.enter)="startRename()" (keydown.f2)="startRename()" (dblclick)="startRename()">{{ name }}</button> |
|||
@if (renamable()) { |
|||
<button type="button" class="ai-chat-name-pen" [attr.aria-label]="'action.rename' | translate" |
|||
[matTooltip]="'action.rename' | translate" matTooltipPosition="above" (click)="startRename()"> |
|||
<mat-icon fontSet="material-icons-round">edit</mat-icon> |
|||
</button> |
|||
} |
|||
</span> |
|||
@if (level(); as current) { |
|||
<span class="ai-chat-status" [class]="'ai-chat-status ' + current" |
|||
[matTooltip]="statusTip()" [matTooltipDisabled]="!statusTip()" matTooltipPosition="below"> |
|||
<span class="tb-ai-status-mark" [class]="'tb-ai-status-mark ' + current"></span> |
|||
<span>{{ ('ai-assistant.status-' + current) | translate }}</span> |
|||
</span> |
|||
} |
|||
} |
|||
} @else { |
|||
<span class="ai-chat-name" [class.compact]="compact()">{{ placeholder() }}</span> |
|||
} |
|||
@ -0,0 +1,144 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
@use './ai-icon-button' as *; |
|||
:host { |
|||
display: contents; |
|||
} |
|||
|
|||
.ai-chat-name-wrap { |
|||
position: relative; |
|||
padding-right: 28px; |
|||
display: inline-flex; |
|||
align-items: center; |
|||
flex: 0 1 auto; |
|||
min-width: 0; |
|||
|
|||
&:hover .ai-chat-name-pen, &:focus-within .ai-chat-name-pen { |
|||
opacity: 1; |
|||
} |
|||
} |
|||
|
|||
.ai-chat-name { |
|||
flex: 0 1 auto; |
|||
min-width: 0; |
|||
overflow: hidden; |
|||
white-space: nowrap; |
|||
padding: 0; |
|||
border: 0; |
|||
background: none; |
|||
font: 500 15px/20px var(--tb-font); |
|||
letter-spacing: normal; |
|||
text-align: left; |
|||
color: var(--tb-ink); |
|||
cursor: default; |
|||
|
|||
&.clipped { |
|||
mask-image: linear-gradient(90deg, #000 calc(100% - 44px), transparent calc(100% - 8px)); |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--ai-focus); |
|||
outline-offset: 2px; |
|||
border-radius: 4px; |
|||
} |
|||
} |
|||
|
|||
.ai-chat-name-pen { |
|||
position: absolute; |
|||
right: 0; |
|||
width: 24px; |
|||
height: 24px; |
|||
padding: 0; |
|||
border: 0; |
|||
border-radius: 6px; |
|||
background: transparent; |
|||
color: var(--tb-ink-60); |
|||
display: inline-flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
opacity: 0; |
|||
cursor: pointer; |
|||
transition: opacity .12s ease; |
|||
|
|||
.mat-icon { |
|||
width: 18px; |
|||
height: 18px; |
|||
font-size: 18px; |
|||
} |
|||
|
|||
&:hover { |
|||
background: rgba(0, 0, 0, 0.06); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
&:focus-visible { |
|||
opacity: 1; |
|||
outline: 2px solid var(--ai-focus); |
|||
outline-offset: 1px; |
|||
} |
|||
} |
|||
|
|||
.ai-chat-renaming { |
|||
display: inline-flex; |
|||
align-items: center; |
|||
gap: 2px; |
|||
flex: 1; |
|||
min-width: 0; |
|||
max-width: 480px; |
|||
} |
|||
|
|||
.ai-chat-name.compact { |
|||
font-size: var(--chat-line); |
|||
line-height: 18px; |
|||
} |
|||
|
|||
.ai-chat-status { |
|||
flex: none; |
|||
margin-left: auto; |
|||
display: inline-flex; |
|||
align-items: center; |
|||
gap: 6px; |
|||
font: 400 12.5px/20px var(--tb-font); |
|||
color: var(--tb-ink-54); |
|||
white-space: nowrap; |
|||
|
|||
&.error { |
|||
color: var(--tb-crit); |
|||
} |
|||
|
|||
.tb-ai-status-mark { |
|||
width: 10px; |
|||
height: 10px; |
|||
|
|||
&.running::before { |
|||
width: 8px; |
|||
height: 8px; |
|||
border-width: 1.5px; |
|||
} |
|||
} |
|||
} |
|||
|
|||
.ai-chat-rename { |
|||
flex: 1; |
|||
min-width: 0; |
|||
height: 28px; |
|||
box-sizing: border-box; |
|||
padding: 0; |
|||
border: 0; |
|||
border-bottom: 1.5px solid var(--tb-primary-500); |
|||
border-radius: 0; |
|||
outline: 0; |
|||
background: none; |
|||
font: 500 15px/20px var(--tb-font); |
|||
letter-spacing: normal; |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
|
|||
.ai-chat-name-wrap.static { |
|||
padding-right: 0; |
|||
} |
|||
|
|||
.ai-ib { |
|||
@include ai-icon-button; |
|||
} |
|||
@ -0,0 +1,67 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { Component, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; |
|||
import { ChatLevel } from '@shared/models/ai-chat.models'; |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-chat-title', |
|||
templateUrl: './ai-chat-title.component.html', |
|||
styleUrls: ['./ai-chat-title.component.scss'], |
|||
standalone: false |
|||
}) |
|||
export class AiChatTitleComponent { |
|||
|
|||
title = input<string | null | undefined>(null); |
|||
placeholder = input(''); |
|||
level = input<ChatLevel | null>(null); |
|||
statusTip = input(''); |
|||
renamable = input(true); |
|||
compact = input(false); |
|||
|
|||
@Output() renamed = new EventEmitter<string>(); |
|||
|
|||
private host = inject<ElementRef<HTMLElement>>(ElementRef); |
|||
|
|||
renaming = signal(false); |
|||
nameClipped = signal(false); |
|||
|
|||
startRename(): void { |
|||
if (!this.title() || !this.renamable()) { |
|||
return; |
|||
} |
|||
this.renaming.set(true); |
|||
setTimeout(() => { |
|||
const field = this.host.nativeElement.querySelector<HTMLInputElement>('.ai-chat-rename'); |
|||
field?.focus(); |
|||
field?.select(); |
|||
}); |
|||
} |
|||
|
|||
cancelRename(): void { |
|||
this.renaming.set(false); |
|||
} |
|||
|
|||
onRenameKeydown(event: KeyboardEvent): void { |
|||
if (event.isComposing) { |
|||
return; |
|||
} |
|||
if (event.key === 'Enter') { |
|||
event.preventDefault(); |
|||
this.finishRename((event.target as HTMLInputElement).value); |
|||
} else if (event.key === 'Escape') { |
|||
event.stopPropagation(); |
|||
this.renaming.set(false); |
|||
} |
|||
} |
|||
|
|||
finishRename(value: string): void { |
|||
if (!this.renaming()) { |
|||
return; |
|||
} |
|||
this.renaming.set(false); |
|||
const title = value.trim(); |
|||
if (title && title !== this.title()) { |
|||
this.renamed.emit(title); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,480 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
<div class="art-cols" [class.with-pane]="!!shownFile() && fileOpen()" [class.narrow]="docked()"> |
|||
<div class="ai-chat-col"> |
|||
<header class="ai-chat-head" [class.scrolled]="scrolled()" tb-fullscreen [fullscreenElement]="hostElement" [fullscreen]="fullscreen()" |
|||
(fullscreenChanged)="onFullscreenChanged($event)"> |
|||
<ng-content select="[aiChatLead]"></ng-content> |
|||
@if (variant() === 'panel') { |
|||
<tb-ai-mark size="32"></tb-ai-mark> |
|||
} |
|||
<tb-ai-chat-title [title]="chat()?.title" [placeholder]="historyLoading() ? '' : ((showGetStarted() ? 'ai-assistant.get-started.title' : 'ai-assistant.new-chat') | translate)" [level]="level()" |
|||
[statusTip]="statusTip()" [compact]="variant() === 'panel'" (renamed)="rename($event)"></tb-ai-chat-title> |
|||
<div class="ai-chat-actions"> |
|||
@if (chatFiles().length && !titleRef?.renaming()) { |
|||
<button type="button" class="ai-ib art-files-btn" [class.shown]="!!shownFile() && fileOpen()" [matMenuTriggerFor]="filesMenu" |
|||
(menuClosed)="unlisting.set(null)" |
|||
[matTooltip]="'ai-assistant.file.files' | translate" matTooltipPosition="above" |
|||
[attr.aria-label]="'ai-assistant.file.files-in-chat' | translate: {count: chatFiles().length}"> |
|||
<span class="art-files-ic" aria-hidden="true"><svg viewBox="0 0 24 24" focusable="false"><path d="M4 8.6A1.6 1.6 0 0 1 5.6 7h6.2l3.7 3.7v8.7a1.6 1.6 0 0 1-1.6 1.6H5.6A1.6 1.6 0 0 1 4 19.4Z"/><path d="M11.6 7v2.5a1.2 1.2 0 0 0 1.2 1.2h2.7"/><path d="M8.5 7V4.6A1.6 1.6 0 0 1 10.1 3h6.2L20 6.7v8.7a1.6 1.6 0 0 1-1.6 1.6h-2.9"/></svg></span> |
|||
<span class="art-files-n">{{ chatFiles().length }}</span> |
|||
</button> |
|||
} |
|||
@if (variant() === 'panel') { |
|||
@if (!titleRef?.renaming()) { |
|||
<button type="button" class="ai-ib more" [matMenuTriggerFor]="panelMenu" |
|||
[matTooltip]="'ai-assistant.chats-menu' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.chats-menu' | translate"> |
|||
<mat-icon>more_vert</mat-icon> |
|||
</button> |
|||
<button type="button" class="ai-ib" (click)="toggleFullscreen()" |
|||
[matTooltip]="(fullscreen() ? 'fullscreen.exit' : 'ai-assistant.open-full-screen') | translate" matTooltipPosition="above" |
|||
[attr.aria-label]="(fullscreen() ? 'fullscreen.exit' : 'ai-assistant.open-full-screen') | translate"> |
|||
<mat-icon fontSet="material-icons-round">{{ fullscreen() ? 'fullscreen_exit' : 'fullscreen' }}</mat-icon> |
|||
</button> |
|||
@if (!fullscreen()) { |
|||
<button type="button" class="ai-ib" (click)="closed.emit()" |
|||
[matTooltip]="'action.close' | translate" matTooltipPosition="above" [attr.aria-label]="'action.close' | translate"> |
|||
<mat-icon fontSet="material-icons-round">close</mat-icon> |
|||
</button> |
|||
} |
|||
} |
|||
} @else if (chat() && !titleRef?.renaming()) { |
|||
<button type="button" class="ai-ib more" [matMenuTriggerFor]="chatMenu" |
|||
[matTooltip]="'action.more' | translate" matTooltipPosition="above" [attr.aria-label]="'action.more' | translate"> |
|||
<mat-icon>more_vert</mat-icon> |
|||
</button> |
|||
} |
|||
<ng-content select="[aiChatActions]"></ng-content> |
|||
@if (showGetStarted()) { |
|||
<button type="button" class="ai-tour-link" (click)="takeTour.emit()"> |
|||
<mat-icon fontSet="material-icons-round" aria-hidden="true">tour</mat-icon> |
|||
<span>{{ 'ai-assistant.get-started.take-tour' | translate }}</span> |
|||
</button> |
|||
} |
|||
@if (fullscreenEnabled()) { |
|||
<button type="button" class="ai-ib" (click)="toggleFullscreen()" |
|||
[matTooltip]="(fullscreen() ? 'fullscreen.exit' : 'fullscreen.expand') | translate" matTooltipPosition="above" |
|||
[attr.aria-label]="(fullscreen() ? 'fullscreen.exit' : 'fullscreen.expand') | translate"> |
|||
<mat-icon fontSet="material-icons-round">{{ fullscreen() ? 'fullscreen_exit' : 'fullscreen' }}</mat-icon> |
|||
</button> |
|||
} |
|||
</div> |
|||
</header> |
|||
<div tb-toast [toastTarget]="toastTarget()" class="pointer-events-none absolute inset-0"></div> |
|||
<div #chatArea class="ai-chat-body" [class.empty]="!messages().length && !loading() && !historyLoading()" (scroll)="onLogScroll(chatArea)"> |
|||
@if (messages().length || loading()) { |
|||
<tb-ai-chat-messages |
|||
class="ai-chat-log" |
|||
[messages]="messages()" |
|||
[loading]="loading()" |
|||
[completedExecutions]="completedExecutions()" |
|||
[autoApprove]="autoApprove()" |
|||
[additionalStyles]="markdownStyles" |
|||
[scrollContainer]="chatArea" |
|||
initialScroll="bottom" |
|||
[denyReasons]="denyReasons()" |
|||
[work]="work()" |
|||
(approvalAction)="onApprovalAction($event)" |
|||
(askAgain)="onAskAgain()" |
|||
[feedback]="!!chatId()" |
|||
(rate)="onRate($event)" |
|||
(report)="onReport($event)" |
|||
(resume)="resume()" |
|||
(autoApproveRest)="setAutoApprove(true)" |
|||
(runPlan)="runPlan($event)" |
|||
(changePlan)="changePlan()" |
|||
[shownFile]="fileOpen() ? (shownFile()?.executionId ?? null) : null" |
|||
[ghostFirst]="true" |
|||
(openFile)="showFile($event)" |
|||
(prompt)="ask($event)" |
|||
(stopRun)="stop()" |
|||
(compose)="composeText($event)" |
|||
(answer)="ask($event.message, $event.secrets)" |
|||
(editMessage)="promptInput?.setValue($event)"> |
|||
</tb-ai-chat-messages> |
|||
} @else if (historyLoading()) { |
|||
<div class="ai-chat-loading" role="status"> |
|||
<tb-ai-spin kind="think"></tb-ai-spin> |
|||
<span>{{ 'ai-assistant.loading-chat' | translate }}</span> |
|||
</div> |
|||
} @else if (!chatId() && docked()) { |
|||
<div class="k-newchat"> |
|||
<tb-ai-mark size="44"></tb-ai-mark> |
|||
<h3>{{ startTitle() || ('ai-assistant.panel-title' | translate) }}</h3> |
|||
<p>{{ startLine() || ('ai-assistant.panel-line' | translate) }}</p> |
|||
@if (prompts().length) { |
|||
<div class="prompts" role="list"> |
|||
@for (example of prompts(); track example.message) { |
|||
<button type="button" class="prompt" role="listitem" (click)="ask(example.message)"> |
|||
<mat-icon fontSet="material-icons-round" aria-hidden="true">chat_bubble_outline</mat-icon> |
|||
<span>{{ example.label }}</span> |
|||
<mat-icon fontSet="material-icons-round" class="go" aria-hidden="true">arrow_upward</mat-icon> |
|||
</button> |
|||
} |
|||
</div> |
|||
} |
|||
</div> |
|||
} @else if (!chatId()) { |
|||
<div class="ai-chat-start"> |
|||
<tb-ai-mark size="64"></tb-ai-mark> |
|||
@if (variant() === 'panel') { |
|||
<h1 class="ai-chat-start-title">{{ startTitle() || ('ai-assistant.panel-title' | translate) }}</h1> |
|||
<p class="ai-chat-start-line">{{ startLine() || ('ai-assistant.panel-line' | translate) }}</p> |
|||
} @else { |
|||
<h1 class="ai-chat-start-title">{{ (showGetStarted() ? 'ai-assistant.get-started.heading' : 'ai-assistant.what-to-work-on') | translate }}</h1> |
|||
} |
|||
</div> |
|||
} |
|||
<div #composer class="ai-chat-composer"> |
|||
@if (pill(); as current) { |
|||
<button type="button" class="k-pill" [class.new]="current.mode === 'new'" |
|||
[matTooltip]="current.label" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.go-to-end' | translate" |
|||
(click)="goToEnd(chatArea)"> |
|||
@if (current.mode === 'new') { |
|||
<mat-icon class="tb-mat-18">arrow_downward</mat-icon>{{ current.count }} |
|||
} @else { |
|||
<tb-ai-spin [kind]="current.kind"></tb-ai-spin> |
|||
} |
|||
</button> |
|||
} |
|||
@if (creditsOut(); as limitType) { |
|||
<tb-ai-credits-out [limitType]="limitType" (dismissed)="creditsOut.set(null)"></tb-ai-credits-out> |
|||
} @else if (limitOut(); as platformLimit) { |
|||
<tb-ai-limit-out [platformLimit]="platformLimit" (dismissed)="limitOut.set(null)"></tb-ai-limit-out> |
|||
} @else if (notice(); as current) { |
|||
<div class="k-notice k-notice-edge" [class]="'k-notice k-notice-edge ' + (current.kind === 'block' ? 'blocking' : current.kind)" [attr.role]="current.kind === 'block' ? 'alert' : 'status'"> |
|||
<mat-icon aria-hidden="true">{{ current.icon }}</mat-icon><span>{{ current.text }}</span> |
|||
</div> |
|||
} |
|||
<tb-ai-prompt-input |
|||
[blocked]="notice()?.kind === 'block' || !!creditsOut()" |
|||
[docked]="docked()" |
|||
[placeholder]="placeholder()" |
|||
[suggestion]="suggestion()" |
|||
[quote]="composerQuote()" |
|||
(quoteRemoved)="composerQuote.set(null)" |
|||
[loading]="loading() && !waitingApproval()" |
|||
[dropZone]="chatArea" |
|||
[pinned]="!!messages().length || loading() || historyLoading()" |
|||
[showAutoApprove]="true" |
|||
[sendWhileWorking]="true" |
|||
[autoApprove]="autoApprove()" |
|||
[autoApproveInChat]="!!chatId()" |
|||
[stoppable]="!!chatId()" |
|||
[stopping]="stopping()" |
|||
(stopped)="stop()" |
|||
(autoApproveChange)="setAutoApprove($event)" |
|||
(messageSent)="sendMsgFromUser($event)"> |
|||
</tb-ai-prompt-input> |
|||
</div> |
|||
@if (variant() === 'panel' && !docked() && !chatId() && !messages().length && !loading() && prompts().length) { |
|||
<section class="ai-sec k-prompts" [attr.aria-label]="'ai-assistant.start-a-task' | translate"> |
|||
<div class="prompts" role="list"> |
|||
@for (example of prompts(); track example.message) { |
|||
<button type="button" class="prompt" role="listitem" (click)="ask(example.message)"> |
|||
<mat-icon fontSet="material-icons-round" aria-hidden="true">chat_bubble_outline</mat-icon> |
|||
<span>{{ example.label }}</span> |
|||
<mat-icon fontSet="material-icons-round" class="go" aria-hidden="true">arrow_upward</mat-icon> |
|||
</button> |
|||
} |
|||
</div> |
|||
</section> |
|||
} |
|||
@if (showGetStarted() && !messages().length && !loading()) { |
|||
<section class="ai-sec ai-sec-lg" aria-labelledby="ai-sec-examples"> |
|||
<div class="ai-sec-head"> |
|||
<h2 id="ai-sec-examples">{{ 'ai-assistant.get-started.examples' | translate }}</h2> |
|||
<p>{{ 'ai-assistant.get-started.examples-hint' | translate }}</p> |
|||
</div> |
|||
<div class="k-pcards"> |
|||
@for (example of examples; track example.key) { |
|||
<button type="button" class="k-pcard" (click)="startExample(example)"> |
|||
<span class="k-pcard-tile"><mat-icon fontSet="material-icons-round" aria-hidden="true">{{ example.icon }}</mat-icon></span> |
|||
<span class="k-pcard-body"> |
|||
<b>{{ ('ai-assistant.get-started.example.' + example.key + '.title') | translate }}</b> |
|||
<span>{{ ('ai-assistant.get-started.example.' + example.key + '.what') | translate }}</span> |
|||
</span> |
|||
</button> |
|||
} |
|||
</div> |
|||
</section> |
|||
<section class="ai-cli-band" aria-labelledby="ai-cli-band-h"> |
|||
<span class="ai-cli-band-tile" aria-hidden="true"><mat-icon fontSet="material-icons-round">terminal</mat-icon></span> |
|||
<div class="ai-cli-band-text"> |
|||
<h2 id="ai-cli-band-h">{{ 'ai-assistant.cli.band.heading' | translate }}</h2> |
|||
<p>{{ 'ai-assistant.cli.band.line' | translate }}</p> |
|||
</div> |
|||
<button type="button" class="ai-cli-band-btn" (click)="openCli.emit()"> |
|||
<span>{{ 'ai-assistant.cli.band.action' | translate }}</span> |
|||
<mat-icon fontSet="material-icons-round" aria-hidden="true">arrow_forward</mat-icon> |
|||
</button> |
|||
</section> |
|||
} |
|||
@if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) { |
|||
<section class="ai-sec" aria-labelledby="ai-sec-tasks"> |
|||
<div class="ai-sec-head"><h2 id="ai-sec-tasks">{{ 'ai-assistant.start-a-task' | translate }}</h2></div> |
|||
<div class="ai-tasks"> |
|||
@for (task of tasks; track task) { |
|||
<button type="button" class="ai-task" (click)="startTask(task)"> |
|||
<b>{{ ('ai-assistant.task.' + task + '.title') | translate }}</b> |
|||
<small>{{ ('ai-assistant.task.' + task + '.hint') | translate }}</small> |
|||
<mat-icon fontSet="material-icons-round" aria-hidden="true">chevron_right</mat-icon> |
|||
</button> |
|||
} |
|||
</div> |
|||
</section> |
|||
} |
|||
@if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) { |
|||
<button type="button" class="ai-sol-card" (click)="newSolution.emit()"> |
|||
<tb-ai-mark class="ai-sol-card-mark" size="44" icon="layers"></tb-ai-mark> |
|||
<span class="ai-sol-card-text"> |
|||
<b>{{ 'ai-assistant.create-solution' | translate }}</b> |
|||
<small>{{ 'ai-assistant.create-solution-hint' | translate }}</small> |
|||
</span> |
|||
<span class="ai-sol-card-go"> |
|||
<span class="ai-sol-card-go-t">{{ 'ai-assistant.create-solution-start' | translate }}</span> |
|||
<mat-icon fontSet="material-icons-round" aria-hidden="true">arrow_forward</mat-icon> |
|||
</span> |
|||
</button> |
|||
} |
|||
</div> |
|||
</div> |
|||
@if (shownFile(); as file) { |
|||
@if (fileOpen()) { |
|||
<tb-ai-artifact-pane [class.art-dark]="fileDark(file)" [dark]="fileCode(file)" (closed)="fileOpen.set(false)"> |
|||
<h2 artHead class="art-title" [matTooltip]="file.name" matTooltipPosition="below" [matTooltipShowDelay]="600"> |
|||
<mat-icon class="tb-mat-20" aria-hidden="true">{{ fileMark(file) }}</mat-icon> |
|||
<span class="art-name">{{ fileName(file.name).base }}<span class="art-ext">{{ fileName(file.name).ext }}</span></span> |
|||
</h2> |
|||
<div artHead class="art-head-r"> |
|||
@if (!file.previewed) { |
|||
<div class="art-tools"> |
|||
@if (!fileBody()?.editing()) { |
|||
<button type="button" class="art-tool icon-only" (click)="fileBody()?.openFind()" |
|||
[matTooltip]="'ai-assistant.file.find' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.find' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">search</mat-icon> |
|||
</button> |
|||
} |
|||
<button type="button" class="art-tool icon-only" [class.on]="fileWrap()" [attr.aria-pressed]="fileWrap()" (click)="toggleFileWrap()" |
|||
[matTooltip]="'ai-assistant.file.wrap' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.wrap' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">wrap_text</mat-icon> |
|||
</button> |
|||
<button type="button" class="art-tool icon-only" [matMenuTriggerFor]="fileOptions" |
|||
[matTooltip]="'ai-assistant.file.more' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.more' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">more_vert</mat-icon> |
|||
</button> |
|||
</div> |
|||
} |
|||
<div class="art-tools"> |
|||
<button type="button" class="art-tool icon-only art-copy" [class.copied]="fileCopied()" (click)="copyFile(file)" |
|||
[matTooltip]="(fileCopied() ? 'ai-assistant.copied' : 'ai-assistant.file.copy') | translate" matTooltipPosition="below" |
|||
[attr.aria-label]="'ai-assistant.file.copy' | translate"> |
|||
<mat-icon class="tb-mat-18 art-copy-ic" aria-hidden="true">content_copy</mat-icon> |
|||
<svg class="art-copy-ok" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12.5l4.2 4.2L19 7"/></svg> |
|||
</button> |
|||
<span class="tb-ai-sr-only" aria-live="polite">{{ fileCopied() ? ('ai-assistant.copied' | translate) : '' }}</span> |
|||
@if (file.image) { |
|||
<button type="button" class="art-tool icon-only" [matMenuTriggerFor]="imageDownloads" |
|||
[matTooltip]="'ai-assistant.file.download' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.download' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">download</mat-icon> |
|||
</button> |
|||
} @else { |
|||
<button type="button" class="art-tool icon-only" (click)="downloadFile(file)" |
|||
[matTooltip]="'ai-assistant.file.download' | translate" matTooltipPosition="below" [attr.aria-label]="'ai-assistant.file.download' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">download</mat-icon> |
|||
</button> |
|||
} |
|||
</div> |
|||
</div> |
|||
<tb-ai-file-body [file]="file" [wrap]="fileWrap()" [whitespace]="fileWhitespace()" [saver]="fileSaver" |
|||
[marks]="fileMarks()" (marksChange)="fileMarks.set($event)" (discarded)="onFileDiscarded($event)"></tb-ai-file-body> |
|||
<ng-container ngProjectAs="[artFoot]"> |
|||
@if (fileMarks(); as marks) { |
|||
<footer artFoot class="art-pane-foot art-marks"> |
|||
<span class="file-marked"> |
|||
<span class="file-marked-n">{{ (marks.from === marks.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: marks.from, to: marks.to} }}</span> |
|||
{{ 'ai-assistant.file.marked' | translate }} |
|||
</span> |
|||
<span class="art-spacer"></span> |
|||
<button mat-button type="button" (click)="fileMarks.set(null)">{{ 'ai-assistant.file.clear' | translate }}</button> |
|||
<button mat-stroked-button type="button" (click)="copyMarked(file)"><mat-icon>content_copy</mat-icon>{{ 'action.copy' | translate }}</button> |
|||
<button mat-flat-button type="button" class="art-ask" (click)="askAboutMarks(file)"><mat-icon>auto_awesome</mat-icon>{{ 'ai-assistant.file.ask-about' | translate }}</button> |
|||
</footer> |
|||
} @else { |
|||
<footer artFoot class="art-pane-foot file-bar"> |
|||
<span class="file-bar-info"> |
|||
@if (fileBody()?.editing()) { |
|||
@if (fileBody()?.dirty()) { |
|||
<span class="file-bar-state"><i class="file-bar-dot" aria-hidden="true"></i>{{ 'ai-assistant.file.unsaved' | translate }}</span> |
|||
} @else { |
|||
<span class="file-bar-state">{{ 'ai-assistant.file.editing' | translate }}</span> |
|||
} |
|||
@if (fileBody()?.caret(); as caret) { |
|||
<i class="file-bar-sep" aria-hidden="true">·</i> |
|||
<span class="file-bar-pos">{{ 'ai-assistant.file.position' | translate: {line: caret.line, col: caret.col} }}@if (caret.selected) { ({{ 'ai-assistant.file.selected' | translate: {count: caret.selected} }})}</span> |
|||
} |
|||
} @else if (fileBody()?.saved()) { |
|||
<span class="file-bar-saved"><mat-icon aria-hidden="true">check</mat-icon>{{ 'ai-assistant.file.saved' | translate }}</span> |
|||
} @else { |
|||
<span>{{ 'ai-assistant.file.lines' | translate: {count: file.lines} }}</span> |
|||
<i class="file-bar-sep" aria-hidden="true">·</i> |
|||
<span>{{ file.size }}</span> |
|||
@if (file.edited) { |
|||
<i class="file-bar-sep" aria-hidden="true">·</i> |
|||
<span class="file-bar-ed">{{ 'ai-assistant.file.edited-in-chat' | translate }}</span> |
|||
} |
|||
} |
|||
</span> |
|||
<span class="file-bar-acts"> |
|||
@if (fileBody()?.editing()) { |
|||
@if (fileBody()?.dirty()) { |
|||
<button mat-stroked-button type="button" class="file-bar-b" (click)="fileBody()?.discard()">{{ 'ai-assistant.file.discard' | translate }}</button> |
|||
<button mat-flat-button type="button" class="file-bar-b file-bar-save" [disabled]="loading() || fileBody()?.saving()" (click)="fileBody()?.save()"> |
|||
{{ 'ai-assistant.file.save' | translate }} |
|||
</button> |
|||
} @else { |
|||
<button mat-stroked-button type="button" class="file-bar-b" (click)="fileBody()?.done()">{{ 'ai-assistant.file.done' | translate }}</button> |
|||
} |
|||
} @else if (chatId()) { |
|||
<button mat-stroked-button type="button" class="file-bar-b" (click)="fileBody()?.startEdit()"> |
|||
<mat-icon>edit</mat-icon>{{ 'ai-assistant.file.edit' | translate }} |
|||
</button> |
|||
} |
|||
</span> |
|||
</footer> |
|||
} |
|||
</ng-container> |
|||
</tb-ai-artifact-pane> |
|||
<mat-menu #imageDownloads="matMenu" xPosition="before" class="tb-ai-chat-menu"> |
|||
<button mat-menu-item type="button" (click)="downloadFile(file)"> |
|||
<mat-icon fontSet="material-icons-round">image</mat-icon><span>{{ 'ai-assistant.file.download-svg' | translate }}</span> |
|||
</button> |
|||
<button mat-menu-item type="button" (click)="downloadFileAsPng(file)"> |
|||
<mat-icon fontSet="material-icons-round">photo</mat-icon><span>{{ 'ai-assistant.file.download-png' | translate }}</span> |
|||
</button> |
|||
</mat-menu> |
|||
<mat-menu #fileOptions="matMenu" xPosition="before" class="tb-ai-chat-menu art-opts"> |
|||
@if (!fileBody()?.editing()) { |
|||
<button mat-menu-item role="menuitemcheckbox" [attr.aria-checked]="fileWhitespace()" (click)="$event.stopPropagation(); toggleFileWhitespace()"> |
|||
<mat-icon fontSet="material-icons-round">space_bar</mat-icon> |
|||
<span class="art-opt-l">{{ 'ai-assistant.file.show-whitespace' | translate }}</span> |
|||
<span class="art-switch" [class.on]="fileWhitespace()" aria-hidden="true"><i></i></span> |
|||
</button> |
|||
} |
|||
<div class="art-opt-row" role="group" [attr.aria-label]="'ai-assistant.file.theme' | translate" (click)="$event.stopPropagation()"> |
|||
<mat-icon fontSet="material-icons-round" aria-hidden="true">contrast</mat-icon> |
|||
<span>{{ 'ai-assistant.file.theme' | translate }}</span> |
|||
<div class="art-modes art-opt-modes" role="radiogroup"> |
|||
<button type="button" role="radio" [attr.aria-checked]="fileTheme() === 'dark'" (click)="setFileTheme('dark')"> |
|||
<mat-icon class="tb-mat-16" aria-hidden="true">dark_mode</mat-icon><span>{{ 'ai-assistant.file.dark' | translate }}</span> |
|||
</button> |
|||
<button type="button" role="radio" [attr.aria-checked]="fileTheme() === 'light'" (click)="setFileTheme('light')"> |
|||
<mat-icon class="tb-mat-16" aria-hidden="true">light_mode</mat-icon><span>{{ 'ai-assistant.file.light' | translate }}</span> |
|||
</button> |
|||
</div> |
|||
</div> |
|||
</mat-menu> |
|||
} |
|||
} |
|||
</div> |
|||
|
|||
<mat-menu #panelMenu="matMenu" xPosition="before" class="tb-ai-chat-menu"> |
|||
@if (chat()) { |
|||
<button mat-menu-item (click)="startRename()"> |
|||
<mat-icon fontSet="material-icons-round">edit</mat-icon> |
|||
<span>{{ 'action.rename' | translate }}</span> |
|||
</button> |
|||
<button mat-menu-item (click)="newChat()"> |
|||
<mat-icon fontSet="material-icons-round">add</mat-icon> |
|||
<span>{{ 'ai-assistant.new-chat' | translate }}</span> |
|||
</button> |
|||
} |
|||
@if (docked() && (split() || splitAvailable())) { |
|||
<button mat-menu-item (click)="splitToggle.emit()"> |
|||
<mat-icon fontSet="material-icons-round">{{ split() ? 'view_sidebar' : 'vertical_split' }}</mat-icon> |
|||
<span>{{ (split() ? 'ai-assistant.back-to-panel' : 'ai-assistant.split-view') | translate }}</span> |
|||
</button> |
|||
} |
|||
@if (recentChats().length) { |
|||
<div class="tb-ai-menu-h">{{ 'ai-assistant.recent-chats' | translate }}</div> |
|||
@for (other of recentChats(); track other.id) { |
|||
<button mat-menu-item class="chat" (click)="chatId.set(other.id)"> |
|||
<mat-icon fontSet="material-icons-round">chat_bubble_outline</mat-icon> |
|||
<span class="tb-ai-menu-chat"> |
|||
<span class="t">{{ other.title }}</span> |
|||
@if (levelOf(other); as level) { |
|||
<span class="tb-ai-status-mark" [class]="'tb-ai-status-mark ' + level"></span> |
|||
} |
|||
</span> |
|||
</button> |
|||
} |
|||
} |
|||
<button mat-menu-item (click)="openAllChats()"> |
|||
<mat-icon fontSet="material-icons-round">forum</mat-icon> |
|||
<span>{{ 'ai-assistant.all-chats' | translate }}</span> |
|||
</button> |
|||
@if (chat()) { |
|||
<button mat-menu-item class="danger" (click)="deleteChat()"> |
|||
<mat-icon fontSet="material-icons-round">delete_outline</mat-icon> |
|||
<span>{{ 'action.delete' | translate }}</span> |
|||
</button> |
|||
} |
|||
</mat-menu> |
|||
|
|||
<mat-menu #chatMenu="matMenu" xPosition="before" class="tb-ai-chat-menu"> |
|||
<button mat-menu-item (click)="startRename()"> |
|||
<mat-icon fontSet="material-icons-round">edit</mat-icon> |
|||
<span>{{ 'action.rename' | translate }}</span> |
|||
</button> |
|||
<button mat-menu-item (click)="togglePinned()"> |
|||
<mat-icon fontSet="material-icons-round">push_pin</mat-icon> |
|||
<span>{{ (chat()?.pinned ? 'ai-assistant.unpin' : 'ai-assistant.pin') | translate }}</span> |
|||
</button> |
|||
<button mat-menu-item class="danger" (click)="deleteChat()"> |
|||
<mat-icon fontSet="material-icons-round">delete_outline</mat-icon> |
|||
<span>{{ 'action.delete' | translate }}</span> |
|||
</button> |
|||
</mat-menu> |
|||
|
|||
<mat-menu #filesMenu="matMenu" xPosition="before" class="tb-ai-chat-menu art-list"> |
|||
<div class="tb-ai-menu-h art-list-h">{{ 'ai-assistant.file.files-in-chat' | translate: {count: chatFiles().length} }}</div> |
|||
@for (entry of chatFiles(); track entry.file.name) { |
|||
@if (unlisting() === entry.file.name) { |
|||
<div class="art-list-confirm" (click)="$event.stopPropagation()" (keydown.escape)="keepListed($event)"> |
|||
<span class="art-list-ic"><mat-icon class="tb-mat-18" aria-hidden="true">{{ fileMark(entry.file) }}</mat-icon></span> |
|||
<span class="art-list-q"><b>{{ 'ai-assistant.file.unlist-ask' | translate }}</b> |
|||
<small><span class="art-name">{{ fileName(entry.file.name).base }}<span class="art-ext">{{ fileName(entry.file.name).ext }}</span></span></small></span> |
|||
<button type="button" class="art-list-no" (click)="keepListed($event)" |
|||
[matTooltip]="'ai-assistant.file.keep' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.file.keep' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">close</mat-icon> |
|||
</button> |
|||
<button type="button" class="art-list-yes" (click)="unlist(entry.file, $event)" |
|||
[matTooltip]="'ai-assistant.file.unlist-do' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.file.unlist-do' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">delete_outline</mat-icon> |
|||
</button> |
|||
</div> |
|||
} @else { |
|||
<div class="art-list-row"> |
|||
<button mat-menu-item type="button" class="art-list-item" [class.on]="isShownFile(entry.file)" role="menuitemradio" |
|||
[attr.aria-checked]="isShownFile(entry.file)" (click)="showFile(entry.file)" (keydown.delete)="askUnlist(entry.file, $event)"> |
|||
<span class="art-list-ic"><mat-icon class="tb-mat-18" aria-hidden="true">{{ fileMark(entry.file) }}</mat-icon></span> |
|||
<span class="art-list-t"><b><span class="art-name">{{ fileName(entry.file.name).base }}<span class="art-ext">{{ fileName(entry.file.name).ext }}</span></span></b></span> |
|||
@if (entry.running) { |
|||
<tb-ai-spin kind="gen"></tb-ai-spin> |
|||
} |
|||
@if (isShownFile(entry.file)) { |
|||
<mat-icon class="tb-mat-18 art-list-check" aria-hidden="true">check</mat-icon> |
|||
} |
|||
</button> |
|||
<button type="button" class="art-list-del" tabindex="-1" (click)="askUnlist(entry.file, $event)" |
|||
[matTooltip]="'ai-assistant.file.unlist' | translate" matTooltipPosition="above" [attr.aria-label]="'ai-assistant.file.unlist' | translate"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">delete_outline</mat-icon> |
|||
</button> |
|||
</div> |
|||
} |
|||
} |
|||
</mat-menu> |
|||
@ -0,0 +1,792 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
@use './ai-icon-button' as *; |
|||
:host { |
|||
position: relative; |
|||
display: flex; |
|||
flex-direction: column; |
|||
min-width: 0; |
|||
min-height: 0; |
|||
background: var(--tb-surface); |
|||
font-family: var(--tb-font); |
|||
font-size: var(--chat-line); |
|||
line-height: var(--chat-line-lh); |
|||
letter-spacing: var(--chat-text-ls); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
:host(.tb-fullscreen) { |
|||
margin: 0 !important; |
|||
border-radius: 0 !important; |
|||
box-shadow: none !important; |
|||
} |
|||
|
|||
.ai-chat-head { |
|||
position: relative; |
|||
flex: none; |
|||
display: flex; |
|||
align-items: center; |
|||
gap: 8px; |
|||
height: 48px; |
|||
box-sizing: border-box; |
|||
padding: 0 8px 0 16px; |
|||
border-bottom: 1px solid rgba(0, 0, 0, 0.06); |
|||
|
|||
@media (max-width: 599px) { |
|||
padding: 0 4px 0 8px; |
|||
} |
|||
} |
|||
|
|||
.ai-chat-head::after { |
|||
content: ''; |
|||
position: absolute; |
|||
left: 0; |
|||
right: 0; |
|||
top: 100%; |
|||
z-index: 3; |
|||
height: 12px; |
|||
background: linear-gradient(to bottom, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); |
|||
opacity: 0; |
|||
transition: opacity .15s ease; |
|||
pointer-events: none; |
|||
} |
|||
|
|||
.ai-chat-head.scrolled::after { |
|||
opacity: 1; |
|||
} |
|||
|
|||
:host(.v-panel) .ai-chat-head { |
|||
height: 56px; |
|||
gap: 10px; |
|||
padding: 0 8px 0 12px; |
|||
border-bottom-color: rgba(0, 0, 0, 0.08); |
|||
} |
|||
|
|||
tb-ai-chat-title:has(.ai-chat-status) + .ai-chat-actions { |
|||
margin-left: 0; |
|||
} |
|||
|
|||
.ai-chat-actions { |
|||
flex: none; |
|||
margin-left: auto; |
|||
display: flex; |
|||
align-items: center; |
|||
gap: 2px; |
|||
} |
|||
|
|||
:host ::ng-deep .ai-ib { |
|||
@include ai-icon-button; |
|||
|
|||
&.more .mat-icon { |
|||
font-size: 20px; |
|||
width: 20px; |
|||
height: 20px; |
|||
} |
|||
} |
|||
|
|||
:host(.v-panel) ::ng-deep .ai-ib { |
|||
width: 28px; |
|||
height: 28px; |
|||
} |
|||
|
|||
.ai-chat-body { |
|||
position: relative; |
|||
flex: 1; |
|||
min-height: 0; |
|||
display: flex; |
|||
flex-direction: column; |
|||
align-items: center; |
|||
overflow-x: hidden; |
|||
overflow-y: auto; |
|||
padding: 20px 20px 0; |
|||
container: k-chat / inline-size; |
|||
|
|||
&.empty { |
|||
justify-content: flex-start; |
|||
padding-top: 64px; |
|||
padding-bottom: 24px; |
|||
} |
|||
} |
|||
|
|||
:host(.v-panel) .ai-chat-body { |
|||
padding: 12px 12px 0; |
|||
|
|||
&.empty { |
|||
padding-top: 0; |
|||
padding-bottom: 0; |
|||
} |
|||
} |
|||
|
|||
.ai-chat-log { |
|||
flex: 1 0 auto; |
|||
width: 100%; |
|||
max-width: 760px; |
|||
margin: 4px 0 24px; |
|||
overflow: visible; |
|||
|
|||
@container k-chat (min-width: 900px) { |
|||
max-width: 712px; |
|||
} |
|||
} |
|||
|
|||
.k-newchat, .k-prompts { |
|||
.prompts { |
|||
align-self: stretch; |
|||
display: flex; |
|||
flex-direction: column; |
|||
border-top: 1px solid var(--tb-line); |
|||
} |
|||
|
|||
.prompt { |
|||
display: flex; |
|||
align-items: center; |
|||
gap: 12px; |
|||
min-height: 44px; |
|||
padding: 0 8px; |
|||
border: 0; |
|||
border-bottom: 1px solid var(--tb-line); |
|||
background: none; |
|||
font: 400 14px/20px var(--tb-font); |
|||
color: var(--tb-ink); |
|||
text-align: left; |
|||
cursor: pointer; |
|||
transition: background .12s ease; |
|||
|
|||
> .mat-icon { |
|||
flex: none; |
|||
font-size: 18px; |
|||
width: 18px; |
|||
height: 18px; |
|||
color: var(--tb-ink-54); |
|||
} |
|||
|
|||
> span { |
|||
flex: 1; |
|||
min-width: 0; |
|||
} |
|||
|
|||
.go { |
|||
font-size: 16px; |
|||
width: 16px; |
|||
height: 16px; |
|||
color: var(--tb-ink); |
|||
opacity: 0; |
|||
transform: translateY(2px); |
|||
transition: opacity .12s ease, transform .12s ease; |
|||
} |
|||
|
|||
&:hover, &:focus-visible { |
|||
background: rgba(0, 0, 0, .035); |
|||
outline: none; |
|||
|
|||
.go { |
|||
opacity: .7; |
|||
transform: none; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
|
|||
.k-newchat { |
|||
flex: 1 0 auto; |
|||
align-self: stretch; |
|||
margin: auto 0; |
|||
padding: 24px 6px 12px; |
|||
display: flex; |
|||
flex-direction: column; |
|||
align-items: center; |
|||
justify-content: center; |
|||
text-align: center; |
|||
|
|||
h3 { |
|||
margin: 14px 0 4px; |
|||
font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); |
|||
letter-spacing: 0; |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
p { |
|||
margin: 0 0 20px; |
|||
max-width: 300px; |
|||
font-size: var(--chat-line); |
|||
line-height: var(--chat-line-lh); |
|||
color: var(--tb-ink-54); |
|||
} |
|||
} |
|||
|
|||
.ai-chat-start { |
|||
display: flex; |
|||
flex-direction: column; |
|||
align-items: center; |
|||
gap: 12px; |
|||
text-align: center; |
|||
} |
|||
|
|||
.ai-chat-start-title { |
|||
margin: 0; |
|||
font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); |
|||
letter-spacing: 0; |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
.ai-chat-composer { |
|||
position: sticky; |
|||
bottom: 0; |
|||
z-index: 1; |
|||
flex: none; |
|||
width: 100%; |
|||
max-width: 760px; |
|||
padding: 12px 0 14px; |
|||
background: linear-gradient(color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 40%); |
|||
} |
|||
|
|||
.ai-chat-body:not(.empty) .ai-chat-composer ::ng-deep .composer-field:not(:focus-within) { |
|||
border-color: var(--tb-line); |
|||
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 10px 28px rgba(16, 24, 40, 0.10); |
|||
} |
|||
|
|||
.ai-sec { |
|||
width: 100%; |
|||
max-width: 680px; |
|||
margin-top: 16px; |
|||
text-align: left; |
|||
} |
|||
|
|||
.ai-sec-head h2 { |
|||
margin: 0; |
|||
font: 500 14px/20px var(--tb-font); |
|||
letter-spacing: normal; |
|||
color: var(--tb-text-secondary); |
|||
} |
|||
|
|||
.ai-tasks { |
|||
margin-top: 8px; |
|||
border-radius: 12px; |
|||
background: var(--tb-surface); |
|||
box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.03), 0 1px 2px rgba(16, 24, 40, 0.06), 0 2px 10px rgba(16, 24, 40, 0.06); |
|||
} |
|||
|
|||
.ai-task { |
|||
display: grid; |
|||
grid-template-columns: minmax(0, 1fr) auto 20px; |
|||
align-items: center; |
|||
gap: 12px; |
|||
width: 100%; |
|||
min-height: 44px; |
|||
padding: 0 10px 0 16px; |
|||
border: 0; |
|||
background: none; |
|||
font: 400 14px/20px var(--tb-font); |
|||
letter-spacing: normal; |
|||
text-align: left; |
|||
color: var(--tb-ink); |
|||
cursor: pointer; |
|||
transition: background-color .12s ease; |
|||
|
|||
& + .ai-task { |
|||
border-top: 1px solid rgba(0, 0, 0, 0.06); |
|||
} |
|||
|
|||
&:first-child { |
|||
border-radius: 12px 12px 0 0; |
|||
} |
|||
|
|||
&:last-child { |
|||
border-radius: 0 0 12px 12px; |
|||
} |
|||
|
|||
&:hover { |
|||
background: rgba(0, 0, 0, 0.03); |
|||
|
|||
.mat-icon { |
|||
color: var(--tb-ink); |
|||
transform: translateX(2px); |
|||
} |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 0; |
|||
box-shadow: inset 0 0 0 2px var(--ai-focus); |
|||
} |
|||
|
|||
b { |
|||
min-width: 0; |
|||
overflow: hidden; |
|||
font-weight: 400; |
|||
text-overflow: ellipsis; |
|||
white-space: nowrap; |
|||
} |
|||
|
|||
small { |
|||
max-width: 280px; |
|||
overflow: hidden; |
|||
font-size: 12.5px; |
|||
line-height: 18px; |
|||
color: var(--tb-ink-76); |
|||
text-overflow: ellipsis; |
|||
white-space: nowrap; |
|||
|
|||
@media (max-width: 599px) { |
|||
display: none; |
|||
} |
|||
} |
|||
|
|||
.mat-icon { |
|||
width: 20px; |
|||
height: 20px; |
|||
font-size: 20px; |
|||
color: var(--tb-ink-38); |
|||
transition: transform .15s ease, color .15s ease; |
|||
} |
|||
|
|||
@media (prefers-reduced-motion: reduce) { |
|||
transition: none; |
|||
|
|||
.mat-icon { |
|||
transition: none; |
|||
} |
|||
} |
|||
} |
|||
|
|||
.ai-chat-body.empty .ai-chat-composer { |
|||
position: static; |
|||
max-width: 680px; |
|||
padding-top: 20px; |
|||
background: none; |
|||
} |
|||
|
|||
@media (max-width: 599px) { |
|||
.ai-chat-body { |
|||
padding: 16px 16px 0; |
|||
} |
|||
} |
|||
|
|||
:host(.v-panel) .ai-chat-composer, |
|||
:host(.v-panel) .ai-chat-body.empty .ai-chat-composer { |
|||
position: sticky; |
|||
width: auto; |
|||
max-width: none; |
|||
align-self: stretch; |
|||
margin: 0 -12px; |
|||
padding: 0; |
|||
background: var(--tb-surface); |
|||
} |
|||
|
|||
.ai-chat-start-line { |
|||
margin: -4px 0 0; |
|||
max-width: 420px; |
|||
font-size: var(--chat-line); |
|||
line-height: var(--chat-line-lh); |
|||
color: var(--tb-ink-54); |
|||
} |
|||
|
|||
.ai-chat-col { |
|||
position: relative; |
|||
flex: 1 1 0; |
|||
min-width: 0; |
|||
min-height: 0; |
|||
display: flex; |
|||
flex-direction: column; |
|||
} |
|||
|
|||
.art-cols.with-pane:not(.narrow) .ai-chat-col { |
|||
min-width: var(--chat-col-min, 340px); |
|||
} |
|||
|
|||
:host ::ng-deep .ai-ib.art-files-btn { |
|||
width: auto; |
|||
gap: 4px; |
|||
padding: 0 9px 0 8px; |
|||
border-radius: 10px; |
|||
color: var(--tb-ink-76); |
|||
|
|||
&:hover { |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
&.shown, &[aria-expanded="true"] { |
|||
color: var(--ai-action); |
|||
} |
|||
|
|||
&[aria-expanded="true"] { |
|||
background: color-mix(in srgb, var(--ai-action) 10%, transparent); |
|||
} |
|||
} |
|||
|
|||
:host(.v-panel.split) .ai-chat-body { |
|||
padding: 20px 20px 0; |
|||
} |
|||
|
|||
:host(.v-panel.split) .ai-chat-log { |
|||
max-width: 712px; |
|||
} |
|||
|
|||
:host(.v-panel.split) .ai-chat-composer, |
|||
:host(.v-panel.split) .ai-chat-body.empty .ai-chat-composer { |
|||
width: 100%; |
|||
max-width: 760px; |
|||
align-self: center; |
|||
margin: 0; |
|||
padding: 12px 0 14px; |
|||
background: linear-gradient(color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 40%); |
|||
} |
|||
|
|||
:host(.v-panel.split) .k-newchat { |
|||
width: 100%; |
|||
max-width: 712px; |
|||
margin-left: auto; |
|||
margin-right: auto; |
|||
} |
|||
|
|||
|
|||
@container k-col (min-width: 481px) { |
|||
:host(.v-panel:not(.split)) { |
|||
.ai-chat-body { |
|||
padding: 20px 24px 0; |
|||
} |
|||
|
|||
.ai-chat-log { |
|||
max-width: var(--chat-read-log); |
|||
margin-bottom: 64px; |
|||
} |
|||
|
|||
.ai-chat-composer, .ai-chat-body.empty .ai-chat-composer { |
|||
margin: 0 -24px; |
|||
padding: 0 24px 16px; |
|||
background: var(--tb-surface); |
|||
pointer-events: none; |
|||
|
|||
> * { |
|||
pointer-events: auto; |
|||
} |
|||
|
|||
> tb-ai-prompt-input { |
|||
max-width: var(--chat-read); |
|||
margin: 0 auto; |
|||
} |
|||
} |
|||
|
|||
.ai-chat-body:not(.empty) .ai-chat-composer { |
|||
margin-top: -32px; |
|||
padding-top: 32px; |
|||
background: linear-gradient(180deg, color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 32px); |
|||
} |
|||
} |
|||
} |
|||
|
|||
.ai-sol-card { |
|||
display: grid; |
|||
grid-template-columns: 44px minmax(0, 1fr) auto; |
|||
align-items: center; |
|||
column-gap: 14px; |
|||
width: 100%; |
|||
max-width: 680px; |
|||
margin-top: 24px; |
|||
padding: 14px 16px 14px 14px; |
|||
border: 0; |
|||
border-radius: 12px; |
|||
background: var(--tb-surface); |
|||
text-align: left; |
|||
font: inherit; |
|||
cursor: pointer; |
|||
box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.03), 0 1px 2px rgba(16, 24, 40, 0.06), 0 2px 10px rgba(16, 24, 40, 0.06); |
|||
transition: box-shadow .15s ease; |
|||
|
|||
&:hover { |
|||
box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.05), 0 2px 4px rgba(16, 24, 40, 0.06), 0 8px 24px rgba(16, 24, 40, 0.10); |
|||
|
|||
.ai-sol-card-go .mat-icon { |
|||
transform: translateX(2px); |
|||
} |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 0; |
|||
box-shadow: 0 0 0 2px var(--ai-focus); |
|||
} |
|||
} |
|||
|
|||
.ai-sol-card-mark { |
|||
--ai-mark-fill: radial-gradient(80% 80% at 16% 10%, color-mix(in srgb, var(--tb-surface) 16%, transparent), transparent 62%), |
|||
linear-gradient(135deg in oklab, |
|||
color-mix(in oklab, var(--ai-light-teal) 34%, var(--tb-ink)) 0%, |
|||
color-mix(in oklab, var(--ai-light-aqua) 32%, var(--tb-ink)) 36%, |
|||
color-mix(in oklab, var(--ai-light-lilac) 36%, var(--tb-ink)) 68%, |
|||
color-mix(in oklab, var(--ai-light-peach) 34%, var(--tb-ink)) 100%); |
|||
--ai-mark-edge: 0 4px 12px color-mix(in oklab, var(--tb-ink) 18%, transparent); |
|||
--ai-mark-ink: var(--ai-on-action); |
|||
--ai-mark-ink-fill: linear-gradient(var(--ai-on-action), var(--ai-on-action)); |
|||
} |
|||
|
|||
.ai-sol-card-text { |
|||
display: grid; |
|||
gap: 2px; |
|||
min-width: 0; |
|||
|
|||
b { |
|||
font: 500 var(--chat-text)/var(--chat-text-lh) var(--tb-font); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
small { |
|||
font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); |
|||
color: var(--tb-ink-54); |
|||
} |
|||
} |
|||
|
|||
.ai-sol-card-go { |
|||
display: inline-flex; |
|||
align-items: center; |
|||
gap: 6px; |
|||
padding: 0 4px; |
|||
font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); |
|||
color: var(--ai-link); |
|||
|
|||
.mat-icon { |
|||
font-size: 18px; |
|||
width: 18px; |
|||
height: 18px; |
|||
transition: transform .12s cubic-bezier(.2, 0, 0, 1); |
|||
} |
|||
} |
|||
|
|||
@media (max-width: 599px) { |
|||
.ai-sol-card-go-t { |
|||
display: none; |
|||
} |
|||
} |
|||
|
|||
.ai-sec-lg { |
|||
margin-top: 32px; |
|||
|
|||
.ai-sec-head h2 { |
|||
font: 500 16px/22px var(--tb-font); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
.ai-sec-head p { |
|||
margin: 2px 0 0; |
|||
font: 400 14px/20px var(--tb-font); |
|||
color: var(--tb-ink-60); |
|||
} |
|||
} |
|||
|
|||
.k-pcards { |
|||
display: grid; |
|||
grid-template-columns: repeat(2, minmax(0, 1fr)); |
|||
grid-auto-rows: 1fr; |
|||
gap: 10px; |
|||
margin-top: 14px; |
|||
} |
|||
|
|||
.k-pcard { |
|||
display: flex; |
|||
flex-direction: column; |
|||
align-items: flex-start; |
|||
gap: 12px; |
|||
padding: 16px; |
|||
border: 1px solid rgba(0, 0, 0, 0.08); |
|||
border-radius: 12px; |
|||
background: var(--tb-surface); |
|||
text-align: left; |
|||
font: inherit; |
|||
cursor: pointer; |
|||
transition: border-color .15s ease; |
|||
|
|||
&:hover { |
|||
border-color: rgba(0, 0, 0, 0.18); |
|||
|
|||
.k-pcard-tile::before { |
|||
background-position: 100% 100%; |
|||
} |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--ai-focus); |
|||
outline-offset: 2px; |
|||
} |
|||
} |
|||
|
|||
.k-pcard-tile { |
|||
position: relative; |
|||
isolation: isolate; |
|||
overflow: hidden; |
|||
flex: none; |
|||
display: inline-flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
width: 40px; |
|||
height: 40px; |
|||
border-radius: 11px; |
|||
background: var(--tb-surface); |
|||
color: var(--tb-ink); |
|||
box-shadow: var(--ai-mark-edge); |
|||
|
|||
&::before { |
|||
content: ''; |
|||
position: absolute; |
|||
inset: 0; |
|||
z-index: -1; |
|||
background: var(--ai-mark-fill); |
|||
background-size: 240% 240%; |
|||
background-position: 0% 0%; |
|||
transition: background-position 1.2s cubic-bezier(.4, 0, .2, 1); |
|||
} |
|||
|
|||
.mat-icon { |
|||
font-size: 22px; |
|||
width: 22px; |
|||
height: 22px; |
|||
} |
|||
} |
|||
|
|||
.k-pcard-body { |
|||
display: grid; |
|||
gap: 4px; |
|||
min-width: 0; |
|||
|
|||
b { |
|||
font: 500 15px/21px var(--tb-font); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
span { |
|||
font: 400 13.5px/19px var(--tb-font); |
|||
color: var(--tb-ink-76); |
|||
} |
|||
} |
|||
|
|||
@container k-col (max-width: 560px) { |
|||
.k-pcards { |
|||
grid-template-columns: minmax(0, 1fr); |
|||
} |
|||
} |
|||
|
|||
.ai-tour-link { |
|||
display: inline-flex; |
|||
align-items: center; |
|||
gap: 6px; |
|||
margin: 0 4px 0 0; |
|||
padding: 4px 10px; |
|||
border: 0; |
|||
border-radius: 16px; |
|||
background: none; |
|||
white-space: nowrap; |
|||
cursor: pointer; |
|||
font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); |
|||
color: var(--ai-link); |
|||
|
|||
&:hover { |
|||
background: var(--ai-selected-wash); |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--ai-focus); |
|||
outline-offset: 2px; |
|||
} |
|||
|
|||
.mat-icon { |
|||
font-size: 18px; |
|||
width: 18px; |
|||
height: 18px; |
|||
} |
|||
} |
|||
|
|||
.ai-cli-band { |
|||
display: grid; |
|||
grid-template-columns: 40px minmax(0, 1fr) auto; |
|||
column-gap: 14px; |
|||
align-items: center; |
|||
width: 100%; |
|||
max-width: 680px; |
|||
box-sizing: border-box; |
|||
margin-top: 32px; |
|||
padding: 14px 14px 14px 16px; |
|||
border-radius: 14px; |
|||
text-align: left; |
|||
color: var(--tb-ink); |
|||
background: linear-gradient(160deg, color-mix(in srgb, var(--ai-dark-accent-pale) 62%, var(--tb-surface)), color-mix(in srgb, var(--ai-dark-accent-pale) 34%, var(--tb-surface))); |
|||
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ai-dark-accent-soft) 40%, transparent); |
|||
|
|||
@media (max-width: 599px) { |
|||
grid-template-columns: 40px minmax(0, 1fr); |
|||
row-gap: 12px; |
|||
} |
|||
} |
|||
|
|||
.ai-cli-band-tile { |
|||
width: 40px; |
|||
height: 40px; |
|||
border-radius: 38%; |
|||
display: inline-flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
background: var(--ai-dark); |
|||
color: var(--ai-dark-accent); |
|||
|
|||
.mat-icon { |
|||
font-size: 22px; |
|||
width: 22px; |
|||
height: 22px; |
|||
} |
|||
} |
|||
|
|||
.ai-cli-band-text { |
|||
display: grid; |
|||
gap: 2px; |
|||
min-width: 0; |
|||
|
|||
h2 { |
|||
margin: 0; |
|||
font: 500 var(--chat-text)/var(--chat-text-lh) var(--tb-font); |
|||
color: var(--tb-ink); |
|||
} |
|||
|
|||
p { |
|||
margin: 0; |
|||
font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); |
|||
color: var(--tb-ink-54); |
|||
} |
|||
} |
|||
|
|||
.ai-cli-band-btn { |
|||
display: inline-flex; |
|||
align-items: center; |
|||
gap: 6px; |
|||
height: 36px; |
|||
padding: 0 12px 0 16px; |
|||
border: 0; |
|||
border-radius: 10px; |
|||
background: var(--ai-dark); |
|||
color: var(--ai-on-dark); |
|||
font: 500 var(--chat-line)/1 var(--tb-font); |
|||
letter-spacing: normal; |
|||
white-space: nowrap; |
|||
cursor: pointer; |
|||
transition: background-color .15s cubic-bezier(.2, 0, 0, 1); |
|||
|
|||
.mat-icon { |
|||
font-size: 18px; |
|||
width: 18px; |
|||
height: 18px; |
|||
transition: transform .15s cubic-bezier(.2, 0, 0, 1); |
|||
} |
|||
|
|||
&:hover { |
|||
background: color-mix(in srgb, var(--ai-dark) 86%, var(--ai-on-dark)); |
|||
|
|||
.mat-icon { |
|||
transform: translateX(2px); |
|||
} |
|||
} |
|||
|
|||
&:focus-visible { |
|||
outline: 2px solid var(--ai-focus); |
|||
outline-offset: 2px; |
|||
} |
|||
|
|||
@media (max-width: 599px) { |
|||
grid-column: 1 / -1; |
|||
justify-content: center; |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,938 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { readStored, writeStored } from '@core/local-storage/stored'; |
|||
import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; |
|||
|
|||
export interface CodeLanguage { |
|||
lang: string; |
|||
label: string; |
|||
icon: string; |
|||
} |
|||
|
|||
const FOLD_LINES = 10; |
|||
const LONG_LINE = 72; |
|||
const COPIED_MS = 1500; |
|||
const SIDEWAYS = ['python', 'js', 'c', 'json', 'yaml']; |
|||
|
|||
const LANGUAGES: Record<string, CodeLanguage> = { |
|||
bash: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, |
|||
sh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, |
|||
shell: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, |
|||
zsh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, |
|||
console: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, |
|||
powershell: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, |
|||
ps1: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, |
|||
json: {lang: 'json', label: 'JSON', icon: 'data_object'}, |
|||
yaml: {lang: 'yaml', label: 'YAML', icon: 'description'}, |
|||
yml: {lang: 'yaml', label: 'YAML', icon: 'description'}, |
|||
log: {lang: 'log', label: 'Log', icon: 'notes'}, |
|||
diff: {lang: 'diff', label: 'Diff', icon: 'difference'}, |
|||
patch: {lang: 'diff', label: 'Diff', icon: 'difference'}, |
|||
js: {lang: 'js', label: 'JavaScript', icon: 'code'}, |
|||
javascript: {lang: 'js', label: 'JavaScript', icon: 'code'}, |
|||
ts: {lang: 'js', label: 'TypeScript', icon: 'code'}, |
|||
typescript: {lang: 'js', label: 'TypeScript', icon: 'code'}, |
|||
tbel: {lang: 'js', label: 'TBEL', icon: 'code'}, |
|||
python: {lang: 'python', label: 'Python', icon: 'code'}, |
|||
py: {lang: 'python', label: 'Python', icon: 'code'}, |
|||
c: {lang: 'c', label: 'C', icon: 'code'}, |
|||
cpp: {lang: 'c', label: 'C++', icon: 'code'}, |
|||
arduino: {lang: 'c', label: 'Arduino', icon: 'code'}, |
|||
java: {lang: 'c', label: 'Java', icon: 'code'}, |
|||
sql: {lang: 'text', label: 'SQL', icon: 'code'}, |
|||
xml: {lang: 'markup', label: 'XML', icon: 'code'}, |
|||
html: {lang: 'markup', label: 'HTML', icon: 'code'}, |
|||
svg: {lang: 'markup', label: 'SVG', icon: 'image'}, |
|||
css: {lang: 'css', label: 'CSS', icon: 'code'} |
|||
}; |
|||
|
|||
const FILE_LANGUAGES: Record<string, CodeLanguage> = { |
|||
ino: {lang: 'c', label: 'Arduino', icon: 'code'}, |
|||
h: {lang: 'c', label: 'C', icon: 'code'}, |
|||
hpp: {lang: 'c', label: 'C++', icon: 'code'}, |
|||
md: {lang: 'text', label: 'Markdown', icon: 'article'}, |
|||
markdown: {lang: 'text', label: 'Markdown', icon: 'article'}, |
|||
txt: {lang: 'text', label: 'Text', icon: 'notes'}, |
|||
csv: {lang: 'text', label: 'CSV', icon: 'table_chart'}, |
|||
toml: {lang: 'text', label: 'TOML', icon: 'description'}, |
|||
ini: {lang: 'text', label: 'INI', icon: 'description'}, |
|||
conf: {lang: 'text', label: 'Config', icon: 'description'}, |
|||
env: {lang: 'shell', label: 'Env', icon: 'description'} |
|||
}; |
|||
|
|||
const LABEL_KEYS: Record<string, string> = {Terminal: 'terminal', Log: 'log', Diff: 'diff', Text: 'text', Config: 'config'}; |
|||
|
|||
function shownLabel(label: string, translate: TranslateService): string { |
|||
return LABEL_KEYS[label] ? translate.instant('ai-assistant.code.label.' + LABEL_KEYS[label]) : label; |
|||
} |
|||
|
|||
export function fileLanguage(name: string): CodeLanguage { |
|||
const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : ''; |
|||
return FILE_LANGUAGES[ext] ?? LANGUAGES[ext] ?? {lang: 'text', label: ext ? ext.toUpperCase() : 'Text', icon: 'description'}; |
|||
} |
|||
|
|||
export function decorateCodeBlocks(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { |
|||
readFenceMeta(root); |
|||
mergeTabs(root, translate, copy); |
|||
root.querySelectorAll('pre').forEach(pre => { |
|||
if (!pre.closest('.tb-codeblock')) { |
|||
decorate(pre, translate, copy); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
const FENCE_META = '\u2063tb:'; |
|||
const OS_TABS: Record<string, string> = {macos: 'macos', mac: 'macos', windows: 'windows', linux: 'linux'}; |
|||
|
|||
export function aiFenceMeta(markdown: string): string { |
|||
let open: string | null = null; |
|||
return (markdown ?? '').split('\n').map(line => { |
|||
const fence = /^(\s*)(`{3,}|~{3,})(.*)$/.exec(line); |
|||
if (!fence) { |
|||
return line; |
|||
} |
|||
if (open) { |
|||
if (fence[2].startsWith(open) && !fence[3].trim()) { |
|||
open = null; |
|||
} |
|||
return line; |
|||
} |
|||
open = fence[2]; |
|||
const info = fence[3].trim(); |
|||
const tab = /(?:^|\s)tab=(.+)$/.exec(info)?.[1]?.trim(); |
|||
const words = info.replace(/(?:^|\s)tab=.+$/, '').trim().split(/\s+/).filter(Boolean); |
|||
const fileOf = (word: string) => /^[\w.-]+\.\w+$/.test(word ?? '') ? word : null; |
|||
const file = words.length > 1 ? fileOf(words[1]) : fileOf(words[0]); |
|||
if (!file && !tab) { |
|||
return line; |
|||
} |
|||
const lang = words.length > 1 || !file ? (words[0] ?? '') : fileLanguage(file).lang; |
|||
const meta = JSON.stringify({...(file ? {file} : {}), ...(tab ? {tab} : {})}); |
|||
return fence[1] + fence[2] + lang + '\n' + FENCE_META + encodeURIComponent(meta); |
|||
}).join('\n'); |
|||
} |
|||
|
|||
function readFenceMeta(root: HTMLElement): void { |
|||
root.querySelectorAll('pre > code').forEach(code => { |
|||
const text = code.textContent ?? ''; |
|||
if (!text.startsWith(FENCE_META)) { |
|||
return; |
|||
} |
|||
const end = text.indexOf('\n'); |
|||
let meta: {file?: string; tab?: string} = {}; |
|||
try { |
|||
meta = JSON.parse(decodeURIComponent(text.slice(FENCE_META.length, end < 0 ? text.length : end))); |
|||
} catch { |
|||
meta = {}; |
|||
} |
|||
code.textContent = end < 0 ? '' : text.slice(end + 1); |
|||
if (meta.file) { |
|||
code.setAttribute('data-file', meta.file); |
|||
code.setAttribute('data-label', meta.file); |
|||
} |
|||
if (meta.tab) { |
|||
code.setAttribute('data-tab', meta.tab); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
function mergeTabs(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { |
|||
const unitOf = (pre: Element): Element => { |
|||
const parent = pre.parentElement; |
|||
return parent && parent !== root && parent.tagName === 'DIV' && !/tb-markdown-view/.test(parent.className) |
|||
&& parent.querySelectorAll(':scope > pre').length === 1 ? parent : pre; |
|||
}; |
|||
const pres = Array.from(root.querySelectorAll('pre')).filter(pre => pre.querySelector('code[data-tab]') && !pre.closest('.tb-codeblock')); |
|||
const used = new Set<Element>(); |
|||
pres.forEach(first => { |
|||
if (used.has(first)) { |
|||
return; |
|||
} |
|||
const group = [first]; |
|||
let next = unitOf(first).nextElementSibling; |
|||
while (next) { |
|||
const pre = next.matches('pre') ? next : next.querySelector(':scope > pre'); |
|||
if (!pre || !pre.querySelector('code[data-tab]')) { |
|||
break; |
|||
} |
|||
group.push(pre as HTMLPreElement); |
|||
next = unitOf(pre).nextElementSibling; |
|||
} |
|||
group.forEach(pre => used.add(pre)); |
|||
if (group.length < 2) { |
|||
return; |
|||
} |
|||
const tabs: CodeTab[] = group.map(pre => { |
|||
const code = pre.querySelector('code'); |
|||
const label = code.getAttribute('data-tab'); |
|||
const lang = /(?:^|\s)language-([\w+#-]+)/.exec(code.className)?.[1]?.toLowerCase(); |
|||
return {id: OS_TABS[label.toLowerCase()] ?? label, label, text: (code.textContent ?? '').replace(/\n$/, ''), lang}; |
|||
}); |
|||
const os = tabs.every(tab => Object.values(OS_TABS).includes(tab.id)); |
|||
const key = os ? 'os' : 'tabs:' + tabs.map(tab => tab.id).join('|'); |
|||
const local = /Windows/i.test(navigator.userAgent) ? 'windows' : /Mac/i.test(navigator.userAgent) ? 'macos' : 'linux'; |
|||
const preferred = codeTabGroup(key) ?? (os ? local : null); |
|||
const initial = Math.max(0, tabs.findIndex(tab => tab.id === preferred)); |
|||
const block = codeTabsBlock(tabs, tabs[0].lang ?? 'shell', translate, copy, initial, undefined, {group: key}); |
|||
const anchor = unitOf(group[0]); |
|||
anchor.parentNode.insertBefore(block, anchor); |
|||
group.forEach(pre => unitOf(pre).remove()); |
|||
}); |
|||
} |
|||
|
|||
function languageOf(pre: HTMLElement): CodeLanguage | null { |
|||
const classes = [pre.className, pre.querySelector('code')?.className ?? ''].join(' '); |
|||
const name = /(?:^|\s)language-([\w+#-]+)/.exec(classes)?.[1]?.toLowerCase(); |
|||
const file = pre.querySelector('code')?.getAttribute('data-file'); |
|||
if (file && (!name || name === 'text' || name === 'plaintext' || name === 'none')) { |
|||
return {...fileLanguage(file), label: file}; |
|||
} |
|||
if (!name || name === 'text' || name === 'plaintext' || name === 'none') { |
|||
return null; |
|||
} |
|||
const language = LANGUAGES[name] ?? {lang: 'text', label: name.toUpperCase(), icon: 'code'}; |
|||
const label = pre.querySelector('code')?.getAttribute('data-label'); |
|||
return label ? {...language, label} : language; |
|||
} |
|||
|
|||
function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { |
|||
const text = (pre.textContent ?? '').replace(/\n$/, ''); |
|||
const file = pre.querySelector('code')?.getAttribute('data-file'); |
|||
const noCopy = pre.querySelector('code')?.hasAttribute('data-nocopy'); |
|||
const language = languageOf(pre); |
|||
const lang = language?.lang ?? 'text'; |
|||
const shell = lang === 'shell' || lang === 'powershell'; |
|||
const commands = shell ? splitCommands(text) : [text]; |
|||
const code = element('code', 'lang-' + lang); |
|||
if (commands.length > 1) { |
|||
code.append(...commands.map(command => { |
|||
const row = element('div', 'tb-cmd'); |
|||
row.append(...lines(lang, command), commandCopyBtn(command, translate, copy)); |
|||
return row; |
|||
})); |
|||
} else { |
|||
code.append(...lines(lang, text)); |
|||
} |
|||
pre.className = 'tb-code'; |
|||
pre.replaceChildren(code); |
|||
const lineCount = text.split('\n').length; |
|||
const folds = lineCount > FOLD_LINES && lang !== 'diff'; |
|||
const block = element('div', 'tb-codeblock'); |
|||
const wrapper = pre.closest('.code-wrapper'); |
|||
if (wrapper) { |
|||
wrapper.parentNode.insertBefore(pre, wrapper); |
|||
wrapper.remove(); |
|||
} |
|||
block.dataset.lang = lang; |
|||
block.classList.toggle('shell', shell); |
|||
block.classList.toggle('labeled', !!language || folds); |
|||
block.classList.toggle('folds', folds); |
|||
block.classList.toggle('folded', folds); |
|||
pre.parentNode.insertBefore(block, pre); |
|||
const copyButton = copyBtn(text, translate, copy); |
|||
if (language || folds) { |
|||
const head = element('div', 'tb-codeblock-head'); |
|||
const label = element('span', 'tb-codeblock-label'); |
|||
label.textContent = language ? shownLabel(language.label, translate) : translate.instant('ai-assistant.code.script'); |
|||
if (folds) { |
|||
const toggle = element('button', 'tb-codefold') as HTMLButtonElement; |
|||
toggle.type = 'button'; |
|||
toggle.setAttribute('aria-expanded', 'false'); |
|||
const size = element('span', 'tb-codeblock-size'); |
|||
size.textContent = translate.instant('ai-assistant.code.lines', {count: lineCount}); |
|||
toggle.append(...[language ? icon(language.icon, 'tb-mat-16') : null, label, size, icon('expand_more', 'tb-mat-18 tb-codefold-tg')].filter(Boolean)); |
|||
toggle.addEventListener('click', () => { |
|||
const open = block.classList.toggle('folded') === false; |
|||
toggle.setAttribute('aria-expanded', String(open)); |
|||
if (open) { |
|||
aiRevealOpened(block); |
|||
} |
|||
}); |
|||
head.append(toggle); |
|||
} else { |
|||
head.append(icon(language.icon, 'tb-mat-16'), label); |
|||
} |
|||
const wrap = wrapBtn(block, text, translate); |
|||
head.append(...[wrap, noCopy ? null : copyButton, file ? downloadBtn(file, text, translate) : null].filter(Boolean)); |
|||
block.append(head, pre); |
|||
} else { |
|||
copyButton.classList.add('floating'); |
|||
block.append(...[pre, noCopy ? null : copyButton].filter(Boolean)); |
|||
} |
|||
} |
|||
|
|||
export interface CodeTab { |
|||
label: string; |
|||
text: string; |
|||
id?: string; |
|||
lang?: string; |
|||
} |
|||
|
|||
export interface CodeBlockOptions { |
|||
group?: string; |
|||
label?: string; |
|||
icon?: boolean; |
|||
check?: boolean; |
|||
labelledCopy?: boolean; |
|||
classes?: string; |
|||
} |
|||
|
|||
const GROUP_EVENT = 'tb-code-tab'; |
|||
const LABELLED_COPIED_MS = 1600; |
|||
|
|||
interface GroupPick { |
|||
group: string; |
|||
id: string; |
|||
from: HTMLElement; |
|||
} |
|||
|
|||
type PickableBlock = HTMLElement & {tbPick?: (id: string) => void}; |
|||
|
|||
let groupListening = false; |
|||
|
|||
function listenToGroups(): void { |
|||
if (groupListening) { |
|||
return; |
|||
} |
|||
groupListening = true; |
|||
document.addEventListener(GROUP_EVENT, (event: CustomEvent<GroupPick>) => { |
|||
document.querySelectorAll<PickableBlock>('[data-code-group]').forEach(block => { |
|||
if (block !== event.detail.from && block.dataset.codeGroup === event.detail.group) { |
|||
block.tbPick?.(event.detail.id); |
|||
} |
|||
}); |
|||
}); |
|||
} |
|||
|
|||
export function codeTabGroup(group: string): string | null { |
|||
return readStored('tb-code-' + group); |
|||
} |
|||
|
|||
function storeCodeTab(group: string, id: string): void { |
|||
writeStored('tb-code-' + group, id); |
|||
} |
|||
|
|||
export function pickCodeTab(group: string, id: string, from: HTMLElement = document.body): void { |
|||
storeCodeTab(group, id); |
|||
listenToGroups(); |
|||
document.dispatchEvent(new CustomEvent<GroupPick>(GROUP_EVENT, {detail: {group, id, from}})); |
|||
} |
|||
|
|||
export function onCodeTabGroup(group: string, picked: (id: string) => void): () => void { |
|||
const listener = (event: CustomEvent<GroupPick>) => { |
|||
if (event.detail.group === group) { |
|||
picked(event.detail.id); |
|||
} |
|||
}; |
|||
document.addEventListener(GROUP_EVENT, listener); |
|||
return () => document.removeEventListener(GROUP_EVENT, listener); |
|||
} |
|||
|
|||
export function codeTabsBlock(tabs: CodeTab[], lang: string, translate: TranslateService, copy: (text: string) => boolean, |
|||
initial = 0, picked?: (tab: CodeTab) => void, options: CodeBlockOptions = {}): HTMLElement { |
|||
const languageOf = (tab: CodeTab) => { |
|||
const name = tab.lang ?? lang; |
|||
return LANGUAGES[name] ?? {lang: 'text', label: name.toUpperCase(), icon: 'code'}; |
|||
}; |
|||
const keyOf = (tab: CodeTab) => tab.id ?? tab.label; |
|||
let current = Math.min(Math.max(initial, 0), tabs.length - 1); |
|||
if (options.group) { |
|||
const stored = codeTabGroup(options.group); |
|||
const index = tabs.findIndex(tab => keyOf(tab) === stored); |
|||
if (index >= 0) { |
|||
current = index; |
|||
} |
|||
} |
|||
const block: PickableBlock = element('div', 'tb-codeblock labeled tabbed' + (options.classes ? ' ' + options.classes : '')); |
|||
const head = element('div', 'tb-codeblock-head'); |
|||
const list = element('div', 'tb-codetabs'); |
|||
list.setAttribute('role', 'tablist'); |
|||
if (options.label) { |
|||
list.setAttribute('aria-label', options.label); |
|||
} |
|||
const code = element('code', ''); |
|||
const pre = element('pre', 'tb-code'); |
|||
pre.append(code); |
|||
const select = (index: number, byPerson: boolean) => { |
|||
if (index === current) { |
|||
return; |
|||
} |
|||
current = index; |
|||
paint(); |
|||
if (byPerson) { |
|||
if (options.group) { |
|||
pickCodeTab(options.group, keyOf(tabs[current]), block); |
|||
} |
|||
picked?.(tabs[current]); |
|||
} |
|||
}; |
|||
const buttons = tabs.map((tab, index) => { |
|||
const button = element('button', 'tb-codetab') as HTMLButtonElement; |
|||
button.type = 'button'; |
|||
button.setAttribute('role', 'tab'); |
|||
button.textContent = tab.label; |
|||
button.addEventListener('click', () => select(index, true)); |
|||
button.addEventListener('keydown', event => { |
|||
const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0; |
|||
if (step) { |
|||
event.preventDefault(); |
|||
select((current + step + tabs.length) % tabs.length, true); |
|||
buttons[current].focus(); |
|||
} |
|||
}); |
|||
return button; |
|||
}); |
|||
const paint = () => { |
|||
const language = languageOf(tabs[current]); |
|||
block.dataset.lang = language.lang; |
|||
block.classList.toggle('shell', language.lang === 'shell' || language.lang === 'powershell'); |
|||
code.className = 'lang-' + language.lang; |
|||
buttons.forEach((button, index) => { |
|||
button.setAttribute('aria-selected', String(index === current)); |
|||
button.tabIndex = index === current ? 0 : -1; |
|||
}); |
|||
code.replaceChildren(...lines(language.lang, tabs[current].text)); |
|||
}; |
|||
if (options.group) { |
|||
listenToGroups(); |
|||
block.dataset.codeGroup = options.group; |
|||
block.tbPick = id => { |
|||
const index = tabs.findIndex(tab => keyOf(tab) === id); |
|||
if (index >= 0) { |
|||
select(index, false); |
|||
} |
|||
}; |
|||
} |
|||
list.append(...buttons); |
|||
head.append(...[options.icon === false ? null : icon(languageOf(tabs[current]).icon, 'tb-mat-16'), list, |
|||
copyBtn(() => tabs[current].text, translate, copy, options)].filter(Boolean)); |
|||
block.append(head, pre); |
|||
paint(); |
|||
return block; |
|||
} |
|||
|
|||
export function labelledCodeBlock(text: string, label: string, lang: string, translate: TranslateService, copy: (text: string) => boolean, |
|||
options: CodeBlockOptions = {}): HTMLElement { |
|||
const language = LANGUAGES[lang]?.lang ?? 'text'; |
|||
const block = element('div', 'tb-codeblock labeled' + (options.classes ? ' ' + options.classes : '')); |
|||
block.dataset.lang = language; |
|||
block.classList.toggle('shell', language === 'shell' || language === 'powershell'); |
|||
const head = element('div', 'tb-codeblock-head'); |
|||
const name = element('span', 'tb-codeblock-label'); |
|||
name.textContent = label; |
|||
head.append(name, copyBtn(text, translate, copy, options)); |
|||
const pre = element('pre', 'tb-code'); |
|||
const code = element('code', 'lang-' + language); |
|||
code.append(...lines(language, text)); |
|||
pre.append(code); |
|||
block.append(head, pre); |
|||
return block; |
|||
} |
|||
|
|||
export function valueBlock(label: string, value: string, translate: TranslateService, copy: (text: string) => boolean, |
|||
ariaLabel?: string): HTMLElement { |
|||
const block = element('div', 'tb-codeblock value'); |
|||
block.dataset.lang = 'text'; |
|||
const name = element('span', 'tb-codeblock-label'); |
|||
name.textContent = label; |
|||
const shown = element('code', 'tb-value'); |
|||
shown.textContent = value; |
|||
shown.title = value; |
|||
const button = copyBtn(value, translate, copy, {check: true}); |
|||
if (ariaLabel) { |
|||
button.setAttribute('aria-label', ariaLabel); |
|||
} |
|||
block.append(name, shown, button); |
|||
return block; |
|||
} |
|||
|
|||
export function commandRow(text: string, windows: boolean, translate: TranslateService, copy: (text: string) => boolean): HTMLElement { |
|||
const row = element('div', 'tb-cmdrow'); |
|||
const mark = element('span', 'tb-cmd-p'); |
|||
mark.setAttribute('aria-hidden', 'true'); |
|||
mark.textContent = windows ? '>' : '$'; |
|||
const command = element('code', 'tb-cmd-t'); |
|||
command.append(...lines('shell', text).flatMap(line => Array.from(line.childNodes))); |
|||
const button = copyBtn(text, translate, copy, {check: true}); |
|||
button.classList.add('tb-cmd-copy'); |
|||
button.setAttribute('aria-label', translate.instant('ai-assistant.copy') + ': ' + text); |
|||
row.append(mark, command, button); |
|||
return row; |
|||
} |
|||
|
|||
function wrapBtn(block: HTMLElement, text: string, translate: TranslateService): HTMLButtonElement | null { |
|||
if (!SIDEWAYS.includes(block.dataset.lang) || !text.split('\n').some(line => line.length > LONG_LINE)) { |
|||
return null; |
|||
} |
|||
const button = element('button', 'tb-codecopy tb-wrap') as HTMLButtonElement; |
|||
button.type = 'button'; |
|||
const tip = (on: boolean) => translate.instant(on ? 'ai-assistant.code.one-line-each' : 'ai-assistant.code.wrap-lines'); |
|||
button.dataset.tip = tip(false); |
|||
button.setAttribute('aria-label', translate.instant('ai-assistant.code.wrap-long-lines')); |
|||
button.setAttribute('aria-pressed', 'false'); |
|||
button.append(icon('wrap_text', 'tb-mat-16')); |
|||
button.addEventListener('click', () => { |
|||
const on = block.classList.toggle('wrap'); |
|||
button.setAttribute('aria-pressed', String(on)); |
|||
button.dataset.tip = tip(on); |
|||
}); |
|||
return button; |
|||
} |
|||
|
|||
function commandCopyBtn(text: string, translate: TranslateService, copy: (text: string) => boolean): HTMLButtonElement { |
|||
const button = copyBtn(text, translate, copy); |
|||
button.classList.add('tb-cmdcopy'); |
|||
return button; |
|||
} |
|||
|
|||
function copyBtn(text: string | (() => string), translate: TranslateService, copy: (text: string) => boolean, |
|||
options: CodeBlockOptions = {}): HTMLButtonElement { |
|||
const button = element('button', 'tb-codecopy') as HTMLButtonElement; |
|||
button.type = 'button'; |
|||
button.dataset.tip = translate.instant('ai-assistant.copy'); |
|||
button.dataset.copied = translate.instant('ai-assistant.copied'); |
|||
button.setAttribute('aria-label', translate.instant('ai-assistant.copy')); |
|||
const glyph = icon('content_copy', 'tb-mat-16'); |
|||
button.append(glyph); |
|||
let timer: ReturnType<typeof setTimeout>; |
|||
if (options.labelledCopy) { |
|||
button.classList.add('labelled'); |
|||
const word = element('span', 'lbl'); |
|||
word.setAttribute('aria-live', 'polite'); |
|||
word.textContent = translate.instant('ai-assistant.copy'); |
|||
button.append(word); |
|||
const done = (ms: number) => { |
|||
clearTimeout(timer); |
|||
button.classList.add('done'); |
|||
word.textContent = translate.instant('ai-assistant.copied'); |
|||
glyph.textContent = 'check'; |
|||
timer = setTimeout(() => { |
|||
button.classList.remove('done'); |
|||
word.textContent = translate.instant('ai-assistant.copy'); |
|||
glyph.textContent = 'content_copy'; |
|||
}, ms); |
|||
}; |
|||
button.addEventListener('click', () => { |
|||
if (copy(typeof text === 'function' ? text() : text)) { |
|||
done(LABELLED_COPIED_MS); |
|||
} |
|||
}); |
|||
return button; |
|||
} |
|||
button.append(icon('check', 'tb-mat-16 tb-copy-ok')); |
|||
button.addEventListener('click', () => { |
|||
if (copy(typeof text === 'function' ? text() : text)) { |
|||
button.classList.add('copied'); |
|||
announceCopied(translate.instant('ai-assistant.copied')); |
|||
clearTimeout(timer); |
|||
timer = setTimeout(() => button.classList.remove('copied'), COPIED_MS); |
|||
} |
|||
}); |
|||
return button; |
|||
} |
|||
|
|||
let copiedRegion: HTMLElement | null = null; |
|||
|
|||
export function announceCopied(words: string): void { |
|||
if (!copiedRegion?.isConnected) { |
|||
copiedRegion = element('div', 'tb-ai-sr-only'); |
|||
copiedRegion.setAttribute('role', 'status'); |
|||
copiedRegion.setAttribute('aria-live', 'polite'); |
|||
document.body.append(copiedRegion); |
|||
} |
|||
const region = copiedRegion; |
|||
region.textContent = ''; |
|||
setTimeout(() => region.textContent = words, 30); |
|||
} |
|||
|
|||
function downloadBtn(file: string, text: string, translate: TranslateService): HTMLButtonElement { |
|||
const button = element('button', 'tb-codecopy labelled tb-download') as HTMLButtonElement; |
|||
button.type = 'button'; |
|||
button.setAttribute('aria-label', translate.instant('ai-assistant.code.download-file', {name: file})); |
|||
const word = element('span', 'lbl'); |
|||
word.textContent = translate.instant('ai-assistant.code.download'); |
|||
button.append(icon('download', 'tb-mat-16'), word); |
|||
button.addEventListener('click', () => { |
|||
const url = URL.createObjectURL(new Blob([text.endsWith('\n') ? text : text + '\n'], {type: 'text/plain'})); |
|||
const link = document.createElement('a'); |
|||
link.href = url; |
|||
link.download = file; |
|||
link.click(); |
|||
setTimeout(() => URL.revokeObjectURL(url)); |
|||
}); |
|||
return button; |
|||
} |
|||
|
|||
function icon(name: string, size: string): HTMLElement { |
|||
const glyph = element('span', `mat-icon material-icons notranslate ${size}`); |
|||
glyph.setAttribute('aria-hidden', 'true'); |
|||
glyph.textContent = name; |
|||
return glyph; |
|||
} |
|||
|
|||
function element(tag: string, classes: string): HTMLElement { |
|||
const created = document.createElement(tag); |
|||
created.className = classes; |
|||
return created; |
|||
} |
|||
|
|||
type Piece = string | HTMLElement | null; |
|||
|
|||
interface ShellState { |
|||
command: boolean; |
|||
quote: string | null; |
|||
comment?: boolean; |
|||
} |
|||
|
|||
const KEYWORDS: Record<string, RegExp> = { |
|||
python: /^(import|from|as|def|return|if|else|elif|for|in|while|with|try|except|True|False|None|and|or|not|print)$/, |
|||
js: /^(const|let|var|await|async|function|return|if|else|for|of|new|true|false|null|import|from|export)$/, |
|||
c: /^(constexpr|const|char|int|uint16_t|uint32_t|bool|void|return|if|else|define|include|true|false)$/ |
|||
}; |
|||
|
|||
function splitCommands(text: string): string[] { |
|||
const groups: string[][] = []; |
|||
let quote: string | null = null; |
|||
let continued = false; |
|||
text.split('\n').forEach(line => { |
|||
if (!groups.length || (!quote && !continued)) { |
|||
groups.push([]); |
|||
} |
|||
groups[groups.length - 1].push(line); |
|||
quote = openQuoteAfter(line, quote); |
|||
continued = !quote && /\\\s*$/.test(line); |
|||
}); |
|||
return groups.map(group => group.join('\n')); |
|||
} |
|||
|
|||
function openQuoteAfter(line: string, quote: string | null): string | null { |
|||
for (let i = 0; i < line.length; i++) { |
|||
const char = line[i]; |
|||
if (quote) { |
|||
if (char === '\\' && quote === '"') { |
|||
i++; |
|||
} else if (char === quote) { |
|||
quote = null; |
|||
} |
|||
} else if (char === '\\') { |
|||
i++; |
|||
} else if (char === '#' && (i === 0 || /\s/.test(line[i - 1]))) { |
|||
break; |
|||
} else if (char === '"' || char === '\'') { |
|||
quote = char; |
|||
} |
|||
} |
|||
return quote; |
|||
} |
|||
|
|||
export function highlightCode(lang: string, text: string): HTMLElement[] { |
|||
return lines(lang, text); |
|||
} |
|||
|
|||
function lines(lang: string, text: string): HTMLElement[] { |
|||
const state: ShellState = {command: true, quote: null}; |
|||
const highlight = lineHighlighter(lang, state); |
|||
return text.split('\n').map((line, i, all) => { |
|||
let classes = 'tb-line'; |
|||
if (i && /\\\s*$/.test(all[i - 1])) { |
|||
classes += ' cont'; |
|||
} |
|||
if (lang === 'diff') { |
|||
classes += /^\+(?!\+\+ )/.test(line) ? ' add' : /^-(?!-- )/.test(line) ? ' del' : ''; |
|||
} |
|||
const span = element('span', classes); |
|||
span.append(...highlight(line).filter(piece => piece !== null && piece !== '')); |
|||
return span; |
|||
}); |
|||
} |
|||
|
|||
function lineHighlighter(lang: string, state: ShellState): (line: string) => Piece[] { |
|||
switch (lang) { |
|||
case 'shell': |
|||
case 'powershell': |
|||
return line => shellLine(line, state); |
|||
case 'json': |
|||
return jsonLine; |
|||
case 'yaml': |
|||
return yamlLine; |
|||
case 'log': |
|||
return logLine; |
|||
case 'diff': |
|||
return line => /^(\+\+\+ |--- |@@)/.test(line) ? [token('com', line)] : [line]; |
|||
case 'markup': |
|||
return line => markupLine(line, state); |
|||
case 'css': |
|||
return line => cssLine(line, state); |
|||
case 'python': |
|||
case 'js': |
|||
case 'c': |
|||
return line => codeLine(lang, line); |
|||
default: |
|||
return line => [line]; |
|||
} |
|||
} |
|||
|
|||
function blockComment(line: string, state: ShellState, open: string, close: string): [Piece[], string] { |
|||
const out: Piece[] = []; |
|||
let rest = line; |
|||
while (rest) { |
|||
if (state.comment) { |
|||
const end = rest.indexOf(close); |
|||
if (end < 0) { |
|||
out.push(token('com', rest)); |
|||
return [out, '']; |
|||
} |
|||
out.push(token('com', rest.slice(0, end + close.length))); |
|||
rest = rest.slice(end + close.length); |
|||
state.comment = false; |
|||
} |
|||
const start = rest.indexOf(open); |
|||
if (start < 0) { |
|||
return [out, rest]; |
|||
} |
|||
out.push(rest.slice(0, start)); |
|||
state.comment = true; |
|||
rest = rest.slice(start); |
|||
const end = rest.indexOf(close, open.length); |
|||
if (end >= 0) { |
|||
out.push(token('com', rest.slice(0, end + close.length))); |
|||
rest = rest.slice(end + close.length); |
|||
state.comment = false; |
|||
} else { |
|||
out.push(token('com', rest)); |
|||
return [out, '']; |
|||
} |
|||
} |
|||
return [out, '']; |
|||
} |
|||
|
|||
function markupLine(line: string, state: ShellState): Piece[] { |
|||
if (state.comment || line.includes('<!--')) { |
|||
const [pieces, rest] = blockComment(line, state, '<!--', '-->'); |
|||
return [...pieces.flatMap(piece => typeof piece === 'string' ? markupText(piece) : [piece]), ...markupText(rest)]; |
|||
} |
|||
return markupText(line); |
|||
} |
|||
|
|||
function markupText(text: string): Piece[] { |
|||
const out: Piece[] = []; |
|||
const pattern = /(?<tag><\/?[\w:-]+)|(?<close>\/?>)|(?<attr>[\w:@.[\]()*#-]+)(?==)|(?<eq>=)|(?<str>"[^"]*"?|'[^']*'?)|(?<bind>\{\{.*?\}\})|(?<flow>@(?:if|else if|else|for|empty|switch|case|default|let)\b)|(?<other>[^<>="'{@]+|[{@>])/g; |
|||
for (const match of text.matchAll(pattern)) { |
|||
const groups = match.groups ?? {}; |
|||
if (groups.tag) { |
|||
out.push(token('op', groups.tag.startsWith('</') ? '</' : '<'), token('kw', groups.tag.replace(/^<\/?/, ''))); |
|||
} else if (groups.close || groups.eq) { |
|||
out.push(token('op', match[0])); |
|||
} else if (groups.attr) { |
|||
out.push(token('key', groups.attr)); |
|||
} else if (groups.str) { |
|||
out.push(token('str', groups.str)); |
|||
} else if (groups.bind) { |
|||
out.push(token('var', groups.bind)); |
|||
} else if (groups.flow) { |
|||
out.push(token('kw', groups.flow)); |
|||
} else { |
|||
out.push(match[0]); |
|||
} |
|||
} |
|||
return out; |
|||
} |
|||
|
|||
function cssLine(line: string, state: ShellState): Piece[] { |
|||
const [pieces, rest] = state.comment || line.includes('/*') ? blockComment(line, state, '/*', '*/') : [[], line]; |
|||
return [...pieces.flatMap(piece => typeof piece === 'string' ? cssText(piece) : [piece]), ...cssText(rest)]; |
|||
} |
|||
|
|||
function cssText(text: string): Piece[] { |
|||
const declaration = /^(\s*)([\w-]+)(\s*:\s*)([^;{}]*)(;?)(.*)$/.exec(text); |
|||
if (declaration && !/[{]/.test(text) && !/^\s*[.#&:@]/.test(text)) { |
|||
const [, indent, property, colon, value, semi, tail] = declaration; |
|||
return [indent, token('key', property), token('op', colon), ...cssValue(value), semi ? token('op', semi) : '', ...cssText(tail)]; |
|||
} |
|||
const out: Piece[] = []; |
|||
matches(text, /@[\w-]+|[{};]|[^{};@]+/g).forEach(part => { |
|||
if (part.startsWith('@')) { |
|||
out.push(token('kw', part)); |
|||
} else if (/^[{};]$/.test(part)) { |
|||
out.push(token('op', part)); |
|||
} else { |
|||
out.push(part.trim() ? token('fn', part) : part); |
|||
} |
|||
}); |
|||
return out; |
|||
} |
|||
|
|||
function cssValue(value: string): Piece[] { |
|||
return matches(value, /#[0-9a-fA-F]{3,8}\b|-?\d*\.?\d+(?:px|%|em|rem|vh|vw|s|ms|deg|fr)?|"[^"]*"|'[^']*'|var\([^)]*\)|[^\s#\d"'(-]+\(?|\s+|./g) |
|||
.map(part => /^["']/.test(part) ? token('str', part) : /^(#|-?\d|\.\d)/.test(part) ? token('num', part) |
|||
: /^var\(/.test(part) ? token('var', part) : /^\s+$/.test(part) ? part : token('val', part)); |
|||
} |
|||
|
|||
function token(kind: string | null, text: string): Piece { |
|||
if (!kind) { |
|||
return text; |
|||
} |
|||
const span = element('span', 'hl-' + kind); |
|||
span.textContent = text; |
|||
return span; |
|||
} |
|||
|
|||
function shellLine(line: string, state: ShellState): Piece[] { |
|||
if (state.quote) { |
|||
const close = closingQuote(line, state.quote); |
|||
if (close < 0) { |
|||
return [token('str', line)]; |
|||
} |
|||
state.quote = null; |
|||
state.command = false; |
|||
return [token('str', line.slice(0, close + 1)), ...shellLine(line.slice(close + 1), state)]; |
|||
} |
|||
if (/^\s*#/.test(line)) { |
|||
state.command = true; |
|||
return [token('com', line)]; |
|||
} |
|||
const out: Piece[] = []; |
|||
matches(line, /"(?:\\.|[^"\\])*"?|'[^']*'?|\s+|&&|\|\||[|;]|[^\s|;&]+|&/g).forEach(word => { |
|||
if (/^\s+$/.test(word)) { |
|||
out.push(word); |
|||
return; |
|||
} |
|||
if (/^(&&|\|\||\||;|&)$/.test(word)) { |
|||
state.command = true; |
|||
out.push(token('op', word)); |
|||
return; |
|||
} |
|||
if (word === '\\') { |
|||
out.push(token('op', word)); |
|||
return; |
|||
} |
|||
if (/^["']/.test(word)) { |
|||
state.command = false; |
|||
if (word.length === 1 || !word.endsWith(word[0])) { |
|||
state.quote = word[0]; |
|||
} |
|||
out.push(token('str', word)); |
|||
return; |
|||
} |
|||
if (state.command && /^[A-Za-z_]\w*=/.test(word)) { |
|||
out.push(token('var', word)); |
|||
return; |
|||
} |
|||
const kind = state.command ? 'cmd' : /^--?[A-Za-z]/.test(word) ? 'flag' : /^https?:\/\//.test(word) ? 'str' |
|||
: /^\$/.test(word) ? 'var' : /^\d+(\.\d+)?$/.test(word) ? 'num' : null; |
|||
state.command = false; |
|||
out.push(token(kind, word)); |
|||
}); |
|||
if (!state.quote && !/\\\s*$/.test(line)) { |
|||
state.command = true; |
|||
} |
|||
return out; |
|||
} |
|||
|
|||
function closingQuote(line: string, quote: string): number { |
|||
for (let i = 0; i < line.length; i++) { |
|||
if (line[i] === '\\' && quote === '"') { |
|||
i++; |
|||
} else if (line[i] === quote) { |
|||
return i; |
|||
} |
|||
} |
|||
return -1; |
|||
} |
|||
|
|||
function codeLine(lang: string, line: string): Piece[] { |
|||
const comment = lang === 'python' ? /^(\s*)(#.*)$/ : /^(\s*)(\/\/.*)$/; |
|||
const match = line.match(comment); |
|||
if (match) { |
|||
return [match[1], token('com', match[2])]; |
|||
} |
|||
const words = new RegExp('"(?:\\\\.|[^"\\\\])*"?|\'(?:\\\\.|[^\'\\\\])*\'?|`[^`]*`?|' |
|||
+ (lang === 'python' ? '#.*' : '\\/\\/.*') + '|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|.', 'g'); |
|||
return matches(line, words).map((word, i, all) => { |
|||
if (/^(#|\/\/)/.test(word)) { |
|||
return token('com', word); |
|||
} |
|||
if (/^["'`]/.test(word)) { |
|||
return token('str', word); |
|||
} |
|||
if (/^\d/.test(word)) { |
|||
return token('num', word); |
|||
} |
|||
if (/^(true|false|null|undefined|True|False|None)$/.test(word)) { |
|||
return token('bool', word); |
|||
} |
|||
if (KEYWORDS[lang]?.test(word)) { |
|||
return token('kw', word); |
|||
} |
|||
if (/^[A-Za-z_$]/.test(word) && all[i + 1] === '(') { |
|||
return token('fn', word); |
|||
} |
|||
return /^[{}()[\],.:;=]$/.test(word) ? token('op', word) : word; |
|||
}); |
|||
} |
|||
|
|||
function jsonLine(line: string): Piece[] { |
|||
return matches(line, /"(?:\\.|[^"\\])*"(\s*:)?|-?\d+(?:\.\d+)?|true|false|null|\s+|./g).flatMap(word => { |
|||
if (/^".*:$/.test(word.replace(/\s/g, ''))) { |
|||
return [token('key', word.replace(/\s*:$/, '')), token('op', word.match(/\s*:$/)[0])]; |
|||
} |
|||
if (/^"/.test(word)) { |
|||
return [token('str', word)]; |
|||
} |
|||
if (/^-?\d/.test(word)) { |
|||
return [token('num', word)]; |
|||
} |
|||
if (/^(true|false|null)$/.test(word)) { |
|||
return [token('bool', word)]; |
|||
} |
|||
return [/^[{}[\],]$/.test(word) ? token('op', word) : word]; |
|||
}); |
|||
} |
|||
|
|||
function yamlValue(value: string): Piece[] { |
|||
const match = value.match(/^(\s*)(.*?)(\s+#.*)?$/); |
|||
const text = match[2]; |
|||
const kind = !text ? null : /^["']/.test(text) ? 'str' : /^(-?\d+(\.\d+)?)$/.test(text) ? 'num' |
|||
: /^(true|false|null|yes|no)$/i.test(text) ? 'bool' : /^[|>]-?$/.test(text) ? 'op' : 'val'; |
|||
return [match[1], text ? token(kind, text) : '', match[3] ? token('com', match[3]) : null]; |
|||
} |
|||
|
|||
function yamlLine(line: string): Piece[] { |
|||
if (/^\s*#/.test(line)) { |
|||
return [token('com', line)]; |
|||
} |
|||
const pair = line.match(/^(\s*)(-\s+)?([\w.\-/]+)(:)(.*)$/); |
|||
if (pair) { |
|||
return [pair[1], pair[2] ? token('op', pair[2]) : null, token('key', pair[3]), token('op', pair[4]), ...yamlValue(pair[5])]; |
|||
} |
|||
const item = line.match(/^(\s*)(-\s+)(.*)$/); |
|||
return item ? [item[1], token('op', item[2]), ...yamlValue(item[3])] : [line]; |
|||
} |
|||
|
|||
function logLine(line: string): Piece[] { |
|||
const match = line.match(/^(.*?\|\s*|\S+\s+\d\d:\d\d:\d\d\S*\s+)?(INFO|WARN(?:ING)?|ERROR|DEBUG)?(.*)$/); |
|||
const level = match[2]; |
|||
const kind = !level ? null : level === 'INFO' ? 'lvl' : level === 'DEBUG' ? 'com' : /^WARN/.test(level) ? 'warn' : 'err'; |
|||
return [match[1] ? token('com', match[1]) : null, level ? token(kind, level) : null, match[3]]; |
|||
} |
|||
|
|||
function matches(line: string, pattern: RegExp): string[] { |
|||
return line.match(pattern) ?? []; |
|||
} |
|||
|
|||
const LONG_CELL = 32; |
|||
|
|||
export function decorateTables(root: HTMLElement): void { |
|||
root.querySelectorAll('table td, table th').forEach((cell: HTMLElement) => { |
|||
cell.classList.toggle('long', (cell.textContent ?? '').trim().length > LONG_CELL); |
|||
}); |
|||
root.querySelectorAll('table td:first-child').forEach((cell: HTMLElement) => { |
|||
if (cell.firstElementChild?.classList.contains('k-md-lead') && cell.childNodes.length === 1) { |
|||
return; |
|||
} |
|||
const lead = element('span', 'k-md-lead'); |
|||
lead.append(...Array.from(cell.childNodes)); |
|||
cell.append(lead); |
|||
}); |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { NgModule } from '@angular/core'; |
|||
import { CommonModule } from '@angular/common'; |
|||
import { SharedModule } from '@shared/shared.module'; |
|||
import { AiCoreModule } from '@home/components/ai/ai-core.module'; |
|||
import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; |
|||
import { AiCreditsComponent } from '@home/components/ai/ai-credits.component'; |
|||
import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component'; |
|||
import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component'; |
|||
import { AiShortcutsDialogComponent } from '@home/components/ai/ai-shortcuts-dialog.component'; |
|||
|
|||
@NgModule({ |
|||
declarations: [ |
|||
AiPromptInputComponent, |
|||
AiCreditsComponent, |
|||
AiAttachmentsComponent, |
|||
AiAttachmentPreviewDialogComponent, |
|||
AiShortcutsDialogComponent |
|||
], |
|||
imports: [ |
|||
CommonModule, |
|||
SharedModule, |
|||
AiCoreModule |
|||
], |
|||
exports: [ |
|||
AiCoreModule, |
|||
AiPromptInputComponent, |
|||
AiCreditsComponent, |
|||
AiAttachmentsComponent |
|||
] |
|||
}) |
|||
export class AiComposerModule {} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue