Browse Source

feat: AI chat connectivity fixes from live testing: the nothing-heard row offers the case's own paste chip that fills the composer and reads 'It is on now, keep waiting', its threshold capped at five minutes; a file the assistant wrote sits inside the hand-over step that uses it; a wait that started before its card shows after it; a reloaded turn keeps each tool's start time; record cards waiting for data re-check until the device is active; a gateway's arrival reads that it connected and JSON values stay out of readings; expanding a disclosure, a folded code block, unchanged review fields or a done card scrolls it clear of the composer; every message sends the browser's operating system in the client context; long answers wrap in the answered-questions card

pull/16848/head
Igor Kulikov 1 week ago
parent
commit
6044477fcf
  1. 6
      ui-ngx/src/app/core/services/ai-assistant-panel.service.ts
  2. 3
      ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts
  3. 23
      ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts
  4. 2
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html
  5. 8
      ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts
  6. 4
      ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts
  7. 11
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html
  8. 35
      ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts
  9. 12
      ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts
  10. 4
      ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts
  11. 39
      ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts
  12. 22
      ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html
  13. 21
      ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts
  14. 15
      ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts
  15. 9
      ui-ngx/src/app/shared/models/ai-chat.models.ts
  16. 3
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  17. 10
      ui-ngx/src/theme/ai-theme.scss

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

@ -5,7 +5,7 @@ import { defer, Observable, Subject } from 'rxjs';
import { distinctUntilChanged, filter, finalize, map } from 'rxjs/operators';
import { NavigationEnd, NavigationStart, Router } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, AiChatView, ChatInfo, AiPromptMessage } from '@shared/models/ai-chat.models';
import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, aiClientOs, AiChatView, ChatInfo, AiPromptMessage } from '@shared/models/ai-chat.models';
import { EntityId } from '@shared/models/id/entity-id';
import { getDefaultTimezone } from '@shared/models/time/time.models';
import { LocalStorageService } from '@core/local-storage/local-storage.service';
@ -397,7 +397,7 @@ export class AiAssistantPanelService implements OnDestroy {
}
setClientContextForView(view: AiChatView): void {
this.setClientContext({view, timeZone: getDefaultTimezone()});
this.setClientContext({view, timeZone: getDefaultTimezone(), os: aiClientOs()});
}
focusWhile<T>(view: AiChatView, name: string | null | undefined, until: Observable<T>): Observable<T> {
@ -406,7 +406,7 @@ export class AiAssistantPanelService implements OnDestroy {
if (!previous || !view.entityId?.id) {
return until;
}
const focus = {context: {view, timeZone: getDefaultTimezone()}, previous, previousName: this._viewName()};
const focus = {context: {view, timeZone: getDefaultTimezone(), os: aiClientOs()}, previous, previousName: this._viewName()};
this._focus = focus;
this._clientContext.set(focus.context);
this._viewName.set(name?.trim() || null);

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

@ -126,6 +126,9 @@ export class AiActionLineComponent {
return null;
}
const time = new Date(action.startedAt + (action.durationMs ?? 0)).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'});
if (check.gateway) {
return {text: this.translate.instant('ai-assistant.hand-over.gateway-connected', {name: check.name, time}), readings: []};
}
return {
text: this.translate.instant('ai-assistant.hand-over.' + (!check.keyCount ? 'arrived-message' : check.keyCount === 1 ? 'arrived-key' : 'arrived-keys')
+ (check.name ? '-from' : ''), {name: check.name, time, count: check.keyCount}),

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

@ -314,6 +314,7 @@ export interface AiHandOverStep {
detail?: string;
markdown?: string;
values: AiHandOverValue[];
file?: string;
done: boolean;
}
@ -334,6 +335,7 @@ export interface AiHandOver {
intervalSeconds?: number;
quiet?: string;
test?: AiHandOverTest;
paste?: {label: string; icon: string; intro: string};
}
export interface AiHandOverTest {
@ -395,7 +397,13 @@ export function aiHandOverOf(args: unknown): AiHandOver | null {
const interval = Number(values.intervalSeconds);
return {title, text: text(values.text), choice, steps, waitFor,
intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, quiet: text(values.quiet),
test: handOverTestOf(values.test)};
test: handOverTestOf(values.test), paste: handOverPasteOf(values.paste)};
}
function handOverPasteOf(value: any): AiHandOver['paste'] {
const label = text(value?.label);
const intro = text(value?.intro);
return label && intro ? {label, intro, icon: iconOf(value.icon, 'terminal')} : undefined;
}
function handOverStepsOf(list: unknown): AiHandOverStep[] {
@ -406,6 +414,7 @@ function handOverStepsOf(list: unknown): AiHandOverStep[] {
title: text(step.title),
detail: text(step.detail),
markdown: text(step.markdown),
file: text(step.file),
done: step.done === true,
values: (Array.isArray(step.values) ? step.values : [])
.filter(value => text(value?.label) && typeof value?.value === 'string' && value.value)
@ -422,6 +431,7 @@ export interface AiConnectionCheck {
note?: string;
readings: {key: string; value: string}[];
keyCount: number;
gateway: boolean;
}
export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null {
@ -438,11 +448,16 @@ export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | 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);
.map(([key, item]) => ({key, value: String((item as any)?.value ?? '')}))
.filter(reading => !/^\s*[{[]/.test(reading.value))
.forEach(reading => readings.push(reading));
const gateway = values.gateway === true;
if (!gateway) {
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), keyCount: new Set(readings.map(reading => reading.key)).size};
note: text(values.note), readings: readings.slice(0, 6), keyCount: new Set(readings.map(reading => reading.key)).size, gateway};
}
export const isKitCardTool = (tool: string): boolean => KIT_CARD_TOOLS.has(tool);

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

@ -79,7 +79,7 @@
}
</table>
@if (unchanged.length) {
<button type="button" class="tb-more" [attr.aria-expanded]="showUnchanged" (click)="showUnchanged = !showUnchanged">
<button type="button" class="tb-more" [attr.aria-expanded]="showUnchanged" (click)="toggleUnchanged()">
<mat-icon aria-hidden="true">{{ showUnchanged ? 'expand_less' : 'expand_more' }}</mat-icon>
{{ (showUnchanged ? 'ai-assistant.review.hide-unchanged' : 'ai-assistant.review.unchanged') | translate: {count: unchanged.length} }}
</button>

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

@ -13,6 +13,7 @@ import {
SimpleChanges,
ViewChild
} from '@angular/core';
import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component';
import { TranslateService } from '@ngx-translate/core';
import { ClipboardService } from 'ngx-clipboard';
import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models';
@ -368,6 +369,13 @@ export class AiApprovalCardComponent implements OnChanges, AfterViewChecked {
return this.state === 'pending' || this.state === 'denied' || this.state === 'expired';
}
toggleUnchanged(): void {
this.showUnchanged = !this.showUnchanged;
if (this.showUnchanged) {
aiRevealOpened(this.host.nativeElement);
}
}
approve(): void {
this.state = this.autoApproved ? 'auto' : 'approved';
this.denying = false;

4
ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts

@ -5,7 +5,7 @@ import { toSignal } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { filter, map, startWith } from 'rxjs/operators';
import { aiPageView, AiChatClientContext } from '@shared/models/ai-chat.models';
import { aiClientOs, aiPageView, AiChatClientContext } from '@shared/models/ai-chat.models';
import { getDefaultTimezone } from '@shared/models/time/time.models';
import { BreadCrumb } from '@shared/components/breadcrumb';
import { BreadcrumbService } from '@core/services/breadcrumb.service';
@ -41,7 +41,7 @@ export class AiAssistantContextService {
const title = this.pageTitle();
const path = this.pagePath();
const type = aiPageView(path);
return title || path !== '/' ? {view: {type, title, path}, timeZone: getDefaultTimezone()} : undefined;
return title || path !== '/' ? {view: {type, title, path}, timeZone: getDefaultTimezone(), os: aiClientOs()} : undefined;
});
readonly welcome = computed(() => aiWelcome(this.clientContext()?.view, this.panelService.viewName(), this.panelService.config(),

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

@ -54,6 +54,7 @@
}
</div>
</div>
} @else if (msg.from === 'ACTION' && files[$index] && inCard.has(files[$index].name)) {
} @else if (msg.from === 'ACTION' && files[$index]; as file) {
<div class="ai art-cards">
<button type="button" class="art-card" [class.on]="shownFile === file.executionId" [attr.aria-pressed]="shownFile === file.executionId"
@ -85,8 +86,16 @@
</div>
} @else if (msg.from === 'ACTION' && handOvers[$index]; as card) {
<div class="ai hand">
<tb-ai-hand-over [handOver]="card.handOver" [wait]="card.wait" [time]="msg.data.startedAt" (prompt)="prompt.emit($event)" (stop)="stopRun.emit()"></tb-ai-hand-over>
<tb-ai-hand-over [handOver]="card.handOver" [wait]="card.wait" [time]="msg.data.startedAt" (prompt)="prompt.emit($event)" (stop)="stopRun.emit()" (compose)="compose.emit($event)"
[files]="latestFiles" (openFile)="openFile.emit($event)"></tb-ai-hand-over>
</div>
@if (waitAfterCard[$index] !== undefined && messages[waitAfterCard[$index]]; as moved) {
@if (moved.from === 'ACTION' && !waitsInCards.has(waitAfterCard[$index])) {
<div class="ai action">
<tb-ai-action-line [action]="moved.data" [names]="detailNames" [more]="0"></tb-ai-action-line>
</div>
}
}
} @else if (msg.from === 'ACTION' && asking?.index === $index) {
<div class="ai ask">
<tb-ai-question [questions]="asking.questions" [time]="msg.data.startedAt" (done)="answerQuestions($event)" (skip)="answerQuestions($event)"></tb-ai-question>

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

@ -33,6 +33,7 @@ import {
HAND_OVER_TOOL,
CHECK_CONNECTION_TOOL,
AiHandOver,
AiHandOverStep,
aiHandOverOf,
aiConnectionCheckOf,
SUGGEST_PROMPTS_TOOL,
@ -140,6 +141,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
streaming = false;
files: Record<number, AiFile> = {};
madeFiles: Record<number, AiMadeFile> = {};
inCard = new Set<string>();
private handledMadeFiles = new Set<string>();
quotes: Record<number, {name: string; icon: string; from: number; to: number; message: string}> = {};
sources: Record<number, AiSource[]> = {};
@ -149,7 +151,9 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
made: Record<number, string[]> = {};
plans: Record<number, {steps: AiPlanStep[]; progress: AiPlanProgress | null; gate: boolean}> = {};
handOvers: Record<number, {handOver: AiHandOver; wait: AiHandOverWait | null}> = {};
private waitsInCards = new Set<number>();
waitsInCards = new Set<number>();
private movedWaits = new Set<number>();
waitAfterCard: Record<number, number> = {};
private keptAsking = new Set<number>();
@ -419,6 +423,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
this.files = this.findFiles();
this.latestFiles = new Map(Object.values(this.files).map(file => [file.name, file]));
this.madeFiles = this.findMadeFiles();
this.inCard = this.placeFiles();
this.downloadRequestedFiles();
this.quotes = this.findQuotes();
this.sources = this.findSources();
@ -627,7 +632,7 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
isListedAction(message: ChatMessage, index = -1): boolean {
return message.from === 'ACTION' && !isKitCardTool(message.data.tool) && !isHiddenAiAction(message.data.tool)
&& !(index >= 0 && this.waitsInCards.has(index));
&& !(index >= 0 && (this.waitsInCards.has(index) || this.movedWaits.has(index)));
}
answerQuestions(answers: AiQuestionAnswer[]): void {
@ -800,6 +805,26 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
return files;
}
private placeFiles(): Set<string> {
const placed = new Set<string>();
const names = [...this.latestFiles.keys()];
const mentions = (step: AiHandOverStep, name: string) => [step.title, step.detail, step.markdown].some(part => part?.includes(name));
Object.values(this.handOvers).forEach(card => {
const groups = [card.handOver.steps, ...(card.handOver.choice?.options.map(option => option.steps ?? []) ?? [])];
groups.forEach(steps => {
steps.filter(step => step.file && !this.latestFiles.has(step.file)).forEach(step => step.file = undefined);
names.filter(name => !steps.some(step => step.file === name)).forEach(name => {
const last = [...steps].reverse().find(step => !step.file && mentions(step, name));
if (last) {
last.file = name;
}
});
steps.filter(step => step.file).forEach(step => placed.add(step.file));
});
});
return placed;
}
private findMadeFiles(): Record<number, AiMadeFile> {
const files: Record<number, AiMadeFile> = {};
this.messages.forEach((message, index) => {
@ -818,6 +843,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
const waits = new Set<number>();
let current = -1;
let early = -1;
const moved = new Set<number>();
const after: Record<number, number> = {};
const waitOf = (message: ActionChatMessage, index: number): AiHandOverWait => {
const running = message.data.status === 'RUNNING' && this.loading;
if (running) {
@ -843,6 +870,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
current = index;
if (early >= 0 && handOver.waitFor) {
cards[index].wait = waitOf(this.messages[early] as ActionChatMessage, early);
moved.add(early);
after[index] = early;
early = -1;
}
}
@ -856,6 +885,8 @@ export class AiChatMessagesComponent implements OnChanges, OnDestroy {
}
});
this.waitsInCards = waits;
this.movedWaits = moved;
this.waitAfterCard = after;
return cards;
}

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

@ -1,7 +1,8 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models';
import { aiPageView, isAiTitledView } from '@shared/models/ai-chat.models';
import { aiClientOs, aiPageView, isAiTitledView } from '@shared/models/ai-chat.models';
import { getDefaultTimezone } from '@shared/models/time/time.models';
import {
Component,
computed,
@ -562,6 +563,7 @@ export class AiChatComponent implements OnInit, OnDestroy {
composeText(text: string): void {
this.promptInput?.setValue(text);
setTimeout(() => this.focus());
}
ask(message: string, secrets?: Record<string, string>): void {
@ -945,9 +947,9 @@ export class AiChatComponent implements OnInit, OnDestroy {
if (prompt.resources.length) {
request.resources = prompt.resources.map(resource => resource.id);
}
if (this.clientContext()) {
request.clientContext = this.clientContext();
}
const context = this.clientContext();
request.clientContext = context ? {...context, os: context.os ?? aiClientOs()}
: {timeZone: getDefaultTimezone(), os: aiClientOs()} as AiChatClientContext;
if (prompt.secrets) {
request.secrets = prompt.secrets;
}
@ -1199,7 +1201,7 @@ export class AiChatComponent implements OnInit, OnDestroy {
tool: started.tool,
arguments: started.arguments,
status: isKitCardTool(started.tool) ? 'SUCCESS' : 'RUNNING',
startedAt: Date.now()
startedAt: started.startedAt ?? Date.now()
};
this.messages.update(list => [...list, {from: 'ACTION', data: action}]);
}

4
ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts

@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { TranslateService } from '@ngx-translate/core';
import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component';
export interface CodeLanguage {
lang: string;
@ -237,6 +238,9 @@ function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: st
toggle.addEventListener('click', () => {
const open = block.classList.toggle('folded') === false;
toggle.setAttribute('aria-expanded', String(open));
if (open) {
aiRevealOpened(block);
}
});
head.append(toggle);
} else {

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

@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { ChangeDetectionStrategy, Component, computed, input, signal } from '@angular/core';
import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, signal } from '@angular/core';
const STORE = 'tb-ai-disclosure';
@ -27,6 +27,38 @@ export function aiDisclosureRemember(key: string, open: boolean): void {
}
}
const REVEAL_GAP = 12;
function scrollerOf(element: HTMLElement): HTMLElement | null {
for (let node = element.parentElement; node; node = node.parentElement) {
const overflow = getComputedStyle(node).overflowY;
if ((overflow === 'auto' || overflow === 'scroll') && node.scrollHeight > node.clientHeight) {
return node;
}
}
return null;
}
export function aiRevealOpened(element: HTMLElement): void {
requestAnimationFrame(() => requestAnimationFrame(() => {
const scroller = scrollerOf(element);
if (!scroller) {
return;
}
const box = element.getBoundingClientRect();
const view = scroller.getBoundingClientRect();
const composer = scroller.querySelector<HTMLElement>('.ai-chat-composer') ?? element.closest('.ai-chat')?.querySelector<HTMLElement>('.ai-chat-composer');
const composerTop = composer?.getBoundingClientRect().top ?? view.bottom;
const bottom = Math.min(view.bottom, composerTop) - REVEAL_GAP;
const overflow = box.bottom - bottom;
if (overflow <= 0) {
return;
}
const room = box.top - view.top - REVEAL_GAP;
scroller.scrollBy({top: Math.min(overflow, Math.max(room, 0)), behavior: 'smooth'});
}));
}
@Component({
selector: 'tb-ai-disclosure',
template: `
@ -51,6 +83,8 @@ export class AiDisclosureComponent {
key = input<string>('');
private host = inject(ElementRef<HTMLElement>);
private toggledOpen = signal<boolean | null>(null);
open = computed(() => this.toggledOpen() ?? aiDisclosureRemembered(this.key()));
@ -62,6 +96,9 @@ export class AiDisclosureComponent {
if (open !== this.open()) {
this.toggledOpen.set(open);
aiDisclosureRemember(this.key(), open);
if (open) {
aiRevealOpened(this.host.nativeElement);
}
}
}
}

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

@ -10,7 +10,7 @@
<mat-icon class="tb-mat-16" aria-hidden="true">person</mat-icon><span class="k-who">{{ 'ai-assistant.hand-over.needs-you' | translate }}</span>
<span class="k-sub">{{ handOver().title }}</span>
</div>
<button mat-icon-button type="button" class="k-hand-close" (click)="open.set(true)" [attr.aria-expanded]="false"
<button mat-icon-button type="button" class="k-hand-close" (click)="unfold()" [attr.aria-expanded]="false"
[attr.aria-label]="'ai-assistant.hand-over.unfold' | translate"><mat-icon>expand_more</mat-icon></button>
<div class="k-body"><p>{{ arrivedLine() }}</p></div>
} @else {
@ -60,6 +60,14 @@
<span class="k-step-d">{{ step.detail }}</span>
}
</label>
@if (step.file && files().get(step.file); as file) {
<button type="button" class="art-card k-step-file" (click)="openFile.emit(file)">
<span class="art-card-ic"><mat-icon class="tb-mat-20" aria-hidden="true">{{ fileMark(file) }}</mat-icon></span>
<span class="art-card-t"><b><span class="art-name">{{ fileName(file.name).base }}<span class="art-ext">{{ fileName(file.name).ext }}</span></span></b>
<small>{{ 'ai-assistant.file.lines' | translate: {count: file.lines} }} · {{ file.size }}</small></span>
<mat-icon class="tb-mat-18 art-card-chev" aria-hidden="true">chevron_right</mat-icon>
</button>
}
@if (step.values.length || step.markdown) {
<div class="k-step-x">
@for (value of step.values; track $index; let v = $index) {
@ -132,9 +140,15 @@
<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>
@if (handOver().paste; as paste) {
<button type="button" class="ob-chip" (click)="startPaste(paste.intro)">
<mat-icon aria-hidden="true">{{ paste.icon }}</mat-icon>{{ paste.label }}
</button>
} @else {
<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()) {

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

@ -1,6 +1,8 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { AfterViewChecked, Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core';
import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models';
import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component';
import { Clipboard } from '@angular/cdk/clipboard';
import { TranslateService } from '@ngx-translate/core';
import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models';
@ -15,6 +17,7 @@ export interface AiHandOverWait {
}
const MIN_SILENCE_MS = 120000;
const MAX_SILENCE_MS = 300000;
const TEST_MARKER = 'aiTestValue';
const OS_LABELS: Record<string, string> = {macos: 'macOS', windows: 'Windows', linux: 'Linux'};
@ -34,10 +37,16 @@ export class AiHandOverComponent implements AfterViewChecked {
handOver = input.required<AiHandOver>();
wait = input<AiHandOverWait | null>(null);
time = input<number>(0);
files = input<ReadonlyMap<string, AiFile>>(new Map());
@Output() prompt = new EventEmitter<string>();
@Output() stop = new EventEmitter<void>();
@Output() compose = new EventEmitter<string>();
@Output() openFile = new EventEmitter<AiFile>();
readonly fileMark = aiFileMark;
readonly fileName = aiFileName;
private host = inject(ElementRef<HTMLElement>);
private translate = inject(TranslateService);
@ -86,7 +95,8 @@ export class AiHandOverComponent implements AfterViewChecked {
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 silenceMs = computed(() => Math.min(MAX_SILENCE_MS,
Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0))));
readonly quiet = computed(() => this.waiting() && this.elapsed() >= this.silenceMs());
readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.elapsed() / 60000)));
readonly stoppedQuiet = computed(() => {
@ -206,6 +216,15 @@ export class AiHandOverComponent implements AfterViewChecked {
}
}
unfold(): void {
this.open.set(true);
aiRevealOpened(this.host.nativeElement);
}
startPaste(intro: string): void {
this.compose.emit(intro + '\n');
}
say(key: string): void {
this.prompt.emit(this.translate.instant(key));
}

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

@ -3,7 +3,8 @@
import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import { Subscription, timer } from 'rxjs';
import { concatMap, take, takeWhile } from 'rxjs/operators';
import { aiEntityKind } from '@home/components/ai/ai-action.models';
import { aiRecordKey, AiRecordView, AiShownRecords } from '@home/components/ai/ai-record.models';
import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service';
@ -16,6 +17,9 @@ const LIST_SHOWN = 8;
const TARGETED_HUB_TYPES = new Set<string>([ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE]);
const WAIT_RECHECK_MS = 10000;
const WAIT_RECHECKS = 90;
@Component({
selector: 'tb-ai-records',
template: `
@ -125,9 +129,12 @@ export class AiRecordsComponent {
this.key();
const shown = untracked(() => this.shown());
this.loading?.unsubscribe();
this.loading = this.loader.loadAll(shown.refs, {image: shown.refs.length === 1})
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(views => this.views.set(views));
this.loading = timer(0, WAIT_RECHECK_MS).pipe(
take(WAIT_RECHECKS),
concatMap(() => this.loader.loadAll(shown.refs, {image: shown.refs.length === 1})),
takeWhile(views => views.some(view => view.state?.tone === 'wait'), true),
takeUntilDestroyed(this.destroyRef)
).subscribe(views => this.views.set(views));
});
}

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

@ -187,6 +187,7 @@ export interface TurnStoppedEvent extends BaseChatEvent {
export interface ToolStarted extends BaseChatToolEventData {
tool: string;
arguments?: unknown;
startedAt?: number;
}
export interface ToolStartedEvent extends BaseChatEvent {
@ -461,6 +462,14 @@ export interface AiChatView {
export interface AiChatClientContext {
view: AiChatView;
timeZone?: string;
os?: string;
}
export function aiClientOs(): string | undefined {
const nav = navigator as Navigator & {userAgentData?: {platform?: string}};
const agent = `${nav.userAgentData?.platform ?? ''} ${navigator.userAgent}`;
return /Android/i.test(agent) ? 'android' : /iPhone|iPad|iPod/i.test(agent) ? 'ios' : /CrOS|Chrome OS/i.test(agent) ? 'chromeos'
: /Win/i.test(agent) ? 'windows' : /Mac/i.test(agent) ? 'macos' : /Linux|X11/i.test(agent) ? 'linux' : undefined;
}
export interface SendChatMessageRequest {

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

@ -2191,6 +2191,7 @@
"needs-you": "Needs you",
"fold": "Fold",
"unfold": "Show the steps",
"gateway-connected": "{{name}} connected at {{time}}.",
"arrived-message": "The first message arrived at {{time}}.",
"arrived-message-from": "The first message from {{name}} arrived at {{time}}.",
"arrived-uplink": "The first uplink arrived at {{time}}.",
@ -2208,7 +2209,7 @@
"wait-uplink": "listening for the first uplink",
"wait-gateway": "listening for the gateway",
"nothing-heard": "nothing heard for {{minutes}} min",
"keep-waiting": "It is on, keep waiting",
"keep-waiting": "It is on now, keep waiting",
"keep-waiting-prompt": "It is on. Keep waiting for the data.",
"what-wrong": "What could be wrong?",
"what-wrong-prompt": "Nothing arrived. What could be wrong?"

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

@ -2282,9 +2282,12 @@ code.k-ent[data-pal="solution"] .k-ent-ic { color: var(--entity-solution-fg); }
display: flex;
flex-wrap: wrap;
gap: 8px;
min-width: 0;
}
.ob-chip[aria-pressed="true"] {
max-width: 100%;
overflow-wrap: anywhere;
height: auto;
min-height: 0;
padding: 0;
@ -6832,6 +6835,13 @@ tb-ai-action-detail.k-detail .tb-codeblock pre.tb-code {
text-decoration-color: var(--tb-ink-38);
}
.k-step-file {
display: flex;
width: auto;
max-width: calc(100% - 28px);
margin: 8px 0 2px 28px;
}
.k-step-x {
margin: 8px 0 2px 28px;
min-width: 0;

Loading…
Cancel
Save