File size: 23,805 Bytes
0b89610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Enterprise Context Optimizer</title>
    <style>
      :root {
        --bg: #050505;
        --panel: #0d0d0d;
        --panel-strong: #111111;
        --ink: #f5f5f5;
        --muted: #9a9a9a;
        --line: #222222;
        --line-strong: #303030;
        --accent: #ffffff;
        --accent-deep: #d9d9d9;
        --good: #8cf0b0;
        --warn: #f2d27a;
        --error: #ff8e8e;
        --shadow: none;
      }
      * { box-sizing: border-box; }
      html, body {
        min-height: 100%;
      }
      body {
        margin: 0;
        font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        color: var(--ink);
        background: var(--bg);
        letter-spacing: -0.01em;
      }
      .shell {
        max-width: 1600px;
        margin: 0 auto;
        padding: 20px;
        min-height: 100vh;
        display: grid;
        grid-template-rows: auto minmax(0, 1fr);
        gap: 16px;
      }
      .card {
        background: var(--panel);
        border: 1px solid var(--line);
        border-radius: 18px;
        box-shadow: var(--shadow);
        padding: 20px;
      }
      h1, h2, h3, p { margin-top: 0; }
      h1 {
        font-size: clamp(1.8rem, 4vw, 2.6rem);
        line-height: 1.05;
        font-weight: 700;
        letter-spacing: -0.03em;
        margin-bottom: 8px;
      }
      h3 {
        font-size: 1.1rem;
        letter-spacing: -0.02em;
      }
      .muted {
        color: var(--muted);
        line-height: 1.6;
        font-size: 0.96rem;
      }
      .stats {
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        gap: 12px;
        margin-top: 14px;
      }
      .stat {
        border: 1px solid var(--line);
        border-radius: 14px;
        padding: 14px;
        background: var(--panel-strong);
      }
      .stat-label {
        font-size: 0.78rem;
        color: var(--muted);
        text-transform: uppercase;
        letter-spacing: 0.06em;
      }
      .stat-value {
        margin-top: 8px;
        font-size: 1.55rem;
        font-weight: 700;
        letter-spacing: -0.03em;
      }
      textarea, button {
        font: inherit;
        border-radius: 18px;
      }
      select {
        font: inherit;
        border-radius: 12px;
        border: 1px solid var(--line);
        padding: 10px 14px;
        background: var(--panel-strong);
        color: var(--ink);
      }
      textarea {
        width: 100%;
        min-height: 100%;
        border: 1px solid var(--line);
        padding: 18px 20px;
        resize: none;
        background: var(--panel-strong);
        color: var(--ink);
        line-height: 1.6;
        transition: border-color .18s ease, box-shadow .18s ease;
      }
      textarea:focus {
        outline: none;
        border-color: #666666;
        box-shadow: 0 0 0 1px #666666;
      }
      button {
        cursor: pointer;
        border: 1px solid transparent;
        padding: 11px 16px;
        font-weight: 600;
        letter-spacing: -0.01em;
        transition: background .18s ease, border-color .18s ease, opacity .18s ease, color .18s ease;
      }
      .primary {
        color: #050505;
        background: var(--accent);
        border-color: var(--accent);
      }
      button:disabled {
        opacity: 0.6;
        cursor: wait;
      }
      .status {
        margin-top: 14px;
        min-height: 46px;
        border-radius: 14px;
        padding: 14px 16px;
        border: 1px solid #4a4124;
        background: #15120a;
        color: var(--warn);
        font-weight: 600;
      }
      .status.good {
        border-color: #1f5131;
        background: #0d1510;
        color: var(--good);
      }
      .status.error {
        border-color: #5a2020;
        background: #180d0d;
        color: var(--error);
      }
      .panel-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 16px;
        min-height: 0;
      }
      pre {
        margin: 0;
        white-space: pre-wrap;
        word-break: break-word;
        border-radius: 14px;
        background: var(--panel-strong);
        color: var(--ink);
        padding: 20px;
        min-height: 100%;
        overflow: auto;
        line-height: 1.72;
        font-size: 0.98rem;
        border: 1px solid var(--line);
      }
      .toolbar {
        display: flex;
        gap: 12px;
        align-items: center;
        flex-wrap: wrap;
        margin-top: 16px;
      }
      .mini {
        color: var(--muted);
        font-size: 0.92rem;
        line-height: 1.5;
      }
      .chips {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-top: 12px;
      }
      .grounding-list {
        display: grid;
        gap: 10px;
        margin-top: 14px;
      }
      .grounding-item {
        padding: 12px 14px;
        border-radius: 12px;
        background: var(--panel-strong);
        border: 1px solid var(--line);
      }
      .grounding-title {
        font-size: 0.82rem;
        font-weight: 700;
        color: var(--ink);
        margin-bottom: 4px;
      }
      .chip {
        padding: 7px 12px;
        border-radius: 999px;
        background: #121212;
        color: var(--ink);
        font-size: 0.8rem;
        font-weight: 600;
        border: 1px solid var(--line);
      }
      .summary-grid {
        display: grid;
        grid-template-columns: minmax(0, 1fr) minmax(320px, 380px);
        gap: 16px;
        align-items: start;
      }
      .workspace {
        display: grid;
        grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
        gap: 16px;
        min-height: 0;
      }
      .pane {
        display: grid;
        grid-template-rows: auto minmax(0, 1fr);
        min-height: 0;
      }
      .pane-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        margin-bottom: 14px;
      }
      .pane-actions {
        display: flex;
        gap: 10px;
        align-items: center;
      }
      .secondary {
        color: var(--ink);
        background: var(--panel-strong);
        border: 1px solid var(--line);
      }
      .pane-subtitle {
        margin: 4px 0 0;
      }
      .output-frame {
        min-height: 0;
      }
      .diff-panel {
        margin-top: 14px;
        border: 1px solid var(--line);
        border-radius: 14px;
        padding: 14px 16px;
        background: var(--panel-strong);
        min-height: 96px;
        line-height: 1.7;
        color: var(--ink);
        overflow: auto;
      }
      .diff-label {
        display: block;
        margin-bottom: 8px;
        font-size: 0.82rem;
        color: var(--muted);
        text-transform: uppercase;
        letter-spacing: 0.05em;
      }
      .diff-added {
        background: #102015;
        color: #8cf0b0;
        border-radius: 6px;
        padding: 2px 4px;
      }
      .diff-removed {
        background: #221111;
        color: #ff8e8e;
        border-radius: 6px;
        padding: 2px 4px;
      }
      @media (max-width: 900px) {
        .stats, .summary-grid, .workspace {
          grid-template-columns: 1fr;
        }
        .shell {
          padding: 14px;
        }
      }
    </style>
</head>
<body>
  <div class="shell">
      <section class="card">
        <div class="toolbar" style="justify-content:space-between; margin-top:0;">
          <div>
            <h1 style="margin:0 0 6px;">Enterprise Context Optimizer</h1>
            <p class="mini" id="summaryNote">Minimal dark mode. Paste a prompt, optimize it, compare the diff, and copy the result.</p>
          </div>
          <div class="toolbar" style="margin-top:0;">
            <label class="mini" for="corpusFamilySelect">Corpus Pack</label>
            <select id="corpusFamilySelect">
              <option value="enterprise_v1">enterprise_v1</option>
              <option value="enterprise_v2">enterprise_v2</option>
            </select>
            <label class="mini" for="compressionModeSelect">Mode</label>
            <select id="compressionModeSelect">
              <option value="balanced">balanced</option>
              <option value="grounded">grounded</option>
              <option value="aggressive">aggressive</option>
            </select>
            <button id="optimizeBtn" class="primary" type="button">Optimize Prompt</button>
            <span id="busyLabel" class="mini">Idle</span>
          </div>
        </div>
        <div class="stats">
          <div class="stat"><div class="stat-label">Current Input</div><div class="stat-value" id="currentInputTokensStat">-</div></div>
          <div class="stat"><div class="stat-label">Optimized Output</div><div class="stat-value" id="finalTokensStat">-</div></div>
          <div class="stat"><div class="stat-label">Chunks Used</div><div class="stat-value" id="selectedChunksStat">-</div></div>
          <div class="stat"><div class="stat-label">Context Tokens</div><div class="stat-value" id="compressedTokensStat">-</div></div>
          <div class="stat"><div class="stat-label">Citation Ready</div><div class="stat-value" id="citationReadyStat">-</div></div>
          <div class="stat"><div class="stat-label">Grounded Overlap</div><div class="stat-value" id="groundedOverlapStat">-</div></div>
          <div class="stat"><div class="stat-label">Tuning Mode</div><div class="stat-value" id="tuningModeStat">-</div></div>
          <div class="stat"><div class="stat-label">Demo Seeds</div><div class="stat-value" id="demoSeedStat">-</div></div>
        </div>
        <div id="statusBox" class="status">Ready. Paste a prompt and click Optimize Prompt.</div>
        <p class="mini" id="citationGuidance">Citation guidance will appear here. Use grounded mode when you want the optimizer to prefer inline evidence anchors.</p>
        <div class="chips" id="keywordChips"></div>
        <div class="chips" id="citationChips"></div>
        <div class="chips" id="demoChips"></div>
        <div class="grounding-list" id="groundingList"></div>
      </section>

      <section class="panel-grid">
        <div class="workspace">
          <section class="card pane">
            <div class="pane-header">
              <div>
                <h3 style="margin:0;">Original Prompt</h3>
                <p class="mini pane-subtitle">Paste or edit your source prompt here.</p>
              </div>
              <div class="pane-actions">
                <button id="pasteBtn" class="secondary" type="button">Paste</button>
              </div>
            </div>
            <textarea id="promptInput" placeholder="Paste your prompt here. Then click Optimize Prompt."></textarea>
            <div class="diff-panel">
              <span class="diff-label">Removed From Original</span>
              <div id="originalDiffPanel">No diff yet.</div>
            </div>
          </section>
          <section class="card pane">
            <div class="pane-header">
              <div>
                <h3 style="margin:0;">Optimized Prompt</h3>
                <p class="mini pane-subtitle">A shorter, cleaner version designed to be ready to copy and paste into your next model call.</p>
              </div>
              <div class="pane-actions">
                <button id="copyBtn" class="secondary" type="button">Copy</button>
              </div>
            </div>
            <pre id="outputPanel" class="output-frame">No optimized prompt yet.</pre>
            <div class="diff-panel">
              <span class="diff-label">Added / Changed In Optimized Prompt</span>
              <div id="optimizedDiffPanel">No diff yet.</div>
            </div>
          </section>
        </div>
      </section>
  </div>

  <script>
    const els = {
      promptInput: document.getElementById("promptInput"),
      optimizeBtn: document.getElementById("optimizeBtn"),
      copyBtn: document.getElementById("copyBtn"),
      pasteBtn: document.getElementById("pasteBtn"),
      corpusFamilySelect: document.getElementById("corpusFamilySelect"),
      compressionModeSelect: document.getElementById("compressionModeSelect"),
      busyLabel: document.getElementById("busyLabel"),
      statusBox: document.getElementById("statusBox"),
      citationGuidance: document.getElementById("citationGuidance"),
      outputPanel: document.getElementById("outputPanel"),
      currentInputTokensStat: document.getElementById("currentInputTokensStat"),
      selectedChunksStat: document.getElementById("selectedChunksStat"),
      compressedTokensStat: document.getElementById("compressedTokensStat"),
      finalTokensStat: document.getElementById("finalTokensStat"),
      citationReadyStat: document.getElementById("citationReadyStat"),
      groundedOverlapStat: document.getElementById("groundedOverlapStat"),
      tuningModeStat: document.getElementById("tuningModeStat"),
      demoSeedStat: document.getElementById("demoSeedStat"),
      keywordChips: document.getElementById("keywordChips"),
      citationChips: document.getElementById("citationChips"),
      demoChips: document.getElementById("demoChips"),
      groundingList: document.getElementById("groundingList"),
      summaryNote: document.getElementById("summaryNote"),
      originalDiffPanel: document.getElementById("originalDiffPanel"),
      optimizedDiffPanel: document.getElementById("optimizedDiffPanel"),
    };

    function approxTokens(text) {
      const value = (text || "").trim();
      if (!value) return 0;
      return Math.max(1, Math.floor(value.length / 4));
    }

    function setBusy(isBusy, label = "Working...") {
      els.optimizeBtn.disabled = isBusy;
      els.copyBtn.disabled = isBusy;
      els.pasteBtn.disabled = isBusy;
      els.busyLabel.textContent = isBusy ? label : "Idle";
    }

    function setStatus(message, tone = "warn") {
      els.statusBox.textContent = message;
      els.statusBox.className = "status";
      if (tone === "good") els.statusBox.classList.add("good");
      if (tone === "error") els.statusBox.classList.add("error");
    }

    async function fetchJson(url, options = {}) {
      const response = await fetch(url, {
        headers: { "Content-Type": "application/json" },
        ...options,
      });
      const body = await response.json();
      if (!response.ok) throw new Error(body.detail || JSON.stringify(body));
      return body;
    }

    function escapeHtml(text) {
      return String(text)
        .replaceAll("&", "&amp;")
        .replaceAll("<", "&lt;")
        .replaceAll(">", "&gt;")
        .replaceAll('"', "&quot;")
        .replaceAll("'", "&#39;");
    }

    function tokenizeForDiff(text) {
      return (text || "").match(/[A-Za-z0-9_]+|[^\sA-Za-z0-9_]+/g) || [];
    }

    function normalizeDiffToken(token) {
      return String(token || "").toLowerCase();
    }

    function diffWords(original, optimized) {
      const a = tokenizeForDiff(original);
      const b = tokenizeForDiff(optimized);
      const dp = Array.from({ length: a.length + 1 }, () => Array(b.length + 1).fill(0));

      for (let i = a.length - 1; i >= 0; i--) {
        for (let j = b.length - 1; j >= 0; j--) {
          if (normalizeDiffToken(a[i]) === normalizeDiffToken(b[j])) {
            dp[i][j] = dp[i + 1][j + 1] + 1;
          } else {
            dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]);
          }
        }
      }

      const left = [];
      const right = [];
      let i = 0;
      let j = 0;
      while (i < a.length && j < b.length) {
        if (normalizeDiffToken(a[i]) === normalizeDiffToken(b[j])) {
          const safe = escapeHtml(a[i]);
          left.push(safe);
          right.push(safe);
          i += 1;
          j += 1;
        } else if (dp[i + 1][j] >= dp[i][j + 1]) {
          left.push(`<span class="diff-removed">${escapeHtml(a[i])}</span>`);
          i += 1;
        } else {
          right.push(`<span class="diff-added">${escapeHtml(b[j])}</span>`);
          j += 1;
        }
      }

      while (i < a.length) {
        left.push(`<span class="diff-removed">${escapeHtml(a[i])}</span>`);
        i += 1;
      }
      while (j < b.length) {
        right.push(`<span class="diff-added">${escapeHtml(b[j])}</span>`);
        j += 1;
      }

      return {
        originalHtml: left.join(" ").replace(/\s+([,.;:!?])/g, "$1"),
        optimizedHtml: right.join(" ").replace(/\s+([,.;:!?])/g, "$1"),
      };
    }

    function renderDiff(original, optimized) {
      if (!(original || "").trim() || !(optimized || "").trim()) {
        els.originalDiffPanel.textContent = "No diff yet.";
        els.optimizedDiffPanel.textContent = "No diff yet.";
        return;
      }
      const diff = diffWords(original, optimized);
      els.originalDiffPanel.innerHTML = diff.originalHtml || escapeHtml(original);
      els.optimizedDiffPanel.innerHTML = diff.optimizedHtml || escapeHtml(optimized);
    }

    function renderResult(result) {
      els.outputPanel.textContent = result.optimized_prompt || "No optimized prompt returned.";
      renderDiff(els.promptInput.value, result.optimized_prompt || "");
      const stats = result.stats || {};
      // Avoid newer JS syntax here; some browsers silently fail and stop updating the UI.
      els.currentInputTokensStat.textContent = (stats.original_prompt_tokens !== undefined && stats.original_prompt_tokens !== null) ? String(stats.original_prompt_tokens) : String(approxTokens(els.promptInput.value));
      els.selectedChunksStat.textContent = (stats.selected_chunks !== undefined && stats.selected_chunks !== null) ? String(stats.selected_chunks) : "-";
      els.compressedTokensStat.textContent = (stats.compressed_context_tokens !== undefined && stats.compressed_context_tokens !== null) ? String(stats.compressed_context_tokens) : "-";
      els.finalTokensStat.textContent = (stats.optimized_prompt_tokens !== undefined && stats.optimized_prompt_tokens !== null) ? String(stats.optimized_prompt_tokens) : "-";
      const grounding = result.grounding || {};
      const tuning = result.context_tuning || {};
      const optimizationMode = result.optimization_mode || els.compressionModeSelect.value || "balanced";
      els.citationReadyStat.textContent = grounding.citation_ready ? "Yes" : "No";
      els.groundedOverlapStat.textContent = (grounding.grounded_overlap !== undefined && grounding.grounded_overlap !== null) ? String(grounding.grounded_overlap) : "-";
      els.tuningModeStat.textContent = tuning.mode || "-";
      els.demoSeedStat.textContent = tuning.top_demo_cases ? String(tuning.top_demo_cases.length) : "-";
      const sourceTokens = (stats.source_tokens !== undefined && stats.source_tokens !== null) ? String(stats.source_tokens) : "-";
      els.summaryNote.textContent = "`Current Input` tracks the text in the prompt box. `Context Tokens` is compressed backend support context. Raw support before compression: " + sourceTokens + ". Active optimization mode: " + optimizationMode + ".";
      if (result.corpus_family) {
        els.summaryNote.textContent += " Active corpus pack: " + result.corpus_family + ".";
      }
      if (tuning.leave_one_out) {
        els.summaryNote.textContent += " Leave-one-out masking is active.";
      }
      if (optimizationMode === "grounded") {
        els.summaryNote.textContent += " Grounded mode prefers inline citations even if the final prompt stays slightly longer.";
      } else if (optimizationMode === "aggressive") {
        els.summaryNote.textContent += " Aggressive mode prioritizes shorter output over richer evidence phrasing.";
      } else {
        els.summaryNote.textContent += " Balanced mode tries to preserve constraints while still shortening the prompt.";
      }
      const chips = result.selected_keywords || [];
      els.keywordChips.innerHTML = chips.map((keyword) => `<span class="chip">${keyword}</span>`).join("");
      const citations = grounding.citations || [];
      els.citationChips.innerHTML = citations.map((citation) => `<span class="chip">[${citation}]</span>`).join("");
      els.citationGuidance.textContent = grounding.citation_guidance || (grounding.citation_ready ? "Inline citations are present in the optimized prompt." : "No citation guidance available.");
      const demos = tuning.top_demo_cases || [];
      els.demoChips.innerHTML = demos.map((demo) => `<span class="chip">${demo}</span>`).join("");
      const notes = grounding.evidence_notes || [];
      els.groundingList.innerHTML = notes.map((item) => `<div class="grounding-item"><div class="grounding-title">[${item.chunk_id}]</div><div>${item.note}</div></div>`).join("");
    }

    els.optimizeBtn.addEventListener("click", async () => {
      const prompt = els.promptInput.value.trim();
      if (!prompt) {
        setStatus("Please paste a prompt first.", "error");
        return;
      }
      setBusy(true, "Optimizing...");
      setStatus("Running retrieval, ranking, compression, and prompt rewriting...", "warn");
      try {
        const result = await fetchJson("/optimize-prompt", {
          method: "POST",
          body: JSON.stringify({
            prompt,
            corpus_family: els.corpusFamilySelect.value,
            compression_mode: els.compressionModeSelect.value,
          }),
        });
        renderResult(result);
        setStatus("Optimization complete. The output below is ready to copy and paste.", "good");
      } catch (error) {
        setStatus(error.message, "error");
      } finally {
        setBusy(false);
      }
    });

    els.copyBtn.addEventListener("click", async () => {
      const text = els.outputPanel.textContent || "";
      if (!text || text === "No optimized prompt yet.") {
        setStatus("There is no optimized output to copy yet.", "error");
        return;
      }
      try {
        await navigator.clipboard.writeText(text);
        setStatus("Optimized prompt copied to clipboard.", "good");
      } catch (_error) {
        setStatus("Copy failed. You can still select the output manually.", "error");
      }
    });

    els.pasteBtn.addEventListener("click", async () => {
      try {
        const text = await navigator.clipboard.readText();
        if (!text || !text.trim()) {
          setStatus("Clipboard is empty.", "error");
          return;
        }
        els.promptInput.value = text;
        els.promptInput.dispatchEvent(new Event("input"));
        setStatus("Prompt pasted from clipboard.", "good");
      } catch (_error) {
        setStatus("Paste failed. Your browser may block clipboard read access.", "error");
      }
    });

    els.promptInput.addEventListener("input", () => {
      els.currentInputTokensStat.textContent = String(approxTokens(els.promptInput.value));
      els.finalTokensStat.textContent = "-";
      els.selectedChunksStat.textContent = "-";
      els.compressedTokensStat.textContent = "-";
      els.citationReadyStat.textContent = "-";
      els.groundedOverlapStat.textContent = "-";
      els.tuningModeStat.textContent = "-";
      els.demoSeedStat.textContent = "-";
      els.citationGuidance.textContent = "Citation guidance will appear here. Use grounded mode when you want the optimizer to prefer inline evidence anchors.";
      els.citationChips.innerHTML = "";
      els.demoChips.innerHTML = "";
      els.groundingList.innerHTML = "";
      els.originalDiffPanel.textContent = "No diff yet.";
      els.optimizedDiffPanel.textContent = "No diff yet.";
      els.summaryNote.textContent = "Prompt changed. Click Optimize Prompt to refresh the optimized output, grounding, and backend context stats.";
    });
  </script>
</body>
</html>