diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java index 3b77aad205..d74fc3bf2b 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java @@ -32,7 +32,7 @@ final class TbAiPooledConnection implements ChannelFrameListener { // Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell // before using it that this ThingsBoard understands it. - static final List CLIENT_CAPABILITIES = List.of(); + static final List CLIENT_CAPABILITIES = List.of(ChannelProtocol.CHAT_KIT_CAPABILITY); private final TbAiChannelPool.PoolKey key; private final String origin; diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java index 3f4c906824..3ec9fc0906 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java @@ -72,7 +72,7 @@ class ChannelTbAiTransportTest { assertThat(second).hasSize(3); assertThat(server.connections.get()).isEqualTo(1); ChannelHello hello = server.codec.fromPayload(server.received(ChannelProtocol.HELLO).getFirst().payload(), ChannelHello.class); - assertThat(hello).isEqualTo(new ChannelHello(1, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null)); + assertThat(hello).isEqualTo(new ChannelHello(1, List.of("chat.kit"), "https://tb.example.com", null)); ChannelFrame send = server.received(ChannelProtocol.CHAT_SEND).getFirst(); ChatTurnRequest turnRequest = server.codec.fromPayload(send.payload(), ChatTurnRequest.class); assertThat(turnRequest.request()).isEqualTo(request); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html new file mode 100644 index 0000000000..0ae45625d4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html @@ -0,0 +1,30 @@ + +@if (action().status === 'RUNNING') { + +} @else { +
+ + {{ outcome() }} + @if (duration()) { + {{ duration() }} + } +
+ @if (hasDetails()) { +
+ {{ 'ai-assistant.action.details' | translate }} + @if (request()) { +
{{ 'ai-assistant.action.request' | translate }}
+
{{ request() }}
+ } + @if (result()) { +
{{ 'ai-assistant.action.result' | translate }}
+
{{ result() }}
+ } +
+ } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss new file mode 100644 index 0000000000..f3e2dd07f6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + font-family: var(--tb-font); + letter-spacing: var(--chat-text-ls); +} + +.out { + display: flex; + align-items: flex-start; + gap: 8px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + + .mark { + flex: none; + width: 16px; + height: 16px; + font-size: 16px; + margin-block: calc((var(--chat-line-lh) - 16px) / 2); + color: var(--tb-ok); + } + + .say { + min-width: 0; + overflow-wrap: anywhere; + } + + .dur { + margin-left: auto; + padding-left: 12px; + font-family: var(--tb-mono); + font-size: var(--chat-meta); + color: var(--k-faint); + white-space: nowrap; + } +} + +:host(.fail) .out .mark { + color: var(--tb-crit); +} + +:host(.stopped) .out { + color: var(--tb-text-secondary); + + .mark { + color: var(--tb-ink-38); + } +} + +.disc { + margin: 2px 0 0 24px; + + > summary { + list-style: none; + display: flex; + align-items: center; + gap: 4px; + width: fit-content; + cursor: pointer; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-60, var(--tb-text-secondary)); + + &::-webkit-details-marker { + display: none; + } + + &::before { + content: 'chevron_right'; + flex: none; + width: 18px; + height: 18px; + font: 18px/18px 'Material Icons'; + color: var(--tb-ink-38); + transition: transform .15s ease; + } + + &:hover, &:hover::before { + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + border-radius: 4px; + } + } + + &[open] > summary::before { + transform: rotate(90deg); + } + + .part { + margin: 8px 0 4px; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + font-weight: 500; + color: var(--tb-text-secondary); + } + + pre { + margin: 0; + max-height: 240px; + overflow: auto; + padding: 8px 10px; + border-radius: 8px; + background: var(--tb-line-soft); + font-family: var(--tb-mono); + font-size: 12px; + line-height: 18px; + white-space: pre-wrap; + overflow-wrap: anywhere; + color: var(--tb-ink-76); + } + + @media (prefers-reduced-motion: reduce) { + > summary::before { + transition: none; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts new file mode 100644 index 0000000000..9f04d2129c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject, input } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { + AiAction, + aiActionDetail, + aiActionDuration, + 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(); + + private translate = inject(TranslateService); + + words = computed(() => aiActionWords(this.action().tool, this.action().arguments)); + + running = computed(() => this.translate.instant(this.words().key + '.run', this.words().params)); + + outcome = computed(() => { + const action = this.action(); + const words = this.words(); + switch (action.status) { + case 'SUCCESS': + return this.translate.instant(words.key + '.done', words.params); + case 'FAILURE': + return this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.running())}); + default: + return this.translate.instant('ai-assistant.work.stopped', {words: this.lowerFirst(this.running())}); + } + }); + + icon = computed(() => { + switch (this.action().status) { + case 'SUCCESS': + return 'check'; + case 'FAILURE': + return 'error_outline'; + default: + return 'block'; + } + }); + + duration = computed(() => this.action().durationMs !== undefined ? aiActionDuration(this.action().durationMs) : ''); + + request = computed(() => aiActionDetail(this.action().arguments)); + + result = computed(() => aiActionDetail(this.action().result)); + + hasDetails = computed(() => !!this.request() || !!this.result()); + + private lowerFirst(words: string): string { + return words ? words.charAt(0).toLocaleLowerCase() + words.slice(1) : words; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts new file mode 100644 index 0000000000..c79b097858 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -0,0 +1,182 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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; + kind: AiSpinKind; +} + +export type AiWorkMoment = 'reading-request' | 'going-through-results' | 'applying-change' | 'reading-what-to-change'; + +export interface AiWorkState { + moment: AiWorkMoment; + since: number; +} + +const HIDDEN_TOOLS = new Set(['read_current_time']); + +const TOOL_WORDS: Record = { + 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: 'save-device', + save_calculated_field: 'save-calculated-field', + save_alarm_rule: 'save-alarm-rule', + 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', + add_dashboard_widgets: 'add-widgets', + update_dashboard_widget: 'update-widget', + place_dashboard_widgets: 'place-widgets', + read_dashboard_widget: 'read-widget', + read_dashboard_html_page: 'read-dashboard-page', + save_notification_target: 'save-notification-target', + save_notification_template: 'save-notification-template', + save_notification_rule: 'save-notification-rule', + search_iot_hub_devices: 'search-iot-hub', + read_transport_endpoints: 'read-connection-settings', + read_device_connect_commands: 'read-connection-settings', + search_web: 'search-web' +}; + +const GENERATING_TOOLS: Record = { + set_dashboard_html_page: 'lay-out-dashboard', + reprocess_calculated_field: 'recalculate-history', + research_device_connectivity: 'research-device' +}; + +const SEARCHED_TYPES: Record = { + DEVICE: 'search-devices', + ASSET: 'search-assets', + DASHBOARD: 'search-dashboards', + CUSTOMER: 'search-customers', + USER: 'search-users' +}; + +const DELETED_TARGETS: Record = { + 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', + 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' +}; + +const ACTION_PREFIX = 'ai-assistant.action.'; + +export const isHiddenAiAction = (tool: string): boolean => HIDDEN_TOOLS.has(tool); + +export function aiActionWords(tool: string, args: unknown): AiActionWords { + const values = (args && typeof args === 'object' ? args : {}) as Record; + if (GENERATING_TOOLS[tool]) { + return {key: ACTION_PREFIX + GENERATING_TOOLS[tool], kind: 'gen'}; + } + switch (tool) { + case 'search_entities': + return {key: ACTION_PREFIX + searchedWords(values), 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 '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(ms: number): string { + if (ms < 1000) { + return `${Math.max(Math.round(ms / 100), 1) / 10} s`; + } + const seconds = Math.round(ms / 1000); + if (seconds < 60) { + return `${seconds} s`; + } + const rest = seconds % 60; + return rest ? `${Math.floor(seconds / 60)} min ${rest} s` : `${seconds / 60} min`; +} + +export function aiWorkClock(ms: number): string { + const seconds = Math.floor(ms / 1000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; +} + +export function aiActionDetail(value: unknown): string { + if (value === undefined || value === null || value === '') { + return ''; + } + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value); + return typeof parsed === 'object' && parsed !== null ? JSON.stringify(parsed, null, 2) : value; + } catch { + return value; + } + } + return JSON.stringify(value, null, 2); +} + +function searchedWords(values: Record): string { + const filter = values.entityFilter ?? values; + const types = new Set(); + 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 { + 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; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html index a701a29677..391d844d64 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html @@ -20,6 +20,10 @@ } + } @else if (msg.from === 'ACTION') { +
+ +
} @else {
@if (msg.from === 'APPROVAL') { @@ -63,10 +67,12 @@ } } } -@if (loading && !waitApproval) { +@if (loading && !waitApproval && !actionRunning) {
@if (loadingLongTime) { + } @else if (work) { + } @else {
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 99132af595..111370a1c0 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -148,9 +148,18 @@ } } + .ai.action + .ai.action { + margin-top: calc(6px - var(--chat-turn-gap)); + } + .generating { gap: 10px; + .work { + flex: 1; + min-width: 0; + } + .tb-ai-mark { --m: var(--chat-mark); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts index 68cdfd9d53..60b40f1ad5 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts @@ -4,6 +4,7 @@ import { Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Outpu import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; import { ClipboardService } from 'ngx-clipboard'; import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { AiWorkState } from '@home/components/ai/ai-action.models'; @Component({ selector: 'tb-ai-chat-messages', @@ -22,11 +23,14 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Input() scrollContainer: HTMLElement; @Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage'; @Input() denyReasons: Record = {}; + @Input() work: AiWorkState | undefined; @Output() approvalAction = new EventEmitter(); @Output() resourceError = new EventEmitter(); waitApproval = false; + actionRunning = false; + private static readonly PIN_TO_BOTTOM_MS = 1500; private static readonly COPIED_MS = 1200; @@ -70,6 +74,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } if (changes.messages) { this.lastAnswerIndex = this.findLastAnswerIndex(); + this.actionRunning = this.messages.some(message => message.from === 'ACTION' && message.data.status === 'RUNNING'); if (changes.messages.firstChange) { if (this.initialScroll === 'bottom') { this.pinToBottom(); @@ -97,6 +102,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } else if (wasNearBottom) { setTimeout(() => this.scrollToLastAiMessage(), 0); } + } else if (lastMsg?.from === 'ACTION') { + if (wasNearBottom) { + setTimeout(() => this.scrollToBottom('smooth'), 0); + } } else if (lastMsg?.from === 'APPROVAL') { if (prevLastMsg?.from === 'USER') { setTimeout(() => this.scrollToLastUserMessage(), 0); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index 55479c939f..9f6e31d7e6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -59,6 +59,7 @@ [scrollContainer]="chatArea" initialScroll="bottom" [denyReasons]="denyReasons()" + [work]="work()" (approvalAction)="onApprovalAction($event)"> } @else if (!chatId()) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index 10f6c98f53..3e118c5a06 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -36,9 +36,13 @@ import { ApprovalResult, ChatEvent, SendChatMessageRequest, + AiAction, ToolExecutionRequestedEvent, - ToolExecutionResult + ToolExecutionResult, + ToolFinished, + ToolStarted } from '@shared/models/ai-chat.models'; +import { AiWorkMoment, AiWorkState, isHiddenAiAction } from '@home/components/ai/ai-action.models'; import { EntityId } from '@shared/models/id/entity-id'; import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; @@ -106,6 +110,8 @@ export class AiChatComponent implements OnInit, OnDestroy { stopping = signal(false); + work = signal(undefined); + private answeredApprovals = signal>(new Set()); waitingApproval = computed(() => { @@ -294,6 +300,7 @@ export class AiChatComponent implements OnInit, OnDestroy { this.panelService.setAutoApprove(chatId, true); } this.answeredApprovals.update(set => new Set(set).add(event.executionId)); + this.setWork(event.approved ? 'applying-change' : event.reason ? 'reading-what-to-change' : 'going-through-results'); if (event.reason) { this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason})); } @@ -446,6 +453,12 @@ export class AiChatComponent implements OnInit, OnDestroy { this.affectedEntities.push(...event.data.affectedEntities); } break; + case 'toolStarted': + this.startAction(event.data); + break; + case 'toolFinished': + this.finishAction(event.data); + break; case 'turnStopped': this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'INCOMPLETE', time: Date.now()}]); break; @@ -462,6 +475,47 @@ export class AiChatComponent implements OnInit, OnDestroy { return of(event); } + private startAction(started: ToolStarted): void { + if (isHiddenAiAction(started.tool) || this.isApprovalExecution(started.executionId)) { + return; + } + const action: AiAction = { + executionId: started.executionId, + tool: started.tool, + arguments: started.arguments, + status: 'RUNNING', + startedAt: Date.now() + }; + this.messages.update(list => [...list, {from: 'ACTION', data: action}]); + } + + private finishAction(finished: ToolFinished): void { + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === finished.executionId + ? {from: 'ACTION', data: {...message.data, status: finished.status, durationMs: finished.durationMs, result: finished.result}} + : message)); + if (!this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.setWork('going-through-results', true); + } + } + + private isApprovalExecution(executionId: string): boolean { + return this.messages().some(message => message.from === 'APPROVAL' && message.data.executionId === executionId); + } + + private stopRunningActions(): void { + if (this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.status === 'RUNNING' + ? {from: 'ACTION', data: {...message.data, status: 'STOPPED', durationMs: Date.now() - message.data.startedAt}} + : message)); + } + } + + private setWork(moment: AiWorkMoment, restart = false): void { + if (restart || this.work()?.moment !== moment) { + this.work.set({moment, since: Date.now()}); + } + } + private handleToolApproval(event: ToolExecutionRequestedEvent): void { if (event.data.needsApproval) { this.messages.update(list => [...list, {from: 'APPROVAL', data: event.data}]); @@ -496,6 +550,7 @@ export class AiChatComponent implements OnInit, OnDestroy { private startLoading(): void { this.loading.set(true); + this.setWork('reading-request'); this.chats.setReplying(this.replyingChatId, false); this.replyingChatId = this.chatId(); this.chats.setReplying(this.replyingChatId, true); @@ -507,6 +562,8 @@ export class AiChatComponent implements OnInit, OnDestroy { } this.loading.set(false); this.stopping.set(false); + this.work.set(undefined); + this.stopRunningActions(); if (this.affectedEntities.length) { this.panelService.emitUpdatedData(this.affectedEntities); this.affectedEntities = []; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss new file mode 100644 index 0000000000..af3c53f33a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + color: var(--ai-teal-500); + + &[data-kind="listen"] { + color: var(--tb-caution); + } + + &[data-kind="stop"] { + color: var(--tb-ink-38); + } +} + +.cell { + display: grid; + grid-template-columns: repeat(2, 3px); + grid-template-rows: repeat(3, 3px); + gap: 2px 3px; + + i { + width: 3px; + height: 3px; + border-radius: 50%; + background: currentColor; + visibility: hidden; + + &.on { + visibility: visible; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts new file mode 100644 index 0000000000..1d72167969 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, ElementRef, inject, Input, NgZone, OnDestroy, OnInit } from '@angular/core'; +import { AiSpinKind } from '@home/components/ai/ai-action.models'; + +const FRAME_MS = 80; +const DOT_BITS = [0x01, 0x08, 0x02, 0x10, 0x04, 0x20]; + +const FRAMES: Record = { + think: [...'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'].map(glyph => glyph.charCodeAt(0) - 0x2800), + listen: [0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x3f, 0x3e, 0x3c, 0x38, 0x30, 0x20, 0x00], + gen: [0x01, 0x08, 0x10, 0x20, 0x04, 0x02].map(bit => 0x3f & ~bit), + install: [0x09, 0x12, 0x24, 0x2d, 0x36, 0x3f, 0x3f, 0x3f, 0x00], + stop: [0x12] +}; + +const spinners = new Set(); +let tick = 0; +let timer: ReturnType | undefined; + +function startTimer(zone: NgZone): void { + if (timer || matchMedia('(prefers-reduced-motion: reduce)').matches) { + return; + } + zone.runOutsideAngular(() => { + timer = setInterval(() => { + tick++; + spinners.forEach(spinner => spinner.draw()); + }, FRAME_MS); + }); +} + +@Component({ + selector: 'tb-ai-spin', + template: '', + styleUrls: ['./ai-spin.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'aria-hidden': 'true', + '[attr.data-kind]': 'kind' + } +}) +export class AiSpinComponent implements OnInit, OnDestroy { + + private kindValue: AiSpinKind = 'think'; + + @Input() + set kind(kind: AiSpinKind) { + this.kindValue = kind ?? 'think'; + this.draw(); + } + + get kind(): AiSpinKind { + return this.kindValue; + } + + private host = inject>(ElementRef); + private zone = inject(NgZone); + + ngOnInit(): void { + spinners.add(this); + this.draw(); + startTimer(this.zone); + } + + ngOnDestroy(): void { + spinners.delete(this); + if (!spinners.size && timer) { + clearInterval(timer); + timer = undefined; + } + } + + draw(): void { + const frames = FRAMES[this.kindValue]; + const bits = frames[tick % frames.length]; + const dots = this.host.nativeElement.querySelectorAll('i'); + dots.forEach((dot, index) => dot.classList.toggle('on', !!(bits & DOT_BITS[index]))); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss new file mode 100644 index 0000000000..77fc610d16 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: flex; + align-items: flex-start; + gap: 8px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-text-secondary); + + tb-ai-spin { + margin-block: calc((var(--chat-line-lh) - 16px) / 2); + } +} + +.say { + min-width: 0; +} + +.clock { + margin-left: auto; + padding-left: 12px; + font-family: var(--tb-mono); + font-size: var(--chat-meta); + color: var(--k-faint); + white-space: nowrap; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts new file mode 100644 index 0000000000..f2757372e8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, NgZone, OnInit, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiSpinKind, aiWorkClock } from '@home/components/ai/ai-action.models'; + +const CLOCK_AFTER_MS = 10_000; +const STILL_AFTER_MS = 30_000; + +@Component({ + selector: 'tb-ai-work-line', + template: ` + + {{ say() }} + @if (clock(); as time) { + {{ time }} + } + `, + styleUrls: ['./ai-work-line.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'role': 'status', + '[attr.aria-label]': 'words()' + } +}) +export class AiWorkLineComponent implements OnInit { + + words = input.required(); + + kind = input('think'); + + since = input(Date.now()); + + private now = signal(Date.now()); + + private elapsed = computed(() => Math.max(0, this.now() - this.since())); + + say = computed(() => { + const words = this.words(); + if (this.elapsed() < STILL_AFTER_MS || !words) { + return words; + } + return this.translate.instant('ai-assistant.work.still', {words: words.charAt(0).toLocaleLowerCase() + words.slice(1)}); + }); + + clock = computed(() => this.elapsed() >= CLOCK_AFTER_MS ? aiWorkClock(this.elapsed()) : undefined); + + private translate = inject(TranslateService); + private zone = inject(NgZone); + private destroyRef = inject(DestroyRef); + + ngOnInit(): void { + const timer = this.zone.runOutsideAngular(() => setInterval(() => this.zone.run(() => this.now.set(Date.now())), 1000)); + this.destroyRef.onDestroy(() => clearInterval(timer)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index e8119fb9c4..af5d695777 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -16,6 +16,9 @@ import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component'; import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component'; import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; +import { AiSpinComponent } from '@home/components/ai/ai-spin.component'; +import { AiWorkLineComponent } from '@home/components/ai/ai-work-line.component'; +import { AiActionLineComponent } from '@home/components/ai/ai-action-line.component'; @NgModule({ declarations: [ @@ -31,7 +34,10 @@ import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; AiNoTelemetryModalComponent, AiAttachmentsComponent, AiAttachmentPreviewDialogComponent, - AiTipDirective + AiTipDirective, + AiSpinComponent, + AiWorkLineComponent, + AiActionLineComponent ], imports: [ CommonModule, diff --git a/ui-ngx/src/app/shared/models/ai-chat.models.ts b/ui-ngx/src/app/shared/models/ai-chat.models.ts index 0c3bdcea41..0f3f650b9f 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -107,6 +107,39 @@ export interface TurnStoppedEvent extends BaseChatEvent { data: Record; } +export interface ToolStarted extends BaseChatToolEventData { + tool: string; + arguments?: unknown; +} + +export interface ToolStartedEvent extends BaseChatEvent { + event: 'toolStarted'; + data: ToolStarted; +} + +export interface ToolFinished extends BaseChatToolEventData { + status: 'SUCCESS' | 'FAILURE'; + durationMs: number; + result?: string; +} + +export interface ToolFinishedEvent extends BaseChatEvent { + event: 'toolFinished'; + data: ToolFinished; +} + +export type AiActionStatus = 'RUNNING' | 'SUCCESS' | 'FAILURE' | 'STOPPED'; + +export interface AiAction { + executionId: string; + tool: string; + arguments?: unknown; + status: AiActionStatus; + startedAt: number; + durationMs?: number; + result?: string; +} + export interface ApprovalResult { executionId: string; approved: boolean; @@ -121,7 +154,7 @@ export enum ToolApprovalResult { } export type ChatEvent = AssistantChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent - | TurnResumedEvent | TurnStoppedEvent; + | TurnResumedEvent | TurnStoppedEvent | ToolStartedEvent | ToolFinishedEvent; export enum AiAssistantViewType { DASHBOARD = 'DASHBOARD', diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index 77be22238b..023def6d0b 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/ui-ngx/src/app/shared/models/solution-creator.models.ts @@ -7,7 +7,7 @@ import { EntityId } from '@shared/models/id/entity-id'; import { BaseData } from '@shared/models/base-data'; import { CalculatedFieldType } from '@shared/models/calculated-field.models'; import { AlarmSeverity } from '@shared/models/alarm.models'; -import { ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { AiAction, ToolExecutionRequested, ToolExecutionResult, AiResourceInfo } from '@shared/models/ai-chat.models'; export interface SolutionInfo { id: string; @@ -172,7 +172,7 @@ export interface SolutionStepState { skipInterviewAllowed?: boolean; } -export type ChatMessage = GeneralChatMessage | ApprovalChatMessage; +export type ChatMessage = GeneralChatMessage | ApprovalChatMessage | ActionChatMessage; export interface GeneralChatMessage { from: 'USER' | 'AI' | 'SYSTEM' | 'GENERATE'; @@ -182,6 +182,11 @@ export interface GeneralChatMessage { time?: number; } +export interface ActionChatMessage { + from: 'ACTION'; + data: AiAction; +} + export interface ApprovalChatMessage { from: 'APPROVAL'; data: ToolExecutionRequested; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 213165ffc6..4160d5f34b 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -731,6 +731,252 @@ "attachment-larger-than": "Larger than {{size}}", "attachment-svg-failed": "This SVG can't be converted to an image", "attachment-over-limit": "More than {{count}} files", + "action": { + "search-devices": { + "run": "Looking up devices", + "done": "Looked up devices" + }, + "search-assets": { + "run": "Looking up assets", + "done": "Looked up assets" + }, + "search-dashboards": { + "run": "Looking up dashboards", + "done": "Looked up dashboards" + }, + "search-customers": { + "run": "Looking up customers", + "done": "Looked up customers" + }, + "search-users": { + "run": "Looking up users", + "done": "Looked up users" + }, + "search-tenant": { + "run": "Searching the tenant", + "done": "Searched the tenant" + }, + "read-entity": { + "run": "Reading the record", + "done": "Read the record" + }, + "read-latest-values": { + "run": "Reading the latest values", + "done": "Read the latest values" + }, + "read-history": { + "run": "Reading the history", + "done": "Read the history" + }, + "read-telemetry-keys": { + "run": "Reading the telemetry keys", + "done": "Read the telemetry keys" + }, + "read-attributes": { + "run": "Reading attributes", + "done": "Read attributes" + }, + "save-attributes": { + "run": "Updating the attributes", + "done": "Updated the attributes" + }, + "delete-attributes": { + "run": "Deleting the attributes", + "done": "Deleted the attributes" + }, + "read-relations": { + "run": "Following relations", + "done": "Followed relations" + }, + "read-credentials": { + "run": "Reading the device credentials", + "done": "Read the device credentials" + }, + "save-device": { + "run": "Saving the device", + "done": "Saved the device" + }, + "save-calculated-field": { + "run": "Saving the calculated field", + "done": "Saved the calculated field" + }, + "recalculate-history": { + "run": "Recalculating history", + "done": "Recalculated history" + }, + "save-alarm-rule": { + "run": "Saving the alarm rule", + "done": "Saved the alarm rule" + }, + "create-dashboard": { + "run": "Creating the dashboard", + "done": "Created the dashboard" + }, + "update-dashboard": { + "run": "Updating the dashboard", + "done": "Updated the dashboard" + }, + "add-dashboard-state": { + "run": "Adding a dashboard state", + "done": "Added a dashboard state" + }, + "update-dashboard-state": { + "run": "Updating the dashboard state", + "done": "Updated the dashboard state" + }, + "add-entity-alias": { + "run": "Adding an entity alias", + "done": "Added an entity alias" + }, + "update-entity-alias": { + "run": "Updating the entity alias", + "done": "Updated the entity alias" + }, + "read-entity-alias": { + "run": "Reading the entity alias", + "done": "Read the entity alias" + }, + "add-dashboard-filter": { + "run": "Adding a dashboard filter", + "done": "Added a dashboard filter" + }, + "update-dashboard-filter": { + "run": "Updating the dashboard filter", + "done": "Updated the dashboard filter" + }, + "read-dashboard-filter": { + "run": "Reading the dashboard filter", + "done": "Read the dashboard filter" + }, + "read-dashboard": { + "run": "Reading the dashboard", + "done": "Read the dashboard" + }, + "add-widgets": { + "run": "Adding widgets", + "done": "Added widgets" + }, + "update-widget": { + "run": "Updating the widget", + "done": "Updated the widget" + }, + "place-widgets": { + "run": "Placing the widgets", + "done": "Placed the widgets" + }, + "read-widget": { + "run": "Reading the widget", + "done": "Read the widget" + }, + "lay-out-dashboard": { + "run": "Laying out the dashboard", + "done": "Laid out the dashboard" + }, + "read-dashboard-page": { + "run": "Reading the dashboard page", + "done": "Read the dashboard page" + }, + "save-notification-target": { + "run": "Saving the notification recipients", + "done": "Saved the notification recipients" + }, + "save-notification-template": { + "run": "Saving the notification template", + "done": "Saved the notification template" + }, + "save-notification-rule": { + "run": "Saving the notification rule", + "done": "Saved the notification rule" + }, + "search-iot-hub": { + "run": "Searching IoT Hub", + "done": "Searched IoT Hub" + }, + "read-connection-settings": { + "run": "Looking up the connection settings", + "done": "Looked up the connection settings" + }, + "research-device": { + "run": "Researching the device", + "done": "Researched the device" + }, + "search-web": { + "run": "Searching the web", + "done": "Searched the web" + }, + "read-page": { + "run": "Reading the page", + "done": "Read the page" + }, + "read-site": { + "run": "Reading {{site}}", + "done": "Read {{site}}" + }, + "delete-calculated-field": { + "run": "Deleting the calculated field", + "done": "Deleted the calculated field" + }, + "delete-alarm-rule": { + "run": "Deleting the alarm rule", + "done": "Deleted the alarm rule" + }, + "delete-notification-rule": { + "run": "Deleting the notification rule", + "done": "Deleted the notification rule" + }, + "delete-notification-target": { + "run": "Deleting the notification recipients", + "done": "Deleted the notification recipients" + }, + "delete-notification-template": { + "run": "Deleting the notification template", + "done": "Deleted the notification template" + }, + "delete-dashboard": { + "run": "Deleting the dashboard", + "done": "Deleted the dashboard" + }, + "delete-widget": { + "run": "Deleting the widget", + "done": "Deleted the widget" + }, + "delete-dashboard-state": { + "run": "Deleting the dashboard state", + "done": "Deleted the dashboard state" + }, + "delete-entity-alias": { + "run": "Deleting the entity alias", + "done": "Deleted the entity alias" + }, + "delete-dashboard-filter": { + "run": "Deleting the dashboard filter", + "done": "Deleted the dashboard filter" + }, + "delete-device": { + "run": "Deleting the device", + "done": "Deleted the device" + }, + "delete-other": { + "run": "Deleting", + "done": "Deleted" + }, + "other": { + "run": "Working on a step", + "done": "Finished a step" + }, + "failed": "Failed while {{words}}", + "details": "Details", + "request": "Request", + "result": "Result" + }, + "work": { + "reading-request": "Reading the request", + "going-through-results": "Going through the results", + "applying-change": "Applying the change", + "reading-what-to-change": "Reading what to change", + "still": "Still {{words}}", + "stopped": "Stopped while {{words}}" + }, "file-kind": { "image": "Image", "pdf": "PDF",