30 changed files with 2765 additions and 528 deletions
@ -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<string, string> = {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, unknown>) => 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<string, number>)[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<typeof setInterval> | 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<typeof setTimeout> | null = null; |
|||
const timers = new Set<ReturnType<typeof setTimeout>>(); |
|||
|
|||
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}; |
|||
} |
|||
@ -0,0 +1,116 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
<section class="k-hand" [class.folded]="folded()" [attr.aria-label]="'ai-assistant.hand-over.needs-you' | translate"> |
|||
@if (folded()) { |
|||
<button type="button" class="k-hand-fold" (click)="open.set(true)" [attr.aria-expanded]="false"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">check_circle</mat-icon> |
|||
<span>{{ handOver().title }}</span> |
|||
<mat-icon class="tb-mat-18 k-hand-fold-tg" aria-hidden="true">expand_more</mat-icon> |
|||
</button> |
|||
} @else { |
|||
<div class="k-head"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">person</mat-icon>{{ 'ai-assistant.hand-over.needs-you' | translate }} |
|||
<span class="k-sub">{{ handOver().title }}</span> |
|||
@if (arrived()) { |
|||
<button mat-icon-button type="button" class="k-hand-close" (click)="open.set(false)" |
|||
[attr.aria-label]="'ai-assistant.hand-over.fold' | translate"><mat-icon>expand_less</mat-icon></button> |
|||
} |
|||
</div> |
|||
<div class="k-body"> |
|||
@if (handOver().text) { |
|||
<tb-markdown usePlainMarkdown [data]="handOver().text"></tb-markdown> |
|||
} |
|||
@if (handOver().choice; as choice) { |
|||
<div class="k-choice-panel"> |
|||
<div class="k-choice"> |
|||
<span class="k-qi"><mat-icon class="tb-mat-18" aria-hidden="true">{{ choice.icon }}</mat-icon></span> |
|||
<span class="k-qt">{{ choice.question }}</span> |
|||
<span class="ob-seg k-seg" role="group" [attr.aria-label]="choice.question"> |
|||
@for (option of choice.options; track option.id) { |
|||
<button type="button" [attr.aria-pressed]="choiceValue() === option.id" (click)="pick(option.id)"> |
|||
@if (option.icon) { |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">{{ option.icon }}</mat-icon> |
|||
} |
|||
{{ option.label }} |
|||
</button> |
|||
} |
|||
</span> |
|||
</div> |
|||
@if (choiceText()) { |
|||
<div class="k-choice-body"><tb-markdown usePlainMarkdown [data]="choiceText()"></tb-markdown></div> |
|||
} |
|||
</div> |
|||
} |
|||
@if (handOver().steps.length) { |
|||
<ol class="k-steps"> |
|||
@for (step of handOver().steps; track $index; let i = $index) { |
|||
<li [class.done]="done(i)"> |
|||
<label> |
|||
<input type="checkbox" [checked]="done(i)" (change)="tick(i)"> |
|||
<span class="k-step-t">{{ step.title }}</span> |
|||
@if (step.detail) { |
|||
<span class="k-step-d">{{ step.detail }}</span> |
|||
} |
|||
</label> |
|||
@if (step.values.length || step.markdown) { |
|||
<div class="k-step-x"> |
|||
@for (value of step.values; track $index; let v = $index) { |
|||
<div class="k-value" [class.secret]="value.secret"> |
|||
<mat-icon class="tb-mat-18 k-value-ic" aria-hidden="true">{{ value.icon }}</mat-icon> |
|||
<span class="k-value-l">{{ value.label }}</span> |
|||
<code class="k-value-v">{{ value.secret && !shown().has(i + '-' + v) ? masked(value.value) : value.value }}</code> |
|||
@if (value.secret) { |
|||
<button mat-icon-button type="button" class="k-value-b" (click)="reveal(i + '-' + v)" |
|||
[matTooltip]="(shown().has(i + '-' + v) ? 'ai-assistant.hand-over.hide' : 'ai-assistant.hand-over.show') | translate" |
|||
[attr.aria-label]="(shown().has(i + '-' + v) ? 'ai-assistant.hand-over.hide' : 'ai-assistant.hand-over.show') | translate"> |
|||
<mat-icon class="tb-mat-18">{{ shown().has(i + '-' + v) ? 'visibility_off' : 'visibility' }}</mat-icon> |
|||
</button> |
|||
} |
|||
<button mat-icon-button type="button" class="k-value-b" (click)="copy(i + '-' + v, value.value)" |
|||
[matTooltip]="(copied() === i + '-' + v ? 'ai-assistant.hand-over.copied' : 'action.copy') | translate" |
|||
[attr.aria-label]="'action.copy' | translate"> |
|||
<mat-icon class="tb-mat-18">{{ copied() === i + '-' + v ? 'check' : 'content_copy' }}</mat-icon> |
|||
</button> |
|||
</div> |
|||
} |
|||
@if (step.markdown) { |
|||
<tb-markdown usePlainMarkdown [data]="step.markdown"></tb-markdown> |
|||
} |
|||
</div> |
|||
} |
|||
</li> |
|||
} |
|||
</ol> |
|||
} |
|||
@if (quiet() || stoppedQuiet()) { |
|||
<div class="k-quiet"> |
|||
<div class="k-wait warn" role="status"> |
|||
<mat-icon class="tb-mat-18" aria-hidden="true">schedule</mat-icon> |
|||
<span>{{ 'ai-assistant.hand-over.nothing-heard' | translate: {minutes: quietMinutes()} }}</span> |
|||
@if (waiting()) { |
|||
<span class="clock">{{ clock() }}</span> |
|||
} |
|||
</div> |
|||
<div class="k-chips"> |
|||
<button type="button" class="ob-chip" (click)="say('ai-assistant.hand-over.keep-waiting-prompt')"> |
|||
<mat-icon aria-hidden="true">check</mat-icon>{{ 'ai-assistant.hand-over.keep-waiting' | translate }} |
|||
</button> |
|||
<button type="button" class="ob-chip" (click)="say('ai-assistant.hand-over.what-wrong-prompt')"> |
|||
<mat-icon aria-hidden="true">help_outline</mat-icon>{{ 'ai-assistant.hand-over.what-wrong' | translate }} |
|||
</button> |
|||
</div> |
|||
</div> |
|||
} @else if (waiting()) { |
|||
<div class="k-wait" role="status"> |
|||
<tb-ai-spin kind="think" aria-hidden="true"></tb-ai-spin> |
|||
<span class="k-wait-t">{{ waitLabel() }}</span> |
|||
<span class="clock">{{ clock() }}</span> |
|||
</div> |
|||
} |
|||
</div> |
|||
} |
|||
</section> |
|||
@ -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<AiHandOver>(); |
|||
wait = input<AiHandOverWait | null>(null); |
|||
time = input<number>(0); |
|||
|
|||
@Output() prompt = new EventEmitter<string>(); |
|||
|
|||
private host = inject(ElementRef<HTMLElement>); |
|||
private translate = inject(TranslateService); |
|||
private clipboard = inject(Clipboard); |
|||
|
|||
readonly picked = signal<string | null>(null); |
|||
readonly ticked = signal<ReadonlySet<number>>(new Set()); |
|||
readonly shown = signal<ReadonlySet<string>>(new Set()); |
|||
readonly copied = signal<string | null>(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)); |
|||
} |
|||
} |
|||
@ -0,0 +1,47 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
@let current = view(); |
|||
<section class="k-credits-out" role="alert" [attr.aria-label]="current.title"> |
|||
<div class="k-credits-out-head"> |
|||
<span class="k-credits-out-mark" aria-hidden="true"><mat-icon fontSet="material-icons-round">{{ current.icon }}</mat-icon></span> |
|||
<div class="k-credits-out-text"> |
|||
<b>{{ current.title }}</b> |
|||
<span>{{ current.text }}</span> |
|||
</div> |
|||
<button mat-icon-button type="button" class="k-credits-out-close" [matTooltip]="'action.close' | translate" |
|||
[attr.aria-label]="'action.close' | translate" (click)="dismissed.emit()"> |
|||
<mat-icon>close</mat-icon> |
|||
</button> |
|||
</div> |
|||
@if (current.action !== 'none' || current.usage) { |
|||
<div class="k-credits-out-actions"> |
|||
@switch (current.action) { |
|||
@case ('request') { |
|||
@if (state() === 'sent') { |
|||
<span class="k-credits-out-sent" role="status"><mat-icon fontSet="material-icons-round">check_circle</mat-icon>{{ 'ai-assistant.limit-out.sent' | translate }}</span> |
|||
} @else { |
|||
<button mat-flat-button color="primary" type="button" [disabled]="state() === 'sending'" (click)="request()"> |
|||
{{ current.requestLabel | translate }} |
|||
</button> |
|||
@if (state() === 'failed') { |
|||
<span class="k-credits-out-failed" role="status">{{ 'ai-assistant.limit-out.failed' | translate }}</span> |
|||
} |
|||
} |
|||
} |
|||
@case ('license') { |
|||
<a mat-flat-button color="primary" routerLink="/license">{{ 'ai-assistant.limit-out.manage-license' | translate }}</a> |
|||
} |
|||
@case ('pricing') { |
|||
<a mat-flat-button color="primary" [href]="pricingUrl" target="_blank" rel="noopener">{{ 'subscription.upgrade-plan' | translate }}</a> |
|||
} |
|||
} |
|||
@if (current.usage) { |
|||
<a mat-button routerLink="/usage" class="k-credits-out-usage">{{ 'ai-assistant.limit-out.view-usage' | translate }}</a> |
|||
} |
|||
</div> |
|||
} |
|||
</section> |
|||
@ -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<void>; |
|||
} |
|||
|
|||
const PRICING_URL = 'https://thingsboard.io/pricing/'; |
|||
const WL_REQUESTED_STORAGE_KEY = 'wlRequested'; |
|||
const PE_PACK_REQUESTED_STORAGE_KEY = 'pePackRequested'; |
|||
const FEATURE_KEYS: Record<string, string> = { |
|||
[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<AiPlatformLimit>(); |
|||
|
|||
dismissed = output<void>(); |
|||
|
|||
private notificationService = inject(NotificationService); |
|||
private translate = inject(TranslateService); |
|||
private readonly store = inject(Store<AppState>); |
|||
private readonly user = getCurrentAuthUser(this.store); |
|||
private readonly authState = getCurrentAuthState(this.store); |
|||
|
|||
readonly pricingUrl = PRICING_URL; |
|||
readonly state = signal<RequestState>('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; |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue