Browse Source

Merge pull request #16856 from thingsboard/rc

Merge rc into master
pull/16830/merge
Vladyslav Prykhodko 4 days ago
committed by GitHub
parent
commit
669f361521
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 20
      ui-ngx/src/app/core/services/ai-assistant-panel.service.ts
  2. 20
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html
  3. 4
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts
  4. 105
      ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts
  5. 94
      ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html
  6. 164
      ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss
  7. 121
      ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts
  8. 228
      ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts
  9. 77
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html
  10. 116
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts
  11. 2
      ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts
  12. 91
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  13. 26
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss
  14. 243
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts
  15. 29
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html
  16. 207
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  17. 42
      ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html
  18. 111
      ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts
  19. 23
      ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html
  20. 73
      ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts
  21. 41
      ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts
  22. 74
      ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html
  23. 95
      ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts
  24. 60
      ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html
  25. 26
      ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts
  26. 22
      ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html
  27. 65
      ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts
  28. 25
      ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html
  29. 48
      ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts
  30. 14
      ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss
  31. 186
      ui-ngx/src/app/modules/home/components/ai/ai-question.component.html
  32. 171
      ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts
  33. 97
      ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts
  34. 19
      ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts
  35. 11
      ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts
  36. 5
      ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts
  37. 5
      ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts
  38. 6
      ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts
  39. 158
      ui-ngx/src/app/modules/home/components/ai/ai-references.ts
  40. 6
      ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts
  41. 19
      ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html
  42. 26
      ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts
  43. 4
      ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts
  44. 41
      ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts
  45. 18
      ui-ngx/src/app/modules/home/components/ai/ai-text.ts
  46. 7
      ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss
  47. 10
      ui-ngx/src/app/modules/home/components/ai/ai.module.ts
  48. 6
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html
  49. 4
      ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html
  50. 3
      ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html
  51. 27
      ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss
  52. 16
      ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts
  53. 12
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts
  54. 9
      ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts
  55. 7
      ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts
  56. 2
      ui-ngx/src/app/modules/home/home.component.scss
  57. 2
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.html
  58. 13
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss
  59. 15
      ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.ts
  60. 18
      ui-ngx/src/app/modules/login/pages/login/login.component.ts
  61. 2
      ui-ngx/src/app/modules/tour/welcome-invitation.component.scss
  62. 12
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  63. 10
      ui-ngx/src/app/shared/models/solution-creator.models.ts
  64. 288
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  65. 1355
      ui-ngx/src/theme/ai-theme.scss

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

@ -448,11 +448,31 @@ export class AiAssistantPanelService implements OnDestroy {
}
}
private readonly _keptEdits = signal<{kind: 'dashboard' | 'entity'; reload: () => void} | null>(null);
readonly keptEdits = this._keptEdits.asReadonly();
keepEdits(kind: 'dashboard' | 'entity', reload: () => void): void {
this._keptEdits.set({kind, reload});
}
clearKeptEdits(kind?: 'dashboard' | 'entity'): void {
if (!kind || this._keptEdits()?.kind === kind) {
this._keptEdits.set(null);
}
}
reloadKeptEdits(): void {
const kept = this._keptEdits();
this._keptEdits.set(null);
kept?.reload();
}
emitUpdatedData(affectedEntities: Array<EntityId>): void {
this._updatedData$.next(affectedEntities);
}
teardown(): void {
this._keptEdits.set(null);
this._editorDraftProvider = null;
this._enabled.set(false);
this._detailsOpen.set(false);

20
ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html

@ -5,14 +5,14 @@
-->
@if (hood()) {
<p class="k-hood"><mat-icon class="tb-mat-16" aria-hidden="true">code</mat-icon><span>{{ hood() }}</span></p>
<p class="k-asked"><b>{{ 'ai-assistant.detail.asked-for' | translate }}</b>{{ hood() }}</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"
<tb-ai-record role="listitem" [entityType]="rec.entityType" [alarmRule]="rec.alarmRule" [groupType]="rec.groupType" [name]="rec.name" [badge]="rec.badge" [url]="rec.url"
[hub]="rec.hub"></tb-ai-record>
}
@if (hub().length > LIST_SHOWN) {
@ -26,14 +26,19 @@
}
<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>
<div class="tb-rec line" [attr.data-pal]="kind(row.entityType, row.groupType).palette">
<span class="tb-rec-tile"><tb-icon aria-hidden="true">{{ kind(row.entityType, row.groupType).icon }}</tb-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) {
@if (row.status) {
<span class="tb-rec-meta k-sev-quiet"><tb-ai-sev-mark [severity]="(row.severity || 'INDETERMINATE').toUpperCase()"></tb-ai-sev-mark>{{ 'ai-assistant.detail.alarm-meta' | translate:{
severity: ('alarm.severity-' + (row.severity || 'indeterminate').toLowerCase()) | translate,
status: ('ai-assistant.detail.alarm-status.' + row.status) | translate,
since: row.since || '—'} }}</span>
} @else if (row.meta) {
<span class="tb-rec-meta">{{ row.meta }}</span>
}
</div>
@ -99,7 +104,7 @@
@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>
<tb-icon class="tb-mat-16" aria-hidden="true">{{ chip.icon }}</tb-icon>
}
{{ factValue(fact) }}
</span>
@ -166,6 +171,9 @@
}
</div>
}
@case ('warning') {
<div class="k-warn-block" role="note"><span class="tb-ai-sr-only">{{ 'ai-assistant.detail.heads-up' | translate }}</span>@if (block.label) {<b>{{ say(block.label) }}</b> }@for (row of block.rows; track $index) {<span>{{ rowText(row) }}</span>@if (!$last) {<span>; </span>}}</div>
}
@case ('note') {
<p class="k-detail-note">{{ say(block.text) }}</p>
}

4
ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts

@ -184,8 +184,8 @@ export class AiActionDetailComponent {
return this.urlOf(record.id, record.entityType);
}
kind(entityType: string) {
return entityType === 'IMAGE' ? {icon: 'image', palette: 'view'} : aiEntityKind(entityType, entityType === 'ALARM_RULE');
kind(entityType: string, groupType?: string) {
return entityType === 'IMAGE' ? {icon: 'image', palette: 'view'} : aiEntityKind(entityType, entityType === 'ALARM_RULE', groupType);
}
more(block: AiDetailBlock): number {

105
ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { aiTrueMinus } from '@home/components/ai/ai-text';
import { AiAction } from '@shared/models/ai-chat.models';
import { aiPartTitle, aiPartWord, AiWordList, aiWordList, alarmUpdateAction, widgetParts } from '@home/components/ai/ai-action.models';
import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models';
@ -29,6 +30,8 @@ export interface AiDetailRecord {
name: string;
meta?: string;
severity?: string;
status?: string;
since?: string;
}
export interface AiDetailHubItem {
@ -94,7 +97,8 @@ export type AiDetailBlock =
| {type: 'note'; text: AiDetailText}
| {type: 'text'; text: string}
| {type: 'json'; label: string; text: string}
| {type: 'images'; rows: AiDetailImage[]};
| {type: 'images'; rows: AiDetailImage[]}
| {type: 'warning'; label?: AiDetailText; rows: Array<string | AiDetailText>};
export interface AiDetailImage {
label?: AiDetailText;
@ -108,6 +112,36 @@ export interface AiDetailView {
export type AiDetailNames = ReadonlyMap<string, AiDetailEntity>;
export interface AiStepView {
askedFor?: AiDetailText;
blocks: AiDetailBlock[];
under: AiDetailBlock[];
}
const ASKED_FOR: Record<string, string> = {
'search-named': 'named', 'search-typed': 'typed', 'search-text': 'text', 'search-related-from': 'related-from',
'search-related-to': 'related-to', 'search-alarms-of': 'alarms-of', 'read-attributes-scope': 'attributes-scope',
'read-history': 'history', 'read-history-keys': 'history-keys', 'read-latest-keys': 'latest-keys', 'iot-hub-query': 'query',
'search-web': 'query'
};
export function aiStepView(action: AiAction, names: AiDetailNames): AiStepView {
const view = aiActionDetailView(action, names);
const hood = view.hood?.key.slice(K.length);
const asked = hood ? ASKED_FOR[hood] : undefined;
const askedFor = asked ? {key: K + 'asked.' + asked, params: view.hood.params} : undefined;
const under: AiDetailBlock[] = [];
const blocks: AiDetailBlock[] = [];
for (const block of view.blocks) {
if (block.type === 'list' && block.label?.key === K + 'widget-warnings') {
under.push({type: 'warning', label: block.label, rows: block.rows});
} else {
blocks.push(block);
}
}
return {askedFor, blocks, under};
}
const K = 'ai-assistant.detail.';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@ -195,16 +229,17 @@ const idOf = (value: unknown): string | undefined => typeof value === 'string' ?
const okId = (result: unknown): string | undefined => typeof result === 'string' ? OK_ID.exec(result.trim())?.[1] : undefined;
export function aiValueText(value: unknown): string {
if (value === null || value === undefined) {
return '—';
}
if (typeof value === 'number') {
return Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000);
return aiTrueMinus(Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000));
}
if (typeof value === 'string') {
const parsed = aiParse(value);
return parsed !== value ? aiValueText(parsed) : value.length > 120 ? value.slice(0, 120) + '…' : value;
return parsed !== value ? aiValueText(parsed) : aiTrueMinus(value.length > 120 ? value.slice(0, 120) + '…' : value);
}
if (typeof value === 'boolean') {
return String(value);
@ -213,9 +248,16 @@ export function aiValueText(value: unknown): string {
return json.length > 120 ? json.slice(0, 120) + '…' : json;
}
const ACRONYMS: ReadonlySet<string> = new Set(['fqn', 'id', 'url', 'uri', 'ip', 'api', 'mqtt', 'mqtts', 'http', 'https', 'coap', 'coaps',
'lwm2m', 'snmp', 'ota', 'json', 'tls', 'ssl', 'rpc', 'tbel', 'js', 'ttn', 'tti', 'sms', 'eui', 'oid', 'qos', 'cf']);
export const aiHumanize = (key: string): string => {
const words = key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase();
return words ? words.charAt(0).toUpperCase() + words.slice(1) : key;
if (!words) {
return key;
}
const cased = words.split(' ').map(word => ACRONYMS.has(word) ? word.toUpperCase() : word).join(' ');
return cased.charAt(0).toUpperCase() + cased.slice(1);
};
function entity(id: unknown, entityType: unknown, names: AiDetailNames): AiDetailEntity {
@ -455,15 +497,12 @@ function searchType(values: Values): string | undefined {
return FILTER_TYPES[values.filterType] ?? str(filter.entityType) ?? str(filter.singleEntity?.entityType) ?? str(filter.groupType && 'ENTITY_GROUP');
}
function alarmMeta(row: Values): string {
return [row.severity, row.status, timeOf(row.startTs) ? new Date(timeOf(row.startTs)).toLocaleString() : undefined]
.filter(Boolean).map(String).join(' · ');
}
function recordOf(row: Values, entityType: string): AiDetailRecord | null {
if (entityType === 'ALARM') {
const alarmName = str(row.type) ?? str(row.name);
return alarmName ? {entityType, id: idOf(row.id), name: alarmName, meta: alarmMeta(row), severity: str(row.severity)} : null;
return alarmName ? {entityType, id: idOf(row.id), name: alarmName, severity: str(row.severity)?.toUpperCase(), status: str(row.status)?.toUpperCase(),
since: timeOf(row.startTs) ? dateText(timeOf(row.startTs)) : undefined} : null;
}
const name = str(row.name) ?? str(row.title) ?? str(row.email) ?? str(row.label);
if (!name) {
@ -867,9 +906,22 @@ function changes(values: Values, skip: string[], names: AiDetailNames): AiDetail
return rows.length ? [{type: 'facts', rows}] : [];
}
const MODEL_TEXT_FIELDS: ReadonlySet<string> = new Set(['note']);
function withoutModelText(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(withoutModelText);
}
if (!isObject(value)) {
return value;
}
return Object.fromEntries(Object.entries(value).filter(([key]) => !MODEL_TEXT_FIELDS.has(key))
.map(([key, item]) => [key, withoutModelText(item)]));
}
export function aiActionDetailView(action: AiAction, names: AiDetailNames): AiDetailView {
const values: Values = isObject(aiParse(action.arguments)) ? aiParse(action.arguments) as Values : {};
const result = aiParse(action.result);
const result = withoutModelText(aiParse(action.result));
const failed = action.status === 'FAILURE';
const view = describe(action.tool, values, result, names);
if (failed) {
@ -912,7 +964,7 @@ function grantMeta(grant: Values): string | undefined {
function groupRows(groups: unknown): AiDetailRecord[] {
return (Array.isArray(groups) ? groups.filter(isObject) : []).map(group => ({
entityType: 'ENTITY_GROUP', id: str(group.id), name: str(group.name) ?? '—',
entityType: 'ENTITY_GROUP', groupType: 'USER', id: str(group.id), name: str(group.name) ?? '—',
meta: (Array.isArray(group.grants) ? group.grants.filter(isObject) : []).map(grantMeta).filter(Boolean).join('; ') || undefined
}));
}
@ -975,7 +1027,7 @@ function sentNotification(result: unknown): AiDetailBlock[] {
rows.push({label: K + 'fact.status', value: K + 'notification-status.' + String(result.status).toLowerCase()});
}
if (str(result.sendsAt)) {
rows.push({label: K + 'fact.sends-at', value: new Date(result.sendsAt).toLocaleString()});
rows.push({label: K + 'fact.sends-at', value: dateText(result.sendsAt)});
}
if (str(result.usersTargetName)) {
rows.push({label: K + 'fact.recipients', value: result.usersTargetName});
@ -1100,7 +1152,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
'debugSettings', 'configuration', 'version', 'configurationVersion', ...(configured ? ['entityId', 'description'] : [])], names)
];
if (read.createdTime) {
rows.push({label: K + 'fact.created', value: new Date(read.createdTime).toLocaleString()});
rows.push({label: K + 'fact.created', value: dateText(read.createdTime)});
}
return {hood: text('read-entity', {entity: {...target, name: record.name}}), blocks: [{type: 'records', rows: [record]}, ...(rows.length ? [{type: 'facts', rows} as AiDetailBlock] : [])]};
}
@ -1167,11 +1219,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
if (Array.isArray(result.disabled) && result.disabled.length) {
rows.push({label: K + 'fact.disabled', value: result.disabled.map((name: string) => name.toUpperCase()).join(', ')});
}
const blocks: AiDetailBlock[] = [{type: 'facts', rows}];
if (str(result.note)) {
blocks.push({type: 'text', text: result.note});
}
return {hood: text('read-endpoints'), blocks};
return {hood: text('read-endpoints'), blocks: [{type: 'facts', rows}]};
}
case 'read_device_connect_commands': {
const rows = commands(result);
@ -1348,7 +1396,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
rows.push({label: K + 'fact.version', value: result.version});
}
if (str(result.lastConnect)) {
rows.push({label: K + 'fact.last-connect', value: new Date(result.lastConnect).toLocaleString()});
rows.push({label: K + 'fact.last-connect', value: dateText(result.lastConnect)});
}
const blocks: AiDetailBlock[] = [{type: 'facts', rows}];
const connectors = Array.isArray(result.connectors) ? result.connectors.filter(isObject) : [];
@ -1801,7 +1849,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
}
if (Array.isArray(result.menus)) {
const rows = result.menus.filter(isObject).slice(0, MAX_ROWS).map(menu => `${menu.name} · ${aiHumanize(String(menu.scope))} · ${aiHumanize(String(menu.assigneeType))}`);
return {hood: text('read-custom-menus'), blocks: rows.length ? [{type: 'list', rows}] : generic(result.note, 'result')};
return {hood: text('read-custom-menus'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('nothing-found')}]};
}
const rows: string[] = [];
const walk = (items: unknown, depth: number) => {
@ -1869,7 +1917,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
const counts: AiDetailFact[] = Object.entries(isObject(result.counts) ? result.counts : {})
.map(([state, count]) => ({label: aiHumanize(state), raw: true, value: String(count)}));
const rows = (Array.isArray(result.downlinks) ? result.downlinks.filter(isObject) : []).slice(0, MAX_ROWS)
.map(event => [event.status, event.type, event.action, str(event.time) ? new Date(event.time).toLocaleString() : undefined]
.map(event => [event.status, event.type, event.action, str(event.time) ? dateText(event.time) : undefined]
.filter(Boolean).join(' · '));
const blocks: AiDetailBlock[] = counts.length ? [{type: 'facts', rows: counts}] : [];
if (rows.length) {
@ -2030,7 +2078,7 @@ function describe(tool: string, values: Values, result: unknown, names: AiDetail
return {hood: text('read-versions'), blocks: generic(result, 'result')};
}
const rows = versions.slice(0, MAX_ROWS).map(version => [str(version.name), str(version.author),
str(version.time) ? new Date(version.time).toLocaleString() : undefined].filter(Boolean).join(' · '));
str(version.time) ? dateText(version.time) : undefined].filter(Boolean).join(' · '));
return {hood: text('read-versions'), blocks: rows.length ? [{type: 'list', rows}] : []};
}
case 'commit_version': {
@ -2140,7 +2188,7 @@ function auditLogBlocks(result: unknown): AiDetailBlock[] {
}
const rows: AiDetailRecord[] = logs.slice(0, MAX_ROWS).map(log => {
const target = isObject(log.entity) ? log.entity : {};
const when = str(log.time) ? new Date(log.time).toLocaleString() : undefined;
const when = str(log.time) ? dateText(log.time) : undefined;
const meta = [str(log.action) ? aiHumanize(log.action) : undefined, str(log.user), when, log.status === 'FAILURE' ? '✕' : undefined]
.filter(Boolean).join(' · ');
return {entityType: str(target.type) ?? 'USER', id: str(target.id), name: str(target.name) ?? str(target.type) ?? '—', meta};
@ -2172,10 +2220,19 @@ function endText(value: unknown): string {
return shown === '—' ? K + 'now' : shown;
}
export function aiDateText(date: Date, locale?: string): string {
const now = new Date();
const today = now.toDateString() === date.toDateString();
const options: Intl.DateTimeFormatOptions = today ? {hour: 'numeric', minute: '2-digit'}
: date.getFullYear() === now.getFullYear() ? {day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit'}
: {day: 'numeric', month: 'short', year: 'numeric', hour: 'numeric', minute: '2-digit'};
return new Intl.DateTimeFormat(locale || undefined, options).format(date);
}
function dateText(value: unknown): string {
const parsed = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value;
const date = typeof parsed === 'number' ? new Date(parsed) : typeof parsed === 'string' ? new Date(parsed) : null;
return date && !isNaN(date.getTime()) ? date.toLocaleString([], {dateStyle: 'medium', timeStyle: 'short'}) : '—';
return date && !isNaN(date.getTime()) ? aiDateText(date) : '—';
}
const NAMES_CACHE = new Map<string, Map<string, AiDetailEntity>>();

94
ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html

@ -6,38 +6,80 @@
-->
@switch (action().status) {
@case ('RUNNING') {
<tb-ai-work-line [words]="running()" [kind]="words().kind" [since]="action().startedAt"></tb-ai-work-line>
<tb-ai-work-line [words]="action().progress ? runWords() : running()" [kind]="words().kind" [since]="action().startedAt"></tb-ai-work-line>
@if (action().progress) {
<ul class="k-stages" role="list">
@for (stage of action().stages ?? []; track $index) {
<li class="k-stage"><mat-icon class="tb-mat-18" aria-hidden="true">check</mat-icon>{{ stage }}</li>
}
<li class="k-stage now"><span class="k-stage-ring" aria-hidden="true"></span>{{ action().progress }}</li>
</ul>
}
}
@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 class="k-out" [class.opens]="hasDetails()" (click)="lineClicked($event)">
@switch (mark()) {
@case ('fail') {
<mat-icon class="k-mark fail" aria-hidden="true">error_outline</mat-icon>
}
</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>
@case ('web') {
<mat-icon class="k-mark web" aria-hidden="true">language</mat-icon>
}
<tb-ai-action-detail [view]="detail()" [names]="names()"></tb-ai-action-detail>
</tb-ai-disclosure>
}
@case ('auto') {
<span class="k-mark auto" role="img" [attr.aria-label]="'ai-assistant.action.done-auto' | translate"><mat-icon>check</mat-icon><span class="k-mark-bolt" aria-hidden="true"><mat-icon>bolt</mat-icon></span></span>
}
@default {
<mat-icon class="k-mark" aria-hidden="true">check</mat-icon>
}
}
@let parts = lineParts();
<span class="k-say">{{ parts.head }}@if (parts.chip; as chip) {<ng-container *ngTemplateOutlet="chipTpl; context: {$implicit: chip}"></ng-container>}{{ parts.middle }}<span class="k-keep">{{ parts.tail }}@if (parts.chipLast; as chip) {<ng-container *ngTemplateOutlet="chipTpl; context: {$implicit: chip}"></ng-container>}@if (hasDetails()) {<button type="button" class="k-chev" [attr.aria-expanded]="open()" [attr.aria-controls]="panelId" [attr.aria-label]="'ai-assistant.action.details' | translate" (click)="toggle($event)"><svg viewBox="0 0 14 14" width="14" height="14" aria-hidden="true"><path d="M5.25 3.25 9 7l-3.75 3.75" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg></button>}</span></span>
</div>
<div class="k-stepcol" [class.open]="open()">
@if (failure() !== null || arrival()?.readings?.length || listing() || detail().under.length) {
<div class="k-under">
@if (failure(); as why) {
<div class="k-failgrp">
<div class="k-fail" role="status"><p>{{ why }}</p></div>
<ng-content select=".k-fix"></ng-content>
</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 (detail().under.length) {
<tb-ai-action-detail class="k-under-detail" [view]="{blocks: detail().under}" [names]="names()"></tb-ai-action-detail>
}
</div>
}
@if (hasDetails() && open()) {
<div class="k-det" [id]="panelId">
@if (grouped()) {
@for (member of groupViews(); track member.id) {
<p class="k-group-h">{{ member.words }}</p>
<tb-ai-action-detail [view]="{hood: member.view.askedFor, blocks: member.view.blocks}" [names]="names()"></tb-ai-action-detail>
}
} @else {
<tb-ai-action-detail [view]="{hood: detail().askedFor, blocks: detail().blocks}" [names]="names()"></tb-ai-action-detail>
}
@if (took(); as time) {
<p class="k-took">{{ time }}</p>
}
</div>
}
</div>
}
}
<ng-template #chipTpl let-chip>@if (chip.link) {<a class="tb-chiplink" [routerLink]="chip.link" [title]="chip.name"><code class="k-ent" [attr.data-pal]="chip.palette"><tb-icon class="k-ent-ic" aria-hidden="true">{{ chip.icon }}</tb-icon><span class="k-ent-t">{{ chip.name }}</span><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" [title]="chip.name"><tb-icon class="k-ent-ic" aria-hidden="true">{{ chip.icon }}</tb-icon><span class="k-ent-t">{{ chip.name }}</span></code>}</ng-template>

164
ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss

@ -7,70 +7,173 @@
letter-spacing: var(--chat-text-ls);
}
.out {
.k-out {
display: flex;
align-items: flex-start;
gap: 8px;
margin-top: 2px;
margin-top: 0;
font-family: var(--tb-font);
font-size: var(--chat-line);
line-height: var(--chat-line-lh);
color: var(--tb-ink);
.mark {
&.opens {
cursor: pointer;
}
.k-mark {
flex: none;
display: flex;
display: inline-flex;
justify-content: center;
width: 20px;
height: 22px;
font-size: 22px;
line-height: 22px;
margin-top: 0;
color: var(--tb-ok);
&.fail {
color: var(--tb-crit);
}
&.auto {
position: relative;
> .mat-icon {
display: inline-flex;
justify-content: center;
width: 20px;
height: 22px;
font-size: 22px;
line-height: 22px;
overflow: visible;
color: inherit;
}
}
}
.say {
.k-mark-bolt {
position: absolute;
right: -5px;
bottom: -2px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 11px;
height: 11px;
border-radius: 50%;
background: var(--tb-surface);
box-shadow: 0 0 0 1.5px var(--tb-surface);
color: var(--tb-ok);
> .mat-icon {
width: 11px;
height: 11px;
font-size: 11px;
line-height: 11px;
}
}
.k-say {
flex: 1;
min-width: 0;
overflow-wrap: anywhere;
color: var(--tb-ink-76);
}
.dur {
flex: none;
margin-left: auto;
font-family: var(--tb-mono);
font-size: 12px;
line-height: var(--chat-line-lh);
color: var(--k-faint);
.k-keep {
white-space: nowrap;
}
code.k-ent .k-ent-t {
display: inline-block;
max-width: 180px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: top;
}
&.opens:hover .k-chev {
color: var(--tb-ink);
}
}
:host(.fail) .out .mark {
color: var(--tb-crit);
.k-chev {
display: inline-flex;
align-items: center;
justify-content: center;
margin: 0 0 0 4px;
padding: 0;
border: 0;
border-radius: 4px;
background: none;
color: var(--tb-ink-38);
vertical-align: -2px;
cursor: pointer;
transition: color var(--motion-base, 150ms) var(--ease-standard, ease);
svg {
display: block;
transition: transform var(--motion-base, 150ms) var(--ease-standard, ease);
}
&[aria-expanded="true"] svg {
transform: rotate(90deg);
}
&:focus-visible {
outline: 2px solid var(--ai-focus);
outline-offset: 1px;
}
}
.action-details {
display: block;
margin: 4px 0 0 28px;
.k-stepcol {
margin: 0 0 0 9px;
padding-left: 18px;
border-left: 1px solid transparent;
font-family: var(--tb-font);
::ng-deep .tb-disc.tb-disc-details {
margin: 0;
&.open {
border-left-color: var(--tb-line);
}
}
> summary {
color: var(--tb-ink-76);
}
.k-under {
display: grid;
gap: 8px;
justify-items: start;
margin-top: 6px;
> * {
margin: 0;
max-width: 100%;
}
}
.records {
display: block;
margin: 8px 0 4px;
.k-det {
margin: 6px 0 4px;
max-width: 100%;
> * + * {
margin-top: 8px;
}
}
.k-took {
margin: 0;
font-family: var(--tb-mono);
font-size: var(--chat-meta);
line-height: var(--chat-meta-lh);
color: var(--tb-text-secondary);
font-variant-numeric: tabular-nums;
}
.k-arrived {
display: flex;
flex-wrap: wrap;
gap: 4px 14px;
margin: 4px 0 0 28px;
margin: 0;
font-size: var(--chat-line, 14px);
line-height: 22px;
@ -93,3 +196,12 @@
color: var(--tb-ink);
}
}
.k-group-h {
margin: 0;
font-family: var(--tb-font);
font-size: var(--chat-line);
line-height: var(--chat-line-lh);
font-weight: 500;
color: var(--tb-ink);
}

121
ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, inject, input } from '@angular/core';
import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
import { catchError, distinctUntilChanged, switchMap } from 'rxjs/operators';
@ -9,7 +9,8 @@ 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 { AiDetailFact, AiDetailNames, aiParse, aiStepView } from '@home/components/ai/ai-action-detail.models';
import { aiFold, aiRevealOpened } from '@home/components/ai/ai-disclosure.component';
import {
AiAction,
aiConnectionCheckOf,
@ -66,6 +67,16 @@ export class AiActionLineComponent {
more = input(0);
group = input<AiAction[]>([]);
grouped = computed(() => this.group().length > 1);
groupViews = computed(() => this.grouped() ? this.group().map(action => ({
id: action.executionId,
words: aiActionText(this.translate, aiActionWords(action.tool, action.arguments), 'done'),
view: aiStepView(action, this.names())
})) : []);
outcomeText = input<string>();
autoApproved = input(false);
@ -73,6 +84,9 @@ export class AiActionLineComponent {
linkEntity = input(true);
outcomeChip = computed(() => {
if (this.grouped()) {
return null;
}
const affected = this.action().affectedEntities ?? [];
const entity = this.action().tool === 'update_group_members'
? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) ?? affected[0]
@ -106,15 +120,22 @@ export class AiActionLineComponent {
return action.tool === 'install_iot_hub_item' && result?.type === 'ALARM_RULE';
}
private runWords = computed(() => aiActionText(this.translate, this.words(), 'run'));
readonly 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 group = this.group();
if (group.length < 2) {
return this.outcomeWords();
}
const words = this.outcomeWords();
return this.autoApproved() ? this.translate.instant('ai-assistant.action.auto-approved', {words}) : words;
const said = (action: AiAction) => JSON.stringify(aiActionWords(action.tool, action.arguments));
return group.every(action => said(action) === said(group[0]))
? this.translate.instant('ai-assistant.action.times', {words, count: group.length})
: this.translate.instant('ai-assistant.work.more', {words, count: group.length - 1});
});
arrival = computed(() => {
@ -147,29 +168,105 @@ export class AiActionLineComponent {
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())});
return 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 view = aiStepView(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}] : [])];
const stages = this.action().stages ?? [];
const done = this.action().status === 'SUCCESS' && this.action().progress ? [...stages, this.action().progress] : stages;
const blocks = [...(done.length ? [{type: 'list' as const, label: {key: 'ai-assistant.detail.stages'}, rows: done}] : []),
...view.blocks, ...(facts.length ? [{type: 'facts' as const, rows: facts}] : [])];
return {...view, blocks};
});
records = computed(() => this.action().status === 'SUCCESS' ? this.action().affectedEntities ?? [] : []);
failure = computed(() => {
const action = this.action();
if (action.status !== 'FAILURE') {
return null;
}
const reason = this.reason(action.result);
const unchanged = this.translate.instant('ai-assistant.failed.nothing-changed');
return reason ? `${/[.!?…]$/.test(reason) ? reason : reason + '.'} ${unchanged}` : unchanged;
});
took = computed(() => {
const group = this.group();
const ms = group.length > 1
? Math.max(...group.map(action => action.startedAt + (action.durationMs ?? 0))) - Math.min(...group.map(action => action.startedAt))
: this.action().durationMs;
if (this.action().status === 'FAILURE') {
return '';
}
if (ms == null) {
return this.autoApproved() ? this.translate.instant('ai-assistant.action.done-auto') : '';
}
const time = aiActionDuration(this.translate, ms);
return this.translate.instant(this.autoApproved() ? 'ai-assistant.action.took-auto' : 'ai-assistant.action.took', {time});
});
hasDetails = computed(() => this.grouped() || !!this.detail().askedFor || !!this.detail().blocks.length || !!this.took());
private host = inject(ElementRef<HTMLElement>);
panelId = 'k-det-' + Math.random().toString(36).slice(2, 10);
private key = computed(() => 'action:' + this.action().executionId);
private fold = aiFold(() => this.key());
open = this.fold.open;
mark = computed<'check' | 'fail' | 'web' | 'auto'>(() => {
if (this.action().status === 'FAILURE') {
return 'fail';
}
if (this.action().tool === 'search_web') {
return 'web';
}
return this.autoApproved() ? 'auto' : 'check';
});
lineParts = computed(() => {
const chip = this.outcomeChip();
const split = (text: string) => {
const trimmed = text.trimEnd();
const cut = trimmed.lastIndexOf(' ') + 1;
return {start: trimmed.slice(0, cut), last: trimmed.slice(cut)};
};
if (!chip) {
const {start, last} = split(this.outcome());
return {head: start, chip: null, middle: '', tail: last, chipLast: null};
}
if (!chip.after.trim()) {
return {head: chip.before, chip: null, middle: '', tail: '', chipLast: chip};
}
const {start, last} = split(chip.after);
return {head: chip.before, chip, middle: start, tail: last, chipLast: null};
});
toggle(event?: Event): void {
event?.stopPropagation();
if (this.fold.toggle()) {
setTimeout(() => aiRevealOpened(this.host.nativeElement));
}
}
lineClicked(event: MouseEvent): void {
if (!this.hasDetails() || (event.target as HTMLElement).closest('a, button, input')) {
return;
}
this.toggle();
}
hasDetails = computed(() => !!this.detail().hood || !!this.detail().blocks.length || !!this.records().length);
private reason(result?: string): string | undefined {
const text = result?.trim();

228
ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts

@ -1,7 +1,10 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { SEVERITY_MARK } from '@home/components/ai/ai-text';
import { aiQuestionKind } from '@home/components/ai/ai-question.models';
import { AiQuestion } from '@shared/models/solution-creator.models';
import { TranslateService } from '@ngx-translate/core';
import type { AiAction } from '@shared/models/ai-chat.models';
export type { AiAction, AiActionStatus } from '@shared/models/ai-chat.models';
@ -28,7 +31,7 @@ const TOOL_WORDS: Record<string, string> = {
read_entity: 'read-entity',
read_timeseries_keys: 'read-telemetry-keys',
read_attributes: 'read-attributes',
discover_attribute_keys: 'read-attributes',
discover_attribute_keys: 'discover-attribute-keys',
save_attributes: 'save-attributes',
delete_attributes: 'delete-attributes',
read_entity_relations: 'read-relations',
@ -143,7 +146,8 @@ const TOOL_WORDS: Record<string, string> = {
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',
read_device_connect_commands: 'read-connect-commands',
read_billing: 'read-billing',
search_web: 'search-web',
send_notification: 'send-notification',
read_notifications: 'read-notifications',
@ -187,7 +191,24 @@ const SEARCHED_TYPES: Record<string, string> = {
ASSET: 'search-assets',
DASHBOARD: 'search-dashboards',
CUSTOMER: 'search-customers',
USER: 'search-users'
USER: 'search-users',
ENTITY_VIEW: 'search-entity-views',
EDGE: 'search-edges',
TENANT: 'search-tenants',
DEVICE_PROFILE: 'search-device-profiles',
ASSET_PROFILE: 'search-asset-profiles',
ENTITY_GROUP: 'search-groups'
};
const SEARCHED_FILTERS: Record<string, string> = {
gateway: 'search-gateways',
alarm: 'search-alarms',
alarmRule: 'search-alarm-rules',
calculatedField: 'search-calculated-fields',
notificationTarget: 'search-notification-targets',
notificationTemplate: 'search-notification-templates',
notificationRule: 'search-notification-rules',
image: 'search-images'
};
const DELETED_TARGETS: Record<string, string> = {
@ -242,6 +263,18 @@ const ACTION_PREFIX = 'ai-assistant.action.';
export const isHiddenAiAction = (tool: string): boolean => HIDDEN_TOOLS.has(tool);
const READ_VERBS = /^(read|search|discover|fetch|list|check_dashboard_access|research)_/;
const NEVER_GROUPED: ReadonlySet<string> = new Set(['read_device_credentials', 'read_device_connect_commands', 'check_connection',
'research_device_connectivity', 'read_iot_hub_device']);
export function aiGroupableRead(action: AiAction): boolean {
if (action.status !== 'SUCCESS' || NEVER_GROUPED.has(action.tool)) {
return false;
}
return action.readOnly ?? READ_VERBS.test(action.tool + '_');
}
export const SUGGEST_PROMPTS_TOOL = 'suggest_next_prompts';
export const ASK_USER_TOOL = 'ask_user';
@ -338,7 +371,6 @@ export interface AiHandOver {
steps: AiHandOverStep[];
waitFor?: 'message' | 'uplink' | 'gateway';
intervalSeconds?: number;
quiet?: string;
test?: AiHandOverTest;
paste?: {label: string; icon: string; intro: string};
}
@ -346,7 +378,6 @@ export interface AiHandOver {
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;
}
@ -359,10 +390,6 @@ function handOverTestOf(value: any): AiHandOverTest | undefined {
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;
@ -371,7 +398,7 @@ function handOverTestOf(value: any): AiHandOverTest | undefined {
sample = undefined;
}
const accessToken = text(value.accessToken);
return {hint: text(value.hint), commands, outcomes, ...(sample && accessToken ? {sample, accessToken} : {})};
return {hint: text(value.hint), commands, ...(sample && accessToken ? {sample, accessToken} : {})};
}
const text = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined;
@ -401,7 +428,7 @@ export function aiHandOverOf(args: unknown): AiHandOver | null {
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),
intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined,
test: handOverTestOf(values.test), paste: handOverPasteOf(values.paste)};
}
@ -483,6 +510,36 @@ export interface AiPlanProgress {
skipped: number[];
}
export type AiPlanMark = 'todo' | 'now' | 'done' | 'off';
export interface AiPlanStatus {
marks: AiPlanMark[];
done: number;
counted: number;
now: number;
finished: boolean;
}
export function aiPlanStatus(steps: AiPlanStep[], progress: AiPlanProgress | null): AiPlanStatus {
const marks = steps.map((_, index): AiPlanMark => {
const number = index + 1;
if (progress?.done.includes(number)) {
return 'done';
}
if (progress?.skipped.includes(number)) {
return 'off';
}
return progress?.now === number ? 'now' : 'todo';
});
return {
marks,
done: marks.filter(mark => mark === 'done').length,
counted: marks.filter(mark => mark !== 'off').length,
now: progress?.now ?? marks.findIndex(mark => mark !== 'done' && mark !== 'off') + 1,
finished: !!progress && marks.every(mark => mark === 'done' || mark === 'off')
};
}
export function aiPlanOf(args: unknown): AiPlanStep[] {
const steps = (args as {steps?: unknown})?.steps;
if (!Array.isArray(steps)) {
@ -512,7 +569,11 @@ export function aiPlanProgressOf(args: unknown): AiPlanProgress {
};
}
export function aiQuestionsOf(args: unknown): AiQuestion[] {
export type AiSeverityWord = (severity: string) => string;
const PLAIN_SEVERITY_WORD: AiSeverityWord = severity => severity.charAt(0) + severity.slice(1).toLowerCase();
export function aiQuestionsOf(args: unknown, word: AiSeverityWord = PLAIN_SEVERITY_WORD): AiQuestion[] {
const questions = (args as {questions?: unknown})?.questions;
if (!Array.isArray(questions)) {
return [];
@ -522,21 +583,57 @@ export function aiQuestionsOf(args: unknown): AiQuestion[] {
.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,
question: aiSeverityWords(question.question.trim(), word),
parts: aiSeverityParts(question.question.trim()),
why: typeof question.why === 'string' ? aiSeverityWords(question.why, word) : 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})),
.map(option => ({label: aiSeverityWords(option.label.trim(), word), hint: typeof option.hint === 'string' ? aiSeverityWords(option.hint, word) : 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
}));
color: question.color === true && question.multiple !== true,
other: aiQuestionOther(question.other),
number: aiQuestionNumber(question.number),
date: question.date === true && question.multiple !== true && Array.isArray(question.options) && question.options.length > 0
} as AiQuestion))
.map(question => ({...question, kind: aiQuestionKind(question)}));
}
const SEVERITY_MARKS = new RegExp(SEVERITY_MARK.source, 'g');
export function aiSeverityWords(text: string, word: AiSeverityWord = PLAIN_SEVERITY_WORD): string {
return text.replace(SEVERITY_MARKS, (_, severity: string) => word(severity));
}
function aiSeverityParts(text: string): Array<{text?: string; severity?: string}> | undefined {
if (!new RegExp(SEVERITY_MARKS.source).test(text)) {
return undefined;
}
return text.split(new RegExp(SEVERITY_MARKS.source)).map((part, index) => index % 2 ? {severity: part} : {text: part}).filter(part => part.severity || part.text);
}
function aiQuestionOther(other: any): AiQuestion['other'] {
const label = typeof other?.label === 'string' && other.label.trim() ? other.label.trim() : undefined;
const placeholder = typeof other?.placeholder === 'string' && other.placeholder.trim() ? other.placeholder.trim() : undefined;
return label || placeholder ? {label, placeholder} : undefined;
}
function aiQuestionNumber(number: any): AiQuestion['number'] {
if (!number || typeof number !== 'object') {
return undefined;
}
const finite = (value: unknown) => typeof value === 'number' && isFinite(value) ? value : undefined;
const size = number.size === 'short' || number.size === 'medium' ? number.size : 'long';
return {suggested: finite(number.suggested), unit: typeof number.unit === 'string' && number.unit.trim() ? number.unit.trim() : undefined,
step: finite(number.step), size};
}
const MAX_PROMPTS = 4;
const PROMPT_ICONS: Record<string, string> = {domain: 'mdi:cube-outline', rule: 'mdi:bell-cog', functions: 'mdi:function-variant'};
export interface AiPrompt {
text: string;
icon?: string;
@ -562,7 +659,7 @@ export function aiPromptsOf(args: unknown): AiPrompt[] {
}
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}))
.map(prompt => ({text: prompt.text.trim(), icon: typeof prompt.icon === 'string' && /^[a-z0-9_]+$/.test(prompt.icon) ? PROMPT_ICONS[prompt.icon] ?? prompt.icon : undefined}))
.slice(0, MAX_PROMPTS);
}
@ -708,6 +805,12 @@ function hasId(value: unknown): boolean {
function searchedWords(values: Record<string, any>): string {
const filter = values.entityFilter ?? values;
if (typeof filter?.filterType === 'string' && SEARCHED_FILTERS[filter.filterType]) {
return SEARCHED_FILTERS[filter.filterType];
}
if (filter?.statusList || filter?.severityList || filter?.typeList || filter?.searchPropagatedAlarms !== undefined) {
return 'search-alarms';
}
const types = new Set<string>();
const add = (type: unknown) => typeof type === 'string' && types.add(type);
add(filter?.entityType);
@ -747,7 +850,7 @@ function siteOf(url: unknown): string | undefined {
}
}
export type AiEntityPalette = 'device' | 'path' | 'chain' | 'rule' | 'view' | 'people' | 'solution';
export type AiEntityPalette = 'device' | 'path' | 'chain' | 'rule' | 'view' | 'people' | 'solution' | 'none';
export interface AiEntityKind {
icon: string;
@ -759,63 +862,68 @@ const ENTITY_KINDS: Record<string, AiEntityKind> = {
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'},
DEVICE_PROFILE: {icon: 'mdi:alpha-d-box', palette: 'device'},
ASSET: {icon: 'mdi:cube-outline', palette: 'device'},
ASSET_PROFILE: {icon: 'mdi:alpha-a-box', palette: 'device'},
AGENT: {icon: 'settings_applications', palette: 'device'},
AGENT_APPLICATION: {icon: 'apps', palette: 'device'},
AGENT_PROFILE: {icon: 'group_work', palette: 'device'},
AGENT_APP_PROFILE: {icon: 'description', palette: 'device'},
OTA_PACKAGE: {icon: 'system_update_alt', 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'},
CALCULATED_FIELD: {icon: 'mdi:function-variant', palette: 'path'},
RULE_CHAIN: {icon: 'settings_ethernet', palette: 'chain'},
EDGE_RULE_CHAIN: {icon: 'settings_ethernet', palette: 'chain'},
SCHEDULER_EVENT: {icon: 'schedule', palette: 'chain'},
ALARM_RULE: {icon: 'mdi:bell-cog', 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'},
NOTIFICATION_RULE: {icon: 'mdi:message-cog', palette: 'rule'},
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'},
DASHBOARD_STATE: {icon: 'layers', palette: 'view'},
DASHBOARD_ENTITY_ALIAS: {icon: 'label', palette: 'view'},
DASHBOARD_FILTER: {icon: 'filter_list', palette: 'view'},
REPORT_TEMPLATE: {icon: 'edit_document', 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'},
SCHEDULED_REPORT: {icon: 'mdi:file-clock', palette: 'view'},
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'},
MAIL_TEMPLATE: {icon: 'drafts', palette: 'view'},
NOTIFICATION_TEMPLATE: {icon: 'mdi:message-draw', palette: 'view'},
CUSTOM_TRANSLATION: {icon: 'translate', palette: 'view'},
CUSTOM_MENU: {icon: 'menu', palette: 'view'},
MOBILE_APP: {icon: 'smartphone', palette: 'view'},
MOBILE_BUNDLE: {icon: 'phonelink_setup', palette: 'view'},
MOBILE_QR_CODE: {icon: 'qr_code', 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'}
MY_PROFILE: {icon: 'account_circle', palette: 'people'},
NOTIFICATION_TARGET: {icon: 'contacts', palette: 'people'},
ROLE: {icon: 'badge', palette: 'people'},
GROUP_PERMISSION: {icon: 'verified_user', palette: 'people'},
SOLUTION_TEMPLATE: {icon: 'dashboard_customize', palette: 'solution'},
IOT_HUB: {icon: 'hub', palette: 'solution'},
MAIL_SERVER: {icon: 'mail', palette: 'none'},
TWO_FACTOR_SETTINGS: {icon: 'mdi:two-factor-authentication', palette: 'none'},
MY_TWO_FACTOR: {icon: 'mdi:two-factor-authentication', palette: 'none'},
DOMAIN: {icon: 'language', palette: 'none'},
API_KEY: {icon: 'vpn_key', palette: 'none'},
TB_RESOURCE: {icon: 'mdi:rhombus-split', palette: 'none'},
SECRET: {icon: 'lock', palette: 'none'},
ENTITY_GROUP: {icon: 'folder', palette: 'none'}
};
export function aiEntityKind(entityType: string, alarmRule = false): AiEntityKind {
return ENTITY_KINDS[alarmRule ? 'ALARM_RULE' : entityType] ?? {icon: 'category', palette: 'solution'};
export function aiEntityKind(entityType: string, alarmRule = false, groupType?: string | null): AiEntityKind {
if (entityType === 'ENTITY_GROUP') {
return {icon: 'folder', palette: (groupType && ENTITY_KINDS[groupType]?.palette) || 'none'};
}
return ENTITY_KINDS[alarmRule ? 'ALARM_RULE' : entityType] ?? {icon: 'category', palette: 'none'};
}

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

@ -11,7 +11,6 @@
[class.done]="state === 'approved'"
[class.auto]="state === 'auto'"
[class.denied]="state === 'denied'"
[class.expired]="state === 'expired'"
[class.danger]="isDestructive">
<div class="k-head"><mat-icon aria-hidden="true">{{ headIcon }}</mat-icon>{{ headText }}</div>
@if (listing; as hub) {
@ -21,8 +20,7 @@
<tb-ai-record [entityType]="review.entityType" [alarmRule]="alarmRule" [name]="recordName" [meta]="meta"
[class.closed]="recordClosed" [class.planned]="planned"></tb-ai-record>
}
@switch (state) {
@case ('pending') {
@if (state === 'pending' || state === 'waiting') {
@if (!review) {
<p class="k-review-p">{{ data.message }}</p>
}
@ -30,7 +28,7 @@
<dl class="k-fields">
@for (fact of facts; track $index) {
<dt>@if (fact.labelCode) { <code>{{ fact.label }}</code> } @else { {{ fact.label }} }</dt>
<dd>@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> }{{ fact.value }}</span> } @else if (fact.image) { <img tbAiFadeIn class="k-img" [src]="fact.value | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else if (fact.valueCode) { <code>{{ fact.value }}</code> } @else { {{ fact.value }} }</dd>
<dd>@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) { <tb-icon class="tb-mat-16" aria-hidden="true">{{ chip.icon }}</tb-icon> }{{ fact.value }}</span> } @else if (fact.image) { <img tbAiFadeIn class="k-img" [src]="fact.value | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else if (fact.valueCode) { <code>{{ fact.value }}</code> } @else { {{ fact.value }} }</dd>
}
</dl>
}
@ -41,43 +39,29 @@
<div class="k-review-code"><pre><code [class]="'language-' + block.lang" [attr.data-nocopy]="block.lang === 'diff' ? '' : null" [attr.data-label]="block.current !== undefined ? block.label + ' · ' + ('ai-assistant.review.new' | translate) : block.label">{{ block.value }}</code></pre></div>
}
@if (changes.length) {
<table class="k-diff" [class.k-diff-stacked]="stackedDiff">
<thead>
<tr>
<td></td>
<th scope="col">{{ 'ai-assistant.review.current' | translate }}</th>
<th scope="col">{{ 'ai-assistant.review.new' | translate }}</th>
</tr>
</thead>
<tbody>
@for (change of changes; track $index) {
<tr>
<th scope="row">@if (change.labelCode) { <code>{{ change.label }}</code> } @else { {{ change.label }} }</th>
@if (change.image || change.currentImage) {
<td class="k-diff-was">
@if (change.currentImage) { <img tbAiFadeIn class="k-img was" [src]="change.current | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else { {{ change.current }} }
</td>
<td class="k-diff-now">
@if (change.image) { <img tbAiFadeIn class="k-img" [src]="change.value | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else { <span>{{ change.value }}</span> }
</td>
} @else {
<td class="k-diff-was">{{ change.current }}</td>
<td class="k-diff-now"><span>{{ change.value }}</span></td>
}
</tr>
}
</tbody>
<div class="k-diff">
@for (change of changes; track $index) {
<div class="k-diff-f" [class.long]="isLongChange(change)">
<div class="k-diff-l">@if (change.labelCode) { <code>{{ change.label }}</code> } @else { {{ change.label }} }</div>
<div class="k-diff-v">
<span class="k-diff-was">@if (change.currentImage) { <img tbAiFadeIn class="k-img was" [src]="change.current | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else { {{ change.current }} }</span>
<span class="k-diff-to" aria-hidden="true">→</span>
<span class="tb-ai-sr-only">{{ 'ai-assistant.review.changes-to' | translate }}</span>
<span>@if (change.image) { <img tbAiFadeIn class="k-img" [src]="change.value | image: {preview: true, ignoreLoadingImage: true} | async" alt=""> } @else { {{ change.value }} }</span>
</div>
</div>
}
@if (unchanged.length && showUnchanged) {
<tbody class="k-diff-same">
<div class="k-diff-same">
@for (same of unchanged; track $index) {
<tr>
<th scope="row">@if (same.labelCode) { <code>{{ same.label }}</code> } @else { {{ same.label }} }</th>
<td colspan="2">{{ same.value }}</td>
</tr>
<div class="k-diff-f">
<div class="k-diff-l">@if (same.labelCode) { <code>{{ same.label }}</code> } @else { {{ same.label }} }</div>
<div class="k-diff-v"><span class="k-diff-was">{{ same.value }}</span></div>
</div>
}
</tbody>
</div>
}
</table>
</div>
@if (unchanged.length) {
<button type="button" class="tb-ai-more" [attr.aria-expanded]="showUnchanged" (click)="toggleUnchanged()">
<mat-icon aria-hidden="true">{{ showUnchanged ? 'expand_less' : 'expand_more' }}</mat-icon>
@ -86,11 +70,11 @@
}
}
<div class="k-actions">
<button mat-flat-button type="button" [class.warn]="isDestructive" (click)="approve()">
<button mat-flat-button type="button" [class.warn]="isDestructive" [disabled]="state === 'waiting' && busy" (click)="approve()">
<mat-icon>{{ isDestructive ? 'delete' : 'check' }}</mat-icon>
{{ approveLabel | translate }}
</button>
<button mat-button type="button" (click)="deny()">
<button mat-button type="button" [disabled]="state === 'waiting' && busy" (click)="deny()">
<mat-icon>close</mat-icon>
{{ 'ai-assistant.deny' | translate }}
</button>
@ -104,19 +88,8 @@
(keydown.escape)="$event.stopPropagation(); closeDeny()">
</div>
}
}
@case ('denied') {
<p class="k-review-p">{{ 'ai-assistant.review.denied-text' | translate }}</p>
}
@case ('expired') {
<p class="k-review-p">{{ 'ai-assistant.review.expired-text' | translate }}</p>
<div class="k-actions">
<button mat-stroked-button type="button" (click)="askAgain.emit()">
<mat-icon>refresh</mat-icon>
{{ 'ai-assistant.review.ask-again' | translate }}
</button>
</div>
}
} @else if (state === 'denied') {
<p class="k-review-p">{{ 'ai-assistant.review.denied-text' | translate }}</p>
}
@if (data.time) {
<time class="k-time" [attr.datetime]="data.time | date:'yyyy-MM-ddTHH:mm:ss'">{{ data.time | date:'HH:mm' }}</time>

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

@ -32,7 +32,7 @@ import { AiAction, HUB_INSTALL_TOOLS } from '@home/components/ai/ai-action.model
import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models';
import { MailTemplate, mailTemplateTranslations } from '@shared/models/settings.models';
export type ApprovalCardState = 'pending' | 'approved' | 'auto' | 'denied' | 'expired';
export type ApprovalCardState = 'pending' | 'waiting' | 'approved' | 'auto' | 'denied';
import { AiDetailFact } from '@home/components/ai/ai-action-detail.models';
import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service';
@ -69,7 +69,8 @@ const VALUE_TOKENS: Record<string, string[]> = {
const CODE_FIELDS = new Set(['arguments', 'expression', 'output']);
const REVIEW_VERBS = new Set(['install', 'restart', 'update', 'upgrade', 'upgrade-agent', 'delete', 'cancel', 'sync']);
const HEAD_VERBS = new Set(['create', 'update', 'delete', 'install', 'acknowledge', 'clear', 'assign', 'unassign']);
const REVIEW_VERBS = new Set(['install', 'restart', 'update', 'upgrade', 'upgrade-agent', 'delete', 'cancel', 'sync', 'acknowledge', 'clear', 'assign', 'unassign']);
const IMAGE_FIELDS = new Set(['widget-image', 'scada-symbol']);
@ -148,12 +149,63 @@ const CONVERTER_ICONS: Record<string, string> = {UPLINK: 'call_received', DOWNLI
const IMAGE_VALUE = /^(tb-image;|\/api\/images\/|data:image\/)/;
const STACK_AT = 24;
const LONG_CHANGE_AT = 36;
const COMMON_VALUES = new Set(['on', 'off', 'automatic', 'set', 'not set', 'default']);
const OWN_TYPE_LABELS = new Set(['ALARM_RULE', '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', 'SCADA_SYMBOL']);
const PROFILE_TYPES = new Set<string>([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]);
function aiApproveLabel(data: ToolExecutionRequested): string {
const review = data?.review;
const versionId = HUB_INSTALL_TOOLS.has(data?.tool) ? (data.arguments as {versionId?: unknown})?.versionId : null;
if (typeof versionId === 'string' && versionId) {
return 'ai-assistant.record.install';
}
if (review?.verb && REVIEW_VERBS.has(review.verb)) {
return 'ai-assistant.review.verb.' + review.verb;
}
if (data?.destructive) {
return 'ai-assistant.review.delete';
}
switch (review?.change) {
case 'CREATE':
return 'ai-assistant.review.create';
case 'UPDATE':
return 'ai-assistant.review.update';
default:
return 'ai-assistant.approve';
}
}
function aiReviewTypeLabel(translate: TranslateService, entityType: string): string {
if (OWN_TYPE_LABELS.has(entityType)) {
return translate.instant('ai-assistant.review.type.' + entityType);
}
const translation = entityTypeTranslations.get(entityType as EntityType)?.type;
return translation ? translate.instant(translation) : entityType;
}
function aiChangeHead(translate: TranslateService, data: ToolExecutionRequested): string | null {
const review = data?.review;
const label = aiApproveLabel(data);
if (!review?.entityType || label === 'ai-assistant.approve') {
return null;
}
const verb = label.split('.').pop();
if (!HEAD_VERBS.has(verb)) {
return translate.instant(label);
}
const type = review.detail === 'alarm-rule' ? 'ALARM_RULE' : review.entityType;
const key = 'ai-assistant.review.kind.' + type;
const phrase = translate.instant(key);
const kind = phrase !== key ? phrase : aiReviewTypeLabel(translate, type);
return translate.instant('ai-assistant.review.head-change.' + verb, {kind});
}
export function aiReviewHead(translate: TranslateService, data: ToolExecutionRequested): string {
return aiChangeHead(translate, data) ?? translate.instant('ai-assistant.review.head.pending');
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'tb-ai-approval-card',
@ -171,11 +223,13 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
@Input() answered = false;
@Input() busy = false;
@ViewChild('denyInput') denyInput: ElementRef<HTMLInputElement>;
@Output() approvalAction = new EventEmitter<ApprovalResult>();
@Output() askAgain = new EventEmitter<void>();
@Output() answerLater = new EventEmitter<ApprovalResult>();
denying = false;
@ -218,7 +272,7 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
if (changes.completedExecution && this.completedExecution?.executionId === this.data.executionId) {
const result = this.completedExecution;
if (result.approvalStatus === ToolApprovalResult.TIMEOUT) {
this.state = 'expired';
this.state = 'waiting';
} else if (result.approvalStatus === ToolApprovalResult.DENIED) {
this.state = 'denied';
} else {
@ -255,17 +309,23 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
return 'bolt';
case 'denied':
return 'block';
case 'expired':
return 'timer_off';
default:
return 'rate_review';
}
}
get headText(): string {
if (this.state === 'pending' || this.state === 'waiting') {
return this.changeHead() ?? this.translate.instant('ai-assistant.review.head.pending');
}
return this.translate.instant('ai-assistant.review.head.' + this.state);
}
private changeHead(): string | null {
return aiChangeHead(this.translate, this.data);
}
get outcomeText(): string {
const result = this.completedExecution;
const failed = result?.executionStatus !== 'SUCCESS';
@ -282,27 +342,15 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
}
get approveLabel(): string {
if (this.hubVersionId) {
return 'ai-assistant.record.install';
}
if (this.review?.verb && REVIEW_VERBS.has(this.review.verb)) {
return 'ai-assistant.review.verb.' + this.review.verb;
}
if (this.isDestructive) {
return 'ai-assistant.review.delete';
}
switch (this.review?.change) {
case 'CREATE':
return 'ai-assistant.review.create';
case 'UPDATE':
return 'ai-assistant.review.update';
default:
return 'ai-assistant.approve';
}
return aiApproveLabel(this.data);
}
get recordName(): string {
const name = this.review?.name;
if (this.review?.entityType === 'WHITE_LABELING' && (name === 'GENERAL' || name === 'LOGIN')) {
return this.translate.instant('ai-assistant.review.white-labeling-target.' + name);
}
const template = this.review?.entityType === 'MAIL_TEMPLATE' && name ? mailTemplateTranslations.get(name as MailTemplate) : undefined;
return template ? this.translate.instant(template) : name;
}
@ -355,9 +403,8 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
];
}
get stackedDiff(): boolean {
return this.changes.some(change => !change.image && !change.currentImage
&& ((change.current?.length ?? 0) > STACK_AT || (change.value?.length ?? 0) > STACK_AT));
isLongChange(change: AiReviewRow): boolean {
return !change.image && !change.currentImage && (change.current?.length ?? 0) + (change.value?.length ?? 0) > LONG_CHANGE_AT;
}
get changes(): AiReviewRow[] {
@ -369,7 +416,7 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
}
get recordClosed(): boolean {
return this.state === 'pending' || this.state === 'denied' || this.state === 'expired';
return this.state === 'pending' || this.state === 'denied' || this.state === 'waiting';
}
toggleUnchanged(): void {
@ -380,9 +427,10 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
}
approve(): void {
const later = this.state === 'waiting';
this.state = this.autoApproved ? 'auto' : 'approved';
this.denying = false;
this.approvalAction.emit({executionId: this.data.executionId, approved: true});
(later ? this.answerLater : this.approvalAction).emit({executionId: this.data.executionId, approved: true});
}
deny(): void {
@ -396,9 +444,10 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
sendDeny(words: string): void {
const reason = words.trim();
const later = this.state === 'waiting';
this.denying = false;
this.state = 'denied';
this.approvalAction.emit(reason
(later ? this.answerLater : this.approvalAction).emit(reason
? {executionId: this.data.executionId, approved: false, reason}
: {executionId: this.data.executionId, approved: false});
}
@ -475,10 +524,7 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
}
private typeLabel(entityType: string): string {
if (OWN_TYPE_LABELS.has(entityType)) {
return this.translate.instant('ai-assistant.review.type.' + entityType);
}
const translation = entityTypeTranslations.get(entityType as EntityType)?.type;
return translation ? this.translate.instant(translation) : entityType;
return aiReviewTypeLabel(this.translate, entityType);
}
}

2
ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts

@ -21,7 +21,7 @@ export interface AiCardAction {
[matTooltip]="action.tip ?? ''" [matTooltipDisabled]="!action.tip" matTooltipPosition="above"
(click)="press(action)">
@if (action.icon) {
<mat-icon aria-hidden="true">{{ action.icon }}</mat-icon>
<tb-icon aria-hidden="true">{{ action.icon }}</tb-icon>
}
{{ action.label }}
</button>

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

@ -65,6 +65,17 @@
<mat-icon class="tb-mat-18 art-card-chev" aria-hidden="true">chevron_right</mat-icon>
</button>
</div>
} @else if (msg.from === 'ACTION' && madeFiles[$index]?.preview === 'image') {
@let pic = madeFiles[$index];
<div class="ai k-made-pic-row">
<button type="button" class="k-made-pic" (click)="openMadeFile(pic)" [attr.aria-label]="'ai-assistant.file.open' | translate">
@if (madeUrl(pic) | async; as url) {
<img [src]="url" [alt]="pic.resource.name">
} @else {
<span class="k-made-pic-wait" aria-hidden="true"></span>
}
</button>
</div>
} @else if (msg.from === 'ACTION' && madeFiles[$index]; as made) {
<div class="ai art-cards">
<div class="art-card made">
@ -80,14 +91,15 @@
</div>
</div>
} @else if (msg.from === 'ACTION' && plans[$index]; as plan) {
<div class="ai plan">
<tb-ai-plan [steps]="plan.steps" [progress]="plan.progress" [gate]="plan.gate" [autoApprove]="autoApprove"
<div class="ai plan" [attr.data-dock]="$index">
<tb-ai-plan [steps]="plan.steps" [progress]="plan.progress" [gate]="plan.gate" [replacedAfter]="plan.replacedAfter" [autoApprove]="autoApprove"
(run)="runPlan.emit({run: $event, steps: plan.steps})" (change)="changePlan.emit()"></tb-ai-plan>
</div>
} @else if (msg.from === 'ACTION' && handOvers[$index]; as card) {
<div class="ai hand">
<div class="ai hand" [attr.data-dock]="$index">
<tb-ai-hand-over [handOver]="card.handOver" [wait]="card.wait" [time]="msg.data.startedAt" (prompt)="prompt.emit($event)" (stop)="stopRun.emit()" (compose)="compose.emit($event)"
[files]="latestFiles" (openFile)="openFile.emit($event)"></tb-ai-hand-over>
[files]="latestFiles" (openFile)="openFile.emit($event)" [cardId]="msg.data.executionId"
[canListenAgain]="!loading" (listenAgain)="listenAgain()" [testRequest]="testRequests[msg.data.executionId] ?? 0"></tb-ai-hand-over>
</div>
@if (waitAfterCard[$index] !== undefined && messages[waitAfterCard[$index]]; as moved) {
@if (moved.from === 'ACTION' && !waitsInCards.has(waitAfterCard[$index])) {
@ -101,16 +113,13 @@
<tb-ai-question [questions]="asking.questions" [time]="msg.data.startedAt" (done)="answerQuestions($event)" (skip)="answerQuestions($event)"></tb-ai-question>
</div>
} @else if (msg.from === 'ACTION') {
@if (isListedAction(msg, $index) && (msg.data.status !== 'RUNNING' || $index === runningLead)) {
@if (isListedAction(msg, $index) && !groupedAway.has($index) && (msg.data.status !== 'RUNNING' || $index === runningLead)) {
<div class="ai action">
<tb-ai-action-line [action]="msg.data" [names]="detailNames" [more]="$index === runningLead ? runningCount - 1 : 0"></tb-ai-action-line>
@if ($index === retryIndex) {
<div class="k-actions action-ways">
<button mat-stroked-button type="button" (click)="prompt.emit(retryPrompt)">
<mat-icon>replay</mat-icon>{{ 'ai-assistant.action.try-again' | translate }}
</button>
</div>
}
<tb-ai-action-line [action]="msg.data" [names]="detailNames" [more]="$index === runningLead ? runningCount - 1 : 0" [group]="readGroups[$index] ?? []">
@if ($index === retryIndex) {
<div class="k-fix"><ng-container *ngTemplateOutlet="tryAgain"></ng-container></div>
}
</tb-ai-action-line>
</div>
}
} @else {
@ -130,19 +139,32 @@
[completedExecution]="getCompletedExecution(msg)"
[autoApprove]="autoApprove"
[answered]="!!denyReasons[getApprovalData(msg).executionId]"
[busy]="loading"
(approvalAction)="approval($event)"
(askAgain)="askAgain.emit()">
(answerLater)="answerLater.emit($event)">
</tb-ai-approval-card>
} @else if (msg.status === 'RETRIED' || msg.status === 'RESUMED') {
<p class="k-retried"><mat-icon aria-hidden="true">{{ msg.status === 'RETRIED' ? 'refresh' : 'play_arrow' }}</mat-icon>{{ (msg.status === 'RETRIED' ? 'ai-assistant.failed.tried-again' : 'ai-assistant.failed.resumed') | translate: {time: clockText(msg.time)} }}</p>
} @else if (msg.status === 'INCOMPLETE' || msg.status === 'STOPPED') {
<div class="incomplete flex" role="status">
<mat-icon class="incomplete-icon">warning_amber</mat-icon>
<span>{{ msg.status === 'STOPPED' ? stoppedText($index, msg.content) : msg.content }}</span>
</div>
@if (msg.status === 'INCOMPLETE') {
<div class="k-failgrp">
<div class="k-fail" role="status"><p><b>{{ 'ai-assistant.failed.headline' | translate }}</b> {{ failText($index, msg) }}</p></div>
@if ($last && !loading && retry.observed) {
<div class="k-fix"><ng-container *ngTemplateOutlet="tryAgain"></ng-container></div>
}
</div>
} @else {
<p class="stop-note" role="status">{{ stoppedText($index, msg.content) }}</p>
}
@if (summaries[$index]; as entities) {
<tb-ai-run-summary class="summary" [entities]="entities"></tb-ai-run-summary>
}
@if (msg.status === 'STOPPED' && $last && !loading) {
<tb-ai-card-actions [actions]="resumeActions()" (act)="resume.emit()"></tb-ai-card-actions>
@if (msg.chips?.length) {
<tb-ai-card-actions [actions]="chipActions(msg.chips)" (act)="chip.emit($event)"></tb-ai-card-actions>
} @else {
<tb-ai-card-actions [actions]="resumeActions()" (act)="resume.emit()"></tb-ai-card-actions>
}
}
} @else {
<div class="agent" [class.done]="msg.done" [class.streaming]="msg.streaming" #answer>
@ -235,7 +257,7 @@
@for (option of prompts.items; track $index) {
<button type="button" class="ob-chip" (click)="prompt.emit(option.text)">
@if (option.icon) {
<mat-icon aria-hidden="true">{{ option.icon }}</mat-icon>
<tb-icon aria-hidden="true">{{ option.icon }}</tb-icon>
}
{{ option.text }}
</button>
@ -277,6 +299,29 @@
}
}
}
@if (dock && dockVisible) {
<div class="k-dock-row" [class.you]="dock.kind === 'hand'" role="region"
[attr.aria-label]="(dock.kind === 'hand' ? 'ai-assistant.dock.hand-label' : 'ai-assistant.dock.plan-label') | translate">
<div class="k-plan-strip-row" (click)="dockClicked($event)">
<tb-ai-step-mark [mark]="dock.state === 'idle' ? 'todo' : dock.state"></tb-ai-step-mark>
<span class="k-plan-strip-t">@if (dock.kind === 'hand' && dock.state !== 'stopped') {<span class="k-you">{{ 'ai-assistant.plan.you' | translate }}</span>}{{ dock.text }}</span>
@if (dock.count) {
<span class="k-plan-strip-n">{{ dock.count }}</span>
}
@if (dock.kind === 'hand' && dock.state === 'listen' && dock.canTest) {
<button mat-button type="button" (click)="dockTest()"><mat-icon>science</mat-icon>{{ 'ai-assistant.hand-over.send-test' | translate }}</button>
}
@if (dock.kind === 'hand' && dock.state === 'stopped' && !loading) {
<button mat-button type="button" (click)="listenAgain()"><mat-icon>play_arrow</mat-icon>{{ 'ai-assistant.hand-over.listen-again' | translate }}</button>
}
<button type="button" class="k-iconbtn" (click)="toDockCard()"
[matTooltip]="(dock.kind === 'hand' ? 'ai-assistant.dock.to-hand' : 'ai-assistant.dock.to-plan') | translate" matTooltipPosition="above"
[attr.aria-label]="(dock.kind === 'hand' ? 'ai-assistant.dock.to-hand' : 'ai-assistant.dock.to-plan') | translate">
<mat-icon class="tb-mat-18" aria-hidden="true">{{ dockBelow ? 'arrow_downward' : 'arrow_upward' }}</mat-icon>
</button>
</div>
</div>
}
@if (loading && !waitApproval && !actionRunning && !streaming) {
<div class="generating flex items-center">
@if (work) {
@ -289,3 +334,9 @@
}
</div>
}
<ng-template #tryAgain>
<button mat-stroked-button type="button" (click)="retry.emit()">
<mat-icon>refresh</mat-icon>{{ 'ai-assistant.action.try-again' | translate }}
</button>
</ng-template>

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

@ -274,23 +274,11 @@
color: var(--k-grey);
}
.incomplete {
align-items: center;
gap: 10px;
padding: 8px 8px 8px 12px;
border-radius: 10px;
font-size: 13.5px;
line-height: 19px;
color: var(--tb-ink-76);
background: var(--tb-caution-tint);
.incomplete-icon {
flex: none;
color: var(--tb-caution);
font-size: 18px;
width: 18px;
height: 18px;
}
.stop-note {
margin: 0;
font-size: var(--chat-line);
line-height: var(--chat-line-lh);
color: var(--tb-ink);
}
.ai.action + .ai.action {
@ -649,7 +637,3 @@
}
}
}
.action-ways {
margin: 8px 0 4px 28px;
}

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

@ -1,8 +1,11 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { aiClockText, aiLocale } from '@home/components/ai/ai-text';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, inject, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core';
import { ActionChatMessage, AiQuestion, AiQuestionAnswer, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models';
import { ClipboardService } from 'ngx-clipboard';
import { Observable, of } from 'rxjs';
import { catchError, shareReplay } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import {
ANSWER_PROBLEMS,
@ -33,8 +36,11 @@ import {
CHECK_CONNECTION_TOOL,
CITE_SOURCES_TOOL,
HAND_OVER_TOOL,
AiAction,
aiGroupableRead,
isHiddenAiAction,
isKitCardTool,
aiPlanStatus,
PROPOSE_PLAN_TOOL,
SUGGEST_PROMPTS_TOOL,
UPDATE_PLAN_TOOL
@ -72,6 +78,15 @@ import { Router } from '@angular/router';
const SOLUTION_STEP_TOOLS = ['create_solution', 'install_solution'];
interface AiDockRow {
kind: 'hand' | 'plan';
index: number;
text: string;
state: 'listen' | 'stopped' | 'run' | 'idle';
count?: string;
canTest?: boolean;
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'tb-ai-chat-messages',
@ -109,9 +124,22 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
@Output() chip = new EventEmitter<string>();
@Output() report = new EventEmitter<AnswerReportEvent>();
@Output() approvalAction = new EventEmitter<ApprovalResult>();
@Output() askAgain = new EventEmitter<void>();
@Output() answerLater = new EventEmitter<ApprovalResult>();
@Output() editMessage = new EventEmitter<string>();
@Output() resume = new EventEmitter<void>();
@Output() dockShown = new EventEmitter<boolean>();
@Output() listen = new EventEmitter<void>();
@Input() slotTaken = false;
testRequests: Record<string, number> = {};
private readonly severityWord = (severity: string): string => this.translate.instant('alarm.severity-' + severity.toLowerCase());
dock: AiDockRow | null = null;
private madeUrls = new Map<string, Observable<string | null>>();
dockVisible = false;
dockBelow = false;
private dockScroller: HTMLElement | null = null;
private readonly placeDockOnScroll = () => this.placeDock();
@Output() retry = new EventEmitter<void>();
@Output() autoApproveRest = new EventEmitter<void>();
@Output() runPlan = new EventEmitter<{run: AiPlanRun; steps: AiPlanStep[]}>();
@Output() changePlan = new EventEmitter<void>();
@ -129,6 +157,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
runningLead = -1;
readGroups: Record<number, AiAction[]> = {};
groupedAway = new Set<number>();
runningCount = 0;
summaries: Record<number, EntityId[]> = {};
@ -149,7 +181,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
records: Record<number, AiShownRecords[]> = {};
made: Record<number, string[]> = {};
plans: Record<number, {steps: AiPlanStep[]; progress: AiPlanProgress | null; gate: boolean}> = {};
plans: Record<number, {steps: AiPlanStep[]; progress: AiPlanProgress | null; gate: boolean; replacedAfter: number | null}> = {};
handOvers: Record<number, {handOver: AiHandOver; wait: AiHandOverWait | null}> = {};
waitsInCards = new Set<number>();
private movedWaits = new Set<number>();
@ -192,6 +224,15 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
private dialog: MatDialog,
private aiResourceService: AiResourceService) {}
madeUrl(file: AiMadeFile): Observable<string | null> {
let url = this.madeUrls.get(file.executionId);
if (!url) {
url = this.aiResourceService.getUrl(file.resource.id).pipe(catchError(() => of(null)), shareReplay(1));
this.madeUrls.set(file.executionId, url);
}
return url;
}
openMadeFile(file: AiMadeFile): void {
if (file.preview === 'image') {
this.dialog.open<AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData>(AiAttachmentPreviewDialogComponent, {
@ -399,6 +440,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
&& !changes.messages?.firstChange && this.isNearBottom()) {
setTimeout(() => this.followTurnEnd(), 0);
}
if (changes.slotTaken && !changes.slotTaken.firstChange) {
setTimeout(() => this.placeDock());
}
if (changes.messages) {
this.refreshDayLines();
this.detailNames = aiDetailNames(this.messages as Array<{from: string; data?: any; references?: Array<{id: string; name: string; entityType: string}>}>, this.detailNames);
@ -423,6 +467,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
}
this.plans = this.findPlans();
this.handOvers = this.findHandOvers();
this.dock = this.findDock();
this.followDock();
this.files = this.findFiles();
this.latestFiles = new Map(Object.values(this.files).map(file => [file.name, file]));
this.madeFiles = this.findMadeFiles();
@ -459,6 +505,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
this.actionRunning = running.length > 0;
this.runningLead = running.length ? running[0] : -1;
this.runningCount = running.length;
this.findReadGroups();
if (changes.messages.firstChange) {
if (this.initialScroll === 'bottom') {
this.pinToBottom();
@ -473,11 +520,13 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
const msgs = changes.messages.currentValue as ChatMessage[];
const lastMsg = msgs[msgs.length - 1];
// In auto-approve we are not blocked on the user, so the assistant keeps working: the
// thinking indicator must stay visible (waitApproval false) and the view must follow the
// stream of auto-generated cards down to the bottom.
// thinking indicator stays visible (waitApproval false), and the view follows the stream of
// auto-generated cards only while the reader is near the bottom.
this.waitApproval = lastMsg?.from === 'APPROVAL' && !this.autoApprove && !this.isAnswered(lastMsg as ApprovalChatMessage);
if (this.autoApprove) {
setTimeout(() => this.scrollToBottom('auto'), 0);
if (wasNearBottom) {
setTimeout(() => this.scrollToBottom('auto'), 0);
}
} else if (lastMsg?.from === 'USER') {
setTimeout(() => this.scrollToBottom('smooth'), 0);
} else if (lastMsg?.from === 'AI') {
@ -491,7 +540,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
setTimeout(() => this.scrollToBottom('smooth'), 0);
}
} else if (lastMsg?.from === 'APPROVAL' && this.waitApproval) {
setTimeout(() => this.revealLastApproval(), 0);
if (wasNearBottom) {
setTimeout(() => this.revealLastApproval(), 0);
}
} else if (lastMsg?.from === 'APPROVAL') {
if (prevLastMsg?.from === 'USER') {
setTimeout(() => this.scrollToLastUserMessage(), 0);
@ -588,7 +639,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
const options: Intl.DateTimeFormatOptions = days > 1 && days <= 6
? {weekday: 'long', day: 'numeric', month: 'long'}
: date.getFullYear() === today.getFullYear() ? {day: 'numeric', month: 'long'} : {day: 'numeric', month: 'long', year: 'numeric'};
return new Intl.DateTimeFormat(this.translate.currentLang?.replace('_', '-') || undefined, options).format(date).replace(',', '');
return new Intl.DateTimeFormat(aiLocale(this.translate.currentLang), options).format(date).replace(',', '');
}
private findSummaries(): Record<number, EntityId[]> {
@ -633,6 +684,50 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
return summaries;
}
private findReadGroups(): void {
const groups: Record<number, AiAction[]> = {};
const away = new Set<number>();
const turns: number[][] = [[]];
this.messages.forEach((message, index) => {
if (message.from === 'USER') {
turns.push([]);
}
turns[turns.length - 1].push(index);
});
for (const turn of turns) {
const answered = turn.some(index => this.messages[index].from === 'AI' && !(this.messages[index] as GeneralChatMessage).streaming
&& turn.indexOf(index) === turn.length - 1);
let lead = -1;
for (const index of turn) {
const message = this.messages[index];
const action = message.from === 'ACTION' ? (message as ActionChatMessage).data : null;
if (action && isHiddenAiAction(action.tool)) {
continue;
}
if (action && this.isListedAction(message, index) && aiGroupableRead(action)) {
if (lead >= 0) {
groups[lead].push(action);
away.add(index);
} else {
lead = index;
groups[lead] = [action];
}
continue;
}
if (!answered || message.from === 'USER' || message.from === 'AI') {
lead = -1;
}
}
}
Object.keys(groups).forEach(key => {
if (groups[Number(key)].length < 2) {
delete groups[Number(key)];
}
});
this.readGroups = groups;
this.groupedAway = away;
}
isListedAction(message: ChatMessage, index = -1): boolean {
return message.from === 'ACTION' && !isKitCardTool(message.data.tool) && !isHiddenAiAction(message.data.tool)
&& !(index >= 0 && (this.waitsInCards.has(index) || this.movedWaits.has(index)));
@ -642,8 +737,22 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
this.answer.emit(aiAnswersPrompt(answers));
}
get retryPrompt(): string {
return this.translate.instant('ai-assistant.action.try-again-prompt');
failText(index: number, message: GeneralChatMessage): string {
let steps = false;
for (let i = index - 1; i >= 0 && this.messages[i].from !== 'USER'; i--) {
if (this.messages[i].from === 'APPROVAL' || (this.messages[i].from === 'ACTION' && this.isListedAction(this.messages[i] as ActionChatMessage))) {
steps = true;
break;
}
}
const reason = message.failure?.reason;
const words = reason === 'TIMED_OUT' || reason === 'MODEL_ERROR' || reason === 'CREDITS_USED_UP' ? [this.translate.instant('ai-assistant.failed.reason.' + reason)] : [];
words.push(this.translate.instant(steps ? 'ai-assistant.failed.steps-done' : 'ai-assistant.failed.nothing-changed'));
return words.join(' ');
}
clockText(time?: number): string {
return aiClockText(time, this.translate.currentLang);
}
stoppedText(index: number, content: string): string {
@ -660,7 +769,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
}
for (let i = this.messages.length - 1; i >= 0; i--) {
const message = this.messages[i];
if (message.from === 'USER') {
if (message.from === 'USER' || (message as GeneralChatMessage).status === 'INCOMPLETE' || !this.retry.observed) {
return -1;
}
if (message.from === 'ACTION' && this.isListedAction(message)) {
@ -697,7 +806,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
return null;
}
if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) {
const questions = aiQuestionsOf(message.data.arguments);
const questions = aiQuestionsOf(message.data.arguments, this.severityWord);
return questions.length ? {index: i, questions} : null;
}
}
@ -748,6 +857,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
}
}
listenAgain(): void {
this.listen.emit();
}
resumeActions(): AiCardAction[] {
return [{id: 'resume', icon: 'play_arrow', label: this.translate.instant('ai-assistant.resume')}];
}
@ -859,7 +972,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
};
this.messages.forEach((message, index) => {
if (message.from === 'USER') {
current = -1;
if (current >= 0 && (!cards[current].handOver.waitFor || cards[current].wait?.check?.dataArriving)) {
current = -1;
}
early = -1;
return;
}
@ -893,8 +1008,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
return cards;
}
private findPlans(): Record<number, {steps: AiPlanStep[]; progress: AiPlanProgress | null; gate: boolean}> {
const plans: Record<number, {steps: AiPlanStep[]; progress: AiPlanProgress | null; gate: boolean}> = {};
private findPlans(): Record<number, {steps: AiPlanStep[]; progress: AiPlanProgress | null; gate: boolean; replacedAfter: number | null}> {
const plans: Record<number, {steps: AiPlanStep[]; progress: AiPlanProgress | null; gate: boolean; replacedAfter: number | null}> = {};
let current = -1;
this.messages.forEach((message, index) => {
if (message.from !== 'ACTION') {
@ -903,7 +1018,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
if (message.data.tool === PROPOSE_PLAN_TOOL) {
const steps = aiPlanOf(message.data.arguments);
if (steps.length) {
plans[index] = {steps, progress: null, gate: false};
if (current >= 0 && plans[current].progress && !this.planFinished(plans[current])) {
plans[current].replacedAfter = plans[current].progress.done.length;
}
plans[index] = {steps, progress: null, gate: false, replacedAfter: null};
current = index;
}
} else if (message.data.tool === UPDATE_PLAN_TOOL && current >= 0) {
@ -917,12 +1035,16 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
return plans;
}
private planFinished(plan: {steps: AiPlanStep[]; progress: AiPlanProgress | null}): boolean {
return aiPlanStatus(plan.steps, plan.progress).finished;
}
private findAnswers(): Record<number, AiQuestionAnswer[]> {
const answers: Record<number, AiQuestionAnswer[]> = {};
let questions: AiQuestion[] = [];
this.messages.forEach((message, index) => {
if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) {
questions = aiQuestionsOf(message.data.arguments);
questions = aiQuestionsOf(message.data.arguments, this.severityWord);
} else if (message.from === 'USER') {
const found = questions.length ? aiAnswersOf(message.content, questions) : null;
if (found) {
@ -966,7 +1088,78 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
return -1;
}
dockClicked(event: MouseEvent): void {
if (!(event.target as HTMLElement).closest('a, button')) {
this.toDockCard();
}
}
toDockCard(): void {
const card = this.dock ? this.elementRef.nativeElement.querySelector<HTMLElement>(`[data-dock="${this.dock.index}"]`) : null;
card?.scrollIntoView({block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'});
}
dockTest(): void {
const id = this.dock ? (this.messages[this.dock.index] as ActionChatMessage)?.data.executionId : null;
if (id) {
this.testRequests = {...this.testRequests, [id]: (this.testRequests[id] ?? 0) + 1};
}
}
private findDock(): AiDockRow | null {
const lastUser = this.messages.map(message => message.from).lastIndexOf('USER');
const handIndex = Object.keys(this.handOvers).map(Number).pop();
const card = handIndex !== undefined ? this.handOvers[handIndex] : undefined;
if (card?.handOver.waitFor && card.wait && !card.wait.check?.dataArriving && (card.wait.running || handIndex > lastUser)) {
return {kind: 'hand', index: handIndex, text: card.handOver.title, state: card.wait.running ? 'listen' : 'stopped',
canTest: !!card.handOver.test?.sample && card.handOver.waitFor === 'message'};
}
const planIndex = Object.keys(this.plans).map(Number).pop();
const plan = planIndex !== undefined ? this.plans[planIndex] : undefined;
if (!plan?.progress || plan.replacedAfter !== null || this.planFinished(plan)) {
return null;
}
const status = aiPlanStatus(plan.steps, plan.progress);
const step = plan.steps[Math.max(0, status.now - 1)];
return {kind: 'plan', index: planIndex, text: step?.text.replace(/`/g, '') ?? '', state: this.loading ? 'run' : 'idle',
count: this.translate.instant('ai-assistant.plan.done-of', {done: status.done, count: status.counted})};
}
private followDock(): void {
const scroller = this.scroller;
if (scroller !== this.dockScroller) {
this.dockScroller?.removeEventListener('scroll', this.placeDockOnScroll);
scroller.addEventListener('scroll', this.placeDockOnScroll, {passive: true});
this.dockScroller = scroller;
}
setTimeout(() => this.placeDock());
}
private placeDock(): void {
let visible = false;
let below = this.dockBelow;
if (this.dock && !this.slotTaken) {
const card = this.elementRef.nativeElement.querySelector<HTMLElement>(`[data-dock="${this.dock.index}"]`);
if (card) {
const box = this.scroller.getBoundingClientRect();
const rect = card.getBoundingClientRect();
visible = Math.min(rect.bottom, box.bottom) - Math.max(rect.top, box.top) <= 40;
below = rect.top >= box.bottom - 40;
}
}
if (below !== this.dockBelow) {
this.dockBelow = below;
this.cd.markForCheck();
}
if (visible !== this.dockVisible) {
this.dockVisible = visible;
this.dockShown.emit(visible);
this.cd.markForCheck();
}
}
ngOnDestroy(): void {
this.dockScroller?.removeEventListener('scroll', this.placeDockOnScroll);
clearTimeout(this.copiedTimeout);
clearTimeout(this.dayTimer);
this.releaseBottom?.();
@ -1035,17 +1228,21 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
}
scrollToLastUserMessage(): void {
const userMessages = this.elementRef.nativeElement.querySelectorAll('.user');
if (userMessages.length) {
userMessages[userMessages.length - 1].scrollIntoView({block: 'start', behavior: this.motion('smooth')});
}
this.scrollToStart(this.elementRef.nativeElement.querySelectorAll('.user'));
}
private scrollToLastAiMessage(): void {
const aiMessages = this.elementRef.nativeElement.querySelectorAll('.ai');
if (aiMessages.length) {
aiMessages[aiMessages.length - 1].scrollIntoView({block: 'start', behavior: this.motion('smooth')});
this.scrollToStart(this.elementRef.nativeElement.querySelectorAll('.ai'));
}
private scrollToStart(messages: NodeListOf<HTMLElement>): void {
const message = messages[messages.length - 1];
const scroller = this.scroller;
if (!message || !scroller) {
return;
}
const top = scroller.scrollTop + message.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
scroller.scrollTo({top, behavior: this.motion('smooth')});
}
parseResult(msg: string): string {

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

@ -79,11 +79,15 @@
[denyReasons]="denyReasons()"
[work]="work()"
(approvalAction)="onApprovalAction($event)"
(askAgain)="onAskAgain()"
(answerLater)="answerLater($event)"
[slotTaken]="!!notice() || !!creditsOut() || !!limitOut()"
(dockShown)="dockShown.set($event)"
[feedback]="!!chatId()"
(rate)="onRate($event)"
(report)="onReport($event)"
(resume)="resume()"
(listen)="runAgain('listen')"
(retry)="runAgain('retry')"
(autoApproveRest)="setAutoApprove(true)"
(runPlan)="runPlan($event)"
(changePlan)="changePlan()"
@ -131,11 +135,16 @@
}
<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"
<button type="button" class="k-pill" [class.new]="current.mode !== 'work'"
[matTooltip]="current.mode === 'card' && dockShown() ? ('ai-assistant.go-to-end' | translate) : current.label" matTooltipPosition="above"
[attr.aria-label]="current.mode === 'card' && !dockShown() ? ('ai-assistant.go-to-card' | translate: {label: current.label}) : ('ai-assistant.go-to-end' | translate)"
(click)="goToEnd(chatArea)">
@if (current.mode === 'new') {
@if (current.mode === 'card') {
<mat-icon class="tb-mat-18">arrow_downward</mat-icon>@if (!dockShown()) {{{ current.label }}}
} @else if (current.mode === 'new') {
<mat-icon class="tb-mat-18">arrow_downward</mat-icon>{{ current.count }}
} @else if (dockShown()) {
<mat-icon class="tb-mat-18">arrow_downward</mat-icon>
} @else {
<tb-ai-spin [kind]="current.kind"></tb-ai-spin>
}
@ -149,6 +158,13 @@
<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>
} @else if (keptEdits(); as kept) {
<div class="k-notice k-notice-edge" role="status">
<mat-icon aria-hidden="true">sync</mat-icon><span>{{ ('ai-assistant.kept-edits.' + kept.kind) | translate }}</span>
<button mat-button type="button" (click)="reloadKeptEdits()">{{ 'ai-assistant.kept-edits.reload' | translate }}</button>
<button mat-icon-button type="button" class="k-notice-x" [matTooltip]="'action.close' | translate" [attr.aria-label]="'action.close' | translate"
(click)="dismissKeptEdits()"><mat-icon>close</mat-icon></button>
</div>
}
<tb-ai-prompt-input
[blocked]="notice()?.kind === 'block' || !!creditsOut()"
@ -270,11 +286,10 @@
</div>
}
<div class="art-tools">
<button type="button" class="art-tool icon-only art-copy" [class.copied]="fileCopied()" (click)="copyFile(file)"
<button type="button" class="art-tool icon-only" [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>
<mat-icon class="tb-mat-18" aria-hidden="true">{{ fileCopied() ? 'check' : 'content_copy' }}</mat-icon>
</button>
<span class="tb-ai-sr-only" aria-live="polite">{{ fileCopied() ? ('ai-assistant.copied' | translate) : '' }}</span>
@if (file.image) {

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

@ -60,13 +60,15 @@ import {
ApprovalResult,
ChatEvent,
SendChatMessageRequest,
ToolApprovalResult,
AiAction,
ToolExecutionRequestedEvent,
ToolExecutionResult,
ToolFinished,
ToolStarted
} from '@shared/models/ai-chat.models';
import { aiActionText, aiActionWords, aiQuestionsOf, AiPlanStep, AiSpinKind, AiWorkMoment, AiWorkState, aiTurnPrompts, isHiddenAiAction, isKitCardTool, ASK_USER_TOOL } from '@home/components/ai/ai-action.models';
import { aiActionText, aiActionWords, aiQuestionsOf, AiPlanStep, AiSpinKind, AiWorkMoment, AiWorkState, aiTurnPrompts, isHiddenAiAction, isKitCardTool, ASK_USER_TOOL, HAND_OVER_TOOL } from '@home/components/ai/ai-action.models';
import { aiHandOverProgress } from '@home/components/ai/ai-hand-over.component';
import { AiPlanRun } from '@home/components/ai/ai-plan.component';
import { AiFile, aiFileMark, aiFileName, aiFileOf, downloadAiFile, downloadAiFileAsPng, WRITE_FILE_TOOL } from '@home/components/ai/ai-file.models';
import { AiFileBodyComponent, AiFileMarks, AiFileSaver } from '@home/components/ai/ai-file-body.component';
@ -74,7 +76,8 @@ import { ClipboardService } from 'ngx-clipboard';
import { AiChatMessagesComponent, AnswerRatingEvent, AnswerReportEvent } from '@home/components/ai/ai-chat-messages.component';
import { EntityId } from '@shared/models/id/entity-id';
import { EntityType } from '@shared/models/entity-type.models';
import { AiAssistantViewType } from '@shared/models/ai-chat.models';
import { AiAssistantViewType, AiRunAgain } from '@shared/models/ai-chat.models';
import { aiReviewHead } from '@home/components/ai/ai-approval-card.component';
import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component';
import { readStored, writeStored } from '@core/local-storage/stored';
import { AiAnswerFeedback, aiRateAnswer, aiReportAnswer, aiTrackLogScroll } from '@home/components/ai/ai-chat-session';
@ -213,6 +216,22 @@ export class AiChatComponent implements OnInit, OnDestroy {
fileBody = viewChild(AiFileBodyComponent);
private composerBox = viewChild<ElementRef<HTMLElement>>('composer');
private composerHeight = effect(onCleanup => {
const box = this.composerBox()?.nativeElement;
const body = box?.parentElement;
if (!box || !body || typeof ResizeObserver === 'undefined') {
return;
}
const observer = new ResizeObserver(() => {
const field = box.querySelector<HTMLElement>('.composer-field') ?? box;
body.style.setProperty('--k-composer-h', Math.round(box.getBoundingClientRect().bottom - field.getBoundingClientRect().top) + 'px');
});
observer.observe(box);
onCleanup(() => observer.disconnect());
});
private chatArea = viewChild<ElementRef<HTMLElement>>('chatArea');
private chatLog = viewChild(AiChatMessagesComponent, {read: ElementRef});
@ -352,10 +371,17 @@ export class AiChatComponent implements OnInit, OnDestroy {
private seenMessages = 0;
pill = computed<{mode: 'work' | 'new'; kind: AiSpinKind; label: string; count: number} | null>(() => {
pill = computed<{mode: 'work' | 'new' | 'card'; kind: AiSpinKind; label: string; count: number} | null>(() => {
if (this.atEnd()) {
return null;
}
const waiting = this.waitingApproval();
if (waiting) {
return {mode: 'card', kind: 'think', label: aiReviewHead(this.translate, waiting.data), count: 0};
}
if (this.awaitingAnswer()) {
return {mode: 'card', kind: 'think', label: this.translate.instant('ai-assistant.question.needs-answer'), count: 0};
}
if (this.loading() && !this.waitingApproval()) {
const running = this.messages().filter((message): message is ActionChatMessage =>
message.from === 'ACTION' && message.data.status === 'RUNNING');
@ -371,6 +397,9 @@ export class AiChatComponent implements OnInit, OnDestroy {
});
private answeredApprovals = signal<ReadonlySet<string>>(new Set());
private rerun: (() => void) | null = null;
dockShown = signal(false);
waitingApproval = computed<ApprovalChatMessage | undefined>(() => {
if (this.autoApprove()) {
@ -388,6 +417,8 @@ export class AiChatComponent implements OnInit, OnDestroy {
return false;
}
const messages = this.messages();
const completed = this.completedExecutions();
const answered = this.answeredApprovals();
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (message.from === 'USER') {
@ -396,6 +427,10 @@ export class AiChatComponent implements OnInit, OnDestroy {
if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) {
return aiQuestionsOf(message.data.arguments).length > 0;
}
if (message.from === 'APPROVAL' && completed[message.data.executionId]?.approvalStatus === ToolApprovalResult.TIMEOUT
&& !answered.has(message.data.executionId)) {
return true;
}
}
return false;
});
@ -425,6 +460,16 @@ export class AiChatComponent implements OnInit, OnDestroy {
private aiChat = inject(AiChatService);
private chats = inject(AiChatsService);
private panelService = inject(AiAssistantPanelService);
readonly keptEdits = this.panelService.keptEdits;
reloadKeptEdits(): void {
this.panelService.reloadKeptEdits();
}
dismissKeptEdits(): void {
this.panelService.clearKeptEdits();
}
private whiteLabelingService = inject(WhiteLabelingService);
private customMenuService = inject(CustomMenuService);
private translate = inject(TranslateService);
@ -787,10 +832,24 @@ export class AiChatComponent implements OnInit, OnDestroy {
&& message.time === answer.time) ? {...message, ...patch} as GeneralChatMessage : message));
}
onAskAgain(): void {
if (!this.loading()) {
this.sendMsgFromUser({message: this.translate.instant('ai-assistant.review.ask-again-message'), resources: []});
answerLater(event: ApprovalResult): void {
if (event.reason) {
this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason}));
}
this.answeredApprovals.update(set => new Set(set).add(event.executionId));
if (!this.runAgain(event.approved ? 'approve' : 'deny', event.executionId, event.reason)) {
this.reopenCard(event.executionId);
}
}
private reopenCard(executionId: string): void {
this.answeredApprovals.update(set => {
const next = new Set(set);
next.delete(executionId);
return next;
});
this.denyReasons.update(({[executionId]: _, ...rest}) => rest);
this.completedExecutions.update(map => map[executionId] ? {...map, [executionId]: {...map[executionId]}} : map);
}
sendMsgFromUser(prompt: AiPromptMessage): void {
@ -866,7 +925,44 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
resume(): void {
this.sendMsgFromUser({message: this.translate.instant('ai-assistant.resume'), resources: []});
this.runAgain('resume');
}
runAgain(again: AiRunAgain, executionId?: string, reason?: string): boolean {
if (this.loading() || !this.chatId() || this.waitingApproval()) {
return false;
}
const failed = again === 'retry' ? this.messages().filter(message => (message as GeneralChatMessage).status === 'INCOMPLETE') : [];
const marker: GeneralChatMessage | null = again === 'retry' || again === 'resume'
? {from: 'AI', content: '', status: again === 'retry' ? 'RETRIED' : 'RESUMED', time: Date.now()} : null;
const undo = () => {
this.messages.update(list => [...list.filter(message => message !== marker), ...failed]);
if (executionId) {
this.reopenCard(executionId);
}
};
this.clearPassingNotice();
this.messages.update(list => [...list.filter(message => !failed.includes(message)), ...(marker ? [marker] : [])]);
this.rerun = undo;
this.sendMessage({message: '', resources: []}, {again, executionId, reason}).pipe(
finalize(() => this.rerun = null)
).subscribe({
error: err => {
if (this.isConnectionLost(err) && this.chatId()) {
this.setNotice('warn', 'wifi_off', 'connection-lost');
this.resumeTurn(this.chatId(), true);
return;
}
undo();
const limitType = aiCreditsLimitOf(err);
if (limitType) {
this.creditsOut.set(limitType);
} else {
setTimeout(() => this.showErrorMessage(err), 0);
}
}
});
return true;
}
private sendWhileWorking(prompt: AiPromptMessage, userMessage: ChatMessage): void {
@ -926,6 +1022,12 @@ export class AiChatComponent implements OnInit, OnDestroy {
const context = this.clientContext();
request.clientContext = context ? {...context, os: context.os ?? aiClientOs()}
: {timeZone: getDefaultTimezone(), os: aiClientOs()} as AiChatClientContext;
const card = [...this.messages()].reverse().find((message): message is ActionChatMessage =>
message.from === 'ACTION' && message.data.tool === HAND_OVER_TOOL);
const progress = card ? aiHandOverProgress(card.data.executionId) : null;
if (progress?.ticks.length) {
request.clientContext.handOver = {title: progress.title, ticked: progress.ticked, steps: progress.steps};
}
if (prompt.secrets) {
request.secrets = prompt.secrets;
}
@ -936,7 +1038,7 @@ export class AiChatComponent implements OnInit, OnDestroy {
return request;
}
private sendMessage(prompt: AiPromptMessage): Observable<ChatEvent> {
private sendMessage(prompt: AiPromptMessage, again?: {again: AiRunAgain; executionId?: string; reason?: string}): Observable<ChatEvent> {
this.messageCancelled = false;
const startOrContinue$ = this.chatId()
? of(null)
@ -948,6 +1050,19 @@ export class AiChatComponent implements OnInit, OnDestroy {
})
);
const request = this.chatRequest(prompt);
this.limitOut.set(null);
if (!again || again.again === 'retry' || again.again === 'resume') {
this.closeWaitingCards();
}
if (again) {
request.again = again.again;
if (again.executionId) {
request.executionId = again.executionId;
}
if (again.reason) {
request.reason = again.reason;
}
}
this.setWork('reading-request', true);
this.loading.set(true);
return startOrContinue$.pipe(
@ -1052,9 +1167,10 @@ export class AiChatComponent implements OnInit, OnDestroy {
case 'toolExecutionRequested':
this.handleToolApproval(event);
break;
case 'toolExecutionResult':
case 'toolExecutionResult': {
const replayed = this.completedExecutions()[event.data.executionId]?.approvalStatus === event.data.approvalStatus;
this.completedExecutions.update(map => ({...map, [event.data.executionId]: event.data}));
if (event.data.executionStatus === 'SUCCESS') {
if (event.data.executionStatus === 'SUCCESS' && !replayed) {
const call = this.messages().find(message => (message.from === 'APPROVAL' || message.from === 'ACTION')
&& message.data.executionId === event.data.executionId);
if (call?.from === 'APPROVAL' || call?.from === 'ACTION') {
@ -1066,10 +1182,11 @@ export class AiChatComponent implements OnInit, OnDestroy {
this.leaveDeletedScadaSymbol(call.data.tool, call.data.arguments);
}
}
if (event.data.affectedEntities?.length) {
if (event.data.affectedEntities?.length && !replayed) {
this.emitUpdated(event.data.affectedEntities);
}
break;
}
case 'toolStarted':
this.work.update(work => work?.headline ? {moment: work.moment, since: work.since} : work);
this.startAction(event.data);
@ -1090,10 +1207,20 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
break;
default:
if (event.event === 'error' && event.data?.code) {
this.restoreLastPrompt();
if (event.event === 'error' && event.data?.code === 'CREDITS_USED_UP' && this.ranSteps()) {
this.creditsOut.set('POOL');
this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: '', status: 'INCOMPLETE',
failure: {reason: 'CREDITS_USED_UP'}, time: Date.now()}]);
} else if (event.event === 'error' && event.data?.code) {
if (this.rerun) {
this.rerun();
} else {
this.restoreLastPrompt();
}
if (event.data.code === 'CREDITS_USED_UP') {
this.discardFreshChat();
if (!this.rerun) {
this.discardFreshChat();
}
this.creditsOut.set('POOL');
} else {
this.setNotice('warn', 'hourglass_top', 'rate-limited');
@ -1101,7 +1228,8 @@ export class AiChatComponent implements OnInit, OnDestroy {
} else if (event.event === 'error') {
const message = event.data?.message || this.translate.instant('ai-assistant.run-failed');
this.chats.setFailed(this.chatId(), message);
this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: message, status: 'INCOMPLETE', time: Date.now()}]);
const failure = {reason: event.data?.reason};
this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: message, status: 'INCOMPLETE', failure, time: Date.now()}]);
}
}
return of(event);
@ -1158,7 +1286,8 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
private startAction(started: ToolStarted): void {
if (isHiddenAiAction(started.tool) || this.isApprovalExecution(started.executionId)) {
if (isHiddenAiAction(started.tool) || this.isApprovalExecution(started.executionId)
|| this.messages().some(message => message.from === 'ACTION' && message.data.executionId === started.executionId)) {
return;
}
const action: AiAction = {
@ -1166,7 +1295,8 @@ export class AiChatComponent implements OnInit, OnDestroy {
tool: started.tool,
arguments: started.arguments,
status: isKitCardTool(started.tool) ? 'SUCCESS' : 'RUNNING',
startedAt: started.startedAt ?? Date.now()
startedAt: started.startedAt ?? Date.now(),
...(started.readOnly ? {readOnly: true} : {})
};
this.messages.update(list => [...list, {from: 'ACTION', data: action}]);
}
@ -1190,15 +1320,13 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
const executionId = running.data.executionId;
this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === executionId
? {from: 'ACTION', data: {...message.data, progress}} : message));
? {from: 'ACTION', data: {...message.data, progress, stages: message.data.progress && message.data.progress !== progress
? [...(message.data.stages ?? []), message.data.progress] : message.data.stages}} : message));
return true;
}
private thinkingHeadline(data: {headline?: string; tool?: string; arguments?: unknown} | undefined): string | undefined {
if (data?.tool) {
return aiActionText(this.translate, aiActionWords(data.tool, data.arguments), 'run');
}
return data?.headline;
return data?.tool ? aiActionText(this.translate, aiActionWords(data.tool, data.arguments), 'run') : undefined;
}
private openCreatedDashboard(tool: string | undefined, affected: EntityId[] | undefined): void {
@ -1347,6 +1475,10 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
private finishAction(finished: ToolFinished): void {
const known = this.messages().find(message => message.from === 'ACTION' && message.data.executionId === finished.executionId);
if (known?.from === 'ACTION' && known.data.status !== 'RUNNING') {
return;
}
if (finished.status === 'SUCCESS') {
const started = this.messages().find(message => message.from === 'ACTION' && message.data.executionId === finished.executionId);
if (started?.from === 'ACTION') {
@ -1385,10 +1517,31 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
}
private closeWaitingCards(): void {
this.completedExecutions.update(map => {
const waiting = Object.keys(map).filter(id => map[id]?.approvalStatus === ToolApprovalResult.TIMEOUT);
return waiting.length ? {...map, ...Object.fromEntries(waiting.map(id => [id, {...map[id], approvalStatus: ToolApprovalResult.DENIED}]))} : map;
});
}
private handleToolApproval(event: ToolExecutionRequestedEvent): void {
if (event.data.needsApproval) {
this.messages.update(list => [...list, {from: 'APPROVAL', data: event.data}]);
if (!event.data.needsApproval) {
return;
}
const id = event.data.executionId;
if (this.messages().some(message => message.from === 'APPROVAL' && message.data.executionId === id)) {
if (this.completedExecutions()[id]?.approvalStatus !== ToolApprovalResult.TIMEOUT) {
return;
}
this.completedExecutions.update(map => {
const {[id]: _, ...rest} = map;
return rest;
});
this.messages.update(list => list.map(message => message.from === 'APPROVAL' && message.data.executionId === id
? {from: 'APPROVAL', data: event.data} : message));
return;
}
this.messages.update(list => [...list, {from: 'APPROVAL', data: event.data}]);
}
private showHistory(messages: ChatMessage[]): void {
@ -1494,6 +1647,12 @@ export class AiChatComponent implements OnInit, OnDestroy {
}
}
private ranSteps(): boolean {
const messages = this.messages();
const last = messages.map(message => message.from).lastIndexOf('USER');
return messages.slice(last + 1).some(message => message.from === 'ACTION' || message.from === 'APPROVAL');
}
private restoreLastPrompt(): void {
const messages = this.messages();
const last = messages.map(message => message.from).lastIndexOf('USER');

42
ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html

@ -0,0 +1,42 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="k-colours" role="radiogroup" [attr.aria-label]="question().question">
@for (option of question().options; track option.label) {
<button type="button" role="radio" class="k-colour" [attr.aria-checked]="value() === option.label"
[disabled]="disabled()" (click)="pick(option.label)">
<span class="k-sw" [style.background]="colorOf(option.label)" aria-hidden="true"></span>
<span class="k-colour-t"><b>{{ option.hint || colorOf(option.label)?.toUpperCase() }}</b>@if (option.hint) {<small>{{ colorOf(option.label)?.toUpperCase() }}</small>}</span>
</button>
}
<button type="button" role="radio" class="k-colour" [attr.aria-checked]="other()" [disabled]="disabled()" (click)="openHex()">
@if (hex(); as color) {
<span class="k-sw" [style.background]="color" aria-hidden="true"></span>
<span class="k-colour-t"><b>{{ 'ai-assistant.question.other-color-short' | translate }}</b><small>{{ color }}</small></span>
} @else {
<span class="k-sw other" aria-hidden="true"><mat-icon class="tb-mat-16">palette</mat-icon></span>
<span class="k-colour-t"><b>{{ (other() ? 'ai-assistant.question.other-color-short' : 'ai-assistant.question.other-color') | translate }}</b></span>
}
</button>
</div>
@if (other()) {
<div class="k-hexf">
<span class="k-hexf-f">
<span class="k-hexf-hash" aria-hidden="true">#</span>
<input #hexInput class="k-hex-in" type="text" maxlength="7" placeholder="00897B" spellcheck="false" autocomplete="off"
[value]="digits()" [disabled]="disabled()" [attr.aria-invalid]="wrong() || null"
[attr.aria-label]="'ai-assistant.question.hex-label' | translate: {question: question().question, label: ('ai-assistant.question.other-color-short' | translate)}"
(input)="typeHex(hexInput)" (blur)="checkHex(hexInput)" (keydown.enter)="hexEnter($event, hexInput)">
<button mat-icon-button type="button" [disabled]="disabled()"
[matTooltip]="'ai-assistant.question.pick-color' | translate" matTooltipPosition="above"
[attr.aria-label]="'ai-assistant.question.pick-color' | translate"
(click)="openPicker($any($event.currentTarget), hexInput)"><mat-icon>colorize</mat-icon></button>
</span>
</div>
@if (wrong()) {
<p class="k-opterr row" role="alert">{{ 'ai-assistant.question.hex-error' | translate }}</p>
}
}

111
ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts

@ -0,0 +1,111 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, model, output, Renderer2, signal, ViewContainerRef } from '@angular/core';
import { AiQuestion } from '@shared/models/solution-creator.models';
import { TbPopoverService } from '@shared/components/popover.service';
import { ColorPickerPanelComponent } from '@shared/components/color-picker/color-picker-panel.component';
import tinycolor from 'tinycolor2';
import { aiColorOf, aiHexOf, aiIsFree } from '@home/components/ai/ai-question.models';
export function aiColorReady(question: AiQuestion, value: string): boolean {
return question.options.some(option => option.label === value) || !!aiHexOf(value);
}
export function aiColorAnswer(question: AiQuestion, value: string): string {
return question.options.some(option => option.label === value) ? value : aiHexOf(value) ?? '';
}
@Component({
selector: 'tb-ai-color-field',
templateUrl: './ai-color-field.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false
})
export class AiColorFieldComponent {
question = input.required<AiQuestion>();
value = model('');
disabled = input(false);
enter = output<Event>();
private elementRef: ElementRef<HTMLElement> = inject(ElementRef);
private popoverService = inject(TbPopoverService);
private renderer = inject(Renderer2);
private viewContainerRef = inject(ViewContainerRef);
readonly colorOf = aiColorOf;
readonly wrong = signal(false);
readonly other = computed(() => aiIsFree(this.question()) || !this.question().options.some(option => option.label === this.value()));
readonly hex = computed(() => this.other() ? aiHexOf(this.value()) : null);
readonly digits = computed(() => this.value().replace(/^#/, ''));
readonly ready = computed(() => aiColorReady(this.question(), this.value()));
pick(label: string): void {
this.wrong.set(false);
this.value.set(label);
}
openHex(): void {
if (this.disabled()) {
return;
}
if (!this.other()) {
this.value.set('#');
}
setTimeout(() => this.elementRef.nativeElement.querySelector<HTMLInputElement>('.k-hex-in')?.focus());
}
typeHex(field: HTMLInputElement): void {
if (field.value.startsWith('#')) {
field.value = field.value.slice(1);
}
this.value.set('#' + field.value.trim());
if (aiHexOf(field.value)) {
this.wrong.set(false);
}
}
checkHex(field: HTMLInputElement): void {
this.wrong.set(!!field.value.trim() && !aiHexOf(field.value));
}
hexEnter(event: Event, field: HTMLInputElement): void {
if ((event as KeyboardEvent).isComposing) {
return;
}
event.preventDefault();
if (aiHexOf(field.value)) {
this.enter.emit(event);
} else {
this.wrong.set(true);
}
}
openPicker(trigger: HTMLElement, field: HTMLInputElement): void {
if (this.disabled()) {
return;
}
if (this.popoverService.hasPopover(trigger)) {
this.popoverService.hidePopover(trigger);
return;
}
const popover = this.popoverService.displayPopover({
trigger,
renderer: this.renderer,
hostView: this.viewContainerRef,
componentType: ColorPickerPanelComponent,
preferredPlacement: ['bottomLeft', 'bottom', 'topLeft', 'top'],
context: {color: this.hex() ?? '#305680', disableAlpha: true, colorCancelButton: true},
showCloseButton: false,
popoverContentStyle: {padding: '12px 4px 12px 12px'},
isModal: true
});
popover.tbComponentRef.instance.popover = popover;
popover.tbComponentRef.instance.colorSelected.subscribe((color: string) => {
popover.hide();
field.value = tinycolor(color).toHex().toUpperCase();
this.typeHex(field);
});
popover.tbComponentRef.instance.colorCancelDialog.subscribe(() => popover.hide());
}
}

23
ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html

@ -0,0 +1,23 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="k-cal" role="dialog" [attr.aria-label]="'ai-assistant.question.another-day' | translate"
(keydown.escape)="$event.stopPropagation(); popover?.hide()">
<mat-calendar [selected]="selected" [startAt]="selected" [minDate]="minDate" (selectedChange)="select($event)"></mat-calendar>
<div class="k-cal-t">
<span>{{ 'ai-assistant.question.time' | translate }}</span>
<input #timeInput type="text" inputmode="numeric" class="k-cal-time" maxlength="5" spellcheck="false" autocomplete="off"
[value]="time" [attr.aria-invalid]="timeWrong || null" [attr.aria-label]="'ai-assistant.question.time' | translate"
(input)="typeTime(timeInput)" (blur)="settleTime(timeInput)"
(keydown.arrowup)="$event.preventDefault(); stepTime(timeInput, 15)" (keydown.arrowdown)="$event.preventDefault(); stepTime(timeInput, -15)"
(keydown.enter)="$event.preventDefault(); apply(timeInput)">
<span class="tb-spacer"></span>
<button mat-flat-button type="button" color="primary" (click)="apply(timeInput)">{{ 'ai-assistant.question.apply' | translate }}</button>
</div>
@if (timeWrong) {
<p class="k-opterr k-cal-err">{{ 'ai-assistant.question.time-wrong' | translate }}</p>
}
</div>

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

@ -0,0 +1,73 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, inject } from '@angular/core';
import { TbPopoverComponent } from '@shared/components/popover.component';
import { aiReadTime } from '@home/components/ai/ai-question.models';
export interface AiPickedDay {
date: Date;
time: string;
}
@Component({
selector: 'tb-ai-date-panel',
templateUrl: './ai-date-panel.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false
})
export class AiDatePanelComponent {
selected: Date;
time = '9:00';
popover: TbPopoverComponent;
readonly minDate = startOfDay(new Date());
readonly applied = new EventEmitter<AiPickedDay>();
timeWrong = false;
private cd = inject(ChangeDetectorRef);
select(date: Date): void {
this.selected = date;
this.cd.markForCheck();
}
typeTime(field: HTMLInputElement): void {
this.time = field.value;
this.timeWrong = false;
}
settleTime(field: HTMLInputElement): void {
const time = aiReadTime(field.value);
if (time) {
field.value = time;
this.time = time;
}
}
stepTime(field: HTMLInputElement, minutes: number): void {
const time = aiReadTime(field.value);
if (!time) {
return;
}
const [hours, mins] = time.split(':').map(Number);
const total = (((hours * 60 + mins + minutes) % 1440) + 1440) % 1440;
field.value = `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
this.time = field.value;
}
apply(field: HTMLInputElement): void {
const time = aiReadTime(field.value);
if (!time || !this.selected) {
this.timeWrong = !time;
this.cd.markForCheck();
field.focus();
return;
}
this.applied.emit({date: this.selected, time});
}
}
function startOfDay(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

41
ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, signal } from '@angular/core';
import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, linkedSignal, WritableSignal } from '@angular/core';
const STORE = 'tb-ai-disclosure';
@ -27,6 +27,26 @@ export function aiDisclosureRemember(key: string, open: boolean): void {
}
}
export interface AiFold {
readonly open: WritableSignal<boolean>;
toggle(): boolean;
}
export function aiFold(key?: () => string): AiFold {
const open = linkedSignal(() => key ? aiDisclosureRemembered(key()) : false);
return {
open,
toggle: () => {
const next = !open();
open.set(next);
if (key) {
aiDisclosureRemember(key(), next);
}
return next;
}
};
}
const REVEAL_GAP = 12;
function scrollerOf(element: HTMLElement): HTMLElement | null {
@ -79,26 +99,19 @@ export class AiDisclosureComponent {
summary = input.required<string>();
variant = input<'details' | 'section' | 'divided'>('section');
key = input<string>('');
variant = input<'section' | 'divided'>('section');
private host = inject(ElementRef<HTMLElement>);
private toggledOpen = signal<boolean | null>(null);
private fold = aiFold();
open = computed(() => this.toggledOpen() ?? aiDisclosureRemembered(this.key()));
open = this.fold.open;
classes = computed(() => 'tb-disc ' + (this.variant() === 'details' ? 'tb-disc-details'
: this.variant() === 'divided' ? 'tb-disc-section tb-disc-divided' : 'tb-disc-section'));
classes = computed(() => 'tb-disc tb-disc-section' + (this.variant() === 'divided' ? ' tb-disc-divided' : ''));
toggled(open: boolean): void {
if (open !== this.open()) {
this.toggledOpen.set(open);
aiDisclosureRemember(this.key(), open);
if (open) {
aiRevealOpened(this.host.nativeElement);
}
if (open !== this.open() && this.fold.toggle()) {
aiRevealOpened(this.host.nativeElement);
}
}
}

74
ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html

@ -6,12 +6,9 @@
-->
<section class="k-hand" [class.done]="folded()" [attr.aria-label]="'ai-assistant.hand-over.needs-you' | translate">
@if (folded()) {
<div class="k-head">
<mat-icon class="tb-mat-16" aria-hidden="true">person</mat-icon><span class="k-who">{{ 'ai-assistant.hand-over.needs-you' | translate }}</span>
<span class="k-sub">{{ handOver().title }}</span>
</div>
<button mat-icon-button type="button" class="k-hand-close" (click)="unfold()" [attr.aria-expanded]="false"
[attr.aria-label]="'ai-assistant.hand-over.unfold' | translate"><mat-icon>expand_more</mat-icon></button>
<button type="button" class="k-hand-fold" [attr.aria-expanded]="false" [attr.aria-label]="'ai-assistant.hand-over.unfold' | translate" (click)="unfold()">
<mat-icon class="tb-mat-18" aria-hidden="true">check_circle</mat-icon><span>{{ handOver().title }}</span><mat-icon class="tb-mat-18" aria-hidden="true">expand_more</mat-icon>
</button>
<div class="k-body"><p>{{ arrivedLine() }}</p></div>
} @else {
<div class="k-head">
@ -37,7 +34,7 @@
@for (option of choice.options; track option.id) {
<button type="button" [attr.aria-pressed]="choiceValue() === option.id" (click)="pick(option.id)">
@if (option.icon) {
<mat-icon class="tb-mat-18" aria-hidden="true">{{ option.icon }}</mat-icon>
<tb-icon class="tb-mat-18" aria-hidden="true">{{ option.icon }}</tb-icon>
}
{{ option.label }}
</button>
@ -70,6 +67,7 @@
}
@if (step.values.length || step.markdown) {
<div class="k-step-x">
<div class="k-values" [class.k-vgroup]="step.values.length > 1">
@for (value of step.values; track $index; let v = $index) {
<div class="tb-codeblock value k-value" data-lang="text" [class.secret]="value.secret">
<mat-icon class="tb-mat-16 k-value-ic" aria-hidden="true">{{ value.icon }}</mat-icon>
@ -90,6 +88,7 @@
</button>
</div>
}
</div>
@if (step.markdown) {
<tb-markdown usePlainMarkdown [highlight]="false" [data]="md(step.markdown)" (ready)="decorate()"></tb-markdown>
}
@ -105,36 +104,40 @@
<p class="ob-hint">{{ test.hint }}</p>
}
<div class="k-test-slot"></div>
@if (test.outcomes.length) {
<tb-ai-disclosure variant="section" [summary]="'ai-assistant.hand-over.what-you-see' | translate">
<table class="k-outcomes">
@for (outcome of test.outcomes; track $index) {
<tr [class.ok]="outcome.ok" [class.warn]="!outcome.ok">
<td><code>{{ outcome.output }}</code></td>
<td>{{ outcome.meaning }}</td>
</tr>
}
</table>
</tb-ai-disclosure>
}
</tb-ai-disclosure>
}
@if (quiet() || stoppedQuiet()) {
@if (stopped()) {
<div class="k-quiet">
<div class="k-wait stopped" role="status">
<mat-icon class="tb-mat-18" aria-hidden="true">stop_circle</mat-icon>
<span class="k-wait-t">{{ 'ai-assistant.hand-over.stopped-at' | translate: {time: stoppedAt()} }}</span>
@if (canListenAgain()) {
<span class="k-wait-tools">
<button mat-button type="button" (click)="listenAgain.emit()">
<mat-icon>play_arrow</mat-icon>{{ 'ai-assistant.hand-over.listen-again' | translate }}
</button>
</span>
}
</div>
</div>
} @else if (quiet()) {
<div class="k-quiet">
<div class="k-wait warn" role="status">
<mat-icon class="tb-mat-18" aria-hidden="true">schedule</mat-icon>
<span>{{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.nothing-heard') | translate: {minutes: quietMinutes()} }}</span>
@if (waiting()) {
<span class="clock">{{ clock() }}</span>
}
<span class="clock">{{ clock() }}</span>
<span class="k-wait-tools">
<button type="button" class="k-wait-tool" (click)="stop.emit()"
[matTooltip]="'ai-assistant.hand-over.stop-listening' | translate" matTooltipPosition="above"
[attr.aria-label]="'ai-assistant.hand-over.stop-listening' | translate">
<mat-icon class="tb-mat-16" aria-hidden="true">stop</mat-icon>
</button>
</span>
</div>
@if (handOver().quiet && !undecoded()) {
<p class="ob-hint">{{ handOver().quiet }}</p>
}
<div class="k-chips">
@if (canSendTest() && waiting()) {
<button type="button" class="ob-chip" [disabled]="testState() === 'sending'" (click)="sendTest()">
<mat-icon aria-hidden="true">science</mat-icon>{{ 'ai-assistant.hand-over.send-test-here' | translate }}
@if (canSendTest()) {
<button mat-stroked-button type="button" [disabled]="testState() === 'sending'" (click)="sendTest()">
<mat-icon>science</mat-icon>{{ 'ai-assistant.hand-over.send-test' | translate }}
</button>
}
<button type="button" class="ob-chip" (click)="say('ai-assistant.hand-over.keep-waiting-prompt')">
@ -167,15 +170,18 @@
</div>
@if (canSendTest()) {
<div class="k-chips">
<button type="button" class="ob-chip" [disabled]="testState() === 'sending'" (click)="sendTest()"
<button mat-stroked-button type="button" [disabled]="testState() === 'sending'" (click)="sendTest()"
[matTooltip]="'ai-assistant.hand-over.send-test-tip' | translate" matTooltipPosition="above">
<mat-icon aria-hidden="true">science</mat-icon>{{ 'ai-assistant.hand-over.send-test' | translate }}
<mat-icon>science</mat-icon>{{ 'ai-assistant.hand-over.send-test' | translate }}
</button>
</div>
}
@if (testNote(); as note) {
<p class="k-test-note" [class.warn]="testState() === 'failed'" role="status">{{ note }}</p>
}
</div>
}
@if (testNote(); as note) {
<div class="k-test-line" [class.warn]="testState() === 'failed'" role="status">
<mat-icon class="tb-mat-18" aria-hidden="true">{{ testState() === 'failed' ? 'error_outline' : 'science' }}</mat-icon>
<span>{{ note }}</span>
</div>
}
</div>

95
ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts

@ -1,8 +1,9 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { readStored, writeStored } from '@core/local-storage/stored';
import { AfterViewChecked, Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, NgZone, Output, signal, untracked } from '@angular/core';
import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models';
import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component';
import { aiFold, aiRevealOpened } from '@home/components/ai/ai-disclosure.component';
import { Clipboard } from '@angular/cdk/clipboard';
import { TranslateService } from '@ngx-translate/core';
import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models';
@ -26,6 +27,45 @@ function localOs(): string {
return /Windows/i.test(platform) ? 'windows' : /Mac/i.test(platform) ? 'macos' : 'linux';
}
const COPIED_MS = 1500;
const PROGRESS_KEY = 'tb.ai.handOver.';
const PROGRESS_INDEX = 'tb.ai.handOvers';
const MAX_SAVED_PROGRESS = 50;
export interface AiHandOverProgress {
title: string;
choice?: string;
ticks: number[];
ticked: string[];
steps: number;
}
export function aiHandOverProgress(cardId: string): AiHandOverProgress | null {
if (!cardId) {
return null;
}
try {
const saved = readStored(PROGRESS_KEY + cardId);
return saved ? JSON.parse(saved) as AiHandOverProgress : null;
} catch {
return null;
}
}
function aiSaveHandOverProgress(cardId: string, progress: AiHandOverProgress): void {
if (!cardId) {
return;
}
writeStored(PROGRESS_KEY + cardId, JSON.stringify(progress));
let saved: string[] = [];
try {
saved = JSON.parse(readStored(PROGRESS_INDEX) ?? '[]');
} catch {
saved = [];
}
const kept = [...saved.filter(id => id !== cardId), cardId];
kept.slice(0, Math.max(0, kept.length - MAX_SAVED_PROGRESS)).forEach(id => writeStored(PROGRESS_KEY + id, null));
writeStored(PROGRESS_INDEX, JSON.stringify(kept.slice(-MAX_SAVED_PROGRESS)));
}
@Component({
selector: 'tb-ai-hand-over',
@ -38,12 +78,26 @@ export class AiHandOverComponent implements AfterViewChecked {
wait = input<AiHandOverWait | null>(null);
time = input<number>(0);
files = input<ReadonlyMap<string, AiFile>>(new Map());
cardId = input<string>('');
testRequest = input(0);
private handledTest = 0;
private testRequested = effect(() => {
const request = this.testRequest();
if (request > this.handledTest) {
this.handledTest = request;
untracked(() => this.sendTest());
}
});
canListenAgain = input(false);
@Output() prompt = new EventEmitter<string>();
@Output() stop = new EventEmitter<void>();
@Output() compose = new EventEmitter<string>();
@Output() openFile = new EventEmitter<AiFile>();
@Output() listenAgain = new EventEmitter<void>();
readonly fileMark = aiFileMark;
readonly fileName = aiFileName;
@ -57,10 +111,13 @@ export class AiHandOverComponent implements AfterViewChecked {
readonly shown = signal<ReadonlySet<string>>(new Set());
readonly copied = signal<string | null>(null);
readonly now = signal(Date.now());
readonly open = signal(false);
private readonly fold = aiFold();
readonly open = this.fold.open;
readonly testState = signal<'idle' | 'sending' | 'sent' | 'failed'>('idle');
readonly testAt = signal(0);
readonly testError = signal('');
readonly lastTickAt = signal(0);
readonly choiceValue = computed(() => this.picked() ?? this.handOver().choice?.value ?? null);
readonly steps = computed(() => {
@ -97,13 +154,18 @@ export class AiHandOverComponent implements AfterViewChecked {
});
readonly silenceMs = computed(() => Math.min(MAX_SILENCE_MS,
Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0))));
readonly quiet = computed(() => this.waiting() && this.elapsed() >= this.silenceMs());
readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.elapsed() / 60000)));
readonly silent = computed(() => Math.max(0, this.now() - Math.max(this.wait()?.startedAt ?? this.now(), this.lastTickAt())));
readonly quiet = computed(() => this.waiting() && this.silent() >= this.silenceMs());
readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.silent() / 60000)));
readonly undecoded = computed(() => this.wait()?.check?.failedStep === 'decoded');
readonly stoppedQuiet = computed(() => {
readonly stopped = computed(() => {
const wait = this.wait();
return !!wait && !wait.running && !!wait.check && !wait.check.dataArriving;
});
readonly stoppedAt = computed(() => {
const at = this.wait()?.endedAt;
return at ? new Date(at).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}) : '';
});
constructor() {
const zone = inject(NgZone);
@ -125,6 +187,15 @@ export class AiHandOverComponent implements AfterViewChecked {
}
});
inject(DestroyRef).onDestroy(stopTimer);
effect(() => {
const saved = aiHandOverProgress(this.cardId());
untracked(() => {
if (saved?.choice) {
this.picked.set(saved.choice);
}
this.ticked.set(new Set(saved?.ticks ?? []));
});
});
effect(() => {
this.choiceText();
this.steps();
@ -168,6 +239,7 @@ export class AiHandOverComponent implements AfterViewChecked {
pick(id: string): void {
this.picked.set(id);
this.ticked.set(new Set());
this.saveProgress();
}
tick(index: number): void {
@ -178,6 +250,19 @@ export class AiHandOverComponent implements AfterViewChecked {
next.add(index);
}
this.ticked.set(next);
this.lastTickAt.set(Date.now());
this.saveProgress();
}
private saveProgress(): void {
const steps = this.steps();
aiSaveHandOverProgress(this.cardId(), {
title: this.handOver().title,
choice: this.picked() ?? undefined,
ticks: [...this.ticked()],
ticked: steps.filter((_, index) => this.done(index)).map(step => step.title),
steps: steps.length
});
}
done(index: number): boolean {

60
ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html

@ -5,43 +5,27 @@
-->
@let current = view();
<section class="k-credits-out" role="alert" [attr.aria-label]="current.title">
<div class="k-credits-out-head">
<span class="k-credits-out-mark" aria-hidden="true"><mat-icon fontSet="material-icons-round">{{ current.icon }}</mat-icon></span>
<div class="k-credits-out-text">
<b>{{ current.title }}</b>
<span>{{ current.text }}</span>
</div>
<button mat-icon-button type="button" class="k-credits-out-close" [matTooltip]="'action.close' | translate"
[attr.aria-label]="'action.close' | translate" (click)="dismissed.emit()">
<mat-icon>close</mat-icon>
</button>
</div>
@if (current.action !== 'none' || current.usage) {
<div class="k-credits-out-actions">
@switch (current.action) {
@case ('request') {
@if (state() === 'sent') {
<span class="k-credits-out-sent" role="status"><mat-icon fontSet="material-icons-round">check_circle</mat-icon>{{ 'ai-assistant.limit-out.sent' | translate }}</span>
} @else {
<button mat-flat-button color="primary" type="button" [disabled]="state() === 'sending'" (click)="request()">
{{ current.requestLabel | translate }}
</button>
@if (state() === 'failed') {
<span class="k-credits-out-failed" role="status">{{ 'ai-assistant.limit-out.failed' | translate }}</span>
}
}
}
@case ('license') {
<a mat-flat-button color="primary" routerLink="/license">{{ 'ai-assistant.limit-out.manage-license' | translate }}</a>
}
@case ('pricing') {
<a mat-flat-button color="primary" [href]="pricingUrl" target="_blank" rel="noopener">{{ 'subscription.upgrade-plan' | translate }}</a>
}
<div class="k-notice k-notice-edge warn" role="status">
<mat-icon aria-hidden="true">{{ current.icon }}</mat-icon>
<span>{{ noticeText() }}</span>
@switch (current.action) {
@case ('request') {
@if (state() === 'sent') {
<small class="k-notice-done">{{ 'ai-assistant.limit-out.sent' | translate }}</small>
} @else {
<button mat-button type="button" [disabled]="state() === 'sending'" (click)="request()">{{ current.requestLabel | translate }}</button>
}
@if (current.usage) {
<a mat-button routerLink="/usage" class="k-credits-out-usage">{{ 'ai-assistant.limit-out.view-usage' | translate }}</a>
}
</div>
}
@case ('license') {
<a mat-button routerLink="/license">{{ 'ai-assistant.limit-out.manage-license' | translate }}</a>
}
@case ('pricing') {
<a mat-button [href]="pricingUrl" target="_blank" rel="noopener">{{ 'subscription.upgrade-plan' | translate }}</a>
}
}
</section>
<button mat-icon-button type="button" class="k-notice-x" [matTooltip]="'action.close' | translate" [attr.aria-label]="'action.close' | translate"
(click)="dismissed.emit()"><mat-icon>close</mat-icon></button>
</div>
@if (state() === 'failed') {
<p class="k-notice-err" role="status">{{ 'ai-assistant.limit-out.failed' | translate }}</p>
}

26
ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { aiLocale } from '@home/components/ai/ai-text';
import { ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal } from '@angular/core';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
@ -20,9 +21,7 @@ type LimitAction = 'request' | 'license' | 'pricing' | 'none';
interface LimitView {
icon: string;
title: string;
text: string;
action: LimitAction;
usage: boolean;
requestLabel?: string;
storageKey: string;
send?: () => Observable<void>;
@ -60,6 +59,11 @@ export class AiLimitOutComponent {
readonly pricingUrl = PRICING_URL;
readonly state = signal<RequestState>('idle');
readonly view = computed(() => this.viewOf(this.platformLimit()));
readonly noticeText = computed(() => {
const limit = this.platformLimit();
const title = this.view().title;
return limit.limit ? this.say('notice-count', {title, limit: this.count(limit.limit)}) : this.say('notice', {title});
});
constructor() {
effect(() => this.state.set(this.wasRequested(this.view().storageKey) ? 'sent' : 'idle'));
@ -80,10 +84,12 @@ export class AiLimitOutComponent {
});
}
private count(value: number): string {
return value.toLocaleString(aiLocale(this.translate.currentLang));
}
private viewOf(limit: AiPlatformLimit): LimitView {
const tenantAdmin = this.user?.authority === Authority.TENANT_ADMIN;
const sysAdmin = this.user?.authority === Authority.SYS_ADMIN;
const customer = this.user?.authority === Authority.CUSTOMER_USER;
const oldLicense = !(this.authState?.licenseVersion > 1);
const config = {ignoreLoading: true, ignoreErrors: true};
if (limit.errorCode === 41 && limit.entityType) {
@ -91,11 +97,7 @@ export class AiLimitOutComponent {
return {
icon: 'data_usage',
title: this.say('entity-title', {entities: this.entities(entityType)}),
text: customer
? this.say('tenant-text-plain', {entities: this.entities(entityType).toLowerCase()})
: this.say('tenant-text', {limit: limit.limit, entities: this.entities(entityType).toLowerCase()}),
action: 'request',
usage: tenantAdmin,
requestLabel: 'ai-assistant.limit-out.request',
storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${entityType}:${limit.limit}`,
send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(entityType, false, config)
@ -107,11 +109,7 @@ export class AiLimitOutComponent {
return {
icon: 'data_usage',
title: this.say('entity-title', {entities: this.entities(licensedType)}),
text: oldLicense
? this.say('license-text-old', {entities: this.entities(licensedType).toLowerCase()})
: this.say('license-text', {entities: this.entities(licensedType).toLowerCase()}),
action: oldLicense ? 'pricing' : (sysAdmin ? 'license' : 'request'),
usage: false,
requestLabel: 'ai-assistant.limit-out.request',
storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${licensedType}:license`,
send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(licensedType, true, config)
@ -128,9 +126,7 @@ export class AiLimitOutComponent {
? this.translate.instant(`platform-feature.${featureKey}.not-in-ce-grant`)
: (whiteLabeling ? this.translate.instant('platform-feature.white-labeling.not-in-plan')
: this.say('feature-title', {feature: this.say(`feature.${featureKey}`)})),
text: this.say(addon === AddonType.WHITE_LABELING ? 'white-labeling-text' : 'pack-text'),
action: sysAdmin ? 'license' : (oldLicense && !grant ? 'pricing' : 'request'),
usage: false,
requestLabel: 'subscription.request-access',
storageKey: addon === AddonType.WHITE_LABELING ? WL_REQUESTED_STORAGE_KEY : PE_PACK_REQUESTED_STORAGE_KEY,
send: () => this.notificationService.sendAddonAccessRequest(addon, config)
@ -139,9 +135,7 @@ export class AiLimitOutComponent {
return {
icon: 'lock',
title: this.say('license-required'),
text: limit.message ?? '',
action: sysAdmin ? 'license' : 'none',
usage: false,
storageKey: ''
};
}

22
ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html

@ -0,0 +1,22 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="k-numf" [class.s]="size() === 's'" [class.m]="size() === 'm'" [class.l]="size() === 'l'">
<button mat-icon-button type="button" [disabled]="disabled()" [attr.aria-label]="'ai-assistant.question.lower' | translate: {step: step()}"
(click)="stepBy(numInput, -1)"><mat-icon>remove</mat-icon></button>
<input #numInput class="k-num-in" type="text" inputmode="decimal" spellcheck="false" [disabled]="disabled()"
[value]="value()" [attr.aria-invalid]="wrong() || null" [attr.aria-label]="question().question + (question().number?.unit ? ' · ' + question().number.unit : '')"
(input)="typed(numInput)" (blur)="settle()" (keydown.arrowup)="$event.preventDefault(); stepBy(numInput, 1)"
(keydown.arrowdown)="$event.preventDefault(); stepBy(numInput, -1)" (keydown.enter)="onEnter($event)">
@if (question().number?.unit) {
<span class="k-unit">{{ question().number.unit }}</span>
}
<button mat-icon-button type="button" [disabled]="disabled()" [attr.aria-label]="'ai-assistant.question.higher' | translate: {step: step()}"
(click)="stepBy(numInput, 1)"><mat-icon>add</mat-icon></button>
</div>
@if (wrong()) {
<p class="k-opterr row" role="alert">{{ 'ai-assistant.question.number-error' | translate }}</p>
}

65
ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts

@ -0,0 +1,65 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, inject, input, model, output, signal } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { AiQuestion } from '@shared/models/solution-creator.models';
import { aiLocale, aiNumberReady, aiReadNumber, aiSayNumber, aiStepDecimals } from '@home/components/ai/ai-question.models';
@Component({
selector: 'tb-ai-number-field',
templateUrl: './ai-number-field.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false
})
export class AiNumberFieldComponent {
question = input.required<AiQuestion>();
value = model('');
disabled = input(false);
enter = output<Event>();
private translate = inject(TranslateService);
private touched = signal(false);
readonly ready = computed(() => aiNumberReady(this.value(), this.locale()));
readonly wrong = computed(() => this.touched() && !!this.value().trim() && !this.ready());
readonly size = computed(() => this.question().number?.size === 'short' ? 's' : this.question().number?.size === 'medium' ? 'm' : 'l');
readonly step = computed(() => this.question().number?.step > 0 ? this.question().number.step : 1);
typed(field: HTMLInputElement): void {
this.value.set(field.value);
}
stepBy(field: HTMLInputElement, direction: number): void {
if (this.disabled()) {
return;
}
const current = aiReadNumber(field.value, this.locale());
const base = isNaN(current) ? (this.question().number?.suggested ?? 0) : current;
const decimals = Math.max(aiStepDecimals(this.step()), isNaN(current) ? 0 : aiStepDecimals(current));
field.value = aiSayNumber(+(base + direction * this.step()).toFixed(decimals));
this.touched.set(false);
this.value.set(field.value);
field.focus();
}
settle(): void {
this.touched.set(true);
}
onEnter(event: Event): void {
if ((event as KeyboardEvent).isComposing) {
return;
}
if (!this.ready()) {
event.preventDefault();
this.touched.set(true);
return;
}
this.enter.emit(event);
}
private locale(): string {
return aiLocale(this.translate.currentLang);
}
}

25
ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html

@ -4,7 +4,19 @@
SPDX-License-Identifier: BUSL-1.1
-->
<div class="k-plan min" [class.gate]="gate()">
@if (folded()) {
<button type="button" class="k-plan-fold" [attr.aria-expanded]="open()" (click)="toggleFold()">
@if (replacedAfter() !== null) {
<span class="k-stage-ring" aria-hidden="true"></span>
} @else {
<mat-icon class="k-mark" aria-hidden="true">check</mat-icon>
}
<span class="k-plan-fold-t">{{ foldText() }}</span>
<mat-icon class="tb-mat-18 k-plan-fold-chev" [class.open]="open()" aria-hidden="true">chevron_right</mat-icon>
</button>
}
@if (!folded() || open()) {
<div class="k-plan min" [class.gate]="gate()" [class.in-fold]="folded()">
<div class="k-plan-head">
<span>{{ 'ai-assistant.plan.title' | translate }}</span>
<span class="k-plan-count">{{ gate() || !progress() ? ('ai-assistant.plan.steps' | translate: {count: counted()}) : ('ai-assistant.plan.done-of' | translate: {done: done(), count: counted()}) }}</span>
@ -23,15 +35,9 @@
<input type="checkbox" class="k-check" [checked]="checked($index)" (change)="toggle($index)"
[attr.aria-label]="step.text">
} @else {
<span class="k-pmark" [class]="'k-pmark ' + marks()[$index]">
@if (marks()[$index] === 'done') {
<mat-icon aria-hidden="true">check</mat-icon>
} @else if (marks()[$index] === 'off') {
<mat-icon aria-hidden="true">remove</mat-icon>
}
</span>
<tb-ai-step-mark [mark]="marks()[$index]"></tb-ai-step-mark>
}
<span class="k-what">@if (step.by === 'user') {<span class="k-you">{{ 'ai-assistant.plan.you' | translate }}</span>@if (step.needs) {<span class="k-need">{{ 'ai-assistant.plan.needs.' + step.needs | translate }}</span>}}@for (part of parts(step.text); track $index) {@if (part.code) {<code>{{ part.text }}</code>} @else {{{ part.text }}}}</span>
<span class="k-what">@if (step.by === 'user') {<span class="k-you">{{ 'ai-assistant.plan.you' | translate }}</span>}@for (part of parts(step.text); track $index) {@if (part.code) {<code>{{ part.text }}</code>} @else {{{ part.text }}}}@if (step.by === 'user' && step.needs) {<span class="k-need"> {{ 'ai-assistant.plan.needs.' + step.needs | translate }}</span>}</span>
</li>
}
</ol>
@ -55,3 +61,4 @@
</div>
}
</div>
}

48
ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts

@ -1,15 +1,16 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, computed, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { decorateReferences } from '@home/components/ai/ai-references';
import { AiPlanProgress, AiPlanStep } from '@home/components/ai/ai-action.models';
import { AiPlanProgress, AiPlanStep, aiPlanStatus } from '@home/components/ai/ai-action.models';
import { aiFold } from '@home/components/ai/ai-disclosure.component';
export interface AiPlanRun {
auto: boolean;
skipped: number[];
}
type AiPlanMark = 'todo' | 'now' | 'done' | 'off';
@Component({
selector: 'tb-ai-plan',
@ -22,6 +23,11 @@ export class AiPlanComponent {
progress = input<AiPlanProgress | null>(null);
gate = input(false);
autoApprove = input(false);
replacedAfter = input<number | null>(null);
private fold = aiFold();
open = this.fold.open;
@Output() run = new EventEmitter<AiPlanRun>();
@Output() change = new EventEmitter<void>();
@ -29,9 +35,12 @@ export class AiPlanComponent {
private cleared = signal<ReadonlySet<number>>(new Set());
private host = inject(ElementRef<HTMLElement>);
private translate = inject(TranslateService);
private chips = effect(() => {
const steps = this.steps();
this.open();
this.folded();
setTimeout(() => {
const whats = (this.host.nativeElement as HTMLElement).querySelectorAll<HTMLElement>('.k-plan li .k-what');
steps.forEach((step, index) => {
@ -42,25 +51,30 @@ export class AiPlanComponent {
});
});
marks = computed<AiPlanMark[]>(() => {
const progress = this.progress();
return this.steps().map((_, index) => {
const number = index + 1;
if (progress?.done.includes(number)) {
return 'done';
}
if (progress?.skipped.includes(number)) {
return 'off';
}
return progress?.now === number ? 'now' : 'todo';
});
});
status = computed(() => aiPlanStatus(this.steps(), this.progress()));
marks = computed(() => this.status().marks);
counted = computed(() => this.gate()
? this.steps().filter((step, index) => !step.optional || !this.cleared().has(index)).length
: this.marks().filter(mark => mark !== 'off').length);
: this.status().counted);
done = computed(() => this.marks().filter(mark => mark === 'done').length);
done = computed(() => this.status().done);
finished = computed(() => !this.gate() && this.status().finished);
folded = computed(() => this.replacedAfter() !== null || this.finished());
foldText = computed(() => {
const translate = this.translate;
return this.replacedAfter() !== null
? translate.instant('ai-assistant.plan.replaced', {done: this.replacedAfter(), count: this.counted()})
: translate.instant('ai-assistant.plan.folded', {done: this.done(), count: this.counted()});
});
toggleFold(): void {
this.fold.toggle();
}
parts(text: string): {text: string; code: boolean}[] {
return text.split('`').map((part, index) => ({text: part, code: index % 2 === 1})).filter(part => part.text);

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

@ -511,7 +511,7 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox=
.composer-chevron {
--chevron: 17px;
height: var(--chat-text-lh, 22px);
height: var(--chat-line-lh, 20px);
}
.composer-foot .composer-auto {
@ -682,9 +682,6 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox=
}
.composer-slash {
position: absolute;
top: 50%;
right: 19px;
display: inline-flex;
align-items: center;
justify-content: center;
@ -695,11 +692,14 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox=
border: 1px solid var(--tb-line);
border-bottom-width: 2px;
border-radius: 5px;
background: none;
color: var(--k-faint);
font: 400 11px/1 var(--tb-font);
background: var(--chat-key);
color: var(--tb-ink-76);
font: 500 11px/1 var(--tb-font);
letter-spacing: .2px;
white-space: nowrap;
position: absolute;
top: 50%;
right: 19px;
pointer-events: none;
transform: translateY(-50%);
}

186
ui-ngx/src/app/modules/home/components/ai/ai-question.component.html

@ -70,112 +70,118 @@
@if (numbered) {
<span class="k-qn" aria-hidden="true"><b>{{ numbered }}</b></span>
}
<b>{{ step.question }}</b>
<b>@if (step.parts) {@for (part of step.parts; track $index) {@if (part.severity) {<span [class]="'k-sev ' + part.severity.toLowerCase()"><tb-ai-sev-mark [severity]="part.severity"></tb-ai-sev-mark>{{ ('alarm.severity-' + part.severity.toLowerCase()) | translate }}</span>} @else {{{ part.text }}}}} @else {{{ step.question }}}</b>
@if (step.why) {
<span class="k-why">{{ step.why }}</span>
}
</div>
<div class="k-ask-a">
@if (isFree(step) && isColor(step)) {
<div class="k-optrow">
<button #freeColor type="button" class="ob-chip" [attr.aria-pressed]="!!otherText(step)" [disabled]="disabled()"
(click)="pickColor(step, freeColor)">
@if (colorOf(otherText(step)); as color) {
<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>{{ color }}
} @else {
<mat-icon aria-hidden="true">palette</mat-icon>{{ 'ai-assistant.question.pick-color' | translate }}
}
</button>
</div>
} @else if (isFree(step)) {
<div class="k-optcards list">
<div class="k-optcard other free" (click)="$any($event.currentTarget).querySelector('.k-opt-input')?.focus()">
<span class="k-optbody">
<b>{{ 'ai-assistant.question.your-answer' | translate }}</b>
@if (step.secret) {
<input #secretInput class="k-opt-input" type="password" autocomplete="new-password" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)" [placeholder]="'ai-assistant.question.type-secret' | translate"
[attr.aria-label]="step.question" (input)="type(step, secretInput)" (keydown.enter)="onEnter($event)">
} @else {
@switch (kind(step)) {
@case ('color') {
<tb-ai-color-field [question]="step" [value]="colorValue(step)" [disabled]="disabled()"
(valueChange)="setColor(step, $event)" (enter)="onEnter($event)"></tb-ai-color-field>
}
@case ('secret') {
<tb-ai-secret-field [question]="step" [value]="otherText(step)" [disabled]="disabled()"
(valueChange)="setTyped(step, $event)" (enter)="onEnter($event)"></tb-ai-secret-field>
}
@case ('number') {
<tb-ai-number-field [question]="step" [value]="otherText(step)" [disabled]="disabled()"
(valueChange)="setTyped(step, $event)" (enter)="onEnter($event)"></tb-ai-number-field>
}
@case ('text') {
<div class="k-optcards list">
<div class="k-optcard other free" (click)="$any($event.currentTarget).querySelector('.k-opt-input')?.focus()">
<span class="k-optbody">
<b>{{ otherLabel(step) }}</b>
<textarea #freeArea class="k-opt-input" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)" [placeholder]="'ai-assistant.question.type-answer' | translate"
[value]="otherText(step)" [placeholder]="step.other?.placeholder || ('ai-assistant.question.type-answer' | translate)"
[attr.aria-label]="step.question" (input)="type(step, freeArea)" (keydown.enter)="onEnter($event)"></textarea>
}
</span>
</span>
</div>
</div>
</div>
} @else if (step.multiple) {
<div class="k-optcards" [class.list]="step.options.length >= 5" role="group" [attr.aria-label]="step.question"
[style.--n]="step.options.length">
@for (option of step.options; track option.label) {
<button type="button" role="checkbox" class="k-optcard multi" [attr.aria-checked]="isChosen(step, option.label)"
[disabled]="disabled()" (click)="toggle(step, option.label)">
}
@case ('multi') {
<div class="k-optcards" [class.list]="step.options.length >= 5" role="group" [attr.aria-label]="step.question"
[style.--n]="step.options.length">
@for (option of step.options; track option.label) {
<button type="button" role="checkbox" class="k-optcard multi" [attr.aria-checked]="isChosen(step, option.label)"
[disabled]="disabled()" (click)="toggle(step, option.label)">
<span class="k-optdot"><mat-icon aria-hidden="true">check</mat-icon></span>
<span class="k-optbody"><b>@if (colorOf(option.label); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
</button>
}
<div class="k-optcard multi other" role="checkbox" [attr.aria-checked]="isOther(step)" (click)="multiArea.focus()">
<span class="k-optdot"><mat-icon aria-hidden="true">check</mat-icon></span>
<span class="k-optbody"><b>@if (colorOf(option.label); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
</button>
}
<div class="k-optcard multi other" role="checkbox" [attr.aria-checked]="isOther(step)" (click)="multiArea.focus()">
<span class="k-optdot"><mat-icon aria-hidden="true">check</mat-icon></span>
<span class="k-optbody">
<b>{{ 'ai-assistant.question.other' | translate }}</b>
<textarea #multiArea class="k-opt-input" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)" [placeholder]="'ai-assistant.question.other-hint' | translate"
[attr.aria-label]="step.question + ' · ' + ('ai-assistant.question.other' | translate)"
(input)="type(step, multiArea)" (keydown.enter)="onEnter($event)"></textarea>
</span>
<span class="k-optbody">
<b>{{ otherLabel(step) }}</b>
<textarea #multiArea class="k-opt-input" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)" [placeholder]="step.other?.placeholder || ('ai-assistant.question.other-hint' | translate)"
[attr.aria-label]="step.question + ' · ' + otherLabel(step)"
(input)="type(step, multiArea)" (keydown.enter)="onEnter($event)"></textarea>
</span>
</div>
</div>
</div>
} @else if (isChipRow(step)) {
<div class="k-optrow" role="radiogroup" [attr.aria-label]="step.question">
@for (option of step.options; track option.label) {
<button type="button" role="radio" class="ob-chip" [attr.aria-checked]="!isOther(step) && valueOf(step) === option.label"
[attr.aria-pressed]="!isOther(step) && valueOf(step) === option.label"
[disabled]="disabled()" (click)="pick(step, option.label)">@if (colorOf(option.label); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ option.label }}</button>
}
@if (isColor(step)) {
<button #otherColor type="button" role="radio" class="ob-chip" [attr.aria-checked]="isOther(step)" [attr.aria-pressed]="isOther(step)"
[disabled]="disabled()" (click)="pickColor(step, otherColor)">
@if (isOther(step) && colorOf(otherText(step)); as color) {
<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>{{ color }}
} @else {
<mat-icon aria-hidden="true">palette</mat-icon>{{ 'ai-assistant.question.other-color' | translate }}
}
}
@case ('date') {
<div class="k-optrow" role="radiogroup" [attr.aria-label]="step.question">
@for (option of step.options; track option.label) {
<button type="button" role="radio" class="ob-chip" [attr.aria-checked]="!isOther(step) && valueOf(step) === option.label"
[attr.aria-pressed]="!isOther(step) && valueOf(step) === option.label"
[disabled]="disabled()" (click)="pick(step, option.label)">{{ option.label }}</button>
}
<button #dayChip type="button" role="radio" class="ob-chip" aria-haspopup="dialog" [attr.aria-expanded]="dayOpen() === step.id"
[attr.aria-checked]="isOther(step) && !!otherText(step)" [attr.aria-pressed]="isOther(step) && !!otherText(step)"
[disabled]="disabled()" (click)="openDay(step, dayChip)">
<mat-icon aria-hidden="true">calendar_today</mat-icon>{{ isOther(step) && otherText(step) ? otherText(step) : otherLabel(step) + '…' }}
</button>
} @else {
</div>
}
@case ('chips') {
<div class="k-optrow" role="radiogroup" [attr.aria-label]="step.question">
@for (option of step.options; track option.label) {
<button type="button" role="radio" class="ob-chip" [attr.aria-checked]="!isOther(step) && valueOf(step) === option.label"
[attr.aria-pressed]="!isOther(step) && valueOf(step) === option.label"
[disabled]="disabled()" (click)="pick(step, option.label)">{{ option.label }}</button>
}
<button type="button" role="radio" class="ob-chip" [attr.aria-checked]="isOther(step)" [attr.aria-pressed]="isOther(step)"
[disabled]="disabled()" (click)="pickOther(step)">{{ 'ai-assistant.question.other-chip' | translate }}</button>
[disabled]="disabled()" (click)="pickOther(step)">{{ step.other?.label ? step.other.label + '…' : ('ai-assistant.question.other-chip' | translate) }}</button>
</div>
@if (isOther(step) && step.number) {
<tb-ai-number-field [question]="step" [value]="otherText(step)" [disabled]="disabled()"
(valueChange)="setTyped(step, $event)" (enter)="onEnter($event)"></tb-ai-number-field>
} @else if (isOther(step)) {
<textarea #rowArea class="k-opt-input k-other-area" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)" [placeholder]="step.other?.placeholder || ('ai-assistant.question.other-hint' | translate)"
[attr.aria-label]="step.question + ' · ' + otherLabel(step)"
(input)="type(step, rowArea)" (keydown.enter)="onEnter($event)"></textarea>
} @else if (chosenHint(step); as hint) {
<p class="k-opthint">{{ hint }}</p>
}
</div>
@if (isOther(step) && !isColor(step)) {
<textarea #rowArea class="k-opt-input k-other-area" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)" [placeholder]="'ai-assistant.question.other-hint' | translate"
[attr.aria-label]="step.question + ' · ' + ('ai-assistant.question.other' | translate)"
(input)="type(step, rowArea)" (keydown.enter)="onEnter($event)"></textarea>
} @else if (chosenHint(step); as hint) {
<p class="k-opthint">{{ hint }}</p>
}
} @else {
<div class="k-optcards" [class.list]="step.options.length >= 5" role="radiogroup" [attr.aria-label]="step.question"
[style.--n]="step.options.length">
@for (option of step.options; track option.label) {
<button type="button" role="radio" class="k-optcard" [attr.aria-checked]="!isOther(step) && valueOf(step) === option.label"
[disabled]="disabled()" (click)="pick(step, option.label)">
@default {
<div class="k-optcards" [class.list]="step.options.length >= 5 || step.options.length < 2" role="radiogroup" [attr.aria-label]="step.question"
[style.--n]="step.options.length">
@for (option of step.options; track option.label) {
<button type="button" role="radio" class="k-optcard" [attr.aria-checked]="!isOther(step) && valueOf(step) === option.label"
[disabled]="disabled()" (click)="pick(step, option.label)">
<span class="k-optdot"></span>
<span class="k-optbody"><b>{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
</button>
}
<div class="k-optcard other" role="radio" [attr.aria-checked]="isOther(step)" (click)="otherArea.focus()">
<span class="k-optdot"></span>
<span class="k-optbody"><b>@if (colorOf(option.label); as color) {<span class="k-swatch" [style.background]="color" aria-hidden="true"></span>}{{ option.label }}</b>@if (option.hint) {<span>{{ option.hint }}</span>}</span>
</button>
}
<div class="k-optcard other" role="radio" [attr.aria-checked]="isOther(step)" (click)="otherArea.focus()">
<span class="k-optdot"></span>
<span class="k-optbody">
<b>{{ 'ai-assistant.question.other' | translate }}</b>
<textarea #otherArea class="k-opt-input" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)"
[placeholder]="'ai-assistant.question.other-hint' | translate"
[attr.aria-label]="step.question + ' · ' + ('ai-assistant.question.other' | translate)"
(focus)="pickOther(step)" (input)="type(step, otherArea)" (keydown.enter)="onEnter($event)"></textarea>
</span>
<span class="k-optbody">
<b>{{ otherLabel(step) }}</b>
<textarea #otherArea class="k-opt-input" rows="1" spellcheck="false" [disabled]="disabled()"
[value]="otherText(step)"
[placeholder]="step.other?.placeholder || ('ai-assistant.question.other-hint' | translate)"
[attr.aria-label]="step.question + ' · ' + otherLabel(step)"
(focus)="pickOther(step)" (input)="type(step, otherArea)" (keydown.enter)="onEnter($event)"></textarea>
</span>
</div>
</div>
</div>
}
}
</div>
</ng-template>

171
ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts

@ -1,20 +1,25 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, computed, EventEmitter, inject, input, Output, Renderer2, signal, ViewContainerRef } from '@angular/core';
import { ChangeDetectionStrategy, Component, computed, EventEmitter, inject, input, Output, Renderer2, signal, ViewContainerRef } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { AiQuestion, AiQuestionAnswer } from '@shared/models/solution-creator.models';
import { AiQuestion, AiQuestionAnswer, AiQuestionKind } from '@shared/models/solution-creator.models';
import { TbPopoverService } from '@shared/components/popover.service';
import { ColorPickerPanelComponent } from '@shared/components/color-picker/color-picker-panel.component';
import tinycolor from 'tinycolor2';
import {
aiColorOf,
aiIsFree,
aiIsNumber,
aiKindOf,
aiLocale,
aiNumberReady,
aiSayNumber
} from '@home/components/ai/ai-question.models';
import { aiColorAnswer, aiColorReady } from '@home/components/ai/ai-color-field.component';
import { AiDatePanelComponent, AiPickedDay } from '@home/components/ai/ai-date-panel.component';
export { aiColorOf } from '@home/components/ai/ai-question.models';
const MULTI_SEPARATOR = ', ';
const HEX_COLOR = /#[0-9a-f]{6}(?![0-9a-z])|#[0-9a-f]{3}(?![0-9a-z])/i;
export function aiColorOf(text: string | undefined): string | null {
return text?.match(HEX_COLOR)?.[0] ?? null;
}
export function aiAnswersText(answers: AiQuestionAnswer[]): string {
return answers.map(item => item.question.question.trim() + ' ' + item.answer.trim()).join('\n');
}
@ -56,6 +61,7 @@ function recommendedOf(question: AiQuestion): string[] {
@Component({
selector: 'tb-ai-question',
templateUrl: './ai-question.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false
})
export class AiQuestionComponent {
@ -74,10 +80,13 @@ export class AiQuestionComponent {
private viewContainerRef = inject(ViewContainerRef);
colorOf = aiColorOf;
isFree = aiIsFree;
at = signal(0);
move = signal<'next' | 'back' | null>(null);
dayOpen = signal<string | null>(null);
private picked = signal<Record<string, string>>({});
private days: Record<string, AiPickedDay> = {};
private chosen = signal<Record<string, string[]>>({});
private typed = signal<Record<string, string>>({});
@ -89,11 +98,11 @@ export class AiQuestionComponent {
if (picked !== undefined) {
return picked;
}
return this.isFree(question) ? '' : this.defaultOf(question);
return this.isFree(question) || question.date ? '' : this.defaultOf(question);
}
isFree(question: AiQuestion): boolean {
return !question.options?.length;
kind(question: AiQuestion): AiQuestionKind {
return aiKindOf(question);
}
isChosen(question: AiQuestion, label: string): boolean {
@ -116,83 +125,110 @@ export class AiQuestionComponent {
}
otherText(question: AiQuestion): string {
return this.typed()[question.id] ?? '';
}
ready(question: AiQuestion): boolean {
if (question.multiple && !this.isFree(question)) {
return true;
const typed = this.typed()[question.id];
if (typed !== undefined) {
return typed;
}
return this.isOther(question) ? !!this.otherText(question).trim() : !!this.valueOf(question);
const suggested = aiIsNumber(question) ? question.number?.suggested : undefined;
return suggested !== undefined && suggested !== null ? aiSayNumber(suggested) : '';
}
sheet = computed(() => this.questions().length > 1 && this.questions().every(question =>
!question.multiple && !this.isFree(question) && (this.isChipRow(question) || question.options.length <= 3)));
allReady = computed(() => this.questions().every(question => this.ready(question)));
finish(): void {
if (!this.disabled() && this.questions().every(question => this.ready(question))) {
this.done.emit(this.answers());
}
otherLabel(question: AiQuestion): string {
return question.other?.label || this.translate.instant(this.isFree(question) ? 'ai-assistant.question.your-answer'
: question.date ? 'ai-assistant.question.another-day' : 'ai-assistant.question.other');
}
isChipRow(question: AiQuestion): boolean {
return !question.multiple && question.options.length >= 2 && question.options.length <= (this.isColor(question) ? 6 : 4)
&& question.options.every(option => option.label.length <= 24);
}
chosenHint(question: AiQuestion): string | undefined {
const value = this.valueOf(question);
return question.options.find(option => option.label === value)?.hint;
colorValue(question: AiQuestion): string {
const picked = this.picked()[question.id];
return picked === null || aiIsFree(question) ? this.typed()[question.id] ?? '' : picked ?? this.defaultOf(question);
}
pick(question: AiQuestion, label: string): void {
this.picked.update(values => ({...values, [question.id]: label}));
setColor(question: AiQuestion, value: string): void {
if (question.options.some(option => option.label === value)) {
this.pick(question, value);
} else {
this.picked.update(values => ({...values, [question.id]: null}));
this.typed.update(values => ({...values, [question.id]: value}));
}
}
isColor(question: AiQuestion): boolean {
return !question.multiple && !question.secret
&& (!!question.color || (!!question.options?.length && question.options.every(option => !!aiColorOf(option.label))));
setTyped(question: AiQuestion, value: string): void {
this.pickOther(question);
this.typed.update(values => ({...values, [question.id]: value}));
}
pickColor(question: AiQuestion, trigger: HTMLElement): void {
openDay(question: AiQuestion, chip: HTMLElement): void {
if (this.disabled()) {
return;
}
if (this.popoverService.hasPopover(trigger)) {
this.popoverService.hidePopover(trigger);
if (this.popoverService.hasPopover(chip)) {
this.popoverService.hidePopover(chip);
return;
}
const current = aiColorOf(this.isOther(question) ? this.otherText(question) : this.valueOf(question)) ?? '#305680';
const today = new Date();
const chosen = this.days[question.id];
const popover = this.popoverService.displayPopover({
trigger,
trigger: chip,
renderer: this.renderer,
hostView: this.viewContainerRef,
componentType: ColorPickerPanelComponent,
componentType: AiDatePanelComponent,
preferredPlacement: ['bottomLeft', 'bottom', 'topLeft', 'top'],
context: {color: current, disableAlpha: true, colorCancelButton: true},
context: {
selected: chosen?.date ?? new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1),
time: chosen?.time ?? '9:00'
},
showCloseButton: false,
popoverContentStyle: {padding: '12px 4px 12px 12px'},
popoverContentStyle: {padding: '8px 12px 12px'},
isModal: true
});
this.dayOpen.set(question.id);
popover.tbHideStart.subscribe(() => this.dayOpen.set(null));
popover.tbComponentRef.instance.popover = popover;
popover.tbComponentRef.instance.colorSelected.subscribe((color: string) => {
popover.tbComponentRef.instance.applied.subscribe((day: AiPickedDay) => {
this.days[question.id] = day;
this.picked.update(values => ({...values, [question.id]: null}));
this.typed.update(values => ({...values, [question.id]:
`${day.date.toLocaleDateString(this.locale(), {weekday: 'long', day: 'numeric', month: 'short'})}, ${day.time}`}));
popover.hide();
const hex = tinycolor(color).toHexString();
if (!question.options?.length) {
this.typed.update(values => ({...values, [question.id]: hex}));
return;
}
const option = question.options.find(item => aiColorOf(item.label)?.toLowerCase() === hex);
if (option) {
this.pick(question, option.label);
} else {
this.picked.update(values => ({...values, [question.id]: null}));
this.typed.update(values => ({...values, [question.id]: hex}));
}
chip.focus();
});
popover.tbComponentRef.instance.colorCancelDialog.subscribe(() => popover.hide());
}
private locale(): string {
return aiLocale(this.translate.currentLang);
}
ready(question: AiQuestion): boolean {
if (question.multiple && !this.isFree(question)) {
return true;
}
if (aiKindOf(question) === 'color') {
return aiColorReady(question, this.colorValue(question));
}
if (this.isOther(question) && aiIsNumber(question)) {
return aiNumberReady(this.otherText(question), this.locale());
}
return this.isOther(question) ? !!this.otherText(question).trim() : !!this.valueOf(question);
}
sheet = computed(() => this.questions().length > 1 && this.questions().every(question =>
!question.multiple && !aiIsFree(question) && (aiKindOf(question) === 'chips' || aiKindOf(question) === 'color' || question.options.length <= 3)));
allReady = computed(() => this.questions().every(question => this.ready(question)));
finish(): void {
if (!this.disabled() && this.questions().every(question => this.ready(question))) {
this.done.emit(this.answers());
}
}
chosenHint(question: AiQuestion): string | undefined {
const value = this.valueOf(question);
return question.options.find(option => option.label === value)?.hint;
}
pick(question: AiQuestion, label: string): void {
this.picked.update(values => ({...values, [question.id]: label}));
}
pickOther(question: AiQuestion): void {
@ -274,6 +310,13 @@ export class AiQuestionComponent {
}
return values.length ? values.join(MULTI_SEPARATOR) : this.translate.instant('ai-assistant.question.none');
}
if (aiKindOf(question) === 'color') {
return aiColorAnswer(question, this.colorValue(question));
}
if (this.isOther(question) && aiIsNumber(question)) {
const value = this.otherText(question).trim();
return value && question.number?.unit ? `${value} ${question.number.unit}` : value;
}
return this.isOther(question) ? this.otherText(question).trim() : this.valueOf(question);
}

97
ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts

@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { AiQuestion, AiQuestionKind } from '@shared/models/solution-creator.models';
import { MINUS } from '@home/components/ai/ai-text';
export { aiLocale } from '@home/components/ai/ai-text';
const HEX_COLOR = /#[0-9a-f]{6}(?![0-9a-z])|#[0-9a-f]{3}(?![0-9a-z])/i;
export function aiColorOf(text: string | undefined): string | null {
return text?.match(HEX_COLOR)?.[0] ?? null;
}
export function aiIsFree(question: AiQuestion): boolean {
return !question.options?.length;
}
export function aiIsColor(question: AiQuestion): boolean {
return !question.multiple && !question.secret
&& (!!question.color || (!!question.options?.length && question.options.every(option => !!aiColorOf(option.label))));
}
export function aiIsNumber(question: AiQuestion): boolean {
return !!question.number && !question.multiple && !question.secret && !question.date && !aiIsColor(question);
}
export function aiIsChipRow(question: AiQuestion): boolean {
return !question.multiple && question.options.length >= 2 && question.options.length <= (aiIsColor(question) ? 6 : 4)
&& question.options.every(option => option.label.length <= 24);
}
export function aiQuestionKind(question: AiQuestion): AiQuestionKind {
const free = aiIsFree(question);
if (aiIsColor(question)) {
return 'color';
}
if (free) {
return question.secret ? 'secret' : aiIsNumber(question) ? 'number' : 'text';
}
if (question.multiple) {
return 'multi';
}
if (question.date) {
return 'date';
}
return aiIsChipRow(question) ? 'chips' : 'cards';
}
export function aiKindOf(question: AiQuestion): AiQuestionKind {
return question.kind ?? aiQuestionKind(question);
}
export function aiSayNumber(value: number): string {
return String(value).replace('-', MINUS);
}
export function aiReadNumber(text: string, locale?: string): number {
let normalized = String(text ?? '').trim().replace(/[\s  ]/g, '').replace(MINUS, '-');
const commaDecimal = (1.5).toLocaleString(locale).charAt(1) === ',';
const thousands = /^-?\d{1,3}(,\d{3})+(\.\d+)?$/.test(normalized);
if (normalized.includes(',') && !normalized.includes('.') && (commaDecimal || !thousands)) {
normalized = normalized.replace(',', '.');
} else {
normalized = normalized.replace(/,/g, '');
}
return /^[-+]?(\d+\.?\d*|\.\d+)$/.test(normalized) ? parseFloat(normalized) : NaN;
}
export function aiNumberReady(text: string, locale?: string): boolean {
return !isNaN(aiReadNumber(text, locale));
}
export function aiStepDecimals(step: number): number {
const text = String(step);
return text.includes('e-') ? +text.split('e-')[1] : (text.split('.')[1]?.length ?? 0);
}
export function aiHexOf(text: string | undefined): string | null {
const digits = (text ?? '').trim().replace(/^#/, '');
if (!/^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(digits)) {
return null;
}
const full = digits.length === 3 ? digits.split('').map(digit => digit + digit).join('') : digits;
return '#' + full.toUpperCase();
}
export function aiReadTime(text: string): string | null {
const match = String(text).trim().match(/^(\d{1,2})(?:[:.h]?(\d{2}))?$/);
if (!match) {
return null;
}
const hours = +match[1];
const minutes = match[2] ? +match[2] : 0;
return hours < 24 && minutes < 60 ? `${hours}:${String(minutes).padStart(2, '0')}` : null;
}

19
ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts

@ -56,10 +56,10 @@ export function aiWidgetThumb(): string {
} @else {
<span class="tb-rec-img" [innerHTML]="thumb()"></span>
}
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ kind().icon }}</mat-icon></span>
<span class="tb-rec-tile"><tb-icon aria-hidden="true">{{ kind().icon }}</tb-icon></span>
</span>
} @else {
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ kind().icon }}</mat-icon></span>
<span class="tb-rec-tile"><tb-icon aria-hidden="true">{{ kind().icon }}</tb-icon></span>
}
<div class="tb-rec-body">
@if (rec.url) {
@ -123,9 +123,9 @@ export function aiWidgetThumb(): string {
@if (note()) {
<p class="tb-rec-note">{{ note() }}</p>
}
@if (facts().length) {
@if (shownFacts().length) {
<dl class="tb-ai-facts tb-rec-facts">
@for (fact of facts(); track $index) {
@for (fact of shownFacts(); track $index) {
<dt>{{ fact.label }}</dt>
<dd>@for (part of parts(fact); track $index) {@if (part.code) {<code>{{ part.text }}</code>} @else {{{ part.text }}}}</dd>
}
@ -163,7 +163,7 @@ export class AiRecordCardComponent {
installing = signal(false);
kind = computed(() => aiEntityKind(this.view().entityType, this.view().alarmRule));
kind = computed(() => aiEntityKind(this.view().entityType, this.view().alarmRule, this.view().groupType));
picture = computed(() => {
const view = this.view();
@ -178,7 +178,14 @@ export class AiRecordCardComponent {
return primary === 'open' && this.view().url ? 'open' : null;
});
hasFoot = computed(() => !!this.note() || this.facts().length > 0 || this.actions().length > 0);
shownFacts = computed(() => {
const view = this.view();
const said = [view.badge, this.meta() || view.meta].filter(Boolean).map(text => text.toLowerCase());
const sameWords = (value: string) => said.some(text => text === value || text.split(' · ').includes(value));
return this.facts().filter(fact => !sameWords(fact.value.trim().toLowerCase()));
});
hasFoot = computed(() => !!this.note() || this.shownFacts().length > 0 || this.actions().length > 0);
thumb = computed(() => this.sanitizer.bypassSecurityTrustHtml(this.view().entityType === EntityType.WIDGET_TYPE
? aiWidgetThumb() : aiDashboardThumb(this.view().widgets ?? 4)));

11
ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { aiLocale } from '@home/components/ai/ai-text';
import { TB_IMAGE_PREFIX } from '@shared/models/resource.models';
import { ReportTemplateService } from '@core/http/report-template.service';
import { widgetType, widgetTypesData } from '@shared/models/widget.models';
@ -27,6 +28,7 @@ import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-i
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { DeviceInfo } from '@shared/models/device.models';
import { getEntityDetailsPageURL } from '@core/utils';
import { aiDateText } from '@home/components/ai/ai-action-detail.models';
import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils';
import { HttpClient } from '@angular/common/http';
import { AiRecordRef, AiRecordState, AiRecordView } from '@home/components/ai/ai-record.models';
@ -167,7 +169,7 @@ export class AiRecordLoaderService {
const base = group.type ? baseDetailsPageByEntityType.get(group.type) : undefined;
const typeKey = group.type ? entityTypeTranslations.get(group.type)?.type : undefined;
return {
key, entityType, alarmRule: false, name: group.name,
key, entityType, alarmRule: false, name: group.name, groupType: group.type,
url: base ? `${base.replace(/\/all$/, '/groups')}/${entity.id}` : undefined,
meta: typeKey ? this.translate.instant('ai-assistant.record.group-of', {type: this.translate.instant(typeKey)})
: this.typeLabel(entityType)
@ -319,13 +321,10 @@ export class AiRecordLoaderService {
}
private locale(): string | undefined {
return this.translate.currentLang?.replace('_', '-') || undefined;
return aiLocale(this.translate.currentLang);
}
private time(ts: number): string {
const date = new Date(ts);
const today = new Date().toDateString() === date.toDateString();
return new Intl.DateTimeFormat(this.locale(), today ? {hour: '2-digit', minute: '2-digit'}
: {day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit'}).format(date);
return aiDateText(new Date(ts), this.locale());
}
}

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

@ -9,7 +9,7 @@ export { AiRecordState } from '@home/components/ai/ai-record.models';
@Component({
selector: 'tb-ai-record',
template: `
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ kind().icon }}</mat-icon></span>
<span class="tb-rec-tile"><tb-icon aria-hidden="true">{{ kind().icon }}</tb-icon></span>
@if (url()) {
<a class="tb-rec-name" [routerLink]="url()" [matTooltip]="name()" matTooltipPosition="above" [matTooltipShowDelay]="600">{{ name() }}</a>
} @else {
@ -50,6 +50,7 @@ export class AiRecordComponent {
entityType = input.required<string>();
alarmRule = input(false);
groupType = input<string | undefined>(undefined);
name = input.required<string>();
@ -65,5 +66,5 @@ export class AiRecordComponent {
hub = input<AiHubMeta>();
kind = computed(() => aiEntityKind(this.entityType(), this.alarmRule()));
kind = computed(() => aiEntityKind(this.entityType(), this.alarmRule(), this.groupType()));
}

5
ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { aiTrueMinus } from '@home/components/ai/ai-text';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
export const SHOW_RECORDS_TOOL = 'show_records';
@ -34,6 +35,7 @@ export interface AiRecordView {
key: string;
entityType: string;
alarmRule: boolean;
groupType?: string;
name: string;
meta: string;
badge?: string;
@ -99,5 +101,6 @@ export function aiShownRecordsOf(args: unknown): AiShownRecords | null {
export function aiFactParts(value: string): Array<{text: string; code: boolean}> {
return value.split(/(`[^`]+`)/).filter(part => part.length)
.map(part => part.length > 2 && part.startsWith('`') && part.endsWith('`') ? {text: part.slice(1, -1), code: true} : {text: part, code: false});
.map(part => part.length > 2 && part.startsWith('`') && part.endsWith('`') ? {text: part.slice(1, -1), code: true}
: {text: aiTrueMinus(part), code: false});
}

6
ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts

@ -29,14 +29,14 @@ const WAIT_RECHECKS = 90;
} @else if (views().length > 1) {
<div class="tb-list" [class.open]="listOpen()" [attr.data-pal]="listKind()?.palette ?? null">
<button type="button" class="tb-list-head" [attr.aria-expanded]="listOpen()" (click)="toggleList()">
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ listKind()?.icon ?? 'interests' }}</mat-icon></span>
<span class="tb-rec-tile"><tb-icon aria-hidden="true">{{ listKind()?.icon ?? 'interests' }}</tb-icon></span>
<span class="tb-list-label">{{ listLabel() }}</span>
<mat-icon class="tb-list-chev" aria-hidden="true">expand_more</mat-icon>
</button>
@if (listOpen()) {
<div class="tb-list-body" role="list" [attr.aria-label]="listLabel()">
@for (rec of shownViews(); track rec.key) {
<tb-ai-record role="listitem" [entityType]="rec.entityType" [alarmRule]="rec.alarmRule" [name]="rec.name"
<tb-ai-record role="listitem" [entityType]="rec.entityType" [alarmRule]="rec.alarmRule" [groupType]="rec.groupType" [name]="rec.name"
[meta]="sameKind() ? lineMeta(rec) : rec.meta" [badge]="rec.badge" [url]="rec.url" [state]="rec.state" [alarm]="rec.alarm"
[hub]="rec.hub"></tb-ai-record>
}
@ -101,7 +101,7 @@ export class AiRecordsComponent {
sameKind = computed(() => new Set(this.views().map(view => this.kindKey(view))).size === 1);
listKind = computed(() => this.sameKind() && this.views().length ? aiEntityKind(this.views()[0].entityType, this.views()[0].alarmRule) : null);
listKind = computed(() => this.sameKind() && this.views().length ? aiEntityKind(this.views()[0].entityType, this.views()[0].alarmRule, this.views()[0].groupType) : null);
listLabel = computed(() => {
const views = this.views();

158
ui-ngx/src/app/modules/home/components/ai/ai-references.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { SEVERITY_MARK } from '@home/components/ai/ai-text';
import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models';
import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models';
import { aiEntityKind } from '@home/components/ai/ai-action.models';
@ -34,6 +35,10 @@ export function decorateReferences(root: HTMLElement, references: AiReference[]
nodes.forEach(node => replaceIn(node, pattern, linkable));
}
const PLAIN_WORD = /^\p{Ll}+$/u;
const QUOTE_OPEN = /["'“‘«]$/u;
const QUOTE_CLOSE = /^["'”’»]/u;
function replaceIn(node: Text, pattern: RegExp, references: AiReference[]): void {
let rest = node.textContent ?? '';
let match = pattern.exec(rest);
@ -46,8 +51,12 @@ function replaceIn(node: Text, pattern: RegExp, references: AiReference[]): void
fragment.append(rest.slice(0, match.index));
}
const reference = references.find(item => item.name === match[1]);
fragment.append(reference ? chip(reference) : match[1]);
rest = rest.slice(match.index + match[1].length);
const before = rest.slice(0, match.index);
const after = rest.slice(match.index + match[1].length);
const standsAsName = !reference || !PLAIN_WORD.test(reference.name)
|| (node.textContent ?? '').trim() === reference.name || (QUOTE_OPEN.test(before) && QUOTE_CLOSE.test(after));
fragment.append(reference && standsAsName ? chip(reference) : match[1]);
rest = after;
match = pattern.exec(rest);
}
if (rest) {
@ -56,6 +65,44 @@ function replaceIn(node: Text, pattern: RegExp, references: AiReference[]): void
node.replaceWith(fragment);
}
const SVG_ICONS = new Map<string, Promise<SVGElement | null>>();
function svgIcon(name: string): Promise<SVGElement | null> {
let icon = SVG_ICONS.get(name);
if (!icon) {
const [namespace, file] = name.split(':');
icon = namespace !== 'mdi' || !/^[a-z0-9-]+$/.test(file) ? Promise.resolve(null)
: fetch(`./assets/mdi/${file}.svg`).then(response => response.ok ? response.text() : '').then(text => {
const svg = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;
return svg?.nodeName === 'svg' ? svg as unknown as SVGElement : null;
}).catch(() => null);
SVG_ICONS.set(name, icon);
}
return icon;
}
function aiIconElement(name: string, className: string): HTMLElement {
const icon = document.createElement('span');
icon.setAttribute('aria-hidden', 'true');
if (!name.includes(':')) {
icon.className = 'mat-icon notranslate material-icons mat-ligature-font ' + className;
icon.textContent = name;
return icon;
}
icon.className = 'mat-icon notranslate ' + className;
svgIcon(name).then(svg => {
if (svg) {
const copy = svg.cloneNode(true) as SVGElement;
copy.setAttribute('width', '100%');
copy.setAttribute('height', '100%');
copy.setAttribute('fill', 'currentColor');
copy.setAttribute('focusable', 'false');
icon.replaceChildren(copy);
}
});
return icon;
}
const REFERENCE_PAGES: Record<string, string> = {
ALARM_RULE: '/alarms/alarm-rules',
EDGE_RULE_CHAIN: '/edgeManagement/templates/ruleChains'
@ -66,11 +113,7 @@ function chip(reference: AiReference): HTMLElement {
const code = document.createElement('code');
code.className = 'k-ent';
code.dataset.pal = kind.palette;
const icon = document.createElement('span');
icon.className = 'mat-icon notranslate material-icons mat-ligature-font k-ent-ic';
icon.setAttribute('aria-hidden', 'true');
icon.textContent = kind.icon;
code.append(icon, reference.name);
code.append(aiIconElement(kind.icon, 'k-ent-ic'), reference.name);
const base = REFERENCE_PAGES[reference.entityType] ?? baseDetailsPageByEntityType.get(reference.entityType as EntityType);
if (!base || !reference.id) {
return code;
@ -145,43 +188,90 @@ function lastText(root: Node): Text | null {
return null;
}
const SEVERITY_SKIP = 'code, pre, a, table, .k-sev, .tb-chiplink';
const SEVERITY_SKIP = 'code, pre, a, table, .k-sev, .tb-chiplink, .tb-rec, tb-ai-record, tb-ai-records';
const MARK_SKIP = 'code, pre, a, .k-sev, .tb-chiplink';
export function decorateSeverities(root: HTMLElement, severities: string[] | undefined, label: (severity: string) => string): void {
if (!severities?.length) {
return;
}
const pattern = new RegExp(`(?<![\\p{L}\\p{N}_])(${severities.map(severity => severity.toLowerCase()).join('|')})(?![\\p{L}\\p{N}_])`, 'iu');
function aiHasSeverityMarks(text: string | undefined): boolean {
return !!text && SEVERITY_MARK.test(text);
}
function severityChip(severity: string, label: (severity: string) => string): HTMLElement {
const chip = document.createElement('span');
chip.className = 'k-sev ' + severity.toLowerCase();
chip.append(aiSevMarkElement(severity), label(severity));
return chip;
}
function textNodes(root: HTMLElement, skip: string): Text[] {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode: node => node.parentElement?.closest(SEVERITY_SKIP) || !node.textContent?.trim() ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT
acceptNode: node => node.parentElement?.closest(skip) || !node.textContent?.trim() ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT
});
const nodes: Text[] = [];
while (walker.nextNode()) {
nodes.push(walker.currentNode as Text);
}
nodes.forEach(node => {
let rest = node.textContent ?? '';
let match = pattern.exec(rest);
if (!match) {
return;
return nodes;
}
function replaceMatches(node: Text, pattern: RegExp, chip: (match: RegExpExecArray) => Node | null): void {
let rest = node.textContent ?? '';
let match = pattern.exec(rest);
if (!match) {
return;
}
const fragment = document.createDocumentFragment();
while (match) {
if (match.index > 0) {
fragment.append(rest.slice(0, match.index));
}
const fragment = document.createDocumentFragment();
while (match) {
if (match.index > 0) {
fragment.append(rest.slice(0, match.index));
}
const severity = match[1].toUpperCase();
const chip = document.createElement('span');
chip.className = 'k-sev ' + severity.toLowerCase();
chip.append(aiSevMarkElement(severity), label(severity));
fragment.append(chip);
rest = rest.slice(match.index + match[1].length);
match = pattern.exec(rest);
fragment.append(chip(match) ?? match[0]);
rest = rest.slice(match.index + match[0].length);
match = pattern.exec(rest);
}
if (rest) {
fragment.append(rest);
}
node.replaceWith(fragment);
}
export function decorateSeverities(root: HTMLElement, severities: string[] | undefined, label: (severity: string) => string): void {
if (aiHasSeverityMarks(root.textContent ?? '')) {
textNodes(root, MARK_SKIP).forEach(node => replaceMatches(node, SEVERITY_MARK, match => severityChip(match[1], label)));
decorateAlarmTables(root);
return;
}
if (!severities?.length) {
return;
}
const pattern = new RegExp(`(?<![\\p{L}\\p{N}_])(${severities.map(severity => severity.toLowerCase()).join('|')})(?![\\p{L}\\p{N}_])`, 'iu');
const chipped = new Set<string>();
textNodes(root, SEVERITY_SKIP).forEach(node => replaceMatches(node, pattern, match => {
const severity = match[1].toUpperCase();
if (chipped.has(severity)) {
return null;
}
if (rest) {
fragment.append(rest);
chipped.add(severity);
return severityChip(severity, label);
}));
}
function decorateAlarmTables(root: HTMLElement): void {
root.querySelectorAll('table').forEach(table => {
const rows = Array.from(table.querySelectorAll('tbody tr'));
const columns = table.querySelectorAll('thead th').length;
if (columns < 4 || !rows.length || !rows.every(row => row.children[2]?.querySelector('.k-sev'))) {
return;
}
node.replaceWith(fragment);
table.classList.add('k-alarms');
rows.forEach(row => {
const [alarm, device] = [row.children[0] as HTMLElement, row.children[1] as HTMLElement];
if (!alarm.querySelector('.k-cell-meta') && device?.textContent?.trim()) {
const meta = document.createElement('span');
meta.className = 'k-cell-meta';
meta.append(...Array.from(device.childNodes).map(node => node.cloneNode(true)));
alarm.append(meta);
}
});
});
}

6
ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts

@ -21,14 +21,14 @@ const LEAD_TYPES = new Set<string>([EntityType.DASHBOARD, EntityType.WIDGET_TYPE
@if (rest().length > 1) {
<div class="tb-list" [class.open]="listOpen()" [attr.data-pal]="listKind()?.palette ?? null">
<button type="button" class="tb-list-head" [attr.aria-expanded]="listOpen()" (click)="toggleList()">
<span class="tb-rec-tile"><mat-icon aria-hidden="true">{{ listKind()?.icon ?? 'interests' }}</mat-icon></span>
<span class="tb-rec-tile"><tb-icon aria-hidden="true">{{ listKind()?.icon ?? 'interests' }}</tb-icon></span>
<span class="tb-list-label">{{ listLabel() }}</span>
<mat-icon class="tb-list-chev" aria-hidden="true">expand_more</mat-icon>
</button>
@if (listOpen()) {
<div class="tb-list-body" role="list" [attr.aria-label]="'ai-assistant.summary.made' | translate">
@for (row of shownRows(); track row.key) {
<tb-ai-record role="listitem" [entityType]="row.entityType" [alarmRule]="row.alarmRule" [name]="row.name"
<tb-ai-record role="listitem" [entityType]="row.entityType" [alarmRule]="row.alarmRule" [groupType]="row.groupType" [name]="row.name"
[meta]="row.meta" [badge]="row.badge" [url]="row.url" [state]="row.state" [alarm]="row.alarm"></tb-ai-record>
}
@if (rest().length > LIST_SHOWN) {
@ -43,7 +43,7 @@ const LEAD_TYPES = new Set<string>([EntityType.DASHBOARD, EntityType.WIDGET_TYPE
} @else if (rest().length) {
<div class="k-recs" role="list" [attr.aria-label]="'ai-assistant.summary.made' | translate">
@for (row of rest(); track row.key) {
<tb-ai-record role="listitem" [entityType]="row.entityType" [alarmRule]="row.alarmRule" [name]="row.name"
<tb-ai-record role="listitem" [entityType]="row.entityType" [alarmRule]="row.alarmRule" [groupType]="row.groupType" [name]="row.name"
[meta]="row.meta" [badge]="row.badge" [url]="row.url" [state]="row.state" [alarm]="row.alarm"></tb-ai-record>
}
</div>

19
ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html

@ -0,0 +1,19 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="k-secret">
<span class="k-secret-f">
<input #secretInput class="k-opt-input" [type]="shown() ? 'text' : 'password'" autocomplete="new-password" spellcheck="false"
[disabled]="disabled()" [value]="value()" [placeholder]="question().other?.placeholder || ('ai-assistant.question.type-secret' | translate)"
[attr.aria-label]="question().question" (input)="value.set(secretInput.value)" (keydown.enter)="enter.emit($event)">
<button mat-icon-button type="button" class="k-show" [disabled]="disabled()"
[attr.aria-label]="(shown() ? 'ai-assistant.question.hide' : 'ai-assistant.question.show') | translate"
[matTooltip]="(shown() ? 'ai-assistant.question.hide' : 'ai-assistant.question.show') | translate"
(click)="toggle(secretInput)">
<mat-icon>{{ shown() ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
</span>
</div>

26
ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts

@ -0,0 +1,26 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, input, model, output, signal } from '@angular/core';
import { AiQuestion } from '@shared/models/solution-creator.models';
@Component({
selector: 'tb-ai-secret-field',
templateUrl: './ai-secret-field.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false
})
export class AiSecretFieldComponent {
question = input.required<AiQuestion>();
value = model('');
disabled = input(false);
enter = output<Event>();
readonly shown = signal(false);
readonly ready = computed(() => !!this.value());
toggle(field: HTMLInputElement): void {
this.shown.update(shown => !shown);
field.focus();
}
}

4
ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts

@ -57,10 +57,10 @@ const LIST_PAGES: Record<string, {entityType: string; url: string}> = {
<span>{{ 'ai-assistant.started-from' | translate }}</span>
@if (current.url) {
<a class="tb-chiplink" [routerLink]="current.url" [matTooltip]="'ai-assistant.open-page' | translate: {name: current.name}" matTooltipPosition="above">
<code class="k-ent" [attr.data-pal]="kind().palette"><mat-icon class="k-ent-ic" aria-hidden="true">{{ kind().icon }}</mat-icon>{{ current.name }}<mat-icon class="tb-chip-go" aria-hidden="true">chevron_right</mat-icon></code>
<code class="k-ent" [attr.data-pal]="kind().palette"><tb-icon class="k-ent-ic" aria-hidden="true">{{ kind().icon }}</tb-icon>{{ current.name }}<mat-icon class="tb-chip-go" aria-hidden="true">chevron_right</mat-icon></code>
</a>
} @else {
<code class="k-ent" [attr.data-pal]="kind().palette"><mat-icon class="k-ent-ic" aria-hidden="true">{{ kind().icon }}</mat-icon>{{ current.name }}</code>
<code class="k-ent" [attr.data-pal]="kind().palette"><tb-icon class="k-ent-ic" aria-hidden="true">{{ kind().icon }}</tb-icon>{{ current.name }}</code>
}
}
`,

41
ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts

@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { AiPlanMark } from '@home/components/ai/ai-action.models';
export type AiStepMark = AiPlanMark | 'listen' | 'run' | 'stopped';
@Component({
selector: 'tb-ai-step-mark',
template: `
@switch (mark()) {
@case ('stopped') {
<mat-icon class="tb-mat-18 off" aria-hidden="true">stop_circle</mat-icon>
}
@case ('listen') {
<tb-ai-spin kind="listen" aria-hidden="true"></tb-ai-spin>
}
@case ('run') {
<tb-ai-spin kind="think" aria-hidden="true"></tb-ai-spin>
}
@default {
<span [class]="'k-pmark ' + mark()" aria-hidden="true">
@if (mark() === 'done') {
<mat-icon>check</mat-icon>
} @else if (mark() === 'off') {
<mat-icon>remove</mat-icon>
}
</span>
}
}
`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
host: {
'class': 'tb-ai-step-mark'
}
})
export class AiStepMarkComponent {
mark = input.required<AiStepMark>();
}

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

@ -0,0 +1,18 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
export const MINUS = '\u2212';
export const SEVERITY_MARK = /\{(CRITICAL|MAJOR|MINOR|WARNING|INDETERMINATE)\}/;
export function aiTrueMinus(text: string): string {
return text.replace(/(^|[\s(=:])-(?=\d)/g, '$1' + MINUS);
}
export function aiLocale(lang: string | undefined): string | undefined {
return lang ? lang.replace('_', '-') : undefined;
}
export function aiClockText(time: number | undefined, lang: string | undefined): string {
return new Date(time ?? Date.now()).toLocaleTimeString(aiLocale(lang), {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'});
}

7
ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss

@ -19,7 +19,7 @@
min-width: 0;
font-family: var(--tb-font);
font-size: var(--chat-line);
background: linear-gradient(90deg, var(--tb-ink-54) 0%, var(--tb-ink) 42%, var(--tb-ink-54) 58%, var(--tb-ink-54) 100%);
background: linear-gradient(90deg, var(--tb-ink-76) 0%, var(--tb-ink) 42%, var(--tb-ink-76) 58%, var(--tb-ink-76) 100%);
background-size: 260% 100%;
-webkit-background-clip: text;
background-clip: text;
@ -34,8 +34,7 @@
}
.clock {
margin-left: auto;
padding-left: 12px;
flex: none;
white-space: nowrap;
font-family: var(--tb-mono);
font-variant-numeric: tabular-nums;
@ -68,6 +67,6 @@
.say {
animation: none;
background: none;
color: var(--tb-ink-76);
color: var(--tb-ink);
}
}

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

@ -23,6 +23,11 @@ import { AiRecordsComponent } from '@home/components/ai/ai-records.component';
import { AiCardActionsComponent } from '@home/components/ai/ai-card-actions.component';
import { AiDisclosureComponent } from '@home/components/ai/ai-disclosure.component';
import { AiQuestionComponent } from '@home/components/ai/ai-question.component';
import { AiNumberFieldComponent } from '@home/components/ai/ai-number-field.component';
import { AiSecretFieldComponent } from '@home/components/ai/ai-secret-field.component';
import { AiColorFieldComponent } from '@home/components/ai/ai-color-field.component';
import { AiDatePanelComponent } from '@home/components/ai/ai-date-panel.component';
import { AiStepMarkComponent } from '@home/components/ai/ai-step-mark.component';
import { AiPlanComponent } from '@home/components/ai/ai-plan.component';
import { AiHandOverComponent } from '@home/components/ai/ai-hand-over.component';
import { AiArtifactPaneComponent } from '@home/components/ai/ai-artifact-pane.component';
@ -47,6 +52,11 @@ import { AiFileBodyComponent } from '@home/components/ai/ai-file-body.component'
AiCardActionsComponent,
AiDisclosureComponent,
AiQuestionComponent,
AiNumberFieldComponent,
AiSecretFieldComponent,
AiColorFieldComponent,
AiDatePanelComponent,
AiStepMarkComponent,
AiPlanComponent,
AiHandOverComponent,
AiArtifactPaneComponent,

6
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html

@ -47,11 +47,11 @@
@if (link(row.type, row); as url) {
<a class="sol-name sol-ent" [attr.data-pal]="row.palette" [routerLink]="url" matTooltipPosition="above" matTooltipShowDelay="600"
[matTooltip]="'solution-creator.pane.open-list' | translate: {name: row.primary.additionalData?.name}">
<mat-icon aria-hidden="true">{{ row.icon }}</mat-icon><b>{{ row.primary.additionalData?.name }}</b>
<tb-icon aria-hidden="true">{{ row.icon }}</tb-icon><b>{{ row.primary.additionalData?.name }}</b>
</a>
} @else {
<span class="sol-name" [attr.data-pal]="row.palette">
<mat-icon aria-hidden="true">{{ row.icon }}</mat-icon><b>{{ row.primary.additionalData?.name }}</b>
<tb-icon aria-hidden="true">{{ row.icon }}</tb-icon><b>{{ row.primary.additionalData?.name }}</b>
</span>
}
</td>
@ -107,7 +107,7 @@
@default {
<td>
@if (row.details.chip; as chip) {
<code class="k-ent" [attr.data-pal]="chip.palette"><mat-icon class="k-ent-ic" aria-hidden="true">{{ chip.icon }}</mat-icon>{{ chip.label }}</code>
<code class="k-ent" [attr.data-pal]="chip.palette"><tb-icon class="k-ent-ic" aria-hidden="true">{{ chip.icon }}</tb-icon>{{ chip.label }}</code>
}
</td>
}

4
ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html

@ -36,7 +36,7 @@
<tr class="clickable" [class.on]="open() === key" (click)="toggle(key)" [attr.aria-expanded]="open() === key">
<td class="wrap">
<span class="sol-name" [attr.data-pal]="kind(profile).palette">
<mat-icon aria-hidden="true">{{ kind(profile).icon }}</mat-icon><b>{{ profile.name }}</b>
<tb-icon aria-hidden="true">{{ kind(profile).icon }}</tb-icon>@if (profile.name?.trim()) {<b>{{ profile.name }}</b>} @else {<b class="sol-unnamed">{{ typeLabel(profile) }} {{ $index + 1 }}</b>}
</span>
</td>
<td class="secondary nowrap">{{ typeLabel(profile) }}</td>
@ -105,7 +105,7 @@
@if (schemaEntity(); as entity) {
<div class="sol-schema-detail">
<div class="sol-name" [attr.data-pal]="kind(entity).palette">
<mat-icon aria-hidden="true">{{ kind(entity).icon }}</mat-icon><b>{{ entity.name }}</b>
<tb-icon aria-hidden="true">{{ kind(entity).icon }}</tb-icon><b>{{ entity.name }}</b>
</div>
<ng-container *ngTemplateOutlet="profileDetail; context: {$implicit: entity}"></ng-container>
</div>

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

@ -232,8 +232,7 @@
<button type="button" class="art-tool icon-only art-copy" [class.copied]="jsonCopied()" (click)="copyJson()"
[matTooltip]="(jsonCopied() ? '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>
<mat-icon class="tb-mat-18" aria-hidden="true">{{ jsonCopied() ? 'check' : 'content_copy' }}</mat-icon>
</button>
<span class="tb-ai-sr-only" aria-live="polite">{{ jsonCopied() ? ('ai-assistant.copied' | translate) : '' }}</span>
<button type="button" class="art-tool icon-only" (click)="downloadJson()"

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

@ -666,37 +666,38 @@ tb-ai-chat-title:has(.ai-chat-status) + .sol-head-actions {
.sol-feats {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 14px 24px;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px 32px;
align-items: start;
@media (max-width: 860px) {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (max-width: 480px) {
grid-template-columns: minmax(0, 1fr);
}
}
.sol-feat {
display: flex;
gap: 10px;
display: grid;
grid-template-columns: auto minmax(0, 1fr);
column-gap: 12px;
align-items: start;
min-width: 0;
> .mat-icon {
flex: none;
box-sizing: content-box;
font-size: 20px;
width: 20px;
height: 20px;
line-height: 16px;
margin-top: 1px;
color: var(--k-grey);
line-height: 20px;
margin-top: -6px;
padding: 6px;
border-radius: 8px;
background: color-mix(in oklab, var(--tb-ink) 5%, transparent);
color: var(--tb-ink-76);
}
> div {
display: grid;
gap: 2px;
gap: 4px;
align-content: start;
min-width: 0;
}

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

@ -437,6 +437,9 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe
onChip(id: string): void {
switch (id) {
case 'resume':
this.resume();
break;
case 'view-as':
this.viewAsMainUser();
break;
@ -896,14 +899,19 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe
this.notice.set({kind, icon, text: this.translate.instant('ai-assistant.notice.' + key)});
}
private wasStopped(err: any, again: () => void): boolean {
private wasStopped(err: any, again: () => void, phase: 'chat' | 'build' | 'install' = 'chat'): boolean {
if (!this.stopping() || err?.status !== 409) {
return false;
}
this.stopping.set(false);
this.stoppedAction = again;
this.messageSteps = [...this.messageSteps, this.solutionStep()];
this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('solution-creator.stopped'), status: 'STOPPED', time: Date.now()}]);
const chips = phase === 'chat' ? undefined : [
{id: 'resume', icon: 'play_arrow', label: this.translate.instant(phase === 'install' ? 'solution-creator.create-solution' : 'ai-assistant.resume')},
{id: 'edit', icon: 'edit', label: this.translate.instant('solution-creator.change-design')}
];
this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('solution-creator.stopped' + (phase === 'chat' ? '' : '-' + phase)),
status: 'STOPPED', time: Date.now(), ...(chips ? {chips} : {})}]);
setTimeout(() => this.scrollLogToEnd(true));
return true;
}
@ -1016,7 +1024,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe
if (err?.status !== 0 && !SolutionChatComponent.unloading) {
SolutionChatComponent.markMaking(this.solutionId, false);
}
if (!this.wasStopped(err, () => this.nextStep()) && !this.noticeFor(err)) {
if (!this.wasStopped(err, () => this.nextStep(), 'build') && !this.noticeFor(err)) {
this.reportFailure(err);
}
}
@ -1058,7 +1066,7 @@ export class SolutionChatComponent extends PageComponent implements OnInit, OnDe
if (err?.status !== 0 && !SolutionChatComponent.unloading) {
SolutionChatComponent.markMaking(this.solutionId, false);
}
if (!this.wasStopped(err, () => this.installSolution()) && !this.noticeFor(err)) {
if (!this.wasStopped(err, () => this.installSolution(), 'install') && !this.noticeFor(err)) {
this.reportFailure(err, 'install');
}
}

12
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts

@ -436,7 +436,14 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
const dashboards = affected.filter(entityId => entityId.entityType === EntityType.DASHBOARD);
if (dashboards.length) {
if (dashboards.some(dashboard => dashboard.id === this.currentDashboardId)) {
this.reloadDashboard();
if (this.isEdit && !(this.editedWhileEmpty && this.dashboardUtils.isEmptyDashboard(this.dashboard))) {
this.panelService.keepEdits('dashboard', () => {
this.setEditMode(false, true);
this.reloadDashboard();
});
} else {
this.reloadDashboard();
}
} else {
this.currentDashboardIdChanged(dashboards[0].id);
}
@ -1326,6 +1333,9 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
}
private setEditMode(isEdit: boolean, revert: boolean) {
if (!isEdit) {
this.panelService.clearKeptEdits('dashboard');
}
this.isEdit = isEdit;
this.editedWhileEmpty = false;
if (this.isEdit) {

9
ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts

@ -235,7 +235,14 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa
affectedEntities.some(entityId => entityId.entityType === (entitiesTableConfig.aiReloadEntityType ?? entitiesTableConfig.entityType))),
takeUntil(this.destroy$)
).subscribe(() => {
this.updateData(false);
if (this.isDetailsOpen && this.entityDetailsPanel?.isEdit) {
this.panelService.keepEdits('entity', () => {
this.entityDetailsPanel.isEdit = false;
this.updateData(false, true);
});
} else {
this.updateData(false);
}
});
}

7
ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service';
import {
AfterViewInit,
ChangeDetectionStrategy,
@ -7,6 +8,7 @@ import {
Component,
ComponentRef,
EventEmitter,
inject,
Injector,
Input,
OnDestroy,
@ -59,6 +61,8 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV
entitiesTableConfigValue: EntityTableConfig<BaseData<HasId>>;
isEditValue = false;
private aiPanelService = inject(AiAssistantPanelService);
selectedTab = 0;
entityTypes = EntityType;
@ -115,6 +119,9 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV
}
set isEdit(val: boolean) {
if (this.isEditValue && !val) {
this.aiPanelService.clearKeptEdits('entity');
}
this.isEditValue = val;
if (this.entityComponent) {
this.entityComponent.isEdit = val;

2
ui-ngx/src/app/modules/home/home.component.scss

@ -179,7 +179,7 @@
.tb-site-content {
position: relative;
overflow: hidden;
overflow: clip;
}
.tb-site-main.openAiAssistant {

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

@ -50,7 +50,7 @@
<kbd class="ai-find-key" aria-hidden="true">{{ shortcutModifier }}K</kbd>
}
</label>
<nav class="ai-list" [attr.aria-label]="'ai-assistant.chats' | translate">
<nav #chatList class="ai-list" [attr.aria-label]="'ai-assistant.chats' | translate" (scroll)="listEdges()">
@for (group of groups(); track group.label) {
<section class="ai-sect">
<h3>{{ group.label }}</h3>

13
ui-ngx/src/app/modules/home/pages/ai-assistant/ai-assistant.component.scss

@ -212,7 +212,7 @@
&:focus-within {
background: var(--tb-surface);
box-shadow: inset 0 0 0 1px var(--k-stroke-hover);
box-shadow: inset 0 0 0 1px var(--ai-focus);
.mat-icon {
color: var(--tb-ink);
@ -275,11 +275,22 @@
}
.ai-list {
--fade-t: 0px;
--fade-b: 0px;
flex: 1;
min-height: 0;
overflow-y: auto;
margin-top: 4px;
padding-right: 4px;
mask-image: linear-gradient(to bottom, transparent 0, #000 var(--fade-t), #000 calc(100% - var(--fade-b)), transparent 100%);
&.scrolled {
--fade-t: 24px;
}
&.more {
--fade-b: 24px;
}
}
.ai-sect {

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

@ -72,6 +72,7 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
@ViewChild(AiChatComponent) chat: AiChatComponent;
@ViewChild(SolutionChatComponent) solutionChat: SolutionChatComponent;
@ViewChild('searchInput') searchInput: ElementRef<HTMLInputElement>;
@ViewChild('chatList') chatList: ElementRef<HTMLElement>;
readonly toastTarget = 'aiAssistantPage';
@ -211,6 +212,20 @@ export class AiAssistantComponent implements OnInit, OnDestroy {
}
});
private listEdgesEffect = effect(() => {
this.groups();
setTimeout(() => this.listEdges());
});
listEdges(): void {
const list = this.chatList?.nativeElement;
if (!list) {
return;
}
list.classList.toggle('scrolled', list.scrollTop > 1);
list.classList.toggle('more', list.scrollTop + list.clientHeight < list.scrollHeight - 1);
}
private leaveGetStarted = effect(() => {
if (this.chatId() || this.solutionId()) {
untracked(() => {

18
ui-ngx/src/app/modules/login/pages/login/login.component.ts

@ -1,7 +1,8 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, HostBinding, OnInit } from '@angular/core';
import { Component, DestroyRef, HostBinding, inject, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { AuthService } from '@core/auth/auth.service';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';
@ -15,7 +16,8 @@ import { SelfRegistrationService } from '@core/http/self-register.service';
import { OAuth2ClientLoginInfo } from '@shared/models/oauth2.models';
import { validateEmail } from '@app/core/utils';
import { PageComponent } from '@shared/components/page.component';
import { finalize } from 'rxjs/operators';
import { filter } from 'rxjs/operators';
import { selectAuth } from '@core/auth/auth.selectors';
@Component({
selector: 'tb-login',
@ -45,17 +47,23 @@ export class LoginComponent extends PageComponent implements OnInit {
super();
}
private destroyRef = inject(DestroyRef);
ngOnInit() {
this.oauth2Clients = this.authService.oauth2Clients;
this.store.select(selectAuth).pipe(
filter(authState => this.isLoading && !!authState?.isUserLoaded && !authState.isAuthenticated),
takeUntilDestroyed(this.destroyRef)
).subscribe(() => this.isLoading = false);
}
login(): void {
if (this.loginFormGroup.valid) {
this.isLoading = true;
this.authService.login(this.loginFormGroup.value).pipe(
finalize(() => {this.isLoading = false;})
).subscribe({
this.authService.login(this.loginFormGroup.value).subscribe({
error: (error: HttpErrorResponse) => {
this.isLoading = false;
if (error && error.error && error.error.errorCode) {
if (error.error.errorCode === Constants.serverErrorCode.credentialsExpired) {
this.router.navigateByUrl(`login/resetExpiredPassword?resetToken=${error.error.resetToken}`);

2
ui-ngx/src/app/modules/tour/welcome-invitation.component.scss

@ -225,7 +225,7 @@
.rq-hfield { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; height: 46px; padding: 0 8px 0 16px; border-radius: var(--tb-widget-radius); background: var(--tb-surface); box-shadow: var(--tb-widget-shadow); transition: box-shadow .2s ease; }
.rq-hfield .rq-pre { flex: none; width: 18px; font-size: 20px; line-height: 24px; color: var(--ai-action); }
.rq-hfield .rq-typing { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; font: 400 16px/24px var(--tb-font); color: var(--tb-ink); text-align: left; }
.rq-hkey { flex: none; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; min-width: 22px; height: 22px; margin-right: 8px; padding: 0 6px; border: 1px solid var(--tb-line); border-radius: 6px; font: 500 12px/1 var(--tb-font); color: var(--tb-ink-54); }
.rq-hkey { flex: none; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; min-width: 20px; height: 20px; margin-right: 8px; padding: 0 5px; border: 1px solid var(--tb-line); border-bottom-width: 2px; border-radius: 5px; background: var(--chat-key, #f6f7f9); color: var(--tb-ink-76); font: 500 11px/1 var(--tb-font); letter-spacing: .2px; white-space: nowrap; }
.rq-hfield .rq-send { display: none; align-self: center; width: 32px; height: 32px; }
.rq-hrow.typing .rq-hfield { box-shadow: 0 0 0 2px var(--ai-focus), 0 8px 24px var(--ai-focus-shadow); }
.rq-hrow.typing .rq-hfield .rq-pre { color: var(--ai-focus); }

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

@ -158,6 +158,8 @@ export interface ErrorEvent extends BaseChatEvent {
data: {
message: string;
code?: 'CREDITS_USED_UP' | 'RATE_LIMITED';
reason?: 'NO_REPLY' | 'TIMED_OUT' | 'MODEL_ERROR' | 'FAILED';
wrote?: boolean;
};
}
@ -188,6 +190,8 @@ export interface ToolStarted extends BaseChatToolEventData {
tool: string;
arguments?: unknown;
startedAt?: number;
readOnly?: boolean;
groupId?: string;
}
export interface ToolStartedEvent extends BaseChatEvent {
@ -220,6 +224,8 @@ export interface AiAction {
affectedEntities?: Array<EntityId>;
edited?: boolean;
progress?: string;
readOnly?: boolean;
stages?: string[];
}
export interface ApprovalResult {
@ -463,6 +469,7 @@ export interface AiChatClientContext {
view: AiChatView;
timeZone?: string;
os?: string;
handOver?: {title: string; ticked: string[]; steps: number};
}
export function aiClientOs(): string | undefined {
@ -478,8 +485,13 @@ export interface SendChatMessageRequest {
resources?: string[];
secrets?: Record<string, string>;
editorDraft?: unknown;
again?: AiRunAgain;
executionId?: string;
reason?: string;
}
export type AiRunAgain = 'retry' | 'resume' | 'listen' | 'approve' | 'deny';
export interface AiResourceFacts {
pages?: number;
rows?: number;

10
ui-ngx/src/app/shared/models/solution-creator.models.ts

@ -66,16 +66,23 @@ export interface AiQuestionOption {
hint?: string;
}
export type AiQuestionKind = 'color' | 'secret' | 'number' | 'text' | 'multi' | 'date' | 'chips' | 'cards';
export interface AiQuestion {
id: string;
kind?: AiQuestionKind;
label?: string;
question: string;
parts?: Array<{text?: string; severity?: string}>;
why?: string;
options: AiQuestionOption[];
recommended?: string | string[];
multiple?: boolean;
secret?: boolean;
color?: boolean;
other?: {label?: string; placeholder?: string};
number?: {suggested?: number; unit?: string; step?: number; size?: 'short' | 'medium' | 'long'};
date?: boolean;
}
export interface AiQuestionAnswer {
@ -253,7 +260,8 @@ export interface GeneralChatMessage {
references?: Array<{name: string; entityType: string; id: string}>;
severities?: string[];
readings?: Array<{key: string; values: string[]}>;
status?: 'INCOMPLETE' | 'STOPPED';
status?: 'INCOMPLETE' | 'STOPPED' | 'RETRIED' | 'RESUMED';
failure?: {reason?: string; wrote?: boolean};
streaming?: boolean;
rating?: 'UP' | 'DOWN';
reported?: boolean;

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

@ -694,7 +694,6 @@
"question": {
"other-chip": "Other…",
"other-color": "Other color…",
"pick-color": "Pick a color",
"needs-answer": "Needs an answer",
"count": "{{at}} of {{of}}",
"other": "Something else",
@ -707,7 +706,23 @@
"no-answer": "No answer",
"your-answer": "Your answer",
"type-answer": "Type the answer",
"type-secret": "Paste it here; it stays hidden"
"type-secret": "Paste it here; it stays hidden",
"higher": "Higher by {{step}}",
"lower": "Lower by {{step}}",
"today": "{{day}}, today",
"time-wrong": "A time such as 9:30, from 0:00 to 23:59.",
"apply": "Apply",
"time": "Time",
"month-after": "The month after",
"month-before": "The month before",
"another-day": "Another day",
"hide": "Hide",
"show": "Show",
"other-color-short": "Other color",
"hex-label": "{{question}} · {{label}}, as a hex",
"hex-error": "A hex has three or six digits, 0–9 and A–F, such as 00897B.",
"number-error": "Enter a number, such as 12.5.",
"pick-color": "Pick with the color picker"
},
"ai-assistant": "AI Assistant",
"configure-with-ai": "Configure with AI",
@ -739,7 +754,7 @@
"approved": "Done",
"error": "Failed",
"thinking": "Thinking...",
"stopped-after": "{ count, plural, =1 {You stopped this reply after 1 step. Nothing more was done.} other {You stopped this reply after # steps. Nothing more was done.} }",
"stopped-after": "You stopped this reply. The steps above are done; nothing after them ran.",
"stopped-before": "You stopped this reply before any step. Nothing was done.",
"notice": {
"connection-lost": "The connection to the AI service is lost. Reconnecting…",
@ -774,6 +789,29 @@
},
"not-visible": "{{count}} not visible to the customer",
"all-visible": "The customer can see every entity this dashboard shows.",
"alarm-meta": "{{severity}}, {{status}} · since {{since}}",
"asked-for": "Asked for",
"heads-up": "Heads-up",
"stages": "Stages",
"asked": {
"named": "names like '{{name}}'",
"typed": "the {{types}} profile",
"text": "'{{text}}'",
"related-from": "what {{entity}} points to",
"related-to": "what points to {{entity}}",
"alarms-of": "{{entity}}",
"attributes-scope": "the {{scope}} of {{entity}}",
"history": "{{entity}}, {{from}} – {{to}}",
"history-keys": "{{keys}} on {{entity}}, {{from}} – {{to}}",
"latest-keys": "{{keys}} of {{entity}}",
"query": "'{{query}}'"
},
"alarm-status": {
"ACTIVE_UNACK": "active, not acknowledged",
"ACTIVE_ACK": "active, acknowledged",
"CLEARED_UNACK": "cleared, not acknowledged",
"CLEARED_ACK": "cleared, acknowledged"
},
"state-aliases": "Resolved only when the dashboard opens: {{aliases}}",
"access-truncated": "Only the first 50 entities were checked.",
"user-groups": "User groups",
@ -1281,6 +1319,74 @@
"run": "Looking up users",
"done": "Looked up users"
},
"search-entity-views": {
"run": "Looking up entity views",
"done": "Looked up entity views"
},
"search-edges": {
"run": "Looking up edges",
"done": "Looked up edges"
},
"search-tenants": {
"run": "Looking up tenants",
"done": "Looked up tenants"
},
"search-device-profiles": {
"run": "Looking up device profiles",
"done": "Looked up device profiles"
},
"search-asset-profiles": {
"run": "Looking up asset profiles",
"done": "Looked up asset profiles"
},
"search-groups": {
"run": "Looking up groups",
"done": "Looked up groups"
},
"search-gateways": {
"run": "Looking up gateways",
"done": "Looked up gateways"
},
"search-alarms": {
"run": "Looking up alarms",
"done": "Looked up alarms"
},
"search-alarm-rules": {
"run": "Looking up alarm rules",
"done": "Looked up alarm rules"
},
"search-calculated-fields": {
"run": "Looking up calculated fields",
"done": "Looked up calculated fields"
},
"search-notification-targets": {
"run": "Looking up notification recipients",
"done": "Looked up notification recipients"
},
"search-notification-templates": {
"run": "Looking up notification templates",
"done": "Looked up notification templates"
},
"search-notification-rules": {
"run": "Looking up notification rules",
"done": "Looked up notification rules"
},
"search-images": {
"run": "Looking up images",
"done": "Looked up images"
},
"discover-attribute-keys": {
"run": "Finding the attribute keys",
"done": "Found the attribute keys"
},
"read-connect-commands": {
"run": "Preparing the device's connection commands",
"done": "Prepared the device's connection commands"
},
"read-billing": {
"run": "Reading the plan and billing",
"done": "Read the plan and billing"
},
"search-tenant": {
"run": "Searching the tenant",
"done": "Searched the tenant"
@ -2206,8 +2312,11 @@
"done": "The solution is installed"
},
"failed": "Failed while {{words}}",
"auto-approved": "{{words}} · auto-approved",
"details": "Details",
"took": "Took {{time}}",
"took-auto": "Auto-approved, took {{time}}",
"done-auto": "Done, auto-approved",
"times": "{words} { count, plural, =2 {twice} other {# times} }",
"request": "Request",
"result": "Result",
"payload": "Payload",
@ -2221,12 +2330,29 @@
"mail-server": "Mail server",
"qr-code": "QR code",
"settings": "Settings",
"try-again": "Try again",
"try-again-prompt": "Try that again"
"try-again": "Try again"
},
"go-to-end": "Go to the end",
"go-to-card": "{{label}}: go to the end",
"kept-edits": {
"dashboard": "The chat changed this dashboard. Reload to see the change; your unsaved edits go.",
"entity": "The chat changed what this page shows. Reload to see the change; your unsaved edits go.",
"reload": "Reload"
},
"resume": "Resume",
"run-failed": "The run stopped with an error.",
"failed": {
"headline": "The run stopped before its answer.",
"steps-done": "The steps above are done; nothing else changed.",
"nothing-changed": "Nothing was changed.",
"reason": {
"TIMED_OUT": "The AI model took too long to answer.",
"MODEL_ERROR": "The AI model service returned an error.",
"CREDITS_USED_UP": "AI credits are used up, so the rest of your request waits."
},
"tried-again": "Tried again at {{time}}",
"resumed": "Resumed at {{time}}"
},
"new-count": "{{ count }} new",
"start-a-task": "Start a task",
"credits": {
@ -2239,12 +2365,12 @@
},
"hand-over": {
"stop-listening": "Stop listening",
"stopped-at": "Stopped listening at {{time}}",
"listen-again": "Listen again",
"test-first": "Test from this computer first",
"what-you-see": "What you should see",
"send-test": "Send a test value",
"send-test-here": "Send a test value from here",
"send-test-tip": "Sends one value as the device, marked as a test; the wait keeps listening for the device itself",
"test-sent": "A test value went in at {{time}} and is on the device's latest telemetry. The wait keeps listening for the device itself.",
"test-sent": "Sent a test value at {{time}}; it is on the latest telemetry. The wait goes on for the device itself.",
"test-failed": "The test value did not go through: {{error}}.",
"needs-you": "Needs you",
"fold": "Fold",
@ -2266,8 +2392,8 @@
"wait-message": "listening for the first message",
"wait-uplink": "listening for the first uplink",
"wait-gateway": "listening for the gateway",
"nothing-heard": "nothing heard for {{minutes}} min",
"not-decoded": "uplinks arrived but were not decoded",
"nothing-heard": "Nothing heard for {{minutes}} min",
"not-decoded": "Uplinks arrived but were not decoded",
"keep-waiting": "It is on now, keep waiting",
"keep-waiting-prompt": "It is on. Keep waiting for the data.",
"what-wrong": "What could be wrong?",
@ -2285,10 +2411,8 @@
},
"limit-out": {
"entity-title": "{{entities}} limit reached",
"tenant-text": "Your tenant can have up to {{limit}} {{entities}}. Your system administrator can raise the limit.",
"tenant-text-plain": "Your tenant has reached its limit of {{entities}}. Your system administrator can raise the limit.",
"license-text": "Your license allows no more {{entities}}. Your system administrator can raise the limit in License management.",
"license-text-old": "You have reached the maximum {{entities}} allowed by your subscription plan. You can upgrade the plan to raise your limits.",
"notice-count": "{{title}}: {{limit}} of {{limit}}.",
"notice": "{{title}}.",
"feature-title": "{{feature}} not included in your plan",
"feature": {
"white-labeling": "White labeling",
@ -2296,14 +2420,11 @@
"scheduler": "Scheduler",
"reporting": "Reports"
},
"white-labeling-text": "With White labeling, your brand replaces ThingsBoard's on the login page, in the mail you send and on every page your customers work in.",
"pack-text": "It comes with the Professional Pack. Request access and your system administrator gets your request.",
"license-required": "License required",
"request": "Request a higher limit",
"manage-license": "Manage license",
"sent": "Request sent to your system administrator.",
"failed": "Couldn't send the request. Try again.",
"view-usage": "View usage"
"failed": "Couldn't send the request. Try again."
},
"get-started": {
"title": "Get started",
@ -2562,17 +2683,31 @@
"upgrade-agent": "Upgrade the agent",
"delete": "Delete",
"cancel": "Cancel the operation",
"sync": "Sync"
"sync": "Sync",
"unassign": "Unassign",
"assign": "Assign",
"clear": "Clear",
"acknowledge": "Acknowledge"
},
"head": {
"pending": "Needs your review",
"approved": "Approved",
"auto": "Auto-approved",
"denied": "Denied",
"expired": "No answer in time"
"denied": "Denied"
},
"head-change": {
"create": "Create {{kind}}",
"update": "Update {{kind}}",
"delete": "Delete {{kind}}",
"install": "Install {{kind}}",
"acknowledge": "Acknowledge {{kind}}",
"clear": "Clear {{kind}}",
"assign": "Assign {{kind}}",
"unassign": "Unassign {{kind}}"
},
"current": "Current",
"new": "New",
"changes-to": "changes to",
"unchanged": "{{count}} unchanged",
"hide-unchanged": "Hide unchanged",
"not-set": "not set",
@ -2580,9 +2715,6 @@
"create": "Create",
"update": "Update",
"denied-text": "Nothing was made.",
"expired-text": "Nothing was made. The run waits here.",
"ask-again": "Ask again",
"ask-again-message": "Ask me again for the same change.",
"field": {
"integrationType": "Integration type",
"agent": "Agent",
@ -2918,6 +3050,91 @@
"NOTIFICATION": "Notification",
"NOTIFICATION_SETTINGS": "Notification delivery",
"NOTIFICATION_PREFERENCES": "Notification preferences"
},
"kind": {
"ADMIN_SETTINGS": "an admin settings",
"AGENT": "an agent",
"AGENT_APPLICATION": "an application",
"AGENT_APP_EVENT": "an agent app event",
"AGENT_APP_PROFILE": "an application profile",
"AGENT_APP_UNIT": "an agent app unit",
"AGENT_BULK_ACTION": "a bulk action",
"AGENT_PROFILE": "an agent profile",
"AI_MODEL": "an AI model",
"ALARM": "an alarm",
"ALARM_RULE": "an alarm rule",
"API_KEY": "an API key",
"API_USAGE_STATE": "an API Usage State",
"ASSET": "an asset",
"ASSET_PROFILE": "an asset profile",
"BLOB_ENTITY": "a blob entity",
"CALCULATED_FIELD": "a calculated field",
"CONVERTER": "a data converter",
"CUSTOMER": "a customer",
"CUSTOM_MENU": "the custom menu",
"CUSTOM_TRANSLATION": "the custom translation",
"DASHBOARD": "a dashboard",
"DASHBOARD_ENTITY_ALIAS": "an entity alias",
"DASHBOARD_FILTER": "a dashboard filter",
"DASHBOARD_STATE": "a dashboard state",
"DASHBOARD_WIDGET": "a widget",
"DEVICE": "a device",
"DEVICE_PROFILE": "a device profile",
"DOMAIN": "a domain",
"EDGE": "an edge",
"ENTITY_GROUP": "an entity Group",
"ENTITY_VIEW": "an entity View",
"GROUP_PERMISSION": "a group Permission",
"IMAGE": "an image",
"INTEGRATION": "an integration",
"JOB": "a task",
"MAIL_SERVER": "the mail server",
"MAIL_TEMPLATE": "a mail template",
"MOBILE_APP": "a mobile app",
"MOBILE_APP_BUNDLE": "a mobile bundle",
"MOBILE_BUNDLE": "a mobile bundle",
"MOBILE_QR_CODE": "a mobile app QR code",
"MY_PROFILE": "your profile",
"MY_TWO_FACTOR": "your account security",
"NOTIFICATION": "a notification",
"NOTIFICATION_PREFERENCES": "the notification preferences",
"NOTIFICATION_REQUEST": "a notification request",
"NOTIFICATION_RULE": "a notification rule",
"NOTIFICATION_SETTINGS": "the notification delivery",
"NOTIFICATION_TARGET": "a notification recipient",
"NOTIFICATION_TEMPLATE": "a notification template",
"OAUTH2_CLIENT": "an OAuth 2.0 client",
"OTA_PACKAGE": "an OTA package",
"PLATFORM_SETTINGS": "the platform settings",
"QUEUE": "a queue",
"QUEUE_STATS": "a queue statistics",
"RELATION": "relations",
"REPORT": "a report",
"REPORT_COMPONENT": "a report component",
"REPORT_ENTITY_ALIAS": "a report entity alias",
"REPORT_FILTER": "a report filter",
"REPORT_TEMPLATE": "a report template",
"ROLE": "a role",
"RPC": "an RPC",
"RULE_CHAIN": "a rule chain",
"RULE_NODE": "a rule node",
"SCADA_SYMBOL": "a SCADA symbol",
"SCHEDULED_REPORT": "a scheduled report",
"SCHEDULER_EVENT": "a scheduler event",
"SECRET": "a secret storage",
"TB_RESOURCE": "a resource",
"TENANT": "a tenant",
"TENANT_PROFILE": "a tenant profile",
"TWO_FACTOR_SETTINGS": "the security settings",
"USER": "a user",
"VERSION": "a version",
"WHITE_LABELING": "the white labeling",
"WIDGETS_BUNDLE": "a widgets bundle",
"WIDGET_TYPE": "a widget"
},
"white-labeling-target": {
"GENERAL": "Platform",
"LOGIN": "Login page"
}
},
"record": {
@ -4311,14 +4528,16 @@
"title": "Plan",
"steps": "{ count, plural, =1 {1 step} other {# steps} }",
"done-of": "{{done}} of {{count}}",
"folded": "Plan, {{done}} of {{count}} done",
"replaced": "Plan replaced by the one below, after {{done}} of {{count}}",
"change": "Change the plan",
"change-ask": "Change the plan.",
"you": "You",
"needs": {
"device": "Requires device",
"account": "Requires account",
"computer": "Requires computer",
"phone": "Requires phone"
"device": "Requires a device.",
"account": "Requires an account.",
"computer": "Requires a computer.",
"phone": "Requires a phone."
},
"run": "Run",
"run-step-by-step": "Run step by step",
@ -4328,6 +4547,12 @@
"run-prompt": "Run the plan.",
"leave-out": "Leave out step {{number}}: {{text}}"
},
"dock": {
"hand-label": "Your step",
"plan-label": "Plan",
"to-hand": "Show the hand-over in the chat",
"to-plan": "Show the plan in the chat"
},
"offer": {
"label": "Auto-approve offer",
"text": "The rest of this run waits for your yes at each step. Let it run through? Every action still shows here, and Stop halts the run.",
@ -15560,6 +15785,9 @@
"solution-creator": {
"opening": "Opening the solution…",
"stopped": "You stopped this step. Nothing was changed.",
"stopped-build": "You stopped building the solution. Nothing was installed.",
"stopped-install": "You stopped the install. It rolled back: nothing from the solution is left.",
"change-design": "Change the design",
"pane": {
"alarms": "Alarms",
"attribute": "attribute",
@ -15652,7 +15880,7 @@
"example-tip": "Puts the example in the composer",
"limits": "Nothing is created in your tenant until you approve the design and install it.",
"what-is-solution": "What is a solution?",
"about-title": "AI solution creator",
"about-title": "ThingsBoard Solutions",
"about-design-title": "A description becomes a design",
"about-design": "The AI drafts the architecture: device and asset profiles, relations, roles, calculated fields and alarm rules.",
"about-approve-title": "You approve each step",

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

File diff suppressed because it is too large
Loading…
Cancel
Save