diff --git a/ui-ngx/src/app/core/services/ai-chats.service.ts b/ui-ngx/src/app/core/services/ai-chats.service.ts index f4d2a2d94c..27efcb2e22 100644 --- a/ui-ngx/src/app/core/services/ai-chats.service.ts +++ b/ui-ngx/src/app/core/services/ai-chats.service.ts @@ -161,7 +161,7 @@ export class AiChatsService { if (this._open().has(chat.id)) { return chat.status === 'FAILED' ? 'error' : null; } - return chat.status === 'NEEDS_YOU' ? 'needs' : chat.status === 'RUNNING' ? 'running' : chat.status === 'FAILED' ? 'error' : null; + return chat.status === 'NEEDS_YOU' ? 'needs' : chat.status === 'NO_DATA' ? 'nodata' : chat.status === 'RUNNING' ? 'running' : chat.status === 'FAILED' ? 'error' : null; } needsAttention(chat: ChatInfo): boolean { 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 4ebbed306f..ac3c919e2b 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 @@ -14,7 +14,7 @@ @default {
- @if (outcomeChip(); as chip) {{{ chip.before }}@if (chip.link) {{{ chip.name }}} @else {{{ chip.name }}}{{ chip.after }}} @else {{{ outcome() }}} + @if (outcomeChip(); as chip) {{{ chip.before }}@if (chip.link) {{{ chip.name }}} @else {{{ chip.name }}}{{ chip.after }}} @else {{{ outcome() }}} @if (duration()) { {{ duration() }} } 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 303cb96cab..466bc0dd75 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 @@ -32,6 +32,9 @@ const TOOL_WORDS: Record = { delete_attributes: 'delete-attributes', read_entity_relations: 'read-relations', read_device_credentials: 'read-credentials', + save_device_credentials: 'save-credentials', + test_converter: 'test-converter', + read_converter_library: 'read-converter-library', create_dashboard: 'create-dashboard', update_dashboard: 'update-dashboard', add_dashboard_state: 'add-dashboard-state', @@ -168,6 +171,9 @@ const SAVED_KINDS: Record = { save_entity_view: ['entity-view', ''], save_asset: ['asset', ''], save_asset_profile: ['asset-profile', ''], + save_device_profile: ['device-profile', ''], + save_converter: ['converter', ''], + save_integration: ['integration', ''], save_secret: ['secret', ''], save_ai_model: ['ai-model', ''], save_resource: ['resource', ''] @@ -210,6 +216,9 @@ const DELETED_TARGETS: Record = { IMAGE: 'delete-image', ENTITY_VIEW: 'delete-entity-view', ASSET_PROFILE: 'delete-asset-profile', + DEVICE_PROFILE: 'delete-device-profile', + INTEGRATION: 'delete-integration', + CONVERTER: 'delete-converter', SECRET: 'delete-secret', AI_MODEL: 'delete-ai-model', RESOURCE: 'delete-resource', @@ -286,7 +295,115 @@ export function aiSourcesOf(args: unknown): AiSource[] { export const UPDATE_PLAN_TOOL = 'update_plan'; -const KIT_CARD_TOOLS = new Set([SUGGEST_PROMPTS_TOOL, ASK_USER_TOOL, PROPOSE_PLAN_TOOL, UPDATE_PLAN_TOOL, 'write_file', 'create_file', CITE_SOURCES_TOOL, 'show_records']); +export const HAND_OVER_TOOL = 'hand_over'; + +export const CHECK_CONNECTION_TOOL = 'check_connection'; + +const KIT_CARD_TOOLS = new Set([SUGGEST_PROMPTS_TOOL, ASK_USER_TOOL, PROPOSE_PLAN_TOOL, UPDATE_PLAN_TOOL, 'write_file', 'create_file', CITE_SOURCES_TOOL, 'show_records', + HAND_OVER_TOOL]); + +export interface AiHandOverValue { + label: string; + value: string; + secret: boolean; + icon: string; +} + +export interface AiHandOverStep { + title: string; + detail?: string; + markdown?: string; + values: AiHandOverValue[]; + done: boolean; +} + +export interface AiHandOverOption { + id: string; + label: string; + icon?: string; + text: string; +} + +export interface AiHandOver { + title: string; + text?: string; + choice?: {question: string; icon: string; value: string; options: AiHandOverOption[]}; + steps: AiHandOverStep[]; + waitFor?: 'message' | 'uplink' | 'gateway'; + intervalSeconds?: number; +} + +const text = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; + +const ICON_NAME = /^[a-z0-9_]{2,40}$/; + +const iconOf = (value: unknown, fallback: string): string => typeof value === 'string' && ICON_NAME.test(value) ? value : fallback; + +export function aiHandOverOf(args: unknown): AiHandOver | null { + const values = (args ?? {}) as Record; + const title = text(values.title); + if (!title) { + return null; + } + const steps: AiHandOverStep[] = (Array.isArray(values.steps) ? values.steps : []) + .filter(step => text(step?.title)) + .slice(0, 6) + .map(step => ({ + title: text(step.title), + detail: text(step.detail), + markdown: text(step.markdown), + done: step.done === true, + values: (Array.isArray(step.values) ? step.values : []) + .filter(value => text(value?.label) && typeof value?.value === 'string' && value.value) + .slice(0, 4) + .map(value => ({label: text(value.label), value: value.value, secret: value.secret === true, + icon: iconOf(value.icon, value.secret === true ? 'key' : /^https?:\/\//.test(value.value) ? 'link' : 'label')})) + })); + const options: AiHandOverOption[] = (Array.isArray(values.choice?.options) ? values.choice.options : []) + .filter(option => text(option?.id) && text(option?.label)) + .slice(0, 4) + .map(option => ({id: text(option.id), label: text(option.label), icon: typeof option.icon === 'string' && ICON_NAME.test(option.icon) ? option.icon : undefined, + text: text(option.text) ?? ''})); + const choice = options.length >= 2 ? { + question: text(values.choice.question) ?? '', + icon: iconOf(values.choice.icon, 'tune'), + value: options.some(option => option.id === values.choice.value) ? values.choice.value : options[0].id, + options + } : undefined; + const waitFor = ['message', 'uplink', 'gateway'].includes(values.waitFor) ? values.waitFor : undefined; + const interval = Number(values.intervalSeconds); + return {title, text: text(values.text), choice, steps, waitFor, + intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined}; +} + +export interface AiConnectionCheck { + dataArriving: boolean; + failedStep?: string; + name?: string; + note?: string; + readings: {key: string; value: string}[]; +} + +export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { + let values: any = result; + if (typeof result === 'string') { + try { + values = JSON.parse(result); + } catch { + return null; + } + } + if (!values || typeof values !== 'object' || !values.steps) { + return null; + } + const readings: {key: string; value: string}[] = []; + const add = (telemetry: unknown) => Object.entries(telemetry && typeof telemetry === 'object' ? telemetry : {}) + .forEach(([key, item]) => readings.push({key, value: String((item as any)?.value ?? '')})); + add(values.telemetry); + (Array.isArray(values.devices) ? values.devices : []).forEach(device => add(device?.telemetry)); + return {dataArriving: values.steps.dataArriving === true, failedStep: text(values.failedStep), name: text(values.name), + note: text(values.note), readings: readings.slice(0, 6)}; +} export const isKitCardTool = (tool: string): boolean => KIT_CARD_TOOLS.has(tool); @@ -442,6 +559,8 @@ export function aiActionWords(tool: string, args: unknown): AiActionWords { return {key: ACTION_PREFIX + telemetryWords(values), kind: 'think'}; case 'delete': return {key: ACTION_PREFIX + (DELETED_TARGETS[values.targetType] ?? 'delete-other'), kind: 'think'}; + case 'check_connection': + return {key: ACTION_PREFIX + (Number(values.waitSeconds) > 0 ? 'wait-for-data' : 'check-connection'), kind: 'think'}; case 'fetch_web_page': { const site = siteOf(values.url); return site ? {key: ACTION_PREFIX + 'read-site', params: {site}, kind: 'think'} : {key: ACTION_PREFIX + 'read-page', kind: 'think'}; 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 edc2614af2..9883601024 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 @@ -83,12 +83,16 @@
+ } @else if (msg.from === 'ACTION' && handOvers[$index]; as card) { +
+ +
} @else if (msg.from === 'ACTION' && asking?.index === $index) {
} @else if (msg.from === 'ACTION') { - @if (isListedAction(msg) && (msg.data.status !== 'RUNNING' || $index === runningLead)) { + @if (isListedAction(msg, $index) && (msg.data.status !== 'RUNNING' || $index === runningLead)) {
@if ($index === retryIndex) { @@ -167,15 +171,18 @@ @if (sources[$index]; as cited) {
@for (source of cited; track source.url) { -
- - - {{ source.title }}@if (source.external) {} - {{ source.from }} - @if (source.quote) { - {{ source.quote }} - } - +
+
+ + + +
+ @if (source.quote) { +
{{ source.quote }}
+ }
}
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 73cd682b7a..3e0ead471d 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 @@ -438,12 +438,12 @@ code:not([class*=language-]):not(.k-ent):not(pre code) { display: inline-block; white-space: nowrap; - padding: 2px 7px; + padding: var(--chat-chip-pad, 1px) 7px; border-radius: 5px; background: rgba(0, 0, 0, 0.06); font-family: var(--tb-mono); - font-size: 14px; - line-height: 18px; + font-size: var(--chat-chip-mono, 14px); + line-height: var(--chat-chip-lh, 18px); color: var(--tb-ink); } @@ -456,22 +456,37 @@ display: inline-block; max-width: 100%; box-sizing: border-box; - padding: 2px 7px; + padding: var(--chat-chip-pad, 1px) 7px; border-radius: 5px; - background: rgba(0, 0, 0, 0.05); - font: 400 14px/18px var(--tb-font); + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--tb-line); + font: 400 var(--chat-chip, 14px)/var(--chat-chip-lh, 18px) var(--tb-font); color: var(--tb-ink); white-space: nowrap; } - a .k-ext { - width: 14px; - height: 14px; - margin-left: 4px; - font-size: 14px; - line-height: 14px; - vertical-align: -2px; - color: var(--tb-ink-38); + a.tb-chiplink > code.k-ent { + padding-right: 2px; + } + + a.tb-chiplink:hover > code.k-ent, a.tb-chiplink:focus-visible > code.k-ent { + box-shadow: inset 0 0 0 1px var(--tb-ink-38); + } + + .k-ext-tail { + white-space: nowrap; + } + + .k-ext-tail > .k-ext { + display: inline-block; + width: 13px; + height: 13px; + margin-left: 1px; + font-size: 13px; + line-height: 13px; + vertical-align: -1px; + opacity: .82; + text-decoration: none; } a:not(.tb-chiplink) { @@ -490,13 +505,17 @@ > table { display: block; - width: auto; + width: fit-content; max-width: 100%; + box-sizing: border-box; overflow-x: auto; + scrollbar-width: thin; margin: 14px 0 0; - border: 0; - border-radius: 0; - border-collapse: collapse; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + border-collapse: separate; + border-spacing: 0; table-layout: auto; font-size: 14px; line-height: 20px; @@ -506,11 +525,12 @@ background: none; > tr > th { - padding: 0 20px 6px 0; + padding: 8px 20px 8px 0; font-size: 12.5px; line-height: 16px; font-weight: 500; color: var(--tb-text-secondary); + border: 0; border-bottom: 1px solid var(--tb-line); text-align: left; white-space: nowrap; @@ -522,6 +542,7 @@ font-size: 14px; line-height: 20px; color: var(--tb-ink); + border: 0; border-bottom: 1px solid rgba(0, 0, 0, 0.06); vertical-align: top; white-space: nowrap; @@ -529,11 +550,14 @@ > tbody > tr:last-child > td { border-bottom: 0; - padding-bottom: 0; + } + + th:first-child, td:first-child { + padding-left: 12px; } th:last-child, td:last-child { - padding-right: 0; + padding-right: 12px; } td.long { @@ -548,6 +572,59 @@ th[align="center"], td[align="center"] { text-align: center; } + + td code.k-ent { + padding: 0; + background: none; + box-shadow: none; + font-weight: 500; + } + + td .tb-chip-go { + display: none; + } + + td a.tb-chiplink > code.k-ent { + padding: 0; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: color-mix(in srgb, currentColor 28%, transparent); + transition: text-decoration-color .12s ease; + } + + td a.tb-chiplink:hover > code.k-ent, td a.tb-chiplink:focus-visible > code.k-ent { + box-shadow: none; + text-decoration-color: currentColor; + } + + @container k-col (max-width: 480px) { + th:first-child, td:first-child { + position: sticky; + left: 0; + z-index: 1; + padding-left: 8px; + padding-right: 10px; + background: var(--tb-surface); + border-right: 1px solid var(--tb-line); + white-space: normal; + } + + th:nth-child(2), td:nth-child(2) { + padding-left: 12px; + } + + th:last-child, td:last-child { + padding-right: 8px; + } + + td:first-child > .k-md-lead { + display: inline-block; + width: max-content; + max-width: 172px; + vertical-align: top; + } + } } @include ai-code-blocks; 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 04983c1885..2d4443befa 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 @@ -30,6 +30,11 @@ import { isHiddenAiAction, isKitCardTool, PROPOSE_PLAN_TOOL, + HAND_OVER_TOOL, + CHECK_CONNECTION_TOOL, + AiHandOver, + aiHandOverOf, + aiConnectionCheckOf, SUGGEST_PROMPTS_TOOL, UPDATE_PLAN_TOOL } from '@home/components/ai/ai-action.models'; @@ -57,7 +62,8 @@ export interface AnswerReportEvent { problem: AnswerProblem; comment?: string; } -import { decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; +import { announceCopied, decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; +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'; @@ -141,6 +147,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { made: Record = {}; plans: Record = {}; + handOvers: Record = {}; + private waitsInCards = new Set(); private keptAsking = new Set(); @@ -151,7 +159,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { private dayTimer: ReturnType; private static readonly PIN_TO_BOTTOM_MS = 1500; - private static readonly COPIED_MS = 1200; + private static readonly COPIED_MS = 1500; private static readonly FOLD_LINES = 6; private static readonly FOLD_CHARS = 600; @@ -210,6 +218,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { copyText(text: string, index: number): void { if (this.clipboard.copyFromContent(text)) { this.copiedIndex = index; + announceCopied(this.translate.instant('ai-assistant.copied')); clearTimeout(this.copiedTimeout); this.copiedTimeout = setTimeout(() => this.copiedIndex = -1, AiChatMessagesComponent.COPIED_MS); } @@ -225,7 +234,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { decorateTables(answer); decorateSections(answer, this.sectionScope(message)); decorateReferences(answer, (message as GeneralChatMessage)?.references); - decorateLinks(answer); + decorateLinks(answer, this.translate.instant('ai-assistant.opens-new-tab')); decorateHints(answer); decorateValues(answer, (message as GeneralChatMessage)?.readings); decorateFileChips(answer, this.latestFiles, this.shownFileName()); @@ -274,6 +283,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { const text = (answer.querySelector('tb-markdown') ?? answer).innerText.trim(); if (this.clipboard.copyFromContent(text)) { this.copiedIndex = index; + announceCopied(this.translate.instant('ai-assistant.copied')); clearTimeout(this.copiedTimeout); this.copiedTimeout = setTimeout(() => this.copiedIndex = -1, AiChatMessagesComponent.COPIED_MS); } @@ -404,6 +414,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { setTimeout(() => this.keepAskInView()); } this.plans = this.findPlans(); + this.handOvers = this.findHandOvers(); this.files = this.findFiles(); this.latestFiles = new Map(Object.values(this.files).map(file => [file.name, file])); this.madeFiles = this.findMadeFiles(); @@ -613,8 +624,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { return summaries; } - isListedAction(message: ChatMessage): boolean { - return message.from === 'ACTION' && !isKitCardTool(message.data.tool) && !isHiddenAiAction(message.data.tool); + isListedAction(message: ChatMessage, index = -1): boolean { + return message.from === 'ACTION' && !isKitCardTool(message.data.tool) && !isHiddenAiAction(message.data.tool) + && !(index >= 0 && this.waitsInCards.has(index)); } answerQuestions(answers: AiQuestionAnswer[]): void { @@ -800,6 +812,38 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy { return files; } + private findHandOvers(): Record { + const cards: Record = {}; + const waits = new Set(); + let current = -1; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + current = -1; + return; + } + if (message.from !== 'ACTION') { + return; + } + if (message.data.tool === HAND_OVER_TOOL) { + const handOver = aiHandOverOf(message.data.arguments); + if (handOver) { + cards[index] = {handOver, wait: null}; + current = index; + } + } else if (message.data.tool === CHECK_CONNECTION_TOOL && current >= 0 && cards[current].handOver.waitFor + && Number((message.data.arguments as {waitSeconds?: unknown})?.waitSeconds) > 0) { + const running = message.data.status === 'RUNNING' && this.loading; + cards[current].wait = {running, startedAt: message.data.startedAt, progress: message.data.progress, + check: running ? null : aiConnectionCheckOf(message.data.result)}; + if (running) { + waits.add(index); + } + } + }); + this.waitsInCards = waits; + return cards; + } + private findPlans(): Record { const plans: Record = {}; let current = -1; 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 13bb1adfdd..6681acb69e 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 @@ -142,6 +142,8 @@ } @if (creditsOut(); as limitType) { + } @else if (limitOut(); as platformLimit) { + } @else if (notice(); as current) {
{{ current.text }} 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 123d49c7ea..e9687dfce5 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 @@ -48,6 +48,7 @@ import { ActionChatMessage, AiStartedFrom, ApprovalChatMessage, ChatMessage, Gen import { AiAssistantPromptExample, AiChatClientContext, + AiPlatformLimit, AiLinesQuote, AiNotice, AiPromptMessage, @@ -353,6 +354,8 @@ export class AiChatComponent implements OnInit, OnDestroy { creditsOut = signal(null); + limitOut = signal(null); + private freshChatId: string | null = null; private noticeTimer: ReturnType; @@ -872,6 +875,7 @@ export class AiChatComponent implements OnInit, OnDestroy { this.shownChatId = chatId; this.resetLogPosition(0); this.messages.set([]); + this.limitOut.set(null); this.completedExecutions.set({}); this.denyReasons.set({}); this.answeredApprovals.set(new Set()); @@ -1096,6 +1100,9 @@ export class AiChatComponent implements OnInit, OnDestroy { case 'toolFinished': this.finishAction(event.data); break; + case 'limitReached': + this.limitOut.set(event.data); + break; case 'turnStopped': this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'STOPPED', time: Date.now()}]); break; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.html index 88ea5bf290..40d668b50c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.html @@ -29,32 +29,18 @@

{{ 'ai-assistant.cli.hero.title' | translate }}

{{ 'ai-assistant.cli.hero.lead' | translate }}

-
-
- @for (item of ways; track item) { - - } -
- @if (way() === 'terminal') { -
- } @else { -
-
- -
- } -
-

{{ (way() === 'terminal' ? 'ai-assistant.cli.note-terminal' : 'ai-assistant.cli.note-agent') | translate }}

- + + {{ 'ai-assistant.cli.hero.docs' | translate }} + +
+
@@ -66,7 +52,8 @@
  • @for (agent of agents; track agent.id) { - } @@ -77,8 +64,13 @@
  • diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss index 943424e131..9b8ce8b762 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.scss @@ -175,6 +175,7 @@ $hero-bg: #1b252c; margin: 0; font-size: 16px; line-height: 24px; + max-width: 56ch; letter-spacing: 0.15px; color: #b4bec6; text-wrap: pretty; @@ -223,50 +224,57 @@ $hero-bg: #1b252c; } .ai-cli-hero-set { - position: relative; display: grid; - justify-items: start; - gap: 12px; + gap: 24px; max-width: 680px; margin: 20px auto 0; } -.ai-cli-seg { - display: inline-flex; - padding: 2px; - border-radius: 100px; - background: rgba(255, 255, 255, 0.08); +.ai-cli-acts { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 20px; + padding-left: 72px; +} - button { - height: 30px; - padding: 0 14px; - border: 0; - border-radius: 100px; - background: none; - color: #b4bec6; - font-family: inherit; - font-size: var(--chat-line); - line-height: 1; - cursor: pointer; - transition: background-color $motion $ease, color $motion $ease; +.ai-cli-start { + display: inline-flex; + align-items: center; + gap: 6px; + height: 40px; + padding: 0 14px 0 18px; + border: 0; + border-radius: 10px; + background: var(--ai-dark-accent); + color: var(--ai-on-dark-accent); + font-family: inherit; + font-size: var(--chat-text); + font-weight: 500; + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: background-color $motion $ease; - b { - font-weight: 500; - } + .mat-icon { + font-size: var(--chat-icon); + width: var(--chat-icon); + height: var(--chat-icon); + color: inherit; + transition: transform $motion $ease; + } - &:hover { - color: #fff; - } + &:hover { + background: var(--ai-dark-accent-hover); - &[aria-pressed="true"] { - background: var(--ai-dark-accent); - color: var(--ai-on-dark-accent); + .mat-icon { + transform: translateY(2px); } + } - &:focus-visible { - outline: 2px solid var(--ai-dark-accent-pale); - outline-offset: 2px; - } + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: 2px; } } @@ -274,21 +282,6 @@ $hero-bg: #1b252c; display: contents; } -.ai-cli-clamp { - position: relative; - justify-self: stretch; - min-width: 0; - display: grid; - - > .ai-cli-more-t { - position: absolute; - left: 50%; - bottom: 10px; - transform: translateX(-50%); - height: 28px; - } -} - .ai-cli-alt { display: inline-flex; align-items: center; @@ -312,6 +305,15 @@ $hero-bg: #1b252c; height: 18px; } + &, &:hover, &:focus { + border-bottom: 0; + text-decoration: none; + } + + &:is(a) { + letter-spacing: inherit; + } + &:hover { color: var(--ai-dark-accent-pale); } @@ -327,24 +329,6 @@ $hero-bg: #1b252c; } } -.ai-cli-foot { - justify-self: stretch; - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 4px 16px; - min-width: 0; -} - -.ai-cli-prompt-note { - margin: 0; - font-size: 13px; - line-height: 19px; - color: #9fadb7; - text-wrap: balance; -} - .ai-cli { max-width: 680px; margin: 24px auto 0; @@ -354,10 +338,14 @@ $hero-bg: #1b252c; text-wrap: pretty; } - :is(h2, p, .ai-cli-body > b, .ai-cli-step-head > b, .ai-cli-subs > li > b) { + :is(h2, p, .ai-cli-body > b, .ai-cli-step-head > b, .ai-cli-subs > li > b), .ai-cli-flow > li > :is(b, p) { text-wrap: balance; } + p { + letter-spacing: inherit; + } + code { padding: 1px 5px; border-radius: 4px; @@ -426,7 +414,7 @@ $hero-bg: #1b252c; } .ai-cli-pic { - height: 136px; + height: 120px; box-sizing: border-box; min-width: 0; padding: 0 16px; @@ -452,7 +440,7 @@ $hero-bg: #1b252c; border: 0; border-radius: 18px; background: var(--tb-surface); - box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.06), 0 2px 4px rgba(16, 24, 40, 0.06), 0 8px 20px rgba(16, 24, 40, 0.1); + box-shadow: 0 1px 3px color-mix(in srgb, var(--glow) 16%, transparent), 0 12px 26px -8px color-mix(in srgb, var(--glow) 46%, transparent); animation: ai-cli-rise $breathe ease-in-out infinite alternate; & + .ai-cli-logo { @@ -477,15 +465,49 @@ $hero-bg: #1b252c; font-family: var(--tb-mono); font-size: 12.5px; font-weight: 500; - line-height: 22px; + line-height: 20px; color: var(--tb-ink); + .commit { + display: flex; + align-items: center; + gap: 6px; + height: 20px; + min-width: 0; + margin-bottom: 6px; + font-size: var(--chat-meta); + font-weight: 400; + white-space: nowrap; + color: var(--tb-ink-54); + + .mat-icon { + flex: none; + font-size: 15px; + width: 15px; + height: 15px; + line-height: 15px; + color: var(--ai-selected); + } + + b { + flex: none; + font-weight: 500; + color: var(--ai-selected); + } + + > span:last-child { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } + } + .row { position: relative; display: flex; align-items: center; gap: 6px; - height: 22px; + height: 20px; min-width: 0; padding-left: calc(var(--d) * 18px); white-space: nowrap; @@ -511,35 +533,53 @@ $hero-bg: #1b252c; &.tone-view { color: var(--entity-view-fg); } + + &.tone-rule { + color: var(--entity-rule-fg); + } } - &:not(:first-child)::before { + &:not(.top)::before { content: ''; position: absolute; left: calc((var(--d) - 1) * 18px + 7px); - top: -4px; - width: 8px; - height: 15px; - box-sizing: border-box; - border-left: 1px solid var(--k-stroke-hover); - border-bottom: 1px solid var(--k-stroke-hover); - border-bottom-left-radius: 5px; + top: 10px; + width: 9px; + border-top: 1px solid var(--k-stroke-hover); } - &:not(:first-child):not(.last)::after { + &:not(.top):not(.last)::after { content: ''; position: absolute; left: calc((var(--d) - 1) * 18px + 7px); - top: 6px; - bottom: -4px; + top: 0; + bottom: 0; border-left: 1px solid var(--k-stroke-hover); } + + &.last:not(.top)::before { + top: 0; + height: 11px; + box-sizing: border-box; + border-top: 0; + border-left: 1px solid var(--k-stroke-hover); + border-bottom: 1px solid var(--k-stroke-hover); + border-bottom-left-radius: 5px; + } + + &.first:not(.last)::after, &.first.last::before { + top: -1px; + } + + &.first.last::before { + height: 12px; + } } } .ai-cli-ask { display: grid; - gap: 4px; + gap: 2px; min-width: 0; font-family: var(--tb-mono); font-size: 12.5px; @@ -547,15 +587,29 @@ $hero-bg: #1b252c; line-height: 18px; color: var(--tb-ink-76); - .q { + .chk { + display: grid; + grid-template-columns: 12px minmax(0, 1fr); + gap: 4px; margin-bottom: 4px; + font-weight: 400; + color: var(--tb-ink-54); + + > i { + font-style: normal; + color: var(--ai-selected); + } + } + + .q { + margin-bottom: 2px; font-weight: 600; color: var(--tb-ink); } .opt { display: grid; - grid-template-columns: 12px minmax(0, 1fr); + grid-template-columns: 12px minmax(0, 1fr) auto; gap: 4px; margin: 0 -6px; padding: 2px 6px; @@ -567,6 +621,11 @@ $hero-bg: #1b252c; animation: ai-cli-lit $breathe ease-in-out infinite alternate; } + .enter { + color: var(--ai-selected); + opacity: 0.7; + } + &.on { background: var(--ai-selected-wash); color: var(--ai-selected-text); @@ -622,7 +681,7 @@ $hero-bg: #1b252c; z-index: 1; width: 44px; height: 44px; - border-radius: 50%; + border-radius: 13px; display: inline-flex; align-items: center; justify-content: center; @@ -792,7 +851,6 @@ $hero-bg: #1b252c; .ai-cli-keys { height: 36px; - margin-top: 6px; border-color: var(--k-stroke); color: var(--tb-ink-76); @@ -965,72 +1023,350 @@ $hero-bg: #1b252c; margin-top: 10px; } - .ai-cli-cta { - .tb-codeblock { - justify-self: stretch; - min-width: 0; - margin: 0; - border-radius: 8px; - box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1); + .ai-cli-term { + --term-bg: color-mix(in srgb, #{$hero-bg} 58%, #000); + --term-fg: var(--tb-code-fg); + --term-text: #9fadb7; + --term-muted: #7d8c96; + --term-faint: #5f6f7a; + --term-hover: #b4bec6; + --term-rule: rgba(255, 255, 255, 0.07); + --term-art: linear-gradient(90deg in oklab, var(--ai-dark-accent), var(--ai-light-lilac), var(--ai-light-peach)); + min-width: 0; + + .banner { + display: grid; + color: var(--term-muted); + + .art { + justify-self: start; + max-width: 100%; + margin-bottom: 10px; + overflow: hidden; + white-space: pre; + font-size: 12px; + line-height: 13px; + color: var(--ai-dark-accent-soft); + } - .tb-code { - white-space: pre-wrap; + b { + font-weight: 500; + color: var(--term-fg); + } + + i { + font-style: normal; + color: var(--ai-dark-accent); } } - .tb-codeblock-head { - color: var(--ai-dark-accent); - border-bottom-color: color-mix(in srgb, var(--ai-dark-accent) 16%, transparent); + .r { + display: grid; + grid-template-columns: 2ch minmax(0, 1fr); + min-width: 0; + overflow-wrap: anywhere; - > .tb-codeblock-label { + > i { + font-style: normal; color: var(--ai-dark-accent); - font-weight: 500; } - .tb-codecopy.labelled { + &.past { + opacity: 0.5; + } + + &.think { + color: var(--term-muted); + + > i { + display: inline-block; + transform: scale(1.5); + transform-origin: 30% 55%; + } + + &.done > i { + color: var(--term-faint); + } + } + + &.out.run .t { + color: var(--term-faint); + } + + &:is(.you, .tool, .say, .think) { + margin-top: var(--chat-line-lh); + } + + &.you { + color: #fff; + } + + &:is(.tool, .say, .ask) { + color: var(--term-fg); + } + + &.tool b { + font-weight: 500; color: var(--ai-dark-accent); - font: 500 12.5px/1 var(--tb-font); - - .mat-icon { - font-size: 16px; - width: 16px; - height: 16px; - color: currentColor; - opacity: 1; + } + + &:is(.out, .ok, .ask) { + padding-left: 2ch; + } + + &.out > i { + color: var(--term-faint); + } + + &.say > i { + color: #fff; + } + } + + .caret { + display: inline-block; + width: 1ch; + height: 1.15em; + vertical-align: text-bottom; + background: var(--ai-dark-accent); + animation: ai-cli-lit $breathe ease-in-out infinite alternate; + + &.typing { + animation: none; + } + } + } + + @supports ((background-clip: text) or (-webkit-background-clip: text)) { + .ai-cli-term .banner .art { + background: var(--term-art); + -webkit-background-clip: text; + background-clip: text; + color: transparent; + } + } + + @media (forced-colors: active) { + .ai-cli-term .banner .art { + background: none; + color: CanvasText; + } + } + + .ai-cli-term-bar { + display: flex; + align-items: flex-end; + min-width: 0; + + .dots { + flex: none; + display: flex; + gap: 6px; + margin: 0 4px 12px 14px; + + i { + width: 8px; + height: 8px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.1); + } + } + + .tabs { + display: flex; + gap: 2px; + min-width: 0; + padding: 0 18px 0 10px; + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + } + + [role="tab"] { + position: relative; + flex: none; + height: 32px; + padding: 0 14px; + border: 0; + border-radius: 8px 8px 0 0; + background: none; + color: var(--term-muted); + font-family: var(--tb-mono); + font-size: var(--chat-meta); + line-height: 1; + letter-spacing: normal; + cursor: pointer; + transition: color $motion $ease; + + &:hover { + background: rgba(255, 255, 255, 0.04); + color: var(--term-hover); + } + + &[aria-selected="true"] { + background: var(--term-bg); + color: var(--term-fg); + + &::before, &::after { + content: ''; + position: absolute; + bottom: 0; + width: 8px; + height: 8px; + pointer-events: none; } - &:hover { - background: color-mix(in srgb, var(--ai-dark-accent) 12%, transparent); - color: var(--ai-dark-accent-hover); + &::before { + left: -8px; + background: radial-gradient(circle at 0 0, transparent 8px, var(--term-bg) 8.5px); } - &.done { - background: color-mix(in srgb, var(--ai-dark-accent) 16%, transparent); - color: var(--ai-dark-accent-pale); + &::after { + right: -8px; + background: radial-gradient(circle at 100% 0, transparent 8px, var(--term-bg) 8.5px); } } + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: -2px; + } } } - .ai-cli-clamp { - > .tb-codeblock { - min-width: 0; + .ai-cli-term-body { + height: 268px; + display: flex; + flex-direction: column; + border-radius: 10px; + background: var(--term-bg); + box-shadow: 0 18px 40px -18px rgba(0, 0, 0, 0.55); + overflow: hidden; + + &:focus-visible { + outline: 2px solid var(--ai-dark-accent-pale); + outline-offset: 2px; + } + } + + .ai-cli-term-view { + flex: 1; + min-height: 0; + box-sizing: border-box; + padding: 12px 16px 10px; + display: flex; + flex-direction: column; + overflow: hidden; + + &.full { + justify-content: flex-end; + -webkit-mask-image: linear-gradient(transparent, #000 30px); + mask-image: linear-gradient(transparent, #000 30px); + } + } + + .ai-cli-term-rows { + display: grid; + font-family: var(--tb-mono); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--term-text); + transition: opacity .24s cubic-bezier(.05, .7, .1, 1); + + > .r:first-child { + margin-top: 0; + } + + &.out { + opacity: 0; + transition: opacity .16s cubic-bezier(.3, 0, .8, .15); + } + } + + .ai-cli-term-input { + flex: none; + display: grid; + grid-template-columns: 2ch minmax(0, 1fr); + padding: 10px 16px 12px; + box-shadow: inset 0 1px 0 var(--term-rule); + font-family: var(--tb-mono); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: #fff; + overflow-wrap: anywhere; + + > i { + font-style: normal; + color: var(--ai-dark-accent); } - .tb-code { - padding-bottom: 48px; + &.menu .t { + display: grid; } - &.shut .tb-code { - $fade: linear-gradient(#000 calc(100% - 132px), rgba(0, 0, 0, 0.82) calc(100% - 108px), rgba(0, 0, 0, 0.5) calc(100% - 82px), - rgba(0, 0, 0, 0.2) calc(100% - 58px), rgba(0, 0, 0, 0.05) calc(100% - 40px), transparent calc(100% - 26px)); - max-height: 204px; + .opt { + color: var(--term-muted); + + &.on { + color: var(--ai-dark-accent); + } + + &.press { + color: var(--ai-dark-accent-pale); + } + } + } + + @container (min-width: 640px) { + .ai-cli-term { + width: 100%; + max-width: 600px; + margin-left: 72px; box-sizing: border-box; - overflow: hidden; - -webkit-mask-image: $fade; - mask-image: $fade; } } + + @container (max-width: 639px) { + .ai-cli-term-bar { + .dots { + display: none; + } + + .tabs { + padding: 0 10px; + } + } + + .ai-cli-term .banner .art { + font-size: 9.5px; + line-height: 10px; + } + } + + @media (prefers-reduced-motion: reduce) { + .ai-cli-term .caret, .ai-cli-term-rows { + animation: none; + transition: none; + } + } +} + +@container (max-width: 480px) { + .ai-cli-start .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +@media (max-width: 720px) { + .ai-cli-head .ob-title { + font-size: 22px; + line-height: 28px; + } } @media (prefers-reduced-motion: reduce) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts index 6d512f0a4e..87d3bac663 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli-guide.component.ts @@ -9,7 +9,7 @@ import { ElementRef, inject, Injector, - input, + NgZone, output, signal } from '@angular/core'; @@ -39,17 +39,18 @@ import { CliOs, CliWay } from '@home/components/ai/ai-cli.models'; +import { cliTerm, CliTerm } from '@home/components/ai/ai-cli-term'; interface CliPicks { way?: CliWay; build?: CliBuild; - open?: boolean; } interface CliTreeRow { depth: number; name: string; last: boolean; + first: boolean; icon: string; tone?: string; } @@ -69,8 +70,6 @@ export class AiCliGuideComponent { private static readonly PICKS_KEY = 'tb-ai-cli'; - copiedUntil = input(0); - closed = output(); readonly docs = CLI_DOCS; @@ -88,11 +87,10 @@ export class AiCliGuideComponent { readonly url = window.location.origin; readonly tree: CliTreeRow[] = [ - {depth: 0, name: 'thingsboard-project', last: true, icon: 'folder'}, - {depth: 1, name: 'solutions/office', last: true, icon: 'folder'}, - {depth: 2, name: 'devices', last: false, icon: 'memory', tone: 'device'}, - {depth: 2, name: 'dashboards', last: false, icon: 'dashboard', tone: 'view'}, - {depth: 2, name: 'device-profiles', last: true, icon: 'category', tone: 'device'} + {depth: 0, name: 'smart-retail', last: true, first: false, icon: 'folder'}, + {depth: 1, name: 'devices', last: false, first: true, icon: 'memory', tone: 'device'}, + {depth: 1, name: 'dashboards', last: false, first: false, icon: 'dashboard', tone: 'view'}, + {depth: 1, name: 'alarm-rules', last: true, first: false, icon: 'rule', tone: 'rule'} ]; private readonly picks = AiCliGuideComponent.readPicks(); @@ -101,8 +99,6 @@ export class AiCliGuideComponent { build = signal(CLI_BUILDS.some(item => item.id === this.picks.build) ? this.picks.build : 'sensor'); - promptOpen = signal(!!this.picks.open); - os = signal(AiCliGuideComponent.storedOs()); fullscreen = signal(false); @@ -114,12 +110,17 @@ export class AiCliGuideComponent { private router = inject(Router); private injector = inject(Injector); private host = inject>(ElementRef); + private zone = inject(NgZone); + private term: CliTerm | null = null; readonly hostElement = this.host.nativeElement; constructor() { const stop = onCodeTabGroup(CLI_OS_GROUP, id => this.os.set(id === 'windows' ? 'windows' : 'unix')); - inject(DestroyRef).onDestroy(stop); + inject(DestroyRef).onDestroy(() => { + stop(); + this.term?.destroy(); + }); afterRenderEffect(() => { this.way(); this.build(); @@ -150,22 +151,6 @@ export class AiCliGuideComponent { this.savePicks(); } - togglePrompt(event: Event): void { - const control = event.currentTarget as HTMLElement; - const top = control.getBoundingClientRect().top; - const open = !this.promptOpen(); - this.promptOpen.set(open); - this.savePicks(); - if (!open) { - afterNextRender(() => { - const scroller = this.scroller(); - if (scroller) { - scroller.scrollTop += control.getBoundingClientRect().top - top; - } - }, {injector: this.injector}); - } - } - toSteps(): void { const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; this.hostElement.querySelector('#ai-cli-steps')?.scrollIntoView({behavior: reduce ? 'auto' : 'smooth', block: 'start'}); @@ -194,7 +179,7 @@ export class AiCliGuideComponent { private fillSlots(): void { this.hostElement.querySelectorAll('.ai-cli-slot').forEach(slot => { - const key = slot.dataset.kind + ':' + (slot.dataset.key ?? '') + (slot.dataset.kind === 'prompt-hero' ? ':' + this.copiedUntil() : ''); + const key = slot.dataset.kind + ':' + (slot.dataset.key ?? ''); if (slot.dataset.built !== key) { slot.dataset.built = key; slot.replaceChildren(this.blockFor(slot.dataset.kind, slot.dataset.key)); @@ -206,13 +191,10 @@ export class AiCliGuideComponent { const copy = (text: string) => this.clipboard.copyFromContent(text); const say = (word: string) => this.translate.instant('ai-assistant.cli.' + word); switch (kind) { - case 'install-hero': - return this.installBlock(true); + case 'term': + return this.termBlock(); case 'install': - return this.installBlock(false); - case 'prompt-hero': - return labelledCodeBlock(say('setup-prompt'), say('setup-prompt-label'), 'text', this.translate, copy, - {labelledCopy: true, classes: 'wrap', copiedFor: Math.max(0, this.copiedUntil() - Date.now())}); + return this.installBlock(); case 'prompt': return labelledCodeBlock(say('setup-prompt'), say('setup-prompt-label'), 'text', this.translate, copy, {check: true, classes: 'wrap'}); @@ -234,14 +216,19 @@ export class AiCliGuideComponent { } } - private installBlock(hero: boolean): HTMLElement { + private termBlock(): HTMLElement { + this.term?.destroy(); + this.term = this.zone.runOutsideAngular(() => cliTerm((key, params) => this.translate.instant(key, params))); + return this.term.element; + } + + private installBlock(): HTMLElement { return codeTabsBlock([ {id: 'unix', label: this.translate.instant('ai-assistant.cli.mac-linux'), text: CLI_INSTALL.unix, lang: 'shell'}, {id: 'windows', label: this.translate.instant('ai-assistant.cli.windows'), text: CLI_INSTALL.windows, lang: 'powershell'} ], 'shell', this.translate, text => this.clipboard.copyFromContent(text), this.os() === 'windows' ? 1 : 0, tab => this.os.set(tab.id === 'windows' ? 'windows' : 'unix'), - {group: CLI_OS_GROUP, label: this.translate.instant('ai-assistant.cli.terminal'), icon: false, - labelledCopy: hero, check: !hero}); + {group: CLI_OS_GROUP, label: this.translate.instant('ai-assistant.cli.terminal'), icon: false, check: true}); } private agentBlock(text: (agent: CliAgentInfo) => string): HTMLElement { @@ -251,7 +238,7 @@ export class AiCliGuideComponent { } private savePicks(): void { - const picks: CliPicks = {way: this.way(), build: this.build(), open: this.promptOpen()}; + const picks: CliPicks = {way: this.way(), build: this.build()}; try { localStorage.setItem(AiCliGuideComponent.PICKS_KEY, JSON.stringify(picks)); } catch { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts b/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts new file mode 100644 index 0000000000..b38085e1c9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli-term.ts @@ -0,0 +1,380 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + CLI_ART, + CLI_TERM_HOLD, + CLI_TERM_SESSIONS, + CLI_TERM_WAIT, + CLI_VERSION, + CliTermRow, + CliTermSession +} from '@home/components/ai/ai-cli.models'; + +export interface CliTerm { + element: HTMLElement; + destroy: () => void; +} + +const MARK: Record = {you: '❯', tool: '●', out: '└', say: '●', ok: '✔', ask: '', think: '⠿'}; +const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'; + +let shownTab = 0; +let turning = true; +let termCount = 0; + +type Kid = Node | string | null; + +function el(tag: string, cls?: string, ...kids: Kid[]): HTMLElement { + const node = document.createElement(tag); + if (cls) { + node.className = cls; + } + kids.forEach(kid => { + if (kid != null) { + node.append(kid); + } + }); + return node; +} + +const jitter = (lo: number, hi: number) => lo + Math.random() * (hi - lo); + +export function cliTerm(say: (key: string, params?: Record) => string): CliTerm { + const calm = matchMedia('(prefers-reduced-motion: reduce)').matches; + const uid = 'ai-cli-term-' + (++termCount); + const t = (key: string) => say('ai-assistant.cli.term.' + key); + const list = el('div', 'ai-cli-term-rows'); + list.setAttribute('role', 'img'); + const view = el('div', 'ai-cli-term-view', list); + const typed = document.createTextNode(''); + const caret = el('span', 'caret'); + const line = el('span', 't', typed, caret); + const input = el('div', 'ai-cli-term-input', el('i', null, '❯'), line); + input.setAttribute('aria-hidden', 'true'); + const body = el('div', 'ai-cli-term-body', view, input); + body.setAttribute('role', 'tabpanel'); + body.id = uid + '-panel'; + body.tabIndex = 0; + const touch = () => { + turning = false; + }; + const pickTab = (k: number) => { + touch(); + if (k !== shownTab) { + play(k); + } + }; + const tabs = CLI_TERM_SESSIONS.map((session, k) => { + const tab = el('button', null, session.tab) as HTMLButtonElement; + tab.type = 'button'; + tab.setAttribute('role', 'tab'); + tab.id = `${uid}-tab-${k}`; + tab.setAttribute('aria-controls', body.id); + tab.addEventListener('click', () => pickTab(k)); + return tab; + }); + const strip = el('div', 'tabs', ...tabs); + strip.setAttribute('role', 'tablist'); + strip.setAttribute('aria-label', t('label')); + strip.addEventListener('keydown', (event: KeyboardEvent) => { + const k = tabs.indexOf(document.activeElement as HTMLButtonElement); + const n = tabs.length; + const to = ({ArrowRight: k + 1, ArrowLeft: k - 1 + n, Home: 0, End: n - 1} as Record)[event.key]; + if (k < 0 || to == null) { + return; + } + event.preventDefault(); + pickTab(to % n); + tabs[to % n].focus(); + }); + const dots = el('span', 'dots', el('i'), el('i'), el('i')); + dots.setAttribute('aria-hidden', 'true'); + const root = el('div', 'ai-cli-term', el('div', 'ai-cli-term-bar', dots, strip), body); + root.addEventListener('click', touch); + + let run = 0; + let spin: ReturnType | null = null; + let thinking: HTMLElement | null = null; + let t0 = 0; + let seen = true; + let hover = false; + let started = false; + let told = false; + let io: IntersectionObserver | null = null; + let fallback: ReturnType | null = null; + const timers = new Set>(); + + const later = (ms: number, fn: () => void) => { + const r = run; + const id = setTimeout(() => { + timers.delete(id); + if (r === run && root.isConnected) { + fn(); + } + }, ms); + timers.add(id); + }; + const stopSpin = () => { + if (spin) { + clearInterval(spin); + spin = null; + } + }; + const setInput = (text: string) => { + typed.data = text; + line.replaceChildren(typed, caret); + input.classList.remove('menu'); + caret.classList.toggle('typing', !!text); + }; + const stop = () => { + run += 1; + timers.forEach(clearTimeout); + timers.clear(); + stopSpin(); + thinking = null; + setInput(''); + }; + const fit = () => { + const room = view.clientHeight; + if (room) { + view.classList.toggle('full', list.offsetHeight > room - 16); + } + }; + const row = (kind: string, ...kids: Kid[]) => { + const r = el('span', 'r ' + kind, el('i', null, MARK[kind.split(' ')[0]]), el('span', 't', ...kids)); + list.insertBefore(r, thinking); + fit(); + return r; + }; + const toolRow = (item: CliTermRow) => row('tool', el('b', null, item.tool), `(${item.arg})`); + const think = () => { + t0 = Date.now(); + thinking = el('span', 'r think', el('i', null, SPIN[0]), el('span', 't', t('thinking'))); + list.append(thinking); + fit(); + let f = 0; + const glyph = thinking.firstChild as HTMLElement; + spin = setInterval(() => { + if (!root.isConnected) { + stopSpin(); + return; + } + f += 1; + glyph.textContent = SPIN[f % SPIN.length]; + }, 90); + }; + const done = () => { + if (!thinking) { + return; + } + stopSpin(); + thinking.classList.add('done'); + thinking.firstChild.textContent = '⠿'; + thinking.lastChild.textContent = say('ai-assistant.cli.term.done', {seconds: Math.max(1, Math.round((Date.now() - t0) / 1000))}); + thinking = null; + }; + const send = (text: string, next: () => void) => { + setInput(''); + row('you', text); + think(); + later(jitter(900, 1500), next); + }; + const type = (text: string, next: () => void) => { + let n = 0; + const tick = () => { + n += 1; + typed.data = text.slice(0, n); + caret.classList.add('typing'); + const ch = text[n - 1]; + if (n < text.length) { + later(ch === ' ' ? jitter(45, 120) : /[.,:]/.test(ch) ? jitter(140, 280) : jitter(30, 75), tick); + } else { + later(420, () => send(text, next)); + } + }; + tick(); + }; + const pick = (options: string[], next: () => void) => { + input.classList.add('menu'); + line.replaceChildren(...options.map((option, j) => el('span', 'opt' + (j ? '' : ' on'), `${j + 1}. ${option}`))); + later(1400, () => { + (line.firstChild as HTMLElement).classList.add('press'); + later(240, () => send(options[0], next)); + }); + }; + const stream = (node: HTMLElement, text: string, next: () => void) => { + const words = text.split(' '); + let n = 0; + const tick = () => { + n = Math.min(words.length, n + 1 + Math.floor(Math.random() * 3)); + node.textContent = words.slice(0, n).join(' '); + fit(); + if (n < words.length) { + later(jitter(45, 100), tick); + } else { + next(); + } + }; + tick(); + }; + const step = (rows: CliTermRow[], i: number) => { + if (i >= rows.length) { + done(); + if (turning) { + later(CLI_TERM_HOLD, advance); + } + return; + } + const item = rows[i]; + const go = () => later(CLI_TERM_WAIT[(rows[i + 1] ?? {kind: 'you'}).kind], () => step(rows, i + 1)); + if (item.kind === 'you') { + done(); + type(t(item.text), () => step(rows, i + 1)); + return; + } + if (item.kind === 'pick') { + done(); + pick(item.options.map(t), () => step(rows, i + 1)); + return; + } + if (item.kind === 'tool') { + toolRow(item); + go(); + return; + } + if (item.kind === 'out') { + const r = row('out run', t('running')); + later(item.ms || 1200, () => { + r.classList.remove('run'); + r.lastChild.textContent = t(item.text); + fit(); + go(); + }); + return; + } + stream(row(item.kind).lastChild as HTMLElement, t(item.text), go); + }; + const advance = () => { + if (!turning) { + return; + } + if (hover || !seen || document.hidden) { + later(600, advance); + return; + } + play((shownTab + 1) % CLI_TERM_SESSIONS.length); + }; + const intro = (session: CliTermSession) => { + if (session.banner) { + list.append(el('div', 'banner', el('span', 'art', CLI_ART), el('b', null, CLI_VERSION), + el('span', null, el('i', null, '✔'), ' ' + t('connected')), el('span', null, el('i', null, '✔'), ' ' + t('detected')))); + fit(); + return; + } + (session.intro ?? []).forEach(item => { + const r = item.kind === 'done' ? row('think done', say('ai-assistant.cli.term.done', {seconds: item.seconds})) + : item.kind === 'tool' ? toolRow(item) : row(item.kind, t(item.text)); + r.classList.add('past'); + }); + }; + const still = (rows: CliTermRow[]) => rows.forEach(item => { + if (item.kind === 'tool') { + toolRow(item); + } else if (item.kind === 'pick') { + row('you', t(item.options[0])); + } else { + row(item.kind, t(item.text)); + } + }); + const mark = (k: number) => { + shownTab = k; + tabs.forEach((tab, j) => { + tab.setAttribute('aria-selected', String(j === k)); + tab.tabIndex = j === k ? 0 : -1; + }); + if (strip.scrollWidth > strip.clientWidth) { + strip.scrollLeft += tabs[k].getBoundingClientRect().left - strip.getBoundingClientRect().left - 10; + } + body.setAttribute('aria-labelledby', tabs[k].id); + list.setAttribute('aria-label', say('ai-assistant.cli.term.picture', {about: t(CLI_TERM_SESSIONS[k].tab + '.about')})); + }; + const opening = (k: number) => { + list.replaceChildren(); + view.classList.remove('full'); + intro(CLI_TERM_SESSIONS[k]); + if (calm) { + still(CLI_TERM_SESSIONS[k].rows); + } + }; + const begin = (k: number) => later(CLI_TERM_WAIT.you, () => step(CLI_TERM_SESSIONS[k].rows, 0)); + function play(k: number): void { + stop(); + mark(k); + started = true; + const go = () => { + list.classList.remove('out'); + opening(k); + if (!calm) { + begin(k); + } + }; + if (list.firstChild && !calm) { + list.classList.add('out'); + later(260, go); + } else { + go(); + } + } + const refit = () => { + if (root.isConnected) { + fit(); + } + }; + + shownTab = Math.min(shownTab, CLI_TERM_SESSIONS.length - 1); + mark(shownTab); + opening(shownTab); + requestAnimationFrame(refit); + const destroy = () => { + stop(); + io?.disconnect(); + if (fallback) { + clearTimeout(fallback); + } + }; + if (calm) { + return {element: root, destroy}; + } + root.addEventListener('pointerenter', (event: PointerEvent) => { + if (event.pointerType === 'mouse') { + hover = true; + } + }); + root.addEventListener('pointerleave', () => { + hover = false; + }); + const start = () => { + if (!started) { + started = true; + begin(shownTab); + } + }; + if ('IntersectionObserver' in window) { + io = new IntersectionObserver(entries => { + told = true; + seen = entries[entries.length - 1].isIntersecting; + if (seen) { + start(); + } + }, {threshold: 0.2}); + io.observe(root); + } + fallback = setTimeout(() => { + fallback = null; + if (!told && root.isConnected) { + seen = true; + start(); + } + }, 1500); + return {element: root, destroy}; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts index 46dfc24860..b8651dcee3 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-cli.models.ts @@ -13,8 +13,6 @@ export const CLI_OS_GROUP = 'cli-os'; export const CLI_AGENT_GROUP = 'cli-agent'; -export const CLI_COPIED_MS = 4000; - export const CLI_DOCS = 'https://thingsboard.io/docs/cli/'; export const CLI_INSTALL: Record = { @@ -28,11 +26,12 @@ export interface CliAgentInfo { run: string; restart: string; get: string; + glow: string; } export const CLI_AGENTS: CliAgentInfo[] = [ - {id: 'claude', name: 'Claude Code', run: 'claude', restart: 'claude --continue', get: 'https://claude.com/claude-code'}, - {id: 'antigravity', name: 'Antigravity', run: 'agy', restart: 'agy', get: 'https://antigravity.google/'} + {id: 'claude', name: 'Claude Code', run: 'claude', restart: 'claude --continue', get: 'https://claude.com/claude-code', glow: '#D97757'}, + {id: 'antigravity', name: 'Antigravity', run: 'agy', restart: 'agy', get: 'https://antigravity.google/', glow: '#3186FF'} ]; export interface CliBuildInfo { @@ -72,6 +71,108 @@ export const CLI_DOCS_LINKS: CliDocsLink[] = [ {key: 'all', icon: 'menu_book', path: ''} ]; +export type CliTermKind = 'you' | 'pick' | 'tool' | 'out' | 'say' | 'ok' | 'ask' | 'done'; + +export interface CliTermRow { + kind: CliTermKind; + text?: string; + tool?: string; + arg?: string; + ms?: number; + options?: string[]; + seconds?: number; +} + +export interface CliTermSession { + tab: string; + banner?: boolean; + intro?: CliTermRow[]; + rows: CliTermRow[]; +} + +export const CLI_VERSION = 'thingsboard-cli 4.4.0.2.post1'; + +export const CLI_ART = [ + ' _____ _ _ ____ _ ', + '|_ _| |__ (_)_ __ __ _ ___| __ ) ___ __ _ _ __ __| |', + ' | | | \'_ \\| | \'_ \\ / _` / __| _ \\ / _ \\ / _` | \'__/ _` |', + ' | | | | | | | | | | (_| \\__ \\ |_) | (_) | (_| | | | (_| |', + ' |_| |_| |_|_|_| |_|\\__, |___/____/ \\___/ \\__,_|_| \\__,_|', + ' |___/ ' +].join('\n'); + +export const CLI_TERM_WAIT: Record = {you: 1200, pick: 300, tool: 380, out: 60, say: 520, ok: 110, ask: 260}; + +export const CLI_TERM_HOLD = 6000; + +export const CLI_TERM_SESSIONS: CliTermSession[] = [ + { + tab: 'office-sensor', + banner: true, + rows: [ + {kind: 'you', text: 'office-sensor.you'}, + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'office-sensor.written', ms: 2600}, + {kind: 'say', text: 'office-sensor.ready'}, + {kind: 'ok', text: 'office-sensor.device'}, + {kind: 'ok', text: 'office-sensor.alarm'}, + {kind: 'ok', text: 'office-sensor.dashboard'}, + {kind: 'ask', text: 'office-sensor.ask'}, + {kind: 'pick', options: ['office-sensor.stream', 'office-sensor.deploy-only', 'office-sensor.not-now']}, + {kind: 'tool', tool: 'Bash', arg: 'tb push office'}, + {kind: 'out', text: 'office-sensor.deployed', ms: 1500}, + {kind: 'tool', tool: 'Bash', arg: 'tb emulator run --duration 5m'}, + {kind: 'out', text: 'office-sensor.streaming', ms: 1100} + ] + }, + { + tab: 'smart-retail', + intro: [ + {kind: 'tool', tool: 'Bash', arg: 'tb device list'}, + {kind: 'out', text: 'smart-retail.devices'}, + {kind: 'say', text: 'smart-retail.connected'}, + {kind: 'done', seconds: 6} + ], + rows: [ + {kind: 'you', text: 'smart-retail.you'}, + {kind: 'tool', tool: 'Skill', arg: 'design-solution-architecture'}, + {kind: 'out', text: 'smart-retail.designed', ms: 2800}, + {kind: 'say', text: 'smart-retail.approve'}, + {kind: 'pick', options: ['smart-retail.step', 'smart-retail.whole']}, + {kind: 'say', text: 'smart-retail.first'}, + {kind: 'ok', text: 'smart-retail.overview'}, + {kind: 'ok', text: 'smart-retail.store'}, + {kind: 'ask', text: 'smart-retail.build'}, + {kind: 'pick', options: ['smart-retail.yes', 'smart-retail.not-yet']}, + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'smart-retail.built', ms: 3000}, + {kind: 'say', text: 'smart-retail.next'} + ] + }, + { + tab: 'freezer-limits', + intro: [ + {kind: 'tool', tool: 'Skill', arg: 'create-solution'}, + {kind: 'out', text: 'smart-retail.built'}, + {kind: 'say', text: 'smart-retail.next'}, + {kind: 'done', seconds: 41} + ], + rows: [ + {kind: 'you', text: 'freezer-limits.you'}, + {kind: 'tool', tool: 'Skill', arg: 'update-solution'}, + {kind: 'out', text: 'freezer-limits.updated', ms: 2400}, + {kind: 'say', text: 'freezer-limits.done'}, + {kind: 'ok', text: 'freezer-limits.attribute'}, + {kind: 'ok', text: 'freezer-limits.alarm'}, + {kind: 'ok', text: 'freezer-limits.dashboard'}, + {kind: 'ask', text: 'freezer-limits.ask'}, + {kind: 'pick', options: ['freezer-limits.push', 'freezer-limits.not-now']}, + {kind: 'tool', tool: 'Bash', arg: 'tb push smart-retail --profile dev'}, + {kind: 'out', text: 'freezer-limits.deployed', ms: 1600} + ] + } +]; + export function cliOs(): CliOs { const nav = navigator as Navigator & {userAgentData?: {platform?: string}}; return /win/i.test(nav.userAgentData?.platform || navigator.platform || '') ? 'windows' : 'unix'; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts index 22c1fc5a49..334fc0dc83 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -157,7 +157,6 @@ export interface CodeBlockOptions { icon?: boolean; check?: boolean; labelledCopy?: boolean; - copiedFor?: number; classes?: string; } @@ -409,17 +408,13 @@ function copyBtn(text: string | (() => string), translate: TranslateService, cop done(LABELLED_COPIED_MS); } }); - if (options.copiedFor > 0) { - done(options.copiedFor); - } return button; } - if (options.check) { - button.append(icon('check', 'tb-mat-16 tb-copy-ok')); - } + button.append(icon('check', 'tb-mat-16 tb-copy-ok')); button.addEventListener('click', () => { if (copy(typeof text === 'function' ? text() : text)) { button.classList.add('copied'); + announceCopied(translate.instant('ai-assistant.copied')); clearTimeout(timer); timer = setTimeout(() => button.classList.remove('copied'), COPIED_MS); } @@ -427,6 +422,20 @@ function copyBtn(text: string | (() => string), translate: TranslateService, cop return button; } +let copiedRegion: HTMLElement | null = null; + +export function announceCopied(words: string): void { + if (!copiedRegion?.isConnected) { + copiedRegion = element('div', 'tb-ai-sr-only'); + copiedRegion.setAttribute('role', 'status'); + copiedRegion.setAttribute('aria-live', 'polite'); + document.body.append(copiedRegion); + } + const region = copiedRegion; + region.textContent = ''; + setTimeout(() => region.textContent = words, 30); +} + function icon(name: string, size: string): HTMLElement { const glyph = element('span', `mat-icon material-icons notranslate ${size}`); glyph.setAttribute('aria-hidden', 'true'); @@ -790,4 +799,12 @@ export function decorateTables(root: HTMLElement): void { root.querySelectorAll('table td, table th').forEach((cell: HTMLElement) => { cell.classList.toggle('long', (cell.textContent ?? '').trim().length > LONG_CELL); }); + root.querySelectorAll('table td:first-child').forEach((cell: HTMLElement) => { + if (cell.firstElementChild?.classList.contains('k-md-lead') && cell.childNodes.length === 1) { + return; + } + const lead = element('span', 'k-md-lead'); + lead.append(...Array.from(cell.childNodes)); + cell.append(lead); + }); } 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 new file mode 100644 index 0000000000..4a09dc26d5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -0,0 +1,116 @@ + +
    + @if (folded()) { + + } @else { +
    + {{ 'ai-assistant.hand-over.needs-you' | translate }} + {{ handOver().title }} + @if (arrived()) { + + } +
    +
    + @if (handOver().text) { + + } + @if (handOver().choice; as choice) { +
    +
    + + {{ choice.question }} + + @for (option of choice.options; track option.id) { + + } + +
    + @if (choiceText()) { +
    + } +
    + } + @if (handOver().steps.length) { +
      + @for (step of handOver().steps; track $index; let i = $index) { +
    1. + + @if (step.values.length || step.markdown) { +
      + @for (value of step.values; track $index; let v = $index) { +
      + + {{ value.label }} + {{ value.secret && !shown().has(i + '-' + v) ? masked(value.value) : value.value }} + @if (value.secret) { + + } + +
      + } + @if (step.markdown) { + + } +
      + } +
    2. + } +
    + } + @if (quiet() || stoppedQuiet()) { +
    +
    + + {{ 'ai-assistant.hand-over.nothing-heard' | translate: {minutes: quietMinutes()} }} + @if (waiting()) { + {{ clock() }} + } +
    +
    + + +
    +
    + } @else if (waiting()) { +
    + + {{ waitLabel() }} + {{ clock() }} +
    + } +
    + } +
    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 new file mode 100644 index 0000000000..d76d19b58a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { Clipboard } from '@angular/cdk/clipboard'; +import { TranslateService } from '@ngx-translate/core'; +import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models'; +import { announceCopied, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; + +export interface AiHandOverWait { + running: boolean; + startedAt: number; + progress?: string; + check?: AiConnectionCheck | null; +} + +const MIN_SILENCE_MS = 120000; +const COPIED_MS = 1500; + +@Component({ + selector: 'tb-ai-hand-over', + templateUrl: './ai-hand-over.component.html', + standalone: false +}) +export class AiHandOverComponent { + + handOver = input.required(); + wait = input(null); + time = input(0); + + @Output() prompt = new EventEmitter(); + + private host = inject(ElementRef); + private translate = inject(TranslateService); + private clipboard = inject(Clipboard); + + readonly picked = signal(null); + readonly ticked = signal>(new Set()); + readonly shown = signal>(new Set()); + readonly copied = signal(null); + readonly now = signal(Date.now()); + readonly open = signal(false); + + readonly choiceValue = computed(() => this.picked() ?? this.handOver().choice?.value ?? null); + readonly choiceText = computed(() => this.handOver().choice?.options.find(option => option.id === this.choiceValue())?.text ?? ''); + + readonly arrived = computed(() => this.wait()?.check?.dataArriving === true); + readonly folded = computed(() => this.arrived() && !this.open()); + + readonly waiting = computed(() => !!this.wait()?.running); + readonly elapsed = computed(() => Math.max(0, this.now() - (this.wait()?.startedAt ?? this.now()))); + readonly clock = computed(() => { + const seconds = Math.floor(this.elapsed() / 1000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; + }); + readonly silenceMs = computed(() => 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 stoppedQuiet = computed(() => { + const wait = this.wait(); + return !!wait && !wait.running && !!wait.check && !wait.check.dataArriving; + }); + + constructor() { + const timer = setInterval(() => { + if (this.waiting()) { + this.now.set(Date.now()); + } + }, 1000); + inject(DestroyRef).onDestroy(() => clearInterval(timer)); + effect(() => { + this.choiceText(); + this.handOver(); + this.folded(); + setTimeout(() => decorateCodeBlocks(this.host.nativeElement, this.translate, text => this.clipboard.copy(text))); + }); + } + + waitLabel(): string { + return this.translate.instant('ai-assistant.hand-over.wait-' + (this.handOver().waitFor ?? 'message')); + } + + pick(id: string): void { + this.picked.set(id); + } + + tick(index: number): void { + const next = new Set(this.ticked()); + if (next.has(index)) { + next.delete(index); + } else { + next.add(index); + } + this.ticked.set(next); + } + + done(index: number): boolean { + return this.ticked().has(index) !== (this.handOver().steps[index]?.done === true); + } + + reveal(key: string): void { + const next = new Set(this.shown()); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + this.shown.set(next); + } + + masked(value: string): string { + return value.length > 8 ? value.slice(0, 4) + '••••••••' + value.slice(-4) : '••••••••'; + } + + copy(key: string, value: string): void { + if (this.clipboard.copy(value)) { + this.copied.set(key); + announceCopied(this.translate.instant('ai-assistant.copied')); + setTimeout(() => this.copied.set(null), COPIED_MS); + } + } + + say(key: string): void { + this.prompt.emit(this.translate.instant(key)); + } +} 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 new file mode 100644 index 0000000000..86ade52c20 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html @@ -0,0 +1,47 @@ + +@let current = view(); + 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 new file mode 100644 index 0000000000..c025bea6fc --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { Observable } from 'rxjs'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { NotificationService } from '@core/http/notification.service'; +import { Authority } from '@shared/models/authority.enum'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { AddonType, SubscriptionEntry, subscriptionEntryToEntityType } from '@shared/models/subscription.models'; +import { AiPlatformLimit } from '@shared/models/ai-chat.models'; + +type RequestState = 'idle' | 'sending' | 'sent' | 'failed'; + +type LimitAction = 'request' | 'license' | 'pricing' | 'none'; + +interface LimitView { + icon: string; + title: string; + text: string; + action: LimitAction; + usage: boolean; + requestLabel?: string; + storageKey: string; + send?: () => Observable; +} + +const PRICING_URL = 'https://thingsboard.io/pricing/'; +const WL_REQUESTED_STORAGE_KEY = 'wlRequested'; +const PE_PACK_REQUESTED_STORAGE_KEY = 'pePackRequested'; +const FEATURE_KEYS: Record = { + [SubscriptionEntry.WHITE_LABELING]: 'white-labeling', + INTEGRATIONS: 'integrations', + SCHEDULER: 'scheduler', + REPORTING: 'reporting' +}; + +@Component({ + selector: 'tb-ai-limit-out', + templateUrl: './ai-limit-out.component.html', + styleUrls: ['./ai-credits-out.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiLimitOutComponent { + + platformLimit = input.required(); + + dismissed = output(); + + private notificationService = inject(NotificationService); + private translate = inject(TranslateService); + private readonly store = inject(Store); + private readonly user = getCurrentAuthUser(this.store); + private readonly authState = getCurrentAuthState(this.store); + + readonly pricingUrl = PRICING_URL; + readonly state = signal('idle'); + readonly view = computed(() => this.viewOf(this.platformLimit())); + + constructor() { + effect(() => this.state.set(this.wasRequested(this.view().storageKey) ? 'sent' : 'idle')); + } + + request(): void { + const send = this.view().send; + if (!send || this.state() === 'sending' || this.state() === 'sent') { + return; + } + this.state.set('sending'); + send().subscribe({ + next: () => { + this.rememberRequested(this.view().storageKey); + this.state.set('sent'); + }, + error: () => this.state.set('failed') + }); + } + + 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) { + const entityType = limit.entityType; + return { + icon: 'data_usage', + title: this.say('entity-title', {entities: this.entities(entityType)}), + text: customer + ? this.say('tenant-text-plain', {entities: this.entities(entityType).toLowerCase()}) + : this.say('tenant-text', {limit: limit.limit, entities: this.entities(entityType).toLowerCase()}), + action: 'request', + usage: tenantAdmin, + requestLabel: 'ai-assistant.limit-out.request', + storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${entityType}:${limit.limit}`, + send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(entityType, false, config) + }; + } + const entry = limit.subscriptionEntry as SubscriptionEntry; + const licensedType = subscriptionEntryToEntityType.get(entry); + if (limit.subscriptionErrorCode === 'LIMIT_REACHED' && licensedType) { + 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) + }; + } + const featureKey = FEATURE_KEYS[limit.subscriptionEntry ?? '']; + if (limit.subscriptionErrorCode === 'FEATURE_DISABLED' && featureKey) { + const whiteLabeling = entry === SubscriptionEntry.WHITE_LABELING; + const grant = !!this.authState?.communityGrantLicense; + const addon = whiteLabeling && !grant ? AddonType.WHITE_LABELING : AddonType.PROFESSIONAL_UPGRADE; + return { + icon: whiteLabeling ? 'palette' : 'lock', + title: grant + ? 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) + }; + } + return { + icon: 'lock', + title: this.say('license-required'), + text: limit.message ?? '', + action: sysAdmin ? 'license' : 'none', + usage: false, + storageKey: '' + }; + } + + private entities(entityType: EntityType): string { + const translations = entityTypeTranslations.get(entityType); + return translations ? this.translate.instant(translations.typePlural) as string : entityType; + } + + private say(key: string, params?: object): string { + return this.translate.instant('ai-assistant.limit-out.' + key, params); + } + + private wasRequested(key: string): boolean { + if (!key) { + return false; + } + try { + const stored = localStorage.getItem(key); + return stored === 'sent' || stored === 'true'; + } catch { + return false; + } + } + + private rememberRequested(key: string): void { + if (!key) { + return; + } + try { + localStorage.setItem(key, key === WL_REQUESTED_STORAGE_KEY || key === PE_PACK_REQUESTED_STORAGE_KEY ? JSON.stringify(true) : 'sent'); + } catch { + return; + } + } +} 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 78f6ee88fd..bde8d07d8e 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 @@ -689,15 +689,17 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= align-items: center; justify-content: center; box-sizing: border-box; - min-width: 22px; - height: 22px; - padding: 0 6px; + min-width: 20px; + height: 20px; + padding: 0 5px; border: 1px solid var(--tb-line); border-bottom-width: 2px; - border-radius: 6px; - background: var(--tb-surface); - color: var(--tb-ink-54); - font: 500 12px/1 var(--tb-font); + border-radius: 5px; + background: none; + color: var(--k-faint); + font: 400 11px/1 var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; pointer-events: none; transform: translateY(-50%); } 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 99815a7b25..328ffb0945 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 @@ -43,7 +43,7 @@ export function aiWidgetThumb(): string { template: ` @let rec = view();
    + [class.with-pic]="picture()" [class.primary]="!!primaryAction()" [class.open-icon]="primaryAction() === 'open'" [class.tight]="tight()" [class.with-details]="hasFoot()">
    @if (picture()) {