diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html index 47735c3c8e..99ccd58434 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html @@ -82,7 +82,19 @@ @for (fact of block.rows; track $index) {
{{ label(fact) }}
- @if (factLink(fact); as url) { + @if (fact.images; as pair) { + + @if (pair.current) { + + + } + @if (pair.value) { + + } @else { + {{ 'ai-assistant.review.not-set' | translate }} + } + + } @else if (factLink(fact); as url) { {{ factValue(fact) }} } @else if (fact.secret && !revealed().has(view().hood?.key + $index)) { {{ masked(factValue(fact)) }} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts index f602dcbf2b..1fb81bb84e 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts @@ -58,6 +58,7 @@ export interface AiDetailFact { entity?: AiDetailEntity; mono?: boolean; secret?: boolean; + images?: {current?: string; value?: string}; } export interface AiDetailCommand { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index 36eedd50bb..fc63f629b7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -30,7 +30,7 @@
@for (fact of facts; track $index) {
@if (fact.labelCode) { {{ fact.label }} } @else { {{ fact.label }} }
-
@if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
+
@if (fact.image) { } @else if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
}
} @@ -47,8 +47,17 @@ @for (change of changes; track $index) { @if (change.labelCode) { {{ change.label }} } @else { {{ change.label }} } - {{ change.current }} - {{ change.value }} + @if (change.image || change.currentImage) { + + @if (change.currentImage) { } @else { {{ change.current }} } + + + @if (change.image) { } @else { {{ change.value }} } + + } @else { + {{ change.current }} + {{ change.value }} + } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index 4f43876bbc..7fb3bd4d71 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -37,6 +37,8 @@ export interface AiReviewRow { valueCode: boolean; current?: string; value: string; + image?: boolean; + currentImage?: boolean; } const MAX_FIELDS = 5; @@ -52,6 +54,10 @@ const VALUE_TOKENS: Record = { const CODE_FIELDS = new Set(['arguments', 'expression', 'output']); +const IMAGE_FIELDS = new Set(['widget-image']); + +const IMAGE_VALUE = /^(tb-image;|\/api\/images\/|data:image\/)/; + const STACK_AT = 24; const OWN_TYPE_LABELS = new Set(['DASHBOARD_WIDGET', 'DASHBOARD_STATE', 'DASHBOARD_ENTITY_ALIAS', 'DASHBOARD_FILTER', 'NOTIFICATION', 'NOTIFICATION_SETTINGS', 'NOTIFICATION_PREFERENCES', 'IMAGE', 'PLATFORM_SETTINGS', 'RELATION', 'VERSION', 'WHITE_LABELING', 'MAIL_TEMPLATE', 'CUSTOM_TRANSLATION', 'CUSTOM_MENU', 'MOBILE_APP', 'MOBILE_BUNDLE', 'MOBILE_QR_CODE', 'TWO_FACTOR_SETTINGS', 'MY_PROFILE', 'MY_TWO_FACTOR', 'MAIL_SERVER', 'REPORT_COMPONENT', 'REPORT_ENTITY_ALIAS', 'REPORT_FILTER', 'SCHEDULED_REPORT']); @@ -221,7 +227,7 @@ export class AiApprovalCardComponent implements OnChanges { } get facts(): AiReviewRow[] { - const rows = this.rows('FACT').slice(0, MAX_FIELDS); + const rows = [...this.rows('FACT').slice(0, MAX_FIELDS), ...this.rows('CHANGE', field => field.current === undefined || field.current === null)]; if (this.listing && this.review?.target) { rows.push({label: this.translate.instant('ai-assistant.record.set-up-on'), labelCode: false, valueCode: false, value: this.review.target}); } @@ -230,8 +236,11 @@ export class AiApprovalCardComponent implements OnChanges { private reviewFacts(): AiDetailFact[] { return [ - ...this.rows('FACT').map(row => ({label: row.label, raw: true, value: row.value, mono: row.valueCode})), - ...this.rows('CHANGE').map(row => ({label: row.label, raw: true, value: `${row.current ?? '—'} → ${row.value}`, mono: row.valueCode})) + ...this.rows('FACT').map(row => row.image ? {label: row.label, raw: true, images: {value: row.value}} + : {label: row.label, raw: true, value: row.value, mono: row.valueCode}), + ...this.rows('CHANGE').map(row => row.image || row.currentImage + ? {label: row.label, raw: true, images: {current: row.currentImage ? row.current : undefined, value: row.image ? row.value : undefined}} + : {label: row.label, raw: true, value: `${row.current ?? '—'} → ${row.value}`, mono: row.valueCode}) ]; } @@ -240,7 +249,7 @@ export class AiApprovalCardComponent implements OnChanges { } get changes(): AiReviewRow[] { - return this.rows('CHANGE'); + return this.rows('CHANGE', field => field.current !== undefined && field.current !== null); } get unchanged(): AiReviewRow[] { @@ -294,13 +303,15 @@ export class AiApprovalCardComponent implements OnChanges { }); } - private rows(kind: AiReviewField['kind']): AiReviewRow[] { - return (this.review?.fields ?? []).filter(field => field.kind === kind).map(field => ({ + private rows(kind: AiReviewField['kind'], include: (field: AiReviewField) => boolean = () => true): AiReviewRow[] { + return (this.review?.fields ?? []).filter(field => field.kind === kind && include(field)).map(field => ({ label: field.name ?? this.translate.instant('ai-assistant.review.field.' + field.id), labelCode: !!field.name, valueCode: CODE_FIELDS.has(field.id) && field.value !== undefined && field.value !== null, current: kind === 'CHANGE' ? this.value(field, field.current) : undefined, - value: this.value(field, field.value) + value: this.value(field, field.value), + image: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.value ?? ''), + currentImage: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.current ?? '') })); } 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 3bd8f96d37..fe2618f3b9 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 @@ -959,9 +959,11 @@ export class AiChatComponent implements OnInit, OnDestroy { case 'assistantDelta': this.appendDelta(event.data.text); break; - case 'thinking': - this.work.update(work => work && event.data?.headline ? {...work, headline: event.data.headline} : work); + case 'thinking': { + const headline = this.thinkingHeadline(event.data); + this.work.update(work => work && headline ? {...work, headline} : work); break; + } case 'assistantMessage': this.messages.update(list => [...this.withoutStreaming(list), { from: 'AI', content: event.data.message, time: Date.now(), @@ -1098,6 +1100,14 @@ export class AiChatComponent implements OnInit, OnDestroy { this.router.navigate(['/reporting/templates', created.id]); } + private thinkingHeadline(data: {headline?: string; tool?: string; arguments?: unknown} | undefined): string | undefined { + if (data?.tool) { + const words = aiActionWords(data.tool, data.arguments); + return this.translate.instant(words.key + '.run', words.params); + } + return data?.headline; + } + private openCreatedWidget(tool: string | undefined, affected: EntityId[] | undefined): void { const chatId = this.chatId(); const created = affected?.find(entity => entity.entityType === EntityType.WIDGET_TYPE); @@ -1316,9 +1326,10 @@ export class AiChatComponent implements OnInit, OnDestroy { this.stopping.set(false); this.work.set(undefined); this.stopRunningActions(); - if (this.affectedEntities.length) { - this.panelService.emitUpdatedData(this.affectedEntities); - this.affectedEntities = []; + const notYetReloaded = this.affectedEntities.filter(entity => !LIVE_EDITED_TYPES.has(entity.entityType as EntityType)); + this.affectedEntities = []; + if (notYetReloaded.length) { + this.panelService.emitUpdatedData(notYetReloaded); } this.chats.setReplying(this.replyingChatId, false); this.replyingChatId = undefined; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts index 5c2820c97d..bbd64dc9e1 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -29,6 +29,15 @@ export function aiDashboardThumb(cards: number): string { + `${rows}`; } +export function aiWidgetThumb(): string { + return `` + + `` + + `` + + `` + + `` + + ``; +} + @Component({ selector: 'tb-ai-record-card', template: ` @@ -155,7 +164,7 @@ export class AiRecordCardComponent { picture = computed(() => { const view = this.view(); - return !!(view.image || view.imageUrl || view.entityType === EntityType.DASHBOARD); + return !!(view.image || view.imageUrl || view.entityType === EntityType.DASHBOARD || view.entityType === EntityType.WIDGET_TYPE); }); primaryAction = computed(() => { @@ -168,7 +177,8 @@ export class AiRecordCardComponent { hasFoot = computed(() => !!this.note() || this.facts().length > 0 || this.actions().length > 0); - thumb = computed(() => this.sanitizer.bypassSecurityTrustHtml(aiDashboardThumb(this.view().widgets ?? 4))); + thumb = computed(() => this.sanitizer.bypassSecurityTrustHtml(this.view().entityType === EntityType.WIDGET_TYPE + ? aiWidgetThumb() : aiDashboardThumb(this.view().widgets ?? 4))); openLabel = computed(() => this.translate.instant('ai-assistant.record.open-type', {type: this.typeWord()})); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts index da066c3c7e..578c71b5c3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts @@ -185,9 +185,11 @@ export class AiRecordLoaderService { meta: this.translate.instant(template.type === ReportTemplateType.SUB_REPORT ? 'ai-assistant.record.sub-report' : 'ai-assistant.record.report') }))); case EntityType.WIDGET_TYPE: - return this.http.get<{name: string; widgetType?: string}>(`/api/widgetTypeInfo/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + return this.http.get<{name: string; widgetType?: string; image?: string; description?: string}>(`/api/widgetTypeInfo/${entity.id}`, + defaultHttpOptionsFromConfig(CONFIG)) .pipe(map(info => ({ key, entityType, alarmRule: false, name: info.name, url: `/resources/widgets-library/widget-types/${entity.id}`, + image: info.image || undefined, description: info.description || undefined, meta: info.widgetType && widgetTypesData.get(info.widgetType as widgetType) ? this.translate.instant(widgetTypesData.get(info.widgetType as widgetType).name) : undefined }))); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts index 77d4a6d1e1..174ec7b836 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts @@ -10,6 +10,8 @@ import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.m import { AiRecordView } from '@home/components/ai/ai-record.models'; import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +const LEAD_TYPES = new Set([EntityType.DASHBOARD, EntityType.WIDGET_TYPE]); + @Component({ selector: 'tb-ai-run-summary', template: ` @@ -57,7 +59,7 @@ export class AiRunSummaryComponent { rows = signal([]); - lead = computed(() => this.rows().find(row => row.entityType === EntityType.DASHBOARD && !!row.url) ?? null); + lead = computed(() => this.rows().find(row => LEAD_TYPES.has(row.entityType as EntityType) && !!row.url) ?? null); rest = computed(() => this.rows().filter(row => row !== this.lead())); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts index 8fc84f76c1..a67a7b7cab 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts @@ -1,9 +1,8 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { Injectable } from '@angular/core'; -import { from, Observable, of } from 'rxjs'; +import { firstValueFrom, from, Observable, of } from 'rxjs'; import { catchError, filter, map, switchMap, take, timeout } from 'rxjs/operators'; -import html2canvas from 'html2canvas'; import { WidgetService } from '@core/http/widget.service'; import { AiResourceService } from '@core/http/ai-resource.service'; import { migrateWidgetTypeToDynamicForms } from '@shared/models/widget.models'; @@ -15,6 +14,8 @@ const MAX_REASON_LENGTH = 1900; const MAX_LINE_LENGTH = 300; const PREVIEW_WIDTH = 1280; const PREVIEW_HEIGHT = 800; +const STYLE_CHUNK = 8; +const ICON_FONT = /material (icons|symbols)/i; interface WidgetCheckReport { initialised: boolean; @@ -26,6 +27,8 @@ interface WidgetCheckReport { screenshot?: string; } +type CapturedReport = WidgetCheckReport & {canvas?: HTMLCanvasElement}; + @Injectable({ providedIn: 'root' }) @@ -50,9 +53,9 @@ export class AiWidgetCheckService { ); } - private run(widget: WidgetInfo): Promise { + private run(widget: WidgetInfo): Promise { return new Promise(resolve => { - const report: WidgetCheckReport & {canvas?: HTMLCanvasElement} = {initialised: false, errors: [], console: []}; + const report: CapturedReport = {initialised: false, errors: [], console: []}; const config = JSON.parse(widget.defaultConfig || '{}'); config.title = config.title || widget.widgetName; const frame = document.createElement('iframe'); @@ -142,29 +145,98 @@ export class AiWidgetCheckService { } } - private capture(frame: HTMLIFrameElement): Promise { + private async capture(frame: HTMLIFrameElement): Promise { const doc = frame.contentDocument; + const win = frame.contentWindow; const target = (doc?.querySelector('tb-widget-container') || doc?.querySelector('tb-widget')) as HTMLElement; - if (!target) { - return Promise.resolve(undefined); + if (!target || !win) { + return undefined; + } + const rect = target.getBoundingClientRect(); + const width = Math.ceil(rect.width); + const height = Math.ceil(rect.height); + if (!width || !height) { + return undefined; + } + const clone = target.cloneNode(true) as HTMLElement; + const sources = [target, ...Array.from(target.querySelectorAll('*'))]; + const copies = [clone, ...Array.from(clone.querySelectorAll('*'))]; + for (let i = 0; i < sources.length; i++) { + if (i % STYLE_CHUNK === STYLE_CHUNK - 1) { + await new Promise(resolve => setTimeout(resolve)); + } + this.copyElement(win, sources[i], copies[i]); + } + const markup = new XMLSerializer().serializeToString(clone); + const svg = `` + + `${markup}`; + const image = new Image(); + image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg); + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + canvas.getContext('2d').drawImage(image, 0, 0); + return canvas; + } + + private copyElement(win: Window, source: Element, copy: Element) { + const style = win.getComputedStyle(source); + let text = ''; + for (const property of Array.from(style)) { + if (!property.startsWith('--')) { + text += `${property}:${style.getPropertyValue(property)};`; + } + } + copy.setAttribute('style', text); + const glyph = source.tagName !== 'CANVAS' && ICON_FONT.test(style.fontFamily) && source.childElementCount === 0; + const image = source.tagName === 'CANVAS' ? this.canvasImage(source as HTMLCanvasElement) + : glyph ? this.glyphImage(win, source, style) : undefined; + if (glyph && !image) { + copy.setAttribute('style', text + 'visibility:hidden;'); + return; + } + if (image) { + const img = copy.ownerDocument.createElement('img'); + img.setAttribute('src', image); + img.setAttribute('style', text); + copy.replaceWith(img); } - return html2canvas(target, {logging: false, useCORS: true, backgroundColor: null, scale: 1}) - .catch(() => undefined); } - private attachScreenshot(report: WidgetCheckReport & {canvas?: HTMLCanvasElement}): Observable { + private canvasImage(canvas: HTMLCanvasElement): string | undefined { + try { + return canvas.toDataURL(); + } catch (e) { + return undefined; + } + } + + private glyphImage(win: Window, source: Element, style: CSSStyleDeclaration): string | undefined { + const rect = source.getBoundingClientRect(); + const glyph = source.textContent?.trim(); + if (!glyph || !rect.width || !rect.height) { + return undefined; + } + const canvas = win.document.createElement('canvas'); + canvas.width = Math.ceil(rect.width); + canvas.height = Math.ceil(rect.height); + const context = canvas.getContext('2d'); + context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`; + context.fillStyle = style.color; + context.textAlign = 'center'; + context.textBaseline = 'middle'; + context.fillText(glyph, canvas.width / 2, canvas.height / 2); + return this.canvasImage(canvas); + } + + private attachScreenshot(report: CapturedReport): Observable { const canvas = report.canvas; delete report.canvas; - if (!canvas) { - return of(report); - } - return from(new Promise(resolve => canvas.toBlob(blob => resolve(blob), 'image/png'))).pipe( - switchMap(blob => blob ? this.aiResources.upload(new File([blob], 'widget-check.png', {type: 'image/png'})) : of(null)), - filter(event => !event || event.type === 'done'), - take(1), - map(event => { - if (event?.type === 'done' && event.resource?.id) { - report.screenshot = event.resource.id; + return from(this.upload(canvas, 'widget-check.png')).pipe( + map(screenshot => { + if (screenshot) { + report.screenshot = screenshot; } return report; }), @@ -172,6 +244,19 @@ export class AiWidgetCheckService { ); } + private upload(canvas: HTMLCanvasElement | undefined, name: string): Promise { + if (!canvas) { + return Promise.resolve(undefined); + } + return new Promise(resolve => canvas.toBlob(blob => resolve(blob), 'image/png')).then(blob => !blob ? undefined : + firstValueFrom(this.aiResources.upload(new File([blob], name, {type: 'image/png'})).pipe( + filter(event => event.type === 'done'), + take(1), + map(event => event.type === 'done' ? event.resource?.id : undefined), + catchError(() => of(undefined)) + ), {defaultValue: undefined})); + } + private toReason(report: WidgetCheckReport): string { const trimmed: WidgetCheckReport = {...report, errors: report.errors.slice(0, 6), console: [...new Set(report.console)].slice(0, 5)}; let reason = JSON.stringify(trimmed); 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 index cdbf19657c..d5f567a735 100644 --- 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 @@ -1,6 +1,6 @@ // 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 { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, linkedSignal, NgZone, OnInit, signal } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { AiSpinKind, aiWorkClock } from '@home/components/ai/ai-action.models'; @@ -41,9 +41,18 @@ export class AiWorkLineComponent implements OnInit { private elapsed = computed(() => Math.max(0, this.now() - this.since())); + private shown = computed(() => ({words: this.words(), since: this.since()}), { + equal: (a, b) => a.words === b.words && a.since === b.since + }); + + private wordsSince = linkedSignal<{words: string; since: number}, number>({ + source: this.shown, + computation: (shown, previous) => !previous || previous.source.since !== shown.since ? shown.since : Date.now() + }); + say = computed(() => { const words = this.words(); - if (this.held() || this.elapsed() < STILL_AFTER_MS || !words) { + if (this.held() || this.now() - this.wordsSince() < STILL_AFTER_MS || !words) { return words; } return this.translate.instant('ai-assistant.work.still', {words: words.charAt(0).toLocaleLowerCase() + words.slice(1)}); 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 7233c3771e..1116170aa8 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -244,7 +244,7 @@ export interface AssistantDeltaChatEvent extends BaseChatEvent { export interface ThinkingChatEvent extends BaseChatEvent { event: 'thinking'; - data: {headline: string}; + data: {headline?: string; tool?: string; arguments?: unknown}; } export type ChatEvent = AssistantChatEvent | AssistantDeltaChatEvent | ToolExecutionRequestedEvent | ToolExecutionResultEvent | ErrorEvent | ChatTitleGeneratedEvent diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 15d5714aaf..385008ad31 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -1269,6 +1269,41 @@ } } +.k-detail-images { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--tb-text-muted); +} + +.k-detail-img { + display: block; + width: 100px; + height: 80px; + object-fit: contain; + border: 1px solid var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + background: #fff; + + &.was { + opacity: .6; + } +} + +.k-review .k-img { + display: block; + width: 150px; + height: 120px; + object-fit: contain; + border: 1px solid var(--tb-ink-12, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + background: #fff; + + &.was { + opacity: .6; + } +} + .k-review code, .k-diff code { display: inline-block;