Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 | 92x 103x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 15x 15x 15x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 92x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 7x 22x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 23x 2x 2x 23x 2x 2x 23x 2x 2x 23x 23x 2x 2x 2x 2x 22x 14x 14x 14x 36x 36x 36x 36x 36x 36x 36x 41x 3x 41x 41x 39x 41x 41x 39x 39x 39x 39x 41x 41x 41x 39x 39x 39x 14x 14x 14x 14x 14x 14x 39x 39x 39x 39x 1x 39x 39x 38x 39x 10x 39x 28x 28x 14x 14x 14x 14x 14x 14x 14x 28x 28x 28x 14x 14x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 2x 2x 2x 2x 2x 26x 26x 26x 26x 14x 14x 14x 14x 14x 14x 14x 14x 14x 92x 92x 92x 92x 92x 92x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 14x 14x 14x 13x 13x 13x 13x 13x 13x 10x 10x 10x 10x 10x 10x 10x 13x 13x 13x 13x 13x 13x 13x 14x 14x 14x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 28x 28x 28x 28x 28x 28x 28x 8x 8x 10x 10x 8x 8x 28x 28x 28x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 14x 92x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 45x 45x 45x 45x 45x 45x 2x 2x 45x 45x 1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 16x 16x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 16x 323x 323x 323x 323x 323x 179x 179x 179x 179x 179x 179x 179x 179x 179x 179x 92x 92x 323x 323x 323x 323x 323x 323x 323x 323x 323x 45x 45x 32x 45x 45x 1x 323x 323x 323x 131x 15x 15x 15x 15x 15x 15x 15x 17x 17x 17x 17x 17x 17x 11x 11x 11x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 323x 1x 1x 17x 1x 1x 1x 1x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 1x 1x 1x 1x 1x 1x 17x 1x 1x 1x 1x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 17x 17x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x | import { html, TemplateResult } from 'lit-html';
import { css, PropertyValues } from 'lit';
import { property, state } from 'lit/decorators.js';
import { RapidElement } from '../RapidElement';
import { getStore } from '../store/Store';
import { AppState, fromStore, zustand } from '../store/AppState';
import { FlowDefinition } from '../store/flow-definition';
import { TranslationEntry, buildTranslationBundles } from './flow-translations';
import { getLanguageDisplayName } from './utils';
import { LLMModel, hasLLMRole } from './flow-utils';
interface TranslationModel {
uuid: string;
name: string;
}
const MODELS_ENDPOINT = '/api/internal/llms.json';
const ADD_MODEL_URL = '/ai/';
// Max size of the serialized JSON payload per translate request. Keeps the
// LLM's output comfortably below its token limit. Measured against the full
// payload (uuids, keys, JSON structural chars, and source strings).
const TRANSLATION_BATCH_CHAR_LIMIT = 10000;
export class AutoTranslate extends RapidElement {
static get styles() {
return css`
:host {
display: contents;
}
.auto-translate-body {
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px;
font-size: 14px;
color: #374151;
}
.auto-translate-body p {
margin: 0;
}
.auto-translate-loading {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: #6b7280;
}
.auto-translate-empty {
display: flex;
flex-direction: column;
gap: 8px;
font-size: 13px;
}
.auto-translate-empty a {
color: var(--color-link);
text-decoration: none;
}
.auto-translate-empty a:hover {
text-decoration: underline;
}
.auto-translate-status {
display: flex;
align-items: center;
gap: 6px;
/* align with the progress bar in the body (body has 20px padding,
dialog-footer has 10px) */
padding-left: 10px;
font-size: 12px;
color: #6b7280;
}
.auto-translate-status-spinner {
--icon-color: #6b7280;
}
.auto-translate-error-block {
display: flex;
flex-direction: column;
gap: 6px;
padding: 12px 14px;
background: #fef2f2;
border: 1px solid #fecaca;
border-radius: 6px;
overflow: hidden;
font-size: 13px;
color: #7f1d1d;
}
.auto-translate-error-block p {
margin: 0;
}
.auto-translate-error-help {
color: inherit;
}
.auto-translate-error-toggle {
align-self: flex-start;
margin-top: 2px;
padding: 0;
background: none;
border: none;
color: inherit;
font: inherit;
font-size: 12px;
text-decoration: underline;
cursor: pointer;
}
.auto-translate-error-details {
margin: 6px -14px -12px;
padding: 10px 14px;
background: #fff;
border-top: 1px solid #fecaca;
font-size: 12px;
color: inherit;
white-space: pre-wrap;
word-break: break-word;
}
`;
}
@property({ attribute: false })
definition: FlowDefinition | null = null;
@property({ type: String, attribute: 'language-code' })
languageCode = '';
@property({ type: Boolean })
disabled = false;
@fromStore(zustand, (state: AppState) => state.brand)
private brand!: string;
// Reactive flag the host can read to show "translating" state in UI
// adjacent to this component (e.g. the toolbar button).
@property({ type: Boolean, reflect: true })
running = false;
@state()
dialogOpen = false;
@state()
models: TranslationModel[] = [];
@state()
modelsLoading = false;
@state()
selectedModel: TranslationModel | null = null;
@state()
progress: { done: number; total: number } = { done: 0, total: 0 };
@state()
error: string | null = null;
@state()
errorExpanded = false;
@state()
interrupt = false;
@state()
updateExisting = false;
// Tracks whether the dialog has ever opened so we can keep it mounted
// afterwards (so it sees its own close transition) without paying
// for an empty hidden dialog before that.
private everOpened = false;
/**
* Public entry point. If a translation is in flight, sets the interrupt
* flag; otherwise opens the model picker.
*/
public async start(): Promise<void> {
if (this.disabled) {
return;
}
if (this.running) {
this.interrupt = true;
return;
}
this.error = null;
this.errorExpanded = false;
this.selectedModel = null;
this.updateExisting = false;
this.dialogOpen = true;
await this.loadModels();
if (this.models.length === 1) {
this.selectedModel = this.models[0];
}
}
private async loadModels(): Promise<void> {
this.modelsLoading = true;
try {
const store = getStore();
const results: LLMModel[] = store
? ((await store.getResults(MODELS_ENDPOINT, { force: true })) ?? [])
: [];
this.models = results
.filter((r) => hasLLMRole(r, 'editing'))
.map((r) => ({
uuid: r.uuid,
name: r.name
}));
} catch (err) {
console.error('Failed to load AI models', err);
this.models = [];
this.error = 'Unable to load AI models.';
} finally {
this.modelsLoading = false;
}
}
private handleModelChange(event: Event): void {
const select = event.target as any;
const next = select?.values?.[0];
this.selectedModel = next ? { uuid: next.uuid, name: next.name } : null;
}
private handleUpdateExistingChange(event: Event): void {
const checkbox = event.target as any;
this.updateExisting = !!checkbox?.checked;
}
private confirmTranslate(): void {
if (!this.selectedModel) {
return;
}
this.dialogOpen = false;
this.runAutoTranslation().catch((err) => {
console.error('Auto translation failed', err);
this.error = 'Auto translation failed. Please try again.';
this.running = false;
});
}
private cancelDialog(): void {
this.dialogOpen = false;
}
private dismissError(): void {
this.error = null;
this.errorExpanded = false;
this.progress = { done: 0, total: 0 };
}
/**
* Builds batches of translation requests from all untranslated entries,
* grouping so each request's serialized payload stays under
* TRANSLATION_BATCH_CHAR_LIMIT. Skips entries whose source matches a
* translation already present in the flow (those are returned in
* preTranslated for direct application), and dedupes pending entries
* sharing identical source arrays so each unique array is sent at most
* once (duplicates are returned in duplicateKeyToCanonical for
* propagation when the canonical key's translation lands). When
* updateExisting is true, already-translated entries are also included
* and the pre-translation reuse path is skipped so all localizable
* entries are sent to the LLM.
*/
private buildTranslationBatches(): {
keyToEntries: Map<string, TranslationEntry[]>;
batches: { items: Record<string, string[]> }[];
preTranslated: Map<string, string[]>;
duplicateKeyToCanonical: Map<string, string>;
} {
const keyToEntries = new Map<string, TranslationEntry[]>();
const batches: { items: Record<string, string[]> }[] = [];
const preTranslated = new Map<string, string[]>();
const duplicateKeyToCanonical = new Map<string, string>();
if (!this.definition) {
return { keyToEntries, batches, preTranslated, duplicateKeyToCanonical };
}
const bundles = buildTranslationBundles(this.definition, this.languageCode);
const updateExisting = this.updateExisting;
// Map source-content -> already-stored translation array, built from
// entries that have a translation in the live localization map. Reading
// the stored array (not entry.to) preserves the original shape. Skipped
// in update mode so we always re-translate via the LLM.
const existingByContent = new Map<string, string[]>();
const localization =
this.definition.localization?.[this.languageCode] || {};
if (!updateExisting) {
for (const bundle of bundles) {
for (const entry of bundle.translations) {
// Skip entries with no real translation: an empty array OR an
// array of only empty/whitespace strings shouldn't seed reuse,
// or we'd silently propagate a blank to other matching sources.
if (
!entry.toValues ||
!entry.toValues.some((v) => v && v.trim().length > 0)
) {
continue;
}
if (!entry.fromValues || entry.fromValues.length === 0) {
continue;
}
const stored = localization[entry.uuid]?.[entry.attribute];
if (!Array.isArray(stored) || stored.length === 0) {
continue;
}
const contentKey = JSON.stringify(entry.fromValues);
if (!existingByContent.has(contentKey)) {
existingByContent.set(contentKey, stored);
}
}
}
}
// Collect pending entries preserving order. Each unique key (uuid +
// attribute) maps to its source array (entry.fromValues), preserving
// multi-item structure for attributes like router-case `arguments`.
// In update mode we include entries that already have a translation.
// Invariant: findTranslations produces at most one entry per
// (uuid, attribute) pair, so the first fromValues is authoritative
// and any later entry with the same key is treated as a duplicate.
const valuesByKey = new Map<string, string[]>();
for (const bundle of bundles) {
for (const entry of bundle.translations) {
if (
!updateExisting &&
entry.toValues &&
entry.toValues.some((v) => v && v.trim().length > 0)
) {
continue;
}
if (!entry.fromValues || entry.fromValues.length === 0) {
continue;
}
const key = `${entry.uuid}:${entry.attribute}`;
const list = keyToEntries.get(key) || [];
list.push(entry);
keyToEntries.set(key, list);
if (!valuesByKey.has(key)) {
valuesByKey.set(key, entry.fromValues);
}
}
}
// Split pending keys into pre-translated (matching an existing
// translation), duplicates (sharing content with an earlier pending
// key), and unique canonical keys that need to be sent to the LLM.
const canonicalByContent = new Map<string, string>();
const canonicalKeysWithValues: { key: string; values: string[] }[] = [];
for (const [key, values] of valuesByKey) {
const contentKey = JSON.stringify(values);
const existing = existingByContent.get(contentKey);
if (existing && existing.length === values.length) {
preTranslated.set(key, existing);
continue;
}
const canonical = canonicalByContent.get(contentKey);
if (canonical) {
duplicateKeyToCanonical.set(key, canonical);
continue;
}
canonicalByContent.set(contentKey, key);
canonicalKeysWithValues.push({ key, values });
}
const source = this.definition.language;
const target = this.languageCode;
const measurePayload = (items: Record<string, string[]>): number =>
JSON.stringify({ source, target, items }).length;
let current: Record<string, string[]> = {};
for (const { key, values } of canonicalKeysWithValues) {
const tentative = { ...current, [key]: values };
const tentativeSize = measurePayload(tentative);
const batchHasItems = Object.keys(current).length > 0;
if (tentativeSize > TRANSLATION_BATCH_CHAR_LIMIT && batchHasItems) {
// a single oversized entry still ships on its own
batches.push({ items: current });
current = { [key]: values };
} else {
current = tentative;
}
}
if (Object.keys(current).length > 0) {
batches.push({ items: current });
}
return { keyToEntries, batches, preTranslated, duplicateKeyToCanonical };
}
/**
* Drives the batch loop. Public so tests can invoke directly with a
* pre-set selectedModel.
*/
public async runAutoTranslation(): Promise<void> {
if (
!this.definition ||
!this.selectedModel ||
this.languageCode === this.definition.language
) {
return;
}
const { keyToEntries, batches, preTranslated, duplicateKeyToCanonical } =
this.buildTranslationBatches();
// Apply entries that match an existing translation immediately so we
// don't need an LLM round-trip for them.
if (preTranslated.size > 0) {
this.applyBatchTranslations(
Object.fromEntries(preTranslated),
keyToEntries
);
}
if (batches.length === 0) {
return;
}
// Inverse of duplicateKeyToCanonical so we can quickly find which keys
// need to be back-filled when a canonical key's translation lands.
const duplicatesByCanonical = new Map<string, string[]>();
for (const [dup, canonical] of duplicateKeyToCanonical) {
const list = duplicatesByCanonical.get(canonical) || [];
list.push(dup);
duplicatesByCanonical.set(canonical, list);
}
this.running = true;
this.interrupt = false;
this.progress = { done: 0, total: batches.length };
const source = this.definition.language;
const target = this.languageCode;
const url = `/llm/translate/${this.selectedModel.uuid}/`;
const store = getStore();
if (!store) {
this.running = false;
return;
}
for (let i = 0; i < batches.length; i++) {
if (this.interrupt) {
break;
}
try {
const response = await store.postJSON(url, {
source,
target,
items: batches[i].items
});
if (response.status >= 200 && response.status < 300) {
const returned: Record<string, string[]> = response.json?.items || {};
const expanded: Record<string, string[]> = { ...returned };
for (const canonical of Object.keys(returned)) {
const dups = duplicatesByCanonical.get(canonical);
if (dups) {
for (const dup of dups) {
expanded[dup] = returned[canonical];
}
}
}
this.applyBatchTranslations(expanded, keyToEntries);
} else {
this.error =
response.json?.error ||
`Translate request failed (${response.status}).`;
break;
}
} catch (err) {
console.error('Translate request failed', err);
this.error = 'Translate request failed.';
break;
}
this.progress = { done: i + 1, total: batches.length };
}
this.running = false;
this.interrupt = false;
}
private applyBatchTranslations(
returned: Record<string, string[]>,
keyToEntries: Map<string, TranslationEntry[]>
): void {
const store = getStore();
if (!store || !this.definition) {
return;
}
// group updates by uuid so multiple attributes merge into one write
const updatesByUuid = new Map<string, Record<string, any>>();
for (const [key, values] of Object.entries(returned)) {
const entries = keyToEntries.get(key);
if (!entries || entries.length === 0) {
continue;
}
const [firstEntry] = entries;
const uuid = firstEntry.uuid;
const attribute = firstEntry.attribute;
keyToEntries.delete(key);
if (!values || values.length === 0) {
continue;
}
// read from the live store rather than this.definition, which can
// lag behind across batches and cause earlier attributes to be
// overwritten when multiple attrs on the same uuid land in
// different batches
const liveDefinition = zustand.getState().flowDefinition;
const existing =
liveDefinition?.localization?.[this.languageCode]?.[uuid] || {};
const existingValues = Array.isArray(existing[attribute])
? (existing[attribute] as string[])
: null;
// Never replace an existing non-empty translation with an empty
// value: when re-translating already-localized content the LLM may
// return blanks for some entries; keep the prior translation in
// those slots. Only safe when the arrays align by index — if the
// source array length has changed since the last translation, the
// old values aren't tied to the same items anymore, so skip the
// per-item preserve and let the LLM result through unchanged.
const canPreservePerItem =
!!existingValues && existingValues.length === values.length;
const mergedValues = values.map((v, i) => {
const isEmpty =
v === null ||
v === undefined ||
(typeof v === 'string' && v.trim().length === 0);
if (isEmpty && canPreservePerItem && existingValues![i]) {
return existingValues![i];
}
return v;
});
const hasContent = mergedValues.some(
(v) => v && (typeof v !== 'string' || v.trim().length > 0)
);
if (!hasContent) {
continue;
}
const merged = updatesByUuid.get(uuid) || { ...existing };
merged[attribute] = mergedValues;
updatesByUuid.set(uuid, merged);
}
for (const [uuid, merged] of updatesByUuid.entries()) {
store.getState().updateLocalization(this.languageCode, uuid, merged);
zustand.getState().markAutoTranslated(
this.languageCode,
uuid,
Object.keys(merged).filter(
(k) => merged[k] && (merged[k] as any[]).length > 0
)
);
}
}
protected updated(changed: PropertyValues): void {
if (changed.has('running')) {
// emit a state-change event so the host can update adjacent UI
// (e.g. toolbar button) without polling
this.dispatchEvent(
new CustomEvent('temba-auto-translate-changed', {
detail: { running: this.running },
bubbles: true,
composed: true
})
);
}
}
private handleDialogButton(event: CustomEvent): void {
const name = event.detail?.button?.name;
if (this.error) {
// only the Dismiss button shows in the error state
this.dismissError();
return;
}
if (this.running) {
// only the Stop button shows while running
if (!this.interrupt) {
this.interrupt = true;
}
return;
}
if (name === 'Translate') {
this.confirmTranslate();
} else {
this.cancelDialog();
}
}
public render(): TemplateResult | string {
const showPicker = this.dialogOpen;
const showProgress = this.running || !!this.error;
const open = showPicker || showProgress;
// Skip rendering until the dialog has been opened at least once so we
// don't pay for an empty hidden dialog on every editor instance.
if (!open && !this.everOpened) {
return '';
}
if (open) {
this.everOpened = true;
}
let header = 'Auto Translation';
let body: TemplateResult = html``;
let gutter: TemplateResult | string = '';
let primary = '';
let cancel = '';
let disabled = false;
if (this.error) {
header = 'Problem with AI Model';
body = this.renderErrorBody();
cancel = 'Dismiss';
} else if (this.running) {
body = this.renderRunningBody();
gutter = this.renderRunningGutter();
// Stop is the primary so the dialog does NOT auto-close on click;
// we close it ourselves once the in-flight batch returns
primary = 'Stop';
disabled = this.interrupt;
} else if (showPicker) {
const noModels = !this.modelsLoading && this.models.length === 0;
body = this.renderPickerBody();
cancel = noModels ? 'Close' : 'Cancel';
primary = noModels ? '' : 'Translate';
disabled = this.modelsLoading || noModels || !this.selectedModel;
}
// We always render the dialog (after first open) so it sees the
// open: true -> false transition and runs its body scroll/unlock
// cleanup; otherwise body styles can stay stuck after auto-translate
// completes.
return html`
<temba-dialog
header=${header}
.open=${open}
size="small"
primaryButtonName=${primary}
cancelButtonName=${cancel}
?disabled=${disabled}
variant="flat"
@temba-button-clicked=${this.handleDialogButton}
>
<div class="auto-translate-body">${body}</div>
${gutter ? html`<div slot="gutter">${gutter}</div>` : ''}
</temba-dialog>
`;
}
private renderPickerBody(): TemplateResult {
if (this.modelsLoading) {
return html`<div class="auto-translate-loading">
<temba-loading units="3" size="8"></temba-loading>
</div>`;
}
if (this.models.length === 0) {
return html`
<div class="auto-translate-empty">
<p>You need to add an AI model before you can auto translate.</p>
<p>
<a href="${ADD_MODEL_URL}" target="_blank" rel="noopener"
>Manage AI models</a
>
</p>
</div>
`;
}
const selected = this.selectedModel ? [this.selectedModel] : [];
const languageName = getLanguageDisplayName(this.languageCode);
const aiClause = this.brand
? html`${this.brand} uses AI for automatic translation, which can make
mistakes,`
: html`Automatic translation uses AI, which can make mistakes,`;
return html`
<p>
All remaining text for <strong>${languageName}</strong> will be
translated automatically. ${aiClause} so it is important to review all
of your translations to verify they are correct.
</p>
${this.models.length > 1
? html`<temba-select
class="auto-translate-model-select"
endpoint="${MODELS_ENDPOINT}"
valueKey="uuid"
.values=${selected}
.shouldExclude=${(option: LLMModel) =>
!hasLLMRole(option, 'editing')}
?searchable=${true}
placeholder="Select an AI model"
@change=${this.handleModelChange}
></temba-select>`
: ''}
<temba-checkbox
class="auto-translate-update-existing"
label="Update existing translations"
?checked=${this.updateExisting}
@change=${this.handleUpdateExistingChange}
></temba-checkbox>
`;
}
private renderRunningBody(): TemplateResult {
const { done, total } = this.progress;
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
return html`
<temba-progress
.total=${total}
.current=${done}
.pct=${pct}
showPercentage
></temba-progress>
`;
}
private renderRunningGutter(): TemplateResult {
const { done, total } = this.progress;
// current batch is 1-indexed: while batch 0 is in flight, done is still
// 0, so we display "1 of N"
const currentBatch = Math.min(done + 1, total);
const statusText = this.interrupt
? 'Stopping...'
: total > 1
? `Translating ${currentBatch} of ${total}`
: 'Translating';
return html`
<div class="auto-translate-status">
<temba-icon
class="auto-translate-status-spinner"
name="progress_spinner"
size="0.9"
spin
></temba-icon>
<span>${statusText}</span>
</div>
`;
}
private renderErrorBody(): TemplateResult {
return html`
<div class="auto-translate-error-block">
<p class="auto-translate-error-help">
Any translations already applied have been kept. You can try again, or
check the AI model's settings if the problem persists.
</p>
${this.errorExpanded
? html`<pre class="auto-translate-error-details">${this.error}</pre>`
: html`<button
class="auto-translate-error-toggle"
type="button"
@click=${() => (this.errorExpanded = true)}
>
Show details
</button>`}
</div>
`;
}
}
|