diff --git a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts index c742ca7fb6..e0d3028f40 100644 --- a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts +++ b/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): void { this._updatedData$.next(affectedEntities); } teardown(): void { + this._keptEdits.set(null); this._editorDraftProvider = null; this._enabled.set(false); this._detailsOpen.set(false); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html index d08107aa5b..92b784a2e3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html @@ -5,14 +5,14 @@ --> @if (hood()) { -

{{ hood() }}

+

{{ 'ai-assistant.detail.asked-for' | translate }}{{ hood() }}

} @for (block of view().blocks; track $index) { @switch (block.type) { @case ('hub') {
@for (rec of shown(hub(), 'hub'); track rec.key) { - } @if (hub().length > LIST_SHOWN) { @@ -26,14 +26,19 @@ }
@for (row of shown(block.rows, 'records' + $index); track $index) { -
- +
+ @if (recordUrl(row); as url) { {{ row.name }} } @else { {{ row.name }} } - @if (row.meta) { + @if (row.status) { + {{ '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 || '—'} }} + } @else if (row.meta) { {{ row.meta }} }
@@ -99,7 +104,7 @@ @if (chip.image) { } @else if (chip.icon) { - + } {{ factValue(fact) }} @@ -166,6 +171,9 @@ }
} + @case ('warning') { +
{{ 'ai-assistant.detail.heads-up' | translate }}@if (block.label) {{{ say(block.label) }} }@for (row of block.rows; track $index) {{{ rowText(row) }}@if (!$last) {; }}
+ } @case ('note') {

{{ say(block.text) }}

} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts index 12b1578b66..549379f90e 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts +++ b/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 { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts index 0d4a76d11c..cc683f1984 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts @@ -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}; export interface AiDetailImage { label?: AiDetailText; @@ -108,6 +112,36 @@ export interface AiDetailView { export type AiDetailNames = ReadonlyMap; +export interface AiStepView { + askedFor?: AiDetailText; + blocks: AiDetailBlock[]; + under: AiDetailBlock[]; +} + +const ASKED_FOR: Record = { + '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 = 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 = 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>(); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html index 1fd53e8632..f944b1445f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html @@ -6,38 +6,80 @@ --> @switch (action().status) { @case ('RUNNING') { - + + @if (action().progress) { +
    + @for (stage of action().stages ?? []; track $index) { +
  • {{ stage }}
  • + } +
  • {{ action().progress }}
  • +
+ } } @case ('STOPPED') { } @default { -
- - @if (outcomeChip(); as chip) {{{ chip.before }}@if (chip.link) {{{ chip.name }}} @else {{{ chip.name }}}{{ chip.after }}} @else {{{ outcome() }}} - @if (duration()) { - {{ duration() }} - } -
- @if (arrival()?.readings?.length) { -
- @for (reading of arrival().readings; track reading.key) { - {{ reading.key }}{{ reading.value }} +
+ @switch (mark()) { + @case ('fail') { + } -
- } - @if (listing(); as hub) { -
- -
- } - @if (hasDetails()) { - - @if (records().length) { - + @case ('web') { + } - - - } + @case ('auto') { + check + } + @default { + + } + } + @let parts = lineParts(); + {{ parts.head }}@if (parts.chip; as chip) {}{{ parts.middle }}{{ parts.tail }}@if (parts.chipLast; as chip) {}@if (hasDetails()) {} +
+
+ @if (failure() !== null || arrival()?.readings?.length || listing() || detail().under.length) { +
+ @if (failure(); as why) { +
+

{{ why }}

+ +
+ } + @if (arrival()?.readings?.length) { +
+ @for (reading of arrival().readings; track reading.key) { + {{ reading.key }}{{ reading.value }} + } +
+ } + @if (listing(); as hub) { +
+ +
+ } + @if (detail().under.length) { + + } +
+ } + @if (hasDetails() && open()) { +
+ @if (grouped()) { + @for (member of groupViews(); track member.id) { +

{{ member.words }}

+ + } + } @else { + + } + @if (took(); as time) { +

{{ time }}

+ } +
+ } +
} } +@if (chip.link) {{{ chip.name }}} @else {{{ chip.name }}} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss index 7143edb765..9c2ad20d60 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss @@ -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); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts index 4005f165f7..8cf16b3431 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -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([]); + + 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(); 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(new Map()); facts = input([]); 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); + + 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(); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts index 1a1a3164c6..d2afdc3ec3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -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 = { 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 = { 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 = { 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 = { + 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 = { @@ -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 = 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; 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 | 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 = {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 { 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(); 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 = { 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'}; } + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index 020db48d8b..b81ca99f6c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -11,7 +11,6 @@ [class.done]="state === 'approved'" [class.auto]="state === 'auto'" [class.denied]="state === 'denied'" - [class.expired]="state === 'expired'" [class.danger]="isDestructive">
{{ headText }}
@if (listing; as hub) { @@ -21,8 +20,7 @@ } - @switch (state) { - @case ('pending') { + @if (state === 'pending' || state === 'waiting') { @if (!review) {

{{ data.message }}

} @@ -30,7 +28,7 @@
@for (fact of facts; track $index) {
@if (fact.labelCode) { {{ fact.label }} } @else { {{ fact.label }} }
-
@if (fact.chip; as chip) { @if (chip.image) { } @else if (chip.icon) { }{{ fact.value }} } @else if (fact.image) { } @else if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
+
@if (fact.chip; as chip) { @if (chip.image) { } @else if (chip.icon) { }{{ fact.value }} } @else if (fact.image) { } @else if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
}
} @@ -41,43 +39,29 @@
{{ block.value }}
} @if (changes.length) { - - - - - - - - - - @for (change of changes; track $index) { - - - @if (change.image || change.currentImage) { - - - } @else { - - - } - - } - +
+ @for (change of changes; track $index) { +
+
@if (change.labelCode) { {{ change.label }} } @else { {{ change.label }} }
+
+ @if (change.currentImage) { } @else { {{ change.current }} } + + {{ 'ai-assistant.review.changes-to' | translate }} + @if (change.image) { } @else { {{ change.value }} } +
+
+ } @if (unchanged.length && showUnchanged) { -
+
@for (same of unchanged; track $index) { -
- - - +
+
@if (same.labelCode) { {{ same.label }} } @else { {{ same.label }} }
+
{{ same.value }}
+
} - + } -
{{ 'ai-assistant.review.current' | translate }}{{ 'ai-assistant.review.new' | translate }}
@if (change.labelCode) { {{ change.label }} } @else { {{ change.label }} } - @if (change.currentImage) { } @else { {{ change.current }} } - - @if (change.image) { } @else { {{ change.value }} } - {{ change.current }}{{ change.value }}
@if (same.labelCode) { {{ same.label }} } @else { {{ same.label }} }{{ same.value }}
+
@if (unchanged.length) { - @@ -104,19 +88,8 @@ (keydown.escape)="$event.stopPropagation(); closeDeny()">
} - } - @case ('denied') { -

{{ 'ai-assistant.review.denied-text' | translate }}

- } - @case ('expired') { -

{{ 'ai-assistant.review.expired-text' | translate }}

-
- -
- } + } @else if (state === 'denied') { +

{{ 'ai-assistant.review.denied-text' | translate }}

} @if (data.time) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index 9f71414f4e..07f3f2629f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -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 = { 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 = {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([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; @Output() approvalAction = new EventEmitter(); - @Output() askAgain = new EventEmitter(); + @Output() answerLater = new EventEmitter(); 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); } + } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts index 9b71eda0a9..fa7b749311 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts +++ b/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) { - + } {{ action.label }} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html index e406abc2f6..dd8507412b 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html @@ -65,6 +65,17 @@ + } @else if (msg.from === 'ACTION' && madeFiles[$index]?.preview === 'image') { + @let pic = madeFiles[$index]; +
+ +
} @else if (msg.from === 'ACTION' && madeFiles[$index]; as made) {
@@ -80,14 +91,15 @@
} @else if (msg.from === 'ACTION' && plans[$index]; as plan) { -
- +
} @else if (msg.from === 'ACTION' && handOvers[$index]; as card) { -
+
+ [files]="latestFiles" (openFile)="openFile.emit($event)" [cardId]="msg.data.executionId" + [canListenAgain]="!loading" (listenAgain)="listenAgain()" [testRequest]="testRequests[msg.data.executionId] ?? 0">
@if (waitAfterCard[$index] !== undefined && messages[waitAfterCard[$index]]; as moved) { @if (moved.from === 'ACTION' && !waitsInCards.has(waitAfterCard[$index])) { @@ -101,16 +113,13 @@
} @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)) {
- - @if ($index === retryIndex) { -
- -
- } + + @if ($index === retryIndex) { +
+ } +
} } @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)"> + } @else if (msg.status === 'RETRIED' || msg.status === 'RESUMED') { +

{{ (msg.status === 'RETRIED' ? 'ai-assistant.failed.tried-again' : 'ai-assistant.failed.resumed') | translate: {time: clockText(msg.time)} }}

} @else if (msg.status === 'INCOMPLETE' || msg.status === 'STOPPED') { -
- warning_amber - {{ msg.status === 'STOPPED' ? stoppedText($index, msg.content) : msg.content }} -
+ @if (msg.status === 'INCOMPLETE') { +
+

{{ 'ai-assistant.failed.headline' | translate }} {{ failText($index, msg) }}

+ @if ($last && !loading && retry.observed) { +
+ } +
+ } @else { +

{{ stoppedText($index, msg.content) }}

+ } @if (summaries[$index]; as entities) { } @if (msg.status === 'STOPPED' && $last && !loading) { - + @if (msg.chips?.length) { + + } @else { + + } } } @else {
@@ -235,7 +257,7 @@ @for (option of prompts.items; track $index) { @@ -277,6 +299,29 @@ } } } +@if (dock && dockVisible) { +
+
+ + @if (dock.kind === 'hand' && dock.state !== 'stopped') {{{ 'ai-assistant.plan.you' | translate }}}{{ dock.text }} + @if (dock.count) { + {{ dock.count }} + } + @if (dock.kind === 'hand' && dock.state === 'listen' && dock.canTest) { + + } + @if (dock.kind === 'hand' && dock.state === 'stopped' && !loading) { + + } + +
+
+} @if (loading && !waitApproval && !actionRunning && !streaming) {
@if (work) { @@ -289,3 +334,9 @@ }
} + + + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index 758bb07ea5..8680d28d7f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -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; -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts index a17001873c..eeeccaea33 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts @@ -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(); @Output() report = new EventEmitter(); @Output() approvalAction = new EventEmitter(); - @Output() askAgain = new EventEmitter(); + @Output() answerLater = new EventEmitter(); @Output() editMessage = new EventEmitter(); @Output() resume = new EventEmitter(); + @Output() dockShown = new EventEmitter(); + @Output() listen = new EventEmitter(); + @Input() slotTaken = false; + testRequests: Record = {}; + + private readonly severityWord = (severity: string): string => this.translate.instant('alarm.severity-' + severity.toLowerCase()); + dock: AiDockRow | null = null; + private madeUrls = new Map>(); + dockVisible = false; + dockBelow = false; + private dockScroller: HTMLElement | null = null; + private readonly placeDockOnScroll = () => this.placeDock(); + @Output() retry = new EventEmitter(); @Output() autoApproveRest = new EventEmitter(); @Output() runPlan = new EventEmitter<{run: AiPlanRun; steps: AiPlanStep[]}>(); @Output() changePlan = new EventEmitter(); @@ -129,6 +157,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { runningLead = -1; + readGroups: Record = {}; + + groupedAway = new Set(); + runningCount = 0; summaries: Record = {}; @@ -149,7 +181,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { records: Record = {}; made: Record = {}; - plans: Record = {}; + plans: Record = {}; handOvers: Record = {}; waitsInCards = new Set(); private movedWaits = new Set(); @@ -192,6 +224,15 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { private dialog: MatDialog, private aiResourceService: AiResourceService) {} + madeUrl(file: AiMadeFile): Observable { + 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, { @@ -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 { @@ -633,6 +684,50 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { return summaries; } + private findReadGroups(): void { + const groups: Record = {}; + const away = new Set(); + 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 { - const plans: Record = {}; + private findPlans(): Record { + const plans: Record = {}; 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 { const answers: Record = {}; 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(`[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(`[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): 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 { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html index 6022e31a11..5b224c38db 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -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 @@ }
@if (pill(); as current) { - + +
} }
- {{ fileCopied() ? ('ai-assistant.copied' | translate) : '' }} @if (file.image) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts index 4e971408b9..f49109abf2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -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>('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('.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>('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>(new Set()); + private rerun: (() => void) | null = null; + + dockShown = signal(false); waitingApproval = computed(() => { 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 { + private sendMessage(prompt: AiPromptMessage, again?: {again: AiRunAgain; executionId?: string; reason?: string}): Observable { 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'); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html new file mode 100644 index 0000000000..681a5dde69 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html @@ -0,0 +1,42 @@ + +
+ @for (option of question().options; track option.label) { + + } + +
+@if (other()) { +
+ + + + + +
+ @if (wrong()) { + + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts new file mode 100644 index 0000000000..2b06877fab --- /dev/null +++ b/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(); + value = model(''); + disabled = input(false); + enter = output(); + + private elementRef: ElementRef = 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('.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()); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html new file mode 100644 index 0000000000..7b65d79e94 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html @@ -0,0 +1,23 @@ + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts new file mode 100644 index 0000000000..0c9180135e --- /dev/null +++ b/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(); + 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()); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts index c9dd54eadf..11e2c8b819 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts +++ b/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; + 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(); - variant = input<'details' | 'section' | 'divided'>('section'); - - key = input(''); + variant = input<'section' | 'divided'>('section'); private host = inject(ElementRef); - private toggledOpen = signal(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); } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html index 9986a409e0..874b04463f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -6,12 +6,9 @@ -->
@if (folded()) { -
- {{ 'ai-assistant.hand-over.needs-you' | translate }} - {{ handOver().title }} -
- +

{{ arrivedLine() }}

} @else {
@@ -37,7 +34,7 @@ @for (option of choice.options; track option.id) { @@ -70,6 +67,7 @@ } @if (step.values.length || step.markdown) {
+
@for (value of step.values; track $index; let v = $index) {
@@ -90,6 +88,7 @@
} +
@if (step.markdown) { } @@ -105,36 +104,40 @@

{{ test.hint }}

}
- @if (test.outcomes.length) { - - - @for (outcome of test.outcomes; track $index) { - - - - - } -
{{ outcome.output }}{{ outcome.meaning }}
-
- } } - @if (quiet() || stoppedQuiet()) { + @if (stopped()) { +
+
+ + {{ 'ai-assistant.hand-over.stopped-at' | translate: {time: stoppedAt()} }} + @if (canListenAgain()) { + + + + } +
+
+ } @else if (quiet()) {
{{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.nothing-heard') | translate: {minutes: quietMinutes()} }} - @if (waiting()) { - {{ clock() }} - } + {{ clock() }} + + +
- @if (handOver().quiet && !undecoded()) { -

{{ handOver().quiet }}

- }
- @if (canSendTest() && waiting()) { - }
@if (canSendTest()) {
-
} - @if (testNote(); as note) { -

{{ note }}

- } +
+ } + @if (testNote(); as note) { +
+ + {{ note }}
}
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts index 87803444ad..1b6dd6f36d 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts +++ b/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(null); time = input(0); files = input>(new Map()); + cardId = input(''); + 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(); @Output() stop = new EventEmitter(); @Output() compose = new EventEmitter(); @Output() openFile = new EventEmitter(); + @Output() listenAgain = new EventEmitter(); readonly fileMark = aiFileMark; readonly fileName = aiFileName; @@ -57,10 +111,13 @@ export class AiHandOverComponent implements AfterViewChecked { readonly shown = signal>(new Set()); readonly copied = signal(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 { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html index 86ade52c20..0ea48ad67d 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html @@ -5,43 +5,27 @@ --> @let current = view(); - + +
+@if (state() === 'failed') { +

{{ 'ai-assistant.limit-out.failed' | translate }}

+} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts index e966ca6c88..b6878ea0f0 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts +++ b/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; @@ -60,6 +59,11 @@ export class AiLimitOutComponent { readonly pricingUrl = PRICING_URL; readonly state = signal('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: '' }; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html new file mode 100644 index 0000000000..262b55a238 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html @@ -0,0 +1,22 @@ + +
+ + + @if (question().number?.unit) { + {{ question().number.unit }} + } + +
+@if (wrong()) { + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts new file mode 100644 index 0000000000..c06d2361a7 --- /dev/null +++ b/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(); + value = model(''); + disabled = input(false); + enter = output(); + + 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); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html index 93d741ce42..3cfbfe0da2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html @@ -4,7 +4,19 @@ SPDX-License-Identifier: BUSL-1.1 --> -
+@if (folded()) { + +} +@if (!folded() || open()) { +
{{ 'ai-assistant.plan.title' | translate }} {{ gate() || !progress() ? ('ai-assistant.plan.steps' | translate: {count: counted()}) : ('ai-assistant.plan.done-of' | translate: {done: done(), count: counted()}) }} @@ -23,15 +35,9 @@ } @else { - - @if (marks()[$index] === 'done') { - - } @else if (marks()[$index] === 'off') { - - } - + } - @if (step.by === 'user') {{{ 'ai-assistant.plan.you' | translate }}@if (step.needs) {{{ 'ai-assistant.plan.needs.' + step.needs | translate }}}}@for (part of parts(step.text); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}} + @if (step.by === 'user') {{{ 'ai-assistant.plan.you' | translate }}}@for (part of parts(step.text); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}}@if (step.by === 'user' && step.needs) { {{ 'ai-assistant.plan.needs.' + step.needs | translate }}} } @@ -55,3 +61,4 @@
}
+} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts index 7b4d336115..05442d6a15 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts +++ b/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(null); gate = input(false); autoApprove = input(false); + replacedAfter = input(null); + + private fold = aiFold(); + + open = this.fold.open; @Output() run = new EventEmitter(); @Output() change = new EventEmitter(); @@ -29,9 +35,12 @@ export class AiPlanComponent { private cleared = signal>(new Set()); private host = inject(ElementRef); + private translate = inject(TranslateService); private chips = effect(() => { const steps = this.steps(); + this.open(); + this.folded(); setTimeout(() => { const whats = (this.host.nativeElement as HTMLElement).querySelectorAll('.k-plan li .k-what'); steps.forEach((step, index) => { @@ -42,25 +51,30 @@ export class AiPlanComponent { }); }); - marks = computed(() => { - 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); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss index bde8d07d8e..72fbccb13c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss +++ b/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%); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html index 05858aa02a..79c6653a57 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html @@ -70,112 +70,118 @@ @if (numbered) { } - {{ step.question }} + @if (step.parts) {@for (part of step.parts; track $index) {@if (part.severity) {{{ ('alarm.severity-' + part.severity.toLowerCase()) | translate }}} @else {{{ part.text }}}}} @else {{{ step.question }}} @if (step.why) { {{ step.why }} }
- @if (isFree(step) && isColor(step)) { -
- -
- } @else if (isFree(step)) { -
-
- - {{ 'ai-assistant.question.your-answer' | translate }} - @if (step.secret) { - - } @else { + @switch (kind(step)) { + @case ('color') { + + } + @case ('secret') { + + } + @case ('number') { + + } + @case ('text') { +
+
+ + {{ otherLabel(step) }} - } - + +
-
- } @else if (step.multiple) { -
- @for (option of step.options; track option.label) { - + } + -
- } @else if (isChipRow(step)) { -
- @for (option of step.options; track option.label) { - - } - @if (isColor(step)) { - + } + - } @else { +
+ } + @case ('chips') { +
+ @for (option of step.options; track option.label) { + + } + [disabled]="disabled()" (click)="pickOther(step)">{{ step.other?.label ? step.other.label + '…' : ('ai-assistant.question.other-chip' | translate) }} +
+ @if (isOther(step) && step.number) { + + } @else if (isOther(step)) { + + } @else if (chosenHint(step); as hint) { +

{{ hint }}

} -
- @if (isOther(step) && !isColor(step)) { - - } @else if (chosenHint(step); as hint) { -

{{ hint }}

} - } @else { -
- @for (option of step.options; track option.label) { - + } + -
+ } }
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts index aff1efef08..20be493d3a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts +++ b/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(null); private picked = signal>({}); + private days: Record = {}; private chosen = signal>({}); private typed = signal>({}); @@ -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); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts new file mode 100644 index 0000000000..22bf9719c9 --- /dev/null +++ b/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; +} + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts index 6ccf98dd90..9e549aa121 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -56,10 +56,10 @@ export function aiWidgetThumb(): string { } @else { } - + } @else { - + }
@if (rec.url) { @@ -123,9 +123,9 @@ export function aiWidgetThumb(): string { @if (note()) {

{{ note() }}

} - @if (facts().length) { + @if (shownFacts().length) {
- @for (fact of facts(); track $index) { + @for (fact of shownFacts(); track $index) {
{{ fact.label }}
@for (part of parts(fact); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}}
} @@ -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))); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts index 2da3acfb33..3fc7f6fda4 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts @@ -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()); } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts index 71899ef487..306780ff62 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts +++ b/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: ` - + @if (url()) { {{ name() }} } @else { @@ -50,6 +50,7 @@ export class AiRecordComponent { entityType = input.required(); alarmRule = input(false); + groupType = input(undefined); name = input.required(); @@ -65,5 +66,5 @@ export class AiRecordComponent { hub = input(); - kind = computed(() => aiEntityKind(this.entityType(), this.alarmRule())); + kind = computed(() => aiEntityKind(this.entityType(), this.alarmRule(), this.groupType())); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts index b714aef730..d8d7308ec2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts +++ b/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}); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts index 6df80b9e27..ac27ede19d 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts +++ b/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) {
@if (listOpen()) {
@for (rec of shownViews(); track rec.key) { - } @@ -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(); diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-references.ts b/ui-ngx/src/app/modules/home/components/ai/ai-references.ts index 48acad0a84..c4a71bf928 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-references.ts +++ b/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>(); + +function svgIcon(name: string): Promise { + 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 = { 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(`(? 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(`(? severity.toLowerCase()).join('|')})(?![\\p{L}\\p{N}_])`, 'iu'); + const chipped = new Set(); + 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); + } + }); }); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts index d3f544b305..3d512d4cf3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts @@ -21,14 +21,14 @@ const LEAD_TYPES = new Set([EntityType.DASHBOARD, EntityType.WIDGET_TYPE @if (rest().length > 1) {
@if (listOpen()) {
@for (row of shownRows(); track row.key) { - } @if (rest().length > LIST_SHOWN) { @@ -43,7 +43,7 @@ const LEAD_TYPES = new Set([EntityType.DASHBOARD, EntityType.WIDGET_TYPE } @else if (rest().length) {
@for (row of rest(); track row.key) { - }
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html new file mode 100644 index 0000000000..92d0c4bacd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html @@ -0,0 +1,19 @@ + +
+ + + + +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts new file mode 100644 index 0000000000..b41bf8d4cf --- /dev/null +++ b/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(); + value = model(''); + disabled = input(false); + enter = output(); + + readonly shown = signal(false); + readonly ready = computed(() => !!this.value()); + + toggle(field: HTMLInputElement): void { + this.shown.update(shown => !shown); + field.focus(); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts index c51e0c5498..2d42ea2b29 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts @@ -57,10 +57,10 @@ const LIST_PAGES: Record = { {{ 'ai-assistant.started-from' | translate }} @if (current.url) { - {{ current.name }} + {{ current.name }} } @else { - {{ current.name }} + {{ current.name }} } } `, diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts new file mode 100644 index 0000000000..ee9b4b60e0 --- /dev/null +++ b/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') { + + } + @case ('listen') { + + } + @case ('run') { + + } + @default { + + } + } + `, + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false, + host: { + 'class': 'tb-ai-step-mark' + } +}) +export class AiStepMarkComponent { + + mark = input.required(); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-text.ts b/ui-ngx/src/app/modules/home/components/ai/ai-text.ts new file mode 100644 index 0000000000..79d94c5e9a --- /dev/null +++ b/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'}); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss index d44f437a08..fe1e9efea1 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss @@ -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); } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index a6e37d5ae5..a85d2bcc33 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -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, diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html index ab5e08a289..1ed3f7498a 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html +++ b/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) { - {{ row.primary.additionalData?.name }} + {{ row.primary.additionalData?.name }} } @else { - {{ row.primary.additionalData?.name }} + {{ row.primary.additionalData?.name }} } @@ -107,7 +107,7 @@ @default { @if (row.details.chip; as chip) { - {{ chip.label }} + {{ chip.label }} } } diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html index ef78179801..e0328bc846 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html @@ -36,7 +36,7 @@ - {{ profile.name }} + @if (profile.name?.trim()) {{{ profile.name }}} @else {{{ typeLabel(profile) }} {{ $index + 1 }}} {{ typeLabel(profile) }} @@ -105,7 +105,7 @@ @if (schemaEntity(); as entity) {
- {{ entity.name }} + {{ entity.name }}
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html index 5895225f5a..87633b1124 100644 --- a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -232,8 +232,7 @@ {{ jsonCopied() ? ('ai-assistant.copied' | translate) : '' }}