From dcc3c800ac3f735f188a9025a3bb1a8a822f0681 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Tue, 1 Dec 2026 11:21:50 +0200 Subject: [PATCH 1/4] =?UTF-8?q?AI=20chat=20design=20sync=20U1=E2=80=93U10:?= =?UTF-8?q?=20action=20lines=20on=20the=20kit's=20step=20line=20(the=20who?= =?UTF-8?q?le=20line=20opens=20Details,=20stages=20while=20running,=20a=20?= =?UTF-8?q?failure=20block=20with=20its=20fix,=20credentials,=20connect=20?= =?UTF-8?q?commands=20and=20research=20folded=20into=20Details);=20a=20fai?= =?UTF-8?q?led=20turn's=20red=20block=20with=20Try=20again=20and=20a=20sto?= =?UTF-8?q?pped=20turn's=20Resume=20that=20continue=20in=20place=20(again:?= =?UTF-8?q?=20retry|resume),=20with=20Tried=20again=20/=20Resumed=20lines?= =?UTF-8?q?=20in=20history;=20approval=20cards=20headed=20verb=20+=20kind?= =?UTF-8?q?=20with=20a=20per-field=20diff,=20waiting=20cards=20answered=20?= =?UTF-8?q?later=20(again:=20approve|deny);=20question=20fields=20for=20nu?= =?UTF-8?q?mber,=20date=20with=20a=20month=20calendar,=20secret=20with=20S?= =?UTF-8?q?how,=20colours=20and=20Other;=20hand-over=20ticks=20kept=20and?= =?UTF-8?q?=20sent=20as=20clientContext,=20a=20folding=20card,=20Stopped?= =?UTF-8?q?=20with=20Listen=20again,=20a=20dock=20row=20over=20the=20compo?= =?UTF-8?q?ser=20for=20the=20hand-over=20or=20plan;=20plans=20fold=20when?= =?UTF-8?q?=20finished=20or=20replaced;=20severity=20chips=20from=20marker?= =?UTF-8?q?s=20and=20the=20alarms=20table;=20entity=20icons=20through=20tb?= =?UTF-8?q?-icon=20on=20the=20iconography=20lab's=20palette;=20kept=20unsa?= =?UTF-8?q?ved=20edits=20on=20the=20entity=20drawer=20and=20dashboard=20wi?= =?UTF-8?q?th=20Reload;=20limits=20as=20a=20notice;=20inline=20pictures;?= =?UTF-8?q?=20credits=20running=20out=20mid-run;=20a=20stopped=20solution'?= =?UTF-8?q?s=20phase;=20the=20shared=20key=20look=20for=20"/";=20alarm=20c?= =?UTF-8?q?ard=20verbs=20acknowledge,=20clear,=20assign,=20unassign?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../services/ai-assistant-panel.service.ts | 14 + .../ai/ai-action-detail.component.html | 20 +- .../ai/ai-action-detail.component.ts | 4 +- .../components/ai/ai-action-detail.models.ts | 107 +- .../ai/ai-action-line.component.html | 94 +- .../ai/ai-action-line.component.scss | 160 +- .../components/ai/ai-action-line.component.ts | 122 +- .../home/components/ai/ai-action.models.ts | 180 ++- .../ai/ai-approval-card.component.html | 73 +- .../ai/ai-approval-card.component.ts | 113 +- .../ai/ai-card-actions.component.ts | 2 +- .../ai/ai-chat-messages.component.html | 105 +- .../ai/ai-chat-messages.component.scss | 26 +- .../ai/ai-chat-messages.component.ts | 227 ++- .../home/components/ai/ai-chat.component.html | 25 +- .../home/components/ai/ai-chat.component.ts | 156 +- .../components/ai/ai-hand-over.component.html | 74 +- .../components/ai/ai-hand-over.component.ts | 70 +- .../components/ai/ai-limit-out.component.html | 58 +- .../components/ai/ai-limit-out.component.ts | 5 + .../home/components/ai/ai-plan.component.html | 17 +- .../home/components/ai/ai-plan.component.ts | 18 + .../ai/ai-prompt-input.component.scss | 14 +- .../components/ai/ai-question.component.html | 176 ++- .../components/ai/ai-question.component.ts | 283 +++- .../components/ai/ai-record-card.component.ts | 19 +- .../components/ai/ai-record-loader.service.ts | 8 +- .../home/components/ai/ai-record.component.ts | 5 +- .../home/components/ai/ai-record.models.ts | 4 +- .../components/ai/ai-records.component.ts | 6 +- .../home/components/ai/ai-references.ts | 162 +- .../components/ai/ai-run-summary.component.ts | 6 +- .../ai/ai-started-from.component.ts | 4 +- .../components/ai/ai-work-line.component.scss | 7 +- .../pane/solution-installed.component.html | 6 +- .../pane/solution-overview.component.html | 4 +- .../ai/solution/solution-chat.component.html | 3 +- .../ai/solution/solution-chat.component.ts | 16 +- .../dashboard-page.component.ts | 9 +- .../entity/entities-table.component.ts | 9 +- .../src/app/modules/home/home.component.scss | 2 +- .../tour/welcome-invitation.component.scss | 2 +- .../src/app/shared/models/ai-chat.models.ts | 14 + .../shared/models/solution-creator.models.ts | 7 +- .../assets/locale/locale.constant-en_US.json | 186 ++- ui-ngx/src/theme/ai-theme.scss | 1365 ++++++++++++----- 46 files changed, 3092 insertions(+), 895 deletions(-) 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..8c457311cd 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,25 @@ 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}); + } + + 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..dc1a05f8d1 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 @@ -29,6 +29,8 @@ export interface AiDetailRecord { name: string; meta?: string; severity?: string; + status?: string; + since?: string; } export interface AiDetailHubItem { @@ -94,7 +96,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 +111,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 +228,20 @@ 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 aiTrueMinus(text: string): string { + return text.replace(/(^|[\s(=:])-(?=\d)/g, '$1\u2212'); +} + 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 +250,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 +499,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 +908,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 +966,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 +1029,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 +1154,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 +1221,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 +1398,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 +1851,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 +1919,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 +2080,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 +2190,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 +2222,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..6b9d22bb56 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,169 @@ 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 { + width: 16px; + height: 16px; + font-size: 16px; + line-height: 16px; + color: inherit; + } + } } - .say { + .k-mark-bolt { + position: absolute; + right: 1px; + bottom: -3px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 12px; + height: 12px; + border-radius: 6px; + background: 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 +192,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..c9ab970d2c 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, linkedSignal } 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 { aiDisclosureRemember, aiDisclosureRemembered, 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,106 @@ 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); + + open = linkedSignal(() => aiDisclosureRemembered(this.key())); + + 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(); + const open = !this.open(); + this.open.set(open); + aiDisclosureRemember(this.key(), open); + if (open) { + 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..e3902db419 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 @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 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 +29,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 +144,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 +189,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 +261,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'; @@ -522,21 +553,56 @@ 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()), + parts: aiSeverityParts(question.question.trim()), + why: typeof question.why === 'string' ? aiSeverityWords(question.why) : undefined, options: (Array.isArray(question.options) ? question.options : []) .filter(option => typeof option?.label === 'string' && option.label.trim()) .slice(0, 6) - .map(option => ({label: option.label.trim(), hint: typeof option.hint === 'string' ? option.hint : undefined})), + .map(option => ({label: aiSeverityWords(option.label.trim()), hint: typeof option.hint === 'string' ? aiSeverityWords(option.hint) : undefined})), recommended: Array.isArray(question.recommended) ? question.recommended.filter(label => typeof label === 'string') : undefined, multiple: question.multiple === true, secret: question.secret === true && !(Array.isArray(question.options) && question.options.length), - color: question.color === true && question.multiple !== true + 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 })); } +const SEVERITY_MARKS = /\{(CRITICAL|MAJOR|MINOR|WARNING|INDETERMINATE)\}/g; + +export function aiSeverityWords(text: string): string { + return text.replace(SEVERITY_MARKS, (_, severity: string) => severity.charAt(0) + severity.slice(1).toLowerCase()); +} + +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 +628,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 +774,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 +819,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 +831,71 @@ 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'}; +} + +export function aiIconSvg(icon: string): string | null { + return icon.includes(':') ? icon : null; } 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..0794e97cd7 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) {
} - } - @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..16586f4033 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,10 @@ 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 OWN_HEAD_KINDS = new Set(['MY_PROFILE', 'MY_TWO_FACTOR', 'RELATION']); +const THE_HEAD_KINDS = new Set(['WHITE_LABELING', 'TWO_FACTOR_SETTINGS', 'MAIL_SERVER', 'PLATFORM_SETTINGS', 'NOTIFICATION_SETTINGS', + 'NOTIFICATION_PREFERENCES', 'CUSTOM_MENU', 'CUSTOM_TRANSLATION']); +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 +151,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]); +export 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'; + } +} + +export 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; +} + +export 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 = translate.instant(label); + if (review.verb && REVIEW_VERBS.has(review.verb) && !['install', 'delete', 'update', 'acknowledge', 'clear', 'assign', 'unassign'].includes(review.verb)) { + return verb; + } + const kind = review.detail === 'alarm-rule' ? translate.instant('ai-assistant.review.type.ALARM_RULE') : aiReviewTypeLabel(translate, review.entityType); + const noun = /^[A-Z][a-z]/.test(kind) ? kind.charAt(0).toLowerCase() + kind.slice(1) : kind; + const form = OWN_HEAD_KINDS.has(review.entityType) ? 'own' : THE_HEAD_KINDS.has(review.entityType) ? 'the' + : /^(?:[aeio]|u(?![sn]i|s[eu])|[AEFHILMNORX][A-Z])/.test(noun) ? 'an' : 'a'; + return translate.instant('ai-assistant.review.head-change.' + form, {verb, kind: noun}); +} + +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', @@ -175,7 +229,7 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked { @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,25 +342,10 @@ 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; const template = this.review?.entityType === 'MAIL_TEMPLATE' && name ? mailTemplateTranslations.get(name as MailTemplate) : undefined; @@ -355,9 +400,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 +413,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 +424,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 +441,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 +521,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..0f6337a55a 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()">
@if (waitAfterCard[$index] !== undefined && messages[waitAfterCard[$index]]; as moved) { @if (moved.from === 'ACTION' && !waitsInCards.has(waitAfterCard[$index])) { @@ -101,16 +113,17 @@
} @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 { @@ -131,18 +144,34 @@ [autoApprove]="autoApprove" [answered]="!!denyReasons[getApprovalData(msg).executionId]" (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 +264,7 @@ @for (option of prompts.items; track $index) { @@ -277,6 +306,42 @@ } } } +@if (dock && dockVisible) { +
+
+ @switch (dock.state) { + @case ('stopped') { + + } + @case ('listen') { + + } + @case ('run') { + + } + @default { + + } + } + @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) { 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..70939b8e2d 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,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, inject, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; +import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, inject, Input, OnChanges, OnDestroy, Output, QueryList, SimpleChanges, ViewChildren } 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,6 +35,8 @@ import { CHECK_CONNECTION_TOOL, CITE_SOURCES_TOOL, HAND_OVER_TOOL, + AiAction, + aiGroupableRead, isHiddenAiAction, isKitCardTool, PROPOSE_PLAN_TOOL, @@ -64,7 +68,7 @@ export interface AnswerReportEvent { comment?: string; } import { aiFenceMeta, announceCopied, decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; -import { AiHandOverWait } from '@home/components/ai/ai-hand-over.component'; +import { AiHandOverComponent, AiHandOverWait } from '@home/components/ai/ai-hand-over.component'; import { aiDetailNames, AiDetailNames } from '@home/components/ai/ai-action-detail.models'; import { decorateFileChips, decorateHints, decorateLinks, decorateReferences, decorateSeverities, decorateValues } from '@home/components/ai/ai-references'; import { AlarmSeverity, alarmSeverityTranslations } from '@shared/models/alarm.models'; @@ -72,6 +76,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 +122,19 @@ 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; + @ViewChildren(AiHandOverComponent) handOverCards: QueryList; + dock: AiDockRow | null = null; + private madeUrls = new Map>(); + dockVisible = 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 +152,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { runningLead = -1; + readGroups: Record = {}; + + groupedAway = new Set(); + runningCount = 0; summaries: Record = {}; @@ -149,7 +176,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 +219,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 +435,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 +462,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 +500,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(); @@ -477,7 +519,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { // stream of auto-generated cards down to 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 +535,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); @@ -633,6 +679,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 +732,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 new Date(time ?? Date.now()).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}); } stoppedText(index: number, content: string): string { @@ -660,7 +764,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)) { @@ -748,6 +852,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 +967,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 +1003,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 +1013,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,6 +1030,11 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { return plans; } + private planFinished(plan: {steps: AiPlanStep[]; progress: AiPlanProgress | null}): boolean { + const progress = plan.progress; + return !!progress && plan.steps.every((_, index) => progress.done.includes(index + 1) || progress.skipped.includes(index + 1)); + } + private findAnswers(): Record { const answers: Record = {}; let questions: AiQuestion[] = []; @@ -966,7 +1084,72 @@ 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; + this.handOverCards?.find(card => card.cardId() === id)?.sendTest(); + } + + 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 progress = plan.progress; + const counted = plan.steps.filter((_, index) => !progress.skipped.includes(index + 1)); + const now = progress.now ?? plan.steps.findIndex((_, index) => !progress.done.includes(index + 1) && !progress.skipped.includes(index + 1)) + 1; + const step = plan.steps[Math.max(0, 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: progress.done.length, count: counted.length})}; + } + + 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; + 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; + } + } + 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 +1218,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..7f5753d97b 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) { - +
} @else if (notice(); as current) {
{{ current.text }} @@ -273,8 +287,7 @@ {{ 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..8506c142ac 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'); @@ -372,6 +398,8 @@ export class AiChatComponent implements OnInit, OnDestroy { private answeredApprovals = signal>(new Set()); + dockShown = signal(false); + waitingApproval = computed(() => { if (this.autoApprove()) { return undefined; @@ -388,6 +416,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 +426,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 +459,12 @@ 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(); + } private whiteLabelingService = inject(WhiteLabelingService); private customMenuService = inject(CustomMenuService); private translate = inject(TranslateService); @@ -787,10 +827,12 @@ 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)); + this.runAgain(event.approved ? 'approve' : 'deny', event.executionId, event.reason); } sendMsgFromUser(prompt: AiPromptMessage): void { @@ -866,7 +908,29 @@ 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): void { + if (this.loading() || !this.chatId() || this.waitingApproval()) { + return; + } + 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; + this.clearPassingNotice(); + this.messages.update(list => [...list.filter(message => !failed.includes(message)), ...(marker ? [marker] : [])]); + this.sendMessage({message: '', resources: []}, {again, executionId, reason}).subscribe({ + error: err => { + if (this.isConnectionLost(err) && this.chatId()) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.resumeTurn(this.chatId(), true); + return; + } + this.messages.update(list => [...list.filter(message => message !== marker), ...failed]); + setTimeout(() => this.showErrorMessage(err), 0); + } + }); } private sendWhileWorking(prompt: AiPromptMessage, userMessage: ChatMessage): void { @@ -926,6 +990,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 +1006,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 +1018,16 @@ export class AiChatComponent implements OnInit, OnDestroy { }) ); const request = this.chatRequest(prompt); + this.limitOut.set(null); + 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 +1132,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 +1147,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,7 +1172,11 @@ export class AiChatComponent implements OnInit, OnDestroy { } break; default: - if (event.event === 'error' && event.data?.code) { + 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) { this.restoreLastPrompt(); if (event.data.code === 'CREDITS_USED_UP') { this.discardFreshChat(); @@ -1101,7 +1187,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, wrote: event.data?.wrote}; + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: message, status: 'INCOMPLETE', failure, time: Date.now()}]); } } return of(event); @@ -1158,7 +1245,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 +1254,9 @@ 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} : {}), + ...(started.groupId ? {groupId: started.groupId} : {}) }; this.messages.update(list => [...list, {from: 'ACTION', data: action}]); } @@ -1190,15 +1280,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 +1435,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') { @@ -1386,9 +1478,23 @@ export class AiChatComponent implements OnInit, OnDestroy { } 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 +1600,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-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..d56d2e11e9 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 @@ -26,6 +26,38 @@ 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.'; + +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 = localStorage.getItem(PROGRESS_KEY + cardId); + return saved ? JSON.parse(saved) as AiHandOverProgress : null; + } catch { + return null; + } +} + +function aiSaveHandOverProgress(cardId: string, progress: AiHandOverProgress): void { + if (!cardId) { + return; + } + try { + localStorage.setItem(PROGRESS_KEY + cardId, JSON.stringify(progress)); + } catch { + return; + } +} @Component({ selector: 'tb-ai-hand-over', @@ -38,12 +70,15 @@ export class AiHandOverComponent implements AfterViewChecked { wait = input(null); time = input(0); files = input>(new Map()); + cardId = input(''); + 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; @@ -61,6 +96,7 @@ export class AiHandOverComponent implements AfterViewChecked { 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 +133,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 +166,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 +218,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 +229,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..c01b6e7e06 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,25 @@ --> @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..cfcca100bd 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 @@ -60,6 +60,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: limit.limit}) : this.say('notice', {title}); + }); constructor() { effect(() => this.state.set(this.wasRequested(this.view().storageKey) ? 'sent' : 'idle')); 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..aa8d94df9f 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()}) }} @@ -31,7 +43,7 @@ } } - @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 +67,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..e78e911fd2 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,6 +1,7 @@ // 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'; @@ -22,6 +23,9 @@ export class AiPlanComponent { progress = input(null); gate = input(false); autoApprove = input(false); + replacedAfter = input(null); + + open = signal(false); @Output() run = new EventEmitter(); @Output() change = new EventEmitter(); @@ -29,9 +33,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) => { @@ -62,6 +69,17 @@ export class AiPlanComponent { done = computed(() => this.marks().filter(mark => mark === 'done').length); + finished = computed(() => !this.gate() && !!this.progress() && this.marks().every(mark => mark === 'done' || mark === 'off')); + + 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()}); + }); + 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..3c76012af8 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,37 +70,40 @@ @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 (step.secret && isFree(step)) { +
+ + + +
+ } @else if (isNumber(step) && isFree(step)) { + } @else if (isFree(step)) {
- {{ 'ai-assistant.question.your-answer' | translate }} - @if (step.secret) { - - } @else { - - } + {{ otherLabel(step) }} +
@@ -117,61 +120,117 @@
- } @else if (isChipRow(step)) { + } @else if (isColor(step)) { +
+ @for (option of step.options; track option.label) { + + } + +
+ } @else if (step.date) {
@for (option of step.options; track option.label) { + [disabled]="disabled()" (click)="pick(step, option.label)">{{ option.label }} } - @if (isColor(step)) { - - } @else { - + @if (calendar(); as cal) { + @if (cal.id === step.id) { + + } + } + +
+ } @else if (isChipRow(step)) { +
+ @for (option of step.options; track option.label) { + } +
- @if (isOther(step) && !isColor(step)) { + @if (isOther(step) && isNumber(step)) { + + } @else if (isOther(step)) { } @else if (chosenHint(step); as hint) {

{{ hint }}

} } @else { -
@for (option of step.options; track option.label) { } @@ -179,3 +238,32 @@ }
+ + +
+ + + @if (step.number?.unit) { + {{ step.number.unit }} + } + +
+
+ + + + 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..b628a0d0ae 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,6 +1,6 @@ // 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 { Component, computed, ElementRef, EventEmitter, HostListener, inject, input, Output, Renderer2, signal, ViewChild, ViewContainerRef } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { AiQuestion, AiQuestionAnswer } from '@shared/models/solution-creator.models'; import { TbPopoverService } from '@shared/components/popover.service'; @@ -48,6 +48,49 @@ export function aiAnswersOf(content: string | undefined, questions: AiQuestion[] return answers.length ? answers : null; } +interface AiCalendarState { + id: string; + y: number; + m: number; + sel: number; + time: string; + error: boolean; + up: boolean; + shift: number; +} + +interface AiCalendarDay { + date: Date; + time: number; + day: number; + past: boolean; + today: boolean; + selected: boolean; + label: string; +} + +function startOfDay(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()); +} + +function sayNumber(value: number): string { + return String(value).replace('-', '\u2212'); +} + +function readNumber(text: string): number { + return parseFloat(String(text).replace(/[,\s]/g, '').replace('\u2212', '-')); +} + +function readTime(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; +} + function recommendedOf(question: AiQuestion): string[] { const recommended = Array.isArray(question.recommended) ? question.recommended : question.recommended ? [question.recommended] : []; return recommended.filter(label => question.options.some(option => option.label === label)); @@ -78,6 +121,11 @@ export class AiQuestionComponent { at = signal(0); move = signal<'next' | 'back' | null>(null); private picked = signal>({}); + shownSecret = signal(null); + calendar = signal(null); + @ViewChild('calPop') calPop?: ElementRef; + private calTrigger: HTMLElement | null = null; + private days: Record = {}; private chosen = signal>({}); private typed = signal>({}); @@ -89,7 +137,7 @@ 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 { @@ -116,7 +164,232 @@ export class AiQuestionComponent { } otherText(question: AiQuestion): string { - return this.typed()[question.id] ?? ''; + const typed = this.typed()[question.id]; + if (typed !== undefined) { + return typed; + } + const suggested = this.isNumber(question) ? question.number?.suggested : undefined; + return suggested !== undefined && suggested !== null ? sayNumber(suggested) : ''; + } + + 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'); + } + + isNumber(question: AiQuestion): boolean { + return !!question.number && !question.multiple && !question.secret && !question.date && !this.isColor(question); + } + + numSize(question: AiQuestion): 's' | 'm' | 'l' { + return question.number?.size === 'short' ? 's' : question.number?.size === 'medium' ? 'm' : 'l'; + } + + stepOf(question: AiQuestion): number { + return question.number?.step && question.number.step > 0 ? question.number.step : 1; + } + + stepNumber(question: AiQuestion, input: HTMLInputElement, direction: number): void { + if (this.disabled()) { + return; + } + const current = readNumber(input.value); + const base = isNaN(current) ? (question.number?.suggested ?? 0) : current; + input.value = sayNumber(Math.round((base + direction * this.stepOf(question)) * 100) / 100); + this.type(question, input); + input.focus(); + } + + toggleSecret(question: AiQuestion, input: HTMLInputElement): void { + this.shownSecret.update(id => id === question.id ? null : question.id); + input.focus(); + } + + toggleCalendar(question: AiQuestion, chip: HTMLElement): void { + if (this.disabled()) { + return; + } + if (this.calendar()?.id === question.id) { + this.closeCalendar(false); + return; + } + const today = startOfDay(new Date()); + const chosen = this.days[question.id]; + const day = chosen ? new Date(chosen.date) : new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); + this.calTrigger = chip; + this.calendar.set({id: question.id, y: day.getFullYear(), m: day.getMonth(), sel: day.getTime(), time: chosen?.time ?? '9:00', error: false, up: false, shift: 0}); + setTimeout(() => { + this.placeCalendar(); + this.focusDay(); + }); + } + + closeCalendar(back: boolean): void { + this.calendar.set(null); + if (back) { + this.calTrigger?.focus(); + } + } + + canGoBack(): boolean { + const cal = this.calendar(); + const today = new Date(); + return !!cal && (cal.y > today.getFullYear() || (cal.y === today.getFullYear() && cal.m > today.getMonth())); + } + + shiftMonth(by: number): void { + this.calendar.update(cal => { + if (!cal) { + return cal; + } + const first = new Date(cal.y, cal.m + by, 1); + return {...cal, y: first.getFullYear(), m: first.getMonth()}; + }); + } + + monthTitle(): string { + const cal = this.calendar(); + return cal ? new Date(cal.y, cal.m, 1).toLocaleDateString(this.locale(), {month: 'long', year: 'numeric'}) : ''; + } + + weekdays(): string[] { + return Array.from({length: 7}, (_, index) => new Date(2024, 0, 1 + index).toLocaleDateString(this.locale(), {weekday: 'short'}).slice(0, 2)); + } + + leadDays(): number[] { + const cal = this.calendar(); + return cal ? Array.from({length: (new Date(cal.y, cal.m, 1).getDay() + 6) % 7}, (_, index) => index) : []; + } + + monthDays(): AiCalendarDay[] { + const cal = this.calendar(); + if (!cal) { + return []; + } + const today = startOfDay(new Date()).getTime(); + const count = new Date(cal.y, cal.m + 1, 0).getDate(); + return Array.from({length: count}, (_, index) => { + const date = new Date(cal.y, cal.m, index + 1); + const time = date.getTime(); + const label = date.toLocaleDateString(this.locale(), {weekday: 'long', day: 'numeric', month: 'long'}); + return {date, time, day: index + 1, past: time < today, today: time === today, selected: time === cal.sel, + label: time === today ? this.translate.instant('ai-assistant.question.today', {day: label}) : label}; + }); + } + + selectDay(date: Date): void { + this.calendar.update(cal => cal ? {...cal, sel: date.getTime()} : cal); + setTimeout(() => this.focusDay()); + } + + calendarKey(event: KeyboardEvent): void { + const cal = this.calendar(); + if (!cal || !(event.target as HTMLElement).classList.contains('k-cal-d')) { + return; + } + const weekday = (new Date(cal.sel).getDay() + 6) % 7; + const by = {ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7, Home: -weekday, End: 6 - weekday}[event.key]; + if (by === undefined) { + return; + } + event.preventDefault(); + const current = new Date(cal.sel); + const next = new Date(current.getFullYear(), current.getMonth(), current.getDate() + by); + if (next.getTime() < startOfDay(new Date()).getTime()) { + return; + } + this.calendar.set({...cal, sel: next.getTime(), y: next.getFullYear(), m: next.getMonth()}); + setTimeout(() => this.focusDay()); + } + + typeTime(value: string): void { + this.calendar.update(cal => cal ? {...cal, time: value, error: false} : cal); + } + + settleTime(input: HTMLInputElement): void { + const time = readTime(input.value); + if (time) { + input.value = time; + this.typeTime(time); + } + } + + stepTime(input: HTMLInputElement, minutes: number): void { + const time = readTime(input.value); + if (!time) { + return; + } + const [hours, mins] = time.split(':').map(Number); + const total = (((hours * 60 + mins + minutes) % 1440) + 1440) % 1440; + input.value = `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`; + this.typeTime(input.value); + } + + applyDay(question: AiQuestion, input: HTMLInputElement): void { + const cal = this.calendar(); + if (!cal) { + return; + } + const time = readTime(input.value); + if (!time) { + this.calendar.set({...cal, error: true}); + input.focus(); + return; + } + const day = new Date(cal.sel); + this.days[question.id] = {date: cal.sel, time}; + this.picked.update(values => ({...values, [question.id]: null})); + this.typed.update(values => ({...values, [question.id]: + `${day.toLocaleDateString(this.locale(), {weekday: 'long', day: 'numeric', month: 'short'})}, ${time}`})); + this.closeCalendar(true); + } + + @HostListener('document:mousedown', ['$event']) + onDocumentDown(event: MouseEvent): void { + if (!this.calendar()) { + return; + } + const target = event.target as Node; + if (!this.calPop?.nativeElement.contains(target) && !this.calTrigger?.contains(target)) { + this.closeCalendar(false); + } + } + + private placeCalendar(): void { + const pop = this.calPop?.nativeElement; + const cal = this.calendar(); + if (!pop || !cal) { + return; + } + const box = pop.getBoundingClientRect(); + let top = 0; + let bottom = innerHeight; + let left = 0; + let right = innerWidth; + for (let element = pop.parentElement; element && element !== document.body; element = element.parentElement) { + const style = getComputedStyle(element); + if (/(auto|scroll|hidden|clip)/.test(style.overflowY + style.overflowX)) { + const rect = element.getBoundingClientRect(); + top = Math.max(top, rect.top); + bottom = Math.min(bottom, rect.bottom); + left = Math.max(left, rect.left); + right = Math.min(right, rect.right); + } + } + const anchor = pop.parentElement.getBoundingClientRect(); + const up = box.bottom > bottom - 8 && anchor.top - top - 6 >= box.height; + const over = box.right - (right - 8); + const shift = over > 0 ? -Math.min(over, Math.max(0, box.left - left - 8)) : 0; + this.calendar.set({...cal, up, shift}); + } + + private focusDay(): void { + const pop = this.calPop?.nativeElement; + (pop?.querySelector('.k-cal-d[aria-pressed="true"]') as HTMLElement ?? pop?.querySelector('.k-cal-d:not([disabled])') as HTMLElement)?.focus({preventScroll: true}); + } + + private locale(): string { + return (this.translate.currentLang || 'en_US').replace('_', '-'); } ready(question: AiQuestion): boolean { @@ -274,6 +547,10 @@ export class AiQuestionComponent { } return values.length ? values.join(MULTI_SEPARATOR) : this.translate.instant('ai-assistant.question.none'); } + if (this.isOther(question) && this.isNumber(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-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..933d011e7d 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 @@ -27,6 +27,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 +168,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) @@ -323,9 +324,6 @@ export class AiRecordLoaderService { } 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..dd741ea36d 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 @@ -34,6 +34,7 @@ export interface AiRecordView { key: string; entityType: string; alarmRule: boolean; + groupType?: string; name: string; meta: string; badge?: string; @@ -99,5 +100,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: part.replace(/(^|[\s(=:])-(?=\d)/g, '$1\u2212'), 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..be1eb5e372 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 @@ -34,6 +34,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 +50,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 +64,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; +} + +export 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 +112,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 +187,95 @@ 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'; +const SEVERITY_MARK = /\{(CRITICAL|MAJOR|MINOR|WARNING|INDETERMINATE)\}/; -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'); +export function aiHasSeverityMarks(text: string | undefined): boolean { + return !!text && SEVERITY_MARK.test(text); +} + +export function aiPlainSeverities(text: string, label: (severity: string) => string): string { + return text.replace(new RegExp(SEVERITY_MARK.source, 'g'), (_, severity: string) => label(severity)); +} + +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-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-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/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) : '' }}
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 70939b8e2d..c730df61ac 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 @@ -132,6 +132,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { 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(); @@ -1133,14 +1134,20 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { 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); 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 7f5753d97b..b004057cf1 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 @@ -136,11 +136,11 @@
@if (pill(); as current) {
+ @if (isOther(step)) { +
+ + + + + +
+ @if (hexWrong()[step.id]) { + + } + } } @else if (step.date) {
@for (option of step.options; track option.label) { @@ -256,11 +274,14 @@ -
} @@ -70,11 +70,11 @@ } }
- - 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 e675da8bf2..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 @@ -69,9 +69,7 @@ const VALUE_TOKENS: Record = { const CODE_FIELDS = new Set(['arguments', 'expression', 'output']); -const OWN_HEAD_KINDS = new Set(['MY_PROFILE', 'MY_TWO_FACTOR', 'RELATION']); -const THE_HEAD_KINDS = new Set(['WHITE_LABELING', 'TWO_FACTOR_SETTINGS', 'MAIL_SERVER', 'PLATFORM_SETTINGS', 'NOTIFICATION_SETTINGS', - 'NOTIFICATION_PREFERENCES', 'CUSTOM_MENU', 'CUSTOM_TRANSLATION']); +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']); @@ -157,7 +155,7 @@ const OWN_TYPE_LABELS = new Set(['ALARM_RULE', 'DASHBOARD_WIDGET', 'DASHBOARD_ST const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); -export function aiApproveLabel(data: ToolExecutionRequested): string { +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) { @@ -179,7 +177,7 @@ export function aiApproveLabel(data: ToolExecutionRequested): string { } } -export function aiReviewTypeLabel(translate: TranslateService, entityType: string): string { +function aiReviewTypeLabel(translate: TranslateService, entityType: string): string { if (OWN_TYPE_LABELS.has(entityType)) { return translate.instant('ai-assistant.review.type.' + entityType); } @@ -187,21 +185,21 @@ export function aiReviewTypeLabel(translate: TranslateService, entityType: strin return translation ? translate.instant(translation) : entityType; } -export function aiChangeHead(translate: TranslateService, data: ToolExecutionRequested): string | null { +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 = translate.instant(label); - if (review.verb && REVIEW_VERBS.has(review.verb) && !['install', 'delete', 'update', 'acknowledge', 'clear', 'assign', 'unassign'].includes(review.verb)) { - return verb; + const verb = label.split('.').pop(); + if (!HEAD_VERBS.has(verb)) { + return translate.instant(label); } - const kind = review.detail === 'alarm-rule' ? translate.instant('ai-assistant.review.type.ALARM_RULE') : aiReviewTypeLabel(translate, review.entityType); - const noun = /^[A-Z][a-z]/.test(kind) ? kind.charAt(0).toLowerCase() + kind.slice(1) : kind; - const form = OWN_HEAD_KINDS.has(review.entityType) ? 'own' : THE_HEAD_KINDS.has(review.entityType) ? 'the' - : /^(?:[aeio]|u(?![sn]i|s[eu])|[AEFHILMNORX][A-Z])/.test(noun) ? 'an' : 'a'; - return translate.instant('ai-assistant.review.head-change.' + form, {verb, kind: noun}); + 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 { @@ -225,6 +223,8 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked { @Input() answered = false; + @Input() busy = false; + @ViewChild('denyInput') denyInput: ElementRef; @Output() approvalAction = new EventEmitter(); 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 0b1b87ef77..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 @@ -99,7 +99,7 @@
+ [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])) { @@ -117,11 +117,7 @@
@if ($index === retryIndex) { -
- -
+
}
@@ -143,6 +139,7 @@ [completedExecution]="getCompletedExecution(msg)" [autoApprove]="autoApprove" [answered]="!!denyReasons[getApprovalData(msg).executionId]" + [busy]="loading" (approvalAction)="approval($event)" (answerLater)="answerLater.emit($event)"> @@ -153,11 +150,7 @@

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

@if ($last && !loading && retry.observed) { -
- -
+
}
} @else { @@ -310,20 +303,7 @@
- @switch (dock.state) { - @case ('stopped') { - - } - @case ('listen') { - - } - @case ('run') { - - } - @default { - - } - } + @if (dock.kind === 'hand' && dock.state !== 'stopped') {{{ 'ai-assistant.plan.you' | translate }}}{{ dock.text }} @if (dock.count) { {{ dock.count }} @@ -354,3 +334,9 @@ }
} + + + + 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 c730df61ac..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,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, inject, Input, OnChanges, OnDestroy, Output, QueryList, SimpleChanges, ViewChildren } from '@angular/core'; +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'; @@ -39,6 +40,7 @@ import { aiGroupableRead, isHiddenAiAction, isKitCardTool, + aiPlanStatus, PROPOSE_PLAN_TOOL, SUGGEST_PROMPTS_TOOL, UPDATE_PLAN_TOOL @@ -68,7 +70,7 @@ export interface AnswerReportEvent { comment?: string; } import { aiFenceMeta, announceCopied, decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; -import { AiHandOverComponent, AiHandOverWait } from '@home/components/ai/ai-hand-over.component'; +import { AiHandOverWait } from '@home/components/ai/ai-hand-over.component'; import { aiDetailNames, AiDetailNames } from '@home/components/ai/ai-action-detail.models'; import { decorateFileChips, decorateHints, decorateLinks, decorateReferences, decorateSeverities, decorateValues } from '@home/components/ai/ai-references'; import { AlarmSeverity, alarmSeverityTranslations } from '@shared/models/alarm.models'; @@ -128,7 +130,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Output() dockShown = new EventEmitter(); @Output() listen = new EventEmitter(); @Input() slotTaken = false; - @ViewChildren(AiHandOverComponent) handOverCards: QueryList; + 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; @@ -516,8 +520,8 @@ 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) { if (wasNearBottom) { @@ -635,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 { @@ -748,7 +752,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } clockText(time?: number): string { - return new Date(time ?? Date.now()).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}); + return aiClockText(time, this.translate.currentLang); } stoppedText(index: number, content: string): string { @@ -802,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; } } @@ -1032,8 +1036,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { } private planFinished(plan: {steps: AiPlanStep[]; progress: AiPlanProgress | null}): boolean { - const progress = plan.progress; - return !!progress && plan.steps.every((_, index) => progress.done.includes(index + 1) || progress.skipped.includes(index + 1)); + return aiPlanStatus(plan.steps, plan.progress).finished; } private findAnswers(): Record { @@ -1041,7 +1044,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { 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) { @@ -1098,7 +1101,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { dockTest(): void { const id = this.dock ? (this.messages[this.dock.index] as ActionChatMessage)?.data.executionId : null; - this.handOverCards?.find(card => card.cardId() === id)?.sendTest(); + if (id) { + this.testRequests = {...this.testRequests, [id]: (this.testRequests[id] ?? 0) + 1}; + } } private findDock(): AiDockRow | null { @@ -1114,12 +1119,10 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { if (!plan?.progress || plan.replacedAfter !== null || this.planFinished(plan)) { return null; } - const progress = plan.progress; - const counted = plan.steps.filter((_, index) => !progress.skipped.includes(index + 1)); - const now = progress.now ?? plan.steps.findIndex((_, index) => !progress.done.includes(index + 1) && !progress.skipped.includes(index + 1)) + 1; - const step = plan.steps[Math.max(0, now - 1)]; + 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: progress.done.length, count: counted.length})}; + count: this.translate.instant('ai-assistant.plan.done-of', {done: status.done, count: status.counted})}; } private followDock(): void { 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 b004057cf1..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 @@ -154,14 +154,16 @@ } @else if (limitOut(); as platformLimit) { + } @else if (notice(); as current) { +
+ {{ current.text }} +
} @else if (keptEdits(); as kept) {
{{ ('ai-assistant.kept-edits.' + kept.kind) | translate }} -
- } @else if (notice(); as current) { -
- {{ current.text }} +
} }
- + } + +
+@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.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts index d56d2e11e9..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'; @@ -27,6 +28,8 @@ function localOs(): string { } 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; @@ -41,7 +44,7 @@ export function aiHandOverProgress(cardId: string): AiHandOverProgress | null { return null; } try { - const saved = localStorage.getItem(PROGRESS_KEY + cardId); + const saved = readStored(PROGRESS_KEY + cardId); return saved ? JSON.parse(saved) as AiHandOverProgress : null; } catch { return null; @@ -52,11 +55,16 @@ function aiSaveHandOverProgress(cardId: string, progress: AiHandOverProgress): v if (!cardId) { return; } + writeStored(PROGRESS_KEY + cardId, JSON.stringify(progress)); + let saved: string[] = []; try { - localStorage.setItem(PROGRESS_KEY + cardId, JSON.stringify(progress)); + saved = JSON.parse(readStored(PROGRESS_INDEX) ?? '[]'); } catch { - return; + 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({ @@ -71,6 +79,17 @@ export class AiHandOverComponent implements AfterViewChecked { 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(); @@ -92,7 +111,9 @@ 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(''); 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 c01b6e7e06..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 @@ -23,6 +23,8 @@ {{ 'subscription.upgrade-plan' | translate }} } } +
@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 b356f1bbef..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; @@ -86,13 +85,11 @@ export class AiLimitOutComponent { } private count(value: number): string { - return value.toLocaleString(this.translate.currentLang?.replace('_', '-') || undefined); + 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) { @@ -100,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: this.count(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) @@ -116,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) @@ -137,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) @@ -148,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 aa8d94df9f..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 @@ -5,7 +5,7 @@ --> @if (folded()) { -
- @if (isFree(step) && isColor(step)) { -
- -
- } @else if (step.secret && isFree(step)) { -
- - - - -
- } @else if (isNumber(step) && isFree(step)) { - - } @else if (isFree(step)) { -
-
- - {{ otherLabel(step) }} - - + @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 (isColor(step)) { -
- @for (option of step.options; track option.label) { - - } - -
- @if (isOther(step)) { -
- - - - - -
- @if (hexWrong()[step.id]) { - - } } - } @else if (step.date) { -
- @for (option of step.options; track option.label) { - - } - - + } + - @if (calendar(); as cal) { - @if (cal.id === step.id) { - - } +
+ } + @case ('chips') { +
+ @for (option of step.options; track option.label) { + } - -
- } @else if (isChipRow(step)) { -
- @for (option of step.options; track option.label) { - + +
+ @if (isOther(step) && step.number) { + + } @else if (isOther(step)) { + + } @else if (chosenHint(step); as hint) { +

{{ hint }}

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

{{ hint }}

} - } @else { -
- @for (option of step.options; track option.label) { - + } + -
- } -
- - - -
- - - @if (step.number?.unit) { - {{ step.number.unit }} + } } -
- - - - 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 853b6e9c8f..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, ElementRef, EventEmitter, HostListener, inject, input, Output, Renderer2, signal, ViewChild, 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'); } @@ -48,49 +53,6 @@ export function aiAnswersOf(content: string | undefined, questions: AiQuestion[] return answers.length ? answers : null; } -interface AiCalendarState { - id: string; - y: number; - m: number; - sel: number; - time: string; - error: boolean; - up: boolean; - shift: number; -} - -interface AiCalendarDay { - date: Date; - time: number; - day: number; - past: boolean; - today: boolean; - selected: boolean; - label: string; -} - -function startOfDay(date: Date): Date { - return new Date(date.getFullYear(), date.getMonth(), date.getDate()); -} - -function sayNumber(value: number): string { - return String(value).replace('-', '\u2212'); -} - -function readNumber(text: string): number { - return parseFloat(String(text).replace(/[,\s]/g, '').replace('\u2212', '-')); -} - -function readTime(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; -} - function recommendedOf(question: AiQuestion): string[] { const recommended = Array.isArray(question.recommended) ? question.recommended : question.recommended ? [question.recommended] : []; return recommended.filter(label => question.options.some(option => option.label === label)); @@ -99,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 { @@ -112,22 +75,18 @@ export class AiQuestionComponent { @Output() skip = new EventEmitter(); private translate = inject(TranslateService); - private elementRef: ElementRef = inject(ElementRef); private popoverService = inject(TbPopoverService); private renderer = inject(Renderer2); private viewContainerRef = inject(ViewContainerRef); colorOf = aiColorOf; + isFree = aiIsFree; at = signal(0); move = signal<'next' | 'back' | null>(null); + dayOpen = signal(null); private picked = signal>({}); - shownSecret = signal(null); - hexWrong = signal>({}); - calendar = signal(null); - @ViewChild('calPop') calPop?: ElementRef; - private calTrigger: HTMLElement | null = null; - private days: Record = {}; + private days: Record = {}; private chosen = signal>({}); private typed = signal>({}); @@ -142,8 +101,8 @@ export class AiQuestionComponent { 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 { @@ -170,8 +129,8 @@ export class AiQuestionComponent { if (typed !== undefined) { return typed; } - const suggested = this.isNumber(question) ? question.number?.suggested : undefined; - return suggested !== undefined && suggested !== null ? sayNumber(suggested) : ''; + const suggested = aiIsNumber(question) ? question.number?.suggested : undefined; + return suggested !== undefined && suggested !== null ? aiSayNumber(suggested) : ''; } otherLabel(question: AiQuestion): string { @@ -179,233 +138,81 @@ export class AiQuestionComponent { : question.date ? 'ai-assistant.question.another-day' : 'ai-assistant.question.other'); } - isNumber(question: AiQuestion): boolean { - return !!question.number && !question.multiple && !question.secret && !question.date && !this.isColor(question); - } - - numSize(question: AiQuestion): 's' | 'm' | 'l' { - return question.number?.size === 'short' ? 's' : question.number?.size === 'medium' ? 'm' : 'l'; - } - - stepOf(question: AiQuestion): number { - return question.number?.step && question.number.step > 0 ? question.number.step : 1; + colorValue(question: AiQuestion): string { + const picked = this.picked()[question.id]; + return picked === null || aiIsFree(question) ? this.typed()[question.id] ?? '' : picked ?? this.defaultOf(question); } - stepNumber(question: AiQuestion, input: HTMLInputElement, direction: number): void { - if (this.disabled()) { - return; + 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})); } - const current = readNumber(input.value); - const base = isNaN(current) ? (question.number?.suggested ?? 0) : current; - input.value = sayNumber(Math.round((base + direction * this.stepOf(question)) * 100) / 100); - this.type(question, input); - input.focus(); } - toggleSecret(question: AiQuestion, input: HTMLInputElement): void { - this.shownSecret.update(id => id === question.id ? null : question.id); - input.focus(); + setTyped(question: AiQuestion, value: string): void { + this.pickOther(question); + this.typed.update(values => ({...values, [question.id]: value})); } - toggleCalendar(question: AiQuestion, chip: HTMLElement): void { + openDay(question: AiQuestion, chip: HTMLElement): void { if (this.disabled()) { return; } - if (this.calendar()?.id === question.id) { - this.closeCalendar(false); + if (this.popoverService.hasPopover(chip)) { + this.popoverService.hidePopover(chip); return; } - const today = startOfDay(new Date()); - const chosen = this.days[question.id]; - const day = chosen ? new Date(chosen.date) : new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); - this.calTrigger = chip; - this.calendar.set({id: question.id, y: day.getFullYear(), m: day.getMonth(), sel: day.getTime(), time: chosen?.time ?? '9:00', error: false, up: false, shift: 0}); - setTimeout(() => { - this.placeCalendar(); - this.focusDay(); - }); - } - - closeCalendar(back: boolean): void { - this.calendar.set(null); - if (back) { - this.calTrigger?.focus(); - } - } - - canGoBack(): boolean { - const cal = this.calendar(); const today = new Date(); - return !!cal && (cal.y > today.getFullYear() || (cal.y === today.getFullYear() && cal.m > today.getMonth())); - } - - shiftMonth(by: number): void { - this.calendar.update(cal => { - if (!cal) { - return cal; - } - const first = new Date(cal.y, cal.m + by, 1); - return {...cal, y: first.getFullYear(), m: first.getMonth()}; + const chosen = this.days[question.id]; + const popover = this.popoverService.displayPopover({ + trigger: chip, + renderer: this.renderer, + hostView: this.viewContainerRef, + componentType: AiDatePanelComponent, + preferredPlacement: ['bottomLeft', 'bottom', 'topLeft', 'top'], + context: { + selected: chosen?.date ?? new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1), + time: chosen?.time ?? '9:00' + }, + showCloseButton: false, + popoverContentStyle: {padding: '8px 12px 12px'}, + isModal: true }); - } - - monthTitle(): string { - const cal = this.calendar(); - return cal ? new Date(cal.y, cal.m, 1).toLocaleDateString(this.locale(), {month: 'long', year: 'numeric'}) : ''; - } - - weekdays(): string[] { - return Array.from({length: 7}, (_, index) => new Date(2024, 0, 1 + index).toLocaleDateString(this.locale(), {weekday: 'short'}).slice(0, 2)); - } - - leadDays(): number[] { - const cal = this.calendar(); - return cal ? Array.from({length: (new Date(cal.y, cal.m, 1).getDay() + 6) % 7}, (_, index) => index) : []; - } - - monthDays(): AiCalendarDay[] { - const cal = this.calendar(); - if (!cal) { - return []; - } - const today = startOfDay(new Date()).getTime(); - const count = new Date(cal.y, cal.m + 1, 0).getDate(); - return Array.from({length: count}, (_, index) => { - const date = new Date(cal.y, cal.m, index + 1); - const time = date.getTime(); - const label = date.toLocaleDateString(this.locale(), {weekday: 'long', day: 'numeric', month: 'long'}); - return {date, time, day: index + 1, past: time < today, today: time === today, selected: time === cal.sel, - label: time === today ? this.translate.instant('ai-assistant.question.today', {day: label}) : label}; + this.dayOpen.set(question.id); + popover.tbHideStart.subscribe(() => this.dayOpen.set(null)); + popover.tbComponentRef.instance.popover = popover; + 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(); + chip.focus(); }); } - selectDay(date: Date): void { - this.calendar.update(cal => cal ? {...cal, sel: date.getTime()} : cal); - setTimeout(() => this.focusDay()); - } - - calendarKey(event: KeyboardEvent): void { - const cal = this.calendar(); - if (!cal || !(event.target as HTMLElement).classList.contains('k-cal-d')) { - return; - } - const weekday = (new Date(cal.sel).getDay() + 6) % 7; - const by = {ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7, Home: -weekday, End: 6 - weekday}[event.key]; - if (by === undefined) { - return; - } - event.preventDefault(); - const current = new Date(cal.sel); - const next = new Date(current.getFullYear(), current.getMonth(), current.getDate() + by); - if (next.getTime() < startOfDay(new Date()).getTime()) { - return; - } - this.calendar.set({...cal, sel: next.getTime(), y: next.getFullYear(), m: next.getMonth()}); - setTimeout(() => this.focusDay()); - } - - typeTime(value: string): void { - this.calendar.update(cal => cal ? {...cal, time: value, error: false} : cal); - } - - settleTime(input: HTMLInputElement): void { - const time = readTime(input.value); - if (time) { - input.value = time; - this.typeTime(time); - } - } - - stepTime(input: HTMLInputElement, minutes: number): void { - const time = readTime(input.value); - if (!time) { - return; - } - const [hours, mins] = time.split(':').map(Number); - const total = (((hours * 60 + mins + minutes) % 1440) + 1440) % 1440; - input.value = `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`; - this.typeTime(input.value); - } - - applyDay(question: AiQuestion, input: HTMLInputElement): void { - const cal = this.calendar(); - if (!cal) { - return; - } - const time = readTime(input.value); - if (!time) { - this.calendar.set({...cal, error: true}); - input.focus(); - return; - } - const day = new Date(cal.sel); - this.days[question.id] = {date: cal.sel, time}; - this.picked.update(values => ({...values, [question.id]: null})); - this.typed.update(values => ({...values, [question.id]: - `${day.toLocaleDateString(this.locale(), {weekday: 'long', day: 'numeric', month: 'short'})}, ${time}`})); - this.closeCalendar(true); - } - - @HostListener('document:mousedown', ['$event']) - onDocumentDown(event: MouseEvent): void { - if (!this.calendar()) { - return; - } - const target = event.target as Node; - if (!this.calPop?.nativeElement.contains(target) && !this.calTrigger?.contains(target)) { - this.closeCalendar(false); - } - } - - private placeCalendar(): void { - const pop = this.calPop?.nativeElement; - const cal = this.calendar(); - if (!pop || !cal) { - return; - } - const box = pop.getBoundingClientRect(); - let top = 0; - let bottom = innerHeight; - let left = 0; - let right = innerWidth; - for (let element = pop.parentElement; element && element !== document.body; element = element.parentElement) { - const style = getComputedStyle(element); - if (/(auto|scroll|hidden|clip)/.test(style.overflowY + style.overflowX)) { - const rect = element.getBoundingClientRect(); - top = Math.max(top, rect.top); - bottom = Math.min(bottom, rect.bottom); - left = Math.max(left, rect.left); - right = Math.min(right, rect.right); - } - } - const anchor = pop.parentElement.getBoundingClientRect(); - const up = box.bottom > bottom - 8 && anchor.top - top - 6 >= box.height; - const over = box.right - (right - 8); - const shift = over > 0 ? -Math.min(over, Math.max(0, box.left - left - 8)) : 0; - this.calendar.set({...cal, up, shift}); - } - - private focusDay(): void { - const pop = this.calPop?.nativeElement; - (pop?.querySelector('.k-cal-d[aria-pressed="true"]') as HTMLElement ?? pop?.querySelector('.k-cal-d:not([disabled])') as HTMLElement)?.focus({preventScroll: true}); - } - private locale(): string { - return (this.translate.currentLang || 'en_US').replace('_', '-'); + return aiLocale(this.translate.currentLang); } ready(question: AiQuestion): boolean { if (question.multiple && !this.isFree(question)) { return true; } - if (this.isOther(question) && this.isColor(question)) { - return !!this.hexOf(this.otherText(question)); + 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 && !this.isFree(question) && (this.isChipRow(question) || question.options.length <= 3))); + !question.multiple && !aiIsFree(question) && (aiKindOf(question) === 'chips' || aiKindOf(question) === 'color' || question.options.length <= 3))); allReady = computed(() => this.questions().every(question => this.ready(question))); @@ -415,11 +222,6 @@ export class AiQuestionComponent { } } - 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; @@ -429,89 +231,6 @@ export class AiQuestionComponent { this.picked.update(values => ({...values, [question.id]: label})); } - isColor(question: AiQuestion): boolean { - return !question.multiple && !question.secret - && (!!question.color || (!!question.options?.length && question.options.every(option => !!aiColorOf(option.label)))); - } - - hexOf(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(); - } - - hexDigits(question: AiQuestion): string { - return this.otherText(question).replace(/^#/, ''); - } - - openHex(question: AiQuestion, field: HTMLInputElement | undefined): void { - if (this.disabled()) { - return; - } - if (!this.isOther(question)) { - this.picked.update(values => ({...values, [question.id]: null})); - } - setTimeout(() => (field ?? this.elementRef.nativeElement.querySelector('.k-hex-in'))?.focus()); - } - - typeHex(question: AiQuestion, field: HTMLInputElement): void { - if (field.value.startsWith('#')) { - field.value = field.value.slice(1); - } - this.pickOther(question); - this.typed.update(values => ({...values, [question.id]: field.value.trim()})); - if (this.hexOf(field.value)) { - this.hexWrong.update(values => ({...values, [question.id]: false})); - } - } - - checkHex(question: AiQuestion, field: HTMLInputElement): void { - this.hexWrong.update(values => ({...values, [question.id]: !!field.value.trim() && !this.hexOf(field.value)})); - } - - hexEnter(question: AiQuestion, event: Event, field: HTMLInputElement): void { - if ((event as KeyboardEvent).isComposing) { - return; - } - event.preventDefault(); - if (this.hexOf(field.value)) { - this.onEnter(event); - } else { - this.hexWrong.update(values => ({...values, [question.id]: true})); - } - } - - openColorPicker(question: AiQuestion, 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.hexOf(this.otherText(question)) ?? '#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(question, field); - }); - popover.tbComponentRef.instance.colorCancelDialog.subscribe(() => popover.hide()); - } - pickOther(question: AiQuestion): void { if (question.multiple || this.isFree(question)) { return; @@ -591,13 +310,13 @@ export class AiQuestionComponent { } return values.length ? values.join(MULTI_SEPARATOR) : this.translate.instant('ai-assistant.question.none'); } - if (this.isOther(question) && this.isNumber(question)) { + 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; } - if (this.isOther(question) && this.isColor(question)) { - return this.hexOf(this.otherText(question)) ?? ''; - } 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-loader.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts index 933d011e7d..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'; @@ -320,7 +321,7 @@ export class AiRecordLoaderService { } private locale(): string | undefined { - return this.translate.currentLang?.replace('_', '-') || undefined; + return aiLocale(this.translate.currentLang); } private time(ts: number): string { 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 dd741ea36d..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'; @@ -101,5 +102,5 @@ 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.replace(/(^|[\s(=:])-(?=\d)/g, '$1\u2212'), code: false}); + : {text: aiTrueMinus(part), code: false}); } 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 be1eb5e372..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'; @@ -80,7 +81,7 @@ function svgIcon(name: string): Promise { return icon; } -export function aiIconElement(name: string, className: string): HTMLElement { +function aiIconElement(name: string, className: string): HTMLElement { const icon = document.createElement('span'); icon.setAttribute('aria-hidden', 'true'); if (!name.includes(':')) { @@ -189,16 +190,11 @@ function lastText(root: Node): Text | null { 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'; -const SEVERITY_MARK = /\{(CRITICAL|MAJOR|MINOR|WARNING|INDETERMINATE)\}/; -export function aiHasSeverityMarks(text: string | undefined): boolean { +function aiHasSeverityMarks(text: string | undefined): boolean { return !!text && SEVERITY_MARK.test(text); } -export function aiPlainSeverities(text: string, label: (severity: string) => string): string { - return text.replace(new RegExp(SEVERITY_MARK.source, 'g'), (_, severity: string) => label(severity)); -} - function severityChip(severity: string, label: (severity: string) => string): HTMLElement { const chip = document.createElement('span'); chip.className = 'k-sev ' + severity.toLowerCase(); 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-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.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/dashboard-page/dashboard-page.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts index 4b16ab6e57..2e5c9ff137 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts @@ -1333,6 +1333,9 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC } private setEditMode(isEdit: boolean, revert: boolean) { + if (!isEdit) { + this.panelService.clearKeptEdits('dashboard'); + } this.isEdit = isEdit; this.editedWhileEmpty = false; if (this.isEdit) { diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts index 393a4b8503..fd4d1fbe34 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-License-Identifier: Apache-2.0 +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { AfterViewInit, ChangeDetectionStrategy, @@ -7,6 +8,7 @@ import { Component, ComponentRef, EventEmitter, + inject, Injector, Input, OnDestroy, @@ -59,6 +61,8 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV entitiesTableConfigValue: EntityTableConfig>; isEditValue = false; + + private aiPanelService = inject(AiAssistantPanelService); selectedTab = 0; entityTypes = EntityType; @@ -115,6 +119,9 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV } set isEdit(val: boolean) { + if (this.isEditValue && !val) { + this.aiPanelService.clearKeptEdits('entity'); + } this.isEditValue = val; if (this.entityComponent) { this.entityComponent.isEdit = val; diff --git a/ui-ngx/src/app/shared/models/ai-chat.models.ts b/ui-ngx/src/app/shared/models/ai-chat.models.ts index b638732c77..d6c7442594 100644 --- a/ui-ngx/src/app/shared/models/ai-chat.models.ts +++ b/ui-ngx/src/app/shared/models/ai-chat.models.ts @@ -225,8 +225,6 @@ export interface AiAction { edited?: boolean; progress?: string; readOnly?: boolean; - groupId?: string; - parentId?: string; stages?: string[]; } diff --git a/ui-ngx/src/app/shared/models/solution-creator.models.ts b/ui-ngx/src/app/shared/models/solution-creator.models.ts index d141aad78a..8651c0570e 100644 --- a/ui-ngx/src/app/shared/models/solution-creator.models.ts +++ b/ui-ngx/src/app/shared/models/solution-creator.models.ts @@ -66,8 +66,11 @@ export interface AiQuestionOption { hint?: string; } +export type AiQuestionKind = 'color' | 'secret' | 'number' | 'text' | 'multi' | 'date' | 'chips' | 'cards'; + export interface AiQuestion { id: string; + kind?: AiQuestionKind; label?: string; question: string; parts?: Array<{text?: string; severity?: string}>; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 47067138c9..3ae8bc4053 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -721,6 +721,7 @@ "other-color-short": "Other color", "hex-label": "{{question}} · {{label}}, as a hex", "hex-error": "A hex has three or six digits, 0–9 and A–F, such as 00897B.", + "number-error": "Enter a number, such as 12.5.", "pick-color": "Pick with the color picker" }, "ai-assistant": "AI Assistant", @@ -2412,10 +2413,6 @@ "entity-title": "{{entities}} limit reached", "notice-count": "{{title}}: {{limit}} of {{limit}}.", "notice": "{{title}}.", - "tenant-text": "Your tenant can have up to {{limit}} {{entities}}. Your system administrator can raise the limit.", - "tenant-text-plain": "Your tenant has reached its limit of {{entities}}. Your system administrator can raise the limit.", - "license-text": "Your license allows no more {{entities}}. Your system administrator can raise the limit in License management.", - "license-text-old": "You have reached the maximum {{entities}} allowed by your subscription plan. You can upgrade the plan to raise your limits.", "feature-title": "{{feature}} not included in your plan", "feature": { "white-labeling": "White labeling", @@ -2423,14 +2420,11 @@ "scheduler": "Scheduler", "reporting": "Reports" }, - "white-labeling-text": "With White labeling, your brand replaces ThingsBoard's on the login page, in the mail you send and on every page your customers work in.", - "pack-text": "It comes with the Professional Pack. Request access and your system administrator gets your request.", "license-required": "License required", "request": "Request a higher limit", "manage-license": "Manage license", "sent": "Request sent to your system administrator.", - "failed": "Couldn't send the request. Try again.", - "view-usage": "View usage" + "failed": "Couldn't send the request. Try again." }, "get-started": { "title": "Get started", @@ -2702,10 +2696,14 @@ "denied": "Denied" }, "head-change": { - "a": "{{verb}} a {{kind}}", - "an": "{{verb}} an {{kind}}", - "the": "{{verb}} the {{kind}}", - "own": "{{verb}} {{kind}}" + "create": "Create {{kind}}", + "update": "Update {{kind}}", + "delete": "Delete {{kind}}", + "install": "Install {{kind}}", + "acknowledge": "Acknowledge {{kind}}", + "clear": "Clear {{kind}}", + "assign": "Assign {{kind}}", + "unassign": "Unassign {{kind}}" }, "current": "Current", "new": "New", @@ -3053,6 +3051,87 @@ "NOTIFICATION_SETTINGS": "Notification delivery", "NOTIFICATION_PREFERENCES": "Notification preferences" }, + "kind": { + "ADMIN_SETTINGS": "an admin settings", + "AGENT": "an agent", + "AGENT_APPLICATION": "an application", + "AGENT_APP_EVENT": "an agent app event", + "AGENT_APP_PROFILE": "an application profile", + "AGENT_APP_UNIT": "an agent app unit", + "AGENT_BULK_ACTION": "a bulk action", + "AGENT_PROFILE": "an agent profile", + "AI_MODEL": "an AI model", + "ALARM": "an alarm", + "ALARM_RULE": "an alarm rule", + "API_KEY": "an API key", + "API_USAGE_STATE": "an API Usage State", + "ASSET": "an asset", + "ASSET_PROFILE": "an asset profile", + "BLOB_ENTITY": "a blob entity", + "CALCULATED_FIELD": "a calculated field", + "CONVERTER": "a data converter", + "CUSTOMER": "a customer", + "CUSTOM_MENU": "the custom menu", + "CUSTOM_TRANSLATION": "the custom translation", + "DASHBOARD": "a dashboard", + "DASHBOARD_ENTITY_ALIAS": "an entity alias", + "DASHBOARD_FILTER": "a dashboard filter", + "DASHBOARD_STATE": "a dashboard state", + "DASHBOARD_WIDGET": "a widget", + "DEVICE": "a device", + "DEVICE_PROFILE": "a device profile", + "DOMAIN": "a domain", + "EDGE": "an edge", + "ENTITY_GROUP": "an entity Group", + "ENTITY_VIEW": "an entity View", + "GROUP_PERMISSION": "a group Permission", + "IMAGE": "an image", + "INTEGRATION": "an integration", + "JOB": "a task", + "MAIL_SERVER": "the mail server", + "MAIL_TEMPLATE": "a mail template", + "MOBILE_APP": "a mobile app", + "MOBILE_APP_BUNDLE": "a mobile bundle", + "MOBILE_BUNDLE": "a mobile bundle", + "MOBILE_QR_CODE": "a mobile app QR code", + "MY_PROFILE": "your profile", + "MY_TWO_FACTOR": "your account security", + "NOTIFICATION": "a notification", + "NOTIFICATION_PREFERENCES": "the notification preferences", + "NOTIFICATION_REQUEST": "a notification request", + "NOTIFICATION_RULE": "a notification rule", + "NOTIFICATION_SETTINGS": "the notification delivery", + "NOTIFICATION_TARGET": "a notification recipient", + "NOTIFICATION_TEMPLATE": "a notification template", + "OAUTH2_CLIENT": "an OAuth 2.0 client", + "OTA_PACKAGE": "an OTA package", + "PLATFORM_SETTINGS": "the platform settings", + "QUEUE": "a queue", + "QUEUE_STATS": "a queue statistics", + "RELATION": "relations", + "REPORT": "a report", + "REPORT_COMPONENT": "a report component", + "REPORT_ENTITY_ALIAS": "a report entity alias", + "REPORT_FILTER": "a report filter", + "REPORT_TEMPLATE": "a report template", + "ROLE": "a role", + "RPC": "an RPC", + "RULE_CHAIN": "a rule chain", + "RULE_NODE": "a rule node", + "SCADA_SYMBOL": "a SCADA symbol", + "SCHEDULED_REPORT": "a scheduled report", + "SCHEDULER_EVENT": "a scheduler event", + "SECRET": "a secret storage", + "TB_RESOURCE": "a resource", + "TENANT": "a tenant", + "TENANT_PROFILE": "a tenant profile", + "TWO_FACTOR_SETTINGS": "the security settings", + "USER": "a user", + "VERSION": "a version", + "WHITE_LABELING": "the white labeling", + "WIDGETS_BUNDLE": "a widgets bundle", + "WIDGET_TYPE": "a widget" + }, "white-labeling-target": { "GENERAL": "Platform", "LOGIN": "Login page" diff --git a/ui-ngx/src/theme/ai-theme.scss b/ui-ngx/src/theme/ai-theme.scss index 5396eb0939..e5be90a4ce 100644 --- a/ui-ngx/src/theme/ai-theme.scss +++ b/ui-ngx/src/theme/ai-theme.scss @@ -1417,7 +1417,6 @@ color: var(--tb-crit); } - &.expired > .k-head, &.denied > .k-head { color: var(--tb-text-secondary); } @@ -1430,7 +1429,6 @@ line-height: 21px; color: var(--tb-ink); - .k-review.expired &, .k-review.denied & { color: var(--tb-text-secondary); } @@ -1889,6 +1887,10 @@ code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); } } } +.tb-ai-step-mark { + display: contents; +} + .k-pmark { box-sizing: border-box; display: inline-flex; @@ -2907,6 +2909,20 @@ textarea.k-opt-input { flex: none; height: 30px; } + + .k-notice-x.mat-mdc-icon-button.mat-mdc-button-base { + flex: none; + --mdc-icon-button-state-layer-size: 30px; + --mat-icon-button-state-layer-size: 30px; + width: 30px; + height: 30px; + margin: -4px -2px -4px -6px; + padding: 6px; + + .mat-icon { + color: var(--tb-ink-54); + } + } } .k-notice-edge { @@ -4822,142 +4838,61 @@ cursor: pointer; font-weight: 500; } -.k-ask .k-anchor { - position: relative; - display: inline-flex; - - > .ob-chip > .mat-icon { - flex: none; - width: 18px; - height: 18px; - margin: 0 6px 0 -2px; - font-size: 18px; - } -} - -.k-ask .k-pop { - position: absolute; - top: calc(100% + 6px); - left: 0; - z-index: 40; - - &.up { - top: auto; - bottom: calc(100% + 6px); - } +.k-ask .k-optrow .ob-chip > .mat-icon { + flex: none; + width: 18px; + height: 18px; + margin: 0 6px 0 -2px; + font-size: 18px; } -.k-ask .k-cal { - width: 300px; +.k-cal { + width: 296px; box-sizing: border-box; - padding: 10px 12px 12px; - border: 1px solid var(--tb-line); - border-radius: 12px; - background: var(--tb-surface); - box-shadow: 0 4px 8px rgba(16, 24, 40, 0.08), 0 12px 32px rgba(16, 24, 40, 0.16); font-family: var(--tb-font); -} -.k-ask .k-cal-h { - display: flex; - align-items: center; - justify-content: space-between; - margin-bottom: 4px; - - b { - font-size: var(--chat-line); - line-height: var(--chat-line-lh); - font-weight: 500; - } -} - -.k-ask .k-cal-g { - display: grid; - grid-template-columns: repeat(7, minmax(0, 1fr)); - gap: 2px; -} - -.k-ask .k-cal-w { - display: grid; - place-items: center; - height: 28px; - font-size: var(--chat-caption); - color: var(--tb-text-muted); -} - -.k-ask .k-cal-d { - display: grid; - place-items: center; - height: 34px; - padding: 0; - border: 0; - border-radius: 17px; - background: none; - font: inherit; - font-size: var(--chat-line); - color: var(--tb-ink); - cursor: pointer; - font-variant-numeric: tabular-nums; - - &:hover:not([disabled]) { - background: rgba(0, 0, 0, 0.05); - } - - &[disabled] { - color: var(--tb-ink-38); - cursor: default; - } - - &.today { - box-shadow: inset 0 0 0 1px var(--tb-ink-38); - } - - &[aria-pressed="true"] { - background: var(--ai-selected); - color: #fff; - box-shadow: none; - } + .k-cal-t { + display: flex; + align-items: center; + gap: 10px; + margin-top: 6px; + padding-top: 10px; + border-top: 1px solid var(--tb-line); - &:focus-visible { - outline: 2px solid var(--ai-focus); - outline-offset: 1px; + > span:first-child { + font-size: var(--chat-line); + color: var(--tb-text-secondary); + } } -} - -.k-ask .k-cal-t { - display: flex; - align-items: center; - gap: 10px; - margin-top: 10px; - padding-top: 10px; - border-top: 1px solid var(--tb-line); - > span:first-child { + .k-cal-time { + box-sizing: border-box; + width: 7ch; + min-height: 36px; + padding: 7px 10px; + border: 1px solid rgba(0, 0, 0, 0.2); + border-radius: 8px; + font: inherit; font-size: var(--chat-line); - color: var(--tb-text-secondary); - } -} + font-variant-numeric: tabular-nums; -.k-ask .k-cal-time { - box-sizing: border-box; - width: 7ch; - min-height: 36px; - padding: 7px 10px; - border: 1px solid rgba(0, 0, 0, 0.2); - border-radius: 8px; - font: inherit; - font-size: var(--chat-line); - font-variant-numeric: tabular-nums; + &:focus { + outline: 0; + border-color: var(--ai-focus); + box-shadow: inset 0 0 0 1px var(--ai-focus); + } - &:focus { - outline: 0; - border-color: var(--ai-focus); - box-shadow: inset 0 0 0 1px var(--ai-focus); + &[aria-invalid="true"] { + border-color: var(--tb-crit); + box-shadow: inset 0 0 0 1px var(--tb-crit); + } } - &[aria-invalid="true"] { - border-color: var(--tb-crit); - box-shadow: inset 0 0 0 1px var(--tb-crit); + .k-cal-err { + margin: 6px 0 0; + font-size: 12.5px; + line-height: 17px; + color: var(--tb-crit); } } @@ -4970,10 +4905,6 @@ cursor: pointer; color: var(--tb-crit); } -.k-ask .k-cal-err { - margin: 6px 0 0; -} - .k-ask.sheet { gap: 0; @@ -7199,17 +7130,6 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code { gap: 6px; } - .ob-chip { - height: 28px; - padding: 0 10px; - font-size: var(--chat-line); - - .mat-icon { - font-size: 16px; - width: 16px; - height: 16px; - } - } } .k-test-line { @@ -7540,11 +7460,15 @@ tb-ai-action-line .k-det tb-ai-action-detail.k-detail { flex: none; } - > .mat-icon.off { + .tb-ai-step-mark > .mat-icon { + flex: none; + } + + .tb-ai-step-mark > .mat-icon.off { color: var(--tb-ink-38); } - > .k-pmark { + .tb-ai-step-mark > .k-pmark { flex: none; margin-top: 0; }